@pontive/server 1.23.1 → 1.24.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 (48) hide show
  1. package/README.md +42 -0
  2. package/dist/authorization.cjs +1 -1
  3. package/dist/authorization.js +2 -2
  4. package/dist/client-BiVX0Gh-.cjs +2 -0
  5. package/dist/client-BiVX0Gh-.cjs.map +1 -0
  6. package/dist/client-_s4seciG.js +6693 -0
  7. package/dist/client-_s4seciG.js.map +1 -0
  8. package/dist/env.d.cts +2 -0
  9. package/dist/env.d.ts +2 -0
  10. package/dist/index.cjs +4 -4
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +4 -0
  13. package/dist/index.d.ts +4 -0
  14. package/dist/index.js +219 -248
  15. package/dist/index.js.map +1 -1
  16. package/dist/management/client.d.cts +68 -0
  17. package/dist/management/client.d.ts +68 -0
  18. package/dist/management/core.d.cts +112 -0
  19. package/dist/management/core.d.ts +112 -0
  20. package/dist/management/errors.d.cts +78 -0
  21. package/dist/management/errors.d.ts +78 -0
  22. package/dist/management/generated/namespaces.d.cts +5404 -0
  23. package/dist/management/generated/namespaces.d.ts +5404 -0
  24. package/dist/management/generated/types.d.cts +7756 -0
  25. package/dist/management/generated/types.d.ts +7756 -0
  26. package/dist/management/index.d.cts +10 -0
  27. package/dist/management/index.d.ts +10 -0
  28. package/dist/management-credential--CmS8XaV.cjs +2 -0
  29. package/dist/management-credential--CmS8XaV.cjs.map +1 -0
  30. package/dist/management-credential-CynS93TR.js +166 -0
  31. package/dist/management-credential-CynS93TR.js.map +1 -0
  32. package/dist/management.cjs +2 -0
  33. package/dist/management.cjs.map +1 -0
  34. package/dist/management.js +20 -0
  35. package/dist/management.js.map +1 -0
  36. package/dist/resource-server.cjs +1 -1
  37. package/dist/resource-server.cjs.map +1 -1
  38. package/dist/resource-server.js +3 -4
  39. package/dist/resource-server.js.map +1 -1
  40. package/package.json +12 -2
  41. package/dist/management-credential-BNyhHagG.cjs +0 -2
  42. package/dist/management-credential-BNyhHagG.cjs.map +0 -1
  43. package/dist/management-credential-VhmMzGDl.js +0 -39
  44. package/dist/management-credential-VhmMzGDl.js.map +0 -1
  45. package/dist/oidc--We55Nrh.cjs +0 -2
  46. package/dist/oidc--We55Nrh.cjs.map +0 -1
  47. package/dist/oidc-CB0FqjFz.js +0 -131
  48. package/dist/oidc-CB0FqjFz.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/config.ts","../src/env.ts","../src/cookies.ts","../src/organization.ts","../src/browser-mode.ts","../src/preview-hosts.ts","../src/refresh.ts","../src/seal.ts","../src/server-auth.ts","../src/auth.ts"],"sourcesContent":["/**\n * What an app tells the SDK, and the defaults for everything it doesn't.\n *\n * Whether `clientSecret` is set picks the mode, and nothing else does:\n *\n * - **With a secret** (a confidential oauth app): the server holds the whole\n * session in a sealed cookie, signs users in through its own routes, and\n * refreshes in middleware. Needs `sessionSecret`.\n * - **Without one** (a regular app, or a public oauth app): the browser SDK\n * signs users in and is the only thing that refreshes. The server reads the\n * access token cookie the auth server keeps current, through the auth proxy,\n * and sends a lapsed navigation through the auth server's session handshake.\n *\n * Everything beyond the first few fields exists for the rare app that must\n * differ, and its default is the decision the SDK makes for everyone else.\n *\n * **The environment** (pontive-spec 47 §6.1): `issuer`, `clientId`,\n * `clientSecret` and `sessionSecret` fall back to `PONTIVE_ISSUER`,\n * `PONTIVE_CLIENT_ID`, `PONTIVE_CLIENT_SECRET` and `PONTIVE_SESSION_SECRET`\n * when not passed; a value passed always wins. With neither an `issuer` nor\n * `PONTIVE_ISSUER`, development (`NODE_ENV=development`) runs in **keyless\n * mode** (§6.2): the SDK creates an unclaimed development instance on first\n * use and writes its settings to `.env.local`. `PONTIVE_KEYLESS=0` turns that\n * off; outside development a missing issuer is an error.\n */\nexport interface ServerAuthConfig {\n /** The Pontive auth domain, e.g. `https://acme.auth.us.pontive.com`. Default `PONTIVE_ISSUER`. */\n issuer?: string;\n /** The app's id. Default `PONTIVE_CLIENT_ID`. */\n clientId?: string;\n /**\n * Set for a confidential app. It is sent on every token call, and is what\n * lets the app hold its refresh token on its server at all. Default\n * `PONTIVE_CLIENT_SECRET`.\n */\n clientSecret?: string;\n /**\n * Encrypts the session cookie. At least 32 characters; rotating it signs\n * everyone out. Required with a `clientSecret`; unused without one, where the\n * server stores nothing. Default `PONTIVE_SESSION_SECRET`.\n */\n sessionSecret?: string;\n /**\n * The app's public origin, e.g. `https://app.acme.com`. Set it for any\n * deployment behind a proxy or in a container, where the request's own URL\n * names the address the server binds to rather than the one a browser uses.\n * Without it the origin comes from `x-forwarded-proto`/`x-forwarded-host`,\n * then the request URL.\n */\n baseUrl?: string;\n\n /**\n * Without a `clientSecret`: where the auth proxy serves the auth server on\n * this app's origin. Default `/__pontive`, the auth proxy's own default.\n */\n authPath?: string;\n\n /** Default `openid email profile offline_access`. */\n scopes?: string;\n /** Where the SDK's sign-in routes live. Default `/api/auth`. */\n basePath?: string;\n /** Default `${origin}${basePath}/callback`; must be registered on the app verbatim. */\n redirectUri?: string;\n /** The app's own sign-in page: failed sign-ins and signed-out users land here. Default `/login`. */\n signInPath?: string;\n /** Where a sign-in lands when it did not start from a page. Default `/`. */\n afterSignInPath?: string;\n /** An OIDC `prompt` to send, e.g. `login`. */\n prompt?: string;\n /** Default `pontive_session`. */\n cookieName?: string;\n /** Default: whether the public origin is https. */\n secureCookies?: boolean;\n /**\n * Whether the SDK's own cookies — the session and the sign-in transaction —\n * are written `SameSite=None; Secure`, so the browser still sends them to a\n * page inside an iframe on another site: an app builder's preview\n * (pontive-spec 06, *SDK in builder previews*). `\"auto\"`, the default, does\n * so when the public origin is a builder preview host (`*.lovable.app`,\n * `*.lovableproject.com`, `*.vusercontent.net`, `*.v0.app`,\n * `*.webcontainer-api.io`, `*.replit.dev`, …); `true` always, `false`\n * never. Lax everywhere else. A browser that blocks third-party cookies\n * (Safari, Firefox's partitioning) withholds them in the frame anyway.\n */\n iframeSafe?: boolean | \"auto\";\n /**\n * Whether sign-in uses the auth domain's hosted preview callback as its\n * `redirect_uri` (pontive-spec 06, *Builder previews*): for an app builder's\n * preview, whose host changes per draft and cannot be registered. The app\n * turns the builder on in its *Builder previews* setting, on a development\n * instance. The sign-in then runs in a popup; the callback page hands the\n * code back to this page, which forwards it to the `callback` route, and the\n * code is redeemed here with `redirect_uri` the hosted callback. `\"auto\"`,\n * the default, does so when the public origin is a preview host of a known\n * builder (`*.lovableproject.com`, `*.vusercontent.net`,\n * `*.<server>.replit.dev`, …); `\"always\"` everywhere, `\"never\"` never — for\n * a preview whose exact callback is registered.\n */\n previewCallback?: \"auto\" | \"always\" | \"never\";\n /** The session cookie's lifetime. Default 7 days. */\n sessionMaxAgeSeconds?: number;\n /** Refresh when fewer than this many seconds remain. Default 60. */\n refreshSkewSeconds?: number;\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Where the SDK reports a failed refresh or sign-in. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\nexport interface ResolvedConfig {\n /** `server`: a confidential app holding its own session. `browser`: the browser SDK's session, read. */\n mode: \"server\" | \"browser\";\n authPath: string;\n issuer: string;\n clientId: string;\n clientSecret?: string;\n sessionSecret: string;\n baseUrl?: string;\n scopes: string;\n basePath: string;\n redirectUri?: string;\n signInPath: string;\n afterSignInPath: string;\n prompt?: string;\n cookieName: string;\n secureCookies?: boolean;\n iframeSafe: boolean | \"auto\";\n previewCallback: \"auto\" | \"always\" | \"never\";\n sessionMaxAgeSeconds: number;\n refreshSkewSeconds: number;\n fetch: typeof fetch;\n logger: Pick<Console, \"warn\">;\n}\n\nconst SEVEN_DAYS = 7 * 24 * 60 * 60;\n\nexport function resolveConfig(config: ServerAuthConfig): ResolvedConfig {\n const mode = config.clientSecret ? \"server\" : \"browser\";\n\n const required: (keyof ServerAuthConfig)[] = [\"issuer\", \"clientId\"];\n if (mode === \"server\") required.push(\"sessionSecret\");\n for (const key of required) {\n if (!config[key]) {\n const env = { issuer: \"PONTIVE_ISSUER\", clientId: \"PONTIVE_CLIENT_ID\", sessionSecret: \"PONTIVE_SESSION_SECRET\" }[key as string];\n throw new Error(`@pontive/server: ${key} is required${env ? ` (pass it, or set ${env})` : \"\"}`);\n }\n }\n\n if (mode === \"server\" && config.sessionSecret!.length < 32) {\n throw new Error(\"@pontive/server: sessionSecret must be at least 32 characters\");\n }\n\n if (config.baseUrl) {\n try {\n new URL(config.baseUrl);\n } catch {\n throw new Error(`@pontive/server: baseUrl \"${config.baseUrl}\" is not an absolute URL`);\n }\n }\n\n return {\n mode,\n authPath: (config.authPath ?? \"/__pontive\").replace(/\\/+$/, \"\"),\n issuer: config.issuer!.replace(/\\/+$/, \"\"),\n clientId: config.clientId!,\n clientSecret: config.clientSecret || undefined,\n sessionSecret: config.sessionSecret ?? \"\",\n baseUrl: config.baseUrl ? new URL(config.baseUrl).origin : undefined,\n scopes: config.scopes ?? \"openid email profile offline_access\",\n basePath: (config.basePath ?? \"/api/auth\").replace(/\\/+$/, \"\"),\n redirectUri: config.redirectUri,\n signInPath: config.signInPath ?? \"/login\",\n afterSignInPath: config.afterSignInPath ?? \"/\",\n prompt: config.prompt,\n cookieName: config.cookieName ?? \"pontive_session\",\n secureCookies: config.secureCookies,\n iframeSafe: config.iframeSafe ?? \"auto\",\n previewCallback: config.previewCallback ?? \"auto\",\n sessionMaxAgeSeconds: config.sessionMaxAgeSeconds ?? SEVEN_DAYS,\n refreshSkewSeconds: config.refreshSkewSeconds ?? 60,\n fetch: config.fetch ?? ((...args) => fetch(...args)),\n logger: config.logger ?? console,\n };\n}\n","import type { ServerAuthConfig } from \"./config\";\n\n/**\n * The environment contract (pontive-spec 47 §6.1): the variables the SDK falls\n * back to when the app does not pass a field. Explicit config always wins.\n *\n * | Variable | Holds |\n * | ------------------------ | -------------------------------------------------- |\n * | `PONTIVE_ISSUER` | the instance's issuer (its auth domain origin) |\n * | `PONTIVE_CLIENT_ID` | the app's id |\n * | `PONTIVE_CLIENT_SECRET` | a confidential (`web`) app's client secret |\n * | `PONTIVE_SESSION_SECRET` | 32+ random characters, generated locally |\n * | `PONTIVE_SECRET_KEY` | the instance's secret key (management calls; not read here) |\n * | `PONTIVE_INSTANCE_ID` | the instance's id (not secret; not read here) |\n *\n * And for keyless mode (§6.2): `PONTIVE_KEYLESS` (`0` turns it off),\n * `PONTIVE_API_URL` (where the provisioning routes live, default\n * `https://api.pontive.com`) and `PONTIVE_REGION` (the region to provision in;\n * default: the one nearest the caller).\n */\nexport const PONTIVE_ENV = {\n issuer: \"PONTIVE_ISSUER\",\n clientId: \"PONTIVE_CLIENT_ID\",\n clientSecret: \"PONTIVE_CLIENT_SECRET\",\n sessionSecret: \"PONTIVE_SESSION_SECRET\",\n secretKey: \"PONTIVE_SECRET_KEY\",\n instanceId: \"PONTIVE_INSTANCE_ID\",\n apiUrl: \"PONTIVE_API_URL\",\n region: \"PONTIVE_REGION\",\n keyless: \"PONTIVE_KEYLESS\",\n} as const;\n\nexport type Env = Readonly<Record<string, string | undefined>>;\n\n/** `process.env`, or nothing where there is no `process` (a browser, some edge runtimes). */\nexport function processEnv(): Env {\n try {\n return (globalThis as { process?: { env?: Env } }).process?.env ?? {};\n } catch {\n return {};\n }\n}\n\nconst nonEmpty = (value: string | undefined): string | undefined => (value && value.trim() ? value.trim() : undefined);\n\n/** The config with every field the app left out taken from the environment. */\nexport function withEnvFallback(config: ServerAuthConfig, env: Env = processEnv()): ServerAuthConfig {\n return {\n ...config,\n issuer: config.issuer || nonEmpty(env[PONTIVE_ENV.issuer]),\n clientId: config.clientId || nonEmpty(env[PONTIVE_ENV.clientId]),\n clientSecret: config.clientSecret || nonEmpty(env[PONTIVE_ENV.clientSecret]),\n sessionSecret: config.sessionSecret || nonEmpty(env[PONTIVE_ENV.sessionSecret]),\n };\n}\n\n/** `NODE_ENV === \"development\"`: `next dev`, `vite`, and the like. Never a production build. */\nexport function isDevelopment(env: Env = processEnv()): boolean {\n return env.NODE_ENV === \"development\";\n}\n\n/**\n * Whether keyless mode applies (pontive-spec 47 §6.2, decision E3): in\n * development only, with no issuer passed or in `PONTIVE_ISSUER`, unless\n * `PONTIVE_KEYLESS=0`. Anywhere else a missing issuer is the usual\n * `issuer is required` error.\n */\nexport function keylessApplies(config: ServerAuthConfig, env: Env = processEnv()): boolean {\n return isDevelopment(env) && !config.issuer && env[PONTIVE_ENV.keyless]?.trim() !== \"0\";\n}\n","/**\n * Cookie reading and writing, on plain header strings so it runs anywhere a\n * Web `Request`/`Response` does.\n *\n * A sealed session outgrows one cookie (browsers cap each at about 4 KB, and an\n * access token, a refresh token and a user fit in about 3–5), so it is split\n * across numbered chunks: `name`, `name.1`, `name.2`, … and joined on read.\n */\n\n/** Characters per chunk, leaving room under the ~4096-byte cap for the name and attributes. */\nexport const CHUNK_SIZE = 3500;\n/** Upper bound on chunks probed when reading or clearing. */\nexport const MAX_CHUNKS = 16;\n\nexport interface CookieAttributes {\n /** Seconds; 0 deletes the cookie. */\n maxAge: number;\n secure: boolean;\n /**\n * `Lax` unless said otherwise. `None` is for a page inside an app builder's\n * preview iframe, where the browser withholds a Lax cookie from every\n * request (`ServerAuthConfig.iframeSafe`); it is always `Secure`.\n */\n sameSite?: \"Lax\" | \"None\";\n}\n\n/** Parses a `Cookie` request header into name → value. */\nexport function parseCookies(header: string | null | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!header) return out;\n\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) continue;\n\n const name = part.slice(0, eq).trim();\n if (!name || out.has(name)) continue;\n\n out.set(name, part.slice(eq + 1).trim());\n }\n\n return out;\n}\n\n/** Serialises a `Cookie` request header from name → value. */\nexport function formatCookieHeader(cookies: Map<string, string>): string {\n return [...cookies].map(([name, value]) => `${name}=${value}`).join(\"; \");\n}\n\n/**\n * A `Set-Cookie` value. Always HttpOnly, host-only and `Path=/`, and\n * `SameSite=Lax` unless `attrs` say `None`: Lax is what lets the cookie ride\n * the top-level redirect back from the sign-in page, and nothing here is ever\n * for script. `SameSite=None` is always `Secure`, as browsers require.\n *\n * Never `Partitioned`: a preview signs in through a popup, a top-level window\n * whose cookies are keyed to the app's own site, and a partitioned cookie\n * written there would be invisible to the same app framed under the\n * builder's site.\n */\nexport function serializeCookie(name: string, value: string, attrs: CookieAttributes): string {\n const sameSite = attrs.sameSite ?? \"Lax\";\n const parts = [`${name}=${value}`, \"Path=/\", \"HttpOnly\", `SameSite=${sameSite}`, `Max-Age=${attrs.maxAge}`];\n if (attrs.secure || sameSite === \"None\") parts.push(\"Secure\");\n\n return parts.join(\"; \");\n}\n\nexport function chunkName(name: string, index: number): string {\n return index === 0 ? name : `${name}.${index}`;\n}\n\n/** Joins a chunked value, or null when its first chunk is absent. */\nexport function readChunked(cookies: Map<string, string>, name: string): string | null {\n const first = cookies.get(name);\n if (first === undefined) return null;\n\n let value = first;\n for (let i = 1; i < MAX_CHUNKS; i++) {\n const part = cookies.get(chunkName(name, i));\n if (part === undefined) break;\n value += part;\n }\n\n return value;\n}\n\n/**\n * The `Set-Cookie` values that store `value` in chunks, and delete any chunk\n * the request carried beyond what it now needs. Also updates `cookies` in\n * place, so a caller can forward the new state on the same request.\n */\nexport function writeChunked(\n cookies: Map<string, string>,\n name: string,\n value: string,\n attrs: CookieAttributes,\n): string[] {\n const out: string[] = [];\n const count = Math.max(1, Math.ceil(value.length / CHUNK_SIZE));\n\n for (let i = 0; i < count; i++) {\n const chunk = value.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);\n cookies.set(chunkName(name, i), chunk);\n out.push(serializeCookie(chunkName(name, i), chunk, attrs));\n }\n\n for (let i = count; i < MAX_CHUNKS; i++) {\n const stale = chunkName(name, i);\n if (!cookies.has(stale)) break;\n cookies.delete(stale);\n out.push(serializeCookie(stale, \"\", { ...attrs, maxAge: 0 }));\n }\n\n return out;\n}\n\n/** The `Set-Cookie` values that delete every chunk the request carried. */\nexport function clearChunked(\n cookies: Map<string, string>,\n name: string,\n attrs: Omit<CookieAttributes, \"maxAge\">,\n): string[] {\n const out: string[] = [];\n\n for (let i = 0; i < MAX_CHUNKS; i++) {\n const chunk = chunkName(name, i);\n if (!cookies.has(chunk)) {\n if (i > 0) break;\n continue;\n }\n cookies.delete(chunk);\n out.push(serializeCookie(chunk, \"\", { ...attrs, maxAge: 0 }));\n }\n\n return out;\n}\n","import { decodeJwt } from \"jose\";\n\n/**\n * The organization a session acts in, as its access token states it. Roles\n * and permissions are the user's effective ones there, which the auth server\n * resolves afresh on every refresh.\n */\nexport interface Organization {\n id: string;\n /**\n * Every role the user effectively holds there. There is no single \"role\":\n * a member can hold several and roles have no precedence, so check for the\n * one you need.\n */\n roles: string[];\n permissions: string[];\n}\n\n/** The route, under `basePath`, that moves a session to another organization. */\nexport const SWITCH_ORGANIZATION_ROUTE = \"switch-organization\";\n\n/**\n * Why a switch did not happen, on the return path as `organization_error`:\n * `not_a_member` when the user cannot act in that organization.\n */\nexport const ORGANIZATION_ERROR_PARAM = \"organization_error\";\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n\n/** The organization in a set of access-token claims, or null for none. */\nexport function organizationFromClaims(claims: Record<string, unknown>): Organization | null {\n const id = claims.org_id;\n if (typeof id !== \"string\" || id === \"\") return null;\n\n return {\n id,\n roles: strings(claims.roles),\n permissions: strings(claims.permissions),\n };\n}\n\n/**\n * An access token's claims, or none when it is not a JWT. The token is read,\n * not verified: this is only ever called on a token that was verified, or\n * that came straight from the token endpoint over TLS.\n */\nexport function claimsFromToken(accessToken: string): Record<string, unknown> {\n try {\n return decodeJwt(accessToken);\n } catch {\n return {};\n }\n}\n\n/**\n * The path a browser is sent to, on this app, to switch organization and\n * then land on `returnTo`. Link to it, or redirect to it from a server action.\n */\nexport function switchOrganizationPath(basePath: string, organizationId: string, returnTo = \"/\"): string {\n const params = new URLSearchParams({ organization_id: organizationId, returnTo });\n\n return `${basePath}/${SWITCH_ORGANIZATION_ROUTE}?${params.toString()}`;\n}\n","import type { JWTPayload } from \"jose\";\n\nimport type { ResolvedConfig } from \"./config\";\nimport { parseCookies } from \"./cookies\";\nimport { sha256Hex, userInfo, verifyJwt, type ClientCredentials } from \"./oidc\";\nimport { organizationFromClaims, SWITCH_ORGANIZATION_ROUTE } from \"./organization\";\nimport type { CoreAuth, RefreshOutcome, Session, SessionUser } from \"./server-auth\";\n\n/**\n * Server-side sessions for an app whose browser holds the session: a regular\n * app, or a public oauth app, on the browser SDK.\n *\n * The browser SDK signs the user in and is the only thing that ever spends the\n * refresh token. The auth server, reached through the auth proxy on this app's\n * origin, keeps an HttpOnly cookie holding the current access token. The server\n * reads and verifies that cookie, and nothing more — so there is exactly one\n * refresher per session, and rotation never sees a token spent twice.\n *\n * When a page navigation arrives with no live access token but with the\n * session marker, the access token has lapsed while the user is still signed\n * in (the tab was closed, or idle past its refresh). The browser is sent\n * through the auth server's session handshake, which renews the cookies and\n * brings it straight back.\n */\n\n/** The access token, written by the auth server wherever it writes the refresh cookie. */\nexport const ACCESS_COOKIE = \"__Host-pontive_access\";\n/** The readable marker: the browser holds a refresh token. */\nexport const SESSION_HINT_COOKIE = \"__Secure-pontive_session_state\";\n\nfunction userFrom(claims: Record<string, unknown>): SessionUser {\n const str = (key: string) => (typeof claims[key] === \"string\" ? (claims[key] as string) : undefined);\n\n return {\n id: str(\"sub\") ?? \"\",\n email: str(\"email\"),\n name: str(\"name\") ?? str(\"email\"),\n username: str(\"preferred_username\"),\n picture: str(\"picture\"),\n emailVerified: claims.email_verified === true,\n };\n}\n\nexport function createBrowserAuth(cfg: ResolvedConfig): CoreAuth {\n const client: ClientCredentials = { issuer: cfg.issuer, clientId: cfg.clientId };\n\n // Profiles by access token, until the token expires. An access token carries\n // who the user is (sub) but not their email or name, so the profile comes\n // from userinfo — once per token per process, not once per request. Keyed by\n // a hash so the map never holds a live credential.\n const profiles = new Map<string, { expiresAt: number; profile: Promise<Record<string, unknown> | null> }>();\n\n function sweep(now: number) {\n for (const [key, entry] of profiles) {\n if (entry.expiresAt <= now) profiles.delete(key);\n }\n }\n\n async function profileFor(token: string, expiresAt: number): Promise<Record<string, unknown> | null> {\n const now = Date.now();\n sweep(now);\n\n const key = await sha256Hex(token);\n const cached = profiles.get(key);\n if (cached) return cached.profile;\n\n const profile = userInfo(client, cfg.fetch, token).catch((err: unknown) => {\n // The session is valid without a profile: fall back to what the token\n // says, and let the next request try again.\n profiles.delete(key);\n cfg.logger.warn(\"[pontive] could not read the user's profile:\", err instanceof Error ? err.message : String(err));\n return null;\n });\n profiles.set(key, { expiresAt, profile });\n\n return profile;\n }\n\n async function read(cookieHeader: string | null | undefined): Promise<Session | null> {\n const token = parseCookies(cookieHeader).get(ACCESS_COOKIE);\n if (!token) return null;\n\n let claims: JWTPayload;\n try {\n claims = await verifyJwt(client, cfg.fetch, token);\n } catch (err) {\n // An expired token is the ordinary case — the handshake renews it — and\n // not worth a warning. Anything else is.\n if ((err as { code?: string }).code !== \"ERR_JWT_EXPIRED\") {\n cfg.logger.warn(\"[pontive] access token cookie refused:\", err instanceof Error ? err.message : String(err));\n }\n\n return null;\n }\n\n const expiresAt = (claims.exp ?? 0) * 1000;\n const profile = await profileFor(token, expiresAt);\n\n return {\n // The token's own claims win for sub: the profile describes the user the\n // token names, never another one.\n user: userFrom({ ...profile, ...claims, sub: claims.sub }),\n accessToken: token,\n expiresAt,\n sessionId: typeof claims.sid === \"string\" ? claims.sid : undefined,\n organization: organizationFromClaims(claims),\n claims,\n };\n }\n\n return {\n // Sign-in and sign-out belong to the browser SDK's widgets in this mode.\n // Switching organization is the one route: the browser is sent through\n // the auth server's session handshake with the organization, which renews\n // its cookies into it — the browser stays the only thing that spends the\n // refresh token. A refused switch comes back with organization_error.\n async handle(request) {\n const url = new URL(request.url);\n if (url.pathname !== `${cfg.basePath}/${SWITCH_ORGANIZATION_ROUTE}`) return null;\n\n const organizationId = url.searchParams.get(\"organization_id\");\n const returnTo = safeReturnPath(url.searchParams.get(\"returnTo\"));\n\n // Same-origin paths, never absolute URLs built from request.url: behind a\n // proxy or in a container that is the server's own address (0.0.0.0:3000),\n // not the host the browser used. A route handler may answer with a\n // relative Location; the browser resolves it against the page it is on.\n if (!organizationId) return redirectTo(returnTo);\n\n const handshake = new URL(`${cfg.authPath}/oauth2/session`, url.origin);\n handshake.searchParams.set(\"client_id\", cfg.clientId);\n handshake.searchParams.set(\"return_to\", returnTo);\n handshake.searchParams.set(\"organization_id\", organizationId);\n\n return redirectTo(handshake.pathname + handshake.search);\n },\n\n getSession: read,\n\n async refresh(request) {\n const cookieHeader = request.headers.get(\"cookie\");\n const session = await read(cookieHeader);\n const outcome: RefreshOutcome = { session, setCookies: [], cookieHeader: cookieHeader ?? \"\" };\n\n if (session || !parseCookies(cookieHeader).has(SESSION_HINT_COOKIE)) return outcome;\n\n // Signed in, but the access token has lapsed. Never refreshed here: the\n // browser goes through the handshake, so the browser stays the only\n // thing that spends the refresh token.\n const url = new URL(request.url);\n const handshake = new URL(`${cfg.authPath}/oauth2/session`, url.origin);\n handshake.searchParams.set(\"client_id\", cfg.clientId);\n handshake.searchParams.set(\"return_to\", url.pathname + url.search);\n\n return { ...outcome, handshake: handshake.pathname + handshake.search };\n },\n };\n}\n\n/** Only a same-origin path may be returned to: no open redirect. */\nfunction safeReturnPath(value: string | null): string {\n if (value && value.startsWith(\"/\") && !value.startsWith(\"//\") && !value.startsWith(\"/\\\\\")) return value;\n return \"/\";\n}\n\nfunction redirectTo(location: string): Response {\n return new Response(null, { status: 302, headers: { location, \"cache-control\": \"no-store\" } });\n}\n","/**\n * App builders' preview hosts (pontive-spec 06, *SDK in builder previews*):\n * Lovable, v0, Replit, Bolt and CodeSandbox show an app's preview inside an\n * iframe on their own site, so a page served on one of these is assumed to be\n * framed. The same list as `@pontive/oidc-client`'s\n * `BUILDER_PREVIEW_HOST_SUFFIXES`; keep them together.\n */\nexport const BUILDER_PREVIEW_HOST_SUFFIXES: readonly string[] = [\n \"lovable.app\",\n \"lovableproject.com\",\n \"lovable.dev\",\n \"vusercontent.net\",\n \"v0.dev\",\n \"v0.app\",\n \"webcontainer-api.io\",\n \"webcontainer.io\",\n \"replit.dev\",\n \"replit.app\",\n \"lp.dev\",\n \"bolt.host\",\n \"csb.app\",\n];\n\n/** Whether `hostname` is a builder preview host or below one. */\nexport function isBuilderPreviewHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/\\.$/, \"\");\n return BUILDER_PREVIEW_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));\n}\n\n/**\n * Each builder preview preset's host patterns, as the app's\n * `builder_previews` setting names them (pontive-spec 06, *Builder\n * previews*): a `*` is exactly one DNS label. The same as identity-svc's\n * `pkg/app/builderpreview.go` and `@pontive/oidc-client`'s\n * `BUILDER_PREVIEW_PRESETS`; keep them together.\n */\nexport const BUILDER_PREVIEW_PRESETS: Readonly<Record<string, readonly string[]>> = {\n lovable: [\"*.lovableproject.com\", \"*.lovable.app\", \"*.lovable.dev\"],\n v0: [\"*.vusercontent.net\", \"*.lite.vusercontent.net\", \"*.v0.app\", \"*.v0.dev\"],\n vercel: [\"*.vercel.app\"],\n replit: [\"*.replit.dev\", \"*.*.replit.dev\", \"*.replit.app\"],\n bolt: [\n \"*.bolt.host\",\n \"*.webcontainer-api.io\",\n \"*.local-credentialless.webcontainer-api.io\",\n \"*.local-corp.webcontainer-api.io\",\n ],\n codesandbox: [\"*.csb.app\"],\n};\n\n/** The hosted preview callback's path on the auth domain. */\nexport const PREVIEW_CALLBACK_PATH = \"/oauth2/preview-callback\";\n\n/** The `type` of the message the hosted preview callback posts its opener. */\nexport const AUTHORIZATION_RESPONSE_MESSAGE_TYPE = \"pontive:authorization-response\";\n\nconst LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/**\n * The builder preview preset whose hosts `origin` is on, or `null`: an https\n * origin on the default port whose host matches one of its patterns.\n */\nexport function builderPreviewPreset(origin: string): string | null {\n let url: URL;\n try {\n url = new URL(origin);\n } catch {\n return null;\n }\n if (url.protocol !== \"https:\" || url.port !== \"\" || url.origin !== origin) return null;\n\n const got = url.hostname.split(\".\");\n for (const [preset, patterns] of Object.entries(BUILDER_PREVIEW_PRESETS)) {\n for (const pattern of patterns) {\n const want = pattern.split(\".\");\n if (want.length === got.length && want.every((label, i) => (label === \"*\" ? LABEL.test(got[i]) : label === got[i]))) {\n return preset;\n }\n }\n }\n return null;\n}\n\n/**\n * The `redirect_uri` of a sign-in on the preview at `origin`: the hosted\n * preview callback on `issuer`, in exactly the spelling the auth domain\n * admits, which the token request repeats.\n */\nexport function previewCallbackRedirectUri(issuer: string, origin: string): string {\n return `${issuer.replace(/\\/$/, \"\")}${PREVIEW_CALLBACK_PATH}?origin=${encodeURIComponent(origin)}`;\n}\n","import { sha256Hex } from \"./oidc\";\n\n/**\n * One refresh per session, however many requests ask for it.\n *\n * With rotation on, every refresh spends the token it presents. A page that\n * fires several requests the moment its access token expires would otherwise\n * refresh once per request, and every request after the first would present a\n * token the first had already spent — which the issuer reads as theft.\n *\n * Two layers, in this process:\n *\n * - In flight: requests for the same refresh token share one call.\n * - Recently done: a request that arrives a moment later still holding the old\n * cookie (its browser had not yet stored the new one) is handed the same\n * result rather than spending the old token again.\n *\n * Across processes — several replicas of the app — the issuer's reuse grace\n * window covers the same race, so no shared lock is needed.\n */\n\n/** How long a result is handed to late arrivals. Matches the issuer's grace window. */\nexport const RECENT_RESULT_MS = 30_000;\n\nexport class RefreshCoordinator<T> {\n private readonly inFlight = new Map<string, Promise<T>>();\n private readonly recent = new Map<string, { at: number; result: T }>();\n\n constructor(private readonly recentMs: number = RECENT_RESULT_MS) {}\n\n async run(refreshToken: string, refresh: () => Promise<T>): Promise<T> {\n const key = await sha256Hex(refreshToken);\n this.sweep();\n\n const done = this.recent.get(key);\n if (done) return done.result;\n\n let pending = this.inFlight.get(key);\n if (!pending) {\n pending = refresh()\n .then((result) => {\n this.recent.set(key, { at: Date.now(), result });\n return result;\n })\n .finally(() => this.inFlight.delete(key));\n this.inFlight.set(key, pending);\n }\n\n return pending;\n }\n\n private sweep(): void {\n const cutoff = Date.now() - this.recentMs;\n for (const [key, entry] of this.recent) {\n if (entry.at < cutoff) this.recent.delete(key);\n }\n }\n}\n","import { EncryptJWT, jwtDecrypt } from \"jose\";\n\n/**\n * Sealing: authenticated encryption (JWE, `dir` + A256GCM) of whatever the\n * server stores in a cookie. The browser holds ciphertext it can neither read\n * nor alter, which is what lets a refresh token live in a cookie at all.\n */\n\nconst keys = new Map<string, Promise<Uint8Array>>();\n\n/** A 256-bit key derived from the configured secret, whatever its length. */\nfunction keyFor(secret: string): Promise<Uint8Array> {\n let key = keys.get(secret);\n if (!key) {\n key = crypto.subtle\n .digest(\"SHA-256\", new TextEncoder().encode(secret))\n .then((digest) => new Uint8Array(digest));\n keys.set(secret, key);\n }\n\n return key;\n}\n\nexport async function seal(payload: Record<string, unknown>, secret: string, maxAgeSeconds: number): Promise<string> {\n return new EncryptJWT(payload)\n .setProtectedHeader({ alg: \"dir\", enc: \"A256GCM\" })\n .setIssuedAt()\n .setExpirationTime(`${maxAgeSeconds}s`)\n .encrypt(await keyFor(secret));\n}\n\n/** The payload, or null when the value is not one this secret sealed, or has expired. */\nexport async function unseal<T>(value: string, secret: string): Promise<T | null> {\n try {\n const { payload } = await jwtDecrypt(value, await keyFor(secret));\n return payload as T;\n } catch {\n return null;\n }\n}\n","import type { JWTPayload } from \"jose\";\n\nimport { createBrowserAuth } from \"./browser-mode\";\nimport { resolveConfig, type ResolvedConfig, type ServerAuthConfig } from \"./config\";\nimport {\n clearChunked,\n type CookieAttributes,\n formatCookieHeader,\n parseCookies,\n readChunked,\n serializeCookie,\n writeChunked,\n} from \"./cookies\";\nimport {\n authorizationUrl,\n endSessionUrl,\n exchangeCode,\n pkceChallenge,\n randomValue,\n refreshTokens,\n TokenEndpointError,\n verifyIdToken,\n type ClientCredentials,\n type TokenResponse,\n} from \"./oidc\";\nimport {\n AUTHORIZATION_RESPONSE_MESSAGE_TYPE,\n builderPreviewPreset,\n isBuilderPreviewHost,\n previewCallbackRedirectUri,\n} from \"./preview-hosts\";\nimport { RefreshCoordinator } from \"./refresh\";\nimport { seal, unseal } from \"./seal\";\nimport {\n ORGANIZATION_ERROR_PARAM,\n claimsFromToken,\n organizationFromClaims,\n SWITCH_ORGANIZATION_ROUTE,\n type Organization,\n} from \"./organization\";\n\nexport interface SessionUser {\n id: string;\n email?: string;\n name?: string;\n username?: string;\n picture?: string;\n emailVerified: boolean;\n}\n\n/** What `getSession` hands the app. */\nexport interface Session {\n user: SessionUser;\n /** A valid access token, for calling APIs as this user. */\n accessToken: string;\n /** When the access token expires, epoch milliseconds. */\n expiresAt: number;\n /** The issuer's session id (`sid`), when it sent one. */\n sessionId?: string;\n /**\n * The organization the session acts in, or null for none: every B2C\n * session, and a B2B one whose app has not picked an organization. Move it\n * with the `switch-organization` route (`switchOrganizationPath`).\n */\n organization: Organization | null;\n /**\n * Every claim of the access token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it:\n *\n * ```ts\n * const legacyId = typeof session.claims.legacy_user_id === \"string\" ? session.claims.legacy_user_id : undefined;\n * ```\n */\n claims: Record<string, unknown>;\n}\n\n/** What the cookie holds: the session plus the refresh token, which the app never sees. */\ninterface StoredSession extends Omit<Session, \"organization\" | \"claims\"> {\n refreshToken?: string;\n}\n\n/** A sign-in in progress, sealed into its own short-lived cookie. */\ninterface SignInTransaction {\n state: string;\n verifier: string;\n nonce: string;\n returnTo: string;\n /** Started in a popup (`login?popup=1`): the callback hands back to the opener rather than redirecting. */\n popup?: boolean;\n /**\n * The redirect_uri the authorization request named, which the token request\n * repeats: the auth domain's hosted preview callback for a sign-in on an\n * app builder's preview, which the page that opened the popup forwards to\n * the callback route itself.\n */\n redirectUri?: string;\n /** The redirect_uri was the hosted preview callback. */\n previewCallback?: boolean;\n}\n\n/** What a refresh produced, for the middleware to apply. */\nexport interface RefreshOutcome {\n /** The session after the refresh, or null when there is none (or it could not be refreshed). */\n session: Session | null;\n /** `Set-Cookie` values for the response. Empty when nothing changed. */\n setCookies: string[];\n /**\n * The request's `Cookie` header as it should be seen by whatever handles\n * this request next, carrying the refreshed session. Forward it, so a page\n * rendered on this very request reads the new token rather than the expired\n * one the browser sent.\n */\n cookieHeader: string;\n /**\n * Set when a signed-in browser's access token has lapsed and it must go\n * through the auth server's session handshake to renew it — browser mode\n * only. A path on this app's origin. Send a page navigation there; any other\n * request just proceeds without a session.\n */\n handshake?: string;\n}\n\nexport interface ServerAuth {\n /**\n * Handles the SDK's routes under `basePath`: `/login`, `/callback` and\n * `/logout`. Null for any other path.\n */\n handle(request: Request): Promise<Response | null>;\n /**\n * The session in a `Cookie` header, or null. Read-only and never refreshes:\n * any server code can call it, including code that cannot set cookies.\n * Returns null for a session whose access token has expired — `refresh`,\n * run in middleware ahead of the request, is what keeps it current.\n */\n getSession(cookieHeader: string | null | undefined): Promise<Session | null>;\n /**\n * Refreshes the session when its access token is about to expire. For\n * middleware: it runs before anything renders, and its response can always\n * carry the new cookie. Concurrent calls for one session share one refresh.\n */\n refresh(request: Request): Promise<RefreshOutcome>;\n /**\n * What the app's `<Provider>` needs, from the server: the app's id (so no\n * `NEXT_PUBLIC_` copy of it is needed), the auth domain, and, while the\n * instance is an unclaimed one this project created (keyless mode), the\n * claim route for the development banner's *Claim it*. Render the provider\n * with them from server code.\n */\n providerProps(): Promise<ProviderProps>;\n}\n\n/** `<Provider>`'s inputs the server knows (`appId`, `domain`, `claimUrl`). */\nexport interface ProviderProps {\n appId: string;\n /** The issuer (confidential mode), or the auth proxy's path on this origin (browser mode). */\n domain: string;\n /** `{basePath}/claim`, only while this project's keyless instance is unclaimed. */\n claimUrl?: string;\n}\n\nconst DEFAULT_ACCESS_TTL_SECONDS = 900;\nconst TRANSACTION_MAX_AGE = 600;\n\n/** Only a same-origin path may be returned to after sign-in: no open redirect. */\nfunction safePath(value: string | null | undefined, fallback: string): string {\n if (value && value.startsWith(\"/\") && !value.startsWith(\"//\") && !value.startsWith(\"/\\\\\")) return value;\n return fallback;\n}\n\nfunction redirect(location: string, setCookies: string[] = []): Response {\n const headers = new Headers({ location, \"cache-control\": \"no-store\" });\n for (const cookie of setCookies) headers.append(\"set-cookie\", cookie);\n\n return new Response(null, { status: 302, headers });\n}\n\n/** The `type` of the message a sign-in popup sends its opener: `@pontive/oidc-client`'s `POPUP_MESSAGE_TYPE`. */\nexport const POPUP_MESSAGE_TYPE = \"pontive:popup-complete\";\n\n/**\n * The end of a sign-in that ran in a popup (`login?popup=1`): an app\n * builder's preview, framed on the builder's site, cannot send itself to the\n * sign-in page (pontive-spec 06, *SDK in builder previews*). The page hands\n * `location` — where a redirect would have gone, on this app's origin — to\n * the window that opened it, by `postMessage` to `origin` only, and closes.\n * Opened without an opener (the user went to the URL directly), it goes\n * there itself.\n *\n * The data rides in a JSON block whose `<` is escaped, so nothing in it can\n * end the script; the script itself is fixed.\n */\nfunction popupResponse(location: string, origin: string, setCookies: string[]): Response {\n const data = JSON.stringify({ message: { type: POPUP_MESSAGE_TYPE, url: location }, origin }).replace(/</g, \"\\\\u003c\");\n const body =\n `<!doctype html><meta charset=\"utf-8\"><title>Signing in</title>` +\n `<script type=\"application/json\" id=\"pontive-popup\">${data}</script>` +\n `<script>(function(){var d=JSON.parse(document.getElementById(\"pontive-popup\").textContent);` +\n `var go=function(){window.location.replace(d.message.url)};` +\n `if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}` +\n `window.close();setTimeout(go,1000)}else{go()}})()</script>`;\n\n const headers = new Headers({\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": \"default-src 'none'; script-src 'unsafe-inline'\",\n \"x-content-type-options\": \"nosniff\",\n });\n for (const cookie of setCookies) headers.append(\"set-cookie\", cookie);\n\n return new Response(body, { status: 200, headers });\n}\n\n/**\n * The page a sign-in on an app builder's preview starts from when it was not\n * opened in a popup (pontive-spec 06, *Builder previews*): the hosted preview\n * callback hands the authorization response to the window that opened the\n * popup, so this page opens it, inside the click, and is that window. It\n * takes the response only from that popup on the auth domain's origin,\n * forwards it to the callback route on this origin, and goes there.\n *\n * The script is fixed and runs by nonce; the data rides in a JSON block whose\n * `<` is escaped.\n */\nfunction previewSignInPage(data: { popupUrl: string; authOrigin: string; callbackUrl: string }): Response {\n const nonce = randomValue();\n const json = JSON.stringify({ ...data, type: AUTHORIZATION_RESPONSE_MESSAGE_TYPE }).replace(/</g, \"\\\\u003c\");\n const body =\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">` +\n `<title>Sign in</title>` +\n `<style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style>` +\n `<p>This preview signs in in a new window.</p><p><button id=\"go\" type=\"button\">Sign in</button></p><p id=\"status\"></p>` +\n `<script type=\"application/json\" id=\"pontive-preview-signin\">${json}</script>` +\n `<script nonce=\"${nonce}\">(function(){var d=JSON.parse(document.getElementById(\"pontive-preview-signin\").textContent);` +\n `var s=document.getElementById(\"status\");var w=null;` +\n `window.addEventListener(\"message\",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;` +\n `var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!==\"object\")return;` +\n `var u=new URL(d.callbackUrl);[\"code\",\"state\",\"iss\",\"error\",\"error_description\",\"error_uri\"].forEach(function(k){` +\n `var v=m.response[k];if(typeof v===\"string\")u.searchParams.set(k,v)});try{w.close()}catch(x){}` +\n `if(u.origin===location.origin)location.replace(u.toString())});` +\n `document.getElementById(\"go\").addEventListener(\"click\",function(){` +\n `w=window.open(d.popupUrl,\"pontive_signin_popup\",\"popup=yes,width=500,height=680\");` +\n `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>`;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,\n \"x-content-type-options\": \"nosniff\",\n \"referrer-policy\": \"no-referrer\",\n },\n });\n}\n\nfunction publicOrigin(cfg: ResolvedConfig, request: Request): string {\n if (cfg.baseUrl) return cfg.baseUrl;\n\n const host = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim() || request.headers.get(\"host\")?.trim();\n if (host) {\n const proto =\n request.headers.get(\"x-forwarded-proto\")?.split(\",\")[0]?.trim() || new URL(request.url).protocol.replace(\":\", \"\");\n try {\n return new URL(`${proto}://${host}`).origin;\n } catch {\n // Fall through to the request URL.\n }\n }\n\n return new URL(request.url).origin;\n}\n\nfunction userFrom(claims: JWTPayload): SessionUser {\n const str = (key: string) => (typeof claims[key] === \"string\" ? (claims[key] as string) : undefined);\n const name =\n str(\"name\") ?? ([str(\"given_name\"), str(\"family_name\")].filter(Boolean).join(\" \") || undefined) ?? str(\"email\");\n\n return {\n id: claims.sub ?? \"\",\n email: str(\"email\"),\n name,\n username: str(\"preferred_username\"),\n picture: str(\"picture\"),\n emailVerified: claims.email_verified === true,\n };\n}\n\nfunction expiresAtFrom(token: TokenResponse): number {\n return Date.now() + (token.expires_in ?? DEFAULT_ACCESS_TTL_SECONDS) * 1000;\n}\n\n/** What both modes do; `createServerAuth` adds the provider's props and keyless mode's claim route. */\nexport type CoreAuth = Omit<ServerAuth, \"providerProps\">;\n\n/** The auth for a resolved config: the confidential mode's, or the browser SDK's. */\nexport function createCoreAuth(cfg: ResolvedConfig): CoreAuth {\n return cfg.mode === \"browser\" ? createBrowserAuth(cfg) : createSessionAuth(cfg);\n}\n\nfunction createSessionAuth(cfg: ResolvedConfig): CoreAuth {\n const client: ClientCredentials = { issuer: cfg.issuer, clientId: cfg.clientId, clientSecret: cfg.clientSecret };\n const txCookie = `${cfg.cookieName}_tx`;\n const coordinator = new RefreshCoordinator<StoredSession | null>();\n\n const secure = (request: Request) => cfg.secureCookies ?? publicOrigin(cfg, request).startsWith(\"https:\");\n // On an app builder's preview host the page is framed on the builder's\n // site, where a Lax cookie is never sent (ServerAuthConfig.iframeSafe).\n const crossSite = (request: Request) =>\n cfg.iframeSafe === true ||\n (cfg.iframeSafe === \"auto\" && isBuilderPreviewHost(new URL(publicOrigin(cfg, request)).hostname));\n const cookieAttrs = (request: Request, maxAge: number): CookieAttributes =>\n crossSite(request) ? { maxAge, secure: true, sameSite: \"None\" } : { maxAge, secure: secure(request) };\n // An app builder's preview signs in through the auth domain's hosted\n // preview callback (ServerAuthConfig.previewCallback).\n const usesPreviewCallback = (request: Request) =>\n cfg.previewCallback === \"always\" ||\n (cfg.previewCallback === \"auto\" && builderPreviewPreset(publicOrigin(cfg, request)) !== null);\n const callbackUrl = (request: Request) => `${publicOrigin(cfg, request)}${cfg.basePath}/callback`;\n const redirectUri = (request: Request) =>\n usesPreviewCallback(request)\n ? previewCallbackRedirectUri(cfg.issuer, publicOrigin(cfg, request))\n : (cfg.redirectUri ?? callbackUrl(request));\n const toSignIn = (request: Request, error?: string) => {\n const url = new URL(cfg.signInPath, publicOrigin(cfg, request));\n if (error) url.searchParams.set(\"error\", error);\n return url.toString();\n };\n\n async function readStored(cookies: Map<string, string>): Promise<StoredSession | null> {\n const raw = readChunked(cookies, cfg.cookieName);\n if (raw === null) return null;\n\n const stored = await unseal<StoredSession>(raw, cfg.sessionSecret);\n if (!stored) cfg.logger.warn(\"[pontive] session cookie could not be read (sealed with another secret, or truncated)\");\n\n return stored;\n }\n\n async function writeStored(cookies: Map<string, string>, stored: StoredSession, request: Request): Promise<string[]> {\n const sealed = await seal({ ...stored }, cfg.sessionSecret, cfg.sessionMaxAgeSeconds);\n\n return writeChunked(cookies, cfg.cookieName, sealed, cookieAttrs(request, cfg.sessionMaxAgeSeconds));\n }\n\n // The organization and the claims are read from the access token each time\n // rather than stored beside it, so they can never disagree with it.\n function publicSession(stored: StoredSession): Session {\n const { refreshToken: _refreshToken, ...session } = stored;\n const claims = claimsFromToken(stored.accessToken);\n return { ...session, organization: organizationFromClaims(claims), claims };\n }\n\n async function signIn(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const previewCallback = usesPreviewCallback(request);\n const popup = url.searchParams.get(\"popup\") === \"1\";\n\n // On a builder preview the response comes back to the window that opened\n // the popup, so a sign-in not started in one starts from a page that\n // opens it.\n if (previewCallback && !popup) {\n const popupUrl = new URL(`${cfg.basePath}/login`, publicOrigin(cfg, request));\n url.searchParams.forEach((value, key) => popupUrl.searchParams.set(key, value));\n popupUrl.searchParams.set(\"popup\", \"1\");\n\n return previewSignInPage({\n popupUrl: popupUrl.toString(),\n authOrigin: new URL(cfg.issuer).origin,\n callbackUrl: callbackUrl(request),\n });\n }\n\n const tx: SignInTransaction = {\n state: randomValue(),\n verifier: randomValue(),\n nonce: randomValue(),\n returnTo: safePath(url.searchParams.get(\"returnTo\") ?? url.searchParams.get(\"next\"), cfg.afterSignInPath),\n popup,\n redirectUri: redirectUri(request),\n previewCallback,\n };\n\n const location = await authorizationUrl(client, cfg.fetch, {\n redirectUri: tx.redirectUri!,\n scopes: cfg.scopes,\n state: tx.state,\n nonce: tx.nonce,\n codeChallenge: await pkceChallenge(tx.verifier),\n prompt: cfg.prompt,\n // The organization the app wants this sign-in to start in; the user is\n // never asked to pick one.\n organizationId: url.searchParams.get(\"organization_id\") ?? undefined,\n // Pre-fills the sign-in page with the address the user is expected to\n // sign in with — an accepted invitation sends its invitee here with it.\n loginHint: url.searchParams.get(\"login_hint\") ?? undefined,\n });\n\n const sealed = await seal({ ...tx }, cfg.sessionSecret, TRANSACTION_MAX_AGE);\n\n return redirect(location, [serializeCookie(txCookie, sealed, cookieAttrs(request, TRANSACTION_MAX_AGE))]);\n }\n\n async function callback(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n // Single use, whatever happens next.\n const setCookies = [serializeCookie(txCookie, \"\", cookieAttrs(request, 0))];\n\n const raw = cookies.get(txCookie);\n const tx = raw ? await unseal<SignInTransaction>(raw, cfg.sessionSecret) : null;\n const code = url.searchParams.get(\"code\");\n // A sign-in that ran in a popup ends by handing back to its opener —\n // unless it went through the hosted preview callback, which handed back\n // already: this request is the opener's own.\n const finish = (location: string) =>\n tx?.popup && !tx.previewCallback\n ? popupResponse(location, publicOrigin(cfg, request), setCookies)\n : redirect(location, setCookies);\n\n const issuerError = url.searchParams.get(\"error\");\n if (issuerError) return finish(toSignIn(request, issuerError));\n\n if (!tx || !code || url.searchParams.get(\"state\") !== tx.state) {\n return finish(toSignIn(request, \"invalid_state\"));\n }\n\n // A response the page forwarded from the hosted preview callback names\n // its issuer (RFC 9207); one naming another is not this sign-in's.\n const iss = url.searchParams.get(\"iss\");\n if (tx.previewCallback && iss !== null && iss !== cfg.issuer) {\n return finish(toSignIn(request, \"invalid_issuer\"));\n }\n\n try {\n const tokens = await exchangeCode(client, cfg.fetch, {\n code,\n codeVerifier: tx.verifier,\n // Exactly as the authorization request named it.\n redirectUri: tx.redirectUri ?? redirectUri(request),\n });\n if (!tokens.id_token) throw new Error(\"the token response carried no id_token; is the openid scope requested?\");\n\n const claims = await verifyIdToken(client, cfg.fetch, tokens.id_token, tx.nonce);\n const stored: StoredSession = {\n user: userFrom(claims),\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n expiresAt: expiresAtFrom(tokens),\n sessionId: typeof claims.sid === \"string\" ? claims.sid : undefined,\n };\n\n setCookies.push(...(await writeStored(cookies, stored, request)));\n } catch (err) {\n cfg.logger.warn(\"[pontive] sign-in failed:\", err instanceof Error ? err.message : String(err));\n return finish(toSignIn(request, \"exchange_failed\"));\n }\n\n return finish(new URL(tx.returnTo, publicOrigin(cfg, request)).toString());\n }\n\n async function signOut(request: Request): Promise<Response> {\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n // Read before clearing: the session holds the sid the issuer's logout needs.\n const stored = await readStored(cookies);\n const setCookies = clearChunked(cookies, cfg.cookieName, cookieAttrs(request, 0));\n\n let location = toSignIn(request);\n try {\n location =\n (await endSessionUrl(client, cfg.fetch, {\n postLogoutRedirectUri: toSignIn(request),\n sessionId: stored?.sessionId,\n })) ?? location;\n } catch (err) {\n // An unreachable issuer must not stop the local sign-out.\n cfg.logger.warn(\"[pontive] could not reach the issuer to end its session:\", err instanceof Error ? err.message : String(err));\n }\n\n return redirect(location, setCookies);\n }\n\n function renewed(stored: StoredSession, tokens: TokenResponse): StoredSession {\n return {\n ...stored,\n accessToken: tokens.access_token,\n // A response without one means rotation is off: the token in hand is still current.\n refreshToken: tokens.refresh_token ?? stored.refreshToken,\n expiresAt: expiresAtFrom(tokens),\n };\n }\n\n /**\n * Moves the session to another organization: a refresh that names it. The\n * user must be able to act there; a refusal leaves the session exactly as it\n * was and tells the app why on its return path, because a refused switch is\n * not a sign-out.\n */\n async function switchOrganization(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n const returnTo = safePath(url.searchParams.get(\"returnTo\"), cfg.afterSignInPath);\n const organizationId = url.searchParams.get(\"organization_id\");\n const back = (error?: string) => {\n const target = new URL(returnTo, publicOrigin(cfg, request));\n if (error) target.searchParams.set(ORGANIZATION_ERROR_PARAM, error);\n return target.toString();\n };\n\n const stored = await readStored(cookies);\n if (!stored?.refreshToken) return redirect(toSignIn(request));\n if (!organizationId) return redirect(back(\"invalid_request\"));\n\n let tokens: TokenResponse;\n try {\n // Not through the coordinator: a switch is not interchangeable with a\n // plain refresh another request may be running for the same token. Both\n // spending it at once is what the auth server's reuse grace is for.\n tokens = await refreshTokens(client, cfg.fetch, stored.refreshToken, organizationId);\n } catch (err) {\n if (err instanceof TokenEndpointError && err.code === \"invalid_request\") {\n return redirect(back(\"not_a_member\"));\n }\n\n cfg.logger.warn(\"[pontive] organization switch failed:\", err instanceof Error ? err.message : String(err));\n return redirect(back(\"switch_failed\"));\n }\n\n return redirect(back(), await writeStored(cookies, renewed(stored, tokens), request));\n }\n\n /**\n * Spends the refresh token once, returning the refreshed session, or null\n * when the issuer refused it for good. Anything transient throws instead, so\n * the coordinator does not hand a passing failure to other requests.\n */\n async function refreshStored(stored: StoredSession): Promise<StoredSession | null> {\n try {\n const tokens = await refreshTokens(client, cfg.fetch, stored.refreshToken!);\n\n return renewed(stored, tokens);\n } catch (err) {\n if (err instanceof TokenEndpointError && err.status >= 400 && err.status < 500) {\n cfg.logger.warn(\"[pontive] refresh refused; signing out:\", err.message);\n return null;\n }\n\n throw err;\n }\n }\n\n return {\n async handle(request) {\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${cfg.basePath}/`)) return null;\n\n const route = pathname.slice(cfg.basePath.length + 1);\n if (route === \"login\" && request.method === \"GET\") return signIn(request);\n if (route === \"callback\" && request.method === \"GET\") return callback(request);\n if (route === \"logout\" && (request.method === \"GET\" || request.method === \"POST\")) return signOut(request);\n if (route === SWITCH_ORGANIZATION_ROUTE && (request.method === \"GET\" || request.method === \"POST\")) {\n return switchOrganization(request);\n }\n\n return null;\n },\n\n async getSession(cookieHeader) {\n const stored = await readStored(parseCookies(cookieHeader));\n if (!stored) return null;\n\n if (Date.now() >= stored.expiresAt) {\n cfg.logger.warn(\n \"[pontive] the session's access token has expired and getSession cannot refresh it. \" +\n \"Run the SDK's middleware on this path so it refreshes before the request is handled.\",\n );\n return null;\n }\n\n return publicSession(stored);\n },\n\n async refresh(request) {\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n const unchanged = (session: Session | null): RefreshOutcome => ({\n session,\n setCookies: [],\n cookieHeader: request.headers.get(\"cookie\") ?? \"\",\n });\n\n const stored = await readStored(cookies);\n if (!stored) return unchanged(null);\n\n // The SDK's own routes manage the session themselves. Refreshing ahead of\n // them only spends a refresh token that sign-out is about to discard, and\n // puts a second session cookie on the response it clears.\n if (new URL(request.url).pathname.startsWith(`${cfg.basePath}/`)) {\n return unchanged(Date.now() < stored.expiresAt ? publicSession(stored) : null);\n }\n\n if (Date.now() < stored.expiresAt - cfg.refreshSkewSeconds * 1000) return unchanged(publicSession(stored));\n\n const signOutNow = (): RefreshOutcome => {\n const setCookies = clearChunked(cookies, cfg.cookieName, cookieAttrs(request, 0));\n return { session: null, setCookies, cookieHeader: formatCookieHeader(cookies) };\n };\n\n if (!stored.refreshToken) return signOutNow();\n\n let refreshed: StoredSession | null;\n try {\n refreshed = await coordinator.run(stored.refreshToken, () => refreshStored(stored));\n } catch (err) {\n // Transient: keep the session and let the next request try again. The\n // token may still have a few seconds of the skew left.\n cfg.logger.warn(\"[pontive] refresh failed, will retry:\", err instanceof Error ? err.message : String(err));\n return unchanged(Date.now() < stored.expiresAt ? publicSession(stored) : null);\n }\n\n if (!refreshed) return signOutNow();\n\n const setCookies = await writeStored(cookies, refreshed, request);\n\n return { session: publicSession(refreshed), setCookies, cookieHeader: formatCookieHeader(cookies) };\n },\n };\n}\n","import { resolveConfig, type ResolvedConfig, type ServerAuthConfig } from \"./config\";\nimport { isDevelopment, keylessApplies, processEnv, withEnvFallback } from \"./env\";\nimport {\n claimLinkFor,\n ENV_FILE,\n ensureKeylessInstance,\n goneMessage,\n KeylessInstanceGoneError,\n keylessMessage,\n KEYLESS_FILE,\n KeylessUnavailableError,\n loopbackCallbacks,\n PontiveApiError,\n readKeylessRecord,\n type KeylessInstance,\n type KeylessRecord,\n} from \"./keyless\";\nimport { createCoreAuth, type CoreAuth, type ProviderProps, type RefreshOutcome, type ServerAuth } from \"./server-auth\";\n\ndeclare const __PONTIVE_SERVER_VERSION__: string;\n\n/** This package's version, sent as `client.version` when keyless mode provisions. */\nexport const PONTIVE_SERVER_VERSION: string = typeof __PONTIVE_SERVER_VERSION__ === \"string\" ? __PONTIVE_SERVER_VERSION__ : \"0.0.0\";\n\n/** Options for framework packages built on this one (@pontive/nextjs). */\nexport interface ServerAuthOptions {\n /** `client.name` when keyless mode provisions an instance. Default `@pontive/server`. */\n clientName?: string;\n /** The project root, where `.env.local` and `.pontive/` live. Default `process.cwd()`. */\n projectDir?: string;\n}\n\n/** The route, under `basePath`, that sends the browser to a claim link (keyless mode). */\nexport const CLAIM_ROUTE = \"claim\";\n\n/**\n * Server-side sessions on Web `Request`/`Response`.\n *\n * Every field of `config` the app leaves out falls back to its `PONTIVE_*`\n * variable (pontive-spec 47 §6.1), so `createServerAuth()` with nothing is a\n * complete setup when the environment holds them. With no issuer anywhere, in\n * development, it runs in **keyless mode** (§6.2): on first use it creates an\n * unclaimed development instance, writes its settings to `.env.local` and\n * `.pontive/keyless.json`, and uses them at once. Outside development a missing\n * issuer is an error, as ever.\n */\nexport function createServerAuth(config: ServerAuthConfig = {}, options: ServerAuthOptions = {}): ServerAuth {\n const env = processEnv();\n const merged = withEnvFallback(config, env);\n if (keylessApplies(merged, env)) return createKeylessAuth(merged, options);\n\n const cfg = resolveConfig(merged);\n // An instance this project created keylessly keeps its claim route after a restart, when the\n // issuer now comes from .env.local: read keyless.json per call, in development only.\n const record = isDevelopment(env) ? () => matchingRecord(projectDir(options), cfg.issuer) : async () => null;\n return withProviderProps(cfg, createCoreAuth(cfg), record);\n}\n\nfunction projectDir(options: ServerAuthOptions): string {\n if (options.projectDir) return options.projectDir;\n const proc = (globalThis as { process?: { cwd?: () => string } }).process;\n if (typeof proc?.cwd !== \"function\") throw new KeylessUnavailableError(\"keyless mode needs a project directory (process.cwd)\");\n return proc.cwd();\n}\n\n/** keyless.json's record when it is this issuer's and still holds its claim token; null otherwise, and wherever it can't be read. */\nasync function matchingRecord(dir: string, issuer: string): Promise<KeylessRecord | null> {\n try {\n const record = await readKeylessRecord(dir);\n return record?.claim_token && record.issuer.replace(/\\/+$/, \"\") === issuer ? record : null;\n } catch {\n return null;\n }\n}\n\n/** The plain-text answer the claim route gives when it can't redirect. */\nfunction text(status: number, body: string): Response {\n return new Response(`${body}\\n`, { status, headers: { \"content-type\": \"text/plain; charset=utf-8\", \"cache-control\": \"no-store\" } });\n}\n\n/**\n * The provider's props, and `{basePath}/claim` while the instance is this\n * project's unclaimed one: it mints a claim link with the claim token kept on\n * the server and sends the browser there. The token never reaches the page.\n */\nfunction withProviderProps(cfg: ResolvedConfig, core: CoreAuth, record: () => Promise<KeylessRecord | null>): ServerAuth {\n const claimPath = `${cfg.basePath}/${CLAIM_ROUTE}`;\n\n async function claim(found: KeylessRecord): Promise<Response> {\n try {\n const link = await claimLinkFor(found, { fetch: cfg.fetch });\n return new Response(null, { status: 302, headers: { location: link.url, \"cache-control\": \"no-store\", \"referrer-policy\": \"no-referrer\" } });\n } catch (err) {\n if (err instanceof PontiveApiError && err.status === 409) {\n return text(409, \"This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard.\");\n }\n if (err instanceof PontiveApiError && err.status === 404) return text(410, goneMessage(found, \"expired\"));\n cfg.logger.warn(\"[pontive] could not create a claim link:\", err instanceof Error ? err.message : String(err));\n return text(502, \"Pontive could not create a claim link just now. Try again, or run `npx pontive claim`.\");\n }\n }\n\n return {\n async handle(request) {\n if (request.method === \"GET\" && new URL(request.url).pathname === claimPath) {\n const found = await record();\n if (found) return claim(found);\n }\n return core.handle(request);\n },\n getSession: cookieHeader => core.getSession(cookieHeader),\n refresh: request => core.refresh(request),\n async providerProps() {\n const found = await record();\n return {\n appId: cfg.clientId,\n domain: cfg.mode === \"browser\" ? cfg.authPath : cfg.issuer,\n ...(found ? { claimUrl: claimPath } : {}),\n };\n },\n };\n}\n\n/** One provisioning per project directory per process; the file lock covers other processes. */\nconst instances = new Map<string, Promise<KeylessInstance>>();\n/** Directories whose console message this process has printed. */\nconst announced = new Set<string>();\n\n/** Forgets the per-process keyless state. For tests. */\nexport function resetKeylessState(): void {\n instances.clear();\n announced.clear();\n}\n\n/**\n * Keyless mode: everything waits for the instance (`keyless.json`'s, or one\n * created now), which is resolved on the first request rather than here,\n * since creating it needs the network.\n */\nfunction createKeylessAuth(merged: ServerAuthConfig, options: ServerAuthOptions): ServerAuth {\n const logger = merged.logger ?? console;\n let ready: Promise<ServerAuth> | undefined;\n let gone: KeylessInstanceGoneError | undefined;\n let warnedUnavailable = false;\n\n async function setup(): Promise<ServerAuth> {\n const dir = projectDir(options);\n const basePath = (merged.basePath ?? \"/api/auth\").replace(/\\/+$/, \"\");\n let pending = instances.get(dir);\n if (!pending) {\n pending = ensureKeylessInstance({\n dir,\n redirectUris: merged.redirectUri ? [merged.redirectUri] : loopbackCallbacks(basePath),\n client: { name: options.clientName ?? \"@pontive/server\", version: PONTIVE_SERVER_VERSION },\n fetch: merged.fetch,\n });\n instances.set(dir, pending);\n pending.catch(() => instances.delete(dir));\n }\n const instance = await pending;\n\n if (!announced.has(dir)) {\n announced.add(dir);\n logger.warn(`\\n${keylessMessage(instance.record, { created: instance.created })}\\n`);\n }\n\n // Next.js and most dev servers read .env.local only at start: the values are used in-process\n // now, and put in process.env for the app's own code (PONTIVE_SECRET_KEY …) until the restart.\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n if (proc?.env) {\n for (const [key, value] of Object.entries(instance.env)) {\n if (value !== undefined && !proc.env[key]) proc.env[key] = value;\n }\n }\n\n if (!merged.clientSecret && !instance.env.PONTIVE_CLIENT_SECRET) {\n throw new Error(\n `@pontive/server: ${KEYLESS_FILE} names ${instance.record.instance_id}, but PONTIVE_CLIENT_SECRET is ` +\n `neither in ${ENV_FILE} nor in the environment. Put it back, or run \\`npx pontive init --reset\\`.`,\n );\n }\n\n const cfg = resolveConfig({\n ...merged,\n issuer: merged.issuer || instance.env.PONTIVE_ISSUER,\n clientId: merged.clientId || instance.env.PONTIVE_CLIENT_ID,\n clientSecret: merged.clientSecret || instance.env.PONTIVE_CLIENT_SECRET,\n sessionSecret: merged.sessionSecret || instance.env.PONTIVE_SESSION_SECRET,\n fetch: watchForRefusal(merged.fetch, instance.record, logger),\n });\n return withProviderProps(cfg, createCoreAuth(cfg), () => matchingRecord(dir, cfg.issuer));\n }\n\n function auth(): Promise<ServerAuth> {\n if (gone) return Promise.reject(gone);\n ready ??= setup().catch((err: unknown) => {\n ready = undefined;\n // Expired is final for this process; anything else (the network, a limit) is tried again next request.\n if (err instanceof KeylessInstanceGoneError) gone = err;\n throw err;\n });\n return ready;\n }\n\n /** An edge runtime (no file system) can't run keyless mode: it proceeds without a session instead. */\n function unavailable(err: unknown): boolean {\n if (!(err instanceof KeylessUnavailableError)) return false;\n if (!warnedUnavailable) {\n warnedUnavailable = true;\n logger.warn(\n `[pontive] ${err.message}. Requests here proceed without a session until the dev server restarts ` +\n \"with the PONTIVE_* variables keyless mode wrote to .env.local.\",\n );\n }\n return true;\n }\n\n return {\n async handle(request) {\n try {\n return await (await auth()).handle(request);\n } catch (err) {\n if (unavailable(err)) return text(503, \"Pontive keyless mode can't run in this runtime; restart the dev server.\");\n throw err;\n }\n },\n async getSession(cookieHeader) {\n try {\n return await (await auth()).getSession(cookieHeader);\n } catch (err) {\n if (unavailable(err)) return null;\n throw err;\n }\n },\n async refresh(request): Promise<RefreshOutcome> {\n try {\n return await (await auth()).refresh(request);\n } catch (err) {\n if (unavailable(err)) return { session: null, setCookies: [], cookieHeader: request.headers.get(\"cookie\") ?? \"\" };\n throw err;\n }\n },\n async providerProps() {\n return (await auth()).providerProps();\n },\n };\n}\n\n/**\n * Says so, once, when the instance refuses the app's credentials (`401` from\n * the token endpoint): it expired, or was claimed and its keys rotated. Keyless\n * mode never creates another instance over it.\n */\nexport function watchForRefusal(base: typeof fetch | undefined, record: KeylessRecord, logger: Pick<Console, \"warn\">): typeof fetch {\n const fetchImpl = base ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let told = false;\n return async (input, init) => {\n const response = await fetchImpl(input, init);\n if (response.status === 401 && !told) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n if (url.startsWith(record.issuer)) {\n told = true;\n logger.warn(`[pontive] ${goneMessage(record, \"refused\")}`);\n }\n }\n return response;\n };\n}\n"],"names":["SEVEN_DAYS","resolveConfig","config","mode","required","key","env","args","PONTIVE_ENV","processEnv","nonEmpty","value","withEnvFallback","isDevelopment","keylessApplies","CHUNK_SIZE","MAX_CHUNKS","parseCookies","header","out","part","eq","name","formatCookieHeader","cookies","serializeCookie","attrs","sameSite","parts","chunkName","index","readChunked","first","i","writeChunked","count","chunk","stale","clearChunked","SWITCH_ORGANIZATION_ROUTE","ORGANIZATION_ERROR_PARAM","strings","v","organizationFromClaims","claims","id","claimsFromToken","accessToken","decodeJwt","switchOrganizationPath","basePath","organizationId","returnTo","params","ACCESS_COOKIE","SESSION_HINT_COOKIE","userFrom","str","createBrowserAuth","cfg","client","profiles","sweep","now","entry","profileFor","token","expiresAt","sha256Hex","cached","profile","userInfo","err","read","cookieHeader","verifyJwt","request","url","safeReturnPath","redirectTo","handshake","session","outcome","location","BUILDER_PREVIEW_HOST_SUFFIXES","isBuilderPreviewHost","hostname","host","suffix","BUILDER_PREVIEW_PRESETS","PREVIEW_CALLBACK_PATH","AUTHORIZATION_RESPONSE_MESSAGE_TYPE","LABEL","builderPreviewPreset","origin","got","preset","patterns","pattern","want","label","previewCallbackRedirectUri","issuer","RECENT_RESULT_MS","RefreshCoordinator","recentMs","refreshToken","refresh","done","pending","result","cutoff","keys","keyFor","secret","digest","seal","payload","maxAgeSeconds","EncryptJWT","unseal","jwtDecrypt","DEFAULT_ACCESS_TTL_SECONDS","TRANSACTION_MAX_AGE","safePath","fallback","redirect","setCookies","headers","cookie","POPUP_MESSAGE_TYPE","popupResponse","body","previewSignInPage","data","nonce","randomValue","publicOrigin","proto","expiresAtFrom","createCoreAuth","createSessionAuth","txCookie","coordinator","secure","crossSite","cookieAttrs","maxAge","usesPreviewCallback","callbackUrl","redirectUri","toSignIn","error","readStored","raw","stored","writeStored","sealed","publicSession","_refreshToken","signIn","previewCallback","popup","popupUrl","tx","authorizationUrl","pkceChallenge","callback","code","finish","issuerError","iss","tokens","exchangeCode","verifyIdToken","signOut","endSessionUrl","renewed","switchOrganization","back","target","refreshTokens","TokenEndpointError","refreshStored","pathname","route","unchanged","signOutNow","refreshed","PONTIVE_SERVER_VERSION","CLAIM_ROUTE","createServerAuth","options","merged","createKeylessAuth","record","matchingRecord","projectDir","withProviderProps","proc","KeylessUnavailableError","dir","readKeylessRecord","text","status","core","claimPath","claim","found","link","claimLinkFor","PontiveApiError","goneMessage","instances","announced","logger","ready","gone","warnedUnavailable","setup","ensureKeylessInstance","loopbackCallbacks","instance","keylessMessage","KEYLESS_FILE","ENV_FILE","watchForRefusal","auth","KeylessInstanceGoneError","unavailable","base","fetchImpl","told","input","init","response"],"mappings":"oKAsIMA,GAAa,MAAc,GAE1B,SAASC,GAAcC,EAA0C,CACtE,MAAMC,EAAOD,EAAO,aAAe,SAAW,UAExCE,EAAuC,CAAC,SAAU,UAAU,EAC9DD,IAAS,UAAUC,EAAS,KAAK,eAAe,EACpD,UAAWC,KAAOD,EAChB,GAAI,CAACF,EAAOG,CAAG,EAAG,CAChB,MAAMC,EAAM,CAAE,OAAQ,iBAAkB,SAAU,oBAAqB,cAAe,wBAAA,EAA2BD,CAAa,EAC9H,MAAM,IAAI,MAAM,oBAAoBA,CAAG,eAAeC,EAAM,qBAAqBA,CAAG,IAAM,EAAE,EAAE,CAChG,CAGF,GAAIH,IAAS,UAAYD,EAAO,cAAe,OAAS,GACtD,MAAM,IAAI,MAAM,+DAA+D,EAGjF,GAAIA,EAAO,QACT,GAAI,CACF,IAAI,IAAIA,EAAO,OAAO,CACxB,MAAQ,CACN,MAAM,IAAI,MAAM,6BAA6BA,EAAO,OAAO,0BAA0B,CACvF,CAGF,MAAO,CACL,KAAAC,EACA,UAAWD,EAAO,UAAY,cAAc,QAAQ,OAAQ,EAAE,EAC9D,OAAQA,EAAO,OAAQ,QAAQ,OAAQ,EAAE,EACzC,SAAUA,EAAO,SACjB,aAAcA,EAAO,cAAgB,OACrC,cAAeA,EAAO,eAAiB,GACvC,QAASA,EAAO,QAAU,IAAI,IAAIA,EAAO,OAAO,EAAE,OAAS,OAC3D,OAAQA,EAAO,QAAU,sCACzB,UAAWA,E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J,EAAA,GAAQ,cAAA,CACxB,CAAA,CAEJ,CAOO,SAASD,GAAgBI,EAAgCnC,EAAuBoB,EAA6C,CAClI,MAAMgB,EAAYD,IAAS,IAAI/N,IAAmC,MAAM,GAAGA,CAAI,GAC/E,IAAIiO,EAAO,GACX,MAAO,OAAOC,EAAOC,IAAS,CAC5B,MAAMC,EAAW,MAAMJ,EAAUE,EAAOC,CAAI,EAC5C,OAAIC,EAAS,SAAW,KAAO,CAACH,IAClB,OAAOC,GAAU,SAAWA,EAAQA,aAAiB,IAAMA,EAAM,SAAA,EAAaA,EAAM,KACxF,WAAWtC,EAAO,MAAM,IAC9BqC,EAAO,GACPjB,EAAO,KAAK,aAAaH,EAAAA,YAAYjB,EAAQ,SAAS,CAAC,EAAE,GAGtDwC,CACT,CACF"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/config.ts","../src/cookies.ts","../src/organization.ts","../src/browser-mode.ts","../src/preview-hosts.ts","../src/refresh.ts","../src/seal.ts","../src/server-auth.ts","../src/auth.ts"],"sourcesContent":["/**\n * What an app tells the SDK, and the defaults for everything it doesn't.\n *\n * Whether `clientSecret` is set picks the mode, and nothing else does:\n *\n * - **With a secret** (a confidential oauth app): the server holds the whole\n * session in a sealed cookie, signs users in through its own routes, and\n * refreshes in middleware. Needs `sessionSecret`.\n * - **Without one** (a regular app, or a public oauth app): the browser SDK\n * signs users in and is the only thing that refreshes. The server reads the\n * access token cookie the auth server keeps current, through the auth proxy,\n * and sends a lapsed navigation through the auth server's session handshake.\n *\n * Everything beyond the first few fields exists for the rare app that must\n * differ, and its default is the decision the SDK makes for everyone else.\n *\n * **The environment** (pontive-spec 47 §6.1): `issuer`, `clientId`,\n * `clientSecret` and `sessionSecret` fall back to `PONTIVE_ISSUER`,\n * `PONTIVE_CLIENT_ID`, `PONTIVE_CLIENT_SECRET` and `PONTIVE_SESSION_SECRET`\n * when not passed; a value passed always wins. With neither an `issuer` nor\n * `PONTIVE_ISSUER`, development (`NODE_ENV=development`) runs in **keyless\n * mode** (§6.2): the SDK creates an unclaimed development instance on first\n * use and writes its settings to `.env.local`. `PONTIVE_KEYLESS=0` turns that\n * off; outside development a missing issuer is an error.\n */\nexport interface ServerAuthConfig {\n /** The Pontive auth domain, e.g. `https://acme.auth.us.pontive.com`. Default `PONTIVE_ISSUER`. */\n issuer?: string;\n /** The app's id. Default `PONTIVE_CLIENT_ID`. */\n clientId?: string;\n /**\n * Set for a confidential app. It is sent on every token call, and is what\n * lets the app hold its refresh token on its server at all. Default\n * `PONTIVE_CLIENT_SECRET`.\n */\n clientSecret?: string;\n /**\n * Encrypts the session cookie. At least 32 characters; rotating it signs\n * everyone out. Required with a `clientSecret`; unused without one, where the\n * server stores nothing. Default `PONTIVE_SESSION_SECRET`.\n */\n sessionSecret?: string;\n /**\n * The app's public origin, e.g. `https://app.acme.com`. Set it for any\n * deployment behind a proxy or in a container, where the request's own URL\n * names the address the server binds to rather than the one a browser uses.\n * Without it the origin comes from `x-forwarded-proto`/`x-forwarded-host`,\n * then the request URL.\n */\n baseUrl?: string;\n\n /**\n * Without a `clientSecret`: where the auth proxy serves the auth server on\n * this app's origin. Default `/__pontive`, the auth proxy's own default.\n */\n authPath?: string;\n\n /** Default `openid email profile offline_access`. */\n scopes?: string;\n /** Where the SDK's sign-in routes live. Default `/api/auth`. */\n basePath?: string;\n /** Default `${origin}${basePath}/callback`; must be registered on the app verbatim. */\n redirectUri?: string;\n /** The app's own sign-in page: failed sign-ins and signed-out users land here. Default `/login`. */\n signInPath?: string;\n /** Where a sign-in lands when it did not start from a page. Default `/`. */\n afterSignInPath?: string;\n /** An OIDC `prompt` to send, e.g. `login`. */\n prompt?: string;\n /** Default `pontive_session`. */\n cookieName?: string;\n /** Default: whether the public origin is https. */\n secureCookies?: boolean;\n /**\n * Whether the SDK's own cookies — the session and the sign-in transaction —\n * are written `SameSite=None; Secure`, so the browser still sends them to a\n * page inside an iframe on another site: an app builder's preview\n * (pontive-spec 06, *SDK in builder previews*). `\"auto\"`, the default, does\n * so when the public origin is a builder preview host (`*.lovable.app`,\n * `*.lovableproject.com`, `*.vusercontent.net`, `*.v0.app`,\n * `*.webcontainer-api.io`, `*.replit.dev`, …); `true` always, `false`\n * never. Lax everywhere else. A browser that blocks third-party cookies\n * (Safari, Firefox's partitioning) withholds them in the frame anyway.\n */\n iframeSafe?: boolean | \"auto\";\n /**\n * Whether sign-in uses the auth domain's hosted preview callback as its\n * `redirect_uri` (pontive-spec 06, *Builder previews*): for an app builder's\n * preview, whose host changes per draft and cannot be registered. The app\n * turns the builder on in its *Builder previews* setting, on a development\n * instance. The sign-in then runs in a popup; the callback page hands the\n * code back to this page, which forwards it to the `callback` route, and the\n * code is redeemed here with `redirect_uri` the hosted callback. `\"auto\"`,\n * the default, does so when the public origin is a preview host of a known\n * builder (`*.lovableproject.com`, `*.vusercontent.net`,\n * `*.<server>.replit.dev`, …); `\"always\"` everywhere, `\"never\"` never — for\n * a preview whose exact callback is registered.\n */\n previewCallback?: \"auto\" | \"always\" | \"never\";\n /** The session cookie's lifetime. Default 7 days. */\n sessionMaxAgeSeconds?: number;\n /** Refresh when fewer than this many seconds remain. Default 60. */\n refreshSkewSeconds?: number;\n /** Defaults to the global `fetch`. */\n fetch?: typeof fetch;\n /** Where the SDK reports a failed refresh or sign-in. Defaults to `console`. */\n logger?: Pick<Console, \"warn\">;\n}\n\nexport interface ResolvedConfig {\n /** `server`: a confidential app holding its own session. `browser`: the browser SDK's session, read. */\n mode: \"server\" | \"browser\";\n authPath: string;\n issuer: string;\n clientId: string;\n clientSecret?: string;\n sessionSecret: string;\n baseUrl?: string;\n scopes: string;\n basePath: string;\n redirectUri?: string;\n signInPath: string;\n afterSignInPath: string;\n prompt?: string;\n cookieName: string;\n secureCookies?: boolean;\n iframeSafe: boolean | \"auto\";\n previewCallback: \"auto\" | \"always\" | \"never\";\n sessionMaxAgeSeconds: number;\n refreshSkewSeconds: number;\n fetch: typeof fetch;\n logger: Pick<Console, \"warn\">;\n}\n\nconst SEVEN_DAYS = 7 * 24 * 60 * 60;\n\nexport function resolveConfig(config: ServerAuthConfig): ResolvedConfig {\n const mode = config.clientSecret ? \"server\" : \"browser\";\n\n const required: (keyof ServerAuthConfig)[] = [\"issuer\", \"clientId\"];\n if (mode === \"server\") required.push(\"sessionSecret\");\n for (const key of required) {\n if (!config[key]) {\n const env = { issuer: \"PONTIVE_ISSUER\", clientId: \"PONTIVE_CLIENT_ID\", sessionSecret: \"PONTIVE_SESSION_SECRET\" }[key as string];\n throw new Error(`@pontive/server: ${key} is required${env ? ` (pass it, or set ${env})` : \"\"}`);\n }\n }\n\n if (mode === \"server\" && config.sessionSecret!.length < 32) {\n throw new Error(\"@pontive/server: sessionSecret must be at least 32 characters\");\n }\n\n if (config.baseUrl) {\n try {\n new URL(config.baseUrl);\n } catch {\n throw new Error(`@pontive/server: baseUrl \"${config.baseUrl}\" is not an absolute URL`);\n }\n }\n\n return {\n mode,\n authPath: (config.authPath ?? \"/__pontive\").replace(/\\/+$/, \"\"),\n issuer: config.issuer!.replace(/\\/+$/, \"\"),\n clientId: config.clientId!,\n clientSecret: config.clientSecret || undefined,\n sessionSecret: config.sessionSecret ?? \"\",\n baseUrl: config.baseUrl ? new URL(config.baseUrl).origin : undefined,\n scopes: config.scopes ?? \"openid email profile offline_access\",\n basePath: (config.basePath ?? \"/api/auth\").replace(/\\/+$/, \"\"),\n redirectUri: config.redirectUri,\n signInPath: config.signInPath ?? \"/login\",\n afterSignInPath: config.afterSignInPath ?? \"/\",\n prompt: config.prompt,\n cookieName: config.cookieName ?? \"pontive_session\",\n secureCookies: config.secureCookies,\n iframeSafe: config.iframeSafe ?? \"auto\",\n previewCallback: config.previewCallback ?? \"auto\",\n sessionMaxAgeSeconds: config.sessionMaxAgeSeconds ?? SEVEN_DAYS,\n refreshSkewSeconds: config.refreshSkewSeconds ?? 60,\n fetch: config.fetch ?? ((...args) => fetch(...args)),\n logger: config.logger ?? console,\n };\n}\n","/**\n * Cookie reading and writing, on plain header strings so it runs anywhere a\n * Web `Request`/`Response` does.\n *\n * A sealed session outgrows one cookie (browsers cap each at about 4 KB, and an\n * access token, a refresh token and a user fit in about 3–5), so it is split\n * across numbered chunks: `name`, `name.1`, `name.2`, … and joined on read.\n */\n\n/** Characters per chunk, leaving room under the ~4096-byte cap for the name and attributes. */\nexport const CHUNK_SIZE = 3500;\n/** Upper bound on chunks probed when reading or clearing. */\nexport const MAX_CHUNKS = 16;\n\nexport interface CookieAttributes {\n /** Seconds; 0 deletes the cookie. */\n maxAge: number;\n secure: boolean;\n /**\n * `Lax` unless said otherwise. `None` is for a page inside an app builder's\n * preview iframe, where the browser withholds a Lax cookie from every\n * request (`ServerAuthConfig.iframeSafe`); it is always `Secure`.\n */\n sameSite?: \"Lax\" | \"None\";\n}\n\n/** Parses a `Cookie` request header into name → value. */\nexport function parseCookies(header: string | null | undefined): Map<string, string> {\n const out = new Map<string, string>();\n if (!header) return out;\n\n for (const part of header.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq < 0) continue;\n\n const name = part.slice(0, eq).trim();\n if (!name || out.has(name)) continue;\n\n out.set(name, part.slice(eq + 1).trim());\n }\n\n return out;\n}\n\n/** Serialises a `Cookie` request header from name → value. */\nexport function formatCookieHeader(cookies: Map<string, string>): string {\n return [...cookies].map(([name, value]) => `${name}=${value}`).join(\"; \");\n}\n\n/**\n * A `Set-Cookie` value. Always HttpOnly, host-only and `Path=/`, and\n * `SameSite=Lax` unless `attrs` say `None`: Lax is what lets the cookie ride\n * the top-level redirect back from the sign-in page, and nothing here is ever\n * for script. `SameSite=None` is always `Secure`, as browsers require.\n *\n * Never `Partitioned`: a preview signs in through a popup, a top-level window\n * whose cookies are keyed to the app's own site, and a partitioned cookie\n * written there would be invisible to the same app framed under the\n * builder's site.\n */\nexport function serializeCookie(name: string, value: string, attrs: CookieAttributes): string {\n const sameSite = attrs.sameSite ?? \"Lax\";\n const parts = [`${name}=${value}`, \"Path=/\", \"HttpOnly\", `SameSite=${sameSite}`, `Max-Age=${attrs.maxAge}`];\n if (attrs.secure || sameSite === \"None\") parts.push(\"Secure\");\n\n return parts.join(\"; \");\n}\n\nexport function chunkName(name: string, index: number): string {\n return index === 0 ? name : `${name}.${index}`;\n}\n\n/** Joins a chunked value, or null when its first chunk is absent. */\nexport function readChunked(cookies: Map<string, string>, name: string): string | null {\n const first = cookies.get(name);\n if (first === undefined) return null;\n\n let value = first;\n for (let i = 1; i < MAX_CHUNKS; i++) {\n const part = cookies.get(chunkName(name, i));\n if (part === undefined) break;\n value += part;\n }\n\n return value;\n}\n\n/**\n * The `Set-Cookie` values that store `value` in chunks, and delete any chunk\n * the request carried beyond what it now needs. Also updates `cookies` in\n * place, so a caller can forward the new state on the same request.\n */\nexport function writeChunked(\n cookies: Map<string, string>,\n name: string,\n value: string,\n attrs: CookieAttributes,\n): string[] {\n const out: string[] = [];\n const count = Math.max(1, Math.ceil(value.length / CHUNK_SIZE));\n\n for (let i = 0; i < count; i++) {\n const chunk = value.slice(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE);\n cookies.set(chunkName(name, i), chunk);\n out.push(serializeCookie(chunkName(name, i), chunk, attrs));\n }\n\n for (let i = count; i < MAX_CHUNKS; i++) {\n const stale = chunkName(name, i);\n if (!cookies.has(stale)) break;\n cookies.delete(stale);\n out.push(serializeCookie(stale, \"\", { ...attrs, maxAge: 0 }));\n }\n\n return out;\n}\n\n/** The `Set-Cookie` values that delete every chunk the request carried. */\nexport function clearChunked(\n cookies: Map<string, string>,\n name: string,\n attrs: Omit<CookieAttributes, \"maxAge\">,\n): string[] {\n const out: string[] = [];\n\n for (let i = 0; i < MAX_CHUNKS; i++) {\n const chunk = chunkName(name, i);\n if (!cookies.has(chunk)) {\n if (i > 0) break;\n continue;\n }\n cookies.delete(chunk);\n out.push(serializeCookie(chunk, \"\", { ...attrs, maxAge: 0 }));\n }\n\n return out;\n}\n","import { decodeJwt } from \"jose\";\n\n/**\n * The organization a session acts in, as its access token states it. Roles\n * and permissions are the user's effective ones there, which the auth server\n * resolves afresh on every refresh.\n */\nexport interface Organization {\n id: string;\n /**\n * Every role the user effectively holds there. There is no single \"role\":\n * a member can hold several and roles have no precedence, so check for the\n * one you need.\n */\n roles: string[];\n permissions: string[];\n}\n\n/** The route, under `basePath`, that moves a session to another organization. */\nexport const SWITCH_ORGANIZATION_ROUTE = \"switch-organization\";\n\n/**\n * Why a switch did not happen, on the return path as `organization_error`:\n * `not_a_member` when the user cannot act in that organization.\n */\nexport const ORGANIZATION_ERROR_PARAM = \"organization_error\";\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : [];\n\n/** The organization in a set of access-token claims, or null for none. */\nexport function organizationFromClaims(claims: Record<string, unknown>): Organization | null {\n const id = claims.org_id;\n if (typeof id !== \"string\" || id === \"\") return null;\n\n return {\n id,\n roles: strings(claims.roles),\n permissions: strings(claims.permissions),\n };\n}\n\n/**\n * An access token's claims, or none when it is not a JWT. The token is read,\n * not verified: this is only ever called on a token that was verified, or\n * that came straight from the token endpoint over TLS.\n */\nexport function claimsFromToken(accessToken: string): Record<string, unknown> {\n try {\n return decodeJwt(accessToken);\n } catch {\n return {};\n }\n}\n\n/**\n * The path a browser is sent to, on this app, to switch organization and\n * then land on `returnTo`. Link to it, or redirect to it from a server action.\n */\nexport function switchOrganizationPath(basePath: string, organizationId: string, returnTo = \"/\"): string {\n const params = new URLSearchParams({ organization_id: organizationId, returnTo });\n\n return `${basePath}/${SWITCH_ORGANIZATION_ROUTE}?${params.toString()}`;\n}\n","import type { JWTPayload } from \"jose\";\n\nimport type { ResolvedConfig } from \"./config\";\nimport { parseCookies } from \"./cookies\";\nimport { sha256Hex, userInfo, verifyJwt, type ClientCredentials } from \"./oidc\";\nimport { organizationFromClaims, SWITCH_ORGANIZATION_ROUTE } from \"./organization\";\nimport type { CoreAuth, RefreshOutcome, Session, SessionUser } from \"./server-auth\";\n\n/**\n * Server-side sessions for an app whose browser holds the session: a regular\n * app, or a public oauth app, on the browser SDK.\n *\n * The browser SDK signs the user in and is the only thing that ever spends the\n * refresh token. The auth server, reached through the auth proxy on this app's\n * origin, keeps an HttpOnly cookie holding the current access token. The server\n * reads and verifies that cookie, and nothing more — so there is exactly one\n * refresher per session, and rotation never sees a token spent twice.\n *\n * When a page navigation arrives with no live access token but with the\n * session marker, the access token has lapsed while the user is still signed\n * in (the tab was closed, or idle past its refresh). The browser is sent\n * through the auth server's session handshake, which renews the cookies and\n * brings it straight back.\n */\n\n/** The access token, written by the auth server wherever it writes the refresh cookie. */\nexport const ACCESS_COOKIE = \"__Host-pontive_access\";\n/** The readable marker: the browser holds a refresh token. */\nexport const SESSION_HINT_COOKIE = \"__Secure-pontive_session_state\";\n\nfunction userFrom(claims: Record<string, unknown>): SessionUser {\n const str = (key: string) => (typeof claims[key] === \"string\" ? (claims[key] as string) : undefined);\n\n return {\n id: str(\"sub\") ?? \"\",\n email: str(\"email\"),\n name: str(\"name\") ?? str(\"email\"),\n username: str(\"preferred_username\"),\n picture: str(\"picture\"),\n emailVerified: claims.email_verified === true,\n };\n}\n\nexport function createBrowserAuth(cfg: ResolvedConfig): CoreAuth {\n const client: ClientCredentials = { issuer: cfg.issuer, clientId: cfg.clientId };\n\n // Profiles by access token, until the token expires. An access token carries\n // who the user is (sub) but not their email or name, so the profile comes\n // from userinfo — once per token per process, not once per request. Keyed by\n // a hash so the map never holds a live credential.\n const profiles = new Map<string, { expiresAt: number; profile: Promise<Record<string, unknown> | null> }>();\n\n function sweep(now: number) {\n for (const [key, entry] of profiles) {\n if (entry.expiresAt <= now) profiles.delete(key);\n }\n }\n\n async function profileFor(token: string, expiresAt: number): Promise<Record<string, unknown> | null> {\n const now = Date.now();\n sweep(now);\n\n const key = await sha256Hex(token);\n const cached = profiles.get(key);\n if (cached) return cached.profile;\n\n const profile = userInfo(client, cfg.fetch, token).catch((err: unknown) => {\n // The session is valid without a profile: fall back to what the token\n // says, and let the next request try again.\n profiles.delete(key);\n cfg.logger.warn(\"[pontive] could not read the user's profile:\", err instanceof Error ? err.message : String(err));\n return null;\n });\n profiles.set(key, { expiresAt, profile });\n\n return profile;\n }\n\n async function read(cookieHeader: string | null | undefined): Promise<Session | null> {\n const token = parseCookies(cookieHeader).get(ACCESS_COOKIE);\n if (!token) return null;\n\n let claims: JWTPayload;\n try {\n claims = await verifyJwt(client, cfg.fetch, token);\n } catch (err) {\n // An expired token is the ordinary case — the handshake renews it — and\n // not worth a warning. Anything else is.\n if ((err as { code?: string }).code !== \"ERR_JWT_EXPIRED\") {\n cfg.logger.warn(\"[pontive] access token cookie refused:\", err instanceof Error ? err.message : String(err));\n }\n\n return null;\n }\n\n const expiresAt = (claims.exp ?? 0) * 1000;\n const profile = await profileFor(token, expiresAt);\n\n return {\n // The token's own claims win for sub: the profile describes the user the\n // token names, never another one.\n user: userFrom({ ...profile, ...claims, sub: claims.sub }),\n accessToken: token,\n expiresAt,\n sessionId: typeof claims.sid === \"string\" ? claims.sid : undefined,\n organization: organizationFromClaims(claims),\n claims,\n };\n }\n\n return {\n // Sign-in and sign-out belong to the browser SDK's widgets in this mode.\n // Switching organization is the one route: the browser is sent through\n // the auth server's session handshake with the organization, which renews\n // its cookies into it — the browser stays the only thing that spends the\n // refresh token. A refused switch comes back with organization_error.\n async handle(request) {\n const url = new URL(request.url);\n if (url.pathname !== `${cfg.basePath}/${SWITCH_ORGANIZATION_ROUTE}`) return null;\n\n const organizationId = url.searchParams.get(\"organization_id\");\n const returnTo = safeReturnPath(url.searchParams.get(\"returnTo\"));\n\n // Same-origin paths, never absolute URLs built from request.url: behind a\n // proxy or in a container that is the server's own address (0.0.0.0:3000),\n // not the host the browser used. A route handler may answer with a\n // relative Location; the browser resolves it against the page it is on.\n if (!organizationId) return redirectTo(returnTo);\n\n const handshake = new URL(`${cfg.authPath}/oauth2/session`, url.origin);\n handshake.searchParams.set(\"client_id\", cfg.clientId);\n handshake.searchParams.set(\"return_to\", returnTo);\n handshake.searchParams.set(\"organization_id\", organizationId);\n\n return redirectTo(handshake.pathname + handshake.search);\n },\n\n getSession: read,\n\n async refresh(request) {\n const cookieHeader = request.headers.get(\"cookie\");\n const session = await read(cookieHeader);\n const outcome: RefreshOutcome = { session, setCookies: [], cookieHeader: cookieHeader ?? \"\" };\n\n if (session || !parseCookies(cookieHeader).has(SESSION_HINT_COOKIE)) return outcome;\n\n // Signed in, but the access token has lapsed. Never refreshed here: the\n // browser goes through the handshake, so the browser stays the only\n // thing that spends the refresh token.\n const url = new URL(request.url);\n const handshake = new URL(`${cfg.authPath}/oauth2/session`, url.origin);\n handshake.searchParams.set(\"client_id\", cfg.clientId);\n handshake.searchParams.set(\"return_to\", url.pathname + url.search);\n\n return { ...outcome, handshake: handshake.pathname + handshake.search };\n },\n };\n}\n\n/** Only a same-origin path may be returned to: no open redirect. */\nfunction safeReturnPath(value: string | null): string {\n if (value && value.startsWith(\"/\") && !value.startsWith(\"//\") && !value.startsWith(\"/\\\\\")) return value;\n return \"/\";\n}\n\nfunction redirectTo(location: string): Response {\n return new Response(null, { status: 302, headers: { location, \"cache-control\": \"no-store\" } });\n}\n","/**\n * App builders' preview hosts (pontive-spec 06, *SDK in builder previews*):\n * Lovable, v0, Replit, Bolt and CodeSandbox show an app's preview inside an\n * iframe on their own site, so a page served on one of these is assumed to be\n * framed. The same list as `@pontive/oidc-client`'s\n * `BUILDER_PREVIEW_HOST_SUFFIXES`; keep them together.\n */\nexport const BUILDER_PREVIEW_HOST_SUFFIXES: readonly string[] = [\n \"lovable.app\",\n \"lovableproject.com\",\n \"lovable.dev\",\n \"vusercontent.net\",\n \"v0.dev\",\n \"v0.app\",\n \"webcontainer-api.io\",\n \"webcontainer.io\",\n \"replit.dev\",\n \"replit.app\",\n \"lp.dev\",\n \"bolt.host\",\n \"csb.app\",\n];\n\n/** Whether `hostname` is a builder preview host or below one. */\nexport function isBuilderPreviewHost(hostname: string): boolean {\n const host = hostname.toLowerCase().replace(/\\.$/, \"\");\n return BUILDER_PREVIEW_HOST_SUFFIXES.some((suffix) => host === suffix || host.endsWith(`.${suffix}`));\n}\n\n/**\n * Each builder preview preset's host patterns, as the app's\n * `builder_previews` setting names them (pontive-spec 06, *Builder\n * previews*): a `*` is exactly one DNS label. The same as identity-svc's\n * `pkg/app/builderpreview.go` and `@pontive/oidc-client`'s\n * `BUILDER_PREVIEW_PRESETS`; keep them together.\n */\nexport const BUILDER_PREVIEW_PRESETS: Readonly<Record<string, readonly string[]>> = {\n lovable: [\"*.lovableproject.com\", \"*.lovable.app\", \"*.lovable.dev\"],\n v0: [\"*.vusercontent.net\", \"*.lite.vusercontent.net\", \"*.v0.app\", \"*.v0.dev\"],\n vercel: [\"*.vercel.app\"],\n replit: [\"*.replit.dev\", \"*.*.replit.dev\", \"*.replit.app\"],\n bolt: [\n \"*.bolt.host\",\n \"*.webcontainer-api.io\",\n \"*.local-credentialless.webcontainer-api.io\",\n \"*.local-corp.webcontainer-api.io\",\n ],\n codesandbox: [\"*.csb.app\"],\n};\n\n/** The hosted preview callback's path on the auth domain. */\nexport const PREVIEW_CALLBACK_PATH = \"/oauth2/preview-callback\";\n\n/** The `type` of the message the hosted preview callback posts its opener. */\nexport const AUTHORIZATION_RESPONSE_MESSAGE_TYPE = \"pontive:authorization-response\";\n\nconst LABEL = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n\n/**\n * The builder preview preset whose hosts `origin` is on, or `null`: an https\n * origin on the default port whose host matches one of its patterns.\n */\nexport function builderPreviewPreset(origin: string): string | null {\n let url: URL;\n try {\n url = new URL(origin);\n } catch {\n return null;\n }\n if (url.protocol !== \"https:\" || url.port !== \"\" || url.origin !== origin) return null;\n\n const got = url.hostname.split(\".\");\n for (const [preset, patterns] of Object.entries(BUILDER_PREVIEW_PRESETS)) {\n for (const pattern of patterns) {\n const want = pattern.split(\".\");\n if (want.length === got.length && want.every((label, i) => (label === \"*\" ? LABEL.test(got[i]) : label === got[i]))) {\n return preset;\n }\n }\n }\n return null;\n}\n\n/**\n * The `redirect_uri` of a sign-in on the preview at `origin`: the hosted\n * preview callback on `issuer`, in exactly the spelling the auth domain\n * admits, which the token request repeats.\n */\nexport function previewCallbackRedirectUri(issuer: string, origin: string): string {\n return `${issuer.replace(/\\/$/, \"\")}${PREVIEW_CALLBACK_PATH}?origin=${encodeURIComponent(origin)}`;\n}\n","import { sha256Hex } from \"./oidc\";\n\n/**\n * One refresh per session, however many requests ask for it.\n *\n * With rotation on, every refresh spends the token it presents. A page that\n * fires several requests the moment its access token expires would otherwise\n * refresh once per request, and every request after the first would present a\n * token the first had already spent — which the issuer reads as theft.\n *\n * Two layers, in this process:\n *\n * - In flight: requests for the same refresh token share one call.\n * - Recently done: a request that arrives a moment later still holding the old\n * cookie (its browser had not yet stored the new one) is handed the same\n * result rather than spending the old token again.\n *\n * Across processes — several replicas of the app — the issuer's reuse grace\n * window covers the same race, so no shared lock is needed.\n */\n\n/** How long a result is handed to late arrivals. Matches the issuer's grace window. */\nexport const RECENT_RESULT_MS = 30_000;\n\nexport class RefreshCoordinator<T> {\n private readonly inFlight = new Map<string, Promise<T>>();\n private readonly recent = new Map<string, { at: number; result: T }>();\n\n constructor(private readonly recentMs: number = RECENT_RESULT_MS) {}\n\n async run(refreshToken: string, refresh: () => Promise<T>): Promise<T> {\n const key = await sha256Hex(refreshToken);\n this.sweep();\n\n const done = this.recent.get(key);\n if (done) return done.result;\n\n let pending = this.inFlight.get(key);\n if (!pending) {\n pending = refresh()\n .then((result) => {\n this.recent.set(key, { at: Date.now(), result });\n return result;\n })\n .finally(() => this.inFlight.delete(key));\n this.inFlight.set(key, pending);\n }\n\n return pending;\n }\n\n private sweep(): void {\n const cutoff = Date.now() - this.recentMs;\n for (const [key, entry] of this.recent) {\n if (entry.at < cutoff) this.recent.delete(key);\n }\n }\n}\n","import { EncryptJWT, jwtDecrypt } from \"jose\";\n\n/**\n * Sealing: authenticated encryption (JWE, `dir` + A256GCM) of whatever the\n * server stores in a cookie. The browser holds ciphertext it can neither read\n * nor alter, which is what lets a refresh token live in a cookie at all.\n */\n\nconst keys = new Map<string, Promise<Uint8Array>>();\n\n/** A 256-bit key derived from the configured secret, whatever its length. */\nfunction keyFor(secret: string): Promise<Uint8Array> {\n let key = keys.get(secret);\n if (!key) {\n key = crypto.subtle\n .digest(\"SHA-256\", new TextEncoder().encode(secret))\n .then((digest) => new Uint8Array(digest));\n keys.set(secret, key);\n }\n\n return key;\n}\n\nexport async function seal(payload: Record<string, unknown>, secret: string, maxAgeSeconds: number): Promise<string> {\n return new EncryptJWT(payload)\n .setProtectedHeader({ alg: \"dir\", enc: \"A256GCM\" })\n .setIssuedAt()\n .setExpirationTime(`${maxAgeSeconds}s`)\n .encrypt(await keyFor(secret));\n}\n\n/** The payload, or null when the value is not one this secret sealed, or has expired. */\nexport async function unseal<T>(value: string, secret: string): Promise<T | null> {\n try {\n const { payload } = await jwtDecrypt(value, await keyFor(secret));\n return payload as T;\n } catch {\n return null;\n }\n}\n","import type { JWTPayload } from \"jose\";\n\nimport { createBrowserAuth } from \"./browser-mode\";\nimport { resolveConfig, type ResolvedConfig, type ServerAuthConfig } from \"./config\";\nimport {\n clearChunked,\n type CookieAttributes,\n formatCookieHeader,\n parseCookies,\n readChunked,\n serializeCookie,\n writeChunked,\n} from \"./cookies\";\nimport {\n authorizationUrl,\n endSessionUrl,\n exchangeCode,\n pkceChallenge,\n randomValue,\n refreshTokens,\n TokenEndpointError,\n verifyIdToken,\n type ClientCredentials,\n type TokenResponse,\n} from \"./oidc\";\nimport {\n AUTHORIZATION_RESPONSE_MESSAGE_TYPE,\n builderPreviewPreset,\n isBuilderPreviewHost,\n previewCallbackRedirectUri,\n} from \"./preview-hosts\";\nimport { RefreshCoordinator } from \"./refresh\";\nimport { seal, unseal } from \"./seal\";\nimport {\n ORGANIZATION_ERROR_PARAM,\n claimsFromToken,\n organizationFromClaims,\n SWITCH_ORGANIZATION_ROUTE,\n type Organization,\n} from \"./organization\";\n\nexport interface SessionUser {\n id: string;\n email?: string;\n name?: string;\n username?: string;\n picture?: string;\n emailVerified: boolean;\n}\n\n/** What `getSession` hands the app. */\nexport interface Session {\n user: SessionUser;\n /** A valid access token, for calling APIs as this user. */\n accessToken: string;\n /** When the access token expires, epoch milliseconds. */\n expiresAt: number;\n /** The issuer's session id (`sid`), when it sent one. */\n sessionId?: string;\n /**\n * The organization the session acts in, or null for none: every B2C\n * session, and a B2B one whose app has not picked an organization. Move it\n * with the `switch-organization` route (`switchOrganizationPath`).\n */\n organization: Organization | null;\n /**\n * Every claim of the access token: the claims template's (say\n * `legacy_user_id`) beside the standard ones the fields above are read\n * from. A claim is whatever the issuer wrote, so check its type before\n * using it:\n *\n * ```ts\n * const legacyId = typeof session.claims.legacy_user_id === \"string\" ? session.claims.legacy_user_id : undefined;\n * ```\n */\n claims: Record<string, unknown>;\n}\n\n/** What the cookie holds: the session plus the refresh token, which the app never sees. */\ninterface StoredSession extends Omit<Session, \"organization\" | \"claims\"> {\n refreshToken?: string;\n}\n\n/** A sign-in in progress, sealed into its own short-lived cookie. */\ninterface SignInTransaction {\n state: string;\n verifier: string;\n nonce: string;\n returnTo: string;\n /** Started in a popup (`login?popup=1`): the callback hands back to the opener rather than redirecting. */\n popup?: boolean;\n /**\n * The redirect_uri the authorization request named, which the token request\n * repeats: the auth domain's hosted preview callback for a sign-in on an\n * app builder's preview, which the page that opened the popup forwards to\n * the callback route itself.\n */\n redirectUri?: string;\n /** The redirect_uri was the hosted preview callback. */\n previewCallback?: boolean;\n}\n\n/** What a refresh produced, for the middleware to apply. */\nexport interface RefreshOutcome {\n /** The session after the refresh, or null when there is none (or it could not be refreshed). */\n session: Session | null;\n /** `Set-Cookie` values for the response. Empty when nothing changed. */\n setCookies: string[];\n /**\n * The request's `Cookie` header as it should be seen by whatever handles\n * this request next, carrying the refreshed session. Forward it, so a page\n * rendered on this very request reads the new token rather than the expired\n * one the browser sent.\n */\n cookieHeader: string;\n /**\n * Set when a signed-in browser's access token has lapsed and it must go\n * through the auth server's session handshake to renew it — browser mode\n * only. A path on this app's origin. Send a page navigation there; any other\n * request just proceeds without a session.\n */\n handshake?: string;\n}\n\nexport interface ServerAuth {\n /**\n * Handles the SDK's routes under `basePath`: `/login`, `/callback` and\n * `/logout`. Null for any other path.\n */\n handle(request: Request): Promise<Response | null>;\n /**\n * The session in a `Cookie` header, or null. Read-only and never refreshes:\n * any server code can call it, including code that cannot set cookies.\n * Returns null for a session whose access token has expired — `refresh`,\n * run in middleware ahead of the request, is what keeps it current.\n */\n getSession(cookieHeader: string | null | undefined): Promise<Session | null>;\n /**\n * Refreshes the session when its access token is about to expire. For\n * middleware: it runs before anything renders, and its response can always\n * carry the new cookie. Concurrent calls for one session share one refresh.\n */\n refresh(request: Request): Promise<RefreshOutcome>;\n /**\n * What the app's `<Provider>` needs, from the server: the app's id (so no\n * `NEXT_PUBLIC_` copy of it is needed), the auth domain, and, while the\n * instance is an unclaimed one this project created (keyless mode), the\n * claim route for the development banner's *Claim it*. Render the provider\n * with them from server code.\n */\n providerProps(): Promise<ProviderProps>;\n}\n\n/** `<Provider>`'s inputs the server knows (`appId`, `domain`, `claimUrl`). */\nexport interface ProviderProps {\n appId: string;\n /** The issuer (confidential mode), or the auth proxy's path on this origin (browser mode). */\n domain: string;\n /** `{basePath}/claim`, only while this project's keyless instance is unclaimed. */\n claimUrl?: string;\n}\n\nconst DEFAULT_ACCESS_TTL_SECONDS = 900;\nconst TRANSACTION_MAX_AGE = 600;\n\n/** Only a same-origin path may be returned to after sign-in: no open redirect. */\nfunction safePath(value: string | null | undefined, fallback: string): string {\n if (value && value.startsWith(\"/\") && !value.startsWith(\"//\") && !value.startsWith(\"/\\\\\")) return value;\n return fallback;\n}\n\nfunction redirect(location: string, setCookies: string[] = []): Response {\n const headers = new Headers({ location, \"cache-control\": \"no-store\" });\n for (const cookie of setCookies) headers.append(\"set-cookie\", cookie);\n\n return new Response(null, { status: 302, headers });\n}\n\n/** The `type` of the message a sign-in popup sends its opener: `@pontive/oidc-client`'s `POPUP_MESSAGE_TYPE`. */\nexport const POPUP_MESSAGE_TYPE = \"pontive:popup-complete\";\n\n/**\n * The end of a sign-in that ran in a popup (`login?popup=1`): an app\n * builder's preview, framed on the builder's site, cannot send itself to the\n * sign-in page (pontive-spec 06, *SDK in builder previews*). The page hands\n * `location` — where a redirect would have gone, on this app's origin — to\n * the window that opened it, by `postMessage` to `origin` only, and closes.\n * Opened without an opener (the user went to the URL directly), it goes\n * there itself.\n *\n * The data rides in a JSON block whose `<` is escaped, so nothing in it can\n * end the script; the script itself is fixed.\n */\nfunction popupResponse(location: string, origin: string, setCookies: string[]): Response {\n const data = JSON.stringify({ message: { type: POPUP_MESSAGE_TYPE, url: location }, origin }).replace(/</g, \"\\\\u003c\");\n const body =\n `<!doctype html><meta charset=\"utf-8\"><title>Signing in</title>` +\n `<script type=\"application/json\" id=\"pontive-popup\">${data}</script>` +\n `<script>(function(){var d=JSON.parse(document.getElementById(\"pontive-popup\").textContent);` +\n `var go=function(){window.location.replace(d.message.url)};` +\n `if(window.opener&&window.opener!==window){try{window.opener.postMessage(d.message,d.origin)}catch(e){}` +\n `window.close();setTimeout(go,1000)}else{go()}})()</script>`;\n\n const headers = new Headers({\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": \"default-src 'none'; script-src 'unsafe-inline'\",\n \"x-content-type-options\": \"nosniff\",\n });\n for (const cookie of setCookies) headers.append(\"set-cookie\", cookie);\n\n return new Response(body, { status: 200, headers });\n}\n\n/**\n * The page a sign-in on an app builder's preview starts from when it was not\n * opened in a popup (pontive-spec 06, *Builder previews*): the hosted preview\n * callback hands the authorization response to the window that opened the\n * popup, so this page opens it, inside the click, and is that window. It\n * takes the response only from that popup on the auth domain's origin,\n * forwards it to the callback route on this origin, and goes there.\n *\n * The script is fixed and runs by nonce; the data rides in a JSON block whose\n * `<` is escaped.\n */\nfunction previewSignInPage(data: { popupUrl: string; authOrigin: string; callbackUrl: string }): Response {\n const nonce = randomValue();\n const json = JSON.stringify({ ...data, type: AUTHORIZATION_RESPONSE_MESSAGE_TYPE }).replace(/</g, \"\\\\u003c\");\n const body =\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">` +\n `<title>Sign in</title>` +\n `<style>body{font-family:system-ui,sans-serif;margin:4rem auto;max-width:28rem;padding:0 1rem}</style>` +\n `<p>This preview signs in in a new window.</p><p><button id=\"go\" type=\"button\">Sign in</button></p><p id=\"status\"></p>` +\n `<script type=\"application/json\" id=\"pontive-preview-signin\">${json}</script>` +\n `<script nonce=\"${nonce}\">(function(){var d=JSON.parse(document.getElementById(\"pontive-preview-signin\").textContent);` +\n `var s=document.getElementById(\"status\");var w=null;` +\n `window.addEventListener(\"message\",function(e){if(!w||e.source!==w||e.origin!==d.authOrigin)return;` +\n `var m=e.data;if(!m||m.type!==d.type||!m.response||typeof m.response!==\"object\")return;` +\n `var u=new URL(d.callbackUrl);[\"code\",\"state\",\"iss\",\"error\",\"error_description\",\"error_uri\"].forEach(function(k){` +\n `var v=m.response[k];if(typeof v===\"string\")u.searchParams.set(k,v)});try{w.close()}catch(x){}` +\n `if(u.origin===location.origin)location.replace(u.toString())});` +\n `document.getElementById(\"go\").addEventListener(\"click\",function(){` +\n `w=window.open(d.popupUrl,\"pontive_signin_popup\",\"popup=yes,width=500,height=680\");` +\n `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>`;\n\n return new Response(body, {\n status: 200,\n headers: {\n \"content-type\": \"text/html; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"content-security-policy\": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'`,\n \"x-content-type-options\": \"nosniff\",\n \"referrer-policy\": \"no-referrer\",\n },\n });\n}\n\nfunction publicOrigin(cfg: ResolvedConfig, request: Request): string {\n if (cfg.baseUrl) return cfg.baseUrl;\n\n const host = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim() || request.headers.get(\"host\")?.trim();\n if (host) {\n const proto =\n request.headers.get(\"x-forwarded-proto\")?.split(\",\")[0]?.trim() || new URL(request.url).protocol.replace(\":\", \"\");\n try {\n return new URL(`${proto}://${host}`).origin;\n } catch {\n // Fall through to the request URL.\n }\n }\n\n return new URL(request.url).origin;\n}\n\nfunction userFrom(claims: JWTPayload): SessionUser {\n const str = (key: string) => (typeof claims[key] === \"string\" ? (claims[key] as string) : undefined);\n const name =\n str(\"name\") ?? ([str(\"given_name\"), str(\"family_name\")].filter(Boolean).join(\" \") || undefined) ?? str(\"email\");\n\n return {\n id: claims.sub ?? \"\",\n email: str(\"email\"),\n name,\n username: str(\"preferred_username\"),\n picture: str(\"picture\"),\n emailVerified: claims.email_verified === true,\n };\n}\n\nfunction expiresAtFrom(token: TokenResponse): number {\n return Date.now() + (token.expires_in ?? DEFAULT_ACCESS_TTL_SECONDS) * 1000;\n}\n\n/** What both modes do; `createServerAuth` adds the provider's props and keyless mode's claim route. */\nexport type CoreAuth = Omit<ServerAuth, \"providerProps\">;\n\n/** The auth for a resolved config: the confidential mode's, or the browser SDK's. */\nexport function createCoreAuth(cfg: ResolvedConfig): CoreAuth {\n return cfg.mode === \"browser\" ? createBrowserAuth(cfg) : createSessionAuth(cfg);\n}\n\nfunction createSessionAuth(cfg: ResolvedConfig): CoreAuth {\n const client: ClientCredentials = { issuer: cfg.issuer, clientId: cfg.clientId, clientSecret: cfg.clientSecret };\n const txCookie = `${cfg.cookieName}_tx`;\n const coordinator = new RefreshCoordinator<StoredSession | null>();\n\n const secure = (request: Request) => cfg.secureCookies ?? publicOrigin(cfg, request).startsWith(\"https:\");\n // On an app builder's preview host the page is framed on the builder's\n // site, where a Lax cookie is never sent (ServerAuthConfig.iframeSafe).\n const crossSite = (request: Request) =>\n cfg.iframeSafe === true ||\n (cfg.iframeSafe === \"auto\" && isBuilderPreviewHost(new URL(publicOrigin(cfg, request)).hostname));\n const cookieAttrs = (request: Request, maxAge: number): CookieAttributes =>\n crossSite(request) ? { maxAge, secure: true, sameSite: \"None\" } : { maxAge, secure: secure(request) };\n // An app builder's preview signs in through the auth domain's hosted\n // preview callback (ServerAuthConfig.previewCallback).\n const usesPreviewCallback = (request: Request) =>\n cfg.previewCallback === \"always\" ||\n (cfg.previewCallback === \"auto\" && builderPreviewPreset(publicOrigin(cfg, request)) !== null);\n const callbackUrl = (request: Request) => `${publicOrigin(cfg, request)}${cfg.basePath}/callback`;\n const redirectUri = (request: Request) =>\n usesPreviewCallback(request)\n ? previewCallbackRedirectUri(cfg.issuer, publicOrigin(cfg, request))\n : (cfg.redirectUri ?? callbackUrl(request));\n const toSignIn = (request: Request, error?: string) => {\n const url = new URL(cfg.signInPath, publicOrigin(cfg, request));\n if (error) url.searchParams.set(\"error\", error);\n return url.toString();\n };\n\n async function readStored(cookies: Map<string, string>): Promise<StoredSession | null> {\n const raw = readChunked(cookies, cfg.cookieName);\n if (raw === null) return null;\n\n const stored = await unseal<StoredSession>(raw, cfg.sessionSecret);\n if (!stored) cfg.logger.warn(\"[pontive] session cookie could not be read (sealed with another secret, or truncated)\");\n\n return stored;\n }\n\n async function writeStored(cookies: Map<string, string>, stored: StoredSession, request: Request): Promise<string[]> {\n const sealed = await seal({ ...stored }, cfg.sessionSecret, cfg.sessionMaxAgeSeconds);\n\n return writeChunked(cookies, cfg.cookieName, sealed, cookieAttrs(request, cfg.sessionMaxAgeSeconds));\n }\n\n // The organization and the claims are read from the access token each time\n // rather than stored beside it, so they can never disagree with it.\n function publicSession(stored: StoredSession): Session {\n const { refreshToken: _refreshToken, ...session } = stored;\n const claims = claimsFromToken(stored.accessToken);\n return { ...session, organization: organizationFromClaims(claims), claims };\n }\n\n async function signIn(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const previewCallback = usesPreviewCallback(request);\n const popup = url.searchParams.get(\"popup\") === \"1\";\n\n // On a builder preview the response comes back to the window that opened\n // the popup, so a sign-in not started in one starts from a page that\n // opens it.\n if (previewCallback && !popup) {\n const popupUrl = new URL(`${cfg.basePath}/login`, publicOrigin(cfg, request));\n url.searchParams.forEach((value, key) => popupUrl.searchParams.set(key, value));\n popupUrl.searchParams.set(\"popup\", \"1\");\n\n return previewSignInPage({\n popupUrl: popupUrl.toString(),\n authOrigin: new URL(cfg.issuer).origin,\n callbackUrl: callbackUrl(request),\n });\n }\n\n const tx: SignInTransaction = {\n state: randomValue(),\n verifier: randomValue(),\n nonce: randomValue(),\n returnTo: safePath(url.searchParams.get(\"returnTo\") ?? url.searchParams.get(\"next\"), cfg.afterSignInPath),\n popup,\n redirectUri: redirectUri(request),\n previewCallback,\n };\n\n const location = await authorizationUrl(client, cfg.fetch, {\n redirectUri: tx.redirectUri!,\n scopes: cfg.scopes,\n state: tx.state,\n nonce: tx.nonce,\n codeChallenge: await pkceChallenge(tx.verifier),\n prompt: cfg.prompt,\n // The organization the app wants this sign-in to start in; the user is\n // never asked to pick one.\n organizationId: url.searchParams.get(\"organization_id\") ?? undefined,\n // Pre-fills the sign-in page with the address the user is expected to\n // sign in with — an accepted invitation sends its invitee here with it.\n loginHint: url.searchParams.get(\"login_hint\") ?? undefined,\n });\n\n const sealed = await seal({ ...tx }, cfg.sessionSecret, TRANSACTION_MAX_AGE);\n\n return redirect(location, [serializeCookie(txCookie, sealed, cookieAttrs(request, TRANSACTION_MAX_AGE))]);\n }\n\n async function callback(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n // Single use, whatever happens next.\n const setCookies = [serializeCookie(txCookie, \"\", cookieAttrs(request, 0))];\n\n const raw = cookies.get(txCookie);\n const tx = raw ? await unseal<SignInTransaction>(raw, cfg.sessionSecret) : null;\n const code = url.searchParams.get(\"code\");\n // A sign-in that ran in a popup ends by handing back to its opener —\n // unless it went through the hosted preview callback, which handed back\n // already: this request is the opener's own.\n const finish = (location: string) =>\n tx?.popup && !tx.previewCallback\n ? popupResponse(location, publicOrigin(cfg, request), setCookies)\n : redirect(location, setCookies);\n\n const issuerError = url.searchParams.get(\"error\");\n if (issuerError) return finish(toSignIn(request, issuerError));\n\n if (!tx || !code || url.searchParams.get(\"state\") !== tx.state) {\n return finish(toSignIn(request, \"invalid_state\"));\n }\n\n // A response the page forwarded from the hosted preview callback names\n // its issuer (RFC 9207); one naming another is not this sign-in's.\n const iss = url.searchParams.get(\"iss\");\n if (tx.previewCallback && iss !== null && iss !== cfg.issuer) {\n return finish(toSignIn(request, \"invalid_issuer\"));\n }\n\n try {\n const tokens = await exchangeCode(client, cfg.fetch, {\n code,\n codeVerifier: tx.verifier,\n // Exactly as the authorization request named it.\n redirectUri: tx.redirectUri ?? redirectUri(request),\n });\n if (!tokens.id_token) throw new Error(\"the token response carried no id_token; is the openid scope requested?\");\n\n const claims = await verifyIdToken(client, cfg.fetch, tokens.id_token, tx.nonce);\n const stored: StoredSession = {\n user: userFrom(claims),\n accessToken: tokens.access_token,\n refreshToken: tokens.refresh_token,\n expiresAt: expiresAtFrom(tokens),\n sessionId: typeof claims.sid === \"string\" ? claims.sid : undefined,\n };\n\n setCookies.push(...(await writeStored(cookies, stored, request)));\n } catch (err) {\n cfg.logger.warn(\"[pontive] sign-in failed:\", err instanceof Error ? err.message : String(err));\n return finish(toSignIn(request, \"exchange_failed\"));\n }\n\n return finish(new URL(tx.returnTo, publicOrigin(cfg, request)).toString());\n }\n\n async function signOut(request: Request): Promise<Response> {\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n // Read before clearing: the session holds the sid the issuer's logout needs.\n const stored = await readStored(cookies);\n const setCookies = clearChunked(cookies, cfg.cookieName, cookieAttrs(request, 0));\n\n let location = toSignIn(request);\n try {\n location =\n (await endSessionUrl(client, cfg.fetch, {\n postLogoutRedirectUri: toSignIn(request),\n sessionId: stored?.sessionId,\n })) ?? location;\n } catch (err) {\n // An unreachable issuer must not stop the local sign-out.\n cfg.logger.warn(\"[pontive] could not reach the issuer to end its session:\", err instanceof Error ? err.message : String(err));\n }\n\n return redirect(location, setCookies);\n }\n\n function renewed(stored: StoredSession, tokens: TokenResponse): StoredSession {\n return {\n ...stored,\n accessToken: tokens.access_token,\n // A response without one means rotation is off: the token in hand is still current.\n refreshToken: tokens.refresh_token ?? stored.refreshToken,\n expiresAt: expiresAtFrom(tokens),\n };\n }\n\n /**\n * Moves the session to another organization: a refresh that names it. The\n * user must be able to act there; a refusal leaves the session exactly as it\n * was and tells the app why on its return path, because a refused switch is\n * not a sign-out.\n */\n async function switchOrganization(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n const returnTo = safePath(url.searchParams.get(\"returnTo\"), cfg.afterSignInPath);\n const organizationId = url.searchParams.get(\"organization_id\");\n const back = (error?: string) => {\n const target = new URL(returnTo, publicOrigin(cfg, request));\n if (error) target.searchParams.set(ORGANIZATION_ERROR_PARAM, error);\n return target.toString();\n };\n\n const stored = await readStored(cookies);\n if (!stored?.refreshToken) return redirect(toSignIn(request));\n if (!organizationId) return redirect(back(\"invalid_request\"));\n\n let tokens: TokenResponse;\n try {\n // Not through the coordinator: a switch is not interchangeable with a\n // plain refresh another request may be running for the same token. Both\n // spending it at once is what the auth server's reuse grace is for.\n tokens = await refreshTokens(client, cfg.fetch, stored.refreshToken, organizationId);\n } catch (err) {\n if (err instanceof TokenEndpointError && err.code === \"invalid_request\") {\n return redirect(back(\"not_a_member\"));\n }\n\n cfg.logger.warn(\"[pontive] organization switch failed:\", err instanceof Error ? err.message : String(err));\n return redirect(back(\"switch_failed\"));\n }\n\n return redirect(back(), await writeStored(cookies, renewed(stored, tokens), request));\n }\n\n /**\n * Spends the refresh token once, returning the refreshed session, or null\n * when the issuer refused it for good. Anything transient throws instead, so\n * the coordinator does not hand a passing failure to other requests.\n */\n async function refreshStored(stored: StoredSession): Promise<StoredSession | null> {\n try {\n const tokens = await refreshTokens(client, cfg.fetch, stored.refreshToken!);\n\n return renewed(stored, tokens);\n } catch (err) {\n if (err instanceof TokenEndpointError && err.status >= 400 && err.status < 500) {\n cfg.logger.warn(\"[pontive] refresh refused; signing out:\", err.message);\n return null;\n }\n\n throw err;\n }\n }\n\n return {\n async handle(request) {\n const { pathname } = new URL(request.url);\n if (!pathname.startsWith(`${cfg.basePath}/`)) return null;\n\n const route = pathname.slice(cfg.basePath.length + 1);\n if (route === \"login\" && request.method === \"GET\") return signIn(request);\n if (route === \"callback\" && request.method === \"GET\") return callback(request);\n if (route === \"logout\" && (request.method === \"GET\" || request.method === \"POST\")) return signOut(request);\n if (route === SWITCH_ORGANIZATION_ROUTE && (request.method === \"GET\" || request.method === \"POST\")) {\n return switchOrganization(request);\n }\n\n return null;\n },\n\n async getSession(cookieHeader) {\n const stored = await readStored(parseCookies(cookieHeader));\n if (!stored) return null;\n\n if (Date.now() >= stored.expiresAt) {\n cfg.logger.warn(\n \"[pontive] the session's access token has expired and getSession cannot refresh it. \" +\n \"Run the SDK's middleware on this path so it refreshes before the request is handled.\",\n );\n return null;\n }\n\n return publicSession(stored);\n },\n\n async refresh(request) {\n const cookies = parseCookies(request.headers.get(\"cookie\"));\n const unchanged = (session: Session | null): RefreshOutcome => ({\n session,\n setCookies: [],\n cookieHeader: request.headers.get(\"cookie\") ?? \"\",\n });\n\n const stored = await readStored(cookies);\n if (!stored) return unchanged(null);\n\n // The SDK's own routes manage the session themselves. Refreshing ahead of\n // them only spends a refresh token that sign-out is about to discard, and\n // puts a second session cookie on the response it clears.\n if (new URL(request.url).pathname.startsWith(`${cfg.basePath}/`)) {\n return unchanged(Date.now() < stored.expiresAt ? publicSession(stored) : null);\n }\n\n if (Date.now() < stored.expiresAt - cfg.refreshSkewSeconds * 1000) return unchanged(publicSession(stored));\n\n const signOutNow = (): RefreshOutcome => {\n const setCookies = clearChunked(cookies, cfg.cookieName, cookieAttrs(request, 0));\n return { session: null, setCookies, cookieHeader: formatCookieHeader(cookies) };\n };\n\n if (!stored.refreshToken) return signOutNow();\n\n let refreshed: StoredSession | null;\n try {\n refreshed = await coordinator.run(stored.refreshToken, () => refreshStored(stored));\n } catch (err) {\n // Transient: keep the session and let the next request try again. The\n // token may still have a few seconds of the skew left.\n cfg.logger.warn(\"[pontive] refresh failed, will retry:\", err instanceof Error ? err.message : String(err));\n return unchanged(Date.now() < stored.expiresAt ? publicSession(stored) : null);\n }\n\n if (!refreshed) return signOutNow();\n\n const setCookies = await writeStored(cookies, refreshed, request);\n\n return { session: publicSession(refreshed), setCookies, cookieHeader: formatCookieHeader(cookies) };\n },\n };\n}\n","import { resolveConfig, type ResolvedConfig, type ServerAuthConfig } from \"./config\";\nimport { isDevelopment, keylessApplies, processEnv, withEnvFallback } from \"./env\";\nimport {\n claimLinkFor,\n ENV_FILE,\n ensureKeylessInstance,\n goneMessage,\n KeylessInstanceGoneError,\n keylessMessage,\n KEYLESS_FILE,\n KeylessUnavailableError,\n loopbackCallbacks,\n PontiveApiError,\n readKeylessRecord,\n type KeylessInstance,\n type KeylessRecord,\n} from \"./keyless\";\nimport { createCoreAuth, type CoreAuth, type ProviderProps, type RefreshOutcome, type ServerAuth } from \"./server-auth\";\n\ndeclare const __PONTIVE_SERVER_VERSION__: string;\n\n/** This package's version, sent as `client.version` when keyless mode provisions. */\nexport const PONTIVE_SERVER_VERSION: string = typeof __PONTIVE_SERVER_VERSION__ === \"string\" ? __PONTIVE_SERVER_VERSION__ : \"0.0.0\";\n\n/** Options for framework packages built on this one (@pontive/nextjs). */\nexport interface ServerAuthOptions {\n /** `client.name` when keyless mode provisions an instance. Default `@pontive/server`. */\n clientName?: string;\n /** The project root, where `.env.local` and `.pontive/` live. Default `process.cwd()`. */\n projectDir?: string;\n}\n\n/** The route, under `basePath`, that sends the browser to a claim link (keyless mode). */\nexport const CLAIM_ROUTE = \"claim\";\n\n/**\n * Server-side sessions on Web `Request`/`Response`.\n *\n * Every field of `config` the app leaves out falls back to its `PONTIVE_*`\n * variable (pontive-spec 47 §6.1), so `createServerAuth()` with nothing is a\n * complete setup when the environment holds them. With no issuer anywhere, in\n * development, it runs in **keyless mode** (§6.2): on first use it creates an\n * unclaimed development instance, writes its settings to `.env.local` and\n * `.pontive/keyless.json`, and uses them at once. Outside development a missing\n * issuer is an error, as ever.\n */\nexport function createServerAuth(config: ServerAuthConfig = {}, options: ServerAuthOptions = {}): ServerAuth {\n const env = processEnv();\n const merged = withEnvFallback(config, env);\n if (keylessApplies(merged, env)) return createKeylessAuth(merged, options);\n\n const cfg = resolveConfig(merged);\n // An instance this project created keylessly keeps its claim route after a restart, when the\n // issuer now comes from .env.local: read keyless.json per call, in development only.\n const record = isDevelopment(env) ? () => matchingRecord(projectDir(options), cfg.issuer) : async () => null;\n return withProviderProps(cfg, createCoreAuth(cfg), record);\n}\n\nfunction projectDir(options: ServerAuthOptions): string {\n if (options.projectDir) return options.projectDir;\n const proc = (globalThis as { process?: { cwd?: () => string } }).process;\n if (typeof proc?.cwd !== \"function\") throw new KeylessUnavailableError(\"keyless mode needs a project directory (process.cwd)\");\n return proc.cwd();\n}\n\n/** keyless.json's record when it is this issuer's and still holds its claim token; null otherwise, and wherever it can't be read. */\nasync function matchingRecord(dir: string, issuer: string): Promise<KeylessRecord | null> {\n try {\n const record = await readKeylessRecord(dir);\n return record?.claim_token && record.issuer.replace(/\\/+$/, \"\") === issuer ? record : null;\n } catch {\n return null;\n }\n}\n\n/** The plain-text answer the claim route gives when it can't redirect. */\nfunction text(status: number, body: string): Response {\n return new Response(`${body}\\n`, { status, headers: { \"content-type\": \"text/plain; charset=utf-8\", \"cache-control\": \"no-store\" } });\n}\n\n/**\n * The provider's props, and `{basePath}/claim` while the instance is this\n * project's unclaimed one: it mints a claim link with the claim token kept on\n * the server and sends the browser there. The token never reaches the page.\n */\nfunction withProviderProps(cfg: ResolvedConfig, core: CoreAuth, record: () => Promise<KeylessRecord | null>): ServerAuth {\n const claimPath = `${cfg.basePath}/${CLAIM_ROUTE}`;\n\n async function claim(found: KeylessRecord): Promise<Response> {\n try {\n const link = await claimLinkFor(found, { fetch: cfg.fetch });\n return new Response(null, { status: 302, headers: { location: link.url, \"cache-control\": \"no-store\", \"referrer-policy\": \"no-referrer\" } });\n } catch (err) {\n if (err instanceof PontiveApiError && err.status === 409) {\n return text(409, \"This Pontive instance has already been claimed. Nothing in your app changes; manage it in the Pontive dashboard.\");\n }\n if (err instanceof PontiveApiError && err.status === 404) return text(410, goneMessage(found, \"expired\"));\n cfg.logger.warn(\"[pontive] could not create a claim link:\", err instanceof Error ? err.message : String(err));\n return text(502, \"Pontive could not create a claim link just now. Try again, or run `npx pontive claim`.\");\n }\n }\n\n return {\n async handle(request) {\n if (request.method === \"GET\" && new URL(request.url).pathname === claimPath) {\n const found = await record();\n if (found) return claim(found);\n }\n return core.handle(request);\n },\n getSession: cookieHeader => core.getSession(cookieHeader),\n refresh: request => core.refresh(request),\n async providerProps() {\n const found = await record();\n return {\n appId: cfg.clientId,\n domain: cfg.mode === \"browser\" ? cfg.authPath : cfg.issuer,\n ...(found ? { claimUrl: claimPath } : {}),\n };\n },\n };\n}\n\n/** One provisioning per project directory per process; the file lock covers other processes. */\nconst instances = new Map<string, Promise<KeylessInstance>>();\n/** Directories whose console message this process has printed. */\nconst announced = new Set<string>();\n\n/** Forgets the per-process keyless state. For tests. */\nexport function resetKeylessState(): void {\n instances.clear();\n announced.clear();\n}\n\n/**\n * Keyless mode: everything waits for the instance (`keyless.json`'s, or one\n * created now), which is resolved on the first request rather than here,\n * since creating it needs the network.\n */\nfunction createKeylessAuth(merged: ServerAuthConfig, options: ServerAuthOptions): ServerAuth {\n const logger = merged.logger ?? console;\n let ready: Promise<ServerAuth> | undefined;\n let gone: KeylessInstanceGoneError | undefined;\n let warnedUnavailable = false;\n\n async function setup(): Promise<ServerAuth> {\n const dir = projectDir(options);\n const basePath = (merged.basePath ?? \"/api/auth\").replace(/\\/+$/, \"\");\n let pending = instances.get(dir);\n if (!pending) {\n pending = ensureKeylessInstance({\n dir,\n redirectUris: merged.redirectUri ? [merged.redirectUri] : loopbackCallbacks(basePath),\n client: { name: options.clientName ?? \"@pontive/server\", version: PONTIVE_SERVER_VERSION },\n fetch: merged.fetch,\n });\n instances.set(dir, pending);\n pending.catch(() => instances.delete(dir));\n }\n const instance = await pending;\n\n if (!announced.has(dir)) {\n announced.add(dir);\n logger.warn(`\\n${keylessMessage(instance.record, { created: instance.created })}\\n`);\n }\n\n // Next.js and most dev servers read .env.local only at start: the values are used in-process\n // now, and put in process.env for the app's own code (PONTIVE_SECRET_KEY …) until the restart.\n const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process;\n if (proc?.env) {\n for (const [key, value] of Object.entries(instance.env)) {\n if (value !== undefined && !proc.env[key]) proc.env[key] = value;\n }\n }\n\n if (!merged.clientSecret && !instance.env.PONTIVE_CLIENT_SECRET) {\n throw new Error(\n `@pontive/server: ${KEYLESS_FILE} names ${instance.record.instance_id}, but PONTIVE_CLIENT_SECRET is ` +\n `neither in ${ENV_FILE} nor in the environment. Put it back, or run \\`npx pontive init --reset\\`.`,\n );\n }\n\n const cfg = resolveConfig({\n ...merged,\n issuer: merged.issuer || instance.env.PONTIVE_ISSUER,\n clientId: merged.clientId || instance.env.PONTIVE_CLIENT_ID,\n clientSecret: merged.clientSecret || instance.env.PONTIVE_CLIENT_SECRET,\n sessionSecret: merged.sessionSecret || instance.env.PONTIVE_SESSION_SECRET,\n fetch: watchForRefusal(merged.fetch, instance.record, logger),\n });\n return withProviderProps(cfg, createCoreAuth(cfg), () => matchingRecord(dir, cfg.issuer));\n }\n\n function auth(): Promise<ServerAuth> {\n if (gone) return Promise.reject(gone);\n ready ??= setup().catch((err: unknown) => {\n ready = undefined;\n // Expired is final for this process; anything else (the network, a limit) is tried again next request.\n if (err instanceof KeylessInstanceGoneError) gone = err;\n throw err;\n });\n return ready;\n }\n\n /** An edge runtime (no file system) can't run keyless mode: it proceeds without a session instead. */\n function unavailable(err: unknown): boolean {\n if (!(err instanceof KeylessUnavailableError)) return false;\n if (!warnedUnavailable) {\n warnedUnavailable = true;\n logger.warn(\n `[pontive] ${err.message}. Requests here proceed without a session until the dev server restarts ` +\n \"with the PONTIVE_* variables keyless mode wrote to .env.local.\",\n );\n }\n return true;\n }\n\n return {\n async handle(request) {\n try {\n return await (await auth()).handle(request);\n } catch (err) {\n if (unavailable(err)) return text(503, \"Pontive keyless mode can't run in this runtime; restart the dev server.\");\n throw err;\n }\n },\n async getSession(cookieHeader) {\n try {\n return await (await auth()).getSession(cookieHeader);\n } catch (err) {\n if (unavailable(err)) return null;\n throw err;\n }\n },\n async refresh(request): Promise<RefreshOutcome> {\n try {\n return await (await auth()).refresh(request);\n } catch (err) {\n if (unavailable(err)) return { session: null, setCookies: [], cookieHeader: request.headers.get(\"cookie\") ?? \"\" };\n throw err;\n }\n },\n async providerProps() {\n return (await auth()).providerProps();\n },\n };\n}\n\n/**\n * Says so, once, when the instance refuses the app's credentials (`401` from\n * the token endpoint): it expired, or was claimed and its keys rotated. Keyless\n * mode never creates another instance over it.\n */\nexport function watchForRefusal(base: typeof fetch | undefined, record: KeylessRecord, logger: Pick<Console, \"warn\">): typeof fetch {\n const fetchImpl = base ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let told = false;\n return async (input, init) => {\n const response = await fetchImpl(input, init);\n if (response.status === 401 && !told) {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n if (url.startsWith(record.issuer)) {\n told = true;\n logger.warn(`[pontive] ${goneMessage(record, \"refused\")}`);\n }\n }\n return response;\n };\n}\n"],"names":["SEVEN_DAYS","resolveConfig","config","mode","required","key","env","args","CHUNK_SIZE","MAX_CHUNKS","parseCookies","header","out","part","eq","name","formatCookieHeader","cookies","value","serializeCookie","attrs","sameSite","parts","chunkName","index","readChunked","first","i","writeChunked","count","chunk","stale","clearChunked","SWITCH_ORGANIZATION_ROUTE","ORGANIZATION_ERROR_PARAM","strings","v","organizationFromClaims","claims","id","claimsFromToken","accessToken","decodeJwt","switchOrganizationPath","basePath","organizationId","returnTo","params","ACCESS_COOKIE","SESSION_HINT_COOKIE","userFrom","str","createBrowserAuth","cfg","client","profiles","sweep","now","entry","profileFor","token","expiresAt","sha256Hex","cached","profile","userInfo","err","read","cookieHeader","verifyJwt","request","url","safeReturnPath","redirectTo","handshake","session","outcome","location","BUILDER_PREVIEW_HOST_SUFFIXES","isBuilderPreviewHost","hostname","host","suffix","BUILDER_PREVIEW_PRESETS","PREVIEW_CALLBACK_PATH","AUTHORIZATION_RESPONSE_MESSAGE_TYPE","LABEL","builderPreviewPreset","origin","got","preset","patterns","pattern","want","label","previewCallbackRedirectUri","issuer","RECENT_RESULT_MS","RefreshCoordinator","recentMs","refreshToken","refresh","done","pending","result","cutoff","keys","keyFor","secret","digest","seal","payload","maxAgeSeconds","EncryptJWT","unseal","jwtDecrypt","DEFAULT_ACCESS_TTL_SECONDS","TRANSACTION_MAX_AGE","safePath","fallback","redirect","setCookies","headers","cookie","POPUP_MESSAGE_TYPE","popupResponse","body","previewSignInPage","data","nonce","randomValue","publicOrigin","proto","expiresAtFrom","createCoreAuth","createSessionAuth","txCookie","coordinator","secure","crossSite","cookieAttrs","maxAge","usesPreviewCallback","callbackUrl","redirectUri","toSignIn","error","readStored","raw","stored","writeStored","sealed","publicSession","_refreshToken","signIn","previewCallback","popup","popupUrl","tx","authorizationUrl","pkceChallenge","callback","code","finish","issuerError","iss","tokens","exchangeCode","verifyIdToken","signOut","endSessionUrl","renewed","switchOrganization","back","target","refreshTokens","TokenEndpointError","refreshStored","pathname","route","unchanged","signOutNow","refreshed","PONTIVE_SERVER_VERSION","CLAIM_ROUTE","createServerAuth","options","processEnv","merged","withEnvFallback","keylessApplies","createKeylessAuth","record","isDevelopment","matchingRecord","projectDir","withProviderProps","proc","KeylessUnavailableError","dir","readKeylessRecord","text","status","core","claimPath","claim","found","link","claimLinkFor","PontiveApiError","goneMessage","instances","announced","logger","ready","gone","warnedUnavailable","setup","ensureKeylessInstance","loopbackCallbacks","instance","keylessMessage","KEYLESS_FILE","ENV_FILE","watchForRefusal","auth","KeylessInstanceGoneError","unavailable","base","fetchImpl","told","input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AI,QAAQ,GAAK,EAAA,EAC7G,MAAMJ,CACR,CACF,EACA,MAAM,eAAgB,CACpB,OAAQ,MAAM+J,EAAA,GAAQ,cAAA,CACxB,CAAA,CAEJ,CAOO,SAASD,GAAgBI,EAAgCpC,EAAuBqB,EAA6C,CAClI,MAAMgB,EAAYD,IAAS,IAAI7N,IAAmC,MAAM,GAAGA,CAAI,GAC/E,IAAI+N,EAAO,GACX,MAAO,OAAOC,EAAOC,IAAS,CAC5B,MAAMC,EAAW,MAAMJ,EAAUE,EAAOC,CAAI,EAC5C,OAAIC,EAAS,SAAW,KAAO,CAACH,IAClB,OAAOC,GAAU,SAAWA,EAAQA,aAAiB,IAAMA,EAAM,SAAA,EAAaA,EAAM,KACxF,WAAWvC,EAAO,MAAM,IAC9BsC,EAAO,GACPjB,EAAO,KAAK,aAAaH,EAAAA,YAAYlB,EAAQ,SAAS,CAAC,EAAE,GAGtDyC,CACT,CACF"}
