skip to content

Framework examples

Copy-pasteable Next.js, Hono, Express, and Cloudflare Workers handlers sharing one jose JWT verifier, plus deployment notes.

updated view markdown ->
for humans

Every provider host implements the same two HTTP routes:

  1. GET /.well-known/agent-signup.json serves your identity-only discovery document with 200 and application/json, no authentication, and no redirects. OPTIONS on the same path answers the CORS preflight with 204 and no body.
  2. POST /api/signup/agent verifies the incoming Authorization: Bearer <jwt> assertion against the broker's public JWKS, enforces issuer, audience, lifetime, scopes, human.verified, delegation.accepted_rp_tos_url, and jti replay protection, then resolves or creates your local account idempotently.

Complete runnable starters live in the public docs repository at Provider examples. Each folder is standalone, and all four share one hardened jose verifier with jku and x5u rejection, allowlist-gated per-issuer JWKS lookup, and the claim checks below.

Shared verification helper

Every example carries its own copy: lib/verify-assertion.ts for Next.js and src/verify-assertion.ts for Hono, Express, and Cloudflare Workers. The copies are identical, so one folder can be copied without cross-folder imports. Run npm install jose, then save this exact file at the matching path in your app:

import {
  createRemoteJWKSet,
  decodeJwt,
  decodeProtectedHeader,
  errors,
  jwtVerify,
  type JWTPayload,
} from "jose";

export interface VerifierConfig {
  issuerAllowlist: string[];
  audience: string;
  requiredScopes: string[];
  termsUrl: string;
  termsSha256?: string;
  jwksUrlOverride?: string;
}

export interface AssertionClaims {
  iss: string;
  aud: string;
  jti: string;
  iat: number;
  exp: number;
  human: { id: string; verified: true } & Record<string, unknown>;
  delegation: {
    scopes: string[];
    accepted_rp_tos_url: string;
    accepted_rp_tos_hash?: string;
  } & Record<string, unknown>;
  [claim: string]: unknown;
}

export type VerifyResult =
  | { ok: true; claims: AssertionClaims }
  | {
      ok: false;
      status: 400 | 401 | 403 | 409;
      error: string;
      error_description: string;
    };

const keySets = new Map<string, ReturnType<typeof createRemoteJWKSet>>();

function jwksFor(url: string) {
  let jwks = keySets.get(url);
  if (!jwks) {
    jwks = createRemoteJWKSet(new URL(url), {
      timeoutDuration: 5000,
      cooldownDuration: 30000,
    });
    keySets.set(url, jwks);
  }
  return jwks;
}

