@hexclave/js 1.0.76 → 1.0.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/{admin-app-impl-B86v7B0O.d.ts → admin-app-impl-CHQtsn4f.d.ts} +11 -9
  2. package/dist/admin-app-impl-CHQtsn4f.d.ts.map +1 -0
  3. package/dist/clickmap/clickmap-core.d.ts +1 -1
  4. package/dist/clickmap/index.d.ts +1 -1
  5. package/dist/{client-app-WOX3pOo1.d.ts → client-app-R5X8wyeV.d.ts} +4 -1
  6. package/dist/client-app-R5X8wyeV.d.ts.map +1 -0
  7. package/dist/dev-tool/dev-tool-core.d.ts +1 -1
  8. package/dist/dev-tool/index.d.ts +1 -1
  9. package/dist/esm/lib/hexclave-app/apps/implementations/admin-app-impl.d.ts +4 -4
  10. package/dist/esm/lib/hexclave-app/apps/implementations/admin-app-impl.d.ts.map +1 -1
  11. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.automatic-side-effects.test.js +30 -1
  12. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.automatic-side-effects.test.js.map +1 -1
  13. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.cross-domain.test.js.map +1 -1
  14. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.d.ts +5 -3
  15. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.d.ts.map +1 -1
  16. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.js +90 -20
  17. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.js.map +1 -1
  18. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.d.ts +1 -0
  19. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.js +83 -0
  20. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.js.map +1 -0
  21. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.d.ts +1 -0
  22. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.js +120 -0
  23. package/dist/esm/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.js.map +1 -0
  24. package/dist/esm/lib/hexclave-app/apps/implementations/common.js +2 -2
  25. package/dist/esm/lib/hexclave-app/apps/implementations/common.js.map +1 -1
  26. package/dist/esm/lib/hexclave-app/apps/implementations/index.d.ts +1 -1
  27. package/dist/esm/lib/hexclave-app/apps/implementations/index.js +1 -1
  28. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.d.ts +1 -1
  29. package/dist/esm/lib/hexclave-app/apps/implementations/server-app-impl.js +1 -1
  30. package/dist/esm/lib/hexclave-app/teams/index.d.ts +3 -0
  31. package/dist/esm/lib/hexclave-app/teams/index.d.ts.map +1 -1
  32. package/dist/esm/lib/hexclave-app/teams/index.js.map +1 -1
  33. package/dist/index.d.ts +1 -1
  34. package/dist/lib/hexclave-app/apps/implementations/admin-app-impl.d.ts +1 -1
  35. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.automatic-side-effects.test.js +29 -0
  36. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.automatic-side-effects.test.js.map +1 -1
  37. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.cross-domain.test.js.map +1 -1
  38. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.d.ts +2 -2
  39. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.js +89 -18
  40. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.js.map +1 -1
  41. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.d.ts +1 -0
  42. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.js +82 -0
  43. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.js.map +1 -0
  44. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.d.ts +1 -0
  45. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.js +119 -0
  46. package/dist/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.js.map +1 -0
  47. package/dist/lib/hexclave-app/apps/implementations/common.js +2 -2
  48. package/dist/lib/hexclave-app/apps/implementations/common.js.map +1 -1
  49. package/dist/lib/hexclave-app/apps/implementations/index.d.ts +1 -1
  50. package/dist/lib/hexclave-app/apps/implementations/index.js +1 -1
  51. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.d.ts +1 -1
  52. package/dist/lib/hexclave-app/apps/implementations/server-app-impl.js +1 -1
  53. package/dist/lib/hexclave-app/apps/index.d.ts +1 -1
  54. package/dist/lib/hexclave-app/apps/interfaces/admin-app.d.ts +1 -1
  55. package/dist/lib/hexclave-app/apps/interfaces/client-app.d.ts +1 -1
  56. package/dist/lib/hexclave-app/apps/interfaces/server-app.d.ts +1 -1
  57. package/dist/lib/hexclave-app/index.d.ts +1 -1
  58. package/dist/lib/hexclave-app/projects/index.d.ts +1 -1
  59. package/dist/lib/hexclave-app/teams/index.d.ts +1 -1
  60. package/dist/lib/hexclave-app/teams/index.js.map +1 -1
  61. package/dist/lib/hexclave-app/users/index.d.ts +1 -1
  62. package/dist/pushed-config-error-overlay/index.d.ts +1 -1
  63. package/package.json +2 -2
  64. package/src/lib/hexclave-app/apps/implementations/client-app-impl.automatic-side-effects.test.ts +38 -1
  65. package/src/lib/hexclave-app/apps/implementations/client-app-impl.cross-domain.test.ts +2 -3
  66. package/src/lib/hexclave-app/apps/implementations/client-app-impl.sign-out.test.ts +96 -0
  67. package/src/lib/hexclave-app/apps/implementations/client-app-impl.ts +126 -24
  68. package/src/lib/hexclave-app/apps/implementations/client-app-impl.untrusted-redirect-card.test.ts +146 -0
  69. package/src/lib/hexclave-app/apps/implementations/common.ts +1 -1
  70. package/src/lib/hexclave-app/teams/index.ts +3 -0
  71. package/dist/admin-app-impl-B86v7B0O.d.ts.map +0 -1
  72. package/dist/client-app-WOX3pOo1.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client-app-impl.cross-domain.test.js","names":["StackClientApp","hexclaveAppInternalsSymbol","AccessToken","Store","HexclaveSetupError","vi","expect"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/client-app-impl.cross-domain.test.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { describe, expect, it, vi } from \"vitest\";\nimport { AccessToken } from \"@hexclave/shared/dist/sessions\";\nimport { HexclaveSetupError } from \"@hexclave/shared/dist/utils/errors\";\nimport { Store } from \"@hexclave/shared/dist/utils/stores\";\nimport { hexclaveAppInternalsSymbol } from \"../../common\";\nimport { StackClientApp } from \"../interfaces/client-app\";\nimport { planRedirectToHandler } from \"./redirect-page-urls\";\n\n// Every app in this file is constructed with `devTool: false`. The tests install a mock window and document, which makes\n// the SDK believe it is in a browser, and mounting the dev tool kicks off a background `getProject()` against a backend\n// that does not exist here. That fetch never settles, and because it runs inside the global store lock, it blocks every\n// later `withWriteLock` caller (`_signOut`, most visibly) for the rest of the test file.\nfunction createAccessTokenString(refreshTokenId: string): string {\n const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString(\"base64url\");\n const nowSeconds = Math.floor(Date.now() / 1000);\n return [\n encode({ alg: \"none\", typ: \"JWT\" }),\n encode({\n sub: \"user-id\",\n exp: nowSeconds + 60,\n iat: nowSeconds,\n iss: \"https://api.example.test\",\n aud: \"project-id\",\n project_id: \"project-id\",\n branch_id: \"main\",\n refresh_token_id: refreshTokenId,\n role: \"authenticated\",\n name: null,\n email: null,\n email_verified: false,\n selected_team_id: null,\n signed_up_at: nowSeconds,\n is_anonymous: false,\n is_restricted: false,\n restricted_reason: null,\n requires_totp_mfa: false,\n }),\n \"\",\n ].join(\".\");\n}\n\nfunction createMockDocument(): Document {\n const cookieJar = new Map<string, string>();\n return {\n get cookie() {\n return [...cookieJar.entries()].map(([key, value]) => `${key}=${value}`).join(\"; \");\n },\n set cookie(str: string) {\n const [nameValue] = str.split(\";\");\n const eqIndex = nameValue.indexOf(\"=\");\n if (eqIndex < 0) return;\n cookieJar.set(nameValue.slice(0, eqIndex).trim(), nameValue.slice(eqIndex + 1).trim());\n },\n createElement: () => ({}),\n } as any;\n}\n\n/**\n * Installs a stand-in for `window` with only the parts the code under test touches. `globalThis.window` is typed as a\n * full `Window`, which a hand-written stub can never be, so the assignment goes through `Reflect.set` — the stub's own\n * shape stays checked, unlike with a cast on the object literal.\n */\nfunction setMockWindow(mockWindow: {\n location: { href: string, replace?: (url: string) => void },\n}): void {\n Reflect.set(globalThis, \"window\", mockWindow);\n}\n\n/**\n * Calls one of the app's `protected` methods, which are part of the flows under test but not of the public SDK surface.\n */\nfunction callProtectedMethod(app: StackClientApp<true>, methodName: string, ...args: unknown[]): Promise<unknown> {\n const method = Reflect.get(app, methodName);\n if (typeof method !== \"function\") {\n throw new Error(`Expected StackClientApp to have a ${methodName} method in tests.`);\n }\n return method.apply(app, args);\n}\n\ndescribe(\"StackClientApp cross-domain auth\", () => {\n it(\"keeps noRedirectBack same-domain redirects free of redirect-back state\", async () => {\n const redirectPlan = await planRedirectToHandler({\n handlerName: \"signIn\",\n rawHandlerUrl: \"/handler/sign-in\",\n noRedirectBack: true,\n currentUrl: new URL(\"https://app.example.test/settings?tab=profile\"),\n localOAuthCallbackUrl: \"/handler/oauth-callback\",\n rawHomeUrl: \"/home\",\n getCrossDomainHandoffParams: async () => {\n throw new Error(\"Same-domain redirects must not create cross-domain handoff parameters.\");\n },\n });\n\n expect(redirectPlan).toEqual({\n type: \"redirect\",\n url: \"/handler/sign-in\",\n });\n });\n\n it(\"returns noRedirectBack cross-domain auth to the source app home\", async () => {\n const handoffState = \"no-redirect-back-state\";\n const handoffCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const currentUrl = new URL(\"https://app.example.test/settings?tab=profile\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n currentUrl.searchParams.set(\n \"hexclave_cross_domain_after_callback_redirect_url\",\n \"https://app.example.test/settings?tab=profile\",\n );\n\n const redirectPlan = await planRedirectToHandler({\n handlerName: \"signIn\",\n rawHandlerUrl: \"https://auth.example.test/handler/sign-in\",\n noRedirectBack: true,\n currentUrl,\n localOAuthCallbackUrl: \"/handler/oauth-callback\",\n rawHomeUrl: \"/home\",\n getCrossDomainHandoffParams: async () => {\n throw new Error(\"Existing cross-domain handoff parameters must be reused.\");\n },\n });\n\n expect(redirectPlan.type).toBe(\"redirect\");\n if (redirectPlan.type !== \"redirect\") {\n throw new Error(\"Expected noRedirectBack sign-in to produce a redirect URL.\");\n }\n\n const hostedUrl = new URL(redirectPlan.url);\n expect(hostedUrl.origin).toBe(\"https://auth.example.test\");\n expect(hostedUrl.pathname).toBe(\"/handler/sign-in\");\n expect(hostedUrl.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\n \"https://app.example.test/home\",\n );\n\n const rawSourceCallbackUrl = hostedUrl.searchParams.get(\"after_auth_return_to\");\n if (rawSourceCallbackUrl == null) {\n throw new Error(\"Expected cross-domain noRedirectBack to include its internal source callback URL.\");\n }\n const sourceCallbackUrl = new URL(rawSourceCallbackUrl);\n expect(sourceCallbackUrl.origin).toBe(\"https://app.example.test\");\n expect(sourceCallbackUrl.pathname).toBe(\"/handler/oauth-callback\");\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_auth\")).toBe(\"1\");\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_state\")).toBe(handoffState);\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_code_challenge\")).toBe(handoffCodeChallenge);\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\n \"https://app.example.test/home\",\n );\n expect(sourceCallbackUrl.toString()).not.toContain(\"/settings\");\n });\n\n it(\"exposes redirect-back-aware handler URLs for devtool previews\", async () => {\n const previousWindow = Reflect.get(globalThis, \"window\");\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n Reflect.set(globalThis, \"window\", {\n location: {\n href: \"http://localhost/music?track=1#song\",\n },\n });\n\n try {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000000\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"none\",\n urls: {\n signIn: \"/handler/sign-in\",\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"signIn\");\n\n const resolved = new URL(redirectUrl, \"http://localhost\");\n expect(resolved.pathname).toBe(\"/handler/sign-in\");\n expect(resolved.searchParams.get(\"after_auth_return_to\")).toBe(\"/music?track=1#song\");\n } finally {\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"uses the fresh post-auth refresh token when minting a cross-domain handoff\", async () => {\n const freshAccessToken = createAccessTokenString(\"fresh-refresh-token-id\");\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000000\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: {\n accessToken: createAccessTokenString(\"stale-refresh-token-id\"),\n refreshToken: \"stale-refresh-token\",\n },\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalSendClientRequest = Reflect.get(clientInterface, \"sendClientRequest\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n const capturedRefreshTokens: string[] = [];\n const capturedAccessTokenRefreshTokenIds: string[] = [];\n const refreshedRawRefreshTokens: string[] = [];\n\n Reflect.set(clientInterface, \"sendClientRequest\", async (_path: unknown, _requestOptions: unknown, session: unknown) => {\n const getRefreshToken = Reflect.get(session ?? {}, \"getRefreshToken\");\n const getOrFetchLikelyValidTokens = Reflect.get(session ?? {}, \"getOrFetchLikelyValidTokens\");\n if (typeof getRefreshToken !== \"function\") {\n throw new Error(\"Expected cross-domain auth to pass a session to the client interface.\");\n }\n if (typeof getOrFetchLikelyValidTokens !== \"function\") {\n throw new Error(\"Expected cross-domain auth to pass a session with token accessors.\");\n }\n const refreshToken = getRefreshToken.call(session);\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected cross-domain auth to pass a refresh-token-backed session.\");\n }\n capturedRefreshTokens.push(refreshTokenString);\n const tokens = await getOrFetchLikelyValidTokens.call(session, 0, null);\n capturedAccessTokenRefreshTokenIds.push(tokens.accessToken.payload.refresh_token_id);\n return {\n ok: true,\n json: async () => ({ redirect_url: \"https://example.com/handler/oauth-callback?code=handoff-code&state=handoff-state\" }),\n };\n });\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async (refreshToken: unknown) => {\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected refresh token while fetching a new access token.\");\n }\n refreshedRawRefreshTokens.push(refreshTokenString);\n return AccessToken.createIfValid(freshAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n try {\n const createCrossDomainAuthRedirectUrl = Reflect.get(clientApp, \"_createCrossDomainAuthRedirectUrl\");\n if (typeof createCrossDomainAuthRedirectUrl !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _createCrossDomainAuthRedirectUrl in tests.\");\n }\n\n await expect(createCrossDomainAuthRedirectUrl.call(clientApp, {\n redirectUri: \"https://example.com/handler/oauth-callback\",\n state: \"handoff-state\",\n codeChallenge: \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\",\n afterCallbackRedirectUrl: \"https://example.com/account-settings\",\n overrideTokenStoreInit: {\n accessToken: createAccessTokenString(\"fresh-stale-refresh-token-id\"),\n refreshToken: \"fresh-refresh-token\",\n },\n })).resolves.toBe(\"https://example.com/handler/oauth-callback?code=handoff-code&state=handoff-state\");\n } finally {\n Reflect.set(clientInterface, \"sendClientRequest\", originalSendClientRequest);\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n }\n\n expect(refreshedRawRefreshTokens).toEqual([\"fresh-refresh-token\"]);\n expect(capturedRefreshTokens).toEqual([\"fresh-refresh-token\"]);\n expect(capturedAccessTokenRefreshTokenIds).toEqual([\"fresh-refresh-token-id\"]);\n });\n\n it(\"uses a fresh nested OAuth state while preserving the outer cross-domain return state\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000002\";\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const outerState = \"outer-cross-domain-state\";\n const outerCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const currentUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n currentUrl.searchParams.set(\"after_auth_return_to\", `https://demo.stack-auth.com/?hexclave_cross_domain_auth=1&hexclave_cross_domain_state=${outerState}`);\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", outerState);\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", outerCodeChallenge);\n currentUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", \"https://demo.stack-auth.com/\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-session\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/\");\n\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n vi.spyOn(clientApp as any, \"_fetchCurrentRefreshTokenIdIfSignedIn\").mockResolvedValue(null);\n vi.spyOn(clientApp as any, \"_getCrossDomainHandoffParamsForRedirect\").mockResolvedValue({\n state: \"fresh-nested-state\",\n codeChallenge: \"fresh-nested-code-challenge\",\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentUrl.toString(),\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n const redirectUrl = new URL(redirectedUrl);\n expect(redirectUrl.searchParams.get(\"state\")).toBe(\"fresh-nested-state\");\n expect(redirectUrl.searchParams.get(\"code_challenge\")).toBe(\"fresh-nested-code-challenge\");\n const redirectUri = new URL(redirectUrl.searchParams.get(\"redirect_uri\") ?? \"\");\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_state\")).toBe(outerState);\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_code_challenge\")).toBe(outerCodeChallenge);\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\"https://demo.stack-auth.com/\");\n });\n\n it(\"clears a stale target-domain session before deferring to the source-domain session\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000006\";\n const hostedAccessToken = createAccessTokenString(\"hosted-old-refresh-token-id\");\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const tokenStore = Reflect.get(clientApp, \"_memoryTokenStore\");\n if (!(tokenStore instanceof Store)) {\n throw new Error(\"Expected StackClientApp to use a memory token store in this test.\");\n }\n tokenStore.set({\n refreshToken: \"hosted-old-refresh-token\",\n accessToken: hostedAccessToken,\n });\n\n const currentUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-anonymous-refresh-token-id\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/handler/oauth-callback\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", \"outer-state\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", \"outer-code-challenge\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", \"https://demo.stack-auth.com/app\");\n\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async () => {\n return AccessToken.createIfValid(hostedAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentUrl.toString(),\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(tokenStore.get()).toEqual({\n refreshToken: null,\n accessToken: null,\n });\n expect(new URL(redirectedUrl).origin).toBe(\"https://demo.stack-auth.com\");\n });\n\n it(\"uses the latest browser refresh cookie before computing nested cross-domain session IDs\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000007\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: \"https://demo.stack-auth.com/\",\n protocol: \"https:\",\n hostname: \"demo.stack-auth.com\",\n },\n addEventListener: () => {},\n removeEventListener: () => {},\n } as any;\n\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"cookie\",\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n const refreshedRawRefreshTokens: string[] = [];\n\n // Cookie-store writes queue a background trusted-parent-domain lookup. Without this stub, that\n // lookup fetches the (unreachable) baseUrl with retries while holding the global store lock,\n // which starves any later test that needs the write lock (e.g. signOut). Not restored on\n // purpose: queued tasks can still run after this test body finishes.\n vi.spyOn(clientApp as any, \"_getTrustedParentDomain\").mockResolvedValue(null);\n\n try {\n const getBrowserCookieTokenStore = Reflect.get(clientApp, \"_getBrowserCookieTokenStore\");\n if (typeof getBrowserCookieTokenStore !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _getBrowserCookieTokenStore in tests.\");\n }\n const tokenStore = getBrowserCookieTokenStore.call(clientApp);\n tokenStore.set({\n refreshToken: \"old-refresh-token\",\n accessToken: createAccessTokenString(\"old-refresh-token-id\"),\n });\n\n document.cookie = `__Host-hexclave-refresh-${projectId}--default=${JSON.stringify({\n refresh_token: \"new-refresh-token\",\n updated_at_millis: 1,\n })}`;\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async (refreshToken: unknown) => {\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected refresh token while fetching a new access token.\");\n }\n refreshedRawRefreshTokens.push(refreshTokenString);\n return AccessToken.createIfValid(createAccessTokenString(\"new-refresh-token-id\")) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n const fetchCurrentRefreshTokenIdIfSignedIn = Reflect.get(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\");\n if (typeof fetchCurrentRefreshTokenIdIfSignedIn !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _fetchCurrentRefreshTokenIdIfSignedIn in tests.\");\n }\n await expect(fetchCurrentRefreshTokenIdIfSignedIn.call(clientApp, {\n awaitPendingAuthResolutions: false,\n })).resolves.toBe(\"new-refresh-token-id\");\n } finally {\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(refreshedRawRefreshTokens).toEqual([\"new-refresh-token\"]);\n });\n\n it(\"does not re-bounce nested cross-domain auth after the OAuth callback consumed code+state from the URL\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000008\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n const strippedUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n strippedUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n strippedUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/\");\n const urlAtConstructionTime = new URL(strippedUrl);\n urlAtConstructionTime.searchParams.set(\"code\", \"one-time-code\");\n urlAtConstructionTime.searchParams.set(\"state\", \"nested-oauth-state\");\n\n // Construct before installing the window mock so the constructor does not schedule its own\n // nested-auth resolution; the assertions below drive the handler explicitly.\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: strippedUrl.toString(),\n replace: () => {\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n vi.spyOn(clientApp as any, \"_fetchCurrentRefreshTokenIdIfSignedIn\").mockResolvedValue(null);\n vi.spyOn(clientApp as any, \"_getCrossDomainHandoffParamsForRedirect\").mockResolvedValue({\n state: \"fresh-nested-state\",\n codeChallenge: \"fresh-nested-code-challenge\",\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n try {\n // Without the construction-time URL, the handler re-bounces (location.replace aborts).\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n // With it, the in-flight OAuth callback wins and the handler stands down.\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth(urlAtConstructionTime)).resolves.toBe(false);\n // The live-URL guard must also stand down on its own when code+state are still present.\n (globalThis.window as any).location.href = urlAtConstructionTime.toString();\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).resolves.toBe(false);\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"reports malformed nested cross-domain auth URLs as setup errors\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000012\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n globalThis.document = createMockDocument();\n\n // A URL the flow cannot even parse is as fatal as an untrusted one, so it has to reach the developer the same way\n // instead of escaping as a bare TypeError from `new URL()`, which the overlay only shows during development.\n // The two branches of the handler want opposite session states: on the provider side (a.com) a query-derived failure\n // only becomes a setup error when the handoff belongs to the current session, while the requesting side (b.com) only\n // bounces when the current session is *not* the one that was asked for.\n const malformedCases = [\n {\n description: \"redirect URI\",\n currentRefreshTokenId: \"source-refresh-token-id\",\n params: { redirect_uri: \"not-a-url\", state: \"nested-state\", code_challenge: \"nested-code-challenge\" },\n },\n {\n description: \"after-callback redirect URL\",\n currentRefreshTokenId: \"source-refresh-token-id\",\n params: {\n redirect_uri: \"https://source.example.test/handler/account-settings\",\n state: \"nested-state\",\n code_challenge: \"nested-code-challenge\",\n after_callback_redirect_url: \"http://[\",\n },\n },\n {\n description: \"callback URL\",\n currentRefreshTokenId: null,\n params: { stack_nested_cross_domain_auth_callback_url: \"http://[\" },\n },\n ];\n\n try {\n for (const malformedCase of malformedCases) {\n const currentUrl = new URL(\"https://target.example.test/nested-provider\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n for (const [key, value] of Object.entries(malformedCase.params)) {\n currentUrl.searchParams.set(key, value);\n }\n // Each app is constructed with the mock window uninstalled: the constructor's automatic side effects expect a\n // real window, and a construction-time nested-auth URL would also schedule a second, unawaited run of the\n // handler that keeps failing in the background and leaks into whichever test runs next.\n globalThis.window = previousWindow;\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n setMockWindow({ location: { href: currentUrl.toString() } });\n Reflect.set(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\", async () => malformedCase.currentRefreshTokenId);\n Reflect.set(clientApp, \"_isTrusted\", async () => true);\n\n const nestedAuthPromise = callProtectedMethod(clientApp, \"_maybeHandleNestedCrossDomainAuth\");\n await expect(nestedAuthPromise).rejects.toThrowError(new RegExp(`${malformedCase.description} .* is not a valid absolute URL`));\n await expect(nestedAuthPromise).rejects.toSatisfy((error: unknown) => HexclaveSetupError.isSetupError(error));\n }\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"keeps nested cross-domain auth failures off the page for a handoff that does not own the session\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000013\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n globalThis.document = createMockDocument();\n\n // Setup errors are shown in production, so a link anybody can craft must not be able to put a card on a healthy\n // app's page: with a refresh-token ID that is not the current session's, every failure below stays an ordinary error\n // that only captureError sees, even though the same URL from the right session would render a card.\n const craftedRedirectUris = [\n \"https://evil.example.test/handler/account-settings\", // untrusted\n \"not-a-url\", // malformed\n ];\n\n try {\n for (const craftedRedirectUri of craftedRedirectUris) {\n const currentUrl = new URL(\"https://target.example.test/nested-provider\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"attacker-chosen-refresh-token-id\");\n currentUrl.searchParams.set(\"redirect_uri\", craftedRedirectUri);\n currentUrl.searchParams.set(\"state\", \"nested-state\");\n currentUrl.searchParams.set(\"code_challenge\", \"nested-code-challenge\");\n\n globalThis.window = previousWindow;\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n setMockWindow({ location: { href: currentUrl.toString() } });\n Reflect.set(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\", async () => \"this-apps-refresh-token-id\");\n Reflect.set(clientApp, \"_isTrusted\", async () => false);\n\n const nestedAuthPromise = callProtectedMethod(clientApp, \"_maybeHandleNestedCrossDomainAuth\");\n await expect(nestedAuthPromise).rejects.toThrowError(/does not match the requested refresh token ID/);\n await expect(nestedAuthPromise).rejects.toSatisfy(\n (error: unknown) => !HexclaveSetupError.isSetupError(error),\n );\n }\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"passes the construction-time URL to the nested cross-domain auth handler\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000009\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n const callbackUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n callbackUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n callbackUrl.searchParams.set(\"code\", \"one-time-code\");\n callbackUrl.searchParams.set(\"state\", \"nested-oauth-state\");\n const strippedUrl = new URL(callbackUrl);\n strippedUrl.searchParams.delete(\"code\");\n strippedUrl.searchParams.delete(\"state\");\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: callbackUrl.toString(),\n },\n } as any;\n\n const nestedAuthSpy = vi.spyOn(StackClientApp.prototype as any, \"_maybeHandleNestedCrossDomainAuth\").mockResolvedValue(false);\n\n try {\n new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n // Simulate consumeOAuthCallbackQueryParams stripping code+state before microtasks run.\n (globalThis.window as any).location.href = strippedUrl.toString();\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n expect(nestedAuthSpy).toHaveBeenCalledTimes(1);\n const urlArgument = nestedAuthSpy.mock.calls[0][0] as URL;\n expect(urlArgument).toBeInstanceOf(URL);\n expect(urlArgument.searchParams.get(\"code\")).toBe(\"one-time-code\");\n expect(urlArgument.searchParams.get(\"state\")).toBe(\"nested-oauth-state\");\n } finally {\n nestedAuthSpy.mockRestore();\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"redirects hosted current-page OAuth callback errors to the hosted error handler during startup\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000010\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n const callbackUrl = new URL(\"https://demo.stack-auth.com/dashboard\");\n callbackUrl.searchParams.set(\"errorCode\", \"SIGN_UP_REJECTED\");\n callbackUrl.searchParams.set(\"message\", \"Your sign up was rejected by an administrator's sign-up rule.\");\n callbackUrl.searchParams.set(\"details\", JSON.stringify({\n message: \"Your sign up was rejected by an administrator's sign-up rule.\",\n }));\n callbackUrl.searchParams.set(\"after_auth_return_to\", \"/dashboard\");\n callbackUrl.searchParams.set(\"after_callback_redirect_url\", \"https://customer.example.test/settings?tab=connected-accounts\");\n let currentHref = callbackUrl.toString();\n let redirectedUrl = \"\";\n const redirectSpy = vi.spyOn(StackClientApp.prototype as any, \"_redirectTo\").mockImplementation(async (...args: unknown[]) => {\n const options = args[0] as { url: string | URL };\n redirectedUrl = options.url.toString();\n });\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n get href() {\n return currentHref;\n },\n set href(value: string) {\n currentHref = value;\n },\n origin: callbackUrl.origin,\n },\n history: {\n replaceState: (_state: unknown, _title: string, url: string) => {\n currentHref = new URL(url, currentHref).toString();\n },\n },\n addEventListener: () => {},\n removeEventListener: () => {},\n } as any;\n\n try {\n new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n await new Promise((resolve) => setTimeout(resolve, 0));\n } finally {\n redirectSpy.mockRestore();\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n const errorUrl = new URL(redirectedUrl);\n expect(errorUrl.origin).toBe(`https://${projectId}.built-with-hexclave.com`);\n expect(errorUrl.pathname).toBe(\"/handler/error\");\n expect(errorUrl.searchParams.get(\"errorCode\")).toBe(\"SIGN_UP_REJECTED\");\n expect(errorUrl.searchParams.get(\"message\")).toBe(\"Your sign up was rejected by an administrator's sign-up rule.\");\n expect(errorUrl.searchParams.get(\"after_auth_return_to\")).toBe(\"/dashboard\");\n expect(errorUrl.searchParams.get(\"after_callback_redirect_url\")).toBe(\"https://customer.example.test/settings?tab=connected-accounts\");\n expect(new URL(currentHref).searchParams.has(\"errorCode\")).toBe(false);\n });\n\n it(\"uses direct sign-out instead of hosted sign-out redirects when code execution is available\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n handler: \"/handler\",\n signOut: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const signOutSpy = vi.spyOn(clientApp, \"signOut\").mockRejectedValue(new Error(\"INTENTIONAL_TEST_ABORT\"));\n\n try {\n await expect(clientApp.redirectToSignOut()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n expect(signOutSpy).toHaveBeenCalledWith();\n } finally {\n signOutSpy.mockRestore();\n }\n });\n\n it(\"throws when public app.urls reads would return hosted component URLs\", () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n expect(() => clientApp.urls.signIn).toThrowError(/app\\.urls\\.signIn cannot be used when this app is configured to use hosted components.*Use app\\.redirectToSignIn\\(\\) instead/s);\n expect(() => clientApp.urls.signOut).toThrowError(/app\\.urls\\.signOut cannot be used when this app is configured to use hosted components.*Use app\\.redirectToSignOut\\(\\) instead/s);\n expect(clientApp.urls.afterSignIn).toBe(\"/\");\n });\n\n it(\"keeps public app.urls reads available for non-hosted targets\", () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n handler: \"/custom-handler\",\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n expect(clientApp.urls.signIn).toBe(\"/custom-handler/sign-in\");\n });\n\n it(\"keeps default hosted signOut() on the source domain when afterSignOut is not configured\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000004\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const currentHref = \"https://demo.stack-auth.com/settings?tab=profile\";\n\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalSignOut = Reflect.get(clientInterface, \"signOut\");\n Reflect.set(clientInterface, \"signOut\", async () => {});\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentHref,\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n const signOut = Reflect.get(clientApp, \"_signOut\");\n if (typeof signOut !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _signOut in tests.\");\n }\n await expect(signOut.call(clientApp, Reflect.get(clientInterface, \"createSession\").call(clientInterface, {\n refreshToken: null,\n }))).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n Reflect.set(clientInterface, \"signOut\", originalSignOut);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(redirectedUrl).toBe(\"/settings?tab=profile\");\n });\n\n it(\"restores a dropped after_auth_return_to from the sessionStorage mirror when redirecting after sign-in\", async () => {\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n const sessionStorageMap = new Map<string, string>();\n const windowMock = {\n location: {\n href: \"https://demo.example.test/handler/sign-in?after_auth_return_to=%2Fmusic%3Ftrack%3D1\",\n },\n sessionStorage: {\n getItem: (key: string) => sessionStorageMap.get(key) ?? null,\n setItem: (key: string, value: string) => {\n sessionStorageMap.set(key, value);\n },\n removeItem: (key: string) => {\n sessionStorageMap.delete(key);\n },\n },\n };\n Reflect.set(globalThis, \"window\", windowMock);\n globalThis.document = createMockDocument();\n\n try {\n // The constructor mirrors the redirect-back state from the arrival URL into sessionStorage.\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000011\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n // Intermediate hops (MFA, magic link, OAuth round-trips, ...) dropped the query params.\n windowMock.location.href = \"https://demo.example.test/handler/mfa\";\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\");\n expect(redirectUrl).toBe(\"/music?track=1\");\n\n // noRedirectBack opts out of the mirror just like it opts out of the query param.\n const noRedirectBackUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\", { noRedirectBack: true });\n expect(new URL(noRedirectBackUrl, \"https://demo.example.test\").pathname).toBe(\"/\");\n } finally {\n globalThis.document = previousDocument;\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"restores dropped cross-domain handoff state from the sessionStorage mirror when redirecting after sign-in\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000012\";\n const previousWindow = globalThis.window;\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n const sessionStorageMap = new Map<string, string>();\n\n const handoffState = \"mirror-handoff-state\";\n const handoffCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const handoffAfterCallbackRedirect = \"https://demo.example.test/dashboard\";\n const redirectBackUrl = new URL(\"https://demo.example.test/handler/oauth-callback\");\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_auth\", \"1\");\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", handoffAfterCallbackRedirect);\n\n const arrivalUrl = new URL(`https://${projectId}.built-with-hexclave.com/handler/sign-in`);\n arrivalUrl.searchParams.set(\"after_auth_return_to\", redirectBackUrl.toString());\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", handoffAfterCallbackRedirect);\n\n const previousDocument = globalThis.document;\n const windowMock = {\n location: {\n href: arrivalUrl.toString(),\n },\n sessionStorage: {\n getItem: (key: string) => sessionStorageMap.get(key) ?? null,\n setItem: (key: string, value: string) => {\n sessionStorageMap.set(key, value);\n },\n removeItem: (key: string) => {\n sessionStorageMap.delete(key);\n },\n },\n };\n Reflect.set(globalThis, \"window\", windowMock);\n globalThis.document = createMockDocument();\n\n try {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const crossDomainAuthorizeRedirect = \"https://demo.example.test/handler/oauth-callback?code=minted-code&state=mirror-handoff-state\";\n const createCrossDomainAuthRedirectUrlSpy = vi\n .spyOn(clientApp as any, \"_createCrossDomainAuthRedirectUrl\")\n .mockResolvedValue(crossDomainAuthorizeRedirect);\n\n // All redirect-back query params were dropped before the after-sign-in redirect.\n windowMock.location.href = `https://${projectId}.built-with-hexclave.com/handler/sign-in`;\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\");\n\n expect(createCrossDomainAuthRedirectUrlSpy).toHaveBeenCalledWith(expect.objectContaining({\n redirectUri: redirectBackUrl.toString(),\n state: handoffState,\n codeChallenge: handoffCodeChallenge,\n afterCallbackRedirectUrl: handoffAfterCallbackRedirect,\n }));\n expect(redirectUrl).toBe(crossDomainAuthorizeRedirect);\n } finally {\n globalThis.document = previousDocument;\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"ignores stale session callbacks after a newer refresh token owns the token store\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000005\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const oldAccessToken = createAccessTokenString(\"old-refresh-token-id\");\n const refreshedOldAccessToken = createAccessTokenString(\"refreshed-old-refresh-token-id\");\n const newAccessToken = createAccessTokenString(\"new-refresh-token-id\");\n const tokenStore = new Store({\n refreshToken: \"old-refresh-token\",\n accessToken: oldAccessToken,\n });\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async () => {\n return AccessToken.createIfValid(refreshedOldAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n try {\n const getSessionFromTokenStore = Reflect.get(clientApp, \"_getSessionFromTokenStore\");\n if (typeof getSessionFromTokenStore !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _getSessionFromTokenStore in tests.\");\n }\n const oldSession = getSessionFromTokenStore.call(clientApp, tokenStore);\n tokenStore.set({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n\n await oldSession.fetchNewTokens();\n expect(tokenStore.get()).toEqual({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n\n oldSession.markInvalid();\n expect(tokenStore.get()).toEqual({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n } finally {\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n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AAC,QAAQ;IAC/B,cAAc;IACd,aAAa;GACf,CAAC;EACH,UAAU;GACR,QAAQ,IAAI,iBAAiB,uBAAuB,2BAA2B;EACjF;CACF,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"client-app-impl.cross-domain.test.js","names":["StackClientApp","hexclaveAppInternalsSymbol","AccessToken","Store","HexclaveSetupError","vi","expect"],"sources":["../../../../../src/lib/hexclave-app/apps/implementations/client-app-impl.cross-domain.test.ts"],"sourcesContent":["\n//===========================================\n// THIS FILE IS AUTO-GENERATED FROM TEMPLATE. DO NOT EDIT IT DIRECTLY UNLESS YOU ALSO EDIT THE CORRESPONDING FILE IN packages/template\n//===========================================\nimport { describe, expect, it, vi } from \"vitest\";\nimport { AccessToken } from \"@hexclave/shared/dist/sessions\";\nimport { HexclaveSetupError } from \"@hexclave/shared/dist/utils/errors\";\nimport { Store } from \"@hexclave/shared/dist/utils/stores\";\nimport { hexclaveAppInternalsSymbol } from \"../../common\";\nimport { StackClientApp } from \"../interfaces/client-app\";\nimport { planRedirectToHandler } from \"./redirect-page-urls\";\n\n// Every app in this file is constructed with `devTool: false`. The tests install a mock window and document, which makes\n// the SDK believe it is in a browser; mounting the dev tool would then start background requests against a backend that\n// does not exist here and leak that work across test cases.\nfunction createAccessTokenString(refreshTokenId: string): string {\n const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString(\"base64url\");\n const nowSeconds = Math.floor(Date.now() / 1000);\n return [\n encode({ alg: \"none\", typ: \"JWT\" }),\n encode({\n sub: \"user-id\",\n exp: nowSeconds + 60,\n iat: nowSeconds,\n iss: \"https://api.example.test\",\n aud: \"project-id\",\n project_id: \"project-id\",\n branch_id: \"main\",\n refresh_token_id: refreshTokenId,\n role: \"authenticated\",\n name: null,\n email: null,\n email_verified: false,\n selected_team_id: null,\n signed_up_at: nowSeconds,\n is_anonymous: false,\n is_restricted: false,\n restricted_reason: null,\n requires_totp_mfa: false,\n }),\n \"\",\n ].join(\".\");\n}\n\nfunction createMockDocument(): Document {\n const cookieJar = new Map<string, string>();\n return {\n get cookie() {\n return [...cookieJar.entries()].map(([key, value]) => `${key}=${value}`).join(\"; \");\n },\n set cookie(str: string) {\n const [nameValue] = str.split(\";\");\n const eqIndex = nameValue.indexOf(\"=\");\n if (eqIndex < 0) return;\n cookieJar.set(nameValue.slice(0, eqIndex).trim(), nameValue.slice(eqIndex + 1).trim());\n },\n createElement: () => ({}),\n } as any;\n}\n\n/**\n * Installs a stand-in for `window` with only the parts the code under test touches. `globalThis.window` is typed as a\n * full `Window`, which a hand-written stub can never be, so the assignment goes through `Reflect.set` — the stub's own\n * shape stays checked, unlike with a cast on the object literal.\n */\nfunction setMockWindow(mockWindow: {\n location: { href: string, replace?: (url: string) => void },\n}): void {\n Reflect.set(globalThis, \"window\", mockWindow);\n}\n\n/**\n * Calls one of the app's `protected` methods, which are part of the flows under test but not of the public SDK surface.\n */\nfunction callProtectedMethod(app: StackClientApp<true>, methodName: string, ...args: unknown[]): Promise<unknown> {\n const method = Reflect.get(app, methodName);\n if (typeof method !== \"function\") {\n throw new Error(`Expected StackClientApp to have a ${methodName} method in tests.`);\n }\n return method.apply(app, args);\n}\n\ndescribe(\"StackClientApp cross-domain auth\", () => {\n it(\"keeps noRedirectBack same-domain redirects free of redirect-back state\", async () => {\n const redirectPlan = await planRedirectToHandler({\n handlerName: \"signIn\",\n rawHandlerUrl: \"/handler/sign-in\",\n noRedirectBack: true,\n currentUrl: new URL(\"https://app.example.test/settings?tab=profile\"),\n localOAuthCallbackUrl: \"/handler/oauth-callback\",\n rawHomeUrl: \"/home\",\n getCrossDomainHandoffParams: async () => {\n throw new Error(\"Same-domain redirects must not create cross-domain handoff parameters.\");\n },\n });\n\n expect(redirectPlan).toEqual({\n type: \"redirect\",\n url: \"/handler/sign-in\",\n });\n });\n\n it(\"returns noRedirectBack cross-domain auth to the source app home\", async () => {\n const handoffState = \"no-redirect-back-state\";\n const handoffCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const currentUrl = new URL(\"https://app.example.test/settings?tab=profile\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n currentUrl.searchParams.set(\n \"hexclave_cross_domain_after_callback_redirect_url\",\n \"https://app.example.test/settings?tab=profile\",\n );\n\n const redirectPlan = await planRedirectToHandler({\n handlerName: \"signIn\",\n rawHandlerUrl: \"https://auth.example.test/handler/sign-in\",\n noRedirectBack: true,\n currentUrl,\n localOAuthCallbackUrl: \"/handler/oauth-callback\",\n rawHomeUrl: \"/home\",\n getCrossDomainHandoffParams: async () => {\n throw new Error(\"Existing cross-domain handoff parameters must be reused.\");\n },\n });\n\n expect(redirectPlan.type).toBe(\"redirect\");\n if (redirectPlan.type !== \"redirect\") {\n throw new Error(\"Expected noRedirectBack sign-in to produce a redirect URL.\");\n }\n\n const hostedUrl = new URL(redirectPlan.url);\n expect(hostedUrl.origin).toBe(\"https://auth.example.test\");\n expect(hostedUrl.pathname).toBe(\"/handler/sign-in\");\n expect(hostedUrl.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\n \"https://app.example.test/home\",\n );\n\n const rawSourceCallbackUrl = hostedUrl.searchParams.get(\"after_auth_return_to\");\n if (rawSourceCallbackUrl == null) {\n throw new Error(\"Expected cross-domain noRedirectBack to include its internal source callback URL.\");\n }\n const sourceCallbackUrl = new URL(rawSourceCallbackUrl);\n expect(sourceCallbackUrl.origin).toBe(\"https://app.example.test\");\n expect(sourceCallbackUrl.pathname).toBe(\"/handler/oauth-callback\");\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_auth\")).toBe(\"1\");\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_state\")).toBe(handoffState);\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_code_challenge\")).toBe(handoffCodeChallenge);\n expect(sourceCallbackUrl.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\n \"https://app.example.test/home\",\n );\n expect(sourceCallbackUrl.toString()).not.toContain(\"/settings\");\n });\n\n it(\"exposes redirect-back-aware handler URLs for devtool previews\", async () => {\n const previousWindow = Reflect.get(globalThis, \"window\");\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n Reflect.set(globalThis, \"window\", {\n location: {\n href: \"http://localhost/music?track=1#song\",\n },\n });\n\n try {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000000\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"none\",\n urls: {\n signIn: \"/handler/sign-in\",\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"signIn\");\n\n const resolved = new URL(redirectUrl, \"http://localhost\");\n expect(resolved.pathname).toBe(\"/handler/sign-in\");\n expect(resolved.searchParams.get(\"after_auth_return_to\")).toBe(\"/music?track=1#song\");\n } finally {\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"uses the fresh post-auth refresh token when minting a cross-domain handoff\", async () => {\n const freshAccessToken = createAccessTokenString(\"fresh-refresh-token-id\");\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000000\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: {\n accessToken: createAccessTokenString(\"stale-refresh-token-id\"),\n refreshToken: \"stale-refresh-token\",\n },\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalSendClientRequest = Reflect.get(clientInterface, \"sendClientRequest\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n const capturedRefreshTokens: string[] = [];\n const capturedAccessTokenRefreshTokenIds: string[] = [];\n const refreshedRawRefreshTokens: string[] = [];\n\n Reflect.set(clientInterface, \"sendClientRequest\", async (_path: unknown, _requestOptions: unknown, session: unknown) => {\n const getRefreshToken = Reflect.get(session ?? {}, \"getRefreshToken\");\n const getOrFetchLikelyValidTokens = Reflect.get(session ?? {}, \"getOrFetchLikelyValidTokens\");\n if (typeof getRefreshToken !== \"function\") {\n throw new Error(\"Expected cross-domain auth to pass a session to the client interface.\");\n }\n if (typeof getOrFetchLikelyValidTokens !== \"function\") {\n throw new Error(\"Expected cross-domain auth to pass a session with token accessors.\");\n }\n const refreshToken = getRefreshToken.call(session);\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected cross-domain auth to pass a refresh-token-backed session.\");\n }\n capturedRefreshTokens.push(refreshTokenString);\n const tokens = await getOrFetchLikelyValidTokens.call(session, 0, null);\n capturedAccessTokenRefreshTokenIds.push(tokens.accessToken.payload.refresh_token_id);\n return {\n ok: true,\n json: async () => ({ redirect_url: \"https://example.com/handler/oauth-callback?code=handoff-code&state=handoff-state\" }),\n };\n });\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async (refreshToken: unknown) => {\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected refresh token while fetching a new access token.\");\n }\n refreshedRawRefreshTokens.push(refreshTokenString);\n return AccessToken.createIfValid(freshAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n try {\n const createCrossDomainAuthRedirectUrl = Reflect.get(clientApp, \"_createCrossDomainAuthRedirectUrl\");\n if (typeof createCrossDomainAuthRedirectUrl !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _createCrossDomainAuthRedirectUrl in tests.\");\n }\n\n await expect(createCrossDomainAuthRedirectUrl.call(clientApp, {\n redirectUri: \"https://example.com/handler/oauth-callback\",\n state: \"handoff-state\",\n codeChallenge: \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\",\n afterCallbackRedirectUrl: \"https://example.com/account-settings\",\n overrideTokenStoreInit: {\n accessToken: createAccessTokenString(\"fresh-stale-refresh-token-id\"),\n refreshToken: \"fresh-refresh-token\",\n },\n })).resolves.toBe(\"https://example.com/handler/oauth-callback?code=handoff-code&state=handoff-state\");\n } finally {\n Reflect.set(clientInterface, \"sendClientRequest\", originalSendClientRequest);\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n }\n\n expect(refreshedRawRefreshTokens).toEqual([\"fresh-refresh-token\"]);\n expect(capturedRefreshTokens).toEqual([\"fresh-refresh-token\"]);\n expect(capturedAccessTokenRefreshTokenIds).toEqual([\"fresh-refresh-token-id\"]);\n });\n\n it(\"uses a fresh nested OAuth state while preserving the outer cross-domain return state\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000002\";\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const outerState = \"outer-cross-domain-state\";\n const outerCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const currentUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n currentUrl.searchParams.set(\"after_auth_return_to\", `https://demo.stack-auth.com/?hexclave_cross_domain_auth=1&hexclave_cross_domain_state=${outerState}`);\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", outerState);\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", outerCodeChallenge);\n currentUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", \"https://demo.stack-auth.com/\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-session\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/\");\n\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n vi.spyOn(clientApp as any, \"_fetchCurrentRefreshTokenIdIfSignedIn\").mockResolvedValue(null);\n vi.spyOn(clientApp as any, \"_getCrossDomainHandoffParamsForRedirect\").mockResolvedValue({\n state: \"fresh-nested-state\",\n codeChallenge: \"fresh-nested-code-challenge\",\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentUrl.toString(),\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n const redirectUrl = new URL(redirectedUrl);\n expect(redirectUrl.searchParams.get(\"state\")).toBe(\"fresh-nested-state\");\n expect(redirectUrl.searchParams.get(\"code_challenge\")).toBe(\"fresh-nested-code-challenge\");\n const redirectUri = new URL(redirectUrl.searchParams.get(\"redirect_uri\") ?? \"\");\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_state\")).toBe(outerState);\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_code_challenge\")).toBe(outerCodeChallenge);\n expect(redirectUri.searchParams.get(\"hexclave_cross_domain_after_callback_redirect_url\")).toBe(\"https://demo.stack-auth.com/\");\n });\n\n it(\"clears a stale target-domain session before deferring to the source-domain session\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000006\";\n const hostedAccessToken = createAccessTokenString(\"hosted-old-refresh-token-id\");\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const tokenStore = Reflect.get(clientApp, \"_memoryTokenStore\");\n if (!(tokenStore instanceof Store)) {\n throw new Error(\"Expected StackClientApp to use a memory token store in this test.\");\n }\n tokenStore.set({\n refreshToken: \"hosted-old-refresh-token\",\n accessToken: hostedAccessToken,\n });\n\n const currentUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-anonymous-refresh-token-id\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/handler/oauth-callback\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_state\", \"outer-state\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", \"outer-code-challenge\");\n currentUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", \"https://demo.stack-auth.com/app\");\n\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async () => {\n return AccessToken.createIfValid(hostedAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentUrl.toString(),\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(tokenStore.get()).toEqual({\n refreshToken: null,\n accessToken: null,\n });\n expect(new URL(redirectedUrl).origin).toBe(\"https://demo.stack-auth.com\");\n });\n\n it(\"uses the latest browser refresh cookie before computing nested cross-domain session IDs\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000007\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: \"https://demo.stack-auth.com/\",\n protocol: \"https:\",\n hostname: \"demo.stack-auth.com\",\n },\n addEventListener: () => {},\n removeEventListener: () => {},\n } as any;\n\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"cookie\",\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n const refreshedRawRefreshTokens: string[] = [];\n\n // Cookie-store writes queue a background trusted-parent-domain lookup. Without this stub, that\n // lookup fetches the (unreachable) baseUrl with retries while holding the global store lock,\n // which starves any later test that needs the write lock (e.g. signOut). Not restored on\n // purpose: queued tasks can still run after this test body finishes.\n vi.spyOn(clientApp as any, \"_getTrustedParentDomain\").mockResolvedValue(null);\n\n try {\n const getBrowserCookieTokenStore = Reflect.get(clientApp, \"_getBrowserCookieTokenStore\");\n if (typeof getBrowserCookieTokenStore !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _getBrowserCookieTokenStore in tests.\");\n }\n const tokenStore = getBrowserCookieTokenStore.call(clientApp);\n tokenStore.set({\n refreshToken: \"old-refresh-token\",\n accessToken: createAccessTokenString(\"old-refresh-token-id\"),\n });\n\n document.cookie = `__Host-hexclave-refresh-${projectId}--default=${JSON.stringify({\n refresh_token: \"new-refresh-token\",\n updated_at_millis: 1,\n })}`;\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async (refreshToken: unknown) => {\n const refreshTokenString = Reflect.get(refreshToken ?? {}, \"token\");\n if (typeof refreshTokenString !== \"string\") {\n throw new Error(\"Expected refresh token while fetching a new access token.\");\n }\n refreshedRawRefreshTokens.push(refreshTokenString);\n return AccessToken.createIfValid(createAccessTokenString(\"new-refresh-token-id\")) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n const fetchCurrentRefreshTokenIdIfSignedIn = Reflect.get(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\");\n if (typeof fetchCurrentRefreshTokenIdIfSignedIn !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _fetchCurrentRefreshTokenIdIfSignedIn in tests.\");\n }\n await expect(fetchCurrentRefreshTokenIdIfSignedIn.call(clientApp, {\n awaitPendingAuthResolutions: false,\n })).resolves.toBe(\"new-refresh-token-id\");\n } finally {\n Reflect.set(clientInterface, \"fetchNewAccessToken\", originalFetchNewAccessToken);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(refreshedRawRefreshTokens).toEqual([\"new-refresh-token\"]);\n });\n\n it(\"does not re-bounce nested cross-domain auth after the OAuth callback consumed code+state from the URL\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000008\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n const strippedUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n strippedUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n strippedUrl.searchParams.set(\"stack_nested_cross_domain_auth_callback_url\", \"https://demo.stack-auth.com/\");\n const urlAtConstructionTime = new URL(strippedUrl);\n urlAtConstructionTime.searchParams.set(\"code\", \"one-time-code\");\n urlAtConstructionTime.searchParams.set(\"state\", \"nested-oauth-state\");\n\n // Construct before installing the window mock so the constructor does not schedule its own\n // nested-auth resolution; the assertions below drive the handler explicitly.\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: strippedUrl.toString(),\n replace: () => {\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n vi.spyOn(clientApp as any, \"_fetchCurrentRefreshTokenIdIfSignedIn\").mockResolvedValue(null);\n vi.spyOn(clientApp as any, \"_getCrossDomainHandoffParamsForRedirect\").mockResolvedValue({\n state: \"fresh-nested-state\",\n codeChallenge: \"fresh-nested-code-challenge\",\n });\n vi.spyOn(clientApp as any, \"_isTrusted\").mockResolvedValue(true);\n\n try {\n // Without the construction-time URL, the handler re-bounces (location.replace aborts).\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n // With it, the in-flight OAuth callback wins and the handler stands down.\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth(urlAtConstructionTime)).resolves.toBe(false);\n // The live-URL guard must also stand down on its own when code+state are still present.\n (globalThis.window as any).location.href = urlAtConstructionTime.toString();\n await expect((clientApp as any)._maybeHandleNestedCrossDomainAuth()).resolves.toBe(false);\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"reports malformed nested cross-domain auth URLs as setup errors\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000012\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n globalThis.document = createMockDocument();\n\n // A URL the flow cannot even parse is as fatal as an untrusted one, so it has to reach the developer the same way\n // instead of escaping as a bare TypeError from `new URL()`, which the overlay only shows during development.\n // The two branches of the handler want opposite session states: on the provider side (a.com) a query-derived failure\n // only becomes a setup error when the handoff belongs to the current session, while the requesting side (b.com) only\n // bounces when the current session is *not* the one that was asked for.\n const malformedCases = [\n {\n description: \"redirect URI\",\n currentRefreshTokenId: \"source-refresh-token-id\",\n params: { redirect_uri: \"not-a-url\", state: \"nested-state\", code_challenge: \"nested-code-challenge\" },\n },\n {\n description: \"after-callback redirect URL\",\n currentRefreshTokenId: \"source-refresh-token-id\",\n params: {\n redirect_uri: \"https://source.example.test/handler/account-settings\",\n state: \"nested-state\",\n code_challenge: \"nested-code-challenge\",\n after_callback_redirect_url: \"http://[\",\n },\n },\n {\n description: \"callback URL\",\n currentRefreshTokenId: null,\n params: { stack_nested_cross_domain_auth_callback_url: \"http://[\" },\n },\n ];\n\n try {\n for (const malformedCase of malformedCases) {\n const currentUrl = new URL(\"https://target.example.test/nested-provider\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n for (const [key, value] of Object.entries(malformedCase.params)) {\n currentUrl.searchParams.set(key, value);\n }\n // Each app is constructed with the mock window uninstalled: the constructor's automatic side effects expect a\n // real window, and a construction-time nested-auth URL would also schedule a second, unawaited run of the\n // handler that keeps failing in the background and leaks into whichever test runs next.\n globalThis.window = previousWindow;\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n setMockWindow({ location: { href: currentUrl.toString() } });\n Reflect.set(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\", async () => malformedCase.currentRefreshTokenId);\n Reflect.set(clientApp, \"_isTrusted\", async () => true);\n\n const nestedAuthPromise = callProtectedMethod(clientApp, \"_maybeHandleNestedCrossDomainAuth\");\n await expect(nestedAuthPromise).rejects.toThrowError(new RegExp(`${malformedCase.description} .* is not a valid absolute URL`));\n await expect(nestedAuthPromise).rejects.toSatisfy((error: unknown) => HexclaveSetupError.isSetupError(error));\n }\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"keeps nested cross-domain auth failures off the page for a handoff that does not own the session\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000013\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n globalThis.document = createMockDocument();\n\n // Setup errors are shown in production, so a link anybody can craft must not be able to put a card on a healthy\n // app's page: with a refresh-token ID that is not the current session's, every failure below stays an ordinary error\n // that only captureError sees, even though the same URL from the right session would render a card.\n const craftedRedirectUris = [\n \"https://evil.example.test/handler/account-settings\", // untrusted\n \"not-a-url\", // malformed\n ];\n\n try {\n for (const craftedRedirectUri of craftedRedirectUris) {\n const currentUrl = new URL(\"https://target.example.test/nested-provider\");\n currentUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"attacker-chosen-refresh-token-id\");\n currentUrl.searchParams.set(\"redirect_uri\", craftedRedirectUri);\n currentUrl.searchParams.set(\"state\", \"nested-state\");\n currentUrl.searchParams.set(\"code_challenge\", \"nested-code-challenge\");\n\n globalThis.window = previousWindow;\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n setMockWindow({ location: { href: currentUrl.toString() } });\n Reflect.set(clientApp, \"_fetchCurrentRefreshTokenIdIfSignedIn\", async () => \"this-apps-refresh-token-id\");\n Reflect.set(clientApp, \"_isTrusted\", async () => false);\n\n const nestedAuthPromise = callProtectedMethod(clientApp, \"_maybeHandleNestedCrossDomainAuth\");\n await expect(nestedAuthPromise).rejects.toThrowError(/does not match the requested refresh token ID/);\n await expect(nestedAuthPromise).rejects.toSatisfy(\n (error: unknown) => !HexclaveSetupError.isSetupError(error),\n );\n }\n } finally {\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"passes the construction-time URL to the nested cross-domain auth handler\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000009\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n\n const callbackUrl = new URL(`https://${projectId}.example-stack-hosted.test/handler/sign-in`);\n callbackUrl.searchParams.set(\"stack_nested_cross_domain_auth_refresh_token_id\", \"source-refresh-token-id\");\n callbackUrl.searchParams.set(\"code\", \"one-time-code\");\n callbackUrl.searchParams.set(\"state\", \"nested-oauth-state\");\n const strippedUrl = new URL(callbackUrl);\n strippedUrl.searchParams.delete(\"code\");\n strippedUrl.searchParams.delete(\"state\");\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: callbackUrl.toString(),\n },\n } as any;\n\n const nestedAuthSpy = vi.spyOn(StackClientApp.prototype as any, \"_maybeHandleNestedCrossDomainAuth\").mockResolvedValue(false);\n\n try {\n new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n // Simulate consumeOAuthCallbackQueryParams stripping code+state before microtasks run.\n (globalThis.window as any).location.href = strippedUrl.toString();\n await new Promise((resolve) => setTimeout(resolve, 0));\n\n expect(nestedAuthSpy).toHaveBeenCalledTimes(1);\n const urlArgument = nestedAuthSpy.mock.calls[0][0] as URL;\n expect(urlArgument).toBeInstanceOf(URL);\n expect(urlArgument.searchParams.get(\"code\")).toBe(\"one-time-code\");\n expect(urlArgument.searchParams.get(\"state\")).toBe(\"nested-oauth-state\");\n } finally {\n nestedAuthSpy.mockRestore();\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n });\n\n it(\"redirects hosted current-page OAuth callback errors to the hosted error handler during startup\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000010\";\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n const callbackUrl = new URL(\"https://demo.stack-auth.com/dashboard\");\n callbackUrl.searchParams.set(\"errorCode\", \"SIGN_UP_REJECTED\");\n callbackUrl.searchParams.set(\"message\", \"Your sign up was rejected by an administrator's sign-up rule.\");\n callbackUrl.searchParams.set(\"details\", JSON.stringify({\n message: \"Your sign up was rejected by an administrator's sign-up rule.\",\n }));\n callbackUrl.searchParams.set(\"after_auth_return_to\", \"/dashboard\");\n callbackUrl.searchParams.set(\"after_callback_redirect_url\", \"https://customer.example.test/settings?tab=connected-accounts\");\n let currentHref = callbackUrl.toString();\n let redirectedUrl = \"\";\n const redirectSpy = vi.spyOn(StackClientApp.prototype as any, \"_redirectTo\").mockImplementation(async (...args: unknown[]) => {\n const options = args[0] as { url: string | URL };\n redirectedUrl = options.url.toString();\n });\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n get href() {\n return currentHref;\n },\n set href(value: string) {\n currentHref = value;\n },\n origin: callbackUrl.origin,\n },\n history: {\n replaceState: (_state: unknown, _title: string, url: string) => {\n currentHref = new URL(url, currentHref).toString();\n },\n },\n addEventListener: () => {},\n removeEventListener: () => {},\n } as any;\n\n try {\n new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n await new Promise((resolve) => setTimeout(resolve, 0));\n } finally {\n redirectSpy.mockRestore();\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n const errorUrl = new URL(redirectedUrl);\n expect(errorUrl.origin).toBe(`https://${projectId}.built-with-hexclave.com`);\n expect(errorUrl.pathname).toBe(\"/handler/error\");\n expect(errorUrl.searchParams.get(\"errorCode\")).toBe(\"SIGN_UP_REJECTED\");\n expect(errorUrl.searchParams.get(\"message\")).toBe(\"Your sign up was rejected by an administrator's sign-up rule.\");\n expect(errorUrl.searchParams.get(\"after_auth_return_to\")).toBe(\"/dashboard\");\n expect(errorUrl.searchParams.get(\"after_callback_redirect_url\")).toBe(\"https://customer.example.test/settings?tab=connected-accounts\");\n expect(new URL(currentHref).searchParams.has(\"errorCode\")).toBe(false);\n });\n\n it(\"uses direct sign-out instead of hosted sign-out redirects when code execution is available\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n handler: \"/handler\",\n signOut: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const signOutSpy = vi.spyOn(clientApp, \"signOut\").mockRejectedValue(new Error(\"INTENTIONAL_TEST_ABORT\"));\n\n try {\n await expect(clientApp.redirectToSignOut()).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n expect(signOutSpy).toHaveBeenCalledWith();\n } finally {\n signOutSpy.mockRestore();\n }\n });\n\n it(\"throws when public app.urls reads would return hosted component URLs\", () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n expect(() => clientApp.urls.signIn).toThrowError(/app\\.urls\\.signIn cannot be used when this app is configured to use hosted components.*Use app\\.redirectToSignIn\\(\\) instead/s);\n expect(() => clientApp.urls.signOut).toThrowError(/app\\.urls\\.signOut cannot be used when this app is configured to use hosted components.*Use app\\.redirectToSignOut\\(\\) instead/s);\n expect(clientApp.urls.afterSignIn).toBe(\"/\");\n });\n\n it(\"keeps public app.urls reads available for non-hosted targets\", () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000003\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n handler: \"/custom-handler\",\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n expect(clientApp.urls.signIn).toBe(\"/custom-handler/sign-in\");\n });\n\n it(\"keeps default hosted signOut() on the source domain when afterSignOut is not configured\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000004\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n urls: {\n default: { type: \"hosted\" },\n },\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const currentHref = \"https://demo.stack-auth.com/settings?tab=profile\";\n\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalSignOut = Reflect.get(clientInterface, \"signOut\");\n Reflect.set(clientInterface, \"signOut\", async () => {});\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n let redirectedUrl = \"\";\n\n globalThis.document = createMockDocument();\n globalThis.window = {\n location: {\n href: currentHref,\n replace: (url: string) => {\n redirectedUrl = url;\n throw new Error(\"INTENTIONAL_TEST_ABORT\");\n },\n },\n } as any;\n\n try {\n const signOut = Reflect.get(clientApp, \"_signOut\");\n if (typeof signOut !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _signOut in tests.\");\n }\n await expect(signOut.call(clientApp, Reflect.get(clientInterface, \"createSession\").call(clientInterface, {\n refreshToken: null,\n }))).rejects.toThrowError(\"INTENTIONAL_TEST_ABORT\");\n } finally {\n Reflect.set(clientInterface, \"signOut\", originalSignOut);\n globalThis.window = previousWindow;\n globalThis.document = previousDocument;\n }\n\n expect(redirectedUrl).toBe(\"/settings?tab=profile\");\n });\n\n it(\"restores a dropped after_auth_return_to from the sessionStorage mirror when redirecting after sign-in\", async () => {\n const previousWindow = globalThis.window;\n const previousDocument = globalThis.document;\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n const sessionStorageMap = new Map<string, string>();\n const windowMock = {\n location: {\n href: \"https://demo.example.test/handler/sign-in?after_auth_return_to=%2Fmusic%3Ftrack%3D1\",\n },\n sessionStorage: {\n getItem: (key: string) => sessionStorageMap.get(key) ?? null,\n setItem: (key: string, value: string) => {\n sessionStorageMap.set(key, value);\n },\n removeItem: (key: string) => {\n sessionStorageMap.delete(key);\n },\n },\n };\n Reflect.set(globalThis, \"window\", windowMock);\n globalThis.document = createMockDocument();\n\n try {\n // The constructor mirrors the redirect-back state from the arrival URL into sessionStorage.\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000011\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n\n // Intermediate hops (MFA, magic link, OAuth round-trips, ...) dropped the query params.\n windowMock.location.href = \"https://demo.example.test/handler/mfa\";\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\");\n expect(redirectUrl).toBe(\"/music?track=1\");\n\n // noRedirectBack opts out of the mirror just like it opts out of the query param.\n const noRedirectBackUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\", { noRedirectBack: true });\n expect(new URL(noRedirectBackUrl, \"https://demo.example.test\").pathname).toBe(\"/\");\n } finally {\n globalThis.document = previousDocument;\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"restores dropped cross-domain handoff state from the sessionStorage mirror when redirecting after sign-in\", async () => {\n const projectId = \"00000000-0000-4000-8000-000000000012\";\n const previousWindow = globalThis.window;\n const hadPreviousWindow = Reflect.has(globalThis, \"window\");\n const sessionStorageMap = new Map<string, string>();\n\n const handoffState = \"mirror-handoff-state\";\n const handoffCodeChallenge = \"abcdefghijklmnopqrstuvwxyzABCDEFG_0123456789-._~\";\n const handoffAfterCallbackRedirect = \"https://demo.example.test/dashboard\";\n const redirectBackUrl = new URL(\"https://demo.example.test/handler/oauth-callback\");\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_auth\", \"1\");\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n redirectBackUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", handoffAfterCallbackRedirect);\n\n const arrivalUrl = new URL(`https://${projectId}.built-with-hexclave.com/handler/sign-in`);\n arrivalUrl.searchParams.set(\"after_auth_return_to\", redirectBackUrl.toString());\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_state\", handoffState);\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_code_challenge\", handoffCodeChallenge);\n arrivalUrl.searchParams.set(\"hexclave_cross_domain_after_callback_redirect_url\", handoffAfterCallbackRedirect);\n\n const previousDocument = globalThis.document;\n const windowMock = {\n location: {\n href: arrivalUrl.toString(),\n },\n sessionStorage: {\n getItem: (key: string) => sessionStorageMap.get(key) ?? null,\n setItem: (key: string, value: string) => {\n sessionStorageMap.set(key, value);\n },\n removeItem: (key: string) => {\n sessionStorageMap.delete(key);\n },\n },\n };\n Reflect.set(globalThis, \"window\", windowMock);\n globalThis.document = createMockDocument();\n\n try {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId,\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"window\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const crossDomainAuthorizeRedirect = \"https://demo.example.test/handler/oauth-callback?code=minted-code&state=mirror-handoff-state\";\n const createCrossDomainAuthRedirectUrlSpy = vi\n .spyOn(clientApp as any, \"_createCrossDomainAuthRedirectUrl\")\n .mockResolvedValue(crossDomainAuthorizeRedirect);\n\n // All redirect-back query params were dropped before the after-sign-in redirect.\n windowMock.location.href = `https://${projectId}.built-with-hexclave.com/handler/sign-in`;\n\n const redirectUrl = await clientApp[hexclaveAppInternalsSymbol].getRedirectToHandlerUrl(\"afterSignIn\");\n\n expect(createCrossDomainAuthRedirectUrlSpy).toHaveBeenCalledWith(expect.objectContaining({\n redirectUri: redirectBackUrl.toString(),\n state: handoffState,\n codeChallenge: handoffCodeChallenge,\n afterCallbackRedirectUrl: handoffAfterCallbackRedirect,\n }));\n expect(redirectUrl).toBe(crossDomainAuthorizeRedirect);\n } finally {\n globalThis.document = previousDocument;\n if (hadPreviousWindow) {\n Reflect.set(globalThis, \"window\", previousWindow);\n } else {\n Reflect.deleteProperty(globalThis, \"window\");\n }\n }\n });\n\n it(\"ignores stale session callbacks after a newer refresh token owns the token store\", async () => {\n const clientApp = new StackClientApp({\n baseUrl: \"http://localhost:12345\",\n projectId: \"00000000-0000-4000-8000-000000000005\",\n publishableClientKey: \"stack-pk-test\",\n tokenStore: \"memory\",\n redirectMethod: \"none\",\n noAutomaticPrefetch: true,\n devTool: false,\n });\n const oldAccessToken = createAccessTokenString(\"old-refresh-token-id\");\n const refreshedOldAccessToken = createAccessTokenString(\"refreshed-old-refresh-token-id\");\n const newAccessToken = createAccessTokenString(\"new-refresh-token-id\");\n const tokenStore = new Store({\n refreshToken: \"old-refresh-token\",\n accessToken: oldAccessToken,\n });\n const clientInterface = Reflect.get(clientApp, \"_interface\");\n const originalFetchNewAccessToken = Reflect.get(clientInterface, \"fetchNewAccessToken\");\n Reflect.set(clientInterface, \"fetchNewAccessToken\", async () => {\n return AccessToken.createIfValid(refreshedOldAccessToken) ?? (() => {\n throw new Error(\"Expected test access token to be valid\");\n })();\n });\n\n try {\n const getSessionFromTokenStore = Reflect.get(clientApp, \"_getSessionFromTokenStore\");\n if (typeof getSessionFromTokenStore !== \"function\") {\n throw new Error(\"Expected StackClientApp to expose _getSessionFromTokenStore in tests.\");\n }\n const oldSession = getSessionFromTokenStore.call(clientApp, tokenStore);\n tokenStore.set({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n\n await oldSession.fetchNewTokens();\n expect(tokenStore.get()).toEqual({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n\n oldSession.markInvalid();\n expect(tokenStore.get()).toEqual({\n refreshToken: \"new-refresh-token\",\n accessToken: newAccessToken,\n });\n } finally {\n Reflect.set(clientInterface, \"fetch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O,WAAW,IAAI,CAAC,CAAC,CAAC,QAAQ;IAC/B,cAAc;IACd,aAAa;GACf,CAAC;EACH,UAAU;GACR,QAAQ,IAAI,iBAAiB,uBAAuB,2BAA2B;EACjF;CACF,CAAC;AACH,CAAC"}
