@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.
Files changed (76) hide show
  1. package/README.md +146 -2
  2. package/dist/auth.d.cts +34 -0
  3. package/dist/auth.d.ts +34 -0
  4. package/dist/authorization.cjs +2 -0
  5. package/dist/authorization.cjs.map +1 -0
  6. package/dist/authorization.d.cts +222 -0
  7. package/dist/authorization.d.ts +222 -0
  8. package/dist/authorization.js +153 -0
  9. package/dist/authorization.js.map +1 -0
  10. package/dist/browser-mode.d.cts +23 -0
  11. package/dist/browser-mode.d.ts +23 -0
  12. package/dist/config.d.cts +131 -0
  13. package/dist/config.d.ts +131 -0
  14. package/dist/cookies.d.cts +50 -0
  15. package/dist/cookies.d.ts +50 -0
  16. package/dist/env.d.cts +44 -0
  17. package/dist/env.d.ts +44 -0
  18. package/dist/index.cjs +5 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +20 -0
  21. package/dist/index.d.ts +20 -0
  22. package/dist/index.js +700 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/keyless.cjs +16 -0
  25. package/dist/keyless.cjs.map +1 -0
  26. package/dist/keyless.d.cts +244 -0
  27. package/dist/keyless.d.ts +244 -0
  28. package/dist/keyless.js +355 -0
  29. package/dist/keyless.js.map +1 -0
  30. package/dist/management-credential-BNyhHagG.cjs +2 -0
  31. package/dist/management-credential-BNyhHagG.cjs.map +1 -0
  32. package/dist/management-credential-VhmMzGDl.js +39 -0
  33. package/dist/management-credential-VhmMzGDl.js.map +1 -0
  34. package/dist/management-credential.d.cts +40 -0
  35. package/dist/management-credential.d.ts +40 -0
  36. package/dist/mcp-auth-info-BGyWua_9.js +19 -0
  37. package/dist/mcp-auth-info-BGyWua_9.js.map +1 -0
  38. package/dist/mcp-auth-info-jblMsSJo.cjs +2 -0
  39. package/dist/mcp-auth-info-jblMsSJo.cjs.map +1 -0
  40. package/dist/mcp-auth-info.d.cts +17 -0
  41. package/dist/mcp-auth-info.d.ts +17 -0
  42. package/dist/oidc--We55Nrh.cjs +2 -0
  43. package/dist/oidc--We55Nrh.cjs.map +1 -0
  44. package/dist/oidc-CB0FqjFz.js +131 -0
  45. package/dist/oidc-CB0FqjFz.js.map +1 -0
  46. package/dist/oidc.d.cts +80 -0
  47. package/dist/oidc.d.ts +80 -0
  48. package/dist/organization.d.cts +35 -0
  49. package/dist/organization.d.ts +35 -0
  50. package/dist/preview-hosts.d.cts +33 -0
  51. package/dist/preview-hosts.d.ts +33 -0
  52. package/dist/refresh.d.cts +28 -0
  53. package/dist/refresh.d.ts +28 -0
  54. package/dist/resource-server-express.cjs +2 -0
  55. package/dist/resource-server-express.cjs.map +1 -0
  56. package/dist/resource-server-express.d.cts +73 -0
  57. package/dist/resource-server-express.d.ts +73 -0
  58. package/dist/resource-server-express.js +57 -0
  59. package/dist/resource-server-express.js.map +1 -0
  60. package/dist/resource-server-mcp.cjs +2 -0
  61. package/dist/resource-server-mcp.cjs.map +1 -0
  62. package/dist/resource-server-mcp.d.cts +70 -0
  63. package/dist/resource-server-mcp.d.ts +70 -0
  64. package/dist/resource-server-mcp.js +59 -0
  65. package/dist/resource-server-mcp.js.map +1 -0
  66. package/dist/resource-server.cjs +2 -0
  67. package/dist/resource-server.cjs.map +1 -0
  68. package/dist/resource-server.d.cts +290 -0
  69. package/dist/resource-server.d.ts +290 -0
  70. package/dist/resource-server.js +301 -0
  71. package/dist/resource-server.js.map +1 -0
  72. package/dist/seal.d.cts +3 -0
  73. package/dist/seal.d.ts +3 -0
  74. package/dist/server-auth.d.cts +100 -0
  75. package/dist/server-auth.d.ts +100 -0
  76. package/package.json +96 -4