function fail(
  status: 400 | 401 | 403 | 409,
  error: string,
  error_description: string,
): VerifyResult {
  return { ok: false, status, error, error_description };
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

function normalizeUrl(value: string) {
  return value.replace(/\/+$/, "");
}

function readBearerToken(header: string | null | undefined): string | null {
  if (typeof header !== "string") return null;
  const match = /^Bearer\s+(\S+)$/i.exec(header.trim());
  return match ? match[1] : null;
}

/**
 * Verify an Agent Identity assertion.
 *
 * The result is a discriminated union: expected failures return
 * `{ ok: false, status, error, error_description }` and never throw.
 *
 * The issuer is read from the unverified payload only to check the configured
 * allowlist before any network call. Signature and claim checks run after the
 * per-issuer JWKS is resolved from the allowlisted issuer, never from `jku` or
 * `x5u`. After verification, the signed issuer must equal the issuer used to
 * select the JWKS, so the token cannot mix one allowlisted key source with a
 * different allowlisted `iss` claim.
 */
export async function verifyAssertion(
  authorization: string | null | undefined,
  cfg: VerifierConfig,
): Promise<VerifyResult> {
  const token = readBearerToken(authorization);
  if (!token) {
    return fail(
      400,
      "invalid_request",
      "Authorization header must be Bearer <jwt>",
    );
  }

  let header: ReturnType<typeof decodeProtectedHeader>;
  try {
    header = decodeProtectedHeader(token);
  } catch {
    return fail(401, "invalid_assertion", "Malformed JOSE header");
  }
  if ("jku" in header || "x5u" in header) {
    return fail(
      401,
      "invalid_assertion",
      "Remote key headers jku and x5u are not allowed",
    );
  }

  let unverified: JWTPayload;
  try {
    unverified = decodeJwt(token);
  } catch {
    return fail(401, "invalid_assertion", "Malformed JWT payload");
  }

  const issuer = unverified.iss;
  if (typeof issuer !== "string" || !cfg.issuerAllowlist.includes(issuer)) {
    return fail(403, "issuer_not_allowed", "Issuer is not in issuer_allowlist");
  }

  const jwksUrl = cfg.jwksUrlOverride ?? `${issuer}/.well-known/jwks.json`;

  let payload: JWTPayload;
  try {
    const result = await jwtVerify(token, jwksFor(jwksUrl), {
      algorithms: ["EdDSA"],
      typ: "agent-id+jwt",
      clockTolerance: 60,
    });
    payload = result.payload;
  } catch (error) {
    const code = (error as { code?: string }).code;
    if (error instanceof errors.JWTExpired || code === "ERR_JWT_EXPIRED") {
      return fail(401, "assertion_expired", "Assertion has expired");
    }
    return fail(
      401,
      "invalid_assertion",
      "Signature or JOSE header verification failed",
    );
  }

  if (typeof payload.iss !== "string" || payload.iss !== issuer) {
    return fail(
      403,
      "issuer_not_allowed",
      "Verified issuer does not match the issuer used to resolve keys",
    );
  }
  if (payload.aud !== cfg.audience) {
    return fail(403, "audience_mismatch", "Assertion audience does not match");
  }

  const iat = payload.iat;
  const exp = payload.exp;
  const now = Math.floor(Date.now() / 1000);
  if (
    typeof iat !== "number" ||
    typeof exp !== "number" ||
    exp <= iat ||
    iat > now + 60 ||
    exp - iat > 300
  ) {
    return fail(
      401,
      "invalid_assertion",
      "Assertion must carry numeric iat and exp with a positive lifetime of at most 300 seconds, and iat no more than 60 seconds in the future",
    );
  }

  const delegation = isRecord(payload.delegation)
    ? payload.delegation
    : undefined;
  const rawScopes = delegation?.scopes;
  const scopes: string[] = Array.isArray(rawScopes)
    ? rawScopes.filter((scope): scope is string => typeof scope === "string")
    : [];
  if (!cfg.requiredScopes.every((scope) => scopes.includes(scope))) {
    return fail(
      403,
      "insufficient_scope",
      "Delegated scopes do not cover required_scopes",
    );
  }

  const human = isRecord(payload.human) ? payload.human : undefined;
  if (
    !human ||
    human.verified !== true ||
    typeof human.id !== "string" ||
    human.id.length === 0
  ) {
    return fail(403, "human_unverified", "The human owner is not verified");
  }

  const acceptedUrl = delegation?.accepted_rp_tos_url;
  if (
    typeof acceptedUrl !== "string" ||
    normalizeUrl(acceptedUrl) !== normalizeUrl(cfg.termsUrl)
  ) {
    return fail(
      409,
      "tos_hash_mismatch",
      "Accepted terms URL does not match the published terms URL",
    );
  }
  if (
    cfg.termsSha256 !== undefined &&
    delegation?.accepted_rp_tos_hash !== cfg.termsSha256
  ) {
    return fail(
      409,
      "tos_hash_mismatch",
      "Accepted terms hash does not match the served terms bytes",
    );
  }

  const jti = payload.jti;
  if (typeof jti !== "string" || jti.length === 0) {
    return fail(401, "invalid_assertion", "Assertion must carry a non-empty jti");
  }

  return {
    ok: true,
    claims: {
      ...payload,
      iss: payload.iss,
      aud: cfg.audience,
      jti,
      iat,
      exp,
      human: { ...human, id: human.id, verified: true },
      delegation: {
        ...(delegation ?? {}),
        scopes,
        accepted_rp_tos_url: acceptedUrl,
        ...(typeof delegation?.accepted_rp_tos_hash === "string"
          ? { accepted_rp_tos_hash: delegation.accepted_rp_tos_hash }
          : {}),
      },
    },
  };
}

The helper returns a discriminated VerifyResult. Expected failures return { ok: false, status, error, error_description } and never throw, so each handler maps a failure to the response envelope in one place.

Framework handlers

Select your runtime below. The handlers use in-memory Map stores so the flow stays readable; replace them with database unique constraints before taking live traffic.

Create app/.well-known/agent-signup.json/route.ts and keep the dot in the directory name:

// app/.well-known/agent-signup.json/route.ts
const PORT = 3003;

function providerOrigin() {
  return process.env.PROVIDER_ORIGIN ?? `http://127.0.0.1:${PORT}`;
}

function providerAudience() {
  return process.env.PROVIDER_AUDIENCE ?? "nextjs-example";
}

function issuerAllowlist() {
  const configured = (process.env.ISSUER_ALLOWLIST ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter((value) => value.length > 0);
  return configured.length > 0 ? configured : ["https://agentregistrar.dev"];
}

function discoveryDocument() {
  const origin = providerOrigin();
  const attestationUri = process.env.ATTESTATION_URI;

  return {
    protocol: "agent-identity-protocol",
    protocol_version: "2.0",
    audience: providerAudience(),
    provider_name: "Next.js App Router example",
    provider_url: origin,
    contact: process.env.PROVIDER_CONTACT ?? "security@example.com",
    issuer_allowlist: issuerAllowlist(),
    required_scopes: ["tos:accept"],
    terms: {
      version: process.env.TERMS_VERSION ?? "2026.1",
      url: process.env.TERMS_URL ?? `${origin}/terms`,
    },
    endpoints: {
      agent_signup: `${origin}/api/signup/agent`,
    },
    ...(attestationUri
      ? { attestation: { mode: "broker" as const, uri: attestationUri } }
      : {}),
  };
}

export function GET() {
  return Response.json(discoveryDocument(), {
    headers: {
      "cache-control": "public, max-age=60",
      "access-control-allow-origin": "*",
    },
  });
}

export function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      "access-control-allow-origin": "*",
      "access-control-allow-methods": "GET, OPTIONS",
      "access-control-allow-headers": "Content-Type",
    },
  });
}