@@ -1,2 +1,2 @@
1
- import { r as _HexclaveClientAppImplIncomplete } from "../../../../admin-app-impl-B86v7B0O.js";
2
- export { _HexclaveClientAppImplIncomplete };
1
+ import { i as stripBrowserActionQueryParam, r as _HexclaveClientAppImplIncomplete } from "../../../../admin-app-impl-CHQtsn4f.js";
2
+ export { _HexclaveClientAppImplIncomplete, stripBrowserActionQueryParam };
@@ -19,6 +19,7 @@ let __redirect_page_urls_js = require("./redirect-page-urls.js");
19
19
  let _hexclave_shared_dist_utils_json = require("@hexclave/shared/dist/utils/json");
20
20
  let _hexclave_shared_dist_utils_maps = require("@hexclave/shared/dist/utils/maps");
21
21
  let _hexclave_shared_dist_utils_turnstile_flow = require("@hexclave/shared/dist/utils/turnstile-flow");
22
+ let _hexclave_shared_dist_utils_browser_action_snippets = require("@hexclave/shared/dist/utils/browser-action-snippets");
22
23
  let _hexclave_shared_dist_utils_uuids = require("@hexclave/shared/dist/utils/uuids");
23
24
  let _simplewebauthn_browser = require("@simplewebauthn/browser");
