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,554 +0,0 @@
1
- /**
2
- * @file password-reset.test.tsx — AC-2's scorer (#5962).
3
- *
4
- * The three pages' branch matrix, rendered against a mocked `auth-env` — the
5
- * idiom the sibling `auth-pages.test.tsx` and `sign-in/__tests__/page.test.tsx`
6
- * already use.
7
- *
8
- * "Never a 404" is STRUCTURAL rather than asserted here: the three segments
9
- * exist as files, so Next resolves them whatever the predicate says. What this
10
- * suite asserts is that each resolves to a real card in every branch.
11
- *
12
- * The seventh case is the one a page-render assertion would miss entirely:
13
- * `forgot-password-card` must pass a NON-EMPTY, ABSOLUTE `redirectTo`. Better
14
- * Auth rejects an empty `callbackURL` on the token route, so without it every
15
- * emitted reset link dead-ends at an error page while the page itself looks
16
- * perfectly correct.
17
- */
18
- import { render, screen, waitFor } from "@testing-library/react";
19
- import userEvent from "@testing-library/user-event";
20
-
21
- const mockIsResetAvailable = jest.fn();
22
- const mockResetSendConfigured = jest.fn();
23
- const mockGetActiveProviderIds = jest.fn();
24
- const mockIsSignUpOpen = jest.fn();
25
- // eslint-disable-next-line no-restricted-syntax -- #507: mock-internal rewrite pending; auth-env.ts is a pure env-introspection module with no external boundary to mock instead.
26
- jest.mock("../../../../lib/auth-env", () => ({
27
- __esModule: true,
28
- getActiveProviderIds: () => mockGetActiveProviderIds(),
29
- isSignUpOpen: () => mockIsSignUpOpen(),
30
- isResetAvailable: () => mockIsResetAvailable(),
31
- resetSendConfigured: () => mockResetSendConfigured(),
32
- // #11106 D9 — auth.ts asks whether to install the phone plugin.
33
- phoneVerificationConfigured: () => false,
34
- }));
35
-
36
- const mockRequestPasswordReset = jest.fn();
37
- const mockResetPassword = jest.fn();
38
- jest.mock("better-auth/react", () => ({
39
- __esModule: true,
40
- createAuthClient: () => ({
41
- requestPasswordReset: (...args: unknown[]) =>
42
- mockRequestPasswordReset(...args),
43
- resetPassword: (...args: unknown[]) => mockResetPassword(...args),
44
- signIn: { social: jest.fn(), email: jest.fn() },
45
- }),
46
- }));
47
-
48
- /**
49
- * #6068 AC-1 exercises `createAuth()`'s `onPasswordReset` callback, so the
50
- * three Better Auth entry points it touches are stubbed the way the sibling
51
- * `apps/web/__tests__/auth/password-reset-config.test.ts` stubs them — the
52
- * real ESM-only module never loads under the Jest CJS preset, and `betterAuth`
53
- * returning `{ options }` is what makes the wired callback reachable at all.
54
- */
55
- jest.mock("better-auth", () => ({
56
- betterAuth: (options: unknown) => ({ options }),
57
- }));
58
-
59
- jest.mock("better-auth/adapters/prisma", () => ({
60
- prismaAdapter: () => ({ id: "mock-prisma-adapter" }),
61
- }));
62
-
63
- jest.mock("better-auth/next-js", () => ({
64
- nextCookies: () => ({ id: "next-cookies" }),
65
- }));
66
-
67
- jest.mock("better-auth/plugins", () => ({
68
- magicLink: () => ({ id: "magic-link" }),
69
- mcp: () => ({ id: "mcp" }),
70
- }));
71
-
72
- // The MCP authorization server (#10357 D12): its ESM-only module never loads here.
73
- // eslint-disable-next-line no-restricted-syntax -- #507: lib/mcp-oauth statically imports ESM-only better-auth/api, which CommonJS Jest cannot load.
74
- jest.mock("../../../../lib/mcp-oauth", () => ({ mcpOAuthPlugin: () => ({ id: "ailk-mcp-oauth" }) }));
75
-
76
- /**
77
- * The signer seam. `buildAuthEmailRequest` has exactly one external
78
- * dependency — `node:crypto`'s `createHmac` — so a throwing `createHmac` is a
79
- * throwing `buildAuthEmailRequest` reached through the real call path, with no
80
- * stub standing in for the function under test. Every other member is the real
81
- * one, and the default implementation below is the real `createHmac`, so only
82
- * the case that opts in sees a failure.
83
- */
84
- const mockCreateHmac = jest.fn();
85
- jest.mock("node:crypto", () => {
86
- const actual = jest.requireActual("node:crypto");
87
- return {
88
- ...actual,
89
- createHmac: (...args: unknown[]) => mockCreateHmac(...args),
90
- };
91
- });
92
-
93
- /**
94
- * #10820 D7 — the confirm page's server action. Rendering `?verify=` must
95
- * spend nothing: the action is the only path to the confirm hop, so a GET that
96
- * called it is the mail-scanner hole this page exists to close.
97
- */
98
- const mockConfirmEmailAction = jest.fn();
99
- // eslint-disable-next-line no-restricted-syntax -- the "use server" action is the page's network boundary (it reaches apps/api over HTTP); its own suite, verify-email/__tests__/actions.test.ts, exercises it.
100
- jest.mock("../verify-email/actions", () => ({
101
- confirmEmailAction: (...args: unknown[]) => mockConfirmEmailAction(...args),
102
- }));
103
-
104
- import en from "../../../../messages/en.json";
105
- import { createAuth } from "../../../../auth";
106
- import ForgotPasswordPage from "../forgot-password/page";
107
- import ResetPasswordPage from "../reset-password/page";
108
- import { ResetPasswordCard } from "../reset-password/reset-password-card";
109
- import SignInPage from "../sign-in/page";
110
- import VerifyEmailPage from "../verify-email/page";
111
-
112
- const ORIGINAL_ENV = process.env;
113
-
114
- /** The slice of Better Auth's options object #6068 AC-1 reads. */
115
- type AuthOptionsUnderTest = {
116
- emailAndPassword?: {
117
- onPasswordReset?: (args: {
118
- user: { id: string; email: string };
119
- }) => Promise<void>;
120
- };
121
- };
122
-
123
- /**
124
- * `NonNullable` on BOTH levels, exactly as the sibling config suite does it:
125
- * the inner one strips the `| undefined` off the optional `prisma` member,
126
- * without which `exactOptionalPropertyTypes: true` rejects the assignment.
127
- */
128
- type AuthPrisma = NonNullable<
129
- NonNullable<Parameters<typeof createAuth>[0]>["prisma"]
130
- >;
131
-
132
- async function renderForgot(): Promise<void> {
133
- render(await ForgotPasswordPage({ params: Promise.resolve({ locale: "en" }) }));
134
- }
135
-
136
- async function renderReset(
137
- query: Record<string, string> = {},
138
- ): Promise<void> {
139
- render(
140
- await ResetPasswordPage({
141
- params: Promise.resolve({ locale: "en" }),
142
- searchParams: Promise.resolve(query),
143
- }),
144
- );
145
- }
146
-
147
- async function renderVerify(
148
- query: Record<string, string> = {},
149
- ): Promise<void> {
150
- render(
151
- await VerifyEmailPage({
152
- params: Promise.resolve({ locale: "en" }),
153
- searchParams: Promise.resolve(query),
154
- }),
155
- );
156
- }
157
-
158
- beforeEach(() => {
159
- process.env = { ...ORIGINAL_ENV, BETTER_AUTH_URL: "https://site.example" };
160
- jest.clearAllMocks();
161
- mockIsResetAvailable.mockReturnValue(true);
162
- mockResetSendConfigured.mockReturnValue(true);
163
- mockGetActiveProviderIds.mockReturnValue(["email"]);
164
- mockIsSignUpOpen.mockReturnValue(false);
165
- mockRequestPasswordReset.mockResolvedValue({ data: {}, error: null });
166
- mockResetPassword.mockResolvedValue({ data: {}, error: null });
167
- // The real signer by default — only the #6068 case below makes it throw.
168
- mockCreateHmac.mockImplementation((...args: unknown[]) =>
169
- // eslint-disable-next-line @typescript-eslint/no-explicit-any -- forwarding an untyped rest to the real overloaded builtin
170
- (jest.requireActual("node:crypto") as any).createHmac(...args),
171
- );
172
- });
173
-
174
- afterAll(() => {
175
- process.env = ORIGINAL_ENV;
176
- });
177
-
178
- // ── The six states AC-2 names ───────────────────────────────────────────────
179
-
180
- describe("/forgot-password", () => {
181
- it("renders the forgot form when reset is available", async () => {
182
- await renderForgot();
183
- expect(screen.getByTestId("auth-email")).toBeInTheDocument();
184
- });
185
-
186
- it("renders the not-available state — never a 404 — when it is not", async () => {
187
- mockResetSendConfigured.mockReturnValue(false);
188
- await renderForgot();
189
- expect(screen.getByTestId("forgot-password-page")).toBeInTheDocument();
190
- expect(screen.getByTestId("auth-invitation-body")).toHaveTextContent(
191
- en.auth.forgotUnavailableBody,
192
- );
193
- expect(screen.queryByTestId("auth-email")).not.toBeInTheDocument();
194
- });
195
- });
196
-
197
- describe("/reset-password", () => {
198
- it("renders the password fields when it carries a token", async () => {
199
- await renderReset({ token: "tok_live" });
200
- expect(screen.getByTestId("auth-password")).toBeInTheDocument();
201
- expect(screen.getByTestId("auth-confirm-password")).toBeInTheDocument();
202
- });
203
-
204
- it("renders the expired-token state — and NO password field — on ?error", async () => {
205
- await renderReset({ error: "INVALID_TOKEN" });
206
- expect(screen.getByTestId("reset-token-error")).toBeInTheDocument();
207
- expect(
208
- screen.getByRole("heading", { name: en.auth.resetExpiredHeading }),
209
- ).toBeInTheDocument();
210
- expect(screen.queryByTestId("auth-password")).not.toBeInTheDocument();
211
- });
212
-
213
- it("renders its own not-available copy when reset is off", async () => {
214
- mockResetSendConfigured.mockReturnValue(false);
215
- await renderReset({ token: "tok_live" });
216
- expect(screen.getByTestId("auth-invitation-body")).toHaveTextContent(
217
- en.auth.resetUnavailableBody,
218
- );
219
- expect(screen.queryByTestId("auth-password")).not.toBeInTheDocument();
220
- });
221
- });
222
-
223
- describe("/verify-email", () => {
224
- it("renders the sent terminus with no ?error", async () => {
225
- await renderVerify();
226
- expect(screen.getByTestId("auth-sent-body")).toBeInTheDocument();
227
- });
228
-
229
- it("renders the expired-token state on ?error", async () => {
230
- await renderVerify({ error: "TOKEN_EXPIRED" });
231
- expect(screen.getByTestId("verify-token-error")).toBeInTheDocument();
232
- expect(screen.queryByTestId("auth-sent-body")).not.toBeInTheDocument();
233
- });
234
-
235
- it("renders a confirm button on ?verify= and spends nothing while rendering (#10820)", async () => {
236
- await renderVerify({ verify: "N".repeat(43) });
237
- expect(screen.getByTestId("verify-email-confirm")).toBeInTheDocument();
238
- expect(screen.getByTestId("verify-email-confirm-button")).toHaveTextContent(
239
- en.auth.confirmButton,
240
- );
241
- expect(mockConfirmEmailAction).not.toHaveBeenCalled();
242
- expect(document.body.innerHTML).not.toContain("N".repeat(43));
243
- });
244
-
245
- it("renders the verified card on ?confirmed=1 (#10820)", async () => {
246
- await renderVerify({ confirmed: "1" });
247
- expect(screen.getByTestId("verify-email-confirmed")).toHaveTextContent(
248
- en.auth.verifiedHeading,
249
- );
250
- });
251
- });
252
-
253
- // ── The flag-alone configuration: intent set, send impossible ──────────────
254
-
255
- describe("the flag alone does not open either page", () => {
256
- /**
257
- * `AILK_AUTH_PASSWORD_RESET=1` with a send conjunct missing is a real
258
- * deployment state, and it is the one a flag-only predicate reads as
259
- * "available". On the request page that renders a live form whose only
260
- * possible outcome is the error card; on the consume page it renders a live
261
- * password field over a POST Better Auth still serves. Both pages key on
262
- * `resetSendConfigured()` so neither can be reached in that state.
263
- */
264
- beforeEach(() => {
265
- mockIsResetAvailable.mockReturnValue(true);
266
- mockResetSendConfigured.mockReturnValue(false);
267
- });
268
-
269
- it("/forgot-password renders not-available, not the form", async () => {
270
- await renderForgot();
271
- expect(screen.getByTestId("auth-invitation-body")).toHaveTextContent(
272
- en.auth.forgotUnavailableBody,
273
- );
274
- expect(screen.queryByTestId("auth-email")).not.toBeInTheDocument();
275
- });
276
-
277
- it("/reset-password renders not-available even carrying a live token", async () => {
278
- await renderReset({ token: "tok_live" });
279
- expect(screen.getByTestId("auth-invitation-body")).toHaveTextContent(
280
- en.auth.resetUnavailableBody,
281
- );
282
- expect(screen.queryByTestId("auth-password")).not.toBeInTheDocument();
283
- });
284
- });
285
-
286
- // ── The seventh case: the redirectTo a render assertion cannot see ──────────
287
-
288
- describe("the forgot island's requestPasswordReset call", () => {
289
- it("passes a non-empty, ABSOLUTE, same-origin redirectTo", async () => {
290
- const user = userEvent.setup();
291
- await renderForgot();
292
-
293
- await user.type(screen.getByTestId("auth-email"), "person@example.com");
294
- await user.click(screen.getByTestId("auth-submit"));
295
-
296
- await waitFor(() => expect(mockRequestPasswordReset).toHaveBeenCalled());
297
- const [args] = mockRequestPasswordReset.mock.calls[0];
298
- expect(args.email).toBe("person@example.com");
299
- expect(args.redirectTo).toBe("https://site.example/reset-password");
300
- // Absolute: originCheck compares an ORIGIN, and an empty callbackURL makes
301
- // Better Auth reject the emitted link outright.
302
- expect(args.redirectTo.startsWith("https://")).toBe(true);
303
- });
304
-
305
- it("swaps to the sent intent only on success", async () => {
306
- const user = userEvent.setup();
307
- await renderForgot();
308
-
309
- await user.type(screen.getByTestId("auth-email"), "person@example.com");
310
- await user.click(screen.getByTestId("auth-submit"));
311
-
312
- await waitFor(() =>
313
- expect(screen.getByTestId("auth-sent-body")).toBeInTheDocument(),
314
- );
315
- });
316
-
317
- it("shows the error state — never 'check your email' — when the server refuses", async () => {
318
- mockRequestPasswordReset.mockResolvedValue({
319
- error: { code: "RESET_PASSWORD_DISABLED" },
320
- });
321
- const user = userEvent.setup();
322
- await renderForgot();
323
-
324
- await user.type(screen.getByTestId("auth-email"), "person@example.com");
325
- await user.click(screen.getByTestId("auth-submit"));
326
-
327
- await waitFor(() =>
328
- expect(screen.getByText(en.auth.resetRequestFailed)).toBeInTheDocument(),
329
- );
330
- // The whole point: a site that cannot send never claims it did.
331
- expect(screen.queryByTestId("auth-sent-body")).not.toBeInTheDocument();
332
- });
333
- });
334
-
335
- describe("the reset island's resetPassword call", () => {
336
- it("sends the token in the body and routes to sign-in on success", async () => {
337
- // The island directly, so the post-reset navigation is observable —
338
- // jsdom's `window.location` is read-only, which is why the component takes
339
- // an injectable `navigate` at all.
340
- const navigate = jest.fn();
341
- const user = userEvent.setup();
342
- render(
343
- <ResetPasswordCard
344
- token="tok_live"
345
- signInHref="/sign-in"
346
- labels={{
347
- resetHeading: en.auth.resetHeading,
348
- resetSubmit: en.auth.resetSubmit,
349
- newPassword: en.auth.newPassword,
350
- confirmPassword: en.auth.confirmPassword,
351
- backToSignIn: en.auth.backToSignIn,
352
- }}
353
- errorLabels={{
354
- resetFailed: en.auth.resetFailed,
355
- invalidToken: en.auth.resetExpiredSubhead,
356
- mismatch: en.auth.passwordMismatch,
357
- }}
358
- navigate={navigate}
359
- />,
360
- );
361
-
362
- await user.type(screen.getByTestId("auth-password"), "a-long-enough-pw");
363
- await user.type(
364
- screen.getByTestId("auth-confirm-password"),
365
- "a-long-enough-pw",
366
- );
367
- await user.click(screen.getByTestId("auth-submit"));
368
-
369
- await waitFor(() => expect(mockResetPassword).toHaveBeenCalled());
370
- expect(mockResetPassword.mock.calls[0][0]).toEqual({
371
- newPassword: "a-long-enough-pw",
372
- token: "tok_live",
373
- });
374
- await waitFor(() => expect(navigate).toHaveBeenCalledWith("/sign-in"));
375
- });
376
-
377
- it("refuses mismatched passwords without calling the server", async () => {
378
- const user = userEvent.setup();
379
- await renderReset({ token: "tok_live" });
380
-
381
- await user.type(screen.getByTestId("auth-password"), "a-long-enough-pw");
382
- await user.type(screen.getByTestId("auth-confirm-password"), "different-pw");
383
- await user.click(screen.getByTestId("auth-submit"));
384
-
385
- await waitFor(() =>
386
- expect(screen.getByText(en.auth.passwordMismatch)).toBeInTheDocument(),
387
- );
388
- expect(mockResetPassword).not.toHaveBeenCalled();
389
- });
390
-
391
- it("treats an absent token as an expired one, and does not call the server", async () => {
392
- const user = userEvent.setup();
393
- await renderReset({});
394
-
395
- await user.type(screen.getByTestId("auth-password"), "a-long-enough-pw");
396
- await user.type(
397
- screen.getByTestId("auth-confirm-password"),
398
- "a-long-enough-pw",
399
- );
400
- await user.click(screen.getByTestId("auth-submit"));
401
-
402
- await waitFor(() =>
403
- expect(
404
- screen.getByText(en.auth.resetExpiredSubhead),
405
- ).toBeInTheDocument(),
406
- );
407
- expect(mockResetPassword).not.toHaveBeenCalled();
408
- });
409
- });
410
-
411
- // ── #6068 AC-1: a throwing signer cannot reject onPasswordReset ─────────────
412
-
413
- /**
414
- * The reset has ALREADY SUCCEEDED by the time `onPasswordReset` runs: the new
415
- * password is written and the presented token is consumed. A rejection here is
416
- * therefore not "the reset failed" — it is a 500 handed to a visitor whose
417
- * password DID change, over a token they can no longer retry with.
418
- *
419
- * `sendPasswordChangedNotice` carries a "never throws by construction"
420
- * invariant, and before #6068 that invariant had a hole: `dispatch()` built
421
- * and SIGNED the request OUTSIDE its own try, so anything `buildAuthEmailRequest`
422
- * threw propagated all the way out. #6061 made this callback unconditional, so
423
- * it now runs in degraded configurations — exactly where a signer is most
424
- * likely to be unhappy.
425
- *
426
- * The signer's one external dependency is `node:crypto`'s `createHmac`, so a
427
- * throwing `createHmac` IS a throwing `buildAuthEmailRequest`, reached through
428
- * the real call path rather than a stubbed-out seam.
429
- */
430
- describe("onPasswordReset survives a throwing buildAuthEmailRequest (#6068)", () => {
431
- const user = { id: "usr_reset", email: "person@example.com" };
432
-
433
- function onPasswordResetUnderTest(deleteMany: jest.Mock): (args: {
434
- user: { id: string; email: string };
435
- }) => Promise<void> {
436
- // `unknown` on the way in, exactly as the sibling config suite does it, so
437
- // the stub needs ONE assertion rather than a double one.
438
- const prismaStub: unknown = { verification: { deleteMany } };
439
- const auth = createAuth({ prisma: prismaStub as AuthPrisma });
440
- // The `betterAuth` mock above returns `{ options }` rather than a real
441
- // instance, so the declared return type is not the runtime shape. There is
442
- // no boundary type to fix: the double assertion IS the mock seam — the
443
- // same seam, and the same justification, as the sibling config suite.
444
- // eslint-disable-next-line no-restricted-syntax -- see above.
445
- const { options } = auth as unknown as { options: AuthOptionsUnderTest };
446
- const callback = options.emailAndPassword?.onPasswordReset;
447
- // Guarded rather than asserted inline: without it the cases below would
448
- // read `undefined(...)` and fail with a TypeError instead of a diagnosis.
449
- if (!callback) throw new Error("onPasswordReset was not wired");
450
- return callback;
451
- }
452
-
453
- beforeEach(() => {
454
- // Past `dispatch()`'s `not_configured` early return — without a secret the
455
- // signer is never reached and the case would pass vacuously.
456
- process.env.AUTH_EMAIL_WEBHOOK_SECRET = "whsec_test";
457
- process.env.AUTH_EMAIL_FROM = "noreply@site.example";
458
- mockCreateHmac.mockImplementation(() => {
459
- throw new Error("signer unavailable");
460
- });
461
- });
462
-
463
- it("resolves rather than rejecting — the completed reset is not turned into a 500", async () => {
464
- const deleteMany = jest.fn().mockResolvedValue({ count: 1 });
465
- await expect(
466
- onPasswordResetUnderTest(deleteMany)({ user }),
467
- ).resolves.toBeUndefined();
468
- });
469
-
470
- it("still consumes the user's other outstanding reset tokens", async () => {
471
- const deleteMany = jest.fn().mockResolvedValue({ count: 2 });
472
- await onPasswordResetUnderTest(deleteMany)({ user });
473
- // The sibling invalidation runs BEFORE the notice, so a notice that threw
474
- // would leave it done-but-unreported; what it may never do is leave the
475
- // caller with a rejected promise over work that already landed.
476
- expect(deleteMany).toHaveBeenCalledWith({
477
- where: {
478
- value: user.id,
479
- identifier: { startsWith: "reset-password:" },
480
- },
481
- });
482
- });
483
- });
484
-
485
- // ── #6068 AC-2: the flag-alone config, read through the REAL predicate ──────
486
-
487
- /**
488
- * The sibling "the flag alone does not open either page" block above drives
489
- * the two reset pages through the MOCKED predicate — it asserts the pages
490
- * branch correctly once `resetSendConfigured()` has already answered false.
491
- * This block asserts the answer itself, and the third affordance: with
492
- * `AILK_AUTH_PASSWORD_RESET=1` and `AUTH_EMAIL_WEBHOOK_SECRET` unset — intent
493
- * set, transport missing, every other conjunct satisfied — the REAL
494
- * `resetSendConfigured()` is what decides, and `/sign-in` must render no
495
- * "Forgot password?" link while `/forgot-password` renders its not-available
496
- * card. A flag-keyed link in this state is the dangling link #6018 shipped to
497
- * prevent and #6061 left behind on this one surface.
498
- *
499
- * The module mock stays (the two pages share it with the whole file); its
500
- * members are re-bound here to `jest.requireActual`'s real implementations, so
501
- * the env vars below — not a `mockReturnValue` — are what the pages read.
502
- */
503
- describe("the flag alone hides the /sign-in forgot link (#6068 AC-2)", () => {
504
- const realAuthEnv = jest.requireActual<
505
- typeof import("../../../../lib/auth-env")
506
- >("../../../../lib/auth-env");
507
-
508
- beforeEach(() => {
509
- mockIsResetAvailable.mockImplementation(() => realAuthEnv.isResetAvailable());
510
- mockResetSendConfigured.mockImplementation(() =>
511
- realAuthEnv.resetSendConfigured(),
512
- );
513
- mockGetActiveProviderIds.mockImplementation(() =>
514
- realAuthEnv.getActiveProviderIds(),
515
- );
516
-
517
- // Every conjunct of `resetSendConfigured()` satisfied EXCEPT the send
518
- // secret: the operator meant to offer reset and the relay cannot sign.
519
- process.env.AILK_AUTH_PASSWORD_RESET = "1";
520
- process.env.AUTH_EMAIL_SERVER = "smtp://mail.example";
521
- process.env.AUTH_EMAIL_FROM = "noreply@site.example";
522
- process.env.BETTER_AUTH_URL = "https://site.example";
523
- process.env.BETTER_AUTH_SECRET = "test-secret";
524
- delete process.env.AUTH_EMAIL_WEBHOOK_SECRET;
525
- });
526
-
527
- it("is a state the two predicates genuinely disagree about", () => {
528
- // Without this the two cases below could pass for the wrong reason — a
529
- // config neither predicate calls available proves nothing about which one
530
- // an affordance keys on.
531
- expect(realAuthEnv.isResetAvailable()).toBe(true);
532
- expect(realAuthEnv.resetSendConfigured()).toBe(false);
533
- });
534
-
535
- it("/sign-in renders the password form and NO forgot link", async () => {
536
- render(
537
- await SignInPage({
538
- params: Promise.resolve({ locale: "en" }),
539
- searchParams: Promise.resolve({}),
540
- }),
541
- );
542
- // The card itself is live — this is a hidden affordance, not a dead page.
543
- expect(screen.getByTestId("auth-password")).toBeInTheDocument();
544
- expect(screen.queryByTestId("auth-forgot")).toBeNull();
545
- });
546
-
547
- it("/forgot-password renders the not-available card", async () => {
548
- await renderForgot();
549
- expect(screen.getByTestId("auth-invitation-body")).toHaveTextContent(
550
- en.auth.forgotUnavailableBody,
551
- );
552
- expect(screen.queryByTestId("auth-email")).not.toBeInTheDocument();
553
- });
554
- });
@@ -1,56 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- *
4
- * `decideConsent` — the consent page's Allow and Deny (#10357 D6). `auth` is
5
- * mocked; `POST /mcp/consent` runs for real in
6
- * `__tests__/auth/mcp-oauth-flow.test.ts`. This suite proves the fallback
7
- * redirect is always a path on this site.
8
- */
9
- const mockConsent = jest.fn();
10
- const mockRedirect = jest.fn();
11
-
12
- // eslint-disable-next-line no-restricted-syntax -- #507: auth.ts loads ESM-only better-auth; its consent endpoint runs for real in mcp-oauth-flow.test.ts.
13
- jest.mock("../../../../../auth", () => ({
14
- auth: { api: { mcpConsent: (...args: unknown[]) => mockConsent(...args) } },
15
- }));
16
-
17
- jest.mock("next/headers", () => ({ headers: jest.fn().mockResolvedValue(new Headers()) }));
18
-
19
- jest.mock("next/navigation", () => ({ redirect: (...args: unknown[]) => mockRedirect(...args) }));
20
-
21
- import { decideConsent } from "../consent.actions";
22
-
23
- function form(values: Record<string, string>): FormData {
24
- const data = new FormData();
25
- for (const [key, value] of Object.entries(values)) data.append(key, value);
26
- return data;
27
- }
28
-
29
- beforeEach(() => {
30
- mockConsent.mockReset();
31
- mockRedirect.mockReset();
32
- });
33
-
34
- it("goes to the client's callback when the consent endpoint answers one", async () => {
35
- mockConsent.mockResolvedValue({ redirectURI: "http://127.0.0.1:53682/callback?code=c" });
36
- await decideConsent(form({ consent_code: "abc", locale: "en", decision: "deny" }));
37
- expect(mockRedirect).toHaveBeenCalledWith("http://127.0.0.1:53682/callback?code=c");
38
- });
39
-
40
- it("returns to this site's consent page on a refusal", async () => {
41
- mockConsent.mockRejectedValue(new Error("refused"));
42
- await decideConsent(form({ consent_code: "abc", locale: "en", decision: "allow" }));
43
- expect(mockRedirect).toHaveBeenCalledWith(expect.stringMatching(/^\/(en\/)?consent\?consent_code=abc$/));
44
- });
45
-
46
- it.each(["/evil.example", "//evil.example", "en/../..", "https://evil.example"])(
47
- "never builds the fallback from a posted locale of %s",
48
- async (locale) => {
49
- mockConsent.mockRejectedValue(new Error("refused"));
50
- await decideConsent(form({ consent_code: "abc", locale, decision: "allow" }));
51
- const target = String(mockRedirect.mock.calls[0]?.[0]);
52
- expect(target.startsWith("//")).toBe(false);
53
- expect(target).not.toContain("evil.example");
54
- expect(target).toMatch(/^\/(en\/)?consent\?consent_code=abc$/);
55
- },
56
- );