Create app/api/signup/agent/route.ts:

// app/api/signup/agent/route.ts
import { verifyAssertion } from "@/lib/verify-assertion";

const PORT = 3003;
const NO_STORE = { "cache-control": "no-store" };

// Local demo only. Use database unique constraints on (iss, human.id) and jti.
const accounts = new Map<string, string>();
const seenJti = new Map<string, string>();

function providerOrigin() {
  return process.env.PROVIDER_ORIGIN ?? `http://127.0.0.1:${PORT}`;
}

function providerAudience() {
  return process.env.PROVIDER_AUDIENCE ?? "nextjs-example";
}

function issuerAllowlist() {
  const configured = (process.env.ISSUER_ALLOWLIST ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter((value) => value.length > 0);
  return configured.length > 0 ? configured : ["https://agentregistrar.dev"];
}

function errorResponse(status: number, error: string, description: string) {
  return Response.json(
    { error, error_description: description, retryable: false },
    { status, headers: NO_STORE },
  );
}

export async function POST(request: Request) {
  const origin = providerOrigin();
  const result = await verifyAssertion(request.headers.get("authorization"), {
    issuerAllowlist: issuerAllowlist(),
    audience: providerAudience(),
    requiredScopes: ["tos:accept"],
    termsUrl: process.env.TERMS_URL ?? `${origin}/terms`,
    termsSha256: process.env.TERMS_SHA256,
    jwksUrlOverride: process.env.JWKS_URL_OVERRIDE,
  });
  if (!result.ok) return errorResponse(result.status, result.error, result.error_description);

  const claims = result.claims;
  const accountKey = `${claims.iss}:${claims.human.id}`;
  const previous = seenJti.get(claims.jti);
  if (previous !== undefined && previous !== accountKey) {
    return errorResponse(
      409,
      "assertion_replayed",
      "Assertion id used in a conflicting context",
    );
  }
  seenJti.set(claims.jti, accountKey);

  const existing = accounts.get(accountKey);
  if (existing) {
    return Response.json(
      { resolution: "resolved", account_id: existing },
      { status: 200, headers: NO_STORE },
    );
  }

  const accountId = `acct_${crypto.randomUUID()}`;
  accounts.set(accountKey, accountId);
  return Response.json(
    {
      resolution: "created",
      account_id: accountId,
      api_key: `key_${crypto.randomUUID()}`,
    },
    { status: 201, headers: NO_STORE },
  );
}

export function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      "access-control-allow-origin": "*",
      "access-control-allow-methods": "POST, OPTIONS",
      "access-control-allow-headers": "Authorization, Content-Type",
      ...NO_STORE,
    },
  });
}