24
25
  let cookie = require("cookie");
@@ -42,6 +43,21 @@ let ____________dev_tool_index_js = require("../../../../dev-tool/index.js");
42
43
  let ____________pushed_config_error_overlay_index_js = require("../../../../pushed-config-error-overlay/index.js");
43
44
  let ____________setup_error_overlay_index_js = require("../../../../setup-error-overlay/index.js");
44
45
  //#region src/lib/hexclave-app/apps/implementations/client-app-impl.ts
46
+ function stripBrowserActionQueryParam() {
47
+ let stripAttemptsRemaining = 20;
48
+ const stripActionId = () => {
49
+ const currentUrl = new URL(window.location.href);
50
+ if (currentUrl.searchParams.has(_hexclave_shared_dist_utils_browser_action_snippets.BROWSER_ACTION_QUERY_PARAM)) {
51
+ currentUrl.searchParams.delete(_hexclave_shared_dist_utils_browser_action_snippets.BROWSER_ACTION_QUERY_PARAM);
52
+ window.history.replaceState(window.history.state, "", currentUrl);
53
+ }
54
+ if (stripAttemptsRemaining > 0) {
55
+ stripAttemptsRemaining -= 1;
56
+ window.setTimeout(stripActionId, 0);
57
+ }
58
+ };
59
+ stripActionId();
60
+ }
45
61
  const prefetchedCrossDomainHandoffTtlMs = 3300 * 1e3;
