cauthy-auth 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.d.mts CHANGED
@@ -32,6 +32,17 @@ interface McpAuthOptions {
32
32
  jwks?: JWTVerifyGetKey;
33
33
  /** The moment to verify at. Default: now. */
34
34
  now?: () => Date;
35
+ /**
36
+ * Ask Cauthy, besides checking the token here, whether the person still
37
+ * allows the agent (RFC 7662). Then an agent is cut off the moment it is
38
+ * disconnected, not when its token runs out, at the price of a call to
39
+ * Cauthy per token every `cacheSeconds` (default 30). Default: off.
40
+ */
41
+ introspect?: boolean | {
42
+ cacheSeconds?: number;
43
+ };
44
+ /** The fetch to call Cauthy with. Default: the global one. */
45
+ fetch?: typeof fetch;
35
46
  }
36
47
  /** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */
37
48
  declare class McpAuthError extends Error {
package/dist/mcp.d.ts CHANGED
@@ -32,6 +32,17 @@ interface McpAuthOptions {
32
32
  jwks?: JWTVerifyGetKey;
33
33
  /** The moment to verify at. Default: now. */
34
34
  now?: () => Date;
35
+ /**
36
+ * Ask Cauthy, besides checking the token here, whether the person still
37
+ * allows the agent (RFC 7662). Then an agent is cut off the moment it is
38
+ * disconnected, not when its token runs out, at the price of a call to
39
+ * Cauthy per token every `cacheSeconds` (default 30). Default: off.
40
+ */
41
+ introspect?: boolean | {
42
+ cacheSeconds?: number;
43
+ };
44
+ /** The fetch to call Cauthy with. Default: the global one. */
45
+ fetch?: typeof fetch;
35
46
  }
36
47
  /** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */
37
48
  declare class McpAuthError extends Error {
package/dist/mcp.js CHANGED
@@ -95,6 +95,29 @@ function mcpAuth(options = {}) {
95
95
  scopes_supported: options.scopesSupported ?? required,
96
96
  ...options.resourceName ? { resource_name: options.resourceName } : {}
97
97
  });
98
+ const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === "object" ? options.introspect.cacheSeconds : void 0) ?? 30) * 1e3 } : null;
99
+ const answers = /* @__PURE__ */ new Map();
100
+ const stillAllowed = async (token, cacheMs) => {
101
+ const now = Date.now();
102
+ const kept = answers.get(token);
103
+ if (kept && kept.until > now) return kept.active;
104
+ let active = false;
105
+ try {
106
+ const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {
107
+ method: "POST",
108
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
109
+ body: new URLSearchParams({ token })
110
+ });
111
+ if (!res.ok) throw new Error(`introspection answered ${res.status}`);
112
+ active = (await res.json()).active === true;
113
+ } catch (err) {
114
+ if (kept) return kept.active;
115
+ throw new McpAuthError(401, "invalid_token", `could not check the token with Cauthy: ${err instanceof Error ? err.message : "unreachable"}`);
116
+ }
117
+ if (answers.size > 1e4) answers.clear();
118
+ answers.set(token, { active, until: now + cacheMs });
119
+ return active;
120
+ };
98
121
  const verify = async (from, needs = []) => {
99
122
  const token = bearer(from);
100
123
  if (token === "") throw new McpAuthError(401, "invalid_request", "no access token");
@@ -114,6 +137,7 @@ function mcpAuth(options = {}) {
114
137
  const clientId = typeof claims.client_id === "string" ? claims.client_id : "";
115
138
  if (clientId === "") throw new McpAuthError(401, "invalid_token", "not a token issued to an agent");
116
139
  const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
140
+ if (introspect && !await stillAllowed(token, introspect.cacheMs)) throw new McpAuthError(401, "invalid_token", "the person disconnected this agent");
117
141
  const missing = [...required, ...needs].filter((s) => !scopes.includes(s));
118
142
  if (missing.length > 0) throw new McpAuthError(403, "insufficient_scope", `this needs ${missing.join(" ")}`);
119
143
  return {
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mcp.ts","../src/verify.ts"],"sourcesContent":["// An MCP server (or any API) that AI agents use as one of your people.\n//\n// import { mcpAuth } from 'cauthy-auth/mcp'\n// const auth = mcpAuth({ resource: 'https://mcp.example.com/mcp', scopes: ['books:read'] })\n//\n// // Fetch-style (Hono, Next.js, Workers, Bun, Deno):\n// export default { fetch: auth.protect((request, agent) => handleMcp(request, agent)) }\n//\n// // Express or plain Node, with the MCP TypeScript SDK (its transport reads req.auth):\n// app.use(auth.middleware())\n//\n// How an agent gets in, as the MCP specification lays it out: it calls the\n// server, which answers 401 and points at its protected resource metadata\n// (RFC 9728); that names Cauthy as the authorization server; the agent\n// registers itself there, sends the person to sign in and allow it, and comes\n// back with a token issued for this server alone (its `aud`). This module is\n// the server's half: the metadata, the 401 that points at it, and checking\n// the token. The resource must be registered in Cauthy's dashboard (AI\n// agents), with the same address, for the workspace whose people use it.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\n\n/** The person an agent acts for, and what they allowed it. */\nexport interface AgentIdentity {\n /** The person. */\n userId: string\n tenantId: string\n email?: string\n /** The person's roles in the workspace. */\n roles: string[]\n /** What the person allowed the agent to do here. */\n scopes: string[]\n /** The agent (its client_id at Cauthy). */\n clientId: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived. */\n token: string\n}\n\nexport interface McpAuthOptions {\n /** This server's address, as registered in Cauthy. Default: `CAUTHY_MCP_RESOURCE`. */\n resource?: string\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** Scopes every call needs. Default: none. */\n scopes?: string[]\n /** The scopes this server understands, to tell agents (`scopes_supported`). Default: `scopes`. */\n scopesSupported?: string[]\n /** A name for the server, shown by some agents. */\n resourceName?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: () => Date\n}\n\n/** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */\nexport class McpAuthError extends Error {\n constructor(\n readonly status: 401 | 403,\n readonly code: 'invalid_request' | 'invalid_token' | 'insufficient_scope',\n readonly description: string,\n ) {\n super(`cauthy-auth: ${description}`)\n this.name = 'McpAuthError'\n }\n}\n\n/** What the MCP TypeScript SDK reads from `req.auth` (its AuthInfo). */\nexport interface McpAuthInfo {\n token: string\n clientId: string\n scopes: string[]\n /** Seconds since the epoch. */\n expiresAt: number\n resource: URL\n extra: { userId: string; tenantId: string; email?: string; roles: string[] }\n}\n\nexport interface McpAuth {\n /** This server's address, in the form Cauthy compares it in. */\n resource: string\n /** Where the protected resource metadata is served. */\n metadataUrl: string\n /** The protected resource metadata (RFC 9728). */\n metadata(): Record<string, unknown>\n /** The metadata's paths: `/.well-known/oauth-protected-resource` plus this server's path. */\n metadataPaths: string[]\n /** Verifies the `Authorization: Bearer` of a request (or a token). Throws `McpAuthError`. */\n verify(from: string | Request | Headers, needs?: string[]): Promise<AgentIdentity>\n /** The answer to a refused token: 401 or 403, with the `WWW-Authenticate` that points an agent at Cauthy. */\n challenge(error?: McpAuthError): Response\n /** The metadata, when the request asks for it; `null` otherwise. */\n handleMetadata(request: Request): Response | null\n /** Wraps a fetch-style handler: serves the metadata, refuses what has no good token, passes the rest with who it is. */\n protect(handler: (request: Request, agent: AgentIdentity) => Response | Promise<Response>, needs?: string[]): (request: Request) => Promise<Response>\n /**\n * Connect-style middleware (Express, Node's http): serves the metadata,\n * refuses what has no good token, and sets `req.agent` and `req.auth` —\n * what the MCP TypeScript SDK's transport hands its tools as `authInfo`.\n */\n middleware(needs?: string[]): (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void\n}\n\n// The slice of Node's (and Express's) request and response this needs.\ninterface NodeRequest {\n method?: string\n url?: string\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n auth?: McpAuthInfo\n agent?: AgentIdentity\n}\ninterface NodeResponse {\n statusCode: number\n setHeader(name: string, value: string): unknown\n end(body?: string): unknown\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\n/**\n * The address in the one form Cauthy keeps it: scheme and host in lower case,\n * no default port, no trailing slash, no query, no fragment.\n */\nexport function canonicalResource(raw: string): string {\n let u: URL\n try {\n u = new URL(raw.trim())\n } catch {\n throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`)\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new Error('cauthy-auth: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('cauthy-auth: resource may not have a query or a fragment')\n return `${u.protocol}//${u.host}${u.pathname.replace(/\\/+$/, '')}`\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\nfunction quoted(v: string): string {\n return `\"${v.replace(/[\"\\\\]/g, '')}\"`\n}\n\n/** Protects an MCP server with Cauthy. */\nexport function mcpAuth(options: McpAuthOptions = {}): McpAuth {\n const rawResource = options.resource ?? env('CAUTHY_MCP_RESOURCE') ?? ''\n if (rawResource === '') throw new Error('cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set')\n const resource = canonicalResource(rawResource)\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new Error('cauthy-auth: issuer (CAUTHY_ISSUER) is not set')\n const required = options.scopes ?? []\n const url = new URL(resource)\n const path = url.pathname === '/' ? '' : url.pathname\n const metadataPaths = [...new Set([`/.well-known/oauth-protected-resource${path}`, '/.well-known/oauth-protected-resource'])]\n const metadataUrl = `${url.origin}${metadataPaths[0]}`\n\n const metadata = () => ({\n resource,\n authorization_servers: [issuer],\n bearer_methods_supported: ['header'],\n scopes_supported: options.scopesSupported ?? required,\n ...(options.resourceName ? { resource_name: options.resourceName } : {}),\n })\n\n const verify = async (from: string | Request | Headers, needs: string[] = []): Promise<AgentIdentity> => {\n const token = bearer(from)\n if (token === '') throw new McpAuthError(401, 'invalid_request', 'no access token')\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: resource,\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now?.(),\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new McpAuthError(401, 'invalid_token', err instanceof Error ? err.message : 'the token is not valid')\n }\n const clientId = typeof claims.client_id === 'string' ? claims.client_id : ''\n if (clientId === '') throw new McpAuthError(401, 'invalid_token', 'not a token issued to an agent')\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n const missing = [...required, ...needs].filter((s) => !scopes.includes(s))\n if (missing.length > 0) throw new McpAuthError(403, 'insufficient_scope', `this needs ${missing.join(' ')}`)\n return {\n userId: String(claims.sub),\n tenantId: typeof claims.tid === 'string' ? claims.tid : '',\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n scopes,\n clientId,\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n\n const authenticate = (error?: McpAuthError): string => {\n const parts = [`resource_metadata=${quoted(metadataUrl)}`]\n if (error && error.code !== 'invalid_request') {\n parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`)\n }\n // What to ask the person for: said when there is no token or it falls short.\n const scope = error?.code === 'invalid_token' ? [] : required\n if (scope.length > 0) parts.push(`scope=${quoted(scope.join(' '))}`)\n return `Bearer ${parts.join(', ')}`\n }\n\n const challenge = (error?: McpAuthError): Response => {\n const status = error?.status ?? 401\n return new Response(JSON.stringify({ error: error?.code ?? 'invalid_request', error_description: error?.description ?? 'an access token is required' }), {\n status,\n headers: { 'content-type': 'application/json', 'www-authenticate': authenticate(error) },\n })\n }\n\n const metadataResponse = () =>\n new Response(JSON.stringify(metadata()), {\n headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },\n })\n\n const isMetadata = (pathname: string, method = 'GET') => method === 'GET' && metadataPaths.includes(pathname.replace(/\\/+$/, '') || '/')\n\n const handleMetadata = (request: Request): Response | null =>\n isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null\n\n const toAuthInfo = (a: AgentIdentity): McpAuthInfo => ({\n token: a.token,\n clientId: a.clientId,\n scopes: a.scopes,\n expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1000),\n resource: new URL(resource),\n extra: { userId: a.userId, tenantId: a.tenantId, ...(a.email ? { email: a.email } : {}), roles: a.roles },\n })\n\n return {\n resource,\n metadataUrl,\n metadataPaths,\n metadata,\n verify,\n challenge,\n handleMetadata,\n protect(handler, needs) {\n return async (request) => {\n const meta = handleMetadata(request)\n if (meta) return meta\n let agent: AgentIdentity\n try {\n agent = await verify(request, needs)\n } catch (err) {\n if (err instanceof McpAuthError) return challenge(err)\n throw err\n }\n return handler(request, agent)\n }\n },\n middleware(needs) {\n return (req, res, next) => {\n const pathname = (req.originalUrl ?? req.url ?? '/').split('?')[0] ?? '/'\n if (isMetadata(pathname, req.method)) {\n res.statusCode = 200\n res.setHeader('content-type', 'application/json')\n res.setHeader('cache-control', 'public, max-age=3600')\n res.setHeader('access-control-allow-origin', '*')\n res.end(JSON.stringify(metadata()))\n return\n }\n const raw = req.headers.authorization\n const header = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '')\n verify(/^Bearer\\s+/i.test(header) ? header : '', needs).then(\n (agent) => {\n req.agent = agent\n req.auth = toAuthInfo(agent)\n next()\n },\n (err: unknown) => {\n if (!(err instanceof McpAuthError)) return next(err)\n res.statusCode = err.status\n res.setHeader('content-type', 'application/json')\n res.setHeader('www-authenticate', authenticate(err))\n res.end(JSON.stringify({ error: err.code, error_description: err.description }))\n },\n )\n }\n },\n }\n}\n","// A backend that is handed a Cauthy access token: is it real, and whose is it?\n//\n// const who = await verifyToken(request) // or the token itself\n// who.userId, who.tenantId, who.roles\n//\n// Cauthy signs its tokens with a key it publishes (/.well-known/jwks.json), so\n// checking one needs no secret and no call to Cauthy per request: the keys are\n// fetched once and cached. Throws `CauthyTokenError` for anything else: answer\n// it 401.\n\nimport { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'\n\n/** Who a verified access token belongs to. */\nexport interface TokenIdentity {\n /** The person. For a system's own token, the client it identifies as. */\n userId: string\n tenantId: string\n email?: string\n roles: string[]\n /** Set when the token is a system's own and not a person's. */\n system?: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: string) {\n super(`cauthy-auth: token refused: ${reason}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The audience the tokens must carry. Default: `CAUTHY_AUDIENCE`; unchecked when neither is set. */\n audience?: string\n /** Refuse a token of any other workspace. Default: `CAUTHY_TENANT_ID`; unchecked when neither is set. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: Date\n}\n\nconst keys = new Map<string, JWTVerifyGetKey>()\n\n/** Cauthy's published keys, fetched once per issuer and cached. */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = keys.get(issuer)\n if (set === undefined) {\n set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 30_000 })\n keys.set(issuer, set)\n }\n return set\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to. Checked: the signature, against Cauthy's\n * published keys; that Cauthy issued it; that it has not expired; and the\n * audience and the workspace, when given.\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new CauthyTokenError('issuer (CAUTHY_ISSUER) is not set')\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no token')\n\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: options.audience ?? env('CAUTHY_AUDIENCE'),\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now,\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new CauthyTokenError(err instanceof Error ? err.message : 'bad signature')\n }\n\n const tenantId = typeof claims.tid === 'string' ? claims.tid : ''\n const wanted = options.tenantId ?? env('CAUTHY_TENANT_ID')\n if (wanted && tenantId !== wanted) throw new CauthyTokenError('issued for another workspace')\n\n return {\n userId: String(claims.sub),\n tenantId,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,IAAAA,eAAgD;;;ACVhD,kBAAoE;AAqCpE,IAAM,OAAO,oBAAI,IAA6B;AAGvC,SAAS,OAAO,QAAiC;AACtD,MAAI,MAAM,KAAK,IAAI,MAAM;AACzB,MAAI,QAAQ,QAAW;AACrB,cAAM,gCAAmB,IAAI,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mBAAmB,IAAI,YAAY,CAAC,CAAC;AAAA,UACjF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["import_jose"]}
1
+ {"version":3,"sources":["../src/mcp.ts","../src/verify.ts"],"sourcesContent":["// An MCP server (or any API) that AI agents use as one of your people.\n//\n// import { mcpAuth } from 'cauthy-auth/mcp'\n// const auth = mcpAuth({ resource: 'https://mcp.example.com/mcp', scopes: ['books:read'] })\n//\n// // Fetch-style (Hono, Next.js, Workers, Bun, Deno):\n// export default { fetch: auth.protect((request, agent) => handleMcp(request, agent)) }\n//\n// // Express or plain Node, with the MCP TypeScript SDK (its transport reads req.auth):\n// app.use(auth.middleware())\n//\n// How an agent gets in, as the MCP specification lays it out: it calls the\n// server, which answers 401 and points at its protected resource metadata\n// (RFC 9728); that names Cauthy as the authorization server; the agent\n// registers itself there, sends the person to sign in and allow it, and comes\n// back with a token issued for this server alone (its `aud`). This module is\n// the server's half: the metadata, the 401 that points at it, and checking\n// the token. The resource must be registered in Cauthy's dashboard (AI\n// agents), with the same address, for the workspace whose people use it.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\n\n/** The person an agent acts for, and what they allowed it. */\nexport interface AgentIdentity {\n /** The person. */\n userId: string\n tenantId: string\n email?: string\n /** The person's roles in the workspace. */\n roles: string[]\n /** What the person allowed the agent to do here. */\n scopes: string[]\n /** The agent (its client_id at Cauthy). */\n clientId: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived. */\n token: string\n}\n\nexport interface McpAuthOptions {\n /** This server's address, as registered in Cauthy. Default: `CAUTHY_MCP_RESOURCE`. */\n resource?: string\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** Scopes every call needs. Default: none. */\n scopes?: string[]\n /** The scopes this server understands, to tell agents (`scopes_supported`). Default: `scopes`. */\n scopesSupported?: string[]\n /** A name for the server, shown by some agents. */\n resourceName?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: () => Date\n /**\n * Ask Cauthy, besides checking the token here, whether the person still\n * allows the agent (RFC 7662). Then an agent is cut off the moment it is\n * disconnected, not when its token runs out, at the price of a call to\n * Cauthy per token every `cacheSeconds` (default 30). Default: off.\n */\n introspect?: boolean | { cacheSeconds?: number }\n /** The fetch to call Cauthy with. Default: the global one. */\n fetch?: typeof fetch\n}\n\n/** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */\nexport class McpAuthError extends Error {\n constructor(\n readonly status: 401 | 403,\n readonly code: 'invalid_request' | 'invalid_token' | 'insufficient_scope',\n readonly description: string,\n ) {\n super(`cauthy-auth: ${description}`)\n this.name = 'McpAuthError'\n }\n}\n\n/** What the MCP TypeScript SDK reads from `req.auth` (its AuthInfo). */\nexport interface McpAuthInfo {\n token: string\n clientId: string\n scopes: string[]\n /** Seconds since the epoch. */\n expiresAt: number\n resource: URL\n extra: { userId: string; tenantId: string; email?: string; roles: string[] }\n}\n\nexport interface McpAuth {\n /** This server's address, in the form Cauthy compares it in. */\n resource: string\n /** Where the protected resource metadata is served. */\n metadataUrl: string\n /** The protected resource metadata (RFC 9728). */\n metadata(): Record<string, unknown>\n /** The metadata's paths: `/.well-known/oauth-protected-resource` plus this server's path. */\n metadataPaths: string[]\n /** Verifies the `Authorization: Bearer` of a request (or a token). Throws `McpAuthError`. */\n verify(from: string | Request | Headers, needs?: string[]): Promise<AgentIdentity>\n /** The answer to a refused token: 401 or 403, with the `WWW-Authenticate` that points an agent at Cauthy. */\n challenge(error?: McpAuthError): Response\n /** The metadata, when the request asks for it; `null` otherwise. */\n handleMetadata(request: Request): Response | null\n /** Wraps a fetch-style handler: serves the metadata, refuses what has no good token, passes the rest with who it is. */\n protect(handler: (request: Request, agent: AgentIdentity) => Response | Promise<Response>, needs?: string[]): (request: Request) => Promise<Response>\n /**\n * Connect-style middleware (Express, Node's http): serves the metadata,\n * refuses what has no good token, and sets `req.agent` and `req.auth` —\n * what the MCP TypeScript SDK's transport hands its tools as `authInfo`.\n */\n middleware(needs?: string[]): (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void\n}\n\n// The slice of Node's (and Express's) request and response this needs.\ninterface NodeRequest {\n method?: string\n url?: string\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n auth?: McpAuthInfo\n agent?: AgentIdentity\n}\ninterface NodeResponse {\n statusCode: number\n setHeader(name: string, value: string): unknown\n end(body?: string): unknown\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\n/**\n * The address in the one form Cauthy keeps it: scheme and host in lower case,\n * no default port, no trailing slash, no query, no fragment.\n */\nexport function canonicalResource(raw: string): string {\n let u: URL\n try {\n u = new URL(raw.trim())\n } catch {\n throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`)\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new Error('cauthy-auth: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('cauthy-auth: resource may not have a query or a fragment')\n return `${u.protocol}//${u.host}${u.pathname.replace(/\\/+$/, '')}`\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\nfunction quoted(v: string): string {\n return `\"${v.replace(/[\"\\\\]/g, '')}\"`\n}\n\n/** Protects an MCP server with Cauthy. */\nexport function mcpAuth(options: McpAuthOptions = {}): McpAuth {\n const rawResource = options.resource ?? env('CAUTHY_MCP_RESOURCE') ?? ''\n if (rawResource === '') throw new Error('cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set')\n const resource = canonicalResource(rawResource)\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new Error('cauthy-auth: issuer (CAUTHY_ISSUER) is not set')\n const required = options.scopes ?? []\n const url = new URL(resource)\n const path = url.pathname === '/' ? '' : url.pathname\n const metadataPaths = [...new Set([`/.well-known/oauth-protected-resource${path}`, '/.well-known/oauth-protected-resource'])]\n const metadataUrl = `${url.origin}${metadataPaths[0]}`\n\n const metadata = () => ({\n resource,\n authorization_servers: [issuer],\n bearer_methods_supported: ['header'],\n scopes_supported: options.scopesSupported ?? required,\n ...(options.resourceName ? { resource_name: options.resourceName } : {}),\n })\n\n const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === 'object' ? options.introspect.cacheSeconds : undefined) ?? 30) * 1000 } : null\n const answers = new Map<string, { active: boolean; until: number }>()\n const stillAllowed = async (token: string, cacheMs: number): Promise<boolean> => {\n const now = Date.now()\n const kept = answers.get(token)\n if (kept && kept.until > now) return kept.active\n let active = false\n try {\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body: new URLSearchParams({ token }),\n })\n if (!res.ok) throw new Error(`introspection answered ${res.status}`)\n active = ((await res.json()) as { active?: unknown }).active === true\n } catch (err) {\n // Cauthy could not be asked: what it last said holds.\n if (kept) return kept.active\n throw new McpAuthError(401, 'invalid_token', `could not check the token with Cauthy: ${err instanceof Error ? err.message : 'unreachable'}`)\n }\n if (answers.size > 10_000) answers.clear()\n answers.set(token, { active, until: now + cacheMs })\n return active\n }\n\n const verify = async (from: string | Request | Headers, needs: string[] = []): Promise<AgentIdentity> => {\n const token = bearer(from)\n if (token === '') throw new McpAuthError(401, 'invalid_request', 'no access token')\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: resource,\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now?.(),\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new McpAuthError(401, 'invalid_token', err instanceof Error ? err.message : 'the token is not valid')\n }\n const clientId = typeof claims.client_id === 'string' ? claims.client_id : ''\n if (clientId === '') throw new McpAuthError(401, 'invalid_token', 'not a token issued to an agent')\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n if (introspect && !(await stillAllowed(token, introspect.cacheMs))) throw new McpAuthError(401, 'invalid_token', 'the person disconnected this agent')\n const missing = [...required, ...needs].filter((s) => !scopes.includes(s))\n if (missing.length > 0) throw new McpAuthError(403, 'insufficient_scope', `this needs ${missing.join(' ')}`)\n return {\n userId: String(claims.sub),\n tenantId: typeof claims.tid === 'string' ? claims.tid : '',\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n scopes,\n clientId,\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n\n const authenticate = (error?: McpAuthError): string => {\n const parts = [`resource_metadata=${quoted(metadataUrl)}`]\n if (error && error.code !== 'invalid_request') {\n parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`)\n }\n // What to ask the person for: said when there is no token or it falls short.\n const scope = error?.code === 'invalid_token' ? [] : required\n if (scope.length > 0) parts.push(`scope=${quoted(scope.join(' '))}`)\n return `Bearer ${parts.join(', ')}`\n }\n\n const challenge = (error?: McpAuthError): Response => {\n const status = error?.status ?? 401\n return new Response(JSON.stringify({ error: error?.code ?? 'invalid_request', error_description: error?.description ?? 'an access token is required' }), {\n status,\n headers: { 'content-type': 'application/json', 'www-authenticate': authenticate(error) },\n })\n }\n\n const metadataResponse = () =>\n new Response(JSON.stringify(metadata()), {\n headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },\n })\n\n const isMetadata = (pathname: string, method = 'GET') => method === 'GET' && metadataPaths.includes(pathname.replace(/\\/+$/, '') || '/')\n\n const handleMetadata = (request: Request): Response | null =>\n isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null\n\n const toAuthInfo = (a: AgentIdentity): McpAuthInfo => ({\n token: a.token,\n clientId: a.clientId,\n scopes: a.scopes,\n expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1000),\n resource: new URL(resource),\n extra: { userId: a.userId, tenantId: a.tenantId, ...(a.email ? { email: a.email } : {}), roles: a.roles },\n })\n\n return {\n resource,\n metadataUrl,\n metadataPaths,\n metadata,\n verify,\n challenge,\n handleMetadata,\n protect(handler, needs) {\n return async (request) => {\n const meta = handleMetadata(request)\n if (meta) return meta\n let agent: AgentIdentity\n try {\n agent = await verify(request, needs)\n } catch (err) {\n if (err instanceof McpAuthError) return challenge(err)\n throw err\n }\n return handler(request, agent)\n }\n },\n middleware(needs) {\n return (req, res, next) => {\n const pathname = (req.originalUrl ?? req.url ?? '/').split('?')[0] ?? '/'\n if (isMetadata(pathname, req.method)) {\n res.statusCode = 200\n res.setHeader('content-type', 'application/json')\n res.setHeader('cache-control', 'public, max-age=3600')\n res.setHeader('access-control-allow-origin', '*')\n res.end(JSON.stringify(metadata()))\n return\n }\n const raw = req.headers.authorization\n const header = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '')\n verify(/^Bearer\\s+/i.test(header) ? header : '', needs).then(\n (agent) => {\n req.agent = agent\n req.auth = toAuthInfo(agent)\n next()\n },\n (err: unknown) => {\n if (!(err instanceof McpAuthError)) return next(err)\n res.statusCode = err.status\n res.setHeader('content-type', 'application/json')\n res.setHeader('www-authenticate', authenticate(err))\n res.end(JSON.stringify({ error: err.code, error_description: err.description }))\n },\n )\n }\n },\n }\n}\n","// A backend that is handed a Cauthy access token: is it real, and whose is it?\n//\n// const who = await verifyToken(request) // or the token itself\n// who.userId, who.tenantId, who.roles\n//\n// Cauthy signs its tokens with a key it publishes (/.well-known/jwks.json), so\n// checking one needs no secret and no call to Cauthy per request: the keys are\n// fetched once and cached. Throws `CauthyTokenError` for anything else: answer\n// it 401.\n\nimport { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'\n\n/** Who a verified access token belongs to. */\nexport interface TokenIdentity {\n /** The person. For a system's own token, the client it identifies as. */\n userId: string\n tenantId: string\n email?: string\n roles: string[]\n /** Set when the token is a system's own and not a person's. */\n system?: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: string) {\n super(`cauthy-auth: token refused: ${reason}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The audience the tokens must carry. Default: `CAUTHY_AUDIENCE`; unchecked when neither is set. */\n audience?: string\n /** Refuse a token of any other workspace. Default: `CAUTHY_TENANT_ID`; unchecked when neither is set. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: Date\n}\n\nconst keys = new Map<string, JWTVerifyGetKey>()\n\n/** Cauthy's published keys, fetched once per issuer and cached. */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = keys.get(issuer)\n if (set === undefined) {\n set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 30_000 })\n keys.set(issuer, set)\n }\n return set\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to. Checked: the signature, against Cauthy's\n * published keys; that Cauthy issued it; that it has not expired; and the\n * audience and the workspace, when given.\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new CauthyTokenError('issuer (CAUTHY_ISSUER) is not set')\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no token')\n\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: options.audience ?? env('CAUTHY_AUDIENCE'),\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now,\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new CauthyTokenError(err instanceof Error ? err.message : 'bad signature')\n }\n\n const tenantId = typeof claims.tid === 'string' ? claims.tid : ''\n const wanted = options.tenantId ?? env('CAUTHY_TENANT_ID')\n if (wanted && tenantId !== wanted) throw new CauthyTokenError('issued for another workspace')\n\n return {\n userId: String(claims.sub),\n tenantId,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,IAAAA,eAAgD;;;ACVhD,kBAAoE;AAqCpE,IAAM,OAAO,oBAAI,IAA6B;AAGvC,SAAS,OAAO,QAAiC;AACtD,MAAI,MAAM,KAAK,IAAI,MAAM;AACzB,MAAI,QAAQ,QAAW;AACrB,cAAM,gCAAmB,IAAI,IAAI,GAAG,MAAM,wBAAwB,GAAG,EAAE,kBAAkB,IAAO,CAAC;AACjG,SAAK,IAAI,QAA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Ac,QAAO,UAAU,GAAG;AACrD,gBAAM;AAAA,QACR;AACA,eAAO,QAAQ,SAAS,KAAK;AAAA,MAC/B;AAAA,IACF;AAAA,IACA,WAAW,OAAO;AAChB,aAAO,CAAC,KAAK,KAAK,SAAS;AACzB,cAAM,YAAY,IAAI,eAAe,IAAI,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK;AACtE,YAAI,WAAW,UAAU,IAAI,MAAM,GAAG;AACpC,cAAI,aAAa;AACjB,cAAI,UAAU,gBAAgB,kBAAkB;AAChD,cAAI,UAAU,iBAAiB,sBAAsB;AACrD,cAAI,UAAU,+BAA+B,GAAG;AAChD,cAAI,IAAI,KAAK,UAAU,SAAS,CAAC,CAAC;AAClC;AAAA,QACF;AACA,cAAM,MAAM,IAAI,QAAQ;AACxB,cAAM,SAAS,MAAM,QAAQ,GAAG,IAAK,IAAI,CAAC,KAAK,KAAO,OAAO;AAC7D,eAAO,cAAc,KAAK,MAAM,IAAI,SAAS,IAAI,KAAK,EAAE;AAAA,UACtD,CAAC,UAAU;AACT,gBAAI,QAAQ;AACZ,gBAAI,OAAO,WAAW,KAAK;AAC3B,iBAAK;AAAA,UACP;AAAA,UACA,CAAC,QAAiB;AAChB,gBAAI,EAAE,eAAe,cAAe,QAAO,KAAK,GAAG;AACnD,gBAAI,aAAa,IAAI;AACrB,gBAAI,UAAU,gBAAgB,kBAAkB;AAChD,gBAAI,UAAU,oBAAoB,aAAa,GAAG,CAAC;AACnD,gBAAI,IAAI,KAAK,UAAU,EAAE,OAAO,IAAI,MAAM,mBAAmB,IAAI,YAAY,CAAC,CAAC;AAAA,UACjF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["import_jose"]}
package/dist/mcp.mjs CHANGED
@@ -69,6 +69,29 @@ function mcpAuth(options = {}) {
69
69
  scopes_supported: options.scopesSupported ?? required,
70
70
  ...options.resourceName ? { resource_name: options.resourceName } : {}
71
71
  });
72
+ const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === "object" ? options.introspect.cacheSeconds : void 0) ?? 30) * 1e3 } : null;
73
+ const answers = /* @__PURE__ */ new Map();
74
+ const stillAllowed = async (token, cacheMs) => {
75
+ const now = Date.now();
76
+ const kept = answers.get(token);
77
+ if (kept && kept.until > now) return kept.active;
78
+ let active = false;
79
+ try {
80
+ const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {
81
+ method: "POST",
82
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
83
+ body: new URLSearchParams({ token })
84
+ });
85
+ if (!res.ok) throw new Error(`introspection answered ${res.status}`);
86
+ active = (await res.json()).active === true;
87
+ } catch (err) {
88
+ if (kept) return kept.active;
89
+ throw new McpAuthError(401, "invalid_token", `could not check the token with Cauthy: ${err instanceof Error ? err.message : "unreachable"}`);
90
+ }
91
+ if (answers.size > 1e4) answers.clear();
92
+ answers.set(token, { active, until: now + cacheMs });
93
+ return active;
94
+ };
72
95
  const verify = async (from, needs = []) => {
73
96
  const token = bearer(from);
74
97
  if (token === "") throw new McpAuthError(401, "invalid_request", "no access token");
@@ -88,6 +111,7 @@ function mcpAuth(options = {}) {
88
111
  const clientId = typeof claims.client_id === "string" ? claims.client_id : "";
89
112
  if (clientId === "") throw new McpAuthError(401, "invalid_token", "not a token issued to an agent");
90
113
  const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
114
+ if (introspect && !await stillAllowed(token, introspect.cacheMs)) throw new McpAuthError(401, "invalid_token", "the person disconnected this agent");
91
115
  const missing = [...required, ...needs].filter((s) => !scopes.includes(s));
92
116
  if (missing.length > 0) throw new McpAuthError(403, "insufficient_scope", `this needs ${missing.join(" ")}`);
93
117
  return {
package/dist/mcp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mcp.ts","../src/verify.ts"],"sourcesContent":["// An MCP server (or any API) that AI agents use as one of your people.\n//\n// import { mcpAuth } from 'cauthy-auth/mcp'\n// const auth = mcpAuth({ resource: 'https://mcp.example.com/mcp', scopes: ['books:read'] })\n//\n// // Fetch-style (Hono, Next.js, Workers, Bun, Deno):\n// export default { fetch: auth.protect((request, agent) => handleMcp(request, agent)) }\n//\n// // Express or plain Node, with the MCP TypeScript SDK (its transport reads req.auth):\n// app.use(auth.middleware())\n//\n// How an agent gets in, as the MCP specification lays it out: it calls the\n// server, which answers 401 and points at its protected resource metadata\n// (RFC 9728); that names Cauthy as the authorization server; the agent\n// registers itself there, sends the person to sign in and allow it, and comes\n// back with a token issued for this server alone (its `aud`). This module is\n// the server's half: the metadata, the 401 that points at it, and checking\n// the token. The resource must be registered in Cauthy's dashboard (AI\n// agents), with the same address, for the workspace whose people use it.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\n\n/** The person an agent acts for, and what they allowed it. */\nexport interface AgentIdentity {\n /** The person. */\n userId: string\n tenantId: string\n email?: string\n /** The person's roles in the workspace. */\n roles: string[]\n /** What the person allowed the agent to do here. */\n scopes: string[]\n /** The agent (its client_id at Cauthy). */\n clientId: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived. */\n token: string\n}\n\nexport interface McpAuthOptions {\n /** This server's address, as registered in Cauthy. Default: `CAUTHY_MCP_RESOURCE`. */\n resource?: string\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** Scopes every call needs. Default: none. */\n scopes?: string[]\n /** The scopes this server understands, to tell agents (`scopes_supported`). Default: `scopes`. */\n scopesSupported?: string[]\n /** A name for the server, shown by some agents. */\n resourceName?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: () => Date\n}\n\n/** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */\nexport class McpAuthError extends Error {\n constructor(\n readonly status: 401 | 403,\n readonly code: 'invalid_request' | 'invalid_token' | 'insufficient_scope',\n readonly description: string,\n ) {\n super(`cauthy-auth: ${description}`)\n this.name = 'McpAuthError'\n }\n}\n\n/** What the MCP TypeScript SDK reads from `req.auth` (its AuthInfo). */\nexport interface McpAuthInfo {\n token: string\n clientId: string\n scopes: string[]\n /** Seconds since the epoch. */\n expiresAt: number\n resource: URL\n extra: { userId: string; tenantId: string; email?: string; roles: string[] }\n}\n\nexport interface McpAuth {\n /** This server's address, in the form Cauthy compares it in. */\n resource: string\n /** Where the protected resource metadata is served. */\n metadataUrl: string\n /** The protected resource metadata (RFC 9728). */\n metadata(): Record<string, unknown>\n /** The metadata's paths: `/.well-known/oauth-protected-resource` plus this server's path. */\n metadataPaths: string[]\n /** Verifies the `Authorization: Bearer` of a request (or a token). Throws `McpAuthError`. */\n verify(from: string | Request | Headers, needs?: string[]): Promise<AgentIdentity>\n /** The answer to a refused token: 401 or 403, with the `WWW-Authenticate` that points an agent at Cauthy. */\n challenge(error?: McpAuthError): Response\n /** The metadata, when the request asks for it; `null` otherwise. */\n handleMetadata(request: Request): Response | null\n /** Wraps a fetch-style handler: serves the metadata, refuses what has no good token, passes the rest with who it is. */\n protect(handler: (request: Request, agent: AgentIdentity) => Response | Promise<Response>, needs?: string[]): (request: Request) => Promise<Response>\n /**\n * Connect-style middleware (Express, Node's http): serves the metadata,\n * refuses what has no good token, and sets `req.agent` and `req.auth` —\n * what the MCP TypeScript SDK's transport hands its tools as `authInfo`.\n */\n middleware(needs?: string[]): (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void\n}\n\n// The slice of Node's (and Express's) request and response this needs.\ninterface NodeRequest {\n method?: string\n url?: string\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n auth?: McpAuthInfo\n agent?: AgentIdentity\n}\ninterface NodeResponse {\n statusCode: number\n setHeader(name: string, value: string): unknown\n end(body?: string): unknown\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\n/**\n * The address in the one form Cauthy keeps it: scheme and host in lower case,\n * no default port, no trailing slash, no query, no fragment.\n */\nexport function canonicalResource(raw: string): string {\n let u: URL\n try {\n u = new URL(raw.trim())\n } catch {\n throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`)\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new Error('cauthy-auth: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('cauthy-auth: resource may not have a query or a fragment')\n return `${u.protocol}//${u.host}${u.pathname.replace(/\\/+$/, '')}`\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\nfunction quoted(v: string): string {\n return `\"${v.replace(/[\"\\\\]/g, '')}\"`\n}\n\n/** Protects an MCP server with Cauthy. */\nexport function mcpAuth(options: McpAuthOptions = {}): McpAuth {\n const rawResource = options.resource ?? env('CAUTHY_MCP_RESOURCE') ?? ''\n if (rawResource === '') throw new Error('cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set')\n const resource = canonicalResource(rawResource)\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new Error('cauthy-auth: issuer (CAUTHY_ISSUER) is not set')\n const required = options.scopes ?? []\n const url = new URL(resource)\n const path = url.pathname === '/' ? '' : url.pathname\n const metadataPaths = [...new Set([`/.well-known/oauth-protected-resource${path}`, '/.well-known/oauth-protected-resource'])]\n const metadataUrl = `${url.origin}${metadataPaths[0]}`\n\n const metadata = () => ({\n resource,\n authorization_servers: [issuer],\n bearer_methods_supported: ['header'],\n scopes_supported: options.scopesSupported ?? required,\n ...(options.resourceName ? { resource_name: options.resourceName } : {}),\n })\n\n const verify = async (from: string | Request | Headers, needs: string[] = []): Promise<AgentIdentity> => {\n const token = bearer(from)\n if (token === '') throw new McpAuthError(401, 'invalid_request', 'no access token')\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: resource,\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now?.(),\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new McpAuthError(401, 'invalid_token', err instanceof Error ? err.message : 'the token is not valid')\n }\n const clientId = typeof claims.client_id === 'string' ? claims.client_id : ''\n if (clientId === '') throw new McpAuthError(401, 'invalid_token', 'not a token issued to an agent')\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n const missing = [...required, ...needs].filter((s) => !scopes.includes(s))\n if (missing.length > 0) throw new McpAuthError(403, 'insufficient_scope', `this needs ${missing.join(' ')}`)\n return {\n userId: String(claims.sub),\n tenantId: typeof claims.tid === 'string' ? claims.tid : '',\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n scopes,\n clientId,\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n\n const authenticate = (error?: McpAuthError): string => {\n const parts = [`resource_metadata=${quoted(metadataUrl)}`]\n if (error && error.code !== 'invalid_request') {\n parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`)\n }\n // What to ask the person for: said when there is no token or it falls short.\n const scope = error?.code === 'invalid_token' ? [] : required\n if (scope.length > 0) parts.push(`scope=${quoted(scope.join(' '))}`)\n return `Bearer ${parts.join(', ')}`\n }\n\n const challenge = (error?: McpAuthError): Response => {\n const status = error?.status ?? 401\n return new Response(JSON.stringify({ error: error?.code ?? 'invalid_request', error_description: error?.description ?? 'an access token is required' }), {\n status,\n headers: { 'content-type': 'application/json', 'www-authenticate': authenticate(error) },\n })\n }\n\n const metadataResponse = () =>\n new Response(JSON.stringify(metadata()), {\n headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },\n })\n\n const isMetadata = (pathname: string, method = 'GET') => method === 'GET' && metadataPaths.includes(pathname.replace(/\\/+$/, '') || '/')\n\n const handleMetadata = (request: Request): Response | null =>\n isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null\n\n const toAuthInfo = (a: AgentIdentity): McpAuthInfo => ({\n token: a.token,\n clientId: a.clientId,\n scopes: a.scopes,\n expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1000),\n resource: new URL(resource),\n extra: { userId: a.userId, tenantId: a.tenantId, ...(a.email ? { email: a.email } : {}), roles: a.roles },\n })\n\n return {\n resource,\n metadataUrl,\n metadataPaths,\n metadata,\n verify,\n challenge,\n handleMetadata,\n protect(handler, needs) {\n return async (request) => {\n const meta = handleMetadata(request)\n if (meta) return meta\n let agent: AgentIdentity\n try {\n agent = await verify(request, needs)\n } catch (err) {\n if (err instanceof McpAuthError) return challenge(err)\n throw err\n }\n return handler(request, agent)\n }\n },\n middleware(needs) {\n return (req, res, next) => {\n const pathname = (req.originalUrl ?? req.url ?? '/').split('?')[0] ?? '/'\n if (isMetadata(pathname, req.method)) {\n res.statusCode = 200\n res.setHeader('content-type', 'application/json')\n res.setHeader('cache-control', 'public, max-age=3600')\n res.setHeader('access-control-allow-origin', '*')\n res.end(JSON.stringify(metadata()))\n return\n }\n const raw = req.headers.authorization\n const header = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '')\n verify(/^Bearer\\s+/i.test(header) ? header : '', needs).then(\n (agent) => {\n req.agent = agent\n req.auth = toAuthInfo(agent)\n next()\n },\n (err: unknown) => {\n if (!(err instanceof McpAuthError)) return next(err)\n res.statusCode = err.status\n res.setHeader('content-type', 'application/json')\n res.setHeader('www-authenticate', authenticate(err))\n res.end(JSON.stringify({ error: err.code, error_description: err.description }))\n },\n )\n }\n },\n }\n}\n","// A backend that is handed a Cauthy access token: is it real, and whose is it?\n//\n// const who = await verifyToken(request) // or the token itself\n// who.userId, who.tenantId, who.roles\n//\n// Cauthy signs its tokens with a key it publishes (/.well-known/jwks.json), so\n// checking one needs no secret and no call to Cauthy per request: the keys are\n// fetched once and cached. Throws `CauthyTokenError` for anything else: answer\n// it 401.\n\nimport { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'\n\n/** Who a verified access token belongs to. */\nexport interface TokenIdentity {\n /** The person. For a system's own token, the client it identifies as. */\n userId: string\n tenantId: string\n email?: string\n roles: string[]\n /** Set when the token is a system's own and not a person's. */\n system?: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: string) {\n super(`cauthy-auth: token refused: ${reason}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The audience the tokens must carry. Default: `CAUTHY_AUDIENCE`; unchecked when neither is set. */\n audience?: string\n /** Refuse a token of any other workspace. Default: `CAUTHY_TENANT_ID`; unchecked when neither is set. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: Date\n}\n\nconst keys = new Map<string, JWTVerifyGetKey>()\n\n/** Cauthy's published keys, fetched once per issuer and cached. */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = keys.get(issuer)\n if (set === undefined) {\n set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 30_000 })\n keys.set(issuer, set)\n }\n return set\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to. Checked: the signature, against Cauthy's\n * published keys; that Cauthy issued it; that it has not expired; and the\n * audience and the workspace, when given.\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new CauthyTokenError('issuer (CAUTHY_ISSUER) is not set')\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no token')\n\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: options.audience ?? env('CAUTHY_AUDIENCE'),\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now,\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new CauthyTokenError(err instanceof Error ? err.message : 'bad signature')\n }\n\n const tenantId = typeof claims.tid === 'string' ? claims.tid : ''\n const wanted = options.tenantId ?? env('CAUTHY_TENANT_ID')\n if (wanted && tenantId !== wanted) throw new CauthyTokenError('issued for another workspace')\n\n return {\n userId: String(claims.sub),\n tenantId,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n}\n"],"mappings":";AAoBA,SAAS,aAAAA,kBAAuC;;;ACVhD,SAAS,oBAAoB,iBAAuC;AAqCpE,IAAM,OAAO,oBAAI,IAA6B;AAGvC,SAAS,OAAO,QAAiC;AACtD,MAAI,MAAM,KAAK,IAAI,MAAM;AACzB,MAAI,QAAQ,QAAW;AACrB,UAAM,mBAAmB,IAAI,IAAI,GAAG,MA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YAAY,CAAC,CAAC;AAAA,UACjF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["jwtVerify","jwtVerify"]}
1
+ {"version":3,"sources":["../src/mcp.ts","../src/verify.ts"],"sourcesContent":["// An MCP server (or any API) that AI agents use as one of your people.\n//\n// import { mcpAuth } from 'cauthy-auth/mcp'\n// const auth = mcpAuth({ resource: 'https://mcp.example.com/mcp', scopes: ['books:read'] })\n//\n// // Fetch-style (Hono, Next.js, Workers, Bun, Deno):\n// export default { fetch: auth.protect((request, agent) => handleMcp(request, agent)) }\n//\n// // Express or plain Node, with the MCP TypeScript SDK (its transport reads req.auth):\n// app.use(auth.middleware())\n//\n// How an agent gets in, as the MCP specification lays it out: it calls the\n// server, which answers 401 and points at its protected resource metadata\n// (RFC 9728); that names Cauthy as the authorization server; the agent\n// registers itself there, sends the person to sign in and allow it, and comes\n// back with a token issued for this server alone (its `aud`). This module is\n// the server's half: the metadata, the 401 that points at it, and checking\n// the token. The resource must be registered in Cauthy's dashboard (AI\n// agents), with the same address, for the workspace whose people use it.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\n\n/** The person an agent acts for, and what they allowed it. */\nexport interface AgentIdentity {\n /** The person. */\n userId: string\n tenantId: string\n email?: string\n /** The person's roles in the workspace. */\n roles: string[]\n /** What the person allowed the agent to do here. */\n scopes: string[]\n /** The agent (its client_id at Cauthy). */\n clientId: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived. */\n token: string\n}\n\nexport interface McpAuthOptions {\n /** This server's address, as registered in Cauthy. Default: `CAUTHY_MCP_RESOURCE`. */\n resource?: string\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** Scopes every call needs. Default: none. */\n scopes?: string[]\n /** The scopes this server understands, to tell agents (`scopes_supported`). Default: `scopes`. */\n scopesSupported?: string[]\n /** A name for the server, shown by some agents. */\n resourceName?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: () => Date\n /**\n * Ask Cauthy, besides checking the token here, whether the person still\n * allows the agent (RFC 7662). Then an agent is cut off the moment it is\n * disconnected, not when its token runs out, at the price of a call to\n * Cauthy per token every `cacheSeconds` (default 30). Default: off.\n */\n introspect?: boolean | { cacheSeconds?: number }\n /** The fetch to call Cauthy with. Default: the global one. */\n fetch?: typeof fetch\n}\n\n/** A token refused: `status` is 401 (no token, or not a good one) or 403 (a scope missing). */\nexport class McpAuthError extends Error {\n constructor(\n readonly status: 401 | 403,\n readonly code: 'invalid_request' | 'invalid_token' | 'insufficient_scope',\n readonly description: string,\n ) {\n super(`cauthy-auth: ${description}`)\n this.name = 'McpAuthError'\n }\n}\n\n/** What the MCP TypeScript SDK reads from `req.auth` (its AuthInfo). */\nexport interface McpAuthInfo {\n token: string\n clientId: string\n scopes: string[]\n /** Seconds since the epoch. */\n expiresAt: number\n resource: URL\n extra: { userId: string; tenantId: string; email?: string; roles: string[] }\n}\n\nexport interface McpAuth {\n /** This server's address, in the form Cauthy compares it in. */\n resource: string\n /** Where the protected resource metadata is served. */\n metadataUrl: string\n /** The protected resource metadata (RFC 9728). */\n metadata(): Record<string, unknown>\n /** The metadata's paths: `/.well-known/oauth-protected-resource` plus this server's path. */\n metadataPaths: string[]\n /** Verifies the `Authorization: Bearer` of a request (or a token). Throws `McpAuthError`. */\n verify(from: string | Request | Headers, needs?: string[]): Promise<AgentIdentity>\n /** The answer to a refused token: 401 or 403, with the `WWW-Authenticate` that points an agent at Cauthy. */\n challenge(error?: McpAuthError): Response\n /** The metadata, when the request asks for it; `null` otherwise. */\n handleMetadata(request: Request): Response | null\n /** Wraps a fetch-style handler: serves the metadata, refuses what has no good token, passes the rest with who it is. */\n protect(handler: (request: Request, agent: AgentIdentity) => Response | Promise<Response>, needs?: string[]): (request: Request) => Promise<Response>\n /**\n * Connect-style middleware (Express, Node's http): serves the metadata,\n * refuses what has no good token, and sets `req.agent` and `req.auth` —\n * what the MCP TypeScript SDK's transport hands its tools as `authInfo`.\n */\n middleware(needs?: string[]): (req: NodeRequest, res: NodeResponse, next: (err?: unknown) => void) => void\n}\n\n// The slice of Node's (and Express's) request and response this needs.\ninterface NodeRequest {\n method?: string\n url?: string\n originalUrl?: string\n headers: Record<string, string | string[] | undefined>\n auth?: McpAuthInfo\n agent?: AgentIdentity\n}\ninterface NodeResponse {\n statusCode: number\n setHeader(name: string, value: string): unknown\n end(body?: string): unknown\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\n/**\n * The address in the one form Cauthy keeps it: scheme and host in lower case,\n * no default port, no trailing slash, no query, no fragment.\n */\nexport function canonicalResource(raw: string): string {\n let u: URL\n try {\n u = new URL(raw.trim())\n } catch {\n throw new Error(`cauthy-auth: resource ${JSON.stringify(raw)} is not an absolute address`)\n }\n const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '[::1]'\n if (u.protocol !== 'https:' && !(u.protocol === 'http:' && local)) {\n throw new Error('cauthy-auth: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('cauthy-auth: resource may not have a query or a fragment')\n return `${u.protocol}//${u.host}${u.pathname.replace(/\\/+$/, '')}`\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\nfunction quoted(v: string): string {\n return `\"${v.replace(/[\"\\\\]/g, '')}\"`\n}\n\n/** Protects an MCP server with Cauthy. */\nexport function mcpAuth(options: McpAuthOptions = {}): McpAuth {\n const rawResource = options.resource ?? env('CAUTHY_MCP_RESOURCE') ?? ''\n if (rawResource === '') throw new Error('cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set')\n const resource = canonicalResource(rawResource)\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new Error('cauthy-auth: issuer (CAUTHY_ISSUER) is not set')\n const required = options.scopes ?? []\n const url = new URL(resource)\n const path = url.pathname === '/' ? '' : url.pathname\n const metadataPaths = [...new Set([`/.well-known/oauth-protected-resource${path}`, '/.well-known/oauth-protected-resource'])]\n const metadataUrl = `${url.origin}${metadataPaths[0]}`\n\n const metadata = () => ({\n resource,\n authorization_servers: [issuer],\n bearer_methods_supported: ['header'],\n scopes_supported: options.scopesSupported ?? required,\n ...(options.resourceName ? { resource_name: options.resourceName } : {}),\n })\n\n const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === 'object' ? options.introspect.cacheSeconds : undefined) ?? 30) * 1000 } : null\n const answers = new Map<string, { active: boolean; until: number }>()\n const stillAllowed = async (token: string, cacheMs: number): Promise<boolean> => {\n const now = Date.now()\n const kept = answers.get(token)\n if (kept && kept.until > now) return kept.active\n let active = false\n try {\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },\n body: new URLSearchParams({ token }),\n })\n if (!res.ok) throw new Error(`introspection answered ${res.status}`)\n active = ((await res.json()) as { active?: unknown }).active === true\n } catch (err) {\n // Cauthy could not be asked: what it last said holds.\n if (kept) return kept.active\n throw new McpAuthError(401, 'invalid_token', `could not check the token with Cauthy: ${err instanceof Error ? err.message : 'unreachable'}`)\n }\n if (answers.size > 10_000) answers.clear()\n answers.set(token, { active, until: now + cacheMs })\n return active\n }\n\n const verify = async (from: string | Request | Headers, needs: string[] = []): Promise<AgentIdentity> => {\n const token = bearer(from)\n if (token === '') throw new McpAuthError(401, 'invalid_request', 'no access token')\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: resource,\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now?.(),\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new McpAuthError(401, 'invalid_token', err instanceof Error ? err.message : 'the token is not valid')\n }\n const clientId = typeof claims.client_id === 'string' ? claims.client_id : ''\n if (clientId === '') throw new McpAuthError(401, 'invalid_token', 'not a token issued to an agent')\n const scopes = typeof claims.scope === 'string' ? claims.scope.split(' ').filter(Boolean) : []\n if (introspect && !(await stillAllowed(token, introspect.cacheMs))) throw new McpAuthError(401, 'invalid_token', 'the person disconnected this agent')\n const missing = [...required, ...needs].filter((s) => !scopes.includes(s))\n if (missing.length > 0) throw new McpAuthError(403, 'insufficient_scope', `this needs ${missing.join(' ')}`)\n return {\n userId: String(claims.sub),\n tenantId: typeof claims.tid === 'string' ? claims.tid : '',\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n scopes,\n clientId,\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n\n const authenticate = (error?: McpAuthError): string => {\n const parts = [`resource_metadata=${quoted(metadataUrl)}`]\n if (error && error.code !== 'invalid_request') {\n parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`)\n }\n // What to ask the person for: said when there is no token or it falls short.\n const scope = error?.code === 'invalid_token' ? [] : required\n if (scope.length > 0) parts.push(`scope=${quoted(scope.join(' '))}`)\n return `Bearer ${parts.join(', ')}`\n }\n\n const challenge = (error?: McpAuthError): Response => {\n const status = error?.status ?? 401\n return new Response(JSON.stringify({ error: error?.code ?? 'invalid_request', error_description: error?.description ?? 'an access token is required' }), {\n status,\n headers: { 'content-type': 'application/json', 'www-authenticate': authenticate(error) },\n })\n }\n\n const metadataResponse = () =>\n new Response(JSON.stringify(metadata()), {\n headers: { 'content-type': 'application/json', 'cache-control': 'public, max-age=3600', 'access-control-allow-origin': '*' },\n })\n\n const isMetadata = (pathname: string, method = 'GET') => method === 'GET' && metadataPaths.includes(pathname.replace(/\\/+$/, '') || '/')\n\n const handleMetadata = (request: Request): Response | null =>\n isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null\n\n const toAuthInfo = (a: AgentIdentity): McpAuthInfo => ({\n token: a.token,\n clientId: a.clientId,\n scopes: a.scopes,\n expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1000),\n resource: new URL(resource),\n extra: { userId: a.userId, tenantId: a.tenantId, ...(a.email ? { email: a.email } : {}), roles: a.roles },\n })\n\n return {\n resource,\n metadataUrl,\n metadataPaths,\n metadata,\n verify,\n challenge,\n handleMetadata,\n protect(handler, needs) {\n return async (request) => {\n const meta = handleMetadata(request)\n if (meta) return meta\n let agent: AgentIdentity\n try {\n agent = await verify(request, needs)\n } catch (err) {\n if (err instanceof McpAuthError) return challenge(err)\n throw err\n }\n return handler(request, agent)\n }\n },\n middleware(needs) {\n return (req, res, next) => {\n const pathname = (req.originalUrl ?? req.url ?? '/').split('?')[0] ?? '/'\n if (isMetadata(pathname, req.method)) {\n res.statusCode = 200\n res.setHeader('content-type', 'application/json')\n res.setHeader('cache-control', 'public, max-age=3600')\n res.setHeader('access-control-allow-origin', '*')\n res.end(JSON.stringify(metadata()))\n return\n }\n const raw = req.headers.authorization\n const header = Array.isArray(raw) ? (raw[0] ?? '') : (raw ?? '')\n verify(/^Bearer\\s+/i.test(header) ? header : '', needs).then(\n (agent) => {\n req.agent = agent\n req.auth = toAuthInfo(agent)\n next()\n },\n (err: unknown) => {\n if (!(err instanceof McpAuthError)) return next(err)\n res.statusCode = err.status\n res.setHeader('content-type', 'application/json')\n res.setHeader('www-authenticate', authenticate(err))\n res.end(JSON.stringify({ error: err.code, error_description: err.description }))\n },\n )\n }\n },\n }\n}\n","// A backend that is handed a Cauthy access token: is it real, and whose is it?\n//\n// const who = await verifyToken(request) // or the token itself\n// who.userId, who.tenantId, who.roles\n//\n// Cauthy signs its tokens with a key it publishes (/.well-known/jwks.json), so\n// checking one needs no secret and no call to Cauthy per request: the keys are\n// fetched once and cached. Throws `CauthyTokenError` for anything else: answer\n// it 401.\n\nimport { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'\n\n/** Who a verified access token belongs to. */\nexport interface TokenIdentity {\n /** The person. For a system's own token, the client it identifies as. */\n userId: string\n tenantId: string\n email?: string\n roles: string[]\n /** Set when the token is a system's own and not a person's. */\n system?: string\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: string) {\n super(`cauthy-auth: token refused: ${reason}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /** The audience the tokens must carry. Default: `CAUTHY_AUDIENCE`; unchecked when neither is set. */\n audience?: string\n /** Refuse a token of any other workspace. Default: `CAUTHY_TENANT_ID`; unchecked when neither is set. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached. */\n jwks?: JWTVerifyGetKey\n /** The moment to verify at. Default: now. */\n now?: Date\n}\n\nconst keys = new Map<string, JWTVerifyGetKey>()\n\n/** Cauthy's published keys, fetched once per issuer and cached. */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = keys.get(issuer)\n if (set === undefined) {\n set = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), { cooldownDuration: 30_000 })\n keys.set(issuer, set)\n }\n return set\n}\n\nfunction env(name: string): string | undefined {\n return typeof process !== 'undefined' ? process.env?.[name] : undefined\n}\n\nfunction bearer(from: string | Request | Headers): string {\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '').trim()\n const header = (from instanceof Headers ? from : from.headers).get('authorization') ?? ''\n return /^Bearer\\s+/i.test(header) ? header.replace(/^Bearer\\s+/i, '').trim() : ''\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to. Checked: the signature, against Cauthy's\n * published keys; that Cauthy issued it; that it has not expired; and the\n * audience and the workspace, when given.\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n const issuer = (options.issuer ?? env('CAUTHY_ISSUER') ?? '').replace(/\\/+$/, '')\n if (issuer === '') throw new CauthyTokenError('issuer (CAUTHY_ISSUER) is not set')\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no token')\n\n let claims: Record<string, unknown>\n try {\n const verified = await jwtVerify(token, options.jwks ?? keysOf(issuer), {\n algorithms: ['RS256'],\n issuer,\n audience: options.audience ?? env('CAUTHY_AUDIENCE'),\n requiredClaims: ['exp', 'sub'],\n currentDate: options.now,\n })\n claims = verified.payload as Record<string, unknown>\n } catch (err) {\n throw new CauthyTokenError(err instanceof Error ? err.message : 'bad signature')\n }\n\n const tenantId = typeof claims.tid === 'string' ? claims.tid : ''\n const wanted = options.tenantId ?? env('CAUTHY_TENANT_ID')\n if (wanted && tenantId !== wanted) throw new CauthyTokenError('issued for another workspace')\n\n return {\n userId: String(claims.sub),\n tenantId,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n roles: Array.isArray(claims.roles) ? claims.roles.filter((r): r is string => typeof r === 'string') : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n}\n"],"mappings":";AAoBA,SAAS,aAAAA,kBAAuC;;;ACVhD,SAAS,oBAAoB,iBAAuC;AAqCpE,IAAM,OAAO,oBAAI,IAA6B;AAGvC,SAAS,OAAO,QAAiC;AACtD,MAAI,MAAM,KAAK,IAAI,MAAM;AACzB,MAAI,QAAQ,QAAW;AACrB,UAAM,mBAAmB,IAAI,IAAI,GAAG,MAAM,wBAAwB,GAAG,EAAE,kBAAkB,IAAO,CAAC;AACjG,SAAK,IAAI,QAAQ,GAAG;AAAA,EACtB;AACA,SAAO;AACT;;;ADWO,I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ACA,eAAO,QAAQ,SAAS,KAAK;AAAA,MAC/B;AAAA,IACF;AAAA,IACA,WAAW,OAAO;AAChB,aAAO,CAAC,KAAK,KAAK,SAAS;AACzB,cAAM,YAAY,IAAI,eAAe,IAAI,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK;AACtE,YAAI,WAAW,UAAU,IAAI,MAAM,GAAG;AACpC,cAAI,aAAa;AACjB,cAAI,UAAU,gBAAgB,kBAAkB;AAChD,cAAI,UAAU,iBAAiB,sBAAsB;AACrD,cAAI,UAAU,+BAA+B,GAAG;AAChD,cAAI,IAAI,KAAK,UAAU,SAAS,CAAC,CAAC;AAClC;AAAA,QACF;AACA,cAAM,MAAM,IAAI,QAAQ;AACxB,cAAM,SAAS,MAAM,QAAQ,GAAG,IAAK,IAAI,CAAC,KAAK,KAAO,OAAO;AAC7D,eAAO,cAAc,KAAK,MAAM,IAAI,SAAS,IAAI,KAAK,EAAE;AAAA,UACtD,CAAC,UAAU;AACT,gBAAI,QAAQ;AACZ,gBAAI,OAAO,WAAW,KAAK;AAC3B,iBAAK;AAAA,UACP;AAAA,UACA,CAAC,QAAiB;AAChB,gBAAI,EAAE,eAAe,cAAe,QAAO,KAAK,GAAG;AACnD,gBAAI,aAAa,IAAI;AACrB,gBAAI,UAAU,gBAAgB,kBAAkB;AAChD,gBAAI,UAAU,oBAAoB,aAAa,GAAG,CAAC;AACnD,gBAAI,IAAI,KAAK,UAAU,EAAE,OAAO,IAAI,MAAM,mBAAmB,IAAI,YAAY,CAAC,CAAC;AAAA,UACjF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["jwtVerify","jwtVerify"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cauthy-auth",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "description": "Sign in with Cauthy: one route to mount, getSession on the server, useSession in the browser. No database, no screens to build.",
5
5
  "license": "Apache-2.0",
6
6
  "main": "dist/index.js",