The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit 5eea80c71925Commit detailsView latest

api/index.ts 42 lines · 1.9 KB · typescript
1
import type { IncomingMessage, ServerResponse } from 'node:http';
2
import { buildApi } from '../apps/api/src/app.js';
3
import { TrustEngine } from '../packages/core/src/index.js';
4
import { HostedRepository } from '../packages/persistence/src/hosted.js';
5
import { loadAuth0Profile, verifyAuth0Token } from './auth0.js';
6
7
const databaseUrl = process.env.DATABASE_URL;
8
const repository = databaseUrl ? new HostedRepository(databaseUrl) : undefined;
9
const app = buildApi(new TrustEngine(), undefined, repository);
10
const ready = app.ready();
11
12
export default async function handler(request: IncomingMessage, response: ServerResponse) {
13
  const incoming = new URL(request.url ?? '/', 'https://openclasp.local');
14
  const target = incoming.searchParams.get('path');
15
  if (target) request.url = target;
16
  if ((request.url ?? '').startsWith('/v0.1/')) {
17
    const authorization = request.headers.authorization;
18
    const token = authorization?.startsWith('Bearer ') ? authorization.slice(7) : undefined;
19
    if (!token) {
20
      response.statusCode = 401;
21
      response.setHeader('content-type', 'application/json');
22
      response.end(JSON.stringify({ error: 'authentication_required' }));
23
      return;
24
    }
25
    try {
26
      const authentication = await verifyAuth0Token(token, { dashboard: true });
27
      request.headers['x-openclasp-operator'] = authentication.payload.sub!;
28
      if ((request.url ?? '').startsWith('/v0.1/account')) {
29
        const user = await loadAuth0Profile(token);
30
        request.headers['x-openclasp-email'] = encodeURIComponent(user.email ?? '');
31
        request.headers['x-openclasp-name'] = encodeURIComponent(user.name ?? '');
32
      }
33
    } catch {
34
      response.statusCode = 401;
35
      response.setHeader('content-type', 'application/json');
36
      response.end(JSON.stringify({ error: 'invalid_session' }));
37
      return;
38
    }
39
  }
40
  await ready;
41
  app.server.emit('request', request, response);
42
}