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,188 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
-
5
- /**
6
- * Tests for the hub's continue step (#8146, spec
7
- * docs/specs/8146-email-link-sign-in-from-spec.md D4; AC-1(c), AC-3(b)).
8
- *
9
- * `auth.ts` (the Better Auth singleton: `resolveSecret`, the session read) and
10
- * `@working-theory/api-client`'s `hubSignIn` are the external boundaries; both
11
- * are mocked, exactly as the authorize suite does. The route's own decisions
12
- * are under test: where a ref sends the visitor, and what it never does.
13
- */
14
-
15
- // --- Mocks set up BEFORE imports ---
16
-
17
- const mockGetSession = jest.fn();
18
- const mockSecret = "k".repeat(43);
19
- // eslint-disable-next-line no-restricted-syntax -- auth.ts is the Better Auth singleton (its adapter needs a live database); this stand-in for the secret and the session read is the repo-standard double for that boundary (see the authorize suite beside this one).
20
- jest.mock("../../../../../../../auth", () => ({
21
- __esModule: true,
22
- auth: {
23
- api: { getSession: (...args: unknown[]) => mockGetSession(...args) },
24
- },
25
- resolveSecret: () => mockSecret,
26
- }));
27
-
28
- const mockCreateCode = jest.fn();
29
- jest.mock("@working-theory/api-client", () => ({
30
- __esModule: true,
31
- hubSignIn: { createCode: (...args: unknown[]) => mockCreateCode(...args) },
32
- }));
33
-
34
- import { seal } from "../../../../../../../lib/hub-session/seal";
35
- import { GET as authorize } from "../../../authorize/route";
36
- import { mintContinuation } from "../../../continuation";
37
- import { GET } from "../route";
38
-
39
- const HUB = "https://hub.example.com";
40
- const SPOKE_CALLBACK = "https://spoke.example.com/api/hub-session/callback";
41
- const STATE = "s".repeat(43);
42
- const CODE = "k".repeat(43);
43
-
44
- const ORIGINAL_ENV = process.env;
45
-
46
- const QUERY = new URLSearchParams({
47
- response_type: "code",
48
- client_id: "spoke_abc",
49
- redirect_uri: SPOKE_CALLBACK,
50
- state: STATE,
51
- code_challenge: "c".repeat(43),
52
- code_challenge_method: "S256",
53
- }).toString();
54
-
55
- function continueTo(ref: string): Promise<Response> {
56
- return GET(new Request(`${HUB}/api/auth/hub/continue/${ref}`), {
57
- params: Promise.resolve({ ref }),
58
- });
59
- }
60
-
61
- beforeEach(() => {
62
- jest.resetAllMocks();
63
- process.env = { ...ORIGINAL_ENV, BETTER_AUTH_URL: HUB };
64
- });
65
-
66
- afterAll(() => {
67
- process.env = ORIGINAL_ENV;
68
- });
69
-
70
- describe("AC-1(c) — a valid ref returns the visitor to the authorize step", () => {
71
- it("answers 303 to /api/auth/hub/authorize with the same six-key query", async () => {
72
- const res = await continueTo(mintContinuation(QUERY, mockSecret));
73
-
74
- expect(res.status).toBe(303);
75
- expect(res.headers.get("location")).toBe(
76
- `/api/auth/hub/authorize?${QUERY}`,
77
- );
78
- expect(res.headers.get("cache-control")).toBe("no-store");
79
- expect(res.headers.get("referrer-policy")).toBe("no-referrer");
80
- });
81
-
82
- it("chained into the authorize step with a session: 303 to the registered spoke URI with the code and the original state", async () => {
83
- mockGetSession.mockResolvedValue({ user: { id: "u1" } });
84
- mockCreateCode.mockResolvedValue({
85
- ok: true,
86
- body: { code: CODE, redirectUri: SPOKE_CALLBACK },
87
- });
88
-
89
- const step = await continueTo(mintContinuation(QUERY, mockSecret));
90
- const res = await authorize(
91
- new Request(`${HUB}${step.headers.get("location")}`, {
92
- headers: { cookie: "better-auth.session_token=tok" },
93
- }),
94
- );
95
-
96
- expect(res.status).toBe(303);
97
- const target = new URL(res.headers.get("location") ?? "");
98
- expect(`${target.origin}${target.pathname}`).toBe(SPOKE_CALLBACK);
99
- expect(target.searchParams.get("code")).toBe(CODE);
100
- expect(target.searchParams.get("state")).toBe(STATE);
101
- });
102
-
103
- it("reads no session itself: the authorize step decides every code", async () => {
104
- await continueTo(mintContinuation(QUERY, mockSecret));
105
- expect(mockGetSession).not.toHaveBeenCalled();
106
- expect(mockCreateCode).not.toHaveBeenCalled();
107
- });
108
- });
109
-
110
- describe("AC-3(b) — any other ref answers 303 /account", () => {
111
- const good = mintContinuation(QUERY, mockSecret);
112
- const T = Date.now();
113
-
114
- it.each([
115
- [
116
- "the first character flipped",
117
- (good[0] === "A" ? "B" : "A") + good.slice(1),
118
- ],
119
- [
120
- "sealed under another secret",
121
- mintContinuation(QUERY, "x".repeat(43)),
122
- ],
123
- [
124
- 'a valid payload sealed with purpose "flow" and the SAME name',
125
- seal(
126
- { v: 1, q: QUERY, exp: T + 600_000 },
127
- mockSecret,
128
- "flow",
129
- "hub-continue",
130
- ),
131
- ],
132
- ["exp in the past", mintContinuation(QUERY, mockSecret, T - 601_000)],
133
- ["4097 characters", "A".repeat(4097)],
134
- ["a character outside base64url", `${good}%2Fevil`],
135
- [
136
- "plain base64url JSON, unsealed",
137
- Buffer.from(
138
- JSON.stringify({ v: 1, q: QUERY, exp: T + 600_000 }),
139
- ).toString("base64url"),
140
- ],
141
- ["an empty-looking ref", "-"],
142
- ])("%s", async (_name, ref) => {
143
- const res = await continueTo(ref);
144
-
145
- expect(res.status).toBe(303);
146
- expect(res.headers.get("location")).toBe("/account");
147
- expect(res.headers.get("cache-control")).toBe("no-store");
148
- });
149
-
150
- it("a ref sealed under the test secret whose q holds CR/LF answers 303 without throwing, with no CR or LF in Location", async () => {
151
- const ref = seal(
152
- { v: 1, q: "a=1\r\nX-Injected: 1", exp: T + 600_000 },
153
- mockSecret,
154
- "continue",
155
- "hub-continue",
156
- );
157
-
158
- const res = await continueTo(ref);
159
-
160
- expect(res.status).toBe(303);
161
- expect(res.headers.get("location")).not.toMatch(/[\r\n]/);
162
- expect(res.headers.get("x-injected")).toBeNull();
163
- });
164
-
165
- it("every Location is /account or starts with /api/auth/hub/authorize? — never `//` or a scheme", async () => {
166
- const refs = [
167
- good,
168
- "garbage",
169
- mintContinuation("redirect_uri=https://evil.example/x", mockSecret),
170
- mintContinuation("//evil.example/x", mockSecret),
171
- seal(
172
- { v: 1, q: "https://evil.example/x", exp: T + 600_000 },
173
- mockSecret,
174
- "continue",
175
- "hub-continue",
176
- ),
177
- ];
178
- for (const ref of refs) {
179
- const location = (await continueTo(ref)).headers.get("location") ?? "";
180
- expect(
181
- location === "/account" ||
182
- location.startsWith("/api/auth/hub/authorize?"),
183
- ).toBe(true);
184
- expect(location.startsWith("//")).toBe(false);
185
- expect(location).not.toMatch(/^[a-z][a-z0-9+.-]*:/i);
186
- }
187
- });
188
- });
@@ -1,53 +0,0 @@
1
- /**
2
- * The hub's sign-in continuation (#8146, spec
3
- * docs/specs/8146-email-link-sign-in-from-spec.md D4).
4
- *
5
- * GET /api/auth/hub/continue/<ref>
6
- *
7
- * The authorize step, for a signed-out visitor, seals the validated authorize
8
- * query into `<ref>` and sends the visitor to sign in with THIS path as the
9
- * destination (Better Auth decodes a callback twice, so the path must hold
10
- * nothing a decode can change). After sign-in — by the emailed link or by
11
- * Google — the visitor lands here, and this route sends them back to the
12
- * authorize step with the original query.
13
- *
14
- * - a valid, unexpired ref: 303 to `/api/auth/hub/authorize?<the query>`;
15
- * - any other ref (forged, expired, replayed past its life, unreadable): 303
16
- * to the hub's own `/account`. By then the spoke's flow cookie (600 s) has
17
- * expired too, so returning to the spoke could not finish.
18
- *
19
- * Both targets are fixed relative paths: this route redirects nowhere else,
20
- * and never to a URL carried in the ref. It reads no session — the authorize
21
- * step does that and mints the code, so every decision about a code stays in
22
- * one place. It logs nothing.
23
- */
24
- import { resolveSecret } from "../../../../../../auth";
25
- import { openContinuation } from "../../continuation";
26
-
27
- /** Where an unreadable ref goes: the destination the hub's own sign-in uses. */
28
- const FALLBACK_PATH = "/account";
29
-
30
- const AUTHORIZE_PATH = "/api/auth/hub/authorize";
31
-
32
- /** A 303 to a fixed same-origin path. */
33
- function see(location: string): Response {
34
- return new Response(null, {
35
- status: 303,
36
- headers: {
37
- Location: location,
38
- "Cache-Control": "no-store",
39
- // The authorize query rides this URL; no page may leak it through a Referer.
40
- "Referrer-Policy": "no-referrer",
41
- },
42
- });
43
- }
44
-
45
- // platform-decisions-waiver: api-versioning — sign-in redirect step, not a versioned API contract (spec 8146 §7)
46
- export async function GET(
47
- _request: Request,
48
- { params }: { params: Promise<{ ref: string }> },
49
- ): Promise<Response> {
50
- const { ref } = await params;
51
- const query = openContinuation(ref, resolveSecret());
52
- return see(query === null ? FALLBACK_PATH : `${AUTHORIZE_PATH}?${query}`);
53
- }
@@ -1,111 +0,0 @@
1
- /**
2
- * `POST /api/auth/hub/email` — the hub web's half of a spoke-hosted email
3
- * sign-in (#11096 D2, spec docs/specs/11096-the-spoke-hosts-the-sign-spec.md).
4
- *
5
- * A spoke's server (never a browser) posts the email a person typed on the
6
- * spoke's own `/account`, with the six authorize keys of the flow it just
7
- * started and, only when a box was ticked, the agreement ids. In order:
8
- *
9
- * 1. `BETTER_AUTH_URL` pins the origin, else 503. Body ≤ 4 KB of JSON.
10
- * 2. `hubEmailEntryBodySchema` (`.strict()`): anything else — `password`
11
- * among it — is 400 `invalid_request` (D5).
12
- * 3. A caller refused ten times in ten minutes is 429 before any API
13
- * call (`refusedCallerLimit`); a missing or non-`Basic` header is a
14
- * refusal. The hub API's `POST /v1/hub-sign-in/entry` authenticates
15
- * the spoke with the `Authorization` and `x-ailk-spoke-key` it sent, as received,
16
- * and checks the redirect URI is registered for it. A non-200 is passed
17
- * on as its status with `{ error }`, and nothing is sent.
18
- * 4. The six keys are sealed into a continuation ref.
19
- * 5. Better Auth's `signInMagicLink` sends the hub's own link, its callback
20
- * the continue path. Its headers carry only the pinned `Origin`: the
21
- * spoke's two headers never reach Better Auth (SEC-11096-12). The
22
- * agreements plugin's before-hook runs for this server call as for
23
- * HTTP, so a sign-up request without full agreements is
24
- * `400 agreements_required` before any lookup, and `400 sign_up_closed`
25
- * on a closed site.
26
- * 6. 202 `{ sent: true }` for a known and an unknown address alike.
27
- *
28
- * The link's use then runs verify (302), continue, authorize and the spoke's
29
- * callback (303s) — a redirect at every hop, never a hub page. Nothing here
30
- * logs an email, a header or a ref. Under `app/api/auth`, a spoke removal
31
- * seed, so no spoke carries it.
32
- */
33
- import { hubSignIn } from "@working-theory/api-client";
34
- import { hubEmailEntryBodySchema } from "@working-theory/validation";
35
-
36
- import { auth, resolveSecret } from "../../../../../auth";
37
- import { CONTINUE_PATH, pinnedOrigin, sealQuery } from "../continuation";
38
- import {
39
- apiErrorCode,
40
- betterAuthCode,
41
- forwardedClientAuth,
42
- json,
43
- noteRefusedCaller,
44
- parseJson,
45
- readRawBody,
46
- refusedCallerLimit,
47
- refuse,
48
- } from "../entry-shared";
49
-
50
- // platform-decisions-waiver: api-versioning — a hub sign-in step, not a versioned API contract (spec 11096 § 6)
51
- export async function POST(request: Request): Promise<Response> {
52
- const origin = pinnedOrigin();
53
- if (origin === null) return refuse(503, "temporarily_unavailable");
54
-
55
- const raw = await readRawBody(request);
56
- if (raw === null) return refuse(400, "invalid_request");
57
- const parsed = hubEmailEntryBodySchema.safeParse(parseJson(raw));
58
- if (!parsed.success) return refuse(400, "invalid_request");
59
- const body = parsed.data;
60
-
61
- const limited = refusedCallerLimit(request);
62
- if (limited !== null) return limited;
63
- const client = forwardedClientAuth(request);
64
- if (client === null) {
65
- noteRefusedCaller(request);
66
- return refuse(401, "invalid_client");
67
- }
68
-
69
- try {
70
- const checked = await hubSignIn.entry(client, {
71
- clientId: body.client_id,
72
- redirectUri: body.redirect_uri,
73
- email: body.email,
74
- });
75
- if (!checked.ok) {
76
- if (checked.status === 401 || checked.status === 403) {
77
- noteRefusedCaller(request);
78
- }
79
- return refuse(
80
- checked.status,
81
- apiErrorCode(checked.body, "invalid_request"),
82
- );
83
- }
84
- } catch {
85
- return refuse(503, "temporarily_unavailable");
86
- }
87
-
88
- const ref = sealQuery({ response_type: "code", ...body }, resolveSecret());
89
- if (ref === null) return refuse(400, "invalid_request");
90
-
91
- try {
92
- await auth.api.signInMagicLink({
93
- body: {
94
- email: body.email,
95
- callbackURL: `${CONTINUE_PATH}/${ref}`,
96
- ...(body.agreements
97
- ? { metadata: { agreements: body.agreements, locale: body.locale } }
98
- : {}),
99
- },
100
- headers: new Headers({ origin }),
101
- });
102
- } catch (err) {
103
- const code = betterAuthCode(err);
104
- if (code === "AGREEMENTS_REQUIRED")
105
- return refuse(400, "agreements_required");
106
- if (code === "SIGN_UP_CLOSED") return refuse(400, "sign_up_closed");
107
- return refuse(503, "temporarily_unavailable");
108
- }
109
-
110
- return json(202, { sent: true });
111
- }
@@ -1,163 +0,0 @@
1
- /**
2
- * What the hub web's spoke-facing entry routes share (#11096 D2, D9): the
3
- * JSON answer, a bounded JSON body read, the spoke's forwarded client
4
- * authentication, the refused-caller limit, and the mapping of a Better Auth
5
- * refusal onto the wire.
6
- *
7
- * Nothing here logs. The forwarded `Authorization` and spoke key go only to
8
- * the hub API's entry check — never to Better Auth, a log line or an error
9
- * report (SEC-11096-12).
10
- */
11
- import type { HubForwardedClientAuth } from "@working-theory/api-client";
12
-
13
- import {
14
- clientIpFromHeaders,
15
- UNKNOWN_VISITOR_FACTOR,
16
- } from "../../../../src/lib/rate-limit";
17
-
18
- /** A purchase claim's life: three days to open the account (#11096 D9). */
19
- export const PURCHASE_CLAIM_TTL_SECONDS = 72 * 3600;
20
-
21
- /** The name a purchase claim is sealed under — never `hub-continue`. */
22
- export const PURCHASE_CLAIM_NAME = "hub-purchase";
23
-
24
- /** The largest body an entry route reads. */
25
- export const ENTRY_BODY_MAX_BYTES = 4096;
26
-
27
- export function json(
28
- status: number,
29
- body: Record<string, unknown>,
30
- headers: Record<string, string> = {},
31
- ): Response {
32
- return new Response(JSON.stringify(body), {
33
- status,
34
- headers: {
35
- "Content-Type": "application/json",
36
- "Cache-Control": "no-store",
37
- ...headers,
38
- },
39
- });
40
- }
41
-
42
- export const refuse = (status: number, error: string): Response =>
43
- json(status, { error });
44
-
45
- /** The raw body as text, or `null` past 4 KB or on a read failure. */
46
- export async function readRawBody(request: Request): Promise<string | null> {
47
- const declared = Number(request.headers.get("content-length") ?? "0");
48
- if (Number.isFinite(declared) && declared > ENTRY_BODY_MAX_BYTES) return null;
49
- try {
50
- const text = await request.text();
51
- return Buffer.byteLength(text, "utf8") > ENTRY_BODY_MAX_BYTES ? null : text;
52
- } catch {
53
- return null;
54
- }
55
- }
56
-
57
- /** The parsed JSON value of `raw`, or `undefined` when it does not parse. */
58
- export function parseJson(raw: string): unknown {
59
- try {
60
- return JSON.parse(raw) as unknown;
61
- } catch {
62
- return undefined;
63
- }
64
- }
65
-
66
- /** `Basic <base64>`: the only `Authorization` shape a spoke sends. */
67
- const BASIC_AUTHORIZATION = /^Basic [A-Za-z0-9+/]{4,684}={0,2}$/;
68
-
69
- /**
70
- * The spoke's `Authorization` and `x-ailk-spoke-key`, as received, or `null`
71
- * when either is missing or the `Authorization` is not `Basic <base64>`: the
72
- * hub API decides whether they are good.
73
- */
74
- export function forwardedClientAuth(
75
- request: Request,
76
- ): HubForwardedClientAuth | null {
77
- const authorization = request.headers.get("authorization");
78
- const spokeKey = request.headers.get("x-ailk-spoke-key");
79
- if (!authorization || !spokeKey) return null;
80
- if (!BASIC_AUTHORIZATION.test(authorization) || spokeKey.length > 256) {
81
- return null;
82
- }
83
- return { authorization, spokeKey };
84
- }
85
-
86
- // ── The refused-caller limit (SEC review of #11096) ─────────────────────────
87
- //
88
- // These routes are public, and every call that reaches the hub API arrives
89
- // from this app's own egress address, which the API's per-IP limiter counts
90
- // as one caller. So a caller sending credentials the API refuses could spend
91
- // that budget for every spoke. The caller here is a spoke's SERVER, not a
92
- // person, so a plain request cap would also cap a busy spoke's real sign-ins;
93
- // what is limited instead is REFUSALS: a caller whose credentials were
94
- // missing, malformed or refused by the API (401/403) ten times in ten minutes
95
- // is answered 429 before any API call until the window ends. A spoke whose
96
- // credentials are good never accrues one. The address is the per-visitor
97
- // limiter's (`clientIpFromHeaders`); an unreadable one shares one bucket
98
- // `UNKNOWN_VISITOR_FACTOR` times as wide. Per instance and best-effort, like
99
- // that limiter.
100
-
101
- const REFUSALS_PER_WINDOW = 10;
102
- const REFUSAL_WINDOW_MS = 10 * 60_000;
103
- const MAX_TRACKED_CALLERS = 5000;
104
-
105
- const refusals = new Map<string, { count: number; resetAt: number }>();
106
-
107
- /** Test seam: forget every caller's refusals. */
108
- export function __resetRefusedCallers(): void {
109
- refusals.clear();
110
- }
111
-
112
- function callerKey(request: Request): { key: string; limit: number } {
113
- const address = clientIpFromHeaders(request.headers);
114
- return address === "unknown"
115
- ? { key: "unknown", limit: UNKNOWN_VISITOR_FACTOR * REFUSALS_PER_WINDOW }
116
- : { key: address, limit: REFUSALS_PER_WINDOW };
117
- }
118
-
119
- /** A 429 when this caller has used up its refusals, else `null`. Counts nothing. */
120
- export function refusedCallerLimit(request: Request): Response | null {
121
- const { key, limit } = callerKey(request);
122
- const now = Date.now();
123
- const entry = refusals.get(key);
124
- if (!entry || entry.resetAt <= now || entry.count < limit) return null;
125
- return json(
126
- 429,
127
- { error: "rate_limited" },
128
- { "Retry-After": String(Math.max(1, Math.ceil((entry.resetAt - now) / 1000))) },
129
- );
130
- }
131
-
132
- /** Count one refusal against this caller. */
133
- export function noteRefusedCaller(request: Request): void {
134
- const { key } = callerKey(request);
135
- const now = Date.now();
136
- const entry = refusals.get(key);
137
- if (entry && entry.resetAt > now) {
138
- entry.count += 1;
139
- return;
140
- }
141
- if (refusals.size >= MAX_TRACKED_CALLERS) {
142
- for (const [k, v] of refusals) if (v.resetAt <= now) refusals.delete(k);
143
- const oldest = refusals.keys().next().value;
144
- if (refusals.size >= MAX_TRACKED_CALLERS && oldest !== undefined) {
145
- refusals.delete(oldest);
146
- }
147
- }
148
- refusals.set(key, { count: 1, resetAt: now + REFUSAL_WINDOW_MS });
149
- }
150
-
151
- /** The `error.code` of a refused api-client call, or `fallback`. */
152
- export function apiErrorCode(body: unknown, fallback: string): string {
153
- const code = (body as { error?: { code?: unknown } } | null)?.error?.code;
154
- return typeof code === "string" && /^[a-z_]{1,64}$/.test(code)
155
- ? code
156
- : fallback;
157
- }
158
-
159
- /** The `code` a Better Auth `APIError` carries, or `null`. */
160
- export function betterAuthCode(err: unknown): string | null {
161
- const code = (err as { body?: { code?: unknown } } | null)?.body?.code;
162
- return typeof code === "string" ? code : null;
163
- }
@@ -1,86 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
-
5
- /**
6
- * The sealed return a spoke's password link carries (#11162 AC-2): it opens
7
- * only to the registered origin plus the Security path it was minted from,
8
- * under its own name, within its life.
9
- */
10
- import { mintContinuation } from "../../continuation";
11
- import {
12
- SECURITY_RETURN_NAME,
13
- SECURITY_RETURN_TTL_SECONDS,
14
- SPOKE_RETURN_PATH,
15
- mintSecurityReturn,
16
- openSecurityReturn,
17
- } from "../return";
18
-
19
- const SECRET = "k".repeat(43);
20
- const SPOKE = "https://spoke.example";
21
-
22
- /** Where a ref for `origin` + `path` lands: the spoke's return route, the tab as `next`. */
23
- function landing(origin: string, path: string): string {
24
- return `${origin}${SPOKE_RETURN_PATH}?next=${encodeURIComponent(path)}`;
25
- }
26
-
27
- describe("mintSecurityReturn / openSecurityReturn", () => {
28
- it("round-trips the origin and the Security path as the spoke's return route with the tab as next", () => {
29
- const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET);
30
- expect(ref).toMatch(/^[A-Za-z0-9_-]+$/);
31
- expect(openSecurityReturn(ref, SECRET)).toBe(landing(SPOKE, "/account/security"));
32
- expect(SPOKE_RETURN_PATH).toBe("/api/hub-session/password/return");
33
- expect(openSecurityReturn(mintSecurityReturn(SPOKE, "/fr/account/security", SECRET), SECRET)).toBe(
34
- landing(SPOKE, "/fr/account/security"),
35
- );
36
- });
37
-
38
- it("opens a loopback http origin, for a local spoke", () => {
39
- const ref = mintSecurityReturn("http://127.0.0.1:3100", "/account/security", SECRET);
40
- expect(openSecurityReturn(ref, SECRET)).toBe(landing("http://127.0.0.1:3100", "/account/security"));
41
- });
42
-
43
- it("outlives the hour-long link, and no more than ten minutes past it", () => {
44
- const now = Date.now();
45
- const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET, now);
46
- expect(SECURITY_RETURN_TTL_SECONDS).toBe(3600 + 600);
47
- expect(openSecurityReturn(ref, SECRET, now + 3600_000)).toBe(landing(SPOKE, "/account/security"));
48
- expect(openSecurityReturn(ref, SECRET, now + SECURITY_RETURN_TTL_SECONDS * 1000)).toBeNull();
49
- });
50
-
51
- it("never opens under another secret, nor a continuation or a purchase claim sealed under their names", () => {
52
- const ref = mintSecurityReturn(SPOKE, "/account/security", SECRET);
53
- expect(openSecurityReturn(ref, "x".repeat(43))).toBeNull();
54
- const query = new URLSearchParams({ o: SPOKE, p: "/account/security" }).toString();
55
- expect(openSecurityReturn(mintContinuation(query, SECRET), SECRET)).toBeNull();
56
- expect(openSecurityReturn(mintContinuation(query, SECRET, Date.now(), "hub-purchase"), SECRET)).toBeNull();
57
- expect(SECURITY_RETURN_NAME).not.toBe("hub-continue");
58
- });
59
-
60
- it.each([
61
- ["an http origin off loopback", { o: "http://spoke.example", p: "/account/security" }],
62
- ["an origin with a path", { o: `${SPOKE}/x`, p: "/account/security" }],
63
- ["an origin that is not a URL", { o: "spoke.example", p: "/account/security" }],
64
- ["a javascript: scheme", { o: "javascript:alert(1)", p: "/account/security" }],
65
- ["a path off the Security tab", { o: SPOKE, p: "/account" }],
66
- ["a path with a query", { o: SPOKE, p: "/account/security?x=1" }],
67
- ["a third key", { o: SPOKE, p: "/account/security", q: "1" }],
68
- ["a missing path", { o: SPOKE }],
69
- ] as Array<[string, Record<string, string>]>)("refuses a forged payload holding %s", (_label, payload) => {
70
- const forged = mintContinuation(
71
- new URLSearchParams(payload).toString(),
72
- SECRET,
73
- Date.now(),
74
- SECURITY_RETURN_NAME,
75
- SECURITY_RETURN_TTL_SECONDS,
76
- );
77
- expect(openSecurityReturn(forged, SECRET)).toBeNull();
78
- });
79
-
80
- it.each([["", ""], ["not base64url", "a.b/c"], ["too long", "a".repeat(5000)]])(
81
- "refuses %s as a ref",
82
- (_label, ref) => {
83
- expect(openSecurityReturn(ref, SECRET)).toBeNull();
84
- },
85
- );
86
- });