cauthy-auth 0.24.0 → 0.24.1
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/cli.js +31 -8
- package/dist/client.js +9 -2
- package/dist/client.js.map +1 -1
- package/dist/client.mjs +9 -2
- package/dist/client.mjs.map +1 -1
- package/dist/index.js +36 -13
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +36 -13
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.js +12 -3
- package/dist/mcp.js.map +1 -1
- package/dist/mcp.mjs +12 -3
- package/dist/mcp.mjs.map +1 -1
- package/dist/react.js +24 -4
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +24 -4
- package/dist/react.mjs.map +1 -1
- package/dist/svelte.js +9 -2
- package/dist/svelte.js.map +1 -1
- package/dist/svelte.mjs +9 -2
- package/dist/svelte.mjs.map +1 -1
- package/dist/theme.js +29 -4
- package/dist/theme.js.map +1 -1
- package/dist/theme.mjs +27 -4
- package/dist/theme.mjs.map +1 -1
- package/dist/vue.js +9 -2
- package/dist/vue.js.map +1 -1
- package/dist/vue.mjs +9 -2
- package/dist/vue.mjs.map +1 -1
- package/package.json +1 -1
package/dist/mcp.js
CHANGED
|
@@ -30,6 +30,15 @@ var import_jose2 = require("jose");
|
|
|
30
30
|
|
|
31
31
|
// src/verify.ts
|
|
32
32
|
var import_jose = require("jose");
|
|
33
|
+
|
|
34
|
+
// src/url.ts
|
|
35
|
+
function withoutTrailingSlashes(s) {
|
|
36
|
+
let end = s.length;
|
|
37
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
|
|
38
|
+
return s.slice(0, end);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/verify.ts
|
|
33
42
|
var keys = /* @__PURE__ */ new Map();
|
|
34
43
|
function keysOf(issuer) {
|
|
35
44
|
let set = keys.get(issuer);
|
|
@@ -80,7 +89,7 @@ function canonicalResource(raw) {
|
|
|
80
89
|
throw new Error("cauthy-auth: resource must be an https address");
|
|
81
90
|
}
|
|
82
91
|
if (u.search !== "" || u.hash !== "") throw new Error("cauthy-auth: resource may not have a query or a fragment");
|
|
83
|
-
return `${u.protocol}//${u.host}${u.pathname
|
|
92
|
+
return `${u.protocol}//${u.host}${withoutTrailingSlashes(u.pathname)}`;
|
|
84
93
|
}
|
|
85
94
|
function bearer(from) {
|
|
86
95
|
if (typeof from === "string") return from.replace(/^Bearer\s+/i, "").trim();
|
|
@@ -97,7 +106,7 @@ function mcpAuth(options = {}) {
|
|
|
97
106
|
const rawResource = options.resource ?? env("CAUTHY_MCP_RESOURCE") ?? "";
|
|
98
107
|
if (rawResource === "") throw new Error("cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set");
|
|
99
108
|
const resource = canonicalResource(rawResource);
|
|
100
|
-
const issuer = (options.issuer ?? env("CAUTHY_ISSUER") ?? "")
|
|
109
|
+
const issuer = withoutTrailingSlashes(options.issuer ?? env("CAUTHY_ISSUER") ?? "");
|
|
101
110
|
if (issuer === "") throw new Error("cauthy-auth: issuer (CAUTHY_ISSUER) is not set");
|
|
102
111
|
const required = options.scopes ?? [];
|
|
103
112
|
const url = new URL(resource);
|
|
@@ -234,7 +243,7 @@ ${scopes.join(" ")}`;
|
|
|
234
243
|
const metadataResponse = () => new Response(JSON.stringify(metadata()), {
|
|
235
244
|
headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", "access-control-allow-origin": "*" }
|
|
236
245
|
});
|
|
237
|
-
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(pathname
|
|
246
|
+
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(withoutTrailingSlashes(pathname) || "/");
|
|
238
247
|
const handleMetadata = (request) => isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null;
|
|
239
248
|
const toAuthInfo = (a) => ({
|
|
240
249
|
token: a.token,
|
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//\n// A server that calls another of the workspace's servers for the person\n// trades the agent's token for one for that server (token exchange, RFC 8693):\n//\n// const auth = mcpAuth({ resource, clientId, clientSecret }) // from the dashboard\n// const { accessToken } = await auth.exchange(agent, 'https://api.example.com', ['orders:read'])\n//\n// The workspace's admins must have delegated that call in the dashboard, and\n// the person allowed it when they connected the agent.\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 * Set when the token came by token exchange: the server that called this\n * one for the person (the `act` claim's subject).\n */\n actor?: 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 * This server's client_id and secret at Cauthy, for token exchange (AI\n * agents → the server → Server credentials). Defaults:\n * `CAUTHY_MCP_CLIENT_ID`, `CAUTHY_MCP_CLIENT_SECRET`.\n */\n clientId?: string\n clientSecret?: string\n}\n\n/** What a token exchange answers. */\nexport interface ExchangedToken {\n /** The token for the other server, as the person. Send it as `Authorization: Bearer`. */\n accessToken: string\n /** What it allows there. */\n scopes: string[]\n /** UTC, ISO 8601. Never later than the agent's own token. */\n expiresAt: string\n}\n\n/** A token exchange Cauthy refused, with the OAuth error it answered. */\nexport class CauthyExchangeError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly description: string,\n ) {\n super(`cauthy-auth: token exchange refused (${code}): ${description}`)\n this.name = 'CauthyExchangeError'\n }\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 * Trades the agent's token this server received for one for another of the\n * workspace's servers, to call it for the person (RFC 8693). Needs this\n * server's `clientId` and `clientSecret`. Answers are kept until shortly\n * before they expire. Throws `CauthyExchangeError` when Cauthy refuses.\n */\n exchange(from: string | AgentIdentity, target: string, scopes?: string[]): Promise<ExchangedToken>\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 isActor(v: unknown): v is { sub: string } {\n return typeof v === 'object' && v !== null && typeof (v as { sub?: unknown }).sub === 'string'\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 token is no longer allowed: the agent was disconnected, or its access withdrawn')\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 ...(isActor(claims.act) ? { actor: claims.act.sub } : {}),\n }\n }\n\n const clientId = options.clientId ?? env('CAUTHY_MCP_CLIENT_ID') ?? ''\n const clientSecret = options.clientSecret ?? env('CAUTHY_MCP_CLIENT_SECRET') ?? ''\n const exchanged = new Map<string, ExchangedToken & { until: number }>()\n const exchange = async (from: string | AgentIdentity, target: string, scopes: string[] = []): Promise<ExchangedToken> => {\n if (clientId === '' || clientSecret === '') {\n throw new Error('cauthy-auth: token exchange needs clientId and clientSecret (CAUTHY_MCP_CLIENT_ID, CAUTHY_MCP_CLIENT_SECRET)')\n }\n const subject = typeof from === 'string' ? bearer(from) : from.token\n const to = canonicalResource(target)\n const key = `${subject}\\n${to}\\n${scopes.join(' ')}`\n const kept = exchanged.get(key)\n if (kept && kept.until > Date.now()) return { accessToken: kept.accessToken, scopes: kept.scopes, expiresAt: kept.expiresAt }\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n authorization: `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`,\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subject,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n resource: to,\n ...(scopes.length > 0 ? { scope: scopes.join(' ') } : {}),\n }),\n })\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new CauthyExchangeError(res.status, typeof body.error === 'string' ? body.error : 'server_error',\n typeof body.error_description === 'string' ? body.error_description : `Cauthy answered ${res.status}`)\n }\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 0\n const out: ExchangedToken = {\n accessToken: body.access_token,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n }\n if (exchanged.size > 10_000) exchanged.clear()\n // Kept until 30 seconds before it runs out, so it is never sent stale.\n exchanged.set(key, { ...out, until: Date.now() + Math.max(0, expiresIn - 30) * 1000 })\n return out\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 exchange,\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;AAAA;AA6BA,IAAAA,eAAgD;;;ACnBhD,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,QAAQ,GAAG;AAAA,EACtB;AACA,SAAO;AACT;;;AD0CO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACW,QACA,MACA,aACT;AACA,UAAM,wCAAwC,IAAI,MAAM,WAAW,EAAE;AAJ5D;AACA;AACA;AAGT,SAAK,OAAO;AAA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ChD,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","clientId"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/verify.ts","../src/url.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//\n// A server that calls another of the workspace's servers for the person\n// trades the agent's token for one for that server (token exchange, RFC 8693):\n//\n// const auth = mcpAuth({ resource, clientId, clientSecret }) // from the dashboard\n// const { accessToken } = await auth.exchange(agent, 'https://api.example.com', ['orders:read'])\n//\n// The workspace's admins must have delegated that call in the dashboard, and\n// the person allowed it when they connected the agent.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\nimport { withoutTrailingSlashes } from './url'\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 * Set when the token came by token exchange: the server that called this\n * one for the person (the `act` claim's subject).\n */\n actor?: 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 * This server's client_id and secret at Cauthy, for token exchange (AI\n * agents → the server → Server credentials). Defaults:\n * `CAUTHY_MCP_CLIENT_ID`, `CAUTHY_MCP_CLIENT_SECRET`.\n */\n clientId?: string\n clientSecret?: string\n}\n\n/** What a token exchange answers. */\nexport interface ExchangedToken {\n /** The token for the other server, as the person. Send it as `Authorization: Bearer`. */\n accessToken: string\n /** What it allows there. */\n scopes: string[]\n /** UTC, ISO 8601. Never later than the agent's own token. */\n expiresAt: string\n}\n\n/** A token exchange Cauthy refused, with the OAuth error it answered. */\nexport class CauthyExchangeError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly description: string,\n ) {\n super(`cauthy-auth: token exchange refused (${code}): ${description}`)\n this.name = 'CauthyExchangeError'\n }\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 * Trades the agent's token this server received for one for another of the\n * workspace's servers, to call it for the person (RFC 8693). Needs this\n * server's `clientId` and `clientSecret`. Answers are kept until shortly\n * before they expire. Throws `CauthyExchangeError` when Cauthy refuses.\n */\n exchange(from: string | AgentIdentity, target: string, scopes?: string[]): Promise<ExchangedToken>\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}${withoutTrailingSlashes(u.pathname)}`\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 isActor(v: unknown): v is { sub: string } {\n return typeof v === 'object' && v !== null && typeof (v as { sub?: unknown }).sub === 'string'\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 = withoutTrailingSlashes(options.issuer ?? env('CAUTHY_ISSUER') ?? '')\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 token is no longer allowed: the agent was disconnected, or its access withdrawn')\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 ...(isActor(claims.act) ? { actor: claims.act.sub } : {}),\n }\n }\n\n const clientId = options.clientId ?? env('CAUTHY_MCP_CLIENT_ID') ?? ''\n const clientSecret = options.clientSecret ?? env('CAUTHY_MCP_CLIENT_SECRET') ?? ''\n const exchanged = new Map<string, ExchangedToken & { until: number }>()\n const exchange = async (from: string | AgentIdentity, target: string, scopes: string[] = []): Promise<ExchangedToken> => {\n if (clientId === '' || clientSecret === '') {\n throw new Error('cauthy-auth: token exchange needs clientId and clientSecret (CAUTHY_MCP_CLIENT_ID, CAUTHY_MCP_CLIENT_SECRET)')\n }\n const subject = typeof from === 'string' ? bearer(from) : from.token\n const to = canonicalResource(target)\n const key = `${subject}\\n${to}\\n${scopes.join(' ')}`\n const kept = exchanged.get(key)\n if (kept && kept.until > Date.now()) return { accessToken: kept.accessToken, scopes: kept.scopes, expiresAt: kept.expiresAt }\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n authorization: `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`,\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subject,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n resource: to,\n ...(scopes.length > 0 ? { scope: scopes.join(' ') } : {}),\n }),\n })\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new CauthyExchangeError(res.status, typeof body.error === 'string' ? body.error : 'server_error',\n typeof body.error_description === 'string' ? body.error_description : `Cauthy answered ${res.status}`)\n }\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 0\n const out: ExchangedToken = {\n accessToken: body.access_token,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n }\n if (exchanged.size > 10_000) exchanged.clear()\n // Kept until 30 seconds before it runs out, so it is never sent stale.\n exchanged.set(key, { ...out, until: Date.now() + Math.max(0, expiresIn - 30) * 1000 })\n return out\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(withoutTrailingSlashes(pathname) || '/')\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 exchange,\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'\nimport { withoutTrailingSlashes } from './url'\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 = withoutTrailingSlashes(options.issuer ?? env('CAUTHY_ISSUER') ?? '')\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","/**\n * The address without its trailing slashes: `https://auth.example.com/` and\n * `https://auth.example.com` name the same issuer. A loop, not `/\\/+$/`,\n * which backtracks over a long run of slashes.\n */\nexport function withoutTrailingSlashes(s: string): string {\n let end = s.length\n while (end > 0 && s.charCodeAt(end - 1) === 47) end--\n return s.slice(0, end)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BA,IAAAA,eAAgD;;;ACnBhD,kBAAoE;;;ACL7D,SAAS,uBAAuB,GAAmB;AACxD,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC,MAAM,GAAI;AAChD,SAAO,EAAE,MAAM,GAAG,GAAG;AACvB;;;ADuCA,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,QAAQ,GAAG;AAAA,EACtB;AACA,SAAO;AACT;;;AD0CO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACW,QACA,MACA,aACT;AACA,UAAM,wCAAwC,IAAI,MAAM,WAAW,EAAE;AAJ5D;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,QACA,MACA,aACT;AACA,UAAM,gBAAgB,WAA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;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","clientId"]}
|
package/dist/mcp.mjs
CHANGED
|
@@ -3,6 +3,15 @@ import { jwtVerify as jwtVerify2 } from "jose";
|
|
|
3
3
|
|
|
4
4
|
// src/verify.ts
|
|
5
5
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
6
|
+
|
|
7
|
+
// src/url.ts
|
|
8
|
+
function withoutTrailingSlashes(s) {
|
|
9
|
+
let end = s.length;
|
|
10
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
|
|
11
|
+
return s.slice(0, end);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/verify.ts
|
|
6
15
|
var keys = /* @__PURE__ */ new Map();
|
|
7
16
|
function keysOf(issuer) {
|
|
8
17
|
let set = keys.get(issuer);
|
|
@@ -53,7 +62,7 @@ function canonicalResource(raw) {
|
|
|
53
62
|
throw new Error("cauthy-auth: resource must be an https address");
|
|
54
63
|
}
|
|
55
64
|
if (u.search !== "" || u.hash !== "") throw new Error("cauthy-auth: resource may not have a query or a fragment");
|
|
56
|
-
return `${u.protocol}//${u.host}${u.pathname
|
|
65
|
+
return `${u.protocol}//${u.host}${withoutTrailingSlashes(u.pathname)}`;
|
|
57
66
|
}
|
|
58
67
|
function bearer(from) {
|
|
59
68
|
if (typeof from === "string") return from.replace(/^Bearer\s+/i, "").trim();
|
|
@@ -70,7 +79,7 @@ function mcpAuth(options = {}) {
|
|
|
70
79
|
const rawResource = options.resource ?? env("CAUTHY_MCP_RESOURCE") ?? "";
|
|
71
80
|
if (rawResource === "") throw new Error("cauthy-auth: resource (CAUTHY_MCP_RESOURCE) is not set");
|
|
72
81
|
const resource = canonicalResource(rawResource);
|
|
73
|
-
const issuer = (options.issuer ?? env("CAUTHY_ISSUER") ?? "")
|
|
82
|
+
const issuer = withoutTrailingSlashes(options.issuer ?? env("CAUTHY_ISSUER") ?? "");
|
|
74
83
|
if (issuer === "") throw new Error("cauthy-auth: issuer (CAUTHY_ISSUER) is not set");
|
|
75
84
|
const required = options.scopes ?? [];
|
|
76
85
|
const url = new URL(resource);
|
|
@@ -207,7 +216,7 @@ ${scopes.join(" ")}`;
|
|
|
207
216
|
const metadataResponse = () => new Response(JSON.stringify(metadata()), {
|
|
208
217
|
headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", "access-control-allow-origin": "*" }
|
|
209
218
|
});
|
|
210
|
-
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(pathname
|
|
219
|
+
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(withoutTrailingSlashes(pathname) || "/");
|
|
211
220
|
const handleMetadata = (request) => isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null;
|
|
212
221
|
const toAuthInfo = (a) => ({
|
|
213
222
|
token: a.token,
|
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//\n// A server that calls another of the workspace's servers for the person\n// trades the agent's token for one for that server (token exchange, RFC 8693):\n//\n// const auth = mcpAuth({ resource, clientId, clientSecret }) // from the dashboard\n// const { accessToken } = await auth.exchange(agent, 'https://api.example.com', ['orders:read'])\n//\n// The workspace's admins must have delegated that call in the dashboard, and\n// the person allowed it when they connected the agent.\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 * Set when the token came by token exchange: the server that called this\n * one for the person (the `act` claim's subject).\n */\n actor?: 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 * This server's client_id and secret at Cauthy, for token exchange (AI\n * agents → the server → Server credentials). Defaults:\n * `CAUTHY_MCP_CLIENT_ID`, `CAUTHY_MCP_CLIENT_SECRET`.\n */\n clientId?: string\n clientSecret?: string\n}\n\n/** What a token exchange answers. */\nexport interface ExchangedToken {\n /** The token for the other server, as the person. Send it as `Authorization: Bearer`. */\n accessToken: string\n /** What it allows there. */\n scopes: string[]\n /** UTC, ISO 8601. Never later than the agent's own token. */\n expiresAt: string\n}\n\n/** A token exchange Cauthy refused, with the OAuth error it answered. */\nexport class CauthyExchangeError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly description: string,\n ) {\n super(`cauthy-auth: token exchange refused (${code}): ${description}`)\n this.name = 'CauthyExchangeError'\n }\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 * Trades the agent's token this server received for one for another of the\n * workspace's servers, to call it for the person (RFC 8693). Needs this\n * server's `clientId` and `clientSecret`. Answers are kept until shortly\n * before they expire. Throws `CauthyExchangeError` when Cauthy refuses.\n */\n exchange(from: string | AgentIdentity, target: string, scopes?: string[]): Promise<ExchangedToken>\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 isActor(v: unknown): v is { sub: string } {\n return typeof v === 'object' && v !== null && typeof (v as { sub?: unknown }).sub === 'string'\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 token is no longer allowed: the agent was disconnected, or its access withdrawn')\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 ...(isActor(claims.act) ? { actor: claims.act.sub } : {}),\n }\n }\n\n const clientId = options.clientId ?? env('CAUTHY_MCP_CLIENT_ID') ?? ''\n const clientSecret = options.clientSecret ?? env('CAUTHY_MCP_CLIENT_SECRET') ?? ''\n const exchanged = new Map<string, ExchangedToken & { until: number }>()\n const exchange = async (from: string | AgentIdentity, target: string, scopes: string[] = []): Promise<ExchangedToken> => {\n if (clientId === '' || clientSecret === '') {\n throw new Error('cauthy-auth: token exchange needs clientId and clientSecret (CAUTHY_MCP_CLIENT_ID, CAUTHY_MCP_CLIENT_SECRET)')\n }\n const subject = typeof from === 'string' ? bearer(from) : from.token\n const to = canonicalResource(target)\n const key = `${subject}\\n${to}\\n${scopes.join(' ')}`\n const kept = exchanged.get(key)\n if (kept && kept.until > Date.now()) return { accessToken: kept.accessToken, scopes: kept.scopes, expiresAt: kept.expiresAt }\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n authorization: `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`,\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subject,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n resource: to,\n ...(scopes.length > 0 ? { scope: scopes.join(' ') } : {}),\n }),\n })\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new CauthyExchangeError(res.status, typeof body.error === 'string' ? body.error : 'server_error',\n typeof body.error_description === 'string' ? body.error_description : `Cauthy answered ${res.status}`)\n }\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 0\n const out: ExchangedToken = {\n accessToken: body.access_token,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n }\n if (exchanged.size > 10_000) exchanged.clear()\n // Kept until 30 seconds before it runs out, so it is never sent stale.\n exchanged.set(key, { ...out, until: Date.now() + Math.max(0, expiresIn - 30) * 1000 })\n return out\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 exchange,\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":";AA6BA,SAAS,aAAAA,kBAAuC;;;ACnBhD,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;;;AD0CO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACW,QACA,MACA,aACT;AACA,UAAM,wCAAwC,IAAI,MAAM,WAAW,EAAE;AAJ5D;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,QACA,MACA,aACT;AACA,UAAM,gBAAgB,WAAW,EAAE;AAJ1B;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AA4DA,SAAS,IAAI,MAA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AU;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","clientId"]}
|
|
1
|
+
{"version":3,"sources":["../src/mcp.ts","../src/verify.ts","../src/url.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//\n// A server that calls another of the workspace's servers for the person\n// trades the agent's token for one for that server (token exchange, RFC 8693):\n//\n// const auth = mcpAuth({ resource, clientId, clientSecret }) // from the dashboard\n// const { accessToken } = await auth.exchange(agent, 'https://api.example.com', ['orders:read'])\n//\n// The workspace's admins must have delegated that call in the dashboard, and\n// the person allowed it when they connected the agent.\n\nimport { jwtVerify, type JWTVerifyGetKey } from 'jose'\nimport { keysOf } from './verify'\nimport { withoutTrailingSlashes } from './url'\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 * Set when the token came by token exchange: the server that called this\n * one for the person (the `act` claim's subject).\n */\n actor?: 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 * This server's client_id and secret at Cauthy, for token exchange (AI\n * agents → the server → Server credentials). Defaults:\n * `CAUTHY_MCP_CLIENT_ID`, `CAUTHY_MCP_CLIENT_SECRET`.\n */\n clientId?: string\n clientSecret?: string\n}\n\n/** What a token exchange answers. */\nexport interface ExchangedToken {\n /** The token for the other server, as the person. Send it as `Authorization: Bearer`. */\n accessToken: string\n /** What it allows there. */\n scopes: string[]\n /** UTC, ISO 8601. Never later than the agent's own token. */\n expiresAt: string\n}\n\n/** A token exchange Cauthy refused, with the OAuth error it answered. */\nexport class CauthyExchangeError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n readonly description: string,\n ) {\n super(`cauthy-auth: token exchange refused (${code}): ${description}`)\n this.name = 'CauthyExchangeError'\n }\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 * Trades the agent's token this server received for one for another of the\n * workspace's servers, to call it for the person (RFC 8693). Needs this\n * server's `clientId` and `clientSecret`. Answers are kept until shortly\n * before they expire. Throws `CauthyExchangeError` when Cauthy refuses.\n */\n exchange(from: string | AgentIdentity, target: string, scopes?: string[]): Promise<ExchangedToken>\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}${withoutTrailingSlashes(u.pathname)}`\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 isActor(v: unknown): v is { sub: string } {\n return typeof v === 'object' && v !== null && typeof (v as { sub?: unknown }).sub === 'string'\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 = withoutTrailingSlashes(options.issuer ?? env('CAUTHY_ISSUER') ?? '')\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 token is no longer allowed: the agent was disconnected, or its access withdrawn')\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 ...(isActor(claims.act) ? { actor: claims.act.sub } : {}),\n }\n }\n\n const clientId = options.clientId ?? env('CAUTHY_MCP_CLIENT_ID') ?? ''\n const clientSecret = options.clientSecret ?? env('CAUTHY_MCP_CLIENT_SECRET') ?? ''\n const exchanged = new Map<string, ExchangedToken & { until: number }>()\n const exchange = async (from: string | AgentIdentity, target: string, scopes: string[] = []): Promise<ExchangedToken> => {\n if (clientId === '' || clientSecret === '') {\n throw new Error('cauthy-auth: token exchange needs clientId and clientSecret (CAUTHY_MCP_CLIENT_ID, CAUTHY_MCP_CLIENT_SECRET)')\n }\n const subject = typeof from === 'string' ? bearer(from) : from.token\n const to = canonicalResource(target)\n const key = `${subject}\\n${to}\\n${scopes.join(' ')}`\n const kept = exchanged.get(key)\n if (kept && kept.until > Date.now()) return { accessToken: kept.accessToken, scopes: kept.scopes, expiresAt: kept.expiresAt }\n const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/x-www-form-urlencoded',\n accept: 'application/json',\n authorization: `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`,\n },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',\n subject_token: subject,\n subject_token_type: 'urn:ietf:params:oauth:token-type:access_token',\n resource: to,\n ...(scopes.length > 0 ? { scope: scopes.join(' ') } : {}),\n }),\n })\n const body = (await res.json().catch(() => ({}))) as Record<string, unknown>\n if (!res.ok || typeof body.access_token !== 'string') {\n throw new CauthyExchangeError(res.status, typeof body.error === 'string' ? body.error : 'server_error',\n typeof body.error_description === 'string' ? body.error_description : `Cauthy answered ${res.status}`)\n }\n const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 0\n const out: ExchangedToken = {\n accessToken: body.access_token,\n scopes: typeof body.scope === 'string' ? body.scope.split(' ').filter(Boolean) : [],\n expiresAt: new Date(Date.now() + expiresIn * 1000).toISOString(),\n }\n if (exchanged.size > 10_000) exchanged.clear()\n // Kept until 30 seconds before it runs out, so it is never sent stale.\n exchanged.set(key, { ...out, until: Date.now() + Math.max(0, expiresIn - 30) * 1000 })\n return out\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(withoutTrailingSlashes(pathname) || '/')\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 exchange,\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'\nimport { withoutTrailingSlashes } from './url'\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 = withoutTrailingSlashes(options.issuer ?? env('CAUTHY_ISSUER') ?? '')\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","/**\n * The address without its trailing slashes: `https://auth.example.com/` and\n * `https://auth.example.com` name the same issuer. A loop, not `/\\/+$/`,\n * which backtracks over a long run of slashes.\n */\nexport function withoutTrailingSlashes(s: string): string {\n let end = s.length\n while (end > 0 && s.charCodeAt(end - 1) === 47) end--\n return s.slice(0, end)\n}\n"],"mappings":";AA6BA,SAAS,aAAAA,kBAAuC;;;ACnBhD,SAAS,oBAAoB,iBAAuC;;;ACL7D,SAAS,uBAAuB,GAAmB;AACxD,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC,MAAM,GAAI;AAChD,SAAO,EAAE,MAAM,GAAG,GAAG;AACvB;;;ADuCA,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;;;AD0CO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YACW,QACA,MACA,aACT;AACA,UAAM,wCAAwC,IAAI,MAAM,WAAW,EAAE;AAJ5D;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC,YACW,QACA,MACA,aACT;AACA,UAAM,gBAAgB,WAAW,EAAE;AAJ1B;AACA;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EANW;AAAA,EACA;AAAA,EACA;AAKb;AA4DA,SAAS,IAAI,MAAkC;AAC7C,SAAO,OAAO,YAAY,cAAc,QAAQ,MAAM,IAAI,IAAI;AAChE;AAMO,SAAS,kBAAkB,KAAqB;AACrD,MAAI;AACJ,MAAI;AACF,QAAI,IAAI,IAAI,IAAI,KAAK,CAAC;AAAA,EACxB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B,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","clientId"]}
|
package/dist/react.js
CHANGED
|
@@ -117,6 +117,13 @@ function ceremonyError(e) {
|
|
|
117
117
|
return { code: "passkey_failed", message: "The passkey could not be used. Try again, or sign in another way." };
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
// src/url.ts
|
|
121
|
+
function withoutTrailingSlashes(s) {
|
|
122
|
+
let end = s.length;
|
|
123
|
+
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
|
|
124
|
+
return s.slice(0, end);
|
|
125
|
+
}
|
|
126
|
+
|
|
120
127
|
// src/theme.ts
|
|
121
128
|
function themeVariables(theme) {
|
|
122
129
|
const vars = {};
|
|
@@ -235,7 +242,7 @@ function loadGoogleIdentity() {
|
|
|
235
242
|
var PASSKEY_SECONDS = 300;
|
|
236
243
|
var UNAVAILABLE = { code: "unavailable", message: "Sign-in is unavailable right now. Try again in a moment." };
|
|
237
244
|
function createAuthClient(options = {}) {
|
|
238
|
-
const base = (options.basePath ?? "/api/auth")
|
|
245
|
+
const base = withoutTrailingSlashes(options.basePath ?? "/api/auth");
|
|
239
246
|
const doFetch = (...args) => (options.fetch ?? fetch)(...args);
|
|
240
247
|
const locale = () => {
|
|
241
248
|
const said = typeof options.locale === "function" ? options.locale() : options.locale;
|
|
@@ -979,6 +986,16 @@ function useMethods(auth) {
|
|
|
979
986
|
function sitePath(to) {
|
|
980
987
|
return to && to.startsWith("/") && !to.startsWith("//") && !to.includes("\\") ? to : void 0;
|
|
981
988
|
}
|
|
989
|
+
function sameOrigin(to) {
|
|
990
|
+
const path = sitePath(to);
|
|
991
|
+
if (path || !to) return path;
|
|
992
|
+
try {
|
|
993
|
+
const url = new URL(to);
|
|
994
|
+
return url.origin === window.location.origin ? url.pathname + url.search + url.hash : void 0;
|
|
995
|
+
} catch {
|
|
996
|
+
return void 0;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
982
999
|
function useForm(props) {
|
|
983
1000
|
const t = { ...TEXTS[props.locale ?? "en"], ...props.texts, errors: { ...TEXTS[props.locale ?? "en"].errors, ...props.texts?.errors } };
|
|
984
1001
|
const cx = (slot) => props.classNames?.[slot] ?? `cauthy-${slot}`;
|
|
@@ -989,7 +1006,7 @@ function useForm(props) {
|
|
|
989
1006
|
const say = (e) => t.errors[e.code] ?? e.message;
|
|
990
1007
|
const done = (to) => {
|
|
991
1008
|
if (props.onSuccess) props.onSuccess();
|
|
992
|
-
else window.location.assign(sitePath(to) ?? props.returnTo ?? "/");
|
|
1009
|
+
else window.location.assign(sitePath(to) ?? sameOrigin(props.returnTo) ?? "/");
|
|
993
1010
|
};
|
|
994
1011
|
const root = useRoot(props);
|
|
995
1012
|
return { t, cx, Button, Input, error, setError, busy, setBusy, say, done, root };
|
|
@@ -1251,7 +1268,10 @@ function GoogleOneTap(props) {
|
|
|
1251
1268
|
void auth.signIn.googleOneTap({ signal: ctl.signal, context: props.context }).then((r) => {
|
|
1252
1269
|
if (!r.ok || ctl.signal.aborted) return;
|
|
1253
1270
|
if (props.onSuccess) props.onSuccess();
|
|
1254
|
-
else
|
|
1271
|
+
else {
|
|
1272
|
+
const to = sameOrigin(props.returnTo);
|
|
1273
|
+
if (to) window.location.assign(to);
|
|
1274
|
+
}
|
|
1255
1275
|
});
|
|
1256
1276
|
return () => ctl.abort();
|
|
1257
1277
|
}, [unauthenticated]);
|
|
@@ -1900,7 +1920,7 @@ var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
|
1900
1920
|
var Ctx = (0, import_react3.createContext)(null);
|
|
1901
1921
|
var AHEAD_MS = 6e4;
|
|
1902
1922
|
function CauthyProvider({ children, basePath = "/api/auth", initialSession }) {
|
|
1903
|
-
const base = basePath
|
|
1923
|
+
const base = withoutTrailingSlashes(basePath);
|
|
1904
1924
|
const [session, setSession] = (0, import_react3.useState)(initialSession ?? null);
|
|
1905
1925
|
const [status, setStatus] = (0, import_react3.useState)(
|
|
1906
1926
|
initialSession === void 0 ? "loading" : initialSession === null ? "unauthenticated" : "authenticated"
|