create-ailk 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/add-route.js +1 -1
  2. package/dist/derive-architecture.js +3 -1
  3. package/dist/remove-module.js +18 -14
  4. package/dist/routes.d.ts +29 -2
  5. package/dist/routes.js +269 -23
  6. package/dist/site-manifest.js +6 -4
  7. package/dist/site-roster.d.ts +11 -3
  8. package/dist/site-roster.js +42 -22
  9. package/dist/surfaces.d.ts +11 -3
  10. package/dist/surfaces.js +69 -22
  11. package/dist/sync-routes.js +22 -5
  12. package/dist/template-record.js +3 -1
  13. package/dist/topology.d.ts +11 -0
  14. package/dist/topology.js +253 -3
  15. package/package.json +3 -3
  16. package/templates/apps/web/CLAUDE.md +26 -4
  17. package/templates/apps/web/__tests__/__mocks__/next-intl-server.ts +5 -1
  18. package/templates/apps/web/__tests__/__mocks__/next-intl.ts +5 -1
  19. package/templates/apps/web/__tests__/auth/seam.test.ts +34 -0
  20. package/templates/apps/web/account.config.tsx +2 -3
  21. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  22. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +1 -1
  23. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +1 -1
  24. package/templates/apps/web/app/[locale]/layout.tsx +1 -1
  25. package/templates/apps/web/auth.config.tsx +107 -0
  26. package/templates/apps/web/auth.ts +2 -1
  27. package/templates/apps/web/i18n/request.ts +9 -2
  28. package/templates/apps/web/jest.config.cjs +4 -0
  29. package/templates/apps/web/lib/__tests__/fixtures/site-topology.ts +3 -0
  30. package/templates/apps/web/lib/__tests__/server-api.test.ts +1 -1
  31. package/templates/apps/web/lib/server-api.ts +1 -1
  32. package/templates/apps/web/lib/topology.generated.ts +5 -0
  33. package/templates/apps/web/messages/en.json +0 -152
  34. package/templates/apps/web/middleware.ts +12 -25
  35. package/templates/apps/web/next.config.mjs +8 -0
  36. package/templates/apps/web/package.json +1 -0
  37. package/templates/apps/web/types/messages.d.ts +6 -1
  38. package/versions.json +49 -48
  39. package/templates/apps/web/app/[locale]/(auth)/__tests__/auth-pages.test.tsx +0 -322
  40. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +0 -554
  41. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/consent-actions.test.ts +0 -56
  42. package/templates/apps/web/app/[locale]/(auth)/consent/__tests__/page.test.tsx +0 -164
  43. package/templates/apps/web/app/[locale]/(auth)/consent/consent-form.tsx +0 -132
  44. package/templates/apps/web/app/[locale]/(auth)/consent/consent.actions.ts +0 -51
  45. package/templates/apps/web/app/[locale]/(auth)/consent/page.tsx +0 -144
  46. package/templates/apps/web/app/[locale]/(auth)/forgot-password/forgot-password-card.tsx +0 -101
  47. package/templates/apps/web/app/[locale]/(auth)/forgot-password/page.tsx +0 -111
  48. package/templates/apps/web/app/[locale]/(auth)/layout.tsx +0 -81
  49. package/templates/apps/web/app/[locale]/(auth)/legal-footnote.tsx +0 -35
  50. package/templates/apps/web/app/[locale]/(auth)/reset-password/__tests__/return.test.tsx +0 -179
  51. package/templates/apps/web/app/[locale]/(auth)/reset-password/page.tsx +0 -157
  52. package/templates/apps/web/app/[locale]/(auth)/reset-password/reset-password-card.tsx +0 -126
  53. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/next-path.test.ts +0 -54
  54. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +0 -628
  55. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +0 -43
  56. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +0 -266
  57. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -20
  58. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +0 -234
  59. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +0 -37
  60. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +0 -323
  61. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +0 -93
  62. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/page.test.tsx +0 -301
  63. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +0 -309
  64. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +0 -201
  65. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +0 -366
  66. package/templates/apps/web/app/[locale]/(auth)/use-auth-card-flow.ts +0 -116
  67. package/templates/apps/web/app/[locale]/(auth)/verify-email/__tests__/actions.test.ts +0 -94
  68. package/templates/apps/web/app/[locale]/(auth)/verify-email/actions.ts +0 -77
  69. package/templates/apps/web/app/[locale]/(auth)/verify-email/page.tsx +0 -154
  70. package/templates/apps/web/app/[locale]/(authed)/account/appointments/[slug]/page.tsx +0 -3
  71. package/templates/apps/web/app/[locale]/(authed)/account/appointments/page.tsx +0 -3
  72. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +0 -3
  73. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/versions/[version]/file/route.ts +0 -2
  74. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +0 -3
  75. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +0 -12
  76. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +0 -12
  77. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +0 -12
  78. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +0 -2
  79. package/templates/apps/web/app/[locale]/(authed)/account/inbox/thread/page.tsx +0 -12
  80. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +0 -3
  81. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +0 -10
  82. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +0 -3
  83. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +0 -3
  84. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +0 -12
  85. package/templates/apps/web/app/[locale]/(authed)/account/privacy/export/route.ts +0 -2
  86. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +0 -3
  87. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +0 -3
  88. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +0 -2
  89. package/templates/apps/web/app/[locale]/(authed)/account/support/page.tsx +0 -3
  90. package/templates/apps/web/app/api/auth/[...all]/route.ts +0 -16
  91. package/templates/apps/web/app/api/auth/hub/__tests__/continuation.test.ts +0 -143
  92. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +0 -749
  93. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +0 -964
  94. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +0 -390
  95. package/templates/apps/web/app/api/auth/hub/continuation.ts +0 -127
  96. package/templates/apps/web/app/api/auth/hub/continue/[ref]/__tests__/route.test.ts +0 -188
  97. package/templates/apps/web/app/api/auth/hub/continue/[ref]/route.ts +0 -53
  98. package/templates/apps/web/app/api/auth/hub/email/route.ts +0 -111
  99. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +0 -163
  100. package/templates/apps/web/app/api/auth/hub/password/__tests__/return.test.ts +0 -86
  101. package/templates/apps/web/app/api/auth/hub/password/__tests__/route.test.ts +0 -368
  102. package/templates/apps/web/app/api/auth/hub/password/return.ts +0 -86
  103. package/templates/apps/web/app/api/auth/hub/password/route.ts +0 -171
  104. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +0 -230
  105. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +0 -174
  106. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +0 -60
  107. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +0 -97
  108. package/templates/apps/web/app/api/auth/mcp/__tests__/continuation.test.ts +0 -92
  109. package/templates/apps/web/app/api/auth/mcp/continuation.ts +0 -89
  110. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/__tests__/route.test.ts +0 -59
  111. package/templates/apps/web/app/api/auth/mcp/continue/[ref]/route.ts +0 -41
  112. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +0 -1166
  113. package/templates/apps/web/app/api/hub-session/callback/route.ts +0 -134
  114. package/templates/apps/web/app/api/hub-session/email/route.ts +0 -125
  115. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +0 -49
  116. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +0 -106
  117. package/templates/apps/web/app/api/hub-session/open/route.ts +0 -111
  118. package/templates/apps/web/app/api/hub-session/password/return/route.ts +0 -69
  119. package/templates/apps/web/app/api/hub-session/password/route.ts +0 -106
  120. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +0 -91
  121. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +0 -54
  122. package/templates/apps/web/components/sign-out-trigger.tsx +0 -62
  123. package/templates/apps/web/lib/__tests__/auth-routes.test.ts +0 -140
  124. package/templates/apps/web/lib/auth-routes.ts +0 -125
  125. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +0 -433
  126. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +0 -332
  127. package/templates/apps/web/lib/hub-session/config.ts +0 -110
  128. package/templates/apps/web/lib/hub-session/entry.ts +0 -238
  129. package/templates/apps/web/lib/hub-session/index.ts +0 -21
  130. package/templates/apps/web/lib/hub-session/one-tap.tsx +0 -148
  131. package/templates/apps/web/lib/hub-session/reseal.ts +0 -90
  132. package/templates/apps/web/lib/hub-session/seal.ts +0 -86
  133. package/templates/apps/web/lib/hub-session/session.ts +0 -298
  134. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +0 -277
  135. package/templates/apps/web/lib/next-path.ts +0 -35
