create-ailk 0.34.1 → 0.36.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 (139) hide show
  1. package/README.md +1 -1
  2. package/component-catalog.json +37 -4
  3. package/component-catalog.md +11 -9
  4. package/dist/add-module.js +7 -2
  5. package/dist/derive-architecture.js +2 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/env-catalog.js +8 -0
  9. package/dist/module-architecture.js +9 -0
  10. package/dist/programmatic.js +5 -2
  11. package/dist/site-listing-path.d.ts +8 -0
  12. package/dist/site-listing-path.js +8 -0
  13. package/dist/surfaces.d.ts +20 -0
  14. package/dist/surfaces.js +32 -3
  15. package/dist/template-record.js +2 -0
  16. package/dist/topology.d.ts +4 -4
  17. package/dist/topology.js +104 -60
  18. package/dist/update.js +11 -0
  19. package/package.json +3 -3
  20. package/templates/.env.example +21 -0
  21. package/templates/apps/api/.env.example +7 -0
  22. package/templates/apps/api/CLAUDE.md +14 -9
  23. package/templates/apps/mcp/CLAUDE.md +18 -7
  24. package/templates/apps/web/.env.example +16 -0
  25. package/templates/apps/web/CLAUDE.md +46 -5
  26. package/templates/apps/web/app/[locale]/(auth)/__tests__/password-reset.test.tsx +2 -0
  27. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/page.test.tsx +52 -1
  28. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/remembered-method.test.ts +43 -0
  29. package/templates/apps/web/app/[locale]/(auth)/sign-in/__tests__/sign-in-card.test.tsx +108 -1
  30. package/templates/apps/web/app/[locale]/(auth)/sign-in/page.tsx +36 -3
  31. package/templates/apps/web/app/[locale]/(auth)/sign-in/remembered-method.ts +37 -0
  32. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-card.tsx +90 -33
  33. package/templates/apps/web/app/[locale]/(auth)/sign-in/sign-in-text.ts +9 -4
  34. package/templates/apps/web/app/[locale]/(authed)/__tests__/gate.test.tsx +79 -348
  35. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +12 -1
  36. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +55 -2
  37. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +43 -0
  38. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +10 -5
  39. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +6 -5
  40. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +1 -1
  41. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +60 -6
  42. package/templates/apps/web/app/[locale]/(authed)/account/billing-source.ts +32 -3
  43. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +8 -1
  44. package/templates/apps/web/app/[locale]/(authed)/account/connect/page.tsx +7 -3
  45. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/phone-verification.test.tsx +215 -0
  46. package/templates/apps/web/app/[locale]/(authed)/account/general/__tests__/seam-imports.test.ts +65 -0
  47. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +47 -0
  48. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-actions.ts +122 -0
  49. package/templates/apps/web/app/[locale]/(authed)/account/general/phone-verification.tsx +214 -0
  50. package/templates/apps/web/app/[locale]/(authed)/account/inbox/[kind]/[id]/page.tsx +6 -1
  51. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/invitation-id.test.ts +35 -0
  52. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__/page.test.tsx +266 -0
  53. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/actions.ts +116 -0
  54. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/invitation-id.ts +12 -0
  55. package/templates/apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/page.tsx +154 -0
  56. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +6 -4
  57. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +3 -1
  58. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +15 -13
  59. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +20 -52
  60. package/templates/apps/web/app/[locale]/flows/[slug]/FlowStepperClient.tsx +43 -4
  61. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.deliverable.test.tsx +23 -9
  62. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.invite.test.tsx +15 -0
  63. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.permalink.test.tsx +74 -0
  64. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/FlowStepperClient.test.tsx +34 -1
  65. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/magnet-page.test.tsx +257 -4
  66. package/templates/apps/web/app/[locale]/flows/[slug]/__tests__/save.actions.test.ts +72 -92
  67. package/templates/apps/web/app/[locale]/flows/[slug]/email-moment.ts +2 -2
  68. package/templates/apps/web/app/[locale]/flows/[slug]/magnet-page.tsx +164 -65
  69. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/LevelChart.tsx +100 -0
  70. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsCard.tsx +99 -0
  71. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsClient.tsx +415 -253
  72. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/ResultsEmailStep.tsx +113 -32
  73. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.no-commerce.test.tsx +16 -17
  74. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/ResultsClient.report.test.tsx +284 -0
  75. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/by-result.test.tsx +52 -19
  76. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/cards.test.tsx +402 -0
  77. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/page.test.tsx +100 -12
  78. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/__tests__/score.test.tsx +153 -101
  79. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/meeting-seam.ts +36 -0
  80. package/templates/apps/web/app/[locale]/flows/[slug]/results/[payload]/page.tsx +121 -33
  81. package/templates/apps/web/app/[locale]/flows/[slug]/save.actions.ts +27 -17
  82. package/templates/apps/web/app/[locale]/flows/[slug]/served-flow.ts +91 -0
  83. package/templates/apps/web/app/[locale]/layout.tsx +42 -76
  84. package/templates/apps/web/app/[locale]/purchase/__tests__/success.test.tsx +50 -0
  85. package/templates/apps/web/app/[locale]/purchase/success/page.tsx +48 -7
  86. package/templates/apps/web/app/api/auth/hub/__tests__/entry-routes.test.ts +749 -0
  87. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +189 -6
  88. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +101 -31
  89. package/templates/apps/web/app/api/auth/hub/continuation.ts +51 -2
  90. package/templates/apps/web/app/api/auth/hub/email/route.ts +111 -0
  91. package/templates/apps/web/app/api/auth/hub/entry-shared.ts +163 -0
  92. package/templates/apps/web/app/api/auth/hub/purchase/route.ts +230 -0
  93. package/templates/apps/web/app/api/auth/hub/purchase-link/route.ts +174 -0
  94. package/templates/apps/web/app/api/auth/hub/sign-up/route.ts +60 -0
  95. package/templates/apps/web/app/api/auth/hub/sign-up-evidence.ts +97 -0
  96. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +475 -7
  97. package/templates/apps/web/app/api/hub-session/callback/route.ts +13 -47
  98. package/templates/apps/web/app/api/hub-session/email/route.ts +125 -0
  99. package/templates/apps/web/app/api/hub-session/one-tap/nonce/route.ts +49 -0
  100. package/templates/apps/web/app/api/hub-session/one-tap/route.ts +106 -0
  101. package/templates/apps/web/app/api/hub-session/open/route.ts +111 -0
  102. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +23 -40
  103. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +1 -10
  104. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +122 -0
  105. package/templates/apps/web/app/llms.txt/route.ts +14 -2
  106. package/templates/apps/web/app/sitemap.xml/__tests__/site-listing.test.ts +98 -0
  107. package/templates/apps/web/app/sitemap.xml/route.ts +13 -2
  108. package/templates/apps/web/auth.ts +133 -6
  109. package/templates/apps/web/components/sign-out-trigger.tsx +1 -1
  110. package/templates/apps/web/lib/__tests__/auth-email.test.ts +141 -0
  111. package/templates/apps/web/lib/__tests__/auth-phone.test.ts +445 -0
  112. package/templates/apps/web/lib/__tests__/auth-sms.test.ts +140 -0
  113. package/templates/apps/web/lib/__tests__/fixtures/tsconfig.flow.json +18 -0
  114. package/templates/apps/web/lib/__tests__/site-header.test.ts +13 -0
  115. package/templates/apps/web/lib/__tests__/telemetry-scrub.test.ts +19 -1
  116. package/templates/apps/web/lib/account-config.ts +24 -9
  117. package/templates/apps/web/lib/auth-email.ts +62 -6
  118. package/templates/apps/web/lib/auth-env.ts +13 -0
  119. package/templates/apps/web/lib/auth-sms.ts +180 -0
  120. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +28 -0
  121. package/templates/apps/web/lib/hub-session/__tests__/spoke-sign-in.test.tsx +332 -0
  122. package/templates/apps/web/lib/hub-session/config.ts +7 -1
  123. package/templates/apps/web/lib/hub-session/entry.ts +238 -0
  124. package/templates/apps/web/lib/hub-session/index.ts +1 -4
  125. package/templates/apps/web/lib/hub-session/one-tap.tsx +148 -0
  126. package/templates/apps/web/lib/hub-session/session.ts +120 -2
  127. package/templates/apps/web/lib/hub-session/spoke-sign-in.tsx +277 -0
  128. package/templates/apps/web/lib/site-header.ts +14 -1
  129. package/templates/apps/web/lib/site-listing.ts +7 -0
  130. package/templates/apps/web/lib/telemetry-scrub.ts +11 -0
  131. package/templates/apps/web/lib/topology.generated.ts +39 -0
  132. package/templates/apps/web/messages/en.json +125 -21
  133. package/templates/apps/web/middleware.ts +34 -2
  134. package/templates/apps/web/security-headers.config.ts +21 -0
  135. package/versions.json +47 -47
  136. package/templates/apps/web/app/[locale]/(authed)/sign-in-gate.tsx +0 -162
  137. package/templates/apps/web/components/signed-in-nav.tsx +0 -79
  138. package/templates/apps/web/lib/hub-session/__tests__/sign-in-gate.test.tsx +0 -180
  139. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +0 -162