package/dist/index.d.cts CHANGED
@@ -7,6 +7,9 @@
7
7
  * Framework packages (such as `@pontive/nextjs/server`) wrap it; use it
8
8
  * directly in anything else that speaks Request and Response.
9
9
  *
10
+ * `Pontive` is the management API client (all of it is in
11
+ * `@pontive/server/management`).
12
+ *
10
13
  * Config falls back to the `PONTIVE_*` environment variables, and development
11
14
  * with no issuer runs in keyless mode (see `./keyless`, exported as
12
15
  * `@pontive/server/keyless` for the `pontive` CLI).
@@ -18,3 +21,4 @@ export { ACCESS_COOKIE, SESSION_HINT_COOKIE } from './browser-mode.cjs';
18
21
  export type { ProviderProps, RefreshOutcome, ServerAuth, Session, SessionUser } from './server-auth.cjs';
19
22
  export { ORGANIZATION_ERROR_PARAM, SWITCH_ORGANIZATION_ROUTE, switchOrganizationPath, type Organization, } from './organization.cjs';
20
23
  export type { ServerAuthConfig } from './config.cjs';
24
+ export { Pontive, PontiveAPIError, PontiveConnectionError, type PontiveOptions } from './management/index.cjs';
package/dist/index.d.ts CHANGED
@@ -7,6 +7,9 @@
7
7
  * Framework packages (such as `@pontive/nextjs/server`) wrap it; use it
8
8
  * directly in anything else that speaks Request and Response.
9
9
  *
10
+ * `Pontive` is the management API client (all of it is in
11
+ * `@pontive/server/management`).
12
+ *
10
13
  * Config falls back to the `PONTIVE_*` environment variables, and development
11
14
  * with no issuer runs in keyless mode (see `./keyless`, exported as
12
15
  * `@pontive/server/keyless` for the `pontive` CLI).
@@ -18,3 +21,4 @@ export { ACCESS_COOKIE, SESSION_HINT_COOKIE } from './browser-mode.js';
18
21
  export type { ProviderProps, RefreshOutcome, ServerAuth, Session, SessionUser } from './server-auth.js';
19
22
  export { ORGANIZATION_ERROR_PARAM, SWITCH_ORGANIZATION_ROUTE, switchOrganizationPath, type Organization, } from './organization.js';
20
23
  export type { ServerAuthConfig } from './config.js';
24
+ export { Pontive, PontiveAPIError, PontiveConnectionError, type PontiveOptions } from './management/index.js';