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,21 +0,0 @@
1
- /**
2
- * The spoke's hub-client module (#7894 D7) — sign-in through the hub, with no
3
- * database. It imports no spoke removal seed and no `(auth)` file, so a spoke
4
- * keeps it (create-ailk's closure guard proves that, spec 7894 D9).
5
- */
6
-
7
- export {
8
- HUB_SESSION_CALLBACK_PATH,
9
- type HubSessionConfig,
10
- hubSessionConfig,
11
- } from "./config";
12
- export {
13
- type HubSessionPayload,
14
- type HubSessionUser,
15
- hubNextPath,
16
- hubSessionBuyer,
17
- hubSessionInit,
18
- readHubSession,
19
- } from "./session";
20
- export { resealHubSession } from "./reseal";
21
- export { SpokeSignIn, type SpokeSignInProps } from "./spoke-sign-in";
@@ -1,148 +0,0 @@
1
- "use client"; // "use client" — loads Google's Identity Services script and handles its credential callback in the browser.
2
-
3
- /**
4
- * OneTap — Google One Tap on a spoke's signed-out account page (#11096 D10).
5
- *
6
- * Rendered by `SpokeSignIn` only when the spoke sets `AILK_HUB_ONE_TAP=on`
7
- * and its hub reports a One Tap client id. On mount it asks this site's
8
- * `POST /api/hub-session/one-tap/nonce` for a nonce, loads
9
- * `https://accounts.google.com/gsi/client`, and calls
10
- * `google.accounts.id.initialize({ client_id, nonce, callback,
11
- * use_fedcm_for_prompt: true })` then `prompt()`. Google's callback hands the
12
- * ID token to `POST /api/hub-session/one-tap`; only on `{ ok: true }` — the
13
- * session cookie is set by then — does the page move, to `next`, on this
14
- * site. Any other answer leaves the form as it is. Nothing here logs the
15
- * token or the nonce.
16
- */
17
-
18
- import { type ReactElement, useEffect } from "react";
19
-
20
- const GSI_SRC = "https://accounts.google.com/gsi/client";
21
-
22
- interface GoogleIdentity {
23
- accounts?: {
24
- id?: {
25
- initialize(options: {
26
- client_id: string;
27
- nonce: string;
28
- callback: (response: { credential?: string }) => void;
29
- use_fedcm_for_prompt: boolean;
30
- }): void;
31
- prompt(): void;
32
- };
33
- };
34
- }
35
-
36
- /** The one navigation the island makes — a test seam. */
37
- export const oneTapNavigation = {
38
- assign(url: string): void {
39
- window.location.assign(url);
40
- },
41
- };
42
-
43
- function googleIdentity(): GoogleIdentity | undefined {
44
- return (window as unknown as { google?: GoogleIdentity }).google;
45
- }
46
-
47
- /** How long the island waits for Google's script before it gives up. */
48
- const GSI_TIMEOUT_MS = 10_000;
49
-
50
- /**
51
- * Google's script, loaded once per page. Always settles: it rejects when the
52
- * script fails, loads without `google.accounts.id`, or has not loaded within
53
- * 10 s (a tag already on the page may have loaded before this listened). A
54
- * rejection leaves the form as it is.
55
- */
56
- export function loadGoogle(): Promise<void> {
57
- if (googleIdentity()?.accounts?.id) return Promise.resolve();
58
- return new Promise((resolve, reject) => {
59
- const fail = (): void => reject(new Error("gsi"));
60
- const timer = setTimeout(fail, GSI_TIMEOUT_MS);
61
- const existing = document.querySelector<HTMLScriptElement>(`script[src="${GSI_SRC}"]`);
62
- const script = existing ?? document.createElement("script");
63
- script.addEventListener(
64
- "load",
65
- () => {
66
- clearTimeout(timer);
67
- if (googleIdentity()?.accounts?.id) resolve();
68
- else fail();
69
- },
70
- { once: true },
71
- );
72
- script.addEventListener(
73
- "error",
74
- () => {
75
- clearTimeout(timer);
76
- fail();
77
- },
78
- { once: true },
79
- );
80
- if (existing === null) {
81
- script.src = GSI_SRC;
82
- script.async = true;
83
- document.head.appendChild(script);
84
- }
85
- });
86
- }
87
-
88
- async function postJson(url: string, body: unknown): Promise<unknown> {
89
- const res = await fetch(url, {
90
- method: "POST",
91
- credentials: "same-origin",
92
- headers: { "content-type": "application/json" },
93
- body: JSON.stringify(body),
94
- });
95
- if (!res.ok) return null;
96
- return res.json().catch(() => null);
97
- }
98
-
99
- export interface OneTapProps {
100
- /** The hub's Google client id, from the hub's client info. */
101
- clientId: string;
102
- /** Where to land once signed in — a path on this site, already sanitized. */
103
- next: string;
104
- }
105
-
106
- export function OneTap({ clientId, next }: OneTapProps): ReactElement {
107
- useEffect(() => {
108
- let cancelled = false;
109
- const onCredential = async (response: { credential?: string }): Promise<void> => {
110
- if (typeof response.credential !== "string") return;
111
- const answer = await postJson("/api/hub-session/one-tap", {
112
- credential: response.credential,
113
- }).catch(() => null);
114
- if (
115
- typeof answer === "object" &&
116
- answer !== null &&
117
- (answer as { ok?: unknown }).ok === true
118
- ) {
119
- oneTapNavigation.assign(next);
120
- }
121
- };
122
- const start = async (): Promise<void> => {
123
- const minted = await postJson("/api/hub-session/one-tap/nonce", {});
124
- const nonce =
125
- typeof minted === "object" && minted !== null
126
- ? (minted as { nonce?: unknown }).nonce
127
- : undefined;
128
- if (typeof nonce !== "string") return;
129
- await loadGoogle();
130
- const id = googleIdentity()?.accounts?.id;
131
- if (cancelled || !id) return;
132
- id.initialize({
133
- client_id: clientId,
134
- nonce,
135
- callback: (response) => void onCredential(response),
136
- use_fedcm_for_prompt: true,
137
- });
138
- id.prompt();
139
- };
140
- start().catch(() => undefined);
141
- return () => {
142
- cancelled = true;
143
- };
144
- }, [clientId, next]);
145
-
146
- // Google draws its own prompt; this marker only names the island.
147
- return <div hidden data-testid="spoke-sign-in-one-tap" data-client-id={clientId} />;
148
- }
@@ -1,90 +0,0 @@
1
- /**
2
- * The spoke's session re-seal (#8232, spec
3
- * docs/specs/8232-member-settings-account-general-and-spec.md D11; roadmap
4
- * D9).
5
- *
6
- * After a member saves their name through the hub (`PATCH /v1/member/profile`),
7
- * the sealed session cookie still names the person as they were at sign-in.
8
- * `resealHubSession()` re-reads the person from the hub's own record,
9
- * `GET /v1/hub-sign-in/me`, with the session's credential, and writes the
10
- * cookie again so the next render shows the new name:
11
- *
12
- * - no hub-session configuration (a single site) or no session cookie ⇒
13
- * `"skipped"`, with no call;
14
- * - `/me` refusing, throwing, or answering a person of the wrong shape ⇒
15
- * `"failed"`, and the cookie is left as it is (sign-out is the sign-out
16
- * route's job — a transient hub error never signs the member out);
17
- * - otherwise only `user` changes. `v`, `accessToken` and `expiresAt` are
18
- * kept exactly and `Max-Age` is the remaining lifetime, so a re-seal
19
- * never extends a session (SEC-8232-1). The cookie's name, key and
20
- * attributes are the ones the callback route writes at sign-in
21
- * (`cookieHeader`: `HttpOnly`, `SameSite=Lax`, `Path=/`, `Secure` on an
22
- * https site — SEC-8232-2).
23
- *
24
- * It tests no topology: a single site has no configuration and no cookie.
25
- * Nothing here logs a credential, a cookie value, a name or an email.
26
- */
27
-
28
- import { hubSignIn } from "@working-theory/api-client";
29
- import { cookies, headers } from "next/headers";
30
-
31
- import { hubSessionConfig } from "./config";
32
- import { seal } from "./seal";
33
- import { type HubSessionUser, readHubSessionPayload, sessionCookieName } from "./session";
34
-
35
- /**
36
- * The person `/me` names, when every field is the type the session holds.
37
- * It repeats `session.ts`'s private shape check on purpose: `sync-routes`
38
- * brings this file to a scaffold whose own `session.ts` it never updates,
39
- * so it cannot rely on a new export there.
40
- */
41
- function sessionUser(value: unknown): HubSessionUser | null {
42
- if (typeof value !== "object" || value === null) return null;
43
- const user = value as Record<string, unknown>;
44
- const { name, email, emailVerified, createdAt } = user;
45
- if (
46
- typeof email !== "string" ||
47
- typeof emailVerified !== "boolean" ||
48
- typeof createdAt !== "string" ||
49
- (name !== null && typeof name !== "string")
50
- ) {
51
- return null;
52
- }
53
- return { name, email, emailVerified, createdAt };
54
- }
55
-
56
- /** Re-seals the hub session cookie from the hub's `/me`. Never throws. */
57
- export async function resealHubSession(): Promise<"resealed" | "skipped" | "failed"> {
58
- const config = hubSessionConfig();
59
- if (config === null) return "skipped";
60
- const payload = readHubSessionPayload(await headers());
61
- if (payload === null) return "skipped";
62
- const maxAge = Math.floor((payload.expiresAt - Date.now()) / 1000);
63
- if (maxAge <= 0) return "skipped";
64
-
65
- let user: HubSessionUser | null;
66
- try {
67
- const res = await hubSignIn.me({
68
- headers: { authorization: `Bearer ${payload.accessToken}` },
69
- });
70
- user = res.ok ? sessionUser(res.body.user) : null;
71
- } catch {
72
- user = null;
73
- }
74
- if (user === null) return "failed";
75
-
76
- const name = sessionCookieName(config);
77
- try {
78
- (await cookies()).set(name, seal({ ...payload, user }, config.sessionSecret, "session", name), {
79
- httpOnly: true,
80
- sameSite: "lax",
81
- path: "/",
82
- maxAge,
83
- secure: config.secure,
84
- });
85
- } catch {
86
- // Outside a Server Action or route handler Next refuses a cookie write.
87
- return "failed";
88
- }
89
- return "resealed";
90
- }
@@ -1,86 +0,0 @@
1
- /**
2
- * Sealed values for the hub sign-in (#7894 D7, #8146 D3).
3
- *
4
- * AES-256-GCM with a fresh 12-byte IV per seal. The key is HKDF-SHA256 of the
5
- * caller's secret with one info string per purpose, so the three purposes
6
- * never share a key, and the caller-supplied name is the additional
7
- * authenticated data, so a value sealed for one name never opens as another.
8
- * Two secrets feed this module: `AILK_HUB_SESSION_SECRET` for the spoke's
9
- * `session` and `flow` cookies, and `BETTER_AUTH_SECRET` for the hub's
10
- * `continue` ref (`app/api/auth/hub/continuation.ts`, hub and standalone
11
- * sites only; the entry is unused on a spoke). The key never derives from the
12
- * client secret: a leaked client secret forges no spoke session.
13
- *
14
- * Wire form: base64url(iv ‖ tag ‖ ciphertext). Anything that does not open —
15
- * a wrong key, a wrong name, a truncated or altered value — reads as `null`,
16
- * never a throw. Node `crypto` only; no dependency.
17
- */
18
-
19
- import {
20
- createCipheriv,
21
- createDecipheriv,
22
- hkdfSync,
23
- randomBytes,
24
- } from "node:crypto";
25
-
26
- /** The things this module seals, each under its own derived key. */
27
- export type SealPurpose = "session" | "flow" | "continue";
28
-
29
- const INFO: Record<SealPurpose, string> = {
30
- session: "ailk-hub-session/v1",
31
- flow: "ailk-hub-flow/v1",
32
- continue: "ailk-hub-continue/v1",
33
- };
34
-
35
- const IV_BYTES = 12;
36
- const TAG_BYTES = 16;
37
-
38
- function deriveKey(secret: string, purpose: SealPurpose): Buffer {
39
- return Buffer.from(
40
- hkdfSync("sha256", secret, Buffer.alloc(0), INFO[purpose], 32),
41
- );
42
- }
43
-
44
- /** `value` as JSON, sealed for the cookie `name`. */
45
- export function seal(
46
- value: unknown,
47
- secret: string,
48
- purpose: SealPurpose,
49
- name: string,
50
- ): string {
51
- const iv = randomBytes(IV_BYTES);
52
- const cipher = createCipheriv("aes-256-gcm", deriveKey(secret, purpose), iv);
53
- cipher.setAAD(Buffer.from(name, "utf8"));
54
- const body = Buffer.concat([
55
- cipher.update(JSON.stringify(value), "utf8"),
56
- cipher.final(),
57
- ]);
58
- return Buffer.concat([iv, cipher.getAuthTag(), body]).toString("base64url");
59
- }
60
-
61
- /** The JSON value `sealed` holds for the cookie `name`, or `null` when it does not open. */
62
- export function unseal(
63
- sealed: string,
64
- secret: string,
65
- purpose: SealPurpose,
66
- name: string,
67
- ): unknown {
68
- try {
69
- const raw = Buffer.from(sealed, "base64url");
70
- if (raw.length <= IV_BYTES + TAG_BYTES) return null;
71
- const decipher = createDecipheriv(
72
- "aes-256-gcm",
73
- deriveKey(secret, purpose),
74
- raw.subarray(0, IV_BYTES),
75
- );
76
- decipher.setAAD(Buffer.from(name, "utf8"));
77
- decipher.setAuthTag(raw.subarray(IV_BYTES, IV_BYTES + TAG_BYTES));
78
- const text = Buffer.concat([
79
- decipher.update(raw.subarray(IV_BYTES + TAG_BYTES)),
80
- decipher.final(),
81
- ]).toString("utf8");
82
- return JSON.parse(text) as unknown;
83
- } catch {
84
- return null;
85
- }
86
- }
@@ -1,298 +0,0 @@
1
- /**
2
- * The spoke's hub session (#7894 D7, D12, D13) — read, forwarded, never stored.
3
- *
4
- * A spoke that signs in through its hub has no database: after the callback
5
- * route exchanges a code, the hub-issued credential and the person it names
6
- * live in ONE sealed, `HttpOnly` cookie. This module is everything that reads
7
- * it:
8
- *
9
- * - `readHubSession(headers)` — the web seam's `readSession` on a hub-mode
10
- * spoke: unseals the cookie from the `Cookie` header, no network. Expired,
11
- * unreadable or sealed under another key ⇒ `null`.
12
- * - `hubSessionInit()` — what `forwardedCookieInit()` returns on such a
13
- * spoke: the credential as `Authorization: Bearer`, the ONE request-init
14
- * re-target the account area reads the hub through (D12). The api-client
15
- * adds the spoke key itself; the hub admits the credential only beside it.
16
- * - `hubSessionBuyer(request)` — a customer the hub vouches for at buy time
17
- * (D13): read live from `GET /v1/hub-sign-in/me`, never from the cookie.
18
- *
19
- * And the two writers every route that starts or finishes a sign-in shares
20
- * (#11096 D2, D6): `startHubFlow` seals a new flow, and `sessionCookieFor`
21
- * seals a credential the hub answered into the session cookie.
22
- *
23
- * Nothing here logs a credential, a cookie value or an email.
24
- */
25
-
26
- import { createHash, randomBytes } from "node:crypto";
27
-
28
- import { type HubSignInTokenResponse, hubSignIn } from "@working-theory/api-client";
29
- import { headers as requestHeaders } from "next/headers";
30
-
31
- import { resolveNextPath } from "../next-path";
32
-
33
- import { type HubSessionConfig, hubSessionConfig } from "./config";
34
- import { seal, unseal } from "./seal";
35
-
36
- /** The session cookie: `__Host-` on an https site, plain on a loopback one. */
37
- export function sessionCookieName(config: Pick<HubSessionConfig, "secure">): string {
38
- return config.secure ? "__Host-ailk-hub-session" : "ailk-hub-session";
39
- }
40
-
41
- /** The flow cookie that carries state, verifier and `next` across the hub hop. */
42
- export function flowCookieName(config: Pick<HubSessionConfig, "secure">): string {
43
- return config.secure ? "__Host-ailk-hub-flow" : "ailk-hub-flow";
44
- }
45
-
46
- /** One Tap's nonce cookie (#11096 D10), named as the other two are. */
47
- export function oneTapCookieName(config: Pick<HubSessionConfig, "secure">): string {
48
- return config.secure ? "__Host-ailk-hub-one-tap" : "ailk-hub-one-tap";
49
- }
50
-
51
- /** How long a One Tap nonce lives — Google's prompt and the person's tap. */
52
- export const ONE_TAP_NONCE_TTL_SECONDS = 300;
53
-
54
- /** The person a hub session names — the fields the account area reads. */
55
- export interface HubSessionUser {
56
- name: string | null;
57
- email: string;
58
- emailVerified: boolean;
59
- createdAt: string;
60
- }
61
-
62
- /** What the session cookie holds (sealed). */
63
- export interface HubSessionPayload {
64
- v: 1;
65
- accessToken: string;
66
- /** Epoch milliseconds; the cookie's own `Max-Age` ends at the same time. */
67
- expiresAt: number;
68
- user: HubSessionUser;
69
- }
70
-
71
- /** The value of cookie `name` in a `Cookie` header, or `undefined`. */
72
- export function readCookie(header: string | null, name: string): string | undefined {
73
- if (header === null) return undefined;
74
- for (const part of header.split(";")) {
75
- const at = part.indexOf("=");
76
- if (at === -1) continue;
77
- if (part.slice(0, at).trim() === name) return part.slice(at + 1).trim();
78
- }
79
- return undefined;
80
- }
81
-
82
- /**
83
- * A `Set-Cookie` value for one of this module's cookies — always `HttpOnly`,
84
- * `SameSite=Lax` (the hub's top-level redirect back must carry the flow
85
- * cookie) and `Path=/`; `Secure` on an https site. `maxAge` 0 clears it.
86
- */
87
- export function cookieHeader(
88
- name: string,
89
- value: string,
90
- maxAge: number,
91
- config: Pick<HubSessionConfig, "secure">,
92
- ): string {
93
- return [
94
- `${name}=${value}`,
95
- "Path=/",
96
- "HttpOnly",
97
- "SameSite=Lax",
98
- `Max-Age=${Math.max(0, Math.floor(maxAge))}`,
99
- ...(config.secure ? ["Secure"] : []),
100
- ].join("; ");
101
- }
102
-
103
- function isPayload(value: unknown): value is HubSessionPayload {
104
- if (typeof value !== "object" || value === null) return false;
105
- const v = value as Record<string, unknown>;
106
- const user = v["user"] as Record<string, unknown> | null | undefined;
107
- return (
108
- v["v"] === 1 &&
109
- typeof v["accessToken"] === "string" &&
110
- typeof v["expiresAt"] === "number" &&
111
- typeof user === "object" &&
112
- user !== null &&
113
- typeof user["email"] === "string" &&
114
- typeof user["emailVerified"] === "boolean" &&
115
- (user["name"] === null || typeof user["name"] === "string") &&
116
- typeof user["createdAt"] === "string"
117
- );
118
- }
119
-
120
- /** The sealed session in `headers`, or `null` — not configured, absent, expired or unreadable. */
121
- export function readHubSessionPayload(headers: Headers): HubSessionPayload | null {
122
- const config = hubSessionConfig();
123
- if (config === null) return null;
124
- const name = sessionCookieName(config);
125
- const sealed = readCookie(headers.get("cookie"), name);
126
- if (sealed === undefined || sealed === "") return null;
127
- const value = unseal(sealed, config.sessionSecret, "session", name);
128
- if (!isPayload(value) || value.expiresAt <= Date.now()) return null;
129
- return value;
130
- }
131
-
132
- /** The web seam's `readSession` on a hub-mode spoke: the person, or `null`. */
133
- export function readHubSession(
134
- headers: Headers,
135
- ): Promise<{ user: HubSessionUser } | null> {
136
- const payload = readHubSessionPayload(headers);
137
- return Promise.resolve(payload === null ? null : { user: payload.user });
138
- }
139
-
140
- /**
141
- * `forwardedCookieInit()` on a hub-mode spoke (D12): the credential as a
142
- * Bearer header signed in, no header at all signed out. Never the visitor's
143
- * cookie — the hub has no session for it.
144
- */
145
- export async function hubSessionInit(): Promise<{ headers: Record<string, string> }> {
146
- const payload = readHubSessionPayload(await requestHeaders());
147
- return payload === null
148
- ? { headers: {} }
149
- : { headers: { authorization: `Bearer ${payload.accessToken}` } };
150
- }
151
-
152
- /**
153
- * The customer the hub vouches for, for a spoke's buy route (D13): read live
154
- * from `GET /v1/hub-sign-in/me` with the person's credential (the api-client
155
- * adds the spoke key). `null` with no session, when the hub refuses the
156
- * credential (a revoked one reads as signed out here), when it names no
157
- * customer, or on any failure — a buyer is never taken from the cookie.
158
- */
159
- export async function hubSessionBuyer(
160
- request: Request,
161
- ): Promise<{ customerId: string } | null> {
162
- const payload = readHubSessionPayload(request.headers);
163
- if (payload === null) return null;
164
- try {
165
- const res = await hubSignIn.me({
166
- headers: { authorization: `Bearer ${payload.accessToken}` },
167
- });
168
- if (!res.ok) return null;
169
- const customerId = res.body.billingCustomerId;
170
- return typeof customerId === "string" && customerId !== ""
171
- ? { customerId }
172
- : null;
173
- } catch {
174
- return null;
175
- }
176
- }
177
-
178
- /** Where to land after signing in, when `next` is missing or refused. */
179
- export const HUB_SESSION_FALLBACK_PATH = "/account";
180
-
181
- /**
182
- * Where a sign-in this site cannot complete lands (#11095 D4): the site's
183
- * home. Never `/account`, whose signed-out gate redirects straight back into
184
- * the sign-in — a loop.
185
- */
186
- export const HUB_SESSION_HOME_PATH = "/";
187
-
188
- /**
189
- * The post-sign-in path for `raw`: `resolveNextPath`'s same-origin rule,
190
- * printable ASCII only (it becomes a `Location` header), and never a path
191
- * that resolves under `/api` — dot segments included — so a sign-in lands on
192
- * a page and never re-enters a route handler.
193
- */
194
- export function hubNextPath(raw: unknown): string {
195
- const next = resolveNextPath(raw, HUB_SESSION_FALLBACK_PATH);
196
- if (!/^[\x21-\x7e]+$/.test(next)) return HUB_SESSION_FALLBACK_PATH;
197
- const path = new URL(next, "http://site.invalid").pathname;
198
- return path === "/api" || path.startsWith("/api/")
199
- ? HUB_SESSION_FALLBACK_PATH
200
- : next;
201
- }
202
-
203
- /** How long a sign-in may take on the hub before the flow cookie expires. */
204
- export const FLOW_TTL_SECONDS = 600;
205
-
206
- /** The longest session the spoke keeps — the hub's own credential lifetime (spec 7894 D5). */
207
- const MAX_SESSION_SECONDS = 86_400;
208
-
209
- /** A sign-in flow just started: what the hub is sent, and the cookie that remembers it. */
210
- export interface HubFlow {
211
- /** The opaque `state` the hub echoes back. */
212
- state: string;
213
- /** The S256 challenge of the sealed verifier. */
214
- challenge: string;
215
- /** The `Set-Cookie` value of the sealed flow cookie (ten minutes). */
216
- cookie: string;
217
- }
218
-
219
- /**
220
- * Start a sign-in through the hub (#7894 D2; shared by every route that
221
- * starts one, #11096 D2): a `state` and a PKCE verifier (32 random bytes
222
- * each, base64url) sealed with the sanitized `next` into the flow cookie.
223
- * Nothing here logs the state, the verifier or the challenge.
224
- */
225
- export function startHubFlow(config: HubSessionConfig, next: unknown): HubFlow {
226
- const state = randomBytes(32).toString("base64url");
227
- const verifier = randomBytes(32).toString("base64url");
228
- const challenge = createHash("sha256").update(verifier).digest("base64url");
229
- const name = flowCookieName(config);
230
- const flow = seal(
231
- {
232
- v: 1,
233
- state,
234
- verifier,
235
- next: hubNextPath(next),
236
- expiresAt: Date.now() + FLOW_TTL_SECONDS * 1000,
237
- },
238
- config.sessionSecret,
239
- "flow",
240
- name,
241
- );
242
- return { state, challenge, cookie: cookieHeader(name, flow, FLOW_TTL_SECONDS, config) };
243
- }
244
-
245
- /**
246
- * The session cookie for a credential the hub answered (#11096 D6) — the
247
- * callback's code exchange and One Tap's both mint one. `null` when
248
- * `expiresIn` is not a whole number of seconds from 1 to a day: a malformed
249
- * answer from the hub must never yield a session that does not expire.
250
- */
251
- export function sessionCookieFor(
252
- config: HubSessionConfig,
253
- token: Pick<HubSignInTokenResponse, "accessToken" | "expiresIn" | "user">,
254
- ): string | null {
255
- const { accessToken, expiresIn, user } = token;
256
- if (!Number.isInteger(expiresIn) || expiresIn < 1 || expiresIn > MAX_SESSION_SECONDS) {
257
- return null;
258
- }
259
- const payload: HubSessionPayload = {
260
- v: 1,
261
- accessToken,
262
- expiresAt: Date.now() + expiresIn * 1000,
263
- user: {
264
- name: user.name,
265
- email: user.email,
266
- emailVerified: user.emailVerified,
267
- createdAt: user.createdAt,
268
- },
269
- };
270
- const name = sessionCookieName(config);
271
- return cookieHeader(name, seal(payload, config.sessionSecret, "session", name), expiresIn, config);
272
- }
273
-
274
- /**
275
- * Whether `request` comes from a page on `siteOrigin`: a `Sec-Fetch-Site`
276
- * other than `same-origin`, an `Origin` other than the site's, or a request
277
- * carrying neither is not. The check every state-changing POST of this
278
- * module's routes makes before anything else.
279
- */
280
- export function isSameOrigin(request: Request, siteOrigin: string | null): boolean {
281
- const fetchSite = request.headers.get("sec-fetch-site");
282
- const origin = request.headers.get("origin");
283
- if (fetchSite === null && origin === null) return false;
284
- if (fetchSite !== null && fetchSite !== "same-origin") return false;
285
- if (origin !== null && origin !== siteOrigin) return false;
286
- return true;
287
- }
288
-
289
- /** A 303 with no cache and no referrer, carrying each `Set-Cookie` given. */
290
- export function seeOther(location: string, setCookies: readonly string[] = []): Response {
291
- const headers = new Headers({
292
- Location: location,
293
- "Cache-Control": "no-store",
294
- "Referrer-Policy": "no-referrer",
295
- });
296
- for (const value of setCookies) headers.append("Set-Cookie", value);
297
- return new Response(null, { status: 303, headers });
298
- }