@@ -0,0 +1,17 @@
1
+ import { Principal, ResourceServer } from './resource-server.cjs';
2
+ /**
3
+ * The MCP TypeScript SDK's `AuthInfo`, structurally, so the adapters that set
4
+ * it (Express's `req.auth`) need not import the SDK.
5
+ */
6
+ export interface McpAuthInfo {
7
+ token: string;
8
+ clientId: string;
9
+ scopes: string[];
10
+ /** Seconds since the epoch. */
11
+ expiresAt?: number;
12
+ resource?: URL;
13
+ extra?: Record<string, unknown>;
14
+ }
15
+ /** Where the principal goes in `AuthInfo.extra`. */
16
+ export declare const PRINCIPAL_KEY = "principal";
17
+ export declare function toMcpAuthInfo(rs: ResourceServer, principal: Principal): McpAuthInfo;
@@ -0,0 +1,17 @@
1
+ import { Principal, ResourceServer } from './resource-server.js';
2
+ /**
3
+ * The MCP TypeScript SDK's `AuthInfo`, structurally, so the adapters that set
4
+ * it (Express's `req.auth`) need not import the SDK.
5
+ */
6
+ export interface McpAuthInfo {
7
+ token: string;
8
+ clientId: string;
9
+ scopes: string[];
10
+ /** Seconds since the epoch. */
11
+ expiresAt?: number;
12
+ resource?: URL;
13
+ extra?: Record<string, unknown>;
14
+ }
15
+ /** Where the principal goes in `AuthInfo.extra`. */
16
+ export declare const PRINCIPAL_KEY = "principal";
17
+ export declare function toMcpAuthInfo(rs: ResourceServer, principal: Principal): McpAuthInfo;
@@ -0,0 +1,2 @@
1
+ "use strict";const u=require("jose");class g extends Error{constructor(n,e,o){super(`token endpoint ${n} ${e}: ${o}`),this.status=n,this.code=e}status;code}const k=600*1e3,d=new Map,f=new Map;function m(t){return t.replace(/\/+$/,"")}function a(t,n){const e=m(t);let o=d.get(e);return o||(o=n(`${e}/.well-known/openid-configuration`).then(async r=>{if(!r.ok)throw new Error(`OIDC discovery failed for ${e}: ${r.status}`);return await r.json()}).catch(r=>{throw d.delete(e),r}),d.set(e,o)),o}async function _(t,n,e){const o=f.get(t);if(o&&!e&&Date.now()-o.at<k)return o.set;const r=await n(t);if(!r.ok)throw new Error(`JWKS fetch failed for ${t}: ${r.status}`);const s=u.createLocalJWKSet(await r.json());return f.set(t,{at:Date.now(),set:s}),s}function y(t){let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function S(){return y(crypto.getRandomValues(new Uint8Array(32)))}async function P(t){const n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return y(new Uint8Array(n))}async function U(t){return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)))].map(e=>e.toString(16).padStart(2,"0")).join("")}async function $(t,n,e){const o=await a(t.issuer,n),r=new URL(o.authorization_endpoint);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",t.clientId),r.searchParams.set("redirect_uri",e.redirectUri),r.searchParams.set("scope",e.scopes),r.searchParams.set("state",e.state),r.searchParams.set("nonce",e.nonce),r.searchParams.set("code_challenge",e.codeChallenge),r.searchParams.set("code_challenge_method","S256"),e.prompt&&r.searchParams.set("prompt",e.prompt),e.organizationId&&r.searchParams.set("organization_id",e.organizationId),e.loginHint&&r.searchParams.set("login_hint",e.loginHint),r.toString()}async function l(t,n,e){const o=await a(t.issuer,n),r=new URLSearchParams(e);r.set("client_id",t.clientId);const s={"content-type":"application/x-www-form-urlencoded"};if(t.clientSecret){const i=`${encodeURIComponent(t.clientId)}:${encodeURIComponent(t.clientSecret)}`;s.authorization=`Basic ${btoa(i)}`}const c=await n(o.token_endpoint,{method:"POST",headers:s,body:r});if(!c.ok){let i="unknown_error",w="";try{const h=await c.json();i=h.error??i,w=h.error_description??""}catch{}throw new g(c.status,i,w)}return await c.json()}function C(t,n,e){return l(t,n,{grant_type:"authorization_code",code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri})}function T(t,n,e,o){return l(t,n,{grant_type:"refresh_token",refresh_token:e,...o?{organization_id:o}:{}})}function j(t,n,e){return l(t,n,{grant_type:"client_credentials",...e})}async function p(t,n,e){const o=await a(t.issuer,n),r={issuer:o.issuer,audience:t.clientId};try{return(await u.jwtVerify(e,await _(o.jwks_uri,n,!1),r)).payload}catch(s){if(s.code!=="ERR_JWKS_NO_MATCHING_KEY")throw s;return(await u.jwtVerify(e,await _(o.jwks_uri,n,!0),r)).payload}}async function E(t,n,e,o){const r=await p(t,n,e);if(r.nonce!==o)throw new Error("id_token nonce does not match the sign-in request");return r}async function I(t,n,e){const o=await a(t.issuer,n);if(!o.userinfo_endpoint)return null;const r=await n(o.userinfo_endpoint,{headers:{authorization:`Bearer ${e}`}});if(!r.ok)throw new Error(`userinfo ${r.status}`);return await r.json()}async function R(t,n,e){const o=await a(t.issuer,n);if(!o.end_session_endpoint)return null;const r=new URL(o.end_session_endpoint);return r.searchParams.set("client_id",t.clientId),r.searchParams.set("post_logout_redirect_uri",e.postLogoutRedirectUri),e.sessionId&&r.searchParams.set("logout_hint",e.sessionId),r.toString()}exports.TokenEndpointError=g;exports.authorizationUrl=$;exports.clientCredentialsToken=j;exports.discover=a;exports.endSessionUrl=R;exports.exchangeCode=C;exports.pkceChallenge=P;exports.randomValue=S;exports.refreshTokens=T;exports.sha256Hex=U;exports.userInfo=I;exports.verifyIdToken=E;exports.verifyJwt=p;
2
+ //# sourceMappingURL=oidc--We55Nrh.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc--We55Nrh.cjs","sources":["../src/oidc.ts"],"sourcesContent":["import { createLocalJWKSet, jwtVerify, type JSONWebKeySet, type JWTPayload } from \"jose\";\n\n/**\n * The OIDC relying-party calls: discovery, PKCE, the two token grants and\n * id_token verification. Standard OIDC only, so any compliant issuer works.\n */\n\nexport interface Discovery {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n jwks_uri: string;\n userinfo_endpoint?: string;\n end_session_endpoint?: string;\n}\n\nexport interface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n id_token?: string;\n scope?: string;\n}\n\nexport interface ClientCredentials {\n issuer: string;\n clientId: string;\n clientSecret?: string;\n}\n\n/** An error from the token endpoint, carrying its OAuth code. */\nexport class TokenEndpointError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n description: string,\n ) {\n super(`token endpoint ${status} ${code}: ${description}`);\n }\n}\n\ntype Fetch = typeof fetch;\n\nconst JWKS_TTL_MS = 10 * 60 * 1000;\n\nconst discoveries = new Map<string, Promise<Discovery>>();\nconst jwksCache = new Map<string, { at: number; set: ReturnType<typeof createLocalJWKSet> }>();\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nexport function discover(issuer: string, fetchImpl: Fetch): Promise<Discovery> {\n const key = trimSlash(issuer);\n let pending = discoveries.get(key);\n\n if (!pending) {\n pending = fetchImpl(`${key}/.well-known/openid-configuration`)\n .then(async (res) => {\n if (!res.ok) throw new Error(`OIDC discovery failed for ${key}: ${res.status}`);\n return (await res.json()) as Discovery;\n })\n .catch((err: unknown) => {\n // A failure is not cached: the next request retries.\n discoveries.delete(key);\n throw err;\n });\n discoveries.set(key, pending);\n }\n\n return pending;\n}\n\nasync function jwks(uri: string, fetchImpl: Fetch, force: boolean): Promise<ReturnType<typeof createLocalJWKSet>> {\n const cached = jwksCache.get(uri);\n if (cached && !force && Date.now() - cached.at < JWKS_TTL_MS) return cached.set;\n\n const res = await fetchImpl(uri);\n if (!res.ok) throw new Error(`JWKS fetch failed for ${uri}: ${res.status}`);\n\n const set = createLocalJWKSet((await res.json()) as JSONWebKeySet);\n jwksCache.set(uri, { at: Date.now(), set });\n\n return set;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** A random, URL-safe value for state, nonce and the PKCE verifier. */\nexport function randomValue(): string {\n return base64url(crypto.getRandomValues(new Uint8Array(32)));\n}\n\nexport async function pkceChallenge(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\n return base64url(new Uint8Array(digest));\n}\n\n/** Hex SHA-256, for keying state by a secret without holding the secret. */\nexport async function sha256Hex(value: string): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value)));\n\n return [...digest].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function authorizationUrl(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: {\n redirectUri: string;\n scopes: string;\n state: string;\n nonce: string;\n codeChallenge: string;\n prompt?: string;\n organizationId?: string;\n loginHint?: string;\n },\n): Promise<string> {\n const disc = await discover(client.issuer, fetchImpl);\n const url = new URL(disc.authorization_endpoint);\n\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", client.clientId);\n url.searchParams.set(\"redirect_uri\", input.redirectUri);\n url.searchParams.set(\"scope\", input.scopes);\n url.searchParams.set(\"state\", input.state);\n url.searchParams.set(\"nonce\", input.nonce);\n url.searchParams.set(\"code_challenge\", input.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n if (input.prompt) url.searchParams.set(\"prompt\", input.prompt);\n if (input.organizationId) url.searchParams.set(\"organization_id\", input.organizationId);\n if (input.loginHint) url.searchParams.set(\"login_hint\", input.loginHint);\n\n return url.toString();\n}\n\n/**\n * A token-endpoint call. A confidential client authenticates with HTTP Basic\n * (RFC 6749 §2.3.1); `client_id` is always in the form too, which a public\n * client needs and a confidential one is allowed.\n */\nasync function tokenRequest(\n client: ClientCredentials,\n fetchImpl: Fetch,\n params: Record<string, string>,\n): Promise<TokenResponse> {\n const disc = await discover(client.issuer, fetchImpl);\n const body = new URLSearchParams(params);\n body.set(\"client_id\", client.clientId);\n\n const headers: Record<string, string> = { \"content-type\": \"application/x-www-form-urlencoded\" };\n if (client.clientSecret) {\n const credentials = `${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`;\n headers.authorization = `Basic ${btoa(credentials)}`;\n }\n\n const res = await fetchImpl(disc.token_endpoint, { method: \"POST\", headers, body });\n if (!res.ok) {\n let code = \"unknown_error\";\n let description = \"\";\n\n try {\n const err = (await res.json()) as { error?: string; error_description?: string };\n code = err.error ?? code;\n description = err.error_description ?? \"\";\n } catch {\n // Not JSON; the status says enough.\n }\n\n throw new TokenEndpointError(res.status, code, description);\n }\n\n return (await res.json()) as TokenResponse;\n}\n\nexport function exchangeCode(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: { code: string; codeVerifier: string; redirectUri: string },\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, {\n grant_type: \"authorization_code\",\n code: input.code,\n code_verifier: input.codeVerifier,\n redirect_uri: input.redirectUri,\n });\n}\n\nexport function refreshTokens(\n client: ClientCredentials,\n fetchImpl: Fetch,\n refreshToken: string,\n organizationId?: string,\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, {\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n // Switches the session to that organization; see switchOrganization.\n ...(organizationId ? { organization_id: organizationId } : {}),\n });\n}\n\n/** A client_credentials grant, e.g. with `resource` naming the API the token is for (RFC 8707). */\nexport function clientCredentialsToken(\n client: ClientCredentials,\n fetchImpl: Fetch,\n params: Record<string, string>,\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, { grant_type: \"client_credentials\", ...params });\n}\n\n/**\n * Verifies a JWT the issuer signed for this app: signature, issuer, audience\n * and expiry. A key the cached set does not know refetches the set once, which\n * is how a key rotation at the issuer is picked up without waiting out the\n * cache.\n */\nexport async function verifyJwt(client: ClientCredentials, fetchImpl: Fetch, token: string): Promise<JWTPayload> {\n const disc = await discover(client.issuer, fetchImpl);\n const options = { issuer: disc.issuer, audience: client.clientId };\n\n try {\n return (await jwtVerify(token, await jwks(disc.jwks_uri, fetchImpl, false), options)).payload;\n } catch (err) {\n if ((err as { code?: string }).code !== \"ERR_JWKS_NO_MATCHING_KEY\") throw err;\n return (await jwtVerify(token, await jwks(disc.jwks_uri, fetchImpl, true), options)).payload;\n }\n}\n\n/** Verifies an id_token as verifyJwt does, plus the nonce of the sign-in it answers. */\nexport async function verifyIdToken(\n client: ClientCredentials,\n fetchImpl: Fetch,\n idToken: string,\n nonce: string,\n): Promise<JWTPayload> {\n const payload = await verifyJwt(client, fetchImpl, idToken);\n if (payload.nonce !== nonce) throw new Error(\"id_token nonce does not match the sign-in request\");\n\n return payload;\n}\n\n/**\n * The user's profile claims (OIDC Core §5.3), for an access token that carries\n * none of its own. Null when the issuer offers no userinfo endpoint; throws\n * when it refuses.\n */\nexport async function userInfo(\n client: ClientCredentials,\n fetchImpl: Fetch,\n accessToken: string,\n): Promise<Record<string, unknown> | null> {\n const disc = await discover(client.issuer, fetchImpl);\n if (!disc.userinfo_endpoint) return null;\n\n const res = await fetchImpl(disc.userinfo_endpoint, { headers: { authorization: `Bearer ${accessToken}` } });\n if (!res.ok) throw new Error(`userinfo ${res.status}`);\n\n return (await res.json()) as Record<string, unknown>;\n}\n\n/** RP-initiated logout (OIDC RP-Initiated Logout 1.0), or null when the issuer offers none. */\nexport async function endSessionUrl(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: { postLogoutRedirectUri: string; sessionId?: string },\n): Promise<string | null> {\n const disc = await discover(client.issuer, fetchImpl);\n if (!disc.end_session_endpoint) return null;\n\n const url = new URL(disc.end_session_endpoint);\n url.searchParams.set(\"client_id\", client.clientId);\n url.searchParams.set(\"post_logout_redirect_uri\", input.postLogoutRedirectUri);\n // logout_hint is what lets the issuer end its session without asking \"Sign\n // out?\": only an app holding tokens from that session knows the sid.\n if (input.sessionId) url.searchParams.set(\"logout_hint\", input.sessionId);\n\n return url.toString();\n}\n\n/** For tests: forget cached discovery documents and key sets. */\nexport function resetOidcCaches(): void {\n discoveries.clear();\n jwksCache.clear();\n}\n"],"names":["TokenEndpointError","status","code","description","JWKS_TTL_MS","discoveries","jwksCache","trimSlash","value","discover","issuer","fetchImpl","key","pending","res","err","jwks","uri","force","cached","set","createLocalJWKSet","base64url","bytes","binary","b","randomValue","pkceChallenge","verifier","digest","sha256Hex","authorizationUrl","client","input","disc","url","tokenRequest","params","body","headers","credentials","exchangeCode","refreshTokens","refreshToken","organizationId","clientCredentialsToken","verifyJwt","token","options","jwtVerify","verifyIdToken","idToken","nonce","payload","userInfo","accessTo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AAQrB,CAAS,EACpD,GAAI,CAACuB,EAAK,qBAAsB,OAAO,KAEvC,MAAMC,EAAM,IAAI,IAAID,EAAK,oBAAoB,EAC7C,OAAAC,EAAI,aAAa,IAAI,YAAaH,EAAO,QAAQ,EACjDG,EAAI,aAAa,IAAI,2BAA4BF,EAAM,qBAAqB,EAGxEA,EAAM,WAAWE,EAAI,aAAa,IAAI,cAAeF,EAAM,SAAS,EAEjEE,EAAI,SAAA,CACb"}
@@ -0,0 +1,131 @@
1
+ import { jwtVerify as l, createLocalJWKSet as p } from "jose";
2
+ class y extends Error {
3
+ constructor(n, e, s) {
4
+ super(`token endpoint ${n} ${e}: ${s}`), this.status = n, this.code = e;
5
+ }
6
+ status;
7
+ code;
8
+ }
9
+ const m = 600 * 1e3, d = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map();
10
+ function k(t) {
11
+ return t.replace(/\/+$/, "");
12
+ }
13
+ function i(t, n) {
14
+ const e = k(t);
15
+ let s = d.get(e);
16
+ return s || (s = n(`${e}/.well-known/openid-configuration`).then(async (r) => {
17
+ if (!r.ok) throw new Error(`OIDC discovery failed for ${e}: ${r.status}`);
18
+ return await r.json();
19
+ }).catch((r) => {
20
+ throw d.delete(e), r;
21
+ }), d.set(e, s)), s;
22
+ }
23
+ async function _(t, n, e) {
24
+ const s = h.get(t);
25
+ if (s && !e && Date.now() - s.at < m) return s.set;
26
+ const r = await n(t);
27
+ if (!r.ok) throw new Error(`JWKS fetch failed for ${t}: ${r.status}`);
28
+ const o = p(await r.json());
29
+ return h.set(t, { at: Date.now(), set: o }), o;
30
+ }
31
+ function g(t) {
32
+ let n = "";
33
+ for (const e of t) n += String.fromCharCode(e);
34
+ return btoa(n).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
35
+ }
36
+ function $() {
37
+ return g(crypto.getRandomValues(new Uint8Array(32)));
38
+ }
39
+ async function U(t) {
40
+ const n = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t));
41
+ return g(new Uint8Array(n));
42
+ }
43
+ async function j(t) {
44
+ return [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(t)))].map((e) => e.toString(16).padStart(2, "0")).join("");
45
+ }
46
+ async function C(t, n, e) {
47
+ const s = await i(t.issuer, n), r = new URL(s.authorization_endpoint);
48
+ return r.searchParams.set("response_type", "code"), r.searchParams.set("client_id", t.clientId), r.searchParams.set("redirect_uri", e.redirectUri), r.searchParams.set("scope", e.scopes), r.searchParams.set("state", e.state), r.searchParams.set("nonce", e.nonce), r.searchParams.set("code_challenge", e.codeChallenge), r.searchParams.set("code_challenge_method", "S256"), e.prompt && r.searchParams.set("prompt", e.prompt), e.organizationId && r.searchParams.set("organization_id", e.organizationId), e.loginHint && r.searchParams.set("login_hint", e.loginHint), r.toString();
49
+ }
50
+ async function u(t, n, e) {
51
+ const s = await i(t.issuer, n), r = new URLSearchParams(e);
52
+ r.set("client_id", t.clientId);
53
+ const o = { "content-type": "application/x-www-form-urlencoded" };
54
+ if (t.clientSecret) {
55
+ const a = `${encodeURIComponent(t.clientId)}:${encodeURIComponent(t.clientSecret)}`;
56
+ o.authorization = `Basic ${btoa(a)}`;
57
+ }
58
+ const c = await n(s.token_endpoint, { method: "POST", headers: o, body: r });
59
+ if (!c.ok) {
60
+ let a = "unknown_error", w = "";
61
+ try {
62
+ const f = await c.json();
63
+ a = f.error ?? a, w = f.error_description ?? "";
64
+ } catch {
65
+ }
66
+ throw new y(c.status, a, w);
67
+ }
68
+ return await c.json();
69
+ }
70
+ function E(t, n, e) {
71
+ return u(t, n, {
72
+ grant_type: "authorization_code",
73
+ code: e.code,
74
+ code_verifier: e.codeVerifier,
75
+ redirect_uri: e.redirectUri
76
+ });
77
+ }
78
+ function T(t, n, e, s) {
79
+ return u(t, n, {
80
+ grant_type: "refresh_token",
81
+ refresh_token: e,
82
+ // Switches the session to that organization; see switchOrganization.
83
+ ...s ? { organization_id: s } : {}
84
+ });
85
+ }
86
+ function I(t, n, e) {
87
+ return u(t, n, { grant_type: "client_credentials", ...e });
88
+ }
89
+ async function S(t, n, e) {
90
+ const s = await i(t.issuer, n), r = { issuer: s.issuer, audience: t.clientId };
91
+ try {
92
+ return (await l(e, await _(s.jwks_uri, n, !1), r)).payload;
93
+ } catch (o) {
94
+ if (o.code !== "ERR_JWKS_NO_MATCHING_KEY") throw o;
95
+ return (await l(e, await _(s.jwks_uri, n, !0), r)).payload;
96
+ }
97
+ }
98
+ async function R(t, n, e, s) {
99
+ const r = await S(t, n, e);
100
+ if (r.nonce !== s) throw new Error("id_token nonce does not match the sign-in request");
101
+ return r;
102
+ }
103
+ async function b(t, n, e) {
104
+ const s = await i(t.issuer, n);
105
+ if (!s.userinfo_endpoint) return null;
106
+ const r = await n(s.userinfo_endpoint, { headers: { authorization: `Bearer ${e}` } });
107
+ if (!r.ok) throw new Error(`userinfo ${r.status}`);
108
+ return await r.json();
109
+ }
110
+ async function z(t, n, e) {
111
+ const s = await i(t.issuer, n);
112
+ if (!s.end_session_endpoint) return null;
113
+ const r = new URL(s.end_session_endpoint);
114
+ return r.searchParams.set("client_id", t.clientId), r.searchParams.set("post_logout_redirect_uri", e.postLogoutRedirectUri), e.sessionId && r.searchParams.set("logout_hint", e.sessionId), r.toString();
115
+ }
116
+ export {
117
+ y as T,
118
+ $ as a,
119
+ C as b,
120
+ R as c,
121
+ z as d,
122
+ E as e,
123
+ i as f,
124
+ I as g,
125
+ U as p,
126
+ T as r,
127
+ j as s,
128
+ b as u,
129
+ S as v
130
+ };
131
+ //# sourceMappingURL=oidc-CB0FqjFz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oidc-CB0FqjFz.js","sources":["../src/oidc.ts"],"sourcesContent":["import { createLocalJWKSet, jwtVerify, type JSONWebKeySet, type JWTPayload } from \"jose\";\n\n/**\n * The OIDC relying-party calls: discovery, PKCE, the two token grants and\n * id_token verification. Standard OIDC only, so any compliant issuer works.\n */\n\nexport interface Discovery {\n issuer: string;\n authorization_endpoint: string;\n token_endpoint: string;\n jwks_uri: string;\n userinfo_endpoint?: string;\n end_session_endpoint?: string;\n}\n\nexport interface TokenResponse {\n access_token: string;\n token_type: string;\n expires_in?: number;\n refresh_token?: string;\n id_token?: string;\n scope?: string;\n}\n\nexport interface ClientCredentials {\n issuer: string;\n clientId: string;\n clientSecret?: string;\n}\n\n/** An error from the token endpoint, carrying its OAuth code. */\nexport class TokenEndpointError extends Error {\n constructor(\n readonly status: number,\n readonly code: string,\n description: string,\n ) {\n super(`token endpoint ${status} ${code}: ${description}`);\n }\n}\n\ntype Fetch = typeof fetch;\n\nconst JWKS_TTL_MS = 10 * 60 * 1000;\n\nconst discoveries = new Map<string, Promise<Discovery>>();\nconst jwksCache = new Map<string, { at: number; set: ReturnType<typeof createLocalJWKSet> }>();\n\nfunction trimSlash(value: string): string {\n return value.replace(/\\/+$/, \"\");\n}\n\nexport function discover(issuer: string, fetchImpl: Fetch): Promise<Discovery> {\n const key = trimSlash(issuer);\n let pending = discoveries.get(key);\n\n if (!pending) {\n pending = fetchImpl(`${key}/.well-known/openid-configuration`)\n .then(async (res) => {\n if (!res.ok) throw new Error(`OIDC discovery failed for ${key}: ${res.status}`);\n return (await res.json()) as Discovery;\n })\n .catch((err: unknown) => {\n // A failure is not cached: the next request retries.\n discoveries.delete(key);\n throw err;\n });\n discoveries.set(key, pending);\n }\n\n return pending;\n}\n\nasync function jwks(uri: string, fetchImpl: Fetch, force: boolean): Promise<ReturnType<typeof createLocalJWKSet>> {\n const cached = jwksCache.get(uri);\n if (cached && !force && Date.now() - cached.at < JWKS_TTL_MS) return cached.set;\n\n const res = await fetchImpl(uri);\n if (!res.ok) throw new Error(`JWKS fetch failed for ${uri}: ${res.status}`);\n\n const set = createLocalJWKSet((await res.json()) as JSONWebKeySet);\n jwksCache.set(uri, { at: Date.now(), set });\n\n return set;\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** A random, URL-safe value for state, nonce and the PKCE verifier. */\nexport function randomValue(): string {\n return base64url(crypto.getRandomValues(new Uint8Array(32)));\n}\n\nexport async function pkceChallenge(verifier: string): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\n return base64url(new Uint8Array(digest));\n}\n\n/** Hex SHA-256, for keying state by a secret without holding the secret. */\nexport async function sha256Hex(value: string): Promise<string> {\n const digest = new Uint8Array(await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(value)));\n\n return [...digest].map((b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nexport async function authorizationUrl(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: {\n redirectUri: string;\n scopes: string;\n state: string;\n nonce: string;\n codeChallenge: string;\n prompt?: string;\n organizationId?: string;\n loginHint?: string;\n },\n): Promise<string> {\n const disc = await discover(client.issuer, fetchImpl);\n const url = new URL(disc.authorization_endpoint);\n\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"client_id\", client.clientId);\n url.searchParams.set(\"redirect_uri\", input.redirectUri);\n url.searchParams.set(\"scope\", input.scopes);\n url.searchParams.set(\"state\", input.state);\n url.searchParams.set(\"nonce\", input.nonce);\n url.searchParams.set(\"code_challenge\", input.codeChallenge);\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n if (input.prompt) url.searchParams.set(\"prompt\", input.prompt);\n if (input.organizationId) url.searchParams.set(\"organization_id\", input.organizationId);\n if (input.loginHint) url.searchParams.set(\"login_hint\", input.loginHint);\n\n return url.toString();\n}\n\n/**\n * A token-endpoint call. A confidential client authenticates with HTTP Basic\n * (RFC 6749 §2.3.1); `client_id` is always in the form too, which a public\n * client needs and a confidential one is allowed.\n */\nasync function tokenRequest(\n client: ClientCredentials,\n fetchImpl: Fetch,\n params: Record<string, string>,\n): Promise<TokenResponse> {\n const disc = await discover(client.issuer, fetchImpl);\n const body = new URLSearchParams(params);\n body.set(\"client_id\", client.clientId);\n\n const headers: Record<string, string> = { \"content-type\": \"application/x-www-form-urlencoded\" };\n if (client.clientSecret) {\n const credentials = `${encodeURIComponent(client.clientId)}:${encodeURIComponent(client.clientSecret)}`;\n headers.authorization = `Basic ${btoa(credentials)}`;\n }\n\n const res = await fetchImpl(disc.token_endpoint, { method: \"POST\", headers, body });\n if (!res.ok) {\n let code = \"unknown_error\";\n let description = \"\";\n\n try {\n const err = (await res.json()) as { error?: string; error_description?: string };\n code = err.error ?? code;\n description = err.error_description ?? \"\";\n } catch {\n // Not JSON; the status says enough.\n }\n\n throw new TokenEndpointError(res.status, code, description);\n }\n\n return (await res.json()) as TokenResponse;\n}\n\nexport function exchangeCode(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: { code: string; codeVerifier: string; redirectUri: string },\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, {\n grant_type: \"authorization_code\",\n code: input.code,\n code_verifier: input.codeVerifier,\n redirect_uri: input.redirectUri,\n });\n}\n\nexport function refreshTokens(\n client: ClientCredentials,\n fetchImpl: Fetch,\n refreshToken: string,\n organizationId?: string,\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, {\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n // Switches the session to that organization; see switchOrganization.\n ...(organizationId ? { organization_id: organizationId } : {}),\n });\n}\n\n/** A client_credentials grant, e.g. with `resource` naming the API the token is for (RFC 8707). */\nexport function clientCredentialsToken(\n client: ClientCredentials,\n fetchImpl: Fetch,\n params: Record<string, string>,\n): Promise<TokenResponse> {\n return tokenRequest(client, fetchImpl, { grant_type: \"client_credentials\", ...params });\n}\n\n/**\n * Verifies a JWT the issuer signed for this app: signature, issuer, audience\n * and expiry. A key the cached set does not know refetches the set once, which\n * is how a key rotation at the issuer is picked up without waiting out the\n * cache.\n */\nexport async function verifyJwt(client: ClientCredentials, fetchImpl: Fetch, token: string): Promise<JWTPayload> {\n const disc = await discover(client.issuer, fetchImpl);\n const options = { issuer: disc.issuer, audience: client.clientId };\n\n try {\n return (await jwtVerify(token, await jwks(disc.jwks_uri, fetchImpl, false), options)).payload;\n } catch (err) {\n if ((err as { code?: string }).code !== \"ERR_JWKS_NO_MATCHING_KEY\") throw err;\n return (await jwtVerify(token, await jwks(disc.jwks_uri, fetchImpl, true), options)).payload;\n }\n}\n\n/** Verifies an id_token as verifyJwt does, plus the nonce of the sign-in it answers. */\nexport async function verifyIdToken(\n client: ClientCredentials,\n fetchImpl: Fetch,\n idToken: string,\n nonce: string,\n): Promise<JWTPayload> {\n const payload = await verifyJwt(client, fetchImpl, idToken);\n if (payload.nonce !== nonce) throw new Error(\"id_token nonce does not match the sign-in request\");\n\n return payload;\n}\n\n/**\n * The user's profile claims (OIDC Core §5.3), for an access token that carries\n * none of its own. Null when the issuer offers no userinfo endpoint; throws\n * when it refuses.\n */\nexport async function userInfo(\n client: ClientCredentials,\n fetchImpl: Fetch,\n accessToken: string,\n): Promise<Record<string, unknown> | null> {\n const disc = await discover(client.issuer, fetchImpl);\n if (!disc.userinfo_endpoint) return null;\n\n const res = await fetchImpl(disc.userinfo_endpoint, { headers: { authorization: `Bearer ${accessToken}` } });\n if (!res.ok) throw new Error(`userinfo ${res.status}`);\n\n return (await res.json()) as Record<string, unknown>;\n}\n\n/** RP-initiated logout (OIDC RP-Initiated Logout 1.0), or null when the issuer offers none. */\nexport async function endSessionUrl(\n client: ClientCredentials,\n fetchImpl: Fetch,\n input: { postLogoutRedirectUri: string; sessionId?: string },\n): Promise<string | null> {\n const disc = await discover(client.issuer, fetchImpl);\n if (!disc.end_session_endpoint) return null;\n\n const url = new URL(disc.end_session_endpoint);\n url.searchParams.set(\"client_id\", client.clientId);\n url.searchParams.set(\"post_logout_redirect_uri\", input.postLogoutRedirectUri);\n // logout_hint is what lets the issuer end its session without asking \"Sign\n // out?\": only an app holding tokens from that session knows the sid.\n if (input.sessionId) url.searchParams.set(\"logout_hint\", input.sessionId);\n\n return url.toString();\n}\n\n/** For tests: forget cached discovery documents and key sets. */\nexport function resetOidcCaches(): void {\n discoveries.clear();\n jwksCache.clear();\n}\n"],"names":["TokenEndpointError","status","code","description","JWKS_TTL_MS","discoveries","jwksCache","trimSlash","value","discover","issuer","fetchImpl","key","pending","res","err","jwks","uri","force","cached","set","createLocalJWKSet","base64url","bytes","binary","b","randomValue","pkceChallenge","verifier","digest","sha256Hex","authorizationUrl","client","input","disc","url","tokenRequest","params","body","headers","credentials","exchangeCode","refreshTokens","refreshToken","organizationId","clientCredentialsToken","verifyJwt","token","options","jwtVerify","verifyIdToken","idToken","nonce","payload","userInfo","accessToken","endSessionUrl"],"mappings":";AAgCO,MAAMA,UAA2B,MAAM;AAAA,EAC5C,YACWC,GACAC,GACTC,GACA;AACA,UAAM,kBAAkBF,CAAM,IAAIC,CAAI,KAAKC,CAAW,EAAE,GAJ/C,KAAA,SAAAF,GACA,KAAA,OAAAC;AAAA,EAIX;AAAA,EALW;AAAA,EACA;AAKb;AAIA,MAAME,IAAc,MAAU,KAExBC,wBAAkB,IAAA,GAClBC,wBAAgB,IAAA;AAEtB,SAASC,EAAUC,GAAuB;AACxC,SAAOA,EAAM,QAAQ,QAAQ,EAAE;AACjC;AAEO,SAASC,EAASC,GAAgBC,GAAsC;AAC7E,QAAMC,IAAML,EAAUG,CAAM;AAC5B,MAAIG,IAAUR,EAAY,IAAIO,CAAG;AAEjC,SAAKC,MACHA,IAAUF,EAAU,GAAGC,CAAG,mCAAmC,EAC1D,KAAK,OAAOE,MAAQ;AACnB,QAAI,CAACA,EAAI,GAAI,OAAM,IAAI,MAAM,6BAA6BF,CAAG,KAAKE,EAAI,MAAM,EAAE;AAC9E,WAAQ,MAAMA,EAAI,KAAA;AAAA,EACpB,CAAC,EACA,MAAM,CAACC,MAAiB;AAEvB,UAAAV,EAAY,OAAOO,CAAG,GAChBG;AAAA,EACR,CAAC,GACHV,EAAY,IAAIO,GAAKC,CAAO,IAGvBA;AACT;AAEA,eAAeG,EA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,EAAUd,GAAQrB,GAAWwC,CAAO;AAC1D,MAAIE,EAAQ,UAAUD,EAAO,OAAM,IAAI,MAAM,mDAAmD;AAEhG,SAAOC;AACT;AAOA,eAAsBC,EACpBtB,GACArB,GACA4C,GACyC;AACzC,QAAMrB,IAAO,MAAMzB,EAASuB,EAAO,QAAQrB,CAAS;AACpD,MAAI,CAACuB,EAAK,kBAAmB,QAAO;AAEpC,QAAMpB,IAAM,MAAMH,EAAUuB,EAAK,mBAAmB,EAAE,SAAS,EAAE,eAAe,UAAUqB,CAAW,GAAA,GAAM;AAC3G,MAAI,CAACzC,EAAI,GAAI,OAAM,IAAI,MAAM,YAAYA,EAAI,MAAM,EAAE;AAErD,SAAQ,MAAMA,EAAI,KAAA;AACpB;AAGA,eAAsB0C,EACpBxB,GACArB,GACAsB,GACwB;AACxB,QAAMC,IAAO,MAAMzB,EAASuB,EAAO,QAAQrB,CAAS;AACpD,MAAI,CAACuB,EAAK,qBAAsB,QAAO;AAEvC,QAAMC,IAAM,IAAI,IAAID,EAAK,oBAAoB;AAC7C,SAAAC,EAAI,aAAa,IAAI,aAAaH,EAAO,QAAQ,GACjDG,EAAI,aAAa,IAAI,4BAA4BF,EAAM,qBAAqB,GAGxEA,EAAM,aAAWE,EAAI,aAAa,IAAI,eAAeF,EAAM,SAAS,GAEjEE,EAAI,SAAA;AACb;"}
@@ -0,0 +1,80 @@
1
+ import { JWTPayload } from 'jose';
2
+ /**
3
+ * The OIDC relying-party calls: discovery, PKCE, the two token grants and
4
+ * id_token verification. Standard OIDC only, so any compliant issuer works.
5
+ */
6
+ export interface Discovery {
7
+ issuer: string;
8
+ authorization_endpoint: string;
9
+ token_endpoint: string;
10
+ jwks_uri: string;
11
+ userinfo_endpoint?: string;
12
+ end_session_endpoint?: string;
13
+ }
14
+ export interface TokenResponse {
15
+ access_token: string;
16
+ token_type: string;
17
+ expires_in?: number;
18
+ refresh_token?: string;
19
+ id_token?: string;
20
+ scope?: string;
21
+ }
22
+ export interface ClientCredentials {
23
+ issuer: string;
24
+ clientId: string;
25
+ clientSecret?: string;
26
+ }
27
+ /** An error from the token endpoint, carrying its OAuth code. */
28
+ export declare class TokenEndpointError extends Error {
29
+ readonly status: number;
30
+ readonly code: string;
31
+ constructor(status: number, code: string, description: string);
32
+ }
33
+ type Fetch = typeof fetch;
34
+ export declare function discover(issuer: string, fetchImpl: Fetch): Promise<Discovery>;
35
+ /** A random, URL-safe value for state, nonce and the PKCE verifier. */
36
+ export declare function randomValue(): string;
37
+ export declare function pkceChallenge(verifier: string): Promise<string>;
38
+ /** Hex SHA-256, for keying state by a secret without holding the secret. */
39
+ export declare function sha256Hex(value: string): Promise<string>;
40
+ export declare function authorizationUrl(client: ClientCredentials, fetchImpl: Fetch, input: {
41
+ redirectUri: string;
42
+ scopes: string;
43
+ state: string;
44
+ nonce: string;
45
+ codeChallenge: string;
46
+ prompt?: string;
47
+ organizationId?: string;
48
+ loginHint?: string;
49
+ }): Promise<string>;
50
+ export declare function exchangeCode(client: ClientCredentials, fetchImpl: Fetch, input: {
51
+ code: string;
52
+ codeVerifier: string;
53
+ redirectUri: string;
54
+ }): Promise<TokenResponse>;
55
+ export declare function refreshTokens(client: ClientCredentials, fetchImpl: Fetch, refreshToken: string, organizationId?: string): Promise<TokenResponse>;
56
+ /** A client_credentials grant, e.g. with `resource` naming the API the token is for (RFC 8707). */
57
+ export declare function clientCredentialsToken(client: ClientCredentials, fetchImpl: Fetch, params: Record<string, string>): Promise<TokenResponse>;
58
+ /**
59
+ * Verifies a JWT the issuer signed for this app: signature, issuer, audience
60
+ * and expiry. A key the cached set does not know refetches the set once, which
61
+ * is how a key rotation at the issuer is picked up without waiting out the
62
+ * cache.
63
+ */
64
+ export declare function verifyJwt(client: ClientCredentials, fetchImpl: Fetch, token: string): Promise<JWTPayload>;
65
+ /** Verifies an id_token as verifyJwt does, plus the nonce of the sign-in it answers. */
66
+ export declare function verifyIdToken(client: ClientCredentials, fetchImpl: Fetch, idToken: string, nonce: string): Promise<JWTPayload>;
67
+ /**
68
+ * The user's profile claims (OIDC Core §5.3), for an access token that carries
69
+ * none of its own. Null when the issuer offers no userinfo endpoint; throws
70
+ * when it refuses.
71
+ */
72
+ export declare function userInfo(client: ClientCredentials, fetchImpl: Fetch, accessToken: string): Promise<Record<string, unknown> | null>;
73
+ /** RP-initiated logout (OIDC RP-Initiated Logout 1.0), or null when the issuer offers none. */
74
+ export declare function endSessionUrl(client: ClientCredentials, fetchImpl: Fetch, input: {
75
+ postLogoutRedirectUri: string;
76
+ sessionId?: string;
77
+ }): Promise<string | null>;
78
+ /** For tests: forget cached discovery documents and key sets. */
79
+ export declare function resetOidcCaches(): void;
80
+ export {};
package/dist/oidc.d.ts ADDED
@@ -0,0 +1,80 @@
1
+ import { JWTPayload } from 'jose';
2
+ /**
3
+ * The OIDC relying-party calls: discovery, PKCE, the two token grants and
4
+ * id_token verification. Standard OIDC only, so any compliant issuer works.
5
+ */
6
+ export interface Discovery {
7
+ issuer: string;
8
+ authorization_endpoint: string;
9
+ token_endpoint: string;
10
+ jwks_uri: string;
11
+ userinfo_endpoint?: string;
12
+ end_session_endpoint?: string;
13
+ }
14
+ export interface TokenResponse {
15
+ access_token: string;
16
+ token_type: string;
17
+ expires_in?: number;
18
+ refresh_token?: string;
19
+ id_token?: string;
20
+ scope?: string;
21
+ }
22
+ export interface ClientCredentials {
23
+ issuer: string;
24
+ clientId: string;
25
+ clientSecret?: string;
26
+ }
27
+ /** An error from the token endpoint, carrying its OAuth code. */
28
+ export declare class TokenEndpointError extends Error {
29
+ readonly status: number;
30
+ readonly code: string;
31
+ constructor(status: number, code: string, description: string);
32
+ }
33
+ type Fetch = typeof fetch;
34
+ export declare function discover(issuer: string, fetchImpl: Fetch): Promise<Discovery>;
35
+ /** A random, URL-safe value for state, nonce and the PKCE verifier. */
36
+ export declare function randomValue(): string;
37
+ export declare function pkceChallenge(verifier: string): Promise<string>;
38
+ /** Hex SHA-256, for keying state by a secret without holding the secret. */
39
+ export declare function sha256Hex(value: string): Promise<string>;
40
+ export declare function authorizationUrl(client: ClientCredentials, fetchImpl: Fetch, input: {
41
+ redirectUri: string;
42
+ scopes: string;
43
+ state: string;
44
+ nonce: string;
45
+ codeChallenge: string;
46
+ prompt?: string;
47
+ organizationId?: string;
48
+ loginHint?: string;
49
+ }): Promise<string>;
50
+ export declare function exchangeCode(client: ClientCredentials, fetchImpl: Fetch, input: {
51
+ code: string;
52
+ codeVerifier: string;
53
+ redirectUri: string;
54
+ }): Promise<TokenResponse>;
55
+ export declare function refreshTokens(client: ClientCredentials, fetchImpl: Fetch, refreshToken: string, organizationId?: string): Promise<TokenResponse>;
56
+ /** A client_credentials grant, e.g. with `resource` naming the API the token is for (RFC 8707). */
57
+ export declare function clientCredentialsToken(client: ClientCredentials, fetchImpl: Fetch, params: Record<string, string>): Promise<TokenResponse>;
58
+ /**
59
+ * Verifies a JWT the issuer signed for this app: signature, issuer, audience
60
+ * and expiry. A key the cached set does not know refetches the set once, which
61
+ * is how a key rotation at the issuer is picked up without waiting out the
62
+ * cache.
63
+ */
64
+ export declare function verifyJwt(client: ClientCredentials, fetchImpl: Fetch, token: string): Promise<JWTPayload>;
65
+ /** Verifies an id_token as verifyJwt does, plus the nonce of the sign-in it answers. */
66
+ export declare function verifyIdToken(client: ClientCredentials, fetchImpl: Fetch, idToken: string, nonce: string): Promise<JWTPayload>;
67
+ /**
68
+ * The user's profile claims (OIDC Core §5.3), for an access token that carries
69
+ * none of its own. Null when the issuer offers no userinfo endpoint; throws
70
+ * when it refuses.
71
+ */
72
+ export declare function userInfo(client: ClientCredentials, fetchImpl: Fetch, accessToken: string): Promise<Record<string, unknown> | null>;
73
+ /** RP-initiated logout (OIDC RP-Initiated Logout 1.0), or null when the issuer offers none. */
74
+ export declare function endSessionUrl(client: ClientCredentials, fetchImpl: Fetch, input: {
75
+ postLogoutRedirectUri: string;
76
+ sessionId?: string;
77
+ }): Promise<string | null>;
78
+ /** For tests: forget cached discovery documents and key sets. */
79
+ export declare function resetOidcCaches(): void;
80
+ export {};
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The organization a session acts in, as its access token states it. Roles
3
+ * and permissions are the user's effective ones there, which the auth server
4
+ * resolves afresh on every refresh.
5
+ */
6
+ export interface Organization {
7
+ id: string;
8
+ /**
9
+ * Every role the user effectively holds there. There is no single "role":
10
+ * a member can hold several and roles have no precedence, so check for the
11
+ * one you need.
12
+ */
13
+ roles: string[];
14
+ permissions: string[];
15
+ }
16
+ /** The route, under `basePath`, that moves a session to another organization. */
17
+ export declare const SWITCH_ORGANIZATION_ROUTE = "switch-organization";
18
+ /**
19
+ * Why a switch did not happen, on the return path as `organization_error`:
20
+ * `not_a_member` when the user cannot act in that organization.
21
+ */
22
+ export declare const ORGANIZATION_ERROR_PARAM = "organization_error";
23
+ /** The organization in a set of access-token claims, or null for none. */
24
+ export declare function organizationFromClaims(claims: Record<string, unknown>): Organization | null;
25
+ /**
26
+ * An access token's claims, or none when it is not a JWT. The token is read,
27
+ * not verified: this is only ever called on a token that was verified, or
28
+ * that came straight from the token endpoint over TLS.
29
+ */
30
+ export declare function claimsFromToken(accessToken: string): Record<string, unknown>;
31
+ /**
32
+ * The path a browser is sent to, on this app, to switch organization and
33
+ * then land on `returnTo`. Link to it, or redirect to it from a server action.
34
+ */
35
+ export declare function switchOrganizationPath(basePath: string, organizationId: string, returnTo?: string): string;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The organization a session acts in, as its access token states it. Roles
3
+ * and permissions are the user's effective ones there, which the auth server
4
+ * resolves afresh on every refresh.
5
+ */
6
+ export interface Organization {
7
+ id: string;
8
+ /**
9
+ * Every role the user effectively holds there. There is no single "role":
10
+ * a member can hold several and roles have no precedence, so check for the
11
+ * one you need.
12
+ */
13
+ roles: string[];
14
+ permissions: string[];
15
+ }
16
+ /** The route, under `basePath`, that moves a session to another organization. */
17
+ export declare const SWITCH_ORGANIZATION_ROUTE = "switch-organization";
18
+ /**
19
+ * Why a switch did not happen, on the return path as `organization_error`:
20
+ * `not_a_member` when the user cannot act in that organization.
21
+ */
22
+ export declare const ORGANIZATION_ERROR_PARAM = "organization_error";
23
+ /** The organization in a set of access-token claims, or null for none. */
24
+ export declare function organizationFromClaims(claims: Record<string, unknown>): Organization | null;
25
+ /**
26
+ * An access token's claims, or none when it is not a JWT. The token is read,
27
+ * not verified: this is only ever called on a token that was verified, or
28
+ * that came straight from the token endpoint over TLS.
29
+ */
30
+ export declare function claimsFromToken(accessToken: string): Record<string, unknown>;
31
+ /**
32
+ * The path a browser is sent to, on this app, to switch organization and
33
+ * then land on `returnTo`. Link to it, or redirect to it from a server action.
34
+ */
35
+ export declare function switchOrganizationPath(basePath: string, organizationId: string, returnTo?: string): string;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * App builders' preview hosts (pontive-spec 06, *SDK in builder previews*):
3
+ * Lovable, v0, Replit, Bolt and CodeSandbox show an app's preview inside an
4
+ * iframe on their own site, so a page served on one of these is assumed to be
5
+ * framed. The same list as `@pontive/oidc-client`'s
6
+ * `BUILDER_PREVIEW_HOST_SUFFIXES`; keep them together.
7
+ */
8
+ export declare const BUILDER_PREVIEW_HOST_SUFFIXES: readonly string[];
9
+ /** Whether `hostname` is a builder preview host or below one. */
10
+ export declare function isBuilderPreviewHost(hostname: string): boolean;
11
+ /**
12
+ * Each builder preview preset's host patterns, as the app's
13
+ * `builder_previews` setting names them (pontive-spec 06, *Builder
14
+ * previews*): a `*` is exactly one DNS label. The same as identity-svc's
15
+ * `pkg/app/builderpreview.go` and `@pontive/oidc-client`'s
16
+ * `BUILDER_PREVIEW_PRESETS`; keep them together.
17
+ */
18
+ export declare const BUILDER_PREVIEW_PRESETS: Readonly<Record<string, readonly string[]>>;
19
+ /** The hosted preview callback's path on the auth domain. */
20
+ export declare const PREVIEW_CALLBACK_PATH = "/oauth2/preview-callback";
21
+ /** The `type` of the message the hosted preview callback posts its opener. */
22
+ export declare const AUTHORIZATION_RESPONSE_MESSAGE_TYPE = "pontive:authorization-response";
23
+ /**
24
+ * The builder preview preset whose hosts `origin` is on, or `null`: an https
25
+ * origin on the default port whose host matches one of its patterns.
26
+ */
27
+ export declare function builderPreviewPreset(origin: string): string | null;
28
+ /**
29
+ * The `redirect_uri` of a sign-in on the preview at `origin`: the hosted
30
+ * preview callback on `issuer`, in exactly the spelling the auth domain
31
+ * admits, which the token request repeats.
32
+ */
33
+ export declare function previewCallbackRedirectUri(issuer: string, origin: string): string;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * App builders' preview hosts (pontive-spec 06, *SDK in builder previews*):
3
+ * Lovable, v0, Replit, Bolt and CodeSandbox show an app's preview inside an
4
+ * iframe on their own site, so a page served on one of these is assumed to be
5
+ * framed. The same list as `@pontive/oidc-client`'s
6
+ * `BUILDER_PREVIEW_HOST_SUFFIXES`; keep them together.
7
+ */
8
+ export declare const BUILDER_PREVIEW_HOST_SUFFIXES: readonly string[];
9
+ /** Whether `hostname` is a builder preview host or below one. */
10
+ export declare function isBuilderPreviewHost(hostname: string): boolean;
11
+ /**
12
+ * Each builder preview preset's host patterns, as the app's
13
+ * `builder_previews` setting names them (pontive-spec 06, *Builder
14
+ * previews*): a `*` is exactly one DNS label. The same as identity-svc's
15
+ * `pkg/app/builderpreview.go` and `@pontive/oidc-client`'s
16
+ * `BUILDER_PREVIEW_PRESETS`; keep them together.
17
+ */
18
+ export declare const BUILDER_PREVIEW_PRESETS: Readonly<Record<string, readonly string[]>>;
19
+ /** The hosted preview callback's path on the auth domain. */
20
+ export declare const PREVIEW_CALLBACK_PATH = "/oauth2/preview-callback";
21
+ /** The `type` of the message the hosted preview callback posts its opener. */
22
+ export declare const AUTHORIZATION_RESPONSE_MESSAGE_TYPE = "pontive:authorization-response";
23
+ /**
24
+ * The builder preview preset whose hosts `origin` is on, or `null`: an https
25
+ * origin on the default port whose host matches one of its patterns.
26
+ */
27
+ export declare function builderPreviewPreset(origin: string): string | null;
28
+ /**
29
+ * The `redirect_uri` of a sign-in on the preview at `origin`: the hosted
30
+ * preview callback on `issuer`, in exactly the spelling the auth domain
31
+ * admits, which the token request repeats.
32
+ */
33
+ export declare function previewCallbackRedirectUri(issuer: string, origin: string): string;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * One refresh per session, however many requests ask for it.
3
+ *
4
+ * With rotation on, every refresh spends the token it presents. A page that
5
+ * fires several requests the moment its access token expires would otherwise
6
+ * refresh once per request, and every request after the first would present a
7
+ * token the first had already spent — which the issuer reads as theft.
8
+ *
9
+ * Two layers, in this process:
10
+ *
11
+ * - In flight: requests for the same refresh token share one call.
12
+ * - Recently done: a request that arrives a moment later still holding the old
13
+ * cookie (its browser had not yet stored the new one) is handed the same
14
+ * result rather than spending the old token again.
15
+ *
16
+ * Across processes — several replicas of the app — the issuer's reuse grace
17
+ * window covers the same race, so no shared lock is needed.
18
+ */
19
+ /** How long a result is handed to late arrivals. Matches the issuer's grace window. */
20
+ export declare const RECENT_RESULT_MS = 30000;
21
+ export declare class RefreshCoordinator<T> {
22
+ private readonly recentMs;
23
+ private readonly inFlight;
24
+ private readonly recent;
25
+ constructor(recentMs?: number);
26
+ run(refreshToken: string, refresh: () => Promise<T>): Promise<T>;
27
+ private sweep;
28
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * One refresh per session, however many requests ask for it.
3
+ *
4
+ * With rotation on, every refresh spends the token it presents. A page that
5
+ * fires several requests the moment its access token expires would otherwise
6
+ * refresh once per request, and every request after the first would present a
7
+ * token the first had already spent — which the issuer reads as theft.
8
+ *
9
+ * Two layers, in this process:
10
+ *
11
+ * - In flight: requests for the same refresh token share one call.
12
+ * - Recently done: a request that arrives a moment later still holding the old
13
+ * cookie (its browser had not yet stored the new one) is handed the same
14
+ * result rather than spending the old token again.
15
+ *
16
+ * Across processes — several replicas of the app — the issuer's reuse grace
17
+ * window covers the same race, so no shared lock is needed.
18
+ */
19
+ /** How long a result is handed to late arrivals. Matches the issuer's grace window. */
20
+ export declare const RECENT_RESULT_MS = 30000;
21
+ export declare class RefreshCoordinator<T> {
22
+ private readonly recentMs;
23
+ private readonly inFlight;
24
+ private readonly recent;
25
+ constructor(recentMs?: number);
26
+ run(refreshToken: string, refresh: () => Promise<T>): Promise<T>;
27
+ private sweep;
28
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./mcp-auth-info-jblMsSJo.cjs"),l=require("./resource-server.cjs");async function s(t,e){e.statusCode=t.status,t.headers.forEach((n,r)=>e.setHeader(r,n)),e.end(t.body?new Uint8Array(await t.arrayBuffer()):void 0)}function d(t,e){return(n,r,i)=>{t.verify(n,e).then(o=>{n.principal=o,n.auth=c.toMcpAuthInfo(t,o),i()},o=>{o instanceof l.BearerError?s(o.toResponse(),r).catch(i):i(o)})}}function h(t){return(e,n,r)=>{const i=e.principal??e.auth?.extra?.[c.PRINCIPAL_KEY];if(!i){r(new Error("pontive: requireToolScopes needs requireBearer (or requireBearerAuth) before it"));return}if(e.body===void 0&&e.method==="POST"){r(new Error("pontive: requireToolScopes needs the parsed JSON body (express.json() before it)"));return}t.authorizeToolCalls(i,e.body).then(()=>r(),o=>{o instanceof l.BearerError?s(o.toResponse(),n).catch(r):r(o)})}}function f(t){return(e,n,r)=>{const i=new Headers;for(const[a,u]of Object.entries(e.headers))u!==void 0&&i.set(a,Array.isArray(u)?u.join(", "):u);const o=new Request(new URL(e.originalUrl??e.url??"/","http://localhost"),{method:e.method??"GET",headers:i});t.handleWellKnown(o).then(a=>a?s(a,n):r(),a=>r(a)).catch(r)}}exports.requireBearer=d;exports.requireToolScopes=h;exports.wellKnown=f;
2
+ //# sourceMappingURL=resource-server-express.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-server-express.cjs","sources":["../src/resource-server-express.ts"],"sourcesContent":["import { PRINCIPAL_KEY, toMcpAuthInfo, type McpAuthInfo } from \"./mcp-auth-info\";\nimport { BearerError, type BearerOptions, type Principal, type ResourceServer } from \"./resource-server\";\n\n/**\n * Express (and plain Node `http`) adapters for a resource server from\n * `@pontive/server/resource-server`. Typed structurally, so neither\n * Express nor its types are a dependency.\n *\n * ```ts\n * app.use(wellKnown(rs));\n * app.post(\"/mcp\", requireBearer(rs, { scopes: [\"files:read\"] }), (req, res) => {\n * req.principal; // the verified Principal\n * });\n * ```\n *\n * `requireBearer` also sets `req.auth` to the MCP SDK's `AuthInfo`, which the\n * SDK's `StreamableHTTPServerTransport` hands to tools as `extra.authInfo`, so\n * an Express MCP server needs nothing else:\n *\n * ```ts\n * app.post(\"/mcp\", requireBearer(rs), (req, res) => transport.handleRequest(req, res, req.body));\n * ```\n *\n * `requireToolScopes` after it holds each `tools/call` to the scopes that list\n * the tool.\n */\n\n/** The part of an Express or Node request the adapters read. `requireBearer` sets `principal` and `auth`. */\nexport interface NodeRequestLike {\n method?: string;\n url?: string;\n /** Express's full path, when the middleware is mounted under a prefix. */\n originalUrl?: string;\n headers: Record<string, string | string[] | undefined>;\n principal?: Principal;\n auth?: McpAuthInfo;\n}\n\n/** The part of an Express or Node response the adapters write. */\nexport interface NodeResponseLike {\n statusCode: number;\n setHeader(name: string, value: string): unknown;\n end(body?: string | Uint8Array): unknown;\n}\n\nexport type NextFunction = (err?: unknown) => void;\n\nasync function send(response: Response, res: NodeResponseLike): Promise<void> {\n res.statusCode = response.status;\n response.headers.forEach((value, name) => res.setHeader(name, value));\n res.end(response.body ? new Uint8Array(await response.arrayBuffer()) : undefined);\n}\n\n/**\n * Requires a valid bearer token with every scope in `options.scopes`. On\n * success it sets `req.principal` (and `req.auth`, the MCP SDK's `AuthInfo`\n * with the principal in `extra.principal`) and calls `next()`; otherwise it\n * answers the `401`/`403` itself.\n */\nexport function requireBearer(rs: ResourceServer, options?: BearerOptions) {\n return (req: NodeRequestLike, res: NodeResponseLike, next: NextFunction): void => {\n rs.verify(req, options).then(\n (principal) => {\n req.principal = principal;\n req.auth = toMcpAuthInfo(rs, principal);\n next();\n },\n (err: unknown) => {\n if (err instanceof BearerError) send(err.toResponse(), res).catch(next);\n else next(err);\n },\n );\n };\n}\n\n/**\n * Requires the token to hold a scope that lists each MCP tool the request\n * calls (pontive-spec 44 §12): every `tools/call` in the parsed JSON-RPC body\n * (`express.json()`), checked with `rs.authorizeToolCalls`. A refusal is a\n * `403` with `WWW-Authenticate: Bearer error=\"insufficient_scope\",\n * scope=\"<the scopes listing the tool>\"`, which an MCP client steps up from\n * before the transport sees the call. Any other message passes.\n *\n * Mount it after `requireBearer` (or the MCP SDK's `requireBearerAuth` with\n * Pontive's verifier), whose principal it reads:\n *\n * ```ts\n * app.post(\"/mcp\", requireBearer(rs), requireToolScopes(rs), handler);\n * ```\n */\nexport function requireToolScopes(rs: ResourceServer) {\n return (req: NodeRequestLike & { body?: unknown }, res: NodeResponseLike, next: NextFunction): void => {\n const principal = req.principal ?? (req.auth?.extra?.[PRINCIPAL_KEY] as Principal | undefined);\n if (!principal) {\n next(new Error(\"pontive: requireToolScopes needs requireBearer (or requireBearerAuth) before it\"));\n return;\n }\n if (req.body === undefined && req.method === \"POST\") {\n next(new Error(\"pontive: requireToolScopes needs the parsed JSON body (express.json() before it)\"));\n return;\n }\n rs.authorizeToolCalls(principal, req.body).then(\n () => next(),\n (err: unknown) => {\n if (err instanceof BearerError) send(err.toResponse(), res).catch(next);\n else next(err);\n },\n );\n };\n}\n\n/**\n * Serves the protected resource metadata (both paths, with CORS preflight) and,\n * when the proxy is on, the authorization server metadata. Every other request\n * passes through to `next()`.\n */\nexport function wellKnown(rs: ResourceServer) {\n return (req: NodeRequestLike, res: NodeResponseLike, next: NextFunction): void => {\n const headers = new Headers();\n for (const [name, value] of Object.entries(req.headers)) {\n if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(\", \") : value);\n }\n // Only the path and the headers matter here, so the origin is a placeholder.\n const request = new Request(new URL(req.originalUrl ?? req.url ?? \"/\", \"http://localhost\"), {\n method: req.method ?? \"GET\",\n headers,\n });\n\n rs.handleWellKnown(request).then(\n (response) => (response ? send(response, res) : next()),\n (err: unknown) => next(err),\n ).catch(next);\n };\n}\n"],"names":["send","response","res","value","name","requireBearer","rs","options","req","next","principal","toMcpAuthInfo","err","BearerError","requireToolScopes","PRINCIPAL_KEY","wellKnown","headers","request"],"mappings":"mKA+CA,eAAeA,EAAKC,EAAoBC,EAAsC,CAC5EA,EAAI,WAAaD,EAAS,OAC1BA,EAAS,QAAQ,QAAQ,CAACE,EAAOC,IAASF,EAAI,UAAUE,EAAMD,CAAK,CAAC,EACpED,EAAI,IAAID,EAAS,KAAO,IAAI,WAAW,MAAMA,EAAS,aAAa,EAAI,MAAS,CAClF,CAQO,SAASI,EAAcC,EAAoBC,EAAyB,CACzE,MAAO,CAACC,EAAsBN,EAAuBO,IAA6B,CAChFH,EAAG,OAAOE,EAAKD,CAAO,EAAE,KACrBG,GAAc,CACbF,EAAI,UAAYE,EAChBF,EAAI,KAAOG,gBAAcL,EAAII,CAAS,EACtCD,EAAA,CACF,EACCG,GAAiB,CACZA,aAAeC,cAAab,EAAKY,EAAI,aAAcV,CAAG,EAAE,MAAMO,CAAI,IAC5DG,CAAG,CACf,CAAA,CAEJ,CACF,CAiBO,SAASE,EAAkBR,EAAoB,CACpD,MAAO,CAACE,EAA2CN,EAAuBO,IAA6B,CACrG,MAAMC,EAAYF,EAAI,WAAcA,EAAI,MAAM,QAAQO,eAAa,EACnE,GAAI,CAACL,EAAW,CACdD,EAAK,IAAI,MAAM,iFAAiF,CAAC,EACjG,MACF,CACA,GAAID,EAAI,OAAS,QAAaA,EAAI,SAAW,OAAQ,CACnDC,EAAK,IAAI,MAAM,kFAAkF,CAAC,EAClG,MACF,CACAH,EAAG,mBAAmBI,EAAWF,EAAI,IAAI,EAAE,KACzC,IAAMC,EAAA,EACLG,GAAiB,CACZA,aAAeC,cAAab,EAAKY,EAAI,aAAcV,CAAG,EAAE,MAAMO,CAAI,IAC5DG,CAAG,CACf,CAAA,CAEJ,CACF,CAOO,SAASI,EAAUV,EAAoB,CAC5C,MAAO,CAACE,EAAsBN,EAAuBO,IAA6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