@@ -1,964 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
-
5
- /**
6
- * Tests for the hub's authorize step (#7894, spec
7
- * docs/specs/7894-the-hub-signs-in-its-spec.md D4; AC-4, AC-6).
8
- *
9
- * The Better Auth session read and `@working-theory/api-client`'s `hubSignIn`
10
- * are the two external boundaries; both are mocked. The route's own decisions
11
- * are what is under test: which query it accepts, who it sends to sign in,
12
- * where a minted code goes, and what it refuses to redirect to.
13
- *
14
- * #8757 D9 (AC-6): an optional `login_hint` reaches the sign-in page as
15
- * `email` on the no-session branch only; it never enters the continuation ref
16
- * or the code redirect, and a repeated one is a 400 like any repeated key.
17
- *
18
- * #9912 D3 (AC-1): a single `prompt=create` sends a visitor with no session to
19
- * `/sign-up` with the same continuation; any other value gives `/sign-in`, a
20
- * session ignores it, and it never enters the ref or the code request.
21
- *
22
- * #9966 D2 (AC-4): a person who has not said yes to the spoke is sent to the
23
- * hub's consent page with a sealed ref; only that page's same-origin POST
24
- * sends `consent: true` — the GET a spoke can trigger on page load never does.
25
- *
26
- * #11096 D4 (AC-3): a single `provider_hint=google` with no session and Google
27
- * on goes straight to Google through `auth.api.signInSocial`, carrying the
28
- * state cookie Better Auth set; anything else is today's `/sign-in` redirect.
29
- */
30
-
31
- // --- Mocks set up BEFORE imports ---
32
-
33
- const mockGetSession = jest.fn();
34
- const mockSignInSocial = jest.fn();
35
- const mockSecret = "k".repeat(43);
36
- // eslint-disable-next-line no-restricted-syntax -- auth.ts is the Better Auth singleton (its adapter needs a live database); this stand-in for the session read is the repo-standard double for that boundary (see the sibling suites under app/[locale]/(authed)/account/__tests__).
37
- jest.mock("../../../../../../auth", () => ({
38
- __esModule: true,
39
- auth: {
40
- api: {
41
- getSession: (...args: unknown[]) => mockGetSession(...args),
42
- signInSocial: (...args: unknown[]) => mockSignInSocial(...args),
43
- },
44
- },
45
- resolveSecret: () => mockSecret,
46
- }));
47
-
48
- const mockCreateCode = jest.fn();
49
- jest.mock("@working-theory/api-client", () => ({
50
- __esModule: true,
51
- hubSignIn: { createCode: (...args: unknown[]) => mockCreateCode(...args) },
52
- }));
53
-
54
- import { resolveNextPath } from "../../../../../[locale]/(auth)/sign-in/next-path";
55
- import { mintContinuation, openContinuation } from "../../continuation";
56
- import { GET, POST } from "../route";
57
-
58
- const HUB = "https://hub.example.com";
59
- const CONTINUE = "/api/auth/hub/continue";
60
- const SPOKE_CALLBACK = "https://spoke.example.com/api/hub-session/callback";
61
- const CHALLENGE = "c".repeat(43);
62
- const STATE = "s".repeat(43);
63
- const CODE = "k".repeat(43);
64
-
65
- const ORIGINAL_ENV = process.env;
66
-
67
- function query(overrides: Record<string, string | undefined> = {}): string {
68
- const params = new URLSearchParams({
69
- response_type: "code",
70
- client_id: "spoke_abc",
71
- redirect_uri: SPOKE_CALLBACK,
72
- state: STATE,
73
- code_challenge: CHALLENGE,
74
- code_challenge_method: "S256",
75
- });
76
- for (const [key, value] of Object.entries(overrides)) {
77
- if (value === undefined) params.delete(key);
78
- else params.set(key, value);
79
- }
80
- return params.toString();
81
- }
82
-
83
- function request(
84
- search: string,
85
- headers: Record<string, string> = {},
86
- ): Request {
87
- return new Request(`${HUB}/api/auth/hub/authorize?${search}`, { headers });
88
- }
89
-
90
- beforeEach(() => {
91
- jest.resetAllMocks();
92
- process.env = { ...ORIGINAL_ENV, BETTER_AUTH_URL: `${HUB}/some/base` };
93
- });
94
-
95
- afterAll(() => {
96
- process.env = ORIGINAL_ENV;
97
- });
98
-
99
- describe("a malformed query is a 400 and never a redirect", () => {
100
- it.each([
101
- ["no client_id", { client_id: undefined }],
102
- ["response_type token", { response_type: "token" }],
103
- ["method plain", { code_challenge_method: "plain" }],
104
- ["a short code_challenge", { code_challenge: "short" }],
105
- ["no state", { state: undefined }],
106
- ["a state with a delimiter", { state: "a&b=c;d e" }],
107
- ["no redirect_uri", { redirect_uri: undefined }],
108
- ])("%s", async (_name, overrides) => {
109
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
110
-
111
- const res = await GET(request(query(overrides)));
112
-
113
- expect(res.status).toBe(400);
114
- expect(res.headers.get("location")).toBeNull();
115
- expect(res.headers.get("content-type")).toBe("application/json");
116
- expect(await res.json()).toEqual({ error: "invalid_request" });
117
- expect(mockCreateCode).not.toHaveBeenCalled();
118
- expect(mockGetSession).not.toHaveBeenCalled();
119
- });
120
-
121
- it("a repeated key is ambiguous, so 400", async () => {
122
- const res = await GET(request(`${query()}&client_id=spoke_other`));
123
- expect(res.status).toBe(400);
124
- expect(res.headers.get("location")).toBeNull();
125
- });
126
- });
127
-
128
- describe("no Better Auth session", () => {
129
- /** The `next` value of the 303, and the ref inside it. */
130
- function continuationOf(res: Response): { next: string; ref: string } {
131
- const location = res.headers.get("location") ?? "";
132
- const next = new URL(location, HUB).searchParams.get("next") ?? "";
133
- return { next, ref: next.slice(`${CONTINUE}/`.length) };
134
- }
135
-
136
- it("#8146 AC-1(b): 303 to /sign-in?next= followed by the encoded continue path and a sealed ref", async () => {
137
- mockGetSession.mockResolvedValue(null);
138
- const search = query();
139
-
140
- const res = await GET(request(search));
141
-
142
- expect(res.status).toBe(303);
143
- const { next, ref } = continuationOf(res);
144
- expect(res.headers.get("location")).toBe(
145
- `/sign-in?next=${encodeURIComponent(`${CONTINUE}/${ref}`)}`,
146
- );
147
- expect(next).toBe(`${CONTINUE}/${ref}`);
148
- expect(openContinuation(ref, mockSecret)).toBe(search);
149
- expect(res.headers.get("cache-control")).toBe("no-store");
150
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
151
- expect(mockCreateCode).not.toHaveBeenCalled();
152
- });
153
-
154
- it("#8146 AC-1(b): the next value is a same-origin path the sign-in card keeps (resolveNextPath) and a second decode cannot change", async () => {
155
- mockGetSession.mockResolvedValue(null);
156
-
157
- const res = await GET(request(query()));
158
-
159
- const { next } = continuationOf(res);
160
- expect(next.startsWith(`${CONTINUE}/`)).toBe(true);
161
- // Unchanged — not the fallback — so Better Auth is handed it as the callback
162
- // for Google and for the emailed link alike.
163
- expect(resolveNextPath(next, "/account")).toBe(next);
164
- expect(next).not.toMatch(/^https?:/);
165
- // Better Auth decodes the callback a second time: nothing may change.
166
- expect(next).toMatch(/^[A-Za-z0-9_/-]+$/);
167
- expect(decodeURIComponent(decodeURIComponent(next))).toBe(next);
168
- });
169
-
170
- it("#8146 AC-1(b): the ref holds the canonical six-key query — a reversed query with an extra key opens to the same string, without it", async () => {
171
- mockGetSession.mockResolvedValue(null);
172
- const canonical = query();
173
- const reversed = [...new URLSearchParams(canonical).entries()]
174
- .reverse()
175
- .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
176
- .join("&");
177
-
178
- const res = await GET(request(`${reversed}&extra=1`));
179
-
180
- expect(res.status).toBe(303);
181
- const opened = openContinuation(continuationOf(res).ref, mockSecret);
182
- expect(opened).toBe(canonical);
183
- expect(opened).not.toContain("extra");
184
- });
185
-
186
- it("#8146 AC-3(b): a redirect_uri whose ref would pass 4096 characters is a 400 with NO Location", async () => {
187
- mockGetSession.mockResolvedValue(null);
188
- const redirectUri = "https://spoke.example.com/".padEnd(2048, "/");
189
-
190
- const res = await GET(request(query({ redirect_uri: redirectUri })));
191
-
192
- expect(res.status).toBe(400);
193
- expect(res.headers.get("location")).toBeNull();
194
- expect(await res.json()).toEqual({ error: "invalid_request" });
195
- });
196
-
197
- it("#8146 AC-3(b): a 2048-character redirect_uri whose ref stays under the cap is a normal 303", async () => {
198
- mockGetSession.mockResolvedValue(null);
199
- const redirectUri = "https://spoke.example.com/".padEnd(2048, "a");
200
-
201
- const res = await GET(request(query({ redirect_uri: redirectUri })));
202
-
203
- expect(res.status).toBe(303);
204
- expect(res.headers.get("location")).toMatch(/^\/sign-in\?next=/);
205
- });
206
- });
207
-
208
- describe("a signed-in person", () => {
209
- beforeEach(() => {
210
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
211
- });
212
-
213
- it("AC-4: 303 to the REGISTERED redirect URI with the code and the same state", async () => {
214
- mockCreateCode.mockResolvedValue({
215
- ok: true,
216
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
217
- });
218
-
219
- const res = await GET(
220
- request(query(), { cookie: "better-auth.session_token=tok" }),
221
- );
222
-
223
- expect(res.status).toBe(303);
224
- const target = new URL(res.headers.get("location") ?? "");
225
- expect(`${target.origin}${target.pathname}`).toBe(SPOKE_CALLBACK);
226
- expect(target.searchParams.get("code")).toBe(CODE);
227
- expect(target.searchParams.get("state")).toBe(STATE);
228
- expect(res.headers.get("cache-control")).toBe("no-store");
229
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
230
- });
231
-
232
- it("forwards the visitor's cookie and the hub's pinned origin to the API — nothing else", async () => {
233
- mockCreateCode.mockResolvedValue({
234
- ok: true,
235
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
236
- });
237
-
238
- await GET(
239
- request(query(), {
240
- cookie: "better-auth.session_token=tok",
241
- origin: "https://evil.example",
242
- }),
243
- );
244
-
245
- expect(mockCreateCode).toHaveBeenCalledWith(
246
- {
247
- clientId: "spoke_abc",
248
- redirectUri: SPOKE_CALLBACK,
249
- codeChallenge: CHALLENGE,
250
- },
251
- { headers: { cookie: "better-auth.session_token=tok", origin: HUB } },
252
- );
253
- });
254
-
255
- it("AC-4: a redirect_uri the API does not register is a 400 with NO Location header", async () => {
256
- mockCreateCode.mockResolvedValue({
257
- ok: false,
258
- status: 400,
259
- body: {
260
- ok: false,
261
- error: { code: "invalid_redirect_uri", message: "x" },
262
- },
263
- });
264
-
265
- const res = await GET(
266
- request(
267
- query({
268
- redirect_uri: "https://attacker.example.com/api/hub-session/callback",
269
- }),
270
- ),
271
- );
272
-
273
- expect(res.status).toBe(400);
274
- expect(res.headers.get("location")).toBeNull();
275
- expect(await res.json()).toEqual({ error: "invalid_request" });
276
- });
277
-
278
- it("redirects to the URI the API echoed, never to the query's own", async () => {
279
- // A (hypothetical) API answer for a different URI than the query named.
280
- mockCreateCode.mockResolvedValue({
281
- ok: true,
282
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
283
- });
284
-
285
- const res = await GET(
286
- request(
287
- query({
288
- redirect_uri: "https://attacker.example.com/api/hub-session/callback",
289
- }),
290
- ),
291
- );
292
-
293
- expect(new URL(res.headers.get("location") ?? "").origin).toBe(
294
- "https://spoke.example.com",
295
- );
296
- });
297
-
298
- it("answers 503, not a redirect, when the API echoes a URI that does not parse", async () => {
299
- mockCreateCode.mockResolvedValue({
300
- ok: true,
301
- body: { code: CODE, redirectUri: "not a url" },
302
- });
303
-
304
- const res = await GET(request(query()));
305
-
306
- expect(res.status).toBe(503);
307
- expect(res.headers.get("location")).toBeNull();
308
- });
309
-
310
- it("AC-6: an unverified email goes to the hub's own /account/settings, never the spoke", async () => {
311
- mockCreateCode.mockResolvedValue({
312
- ok: false,
313
- status: 403,
314
- body: { ok: false, error: { code: "email_unverified", message: "x" } },
315
- });
316
-
317
- const res = await GET(request(query()));
318
-
319
- expect(res.status).toBe(303);
320
- expect(res.headers.get("location")).toBe("/account/settings");
321
- expect(res.headers.get("location")).not.toContain("spoke.example.com");
322
- });
323
-
324
- it.each([
325
- ["an unknown client", 400, "invalid_client"],
326
- ["a rate limit", 429, "rate_limited"],
327
- ["a forbidden caller", 403, "forbidden"],
328
- ["an expired session", 401, "unauthorized"],
329
- ])("%s is a 400, never a redirect", async (_name, status, code) => {
330
- mockCreateCode.mockResolvedValue({
331
- ok: false,
332
- status,
333
- body: { ok: false, error: { code, message: "x" } },
334
- });
335
-
336
- const res = await GET(request(query()));
337
-
338
- expect(res.status).toBe(400);
339
- expect(res.headers.get("location")).toBeNull();
340
- });
341
-
342
- it("answers 503 — not a redirect — when the API cannot be reached", async () => {
343
- mockCreateCode.mockRejectedValue(new Error("network"));
344
-
345
- const res = await GET(request(query()));
346
-
347
- expect(res.status).toBe(503);
348
- expect(res.headers.get("location")).toBeNull();
349
- expect(await res.json()).toEqual({ error: "temporarily_unavailable" });
350
- });
351
-
352
- it.each([
353
- ["unset", undefined],
354
- ["not a URL", "not a url"],
355
- ])(
356
- "answers 503 when BETTER_AUTH_URL is %s (no pinned origin to send)",
357
- async (_name, value) => {
358
- if (value === undefined) delete process.env.BETTER_AUTH_URL;
359
- else process.env.BETTER_AUTH_URL = value;
360
-
361
- const res = await GET(request(query()));
362
-
363
- expect(res.status).toBe(503);
364
- expect(mockCreateCode).not.toHaveBeenCalled();
365
- },
366
- );
367
- });
368
-
369
- describe("the login_hint (#8757 D9)", () => {
370
- const HINT = "a@b.example";
371
-
372
- /** The `next` value of the 303, and the ref inside it. */
373
- function continuationOf(res: Response): { next: string; ref: string } {
374
- const location = res.headers.get("location") ?? "";
375
- const next = new URL(location, HUB).searchParams.get("next") ?? "";
376
- return { next, ref: next.slice(`${CONTINUE}/`.length) };
377
- }
378
-
379
- it("no session + a valid login_hint: 303 to /sign-in?next=<continue path>&email=a%40b.example; the ref opens to the six-key canonical query alone", async () => {
380
- mockGetSession.mockResolvedValue(null);
381
- const canonical = query();
382
-
383
- const res = await GET(
384
- request(`${canonical}&login_hint=${encodeURIComponent(HINT)}`),
385
- );
386
-
387
- expect(res.status).toBe(303);
388
- const { next, ref } = continuationOf(res);
389
- expect(res.headers.get("location")).toBe(
390
- `/sign-in?next=${encodeURIComponent(`${CONTINUE}/${ref}`)}&email=a%40b.example`,
391
- );
392
- expect(next).toBe(`${CONTINUE}/${ref}`);
393
- const opened = openContinuation(ref, mockSecret);
394
- expect(opened).toBe(canonical);
395
- expect(opened).not.toContain("login_hint");
396
- expect(opened).not.toContain("email");
397
- expect(mockCreateCode).not.toHaveBeenCalled();
398
- });
399
-
400
- it.each([
401
- ["an invalid login_hint", "nope"],
402
- ["a login_hint carrying a separator", "a@b.example&next=/x"],
403
- ["an over-long login_hint", `${"a".repeat(250)}@b.example`],
404
- ])(
405
- "no session + %s: dropped — the 303 carries no email",
406
- async (_name, hint) => {
407
- mockGetSession.mockResolvedValue(null);
408
- const canonical = query();
409
-
410
- const res = await GET(
411
- request(`${canonical}&login_hint=${encodeURIComponent(hint)}`),
412
- );
413
-
414
- expect(res.status).toBe(303);
415
- const { ref } = continuationOf(res);
416
- expect(res.headers.get("location")).toBe(
417
- `/sign-in?next=${encodeURIComponent(`${CONTINUE}/${ref}`)}`,
418
- );
419
- expect(openContinuation(ref, mockSecret)).toBe(canonical);
420
- },
421
- );
422
-
423
- it.each([
424
- ["no session", null],
425
- ["a session", { user: { id: "u1" } }],
426
- ])(
427
- "a repeated login_hint is a 400 invalid_request (%s)",
428
- async (_name, session) => {
429
- mockGetSession.mockResolvedValue(session);
430
-
431
- const res = await GET(
432
- request(`${query()}&login_hint=a%40b.example&login_hint=c%40d.example`),
433
- );
434
-
435
- expect(res.status).toBe(400);
436
- expect(res.headers.get("location")).toBeNull();
437
- expect(await res.json()).toEqual({ error: "invalid_request" });
438
- expect(mockCreateCode).not.toHaveBeenCalled();
439
- expect(mockGetSession).not.toHaveBeenCalled();
440
- },
441
- );
442
-
443
- it("with a session: the code redirect is unchanged and carries no hint", async () => {
444
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
445
- mockCreateCode.mockResolvedValue({
446
- ok: true,
447
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
448
- });
449
-
450
- const withHint = await GET(
451
- request(`${query()}&login_hint=${encodeURIComponent(HINT)}`, {
452
- cookie: "better-auth.session_token=tok",
453
- }),
454
- );
455
- const without = await GET(
456
- request(query(), { cookie: "better-auth.session_token=tok" }),
457
- );
458
-
459
- expect(withHint.status).toBe(303);
460
- const location = withHint.headers.get("location") ?? "";
461
- expect(location).toBe(without.headers.get("location"));
462
- expect(location).toBe(`${SPOKE_CALLBACK}?code=${CODE}&state=${STATE}`);
463
- expect(location).not.toContain("login_hint");
464
- expect(location).not.toContain("email");
465
- expect(location).not.toContain("b.example");
466
- // The hint is never handed to the API either.
467
- expect(mockCreateCode).toHaveBeenNthCalledWith(
468
- 1,
469
- {
470
- clientId: "spoke_abc",
471
- redirectUri: SPOKE_CALLBACK,
472
- codeChallenge: CHALLENGE,
473
- },
474
- { headers: { cookie: "better-auth.session_token=tok", origin: HUB } },
475
- );
476
- });
477
- });
478
-
479
- describe("the sign-up hint, prompt=create (#9912 D3)", () => {
480
- /** The `next` value of the 303, and the ref inside it. */
481
- function continuationOf(res: Response): { next: string; ref: string } {
482
- const location = res.headers.get("location") ?? "";
483
- const next = new URL(location, HUB).searchParams.get("next") ?? "";
484
- return { next, ref: next.slice(`${CONTINUE}/`.length) };
485
- }
486
-
487
- it("no session + prompt=create: 303 to /sign-up?next=<continue path>; the ref opens to the same six-key query as without the prompt", async () => {
488
- mockGetSession.mockResolvedValue(null);
489
- const canonical = query();
490
-
491
- const res = await GET(request(`${canonical}&prompt=create`));
492
- const plain = await GET(request(canonical));
493
-
494
- expect(res.status).toBe(303);
495
- const location = new URL(res.headers.get("location") ?? "", HUB);
496
- expect(location.pathname).toBe("/sign-up");
497
- expect([...location.searchParams.keys()]).toEqual(["next"]);
498
- const { next, ref } = continuationOf(res);
499
- expect(res.headers.get("location")).toBe(
500
- `/sign-up?next=${encodeURIComponent(`${CONTINUE}/${ref}`)}`,
501
- );
502
- // The sign-up page keeps it, as the sign-in page does.
503
- expect(resolveNextPath(next, "/account")).toBe(next);
504
- const opened = openContinuation(ref, mockSecret);
505
- expect(opened).toBe(canonical);
506
- expect(opened).toBe(
507
- openContinuation(continuationOf(plain).ref, mockSecret),
508
- );
509
- expect(opened).not.toContain("prompt");
510
- expect(res.headers.get("cache-control")).toBe("no-store");
511
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
512
- expect(mockCreateCode).not.toHaveBeenCalled();
513
- });
514
-
515
- it("no session + prompt=create + a valid login_hint: /sign-up carries no email", async () => {
516
- mockGetSession.mockResolvedValue(null);
517
-
518
- const res = await GET(
519
- request(`${query()}&prompt=create&login_hint=a%40b.example`),
520
- );
521
-
522
- expect(res.status).toBe(303);
523
- const location = new URL(res.headers.get("location") ?? "", HUB);
524
- expect(location.pathname).toBe("/sign-up");
525
- expect(location.searchParams.has("email")).toBe(false);
526
- expect(res.headers.get("location")).not.toContain("b.example");
527
- });
528
-
529
- it.each([
530
- ["prompt=login", "login"],
531
- ["prompt=none", "none"],
532
- ["an empty prompt", ""],
533
- ["a cased prompt", "Create"],
534
- ])("no session + %s: today's /sign-in", async (_name, prompt) => {
535
- mockGetSession.mockResolvedValue(null);
536
- const canonical = query();
537
-
538
- const res = await GET(
539
- request(`${canonical}&prompt=${encodeURIComponent(prompt)}`),
540
- );
541
-
542
- expect(res.status).toBe(303);
543
- const { ref } = continuationOf(res);
544
- expect(res.headers.get("location")).toBe(
545
- `/sign-in?next=${encodeURIComponent(`${CONTINUE}/${ref}`)}`,
546
- );
547
- expect(openContinuation(ref, mockSecret)).toBe(canonical);
548
- });
549
-
550
- it.each([
551
- ["no session", null],
552
- ["a session", { user: { id: "u1" } }],
553
- ])(
554
- "a repeated prompt is a 400 invalid_request (%s)",
555
- async (_name, session) => {
556
- mockGetSession.mockResolvedValue(session);
557
-
558
- const res = await GET(request(`${query()}&prompt=create&prompt=create`));
559
-
560
- expect(res.status).toBe(400);
561
- expect(res.headers.get("location")).toBeNull();
562
- expect(await res.json()).toEqual({ error: "invalid_request" });
563
- expect(mockCreateCode).not.toHaveBeenCalled();
564
- expect(mockGetSession).not.toHaveBeenCalled();
565
- },
566
- );
567
-
568
- it("with a session: prompt=create is ignored — the same code redirect and the same API call", async () => {
569
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
570
- mockCreateCode.mockResolvedValue({
571
- ok: true,
572
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
573
- });
574
-
575
- const withPrompt = await GET(
576
- request(`${query()}&prompt=create`, {
577
- cookie: "better-auth.session_token=tok",
578
- }),
579
- );
580
- const without = await GET(
581
- request(query(), { cookie: "better-auth.session_token=tok" }),
582
- );
583
-
584
- expect(withPrompt.status).toBe(303);
585
- const location = withPrompt.headers.get("location") ?? "";
586
- expect(location).toBe(without.headers.get("location"));
587
- expect(location).toBe(`${SPOKE_CALLBACK}?code=${CODE}&state=${STATE}`);
588
- expect(mockCreateCode).toHaveBeenCalledTimes(2);
589
- expect(mockCreateCode.mock.calls[0]).toEqual(mockCreateCode.mock.calls[1]);
590
- });
591
- });
592
-
593
- describe("the consent step (#9966 D2, AC-4)", () => {
594
- const SESSION_COOKIE = "better-auth.session_token=tok";
595
- const CONSENT_REQUIRED = {
596
- ok: false,
597
- status: 403,
598
- body: {
599
- ok: false,
600
- error: { code: "consent_required", message: "Consent required" },
601
- },
602
- };
603
-
604
- /** A same-origin form post of `ref` fields from the hub's consent page. */
605
- function post(
606
- refs: string[],
607
- headers: Record<string, string | undefined> = {},
608
- ): Request {
609
- const body = new URLSearchParams();
610
- for (const ref of refs) body.append("ref", ref);
611
- const sent: Record<string, string> = {
612
- "content-type": "application/x-www-form-urlencoded",
613
- cookie: SESSION_COOKIE,
614
- "sec-fetch-site": "same-origin",
615
- origin: HUB,
616
- };
617
- for (const [key, value] of Object.entries(headers)) {
618
- if (value === undefined) delete sent[key];
619
- else sent[key] = value;
620
- }
621
- return new Request(`${HUB}/api/auth/hub/authorize`, {
622
- method: "POST",
623
- headers: sent,
624
- body: body.toString(),
625
- });
626
- }
627
-
628
- const ref = (search = query(), now?: number) =>
629
- mintContinuation(search, mockSecret, now);
630
-
631
- it("GET: a session the API answers consent_required goes to /account/connect with a sealed ref, and sends no consent", async () => {
632
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
633
- mockCreateCode.mockResolvedValue(CONSENT_REQUIRED);
634
-
635
- const res = await GET(request(query(), { cookie: SESSION_COOKIE }));
636
-
637
- expect(res.status).toBe(303);
638
- const location = new URL(res.headers.get("location") ?? "", HUB);
639
- expect(location.pathname).toBe("/account/connect");
640
- const sealed = location.searchParams.get("ref") ?? "";
641
- expect(openContinuation(sealed, mockSecret)).toBe(query());
642
- expect(mockCreateCode).toHaveBeenCalledTimes(1);
643
- const [body, init] = mockCreateCode.mock.calls[0] as [
644
- Record<string, unknown>,
645
- { headers: Record<string, string> },
646
- ];
647
- expect("consent" in body).toBe(false);
648
- expect("x-internal-auth" in init.headers).toBe(false);
649
- });
650
-
651
- it("POST: a same-origin Continue mints with consent: true and answers a 200 page that navigates to the registered URI with code and state — never a 303, which Chrome blocks under form-action 'self' (#11091)", async () => {
652
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
653
- mockCreateCode.mockResolvedValue({
654
- ok: true,
655
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
656
- });
657
-
658
- const res = await POST(post([ref()]));
659
-
660
- expect(res.status).toBe(200);
661
- expect(res.headers.get("location")).toBeNull();
662
- expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
663
- expect(res.headers.get("cache-control")).toBe("no-store");
664
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
665
- const html = await res.text();
666
- const target = `${SPOKE_CALLBACK}?code=${CODE}&amp;state=${STATE}`;
667
- expect(html).toContain(`<meta http-equiv="refresh" content="0;url=${target}">`);
668
- expect(html).toContain(`<a href="${target}">`);
669
- expect(html).toContain(`<meta name="referrer" content="no-referrer">`);
670
- expect(mockCreateCode).toHaveBeenCalledWith(
671
- {
672
- clientId: "spoke_abc",
673
- redirectUri: SPOKE_CALLBACK,
674
- codeChallenge: CHALLENGE,
675
- consent: true,
676
- },
677
- { headers: { cookie: SESSION_COOKIE, origin: HUB } },
678
- );
679
- });
680
-
681
- it("POST: carries x-internal-auth when the secret is set and the API is https:", async () => {
682
- process.env = {
683
- ...process.env,
684
- OSS_API_INTERNAL_SECRET: "internal-secret",
685
- AILK_API_URL: "https://api.example.com",
686
- };
687
- delete process.env.AILK_SPOKE_KEY;
688
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
689
- mockCreateCode.mockResolvedValue({
690
- ok: true,
691
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
692
- });
693
-
694
- await POST(post([ref()]));
695
-
696
- const [, init] = mockCreateCode.mock.calls[0] as [
697
- unknown,
698
- { headers: Record<string, string> },
699
- ];
700
- expect(init.headers["x-internal-auth"]).toBe("internal-secret");
701
- });
702
-
703
- it("POST: a hub that holds its own spoke key still carries x-internal-auth (#10941)", async () => {
704
- process.env = {
705
- ...process.env,
706
- OSS_API_INTERNAL_SECRET: "internal-secret",
707
- AILK_API_URL: "https://api.example.com",
708
- AILK_SPOKE_KEY: "ailk_spk_the_hubs_own_key",
709
- };
710
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
711
- mockCreateCode.mockResolvedValue({
712
- ok: true,
713
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
714
- });
715
-
716
- const res = await POST(post([ref()]));
717
-
718
- expect(res.status).toBe(200);
719
- const [body, init] = mockCreateCode.mock.calls[0] as [
720
- Record<string, unknown>,
721
- { headers: Record<string, string> },
722
- ];
723
- expect(body.consent).toBe(true);
724
- expect(init.headers["x-internal-auth"]).toBe("internal-secret");
725
- });
726
-
727
- it("POST: withholds x-internal-auth from a plain-http API", async () => {
728
- process.env = {
729
- ...process.env,
730
- OSS_API_INTERNAL_SECRET: "internal-secret",
731
- AILK_API_URL: "http://api.example.com",
732
- };
733
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
734
- mockCreateCode.mockResolvedValue({
735
- ok: true,
736
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
737
- });
738
-
739
- await POST(post([ref()]));
740
-
741
- const [, init] = mockCreateCode.mock.calls[0] as [
742
- unknown,
743
- { headers: Record<string, string> },
744
- ];
745
- expect("x-internal-auth" in init.headers).toBe(false);
746
- });
747
-
748
- it.each([
749
- ["no Sec-Fetch-Site", { "sec-fetch-site": undefined }],
750
- ["Sec-Fetch-Site cross-site", { "sec-fetch-site": "cross-site" }],
751
- ["Sec-Fetch-Site same-site", { "sec-fetch-site": "same-site" }],
752
- ["a foreign Origin", { origin: "https://spoke.example.com" }],
753
- ["no Origin", { origin: undefined }],
754
- ["Origin: null", { origin: "null" }],
755
- ])(
756
- "POST: %s is 403 with no session read and no code",
757
- async (_name, headers) => {
758
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
759
-
760
- const res = await POST(post([ref()], headers));
761
-
762
- expect(res.status).toBe(403);
763
- expect(res.headers.get("location")).toBeNull();
764
- expect(await res.json()).toEqual({ error: "invalid_request" });
765
- expect(mockGetSession).not.toHaveBeenCalled();
766
- expect(mockCreateCode).not.toHaveBeenCalled();
767
- },
768
- );
769
-
770
- it.each([
771
- ["a forged ref", () => ["x".repeat(80)]],
772
- ["an expired ref", () => [ref(query(), Date.now() - 3_600_000)]],
773
- ["two ref fields", () => [ref(), ref()]],
774
- ["no ref field", () => []],
775
- [
776
- "a ref sealing a query that fails the schema",
777
- () => [ref(query({ code_challenge_method: "plain" }))],
778
- ],
779
- ])("POST: %s is 400 with no code", async (_name, refs) => {
780
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
781
-
782
- const res = await POST(post(refs()));
783
-
784
- expect(res.status).toBe(400);
785
- expect(res.headers.get("location")).toBeNull();
786
- expect(mockCreateCode).not.toHaveBeenCalled();
787
- });
788
-
789
- it("POST: no session sends the visitor to sign in, back through the same continuation", async () => {
790
- mockGetSession.mockResolvedValue(null);
791
- const sealed = ref();
792
-
793
- const res = await POST(post([sealed]));
794
-
795
- expect(res.status).toBe(303);
796
- expect(res.headers.get("location")).toBe(
797
- `/sign-in?next=${encodeURIComponent(`${CONTINUE}/${sealed}`)}`,
798
- );
799
- expect(mockCreateCode).not.toHaveBeenCalled();
800
- });
801
-
802
- it("POST: an unverified email goes to /account/settings; any other refusal is a 400", async () => {
803
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
804
- mockCreateCode.mockResolvedValueOnce({
805
- ok: false,
806
- status: 403,
807
- body: { ok: false, error: { code: "email_unverified", message: "x" } },
808
- });
809
- const unverified = await POST(post([ref()]));
810
- expect(unverified.status).toBe(303);
811
- expect(unverified.headers.get("location")).toBe("/account/settings");
812
-
813
- mockCreateCode.mockResolvedValueOnce(CONSENT_REQUIRED);
814
- const refused = await POST(post([ref()]));
815
- expect(refused.status).toBe(400);
816
- expect(refused.headers.get("location")).toBeNull();
817
- });
818
-
819
- // #11095 AC-10 (D10, folded from #11094): the navigating page is built
820
- // only for an https: or loopback http: callback.
821
- it.each([
822
- "http://spoke.example.com/api/hub-session/callback",
823
- "javascript:alert(1)",
824
- "data:text/html,x",
825
- ])(
826
- "POST: an echoed redirect URI %s answers a JSON 503 before any HTML is built",
827
- async (redirectUri) => {
828
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
829
- mockCreateCode.mockResolvedValue({
830
- ok: true,
831
- body: { code: CODE, redirectUri },
832
- });
833
-
834
- const res = await POST(post([ref()]));
835
-
836
- expect(res.status).toBe(503);
837
- expect(res.headers.get("content-type")).toBe("application/json");
838
- expect(res.headers.get("location")).toBeNull();
839
- expect(await res.text()).toBe(
840
- JSON.stringify({ error: "temporarily_unavailable" }),
841
- );
842
- },
843
- );
844
-
845
- it.each([
846
- SPOKE_CALLBACK,
847
- "http://localhost:3000/api/hub-session/callback",
848
- ])(
849
- "POST: an echoed redirect URI %s still answers the 200 page",
850
- async (redirectUri) => {
851
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
852
- mockCreateCode.mockResolvedValue({
853
- ok: true,
854
- body: { code: CODE, redirectUri },
855
- });
856
-
857
- const res = await POST(post([ref()]));
858
-
859
- expect(res.status).toBe(200);
860
- expect(res.headers.get("content-type")).toBe("text/html; charset=utf-8");
861
- expect(await res.text()).toContain('<meta http-equiv="refresh"');
862
- },
863
- );
864
- });
865
-
866
- describe("the provider hint, provider_hint=google (#11096 D4, AC-3)", () => {
867
- const GOOGLE_URL = "https://accounts.google.com/o/oauth2/v2/auth?x";
868
- const STATE_COOKIE =
869
- "better-auth.state=abc; Path=/; HttpOnly; Secure; SameSite=Lax";
870
-
871
- beforeEach(() => {
872
- process.env.GOOGLE_CLIENT_ID = "google-client";
873
- process.env.GOOGLE_CLIENT_SECRET = "google-secret";
874
- mockGetSession.mockResolvedValue(null);
875
- mockSignInSocial.mockResolvedValue({
876
- headers: new Headers([["set-cookie", STATE_COOKIE]]),
877
- response: { url: GOOGLE_URL, redirect: true },
878
- });
879
- });
880
-
881
- it("no session + Google on: 303 to Google's URL with the state cookie, no sign-in card", async () => {
882
- const res = await GET(request(`${query()}&provider_hint=google`));
883
-
884
- expect(res.status).toBe(303);
885
- expect(res.headers.get("location")).toBe(GOOGLE_URL);
886
- expect(res.headers.getSetCookie()).toEqual([STATE_COOKIE]);
887
- expect(res.headers.get("cache-control")).toBe("no-store");
888
- expect(mockSignInSocial).toHaveBeenCalledTimes(1);
889
- const [call] = mockSignInSocial.mock.calls[0] as [
890
- {
891
- body: { provider: string; callbackURL: string; errorCallbackURL: string };
892
- returnHeaders: boolean;
893
- },
894
- ];
895
- expect(call.body.provider).toBe("google");
896
- expect(call.returnHeaders).toBe(true);
897
- expect(call.body.callbackURL.startsWith(`${CONTINUE}/`)).toBe(true);
898
- const ref = call.body.callbackURL.slice(`${CONTINUE}/`.length);
899
- expect(openContinuation(ref, mockSecret)).toBe(query());
900
- expect(call.body.errorCallbackURL).toBe(
901
- `/sign-in?next=${encodeURIComponent(call.body.callbackURL)}`,
902
- );
903
- });
904
-
905
- it("with prompt=create and a login_hint, the Google hint still wins and neither rides along", async () => {
906
- const res = await GET(
907
- request(`${query()}&provider_hint=google&prompt=create&login_hint=a%40b.example`),
908
- );
909
- expect(res.headers.get("location")).toBe(GOOGLE_URL);
910
- });
911
-
912
- it.each([
913
- ["Google off", () => {
914
- delete process.env.GOOGLE_CLIENT_ID;
915
- }],
916
- ["signInSocial throwing", () => {
917
- mockSignInSocial.mockRejectedValue(new Error("boom"));
918
- }],
919
- ["signInSocial answering no url", () => {
920
- mockSignInSocial.mockResolvedValue({ headers: new Headers(), response: {} });
921
- }],
922
- ])("%s: today's 303 to /sign-in?next=<continue path>", async (_name, arrange) => {
923
- arrange();
924
- const res = await GET(request(`${query()}&provider_hint=google`));
925
- expect(res.status).toBe(303);
926
- expect(res.headers.get("location")).toMatch(
927
- new RegExp(`^/sign-in\\?next=${encodeURIComponent(`${CONTINUE}/`)}`),
928
- );
929
- expect(res.headers.getSetCookie()).toEqual([]);
930
- });
931
-
932
- it.each(["github", "", "GOOGLE"])(
933
- "provider_hint=%s does nothing: /sign-in, no social call",
934
- async (hint) => {
935
- const res = await GET(request(`${query()}&provider_hint=${hint}`));
936
- expect(res.headers.get("location")).toMatch(/^\/sign-in\?next=/);
937
- expect(mockSignInSocial).not.toHaveBeenCalled();
938
- },
939
- );
940
-
941
- it("two provider_hint values: 400 before the session read", async () => {
942
- const res = await GET(
943
- request(`${query()}&provider_hint=google&provider_hint=google`),
944
- );
945
- expect(res.status).toBe(400);
946
- expect(await res.json()).toEqual({ error: "invalid_request" });
947
- expect(mockGetSession).not.toHaveBeenCalled();
948
- expect(mockSignInSocial).not.toHaveBeenCalled();
949
- });
950
-
951
- it("with a session: createCode is called and signInSocial is not", async () => {
952
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
953
- mockCreateCode.mockResolvedValue({
954
- ok: true,
955
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
956
- });
957
-
958
- const res = await GET(request(`${query()}&provider_hint=google`));
959
-
960
- expect(res.status).toBe(303);
961
- expect(mockCreateCode).toHaveBeenCalledTimes(1);
962
- expect(mockSignInSocial).not.toHaveBeenCalled();
963
- });
964
- });