@robelest/convex-auth 0.0.4-preview.21 → 0.0.4-preview.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/authorization/index.d.ts +1 -1
- package/dist/authorization/index.js +1 -1
- package/dist/authorization/index.js.map +1 -1
- package/dist/client/index.d.ts +1 -2
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +36 -39
- package/dist/client/index.js.map +1 -1
- package/dist/component/client/index.d.ts +1 -2
- package/dist/component/convex.config.d.ts +2 -2
- package/dist/component/convex.config.d.ts.map +1 -1
- package/dist/component/model.d.ts +5 -5
- package/dist/component/model.d.ts.map +1 -1
- package/dist/component/public/enterprise/audit.d.ts.map +1 -1
- package/dist/component/public/enterprise/audit.js.map +1 -1
- package/dist/component/public/enterprise/core.d.ts.map +1 -1
- package/dist/component/public/enterprise/core.js.map +1 -1
- package/dist/component/public/enterprise/domains.d.ts.map +1 -1
- package/dist/component/public/enterprise/domains.js.map +1 -1
- package/dist/component/public/enterprise/scim.d.ts.map +1 -1
- package/dist/component/public/enterprise/scim.js.map +1 -1
- package/dist/component/public/enterprise/secrets.d.ts.map +1 -1
- package/dist/component/public/enterprise/secrets.js.map +1 -1
- package/dist/component/public/enterprise/webhooks.d.ts.map +1 -1
- package/dist/component/public/enterprise/webhooks.js.map +1 -1
- package/dist/component/public/factors/devices.d.ts.map +1 -1
- package/dist/component/public/factors/devices.js.map +1 -1
- package/dist/component/public/factors/passkeys.d.ts.map +1 -1
- package/dist/component/public/factors/passkeys.js.map +1 -1
- package/dist/component/public/factors/totp.d.ts.map +1 -1
- package/dist/component/public/factors/totp.js.map +1 -1
- package/dist/component/public/groups/core.js.map +1 -1
- package/dist/component/public/groups/invites.d.ts.map +1 -1
- package/dist/component/public/groups/invites.js.map +1 -1
- package/dist/component/public/groups/members.d.ts.map +1 -1
- package/dist/component/public/groups/members.js.map +1 -1
- package/dist/component/public/identity/accounts.d.ts.map +1 -1
- package/dist/component/public/identity/accounts.js.map +1 -1
- package/dist/component/public/identity/codes.d.ts.map +1 -1
- package/dist/component/public/identity/codes.js.map +1 -1
- package/dist/component/public/identity/sessions.d.ts.map +1 -1
- package/dist/component/public/identity/sessions.js.map +1 -1
- package/dist/component/public/identity/tokens.d.ts.map +1 -1
- package/dist/component/public/identity/tokens.js.map +1 -1
- package/dist/component/public/identity/users.d.ts.map +1 -1
- package/dist/component/public/identity/users.js.map +1 -1
- package/dist/component/public/identity/verifiers.d.ts.map +1 -1
- package/dist/component/public/identity/verifiers.js.map +1 -1
- package/dist/component/public/security/keys.d.ts.map +1 -1
- package/dist/component/public/security/keys.js.map +1 -1
- package/dist/component/public/security/limits.d.ts.map +1 -1
- package/dist/component/public/security/limits.js.map +1 -1
- package/dist/component/schema.d.ts +39 -39
- package/dist/component/server/auth.d.ts +95 -52
- package/dist/component/server/auth.d.ts.map +1 -1
- package/dist/component/server/auth.js +63 -43
- package/dist/component/server/auth.js.map +1 -1
- package/dist/component/server/core.js +116 -235
- package/dist/component/server/core.js.map +1 -1
- package/dist/component/server/crypto.js +25 -7
- package/dist/component/server/crypto.js.map +1 -1
- package/dist/component/server/device.js +58 -15
- package/dist/component/server/device.js.map +1 -1
- package/dist/component/server/enterprise/domain.js +148 -59
- package/dist/component/server/enterprise/domain.js.map +1 -1
- package/dist/component/server/enterprise/http.js +36 -15
- package/dist/component/server/enterprise/http.js.map +1 -1
- package/dist/component/server/enterprise/oidc.js +1 -1
- package/dist/component/server/http.js +26 -21
- package/dist/component/server/http.js.map +1 -1
- package/dist/component/server/identity.js +5 -2
- package/dist/component/server/identity.js.map +1 -1
- package/dist/component/server/limits.js +21 -30
- package/dist/component/server/limits.js.map +1 -1
- package/dist/component/server/mutations/account.js +12 -10
- package/dist/component/server/mutations/account.js.map +1 -1
- package/dist/component/server/mutations/code.js +5 -2
- package/dist/component/server/mutations/code.js.map +1 -1
- package/dist/component/server/mutations/invalidate.js +1 -1
- package/dist/component/server/mutations/invalidate.js.map +1 -1
- package/dist/component/server/mutations/oauth.js +10 -4
- package/dist/component/server/mutations/oauth.js.map +1 -1
- package/dist/component/server/mutations/refresh.js +2 -2
- package/dist/component/server/mutations/refresh.js.map +1 -1
- package/dist/component/server/mutations/register.js +46 -42
- package/dist/component/server/mutations/register.js.map +1 -1
- package/dist/component/server/mutations/retrieve.js +21 -25
- package/dist/component/server/mutations/retrieve.js.map +1 -1
- package/dist/component/server/mutations/signature.js +10 -4
- package/dist/component/server/mutations/signature.js.map +1 -1
- package/dist/component/server/mutations/signout.js.map +1 -1
- package/dist/component/server/mutations/store.js +9 -24
- package/dist/component/server/mutations/store.js.map +1 -1
- package/dist/component/server/mutations/verifier.js.map +1 -1
- package/dist/component/server/mutations/verify.js +1 -1
- package/dist/component/server/mutations/verify.js.map +1 -1
- package/dist/component/server/oauth.js +53 -16
- package/dist/component/server/oauth.js.map +1 -1
- package/dist/component/server/passkey.js +115 -31
- package/dist/component/server/passkey.js.map +1 -1
- package/dist/component/server/redirects.js +9 -3
- package/dist/component/server/redirects.js.map +1 -1
- package/dist/component/server/refresh.js +10 -7
- package/dist/component/server/refresh.js.map +1 -1
- package/dist/component/server/runtime.d.ts +3 -3
- package/dist/component/server/runtime.d.ts.map +1 -1
- package/dist/component/server/runtime.js +62 -20
- package/dist/component/server/runtime.js.map +1 -1
- package/dist/component/server/signin.js +34 -10
- package/dist/component/server/signin.js.map +1 -1
- package/dist/component/server/totp.js +79 -19
- package/dist/component/server/totp.js.map +1 -1
- package/dist/component/server/types.d.ts +12 -20
- package/dist/component/server/types.d.ts.map +1 -1
- package/dist/component/server/types.js.map +1 -1
- package/dist/component/server/users.js +6 -3
- package/dist/component/server/users.js.map +1 -1
- package/dist/component/server/utils.js +10 -4
- package/dist/component/server/utils.js.map +1 -1
- package/dist/core/types.d.ts +14 -22
- package/dist/core/types.d.ts.map +1 -1
- package/dist/factors/device.js +8 -9
- package/dist/factors/device.js.map +1 -1
- package/dist/factors/passkey.js +18 -21
- package/dist/factors/passkey.js.map +1 -1
- package/dist/providers/password.js +66 -81
- package/dist/providers/password.js.map +1 -1
- package/dist/runtime/invite.js +2 -8
- package/dist/runtime/invite.js.map +1 -1
- package/dist/server/auth.d.ts +95 -52
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +63 -43
- package/dist/server/auth.js.map +1 -1
- package/dist/server/core.d.ts +71 -159
- package/dist/server/core.d.ts.map +1 -1
- package/dist/server/core.js +116 -235
- package/dist/server/core.js.map +1 -1
- package/dist/server/crypto.d.ts.map +1 -1
- package/dist/server/crypto.js +25 -7
- package/dist/server/crypto.js.map +1 -1
- package/dist/server/device.js +58 -15
- package/dist/server/device.js.map +1 -1
- package/dist/server/enterprise/domain.d.ts +0 -8
- package/dist/server/enterprise/domain.d.ts.map +1 -1
- package/dist/server/enterprise/domain.js +148 -59
- package/dist/server/enterprise/domain.js.map +1 -1
- package/dist/server/enterprise/http.d.ts.map +1 -1
- package/dist/server/enterprise/http.js +35 -14
- package/dist/server/enterprise/http.js.map +1 -1
- package/dist/server/http.d.ts +2 -2
- package/dist/server/http.d.ts.map +1 -1
- package/dist/server/http.js +25 -20
- package/dist/server/http.js.map +1 -1
- package/dist/server/identity.js +5 -2
- package/dist/server/identity.js.map +1 -1
- package/dist/server/index.d.ts +2 -2
- package/dist/server/limits.js +21 -30
- package/dist/server/limits.js.map +1 -1
- package/dist/server/mounts.d.ts +26 -64
- package/dist/server/mounts.d.ts.map +1 -1
- package/dist/server/mounts.js +45 -106
- package/dist/server/mounts.js.map +1 -1
- package/dist/server/mutations/account.d.ts +8 -9
- package/dist/server/mutations/account.d.ts.map +1 -1
- package/dist/server/mutations/account.js +11 -9
- package/dist/server/mutations/account.js.map +1 -1
- package/dist/server/mutations/code.d.ts +13 -13
- package/dist/server/mutations/code.d.ts.map +1 -1
- package/dist/server/mutations/code.js +5 -2
- package/dist/server/mutations/code.js.map +1 -1
- package/dist/server/mutations/invalidate.d.ts +4 -4
- package/dist/server/mutations/invalidate.d.ts.map +1 -1
- package/dist/server/mutations/invalidate.js.map +1 -1
- package/dist/server/mutations/oauth.d.ts +12 -10
- package/dist/server/mutations/oauth.d.ts.map +1 -1
- package/dist/server/mutations/oauth.js +9 -3
- package/dist/server/mutations/oauth.js.map +1 -1
- package/dist/server/mutations/refresh.d.ts +3 -3
- package/dist/server/mutations/refresh.d.ts.map +1 -1
- package/dist/server/mutations/refresh.js +1 -1
- package/dist/server/mutations/refresh.js.map +1 -1
- package/dist/server/mutations/register.d.ts +11 -11
- package/dist/server/mutations/register.d.ts.map +1 -1
- package/dist/server/mutations/register.js +45 -41
- package/dist/server/mutations/register.js.map +1 -1
- package/dist/server/mutations/retrieve.d.ts +6 -6
- package/dist/server/mutations/retrieve.d.ts.map +1 -1
- package/dist/server/mutations/retrieve.js +20 -24
- package/dist/server/mutations/retrieve.js.map +1 -1
- package/dist/server/mutations/signature.d.ts +6 -7
- package/dist/server/mutations/signature.d.ts.map +1 -1
- package/dist/server/mutations/signature.js +9 -3
- package/dist/server/mutations/signature.js.map +1 -1
- package/dist/server/mutations/signin.d.ts +5 -5
- package/dist/server/mutations/signin.d.ts.map +1 -1
- package/dist/server/mutations/signout.js.map +1 -1
- package/dist/server/mutations/store.d.ts +97 -97
- package/dist/server/mutations/store.d.ts.map +1 -1
- package/dist/server/mutations/store.js +8 -23
- package/dist/server/mutations/store.js.map +1 -1
- package/dist/server/mutations/verifier.js.map +1 -1
- package/dist/server/mutations/verify.d.ts +10 -10
- package/dist/server/mutations/verify.d.ts.map +1 -1
- package/dist/server/mutations/verify.js.map +1 -1
- package/dist/server/oauth.js +53 -16
- package/dist/server/oauth.js.map +1 -1
- package/dist/server/passkey.d.ts +2 -2
- package/dist/server/passkey.d.ts.map +1 -1
- package/dist/server/passkey.js +114 -30
- package/dist/server/passkey.js.map +1 -1
- package/dist/server/redirects.js +9 -3
- package/dist/server/redirects.js.map +1 -1
- package/dist/server/refresh.js +10 -7
- package/dist/server/refresh.js.map +1 -1
- package/dist/server/runtime.d.ts +14 -14
- package/dist/server/runtime.d.ts.map +1 -1
- package/dist/server/runtime.js +61 -19
- package/dist/server/runtime.js.map +1 -1
- package/dist/server/signin.js +34 -10
- package/dist/server/signin.js.map +1 -1
- package/dist/server/ssr.d.ts.map +1 -1
- package/dist/server/ssr.js +175 -184
- package/dist/server/ssr.js.map +1 -1
- package/dist/server/totp.js +78 -18
- package/dist/server/totp.js.map +1 -1
- package/dist/server/types.d.ts +13 -21
- package/dist/server/types.d.ts.map +1 -1
- package/dist/server/types.js.map +1 -1
- package/dist/server/users.js +6 -3
- package/dist/server/users.js.map +1 -1
- package/dist/server/utils.js +10 -4
- package/dist/server/utils.js.map +1 -1
- package/package.json +2 -6
- package/src/authorization/index.ts +1 -1
- package/src/cli/index.ts +1 -1
- package/src/client/core/types.ts +14 -14
- package/src/client/factors/device.ts +10 -12
- package/src/client/factors/passkey.ts +23 -26
- package/src/client/index.ts +54 -64
- package/src/client/runtime/invite.ts +5 -7
- package/src/component/index.ts +1 -0
- package/src/component/public/enterprise/audit.ts +6 -1
- package/src/component/public/enterprise/core.ts +1 -0
- package/src/component/public/enterprise/domains.ts +5 -1
- package/src/component/public/enterprise/scim.ts +1 -0
- package/src/component/public/enterprise/secrets.ts +1 -0
- package/src/component/public/enterprise/webhooks.ts +1 -0
- package/src/component/public/factors/devices.ts +1 -0
- package/src/component/public/factors/passkeys.ts +1 -0
- package/src/component/public/factors/totp.ts +1 -0
- package/src/component/public/groups/core.ts +1 -1
- package/src/component/public/groups/invites.ts +7 -1
- package/src/component/public/groups/members.ts +1 -0
- package/src/component/public/identity/accounts.ts +1 -0
- package/src/component/public/identity/codes.ts +1 -0
- package/src/component/public/identity/sessions.ts +1 -0
- package/src/component/public/identity/tokens.ts +1 -0
- package/src/component/public/identity/users.ts +1 -0
- package/src/component/public/identity/verifiers.ts +1 -0
- package/src/component/public/security/keys.ts +1 -0
- package/src/component/public/security/limits.ts +1 -0
- package/src/providers/password.ts +89 -110
- package/src/server/auth.ts +177 -111
- package/src/server/core.ts +197 -233
- package/src/server/crypto.ts +31 -29
- package/src/server/device.ts +65 -32
- package/src/server/enterprise/domain.ts +158 -170
- package/src/server/enterprise/http.ts +46 -39
- package/src/server/http.ts +36 -30
- package/src/server/identity.ts +5 -5
- package/src/server/index.ts +2 -0
- package/src/server/limits.ts +53 -80
- package/src/server/mounts.ts +47 -74
- package/src/server/mutations/account.ts +22 -36
- package/src/server/mutations/code.ts +6 -6
- package/src/server/mutations/invalidate.ts +1 -1
- package/src/server/mutations/oauth.ts +14 -8
- package/src/server/mutations/refresh.ts +5 -4
- package/src/server/mutations/register.ts +87 -132
- package/src/server/mutations/retrieve.ts +44 -44
- package/src/server/mutations/signature.ts +13 -6
- package/src/server/mutations/signout.ts +1 -1
- package/src/server/mutations/store.ts +16 -31
- package/src/server/mutations/verifier.ts +1 -1
- package/src/server/mutations/verify.ts +3 -5
- package/src/server/oauth.ts +60 -69
- package/src/server/passkey.ts +567 -517
- package/src/server/redirects.ts +10 -6
- package/src/server/refresh.ts +14 -18
- package/src/server/runtime.ts +70 -55
- package/src/server/signin.ts +44 -37
- package/src/server/ssr.ts +390 -407
- package/src/server/totp.ts +85 -35
- package/src/server/types.ts +19 -22
- package/src/server/users.ts +7 -6
- package/src/server/utils.ts +10 -12
- package/dist/component/server/authError.js +0 -34
- package/dist/component/server/authError.js.map +0 -1
- package/dist/component/server/errors.d.ts +0 -1
- package/dist/component/server/errors.js +0 -137
- package/dist/component/server/errors.js.map +0 -1
- package/dist/server/authError.d.ts +0 -46
- package/dist/server/authError.d.ts.map +0 -1
- package/dist/server/authError.js +0 -34
- package/dist/server/authError.js.map +0 -1
- package/dist/server/errors.d.ts +0 -177
- package/dist/server/errors.d.ts.map +0 -1
- package/dist/server/errors.js +0 -212
- package/dist/server/errors.js.map +0 -1
- package/src/server/authError.ts +0 -44
- package/src/server/errors.ts +0 -290
package/dist/server/ssr.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr.js","names":["host","error","tokens"],"sources":["../../src/server/ssr.ts"],"sourcesContent":["import { ConvexHttpClient } from \"convex/browser\";\nimport { makeFunctionReference } from \"convex/server\";\nimport { ConvexError } from \"convex/values\";\nimport { parse, serialize } from \"cookie\";\nimport { jwtDecode } from \"jwt-decode\";\n\nimport type {\n SignInAction,\n SignInActionResult,\n SignOutAction,\n} from \"./runtime\";\nimport { Fx } from \"@robelest/fx\";\nimport { isLocalHost } from \"./utils\";\n\nconst signInActionRef: SignInAction = makeFunctionReference(\"auth:signIn\");\nconst signOutActionRef: SignOutAction = makeFunctionReference(\"auth:signOut\");\n\n/** Cookie lifetime configuration for auth tokens. */\nexport type AuthCookieConfig = {\n /** Maximum age in seconds, or `null` for session cookies. */\n maxAge: number | null;\n};\n\n/** Raw cookie values extracted from a request. */\nexport type AuthCookies = {\n /** The JWT access token, or `null` when absent. */\n token: string | null;\n /** The refresh token, or `null` when absent. */\n refreshToken: string | null;\n /** The OAuth PKCE verifier, or `null` when absent. */\n verifier: string | null;\n};\n\n/** A structured cookie ready to be set via any framework's cookie API. */\nexport type AuthCookie = {\n name: string;\n value: string;\n options: {\n path: string;\n httpOnly: boolean;\n secure: boolean;\n sameSite: \"lax\" | \"strict\" | \"none\";\n maxAge?: number;\n expires?: Date;\n };\n};\n\n/**\n * Options for the SSR auth helper returned by {@link server}.\n */\nexport type ServerOptions = {\n /** Convex deployment API URL (e.g. `https://your-app.convex.cloud`). */\n url: string;\n /**\n * Accepted JWT issuers for `refresh()` and `verify()`.\n *\n * By default, this is derived from `url`. If `url` ends with\n * `.convex.cloud`, the matching `.convex.site` issuer is also accepted.\n */\n acceptedIssuers?: string[];\n /**\n * Path the client POSTs auth actions to. Defaults to `\"/api/auth\"`.\n * Must match the `proxyPath` option on the client.\n *\n * @defaultValue \"/api/auth\"\n */\n apiRoute?: string;\n /** Cookie `maxAge` in seconds, or `null` for session cookies. */\n cookieMaxAge?: number | null;\n /** Enable verbose debug logging for token refresh and cookie operations. */\n verbose?: boolean;\n /**\n * Optional namespace for auth cookie names.\n *\n * Use this to isolate auth cookies between multiple local apps on the same host.\n * If omitted, a deterministic deployment-scoped namespace is derived from `url`.\n */\n cookieNamespace?: string;\n /**\n * Control whether `refresh()` handles OAuth `?code=` query parameters.\n *\n * - `true` (default): always exchange the code on GET requests with `text/html` accept.\n * - `false`: never exchange — useful when only the client handles codes.\n * - A function: called with the `Request` for per-request decisions.\n *\n * @defaultValue true\n */\n shouldHandleCode?:\n | ((request: Request) => boolean | Promise<boolean>)\n | boolean;\n};\n\n/**\n * Result returned from `server().refresh()`.\n *\n * Covers both normal SSR refreshes and OAuth code-exchange redirects.\n */\nexport type RefreshResult =\n | {\n /** Code exchange occurred — return the pre-built redirect `Response`. */\n redirect: true;\n /** 302 redirect with Set-Cookie headers already serialized. */\n response: Response;\n }\n | {\n /** No redirect — apply cookies and read the token. */\n redirect: false;\n /** Structured cookies to set on the response. */\n cookies: AuthCookie[];\n /** JWT for SSR hydration, or `null` if not authenticated. */\n token: string | null;\n };\n\nconst TOKEN_COOKIE_BASE_NAME = \"__convexAuthJWT\";\nconst REFRESH_COOKIE_BASE_NAME = \"__convexAuthRefreshToken\";\nconst VERIFIER_COOKIE_BASE_NAME = \"__convexAuthOAuthVerifier\";\nconst DERIVED_COOKIE_NAMESPACE_FALLBACK = \"convexauth\";\n\n/**\n * Derive the cookie names used for auth tokens.\n *\n * On localhost the names are unprefixed; on production hosts they\n * use the `__Host-` prefix for tighter security.\n *\n * @param host - The `Host` header value. Omit to use unprefixed names.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns An object with `token`, `refreshToken`, and `verifier` cookie names.\n */\nexport function authCookieNames(\n host?: string,\n cookieNamespace?: string | null,\n) {\n const prefix = isLocalHost(host) ? \"\" : \"__Host-\";\n const namespace = normalizeCookieNamespace(cookieNamespace);\n const suffix = namespace === null ? \"\" : `_${namespace}`;\n return {\n token: `${prefix}${TOKEN_COOKIE_BASE_NAME}${suffix}`,\n refreshToken: `${prefix}${REFRESH_COOKIE_BASE_NAME}${suffix}`,\n verifier: `${prefix}${VERIFIER_COOKIE_BASE_NAME}${suffix}`,\n };\n}\n\n/**\n * Parse auth cookie values from a raw `Cookie` header string.\n *\n * @param cookieHeader - The raw `Cookie` header, or `null`/`undefined`.\n * @param host - The `Host` header, used to determine cookie name prefixes.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns Parsed {@link AuthCookies} with `token`, `refreshToken`, and `verifier`.\n */\nexport function parseAuthCookies(\n cookieHeader: string | null | undefined,\n host?: string,\n cookieNamespace?: string | null,\n): AuthCookies {\n const names = authCookieNames(host, cookieNamespace);\n const parsed = parse(cookieHeader ?? \"\");\n return {\n token: parsed[names.token] ?? null,\n refreshToken: parsed[names.refreshToken] ?? null,\n verifier: parsed[names.verifier] ?? null,\n };\n}\n\n/**\n * Serialize auth cookies into `Set-Cookie` header strings.\n *\n * Nulled-out values produce deletion cookies (maxAge 0, expired date).\n *\n * @param cookies - The auth cookie values to serialize.\n * @param host - The `Host` header, used for cookie name prefixes and `Secure` flag.\n * @param config - Cookie lifetime config. Defaults to session cookies.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns An array of three `Set-Cookie` header strings.\n */\nexport function serializeAuthCookies(\n cookies: AuthCookies,\n host?: string,\n config: AuthCookieConfig = { maxAge: null },\n cookieNamespace?: string | null,\n) {\n const names = authCookieNames(host, cookieNamespace);\n const secure = !isLocalHost(host);\n const base = {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\" as const,\n secure,\n };\n const maxAge = config.maxAge ?? undefined;\n const serialized = [\n serialize(names.token, cookies.token ?? \"\", {\n ...base,\n maxAge: cookies.token === null ? 0 : maxAge,\n expires: cookies.token === null ? new Date(0) : undefined,\n }),\n serialize(names.refreshToken, cookies.refreshToken ?? \"\", {\n ...base,\n maxAge: cookies.refreshToken === null ? 0 : maxAge,\n expires: cookies.refreshToken === null ? new Date(0) : undefined,\n }),\n serialize(names.verifier, cookies.verifier ?? \"\", {\n ...base,\n maxAge: cookies.verifier === null ? 0 : maxAge,\n expires: cookies.verifier === null ? new Date(0) : undefined,\n }),\n ];\n return serialized;\n}\n\n/**\n * Build structured cookie objects for any SSR framework.\n *\n * Use with SvelteKit's `event.cookies.set()`, TanStack Start's `setCookie()`,\n * Next.js's `cookies().set()`, or any other framework cookie API.\n *\n * @param cookies - The auth cookie values to convert.\n * @param host - The `Host` header, used for cookie name prefixes and `Secure`.\n * @param config - Cookie lifetime config. Defaults to session cookies.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns Structured cookie descriptors ready for framework cookie APIs.\n */\nexport function structuredAuthCookies(\n cookies: AuthCookies,\n host?: string,\n config: AuthCookieConfig = { maxAge: null },\n cookieNamespace?: string | null,\n): AuthCookie[] {\n const names = authCookieNames(host, cookieNamespace);\n const secure = !isLocalHost(host);\n const base = {\n path: \"/\" as const,\n httpOnly: true as const,\n secure,\n sameSite: \"lax\" as const,\n };\n const maxAge = config.maxAge ?? undefined;\n const structured: AuthCookie[] = [\n {\n name: names.token,\n value: cookies.token ?? \"\",\n options: {\n ...base,\n maxAge: cookies.token === null ? 0 : maxAge,\n expires: cookies.token === null ? new Date(0) : undefined,\n },\n },\n {\n name: names.refreshToken,\n value: cookies.refreshToken ?? \"\",\n options: {\n ...base,\n maxAge: cookies.refreshToken === null ? 0 : maxAge,\n expires: cookies.refreshToken === null ? new Date(0) : undefined,\n },\n },\n {\n name: names.verifier,\n value: cookies.verifier ?? \"\",\n options: {\n ...base,\n maxAge: cookies.verifier === null ? 0 : maxAge,\n expires: cookies.verifier === null ? new Date(0) : undefined,\n },\n },\n ];\n\n return structured;\n}\n\n/**\n * Check whether a request pathname matches the auth proxy route.\n *\n * Handles trailing-slash ambiguity: both `/api/auth` and `/api/auth/`\n * match regardless of how `apiRoute` is configured.\n *\n * @param pathname - The request URL pathname.\n * @param apiRoute - The configured proxy route (e.g. `\"/api/auth\"`).\n * @returns `true` when the pathname matches the proxy route.\n *\n * @see {@link server}\n */\nexport function shouldProxyAuthAction(pathname: string, apiRoute: string) {\n if (apiRoute.endsWith(\"/\")) {\n return pathname === apiRoute || pathname === apiRoute.slice(0, -1);\n }\n return pathname === apiRoute || pathname === `${apiRoute}/`;\n}\n\nconst REQUIRED_TOKEN_LIFETIME_MS = 60_000;\nconst MINIMUM_REQUIRED_TOKEN_LIFETIME_MS = 10_000;\n\ntype DecodedToken = { exp?: number; iat?: number; iss?: string };\n\nfunction normalizeCookieNamespace(cookieNamespace?: string | null) {\n if (cookieNamespace === undefined || cookieNamespace === null) {\n return null;\n }\n const normalized = cookieNamespace\n .trim()\n .replace(/[^a-zA-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .toLowerCase();\n return normalized.length > 0 ? normalized : null;\n}\n\n/**\n * Safely check if a string is a valid URL without throwing.\n */\nfunction canParseUrl(value: string): boolean {\n try {\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction serializeAuthCookie(cookie: AuthCookie): string {\n const parts = [\n `${cookie.name}=${cookie.value}`,\n `Path=${cookie.options.path}`,\n ];\n if (cookie.options.httpOnly) parts.push(\"HttpOnly\");\n if (cookie.options.secure) parts.push(\"Secure\");\n if (cookie.options.sameSite)\n parts.push(`SameSite=${cookie.options.sameSite}`);\n if (cookie.options.maxAge !== undefined)\n parts.push(`Max-Age=${cookie.options.maxAge}`);\n if (cookie.options.expires)\n parts.push(`Expires=${cookie.options.expires.toUTCString()}`);\n return parts.join(\"; \");\n}\n\nfunction buildRedirectResponse(\n location: string,\n cookies: AuthCookie[],\n): Response {\n const headers = new Headers({ Location: location });\n for (const cookie of cookies) {\n headers.append(\"Set-Cookie\", serializeAuthCookie(cookie));\n }\n return new Response(null, { status: 302, headers });\n}\n\nfunction deriveCookieNamespaceFromUrl(url: string) {\n if (!canParseUrl(url)) return DERIVED_COOKIE_NAMESPACE_FALLBACK;\n const parsed = new URL(url);\n const raw = `${parsed.hostname}${parsed.pathname}`;\n return normalizeCookieNamespace(raw) ?? DERIVED_COOKIE_NAMESPACE_FALLBACK;\n}\n\nfunction normalizeIssuer(value: string) {\n if (!canParseUrl(value)) return value.replace(/\\/+$/, \"\");\n const parsed = new URL(value);\n const pathname =\n parsed.pathname === \"/\" ? \"\" : parsed.pathname.replace(/\\/+$/, \"\");\n return `${parsed.protocol}//${parsed.host}${pathname}`;\n}\n\nfunction convexSiteIssuerFromCloudUrl(value: string) {\n if (!canParseUrl(value)) return null;\n const parsed = new URL(value);\n if (!parsed.hostname.endsWith(\".convex.cloud\")) {\n return null;\n }\n parsed.hostname =\n parsed.hostname.slice(0, -\".convex.cloud\".length) + \".convex.site\";\n return normalizeIssuer(parsed.toString());\n}\n\nfunction defaultAcceptedIssuersForUrl(value: string) {\n const issuers = [normalizeIssuer(value)];\n const siteIssuer = convexSiteIssuerFromCloudUrl(value);\n if (siteIssuer !== null) {\n issuers.push(siteIssuer);\n }\n return issuers;\n}\n\n/**\n * Create an SSR auth helper for server-side frameworks.\n *\n * Handles cookie-based token management, OAuth code exchange,\n * and automatic JWT refresh on page loads. Works with any\n * framework that gives you a `Request` object — SvelteKit,\n * TanStack Start, Remix, Next.js, etc.\n *\n * @param options - SSR configuration (Convex API URL, issuer rules, proxy route, cookie lifetime).\n * @returns An object with `token`, `verify`, `proxy`, and `refresh` methods.\n *\n * @example SvelteKit hooks\n * ```ts\n * // src/hooks.server.ts\n * import { server } from '@robelest/convex-auth/server';\n *\n * const auth = server({ url: CONVEX_URL });\n *\n * export const handle = async ({ event, resolve }) => {\n * const { cookies, token } = await auth.refresh(event.request);\n * for (const c of cookies) event.cookies.set(c.name, c.value, c.options);\n * event.locals.token = token;\n * return resolve(event);\n * };\n * ```\n *\n * @example Generic proxy endpoint\n * ```ts\n * if (shouldProxyAuthAction(url.pathname, '/api/auth')) {\n * return auth.proxy(request);\n * }\n * ```\n *\n * @param options - Server-side auth configuration including Convex URL,\n * accepted issuers, proxy route, and cookie behavior.\n * @returns SSR helpers for reading tokens, refreshing cookies, and proxying\n * auth actions through an httpOnly-cookie layer.\n *\n * @see {@link shouldProxyAuthAction}\n */\nexport function server(options: ServerOptions) {\n const convexUrl = options.url;\n const apiRoute = options.apiRoute ?? \"/api/auth\";\n const cookieConfig = { maxAge: options.cookieMaxAge ?? null };\n const verbose = options.verbose ?? false;\n const cookieNamespace =\n normalizeCookieNamespace(options.cookieNamespace) ??\n deriveCookieNamespaceFromUrl(convexUrl);\n const acceptedIssuers = new Set(\n (options.acceptedIssuers ?? defaultAcceptedIssuersForUrl(convexUrl))\n .map(normalizeIssuer)\n .filter((issuer) => issuer.length > 0),\n );\n\n return {\n /**\n * Read the JWT from the request cookies without any validation.\n *\n * @param request - The incoming HTTP request.\n * @returns The raw JWT string, or `null` when no token cookie exists.\n */\n token(request: Request): string | null {\n return parseAuthCookies(\n request.headers.get(\"cookie\"),\n request.headers.get(\"host\") ?? new URL(request.url).host,\n cookieNamespace,\n ).token;\n },\n\n /**\n * Check whether the request carries a non-expired JWT.\n *\n * Performs local expiration checking only (no network call).\n * Use for lightweight auth guards in middleware.\n *\n * @param request - The incoming HTTP request.\n * @returns `true` when a valid, non-expired JWT exists in the cookies.\n */\n async verify(request: Request): Promise<boolean> {\n const token = parseAuthCookies(\n request.headers.get(\"cookie\"),\n request.headers.get(\"host\") ?? new URL(request.url).host,\n cookieNamespace,\n ).token;\n if (token === null) {\n return false;\n }\n const decodedToken = await Fx.run(\n Fx.attempt(\n async () => jwtDecode<DecodedToken>(token),\n (decoded) => decoded,\n () => null,\n ),\n );\n if (decodedToken?.exp === undefined || decodedToken.iss === undefined) {\n return false;\n }\n if (!acceptedIssuers.has(normalizeIssuer(decodedToken.iss))) {\n return false;\n }\n return decodedToken.exp * 1000 > Date.now();\n },\n\n /**\n * Handle a proxied `signIn` or `signOut` POST from the client.\n *\n * Validates the route, method, and origin, then forwards the\n * action to Convex and returns a `Response` with updated\n * `Set-Cookie` headers. The client never sees the real\n * refresh token — it stays in httpOnly cookies.\n *\n * @param request - The incoming POST request from the client.\n * @returns A JSON `Response` with auth result and cookie headers.\n */\n async proxy(request: Request): Promise<Response> {\n const requestUrl = new URL(request.url);\n const requestDispatch = !shouldProxyAuthAction(\n requestUrl.pathname,\n apiRoute,\n )\n ? { kind: \"invalidRoute\" as const }\n : request.method !== \"POST\"\n ? { kind: \"invalidMethod\" as const }\n : (() => {\n const originHeader = request.headers.get(\"origin\");\n if (originHeader === null) {\n return false;\n }\n const forwardedProtoHeader =\n request.headers.get(\"x-forwarded-proto\");\n const protocol =\n forwardedProtoHeader !== null\n ? (() => {\n const forwardedProto = forwardedProtoHeader\n .split(\",\")[0]\n ?.trim();\n if (\n forwardedProto !== undefined &&\n forwardedProto.length > 0\n ) {\n return forwardedProto.endsWith(\":\")\n ? forwardedProto\n : `${forwardedProto}:`;\n }\n return new URL(request.url).protocol;\n })()\n : new URL(request.url).protocol;\n const requestHost =\n request.headers.get(\"host\") ?? new URL(request.url).host;\n const hostCandidate = `${protocol}//${requestHost}`;\n const host = canParseUrl(hostCandidate)\n ? new URL(hostCandidate).host\n : requestHost;\n if (!canParseUrl(originHeader)) {\n return true;\n }\n const originUrl = new URL(originHeader);\n return (\n originUrl.host !== host || originUrl.protocol !== protocol\n );\n })()\n ? { kind: \"invalidOrigin\" as const }\n : { kind: \"valid\" as const };\n\n const validationErrorResponse = await Fx.run(\n Fx.match(requestDispatch, requestDispatch.kind, {\n invalidRoute: () => new Response(\"Invalid route\", { status: 404 }),\n invalidMethod: () => new Response(\"Invalid method\", { status: 405 }),\n invalidOrigin: () => new Response(\"Invalid origin\", { status: 403 }),\n valid: () => null,\n }),\n );\n if (validationErrorResponse !== null) {\n return validationErrorResponse;\n }\n\n const body = await Fx.run(\n Fx.attempt(\n async () => {\n const parsed = await request.json();\n if (typeof parsed !== \"object\" || parsed === null) {\n return null;\n }\n return parsed as Record<string, unknown>;\n },\n (parsed) => parsed,\n () => null,\n ),\n );\n if (body === null) {\n return new Response(\"Invalid request body\", { status: 400 });\n }\n\n const action = body.action as string;\n const args =\n typeof body.args === \"object\" && body.args !== null\n ? (body.args as Record<string, any>)\n : {};\n\n const actionDispatch =\n action === \"auth:signIn\"\n ? { action: \"sessionStart\" as const }\n : action === \"auth:signOut\"\n ? { action: \"sessionStop\" as const }\n : null;\n\n if (actionDispatch === null) {\n return new Response(\"Invalid action\", { status: 400 });\n }\n\n const host = request.headers.get(\"host\") ?? new URL(request.url).host;\n const currentCookies = parseAuthCookies(\n request.headers.get(\"cookie\"),\n host,\n cookieNamespace,\n );\n\n return Fx.run(\n Fx.match(actionDispatch, actionDispatch.action, {\n sessionStart: (_) =>\n Fx.from({\n ok: async () => {\n const refreshDispatch =\n args.refreshToken === undefined\n ? { kind: \"passthrough\" as const }\n : currentCookies.refreshToken === null\n ? { kind: \"refreshRequestedWithoutCookie\" as const }\n : {\n kind: \"hydrateRefreshFromCookie\" as const,\n refreshToken: currentCookies.refreshToken,\n };\n\n const refreshResponse = await Fx.run(\n Fx.match(refreshDispatch, refreshDispatch.kind, {\n passthrough: async () => null,\n hydrateRefreshFromCookie: async ({ refreshToken }) => {\n args.refreshToken = refreshToken;\n return null;\n },\n refreshRequestedWithoutCookie: async () => {\n const currentToken = currentCookies.token;\n const decodedToken =\n currentToken === null\n ? null\n : await Fx.run(\n Fx.attempt(\n async () =>\n jwtDecode<DecodedToken>(currentToken),\n (decoded) => decoded,\n () => null,\n ),\n );\n const tokenDispatch =\n currentToken !== null &&\n decodedToken?.exp !== undefined &&\n decodedToken.iss !== undefined &&\n acceptedIssuers.has(\n normalizeIssuer(decodedToken.iss),\n ) &&\n decodedToken.exp * 1000 > Date.now()\n ? {\n kind: \"validToken\" as const,\n token: currentToken,\n }\n : { kind: \"missingToken\" as const };\n return await Fx.run(\n Fx.match(tokenDispatch, tokenDispatch.kind, {\n validToken: ({ token }) =>\n new Response(\n JSON.stringify({\n tokens: {\n token,\n refreshToken: \"dummy\",\n },\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n ),\n missingToken: () =>\n new Response(JSON.stringify({ tokens: null }), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n }),\n );\n },\n }),\n );\n const refreshDecision =\n refreshResponse !== null\n ? {\n kind: \"shortCircuit\" as const,\n response: refreshResponse,\n }\n : { kind: \"continue\" as const };\n const maybeShortCircuitResponse = await Fx.run(\n Fx.match(refreshDecision, refreshDecision.kind, {\n shortCircuit: ({ response }) => response,\n continue: () => null,\n }),\n );\n if (maybeShortCircuitResponse !== null) {\n return maybeShortCircuitResponse;\n }\n\n const client = new ConvexHttpClient(convexUrl);\n const authDispatch =\n args.refreshToken === undefined &&\n args.params?.code === undefined &&\n currentCookies.token !== null\n ? {\n kind: \"attachAuth\" as const,\n token: currentCookies.token,\n }\n : { kind: \"skipAuth\" as const };\n await Fx.run(\n Fx.match(authDispatch, authDispatch.kind, {\n attachAuth: ({ token }) => {\n client.setAuth(token);\n },\n skipAuth: () => undefined,\n }),\n );\n return Fx.run(\n Fx.from({\n ok: () => client.action(signInActionRef, args),\n err: (error) => error,\n }).pipe(\n Fx.fold({\n ok: (result: SignInActionResult) =>\n Fx.run(\n Fx.match(result, result.kind, {\n redirect: (redirectResult) => {\n const response = new Response(\n JSON.stringify({\n kind: \"redirect\",\n redirect: redirectResult.redirect,\n verifier: redirectResult.verifier,\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n for (const value of serializeAuthCookies(\n {\n ...currentCookies,\n verifier: redirectResult.verifier,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return Fx.succeed(response);\n },\n signedIn: (signedInResult) => {\n const response = new Response(\n JSON.stringify({\n kind: \"signedIn\",\n tokens:\n signedInResult.tokens === null\n ? null\n : {\n token: signedInResult.tokens.token,\n refreshToken: \"dummy\",\n },\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n for (const value of serializeAuthCookies(\n {\n token: signedInResult.tokens?.token ?? null,\n refreshToken:\n signedInResult.tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return Fx.succeed(response);\n },\n started: (startedResult) =>\n Fx.succeed(\n new Response(JSON.stringify(startedResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n passkeyOptions: (passkeyOptionsResult) =>\n Fx.succeed(\n new Response(\n JSON.stringify(passkeyOptionsResult),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n ),\n ),\n totpRequired: (totpRequiredResult) =>\n Fx.succeed(\n new Response(\n JSON.stringify(totpRequiredResult),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n ),\n ),\n totpSetup: (totpSetupResult) =>\n Fx.succeed(\n new Response(JSON.stringify(totpSetupResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n deviceCode: (deviceCodeResult) =>\n Fx.succeed(\n new Response(JSON.stringify(deviceCodeResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n }),\n ),\n err: (error: unknown) => {\n const errorBody =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n \"code\" in error.data\n ? {\n error:\n (error.data as { message?: string })\n .message ?? String(error),\n authError: error.data,\n }\n : {\n error:\n error instanceof Error\n ? error.message\n : String(error),\n };\n const response = new Response(\n JSON.stringify(errorBody),\n {\n status: 400,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n const clearSession =\n args.refreshToken !== undefined &&\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n (error.data as Record<string, unknown>).code ===\n \"INVALID_REFRESH_TOKEN\";\n for (const value of serializeAuthCookies(\n {\n token: clearSession ? null : currentCookies.token,\n refreshToken: clearSession\n ? null\n : currentCookies.refreshToken,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return response;\n },\n }),\n ),\n );\n },\n err: (e) => e as never,\n }),\n sessionStop: (_) =>\n Fx.from({\n ok: async () => {\n await Fx.run(\n Fx.from({\n ok: () =>\n (() => {\n const client = new ConvexHttpClient(convexUrl);\n if (currentCookies.token !== null) {\n client.setAuth(currentCookies.token);\n }\n return client.action(signOutActionRef);\n })(),\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] proxy sign-out failed\",\n error,\n );\n const fallbackDispatch =\n currentCookies.refreshToken !== null\n ? {\n kind: \"attemptFallback\" as const,\n refreshToken: currentCookies.refreshToken,\n }\n : { kind: \"skipFallback\" as const };\n return Fx.match(fallbackDispatch, fallbackDispatch.kind, {\n attemptFallback: ({ refreshToken }) =>\n Fx.from({\n ok: async () => {\n const refreshClient = new ConvexHttpClient(\n convexUrl,\n );\n const refreshed = (await refreshClient.action(\n signInActionRef,\n {\n refreshToken,\n },\n )) as SignInActionResult;\n const refreshedTokens = await Fx.run(\n Fx.match(refreshed, refreshed.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n }),\n );\n const fallbackSignOutDispatch =\n refreshedTokens !== null\n ? {\n kind: \"signOutWithRefreshed\" as const,\n token: refreshedTokens.token,\n }\n : { kind: \"skipRefreshedSignOut\" as const };\n await Fx.run(\n Fx.match(\n fallbackSignOutDispatch,\n fallbackSignOutDispatch.kind,\n {\n signOutWithRefreshed: ({ token }) =>\n Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(\n convexUrl,\n );\n client.setAuth(token);\n await client.action(signOutActionRef);\n },\n err: (error) => error,\n }),\n skipRefreshedSignOut: () => Fx.succeed(undefined),\n },\n ),\n );\n },\n err: (fallbackError) => fallbackError,\n }).pipe(\n Fx.recover((fallbackError: unknown) => {\n console.error(\n \"[convex-auth/server] proxy sign-out fallback failed\",\n fallbackError,\n );\n return Fx.succeed(undefined);\n }),\n ),\n skipFallback: () => Fx.succeed(undefined),\n });\n }),\n Fx.map(() => undefined),\n ),\n );\n const response = new Response(JSON.stringify(null), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n for (const value of serializeAuthCookies(\n {\n token: null,\n refreshToken: null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return response;\n },\n err: (e) => e as never,\n }),\n }),\n );\n },\n\n /**\n * Refresh auth tokens on page load.\n *\n * Call this in your server hooks/middleware on every request.\n * It handles three scenarios:\n *\n * 1. **OAuth code exchange** — exchanges a `?code=` query param for tokens and returns a redirect URL.\n * 2. **Token refresh** — refreshes the JWT if it's close to expiry.\n * 3. **No-op** — returns the existing token when no refresh is needed.\n *\n * @param request - The incoming HTTP request.\n * @returns Structured cookies to set on the response, an optional redirect URL, and the current JWT.\n */\n async refresh(request: Request): Promise<RefreshResult> {\n const host = request.headers.get(\"host\") ?? new URL(request.url).host;\n const currentCookies = parseAuthCookies(\n request.headers.get(\"cookie\"),\n host,\n cookieNamespace,\n );\n const currentToken = currentCookies.token;\n\n // CORS request — do not mutate auth cookies from cross-origin requests.\n const originHeader = request.headers.get(\"origin\");\n const forwardedProtoHeader = request.headers.get(\"x-forwarded-proto\");\n const protocol =\n forwardedProtoHeader !== null\n ? (() => {\n const forwardedProto = forwardedProtoHeader.split(\",\")[0]?.trim();\n if (forwardedProto !== undefined && forwardedProto.length > 0) {\n return forwardedProto.endsWith(\":\")\n ? forwardedProto\n : `${forwardedProto}:`;\n }\n return new URL(request.url).protocol;\n })()\n : new URL(request.url).protocol;\n const requestHost =\n request.headers.get(\"host\") ?? new URL(request.url).host;\n const hostCandidate = `${protocol}//${requestHost}`;\n const normalizedHost = canParseUrl(hostCandidate)\n ? new URL(hostCandidate).host\n : requestHost;\n const originUrl =\n originHeader !== null && canParseUrl(originHeader)\n ? new URL(originHeader)\n : null;\n const corsRequest =\n originHeader !== null &&\n (originUrl === null ||\n originUrl.host !== normalizedHost ||\n originUrl.protocol !== protocol);\n const corsDispatch = corsRequest\n ? { kind: \"crossOrigin\" as const }\n : { kind: \"sameOrigin\" as const };\n const corsRefreshResult = await Fx.run(\n Fx.match(corsDispatch, corsDispatch.kind, {\n crossOrigin: () =>\n ({\n redirect: false,\n cookies: [],\n token: null,\n }) satisfies RefreshResult,\n sameOrigin: () => null,\n }),\n );\n if (corsRefreshResult !== null) {\n return corsRefreshResult;\n }\n\n // OAuth code exchange — exchange code for tokens and redirect.\n const requestUrl = new URL(request.url);\n const code = requestUrl.searchParams.get(\"code\");\n const shouldHandleCode =\n options.shouldHandleCode === undefined\n ? true\n : typeof options.shouldHandleCode === \"function\"\n ? await options.shouldHandleCode(request)\n : options.shouldHandleCode;\n\n const codeExchangeDispatch =\n code !== null &&\n request.method === \"GET\" &&\n request.headers.get(\"accept\")?.includes(\"text/html\") &&\n shouldHandleCode\n ? { kind: \"exchange\" as const, code }\n : { kind: \"skip\" as const };\n const codeExchangeResult = await Fx.run(\n Fx.match(codeExchangeDispatch, codeExchangeDispatch.kind, {\n exchange: async ({\n code: verificationCode,\n }): Promise<RefreshResult> => {\n const redirectUrl = new URL(requestUrl.toString());\n return Fx.run(\n Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n params: { code: verificationCode },\n verifier: currentCookies.verifier ?? undefined,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n }),\n );\n return { kind: \"signedIn\" as const, tokens };\n },\n err: (error) => error,\n }).pipe(\n Fx.fold({\n ok: (result): RefreshResult => {\n redirectUrl.searchParams.delete(\"code\");\n const cookies = structuredAuthCookies(\n {\n token: result.tokens?.token ?? null,\n refreshToken: result.tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n );\n return {\n redirect: true,\n response: buildRedirectResponse(\n redirectUrl.toString(),\n cookies,\n ),\n };\n },\n err: (error: unknown): RefreshResult => {\n console.error(\n \"[convex-auth/server] code exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n const terminalCodeExchangeError =\n errorCode === \"OAUTH_INVALID_STATE\" ||\n errorCode === \"OAUTH_PROVIDER_ERROR\" ||\n errorCode === \"OAUTH_MISSING_ID_TOKEN\" ||\n errorCode === \"OAUTH_INVALID_PROFILE\" ||\n errorCode === \"OAUTH_MISSING_VERIFIER\" ||\n errorCode === \"INVALID_VERIFIER\" ||\n errorCode === \"INVALID_VERIFICATION_CODE\";\n if (!terminalCodeExchangeError) {\n return {\n redirect: false,\n cookies: [],\n token: currentCookies.token,\n };\n }\n redirectUrl.searchParams.delete(\"code\");\n const cookies = structuredAuthCookies(\n {\n token: currentCookies.token,\n refreshToken: currentCookies.refreshToken,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n );\n return {\n redirect: true,\n response: buildRedirectResponse(\n redirectUrl.toString(),\n cookies,\n ),\n };\n },\n }),\n ),\n );\n },\n skip: async () => null,\n }),\n );\n const codeExchangeDecision =\n codeExchangeResult !== null\n ? { kind: \"done\" as const, result: codeExchangeResult }\n : { kind: \"continue\" as const };\n const maybeCodeExchangeResult = await Fx.run(\n Fx.match(codeExchangeDecision, codeExchangeDecision.kind, {\n done: ({ result }) => result,\n continue: () => null,\n }),\n );\n if (maybeCodeExchangeResult !== null) {\n return maybeCodeExchangeResult;\n }\n\n // Normal page load — refresh tokens if needed.\n const tokens = await Fx.run(\n Fx.gen(function* () {\n const { token, refreshToken } = currentCookies;\n\n const isMalformedRefreshToken =\n refreshToken !== null &&\n (refreshToken.trim().length === 0 || refreshToken === \"dummy\");\n const malformedRefreshTokenDispatch = isMalformedRefreshToken\n ? { kind: \"malformed\" as const }\n : { kind: \"ok\" as const };\n const malformedRefreshTokenResult = yield* Fx.match(\n malformedRefreshTokenDispatch,\n malformedRefreshTokenDispatch.kind,\n {\n malformed: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie malformed, clearing auth cookies`,\n );\n }\n return null;\n },\n ok: () => undefined,\n },\n );\n if (malformedRefreshTokenResult !== undefined) {\n return malformedRefreshTokenResult;\n }\n\n const decodedToken =\n token === null\n ? null\n : yield* Fx.attempt(\n async () => jwtDecode<DecodedToken>(token),\n (decoded) => decoded,\n () => null,\n );\n const issuerDispatch =\n decodedToken?.iss !== undefined &&\n !acceptedIssuers.has(normalizeIssuer(decodedToken.iss))\n ? { kind: \"issuerMismatch\" as const }\n : { kind: \"issuerOk\" as const };\n const issuerResult = yield* Fx.match(\n issuerDispatch,\n issuerDispatch.kind,\n {\n issuerMismatch: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Access token issuer mismatch, clearing auth cookies`,\n );\n }\n return null;\n },\n issuerOk: () => undefined,\n },\n );\n if (issuerResult !== undefined) {\n return issuerResult;\n }\n\n const tokenState =\n token === null\n ? refreshToken === null\n ? { kind: \"none\" as const }\n : { kind: \"refreshOnly\" as const, refreshToken }\n : refreshToken === null\n ? { kind: \"accessOnly\" as const, token }\n : { kind: \"both\" as const, token, refreshToken };\n\n return yield* Fx.match(tokenState, tokenState.kind, {\n none: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] No auth cookies found, skipping refresh`,\n );\n }\n return Fx.succeed(undefined);\n },\n refreshOnly: ({ refreshToken: refreshTokenValue }) => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Access token cookie missing, attempting refresh-token recovery`,\n );\n }\n return Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>).code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n );\n },\n accessOnly: () => {\n const accessOnlyDispatch =\n decodedToken?.exp !== undefined &&\n decodedToken.iss !== undefined &&\n acceptedIssuers.has(normalizeIssuer(decodedToken.iss)) &&\n decodedToken.exp * 1000 > Date.now()\n ? { kind: \"accessValid\" as const }\n : { kind: \"accessInvalid\" as const };\n return Fx.match(accessOnlyDispatch, accessOnlyDispatch.kind, {\n accessValid: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing but access token still valid`,\n );\n }\n return Fx.succeed(undefined);\n },\n accessInvalid: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing and access token invalid, clearing`,\n );\n }\n return Fx.succeed(null);\n },\n });\n },\n both: ({ refreshToken: refreshTokenValue }) => {\n const bothDecodeDispatch:\n | { kind: \"undecodable\" }\n | {\n kind: \"decoded\";\n decodedToken: DecodedToken & {\n exp: number;\n iat: number;\n };\n } =\n decodedToken?.exp === undefined ||\n decodedToken.iat === undefined\n ? { kind: \"undecodable\" as const }\n : {\n kind: \"decoded\" as const,\n decodedToken: decodedToken as DecodedToken & {\n exp: number;\n iat: number;\n },\n };\n return Fx.match(bothDecodeDispatch, bothDecodeDispatch.kind, {\n undecodable: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Failed to decode access token, attempting refresh-token recovery`,\n );\n }\n return Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n );\n },\n decoded: ({ decodedToken: decodedAccessToken }) => {\n const totalTokenLifetimeMs =\n decodedAccessToken.exp * 1000 -\n decodedAccessToken.iat * 1000;\n const minimumExpiration =\n Date.now() +\n Math.min(\n REQUIRED_TOKEN_LIFETIME_MS,\n Math.max(\n MINIMUM_REQUIRED_TOKEN_LIFETIME_MS,\n totalTokenLifetimeMs / 10,\n ),\n );\n const expirationDispatch =\n decodedAccessToken.exp * 1000 > minimumExpiration\n ? { kind: \"skipRefresh\" as const }\n : { kind: \"refresh\" as const };\n return Fx.match(expirationDispatch, expirationDispatch.kind, {\n skipRefresh: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token valid long enough, skipping refresh`,\n );\n }\n return Fx.succeed(undefined);\n },\n refresh: () =>\n Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>)\n .code === \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n ),\n });\n },\n });\n },\n });\n }),\n );\n if (tokens === undefined) {\n return { redirect: false, cookies: [], token: currentToken };\n }\n\n return {\n redirect: false,\n cookies: structuredAuthCookies(\n {\n token: tokens?.token ?? null,\n refreshToken: tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n ),\n token: tokens?.token ?? null,\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,kBAAg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,iBAAO,GAAG,QACR,OAID;WACD,CACH;SACJ,CAAC;;OAEL,CAAC;;KAEL,CAAC;KACF,CACH;AACD,OAAI,WAAW,OACb,QAAO;IAAE,UAAU;IAAO,SAAS,EAAE;IAAE,OAAO;IAAc;AAG9D,UAAO;IACL,UAAU;IACV,SAAS,sBACP;KACE,OAAO,QAAQ,SAAS;KACxB,cAAc,QAAQ,gBAAgB;KACtC,UAAU;KACX,EACD,MACA,cACA,gBACD;IACD,OAAO,QAAQ,SAAS;IACzB;;EAEJ"}
|
|
1
|
+
{"version":3,"file":"ssr.js","names":["host","error","tokens"],"sources":["../../src/server/ssr.ts"],"sourcesContent":["import { Fx } from \"@robelest/fx\";\nimport { ConvexHttpClient } from \"convex/browser\";\nimport { makeFunctionReference } from \"convex/server\";\nimport { ConvexError } from \"convex/values\";\nimport { parse, serialize } from \"cookie\";\nimport { jwtDecode } from \"jwt-decode\";\n\nimport type {\n SignInAction,\n SignInActionResult,\n SignOutAction,\n} from \"./runtime\";\nimport { isLocalHost } from \"./utils\";\n\nconst signInActionRef: SignInAction = makeFunctionReference(\"auth:signIn\");\nconst signOutActionRef: SignOutAction = makeFunctionReference(\"auth:signOut\");\n\n/** Cookie lifetime configuration for auth tokens. */\nexport type AuthCookieConfig = {\n /** Maximum age in seconds, or `null` for session cookies. */\n maxAge: number | null;\n};\n\n/** Raw cookie values extracted from a request. */\nexport type AuthCookies = {\n /** The JWT access token, or `null` when absent. */\n token: string | null;\n /** The refresh token, or `null` when absent. */\n refreshToken: string | null;\n /** The OAuth PKCE verifier, or `null` when absent. */\n verifier: string | null;\n};\n\n/** A structured cookie ready to be set via any framework's cookie API. */\nexport type AuthCookie = {\n name: string;\n value: string;\n options: {\n path: string;\n httpOnly: boolean;\n secure: boolean;\n sameSite: \"lax\" | \"strict\" | \"none\";\n maxAge?: number;\n expires?: Date;\n };\n};\n\n/**\n * Options for the SSR auth helper returned by {@link server}.\n */\nexport type ServerOptions = {\n /** Convex deployment API URL (e.g. `https://your-app.convex.cloud`). */\n url: string;\n /**\n * Accepted JWT issuers for `refresh()` and `verify()`.\n *\n * By default, this is derived from `url`. If `url` ends with\n * `.convex.cloud`, the matching `.convex.site` issuer is also accepted.\n */\n acceptedIssuers?: string[];\n /**\n * Path the client POSTs auth actions to. Defaults to `\"/api/auth\"`.\n * Must match the `proxyPath` option on the client.\n *\n * @defaultValue \"/api/auth\"\n */\n apiRoute?: string;\n /** Cookie `maxAge` in seconds, or `null` for session cookies. */\n cookieMaxAge?: number | null;\n /** Enable verbose debug logging for token refresh and cookie operations. */\n verbose?: boolean;\n /**\n * Optional namespace for auth cookie names.\n *\n * Use this to isolate auth cookies between multiple local apps on the same host.\n * If omitted, a deterministic deployment-scoped namespace is derived from `url`.\n */\n cookieNamespace?: string;\n /**\n * Control whether `refresh()` handles OAuth `?code=` query parameters.\n *\n * - `true` (default): always exchange the code on GET requests with `text/html` accept.\n * - `false`: never exchange — useful when only the client handles codes.\n * - A function: called with the `Request` for per-request decisions.\n *\n * @defaultValue true\n */\n shouldHandleCode?:\n | ((request: Request) => boolean | Promise<boolean>)\n | boolean;\n};\n\n/**\n * Result returned from `server().refresh()`.\n *\n * Covers both normal SSR refreshes and OAuth code-exchange redirects.\n */\nexport type RefreshResult =\n | {\n /** Code exchange occurred — return the pre-built redirect `Response`. */\n redirect: true;\n /** 302 redirect with Set-Cookie headers already serialized. */\n response: Response;\n }\n | {\n /** No redirect — apply cookies and read the token. */\n redirect: false;\n /** Structured cookies to set on the response. */\n cookies: AuthCookie[];\n /** JWT for SSR hydration, or `null` if not authenticated. */\n token: string | null;\n };\n\nconst TOKEN_COOKIE_BASE_NAME = \"__convexAuthJWT\";\nconst REFRESH_COOKIE_BASE_NAME = \"__convexAuthRefreshToken\";\nconst VERIFIER_COOKIE_BASE_NAME = \"__convexAuthOAuthVerifier\";\nconst DERIVED_COOKIE_NAMESPACE_FALLBACK = \"convexauth\";\n\n/**\n * Derive the cookie names used for auth tokens.\n *\n * On localhost the names are unprefixed; on production hosts they\n * use the `__Host-` prefix for tighter security.\n *\n * @param host - The `Host` header value. Omit to use unprefixed names.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns An object with `token`, `refreshToken`, and `verifier` cookie names.\n */\nexport function authCookieNames(\n host?: string,\n cookieNamespace?: string | null,\n) {\n const prefix = isLocalHost(host) ? \"\" : \"__Host-\";\n const namespace = normalizeCookieNamespace(cookieNamespace);\n const suffix = namespace === null ? \"\" : `_${namespace}`;\n return {\n token: `${prefix}${TOKEN_COOKIE_BASE_NAME}${suffix}`,\n refreshToken: `${prefix}${REFRESH_COOKIE_BASE_NAME}${suffix}`,\n verifier: `${prefix}${VERIFIER_COOKIE_BASE_NAME}${suffix}`,\n };\n}\n\n/**\n * Parse auth cookie values from a raw `Cookie` header string.\n *\n * @param cookieHeader - The raw `Cookie` header, or `null`/`undefined`.\n * @param host - The `Host` header, used to determine cookie name prefixes.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns Parsed {@link AuthCookies} with `token`, `refreshToken`, and `verifier`.\n */\nexport function parseAuthCookies(\n cookieHeader: string | null | undefined,\n host?: string,\n cookieNamespace?: string | null,\n): AuthCookies {\n const names = authCookieNames(host, cookieNamespace);\n const parsed = parse(cookieHeader ?? \"\");\n return {\n token: parsed[names.token] ?? null,\n refreshToken: parsed[names.refreshToken] ?? null,\n verifier: parsed[names.verifier] ?? null,\n };\n}\n\n/**\n * Serialize auth cookies into `Set-Cookie` header strings.\n *\n * Nulled-out values produce deletion cookies (maxAge 0, expired date).\n *\n * @param cookies - The auth cookie values to serialize.\n * @param host - The `Host` header, used for cookie name prefixes and `Secure` flag.\n * @param config - Cookie lifetime config. Defaults to session cookies.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns An array of three `Set-Cookie` header strings.\n */\nexport function serializeAuthCookies(\n cookies: AuthCookies,\n host?: string,\n config: AuthCookieConfig = { maxAge: null },\n cookieNamespace?: string | null,\n) {\n const names = authCookieNames(host, cookieNamespace);\n const secure = !isLocalHost(host);\n const base = {\n path: \"/\",\n httpOnly: true,\n sameSite: \"lax\" as const,\n secure,\n };\n const maxAge = config.maxAge ?? undefined;\n const serialized = [\n serialize(names.token, cookies.token ?? \"\", {\n ...base,\n maxAge: cookies.token === null ? 0 : maxAge,\n expires: cookies.token === null ? new Date(0) : undefined,\n }),\n serialize(names.refreshToken, cookies.refreshToken ?? \"\", {\n ...base,\n maxAge: cookies.refreshToken === null ? 0 : maxAge,\n expires: cookies.refreshToken === null ? new Date(0) : undefined,\n }),\n serialize(names.verifier, cookies.verifier ?? \"\", {\n ...base,\n maxAge: cookies.verifier === null ? 0 : maxAge,\n expires: cookies.verifier === null ? new Date(0) : undefined,\n }),\n ];\n return serialized;\n}\n\n/**\n * Build structured cookie objects for any SSR framework.\n *\n * Use with SvelteKit's `event.cookies.set()`, TanStack Start's `setCookie()`,\n * Next.js's `cookies().set()`, or any other framework cookie API.\n *\n * @param cookies - The auth cookie values to convert.\n * @param host - The `Host` header, used for cookie name prefixes and `Secure`.\n * @param config - Cookie lifetime config. Defaults to session cookies.\n * @param cookieNamespace - Optional namespace suffix for cookie isolation.\n * @returns Structured cookie descriptors ready for framework cookie APIs.\n */\nexport function structuredAuthCookies(\n cookies: AuthCookies,\n host?: string,\n config: AuthCookieConfig = { maxAge: null },\n cookieNamespace?: string | null,\n): AuthCookie[] {\n const names = authCookieNames(host, cookieNamespace);\n const secure = !isLocalHost(host);\n const base = {\n path: \"/\" as const,\n httpOnly: true as const,\n secure,\n sameSite: \"lax\" as const,\n };\n const maxAge = config.maxAge ?? undefined;\n const structured: AuthCookie[] = [\n {\n name: names.token,\n value: cookies.token ?? \"\",\n options: {\n ...base,\n maxAge: cookies.token === null ? 0 : maxAge,\n expires: cookies.token === null ? new Date(0) : undefined,\n },\n },\n {\n name: names.refreshToken,\n value: cookies.refreshToken ?? \"\",\n options: {\n ...base,\n maxAge: cookies.refreshToken === null ? 0 : maxAge,\n expires: cookies.refreshToken === null ? new Date(0) : undefined,\n },\n },\n {\n name: names.verifier,\n value: cookies.verifier ?? \"\",\n options: {\n ...base,\n maxAge: cookies.verifier === null ? 0 : maxAge,\n expires: cookies.verifier === null ? new Date(0) : undefined,\n },\n },\n ];\n\n return structured;\n}\n\n/**\n * Check whether a request pathname matches the auth proxy route.\n *\n * Handles trailing-slash ambiguity: both `/api/auth` and `/api/auth/`\n * match regardless of how `apiRoute` is configured.\n *\n * @param pathname - The request URL pathname.\n * @param apiRoute - The configured proxy route (e.g. `\"/api/auth\"`).\n * @returns `true` when the pathname matches the proxy route.\n *\n * @see {@link server}\n */\nexport function shouldProxyAuthAction(pathname: string, apiRoute: string) {\n if (apiRoute.endsWith(\"/\")) {\n return pathname === apiRoute || pathname === apiRoute.slice(0, -1);\n }\n return pathname === apiRoute || pathname === `${apiRoute}/`;\n}\n\nconst REQUIRED_TOKEN_LIFETIME_MS = 60_000;\nconst MINIMUM_REQUIRED_TOKEN_LIFETIME_MS = 10_000;\n\ntype DecodedToken = { exp?: number; iat?: number; iss?: string };\n\nfunction normalizeCookieNamespace(cookieNamespace?: string | null) {\n if (cookieNamespace === undefined || cookieNamespace === null) {\n return null;\n }\n const normalized = cookieNamespace\n .trim()\n .replace(/[^a-zA-Z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .toLowerCase();\n return normalized.length > 0 ? normalized : null;\n}\n\n/**\n * Safely check if a string is a valid URL without throwing.\n */\nfunction canParseUrl(value: string): boolean {\n try {\n new URL(value);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction serializeAuthCookie(cookie: AuthCookie): string {\n const parts = [\n `${cookie.name}=${cookie.value}`,\n `Path=${cookie.options.path}`,\n ];\n if (cookie.options.httpOnly) parts.push(\"HttpOnly\");\n if (cookie.options.secure) parts.push(\"Secure\");\n if (cookie.options.sameSite)\n parts.push(`SameSite=${cookie.options.sameSite}`);\n if (cookie.options.maxAge !== undefined)\n parts.push(`Max-Age=${cookie.options.maxAge}`);\n if (cookie.options.expires)\n parts.push(`Expires=${cookie.options.expires.toUTCString()}`);\n return parts.join(\"; \");\n}\n\nfunction buildRedirectResponse(\n location: string,\n cookies: AuthCookie[],\n): Response {\n const headers = new Headers({ Location: location });\n for (const cookie of cookies) {\n headers.append(\"Set-Cookie\", serializeAuthCookie(cookie));\n }\n return new Response(null, { status: 302, headers });\n}\n\nfunction deriveCookieNamespaceFromUrl(url: string) {\n if (!canParseUrl(url)) return DERIVED_COOKIE_NAMESPACE_FALLBACK;\n const parsed = new URL(url);\n const raw = `${parsed.hostname}${parsed.pathname}`;\n return normalizeCookieNamespace(raw) ?? DERIVED_COOKIE_NAMESPACE_FALLBACK;\n}\n\nfunction normalizeIssuer(value: string) {\n if (!canParseUrl(value)) return value.replace(/\\/+$/, \"\");\n const parsed = new URL(value);\n const pathname =\n parsed.pathname === \"/\" ? \"\" : parsed.pathname.replace(/\\/+$/, \"\");\n return `${parsed.protocol}//${parsed.host}${pathname}`;\n}\n\nfunction convexSiteIssuerFromCloudUrl(value: string) {\n if (!canParseUrl(value)) return null;\n const parsed = new URL(value);\n if (!parsed.hostname.endsWith(\".convex.cloud\")) {\n return null;\n }\n parsed.hostname =\n parsed.hostname.slice(0, -\".convex.cloud\".length) + \".convex.site\";\n return normalizeIssuer(parsed.toString());\n}\n\nfunction defaultAcceptedIssuersForUrl(value: string) {\n const issuers = [normalizeIssuer(value)];\n const siteIssuer = convexSiteIssuerFromCloudUrl(value);\n if (siteIssuer !== null) {\n issuers.push(siteIssuer);\n }\n return issuers;\n}\n\n/**\n * Create an SSR auth helper for server-side frameworks.\n *\n * Handles cookie-based token management, OAuth code exchange,\n * and automatic JWT refresh on page loads. Works with any\n * framework that gives you a `Request` object — SvelteKit,\n * TanStack Start, Remix, Next.js, etc.\n *\n * @param options - SSR configuration (Convex API URL, issuer rules, proxy route, cookie lifetime).\n * @returns An object with `token`, `verify`, `proxy`, and `refresh` methods.\n *\n * @example SvelteKit hooks\n * ```ts\n * // src/hooks.server.ts\n * import { server } from '@robelest/convex-auth/server';\n *\n * const auth = server({ url: CONVEX_URL });\n *\n * export const handle = async ({ event, resolve }) => {\n * const { cookies, token } = await auth.refresh(event.request);\n * for (const c of cookies) event.cookies.set(c.name, c.value, c.options);\n * event.locals.token = token;\n * return resolve(event);\n * };\n * ```\n *\n * @example Generic proxy endpoint\n * ```ts\n * if (shouldProxyAuthAction(url.pathname, '/api/auth')) {\n * return auth.proxy(request);\n * }\n * ```\n *\n * @param options - Server-side auth configuration including Convex URL,\n * accepted issuers, proxy route, and cookie behavior.\n * @returns SSR helpers for reading tokens, refreshing cookies, and proxying\n * auth actions through an httpOnly-cookie layer.\n *\n * @see {@link shouldProxyAuthAction}\n */\nexport function server(options: ServerOptions) {\n const convexUrl = options.url;\n const apiRoute = options.apiRoute ?? \"/api/auth\";\n const cookieConfig = { maxAge: options.cookieMaxAge ?? null };\n const verbose = options.verbose ?? false;\n const cookieNamespace =\n normalizeCookieNamespace(options.cookieNamespace) ??\n deriveCookieNamespaceFromUrl(convexUrl);\n const acceptedIssuers = new Set(\n (options.acceptedIssuers ?? defaultAcceptedIssuersForUrl(convexUrl))\n .map(normalizeIssuer)\n .filter((issuer) => issuer.length > 0),\n );\n\n return {\n /**\n * Read the JWT from the request cookies without any validation.\n *\n * @param request - The incoming HTTP request.\n * @returns The raw JWT string, or `null` when no token cookie exists.\n */\n token(request: Request): string | null {\n return parseAuthCookies(\n request.headers.get(\"cookie\"),\n request.headers.get(\"host\") ?? new URL(request.url).host,\n cookieNamespace,\n ).token;\n },\n\n /**\n * Check whether the request carries a non-expired JWT.\n *\n * Performs local expiration checking only (no network call).\n * Use for lightweight auth guards in middleware.\n *\n * @param request - The incoming HTTP request.\n * @returns `true` when a valid, non-expired JWT exists in the cookies.\n */\n async verify(request: Request): Promise<boolean> {\n const token = parseAuthCookies(\n request.headers.get(\"cookie\"),\n request.headers.get(\"host\") ?? new URL(request.url).host,\n cookieNamespace,\n ).token;\n if (token === null) {\n return false;\n }\n const decodedToken = await Fx.run(\n Fx.attempt(\n async () => jwtDecode<DecodedToken>(token),\n (decoded) => decoded,\n () => null,\n ),\n );\n if (decodedToken?.exp === undefined || decodedToken.iss === undefined) {\n return false;\n }\n if (!acceptedIssuers.has(normalizeIssuer(decodedToken.iss))) {\n return false;\n }\n return decodedToken.exp * 1000 > Date.now();\n },\n\n /**\n * Handle a proxied `signIn` or `signOut` POST from the client.\n *\n * Validates the route, method, and origin, then forwards the\n * action to Convex and returns a `Response` with updated\n * `Set-Cookie` headers. The client never sees the real\n * refresh token — it stays in httpOnly cookies.\n *\n * @param request - The incoming POST request from the client.\n * @returns A JSON `Response` with auth result and cookie headers.\n */\n async proxy(request: Request): Promise<Response> {\n const requestUrl = new URL(request.url);\n const requestDispatch = !shouldProxyAuthAction(\n requestUrl.pathname,\n apiRoute,\n )\n ? { kind: \"invalidRoute\" as const }\n : request.method !== \"POST\"\n ? { kind: \"invalidMethod\" as const }\n : (() => {\n const originHeader = request.headers.get(\"origin\");\n if (originHeader === null) {\n return false;\n }\n const forwardedProtoHeader =\n request.headers.get(\"x-forwarded-proto\");\n const protocol =\n forwardedProtoHeader !== null\n ? (() => {\n const forwardedProto = forwardedProtoHeader\n .split(\",\")[0]\n ?.trim();\n if (\n forwardedProto !== undefined &&\n forwardedProto.length > 0\n ) {\n return forwardedProto.endsWith(\":\")\n ? forwardedProto\n : `${forwardedProto}:`;\n }\n return new URL(request.url).protocol;\n })()\n : new URL(request.url).protocol;\n const requestHost =\n request.headers.get(\"host\") ?? new URL(request.url).host;\n const hostCandidate = `${protocol}//${requestHost}`;\n const host = canParseUrl(hostCandidate)\n ? new URL(hostCandidate).host\n : requestHost;\n if (!canParseUrl(originHeader)) {\n return true;\n }\n const originUrl = new URL(originHeader);\n return (\n originUrl.host !== host || originUrl.protocol !== protocol\n );\n })()\n ? { kind: \"invalidOrigin\" as const }\n : { kind: \"valid\" as const };\n\n const validationErrorResponse = await Fx.run(\n Fx.match(requestDispatch, requestDispatch.kind, {\n invalidRoute: () => new Response(\"Invalid route\", { status: 404 }),\n invalidMethod: () => new Response(\"Invalid method\", { status: 405 }),\n invalidOrigin: () => new Response(\"Invalid origin\", { status: 403 }),\n valid: () => null,\n }),\n );\n if (validationErrorResponse !== null) {\n return validationErrorResponse;\n }\n\n const body = await Fx.run(\n Fx.attempt(\n async () => {\n const parsed = await request.json();\n if (typeof parsed !== \"object\" || parsed === null) {\n return null;\n }\n return parsed as Record<string, unknown>;\n },\n (parsed) => parsed,\n () => null,\n ),\n );\n if (body === null) {\n return new Response(\"Invalid request body\", { status: 400 });\n }\n\n const action = body.action as string;\n const args =\n typeof body.args === \"object\" && body.args !== null\n ? (body.args as Record<string, any>)\n : {};\n\n const actionDispatch =\n action === \"auth:signIn\"\n ? { action: \"sessionStart\" as const }\n : action === \"auth:signOut\"\n ? { action: \"sessionStop\" as const }\n : null;\n\n if (actionDispatch === null) {\n return new Response(\"Invalid action\", { status: 400 });\n }\n\n const host = request.headers.get(\"host\") ?? new URL(request.url).host;\n const currentCookies = parseAuthCookies(\n request.headers.get(\"cookie\"),\n host,\n cookieNamespace,\n );\n\n return Fx.run(\n Fx.match(actionDispatch, actionDispatch.action, {\n sessionStart: (_) =>\n Fx.promise(async () => {\n const refreshDispatch =\n args.refreshToken === undefined\n ? { kind: \"passthrough\" as const }\n : currentCookies.refreshToken === null\n ? { kind: \"refreshRequestedWithoutCookie\" as const }\n : {\n kind: \"hydrateRefreshFromCookie\" as const,\n refreshToken: currentCookies.refreshToken,\n };\n\n const refreshResponse = await Fx.run(\n Fx.match(refreshDispatch, refreshDispatch.kind, {\n passthrough: async () => null,\n hydrateRefreshFromCookie: async ({ refreshToken }) => {\n args.refreshToken = refreshToken;\n return null;\n },\n refreshRequestedWithoutCookie: async () => {\n const currentToken = currentCookies.token;\n const decodedToken =\n currentToken === null\n ? null\n : await Fx.run(\n Fx.attempt(\n async () => jwtDecode<DecodedToken>(currentToken),\n (decoded) => decoded,\n () => null,\n ),\n );\n const tokenDispatch =\n currentToken !== null &&\n decodedToken?.exp !== undefined &&\n decodedToken.iss !== undefined &&\n acceptedIssuers.has(normalizeIssuer(decodedToken.iss)) &&\n decodedToken.exp * 1000 > Date.now()\n ? {\n kind: \"validToken\" as const,\n token: currentToken,\n }\n : { kind: \"missingToken\" as const };\n return await Fx.run(\n Fx.match(tokenDispatch, tokenDispatch.kind, {\n validToken: ({ token }) =>\n new Response(\n JSON.stringify({\n tokens: {\n token,\n refreshToken: \"dummy\",\n },\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n ),\n missingToken: () =>\n new Response(JSON.stringify({ tokens: null }), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n }),\n );\n },\n }),\n );\n const refreshDecision =\n refreshResponse !== null\n ? {\n kind: \"shortCircuit\" as const,\n response: refreshResponse,\n }\n : { kind: \"continue\" as const };\n const maybeShortCircuitResponse = await Fx.run(\n Fx.match(refreshDecision, refreshDecision.kind, {\n shortCircuit: ({ response }) => response,\n continue: () => null,\n }),\n );\n if (maybeShortCircuitResponse !== null) {\n return maybeShortCircuitResponse;\n }\n\n const client = new ConvexHttpClient(convexUrl);\n const authDispatch =\n args.refreshToken === undefined &&\n args.params?.code === undefined &&\n currentCookies.token !== null\n ? {\n kind: \"attachAuth\" as const,\n token: currentCookies.token,\n }\n : { kind: \"skipAuth\" as const };\n await Fx.run(\n Fx.match(authDispatch, authDispatch.kind, {\n attachAuth: ({ token }) => {\n client.setAuth(token);\n },\n skipAuth: () => undefined,\n }),\n );\n return Fx.run(\n Fx.from({\n ok: () => client.action(signInActionRef, args),\n err: (error) => error,\n }).pipe(\n Fx.fold({\n ok: (result: SignInActionResult) =>\n Fx.run(\n Fx.match(result, result.kind, {\n redirect: (redirectResult) => {\n const response = new Response(\n JSON.stringify({\n kind: \"redirect\",\n redirect: redirectResult.redirect,\n verifier: redirectResult.verifier,\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n for (const value of serializeAuthCookies(\n {\n ...currentCookies,\n verifier: redirectResult.verifier,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return Fx.succeed(response);\n },\n signedIn: (signedInResult) => {\n const response = new Response(\n JSON.stringify({\n kind: \"signedIn\",\n tokens:\n signedInResult.tokens === null\n ? null\n : {\n token: signedInResult.tokens.token,\n refreshToken: \"dummy\",\n },\n }),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n );\n for (const value of serializeAuthCookies(\n {\n token: signedInResult.tokens?.token ?? null,\n refreshToken:\n signedInResult.tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return Fx.succeed(response);\n },\n started: (startedResult) =>\n Fx.succeed(\n new Response(JSON.stringify(startedResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n passkeyOptions: (passkeyOptionsResult) =>\n Fx.succeed(\n new Response(\n JSON.stringify(passkeyOptionsResult),\n {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n },\n ),\n ),\n totpRequired: (totpRequiredResult) =>\n Fx.succeed(\n new Response(JSON.stringify(totpRequiredResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n totpSetup: (totpSetupResult) =>\n Fx.succeed(\n new Response(JSON.stringify(totpSetupResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n deviceCode: (deviceCodeResult) =>\n Fx.succeed(\n new Response(JSON.stringify(deviceCodeResult), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n }),\n ),\n }),\n ),\n err: (error: unknown) => {\n const errorBody =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n \"code\" in error.data\n ? {\n error:\n (error.data as { message?: string }).message ??\n String(error),\n authError: error.data,\n }\n : {\n error:\n error instanceof Error\n ? error.message\n : String(error),\n };\n const response = new Response(JSON.stringify(errorBody), {\n status: 400,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n const clearSession =\n args.refreshToken !== undefined &&\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n (error.data as Record<string, unknown>).code ===\n \"INVALID_REFRESH_TOKEN\";\n for (const value of serializeAuthCookies(\n {\n token: clearSession ? null : currentCookies.token,\n refreshToken: clearSession\n ? null\n : currentCookies.refreshToken,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return response;\n },\n }),\n ),\n );\n }),\n sessionStop: (_) =>\n Fx.promise(async () => {\n await Fx.run(\n Fx.from({\n ok: () =>\n (() => {\n const client = new ConvexHttpClient(convexUrl);\n if (currentCookies.token !== null) {\n client.setAuth(currentCookies.token);\n }\n return client.action(signOutActionRef);\n })(),\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] proxy sign-out failed\",\n error,\n );\n const fallbackDispatch =\n currentCookies.refreshToken !== null\n ? {\n kind: \"attemptFallback\" as const,\n refreshToken: currentCookies.refreshToken,\n }\n : { kind: \"skipFallback\" as const };\n return Fx.match(fallbackDispatch, fallbackDispatch.kind, {\n attemptFallback: ({ refreshToken }) =>\n Fx.from({\n ok: async () => {\n const refreshClient = new ConvexHttpClient(\n convexUrl,\n );\n const refreshed = (await refreshClient.action(\n signInActionRef,\n {\n refreshToken,\n },\n )) as SignInActionResult;\n const refreshedTokens = await Fx.run(\n Fx.match(refreshed, refreshed.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for sign-out fallback refresh\",\n ),\n ),\n }),\n );\n const fallbackSignOutDispatch =\n refreshedTokens !== null\n ? {\n kind: \"signOutWithRefreshed\" as const,\n token: refreshedTokens.token,\n }\n : { kind: \"skipRefreshedSignOut\" as const };\n await Fx.run(\n Fx.match(\n fallbackSignOutDispatch,\n fallbackSignOutDispatch.kind,\n {\n signOutWithRefreshed: ({ token }) =>\n Fx.promise(async () => {\n const client = new ConvexHttpClient(\n convexUrl,\n );\n client.setAuth(token);\n await client.action(signOutActionRef);\n }),\n skipRefreshedSignOut: () =>\n Fx.succeed(undefined),\n },\n ),\n );\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((fallbackError: unknown) => {\n console.error(\n \"[convex-auth/server] proxy sign-out fallback failed\",\n fallbackError,\n );\n return Fx.succeed(undefined);\n }),\n ),\n skipFallback: () => Fx.succeed(undefined),\n });\n }),\n Fx.map(() => undefined),\n ),\n );\n const response = new Response(JSON.stringify(null), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n for (const value of serializeAuthCookies(\n {\n token: null,\n refreshToken: null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n )) {\n response.headers.append(\"Set-Cookie\", value);\n }\n return response;\n }),\n }),\n );\n },\n\n /**\n * Refresh auth tokens on page load.\n *\n * Call this in your server hooks/middleware on every request.\n * It handles three scenarios:\n *\n * 1. **OAuth code exchange** — exchanges a `?code=` query param for tokens and returns a redirect URL.\n * 2. **Token refresh** — refreshes the JWT if it's close to expiry.\n * 3. **No-op** — returns the existing token when no refresh is needed.\n *\n * @param request - The incoming HTTP request.\n * @returns Structured cookies to set on the response, an optional redirect URL, and the current JWT.\n */\n async refresh(request: Request): Promise<RefreshResult> {\n const host = request.headers.get(\"host\") ?? new URL(request.url).host;\n const currentCookies = parseAuthCookies(\n request.headers.get(\"cookie\"),\n host,\n cookieNamespace,\n );\n const currentToken = currentCookies.token;\n\n // CORS request — do not mutate auth cookies from cross-origin requests.\n const originHeader = request.headers.get(\"origin\");\n const forwardedProtoHeader = request.headers.get(\"x-forwarded-proto\");\n const protocol =\n forwardedProtoHeader !== null\n ? (() => {\n const forwardedProto = forwardedProtoHeader.split(\",\")[0]?.trim();\n if (forwardedProto !== undefined && forwardedProto.length > 0) {\n return forwardedProto.endsWith(\":\")\n ? forwardedProto\n : `${forwardedProto}:`;\n }\n return new URL(request.url).protocol;\n })()\n : new URL(request.url).protocol;\n const requestHost =\n request.headers.get(\"host\") ?? new URL(request.url).host;\n const hostCandidate = `${protocol}//${requestHost}`;\n const normalizedHost = canParseUrl(hostCandidate)\n ? new URL(hostCandidate).host\n : requestHost;\n const originUrl =\n originHeader !== null && canParseUrl(originHeader)\n ? new URL(originHeader)\n : null;\n const corsRequest =\n originHeader !== null &&\n (originUrl === null ||\n originUrl.host !== normalizedHost ||\n originUrl.protocol !== protocol);\n const corsDispatch = corsRequest\n ? { kind: \"crossOrigin\" as const }\n : { kind: \"sameOrigin\" as const };\n const corsRefreshResult = await Fx.run(\n Fx.match(corsDispatch, corsDispatch.kind, {\n crossOrigin: () =>\n ({\n redirect: false,\n cookies: [],\n token: null,\n }) satisfies RefreshResult,\n sameOrigin: () => null,\n }),\n );\n if (corsRefreshResult !== null) {\n return corsRefreshResult;\n }\n\n // OAuth code exchange — exchange code for tokens and redirect.\n const requestUrl = new URL(request.url);\n const code = requestUrl.searchParams.get(\"code\");\n const shouldHandleCode =\n options.shouldHandleCode === undefined\n ? true\n : typeof options.shouldHandleCode === \"function\"\n ? await options.shouldHandleCode(request)\n : options.shouldHandleCode;\n\n const codeExchangeDispatch =\n code !== null &&\n request.method === \"GET\" &&\n request.headers.get(\"accept\")?.includes(\"text/html\") &&\n shouldHandleCode\n ? { kind: \"exchange\" as const, code }\n : { kind: \"skip\" as const };\n const codeExchangeResult = await Fx.run(\n Fx.match(codeExchangeDispatch, codeExchangeDispatch.kind, {\n exchange: async ({\n code: verificationCode,\n }): Promise<RefreshResult> => {\n const redirectUrl = new URL(requestUrl.toString());\n return Fx.run(\n Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n params: { code: verificationCode },\n verifier: currentCookies.verifier ?? undefined,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for code exchange\",\n ),\n ),\n }),\n );\n return { kind: \"signedIn\" as const, tokens };\n },\n err: (error) => error,\n }).pipe(\n Fx.fold({\n ok: (result): RefreshResult => {\n redirectUrl.searchParams.delete(\"code\");\n const cookies = structuredAuthCookies(\n {\n token: result.tokens?.token ?? null,\n refreshToken: result.tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n );\n return {\n redirect: true,\n response: buildRedirectResponse(\n redirectUrl.toString(),\n cookies,\n ),\n };\n },\n err: (error: unknown): RefreshResult => {\n console.error(\n \"[convex-auth/server] code exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n const terminalCodeExchangeError =\n errorCode === \"OAUTH_INVALID_STATE\" ||\n errorCode === \"OAUTH_PROVIDER_ERROR\" ||\n errorCode === \"OAUTH_MISSING_ID_TOKEN\" ||\n errorCode === \"OAUTH_INVALID_PROFILE\" ||\n errorCode === \"OAUTH_MISSING_VERIFIER\" ||\n errorCode === \"INVALID_VERIFIER\" ||\n errorCode === \"INVALID_VERIFICATION_CODE\";\n if (!terminalCodeExchangeError) {\n return {\n redirect: false,\n cookies: [],\n token: currentCookies.token,\n };\n }\n redirectUrl.searchParams.delete(\"code\");\n const cookies = structuredAuthCookies(\n {\n token: currentCookies.token,\n refreshToken: currentCookies.refreshToken,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n );\n return {\n redirect: true,\n response: buildRedirectResponse(\n redirectUrl.toString(),\n cookies,\n ),\n };\n },\n }),\n ),\n );\n },\n skip: async () => null,\n }),\n );\n const codeExchangeDecision =\n codeExchangeResult !== null\n ? { kind: \"done\" as const, result: codeExchangeResult }\n : { kind: \"continue\" as const };\n const maybeCodeExchangeResult = await Fx.run(\n Fx.match(codeExchangeDecision, codeExchangeDecision.kind, {\n done: ({ result }) => result,\n continue: () => null,\n }),\n );\n if (maybeCodeExchangeResult !== null) {\n return maybeCodeExchangeResult;\n }\n\n // Normal page load — refresh tokens if needed.\n const tokens = await Fx.run(\n Fx.gen(function* () {\n const { token, refreshToken } = currentCookies;\n\n const isMalformedRefreshToken =\n refreshToken !== null &&\n (refreshToken.trim().length === 0 || refreshToken === \"dummy\");\n const malformedRefreshTokenDispatch = isMalformedRefreshToken\n ? { kind: \"malformed\" as const }\n : { kind: \"ok\" as const };\n const malformedRefreshTokenResult = yield* Fx.match(\n malformedRefreshTokenDispatch,\n malformedRefreshTokenDispatch.kind,\n {\n malformed: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie malformed, clearing auth cookies`,\n );\n }\n return null;\n },\n ok: () => undefined,\n },\n );\n if (malformedRefreshTokenResult !== undefined) {\n return malformedRefreshTokenResult;\n }\n\n const decodedToken =\n token === null\n ? null\n : yield* Fx.attempt(\n async () => jwtDecode<DecodedToken>(token),\n (decoded) => decoded,\n () => null,\n );\n const issuerDispatch =\n decodedToken?.iss !== undefined &&\n !acceptedIssuers.has(normalizeIssuer(decodedToken.iss))\n ? { kind: \"issuerMismatch\" as const }\n : { kind: \"issuerOk\" as const };\n const issuerResult = yield* Fx.match(\n issuerDispatch,\n issuerDispatch.kind,\n {\n issuerMismatch: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Access token issuer mismatch, clearing auth cookies`,\n );\n }\n return null;\n },\n issuerOk: () => undefined,\n },\n );\n if (issuerResult !== undefined) {\n return issuerResult;\n }\n\n const tokenState =\n token === null\n ? refreshToken === null\n ? { kind: \"none\" as const }\n : { kind: \"refreshOnly\" as const, refreshToken }\n : refreshToken === null\n ? { kind: \"accessOnly\" as const, token }\n : { kind: \"both\" as const, token, refreshToken };\n\n return yield* Fx.match(tokenState, tokenState.kind, {\n none: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] No auth cookies found, skipping refresh`,\n );\n }\n return Fx.succeed(undefined);\n },\n refreshOnly: ({ refreshToken: refreshTokenValue }) => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Access token cookie missing, attempting refresh-token recovery`,\n );\n }\n return Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>).code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n );\n },\n accessOnly: () => {\n const accessOnlyDispatch =\n decodedToken?.exp !== undefined &&\n decodedToken.iss !== undefined &&\n acceptedIssuers.has(normalizeIssuer(decodedToken.iss)) &&\n decodedToken.exp * 1000 > Date.now()\n ? { kind: \"accessValid\" as const }\n : { kind: \"accessInvalid\" as const };\n return Fx.match(accessOnlyDispatch, accessOnlyDispatch.kind, {\n accessValid: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing but access token still valid`,\n );\n }\n return Fx.succeed(undefined);\n },\n accessInvalid: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token cookie missing and access token invalid, clearing`,\n );\n }\n return Fx.succeed(null);\n },\n });\n },\n both: ({ refreshToken: refreshTokenValue }) => {\n const bothDecodeDispatch:\n | { kind: \"undecodable\" }\n | {\n kind: \"decoded\";\n decodedToken: DecodedToken & {\n exp: number;\n iat: number;\n };\n } =\n decodedToken?.exp === undefined ||\n decodedToken.iat === undefined\n ? { kind: \"undecodable\" as const }\n : {\n kind: \"decoded\" as const,\n decodedToken: decodedToken as DecodedToken & {\n exp: number;\n iat: number;\n },\n };\n return Fx.match(bothDecodeDispatch, bothDecodeDispatch.kind, {\n undecodable: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Failed to decode access token, attempting refresh-token recovery`,\n );\n }\n return Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>).code ===\n \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n );\n },\n decoded: ({ decodedToken: decodedAccessToken }) => {\n const totalTokenLifetimeMs =\n decodedAccessToken.exp * 1000 -\n decodedAccessToken.iat * 1000;\n const minimumExpiration =\n Date.now() +\n Math.min(\n REQUIRED_TOKEN_LIFETIME_MS,\n Math.max(\n MINIMUM_REQUIRED_TOKEN_LIFETIME_MS,\n totalTokenLifetimeMs / 10,\n ),\n );\n const expirationDispatch =\n decodedAccessToken.exp * 1000 > minimumExpiration\n ? { kind: \"skipRefresh\" as const }\n : { kind: \"refresh\" as const };\n return Fx.match(expirationDispatch, expirationDispatch.kind, {\n skipRefresh: () => {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token valid long enough, skipping refresh`,\n );\n }\n return Fx.succeed(undefined);\n },\n refresh: () =>\n Fx.from({\n ok: async () => {\n const client = new ConvexHttpClient(convexUrl);\n const result = (await client.action(signInActionRef, {\n refreshToken: refreshTokenValue,\n })) as SignInActionResult;\n const tokens = await Fx.run(\n Fx.match(result, result.kind, {\n signedIn: (signedInResult) =>\n Fx.succeed(signedInResult.tokens),\n redirect: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n started: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n passkeyOptions: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpRequired: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n totpSetup: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n deviceCode: () =>\n Fx.fatal(\n new Error(\n \"Invalid `auth:signIn` result for token refresh\",\n ),\n ),\n }),\n );\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refreshed tokens, null=${tokens === null}`,\n );\n }\n return tokens;\n },\n err: (error) => error,\n }).pipe(\n Fx.recover((error: unknown) => {\n console.error(\n \"[convex-auth/server] refresh-token exchange failed\",\n error,\n );\n const errorCode =\n error instanceof ConvexError &&\n typeof error.data === \"object\" &&\n error.data !== null &&\n typeof (error.data as Record<string, unknown>)\n .code === \"string\"\n ? ((error.data as Record<string, unknown>)\n .code as string)\n : null;\n if (errorCode === \"INVALID_REFRESH_TOKEN\") {\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Refresh token rejected, clearing auth cookies`,\n );\n }\n return Fx.succeed(\n null as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }\n if (verbose) {\n console.debug(\n `${new Date().toISOString()} [convex-auth/server] Token refresh failed transiently, keeping current cookies`,\n );\n }\n return Fx.succeed(\n undefined as\n | { token: string; refreshToken: string }\n | null\n | undefined,\n );\n }),\n ),\n });\n },\n });\n },\n });\n }),\n );\n if (tokens === undefined) {\n return { redirect: false, cookies: [], token: currentToken };\n }\n\n return {\n redirect: false,\n cookies: structuredAuthCookies(\n {\n token: tokens?.token ?? null,\n refreshToken: tokens?.refreshToken ?? null,\n verifier: null,\n },\n host,\n cookieConfig,\n cookieNamespace,\n ),\n token: tokens?.token ?? null,\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;AAcA,MAAM,kBAAgC,sBAAsB,cAAc;AAC1E,MAAM,mBAAkC,sBAAsB,eAAe;AAkG7E,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AACjC,MAAM,4BAA4B;AAClC,MAAM,oCAAoC;;;;;;;;;;;AAY1C,SAAgB,gBACd,MACA,iBACA;CACA,MAAM,SAAS,YAAY,KAAK,GAAG,KAAK;CACxC,MAAM,YAAY,yBAAyB,gBAAgB;CAC3D,MAAM,SAAS,cAAc,OAAO,KAAK,IAAI;AAC7C,QAAO;EACL,OAAO,GAAG,SAAS,yBAAyB;EAC5C,cAAc,GAAG,SAAS,2BAA2B;EACrD,UAAU,GAAG,SAAS,4BAA4B;EACnD;;;;;;;;;;AAWH,SAAgB,iBACd,cACA,MACA,iBACa;CACb,MAAM,QAAQ,gBAAgB,MAAM,gBAAgB;CACpD,MAAM,SAAS,MAAM,gBAAgB,GAAG;AACxC,QAAO;EACL,OAAO,OAAO,MAAM,UAAU;EAC9B,cAAc,OAAO,MAAM,iBAAiB;EAC5C,UAAU,OAAO,MAAM,aAAa;EACrC;;;;;;;;;;;;;AAcH,SAAgB,qBACd,SACA,MACA,SAA2B,EAAE,QAAQ,MAAM,EAC3C,iBACA;CACA,MAAM,QAAQ,gBAAgB,MAAM,gBAAgB;CAEpD,MAAM,OAAO;EACX,MAAM;EACN,UAAU;EACV,UAAU;EACV,QALa,CAAC,YAAY,KAAK;EAMhC;CACD,MAAM,SAAS,OAAO,UAAU;AAkBhC,QAjBmB;EACjB,UAAU,MAAM,OAAO,QAAQ,SAAS,IAAI;GAC1C,GAAG;GACH,QAAQ,QAAQ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AI,MAAM,EAAC,aAAa,CAAC,qEAC7B;AAEH,kBAAO,GAAG,QACR,KAID;;AAEH,cAAI,QACF,SAAQ,MACN,oBAAG,IAAI,MAAM,EAAC,aAAa,CAAC,iFAC7B;AAEH,iBAAO,GAAG,QACR,OAID;WACD,CACH;SACJ,CAAC;;OAEL,CAAC;;KAEL,CAAC;KACF,CACH;AACD,OAAI,WAAW,OACb,QAAO;IAAE,UAAU;IAAO,SAAS,EAAE;IAAE,OAAO;IAAc;AAG9D,UAAO;IACL,UAAU;IACV,SAAS,sBACP;KACE,OAAO,QAAQ,SAAS;KACxB,cAAc,QAAQ,gBAAgB;KACtC,UAAU;KACX,EACD,MACA,cACA,gBACD;IACD,OAAO,QAAQ,SAAS;IACzB;;EAEJ"}
|
package/dist/server/totp.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { AuthError } from "./authError.js";
|
|
2
1
|
import { userIdFromIdentitySubject } from "./identity.js";
|
|
3
2
|
import { callVerifierSignature } from "./mutations/signature.js";
|
|
4
3
|
import { callSignIn } from "./mutations/signin.js";
|
|
5
4
|
import { callVerifier } from "./mutations/verifier.js";
|
|
6
5
|
import { mutateTotpInsert, mutateTotpMarkVerified, mutateTotpUpdateLastUsed, mutateVerifierDelete, queryTotpById, queryTotpVerifiedByUserId, queryUserById, queryVerifierById } from "./types.js";
|
|
7
6
|
import { Fx } from "@robelest/fx";
|
|
7
|
+
import { Cv } from "@robelest/fx/convex";
|
|
8
8
|
import { encodeBase32LowerCaseNoPadding } from "@oslojs/encoding";
|
|
9
9
|
import { createTOTPKeyURI, verifyTOTPWithGracePeriod } from "@oslojs/otp";
|
|
10
10
|
|
|
@@ -24,11 +24,23 @@ const TOTP_FLOWS = [
|
|
|
24
24
|
];
|
|
25
25
|
const resolveTotpFlowFx = (params) => {
|
|
26
26
|
const flow = params.flow;
|
|
27
|
-
return typeof flow === "string" && TOTP_FLOWS.includes(flow) ? Fx.succeed(flow) :
|
|
27
|
+
return typeof flow === "string" && TOTP_FLOWS.includes(flow) ? Fx.succeed(flow) : Cv.fail({
|
|
28
|
+
code: "TOTP_MISSING_FLOW",
|
|
29
|
+
message: "Missing `flow` parameter. Expected one of: setup, confirm, verify"
|
|
30
|
+
});
|
|
28
31
|
};
|
|
29
|
-
const requireTotpVerifierFx = (verifier) => verifier != null ? Fx.succeed(verifier) :
|
|
30
|
-
|
|
31
|
-
|
|
32
|
+
const requireTotpVerifierFx = (verifier) => verifier != null ? Fx.succeed(verifier) : Cv.fail({
|
|
33
|
+
code: "TOTP_MISSING_VERIFIER",
|
|
34
|
+
message: "Missing verifier for TOTP operation."
|
|
35
|
+
});
|
|
36
|
+
const requireTotpCodeFx = (params) => typeof params.code === "string" ? Fx.succeed(params.code) : Cv.fail({
|
|
37
|
+
code: "TOTP_MISSING_CODE",
|
|
38
|
+
message: "Missing TOTP code."
|
|
39
|
+
});
|
|
40
|
+
const requireTotpIdFx = (params) => typeof params.totpId === "string" ? Fx.succeed(params.totpId) : Cv.fail({
|
|
41
|
+
code: "TOTP_MISSING_ID",
|
|
42
|
+
message: "Missing TOTP enrollment ID."
|
|
43
|
+
});
|
|
32
44
|
const resolveTotpDispatchFx = (params, verifier) => resolveTotpFlowFx(params).pipe(Fx.chain((flow) => Fx.match({ flow }).on("flow", {
|
|
33
45
|
setup: () => Fx.succeed({
|
|
34
46
|
flow: "setup",
|
|
@@ -57,8 +69,14 @@ const handleTotp = (ctx, provider, args) => {
|
|
|
57
69
|
return resolveTotpDispatchFx(args.params ?? {}, args.verifier).pipe(Fx.chain((dispatch) => Fx.match(dispatch).on("flow", {
|
|
58
70
|
setup: ({ params }) => Fx.from({
|
|
59
71
|
ok: () => ctx.auth.getUserIdentity(),
|
|
60
|
-
err: (e) =>
|
|
61
|
-
|
|
72
|
+
err: (e) => Cv.error({
|
|
73
|
+
code: "INTERNAL_ERROR",
|
|
74
|
+
message: String(e)
|
|
75
|
+
})
|
|
76
|
+
}).pipe(Fx.chain((identity) => identity === null ? Cv.fail({
|
|
77
|
+
code: "TOTP_AUTH_REQUIRED",
|
|
78
|
+
message: "Sign in first, then set up two-factor authentication."
|
|
79
|
+
}) : Fx.succeed(userIdFromIdentitySubject(identity.subject))), Fx.chain((userId) => Fx.from({
|
|
62
80
|
ok: async () => {
|
|
63
81
|
const secret = new Uint8Array(20);
|
|
64
82
|
crypto.getRandomValues(secret);
|
|
@@ -92,15 +110,36 @@ const handleTotp = (ctx, provider, args) => {
|
|
|
92
110
|
})
|
|
93
111
|
};
|
|
94
112
|
},
|
|
95
|
-
err: (e) =>
|
|
113
|
+
err: (e) => Cv.error({
|
|
114
|
+
code: "INTERNAL_ERROR",
|
|
115
|
+
message: `TOTP setup failed: ${String(e)}`
|
|
116
|
+
})
|
|
96
117
|
}))),
|
|
97
118
|
confirm: ({ code, totpId, verifier }) => Fx.from({
|
|
98
119
|
ok: () => ctx.auth.getUserIdentity(),
|
|
99
|
-
err: (e) =>
|
|
100
|
-
|
|
120
|
+
err: (e) => Cv.error({
|
|
121
|
+
code: "INTERNAL_ERROR",
|
|
122
|
+
message: String(e)
|
|
123
|
+
})
|
|
124
|
+
}).pipe(Fx.chain((identity) => identity === null ? Cv.fail({
|
|
125
|
+
code: "TOTP_AUTH_REQUIRED",
|
|
126
|
+
message: "Sign in first, then set up two-factor authentication."
|
|
127
|
+
}) : Fx.succeed(userIdFromIdentitySubject(identity.subject))), Fx.chain((userId) => Fx.from({
|
|
101
128
|
ok: () => queryTotpById(ctx, totpId),
|
|
102
|
-
err: () =>
|
|
103
|
-
|
|
129
|
+
err: () => Cv.error({
|
|
130
|
+
code: "TOTP_NOT_FOUND",
|
|
131
|
+
message: "TOTP enrollment not found."
|
|
132
|
+
})
|
|
133
|
+
}).pipe(Fx.chain((doc) => doc === null ? Cv.fail({
|
|
134
|
+
code: "TOTP_NOT_FOUND",
|
|
135
|
+
message: "TOTP enrollment not found."
|
|
136
|
+
}) : Fx.succeed(doc)), Fx.chain((totpDoc) => totpDoc.verified ? Cv.fail({
|
|
137
|
+
code: "TOTP_ALREADY_VERIFIED",
|
|
138
|
+
message: "TOTP enrollment is already verified."
|
|
139
|
+
}) : Fx.succeed(totpDoc))).pipe(Fx.chain((totpDoc) => verifyTOTPWithGracePeriod(new Uint8Array(totpDoc.secret), provider.options.period, provider.options.digits, code, 30) ? Fx.succeed(totpDoc) : Cv.fail({
|
|
140
|
+
code: "TOTP_INVALID_CODE",
|
|
141
|
+
message: "Invalid TOTP code."
|
|
142
|
+
}))).pipe(Fx.chain((_totpDoc) => Fx.from({
|
|
104
143
|
ok: async () => {
|
|
105
144
|
await mutateTotpMarkVerified(ctx, totpId, Date.now());
|
|
106
145
|
await mutateVerifierDelete(ctx, verifier);
|
|
@@ -109,15 +148,24 @@ const handleTotp = (ctx, provider, args) => {
|
|
|
109
148
|
generateTokens: true
|
|
110
149
|
});
|
|
111
150
|
},
|
|
112
|
-
err: (e) =>
|
|
151
|
+
err: (e) => Cv.error({
|
|
152
|
+
code: "INTERNAL_ERROR",
|
|
153
|
+
message: String(e)
|
|
154
|
+
})
|
|
113
155
|
}))).pipe(Fx.map((signInResult) => ({
|
|
114
156
|
kind: "signedIn",
|
|
115
157
|
signedIn: signInResult
|
|
116
158
|
}))))),
|
|
117
159
|
verify: ({ code, verifier }) => Fx.from({
|
|
118
160
|
ok: () => queryVerifierById(ctx, verifier),
|
|
119
|
-
err: () =>
|
|
120
|
-
|
|
161
|
+
err: () => Cv.error({
|
|
162
|
+
code: "TOTP_INVALID_VERIFIER",
|
|
163
|
+
message: "Invalid or expired TOTP verifier."
|
|
164
|
+
})
|
|
165
|
+
}).pipe(Fx.chain((doc) => doc === null ? Cv.fail({
|
|
166
|
+
code: "TOTP_INVALID_VERIFIER",
|
|
167
|
+
message: "Invalid or expired TOTP verifier."
|
|
168
|
+
}) : Fx.succeed(doc)), Fx.map((doc) => {
|
|
121
169
|
return {
|
|
122
170
|
userId: JSON.parse(doc.signature).userId,
|
|
123
171
|
code,
|
|
@@ -125,8 +173,17 @@ const handleTotp = (ctx, provider, args) => {
|
|
|
125
173
|
};
|
|
126
174
|
}), Fx.chain(({ userId, code: code$1, verifier: verifier$1 }) => Fx.from({
|
|
127
175
|
ok: () => queryTotpVerifiedByUserId(ctx, userId),
|
|
128
|
-
err: () =>
|
|
129
|
-
|
|
176
|
+
err: () => Cv.error({
|
|
177
|
+
code: "TOTP_NO_ENROLLMENT",
|
|
178
|
+
message: "No verified TOTP enrollment found."
|
|
179
|
+
})
|
|
180
|
+
}).pipe(Fx.chain((totpDoc) => totpDoc === null ? Cv.fail({
|
|
181
|
+
code: "TOTP_NO_ENROLLMENT",
|
|
182
|
+
message: "No verified TOTP enrollment found."
|
|
183
|
+
}) : Fx.succeed(totpDoc)), Fx.chain((totpDoc) => verifyTOTPWithGracePeriod(new Uint8Array(totpDoc.secret), totpDoc.period, totpDoc.digits, code$1, 30) ? Fx.succeed(totpDoc) : Cv.fail({
|
|
184
|
+
code: "TOTP_INVALID_CODE",
|
|
185
|
+
message: "Invalid TOTP code."
|
|
186
|
+
})), Fx.chain((totpDoc) => Fx.from({
|
|
130
187
|
ok: async () => {
|
|
131
188
|
await mutateTotpUpdateLastUsed(ctx, totpDoc._id, Date.now());
|
|
132
189
|
await mutateVerifierDelete(ctx, verifier$1);
|
|
@@ -135,7 +192,10 @@ const handleTotp = (ctx, provider, args) => {
|
|
|
135
192
|
generateTokens: true
|
|
136
193
|
});
|
|
137
194
|
},
|
|
138
|
-
err: (e) =>
|
|
195
|
+
err: (e) => Cv.error({
|
|
196
|
+
code: "INTERNAL_ERROR",
|
|
197
|
+
message: String(e)
|
|
198
|
+
})
|
|
139
199
|
})), Fx.map((signInResult) => ({
|
|
140
200
|
kind: "signedIn",
|
|
141
201
|
signedIn: signInResult
|