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
@@ -0,0 +1,140 @@
1
+ /**
2
+ * @file auth-sms.test.ts — the phone plugin's outbound text (#11106 D9).
3
+ *
4
+ * - one serialization: the exact string signed is the string sent, and its
5
+ * `ts` is the signed timestamp;
6
+ * - the signature is the relay's domain-separated base string, never the
7
+ * email relay's;
8
+ * - the validator takes E.164 on `AILK_SMS_COUNTRY_CODES` only (default `1`);
9
+ * - nothing throws, and no log line carries the number or the code.
10
+ */
11
+ import { createHmac } from "node:crypto";
12
+
13
+ import {
14
+ SMS_SIGNATURE_DOMAIN,
15
+ buildAuthSmsRequest,
16
+ isAllowedPhoneNumber,
17
+ makeSendPhoneOtp,
18
+ smsCountryCodes,
19
+ type AuthSmsLog,
20
+ } from "../auth-sms";
21
+
22
+ const SECRET = "test-webhook-secret";
23
+ const NUMBER = "+15555550123";
24
+ const CODE = "482913";
25
+ const ORIGINAL_ENV = { ...process.env };
26
+
27
+ afterEach(() => {
28
+ process.env = { ...ORIGINAL_ENV };
29
+ });
30
+
31
+ function recorder(): { log: AuthSmsLog; lines: string[] } {
32
+ const lines: string[] = [];
33
+ return {
34
+ lines,
35
+ log: {
36
+ warn: (fields) => lines.push(JSON.stringify(fields)),
37
+ info: (fields) => lines.push(JSON.stringify(fields)),
38
+ },
39
+ };
40
+ }
41
+
42
+ describe("buildAuthSmsRequest", () => {
43
+ it("signs the exact bytes it returns, with the relay's own domain", () => {
44
+ const { rawBody, headers } = buildAuthSmsRequest(
45
+ { kind: "phone-verification", userId: "user_1", to: NUMBER, code: CODE },
46
+ SECRET,
47
+ 1_700_000_000,
48
+ );
49
+ expect(JSON.parse(rawBody)).toEqual({
50
+ kind: "phone-verification",
51
+ userId: "user_1",
52
+ to: NUMBER,
53
+ code: CODE,
54
+ ts: 1_700_000_000,
55
+ });
56
+ expect(headers["x-ailk-auth-sms-timestamp"]).toBe("1700000000");
57
+ const expected = `sha256=${createHmac("sha256", SECRET)
58
+ .update(`${SMS_SIGNATURE_DOMAIN}1700000000.${rawBody}`, "utf8")
59
+ .digest("hex")}`;
60
+ expect(headers["x-ailk-auth-sms-signature"]).toBe(expected);
61
+ const emailShaped = `sha256=${createHmac("sha256", SECRET)
62
+ .update(`1700000000.${rawBody}`, "utf8")
63
+ .digest("hex")}`;
64
+ expect(headers["x-ailk-auth-sms-signature"]).not.toBe(emailShaped);
65
+ });
66
+ });
67
+
68
+ describe("isAllowedPhoneNumber (SEC-11106-2)", () => {
69
+ it("takes E.164 on the default list (1) only", () => {
70
+ delete process.env.AILK_SMS_COUNTRY_CODES;
71
+ expect(smsCountryCodes()).toEqual(["1"]);
72
+ expect(isAllowedPhoneNumber(NUMBER)).toBe(true);
73
+ expect(isAllowedPhoneNumber("+447700900123")).toBe(false);
74
+ expect(isAllowedPhoneNumber("15555550123")).toBe(false);
75
+ expect(isAllowedPhoneNumber("+1 555 555 0123")).toBe(false);
76
+ expect(isAllowedPhoneNumber("+0123456789")).toBe(false);
77
+ });
78
+
79
+ it("reads AILK_SMS_COUNTRY_CODES as a comma list", () => {
80
+ process.env.AILK_SMS_COUNTRY_CODES = "1, 44";
81
+ expect(isAllowedPhoneNumber("+447700900123")).toBe(true);
82
+ expect(isAllowedPhoneNumber("+33612345678")).toBe(false);
83
+ });
84
+ });
85
+
86
+ describe("makeSendPhoneOtp", () => {
87
+ it("posts one signed body for the session's user, and logs neither the number nor the code", async () => {
88
+ process.env.AUTH_EMAIL_WEBHOOK_SECRET = SECRET;
89
+ const { log, lines } = recorder();
90
+ const send = jest.fn().mockResolvedValue({ status: 202 });
91
+ const sendOtp = makeSendPhoneOtp({ send, log, sessionUserId: async () => "user_1" });
92
+ await sendOtp({ phoneNumber: NUMBER, code: CODE });
93
+ expect(send).toHaveBeenCalledTimes(1);
94
+ const [rawBody] = send.mock.calls[0] as [string, Record<string, string>];
95
+ expect(JSON.parse(rawBody)).toMatchObject({ userId: "user_1", to: NUMBER, code: CODE });
96
+ expect(lines).toHaveLength(1);
97
+ expect(JSON.parse(lines[0]!)).toEqual({ kind: "phone-verification", userId: "user_1", reason: "sent" });
98
+ });
99
+
100
+ it.each([
101
+ ["the relay refuses", { status: 429 }, "send_failed"],
102
+ ["the relay is unreachable", { status: 0 }, "send_failed"],
103
+ ])("never throws when %s, and logs the status only", async (_label, answer, reason) => {
104
+ process.env.AUTH_EMAIL_WEBHOOK_SECRET = SECRET;
105
+ const { log, lines } = recorder();
106
+ const sendOtp = makeSendPhoneOtp({
107
+ send: jest.fn().mockResolvedValue(answer),
108
+ log,
109
+ sessionUserId: async () => "user_1",
110
+ });
111
+ await expect(sendOtp({ phoneNumber: NUMBER, code: CODE })).resolves.toBeUndefined();
112
+ expect(JSON.parse(lines[0]!)).toMatchObject({ reason, status: answer.status });
113
+ for (const line of lines) {
114
+ expect(line).not.toContain(NUMBER.slice(1));
115
+ expect(line).not.toContain(CODE);
116
+ }
117
+ });
118
+
119
+ it("sends nothing without the secret or without a session", async () => {
120
+ const send = jest.fn();
121
+ const { log, lines } = recorder();
122
+ delete process.env.AUTH_EMAIL_WEBHOOK_SECRET;
123
+ await makeSendPhoneOtp({ send, log, sessionUserId: async () => "user_1" })({ phoneNumber: NUMBER, code: CODE });
124
+ process.env.AUTH_EMAIL_WEBHOOK_SECRET = SECRET;
125
+ await makeSendPhoneOtp({ send, log, sessionUserId: async () => null })({ phoneNumber: NUMBER, code: CODE });
126
+ await makeSendPhoneOtp({
127
+ send,
128
+ log,
129
+ sessionUserId: async () => {
130
+ throw new Error("boom");
131
+ },
132
+ })({ phoneNumber: NUMBER, code: CODE });
133
+ expect(send).not.toHaveBeenCalled();
134
+ expect(lines.map((l) => (JSON.parse(l) as { reason: string }).reason)).toEqual([
135
+ "not_configured",
136
+ "no_session",
137
+ "no_session",
138
+ ]);
139
+ });
140
+ });
@@ -0,0 +1,18 @@
1
+ {
2
+ "//": "Resolution for the auth-phone child process only (#11141): `lib/__tests__/auth-phone.test.ts` runs itself under `node --import tsx` with TSX_TSCONFIG_PATH pointing here, so in this monorepo `@working-theory/api-client` and `@working-theory/validation` resolve to their source rather than an unbuilt dist/. It sits beside the test, not under `__tests__/auth/fixtures/`, because `apps/web/__tests__` never reaches a scaffold; there the mapped paths do not exist and tsx falls back to the installed packages.",
3
+ "compilerOptions": {
4
+ "target": "ES2022",
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "strict": true,
8
+ "baseUrl": ".",
9
+ "paths": {
10
+ "@working-theory/api-client": [
11
+ "../../../../../packages/api-client/src/index.ts"
12
+ ],
13
+ "@working-theory/validation": [
14
+ "../../../../../packages/validation/src/index.ts"
15
+ ]
16
+ }
17
+ }
18
+ }
@@ -149,3 +149,16 @@ describe("signedOutHeaderActions (#10046 AC-3)", () => {
149
149
  expect(mod.HEADER_CTA_LABEL_KEY).toBe("headerCta");
150
150
  });
