Beltic logo
Advanced Topics

Integration Patterns

Common patterns for integrating Beltic credentials with frameworks and platforms.

Production-ready integration patterns for common frameworks and platforms.

Express/Fastify Middleware

import { verifyCredential } from '@beltic/sdk';

export const credentialAuth = (options) => {
  return async (req, res, next) => {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    try {
      const result = await verifyCredential(token, {
        keyResolver: getPublicKey,
        expectedIssuer: options.issuer
      });
      
      req.credential = result.credential;
      next();
    } catch (error) {
      res.status(401).json({ error: 'Invalid credential' });
    }
  };
};

// Usage
app.post('/api/action', credentialAuth({ issuer: 'did:web:beltic.com' }), handler);

Next.js API Routes

// pages/api/agent-action.ts
import { verifyAgentTrustChain } from '@beltic/sdk';

export default async function handler(req, res) {
  const { agentToken } = req.body;
  
  try {
    const trustChain = await verifyAgentTrustChain(agentToken, {
      policy: { minKybTier: 'tier_2', minSafetyScore: 80 }
    });
    
    // Process agent action
    return res.json({ success: true });
  } catch (error) {
    return res.status(403).json({ error: error.message });
  }
}

GraphQL Schema Extension

import { verifyCredential } from '@beltic/sdk';

const typeDefs = `
  type Query {
    verifiedAgent(token: String!): Agent
  }
`;

const resolvers = {
  Query: {
    verifiedAgent: async (_, { token }) => {
      const result = await verifyCredential(token, options);
      return result.credential;
    }
  }
};

Serverless Functions

// AWS Lambda
export const handler = async (event) => {
  const token = event.headers.Authorization;
  
  const result = await verifyCredential(token, {
    keyResolver: async (did) => {
      // Fetch from DynamoDB or S3
      return await getPublicKeyFromStorage(did);
    }
  });
  
  return { statusCode: 200, body: JSON.stringify(result) };
};

Frontend Display

// React component
function AgentBadge({ credential }) {
  const safetyScore = credential.harmfulContentRefusalScore;
  const kybTier = credential.developerKybTier;
  
  return (
    <div className="agent-badge">
      <span className="verified">✓ Verified Agent</span>
      <span>KYB: {kybTier}</span>
      <span>Safety: {safetyScore}/100</span>
    </div>
  );
}

Web Bot Auth Middleware

Verify HTTP message signatures (Web Bot Auth) on incoming requests:

import { 
  verifyHttpSignature, 
  createDefaultKeyResolver,
  verifyCredential 
} from '@beltic/sdk';

export const webBotAuthMiddleware = (options) => {
  return async (req, res, next) => {
    // Check for signature headers
    if (!req.headers['signature-agent']) {
      return res.status(401).json({ error: 'Missing Signature-Agent header' });
    }

    // Verify HTTP signature
    const sigResult = await verifyHttpSignature(
      {
        method: req.method,
        url: `https://${req.hostname}${req.originalUrl}`,
        headers: req.headers,
        body: req.body
      },
      { keyResolver: createDefaultKeyResolver() }
    );

    if (!sigResult.valid) {
      return res.status(401).json({ 
        error: 'Invalid signature',
        details: sigResult.errors 
      });
    }

    // Optionally verify the agent's credential
    if (options.requireCredential) {
      const credential = await fetchAgentCredentialByKeyId(sigResult.keyId);
      
      if (!credential) {
        return res.status(403).json({ error: 'Agent not found' });
      }

      // Verify key binding
      if (credential.httpSigningKeyJwkThumbprint !== sigResult.keyId) {
        return res.status(403).json({ error: 'Key not bound to credential' });
      }

      req.agentCredential = credential;
    }

    req.sigResult = sigResult;
    next();
  };
};

// Usage
app.post('/api/action', 
  webBotAuthMiddleware({ requireCredential: true }), 
  handler
);

Cloudflare Workers

Verify Web Bot Auth in Cloudflare Workers:

import { verifyHttpSignature, createDefaultKeyResolver } from '@beltic/sdk';

export default {
  async fetch(request, env) {
    // Cloudflare already sets cf.bot_management.verified_bot for known bots
    // But you can also verify signatures yourself
    
    const sigResult = await verifyHttpSignature(
      {
        method: request.method,
        url: request.url,
        headers: Object.fromEntries(request.headers),
      },
      { keyResolver: createDefaultKeyResolver() }
    );

    if (!sigResult.valid) {
      return new Response('Invalid signature', { status: 401 });
    }

    // Forward to origin with verified status
    const response = await fetch(request);
    return response;
  }
};

See Also