@cauthyhq/node 0.0.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +180 -1
- package/dist/cauthy-B6Sm3T8M.d.ts +1035 -0
- package/dist/cauthy-ClP5orP4.d.mts +1035 -0
- package/dist/express.d.mts +25 -0
- package/dist/express.d.ts +25 -0
- package/dist/express.js +103 -0
- package/dist/express.js.map +1 -0
- package/dist/express.mjs +77 -0
- package/dist/express.mjs.map +1 -0
- package/dist/fastify.d.mts +38 -0
- package/dist/fastify.d.ts +38 -0
- package/dist/fastify.js +105 -0
- package/dist/fastify.js.map +1 -0
- package/dist/fastify.mjs +79 -0
- package/dist/fastify.mjs.map +1 -0
- package/dist/hono.d.mts +24 -0
- package/dist/hono.d.ts +24 -0
- package/dist/hono.js +51 -0
- package/dist/hono.js.map +1 -0
- package/dist/hono.mjs +25 -0
- package/dist/hono.mjs.map +1 -0
- package/dist/index.d.mts +138 -0
- package/dist/index.d.ts +138 -0
- package/dist/index.js +3474 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +3410 -0
- package/dist/index.mjs.map +1 -0
- package/dist/keys-D5k0omTb.d.mts +64 -0
- package/dist/keys-D5k0omTb.d.ts +64 -0
- package/dist/keys.d.mts +8 -0
- package/dist/keys.d.ts +8 -0
- package/dist/keys.js +157 -0
- package/dist/keys.js.map +1 -0
- package/dist/keys.mjs +129 -0
- package/dist/keys.mjs.map +1 -0
- package/dist/mcp.d.mts +151 -0
- package/dist/mcp.d.ts +151 -0
- package/dist/mcp.js +410 -0
- package/dist/mcp.js.map +1 -0
- package/dist/mcp.mjs +382 -0
- package/dist/mcp.mjs.map +1 -0
- package/dist/next.d.mts +24 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +77 -0
- package/dist/next.js.map +1 -0
- package/dist/next.mjs +52 -0
- package/dist/next.mjs.map +1 -0
- package/dist/testing.d.mts +62 -0
- package/dist/testing.d.ts +62 -0
- package/dist/testing.js +182 -0
- package/dist/testing.js.map +1 -0
- package/dist/testing.mjs +156 -0
- package/dist/testing.mjs.map +1 -0
- package/dist/theme.d.mts +183 -0
- package/dist/theme.d.ts +183 -0
- package/dist/theme.js +531 -0
- package/dist/theme.js.map +1 -0
- package/dist/theme.mjs +496 -0
- package/dist/theme.mjs.map +1 -0
- package/package.json +185 -4
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/mcp.ts
|
|
21
|
+
var mcp_exports = {};
|
|
22
|
+
__export(mcp_exports, {
|
|
23
|
+
CauthyExchangeError: () => CauthyExchangeError,
|
|
24
|
+
McpAuthError: () => McpAuthError,
|
|
25
|
+
canonicalResource: () => canonicalResource,
|
|
26
|
+
mcpAuth: () => mcpAuth
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(mcp_exports);
|
|
29
|
+
var import_jose2 = require("jose");
|
|
30
|
+
|
|
31
|
+
// src/verify.ts
|
|
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
|
|
42
|
+
var CauthyUnavailableError = class extends Error {
|
|
43
|
+
constructor(detail) {
|
|
44
|
+
super(`@cauthyhq/node: Cauthy's keys are unavailable: ${detail}`);
|
|
45
|
+
this.name = "CauthyUnavailableError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var MAX_KEYS_BYTES = 64 * 1024;
|
|
49
|
+
var KEYS_TIMEOUT_MS = 5e3;
|
|
50
|
+
var KEYS_COOLDOWN_MS = 3e4;
|
|
51
|
+
var KEYS_DEFAULT_TTL_S = 300;
|
|
52
|
+
var KEYS_MIN_TTL_S = 60;
|
|
53
|
+
var KEYS_MAX_TTL_S = 3600;
|
|
54
|
+
function remoteKeys(issuer, fetchKeys = fetch) {
|
|
55
|
+
let set;
|
|
56
|
+
let startedAt = 0;
|
|
57
|
+
let expiresAt = 0;
|
|
58
|
+
let inflight;
|
|
59
|
+
const load = async () => {
|
|
60
|
+
startedAt = Date.now();
|
|
61
|
+
try {
|
|
62
|
+
const res = await fetchKeys(`${issuer}/.well-known/jwks.json`, { redirect: "manual", signal: AbortSignal.timeout(KEYS_TIMEOUT_MS), headers: { accept: "application/json" } });
|
|
63
|
+
if (res.status !== 200) throw new Error(`answered ${res.status}`);
|
|
64
|
+
const bytes = await readCapped(res, MAX_KEYS_BYTES);
|
|
65
|
+
const parsed = JSON.parse(new TextDecoder().decode(bytes));
|
|
66
|
+
if (!parsed || !Array.isArray(parsed.keys)) throw new Error("not a key set");
|
|
67
|
+
const seen = /* @__PURE__ */ new Set();
|
|
68
|
+
for (const k of parsed.keys) {
|
|
69
|
+
const usable = k?.kty === "RSA" && (k.use === void 0 || k.use === "sig") && (k.alg === void 0 || k.alg === "RS256");
|
|
70
|
+
if (!usable || typeof k.kid !== "string") continue;
|
|
71
|
+
if (seen.has(k.kid)) throw new Error(`two usable keys share the kid ${JSON.stringify(k.kid)}`);
|
|
72
|
+
seen.add(k.kid);
|
|
73
|
+
}
|
|
74
|
+
set = (0, import_jose.createLocalJWKSet)(parsed);
|
|
75
|
+
const maxAge = /max-age=(\d+)/.exec(res.headers.get("cache-control") ?? "");
|
|
76
|
+
const ttl = Math.max(KEYS_MIN_TTL_S, Math.min(maxAge ? Number(maxAge[1]) : KEYS_DEFAULT_TTL_S, KEYS_MAX_TTL_S));
|
|
77
|
+
expiresAt = Date.now() + ttl * 1e3;
|
|
78
|
+
} catch (err) {
|
|
79
|
+
if (set === void 0) throw new CauthyUnavailableError(err instanceof Error ? err.message : "unreachable");
|
|
80
|
+
expiresAt = Math.max(expiresAt, Date.now() + KEYS_COOLDOWN_MS);
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const refresh = () => {
|
|
84
|
+
inflight ??= load().finally(() => {
|
|
85
|
+
inflight = void 0;
|
|
86
|
+
});
|
|
87
|
+
return inflight;
|
|
88
|
+
};
|
|
89
|
+
return async (header, token) => {
|
|
90
|
+
if (set === void 0 || Date.now() >= expiresAt) await refresh();
|
|
91
|
+
try {
|
|
92
|
+
return await set(header, token);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
const unknown = err?.code === "ERR_JWKS_NO_MATCHING_KEY";
|
|
95
|
+
if (unknown && Date.now() - startedAt >= KEYS_COOLDOWN_MS) {
|
|
96
|
+
await refresh();
|
|
97
|
+
return set(header, token);
|
|
98
|
+
}
|
|
99
|
+
throw err;
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
async function readCapped(res, max) {
|
|
104
|
+
const reader = res.body?.getReader();
|
|
105
|
+
if (!reader) return new Uint8Array();
|
|
106
|
+
const chunks = [];
|
|
107
|
+
let size = 0;
|
|
108
|
+
for (; ; ) {
|
|
109
|
+
const { done, value } = await reader.read();
|
|
110
|
+
if (done) break;
|
|
111
|
+
size += value.length;
|
|
112
|
+
if (size > max) {
|
|
113
|
+
await reader.cancel();
|
|
114
|
+
throw new Error(`over ${max} bytes`);
|
|
115
|
+
}
|
|
116
|
+
chunks.push(value);
|
|
117
|
+
}
|
|
118
|
+
const out = new Uint8Array(size);
|
|
119
|
+
let at = 0;
|
|
120
|
+
for (const c of chunks) {
|
|
121
|
+
out.set(c, at);
|
|
122
|
+
at += c.length;
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
var published = /* @__PURE__ */ new Map();
|
|
127
|
+
function keysOf(issuer) {
|
|
128
|
+
let set = published.get(issuer);
|
|
129
|
+
if (set === void 0) {
|
|
130
|
+
set = remoteKeys(issuer);
|
|
131
|
+
published.set(issuer, set);
|
|
132
|
+
}
|
|
133
|
+
return set;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/mcp.ts
|
|
137
|
+
var CauthyExchangeError = class extends Error {
|
|
138
|
+
constructor(status, code, description) {
|
|
139
|
+
super(`@cauthyhq/node: token exchange refused (${code}): ${description}`);
|
|
140
|
+
this.status = status;
|
|
141
|
+
this.code = code;
|
|
142
|
+
this.description = description;
|
|
143
|
+
this.name = "CauthyExchangeError";
|
|
144
|
+
}
|
|
145
|
+
status;
|
|
146
|
+
code;
|
|
147
|
+
description;
|
|
148
|
+
};
|
|
149
|
+
var McpAuthError = class extends Error {
|
|
150
|
+
constructor(status, code, description) {
|
|
151
|
+
super(`@cauthyhq/node: ${description}`);
|
|
152
|
+
this.status = status;
|
|
153
|
+
this.code = code;
|
|
154
|
+
this.description = description;
|
|
155
|
+
this.name = "McpAuthError";
|
|
156
|
+
}
|
|
157
|
+
status;
|
|
158
|
+
code;
|
|
159
|
+
description;
|
|
160
|
+
};
|
|
161
|
+
function env(name) {
|
|
162
|
+
return typeof process !== "undefined" ? process.env?.[name] : void 0;
|
|
163
|
+
}
|
|
164
|
+
function canonicalResource(raw) {
|
|
165
|
+
let u;
|
|
166
|
+
try {
|
|
167
|
+
u = new URL(raw.trim());
|
|
168
|
+
} catch {
|
|
169
|
+
throw new Error(`@cauthyhq/node: resource ${JSON.stringify(raw)} is not an absolute address`);
|
|
170
|
+
}
|
|
171
|
+
const local = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";
|
|
172
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {
|
|
173
|
+
throw new Error("@cauthyhq/node: resource must be an https address");
|
|
174
|
+
}
|
|
175
|
+
if (u.search !== "" || u.hash !== "") throw new Error("@cauthyhq/node: resource may not have a query or a fragment");
|
|
176
|
+
return `${u.protocol}//${u.host}${withoutTrailingSlashes(u.pathname)}`;
|
|
177
|
+
}
|
|
178
|
+
function bearer(from) {
|
|
179
|
+
if (typeof from === "string") return from.replace(/^Bearer\s+/i, "").trim();
|
|
180
|
+
const header = (from instanceof Headers ? from : from.headers).get("authorization") ?? "";
|
|
181
|
+
return /^Bearer\s+/i.test(header) ? header.replace(/^Bearer\s+/i, "").trim() : "";
|
|
182
|
+
}
|
|
183
|
+
function isActor(v) {
|
|
184
|
+
return typeof v === "object" && v !== null && typeof v.sub === "string";
|
|
185
|
+
}
|
|
186
|
+
function quoted(v) {
|
|
187
|
+
return `"${v.replace(/["\\]/g, "")}"`;
|
|
188
|
+
}
|
|
189
|
+
function mcpAuth(options = {}) {
|
|
190
|
+
const rawResource = options.resource ?? env("CAUTHY_MCP_RESOURCE") ?? "";
|
|
191
|
+
if (rawResource === "") throw new Error("@cauthyhq/node: resource (CAUTHY_MCP_RESOURCE) is not set");
|
|
192
|
+
const resource = canonicalResource(rawResource);
|
|
193
|
+
const issuer = withoutTrailingSlashes(options.issuer ?? env("CAUTHY_ISSUER") ?? "");
|
|
194
|
+
if (issuer === "") throw new Error("@cauthyhq/node: issuer (CAUTHY_ISSUER) is not set");
|
|
195
|
+
const timeoutMs = options.timeoutMs ?? 5e3;
|
|
196
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("@cauthyhq/node: timeoutMs must be a positive number of milliseconds");
|
|
197
|
+
const required = options.scopes ?? [];
|
|
198
|
+
const url = new URL(resource);
|
|
199
|
+
const path = url.pathname === "/" ? "" : url.pathname;
|
|
200
|
+
const metadataPaths = [.../* @__PURE__ */ new Set([`/.well-known/oauth-protected-resource${path}`, "/.well-known/oauth-protected-resource"])];
|
|
201
|
+
const metadataUrl = `${url.origin}${metadataPaths[0]}`;
|
|
202
|
+
const metadata = () => ({
|
|
203
|
+
resource,
|
|
204
|
+
authorization_servers: [issuer],
|
|
205
|
+
bearer_methods_supported: ["header"],
|
|
206
|
+
scopes_supported: options.scopesSupported ?? required,
|
|
207
|
+
...options.resourceName ? { resource_name: options.resourceName } : {}
|
|
208
|
+
});
|
|
209
|
+
const introspect = options.introspect ? { cacheMs: ((typeof options.introspect === "object" ? options.introspect.cacheSeconds : void 0) ?? 30) * 1e3 } : null;
|
|
210
|
+
const answers = /* @__PURE__ */ new Map();
|
|
211
|
+
const stillAllowed = async (token, cacheMs) => {
|
|
212
|
+
const now = Date.now();
|
|
213
|
+
const kept = answers.get(token);
|
|
214
|
+
if (kept && kept.until > now) return kept.active;
|
|
215
|
+
let active = false;
|
|
216
|
+
try {
|
|
217
|
+
const res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/introspect`, {
|
|
218
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
221
|
+
body: new URLSearchParams({ token })
|
|
222
|
+
});
|
|
223
|
+
if (!res.ok) throw new Error(`introspection answered ${res.status}`);
|
|
224
|
+
active = (await res.json()).active === true;
|
|
225
|
+
} catch (err) {
|
|
226
|
+
if (kept) return kept.active;
|
|
227
|
+
throw new McpAuthError(401, "invalid_token", `could not check the token with Cauthy: ${err instanceof Error ? err.message : "unreachable"}`);
|
|
228
|
+
}
|
|
229
|
+
if (answers.size > 1e4) answers.clear();
|
|
230
|
+
answers.set(token, { active, until: now + cacheMs });
|
|
231
|
+
return active;
|
|
232
|
+
};
|
|
233
|
+
const verify = async (from, needs = []) => {
|
|
234
|
+
const token = bearer(from);
|
|
235
|
+
if (token === "") throw new McpAuthError(401, "invalid_request", "no access token");
|
|
236
|
+
let claims;
|
|
237
|
+
try {
|
|
238
|
+
const verified = await (0, import_jose2.jwtVerify)(token, options.jwks ?? keysOf(issuer), {
|
|
239
|
+
algorithms: ["RS256"],
|
|
240
|
+
issuer,
|
|
241
|
+
audience: resource,
|
|
242
|
+
requiredClaims: ["exp", "sub"],
|
|
243
|
+
currentDate: options.now?.()
|
|
244
|
+
});
|
|
245
|
+
claims = verified.payload;
|
|
246
|
+
} catch (err) {
|
|
247
|
+
throw new McpAuthError(401, "invalid_token", err instanceof Error ? err.message : "the token is not valid");
|
|
248
|
+
}
|
|
249
|
+
const clientId2 = typeof claims.client_id === "string" ? claims.client_id : "";
|
|
250
|
+
if (clientId2 === "") throw new McpAuthError(401, "invalid_token", "not a token issued to an agent");
|
|
251
|
+
const scopes = typeof claims.scope === "string" ? claims.scope.split(" ").filter(Boolean) : [];
|
|
252
|
+
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");
|
|
253
|
+
const missing = [...required, ...needs].filter((s) => !scopes.includes(s));
|
|
254
|
+
if (missing.length > 0) throw new McpAuthError(403, "insufficient_scope", `this needs ${missing.join(" ")}`);
|
|
255
|
+
return {
|
|
256
|
+
userId: String(claims.sub),
|
|
257
|
+
tenantId: typeof claims.tid === "string" ? claims.tid : "",
|
|
258
|
+
...typeof claims.email === "string" && claims.email !== "" ? { email: claims.email } : {},
|
|
259
|
+
roles: Array.isArray(claims.roles) ? claims.roles.filter((r) => typeof r === "string") : [],
|
|
260
|
+
scopes,
|
|
261
|
+
clientId: clientId2,
|
|
262
|
+
expiresAt: new Date(claims.exp * 1e3).toISOString(),
|
|
263
|
+
token,
|
|
264
|
+
...isActor(claims.act) ? { actor: claims.act.sub } : {}
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
const clientId = options.clientId ?? env("CAUTHY_MCP_CLIENT_ID") ?? "";
|
|
268
|
+
const clientSecret = options.clientSecret ?? env("CAUTHY_MCP_CLIENT_SECRET") ?? "";
|
|
269
|
+
const exchanged = /* @__PURE__ */ new Map();
|
|
270
|
+
const exchange = async (from, target, scopes = []) => {
|
|
271
|
+
if (clientId === "" || clientSecret === "") {
|
|
272
|
+
throw new Error("@cauthyhq/node: token exchange needs clientId and clientSecret (CAUTHY_MCP_CLIENT_ID, CAUTHY_MCP_CLIENT_SECRET)");
|
|
273
|
+
}
|
|
274
|
+
const subject = typeof from === "string" ? bearer(from) : from.token;
|
|
275
|
+
const to = canonicalResource(target);
|
|
276
|
+
const key = `${subject}
|
|
277
|
+
${to}
|
|
278
|
+
${scopes.join(" ")}`;
|
|
279
|
+
const kept = exchanged.get(key);
|
|
280
|
+
if (kept && kept.until > Date.now()) return { accessToken: kept.accessToken, scopes: kept.scopes, expiresAt: kept.expiresAt };
|
|
281
|
+
let res;
|
|
282
|
+
try {
|
|
283
|
+
res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {
|
|
284
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
285
|
+
method: "POST",
|
|
286
|
+
headers: {
|
|
287
|
+
"content-type": "application/x-www-form-urlencoded",
|
|
288
|
+
accept: "application/json",
|
|
289
|
+
authorization: `Basic ${btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)}`
|
|
290
|
+
},
|
|
291
|
+
body: new URLSearchParams({
|
|
292
|
+
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
|
|
293
|
+
subject_token: subject,
|
|
294
|
+
subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
|
|
295
|
+
resource: to,
|
|
296
|
+
...scopes.length > 0 ? { scope: scopes.join(" ") } : {}
|
|
297
|
+
})
|
|
298
|
+
});
|
|
299
|
+
} catch (err) {
|
|
300
|
+
throw new CauthyExchangeError(503, "temporarily_unavailable", `Cauthy could not be reached: ${err instanceof Error ? err.message : "unreachable"}`);
|
|
301
|
+
}
|
|
302
|
+
const body = await res.json().catch(() => ({}));
|
|
303
|
+
if (!res.ok || typeof body.access_token !== "string") {
|
|
304
|
+
throw new CauthyExchangeError(
|
|
305
|
+
res.status,
|
|
306
|
+
typeof body.error === "string" ? body.error : "server_error",
|
|
307
|
+
typeof body.error_description === "string" ? body.error_description : `Cauthy answered ${res.status}`
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
const expiresIn = typeof body.expires_in === "number" ? body.expires_in : 0;
|
|
311
|
+
const out = {
|
|
312
|
+
accessToken: body.access_token,
|
|
313
|
+
scopes: typeof body.scope === "string" ? body.scope.split(" ").filter(Boolean) : [],
|
|
314
|
+
expiresAt: new Date(Date.now() + expiresIn * 1e3).toISOString()
|
|
315
|
+
};
|
|
316
|
+
if (exchanged.size > 1e4) exchanged.clear();
|
|
317
|
+
exchanged.set(key, { ...out, until: Date.now() + Math.max(0, expiresIn - 30) * 1e3 });
|
|
318
|
+
return out;
|
|
319
|
+
};
|
|
320
|
+
const authenticate = (error) => {
|
|
321
|
+
const parts = [`resource_metadata=${quoted(metadataUrl)}`];
|
|
322
|
+
if (error && error.code !== "invalid_request") {
|
|
323
|
+
parts.push(`error=${quoted(error.code)}`, `error_description=${quoted(error.description)}`);
|
|
324
|
+
}
|
|
325
|
+
const scope = error?.code === "invalid_token" ? [] : required;
|
|
326
|
+
if (scope.length > 0) parts.push(`scope=${quoted(scope.join(" "))}`);
|
|
327
|
+
return `Bearer ${parts.join(", ")}`;
|
|
328
|
+
};
|
|
329
|
+
const challenge = (error) => {
|
|
330
|
+
const status = error?.status ?? 401;
|
|
331
|
+
return new Response(JSON.stringify({ error: error?.code ?? "invalid_request", error_description: error?.description ?? "an access token is required" }), {
|
|
332
|
+
status,
|
|
333
|
+
headers: { "content-type": "application/json", "www-authenticate": authenticate(error) }
|
|
334
|
+
});
|
|
335
|
+
};
|
|
336
|
+
const metadataResponse = () => new Response(JSON.stringify(metadata()), {
|
|
337
|
+
headers: { "content-type": "application/json", "cache-control": "public, max-age=3600", "access-control-allow-origin": "*" }
|
|
338
|
+
});
|
|
339
|
+
const isMetadata = (pathname, method = "GET") => method === "GET" && metadataPaths.includes(withoutTrailingSlashes(pathname) || "/");
|
|
340
|
+
const handleMetadata = (request) => isMetadata(new URL(request.url).pathname, request.method) ? metadataResponse() : null;
|
|
341
|
+
const toAuthInfo = (a) => ({
|
|
342
|
+
token: a.token,
|
|
343
|
+
clientId: a.clientId,
|
|
344
|
+
scopes: a.scopes,
|
|
345
|
+
expiresAt: Math.floor(new Date(a.expiresAt).getTime() / 1e3),
|
|
346
|
+
resource: new URL(resource),
|
|
347
|
+
extra: { userId: a.userId, tenantId: a.tenantId, ...a.email ? { email: a.email } : {}, roles: a.roles }
|
|
348
|
+
});
|
|
349
|
+
return {
|
|
350
|
+
resource,
|
|
351
|
+
metadataUrl,
|
|
352
|
+
metadataPaths,
|
|
353
|
+
metadata,
|
|
354
|
+
verify,
|
|
355
|
+
challenge,
|
|
356
|
+
handleMetadata,
|
|
357
|
+
protect(handler, needs) {
|
|
358
|
+
return async (request) => {
|
|
359
|
+
const meta = handleMetadata(request);
|
|
360
|
+
if (meta) return meta;
|
|
361
|
+
let agent;
|
|
362
|
+
try {
|
|
363
|
+
agent = await verify(request, needs);
|
|
364
|
+
} catch (err) {
|
|
365
|
+
if (err instanceof McpAuthError) return challenge(err);
|
|
366
|
+
throw err;
|
|
367
|
+
}
|
|
368
|
+
return handler(request, agent);
|
|
369
|
+
};
|
|
370
|
+
},
|
|
371
|
+
exchange,
|
|
372
|
+
middleware(needs) {
|
|
373
|
+
return (req, res, next) => {
|
|
374
|
+
const pathname = (req.originalUrl ?? req.url ?? "/").split("?")[0] ?? "/";
|
|
375
|
+
if (isMetadata(pathname, req.method)) {
|
|
376
|
+
res.statusCode = 200;
|
|
377
|
+
res.setHeader("content-type", "application/json");
|
|
378
|
+
res.setHeader("cache-control", "public, max-age=3600");
|
|
379
|
+
res.setHeader("access-control-allow-origin", "*");
|
|
380
|
+
res.end(JSON.stringify(metadata()));
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const raw = req.headers.authorization;
|
|
384
|
+
const header = Array.isArray(raw) ? raw[0] ?? "" : raw ?? "";
|
|
385
|
+
verify(/^Bearer\s+/i.test(header) ? header : "", needs).then(
|
|
386
|
+
(agent) => {
|
|
387
|
+
req.agent = agent;
|
|
388
|
+
req.auth = toAuthInfo(agent);
|
|
389
|
+
next();
|
|
390
|
+
},
|
|
391
|
+
(err) => {
|
|
392
|
+
if (!(err instanceof McpAuthError)) return next(err);
|
|
393
|
+
res.statusCode = err.status;
|
|
394
|
+
res.setHeader("content-type", "application/json");
|
|
395
|
+
res.setHeader("www-authenticate", authenticate(err));
|
|
396
|
+
res.end(JSON.stringify({ error: err.code, error_description: err.description }));
|
|
397
|
+
}
|
|
398
|
+
);
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
404
|
+
0 && (module.exports = {
|
|
405
|
+
CauthyExchangeError,
|
|
406
|
+
McpAuthError,
|
|
407
|
+
canonicalResource,
|
|
408
|
+
mcpAuth
|
|
409
|
+
});
|
|
410
|
+
//# sourceMappingURL=mcp.js.map
|
package/dist/mcp.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
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 '@cauthyhq/node/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 /** How long a call to Cauthy (introspection, token exchange) may take, in milliseconds. Default: 5000. */\n timeoutMs?: number\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(`@cauthyhq/node: 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(`@cauthyhq/node: ${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(`@cauthyhq/node: 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('@cauthyhq/node: resource must be an https address')\n }\n if (u.search !== '' || u.hash !== '') throw new Error('@cauthyhq/node: 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('@cauthyhq/node: 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('@cauthyhq/node: issuer (CAUTHY_ISSUER) is not set')\n const timeoutMs = options.timeoutMs ?? 5000\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('@cauthyhq/node: timeoutMs must be a positive number of milliseconds')\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 signal: AbortSignal.timeout(timeoutMs),\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('@cauthyhq/node: 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 let res: Response\n try {\n res = await (options.fetch ?? fetch)(`${issuer}/v1/oauth/token`, {\n signal: AbortSignal.timeout(timeoutMs),\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 } catch (err) {\n throw new CauthyExchangeError(503, 'temporarily_unavailable', `Cauthy could not be reached: ${err instanceof Error ? err.message : 'unreachable'}`)\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, and read `reason`, one of the closed list of codes in the spec's\n// verification/rules.md.\n\nimport { compactVerify, createLocalJWKSet, type CompactVerifyGetKey, type JSONWebKeySet, type JWTVerifyGetKey } from 'jose'\nimport { parseStrict } from './json'\nimport { CauthyConfigError } from './types'\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 /** What the token says of the address, when it says (a boolean; absent otherwise). */\n emailVerified?: boolean\n roles: string[]\n /** Set when the token is a system's own and not a person's (only with `allowSystem`). */\n system?: string\n /** Set when the token is a guest's (only with `allowAnonymous`). */\n anonymous?: true\n /** UTC, ISO 8601. */\n expiresAt: string\n /** The token as it arrived, to pass on. */\n token: string\n}\n\n/** Why a token was refused: the closed list of verification/rules.md, and `no_token` when none was given. */\nexport type TokenRefusal =\n | 'no_token' | 'too_large' | 'malformed' | 'alg_not_allowed' | 'unsupported_header' | 'missing_kid' | 'unknown_kid' | 'weak_key'\n | 'bad_signature' | 'missing_claim' | 'invalid_claim' | 'wrong_issuer' | 'wrong_audience' | 'expired' | 'not_yet_valid'\n | 'issued_in_future' | 'wrong_tenant' | 'system_token' | 'anonymous_token'\n\n/**\n * Cauthy's keys could not be fetched (or are not a key set): the token may be\n * good, and the application cannot tell. Answer 503, not 401. It is not a\n * `CauthyTokenError`: it says nothing about the token.\n */\nexport class CauthyUnavailableError extends Error {\n constructor(detail: string) {\n super(`@cauthyhq/node: Cauthy's keys are unavailable: ${detail}`)\n this.name = 'CauthyUnavailableError'\n }\n}\n\nexport class CauthyTokenError extends Error {\n constructor(readonly reason: TokenRefusal, readonly detail?: string) {\n super(`@cauthyhq/node: token refused: ${reason}${detail ? ` (${detail})` : ''}`)\n this.name = 'CauthyTokenError'\n }\n}\n\nexport interface VerifyTokenOptions {\n /** Cauthy's address. Default: `CAUTHY_ISSUER`. */\n issuer?: string\n /**\n * Further issuers a token may name, e.g. a workspace's custom domain. The\n * keys always come from `issuer`. Default: none.\n */\n issuers?: string[]\n /** The audience the tokens must carry. Required: this or `CAUTHY_AUDIENCE`. */\n audience?: string\n /** The workspace's id, a lowercase UUID. Required: this or `CAUTHY_TENANT_ID`. */\n tenantId?: string\n /** Cauthy's keys. Default: fetched from the issuer and cached (see `remoteKeys`). */\n jwks?: JWTVerifyGetKey\n /** The fetch to get the keys with. Default: the global one. */\n fetch?: typeof fetch\n /** The moment to verify at. Default: now. */\n now?: Date\n /** Clock tolerance in seconds, 0 to 60. Default: 30. */\n leeway?: number\n /**\n * Accept a system's own token (a `sys` claim) too: for an endpoint another\n * system calls. Default: false, so a system's token never stands for a\n * person (rule R13 of the spec's verification/rules.md).\n */\n allowSystem?: boolean\n /** Accept a guest's token (`anon: true`). Default: false (rule R14). */\n allowAnonymous?: boolean\n}\n\nconst MAX_TOKEN_BYTES = 8192\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/\nconst NIL_UUID = '00000000-0000-0000-0000-000000000000'\nconst SEGMENT = /^[A-Za-z0-9_-]+$/\n\nconst MAX_KEYS_BYTES = 64 * 1024\nconst KEYS_TIMEOUT_MS = 5000\nconst KEYS_COOLDOWN_MS = 30_000\nconst KEYS_DEFAULT_TTL_S = 300\nconst KEYS_MIN_TTL_S = 60\nconst KEYS_MAX_TTL_S = 3600\n\n/**\n * Cauthy's published keys (K1 to K5 of verification/rules.md): fetched with a\n * GET that follows no redirect, within 5 seconds, from `<issuer>/.well-known/jwks.json`;\n * only a 200 of at most 64 KiB counts. Kept for the answer's max-age (at most\n * an hour and at least a minute, 5 minutes when it names none); a `kid` the set lacks fetches again\n * only if the last fetch is older than 30 seconds; one fetch at a time; a\n * failed fetch keeps the last good set, and with none it is\n * `CauthyUnavailableError`.\n */\nexport function remoteKeys(issuer: string, fetchKeys: typeof fetch = fetch): JWTVerifyGetKey {\n let set: JWTVerifyGetKey | undefined\n let startedAt = 0\n let expiresAt = 0\n let inflight: Promise<void> | undefined\n\n const load = async (): Promise<void> => {\n startedAt = Date.now()\n try {\n const res = await fetchKeys(`${issuer}/.well-known/jwks.json`, { redirect: 'manual', signal: AbortSignal.timeout(KEYS_TIMEOUT_MS), headers: { accept: 'application/json' } })\n if (res.status !== 200) throw new Error(`answered ${res.status}`)\n const bytes = await readCapped(res, MAX_KEYS_BYTES)\n const parsed = JSON.parse(new TextDecoder().decode(bytes)) as JSONWebKeySet\n if (!parsed || !Array.isArray(parsed.keys)) throw new Error('not a key set')\n // K6: two usable keys with one kid make the whole set untrustworthy.\n const seen = new Set<string>()\n for (const k of parsed.keys) {\n const usable = k?.kty === 'RSA' && (k.use === undefined || k.use === 'sig') && (k.alg === undefined || k.alg === 'RS256')\n if (!usable || typeof k.kid !== 'string') continue\n if (seen.has(k.kid)) throw new Error(`two usable keys share the kid ${JSON.stringify(k.kid)}`)\n seen.add(k.kid)\n }\n set = createLocalJWKSet(parsed)\n const maxAge = /max-age=(\\d+)/.exec(res.headers.get('cache-control') ?? '')\n // At least a minute: max-age=0 must not mean a fetch for every token.\n const ttl = Math.max(KEYS_MIN_TTL_S, Math.min(maxAge ? Number(maxAge[1]) : KEYS_DEFAULT_TTL_S, KEYS_MAX_TTL_S))\n expiresAt = Date.now() + ttl * 1000\n } catch (err) {\n // The last good set stands, and is not asked for again before the cooldown:\n // an outage must not cost a wait on every verification. With none, the\n // application cannot tell.\n if (set === undefined) throw new CauthyUnavailableError(err instanceof Error ? err.message : 'unreachable')\n expiresAt = Math.max(expiresAt, Date.now() + KEYS_COOLDOWN_MS)\n }\n }\n const refresh = (): Promise<void> => {\n inflight ??= load().finally(() => {\n inflight = undefined\n })\n return inflight\n }\n\n return async (header, token) => {\n if (set === undefined || Date.now() >= expiresAt) await refresh()\n try {\n return await set!(header, token)\n } catch (err) {\n const unknown = (err as { code?: unknown } | null)?.code === 'ERR_JWKS_NO_MATCHING_KEY'\n if (unknown && Date.now() - startedAt >= KEYS_COOLDOWN_MS) {\n await refresh()\n return set!(header, token)\n }\n throw err\n }\n }\n}\n\nasync function readCapped(res: Response, max: number): Promise<Uint8Array> {\n const reader = res.body?.getReader()\n if (!reader) return new Uint8Array()\n const chunks: Uint8Array[] = []\n let size = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n size += value.length\n if (size > max) {\n await reader.cancel()\n throw new Error(`over ${max} bytes`)\n }\n chunks.push(value)\n }\n const out = new Uint8Array(size)\n let at = 0\n for (const c of chunks) {\n out.set(c, at)\n at += c.length\n }\n return out\n}\n\nconst published = new Map<string, JWTVerifyGetKey>()\nconst withFetch = new WeakMap<typeof fetch, Map<string, JWTVerifyGetKey>>()\n\nfunction remoteKeysFor(issuer: string, fetchKeys: typeof fetch): JWTVerifyGetKey {\n let byIssuer = withFetch.get(fetchKeys)\n if (!byIssuer) withFetch.set(fetchKeys, (byIssuer = new Map()))\n let set = byIssuer.get(issuer)\n if (!set) byIssuer.set(issuer, (set = remoteKeys(issuer, fetchKeys)))\n return set\n}\n\n/** Cauthy's published keys, fetched once per issuer and kept (see `remoteKeys`). */\nexport function keysOf(issuer: string): JWTVerifyGetKey {\n let set = published.get(issuer)\n if (set === undefined) {\n set = remoteKeys(issuer)\n published.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 // A raw token is taken as it is: surrounding whitespace is the caller's mistake (R2).\n if (typeof from === 'string') return from.replace(/^Bearer\\s+/i, '')\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 issuerAddress(value: string, what: string): string {\n let url: URL\n try {\n url = new URL(value)\n } catch {\n throw new CauthyConfigError(`${what} must be an https address, e.g. https://id.example.com`)\n }\n // http is for a developer's own machine: localhost, 127.0.0.1, *.localhost and *.test.\n const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname.endsWith('.localhost') || url.hostname.endsWith('.test')\n if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) throw new CauthyConfigError(`${what} must be https (http only for localhost, *.localhost and *.test)`)\n if (url.search !== '' || url.hash !== '') throw new CauthyConfigError(`${what} must have no query or fragment`)\n return withoutTrailingSlashes(value)\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)\n\nfunction decodeJson(segment: string): unknown {\n const padded = segment.replace(/-/g, '+').replace(/_/g, '/')\n return parseStrict(Buffer.from(padded, 'base64').toString('utf8'))\n}\n\n/**\n * A verifier for access tokens, configured once. Refuses to be made without\n * an issuer, an audience and a workspace: a verifier that checks none of\n * them would accept a token of any other application or workspace.\n */\nexport function createTokenVerifier(options: VerifyTokenOptions = {}): (from: string | Request | Headers) => Promise<TokenIdentity> {\n const issuerGiven = options.issuer ?? env('CAUTHY_ISSUER') ?? ''\n if (issuerGiven === '') throw new CauthyConfigError('issuer (CAUTHY_ISSUER) is not set')\n const issuer = issuerAddress(issuerGiven, 'issuer')\n const issuers = [issuer, ...(options.issuers ?? []).map((i) => issuerAddress(i, 'issuers'))]\n const audience = options.audience ?? env('CAUTHY_AUDIENCE') ?? ''\n if (audience === '') throw new CauthyConfigError('audience (CAUTHY_AUDIENCE) is not set: without it a token issued for another application would be accepted')\n const tenant = options.tenantId ?? env('CAUTHY_TENANT_ID') ?? ''\n if (tenant === '') throw new CauthyConfigError('tenantId (CAUTHY_TENANT_ID) is not set: without it a token of another workspace would be accepted')\n if (!UUID.test(tenant) || tenant === NIL_UUID) throw new CauthyConfigError('tenantId must be the workspace\\'s id, a lowercase UUID that is not the nil UUID')\n const leeway = options.leeway ?? 30\n if (!Number.isFinite(leeway) || leeway < 0 || leeway > 60) throw new CauthyConfigError('leeway must be 0 to 60 seconds')\n\n return async (from) => {\n const token = bearer(from)\n if (token === '') throw new CauthyTokenError('no_token')\n // R1\n if (Buffer.byteLength(token) > MAX_TOKEN_BYTES) throw new CauthyTokenError('too_large')\n // R2\n const parts = token.split('.')\n if (parts.length !== 3 || !parts.every((p) => SEGMENT.test(p) || p === '')) throw new CauthyTokenError('malformed', 'not three base64url segments')\n let header: unknown\n try {\n header = decodeJson(parts[0])\n } catch {\n throw new CauthyTokenError('malformed', 'the header is not JSON')\n }\n if (!isObject(header)) throw new CauthyTokenError('malformed', 'the header is not an object')\n // R3, R4, R5: the algorithm is the verifier's, never the token's.\n if (header.alg !== 'RS256') throw new CauthyTokenError('alg_not_allowed')\n if ('crit' in header) throw new CauthyTokenError('unsupported_header')\n // R4: typ is not required, but when present it is JWT or at+jwt, in any case.\n if ('typ' in header && !(typeof header.typ === 'string' && ['jwt', 'at+jwt'].includes(header.typ.toLowerCase()))) {\n throw new CauthyTokenError('unsupported_header', 'typ')\n }\n if (typeof header.kid !== 'string' || header.kid === '') throw new CauthyTokenError('missing_kid')\n\n // R5, R6\n let payloadBytes: Uint8Array\n try {\n const verified = await compactVerify(token, (options.jwks ?? (options.fetch ? remoteKeysFor(issuer, options.fetch) : keysOf(issuer))) as CompactVerifyGetKey, { algorithms: ['RS256'] })\n payloadBytes = verified.payload\n } catch (err) {\n // By code, not by class: the keys may come from another copy of jose.\n const code = (err as { code?: unknown } | null)?.code\n if (code === 'ERR_JWKS_NO_MATCHING_KEY') throw new CauthyTokenError('unknown_kid')\n if (code === 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED') throw new CauthyTokenError('bad_signature')\n if (err instanceof TypeError && /2048/.test(err.message)) throw new CauthyTokenError('weak_key')\n if (code === 'ERR_JWS_INVALID') throw new CauthyTokenError('malformed', err instanceof Error ? err.message : undefined)\n if (err instanceof CauthyUnavailableError) throw err\n throw new CauthyTokenError('bad_signature', err instanceof Error ? err.message : undefined)\n }\n\n // R7\n let claims: unknown\n try {\n claims = parseStrict(new TextDecoder().decode(payloadBytes), ['exp', 'iat', 'nbf'])\n } catch {\n throw new CauthyTokenError('malformed', 'the payload is not JSON')\n }\n if (!isObject(claims)) throw new CauthyTokenError('malformed', 'the payload is not an object')\n for (const name of ['iss', 'sub', 'aud', 'exp', 'iat', 'tid']) {\n if (claims[name] === undefined) throw new CauthyTokenError('missing_claim', name)\n }\n // R8: no claim is null but roles.\n const bad = (name: string): never => {\n throw new CauthyTokenError('invalid_claim', name)\n }\n if (typeof claims.iss !== 'string') bad('iss')\n if (typeof claims.sub !== 'string' || !UUID.test(claims.sub)) bad('sub')\n if (typeof claims.tid !== 'string' || !UUID.test(claims.tid)) bad('tid')\n const aud = claims.aud\n if (!(typeof aud === 'string' || (Array.isArray(aud) && aud.length > 0 && aud.every((a) => typeof a === 'string')))) bad('aud')\n for (const name of ['exp', 'iat', 'nbf']) if (claims[name] !== undefined && !Number.isInteger(claims[name])) bad(name)\n if (claims.roles !== undefined && claims.roles !== null && !(Array.isArray(claims.roles) && claims.roles.every((r) => typeof r === 'string'))) bad('roles')\n if (claims.email !== undefined && typeof claims.email !== 'string') bad('email')\n for (const name of ['email_verified', 'anon']) if (claims[name] !== undefined && typeof claims[name] !== 'boolean') bad(name)\n\n // R9, R10\n if (!issuers.includes(claims.iss as string)) throw new CauthyTokenError('wrong_issuer')\n if (!(Array.isArray(aud) ? aud.includes(audience) : aud === audience)) throw new CauthyTokenError('wrong_audience')\n // R11\n const now = (options.now ?? new Date()).getTime() / 1000\n if (now >= (claims.exp as number) + leeway) throw new CauthyTokenError('expired')\n if (claims.nbf !== undefined && now < (claims.nbf as number) - leeway) throw new CauthyTokenError('not_yet_valid')\n if (now < (claims.iat as number) - leeway) throw new CauthyTokenError('issued_in_future')\n // R12\n if (claims.tid !== tenant) throw new CauthyTokenError('wrong_tenant')\n // R13, R14\n // Its presence is the mark, whatever the value (null and false included).\n if ('sys' in claims && !options.allowSystem) throw new CauthyTokenError('system_token')\n if (claims.anon === true && !options.allowAnonymous) throw new CauthyTokenError('anonymous_token')\n\n return {\n userId: claims.sub as string,\n tenantId: claims.tid as string,\n ...(typeof claims.email === 'string' && claims.email !== '' ? { email: claims.email } : {}),\n ...(typeof claims.email_verified === 'boolean' ? { emailVerified: claims.email_verified } : {}),\n roles: Array.isArray(claims.roles) ? (claims.roles as string[]) : [],\n ...(typeof claims.sys === 'string' && claims.sys !== '' ? { system: claims.sys } : {}),\n ...(claims.anon === true ? { anonymous: true as const } : {}),\n expiresAt: new Date((claims.exp as number) * 1000).toISOString(),\n token,\n }\n }\n}\n\n/**\n * Verifies an access token (or the `Authorization: Bearer` of a request) and\n * answers who it belongs to, by the rules of the spec's verification/rules.md.\n * Needs an issuer, an audience and a workspace (see `createTokenVerifier`,\n * which checks them once, at startup).\n */\nexport async function verifyToken(from: string | Request | Headers, options: VerifyTokenOptions = {}): Promise<TokenIdentity> {\n return createTokenVerifier(options)(from)\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;;;AClBhD,kBAAqH;;;ACN9G,SAAS,uBAAuB,GAAmB;AACxD,MAAI,MAAM,EAAE;AACZ,SAAO,MAAM,KAAK,EAAE,WAAW,MAAM,CAAC,MAAM,GAAI;AAChD,SAAO,EAAE,MAAM,GAAG,GAAG;AACvB;;;ADqCO,IAAM,yBAAN,cAAqC,MAAM;AAAA,EAChD,YAAY,QAAgB;AAC1B,UAAM,kDAAkD,MAAM,EAAE;AAChE,SAAK,OAAO;AAAA,EACd;AACF;AA4CA,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