151
151
  });
152
+
153
+ describe("signedInHeaderActions (#11095 AC-5)", () => {
154
+ it("is one outline-strong Your account link to /account", () => {
155
+ expect(mod.signedInHeaderActions()).toEqual([
156
+ { labelKey: "yourAccount", path: "/account", variant: "outline-strong" },
157
+ ]);
158
+ expect(mod.ACCOUNT_LABEL_KEY).toBe("yourAccount");
159
+ });
160
+
161
+ it("answers a fresh list each call", () => {
162
+ expect(mod.signedInHeaderActions()).not.toBe(mod.signedInHeaderActions());
163
+ });
164
+ });
@@ -3,7 +3,7 @@
3
3
  // server-side, is redacted before a URL reaches Sentry. The query-param scrub
4
4
  // has its own suite, `__tests__/telemetry-scrub.test.ts`.
5
5
 
6
- import { scrubTelemetryUrl } from "../telemetry-scrub";
6
+ import { scrubTelemetryQuery, scrubTelemetryUrl } from "../telemetry-scrub";
7
7
 
8
8
  const GRANT = "dgrant_01920000-0000-7000-8000-000000000001";
9
9
 
@@ -102,3 +102,21 @@ describe("scrubTelemetryUrl — the email-verification nonce (#10820 D2)", () =>
102
102
  expect(scrubbed).toBe("https://site.example/flows/growth-check/verify");
103
103
  });