function methodNotAllowed() {
  return new Response(null, {
    status: 405,
    headers: { allow: "POST", ...NO_STORE },
  });
}

export const GET = methodNotAllowed;
export const HEAD = methodNotAllowed;

The starter also serves plain-text terms at /terms and keeps the import alias @/* in tsconfig.json. From a clone of the docs repository, run:

cd examples/nextjs
npm install
npm run dev

In another terminal, validate discovery on port 3003:

npx @agentregistrar/discovery@2.1.1 validate http://127.0.0.1:3003/.well-known/agent-signup.json --probe-jwks --probe-endpoints --json

Expected: exit code 0, "valid": true, and zero errors. Full source: Next.js App Router starter.

src/app.ts exports a pure Hono app, so the same routes can run on Node, Cloudflare Workers, Bun, and Vercel. The Node starter uses @hono/node-server.

// src/app.ts
import { Hono } from "hono";
import { verifyAssertion } from "./verify-assertion";

const PORT = 3004;
const NO_STORE = { "cache-control": "no-store" };

// Local demo only. Use database unique constraints on (iss, human.id) and jti.
const accounts = new Map<string, string>();
const seenJti = new Map<string, string>();

function providerOrigin() {
  return process.env.PROVIDER_ORIGIN ?? `http://127.0.0.1:${PORT}`;
}

function providerAudience() {
  return process.env.PROVIDER_AUDIENCE ?? "hono-example";
}

function issuerAllowlist() {
  const configured = (process.env.ISSUER_ALLOWLIST ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter((value) => value.length > 0);
  return configured.length > 0 ? configured : ["https://agentregistrar.dev"];
}

export const app = new Hono();

app.get("/.well-known/agent-signup.json", (c) => {
  const origin = providerOrigin();
  const attestationUri = process.env.ATTESTATION_URI;

  return c.json(
    {
      protocol: "agent-identity-protocol",
      protocol_version: "2.0",
      audience: providerAudience(),
      provider_name: "Hono example",
      provider_url: origin,
      contact: process.env.PROVIDER_CONTACT ?? "security@example.com",
      issuer_allowlist: issuerAllowlist(),
      required_scopes: ["tos:accept"],
      terms: {
        version: process.env.TERMS_VERSION ?? "2026.1",
        url: process.env.TERMS_URL ?? `${origin}/terms`,
      },
      endpoints: {
        agent_signup: `${origin}/api/signup/agent`,
      },
      ...(attestationUri
        ? { attestation: { mode: "broker" as const, uri: attestationUri } }
        : {}),
    },
    200,
    {
      "cache-control": "public, max-age=60",
      "access-control-allow-origin": "*",
    },
  );
});

app.options("/.well-known/agent-signup.json", (c) =>
  c.body(null, 204, {
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "GET, OPTIONS",
    "access-control-allow-headers": "Content-Type",
  }),
);

app.post("/api/signup/agent", async (c) => {
  const origin = providerOrigin();
  const errorResponse = (status: 400 | 401 | 403 | 409, error: string, description: string) =>
    c.json(
      { error, error_description: description, retryable: false },
      status,
      NO_STORE,
    );

  const result = await verifyAssertion(c.req.header("authorization"), {
    issuerAllowlist: issuerAllowlist(),
    audience: providerAudience(),
    requiredScopes: ["tos:accept"],
    termsUrl: process.env.TERMS_URL ?? `${origin}/terms`,
    termsSha256: process.env.TERMS_SHA256,
    jwksUrlOverride: process.env.JWKS_URL_OVERRIDE,
  });
  if (!result.ok) return errorResponse(result.status, result.error, result.error_description);

  const claims = result.claims;
  const accountKey = `${claims.iss}:${claims.human.id}`;
  const previous = seenJti.get(claims.jti);
  if (previous !== undefined && previous !== accountKey) {
    return errorResponse(
      409,
      "assertion_replayed",
      "Assertion id used in a conflicting context",
    );
  }
  seenJti.set(claims.jti, accountKey);

  const existing = accounts.get(accountKey);
  if (existing) {
    return c.json(
      { resolution: "resolved", account_id: existing },
      200,
      NO_STORE,
    );
  }

  const accountId = `acct_${crypto.randomUUID()}`;
  accounts.set(accountKey, accountId);
  return c.json(
    {
      resolution: "created",
      account_id: accountId,
      api_key: `key_${crypto.randomUUID()}`,
    },
    201,
    NO_STORE,
  );
});

app.options("/api/signup/agent", (c) =>
  c.body(null, 204, {
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "POST, OPTIONS",
    "access-control-allow-headers": "Authorization, Content-Type",
    ...NO_STORE,
  }),
);

app.all("/api/signup/agent", (c) =>
  c.body(null, 405, { allow: "POST", ...NO_STORE }),
);

Create src/index.ts:

// src/index.ts
import { serve } from "@hono/node-server";
import { app } from "./app";

const port = 3004;

serve({ fetch: app.fetch, port, hostname: "127.0.0.1" }, (info) => {
  console.log(`Hono example listening on http://127.0.0.1:${info.port}`);
});

The starter also serves plain-text terms at /terms. From a clone of the docs repository, run:

cd examples/hono
npm install
npm run dev

In another terminal, validate discovery on port 3004:

npx @agentregistrar/discovery@2.1.1 validate http://127.0.0.1:3004/.well-known/agent-signup.json --probe-jwks --probe-endpoints --json

Expected: exit code 0, "valid": true, and zero errors. Full source: Hono starter.

Create src/server.ts:

// src/server.ts
import express from "express";
import { verifyAssertion } from "./verify-assertion";

const PORT = 3005;
const NO_STORE = { "cache-control": "no-store" };

// Local demo only. Use database unique constraints on (iss, human.id) and jti.
const accounts = new Map<string, string>();
const seenJti = new Map<string, string>();

function providerOrigin() {
  return process.env.PROVIDER_ORIGIN ?? `http://127.0.0.1:${PORT}`;
}

function providerAudience() {
  return process.env.PROVIDER_AUDIENCE ?? "express-example";
}

function issuerAllowlist() {
  const configured = (process.env.ISSUER_ALLOWLIST ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter((value) => value.length > 0);
  return configured.length > 0 ? configured : ["https://agentregistrar.dev"];
}

const app = express();
app.disable("x-powered-by");

app.get("/.well-known/agent-signup.json", (_req, res) => {
  const origin = providerOrigin();
  const attestationUri = process.env.ATTESTATION_URI;

  res
    .set({
      "cache-control": "public, max-age=60",
      "access-control-allow-origin": "*",
    })
    .status(200)
    .json({
      protocol: "agent-identity-protocol",
      protocol_version: "2.0",
      audience: providerAudience(),
      provider_name: "Express example",
      provider_url: origin,
      contact: process.env.PROVIDER_CONTACT ?? "security@example.com",
      issuer_allowlist: issuerAllowlist(),
      required_scopes: ["tos:accept"],
      terms: {
        version: process.env.TERMS_VERSION ?? "2026.1",
        url: process.env.TERMS_URL ?? `${origin}/terms`,
      },
      endpoints: {
        agent_signup: `${origin}/api/signup/agent`,
      },
      ...(attestationUri
        ? { attestation: { mode: "broker" as const, uri: attestationUri } }
        : {}),
    });
});

app.options("/.well-known/agent-signup.json", (_req, res) => {
  res
    .set({
      "access-control-allow-origin": "*",
      "access-control-allow-methods": "GET, OPTIONS",
      "access-control-allow-headers": "Content-Type",
    })
    .status(204)
    .end();
});

app.post("/api/signup/agent", async (req, res) => {
  const origin = providerOrigin();
  const errorResponse = (status: number, error: string, description: string) => {
    res.set(NO_STORE).status(status).json({
      error,
      error_description: description,
      retryable: false,
    });
  };

  const result = await verifyAssertion(req.header("authorization"), {
    issuerAllowlist: issuerAllowlist(),
    audience: providerAudience(),
    requiredScopes: ["tos:accept"],
    termsUrl: process.env.TERMS_URL ?? `${origin}/terms`,
    termsSha256: process.env.TERMS_SHA256,
    jwksUrlOverride: process.env.JWKS_URL_OVERRIDE,
  });
  if (!result.ok) return errorResponse(result.status, result.error, result.error_description);

  const claims = result.claims;
  const accountKey = `${claims.iss}:${claims.human.id}`;
  const previous = seenJti.get(claims.jti);
  if (previous !== undefined && previous !== accountKey) {
    return errorResponse(
      409,
      "assertion_replayed",
      "Assertion id used in a conflicting context",
    );
  }
  seenJti.set(claims.jti, accountKey);

  const existing = accounts.get(accountKey);
  if (existing) {
    res
      .set(NO_STORE)
      .status(200)
      .json({ resolution: "resolved", account_id: existing });
    return;
  }

  const accountId = `acct_${crypto.randomUUID()}`;
  accounts.set(accountKey, accountId);
  res.set(NO_STORE).status(201).json({
    resolution: "created",
    account_id: accountId,
    api_key: `key_${crypto.randomUUID()}`,
  });
});

app.options("/api/signup/agent", (_req, res) => {
  res
    .set({
      "access-control-allow-origin": "*",
      "access-control-allow-methods": "POST, OPTIONS",
      "access-control-allow-headers": "Authorization, Content-Type",
      ...NO_STORE,
    })
    .status(204)
    .end();
});

app.all("/api/signup/agent", (_req, res) => {
  res.set({ allow: "POST", ...NO_STORE }).status(405).end();
});

app.listen(PORT, "127.0.0.1", () => {
  console.log(`Express example listening on http://127.0.0.1:${PORT}`);
});

The starter also serves plain-text terms at /terms. From a clone of the docs repository, run:

cd examples/express
npm install
npm run dev

In another terminal, validate discovery on port 3005:

npx @agentregistrar/discovery@2.1.1 validate http://127.0.0.1:3005/.well-known/agent-signup.json --probe-jwks --probe-endpoints --json

Expected: exit code 0, "valid": true, and zero errors. Full source: Express starter.

jose uses Web Crypto globals and runs on Workers without Node compatibility flags. Configure wrangler.jsonc:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "agent-signup-example-cloudflare-workers",
  "main": "src/worker.ts",
  "compatibility_date": "2026-11-22",
  "observability": {
    "enabled": false
  }
}

Create src/worker.ts:

// src/worker.ts
import { verifyAssertion } from "./verify-assertion";

interface Env {
  PROVIDER_ORIGIN?: string;
  PROVIDER_AUDIENCE?: string;
  PROVIDER_CONTACT?: string;
  ISSUER_ALLOWLIST?: string;
  TERMS_VERSION?: string;
  TERMS_URL?: string;
  TERMS_SHA256?: string;
  JWKS_URL_OVERRIDE?: string;
  ATTESTATION_URI?: string;
}

const PORT = 3006;
const NO_STORE = { "cache-control": "no-store" };

// Local demo only. Use D1 or Durable Objects with unique constraints in production.
const accounts = new Map<string, string>();
const seenJti = new Map<string, string>();

function providerOrigin(env: Env) {
  return env.PROVIDER_ORIGIN ?? `http://127.0.0.1:${PORT}`;
}

function providerAudience(env: Env) {
  return env.PROVIDER_AUDIENCE ?? "cloudflare-workers-example";
}

function issuerAllowlist(env: Env) {
  const configured = (env.ISSUER_ALLOWLIST ?? "")
    .split(",")
    .map((value) => value.trim())
    .filter((value) => value.length > 0);
  return configured.length > 0 ? configured : ["https://agentregistrar.dev"];
}

function json(
  body: unknown,
  status: number,
  headers: Record<string, string> = {},
) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { "content-type": "application/json; charset=utf-8", ...headers },
  });
}

function errorResponse(status: number, error: string, description: string) {
  return json(
    { error, error_description: description, retryable: false },
    status,
    NO_STORE,
  );
}

async function handleSignup(request: Request, env: Env) {
  const origin = providerOrigin(env);
  const result = await verifyAssertion(request.headers.get("authorization"), {
    issuerAllowlist: issuerAllowlist(env),
    audience: providerAudience(env),
    requiredScopes: ["tos:accept"],
    termsUrl: env.TERMS_URL ?? `${origin}/terms`,
    termsSha256: env.TERMS_SHA256,
    jwksUrlOverride: env.JWKS_URL_OVERRIDE,
  });
  if (!result.ok) return errorResponse(result.status, result.error, result.error_description);

  const claims = result.claims;
  const accountKey = `${claims.iss}:${claims.human.id}`;
  const previous = seenJti.get(claims.jti);
  if (previous !== undefined && previous !== accountKey) {
    return errorResponse(
      409,
      "assertion_replayed",
      "Assertion id used in a conflicting context",
    );
  }
  seenJti.set(claims.jti, accountKey);

  const existing = accounts.get(accountKey);
  if (existing) {
    return json(
      { resolution: "resolved", account_id: existing },
      200,
      NO_STORE,
    );
  }

  const accountId = `acct_${crypto.randomUUID()}`;
  accounts.set(accountKey, accountId);
  return json(
    {
      resolution: "created",
      account_id: accountId,
      api_key: `key_${crypto.randomUUID()}`,
    },
    201,
    NO_STORE,
  );
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const origin = providerOrigin(env);

    if (url.pathname === "/.well-known/agent-signup.json") {
      if (request.method === "OPTIONS") {
        return new Response(null, {
          status: 204,
          headers: {
            "access-control-allow-origin": "*",
            "access-control-allow-methods": "GET, OPTIONS",
            "access-control-allow-headers": "Content-Type",
          },
        });
      }
      if (request.method === "GET" || request.method === "HEAD") {
        const attestationUri = env.ATTESTATION_URI;

        return json(
          {
            protocol: "agent-identity-protocol",
            protocol_version: "2.0",
            audience: providerAudience(env),
            provider_name: "Cloudflare Workers example",
            provider_url: origin,
            contact: env.PROVIDER_CONTACT ?? "security@example.com",
            issuer_allowlist: issuerAllowlist(env),
            required_scopes: ["tos:accept"],
            terms: {
              version: env.TERMS_VERSION ?? "2026.1",
              url: env.TERMS_URL ?? `${origin}/terms`,
            },
            endpoints: {
              agent_signup: `${origin}/api/signup/agent`,
            },
            ...(attestationUri
              ? { attestation: { mode: "broker" as const, uri: attestationUri } }
              : {}),
          },
          200,
          {
            "cache-control": "public, max-age=60",
            "access-control-allow-origin": "*",
          },
        );
      }
      return new Response(null, {
        status: 405,
        headers: { allow: "GET, OPTIONS" },
      });
    }

    if (url.pathname === "/api/signup/agent") {
      if (request.method === "OPTIONS") {
        return new Response(null, {
          status: 204,
          headers: {
            "access-control-allow-origin": "*",
            "access-control-allow-methods": "POST, OPTIONS",
            "access-control-allow-headers": "Authorization, Content-Type",
            ...NO_STORE,
          },
        });
      }
      if (request.method !== "POST") {
        return new Response(null, {
          status: 405,
          headers: { allow: "POST", ...NO_STORE },
        });
      }
      return handleSignup(request, env);
    }

    return json(
      {
        error: "not_found",
        error_description: "No such endpoint",
        retryable: false,
      },
      404,
      NO_STORE,
    );
  },
};

Set optional bindings under vars in wrangler.jsonc or in .dev.vars. Leave JWKS_URL_OVERRIDE and ATTESTATION_URI unset for local testing. From a clone of the docs repository, run:

cd examples/cloudflare-workers
npm install
npm run dev

npm run dev runs wrangler dev --port 3006, so Wrangler listens on http://127.0.0.1:3006. In another terminal, validate discovery:

npx @agentregistrar/discovery@2.1.1 validate http://127.0.0.1:3006/.well-known/agent-signup.json --probe-jwks --probe-endpoints --json

Expected: exit code 0, "valid": true, and zero errors. Full source: Cloudflare Workers starter.

Platform and deployment notes

Platform Run directly Gotchas
Vercel Next.js or Hono Exclude /.well-known/agent-signup.json and /api/signup/agent from auth middleware matcher and Vercel Attack Challenge Mode. Serverless memory is ephemeral, so back accounts and jti with a database.
Cloudflare Cloudflare Workers or Hono Add a WAF and Bot Fight Mode skip rule for both routes so automated agents receive JSON, not an HTML challenge. Use D1 or Durable Objects for account and jti uniqueness.
Container and PaaS hosts Express, Hono, or Next.js Railway, Fly.io, Render, Heroku, AWS ECS, and GCP Cloud Run terminate TLS in front of the app. Set PROVIDER_ORIGIN to the canonical https:// origin and do not redirect between www and the apex on discovery.
Netlify Functions or Edge Publish public/.well-known/agent-signup.json without a redirect, or serve that path from a Function or Edge route, and route /api/signup/agent to a Function that returns JSON errors.
AWS API Gateway and Lambda, GCP Cloud Functions Lambda or Function Exempt both routes from custom authorizers, and return JSON error envelopes instead of gateway HTML on auth or method failures.
  • Canonical origin: The examples read the public origin from PROVIDER_ORIGIN, and local tests point the verifier at a fixture JWKS with JWKS_URL_OVERRIDE. The older PROVIDER_URL and BROKER_JWKS_URL names map to the same two settings; use the example names in new code.
  • Bot challenges and auth walls: A challenge page, login redirect, or HTML error body fails discovery and signup probes. Allow both paths before any middleware that authenticates human sessions.
  • Dotfiles on Netlify: Netlify can drop or rewrite dotfile paths. Confirm that GET https://<origin>/.well-known/agent-signup.json returns 200 application/json from the deployed site, not a redirect or the single-page app shell.
  • Gateway error shapes: API Gateway and Cloud Functions can replace an integration error with their own HTML or a different status. Map verification failures to the JSON envelope inside the handler.
  • Database constraints: Enforce uniqueness on (iss, human.id). Record each jti with the account it resolved to, and return 409 assertion_replayed when the same jti arrives for a different account.

Notes before deploying

  • Persist accounts and jti: Replace the in-memory Map stores with unique database constraints on (iss, human.id) and jti, or D1 and Durable Objects on Workers, so restarts and concurrent requests stay idempotent.
  • Remove test overrides: Leave JWKS_URL_OVERRIDE unset in production so keys always resolve from <iss>/.well-known/jwks.json.
  • Do not cache signup responses: Set Cache-Control: no-store on every POST /api/signup/agent response because creation responses may carry show-once credentials.
  • Add optional receipts and context later: Once signup works, see Receipts and context guide to return an RP-signed signup_token and a hash-pinned context pointer.

Next steps

sections

type to search.

up/down navigateenter selectesc close