@pontive/server 0.0.0-stage → 1.23.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/README.md +146 -2
- package/dist/auth.d.cts +34 -0
- package/dist/auth.d.ts +34 -0
- package/dist/authorization.cjs +2 -0
- package/dist/authorization.cjs.map +1 -0
- package/dist/authorization.d.cts +222 -0
- package/dist/authorization.d.ts +222 -0
- package/dist/authorization.js +153 -0
- package/dist/authorization.js.map +1 -0
- package/dist/browser-mode.d.cts +23 -0
- package/dist/browser-mode.d.ts +23 -0
- package/dist/config.d.cts +131 -0
- package/dist/config.d.ts +131 -0
- package/dist/cookies.d.cts +50 -0
- package/dist/cookies.d.ts +50 -0
- package/dist/env.d.cts +44 -0
- package/dist/env.d.ts +44 -0
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +20 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +700 -0
- package/dist/index.js.map +1 -0
- package/dist/keyless.cjs +16 -0
- package/dist/keyless.cjs.map +1 -0
- package/dist/keyless.d.cts +244 -0
- package/dist/keyless.d.ts +244 -0
- package/dist/keyless.js +355 -0
- package/dist/keyless.js.map +1 -0
- package/dist/management-credential-BNyhHagG.cjs +2 -0
- package/dist/management-credential-BNyhHagG.cjs.map +1 -0
- package/dist/management-credential-VhmMzGDl.js +39 -0
- package/dist/management-credential-VhmMzGDl.js.map +1 -0
- package/dist/management-credential.d.cts +40 -0
- package/dist/management-credential.d.ts +40 -0
- package/dist/mcp-auth-info-BGyWua_9.js +19 -0
- package/dist/mcp-auth-info-BGyWua_9.js.map +1 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs +2 -0
- package/dist/mcp-auth-info-jblMsSJo.cjs.map +1 -0
- package/dist/mcp-auth-info.d.cts +17 -0
- package/dist/mcp-auth-info.d.ts +17 -0
- package/dist/oidc--We55Nrh.cjs +2 -0
- package/dist/oidc--We55Nrh.cjs.map +1 -0
- package/dist/oidc-CB0FqjFz.js +131 -0
- package/dist/oidc-CB0FqjFz.js.map +1 -0
- package/dist/oidc.d.cts +80 -0
- package/dist/oidc.d.ts +80 -0
- package/dist/organization.d.cts +35 -0
- package/dist/organization.d.ts +35 -0
- package/dist/preview-hosts.d.cts +33 -0
- package/dist/preview-hosts.d.ts +33 -0
- package/dist/refresh.d.cts +28 -0
- package/dist/refresh.d.ts +28 -0
- package/dist/resource-server-express.cjs +2 -0
- package/dist/resource-server-express.cjs.map +1 -0
- package/dist/resource-server-express.d.cts +73 -0
- package/dist/resource-server-express.d.ts +73 -0
- package/dist/resource-server-express.js +57 -0
- package/dist/resource-server-express.js.map +1 -0
- package/dist/resource-server-mcp.cjs +2 -0
- package/dist/resource-server-mcp.cjs.map +1 -0
- package/dist/resource-server-mcp.d.cts +70 -0
- package/dist/resource-server-mcp.d.ts +70 -0
- package/dist/resource-server-mcp.js +59 -0
- package/dist/resource-server-mcp.js.map +1 -0
- package/dist/resource-server.cjs +2 -0
- package/dist/resource-server.cjs.map +1 -0
- package/dist/resource-server.d.cts +290 -0
- package/dist/resource-server.d.ts +290 -0
- package/dist/resource-server.js +301 -0
- package/dist/resource-server.js.map +1 -0
- package/dist/seal.d.cts +3 -0
- package/dist/seal.d.ts +3 -0
- package/dist/server-auth.d.cts +100 -0
- package/dist/server-auth.d.ts +100 -0
- package/package.json +96 -4
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { decodeJwt as ce, jwtVerify as ie, createRemoteJWKSet as ue, customFetch as le } from "jose";
|
|
2
|
+
import { a as he, m as V } from "./management-credential-VhmMzGDl.js";
|
|
3
|
+
import { f as de } from "./oidc-CB0FqjFz.js";
|
|
4
|
+
class T extends Error {
|
|
5
|
+
constructor(a, n, i, l) {
|
|
6
|
+
super(l), this.status = a, this.code = n, this.wwwAuthenticate = i, this.name = "BearerError";
|
|
7
|
+
}
|
|
8
|
+
status;
|
|
9
|
+
code;
|
|
10
|
+
wwwAuthenticate;
|
|
11
|
+
toResponse() {
|
|
12
|
+
return Response.json(
|
|
13
|
+
{ error: this.code ?? "unauthorized", error_description: this.message },
|
|
14
|
+
{ status: this.status, headers: { "www-authenticate": this.wwwAuthenticate, "cache-control": "no-store" } }
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const S = "/.well-known/oauth-protected-resource", F = "/.well-known/oauth-authorization-server", pe = 300 * 1e3, fe = 600 * 1e3, we = /* @__PURE__ */ new Set(["openid", "profile", "email", "address", "phone", "offline_access"]), me = { usr: "user", svc: "service_account", agt: "agent" }, ye = /* @__PURE__ */ new Set([
|
|
19
|
+
"ERR_JWT_EXPIRED",
|
|
20
|
+
"ERR_JWT_CLAIM_VALIDATION_FAILED",
|
|
21
|
+
"ERR_JWT_INVALID",
|
|
22
|
+
"ERR_JWS_INVALID",
|
|
23
|
+
"ERR_JWS_SIGNATURE_VERIFICATION_FAILED",
|
|
24
|
+
"ERR_JWKS_NO_MATCHING_KEY",
|
|
25
|
+
"ERR_JWKS_MULTIPLE_MATCHING_KEYS",
|
|
26
|
+
"ERR_JOSE_ALG_NOT_ALLOWED",
|
|
27
|
+
"ERR_JOSE_NOT_SUPPORTED"
|
|
28
|
+
]), E = (o) => o.replace(/\/+$/, "");
|
|
29
|
+
function _e(o) {
|
|
30
|
+
let a;
|
|
31
|
+
try {
|
|
32
|
+
a = new URL(o);
|
|
33
|
+
} catch {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (a.protocol !== "https:" && a.protocol !== "http:") return;
|
|
37
|
+
const n = a.pathname === "/" ? "" : E(a.pathname);
|
|
38
|
+
return {
|
|
39
|
+
url: `${a.origin}${S}${n}`,
|
|
40
|
+
paths: n ? [`${S}${n}`, S] : [S]
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
function w(o) {
|
|
44
|
+
return `"${o.replace(/[\\"]/g, "\\$&")}"`;
|
|
45
|
+
}
|
|
46
|
+
function Y(o) {
|
|
47
|
+
return Array.isArray(o) ? o.filter((a) => typeof a == "string") : [];
|
|
48
|
+
}
|
|
49
|
+
function ve(o, a) {
|
|
50
|
+
const n = o.headers;
|
|
51
|
+
if (n instanceof Headers) return n.get(a) ?? void 0;
|
|
52
|
+
const i = n[a] ?? n[a.toLowerCase()];
|
|
53
|
+
return Array.isArray(i) ? i[0] : i;
|
|
54
|
+
}
|
|
55
|
+
function ge(o) {
|
|
56
|
+
return /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(ve(o, "authorization") ?? "")?.[1];
|
|
57
|
+
}
|
|
58
|
+
const m = (o) => ({
|
|
59
|
+
"access-control-allow-origin": "*",
|
|
60
|
+
"access-control-allow-methods": "GET, OPTIONS",
|
|
61
|
+
"access-control-allow-headers": o.headers.get("access-control-request-headers") ?? "*",
|
|
62
|
+
"access-control-max-age": "86400"
|
|
63
|
+
});
|
|
64
|
+
function q(o, a, n) {
|
|
65
|
+
let i, l;
|
|
66
|
+
return {
|
|
67
|
+
get last() {
|
|
68
|
+
return i?.value;
|
|
69
|
+
},
|
|
70
|
+
get() {
|
|
71
|
+
return i && Date.now() - i.at < pe ? Promise.resolve(i.value) : (l ??= o().then((d) => (i = { at: Date.now(), value: d }, d)).catch((d) => {
|
|
72
|
+
if (i)
|
|
73
|
+
return n.warn(`[pontive] ${a} refresh failed; serving the cached copy: ${String(d)}`), i.value;
|
|
74
|
+
throw d;
|
|
75
|
+
}).finally(() => {
|
|
76
|
+
l = void 0;
|
|
77
|
+
}), l);
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function $e(o) {
|
|
82
|
+
const a = (Array.isArray(o.issuer) ? o.issuer : [o.issuer]).map(E);
|
|
83
|
+
if (a.length === 0 || a.some((e) => !e)) throw new Error("resource server: issuer is required");
|
|
84
|
+
if (!o.resource) throw new Error("resource server: resource is required");
|
|
85
|
+
const n = o.resource, i = o.fetch ?? ((...e) => fetch(...e)), l = o.logger ?? console, d = o.leewaySeconds ?? 60, h = _e(n), R = (o.scopes ?? []).map((e) => typeof e == "string" ? e : e.key), M = o.unlistedTools ?? "deny";
|
|
86
|
+
if (o.metadata?.fetch && !h)
|
|
87
|
+
throw new Error("resource server: metadata is only served for an http(s) resource identifier");
|
|
88
|
+
const $ = /* @__PURE__ */ new Map(), X = (e) => {
|
|
89
|
+
let t = $.get(e);
|
|
90
|
+
return t || (t = de(e, i).then((r) => ue(new URL(r.jwks_uri), { [le]: i })).catch((r) => {
|
|
91
|
+
throw $.delete(e), r;
|
|
92
|
+
}), $.set(e, t)), t;
|
|
93
|
+
}, Q = (e, t) => {
|
|
94
|
+
const r = [];
|
|
95
|
+
return h && r.push(`resource_metadata=${w(h.url)}`), e.length && r.push(`scope=${w(e.join(" "))}`), t && r.push(`error=${w(t)}`), r.length ? `Bearer ${r.join(", ")}` : "Bearer";
|
|
96
|
+
}, p = (e, t, r) => new T(401, r ? "invalid_token" : void 0, Q(e, r ? "invalid_token" : void 0), t), D = (e, t = "the token lacks a scope this route needs") => {
|
|
97
|
+
const r = ['error="insufficient_scope"', `scope=${w(e.join(" "))}`];
|
|
98
|
+
return h && r.push(`resource_metadata=${w(h.url)}`), new T(403, "insufficient_scope", `Bearer ${r.join(", ")}`, t);
|
|
99
|
+
}, Z = () => ({
|
|
100
|
+
resource: n,
|
|
101
|
+
authorization_servers: [...a],
|
|
102
|
+
...R.length ? { scopes_supported: [...R] } : {},
|
|
103
|
+
bearer_methods_supported: ["header"],
|
|
104
|
+
...o.resourceName ? { resource_name: o.resourceName } : {},
|
|
105
|
+
...o.resourceDocumentation ? { resource_documentation: o.resourceDocumentation } : {},
|
|
106
|
+
...o.logoUri ? { logo_uri: o.logoUri } : {}
|
|
107
|
+
}), z = o.metadata?.fetch ? he({ ...o.metadata.fetch, issuer: a[0], fetch: i }) : () => Promise.reject(new Error("resource server: no metadata credential")), P = q(async () => {
|
|
108
|
+
const { apiId: e, managementUrl: t } = o.metadata.fetch, r = `${V(t)}/v1/apis/${encodeURIComponent(e)}/resource-metadata`, s = await i(r, { headers: { authorization: `Bearer ${await z()}` } });
|
|
109
|
+
if (!s.ok) throw new Error(`resource metadata fetch failed: ${s.status}`);
|
|
110
|
+
const c = await s.json();
|
|
111
|
+
if (c.resource !== n)
|
|
112
|
+
throw new Error(`resource metadata names ${c.resource}, but this server accepts tokens for ${n}`);
|
|
113
|
+
return c.authorization_servers = [.../* @__PURE__ */ new Set([...c.authorization_servers ?? [], ...a])], c.bearer_methods_supported = ["header"], c;
|
|
114
|
+
}, "resource metadata", l), L = async () => {
|
|
115
|
+
if (!h) throw new Error(`resource server: no metadata for ${n}, which is not an http(s) URL`);
|
|
116
|
+
return o.metadata?.fetch ? P.get() : Z();
|
|
117
|
+
}, N = (e) => {
|
|
118
|
+
const t = /* @__PURE__ */ new Map();
|
|
119
|
+
for (const r of e)
|
|
120
|
+
if (!(typeof r == "string" || !Array.isArray(r.tools)))
|
|
121
|
+
for (const s of r.tools) {
|
|
122
|
+
if (typeof s?.name != "string") continue;
|
|
123
|
+
const c = t.get(s.name) ?? [];
|
|
124
|
+
c.includes(r.key) || c.push(r.key), t.set(s.name, c);
|
|
125
|
+
}
|
|
126
|
+
return t;
|
|
127
|
+
}, j = N(o.scopes ?? []), ee = async () => {
|
|
128
|
+
const { apiId: e, managementUrl: t } = o.metadata.fetch, r = `${V(t)}/v1/apis/${encodeURIComponent(e)}`, s = await i(r, { headers: { authorization: `Bearer ${await z()}` } });
|
|
129
|
+
if (!s.ok) throw new Error(`api fetch failed: ${s.status}`);
|
|
130
|
+
const c = await s.json();
|
|
131
|
+
if (c.identifier !== n)
|
|
132
|
+
throw new Error(`api ${e} is ${String(c.identifier)}, but this server accepts tokens for ${n}`);
|
|
133
|
+
return N(Array.isArray(c.scopes) ? c.scopes : []);
|
|
134
|
+
}, U = j.size === 0 && o.metadata?.fetch ? q(ee, "api scopes", l) : void 0, x = async (e) => [...(U ? await U.get() : j).get(e) ?? []], W = /* @__PURE__ */ new Set(), A = async (e, t) => {
|
|
135
|
+
const r = await x(t);
|
|
136
|
+
if (r.length === 0) {
|
|
137
|
+
if (W.has(t) || (W.add(t), l.warn(
|
|
138
|
+
`[pontive] the tool "${t}" is listed by no scope of ${n}` + (M === "deny" ? "; calls to it are refused until a tool import lists it" : "")
|
|
139
|
+
)), M === "allow") return;
|
|
140
|
+
const s = h ? ` resource_metadata=${w(h.url)}` : "";
|
|
141
|
+
throw new T(403, "insufficient_scope", `Bearer${s}`, `no scope of this API lists the tool "${t}"`);
|
|
142
|
+
}
|
|
143
|
+
if (!r.some((s) => e.scopes.includes(s)))
|
|
144
|
+
throw D(r, `the token holds none of the scopes that list the tool "${t}": ${r.join(", ")}`);
|
|
145
|
+
}, te = async (e, t) => {
|
|
146
|
+
for (const r of Array.isArray(t) ? t : [t]) {
|
|
147
|
+
if (!r || typeof r != "object") continue;
|
|
148
|
+
const { method: s, params: c } = r;
|
|
149
|
+
s === "tools/call" && typeof c?.name == "string" && await A(e, c.name);
|
|
150
|
+
}
|
|
151
|
+
}, re = (e, t) => async (r) => {
|
|
152
|
+
try {
|
|
153
|
+
const s = await I(r, t);
|
|
154
|
+
return await A(s, e), s;
|
|
155
|
+
} catch (s) {
|
|
156
|
+
if (s instanceof T) return s.toResponse();
|
|
157
|
+
throw s;
|
|
158
|
+
}
|
|
159
|
+
}, B = /* @__PURE__ */ new Set(), oe = (e) => {
|
|
160
|
+
const t = /* @__PURE__ */ new Set([...R, ...P.last?.scopes_supported ?? []]);
|
|
161
|
+
if (t.size !== 0)
|
|
162
|
+
for (const r of e)
|
|
163
|
+
t.has(r) || we.has(r) || B.has(r) || (B.add(r), l.warn(
|
|
164
|
+
`[pontive] a verified token for ${n} carries the scope "${r}", which this resource server's configuration does not list`
|
|
165
|
+
));
|
|
166
|
+
}, C = async (e, t) => {
|
|
167
|
+
const r = t?.scopes ?? [];
|
|
168
|
+
let s;
|
|
169
|
+
try {
|
|
170
|
+
s = ce(e);
|
|
171
|
+
} catch {
|
|
172
|
+
throw p(r, "the token is not a JWT", !0);
|
|
173
|
+
}
|
|
174
|
+
const c = typeof s.iss == "string" ? E(s.iss) : void 0;
|
|
175
|
+
if (!c || !a.includes(c)) throw p(r, "the token's issuer is not accepted", !0);
|
|
176
|
+
let u;
|
|
177
|
+
try {
|
|
178
|
+
({ payload: u } = await ie(e, await X(c), {
|
|
179
|
+
issuer: s.iss,
|
|
180
|
+
audience: n,
|
|
181
|
+
clockTolerance: d,
|
|
182
|
+
// An access token (RFC 9068). An ID token is never one, and its
|
|
183
|
+
// audience is the client besides.
|
|
184
|
+
typ: "at+jwt",
|
|
185
|
+
requiredClaims: ["exp", "sub"]
|
|
186
|
+
}));
|
|
187
|
+
} catch (g) {
|
|
188
|
+
const H = g.code;
|
|
189
|
+
throw H && ye.has(H) ? p(r, g.message, !0) : g;
|
|
190
|
+
}
|
|
191
|
+
const k = u.sub, O = me[k.slice(0, k.indexOf("_"))];
|
|
192
|
+
if (!O) throw p(r, "the token's subject is not a user, service account or agent", !0);
|
|
193
|
+
const b = {
|
|
194
|
+
sub: k,
|
|
195
|
+
kind: O,
|
|
196
|
+
clientId: typeof u.client_id == "string" ? u.client_id : typeof u.azp == "string" ? u.azp : "",
|
|
197
|
+
...typeof u.org_id == "string" && u.org_id ? { orgId: u.org_id } : {},
|
|
198
|
+
roles: Y(u.roles),
|
|
199
|
+
permissions: Y(u.permissions),
|
|
200
|
+
scopes: typeof u.scope == "string" ? u.scope.split(" ").filter(Boolean) : [],
|
|
201
|
+
...O === "agent" && typeof u.agent_instance == "string" ? { agentInstance: u.agent_instance } : {},
|
|
202
|
+
token: e,
|
|
203
|
+
claims: u
|
|
204
|
+
}, _ = u.act, v = _ && typeof _.sub == "string" ? _.sub : void 0;
|
|
205
|
+
let f;
|
|
206
|
+
if (v?.startsWith("agt_"))
|
|
207
|
+
f = {
|
|
208
|
+
...b,
|
|
209
|
+
isDelegated: !0,
|
|
210
|
+
actor: {
|
|
211
|
+
sub: v,
|
|
212
|
+
kind: "agent",
|
|
213
|
+
...typeof _.agent_instance == "string" ? { agentInstance: _.agent_instance } : {}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
else if (v?.startsWith("svc_"))
|
|
217
|
+
f = { ...b, isDelegated: !1, actor: { sub: v, kind: "service_account" } };
|
|
218
|
+
else {
|
|
219
|
+
if (v)
|
|
220
|
+
throw p(r, "the token's actor is not an agent or a service account", !0);
|
|
221
|
+
f = { ...b, isDelegated: !1 };
|
|
222
|
+
}
|
|
223
|
+
if (oe(f.scopes), r.some((g) => !f.scopes.includes(g))) throw D(r);
|
|
224
|
+
return f;
|
|
225
|
+
}, I = async (e, t) => {
|
|
226
|
+
const r = ge(e);
|
|
227
|
+
if (!r) throw p(t?.scopes ?? [], "a bearer token is required", !1);
|
|
228
|
+
return C(r, t);
|
|
229
|
+
}, se = (e) => async (t) => {
|
|
230
|
+
try {
|
|
231
|
+
return await I(t, e);
|
|
232
|
+
} catch (r) {
|
|
233
|
+
if (r instanceof T) return r.toResponse();
|
|
234
|
+
throw r;
|
|
235
|
+
}
|
|
236
|
+
}, J = {
|
|
237
|
+
async GET(e) {
|
|
238
|
+
if (!h) return new Response(null, { status: 404 });
|
|
239
|
+
try {
|
|
240
|
+
return Response.json(await L(), {
|
|
241
|
+
headers: { "cache-control": "max-age=300", ...m(e) }
|
|
242
|
+
});
|
|
243
|
+
} catch (t) {
|
|
244
|
+
return l.warn(`[pontive] resource metadata unavailable: ${String(t)}`), Response.json({ error: "temporarily_unavailable" }, { status: 503, headers: m(e) });
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
async OPTIONS(e) {
|
|
248
|
+
return new Response(null, { status: 204, headers: m(e) });
|
|
249
|
+
}
|
|
250
|
+
};
|
|
251
|
+
let y;
|
|
252
|
+
const ae = async () => {
|
|
253
|
+
if (y && Date.now() - y.at < fe) return y.body;
|
|
254
|
+
for (const e of [F, "/.well-known/openid-configuration"]) {
|
|
255
|
+
const t = await i(`${a[0]}${e}`);
|
|
256
|
+
if (t.ok)
|
|
257
|
+
return y = { at: Date.now(), body: await t.text() }, y.body;
|
|
258
|
+
}
|
|
259
|
+
throw new Error(`no authorization server metadata at ${a[0]}`);
|
|
260
|
+
}, G = {
|
|
261
|
+
async GET(e) {
|
|
262
|
+
if (!o.authorizationServerMetadataProxy) return new Response(null, { status: 404 });
|
|
263
|
+
try {
|
|
264
|
+
return new Response(await ae(), {
|
|
265
|
+
headers: { "content-type": "application/json", "cache-control": "max-age=300", ...m(e) }
|
|
266
|
+
});
|
|
267
|
+
} catch (t) {
|
|
268
|
+
return l.warn(`[pontive] authorization server metadata unavailable: ${String(t)}`), Response.json({ error: "temporarily_unavailable" }, { status: 502, headers: m(e) });
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
async OPTIONS(e) {
|
|
272
|
+
return o.authorizationServerMetadataProxy ? new Response(null, { status: 204, headers: m(e) }) : new Response(null, { status: 404 });
|
|
273
|
+
}
|
|
274
|
+
}, K = (e, t) => t.method === "GET" || t.method === "HEAD" ? e.GET(t) : t.method === "OPTIONS" ? e.OPTIONS(t) : Promise.resolve(new Response(null, { status: 405, headers: { allow: "GET, OPTIONS" } })), ne = async (e) => {
|
|
275
|
+
const t = E(new URL(e.url).pathname);
|
|
276
|
+
return h?.paths.includes(t) ? K(J, e) : o.authorizationServerMetadataProxy && t === F ? K(G, e) : null;
|
|
277
|
+
};
|
|
278
|
+
return {
|
|
279
|
+
resource: n,
|
|
280
|
+
issuers: a,
|
|
281
|
+
leewaySeconds: d,
|
|
282
|
+
metadataUrl: h?.url,
|
|
283
|
+
metadataPaths: h?.paths ?? [],
|
|
284
|
+
verify: I,
|
|
285
|
+
verifyToken: C,
|
|
286
|
+
metadata: L,
|
|
287
|
+
requireBearer: se,
|
|
288
|
+
scopesForTool: x,
|
|
289
|
+
authorizeTool: A,
|
|
290
|
+
authorizeToolCalls: te,
|
|
291
|
+
requireTool: re,
|
|
292
|
+
metadataRoute: J,
|
|
293
|
+
authorizationServerMetadataRoute: G,
|
|
294
|
+
handleWellKnown: ne
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
export {
|
|
298
|
+
T as BearerError,
|
|
299
|
+
$e as createResourceServer
|
|
300
|
+
};
|
|
301
|
+
//# sourceMappingURL=resource-server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-server.js","sources":["../src/resource-server.ts"],"sourcesContent":["import {\n createRemoteJWKSet,\n customFetch,\n decodeJwt,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyGetKey,\n} from \"jose\";\n\nimport { managementBase, managementTokenSource, type ManagementCredential } from \"./management-credential\";\nimport { discover } from \"./oidc\";\n\n/**\n * Resource-server middleware: protect an API or an MCP server with tokens a\n * Pontive instance issued for it (pontive-spec 44 §11).\n *\n * `createResourceServer` verifies bearer tokens locally against each issuer's\n * keys, answers a missing or failing token with the `WWW-Authenticate`\n * challenge an MCP client follows, and serves the API's protected resource\n * metadata (RFC 9728). Per request it calls nothing but the cached JWKS.\n *\n * This entry speaks Web `Request`/`Response` (Next route handlers, Hono,\n * Workers, Bun, Deno). `@pontive/server/resource-server/express` and\n * `@pontive/server/resource-server/mcp` adapt it to Express and to the\n * MCP TypeScript SDK.\n */\n\n/** Who a verified token speaks for, told apart by the subject's id prefix. */\nexport type PrincipalKind = \"user\" | \"service_account\" | \"agent\";\n\n/** What every verified principal carries. */\ninterface PrincipalBase {\n /**\n * `usr_…`, `svc_…` or `agt_…`: whom the token speaks for.\n *\n * **For a delegated principal (`isDelegated`) this is the delegator, not the\n * caller.** The caller is the agent in `actor`, and its authority is the\n * intersection of the user's and the agent's, never the user's alone. Do not\n * read or write your own data by `principal.sub` alone for a delegated\n * principal: check by token with the authorization client\n * (`@pontive/server/authorization`), which evaluates the pair, or\n * branch on `principal.isDelegated`.\n */\n sub: string;\n /** From the sub's id prefix; no claim needed. A delegated token's subject is a user, so its kind is `\"user\"`. */\n kind: PrincipalKind;\n /** The client the token was issued to. */\n clientId: string;\n /** The organization the token is scoped to, when it is. */\n orgId?: string;\n /** The token's roles. For a delegated token, already intersected by Pontive (the delegator's roles the agent also holds). */\n roles: string[];\n /** The token's permissions. For a delegated token, already intersected by Pontive. */\n permissions: string[];\n /** The token's granted scopes. */\n scopes: string[];\n /** The agent instance, when the subject itself is an agent. */\n agentInstance?: string;\n /** The raw token, e.g. to check permissions by token. */\n token: string;\n /**\n * Every claim of the verified token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it.\n */\n claims: Record<string, unknown>;\n}\n\n/** Who acts for the subject, from the token's `act` claim (RFC 8693 §4.1). */\nexport interface PrincipalActor {\n /** `agt_…` for an agent acting for its delegator; `svc_…` for an API's backend calling downstream for the user. */\n sub: string;\n kind: \"agent\" | \"service_account\";\n /** The agent's running copy, when it named one. */\n agentInstance?: string;\n}\n\n/**\n * A token an agent holds for its delegator (profile (b), `act.sub` is\n * `agt_…`). `sub` is the user; `actor` is the agent. Its authority is the\n * intersection of both: answer it with a check by token, never by `sub`.\n */\nexport interface DelegatedPrincipal extends PrincipalBase {\n isDelegated: true;\n actor: PrincipalActor & { kind: \"agent\" };\n}\n\n/**\n * Any other token: the subject acts for itself. An `actor` here is a\n * registered API's backend service account calling downstream for the user\n * (profile (a)), a conduit: only the subject is evaluated.\n */\nexport interface UndelegatedPrincipal extends PrincipalBase {\n isDelegated: false;\n actor?: PrincipalActor & { kind: \"service_account\" };\n}\n\n/**\n * The verified caller, as the handler sees it. Narrow on `isDelegated`: a\n * delegated principal's `sub` is the user an agent acts for, and its authority\n * is narrower than that user's.\n */\nexport type Principal = DelegatedPrincipal | UndelegatedPrincipal;\n\n/** The protected resource metadata document (RFC 9728; pontive-spec 44 §9). */\nexport interface ProtectedResourceMetadata {\n resource: string;\n authorization_servers: string[];\n scopes_supported?: string[];\n bearer_methods_supported: string[];\n resource_name?: string;\n resource_documentation?: string;\n logo_uri?: string;\n}\n\n/**\n * How the resource server gets a management API token to read its own\n * metadata: a token, a function returning one, or the client credentials of\n * the API's backend service account (exchanged at the first issuer for a\n * management-audience token, and reused until it is about to expire).\n */\nexport type MetadataCredential = ManagementCredential;\nexport type { ManagementCredential };\n\n/** An MCP tool a scope covers (pontive-spec 44 §5, §12). Only `name` is read here. */\nexport interface ApiScopeTool {\n /** The MCP tool name, as `tools/call` sends it. */\n name: string;\n title?: string;\n read_only?: boolean;\n destructive?: boolean;\n}\n\n/**\n * An API scope as the management API returns it (`GET /v1/apis/{api_id}`,\n * pontive-spec 44 §5), so the dashboard's scopes can be pasted as they are.\n * Only `key` and `tools` are read here.\n */\nexport interface ApiScope {\n key: string;\n description?: string;\n display_name?: string;\n origin?: \"manual\" | \"tool_import\";\n /** The MCP tools the scope covers; a token holding the scope may call each of them (`requireTool`). */\n tools?: ApiScopeTool[];\n}\n\nexport interface ResourceServerConfig {\n /**\n * The instance's issuer: its auth domain, e.g.\n * `https://acme.auth.us.pontive.app`. A list when the instance has more than\n * one auth domain (a custom domain beside the default): a token from any of\n * them is accepted, and each is listed in `authorization_servers`.\n */\n issuer: string | string[];\n /**\n * The API's identifier, exactly as registered. Tokens must carry it in\n * `aud`, and it is the metadata's `resource`. When it is an http(s) URL the\n * metadata is served under its origin (RFC 9728 §3.1).\n */\n resource: string;\n /**\n * The API's scopes, for `scopes_supported`: keys, or the scopes as the\n * management API returns them (`ApiScope`). A scope's `tools` are the MCP\n * tools a token holding it may call (`requireTool`, pontive-spec 44 §12).\n */\n scopes?: (string | ApiScope)[];\n /**\n * What `requireTool` does with a tool no scope lists. `\"deny\"` (the\n * default) refuses it with a `403` that names no scope, since no scope\n * could allow it: a tool added to the server after the last tool import is\n * refused, and logged once, until the import lists it. `\"allow\"` lets any\n * valid token call it.\n */\n unlistedTools?: \"deny\" | \"allow\";\n /** The metadata's `resource_name`. */\n resourceName?: string;\n /** The metadata's `resource_documentation`. */\n resourceDocumentation?: string;\n /** The metadata's `logo_uri`. */\n logoUri?: string;\n /**\n * Read the metadata from Pontive instead of building it from this\n * configuration, for an API whose scopes and display fields are kept in the\n * dashboard. It is fetched on first use and cached for five minutes.\n *\n * When no configured scope lists tools, `requireTool` reads the scopes and\n * their tools from the same API (`GET /v1/apis/{api_id}`, with the\n * same credential and `sys:api:read`), cached the same way.\n */\n metadata?: {\n fetch: {\n /** The API's id (`api_…`). */\n apiId: string;\n /** A credential the management API accepts for `GET /v1/apis/{api_id}/resource-metadata`. */\n credential: MetadataCredential;\n /**\n * The management API's origin in the instance's region, e.g. `https://api.us.pontive.com`.\n * A `/v1`, `/mgmt` or `/mgmt/v1` suffix is dropped (`managementBase`).\n */\n managementUrl: string;\n };\n };\n /**\n * Also serve `/.well-known/oauth-authorization-server`, proxying the\n * issuer's own document, for older MCP clients that ask the resource server\n * for it. Default false.\n */\n authorizationServerMetadataProxy?: boolean;\n /** Clock skew allowed on `exp` and `nbf`. Default 60. */\n leewaySeconds?: number;\n /** Defaults to the global `fetch`. Used for discovery, JWKS and metadata. */\n fetch?: typeof fetch;\n /** Where configuration drift is reported. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\n/** What a route needs of the token beyond its being valid. */\nexport interface BearerOptions {\n /** Every one of these must be granted. */\n scopes?: string[];\n}\n\n/** Anything with request headers: a Web `Request`, `Headers`, or a Node/Express request. */\nexport type RequestLike =\n | Request\n | { headers: Headers | Record<string, string | string[] | undefined> };\n\n/** A route handler pair, e.g. to export from a Next `route.ts`. */\nexport interface RouteHandlers {\n GET(request: Request): Promise<Response>;\n OPTIONS(request: Request): Promise<Response>;\n}\n\n/**\n * Why a request was refused: a `401` (no token, or one that failed) or a\n * `403` (a valid token without a scope the route needs). `toResponse()` is the\n * answer to send.\n */\nexport class BearerError extends Error {\n constructor(\n readonly status: 401 | 403,\n /** Absent when no token was sent (RFC 6750 §3.1). */\n readonly code: \"invalid_token\" | \"insufficient_scope\" | undefined,\n /** The `WWW-Authenticate` header value. */\n readonly wwwAuthenticate: string,\n description: string,\n ) {\n super(description);\n this.name = \"BearerError\";\n }\n\n toResponse(): Response {\n return Response.json(\n { error: this.code ?? \"unauthorized\", error_description: this.message },\n { status: this.status, headers: { \"www-authenticate\": this.wwwAuthenticate, \"cache-control\": \"no-store\" } },\n );\n }\n}\n\nexport interface ResourceServer {\n /** The API identifier tokens must carry in `aud`. */\n readonly resource: string;\n /** The accepted issuers. */\n readonly issuers: readonly string[];\n /** The clock skew allowed on `exp` and `nbf`. */\n readonly leewaySeconds: number;\n /** The metadata's URL, named in every challenge; absent for an identifier that is not an http(s) URL. */\n readonly metadataUrl: string | undefined;\n /** The paths the metadata is served at: the RFC 9728 §3.1 path-suffixed one first. */\n readonly metadataPaths: readonly string[];\n\n /** Verifies the request's bearer token. Throws a `BearerError` when it is missing, fails, or lacks a scope. */\n verify(request: RequestLike, options?: BearerOptions): Promise<Principal>;\n /** Verifies a raw token, as `verify` does. */\n verifyToken(token: string, options?: BearerOptions): Promise<Principal>;\n /** The protected resource metadata document. */\n metadata(): Promise<ProtectedResourceMetadata>;\n /**\n * A guard for Web-standard handlers: the principal, or the `401`/`403`\n * response to return as it is.\n */\n requireBearer(options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /**\n * The scopes that list an MCP tool (pontive-spec 44 §12), from the\n * configured scopes, else from the API in Pontive when `metadata.fetch` is\n * set. Empty for a tool no scope lists.\n */\n scopesForTool(name: string): Promise<string[]>;\n /**\n * Refuses a principal that holds none of the scopes listing the tool: a\n * `BearerError` `403` with `error=\"insufficient_scope\"` and\n * `scope=\"<every scope listing the tool>\"`, any one of which would do. A\n * tool no scope lists follows `unlistedTools`.\n */\n authorizeTool(principal: Principal, name: string): Promise<void>;\n /**\n * `authorizeTool` for every `tools/call` in a JSON-RPC message or batch, as\n * an MCP client posts it; any other message passes. Throws the first refusal.\n * Run it on the parsed body before the MCP transport sees it, so the refusal\n * is an HTTP `403` the client can step up from.\n */\n authorizeToolCalls(principal: Principal, message: unknown): Promise<void>;\n /**\n * A guard for a Web-standard handler that serves one tool: the principal,\n * or the `401`/`403` response to return as it is.\n */\n requireTool(name: string, options?: BearerOptions): (request: Request) => Promise<Principal | Response>;\n\n /** `GET` and `OPTIONS` for the protected resource metadata route. */\n readonly metadataRoute: RouteHandlers;\n /** `GET` and `OPTIONS` for the authorization server metadata proxy (404 unless the proxy is on). */\n readonly authorizationServerMetadataRoute: RouteHandlers;\n /**\n * Answers any of the well-known routes this server serves (both metadata\n * paths, and the AS-metadata proxy when on), or null for any other path. For\n * a catch-all: `return (await rs.handleWellKnown(req)) ?? next()`.\n */\n handleWellKnown(request: Request): Promise<Response | null>;\n}\n\nconst PRM_PATH = \"/.well-known/oauth-protected-resource\";\nconst AS_PATH = \"/.well-known/oauth-authorization-server\";\nconst METADATA_TTL_MS = 5 * 60 * 1000;\nconst AS_METADATA_TTL_MS = 10 * 60 * 1000;\n\n/** OIDC's own scopes, which a token may carry beside the API's. */\nconst OIDC_SCOPES = new Set([\"openid\", \"profile\", \"email\", \"address\", \"phone\", \"offline_access\"]);\n\nconst KINDS: Record<string, PrincipalKind> = { usr: \"user\", svc: \"service_account\", agt: \"agent\" };\n\n/** jose errors that mean the token is bad, rather than that the keys could not be fetched. */\nconst INVALID_TOKEN_CODES = new Set([\n \"ERR_JWT_EXPIRED\",\n \"ERR_JWT_CLAIM_VALIDATION_FAILED\",\n \"ERR_JWT_INVALID\",\n \"ERR_JWS_INVALID\",\n \"ERR_JWS_SIGNATURE_VERIFICATION_FAILED\",\n \"ERR_JWKS_NO_MATCHING_KEY\",\n \"ERR_JWKS_MULTIPLE_MATCHING_KEYS\",\n \"ERR_JOSE_ALG_NOT_ALLOWED\",\n \"ERR_JOSE_NOT_SUPPORTED\",\n]);\n\nconst trimSlash = (value: string) => value.replace(/\\/+$/, \"\");\n\n/** Where the metadata lives for an http(s) identifier (RFC 9728 §3.1); undefined for any other. */\nfunction metadataLocation(resource: string): { url: string; paths: string[] } | undefined {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return undefined;\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return undefined;\n\n const suffix = url.pathname === \"/\" ? \"\" : trimSlash(url.pathname);\n return {\n url: `${url.origin}${PRM_PATH}${suffix}`,\n paths: suffix ? [`${PRM_PATH}${suffix}`, PRM_PATH] : [PRM_PATH],\n };\n}\n\nfunction quote(value: string): string {\n return `\"${value.replace(/[\\\\\"]/g, \"\\\\$&\")}\"`;\n}\n\nfunction stringArray(value: unknown): string[] {\n return Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n}\n\nfunction headerOf(request: RequestLike, name: string): string | undefined {\n const headers = request.headers;\n if (headers instanceof Headers) return headers.get(name) ?? undefined;\n\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** The token from `Authorization: Bearer …`, the only bearer method this server supports. */\nfunction bearerToken(request: RequestLike): string | undefined {\n const match = /^Bearer[ ]+([^ ]+)[ ]*$/i.exec(headerOf(request, \"authorization\") ?? \"\");\n return match?.[1];\n}\n\nconst corsHeaders = (request: Request): Record<string, string> => ({\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-methods\": \"GET, OPTIONS\",\n \"access-control-allow-headers\": request.headers.get(\"access-control-request-headers\") ?? \"*\",\n \"access-control-max-age\": \"86400\",\n});\n\n/**\n * A value fetched on first use and kept for five minutes. A failed refresh\n * keeps the last good value, logged; with none, the failure is thrown. One\n * fetch at a time.\n */\nfunction cachedLoader<T>(load: () => Promise<T>, what: string, logger: Pick<Console, \"warn\">) {\n let fetched: { at: number; value: T } | undefined;\n let fetching: Promise<T> | undefined;\n return {\n get last(): T | undefined {\n return fetched?.value;\n },\n get(): Promise<T> {\n if (fetched && Date.now() - fetched.at < METADATA_TTL_MS) return Promise.resolve(fetched.value);\n fetching ??= load()\n .then((value) => {\n fetched = { at: Date.now(), value };\n return value;\n })\n .catch((err: unknown) => {\n if (fetched) {\n logger.warn(`[pontive] ${what} refresh failed; serving the cached copy: ${String(err)}`);\n return fetched.value;\n }\n throw err;\n })\n .finally(() => {\n fetching = undefined;\n });\n return fetching;\n },\n };\n}\n\nexport function createResourceServer(config: ResourceServerConfig): ResourceServer {\n const issuers = (Array.isArray(config.issuer) ? config.issuer : [config.issuer]).map(trimSlash);\n if (issuers.length === 0 || issuers.some((i) => !i)) throw new Error(\"resource server: issuer is required\");\n if (!config.resource) throw new Error(\"resource server: resource is required\");\n\n const resource = config.resource;\n const fetchImpl = config.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n const logger = config.logger ?? console;\n const leeway = config.leewaySeconds ?? 60;\n const location = metadataLocation(resource);\n const configuredScopes = (config.scopes ?? []).map((s) => (typeof s === \"string\" ? s : s.key));\n const unlistedTools = config.unlistedTools ?? \"deny\";\n\n if (config.metadata?.fetch && !location) {\n throw new Error(\"resource server: metadata is only served for an http(s) resource identifier\");\n }\n\n // One remote key set per issuer: jose caches the keys for ten minutes and\n // refetches on an unknown kid (at most every 30 s), which is how a key\n // rotation is picked up. A failed discovery is not cached.\n const keySets = new Map<string, Promise<JWTVerifyGetKey>>();\n const keySet = (issuer: string): Promise<JWTVerifyGetKey> => {\n let pending = keySets.get(issuer);\n if (!pending) {\n pending = discover(issuer, fetchImpl)\n .then((disc) => createRemoteJWKSet(new URL(disc.jwks_uri), { [customFetch]: fetchImpl }))\n .catch((err: unknown) => {\n keySets.delete(issuer);\n throw err;\n });\n keySets.set(issuer, pending);\n }\n return pending;\n };\n\n const challenge = (scopes: string[], error?: \"invalid_token\"): string => {\n const params: string[] = [];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n if (scopes.length) params.push(`scope=${quote(scopes.join(\" \"))}`);\n if (error) params.push(`error=${quote(error)}`);\n return params.length ? `Bearer ${params.join(\", \")}` : \"Bearer\";\n };\n\n const unauthorized = (scopes: string[], description: string, tokenSent: boolean) =>\n new BearerError(401, tokenSent ? \"invalid_token\" : undefined, challenge(scopes, tokenSent ? \"invalid_token\" : undefined), description);\n\n const insufficientScope = (scopes: string[], description = \"the token lacks a scope this route needs\") => {\n const params = [`error=\"insufficient_scope\"`, `scope=${quote(scopes.join(\" \"))}`];\n if (location) params.push(`resource_metadata=${quote(location.url)}`);\n return new BearerError(403, \"insufficient_scope\", `Bearer ${params.join(\", \")}`, description);\n };\n\n // --- metadata -------------------------------------------------------------\n\n const localMetadata = (): ProtectedResourceMetadata => ({\n resource,\n authorization_servers: [...issuers],\n ...(configuredScopes.length ? { scopes_supported: [...configuredScopes] } : {}),\n bearer_methods_supported: [\"header\"],\n ...(config.resourceName ? { resource_name: config.resourceName } : {}),\n ...(config.resourceDocumentation ? { resource_documentation: config.resourceDocumentation } : {}),\n ...(config.logoUri ? { logo_uri: config.logoUri } : {}),\n });\n\n const credentialToken = config.metadata?.fetch\n ? managementTokenSource({ ...config.metadata.fetch, issuer: issuers[0]!, fetch: fetchImpl })\n : () => Promise.reject(new Error(\"resource server: no metadata credential\"));\n\n const fetchMetadata = async (): Promise<ProtectedResourceMetadata> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}/resource-metadata`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`resource metadata fetch failed: ${res.status}`);\n\n const doc = (await res.json()) as ProtectedResourceMetadata;\n // The metadata must describe the resource whose tokens this server accepts.\n if (doc.resource !== resource) {\n throw new Error(`resource metadata names ${doc.resource}, but this server accepts tokens for ${resource}`);\n }\n // Every issuer this server accepts is an authorization server for it.\n doc.authorization_servers = [...new Set([...(doc.authorization_servers ?? []), ...issuers])];\n doc.bearer_methods_supported = [\"header\"];\n return doc;\n };\n\n const fetchedMetadata = cachedLoader(fetchMetadata, \"resource metadata\", logger);\n\n const metadata = async (): Promise<ProtectedResourceMetadata> => {\n if (!location) throw new Error(`resource server: no metadata for ${resource}, which is not an http(s) URL`);\n if (!config.metadata?.fetch) return localMetadata();\n return fetchedMetadata.get();\n };\n\n // --- tool scopes (44 §12) -----------------------------------------------------\n\n // A tool's scopes: every scope whose `tools` lists it.\n const toolMapOf = (scopes: readonly (string | ApiScope)[]): Map<string, string[]> => {\n const map = new Map<string, string[]>();\n for (const scope of scopes) {\n if (typeof scope === \"string\" || !Array.isArray(scope.tools)) continue;\n for (const tool of scope.tools) {\n if (typeof tool?.name !== \"string\") continue;\n const keys = map.get(tool.name) ?? [];\n if (!keys.includes(scope.key)) keys.push(scope.key);\n map.set(tool.name, keys);\n }\n }\n return map;\n };\n\n const configuredToolMap = toolMapOf(config.scopes ?? []);\n\n const fetchToolMap = async (): Promise<Map<string, string[]>> => {\n const { apiId, managementUrl } = config.metadata!.fetch;\n const url = `${managementBase(managementUrl)}/v1/apis/${encodeURIComponent(apiId)}`;\n const res = await fetchImpl(url, { headers: { authorization: `Bearer ${await credentialToken()}` } });\n if (!res.ok) throw new Error(`api fetch failed: ${res.status}`);\n\n const api = (await res.json()) as { identifier?: string; scopes?: ApiScope[] };\n if (api.identifier !== resource) {\n throw new Error(`api ${apiId} is ${String(api.identifier)}, but this server accepts tokens for ${resource}`);\n }\n return toolMapOf(Array.isArray(api.scopes) ? api.scopes : []);\n };\n\n // Configured tools win; the API in Pontive is read only when none are configured.\n const fetchedToolMap =\n configuredToolMap.size === 0 && config.metadata?.fetch ? cachedLoader(fetchToolMap, \"api scopes\", logger) : undefined;\n\n const scopesForTool = async (name: string): Promise<string[]> => {\n const map = fetchedToolMap ? await fetchedToolMap.get() : configuredToolMap;\n return [...(map.get(name) ?? [])];\n };\n\n const warnedTools = new Set<string>();\n const authorizeTool = async (principal: Principal, name: string): Promise<void> => {\n const scopes = await scopesForTool(name);\n if (scopes.length === 0) {\n if (!warnedTools.has(name)) {\n warnedTools.add(name);\n logger.warn(\n `[pontive] the tool \"${name}\" is listed by no scope of ${resource}` +\n (unlistedTools === \"deny\" ? \"; calls to it are refused until a tool import lists it\" : \"\"),\n );\n }\n if (unlistedTools === \"allow\") return;\n // No scope could allow it, so the challenge names none and asks for no step-up.\n const params = location ? ` resource_metadata=${quote(location.url)}` : \"\";\n throw new BearerError(403, \"insufficient_scope\", `Bearer${params}`, `no scope of this API lists the tool \"${name}\"`);\n }\n if (scopes.some((scope) => principal.scopes.includes(scope))) return;\n throw insufficientScope(scopes, `the token holds none of the scopes that list the tool \"${name}\": ${scopes.join(\", \")}`);\n };\n\n const authorizeToolCalls = async (principal: Principal, message: unknown): Promise<void> => {\n for (const m of Array.isArray(message) ? message : [message]) {\n if (!m || typeof m !== \"object\") continue;\n const { method, params } = m as { method?: unknown; params?: { name?: unknown } };\n // A call without a name is the SDK's to refuse, as invalid params.\n if (method === \"tools/call\" && typeof params?.name === \"string\") await authorizeTool(principal, params.name);\n }\n };\n\n const requireTool = (name: string, options?: BearerOptions) => async (request: Request) => {\n try {\n const principal = await verify(request, options);\n await authorizeTool(principal, name);\n return principal;\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- scope drift ------------------------------------------------------------\n\n const warned = new Set<string>();\n const warnUnknownScopes = (scopes: string[]) => {\n const known = new Set([...configuredScopes, ...(fetchedMetadata.last?.scopes_supported ?? [])]);\n // Nothing declared, nothing to drift from.\n if (known.size === 0) return;\n\n for (const scope of scopes) {\n if (known.has(scope) || OIDC_SCOPES.has(scope) || warned.has(scope)) continue;\n warned.add(scope);\n logger.warn(\n `[pontive] a verified token for ${resource} carries the scope \"${scope}\", which this resource server's configuration does not list`,\n );\n }\n };\n\n // --- verification -----------------------------------------------------------\n\n const verifyToken = async (token: string, options?: BearerOptions): Promise<Principal> => {\n const required = options?.scopes ?? [];\n\n let unverified: JWTPayload;\n try {\n unverified = decodeJwt(token);\n } catch {\n throw unauthorized(required, \"the token is not a JWT\", true);\n }\n\n const issuer = typeof unverified.iss === \"string\" ? trimSlash(unverified.iss) : undefined;\n if (!issuer || !issuers.includes(issuer)) throw unauthorized(required, \"the token's issuer is not accepted\", true);\n\n let payload: JWTPayload;\n try {\n ({ payload } = await jwtVerify(token, await keySet(issuer), {\n issuer: unverified.iss as string,\n audience: resource,\n clockTolerance: leeway,\n // An access token (RFC 9068). An ID token is never one, and its\n // audience is the client besides.\n typ: \"at+jwt\",\n requiredClaims: [\"exp\", \"sub\"],\n }));\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code && INVALID_TOKEN_CODES.has(code)) throw unauthorized(required, (err as Error).message, true);\n throw err;\n }\n\n const sub = payload.sub!;\n const kind = KINDS[sub.slice(0, sub.indexOf(\"_\"))];\n if (!kind) throw unauthorized(required, \"the token's subject is not a user, service account or agent\", true);\n\n const base = {\n sub,\n kind,\n clientId: typeof payload.client_id === \"string\" ? payload.client_id : typeof payload.azp === \"string\" ? payload.azp : \"\",\n ...(typeof payload.org_id === \"string\" && payload.org_id ? { orgId: payload.org_id } : {}),\n roles: stringArray(payload.roles),\n permissions: stringArray(payload.permissions),\n scopes: typeof payload.scope === \"string\" ? payload.scope.split(\" \").filter(Boolean) : [],\n ...(kind === \"agent\" && typeof payload.agent_instance === \"string\"\n ? { agentInstance: payload.agent_instance }\n : {}),\n token,\n claims: payload,\n };\n\n const act = payload.act as { sub?: unknown; agent_instance?: unknown } | undefined;\n const actorSub = act && typeof act.sub === \"string\" ? act.sub : undefined;\n let principal: Principal;\n if (actorSub?.startsWith(\"agt_\")) {\n principal = {\n ...base,\n isDelegated: true,\n actor: {\n sub: actorSub,\n kind: \"agent\",\n ...(typeof act!.agent_instance === \"string\" ? { agentInstance: act!.agent_instance } : {}),\n },\n };\n } else if (actorSub?.startsWith(\"svc_\")) {\n principal = { ...base, isDelegated: false, actor: { sub: actorSub, kind: \"service_account\" } };\n } else if (actorSub) {\n // An act this server does not know how to evaluate: refuse it rather\n // than let the subject's authority stand for an unknown caller.\n throw unauthorized(required, \"the token's actor is not an agent or a service account\", true);\n } else {\n principal = { ...base, isDelegated: false };\n }\n\n warnUnknownScopes(principal.scopes);\n\n if (required.some((scope) => !principal.scopes.includes(scope))) throw insufficientScope(required);\n\n return principal;\n };\n\n const verify = async (request: RequestLike, options?: BearerOptions): Promise<Principal> => {\n const token = bearerToken(request);\n if (!token) throw unauthorized(options?.scopes ?? [], \"a bearer token is required\", false);\n return verifyToken(token, options);\n };\n\n const requireBearer = (options?: BearerOptions) => async (request: Request) => {\n try {\n return await verify(request, options);\n } catch (err) {\n if (err instanceof BearerError) return err.toResponse();\n throw err;\n }\n };\n\n // --- well-known routes ------------------------------------------------------\n\n const metadataRoute: RouteHandlers = {\n async GET(request) {\n if (!location) return new Response(null, { status: 404 });\n try {\n return Response.json(await metadata(), {\n headers: { \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] resource metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 503, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n let asMetadata: { at: number; body: string } | undefined;\n const authorizationServerMetadata = async (): Promise<string> => {\n if (asMetadata && Date.now() - asMetadata.at < AS_METADATA_TTL_MS) return asMetadata.body;\n\n // RFC 8414's document, or the OIDC discovery document, which is a superset.\n for (const path of [AS_PATH, \"/.well-known/openid-configuration\"]) {\n const res = await fetchImpl(`${issuers[0]}${path}`);\n if (res.ok) {\n asMetadata = { at: Date.now(), body: await res.text() };\n return asMetadata.body;\n }\n }\n throw new Error(`no authorization server metadata at ${issuers[0]}`);\n };\n\n const authorizationServerMetadataRoute: RouteHandlers = {\n async GET(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n try {\n return new Response(await authorizationServerMetadata(), {\n headers: { \"content-type\": \"application/json\", \"cache-control\": \"max-age=300\", ...corsHeaders(request) },\n });\n } catch (err) {\n logger.warn(`[pontive] authorization server metadata unavailable: ${String(err)}`);\n return Response.json({ error: \"temporarily_unavailable\" }, { status: 502, headers: corsHeaders(request) });\n }\n },\n async OPTIONS(request) {\n if (!config.authorizationServerMetadataProxy) return new Response(null, { status: 404 });\n return new Response(null, { status: 204, headers: corsHeaders(request) });\n },\n };\n\n const route = (handlers: RouteHandlers, request: Request): Promise<Response> => {\n if (request.method === \"GET\" || request.method === \"HEAD\") return handlers.GET(request);\n if (request.method === \"OPTIONS\") return handlers.OPTIONS(request);\n return Promise.resolve(new Response(null, { status: 405, headers: { allow: \"GET, OPTIONS\" } }));\n };\n\n const handleWellKnown = async (request: Request): Promise<Response | null> => {\n const path = trimSlash(new URL(request.url).pathname);\n if (location?.paths.includes(path)) return route(metadataRoute, request);\n if (config.authorizationServerMetadataProxy && path === AS_PATH) {\n return route(authorizationServerMetadataRoute, request);\n }\n return null;\n };\n\n return {\n resource,\n issuers,\n leewaySeconds: leeway,\n metadataUrl: location?.url,\n metadataPaths: location?.paths ?? [],\n verify,\n verifyToken,\n metadata,\n requireBearer,\n scopesForTool,\n authorizeTool,\n authorizeToolCalls,\n requireTool,\n metadataRoute,\n authorizationServerMetadataRoute,\n handleWellKnown,\n };\n}\n"],"names":["BearerError","status","code","wwwAuthenticate","description","PRM_PATH","AS_PATH","METADATA_TTL_MS","AS_METADATA_TTL_MS","OIDC_SCOPES","KINDS","INVALID_TOKEN_CODES","trimSlash","value","metadataLocation","resource","url","suffix","quote","stringArray","v","headerOf","request","name","headers","bearerToken","corsHeaders","cachedLoader","load","what","logger","fetched","fetching","err","createResourceServer","config","issuers","i","fetchImpl","args","leeway","location","configuredScopes","s","unlistedTools","keySets","keySet","issuer","pending","discover","disc","createRemoteJWKSet","customFetch","challenge","scopes","error","params","unauthorized","tokenSent","insufficientScope","localMetadata","credentialToken","managementTokenSource","fetchedMetadata","apiId","managementUrl","managementBase","res","doc","metadata","toolMapOf","map","scope","tool","keys","configuredToolMap","fetchToolMap","api","fetchedToolMap","scopesForTool","warnedTools","authorizeTool","principal","authorizeToolCalls","message","m","method","requireTool","options","verify","warned","warnUnknownScopes","known","verifyToken","token","required","unverified","decodeJwt","payload","jwtVerify","sub","kind","base","act","actorSub","requireBearer","metadataRoute","asMetadata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I,IAAIU,EAAQ,GAAG,EAAE,QAAQ;AACpD,WAAImB,GAAU,MAAM,SAASoE,CAAI,IAAUE,EAAML,GAAepF,CAAO,IACnEa,EAAO,oCAAoC0E,MAASvG,IAC/CyG,EAAMD,GAAkCxF,CAAO,IAEjD;AAAA,EACT;AAEA,SAAO;AAAA,IACL,UAAAP;AAAA,IACA,SAAAqB;AAAA,IACA,eAAeI;AAAA,IACf,aAAaC,GAAU;AAAA,IACvB,eAAeA,GAAU,SAAS,CAAA;AAAA,IAClC,QAAAgD;AAAA,IACA,aAAAI;AAAA,IACA,UAAAxB;AAAA,IACA,eAAAoC;AAAA,IACA,eAAA1B;AAAA,IACA,eAAAE;AAAA,IACA,oBAAAE;AAAA,IACA,aAAAI;AAAA,IACA,eAAAmB;AAAA,IACA,kCAAAI;AAAA,IACA,iBAAAG;AAAA,EAAA;AAEJ;"}
|
package/dist/seal.d.cts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function seal(payload: Record<string, unknown>, secret: string, maxAgeSeconds: number): Promise<string>;
|
|
2
|
+
/** The payload, or null when the value is not one this secret sealed, or has expired. */
|
|
3
|
+
export declare function unseal<T>(value: string, secret: string): Promise<T | null>;
|
package/dist/seal.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export declare function seal(payload: Record<string, unknown>, secret: string, maxAgeSeconds: number): Promise<string>;
|
|
2
|
+
/** The payload, or null when the value is not one this secret sealed, or has expired. */
|
|
3
|
+
export declare function unseal<T>(value: string, secret: string): Promise<T | null>;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { ResolvedConfig } from './config.cjs';
|
|
2
|
+
import { Organization } from './organization.cjs';
|
|
3
|
+
export interface SessionUser {
|
|
4
|
+
id: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
username?: string;
|
|
8
|
+
picture?: string;
|
|
9
|
+
emailVerified: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** What `getSession` hands the app. */
|
|
12
|
+
export interface Session {
|
|
13
|
+
user: SessionUser;
|
|
14
|
+
/** A valid access token, for calling APIs as this user. */
|
|
15
|
+
accessToken: string;
|
|
16
|
+
/** When the access token expires, epoch milliseconds. */
|
|
17
|
+
expiresAt: number;
|
|
18
|
+
/** The issuer's session id (`sid`), when it sent one. */
|
|
19
|
+
sessionId?: string;
|
|
20
|
+
/**
|
|
21
|
+
* The organization the session acts in, or null for none: every B2C
|
|
22
|
+
* session, and a B2B one whose app has not picked an organization. Move it
|
|
23
|
+
* with the `switch-organization` route (`switchOrganizationPath`).
|
|
24
|
+
*/
|
|
25
|
+
organization: Organization | null;
|
|
26
|
+
/**
|
|
27
|
+
* Every claim of the access token: the claims template's (say
|
|
28
|
+
* `legacy_user_id`) beside the standard ones the fields above are read
|
|
29
|
+
* from. A claim is whatever the issuer wrote, so check its type before
|
|
30
|
+
* using it:
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const legacyId = typeof session.claims.legacy_user_id === "string" ? session.claims.legacy_user_id : undefined;
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
claims: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
/** What a refresh produced, for the middleware to apply. */
|
|
39
|
+
export interface RefreshOutcome {
|
|
40
|
+
/** The session after the refresh, or null when there is none (or it could not be refreshed). */
|
|
41
|
+
session: Session | null;
|
|
42
|
+
/** `Set-Cookie` values for the response. Empty when nothing changed. */
|
|
43
|
+
setCookies: string[];
|
|
44
|
+
/**
|
|
45
|
+
* The request's `Cookie` header as it should be seen by whatever handles
|
|
46
|
+
* this request next, carrying the refreshed session. Forward it, so a page
|
|
47
|
+
* rendered on this very request reads the new token rather than the expired
|
|
48
|
+
* one the browser sent.
|
|
49
|
+
*/
|
|
50
|
+
cookieHeader: string;
|
|
51
|
+
/**
|
|
52
|
+
* Set when a signed-in browser's access token has lapsed and it must go
|
|
53
|
+
* through the auth server's session handshake to renew it — browser mode
|
|
54
|
+
* only. A path on this app's origin. Send a page navigation there; any other
|
|
55
|
+
* request just proceeds without a session.
|
|
56
|
+
*/
|
|
57
|
+
handshake?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface ServerAuth {
|
|
60
|
+
/**
|
|
61
|
+
* Handles the SDK's routes under `basePath`: `/login`, `/callback` and
|
|
62
|
+
* `/logout`. Null for any other path.
|
|
63
|
+
*/
|
|
64
|
+
handle(request: Request): Promise<Response | null>;
|
|
65
|
+
/**
|
|
66
|
+
* The session in a `Cookie` header, or null. Read-only and never refreshes:
|
|
67
|
+
* any server code can call it, including code that cannot set cookies.
|
|
68
|
+
* Returns null for a session whose access token has expired — `refresh`,
|
|
69
|
+
* run in middleware ahead of the request, is what keeps it current.
|
|
70
|
+
*/
|
|
71
|
+
getSession(cookieHeader: string | null | undefined): Promise<Session | null>;
|
|
72
|
+
/**
|
|
73
|
+
* Refreshes the session when its access token is about to expire. For
|
|
74
|
+
* middleware: it runs before anything renders, and its response can always
|
|
75
|
+
* carry the new cookie. Concurrent calls for one session share one refresh.
|
|
76
|
+
*/
|
|
77
|
+
refresh(request: Request): Promise<RefreshOutcome>;
|
|
78
|
+
/**
|
|
79
|
+
* What the app's `<Provider>` needs, from the server: the app's id (so no
|
|
80
|
+
* `NEXT_PUBLIC_` copy of it is needed), the auth domain, and, while the
|
|
81
|
+
* instance is an unclaimed one this project created (keyless mode), the
|
|
82
|
+
* claim route for the development banner's *Claim it*. Render the provider
|
|
83
|
+
* with them from server code.
|
|
84
|
+
*/
|
|
85
|
+
providerProps(): Promise<ProviderProps>;
|
|
86
|
+
}
|
|
87
|
+
/** `<Provider>`'s inputs the server knows (`appId`, `domain`, `claimUrl`). */
|
|
88
|
+
export interface ProviderProps {
|
|
89
|
+
appId: string;
|
|
90
|
+
/** The issuer (confidential mode), or the auth proxy's path on this origin (browser mode). */
|
|
91
|
+
domain: string;
|
|
92
|
+
/** `{basePath}/claim`, only while this project's keyless instance is unclaimed. */
|
|
93
|
+
claimUrl?: string;
|
|
94
|
+
}
|
|
95
|
+
/** The `type` of the message a sign-in popup sends its opener: `@pontive/oidc-client`'s `POPUP_MESSAGE_TYPE`. */
|
|
96
|
+
export declare const POPUP_MESSAGE_TYPE = "pontive:popup-complete";
|
|
97
|
+
/** What both modes do; `createServerAuth` adds the provider's props and keyless mode's claim route. */
|
|
98
|
+
export type CoreAuth = Omit<ServerAuth, "providerProps">;
|
|
99
|
+
/** The auth for a resolved config: the confidential mode's, or the browser SDK's. */
|
|
100
|
+
export declare function createCoreAuth(cfg: ResolvedConfig): CoreAuth;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { ResolvedConfig } from './config.js';
|
|
2
|
+
import { Organization } from './organization.js';
|
|
3
|
+
export interface SessionUser {
|
|
4
|
+
id: string;
|
|
5
|
+
email?: string;
|
|
6
|
+
name?: string;
|
|
7
|
+
username?: string;
|
|
8
|
+
picture?: string;
|
|
9
|
+
emailVerified: boolean;
|
|
10
|
+
}
|
|
11
|
+
/** What `getSession` hands the app. */
|
|
12
|
+
export interface Session {
|
|
13
|
+
user: SessionUser;
|
|
14
|
+
/** A valid access token, for calling APIs as this user. */
|
|
15
|
+
accessToken: string;
|
|
16
|
+
/** When the access token expires, epoch milliseconds. */
|
|
17
|
+
expiresAt: number;
|
|
18
|
+
/** The issuer's session id (`sid`), when it sent one. */
|
|
19
|
+
sessionId?: string;
|
|
20
|
+
/**
|
|
21
|
+
* The organization the session acts in, or null for none: every B2C
|
|
22
|
+
* session, and a B2B one whose app has not picked an organization. Move it
|
|
23
|
+
* with the `switch-organization` route (`switchOrganizationPath`).
|
|
24
|
+
*/
|
|
25
|
+
organization: Organization | null;
|
|
26
|
+
/**
|
|
27
|
+
* Every claim of the access token: the claims template's (say
|
|
28
|
+
* `legacy_user_id`) beside the standard ones the fields above are read
|
|
29
|
+
* from. A claim is whatever the issuer wrote, so check its type before
|
|
30
|
+
* using it:
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* const legacyId = typeof session.claims.legacy_user_id === "string" ? session.claims.legacy_user_id : undefined;
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
claims: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
/** What a refresh produced, for the middleware to apply. */
|
|
39
|
+
export interface RefreshOutcome {
|
|
40
|
+
/** The session after the refresh, or null when there is none (or it could not be refreshed). */
|
|
41
|
+
session: Session | null;
|
|
42
|
+
/** `Set-Cookie` values for the response. Empty when nothing changed. */
|
|
43
|
+
setCookies: string[];
|
|
44
|
+
/**
|
|
45
|
+
* The request's `Cookie` header as it should be seen by whatever handles
|
|
46
|
+
* this request next, carrying the refreshed session. Forward it, so a page
|
|
47
|
+
* rendered on this very request reads the new token rather than the expired
|
|
48
|
+
* one the browser sent.
|
|
49
|
+
*/
|
|
50
|
+
cookieHeader: string;
|
|
51
|
+
/**
|
|
52
|
+
* Set when a signed-in browser's access token has lapsed and it must go
|
|
53
|
+
* through the auth server's session handshake to renew it — browser mode
|
|
54
|
+
* only. A path on this app's origin. Send a page navigation there; any other
|
|
55
|
+
* request just proceeds without a session.
|
|
56
|
+
*/
|
|
57
|
+
handshake?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface ServerAuth {
|
|
60
|
+
/**
|
|
61
|
+
* Handles the SDK's routes under `basePath`: `/login`, `/callback` and
|
|
62
|
+
* `/logout`. Null for any other path.
|
|
63
|
+
*/
|
|
64
|
+
handle(request: Request): Promise<Response | null>;
|
|
65
|
+
/**
|
|
66
|
+
* The session in a `Cookie` header, or null. Read-only and never refreshes:
|
|
67
|
+
* any server code can call it, including code that cannot set cookies.
|
|
68
|
+
* Returns null for a session whose access token has expired — `refresh`,
|
|
69
|
+
* run in middleware ahead of the request, is what keeps it current.
|
|
70
|
+
*/
|
|
71
|
+
getSession(cookieHeader: string | null | undefined): Promise<Session | null>;
|
|
72
|
+
/**
|
|
73
|
+
* Refreshes the session when its access token is about to expire. For
|
|
74
|
+
* middleware: it runs before anything renders, and its response can always
|
|
75
|
+
* carry the new cookie. Concurrent calls for one session share one refresh.
|
|
76
|
+
*/
|
|
77
|
+
refresh(request: Request): Promise<RefreshOutcome>;
|
|
78
|
+
/**
|
|
79
|
+
* What the app's `<Provider>` needs, from the server: the app's id (so no
|
|
80
|
+
* `NEXT_PUBLIC_` copy of it is needed), the auth domain, and, while the
|
|
81
|
+
* instance is an unclaimed one this project created (keyless mode), the
|
|
82
|
+
* claim route for the development banner's *Claim it*. Render the provider
|
|
83
|
+
* with them from server code.
|
|
84
|
+
*/
|
|
85
|
+
providerProps(): Promise<ProviderProps>;
|
|
86
|
+
}
|
|
87
|
+
/** `<Provider>`'s inputs the server knows (`appId`, `domain`, `claimUrl`). */
|
|
88
|
+
export interface ProviderProps {
|
|
89
|
+
appId: string;
|
|
90
|
+
/** The issuer (confidential mode), or the auth proxy's path on this origin (browser mode). */
|
|
91
|
+
domain: string;
|
|
92
|
+
/** `{basePath}/claim`, only while this project's keyless instance is unclaimed. */
|
|
93
|
+
claimUrl?: string;
|
|
94
|
+
}
|
|
95
|
+
/** The `type` of the message a sign-in popup sends its opener: `@pontive/oidc-client`'s `POPUP_MESSAGE_TYPE`. */
|
|
96
|
+
export declare const POPUP_MESSAGE_TYPE = "pontive:popup-complete";
|
|
97
|
+
/** What both modes do; `createServerAuth` adds the provider's props and keyless mode's claim route. */
|
|
98
|
+
export type CoreAuth = Omit<ServerAuth, "providerProps">;
|
|
99
|
+
/** The auth for a resolved config: the confidential mode's, or the browser SDK's. */
|
|
100
|
+
export declare function createCoreAuth(cfg: ResolvedConfig): CoreAuth;
|