104
104
  });
105
+
106
+ describe("scrubTelemetryUrl — the purchase link's claim (#11096 D9, SEC-11096-4)", () => {
107
+ it("strips claim=<sealed> from a spoke's /account link", () => {
108
+ const claim = "C".repeat(120);
109
+ const scrubbed = scrubTelemetryUrl(`https://spoke.example/account?claim=${claim}`);
110
+ expect(scrubbed).not.toContain(claim);
111
+ expect(scrubbed).toBe("https://spoke.example/account");
112
+ });
113
+ });
114
+
115
+ describe("scrubTelemetryUrl — the phone step's number and code (#11106 D9)", () => {
116
+ it("strips phoneNumber and code from a URL and a query", () => {
117
+ expect(
118
+ scrubTelemetryUrl("https://site.example/api/auth/phone-number/verify?phoneNumber=%2B15555550123&code=482913&x=1"),
119
+ ).toBe("https://site.example/api/auth/phone-number/verify?x=1");
120
+ expect(scrubTelemetryQuery("?phoneNumber=%2B15555550123&code=482913")).toBe("");
121
+ });
122
+ });
@@ -107,6 +107,8 @@ import type {
107
107
  AccountUser,
108
108
  } from "@working-theory/templates/account";
109
109
  import { localeHref } from "@working-theory/ui";