@@ -28,9 +28,11 @@ import {
28
28
  confirmSignUpEmail,
29
29
  MAGIC_LINK_TTL_SECONDS,
30
30
  makeMagicLinkOptions,
31
+ makeSendAccountOpen,
31
32
  makeSendResetPassword,
32
33
  makeSendVerificationEmail,
33
34
  makeSendPasswordChangedNotice,
35
+ purchaseCapture,
34
36
  } from "../auth-email";
35
37
 
36
38
  const ORIGINAL_ENV = process.env;
@@ -825,3 +827,142 @@ describe("confirmSignUpEmail (#10820 D7)", () => {
825
827
  expect(JSON.stringify(lines)).not.toContain(NONCE);
826
828
  });
827
829
  });
830
+
831
+ // ── #11096 D9 — the purchase capture and the account-open kind ──────────────
832
+
833
+ describe("sendMagicLink inside purchaseCapture (#11096 D9)", () => {
834
+ const AGREED = { agreements: ["account_terms"], locale: "en" };
835
+
836
+ beforeEach(() => {
837
+ process.env.AILK_AUTH_SIGNUP_OPEN = "true";
838
+ });
839
+
840
+ it("binds the agreements as for any sign-up request, hands the token to the capture and mails nothing", async () => {
841
+ const send = jest.fn().mockResolvedValue({ ok: true });
842
+ const bind = jest.fn().mockResolvedValue(AGREED);
843
+ const { lines, log } = makeLog();
844
+ const { ctx, background, runInBackgroundOrAwait } = makeCtx(null);
845
+ const { sendMagicLink } = makeMagicLinkOptions({ send, log, bind });
846
+ const capture = { token: null as string | null };
847
+
848
+ await purchaseCapture.run(capture, () =>
849
+ sendMagicLink(
850
+ { email: "new@example.com", url: LINK, token: "MLTOKEN", metadata: AGREED },
851
+ ctx,
852
+ ),
853
+ );
854
+ await Promise.all(background);
855
+
856
+ expect(bind).toHaveBeenCalledWith(
857
+ ctx.context.internalAdapter,
858
+ "MLTOKEN",
859
+ AGREED,
860
+ MAGIC_LINK_TTL_SECONDS,
861
+ );
862
+ expect(capture.token).toBe("MLTOKEN");
863
+ expect(send).not.toHaveBeenCalled();
864
+ expect(runInBackgroundOrAwait).not.toHaveBeenCalled();
865
+ expect(JSON.stringify(lines)).not.toContain("MLTOKEN");
866
+ });
867
+
868
+ it("captures nothing and mails nothing for an address that already has an account", async () => {
869
+ const send = jest.fn().mockResolvedValue({ ok: true });
870
+ const bind = jest.fn().mockResolvedValue(AGREED);
871
+ const { ctx } = makeCtx({ id: "user_1", email: "old@example.com" });
872
+ const { sendMagicLink } = makeMagicLinkOptions({ send, log: makeLog().log, bind });
873
+ const capture = { token: null as string | null };
874
+
875
+ await purchaseCapture.run(capture, () =>
876
+ sendMagicLink(
877
+ { email: "old@example.com", url: LINK, token: "MLTOKEN", metadata: AGREED },
878
+ ctx,
879
+ ),
880
+ );
881
+
882
+ expect(capture.token).toBeNull();
883
+ expect(send).not.toHaveBeenCalled();
884
+ });
885
+
886
+ it("captures nothing when the binding fails", async () => {
887
+ const send = jest.fn();
888
+ const bind = jest.fn().mockRejectedValue(new Error("db down"));
889
+ const { ctx } = makeCtx(null);
890
+ const { sendMagicLink } = makeMagicLinkOptions({ send, log: makeLog().log, bind });
891
+ const capture = { token: null as string | null };
892
+
893
+ await purchaseCapture.run(capture, () =>
894
+ sendMagicLink(
895
+ { email: "new@example.com", url: LINK, token: "MLTOKEN", metadata: AGREED },
896
+ ctx,
897
+ ),
898
+ );
899
+
900
+ expect(capture.token).toBeNull();
901
+ expect(send).not.toHaveBeenCalled();
902
+ });
903
+
904
+ it("outside a capture the same call mails, exactly as before", async () => {
905
+ const send = jest.fn().mockResolvedValue({ ok: true });
906
+ const bind = jest.fn().mockResolvedValue(AGREED);
907
+ const { ctx, background } = makeCtx(null);
908
+ const { sendMagicLink } = makeMagicLinkOptions({ send, log: makeLog().log, bind });
909
+
910
+ await sendMagicLink(
911
+ { email: "new@example.com", url: LINK, token: "MLTOKEN", metadata: AGREED },
912
+ ctx,
913
+ );
914
+ await Promise.all(background);
915
+
916
+ expect(send).toHaveBeenCalledTimes(1);
917
+ });
918
+ });
919
+
920
+ describe("makeSendAccountOpen (#11096 D9)", () => {
921
+ const OPEN_URL = "https://spoke.example/account?claim=CLAIM";
922
+
923
+ it("posts one signed account-open body to the buyer: no agreements, no locale", async () => {
924
+ const send = jest.fn().mockResolvedValue({ ok: true });
925
+ const { lines, log } = makeLog();
926
+
927
+ await makeSendAccountOpen({ send, log })({
928
+ to: "buyer@example.com",
929
+ url: OPEN_URL,
930
+ });
931
+
932
+ expect(send).toHaveBeenCalledTimes(1);
933
+ const [rawBody, headers] = send.mock.calls[0] as [string, Record<string, string>];
934
+ expect(JSON.parse(rawBody)).toEqual({
935
+ kind: "account-open",
936
+ userId: "purchase",
937
+ to: "buyer@example.com",
938
+ url: OPEN_URL,
939
+ });
940
+ const timestamp = headers["x-ailk-auth-email-timestamp"]!;
941
+ expect(headers["x-ailk-auth-email-signature"]).toBe(
942
+ `sha256=${createHmac("sha256", "webhook-secret")
943
+ .update(`${timestamp}.${rawBody}`, "utf8")
944
+ .digest("hex")}`,
945
+ );
946
+ const serialized = JSON.stringify(lines);
947
+ expect(serialized).not.toContain("buyer@example.com");
948
+ expect(serialized).not.toContain("CLAIM");
949
+ });
950
+
951
+ it("never throws when the transport fails, and answers false", async () => {
952
+ const send = jest.fn().mockRejectedValue(new Error("down"));
953
+ await expect(
954
+ makeSendAccountOpen({ send, log: makeLog().log })({
955
+ to: "buyer@example.com",
956
+ url: OPEN_URL,
957
+ }),
958
+ ).resolves.toBe(false);
959
+ });
960
+
961
+ it("answers true only when the relay accepted the mail", async () => {
962
+ const accepted = jest.fn().mockResolvedValue({ ok: true, status: 202 });
963
+ const refused = jest.fn().mockResolvedValue({ ok: false, status: 500 });
964
+ const input = { to: "buyer@example.com", url: OPEN_URL };
965
+ await expect(makeSendAccountOpen({ send: accepted, log: makeLog().log })(input)).resolves.toBe(true);
966
+ await expect(makeSendAccountOpen({ send: refused, log: makeLog().log })(input)).resolves.toBe(false);
967
+ });
968
+ });
@@ -0,0 +1,445 @@
1
+ /**
2
+ * @jest-environment node
3
+ *
4
+ * The phone step, end to end against the REAL apps/web `createAuth()` and the
5
+ * REAL better-auth 1.6.22 phone plugin (#11106, spec
6
+ * docs/specs/11106-the-workforce-foundation-roles-by-spec.md D7, D9; AC-6,
7
+ * SEC-11106-1, SEC-11106-2).
8
+ *
9
+ * - signed in with a verified email: send-otp, then verify with
10
+ * `updatePhoneNumber: true`, sets `phoneNumber` and `phoneNumberVerified`;
11
+ * - signed out, send-otp is 401; with an unverified email, 403;
12
+ * - verify without `updatePhoneNumber` is refused and sets no session cookie;
13
+ * - `/sign-in/phone-number` and both phone reset paths are 404;
14
+ * - `/update-user { phoneNumber }` is 400 `PHONE_NUMBER_CANNOT_BE_UPDATED`;
15
+ * - `/sign-up/email` with a `phoneNumber` in its body creates a row whose
16
+ * `phoneNumber` is null;
17
+ * - a `+44` number under the default country list is refused with no relay
18
+ * call;
19
+ * - no captured log line carries the number or the code.
20
+ *
21
+ * better-auth is ESM-only and Jest runs ts-jest in CommonJS, so — the
22
+ * `__tests__/auth/sign-up-agreements.test.ts` pattern — this file is its own
23
+ * child process (`node --import tsx`), with a Prisma double. The relay is the
24
+ * stub sender: `fetch` to `/v1/auth/transactional-sms` is answered in the
25
+ * child and its signed body captured; nothing is texted. The summary carries
26
+ * statuses, codes and booleans — never the code itself.
27
+ */
28
+ import { execFileSync } from "node:child_process";
29
+ import { createHash } from "node:crypto";
30
+ import Module from "node:module";
31
+ import { join } from "node:path";
32
+
33
+ const FLOW_FLAG = "AILK_AUTH_PHONE_FLOW";
34
+ const BASE = "http://localhost:3435";
35
+ const API = `${BASE}/api/auth`;
36
+ const NUMBER = "+15555550123";
37
+ const UK_NUMBER = "+447700900123";
38
+ const STATEMENT = "I accept the [Terms](terms).";
39
+
40
+ type Answer = { status: number; code: string | null; sessionCookie: boolean };
41
+
42
+ type Flow = {
43
+ signUp: { answer: Answer; phoneNumber: unknown; phoneNumberVerified: unknown };
44
+ signedOutSend: Answer;
45
+ unverifiedSend: Answer;
46
+ ukSend: Answer & { relayCalls: number };
47
+ send: Answer & { relayCalls: number; relayTo: string | null; relayKind: string | null };
48
+ verifyWithoutUpdate: Answer & { userPhone: unknown };
49
+ verify: Answer & { phoneNumber: unknown; phoneNumberVerified: unknown };
50
+ closed: Record<"signIn" | "requestReset" | "reset", Answer>;
51
+ updateUser: Answer & { phoneNumber: unknown };
52
+ logNamesNumber: boolean;
53
+ logNamesCode: boolean;
54
+ };
55
+
56
+ // ── The flow (child process) ────────────────────────────────────────────────
57
+
58
+ type Row = Record<string, unknown>;
59
+ type Where = Record<string, unknown>;
60
+
61
+ /** Prisma's where semantics, as far as Better Auth's adapter uses them. */
62
+ function matches(row: Row, where: Where | undefined): boolean {
63
+ if (!where) return true;
64
+ return Object.entries(where).every(([key, condition]) => {
65
+ if (key === "AND") return (condition as Where[]).every((w) => matches(row, w));
66
+ if (key === "OR") return (condition as Where[]).some((w) => matches(row, w));
67
+ const value = row[key];
68
+ if (condition === null || typeof condition !== "object" || condition instanceof Date) {
69
+ return (value ?? null) === condition;
70
+ }
71
+ const filter = condition as Record<string, unknown>;
72
+ const fold = (v: unknown) =>
73
+ filter.mode === "insensitive" && typeof v === "string" ? v.toLowerCase() : v;
74
+ return Object.entries(filter).every(([op, operand]) => {
75
+ switch (op) {
76
+ case "mode":
77
+ return true;
78
+ case "equals":
79
+ return fold(value) === fold(operand);
80
+ case "in":
81
+ return (operand as unknown[]).map(fold).includes(fold(value));
82
+ case "not":
83
+ return value !== operand;
84
+ case "lt":
85
+ return (value as number) < (operand as number);
86
+ case "gt":
87
+ return (value as number) > (operand as number);
88
+ default:
89
+ throw new Error(`double: unsupported where operator ${op}`);
90
+ }
91
+ });
92
+ });
93
+ }
94
+
95
+ const MODELS = ["user", "account", "session", "verification", "consentGrant"] as const;
96
+
97
+ function prismaDouble() {
98
+ const store: Record<string, Row[]> = Object.fromEntries(MODELS.map((m) => [m, []]));
99
+ let ids = 0;
100
+ function delegate(model: string) {
101
+ const rows = () => store[model]!;
102
+ const notFound = () => Object.assign(new Error("not found"), { code: "P2025" });
103
+ return {
104
+ async create(args: { data: Row }) {
105
+ const row = { id: `${model}_${++ids}`, ...args.data };
106
+ rows().push(row);
107
+ return { ...row };
108
+ },
109
+ async createMany(args: { data: Row[] }) {
110
+ for (const data of args.data) rows().push({ id: `${model}_${++ids}`, ...data });
111
+ return { count: args.data.length };
112
+ },
113
+ async findFirst(args: { where?: Where } = {}) {
114
+ const row = rows().find((r) => matches(r, args.where));
115
+ return row ? { ...row } : null;
116
+ },
117
+ async findUnique(args: { where?: Where } = {}) {
118
+ const row = rows().find((r) => matches(r, args.where));
119
+ return row ? { ...row } : null;
120
+ },
121
+ async findMany(args: { where?: Where; take?: number; skip?: number } = {}) {
122
+ const found = rows().filter((r) => matches(r, args.where));
123
+ return found.slice(args.skip ?? 0, (args.skip ?? 0) + (args.take ?? found.length));
124
+ },
125
+ async count(args: { where?: Where } = {}) {
126
+ return rows().filter((r) => matches(r, args.where)).length;
127
+ },
128
+ async update(args: { where: Where; data: Row }) {
129
+ const row = rows().find((r) => matches(r, args.where));
130
+ if (!row) throw notFound();
131
+ Object.assign(row, args.data);
132
+ return { ...row };
133
+ },
134
+ async updateMany(args: { where?: Where; data: Row }) {
135
+ const found = rows().filter((r) => matches(r, args.where));
136
+ for (const row of found) Object.assign(row, args.data);
137
+ return { count: found.length };
138
+ },
139
+ async delete(args: { where: Where }) {
140
+ const index = rows().findIndex((r) => matches(r, args.where));
141
+ if (index < 0) throw notFound();
142
+ return rows().splice(index, 1)[0];
143
+ },
144
+ async deleteMany(args: { where?: Where } = {}) {
145
+ const keep = rows().filter((r) => !matches(r, args.where));
146
+ const count = rows().length - keep.length;
147
+ store[model] = keep;
148
+ return { count };
149
+ },
150
+ };
151
+ }
152
+ const root: Record<string, unknown> = Object.fromEntries(MODELS.map((m) => [m, delegate(m)]));
153
+ root.$transaction = async (fn: (client: unknown) => Promise<unknown>) => fn(root);
154
+ return { root, store };
155
+ }
156
+
157
+ async function runFlow(): Promise<Flow> {
158
+ // The sign-up-agreements suite's reason: seed the native ESM namespaces so
159
+ // `auth.ts` and its lazy `import("better-auth/api")` share one instance.
160
+ for (const entry of [
161
+ "better-auth",
162
+ "better-auth/adapters/prisma",
163
+ "better-auth/next-js",
164
+ "better-auth/plugins",
165
+ ]) {
166
+ const filename = require.resolve(entry);
167
+ const native: unknown = await import(entry);
168
+ require.cache[filename] = Object.assign(new Module(filename), {
169
+ filename,
170
+ loaded: true,
171
+ exports: native,
172
+ });
173
+ }
174
+
175
+ // Every line the app logs, for the PII check; stdout stays the summary.
176
+ const logLines: string[] = [];
177
+ for (const level of ["log", "info", "warn", "error", "debug"] as const) {
178
+ console[level] = (...args: unknown[]) => {
179
+ logLines.push(args.map((a) => (typeof a === "string" ? a : JSON.stringify(a))).join(" "));
180
+ };
181
+ }
182
+
183
+ const { createAuth } = require("../../auth") as typeof import("../../auth");
184
+ const { consent } =
185
+ require("@working-theory/api-client") as typeof import("@working-theory/api-client");
186
+
187
+ // The sign-up evidence, answered locally (one agreement).
188
+ consent.signUpEvidence = async () => ({
189
+ ok: true,
190
+ body: {
191
+ workspaceId: "ws_site_W",
192
+ agreements: [
193
+ {
194
+ purposeId: "account_terms",
195
+ policyVersion: 1,
196
+ locale: "en",
197
+ statement: STATEMENT,
198
+ statementHash: createHash("sha256").update(STATEMENT).digest("hex"),
199
+ },
200
+ ],
201
+ },
202
+ });
203
+
204
+ // The stub sender: the relay answered here, its signed body kept.
205
+ const relayed: Array<{ kind: string; to: string; code: string }> = [];
206
+ const realFetch = globalThis.fetch;
207
+ globalThis.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
208
+ const url = String(input instanceof Request ? input.url : input);
209
+ if (url.endsWith("/v1/auth/transactional-sms")) {
210
+ relayed.push(JSON.parse(String(init?.body)) as { kind: string; to: string; code: string });
211
+ return new Response(JSON.stringify({ ok: true }), { status: 202 });
212
+ }
213
+ return realFetch(input, init);
214
+ };
215
+
216
+ const double = prismaDouble();
217
+ type AuthPrisma = NonNullable<NonNullable<Parameters<typeof createAuth>[0]>["prisma"]>;
218
+ const client: object = double.root;
219
+ const auth = createAuth({ prisma: client as AuthPrisma });
220
+
221
+ let ip = 0;
222
+ const nextIp = () => `203.0.113.${++ip}`;
223
+ const settle = () => new Promise((resolve) => setTimeout(resolve, 50));
224
+
225
+ async function call(path: string, body: unknown, cookie?: string): Promise<Answer> {
226
+ const res = await auth.handler(
227
+ new Request(`${API}${path}`, {
228
+ method: "POST",
229
+ headers: {
230
+ origin: BASE,
231
+ "content-type": "application/json",
232
+ "x-forwarded-for": nextIp(),
233
+ ...(cookie ? { cookie } : {}),
234
+ },
235
+ body: JSON.stringify(body),
236
+ }),
237
+ );
238
+ const text = await res.text();
239
+ let code: string | null;
240
+ try {
241
+ const parsed = JSON.parse(text) as { code?: unknown };
242
+ code = typeof parsed.code === "string" ? parsed.code : null;
243
+ } catch {
244
+ code = null;
245
+ }
246
+ const sessionCookie = res.headers
247
+ .getSetCookie()
248
+ .some((c) => c.slice(0, c.indexOf("=")).endsWith("session_token") && !c.includes("Max-Age=0"));
249
+ await settle();
250
+ return { status: res.status, code, sessionCookie };
251
+ }
252
+
253
+ const userRow = () => double.store.user!.find((u) => u.email === "person@example.test")!;
254
+ const out: Partial<Flow> = {};
255
+
256
+ // ── Sign-up cannot claim a number (SEC-11106-1) ───────────────────────────
257
+ const signUpAnswer = await call("/sign-up/email", {
258
+ email: "person@example.test",
259
+ password: "correct horse battery staple",
260
+ name: "Person",
261
+ agreements: ["account_terms"],
262
+ locale: "en",
263
+ phoneNumber: NUMBER,
264
+ });
265
+ out.signUp = {
266
+ answer: signUpAnswer,
267
+ phoneNumber: userRow()?.phoneNumber ?? null,
268
+ phoneNumberVerified: userRow()?.phoneNumberVerified ?? null,
269
+ };
270
+
271
+ // ── A session: sign in with the password ─────────────────────────────────
272
+ const signIn = await auth.handler(
273
+ new Request(`${API}/sign-in/email`, {
274
+ method: "POST",
275
+ headers: { origin: BASE, "content-type": "application/json", "x-forwarded-for": nextIp() },
276
+ body: JSON.stringify({ email: "person@example.test", password: "correct horse battery staple" }),
277
+ }),
278
+ );
279
+ const cookie = signIn.headers
280
+ .getSetCookie()
281
+ .map((c) => c.slice(0, c.indexOf(";")))
282
+ .join("; ");
283
+
284
+ // ── send-otp needs a verified-email session ───────────────────────────────
285
+ out.signedOutSend = await call("/phone-number/send-otp", { phoneNumber: NUMBER });
286
+ out.unverifiedSend = await call("/phone-number/send-otp", { phoneNumber: NUMBER }, cookie);
287
+ userRow().emailVerified = true;
288
+
289
+ // ── The country list (SEC-11106-2) ────────────────────────────────────────
290
+ const beforeUk = relayed.length;
291
+ const ukAnswer = await call("/phone-number/send-otp", { phoneNumber: UK_NUMBER }, cookie);
292
+ out.ukSend = { ...ukAnswer, relayCalls: relayed.length - beforeUk };
293
+
294
+ // ── Send, then verify ─────────────────────────────────────────────────────
295
+ const beforeSend = relayed.length;
296
+ const sendAnswer = await call("/phone-number/send-otp", { phoneNumber: NUMBER }, cookie);
297
+ const sent = relayed.slice(beforeSend);
298
+ out.send = {
299
+ ...sendAnswer,
300
+ relayCalls: sent.length,
301
+ relayTo: sent[0]?.to ?? null,
302
+ relayKind: sent[0]?.kind ?? null,
303
+ };
304
+ const code = sent[0]?.code ?? "";
305
+
306
+ const withoutUpdate = await call("/phone-number/verify", { phoneNumber: NUMBER, code });
307
+ out.verifyWithoutUpdate = { ...withoutUpdate, userPhone: userRow().phoneNumber ?? null };
308
+
309
+ const verified = await call(
310
+ "/phone-number/verify",
311
+ { phoneNumber: NUMBER, code, updatePhoneNumber: true },
312
+ cookie,
313
+ );
314
+ out.verify = {
315
+ ...verified,
316
+ phoneNumber: userRow().phoneNumber ?? null,
317
+ phoneNumberVerified: userRow().phoneNumberVerified ?? null,
318
+ };
319
+
320
+ // ── The closed paths ──────────────────────────────────────────────────────
321
+ out.closed = {
322
+ signIn: await call("/sign-in/phone-number", { phoneNumber: NUMBER, password: "x".repeat(12) }),
323
+ requestReset: await call("/phone-number/request-password-reset", { phoneNumber: NUMBER }),
324
+ reset: await call("/phone-number/reset-password", {
325
+ phoneNumber: NUMBER,
326
+ otp: "000000",
327
+ newPassword: "y".repeat(12),
328
+ }),
329
+ };
330
+
331
+ // ── /update-user cannot write a number ────────────────────────────────────
332
+ const updateAnswer = await call("/update-user", { phoneNumber: "+15555550999" }, cookie);
333
+ out.updateUser = { ...updateAnswer, phoneNumber: userRow().phoneNumber ?? null };
334
+
335
+ out.logNamesNumber = logLines.some((l) => l.includes(NUMBER) || l.includes(NUMBER.slice(1)));
336
+ out.logNamesCode = code !== "" && logLines.some((l) => l.includes(code));
337
+ return out as Flow;
338
+ }
339
+
340
+ // ── The suite (Jest side) ───────────────────────────────────────────────────
341
+
342
+ function defineSuite(): void {
343
+ const APP_ROOT = join(__dirname, "..", "..");
344
+ // Beside this suite, not under `__tests__/auth/fixtures/`: `apps/web/__tests__`
345
+ // never reaches a scaffold, and this suite does (#11141).
346
+ const FIXTURES = join(__dirname, "fixtures");
347
+ let flow: Flow;
348
+
349
+ beforeAll(() => {
350
+ let stdout: string;
351
+ try {
352
+ stdout = execFileSync(process.execPath, ["--import", "tsx", __filename], {
353
+ cwd: APP_ROOT,
354
+ env: {
355
+ PATH: process.env.PATH ?? "",
356
+ NODE_ENV: "test",
357
+ BETTER_AUTH_TELEMETRY: "0",
358
+ TSX_TSCONFIG_PATH: join(FIXTURES, "tsconfig.flow.json"),
359
+ [FLOW_FLAG]: "1",
360
+ // The phone predicate's two conjuncts, the password method and open
361
+ // sign-up — test values only.
362
+ AUTH_EMAIL_WEBHOOK_SECRET: "flow-webhook-secret",
363
+ BETTER_AUTH_URL: BASE,
364
+ BETTER_AUTH_SECRET: "flow-secret-0123456789abcdef0123456789abcdef",
365
+ AUTH_EMAIL_SERVER: "smtp://mail.site.example",
366
+ AUTH_EMAIL_FROM: "noreply@site.example",
367
+ AILK_AUTH_SIGNUP_OPEN: "1",
368
+ AILK_API_URL: "http://api.site.example",
369
+ NEXT_PUBLIC_ENABLED_LOCALES: "en",
370
+ },
371
+ encoding: "utf8",
372
+ stdio: ["ignore", "pipe", "pipe"],
373
+ });
374
+ } catch (err) {
375
+ const stderr = (err as { stderr?: string }).stderr ?? "";
376
+ throw new Error(`auth-phone flow failed:\n${stderr}`, { cause: err });
377
+ }
378
+ flow = JSON.parse(stdout) as Flow;
379
+ }, 90_000);
380
+
381
+ it("a sign-up cannot claim a number: the created row's phoneNumber is null", () => {
382
+ expect(flow.signUp.answer.status).toBe(200);
383
+ expect(flow.signUp.phoneNumber).toBeNull();
384
+ expect(flow.signUp.phoneNumberVerified).toBeNull();
385
+ });
386
+
387
+ it("send-otp signed out is 401, with an unverified email 403", () => {
388
+ expect(flow.signedOutSend.status).toBe(401);
389
+ expect(flow.unverifiedSend.status).toBe(403);
390
+ expect(flow.unverifiedSend.code).toBe("EMAIL_NOT_VERIFIED");
391
+ });
392
+
393
+ it("a +44 number under the default country list is refused with no relay call", () => {
394
+ expect(flow.ukSend.status).toBe(400);
395
+ expect(flow.ukSend.relayCalls).toBe(0);
396
+ });
397
+
398
+ it("send-otp posts one signed phone-verification body to the relay", () => {
399
+ expect(flow.send.status).toBe(200);
400
+ expect(flow.send.relayCalls).toBe(1);
401
+ expect(flow.send.relayKind).toBe("phone-verification");
402
+ expect(flow.send.relayTo).toBe(NUMBER);
403
+ });
404
+
405
+ it("verify without updatePhoneNumber is refused and sets no session", () => {
406
+ expect(flow.verifyWithoutUpdate.status).toBeGreaterThanOrEqual(400);
407
+ expect(flow.verifyWithoutUpdate.sessionCookie).toBe(false);
408
+ expect(flow.verifyWithoutUpdate.userPhone).toBeNull();
409
+ });
410
+
411
+ it("verify with updatePhoneNumber: true sets both fields", () => {
412
+ expect(flow.verify.status).toBe(200);
413
+ expect(flow.verify.phoneNumber).toBe(NUMBER);
414
+ expect(flow.verify.phoneNumberVerified).toBe(true);
415
+ });
416
+
417
+ it("/sign-in/phone-number and both reset paths are 404", () => {
418
+ expect(flow.closed.signIn.status).toBe(404);
419
+ expect(flow.closed.requestReset.status).toBe(404);
420
+ expect(flow.closed.reset.status).toBe(404);
421
+ });
422
+
423
+ it("/update-user { phoneNumber } is 400 PHONE_NUMBER_CANNOT_BE_UPDATED and writes nothing", () => {
424
+ expect(flow.updateUser.status).toBe(400);
425
+ expect(flow.updateUser.code).toBe("PHONE_NUMBER_CANNOT_BE_UPDATED");
426
+ expect(flow.updateUser.phoneNumber).toBe(NUMBER);
427
+ });
428
+
429
+ it("no captured log line carries the number or the code", () => {
430
+ expect(flow.logNamesNumber).toBe(false);
431
+ expect(flow.logNamesCode).toBe(false);
432
+ });
433
+ }
434
+
435
+ if (process.env[FLOW_FLAG] === "1") {
436
+ runFlow().then(
437
+ (out) => process.stdout.write(JSON.stringify(out)),
438
+ (err: unknown) => {
439
+ process.stderr.write(`${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
440
+ process.exit(1);
441
+ },
442
+ );
443
+ } else {
444
+ defineSuite();
445
+ }