@pontive/server 0.0.0-stage → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
package/dist/index.js ADDED
@@ -0,0 +1,700 @@
1
+ import { readKeylessRecord as ve, KeylessUnavailableError as se, claimLinkFor as Ee, PontiveApiError as W, goneMessage as oe, ensureKeylessInstance as ye, loopbackCallbacks as ke, keylessMessage as _e, KEYLESS_FILE as ge, ENV_FILE as Ie, KeylessInstanceGoneError as Pe } from "./keyless.js";
2
+ import { v as Te, s as ie, u as be, r as K, T as G, a as $, b as Re, p as Ue, e as Ce, c as Ne, d as Oe } from "./oidc-CB0FqjFz.js";
3
+ import { decodeJwt as Ae, jwtDecrypt as Le, EncryptJWT as $e } from "jose";
4
+ const xe = 10080 * 60;
5
+ function ae(e) {
6
+ const t = e.clientSecret ? "server" : "browser", n = ["issuer", "clientId"];
7
+ t === "server" && n.push("sessionSecret");
8
+ for (const s of n)
9
+ if (!e[s]) {
10
+ const c = { issuer: "PONTIVE_ISSUER", clientId: "PONTIVE_CLIENT_ID", sessionSecret: "PONTIVE_SESSION_SECRET" }[s];
11
+ throw new Error(`@pontive/server: ${s} is required${c ? ` (pass it, or set ${c})` : ""}`);
12
+ }
13
+ if (t === "server" && e.sessionSecret.length < 32)
14
+ throw new Error("@pontive/server: sessionSecret must be at least 32 characters");
15
+ if (e.baseUrl)
16
+ try {
17
+ new URL(e.baseUrl);
18
+ } catch {
19
+ throw new Error(`@pontive/server: baseUrl "${e.baseUrl}" is not an absolute URL`);
20
+ }
21
+ return {
22
+ mode: t,
23
+ authPath: (e.authPath ?? "/__pontive").replace(/\/+$/, ""),
24
+ issuer: e.issuer.replace(/\/+$/, ""),
25
+ clientId: e.clientId,
26
+ clientSecret: e.clientSecret || void 0,
27
+ sessionSecret: e.sessionSecret ?? "",
28
+ baseUrl: e.baseUrl ? new URL(e.baseUrl).origin : void 0,
29
+ scopes: e.scopes ?? "openid email profile offline_access",
30
+ basePath: (e.basePath ?? "/api/auth").replace(/\/+$/, ""),
31
+ redirectUri: e.redirectUri,
32
+ signInPath: e.signInPath ?? "/login",
33
+ afterSignInPath: e.afterSignInPath ?? "/",
34
+ prompt: e.prompt,
35
+ cookieName: e.cookieName ?? "pontive_session",
36
+ secureCookies: e.secureCookies,
37
+ iframeSafe: e.iframeSafe ?? "auto",
38
+ previewCallback: e.previewCallback ?? "auto",
39
+ sessionMaxAgeSeconds: e.sessionMaxAgeSeconds ?? xe,
40
+ refreshSkewSeconds: e.refreshSkewSeconds ?? 60,
41
+ fetch: e.fetch ?? ((...s) => fetch(...s)),
42
+ logger: e.logger ?? console
43
+ };
44
+ }
45
+ const U = {
46
+ issuer: "PONTIVE_ISSUER",
47
+ clientId: "PONTIVE_CLIENT_ID",
48
+ clientSecret: "PONTIVE_CLIENT_SECRET",
49
+ sessionSecret: "PONTIVE_SESSION_SECRET",
50
+ secretKey: "PONTIVE_SECRET_KEY",
51
+ instanceId: "PONTIVE_INSTANCE_ID",
52
+ apiUrl: "PONTIVE_API_URL",
53
+ region: "PONTIVE_REGION",
54
+ keyless: "PONTIVE_KEYLESS"
55
+ };
56
+ function V() {
57
+ try {
58
+ return globalThis.process?.env ?? {};
59
+ } catch {
60
+ return {};
61
+ }
62
+ }
63
+ const L = (e) => e && e.trim() ? e.trim() : void 0;
64
+ function Ve(e, t = V()) {
65
+ return {
66
+ ...e,
67
+ issuer: e.issuer || L(t[U.issuer]),
68
+ clientId: e.clientId || L(t[U.clientId]),
69
+ clientSecret: e.clientSecret || L(t[U.clientSecret]),
70
+ sessionSecret: e.sessionSecret || L(t[U.sessionSecret])
71
+ };
72
+ }
73
+ function ce(e = V()) {
74
+ return e.NODE_ENV === "development";
75
+ }
76
+ function Me(e, t = V()) {
77
+ return ce(t) && !e.issuer && t[U.keyless]?.trim() !== "0";
78
+ }
79
+ const D = 3500, z = 16;
80
+ function b(e) {
81
+ const t = /* @__PURE__ */ new Map();
82
+ if (!e) return t;
83
+ for (const n of e.split(";")) {
84
+ const s = n.indexOf("=");
85
+ if (s < 0) continue;
86
+ const c = n.slice(0, s).trim();
87
+ !c || t.has(c) || t.set(c, n.slice(s + 1).trim());
88
+ }
89
+ return t;
90
+ }
91
+ function B(e) {
92
+ return [...e].map(([t, n]) => `${t}=${n}`).join("; ");
93
+ }
94
+ function N(e, t, n) {
95
+ const s = n.sameSite ?? "Lax", c = [`${e}=${t}`, "Path=/", "HttpOnly", `SameSite=${s}`, `Max-Age=${n.maxAge}`];
96
+ return (n.secure || s === "None") && c.push("Secure"), c.join("; ");
97
+ }
98
+ function C(e, t) {
99
+ return t === 0 ? e : `${e}.${t}`;
100
+ }
101
+ function De(e, t) {
102
+ const n = e.get(t);
103
+ if (n === void 0) return null;
104
+ let s = n;
105
+ for (let c = 1; c < z; c++) {
106
+ const a = e.get(C(t, c));
107
+ if (a === void 0) break;
108
+ s += a;
109
+ }
110
+ return s;
111
+ }
112
+ function He(e, t, n, s) {
113
+ const c = [], a = Math.max(1, Math.ceil(n.length / D));
114
+ for (let i = 0; i < a; i++) {
115
+ const l = n.slice(i * D, (i + 1) * D);
116
+ e.set(C(t, i), l), c.push(N(C(t, i), l, s));
117
+ }
118
+ for (let i = a; i < z; i++) {
119
+ const l = C(t, i);
120
+ if (!e.has(l)) break;
121
+ e.delete(l), c.push(N(l, "", { ...s, maxAge: 0 }));
122
+ }
123
+ return c;
124
+ }
125
+ function J(e, t, n) {
126
+ const s = [];
127
+ for (let c = 0; c < z; c++) {
128
+ const a = C(t, c);
129
+ if (!e.has(a)) {
130
+ if (c > 0) break;
131
+ continue;
132
+ }
133
+ e.delete(a), s.push(N(a, "", { ...n, maxAge: 0 }));
134
+ }
135
+ return s;
136
+ }
137
+ const F = "switch-organization", ze = "organization_error", Y = (e) => Array.isArray(e) ? e.filter((t) => typeof t == "string") : [];
138
+ function le(e) {
139
+ const t = e.org_id;
140
+ return typeof t != "string" || t === "" ? null : {
141
+ id: t,
142
+ roles: Y(e.roles),
143
+ permissions: Y(e.permissions)
144
+ };
145
+ }
146
+ function Fe(e) {
147
+ try {
148
+ return Ae(e);
149
+ } catch {
150
+ return {};
151
+ }
152
+ }
153
+ function St(e, t, n = "/") {
154
+ const s = new URLSearchParams({ organization_id: t, returnTo: n });
155
+ return `${e}/${F}?${s.toString()}`;
156
+ }
157
+ const je = "__Host-pontive_access", We = "__Secure-pontive_session_state";
158
+ function Ke(e) {
159
+ const t = (n) => typeof e[n] == "string" ? e[n] : void 0;
160
+ return {
161
+ id: t("sub") ?? "",
162
+ email: t("email"),
163
+ name: t("name") ?? t("email"),
164
+ username: t("preferred_username"),
165
+ picture: t("picture"),
166
+ emailVerified: e.email_verified === !0
167
+ };
168
+ }
169
+ function Ge(e) {
170
+ const t = { issuer: e.issuer, clientId: e.clientId }, n = /* @__PURE__ */ new Map();
171
+ function s(i) {
172
+ for (const [l, d] of n)
173
+ d.expiresAt <= i && n.delete(l);
174
+ }
175
+ async function c(i, l) {
176
+ const d = Date.now();
177
+ s(d);
178
+ const u = await ie(i), p = n.get(u);
179
+ if (p) return p.profile;
180
+ const m = be(t, e.fetch, i).catch((v) => (n.delete(u), e.logger.warn("[pontive] could not read the user's profile:", v instanceof Error ? v.message : String(v)), null));
181
+ return n.set(u, { expiresAt: l, profile: m }), m;
182
+ }
183
+ async function a(i) {
184
+ const l = b(i).get(je);
185
+ if (!l) return null;
186
+ let d;
187
+ try {
188
+ d = await Te(t, e.fetch, l);
189
+ } catch (m) {
190
+ return m.code !== "ERR_JWT_EXPIRED" && e.logger.warn("[pontive] access token cookie refused:", m instanceof Error ? m.message : String(m)), null;
191
+ }
192
+ const u = (d.exp ?? 0) * 1e3, p = await c(l, u);
193
+ return {
194
+ // The token's own claims win for sub: the profile describes the user the
195
+ // token names, never another one.
196
+ user: Ke({ ...p, ...d, sub: d.sub }),
197
+ accessToken: l,
198
+ expiresAt: u,
199
+ sessionId: typeof d.sid == "string" ? d.sid : void 0,
200
+ organization: le(d),
201
+ claims: d
202
+ };
203
+ }
204
+ return {
205
+ // Sign-in and sign-out belong to the browser SDK's widgets in this mode.
206
+ // Switching organization is the one route: the browser is sent through
207
+ // the auth server's session handshake with the organization, which renews
208
+ // its cookies into it — the browser stays the only thing that spends the
209
+ // refresh token. A refused switch comes back with organization_error.
210
+ async handle(i) {
211
+ const l = new URL(i.url);
212
+ if (l.pathname !== `${e.basePath}/${F}`) return null;
213
+ const d = l.searchParams.get("organization_id"), u = Be(l.searchParams.get("returnTo"));
214
+ if (!d) return X(u);
215
+ const p = new URL(`${e.authPath}/oauth2/session`, l.origin);
216
+ return p.searchParams.set("client_id", e.clientId), p.searchParams.set("return_to", u), p.searchParams.set("organization_id", d), X(p.pathname + p.search);
217
+ },
218
+ getSession: a,
219
+ async refresh(i) {
220
+ const l = i.headers.get("cookie"), d = await a(l), u = { session: d, setCookies: [], cookieHeader: l ?? "" };
221
+ if (d || !b(l).has(We)) return u;
222
+ const p = new URL(i.url), m = new URL(`${e.authPath}/oauth2/session`, p.origin);
223
+ return m.searchParams.set("client_id", e.clientId), m.searchParams.set("return_to", p.pathname + p.search), { ...u, handshake: m.pathname + m.search };
224
+ }
225
+ };
226
+ }
227
+ function Be(e) {
228
+ return e && e.startsWith("/") && !e.startsWith("//") && !e.startsWith("/\\") ? e : "/";
229
+ }
230
+ function X(e) {
231
+ return new Response(null, { status: 302, headers: { location: e, "cache-control": "no-store" } });
232
+ }
233
+ const Je = [
234
+ "lovable.app",
235
+ "lovableproject.com",
236
+ "lovable.dev",
237
+ "vusercontent.net",
238
+ "v0.dev",
239
+ "v0.app",
240
+ "webcontainer-api.io",
241
+ "webcontainer.io",
242
+ "replit.dev",
243
+ "replit.app",
244
+ "lp.dev",
245
+ "bolt.host",
246
+ "csb.app"
247
+ ];
248
+ function Ye(e) {
249
+ const t = e.toLowerCase().replace(/\.$/, "");
250
+ return Je.some((n) => t === n || t.endsWith(`.${n}`));
251
+ }
252
+ const Xe = {
253
+ lovable: ["*.lovableproject.com", "*.lovable.app", "*.lovable.dev"],
254
+ v0: ["*.vusercontent.net", "*.lite.vusercontent.net", "*.v0.app", "*.v0.dev"],
255
+ vercel: ["*.vercel.app"],
256
+ replit: ["*.replit.dev", "*.*.replit.dev", "*.replit.app"],
257
+ bolt: [
258
+ "*.bolt.host",
259
+ "*.webcontainer-api.io",
260
+ "*.local-credentialless.webcontainer-api.io",
261
+ "*.local-corp.webcontainer-api.io"
262
+ ],
263
+ codesandbox: ["*.csb.app"]
264
+ }, Ze = "/oauth2/preview-callback", Qe = "pontive:authorization-response", qe = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;
265
+ function et(e) {
266
+ let t;
267
+ try {
268
+ t = new URL(e);
269
+ } catch {
270
+ return null;
271
+ }
272
+ if (t.protocol !== "https:" || t.port !== "" || t.origin !== e) return null;
273
+ const n = t.hostname.split(".");
274
+ for (const [s, c] of Object.entries(Xe))
275
+ for (const a of c) {
276
+ const i = a.split(".");
277
+ if (i.length === n.length && i.every((l, d) => l === "*" ? qe.test(n[d]) : l === n[d]))
278
+ return s;
279
+ }
280
+ return null;
281
+ }
282
+ function tt(e, t) {
283
+ return `${e.replace(/\/$/, "")}${Ze}?origin=${encodeURIComponent(t)}`;
284
+ }
285
+ const nt = 3e4;
286
+ class rt {
287
+ constructor(t = nt) {
288
+ this.recentMs = t;
289
+ }
290
+ recentMs;
291
+ inFlight = /* @__PURE__ */ new Map();
292
+ recent = /* @__PURE__ */ new Map();
293
+ async run(t, n) {
294
+ const s = await ie(t);
295
+ this.sweep();
296
+ const c = this.recent.get(s);
297
+ if (c) return c.result;
298
+ let a = this.inFlight.get(s);
299
+ return a || (a = n().then((i) => (this.recent.set(s, { at: Date.now(), result: i }), i)).finally(() => this.inFlight.delete(s)), this.inFlight.set(s, a)), a;
300
+ }
301
+ sweep() {
302
+ const t = Date.now() - this.recentMs;
303
+ for (const [n, s] of this.recent)
304
+ s.at < t && this.recent.delete(n);
305
+ }
306
+ }
307
+ const Z = /* @__PURE__ */ new Map();
308
+ function ue(e) {
309
+ let t = Z.get(e);
310
+ return t || (t = crypto.subtle.digest("SHA-256", new TextEncoder().encode(e)).then((n) => new Uint8Array(n)), Z.set(e, t)), t;
311
+ }
312
+ async function Q(e, t, n) {
313
+ return new $e(e).setProtectedHeader({ alg: "dir", enc: "A256GCM" }).setIssuedAt().setExpirationTime(`${n}s`).encrypt(await ue(t));
314
+ }
315
+ async function q(e, t) {
316
+ try {
317
+ const { payload: n } = await Le(e, await ue(t));
318
+ return n;
319
+ } catch {
320
+ return null;
321
+ }
322
+ }
323
+ const st = 900, ee = 600;
324
+ function te(e, t) {
325
+ return e && e.startsWith("/") && !e.startsWith("//") && !e.startsWith("/\\") ? e : t;
326
+ }
327
+ function P(e, t = []) {
328
+ const n = new Headers({ location: e, "cache-control": "no-store" });
329
+ for (const s of t) n.append("set-cookie", s);
330
+ return new Response(null, { status: 302, headers: n });
331
+ }
332
+ const ot = "pontive:popup-complete";
333
+ function it(e, t, n) {
334
+ const c = `<!doctype html><meta charset="utf-8"><title>Signing in</title><script type="application/json" id="pontive-popup">${JSON.stringify({ message: { type: ot, url: e }, origin: t }).replace(/</g, "\\u003c")}<\/script><script>(function(){var d=JSON.parse(document.getElementById("pontive-popup").textContent);var go=function(){window.location.replace(d.message.url)};if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}window.close();setTimeout(go,1000)}else{go()}})()<\/script>`, a = new Headers({
335
+ "content-type": "text/html; charset=utf-8",
336
+ "cache-control": "no-store",
337
+ "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'",
338
+ "x-content-type-options": "nosniff"
339
+ });
340
+ for (const i of n) a.append("set-cookie", i);
341
+ return new Response(c, { status: 200, headers: a });
342
+ }
343
+ function at(e) {
344
+ const t = $(), s = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign in</title><style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style><p>This preview signs in in a new window.</p><p><button id="go" type="button">Sign in</button></p><p id="status"></p><script type="application/json" id="pontive-preview-signin">${JSON.stringify({ ...e, type: Qe }).replace(/</g, "\\u003c")}<\/script><script nonce="${t}">(function(){var d=JSON.parse(document.getElementById("pontive-preview-signin").textContent);var s=document.getElementById("status");var w=null;window.addEventListener("message",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!=="object")return;var u=new URL(d.callbackUrl);["code","state","iss","error","error_description","error_uri"].forEach(function(k){var v=m.response[k];if(typeof v==="string")u.searchParams.set(k,v)});try{w.close()}catch(x){}if(u.origin===location.origin)location.replace(u.toString())});document.getElementById("go").addEventListener("click",function(){w=window.open(d.popupUrl,"pontive_signin_popup","popup=yes,width=500,height=680");s.textContent=w?"Finish signing in in the new window.":"The sign-in window was blocked. Allow popups for this site and try again."})})()<\/script>`;
345
+ return new Response(s, {
346
+ status: 200,
347
+ headers: {
348
+ "content-type": "text/html; charset=utf-8",
349
+ "cache-control": "no-store",
350
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${t}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,
351
+ "x-content-type-options": "nosniff",
352
+ "referrer-policy": "no-referrer"
353
+ }
354
+ });
355
+ }
356
+ function g(e, t) {
357
+ if (e.baseUrl) return e.baseUrl;
358
+ const n = t.headers.get("x-forwarded-host")?.split(",")[0]?.trim() || t.headers.get("host")?.trim();
359
+ if (n) {
360
+ const s = t.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() || new URL(t.url).protocol.replace(":", "");
361
+ try {
362
+ return new URL(`${s}://${n}`).origin;
363
+ } catch {
364
+ }
365
+ }
366
+ return new URL(t.url).origin;
367
+ }
368
+ function ct(e) {
369
+ const t = (s) => typeof e[s] == "string" ? e[s] : void 0, n = t("name") ?? ([t("given_name"), t("family_name")].filter(Boolean).join(" ") || void 0) ?? t("email");
370
+ return {
371
+ id: e.sub ?? "",
372
+ email: t("email"),
373
+ name: n,
374
+ username: t("preferred_username"),
375
+ picture: t("picture"),
376
+ emailVerified: e.email_verified === !0
377
+ };
378
+ }
379
+ function ne(e) {
380
+ return Date.now() + (e.expires_in ?? st) * 1e3;
381
+ }
382
+ function pe(e) {
383
+ return e.mode === "browser" ? Ge(e) : lt(e);
384
+ }
385
+ function lt(e) {
386
+ const t = { issuer: e.issuer, clientId: e.clientId, clientSecret: e.clientSecret }, n = `${e.cookieName}_tx`, s = new rt(), c = (r) => e.secureCookies ?? g(e, r).startsWith("https:"), a = (r) => e.iframeSafe === !0 || e.iframeSafe === "auto" && Ye(new URL(g(e, r)).hostname), i = (r, o) => a(r) ? { maxAge: o, secure: !0, sameSite: "None" } : { maxAge: o, secure: c(r) }, l = (r) => e.previewCallback === "always" || e.previewCallback === "auto" && et(g(e, r)) !== null, d = (r) => `${g(e, r)}${e.basePath}/callback`, u = (r) => l(r) ? tt(e.issuer, g(e, r)) : e.redirectUri ?? d(r), p = (r, o) => {
387
+ const h = new URL(e.signInPath, g(e, r));
388
+ return o && h.searchParams.set("error", o), h.toString();
389
+ };
390
+ async function m(r) {
391
+ const o = De(r, e.cookieName);
392
+ if (o === null) return null;
393
+ const h = await q(o, e.sessionSecret);
394
+ return h || e.logger.warn("[pontive] session cookie could not be read (sealed with another secret, or truncated)"), h;
395
+ }
396
+ async function v(r, o, h) {
397
+ const f = await Q({ ...o }, e.sessionSecret, e.sessionMaxAgeSeconds);
398
+ return He(r, e.cookieName, f, i(h, e.sessionMaxAgeSeconds));
399
+ }
400
+ function I(r) {
401
+ const { refreshToken: o, ...h } = r, f = Fe(r.accessToken);
402
+ return { ...h, organization: le(f), claims: f };
403
+ }
404
+ async function R(r) {
405
+ const o = new URL(r.url), h = l(r), f = o.searchParams.get("popup") === "1";
406
+ if (h && !f) {
407
+ const S = new URL(`${e.basePath}/login`, g(e, r));
408
+ return o.searchParams.forEach((y, T) => S.searchParams.set(T, y)), S.searchParams.set("popup", "1"), at({
409
+ popupUrl: S.toString(),
410
+ authOrigin: new URL(e.issuer).origin,
411
+ callbackUrl: d(r)
412
+ });
413
+ }
414
+ const E = {
415
+ state: $(),
416
+ verifier: $(),
417
+ nonce: $(),
418
+ returnTo: te(o.searchParams.get("returnTo") ?? o.searchParams.get("next"), e.afterSignInPath),
419
+ popup: f,
420
+ redirectUri: u(r),
421
+ previewCallback: h
422
+ }, w = await Re(t, e.fetch, {
423
+ redirectUri: E.redirectUri,
424
+ scopes: e.scopes,
425
+ state: E.state,
426
+ nonce: E.nonce,
427
+ codeChallenge: await Ue(E.verifier),
428
+ prompt: e.prompt,
429
+ // The organization the app wants this sign-in to start in; the user is
430
+ // never asked to pick one.
431
+ organizationId: o.searchParams.get("organization_id") ?? void 0,
432
+ // Pre-fills the sign-in page with the address the user is expected to
433
+ // sign in with — an accepted invitation sends its invitee here with it.
434
+ loginHint: o.searchParams.get("login_hint") ?? void 0
435
+ }), _ = await Q({ ...E }, e.sessionSecret, ee);
436
+ return P(w, [N(n, _, i(r, ee))]);
437
+ }
438
+ async function O(r) {
439
+ const o = new URL(r.url), h = b(r.headers.get("cookie")), f = [N(n, "", i(r, 0))], E = h.get(n), w = E ? await q(E, e.sessionSecret) : null, _ = o.searchParams.get("code"), S = (k) => w?.popup && !w.previewCallback ? it(k, g(e, r), f) : P(k, f), y = o.searchParams.get("error");
440
+ if (y) return S(p(r, y));
441
+ if (!w || !_ || o.searchParams.get("state") !== w.state)
442
+ return S(p(r, "invalid_state"));
443
+ const T = o.searchParams.get("iss");
444
+ if (w.previewCallback && T !== null && T !== e.issuer)
445
+ return S(p(r, "invalid_issuer"));
446
+ try {
447
+ const k = await Ce(t, e.fetch, {
448
+ code: _,
449
+ codeVerifier: w.verifier,
450
+ // Exactly as the authorization request named it.
451
+ redirectUri: w.redirectUri ?? u(r)
452
+ });
453
+ if (!k.id_token) throw new Error("the token response carried no id_token; is the openid scope requested?");
454
+ const M = await Ne(t, e.fetch, k.id_token, w.nonce), Se = {
455
+ user: ct(M),
456
+ accessToken: k.access_token,
457
+ refreshToken: k.refresh_token,
458
+ expiresAt: ne(k),
459
+ sessionId: typeof M.sid == "string" ? M.sid : void 0
460
+ };
461
+ f.push(...await v(h, Se, r));
462
+ } catch (k) {
463
+ return e.logger.warn("[pontive] sign-in failed:", k instanceof Error ? k.message : String(k)), S(p(r, "exchange_failed"));
464
+ }
465
+ return S(new URL(w.returnTo, g(e, r)).toString());
466
+ }
467
+ async function A(r) {
468
+ const o = b(r.headers.get("cookie")), h = await m(o), f = J(o, e.cookieName, i(r, 0));
469
+ let E = p(r);
470
+ try {
471
+ E = await Oe(t, e.fetch, {
472
+ postLogoutRedirectUri: p(r),
473
+ sessionId: h?.sessionId
474
+ }) ?? E;
475
+ } catch (w) {
476
+ e.logger.warn("[pontive] could not reach the issuer to end its session:", w instanceof Error ? w.message : String(w));
477
+ }
478
+ return P(E, f);
479
+ }
480
+ function j(r, o) {
481
+ return {
482
+ ...r,
483
+ accessToken: o.access_token,
484
+ // A response without one means rotation is off: the token in hand is still current.
485
+ refreshToken: o.refresh_token ?? r.refreshToken,
486
+ expiresAt: ne(o)
487
+ };
488
+ }
489
+ async function we(r) {
490
+ const o = new URL(r.url), h = b(r.headers.get("cookie")), f = te(o.searchParams.get("returnTo"), e.afterSignInPath), E = o.searchParams.get("organization_id"), w = (y) => {
491
+ const T = new URL(f, g(e, r));
492
+ return y && T.searchParams.set(ze, y), T.toString();
493
+ }, _ = await m(h);
494
+ if (!_?.refreshToken) return P(p(r));
495
+ if (!E) return P(w("invalid_request"));
496
+ let S;
497
+ try {
498
+ S = await K(t, e.fetch, _.refreshToken, E);
499
+ } catch (y) {
500
+ return y instanceof G && y.code === "invalid_request" ? P(w("not_a_member")) : (e.logger.warn("[pontive] organization switch failed:", y instanceof Error ? y.message : String(y)), P(w("switch_failed")));
501
+ }
502
+ return P(w(), await v(h, j(_, S), r));
503
+ }
504
+ async function me(r) {
505
+ try {
506
+ const o = await K(t, e.fetch, r.refreshToken);
507
+ return j(r, o);
508
+ } catch (o) {
509
+ if (o instanceof G && o.status >= 400 && o.status < 500)
510
+ return e.logger.warn("[pontive] refresh refused; signing out:", o.message), null;
511
+ throw o;
512
+ }
513
+ }
514
+ return {
515
+ async handle(r) {
516
+ const { pathname: o } = new URL(r.url);
517
+ if (!o.startsWith(`${e.basePath}/`)) return null;
518
+ const h = o.slice(e.basePath.length + 1);
519
+ return h === "login" && r.method === "GET" ? R(r) : h === "callback" && r.method === "GET" ? O(r) : h === "logout" && (r.method === "GET" || r.method === "POST") ? A(r) : h === F && (r.method === "GET" || r.method === "POST") ? we(r) : null;
520
+ },
521
+ async getSession(r) {
522
+ const o = await m(b(r));
523
+ return o ? Date.now() >= o.expiresAt ? (e.logger.warn(
524
+ "[pontive] the session's access token has expired and getSession cannot refresh it. Run the SDK's middleware on this path so it refreshes before the request is handled."
525
+ ), null) : I(o) : null;
526
+ },
527
+ async refresh(r) {
528
+ const o = b(r.headers.get("cookie")), h = (S) => ({
529
+ session: S,
530
+ setCookies: [],
531
+ cookieHeader: r.headers.get("cookie") ?? ""
532
+ }), f = await m(o);
533
+ if (!f) return h(null);
534
+ if (new URL(r.url).pathname.startsWith(`${e.basePath}/`))
535
+ return h(Date.now() < f.expiresAt ? I(f) : null);
536
+ if (Date.now() < f.expiresAt - e.refreshSkewSeconds * 1e3) return h(I(f));
537
+ const E = () => ({ session: null, setCookies: J(o, e.cookieName, i(r, 0)), cookieHeader: B(o) });
538
+ if (!f.refreshToken) return E();
539
+ let w;
540
+ try {
541
+ w = await s.run(f.refreshToken, () => me(f));
542
+ } catch (S) {
543
+ return e.logger.warn("[pontive] refresh failed, will retry:", S instanceof Error ? S.message : String(S)), h(Date.now() < f.expiresAt ? I(f) : null);
544
+ }
545
+ if (!w) return E();
546
+ const _ = await v(o, w, r);
547
+ return { session: I(w), setCookies: _, cookieHeader: B(o) };
548
+ }
549
+ };
550
+ }
551
+ const ut = "1.23.0", pt = "claim";
552
+ function vt(e = {}, t = {}) {
553
+ const n = V(), s = Ve(e, n);
554
+ if (Me(s, n)) return ht(s, t);
555
+ const c = ae(s), a = ce(n) ? () => de(he(t), c.issuer) : async () => null;
556
+ return fe(c, pe(c), a);
557
+ }
558
+ function he(e) {
559
+ if (e.projectDir) return e.projectDir;
560
+ const t = globalThis.process;
561
+ if (typeof t?.cwd != "function") throw new se("keyless mode needs a project directory (process.cwd)");
562
+ return t.cwd();
563
+ }
564
+ async function de(e, t) {
565
+ try {
566
+ const n = await ve(e);
567
+ return n?.claim_token && n.issuer.replace(/\/+$/, "") === t ? n : null;
568
+ } catch {
569
+ return null;
570
+ }
571
+ }
572
+ function x(e, t) {
573
+ return new Response(`${t}
574
+ `, { status: e, headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" } });
575
+ }
576
+ function fe(e, t, n) {
577
+ const s = `${e.basePath}/${pt}`;
578
+ async function c(a) {
579
+ try {
580
+ const i = await Ee(a, { fetch: e.fetch });
581
+ return new Response(null, { status: 302, headers: { location: i.url, "cache-control": "no-store", "referrer-policy": "no-referrer" } });
582
+ } catch (i) {
583
+ return i instanceof W && i.status === 409 ? x(409, "This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard.") : i instanceof W && i.status === 404 ? x(410, oe(a, "expired")) : (e.logger.warn("[pontive] could not create a claim link:", i instanceof Error ? i.message : String(i)), x(502, "Pontive could not create a claim link just now. Try again, or run `npx pontive claim`."));
584
+ }
585
+ }
586
+ return {
587
+ async handle(a) {
588
+ if (a.method === "GET" && new URL(a.url).pathname === s) {
589
+ const i = await n();
590
+ if (i) return c(i);
591
+ }
592
+ return t.handle(a);
593
+ },
594
+ getSession: (a) => t.getSession(a),
595
+ refresh: (a) => t.refresh(a),
596
+ async providerProps() {
597
+ const a = await n();
598
+ return {
599
+ appId: e.clientId,
600
+ domain: e.mode === "browser" ? e.authPath : e.issuer,
601
+ ...a ? { claimUrl: s } : {}
602
+ };
603
+ }
604
+ };
605
+ }
606
+ const H = /* @__PURE__ */ new Map(), re = /* @__PURE__ */ new Set();
607
+ function ht(e, t) {
608
+ const n = e.logger ?? console;
609
+ let s, c, a = !1;
610
+ async function i() {
611
+ const u = he(t), p = (e.basePath ?? "/api/auth").replace(/\/+$/, "");
612
+ let m = H.get(u);
613
+ m || (m = ye({
614
+ dir: u,
615
+ redirectUris: e.redirectUri ? [e.redirectUri] : ke(p),
616
+ client: { name: t.clientName ?? "@pontive/server", version: ut },
617
+ fetch: e.fetch
618
+ }), H.set(u, m), m.catch(() => H.delete(u)));
619
+ const v = await m;
620
+ re.has(u) || (re.add(u), n.warn(`
621
+ ${_e(v.record, { created: v.created })}
622
+ `));
623
+ const I = globalThis.process;
624
+ if (I?.env)
625
+ for (const [O, A] of Object.entries(v.env))
626
+ A !== void 0 && !I.env[O] && (I.env[O] = A);
627
+ if (!e.clientSecret && !v.env.PONTIVE_CLIENT_SECRET)
628
+ throw new Error(
629
+ `@pontive/server: ${ge} names ${v.record.instance_id}, but PONTIVE_CLIENT_SECRET is neither in ${Ie} nor in the environment. Put it back, or run \`npx pontive init --reset\`.`
630
+ );
631
+ const R = ae({
632
+ ...e,
633
+ issuer: e.issuer || v.env.PONTIVE_ISSUER,
634
+ clientId: e.clientId || v.env.PONTIVE_CLIENT_ID,
635
+ clientSecret: e.clientSecret || v.env.PONTIVE_CLIENT_SECRET,
636
+ sessionSecret: e.sessionSecret || v.env.PONTIVE_SESSION_SECRET,
637
+ fetch: dt(e.fetch, v.record, n)
638
+ });
639
+ return fe(R, pe(R), () => de(u, R.issuer));
640
+ }
641
+ function l() {
642
+ return c ? Promise.reject(c) : (s ??= i().catch((u) => {
643
+ throw s = void 0, u instanceof Pe && (c = u), u;
644
+ }), s);
645
+ }
646
+ function d(u) {
647
+ return u instanceof se ? (a || (a = !0, n.warn(
648
+ `[pontive] ${u.message}. Requests here proceed without a session until the dev server restarts with the PONTIVE_* variables keyless mode wrote to .env.local.`
649
+ )), !0) : !1;
650
+ }
651
+ return {
652
+ async handle(u) {
653
+ try {
654
+ return await (await l()).handle(u);
655
+ } catch (p) {
656
+ if (d(p)) return x(503, "Pontive keyless mode can't run in this runtime; restart the dev server.");
657
+ throw p;
658
+ }
659
+ },
660
+ async getSession(u) {
661
+ try {
662
+ return await (await l()).getSession(u);
663
+ } catch (p) {
664
+ if (d(p)) return null;
665
+ throw p;
666
+ }
667
+ },
668
+ async refresh(u) {
669
+ try {
670
+ return await (await l()).refresh(u);
671
+ } catch (p) {
672
+ if (d(p)) return { session: null, setCookies: [], cookieHeader: u.headers.get("cookie") ?? "" };
673
+ throw p;
674
+ }
675
+ },
676
+ async providerProps() {
677
+ return (await l()).providerProps();
678
+ }
679
+ };
680
+ }
681
+ function dt(e, t, n) {
682
+ const s = e ?? ((...a) => fetch(...a));
683
+ let c = !1;
684
+ return async (a, i) => {
685
+ const l = await s(a, i);
686
+ return l.status === 401 && !c && (typeof a == "string" ? a : a instanceof URL ? a.toString() : a.url).startsWith(t.issuer) && (c = !0, n.warn(`[pontive] ${oe(t, "refused")}`)), l;
687
+ };
688
+ }
689
+ export {
690
+ je as ACCESS_COOKIE,
691
+ pt as CLAIM_ROUTE,
692
+ ze as ORGANIZATION_ERROR_PARAM,
693
+ U as PONTIVE_ENV,
694
+ ut as PONTIVE_SERVER_VERSION,
695
+ We as SESSION_HINT_COOKIE,
696
+ F as SWITCH_ORGANIZATION_ROUTE,
697
+ vt as createServerAuth,
698
+ St as switchOrganizationPath
699
+ };
700
+ //# sourceMappingURL=index.js.map