110
+ import { MessageBubble } from "@working-theory/ui/blocks";
111
+ import { Text } from "@working-theory/ui/primitives";
110
112
  import type {
111
113
  MemberAppointment,
112
114
  MemberMessage,
@@ -115,7 +117,7 @@ import type {
115
117
  MemberResult,
116
118
  } from "@working-theory/validation";
117
119
  import { formatMoney, formatNumber } from "@working-theory/web-i18n";
118
- import { cache } from "react";
120
+ import { cache, createElement } from "react";
119
121
 
120
122
  import { unwrapApiResult } from "./server-api";
121
123
 
@@ -350,20 +352,33 @@ const message: AccountInboxKind<MemberMessage> = {
350
352
  ]
351
353
  : []),
352
354
  ];
355
+ // #11007 — the detail renders through `InboxItemFrame`'s chat layout
356
+ // (`accountChatKinds`): the message is a start-side bubble, captioned
357
+ // with when it was sent; an attached file is the bubble's note. The
358
+ // member feed carries no sender yet, so every message sits on the start
359
+ // side (spec admin-frames-and-list-rails, Clarifications).
360
+ const caption = `${t("messages.sentAt")} · ${formatWhen(data.createdAt, locale)}`;
361
+ const note = data.file ? `${t("messages.file")} · ${data.file.filename}` : undefined;
353
362
  return {
354
- lead: data.body,
355
363
  ...(actions.length > 0 ? { actions } : {}),
356
- fields: {
357
- heading: t("messages.heading"),
358
- items: [
359
- { label: t("messages.sentAt"), value: formatWhen(data.createdAt, locale) },
360
- ...(data.file ? [{ label: t("messages.file"), value: data.file.filename }] : []),
361
- ],
362
- },
364
+ body: createElement(MessageBubble, {
365
+ side: "start",
366
+ caption,
367
+ note,
368
+ "data-testid": "account-item-message",
369
+ children: createElement(Text, { as: "p", className: "whitespace-pre-wrap" }, data.body),
370
+ }),
363
371
  };
364
372
  },
365
373
  };
366
374
 
375
+ /**
376
+ * #11007 — the kinds whose detail is a conversation, rendered through
377
+ * `InboxItemFrame`'s `layout="chat"`; every other kind keeps the stacked
378
+ * head and fields.
379
+ */
380
+ export const accountChatKinds: ReadonlySet<string> = new Set([message.kind]);
381
+
367
382
  /** Each appointment status's message key — a new status is a type error, never a raw key. */