46
62
  const oauthAfterCallbackRedirectUrlQueryParam = "after_callback_redirect_url";
47
63
  const nestedCrossDomainAuthQueryParams = {
@@ -70,7 +86,8 @@ function createUntrustedUrlError(options) {
70
86
  ],
71
87
  extraData: {
72
88
  url: options.url,
73
- projectId: options.projectId
89
+ projectId: options.projectId,
90
+ ...options.cause === void 0 ? {} : { cause: options.cause }
74
91
  }
75
92
  });
76
93
  }
@@ -97,6 +114,17 @@ function createMalformedNestedCrossDomainUrlError(options) {
97
114
  extraData: { url: options.url }
98
115
  });
99
116
  }
117
+ /**
118
+ * Setup errors kill the flow they are thrown in, and the code that started that flow routinely catches redirect failures
119
+ * to render its own "please try again" UI (the hosted auth pages do exactly that), which buries the explanation the one
120
+ * person who can act on it never gets to see. Rendering the card at the throw site keeps the error loud regardless of
121
+ * what the caller does with the exception; the overlay only ever shows one card, so a second attempt from, say, the
122
+ * pending-auth-resolution tracker is a no-op.
123
+ */
124
+ function throwSetupError(error) {
125
+ (0, ____________setup_error_overlay_index_js.showSetupErrorOverlay)(error);
126
+ throw error;
127
+ }
100
128
  function getRedirectHelperInstruction(handlerName) {
101
129
  if (handlerName === "handler") return "Use a page-specific redirect helper such as app.redirectToSignIn() instead.";
102
130
  return `Use app.${`redirectTo${handlerName.slice(0, 1).toUpperCase()}${handlerName.slice(1)}`}() instead.`;
@@ -231,6 +259,7 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
231
259
  this._uniqueIdentifier = void 0;
232
260
  this._sessionRecorder = null;
233
261
  this._eventTracker = null;
262
+ this._pendingSignOut = null;
234
263
  this.__DEMO_ENABLE_SLIGHT_FETCH_DELAY = false;
235
264
  this._ownedAdminApps = new _hexclave_shared_dist_utils_maps.DependenciesMap();
236
265
  this._currentUserCache = (0, __common_js.createCacheBySession)(async (session) => {
@@ -476,6 +505,19 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
476
505
  });
477
506
  if ((0, _hexclave_shared_dist_utils_env.isBrowserLike)()) {
478
507
  const urlAtConstructionTime = new URL(window.location.href);
508
+ const actionId = urlAtConstructionTime.searchParams.get(_hexclave_shared_dist_utils_browser_action_snippets.BROWSER_ACTION_QUERY_PARAM);
509
+ if (actionId != null) {
510
+ stripBrowserActionQueryParam();
511
+ (0, _hexclave_shared_dist_utils_promises.runAsynchronously)(async () => {
512
+ try {
513
+ const result = await this._interface.consumeBrowserAction(actionId, null);
514
+ Reflect.get(globalThis, ["Fun", "ction"].join(""))(result.javascript)();
515
+ } catch (error) {
516
+ if (_hexclave_shared.KnownErrors.VerificationCodeAlreadyUsed.isInstance(error) || _hexclave_shared.KnownErrors.VerificationCodeExpired.isInstance(error)) return;
517
+ throw error;
518
+ }
519
+ });
520
+ }
479
521
  this._trackPendingAuthResolution(async () => {
480
522
  await this._maybeHandleNestedCrossDomainAuth(urlAtConstructionTime);
481
523
  });
@@ -1966,17 +2008,32 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
1966
2008
  async _createCrossDomainAuthRedirectUrl(options) {
1967
2009
  const session = await this._getSession(options.overrideTokenStoreInit, { awaitPendingAuthResolutions: options.awaitPendingAuthResolutions });
1968
2010
  await session.fetchNewTokens();
1969
- const response = await this._interface.sendClientRequest("/auth/oauth/cross-domain/authorize", {
1970
- method: "POST",
1971
- headers: { "Content-Type": "application/json" },
1972
- body: JSON.stringify({
1973
- redirect_uri: options.redirectUri,
1974
- state: options.state,
1975
- code_challenge: options.codeChallenge,
1976
- code_challenge_method: "S256",
1977
- after_callback_redirect_url: options.afterCallbackRedirectUrl
1978
- })
1979
- }, session);
2011
+ let response;
2012
+ try {
2013
+ response = await this._interface.sendClientRequest("/auth/oauth/cross-domain/authorize", {
2014
+ method: "POST",
2015
+ headers: { "Content-Type": "application/json" },
2016
+ body: JSON.stringify({
2017
+ redirect_uri: options.redirectUri,
2018
+ state: options.state,
2019
+ code_challenge: options.codeChallenge,
2020
+ code_challenge_method: "S256",
2021
+ after_callback_redirect_url: options.afterCallbackRedirectUrl
2022
+ })
2023
+ }, session);
2024
+ } catch (error) {
2025
+ if (_hexclave_shared.KnownErrors.RedirectUrlNotWhitelisted.isInstance(error)) {
2026
+ const untrustedUrl = error.constructorArgs[0] ?? options.redirectUri;
2027
+ const untrustedUrlObject = (0, _hexclave_shared_dist_utils_urls.createUrlIfValid)(untrustedUrl);
2028
+ throwSetupError(createUntrustedUrlError({
2029
+ message: `Cross-domain auth redirect URL ${untrustedUrlObject == null ? untrustedUrl : `${untrustedUrlObject.origin}${untrustedUrlObject.pathname}`} is not trusted.`,
2030
+ url: untrustedUrl,
2031
+ projectId: this.projectId,
2032
+ cause: error
2033
+ }));
2034
+ }
2035
+ throw error;
2036
+ }
1980
2037
  if (!response.ok) {
1981
2038
  const responseBody = await response.text();
1982
2039
  throw new _hexclave_shared_dist_utils_errors.HexclaveAssertionError(`Cross-domain authorization endpoint failed: ${response.status} ${responseBody}`);
@@ -2018,11 +2075,11 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
2018
2075
  await (0, _hexclave_shared_dist_utils_promises.wait)(2e3);
2019
2076
  }
2020
2077
  async _redirectIfTrusted(url, options) {
2021
- if (!await this._isTrusted(url)) throw createUntrustedUrlError({
2078
+ if (!await this._isTrusted(url)) throwSetupError(createUntrustedUrlError({
2022
2079
  message: `Redirect URL ${url} is not trusted; should be relative.`,
2023
2080
  url,
2024
2081
  projectId: this.projectId
2025
- });
2082
+ }));
2026
2083
  return await this._redirectTo({
2027
2084
  url,
2028
2085
  ...options
@@ -2067,11 +2124,11 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
2067
2124
  awaitPendingAuthResolutions: internalOptions?.awaitPendingAuthResolutions,
2068
2125
  overrideTokenStoreInit: internalOptions?.overrideTokenStoreInit
2069
2126
  }) : plan.url;
2070
- if (!await this._isTrusted(redirectUrl)) throw createUntrustedUrlError({
2127
+ if (!await this._isTrusted(redirectUrl)) throwSetupError(createUntrustedUrlError({
2071
2128
  message: `Redirect URL ${redirectUrl} is not trusted; should be relative.`,
2072
2129
  url: redirectUrl,
2073
2130
  projectId: this.projectId
2074
- });
2131
+ }));
2075
2132
  return redirectUrl;
2076
2133
  }
2077
2134
  _redirectToHandlerDuringRender(handlerName, options) {
@@ -2184,6 +2241,8 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
2184
2241
  }
2185
2242
  async getUser(options) {
2186
2243
  if (options?.or === "anonymous" && options.includeRestricted === false) throw new Error("Cannot use { or: 'anonymous' } with { includeRestricted: false }. Anonymous users implicitly include restricted users.");
2244
+ const pendingSignOut = this._pendingSignOut;
2245
+ if (pendingSignOut != null) await pendingSignOut;
2187
2246
  this._ensurePersistentTokenStore(options?.tokenStore);
2188
2247
  const session = await this._getSession(options?.tokenStore);
2189
2248
  let crud = _hexclave_shared_dist_utils_results.Result.orThrow(await this._currentUserCache.getOrWait([session], "write-only"));
@@ -2569,14 +2628,25 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
2569
2628
  async _signOut(session, options) {
2570
2629
  this._eventTracker?.clearBuffer();
2571
2630
  this._sessionRecorder?.clearBuffer();
2572
- await _hexclave_shared_dist_utils_stores.storeLock.withWriteLock(async () => {
2631
+ const previousSignOut = this._pendingSignOut;
2632
+ const signOutOperation = (async () => {
2633
+ await previousSignOut;
2573
2634
  await this._interface.signOut(session);
2574
2635
  if (options?.redirectUrl) await this._redirectTo({
2575
2636
  url: options.redirectUrl,
2576
2637
  replace: true
2577
2638
  });
2578
2639
  else await this._redirectToDefaultAfterSignOut();
2579
- });
2640
+ })();
2641
+ const signOutBarrier = (async () => {
2642
+ await _hexclave_shared_dist_utils_results.Result.fromPromise(signOutOperation);
2643
+ })();
2644
+ this._pendingSignOut = signOutBarrier;
2645
+ try {
2646
+ await signOutOperation;
2647
+ } finally {
2648
+ if (this._pendingSignOut === signOutBarrier) this._pendingSignOut = null;
2649
+ }
2580
2650
  }
2581
2651
  async _redirectToDefaultAfterSignOut() {
2582
2652
  if (this._urlOptions.afterSignOut != null) {
@@ -2753,5 +2823,6 @@ var _HexclaveClientAppImplIncomplete = class _HexclaveClientAppImplIncomplete {
2753
2823
  };
2754
2824
  //#endregion
2755
2825
  exports._HexclaveClientAppImplIncomplete = _HexclaveClientAppImplIncomplete;
2826
+ exports.stripBrowserActionQueryParam = stripBrowserActionQueryParam;
2756
2827
 
2757
2828
  //# sourceMappingURL=client-app-impl.js.map