368
383
  const APPOINTMENT_STATUS_KEY = {
369
384
  pending: "appointments.statuses.pending",
@@ -33,6 +33,7 @@
33
33
  * change it reports.
34
34
  */
35
35
 
36
+ import { AsyncLocalStorage } from "node:async_hooks";
36
37
  import { createHmac } from "node:crypto";
37
38
 
38
39
  import { authEmail } from "@working-theory/api-client";
@@ -46,15 +47,17 @@ import {
46
47
  } from "./sign-up-agreements";
47
48
 
48
49
  /**
49
- * The five fixed kinds the relay will send. A caller picks no copy: a sign-up
50
+ * The six fixed kinds the relay will send. A caller picks no copy: a sign-up
50
51
  * link sends agreement ids and a locale, which the API names itself (#9720).
52
+ * `account-open` is a paid buyer's "Open your account" link (#11096 D9).
51
53
  */
52
54
  export type AuthEmailKind =
53
55
  | "password-reset"
54
56
  | "email-verification"
55
57
  | "password-changed"
56
58
  | "magic-link"
57
- | "magic-link-sign-up";
59
+ | "magic-link-sign-up"
60
+ | "account-open";
58
61
 
59
62
  export interface AuthEmailPayload {
60
63
  kind: AuthEmailKind;
@@ -164,7 +167,7 @@ interface DispatchDeps {
164
167
  async function dispatch(
165
168
  payload: AuthEmailPayload,
166
169
  { send, log }: { send: AuthEmailTransport; log: AuthEmailLog },
167
- ): Promise<void> {
170
+ ): Promise<boolean> {
168
171
  const secret = process.env.AUTH_EMAIL_WEBHOOK_SECRET;
169
172
  const base = { userId: payload.userId, kind: payload.kind };
170
173
 
@@ -172,7 +175,7 @@ async function dispatch(
172
175
  // Never sign with an empty key: the relay would reject every delivery and
173
176
  // the deployment would have no local signal at all.
174
177
  log.warn({ ...base, reason: "not_configured" });
175
- return;
178
+ return false;
176
179
  }
177
180
 
178
181
  /**
@@ -196,7 +199,7 @@ async function dispatch(
196
199
  } catch {
197
200
  // The KIND only — see this file's PII boundary note.
198
201
  log.warn({ ...base, reason: "send_failed", errorKind: "signing_failed" });
199
- return;
202
+ return false;
200
203
  }
201
204
 
202
205
  try {
@@ -207,12 +210,14 @@ async function dispatch(
207
210
  // The STATUS, never the response body — the relay's own error text is
208
211
  // not guaranteed free of the address it was given.
209
212
  log.warn({ ...base, reason: "send_failed", errorKind: "relay_rejected" });
210
- return;
213
+ return false;
211
214
  }
212
215
  log.info({ ...base, reason: "sent" });
216
+ return true;
213
217
  } catch {
214
218
  // The error's NAME would be safe; its message is not guaranteed to be.
215
219
  log.warn({ ...base, reason: "send_failed", errorKind: "transport_error" });
220
+ return false;
216
221
  }
217
222
  }
218
223
 
@@ -449,6 +454,48 @@ export function makeSendPasswordChangedNotice(deps: DispatchDeps) {
449
454
  };
450
455
  }
451
456
 
457
+ /**
458
+ * The paid buyer's "Open your account" email (#11096 D9): one link to the
459
+ * spoke's `/account?claim=…`. It carries no agreement copy and signs no one
460
+ * in; the relay only logs `userId`, so it is the fixed sentinel `"purchase"`.
461
+ * Never throws.
462
+ */
463
+ export function makeSendAccountOpen(deps: DispatchDeps) {
464
+ const { send } = deps;
465
+ const log = deps.log ?? defaultLog;
466
+ /** Whether the relay accepted the mail. */
467
+ return async function sendAccountOpen(input: {
468
+ to: string;
469
+ url: string;
470
+ }): Promise<boolean> {
471
+ return dispatch(
472
+ {
473
+ kind: "account-open",
474
+ userId: "purchase",
475
+ to: input.to,
476
+ url: input.url,
477
+ },
478
+ { send, log },
479
+ );
480
+ };
481
+ }
482
+
483
+ /** What one purchase spend gets back from `sendMagicLink` (#11096 D9). */
484
+ export interface PurchaseCaptureStore {
485
+ token: string | null;
486
+ }
487
+
488
+ /**
489
+ * The purchase route's capture (#11096 D9). A `sendMagicLink` call inside
490
+ * `purchaseCapture.run(store, …)` binds a sign-up request's agreements as
491
+ * any sign-up request does, then hands the token to `store` instead of
492
+ * mailing it — so the route can return the hub's own verify URL to the spoke
493
+ * that spent the claim. It captures only a new address with a written
494
+ * binding: an existing account, or a failed binding, leaves `token` null.
495
+ * Outside a capture nothing changes.
496
+ */
497
+ export const purchaseCapture = new AsyncLocalStorage<PurchaseCaptureStore>();
498
+
452
499
  /**
453
500
  * Magic-link token lifetime (#7435 § D2). Five minutes — the library default,
454
501
  * and the number `packages/email`'s magic-link template already promises ("This
@@ -554,6 +601,15 @@ function makeSendMagicLink(deps: MagicLinkDeps) {
554
601
  }
555
602
  }
556
603
 
604
+ // #11096 D9 — inside a purchase capture nothing is mailed: the token of
605
+ // a new address's bound sign-up request goes to the capture.
606
+ const capture = purchaseCapture.getStore();
607
+ if (capture) {
608
+ if (!found && binding) capture.token = data.token;
609
+ log.info({ kind: "magic-link", reason: "captured" });
610
+ return;
611
+ }
612
+
557
613
  // A new address has no user yet; the relay only logs `userId`, so a
558
614
  // sign-up link carries the fixed sentinel and the binding's ids, never
559
615
  // the request's (#9720 D6).
@@ -181,3 +181,16 @@ export function resetSendConfigured(): boolean {
181
181
  if (!process.env.BETTER_AUTH_URL) return false;
182
182
  return Boolean(process.env.BETTER_AUTH_SECRET);
183
183
  }
184
+
185
+ /**
186
+ * True when this deployment can verify a person's phone (#11106 D9): the
187
+ * signed relay's secret (`AUTH_EMAIL_WEBHOOK_SECRET`, which the apps/api SMS
188
+ * relay checks too) and `BETTER_AUTH_URL` (the pinned origin every auth
189
+ * callback rides on). `auth.ts` installs the phone plugin only under this
190
+ * predicate and never on a spoke, and the Account page offers the step only
191
+ * when the plugin is installed. Whether apps/api holds a text provider is
192
+ * apps/api's to say: its relay answers 503 without one.
193
+ */
194
+ export function phoneVerificationConfigured(): boolean {
195
+ return Boolean(process.env.AUTH_EMAIL_WEBHOOK_SECRET && process.env.BETTER_AUTH_URL);
196
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The phone plugin's outbound text (#11106, spec
3
+ * docs/specs/11106-the-workforce-foundation-roles-by-spec.md D9).
4
+ *
5
+ * Better Auth's phone plugin generates a verification code and calls
6
+ * `sendOTP`. `apps/web` sends no text itself: like `lib/auth-email.ts`, this
7
+ * file serializes one body, signs it, and POSTs it to `apps/api`'s
8
+ * `/v1/auth/transactional-sms`, which sends one fixed text. The signed bytes
9
+ * and the sent bytes are one string (`buildAuthSmsRequest`).
10
+ *
11
+ * The base string is domain-separated (`transactional-sms.<ts>.<rawBody>`),
12
+ * so a body signed here never verifies at the email relay or the confirm hop,
13
+ * nor the reverse. The secret is the email relay's.
14
+ *
15
+ * The transport is a bare `fetch` to the API origin `@working-theory/api-client`
16
+ * resolves (`getApiBase()`), the `app/openapi.json/route.ts` precedent: the
17
+ * client package carries no SMS namespace, and this unit adds none.
18
+ *
19
+ * PII BOUNDARY: a log line carries `userId`, `kind` and `reason` — never the
20
+ * number and never the code. NOTHING HERE THROWS: a failed send is a log line,
21
+ * and the person asks for another code.
22
+ */
23
+
24
+ import { createHmac } from "node:crypto";
25
+
26
+ import { getApiBase } from "@working-theory/api-client";
27
+
28
+ /** The relay's base-string domain (`packages/api/src/routes/auth/transactional-sms.ts`). */
29
+ export const SMS_SIGNATURE_DOMAIN = "transactional-sms.";
30
+
31
+ /** Bounds the call so a hung apps/api cannot pin an apps/web worker. */
32
+ const SEND_TIMEOUT_MS = 10_000;
33
+
34
+ /** E.164: a plus, a non-zero first digit, eight to fifteen digits in all. */
35
+ export const E164_PATTERN = /^\+[1-9]\d{7,14}$/;
36
+
37
+ /**
38
+ * `AILK_SMS_COUNTRY_CODES`: the calling codes a code may be texted to,
39
+ * comma-separated, default `1`. The relay re-checks the same list.
40
+ */
41
+ export function smsCountryCodes(raw = process.env.AILK_SMS_COUNTRY_CODES): string[] {
42
+ const codes = (raw ?? "")
43
+ .split(",")
44
+ .map((code) => code.trim().replace(/^\+/, ""))
45
+ .filter((code) => /^[1-9]\d{0,2}$/.test(code));
46
+ return codes.length > 0 ? codes : ["1"];
47
+ }
48
+
49
+ /**
50
+ * The plugin's `phoneNumberValidator` (SEC-11106-2): E.164 only, and only a
51
+ * calling code on the list, so a premium-rate destination elsewhere is
52
+ * refused before any code is generated or sent. Calling codes are
53
+ * prefix-free, so a prefix match names one country code.
54
+ */
55
+ export function isAllowedPhoneNumber(phone: string): boolean {
56
+ if (!E164_PATTERN.test(phone)) return false;
57
+ return smsCountryCodes().some((code) => phone.startsWith(`+${code}`));
58
+ }
59
+
60
+ export interface AuthSmsPayload {
61
+ kind: "phone-verification";
62
+ userId: string;
63
+ to: string;
64
+ code: string;
65
+ }
66
+
67
+ export interface AuthSmsRequest {
68
+ rawBody: string;
69
+ headers: Record<string, string>;
70
+ }
71
+
72
+ /** Sign one body; its `ts` is the signed timestamp, so neither moves alone. */
73
+ export function buildAuthSmsRequest(
74
+ payload: AuthSmsPayload,
75
+ secret: string,
76
+ nowSeconds = Math.floor(Date.now() / 1000),
77
+ ): AuthSmsRequest {
78
+ const rawBody = JSON.stringify({
79
+ kind: payload.kind,
80
+ userId: payload.userId,
81
+ to: payload.to,
82
+ code: payload.code,
83
+ ts: nowSeconds,
84
+ });
85
+ const timestamp = String(nowSeconds);
86
+ const signature = `sha256=${createHmac("sha256", secret)
87
+ .update(`${SMS_SIGNATURE_DOMAIN}${timestamp}.${rawBody}`, "utf8")
88
+ .digest("hex")}`;
89
+ return {
90
+ rawBody,
91
+ headers: {
92
+ "x-ailk-auth-sms-signature": signature,
93
+ "x-ailk-auth-sms-timestamp": timestamp,
94
+ },
95
+ };
96
+ }
97
+
98
+ /** The transport seam; resolves the relay's HTTP status, 0 for no answer. */
99
+ export type AuthSmsTransport = (
100
+ rawBody: string,
101
+ headers: Record<string, string>,
102
+ ) => Promise<{ status: number }>;
103
+
104
+ export interface AuthSmsLog {
105
+ warn: (fields: Record<string, unknown>) => void;
106
+ info: (fields: Record<string, unknown>) => void;
107
+ }
108
+
109
+ const defaultLog: AuthSmsLog = {
110
+ warn: (fields) => console.warn(`[auth-sms] ${JSON.stringify(fields)}`),
111
+ info: (fields) => console.info(`[auth-sms] ${JSON.stringify(fields)}`),
112
+ };
113
+
114
+ /** The production transport: one POST of the exact signed bytes. */
115
+ export const authSmsTransport: AuthSmsTransport = async (rawBody, headers) => {
116
+ try {
117
+ const res = await fetch(`${getApiBase()}/v1/auth/transactional-sms`, {
118
+ method: "POST",
119
+ headers: { "Content-Type": "application/json", ...headers },
120
+ body: rawBody,
121
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
122
+ });
123
+ await res.body?.cancel().catch(() => undefined);
124
+ return { status: res.status };
125
+ } catch {
126
+ return { status: 0 };
127
+ }
128
+ };
129
+
130
+ export interface SendPhoneOtpDeps {
131
+ send?: AuthSmsTransport;
132
+ log?: AuthSmsLog;
133
+ /** The signed-in person the code is for — the plugin's verify step binds it. */
134
+ sessionUserId: (ctx: unknown) => Promise<string | null>;
135
+ }
136
+
137
+ /**
138
+ * The plugin's `sendOTP`. The phone before-hook in `auth.ts` has already
139
+ * refused a caller without a verified-email session, so a missing session
140
+ * here is logged and sends nothing.
141
+ */
142
+ export function makeSendPhoneOtp(deps: SendPhoneOtpDeps) {
143
+ const send = deps.send ?? authSmsTransport;
144
+ const log = deps.log ?? defaultLog;
145
+ return async (
146
+ { phoneNumber, code }: { phoneNumber: string; code: string },
147
+ ctx?: unknown,
148
+ ): Promise<void> => {
149
+ const base = { kind: "phone-verification" };
150
+ const secret = process.env.AUTH_EMAIL_WEBHOOK_SECRET;
151
+ if (!secret) {
152
+ log.warn({ ...base, reason: "not_configured" });
153
+ return;
154
+ }
155
+ let userId: string | null;
156
+ try {
157
+ userId = await deps.sessionUserId(ctx);
158
+ } catch {
159
+ userId = null;
160
+ }
161
+ if (userId === null) {
162
+ log.warn({ ...base, reason: "no_session" });
163
+ return;
164
+ }
165
+ let request: AuthSmsRequest;
166
+ try {
167
+ request = buildAuthSmsRequest({ kind: "phone-verification", userId, to: phoneNumber, code }, secret);
168
+ } catch {
169
+ log.warn({ ...base, userId, reason: "send_failed", errorKind: "signing_failed" });
170
+ return;
171
+ }
172
+ const { status } = await send(request.rawBody, request.headers);
173
+ if (status >= 200 && status < 300) {
174
+ log.info({ ...base, userId, reason: "sent" });
175
+ } else {
176
+ // The status only — the relay's body is never read.
177
+ log.warn({ ...base, userId, reason: "send_failed", status });
178
+ }
179
+ };
180
+ }
@@ -158,9 +158,21 @@ describe("hubSessionConfig", () => {
158
158
  siteOrigin: "http://127.0.0.1:3100",
159
159
  redirectUri: "http://127.0.0.1:3100/api/hub-session/callback",
160
160
  secure: false,
161
+ oneTap: false,
161
162
  });
162
163
  });
163
164
 
165
+ // #11096 D10 — One Tap is on only for exactly `on`.
166
+ it.each([
167
+ ["on", true],
168
+ ["ON", false],
169
+ ["1", false],
170
+ ["", false],
171
+ ])("AILK_HUB_ONE_TAP=%p reads oneTap %p", (value, expected) => {
172
+ configure({ AILK_HUB_ONE_TAP: value });
173
+ expect(hubSessionConfig()?.oneTap).toBe(expected);
174
+ });
175
+
164
176
  it("is secure on an https site", () => {
165
177
  configure({ NEXT_PUBLIC_BASE_URL: "https://spoke.example.com/" });
166
178
  expect(hubSessionConfig()).toMatchObject({
@@ -403,3 +415,19 @@ describe("#8232 AC-5 — resealHubSession", () => {
403
415
  await expect(resealHubSession()).resolves.toBe("failed");
404
416
  });
405
417
  });
418
+
419
+ describe("readBodyText (#11096) — the spoke's body read caps BYTES, not characters", () => {
420
+ const post = (body: string): Request =>
421
+ new Request("https://spoke.example/api/hub-session/email", { method: "POST", body });
422
+
423
+ it("reads a body within 8 KB", async () => {
424
+ const { readBodyText } = await import("../entry");
425
+ await expect(readBodyText(post("a".repeat(8_192)))).resolves.toBe("a".repeat(8_192));
426
+ });
427
+
428
+ it("refuses a body under 8 K characters but over 8 KB of UTF-8", async () => {
429
+ const { readBodyText } = await import("../entry");
430
+ // 3 000 three-byte characters: 3 000 characters, 9 000 bytes.
431
+ await expect(readBodyText(post("€".repeat(3_000)))).resolves.toBeNull();
432
+ });
433
+ });