@zero2webmaster/starter-kit 0.51.1 → 0.54.1

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.51.1 | **Framework:** 2.19.0
3
+ **Version:** 0.54.1 | **Framework:** 2.19.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -84,7 +84,8 @@ The Claude Code skill at `~/.claude/skills/instantiate-z2w-project/SKILL.md` and
84
84
 
85
85
  ## Status
86
86
 
87
- - **v0.51.1 (current)** stops outside customers' scaffolds from naming us in four `nextjs` database comments, drops comment lines that only pointed at a private skill, and credits only `@zero2webmaster/starter-kit` in the footer. Its coordination pointer names the bulletin clone's new `AI/Projects` path.
87
+ - **v0.52.0 (current)** can give a `nextjs` project invite-only login (`hasLogin`, through `--input` or the programmatic API). The login email has a button and an 8-digit code; the code can be typed into the app when it is installed on a phone's home screen, where a tapped link would open the wrong browser. The scaffold gets the login pages, Auth.js setup, the user and account tables, a script to invite the first owner, and tests that log in end to end against an in-memory database. Requires `neon-postgres` and a web UI, and turns email on.
88
+ - **v0.51.1** stops outside customers' scaffolds from naming us in four `nextjs` database comments, drops comment lines that only pointed at a private skill, and credits only `@zero2webmaster/starter-kit` in the footer. Its coordination pointer names the bulletin clone's new `AI/Projects` path.
88
89
  - **v0.51.0** gets ready for the portfolio folder `~/Desktop/Zero2Webmaster/AI/Cursor Projects/` to be renamed `~/Desktop/Zero2Webmaster/AI/Projects/`. It looks for the Templates folder at `AI/Projects/agent-framework/` first, then at `AI/Cursor Projects/agent-framework/`, then at the old `AI/Templates/`. The portfolio sweeps and the bulletin lookups follow the rename too, and never count the same folder twice once the old name is a symlink.
89
90
  - **v0.50.0** looks for the Templates folder at `~/Desktop/Zero2Webmaster/AI/Cursor Projects/agent-framework/` first and falls back to the old `~/Desktop/Zero2Webmaster/AI/Templates/`, so the folder can move without breaking project creation. If neither folder is usable, the error names both.
90
91
  - **v0.49.0** gives the Uptime Kuma next-action the project's own keyword (it still said `"status":"ok"`), tells bulletin projects to report each new monitor to `kuma-watchdog` and to notify `audit-engine` when a project is scaffolded, and extends the American English rule to internal labels such as form and database names.
@@ -153,4 +154,4 @@ Inquiries: kerry@zero2webmaster.com.
153
154
  ---
154
155
 
155
156
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
156
- *Version: 0.51.1 | Last Updated: 2026-11-02*
157
+ *Version: 0.54.1 | Last Updated: 2026-11-04*
package/dist/confirm.d.ts CHANGED
@@ -44,6 +44,7 @@ interface Draft {
44
44
  hasObservability: boolean;
45
45
  acceptsCards: boolean;
46
46
  hasPublicSurface: boolean;
47
+ hasLogin: boolean;
47
48
  customBrand: CustomBrandInputs | null;
48
49
  }
49
50
  export declare function renderDraft(draft: Draft): string;
package/dist/confirm.js CHANGED
@@ -30,6 +30,26 @@ export const CONFIRM_CANCEL_KEYWORDS = ["cancel", "abort", "quit", "q"];
30
30
  // their tests keep importing them from confirm unchanged.
31
31
  export { BRANDS, DB_STRATEGIES, PROJECT_TYPES };
32
32
  export const UNSET_PLACEHOLDER = "[unset — please type]";
33
+ /** The highest line number on the confirm screen. */
34
+ const LAST_LINE = 16;
35
+ /**
36
+ * Why line 16 (login) cannot be accepted with the other lines as they are, or
37
+ * null when it can. Mirrors validateLoginInputs in scaffolders/nextjs-auth.
38
+ */
39
+ function loginProblem(draft) {
40
+ if (!draft.hasLogin)
41
+ return null;
42
+ const needs = [];
43
+ if (draft.projectType !== "nextjs")
44
+ needs.push('project type "nextjs" (line 3)');
45
+ if (draft.dbStrategy !== "neon-postgres")
46
+ needs.push('database "neon-postgres" (line 7)');
47
+ if (draft.hasWebUi !== true)
48
+ needs.push("a web UI (line 8)");
49
+ if (needs.length === 0)
50
+ return null;
51
+ return `Login (line 16) needs ${needs.join(", ")}. Change those lines, or set line 16 to no.`;
52
+ }
33
53
  function fmt(value) {
34
54
  if (value === null || value === undefined)
35
55
  return UNSET_PLACEHOLDER;
@@ -54,7 +74,7 @@ export function renderDraft(draft) {
54
74
  const cb = draft.customBrand;
55
75
  lines.push(` 4a. Brand name ................ ${fmtCustom(cb?.brandName)}`, ` 4b. Capitalization rule ....... ${fmtCustom(cb?.brandNameRule)}`, ` 4c. Primary hex color ......... ${fmtCustom(cb?.primaryColor)}`, ` 4d. Accent hex color .......... ${fmtCustom(cb?.accentColor)}`);
56
76
  }
57
- lines.push(` 5. GitHub owner ................... ${fmt(draft.githubOrg)}`, ` 6. Target path .................... ${fmt(draft.targetPath)}`, ` 7. Database strategy .............. ${fmt(draft.dbStrategy)}`, ` 8. Has web UI ..................... ${fmt(draft.hasWebUi)}`, ` 9. Has cron / scheduled jobs ...... ${fmt(draft.hasCron)}`, ` 10. Participate in agent bulletin .. ${fmt(draft.participateInBulletin)}`, ` 11. Sends transactional/auth email . ${fmt(draft.sendsEmail)}`, ` 12. Accepts user-generated content ${fmt(draft.hasUserContent)}`, ` 13. Wire Sentry error tracking ..... ${fmt(draft.hasObservability)}`, ` 14. Will accept credit cards ....... ${fmt(draft.acceptsCards)}`, ` 15. Public surface (search-indexable) ${fmt(draft.hasPublicSurface)}`);
77
+ lines.push(` 5. GitHub owner ................... ${fmt(draft.githubOrg)}`, ` 6. Target path .................... ${fmt(draft.targetPath)}`, ` 7. Database strategy .............. ${fmt(draft.dbStrategy)}`, ` 8. Has web UI ..................... ${fmt(draft.hasWebUi)}`, ` 9. Has cron / scheduled jobs ...... ${fmt(draft.hasCron)}`, ` 10. Participate in agent bulletin .. ${fmt(draft.participateInBulletin)}`, ` 11. Sends transactional/auth email . ${fmt(draft.sendsEmail)}`, ` 12. Accepts user-generated content ${fmt(draft.hasUserContent)}`, ` 13. Wire Sentry error tracking ..... ${fmt(draft.hasObservability)}`, ` 14. Will accept credit cards ....... ${fmt(draft.acceptsCards)}`, ` 15. Public surface (search-indexable) ${fmt(draft.hasPublicSurface)}`, ` 16. Invite-only login (magic link) . ${fmt(draft.hasLogin)}${draft.hasLogin ? " (turns email on)" : ""}`);
58
78
  return lines.join("\n");
59
79
  }
60
80
  export function parseSlug(raw) {
@@ -344,8 +364,16 @@ async function editField(draft, fieldNumber, opts) {
344
364
  draft.hasPublicSurface = result.value;
345
365
  return null;
346
366
  }
367
+ case 16: {
368
+ const raw = await opts.prompter("Invite-only login — magic link plus a typed 8-digit code (yes/no):", draft.hasLogin ? "yes" : "no");
369
+ const result = parseBoolean(raw, "Invite-only login");
370
+ if (!result.ok)
371
+ return result.error;
372
+ draft.hasLogin = result.value;
373
+ return null;
374
+ }
347
375
  default:
348
- return `Field number must be between 1 and 15. Got: ${fieldNumber}.`;
376
+ return `Field number must be between 1 and ${LAST_LINE}. Got: ${fieldNumber}.`;
349
377
  }
350
378
  }
351
379
  /**
@@ -373,21 +401,27 @@ export async function confirmInputs(parsed, opts) {
373
401
  hasObservability: parsed.hasObservability,
374
402
  acceptsCards: parsed.acceptsCards,
375
403
  hasPublicSurface: parsed.hasPublicSurface,
404
+ hasLogin: parsed.hasLogin === true,
376
405
  customBrand: null,
377
406
  };
378
407
  while (true) {
379
408
  output.write(`\nInferred inputs from your brief:\n\n${renderDraft(draft)}\n\n`);
380
409
  const complete = isComplete(draft);
381
410
  const prompt = complete
382
- ? "Press Enter to accept, a line number (1-15) to edit, or 'cancel' to exit (Ctrl+C also works):"
383
- : "Type a line number (1-15) to fill or edit, or 'cancel' to exit (Ctrl+C also works). Every field must be set before accepting.";
411
+ ? `Press Enter to accept, a line number (1-${LAST_LINE}) to edit, or 'cancel' to exit (Ctrl+C also works):`
412
+ : `Type a line number (1-${LAST_LINE}) to fill or edit, or 'cancel' to exit (Ctrl+C also works). Every field must be set before accepting.`;
384
413
  const reply = (await opts.prompter(prompt)).trim();
385
414
  if (CONFIRM_CANCEL_KEYWORDS.includes(reply.toLowerCase())) {
386
415
  throw new ConfirmCancelledError();
387
416
  }
388
417
  if (reply.length === 0) {
389
- if (complete)
390
- break;
418
+ if (complete) {
419
+ const problem = loginProblem(draft);
420
+ if (problem === null)
421
+ break;
422
+ output.write(`\n ✗ ${problem}\n`);
423
+ continue;
424
+ }
391
425
  if (draft.brand === "custom" &&
392
426
  !customBrandComplete(draft.customBrand)) {
393
427
  draft.customBrand = await gatherCustomBrand(opts.prompter, output, draft.customBrand);
@@ -397,8 +431,8 @@ export async function confirmInputs(parsed, opts) {
397
431
  continue;
398
432
  }
399
433
  const fieldNumber = Number(reply);
400
- if (!Number.isInteger(fieldNumber) || fieldNumber < 1 || fieldNumber > 15) {
401
- output.write(`\n ✗ "${reply}" is not a line number (1-15).\n`);
434
+ if (!Number.isInteger(fieldNumber) || fieldNumber < 1 || fieldNumber > LAST_LINE) {
435
+ output.write(`\n ✗ "${reply}" is not a line number (1-${LAST_LINE}).\n`);
402
436
  continue;
403
437
  }
404
438
  const error = await editField(draft, fieldNumber, opts);
@@ -417,12 +451,16 @@ export async function confirmInputs(parsed, opts) {
417
451
  hasWebUi: draft.hasWebUi,
418
452
  hasCron: draft.hasCron,
419
453
  participateInBulletin: draft.participateInBulletin,
420
- sendsEmail: draft.sendsEmail,
454
+ // A login link has to be sent, so login turns email on.
455
+ sendsEmail: draft.hasLogin ? true : draft.sendsEmail,
421
456
  hasUserContent: draft.hasUserContent,
422
457
  hasObservability: draft.hasObservability,
423
458
  acceptsCards: draft.acceptsCards,
424
459
  hasPublicSurface: draft.hasPublicSurface,
425
460
  };
461
+ if (draft.hasLogin) {
462
+ result.hasLogin = true;
463
+ }
426
464
  if (draft.brand === "custom" && draft.customBrand !== null) {
427
465
  result.customBrand = draft.customBrand;
428
466
  }
package/dist/index.d.ts CHANGED
@@ -157,6 +157,19 @@ export interface ScaffoldInputs {
157
157
  * `python-service` is a different language, so those types ignore this flag.
158
158
  */
159
159
  sendsEmail?: boolean;
160
+ /**
161
+ * Invite-only magic-link login (ROADMAP Step 57, Kerry 2026-11-02), ported
162
+ * from `pharmies`: Auth.js v5, JWT sessions, a send gate that never reveals
163
+ * who has an account, and the login code printed in the email as 8 digits so
164
+ * an app installed on a phone's home screen can be logged into by typing it.
165
+ * Emits the login pages, `auth.ts`, `lib/auth/*`, the users/tenants tables in
166
+ * `db/schema.ts`, `scripts/provision-user.ts` and their tests.
167
+ *
168
+ * Optional, defaults to `false`. Requires `projectType: "nextjs"`,
169
+ * `dbStrategy: "neon-postgres"` and `hasWebUi`; the write path refuses
170
+ * anything else. Turns `sendsEmail` on, because a login link must be sent.
171
+ */
172
+ hasLogin?: boolean;
160
173
  /**
161
174
  * Whether this project accepts user-generated content (UGC) — a community
162
175
  * platform, events app with public listings, marketplace, comments/forum,
package/dist/index.js CHANGED
@@ -22,6 +22,7 @@ import * as path from "node:path";
22
22
  import { Writable } from "node:stream";
23
23
  import { isValidSlug } from "./parse-brief.js";
24
24
  import { writeScaffold } from "./writer.js";
25
+ import { validateLoginInputs } from "./scaffolders/nextjs-auth/index.js";
25
26
  /**
26
27
  * This package's version, READ FROM `package.json` at load time rather than
27
28
  * written here by hand.
@@ -161,6 +162,9 @@ export function validateScaffoldInputs(inputs) {
161
162
  if (typeof inputs.targetPath !== "string" || !path.isAbsolute(inputs.targetPath)) {
162
163
  errors.push(`targetPath must be an absolute path. Got: ${JSON.stringify(inputs.targetPath)}.`);
163
164
  }
165
+ const loginProblem = validateLoginInputs(inputs);
166
+ if (loginProblem)
167
+ errors.push(loginProblem);
164
168
  if (inputs.brand === "custom") {
165
169
  const cb = inputs.customBrand;
166
170
  if (!cb || typeof cb !== "object") {
@@ -49,6 +49,14 @@ export interface ParsedBrief {
49
49
  * "public" than it looks. A human confirms on line 15 either way.
50
50
  */
51
51
  hasPublicSurface: boolean;
52
+ /**
53
+ * Whether the project gets the invite-only magic-link login (with the typed
54
+ * 8-digit code). Not nullable; absent signal means `false`. Only ever `true`
55
+ * when the brief also reads as `nextjs` + `neon-postgres` + a web UI, the
56
+ * only combination the login can be emitted into, so the confirm screen is
57
+ * never handed a yes it would have to refuse. A human confirms on line 16.
58
+ */
59
+ hasLogin: boolean;
52
60
  /** Free-text planning sections lifted verbatim from the brief, if any. */
53
61
  briefSections: BriefSections | undefined;
54
62
  raw: string;
@@ -476,6 +476,28 @@ function inferSendsEmail(brief) {
476
476
  const text = brief.toLowerCase();
477
477
  return /\bmagic[\s-]?link\b|\bpasswordless\b|\btransactional email\b|\bauth email\b|\bconfirmation email\b|\bemail (notification|confirmation|receipt|reminder|verification)\b|\bsends?\s+(an?\s+)?emails?\b|\bemails?\s+(the\s+)?(user|customer|applicant|donor|subscriber|author|admin|member|client|team|them)s?\b|\bamazon ses\b|\bresend\b/.test(text);
478
478
  }
479
+ /**
480
+ * Infer whether the project gets the invite-only login. An explicit field wins
481
+ * (`Has login: yes`); otherwise a brief that talks about signing in, magic
482
+ * links or invitations reads as yes. Returns false for any combination the
483
+ * login cannot be emitted into (see {@link ParsedBrief.hasLogin}).
484
+ */
485
+ function inferHasLogin(brief, projectType, dbStrategy, hasWebUi) {
486
+ if (projectType !== "nextjs" || dbStrategy !== "neon-postgres" || hasWebUi !== true) {
487
+ return false;
488
+ }
489
+ const explicit = explicitBoolean(brief, [
490
+ "invite-only login",
491
+ "has login",
492
+ "login",
493
+ "sign-in",
494
+ "sign in",
495
+ ]);
496
+ if (explicit !== null)
497
+ return explicit;
498
+ const text = brief.toLowerCase();
499
+ return /\bmagic[\s-]?link\b|\bpasswordless\b|\binvite[\s-]only\b|\bsign[\s-]?in code\b|\blog(s|ged|ging)?[\s-]?in\b|\bsign(s|ed|ing)?[\s-]in\b|\blogin\b/.test(text);
500
+ }
479
501
  /**
480
502
  * Infer whether the project accepts user-generated content (UGC). Returns
481
503
  * `false` (not null) when there's no signal — the safe default, since the
@@ -756,6 +778,7 @@ export function parseBrief(brief) {
756
778
  hasObservability: false,
757
779
  acceptsCards: false,
758
780
  hasPublicSurface: false,
781
+ hasLogin: false,
759
782
  briefSections: undefined,
760
783
  raw: brief,
761
784
  };
@@ -764,6 +787,8 @@ export function parseBrief(brief) {
764
787
  const projectType = inferProjectType(trimmed);
765
788
  const hasWebUi = inferHasWebUi(trimmed, projectType);
766
789
  const slug = inferSlug(trimmed);
790
+ const dbStrategy = inferDbStrategy(trimmed);
791
+ const hasLogin = inferHasLogin(trimmed, projectType, dbStrategy, hasWebUi);
767
792
  return {
768
793
  slug,
769
794
  description: inferDescription(trimmed),
@@ -771,15 +796,17 @@ export function parseBrief(brief) {
771
796
  brand,
772
797
  githubOrg: inferGithubOrg(trimmed, brand),
773
798
  targetPath: inferTargetPath(trimmed),
774
- dbStrategy: inferDbStrategy(trimmed),
799
+ dbStrategy,
775
800
  hasWebUi,
776
801
  hasCron: inferHasCron(trimmed),
777
802
  participateInBulletin: inferParticipateInBulletin(trimmed, brand),
778
- sendsEmail: inferSendsEmail(trimmed),
803
+ // A login link has to be sent, so login turns email on.
804
+ sendsEmail: hasLogin || inferSendsEmail(trimmed),
779
805
  hasUserContent: inferHasUserContent(trimmed),
780
806
  hasObservability: inferHasObservability(trimmed, projectType, hasWebUi),
781
807
  acceptsCards: inferAcceptsCards(trimmed, slug),
782
808
  hasPublicSurface: inferHasPublicSurface(trimmed, projectType),
809
+ hasLogin,
783
810
  briefSections: extractBriefSections(trimmed),
784
811
  raw: brief,
785
812
  };
@@ -0,0 +1,46 @@
1
+ import type { BrandPresetSpec } from "../../brand.js";
2
+ import type { ScaffoldInputs } from "../../index.js";
3
+ import { type ScaffoldFile, type ScaffolderOptions } from "../common.js";
4
+ /** True when this scaffold gets login. */
5
+ export declare function wantsLogin(inputs: ScaffoldInputs): boolean;
6
+ /**
7
+ * Refuses an input set that asks for login where it cannot work. Returns an
8
+ * error message, or null when the inputs are fine (or login is off).
9
+ */
10
+ export declare function validateLoginInputs(inputs: ScaffoldInputs): string | null;
11
+ /** Every emitted login file, substituted. Excludes the schema and the CSS block, which merge into other files. */
12
+ export declare function loginFiles(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile[];
13
+ /** `db/schema.ts` with the login tables, replacing the placeholder `example` table. */
14
+ export declare function loginSchema(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): string;
15
+ /** Appended to `app/globals.css`: the few classes the login pages use. */
16
+ export declare function loginGlobalsCss(): string;
17
+ export declare const LOGIN_DEPS: Readonly<Record<string, string>>;
18
+ export declare const LOGIN_DEV_DEPS: Readonly<Record<string, string>>;
19
+ export declare const LOGIN_SCRIPTS: Readonly<Record<string, string>>;
20
+ /**
21
+ * scripts/provision-user.ts runs under plain Node, which needs real `.ts`
22
+ * import paths; tsconfig must allow them. `noEmit` is already on, which this
23
+ * option requires.
24
+ */
25
+ export declare function withTsExtensionImports(tsconfig: string): string;
26
+ /**
27
+ * The env block for login. Replaces the generic CANONICAL_HOSTS block, whose
28
+ * prose describes a seam for an app that writes its own auth; this one
29
+ * describes the code that is actually emitted.
30
+ */
31
+ export declare const LOGIN_ENV_BLOCK = "\n# Login (magic link + 8-digit code)\n\nAUTH_SECRET=\nCANONICAL_HOSTS=\n\n# AUTH_SECRET signs the session cookie. Required: Auth.js refuses to run\n# without it. Make one with:\n# openssl rand -base64 33\n# Use a different value in each environment (local, preview, production).\n#\n# CANONICAL_HOSTS is the comma-separated list of hostnames a login link may\n# point at, such as app.example.com,www.example.com (no https://, no path).\n# Unset or empty means NONE, not all. Off production, loopback hosts\n# (localhost, 127.0.0.1) are also allowed, so local login works without it. A\n# preview deployment that must send real login links lists its own host here.\n#\n# Do NOT set AUTH_URL. The app trusts the request's Host and checks it against\n# CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on\n# several domains.\n";
32
+ /**
33
+ * Mounts the Terms/Privacy footer once in the root layout, after the page
34
+ * content, so every page (logged in or not) links both. Login scaffolds only:
35
+ * without login there are no /terms and /privacy pages to link.
36
+ */
37
+ export declare function withSiteFooter(layout: string): string;
38
+ /**
39
+ * vitest runs `next-auth` through Node's own resolver, which refuses its bare
40
+ * `next/server` import (no extension). Inlining it makes vite resolve it, as
41
+ * `next build` does. Without this, test/auth-flow.test.ts fails to LOAD while
42
+ * `tsc` and `next build` both pass.
43
+ */
44
+ export declare function withNextAuthInlined(vitestConfig: string): string;
45
+ /** The login pages explain themselves; the guide test is told so, with reasons. */
46
+ export declare function withLoginGuideExemptions(guideTest: string): string;
@@ -0,0 +1,170 @@
1
+ // Invite-only magic-link login for `nextjs` scaffolds (`hasLogin`, ROADMAP Step 57).
2
+ //
3
+ // Ported from `pharmies`, the reference implementation: Auth.js v5 with an
4
+ // email provider whose token IS an 8-digit code, printed in the email beside
5
+ // the button, so a person using the app from a phone's home screen can type it
6
+ // instead of tapping a link that opens the wrong browser. JWT sessions, a
7
+ // create-refusing adapter with a phantom user, a send gate that never reveals
8
+ // who has an account, a host allowlist, shared limits on live codes and wrong
9
+ // guesses, and audit rows for login and logout.
10
+ //
11
+ // The emitted files live as real source under ./templates/ and are embedded by
12
+ // scripts/embed-login-templates.mjs into ./templates.generated.ts. Edit the
13
+ // templates, never the generated file.
14
+ //
15
+ // Preconditions (checked by validateLoginInputs, called from scaffold()):
16
+ // `nextjs`, `dbStrategy: "neon-postgres"`, and `hasWebUi`. Login also turns
17
+ // email on, because a login link has to be sent.
18
+ import { sub } from "../common.js";
19
+ import { LOGIN_TEMPLATES } from "./templates.generated.js";
20
+ /** Template keys that are not emitted as files of their own. */
21
+ const SCHEMA_KEY = "db/schema.ts";
22
+ const CSS_KEY = "snippets/globals-login.css";
23
+ function template(key) {
24
+ const body = LOGIN_TEMPLATES[key];
25
+ if (body === undefined)
26
+ throw new Error(`login template missing: ${key}`);
27
+ return body;
28
+ }
29
+ /** True when this scaffold gets login. */
30
+ export function wantsLogin(inputs) {
31
+ return inputs.hasLogin === true;
32
+ }
33
+ /**
34
+ * Refuses an input set that asks for login where it cannot work. Returns an
35
+ * error message, or null when the inputs are fine (or login is off).
36
+ */
37
+ export function validateLoginInputs(inputs) {
38
+ if (!wantsLogin(inputs))
39
+ return null;
40
+ const problems = [];
41
+ if (inputs.projectType !== "nextjs")
42
+ problems.push(`the project type is "${inputs.projectType}", and login is built for "nextjs" only`);
43
+ if (inputs.dbStrategy !== "neon-postgres")
44
+ problems.push(`the database is "${inputs.dbStrategy}", and login stores its users in "neon-postgres"`);
45
+ if (inputs.hasWebUi !== true)
46
+ problems.push("the project has no web UI, and login is a set of pages");
47
+ if (problems.length === 0)
48
+ return null;
49
+ return `hasLogin is on, but ${problems.join("; ")}. Turn hasLogin off, or change those inputs.`;
50
+ }
51
+ /** Every emitted login file, substituted. Excludes the schema and the CSS block, which merge into other files. */
52
+ export function loginFiles(inputs, opts, spec) {
53
+ return Object.keys(LOGIN_TEMPLATES)
54
+ .filter((key) => key !== SCHEMA_KEY && !key.startsWith("snippets/"))
55
+ .map((path) => ({ path, content: sub(template(path), inputs, opts, spec) }));
56
+ }
57
+ /** `db/schema.ts` with the login tables, replacing the placeholder `example` table. */
58
+ export function loginSchema(inputs, opts, spec) {
59
+ return sub(template(SCHEMA_KEY), inputs, opts, spec);
60
+ }
61
+ /** Appended to `app/globals.css`: the few classes the login pages use. */
62
+ export function loginGlobalsCss() {
63
+ return template(CSS_KEY);
64
+ }
65
+ export const LOGIN_DEPS = {
66
+ "next-auth": "^5.0.0-beta.32",
67
+ };
68
+ export const LOGIN_DEV_DEPS = {
69
+ // An in-memory Postgres for test/auth-adapter.test.ts and test/auth-flow.test.ts.
70
+ "@electric-sql/pglite": "^0.5.14",
71
+ };
72
+ export const LOGIN_SCRIPTS = {
73
+ "user:provision": "node --env-file=.env.local scripts/provision-user.ts",
74
+ };
75
+ /**
76
+ * scripts/provision-user.ts runs under plain Node, which needs real `.ts`
77
+ * import paths; tsconfig must allow them. `noEmit` is already on, which this
78
+ * option requires.
79
+ */
80
+ export function withTsExtensionImports(tsconfig) {
81
+ const anchor = '"noEmit": true,';
82
+ if (!tsconfig.includes(anchor))
83
+ throw new Error("tsconfig template changed: cannot add allowImportingTsExtensions");
84
+ return tsconfig.replace(anchor, `${anchor}\n "allowImportingTsExtensions": true,`);
85
+ }
86
+ /**
87
+ * The env block for login. Replaces the generic CANONICAL_HOSTS block, whose
88
+ * prose describes a seam for an app that writes its own auth; this one
89
+ * describes the code that is actually emitted.
90
+ */
91
+ export const LOGIN_ENV_BLOCK = `
92
+ # Login (magic link + 8-digit code)
93
+
94
+ AUTH_SECRET=
95
+ CANONICAL_HOSTS=
96
+
97
+ # AUTH_SECRET signs the session cookie. Required: Auth.js refuses to run
98
+ # without it. Make one with:
99
+ # openssl rand -base64 33
100
+ # Use a different value in each environment (local, preview, production).
101
+ #
102
+ # CANONICAL_HOSTS is the comma-separated list of hostnames a login link may
103
+ # point at, such as app.example.com,www.example.com (no https://, no path).
104
+ # Unset or empty means NONE, not all. Off production, loopback hosts
105
+ # (localhost, 127.0.0.1) are also allowed, so local login works without it. A
106
+ # preview deployment that must send real login links lists its own host here.
107
+ #
108
+ # Do NOT set AUTH_URL. The app trusts the request's Host and checks it against
109
+ # CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on
110
+ # several domains.
111
+ `;
112
+ /**
113
+ * Mounts the Terms/Privacy footer once in the root layout, after the page
114
+ * content, so every page (logged in or not) links both. Login scaffolds only:
115
+ * without login there are no /terms and /privacy pages to link.
116
+ */
117
+ export function withSiteFooter(layout) {
118
+ const importAnchor = 'import { InfoHintCloser } from "@/components/InfoHintCloser";';
119
+ const bodyAnchor = " {children}\n";
120
+ if (!layout.includes(importAnchor) || !layout.includes(bodyAnchor)) {
121
+ throw new Error("layout template changed: cannot mount the site footer");
122
+ }
123
+ return layout
124
+ .replace(importAnchor, `${importAnchor}\nimport { SiteFooter } from "@/components/SiteFooter";`)
125
+ .replace(bodyAnchor, `${bodyAnchor} {/* Terms and Privacy links on every page (components/SiteFooter.tsx). */}\n <SiteFooter />\n`);
126
+ }
127
+ /**
128
+ * vitest runs `next-auth` through Node's own resolver, which refuses its bare
129
+ * `next/server` import (no extension). Inlining it makes vite resolve it, as
130
+ * `next build` does. Without this, test/auth-flow.test.ts fails to LOAD while
131
+ * `tsc` and `next build` both pass.
132
+ */
133
+ export function withNextAuthInlined(vitestConfig) {
134
+ const anchor = ' exclude: ["node_modules/**", ".next/**", "dist/**"],\n';
135
+ if (!vitestConfig.includes(anchor) || !vitestConfig.includes("\n resolve: {\n")) {
136
+ throw new Error("vitest config template changed: cannot inline next-auth or add the JSX transform");
137
+ }
138
+ return vitestConfig.replace(anchor, `${anchor} // next-auth imports the bare specifier \`next/server\`, which Node's resolver
139
+ // refuses; inlined, vite resolves it the way \`next build\` does.
140
+ server: { deps: { inline: ["next-auth", "@auth/core"] } },
141
+ // Each database test builds a fresh in-memory Postgres in beforeEach,
142
+ // ~1.5s alone and past the 10s default once several files run in parallel
143
+ // (pharmies, 2026-10-17). A slow setup is not a failed test.
144
+ hookTimeout: 60_000,
145
+ `).replace("\n resolve: {\n", `
146
+ // tsconfig says \`jsx: "preserve"\` because Next compiles JSX itself. The test
147
+ // runner has no Next, so without this a test that imports a page or a
148
+ // component fails with "invalid JS syntax". Tests only; \`next build\` ignores it.
149
+ oxc: { jsx: { runtime: "automatic" } },
150
+ resolve: {
151
+ `);
152
+ }
153
+ /** The login pages explain themselves; the guide test is told so, with reasons. */
154
+ export function withLoginGuideExemptions(guideTest) {
155
+ const anchor = ' "/": "The scaffold\'s placeholder home page.';
156
+ const at = guideTest.indexOf(anchor);
157
+ if (at < 0)
158
+ throw new Error("guide test template changed: cannot add the login pages");
159
+ const lineEnd = guideTest.indexOf("\n", at) + 1;
160
+ const rows = [
161
+ ' "/login": "The login page explains itself, and a person reads the guide only after logging in.",',
162
+ ' "/login/check-email": "Reached only from the login form; it explains itself.",',
163
+ ' "/login/error": "Reached only from a failed login link; it explains itself.",',
164
+ ' "/dashboard": "The scaffold\'s placeholder logged-in page. When it becomes a real screen, explain it in a guide section and delete this line.",',
165
+ ' "/agree": "The Terms step after logging in; it explains itself.",',
166
+ ' "/terms": "The Terms themselves, linked from every page\'s footer.",',
167
+ ' "/privacy": "The Privacy Policy, linked from every page\'s footer.",',
168
+ ];
169
+ return guideTest.slice(0, lineEnd) + rows.join("\n") + "\n" + guideTest.slice(lineEnd);
170
+ }
@@ -0,0 +1 @@
1
+ export declare const LOGIN_TEMPLATES: Readonly<Record<string, string>>;
@@ -0,0 +1,51 @@
1
+ // GENERATED by scripts/embed-login-templates.mjs. Do not edit by hand:
2
+ // edit src/scaffolders/nextjs-auth/templates/ and run
3
+ // `node scripts/embed-login-templates.mjs`.
4
+ export const LOGIN_TEMPLATES = {
5
+ "app/agree/page.tsx": "// Agree to the Terms. The first thing a person sees after logging in, before\n// anything else in the app, and again whenever the wording changes\n// (CURRENT_TERMS_VERSION in lib/terms.ts). The full text is shown here, not just\n// linked, so nobody agrees to something they were never shown.\n\nimport { redirect } from \"next/navigation\";\n\nimport { TermsText } from \"@/components/TermsText\";\nimport { requireCurrentUser } from \"@/lib/current-user\";\nimport { POST_LOGIN_DESTINATION, PRIVACY_PATH } from \"@/lib/routes\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { CURRENT_TERMS_VERSION, hasAgreedToCurrentTerms } from \"@/lib/terms\";\n\nexport const metadata = pageMetadata({\n title: \"Before you start\",\n description: `Read and agree to the ${SITE_NAME} Terms before using the app.`,\n path: \"/agree\",\n});\n\n// Reads the session cookie, so it can never be prerendered.\nexport const dynamic = \"force-dynamic\";\n\nconst ERRORS: Record<string, string> = {\n unchecked: \"Please tick the box to agree, or log out if you don't agree.\",\n stale: \"The Terms changed while this page was open. Please read the version below and agree again.\",\n};\n\nexport default async function AgreePage({ searchParams }: { searchParams: Promise<{ error?: string }> }) {\n const { user } = await requireCurrentUser();\n if (hasAgreedToCurrentTerms(user)) redirect(POST_LOGIN_DESTINATION);\n\n const { error } = await searchParams;\n const message = error ? ERRORS[error] : undefined;\n\n return (\n <main className=\"page\">\n <h1>Before you start</h1>\n <p className=\"lead\">\n Please read the {SITE_NAME} Terms. You need to agree to them to use the app. How we handle your information is\n in our <a href={PRIVACY_PATH}>Privacy Policy</a>.\n </p>\n\n <TermsText />\n\n <form method=\"post\" action=\"/agree/submit\" className=\"stack agree-form\">\n {message && (\n <p role=\"alert\" className=\"form-error\">\n {message}\n </p>\n )}\n <input type=\"hidden\" name=\"version\" value={CURRENT_TERMS_VERSION} />\n <label className=\"check-row\">\n <input type=\"checkbox\" name=\"agree\" value=\"yes\" required />\n <span>I have read the Terms and I agree to them, and I understand emails from the app may not arrive.</span>\n </label>\n <button type=\"submit\" className=\"btn-primary\">\n I agree, continue\n </button>\n </form>\n\n <form method=\"post\" action=\"/logout\" className=\"stack\">\n <p className=\"fine-print\">If you don&rsquo;t agree, please don&rsquo;t use {SITE_NAME}.</p>\n <button type=\"submit\" className=\"btn-secondary\">\n Log out\n </button>\n </form>\n </main>\n );\n}\n",
6
+ "app/agree/submit/route.ts": "// Records that this person agreed to the current Terms: the version they were\n// shown and the time, plus an audit event. Never clears an earlier agreement;\n// a newer version simply replaces the \"last agreed\" pair on the user row.\n//\n// Uses getCurrentUser(), not getAgreedUser(): this is the one handler a person\n// who has not agreed yet must be able to reach.\n\nimport { eq } from \"drizzle-orm\";\n\nimport { getDb } from \"@/db/client\";\nimport { auditEvents, users } from \"@/db/schema\";\nimport { AUDIT_ACTIONS } from \"@/lib/audit\";\nimport { getCurrentUser } from \"@/lib/current-user\";\nimport { isSameOriginPost, seeOther } from \"@/lib/http\";\nimport { AGREE_PATH, LOGIN_PATH, POST_LOGIN_DESTINATION } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION, parseAgreement } from \"@/lib/terms\";\n\nexport async function POST(request: Request): Promise<Response> {\n if (!isSameOriginPost(request)) return new Response(\"Forbidden\", { status: 403 });\n\n const current = await getCurrentUser();\n if (!current) return seeOther(LOGIN_PATH);\n\n const form = await request.formData().catch(() => null);\n const result = parseAgreement({ agree: form?.get(\"agree\"), version: form?.get(\"version\") });\n if (result !== \"ok\") return seeOther(`${AGREE_PATH}?error=${result}`);\n\n await getDb().transaction(async (tx) => {\n await tx\n .update(users)\n .set({ termsVersion: CURRENT_TERMS_VERSION, termsAcceptedAt: new Date() })\n .where(eq(users.id, current.user.id));\n await tx.insert(auditEvents).values({\n tenantId: current.tenantId,\n userId: current.user.id,\n action: AUDIT_ACTIONS.TERMS_AGREED,\n targetType: \"user\",\n targetId: current.user.id,\n });\n });\n return seeOther(POST_LOGIN_DESTINATION);\n}\n",
7
+ "app/api/auth/[...nextauth]/route.ts": "// Auth.js's own endpoints: the link click (/api/auth/callback/email), the\n// session, CSRF and logout. Configuration lives in /auth.ts.\nimport { handlers } from \"@/auth\";\n\nexport const { GET, POST } = handlers;\n",
8
+ "app/dashboard/page.tsx": "// The first screen after logging in (POST_LOGIN_DESTINATION in lib/routes.ts).\n// A placeholder: replace it with the app's real logged-in home, and keep the\n// requireAgreedUser() call at the top of every page that needs a login (it\n// also sends anyone who has not agreed to the current Terms to /agree).\n//\n// Logging out is a POST form, never a link, so a link or an image tag elsewhere\n// can't log someone out.\n\nimport { requireAgreedUser } from \"@/lib/current-user\";\nimport { pageMetadata } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Dashboard\",\n description: \"Your account.\",\n path: \"/dashboard\",\n});\n\n// Reads the session cookie, so it can never be prerendered.\nexport const dynamic = \"force-dynamic\";\n\nexport default async function DashboardPage() {\n const { user, tenant } = await requireAgreedUser();\n\n return (\n <main className=\"page\">\n <h1>Dashboard</h1>\n <p>\n You&rsquo;re logged in as <strong>{user.email}</strong>, in the account <strong>{tenant.name}</strong>.\n </p>\n <form method=\"post\" action=\"/logout\">\n <button type=\"submit\" className=\"btn-primary\">\n Log out\n </button>\n </form>\n </main>\n );\n}\n",
9
+ "app/login/LoginForm.tsx": "\"use client\";\n\n// A plain <form> posting to /login/submit/: it works with JavaScript off, and\n// from a page left open across deploys (see lib/http.ts). JavaScript adds two\n// things: a \"Sending…\" state, and remembering the typed address (in this tab\n// only) so the next page can show it back. A mistyped address is invisible to\n// the person who typed it until they see it written somewhere else.\n\nimport { useState } from \"react\";\n\nimport { Field } from \"@/components/FormBits\";\n\nexport const TYPED_EMAIL_KEY = \"{{slug}}.login.typedEmail\";\n\nexport function LoginForm() {\n const [sending, setSending] = useState(false);\n\n function onSubmit(event: React.FormEvent<HTMLFormElement>) {\n const email = new FormData(event.currentTarget).get(\"email\");\n try {\n if (typeof email === \"string\") sessionStorage.setItem(TYPED_EMAIL_KEY, email.trim());\n } catch {\n // Private browsing can refuse storage; the next page then shows generic wording.\n }\n setSending(true);\n }\n\n return (\n <form method=\"post\" action=\"/login/submit\" onSubmit={onSubmit} className=\"stack\">\n <Field id=\"email\" label=\"Email address\" required>\n <input\n id=\"email\"\n name=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n inputMode=\"email\"\n required\n autoFocus\n />\n </Field>\n <button type=\"submit\" className=\"btn-primary\" disabled={sending}>\n {sending ? \"Sending…\" : \"Email me a login link\"}\n </button>\n </form>\n );\n}\n",
10
+ "app/login/check-email/CodeForm.tsx": "\"use client\";\n\n// Type the 8-digit code from the login email. Needed when the app is installed\n// on a phone's home screen: the email's button opens the phone's default browser,\n// which logs in THAT browser, not the installed app. Typing the code opens the\n// same address the button would, inside this app (lib/auth/sign-in-code.ts).\n\nimport { useEffect, useState } from \"react\";\n\nimport { Field } from \"@/components/FormBits\";\nimport { buildCodeCallbackPath, normalizeSignInCode, SIGN_IN_CODE_LENGTH } from \"@/lib/auth/sign-in-code\";\nimport { normalizeEmail } from \"@/lib/auth/sign-in-policy\";\n\nimport { TYPED_EMAIL_KEY } from \"../LoginForm\";\n\nexport function CodeForm() {\n const [storedEmail, setStoredEmail] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [going, setGoing] = useState(false);\n\n useEffect(() => {\n try {\n setStoredEmail(sessionStorage.getItem(TYPED_EMAIL_KEY));\n } catch {\n setStoredEmail(null);\n }\n }, []);\n\n function onSubmit(event: React.FormEvent<HTMLFormElement>) {\n event.preventDefault();\n const form = new FormData(event.currentTarget);\n const email = normalizeEmail(storedEmail ?? form.get(\"email\"));\n const code = normalizeSignInCode(String(form.get(\"code\") ?? \"\"));\n if (!email) return setError(\"Please enter the email address you asked for the code with.\");\n if (!code) return setError(`Please enter the ${SIGN_IN_CODE_LENGTH} digits from the email.`);\n setError(null);\n setGoing(true);\n window.location.assign(buildCodeCallbackPath(email, code));\n }\n\n return (\n <form onSubmit={onSubmit} className=\"stack code-form\" noValidate>\n <h2>Or type the code from the email</h2>\n {error && (\n <p role=\"alert\" className=\"form-error\">\n {error}\n </p>\n )}\n {!storedEmail && (\n <Field id=\"email\" label=\"Email\" required>\n <input id=\"email\" name=\"email\" type=\"email\" autoComplete=\"email\" required />\n </Field>\n )}\n <Field id=\"code\" label=\"Login Code\" required>\n <input\n id=\"code\"\n name=\"code\"\n type=\"text\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n pattern=\"[0-9 ]*\"\n maxLength={SIGN_IN_CODE_LENGTH + 2}\n required\n className=\"code-input\"\n />\n </Field>\n <button type=\"submit\" className=\"btn-primary\" disabled={going}>\n {going ? \"Logging in…\" : \"Log in\"}\n </button>\n </form>\n );\n}\n",
11
+ "app/login/check-email/TypedAddress.tsx": "\"use client\";\n\n// Shows back the address typed on the previous page, read from this tab's\n// sessionStorage after mount (never from the URL or the server). Without it,\n// the generic sentence is shown.\n\nimport { useEffect, useState } from \"react\";\n\nimport { TYPED_EMAIL_KEY } from \"../LoginForm\";\n\nexport function TypedAddress() {\n const [email, setEmail] = useState<string | null>(null);\n\n useEffect(() => {\n try {\n setEmail(sessionStorage.getItem(TYPED_EMAIL_KEY));\n } catch {\n setEmail(null);\n }\n }, []);\n\n if (!email) {\n return <p>If the address you entered has access, a login link is on its way.</p>;\n }\n return (\n <p>\n If <strong className=\"typed-address\">{email}</strong> has access, a login link is on its way.\n </p>\n );\n}\n",
12
+ "app/login/check-email/page.tsx": "// Shown after every login request, whatever happened. The wording states a\n// CONDITION (\"if this address has access\"), never an outcome, because this\n// page can't know whether an email went out, and an invited person waiting for\n// a link that will never come needs to know that's possible.\n\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { CodeForm } from \"./CodeForm\";\nimport { TypedAddress } from \"./TypedAddress\";\n\nexport const metadata = pageMetadata({\n title: \"Check your email\",\n description: \"If the address you entered has access, a login link is on its way.\",\n path: \"/login/check-email\",\n});\n\nexport default function CheckEmailPage() {\n return (\n <main className=\"page\">\n <h1>Check your email</h1>\n <TypedAddress />\n <p>Tap the button in the email, or, if you are using {SITE_NAME} from your home screen, type its code below. Either works once and expires in 24 hours.</p>\n <CodeForm />\n <p>\n Not seeing it? Check the spelling of the address above, then your spam folder. If needed, we can{\" \"}\n <a href=\"/login\" className=\"text-link\">\n send another link\n </a>\n .\n </p>\n <p className=\"fine-print\">\n {SITE_NAME} is by invitation, so nothing is sent to an address that hasn&rsquo;t been invited. For your\n privacy, this page looks the same either way.\n </p>\n </main>\n );\n}\n",
13
+ "app/login/error/page.tsx": "// Where Auth.js sends a failed login. The commonest way to get here is opening\n// a login link a second time (a restored tab, a mail app that pre-opened the\n// link, a second device) while already logged in. So check for a session\n// FIRST: telling a logged-in person their link \"expired\" sends them to request\n// a link they don't need.\n//\n// The wording never says whether an address has an account.\n\nimport { getCurrentUser } from \"@/lib/current-user\";\nimport { POST_LOGIN_DESTINATION } from \"@/lib/routes\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Login link problem\",\n description: `This ${SITE_NAME} login link could not log you in.`,\n path: \"/login/error\",\n});\n\nexport default async function LoginErrorPage() {\n const current = await getCurrentUser();\n\n if (current) {\n return (\n <main className=\"page\">\n <h1>You&rsquo;re already logged in</h1>\n <p>\n You&rsquo;re logged in as <strong>{current.user.email}</strong>. Each login link works only once, so\n opening it again did nothing.\n </p>\n <p>\n <a href={POST_LOGIN_DESTINATION} className=\"btn-primary\">\n Go to {SITE_NAME}\n </a>\n </p>\n </main>\n );\n }\n\n return (\n <main className=\"page\">\n <h1>That didn&rsquo;t log you in</h1>\n <p>\n The code may be mistyped, or the link or code was already used or is more than 24 hours old. After too many\n wrong codes, logging in pauses for up to an hour.\n </p>\n <p>\n <a href=\"/login\" className=\"btn-primary\">\n Get a new code\n </a>\n </p>\n <p className=\"fine-print\">\n Using {SITE_NAME} from your home screen? Type the code from the email into the app rather than tapping the\n button, which opens your phone&rsquo;s browser instead.\n </p>\n </main>\n );\n}\n",
14
+ "app/login/page.tsx": "import { redirect } from \"next/navigation\";\n\nimport { getCurrentUser } from \"@/lib/current-user\";\nimport { POST_LOGIN_DESTINATION } from \"@/lib/routes\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { LoginForm } from \"./LoginForm\";\n\nexport const metadata = pageMetadata({\n title: \"Log in\",\n description: `Log in to ${SITE_NAME} with a one-time link sent to your email.`,\n path: \"/login\",\n});\n\nexport default async function LoginPage() {\n // Already logged in: go to the app, never to the public home page.\n if (await getCurrentUser()) redirect(POST_LOGIN_DESTINATION);\n\n return (\n <main className=\"page\">\n <h1>Log in to {SITE_NAME}</h1>\n <p>Enter your email address and we&rsquo;ll send you a link that logs you in. No password needed.</p>\n <LoginForm />\n <p className=\"fine-print\">{SITE_NAME} is by invitation.</p>\n </main>\n );\n}\n",
15
+ "app/login/submit/route.ts": "// Receives the login form. Every outcome ends on the same \"check your email\"\n// page: a real account, an unknown address, a rate limit, a mail failure. That\n// sameness is what stops the form revealing who has an account, so nothing\n// here may branch the response.\n\nimport { signIn } from \"@/auth\";\nimport { normalizeEmail } from \"@/lib/auth/sign-in-policy\";\nimport { isSameOriginPost, seeOther } from \"@/lib/http\";\nimport { CHECK_EMAIL_PATH, POST_LOGIN_DESTINATION } from \"@/lib/routes\";\n\nexport async function POST(request: Request): Promise<Response> {\n if (!isSameOriginPost(request)) return new Response(\"Forbidden\", { status: 403 });\n\n const form = await request.formData().catch(() => null);\n const email = normalizeEmail(form?.get(\"email\"));\n if (email) {\n try {\n // The send gate (lib/auth/send-gate.ts) decides whether an email goes out.\n await signIn(\"email\", { email, redirect: false, redirectTo: POST_LOGIN_DESTINATION });\n } catch (error) {\n console.error(\"[auth] login request failed before the send gate; no email sent.\", error);\n }\n }\n return seeOther(CHECK_EMAIL_PATH);\n}\n",
16
+ "app/logout/route.ts": "// Log out. POST only, so a link or an image tag can't log someone out.\n\nimport { signOut } from \"@/auth\";\nimport { isSameOriginPost, seeOther } from \"@/lib/http\";\nimport { POST_LOGOUT_DESTINATION } from \"@/lib/routes\";\n\nexport async function POST(request: Request): Promise<Response> {\n if (!isSameOriginPost(request)) return new Response(\"Forbidden\", { status: 403 });\n await signOut({ redirect: false, redirectTo: POST_LOGOUT_DESTINATION });\n return seeOther(POST_LOGOUT_DESTINATION);\n}\n",
17
+ "app/privacy/page.tsx": "// The Privacy Policy, public and linked from the footer of every page.\n\nimport { PrivacyText } from \"@/components/PrivacyText\";\nimport { LegalPageEnd, RunBy } from \"@/components/TermsText\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Privacy Policy\",\n description: `What ${SITE_NAME} collects, why, and who else receives it.`,\n path: \"/privacy\",\n});\n\nexport default function PrivacyPage() {\n return (\n <main className=\"page\">\n <h1>{SITE_NAME} Privacy Policy</h1>\n <RunBy />\n <PrivacyText />\n <LegalPageEnd />\n </main>\n );\n}\n",
18
+ "app/terms/page.tsx": "// The Terms, public and linked from the footer of every page, so anyone can\n// read them at any time without logging in. The same text a person agrees to\n// on /agree (components/TermsText.tsx).\n\nimport { LegalPageEnd, TermsText } from \"@/components/TermsText\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Terms\",\n description: `The ${SITE_NAME} Terms: what the app promises, and your responsibility.`,\n path: \"/terms\",\n});\n\nexport default function TermsPage() {\n return (\n <main className=\"page\">\n <h1>{SITE_NAME} Terms</h1>\n <TermsText />\n <LegalPageEnd />\n </main>\n );\n}\n",
19
+ "auth.ts": "// Auth.js (NextAuth v5) configuration: invite-only magic-link login, with the\n// same secret also printed in the email as an 8-digit code.\n//\n// - trustHost: true and NO AUTH_URL env var, so one deployment can serve\n// several domains. The link host is checked against CANONICAL_HOSTS in\n// lib/auth/send-gate.ts instead.\n// - The allowlist is checked twice: before sending (send-gate) and again when\n// the link is clicked (the signIn callback below), so a link sent before\n// access was removed no longer works.\n// - At SEND time the signIn callback allows everyone. Refusing there would\n// change the redirect for unknown addresses and reveal who has an account.\n// The send gate still sends nothing to them.\n// - Sessions are JWTs (lib/auth/session-config.ts).\n// - Function form NextAuth(() => config): env is read per request, so\n// `next build` works without secrets.\n//\n// Only this file and lib/current-user.ts call auth(). Everything else asks\n// lib/current-user.ts who is logged in.\n\nimport NextAuth from \"next-auth\";\nimport type { EmailConfig } from \"next-auth/providers\";\nimport { eq } from \"drizzle-orm\";\n\nimport { getDb } from \"@/db/client\";\nimport { auditEvents, users } from \"@/db/schema\";\nimport { AUDIT_ACTIONS } from \"@/lib/audit\";\nimport { generateSignInCode } from \"@/lib/auth/sign-in-code\";\nimport { sendEmail } from \"@/lib/email/mailer\";\nimport {\n countOutstandingLoginLinks,\n createAdapter,\n findSignInCandidate,\n findSignInCandidateById,\n isPhantomUser,\n} from \"@/lib/auth/adapter\";\nimport { LOGIN_LINK_MAX_AGE_SECONDS } from \"@/lib/auth/login-email\";\nimport { createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport { deliverLoginLink } from \"@/lib/auth/send-gate\";\nimport { sessionConfig } from \"@/lib/auth/session-config\";\nimport { canUserSignIn } from \"@/lib/auth/sign-in-policy\";\n\n/**\n * Where login events are recorded: an audit_events\n * row, written in the same transaction as users.last_login_at.\n */\nexport const AUTH_AUDIT_SINK = \"audit_events\" as const;\n\nconst HOUR = 60 * 60 * 1000;\n// Per server instance. The per-address limit is shared (verification_tokens).\nconst ipLimiter = createRateLimiter({ limit: 20, windowMs: HOUR });\nconst instanceLimiter = createRateLimiter({ limit: 300, windowMs: HOUR });\n\nconst emailProvider: EmailConfig = {\n id: \"email\",\n type: \"email\",\n name: \"Email\",\n maxAge: LOGIN_LINK_MAX_AGE_SECONDS,\n // The token IS the 8-digit code printed in the email (lib/auth/sign-in-code.ts).\n generateVerificationToken: generateSignInCode,\n async sendVerificationRequest({ identifier, url, request }) {\n await deliverLoginLink(\n { identifier, url, headers: request.headers },\n {\n env: process.env,\n findUser: findSignInCandidate,\n countOutstanding: countOutstandingLoginLinks,\n sendEmail,\n ipLimiter,\n instanceLimiter,\n log: console,\n },\n );\n },\n options: {},\n};\n\nexport const { handlers, auth, signIn, signOut } = NextAuth(() => ({\n trustHost: true,\n adapter: createAdapter(),\n providers: [emailProvider],\n session: sessionConfig,\n // Path-only values: Auth.js appends its own query string to each (Trap 2).\n pages: {\n signIn: \"/login\",\n verifyRequest: \"/login/check-email\",\n error: \"/login/error\",\n },\n callbacks: {\n async signIn({ user, email }) {\n // SEND time: allow everyone, so every address gets the same response.\n if (email?.verificationRequest) return true;\n // CLICK time: the real gate. Re-read the row, so access removed after\n // the link was sent is honored.\n if (!user?.id || isPhantomUser(user.id)) return false;\n return canUserSignIn(await findSignInCandidateById(user.id));\n },\n jwt({ token, user }) {\n if (user?.id) {\n token.sub = user.id;\n token.email = (user.email ?? \"\").toLowerCase();\n }\n return token;\n },\n session({ session, token }) {\n if (token.sub && session.user) session.user.id = token.sub;\n return session;\n },\n },\n events: {\n async signIn({ user }) {\n if (!user?.id || isPhantomUser(user.id)) return;\n const db = getDb();\n const [row] = await db.select().from(users).where(eq(users.id, user.id)).limit(1);\n if (!row) return;\n // The audit row and last_login_at land together or not at all.\n await db.transaction(async (tx) => {\n await tx.insert(auditEvents).values({\n tenantId: row.tenantId,\n userId: row.id,\n action: AUDIT_ACTIONS.AUTH_LOGIN,\n targetType: \"user\",\n targetId: row.id,\n });\n await tx.update(users).set({ lastLoginAt: new Date() }).where(eq(users.id, row.id));\n });\n },\n async signOut(message) {\n // JWT sessions: the event carries { token }, not { session }.\n const userId = \"token\" in message ? message.token?.sub : undefined;\n if (!userId || isPhantomUser(userId)) return;\n const db = getDb();\n const [row] = await db.select().from(users).where(eq(users.id, userId)).limit(1);\n if (!row) return;\n await db.insert(auditEvents).values({\n tenantId: row.tenantId,\n userId: row.id,\n action: AUDIT_ACTIONS.AUTH_LOGOUT,\n targetType: \"user\",\n targetId: row.id,\n });\n },\n },\n}));\n",
20
+ "components/PrivacyText.tsx": "// The Privacy Policy, shown on /privacy (public) and linked from the Terms, the\n// agree page and the footer of every page. Not a separate agreement: people\n// agree to the Terms, which link it.\n//\n// 🔴 Every sentence must be true of the code on the day it ships. SERVICES is\n// the list of outside services this app's code sends personal information to,\n// as scaffolded: Vercel (hosting), Neon (database), Amazon SES (the mailer's\n// default; change the line if you set EMAIL_PROVIDER=resend) and Fathom\n// (analytics). Add a row the day you wire another one (Sentry, a payment\n// processor, file storage, an AI service), and change the \"AI\" section if\n// anything a person enters is ever sent to one.\n//\n// ⚠️ Changing the wording? Bump TERMS_LAST_MODIFIED in lib/terms.ts. A plain-\n// English draft, NOT reviewed by a lawyer.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { TERMS_OPERATOR } from \"@/lib/terms\";\n\nconst SERVICES: { name: string; receives: string }[] = [\n { name: \"Vercel\", receives: \"hosts the app, so it handles every request, including your IP address and browser details.\" },\n { name: \"Neon\", receives: \"stores the app's database: your account and everything you enter.\" },\n { name: \"Amazon Web Services (Amazon SES)\", receives: \"sends the app's emails, so it receives your email address and each email.\" },\n { name: \"Fathom Analytics\", receives: \"counts page visits without cookies and without identifying you.\" },\n];\n\nexport function PrivacyText({ headingLevel = 2 }: { headingLevel?: 2 | 3 }) {\n const H = headingLevel === 2 ? \"h2\" : \"h3\";\n return (\n <div className=\"terms-text\">\n <H>What we collect</H>\n <ul>\n <li>What you enter: your name, your email address, and what you add in the app.</li>\n <li>What is created when you use it: when you log in and out, and a record of changes to your account.</li>\n <li>What your browser sends: your IP address and the kind of device and browser you use.</li>\n <li>From whoever invited you: the name and email address they gave us to create your account.</li>\n </ul>\n\n <H>Why</H>\n <p>\n To run {SITE_NAME}, to log you in, and to keep it secure and stop abuse. Agreeing to the Terms does not sign you\n up for any newsletter or marketing email.\n </p>\n\n <H>Who else receives it</H>\n <ul>\n {SERVICES.map((s) => (\n <li key={s.name}>\n <strong>{s.name}</strong> {s.receives}\n </li>\n ))}\n </ul>\n <p>We do not sell or rent your information.</p>\n\n <H>AI</H>\n <p>Nothing you enter in {SITE_NAME} is sent to an AI service.</p>\n\n <H>How long we keep it</H>\n <p>\n We keep your information while you have an account. When an account is closed, {TERMS_OPERATOR} deletes it,\n except where the law requires us to keep a record.\n </p>\n\n <H>Your choices</H>\n <p>\n You can ask to see, correct or delete your information. Use the contact information at the bottom of this page.\n </p>\n\n <H>Changes</H>\n <p>If this policy changes, the new version will be posted here with a new &ldquo;Last modified&rdquo; date.</p>\n </div>\n );\n}\n",
21
+ "components/SiteFooter.tsx": "// The footer on every page, mounted once in app/layout.tsx: links to the Terms\n// and the Privacy Policy, so both are one tap away whether or not anyone is\n// logged in. Each link is a 48px tap target and underlined.\n\nimport { PRIVACY_PATH, TERMS_PATH } from \"@/lib/routes\";\n\nexport function SiteFooter() {\n return (\n <footer className=\"site-footer\">\n <nav aria-label=\"Legal\">\n <a href={TERMS_PATH}>Terms</a>\n <a href={PRIVACY_PATH}>Privacy</a>\n </nav>\n </footer>\n );\n}\n",
22
+ "components/TermsText.tsx": "// Sections: base\n//\n// The wording of the Terms, shown in full on /terms (public) and on /agree\n// (where a person agrees before first use). One component, so the text a\n// person agrees to is byte-for-byte the text the public page shows.\n//\n// ⚠️ Changing the wording? Bump CURRENT_TERMS_VERSION and TERMS_LAST_MODIFIED\n// in lib/terms.ts in the same commit, so everyone is asked to agree again.\n//\n// This is the BASE every app with a login gets. Add a section when the app\n// gains a reason for one (reminders, content other people see, anything that\n// could be read as medical or legal help, payments) and list it on the\n// \"Sections:\" line above. The wording is a plain-English draft, NOT reviewed\n// by a lawyer: have the operator approve it, and a lawyer review it if they\n// choose, before the app is offered to the public.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { PRIVACY_PATH } from \"@/lib/routes\";\nimport {\n formatTermsDate,\n TERMS_CONTACT_URL,\n TERMS_CREATED,\n TERMS_LAST_MODIFIED,\n TERMS_OPERATOR,\n TERMS_OPERATOR_URL,\n} from \"@/lib/terms\";\n\n/** \"SITE is run by OPERATOR\", with the operator linked. The first line of both legal pages. */\nexport function RunBy() {\n return (\n <p className=\"lead\">\n {SITE_NAME} is run by{\" \"}\n <a href={TERMS_OPERATOR_URL} target=\"_blank\" rel=\"noopener noreferrer\">\n {TERMS_OPERATOR}\n </a>\n .\n </p>\n );\n}\n\n/** The one place contact details appear, and the page's dates. The last thing on both legal pages. */\nexport function LegalPageEnd() {\n return (\n <div className=\"legal-end\">\n <p>\n <a className=\"btn-primary\" href={TERMS_CONTACT_URL} target=\"_blank\" rel=\"noopener noreferrer\">\n Contact Us\n </a>\n </p>\n <p className=\"fine-print\">\n Created {formatTermsDate(TERMS_CREATED)} · Last modified {formatTermsDate(TERMS_LAST_MODIFIED)}\n </p>\n </div>\n );\n}\n\nexport function TermsText({ headingLevel = 2 }: { headingLevel?: 2 | 3 }) {\n const H = headingLevel === 2 ? \"h2\" : \"h3\";\n return (\n <div className=\"terms-text\">\n <RunBy />\n\n <H>{SITE_NAME} is provided as-is</H>\n <p>\n We work to keep {SITE_NAME} running and correct, but we do not promise it will always be available, accurate,\n complete or free of errors, or that it suits any particular purpose.\n </p>\n\n <H>Do not rely on emails</H>\n <p>\n Emails and notifications from {SITE_NAME} can be delayed, filtered as spam, or not arrive at all. Do not rely on\n them for anything important; check the app itself.\n </p>\n\n <H>Your choice, your responsibility</H>\n <p>\n You use {SITE_NAME} of your own free will and at your own risk. To the fullest extent the law allows,{\" \"}\n {TERMS_OPERATOR} and the people who build and run {SITE_NAME} are not responsible for any harm, loss or cost\n that comes from using the app or relying on it, and you agree to hold them harmless for it.\n </p>\n\n <H>Your account</H>\n <p>\n Keep access to your email account secure, because that is how you log in. You are responsible for what is done\n through your account. If you think someone else has used it, tell us using the contact information at the bottom\n of this page.\n </p>\n\n <H>Be decent</H>\n <p>\n Do not use {SITE_NAME} to break the law, harass or deceive anyone, try to reach data that is not yours, overload\n or attack the service, or get around its limits. We may suspend or close an account that does.\n </p>\n\n <H>Your information</H>\n <p>\n How we handle it is in our <a href={PRIVACY_PATH}>Privacy Policy</a>.\n </p>\n\n <H>Changes</H>\n <p>\n If these terms change, {SITE_NAME} will show you the new version and ask you to agree again before you carry on.\n Questions are welcome; use the contact information at the bottom of this page.\n </p>\n </div>\n );\n}\n",
23
+ "db/schema.ts": "// Drizzle schema for {{slug}}.\n//\n// Standard Postgres types only, so the schema ports to any Postgres host.\n// Apply it with `npm run db:push` (or `npm run db:generate` for SQL migrations).\n//\n// The tables below are login. Add the app's own tables underneath. Every table\n// that holds an account's data carries `tenant_id NOT NULL` with an index that\n// starts with it, and every query on it filters by the tenantId that\n// lib/current-user.ts returns.\n\nimport { sql } from \"drizzle-orm\";\nimport { boolean, check, index, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from \"drizzle-orm/pg-core\";\n\nconst createdAt = () => timestamp(\"created_at\", { withTimezone: true }).defaultNow().notNull();\n\n/** One account. A single-organization app has one row. */\nexport const tenants = pgTable(\"tenants\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n /** `active` | `suspended`. Text, not an enum, so values can evolve. Anything but `active` blocks login. */\n status: text(\"status\").notNull().default(\"active\"),\n createdAt: createdAt(),\n});\n\n/**\n * People who can log in. Pre-provisioned only (scripts/provision-user.ts):\n * Auth.js never creates a user. The allowlist lives HERE as `sign_in_enabled`,\n * editable in the app, rather than in an env var that needs a redeploy.\n *\n * `email` is unique across ALL tenants, not per tenant: login starts from an\n * email address alone, and one address in two tenants would make \"which\n * account is this?\" unanswerable before the person is even logged in.\n */\nexport const users = pgTable(\n \"users\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n /** Stored lower-cased. */\n email: text(\"email\").notNull(),\n /** Display name, always built from firstName + lastName, never split from it. */\n name: text(\"name\"),\n firstName: text(\"first_name\"),\n /** Null for someone with one name. */\n lastName: text(\"last_name\"),\n /** `owner` to start; add roles as the app needs them. */\n role: text(\"role\").notNull().default(\"owner\"),\n isActive: boolean(\"is_active\").notNull().default(true),\n signInEnabled: boolean(\"sign_in_enabled\").notNull().default(false),\n emailVerifiedAt: timestamp(\"email_verified_at\", { withTimezone: true }),\n lastLoginAt: timestamp(\"last_login_at\", { withTimezone: true }),\n /** The Terms version this person last agreed to (lib/terms.ts). Null = never agreed. */\n termsVersion: text(\"terms_version\"),\n /** When they agreed to `termsVersion`. */\n termsAcceptedAt: timestamp(\"terms_accepted_at\", { withTimezone: true }),\n createdAt: createdAt(),\n },\n (t) => [\n uniqueIndex(\"users_email_uidx\").on(t.email),\n index(\"users_tenant_idx\").on(t.tenantId),\n check(\"users_email_lowercase\", sql`${t.email} = lower(${t.email})`),\n ],\n);\n\n/** Auth.js login tokens: each one is the 8-digit code in a login email. Keyed by email, not by tenant. */\nexport const verificationTokens = pgTable(\n \"verification_tokens\",\n {\n identifier: text(\"identifier\").notNull(),\n token: text(\"token\").notNull(),\n expires: timestamp(\"expires\", { withTimezone: true }).notNull(),\n },\n (t) => [primaryKey({ columns: [t.identifier, t.token] })],\n);\n\n/**\n * Wrong login codes (and used or expired links, which carry the same code), one\n * row per miss. Counted per address over the last hour to lock out guessing\n * (lib/auth/sign-in-code.ts). Keyed by email, not by tenant.\n */\nexport const signInCodeFailures = pgTable(\n \"sign_in_code_failures\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n identifier: text(\"identifier\").notNull(),\n failedAt: timestamp(\"failed_at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => [index(\"sign_in_code_failures_identifier_idx\").on(t.identifier, t.failedAt)],\n);\n\n/** Append-only. Records ids and actions only (lib/audit.ts), never the content of a record. */\nexport const auditEvents = pgTable(\n \"audit_events\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n userId: uuid(\"user_id\").references(() => users.id, { onDelete: \"set null\" }),\n action: text(\"action\").notNull(),\n targetType: text(\"target_type\"),\n targetId: uuid(\"target_id\"),\n createdAt: createdAt(),\n },\n (t) => [index(\"audit_events_tenant_time_idx\").on(t.tenantId, t.createdAt)],\n);\n",
24
+ "lib/audit.ts": "// Audit action names. One constant per action so a typo can't silently create\n// a new kind of event. Audit rows hold ids and actions only, never the content\n// of a person's records. Add a constant here for each new action you record.\n\nexport const AUDIT_ACTIONS = {\n AUTH_LOGIN: \"auth.login\",\n AUTH_LOGOUT: \"auth.logout\",\n TERMS_AGREED: \"user.terms_agreed\",\n} as const;\n\nexport type AuditAction = (typeof AUDIT_ACTIONS)[keyof typeof AUDIT_ACTIONS];\n",
25
+ "lib/auth/adapter.ts": "// The Auth.js adapter: the small set of methods magic-link login needs\n// No session methods, because sessions are JWTs.\n//\n// Three rules:\n// 1. getUserByEmail NEVER returns null. An address that can't log in gets the\n// PHANTOM user, so Auth.js takes the same path for every address and the\n// response can't reveal who has an account. The click-time signIn\n// callback refuses the phantom.\n// 2. createUser throws. Accounts are created by scripts/provision-user.ts,\n// never by clicking a link. If it is ever called, rule 1 has broken.\n// 3. updateUser receives only { id, emailVerified }: no email. It\n// looks the person up by id.\n\nimport \"server-only\";\n\nimport { and, count, eq, gt, lt, sql } from \"drizzle-orm\";\nimport type { Adapter, AdapterUser, VerificationToken } from \"next-auth/adapters\";\n\nimport { getDb } from \"@/db/client\";\nimport { signInCodeFailures, tenants, users, verificationTokens } from \"@/db/schema\";\nimport {\n SIGN_IN_CODE_LIVE_MAX,\n SIGN_IN_CODE_WRONG_GUESS_LIMIT,\n SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS,\n} from \"./sign-in-code\";\nimport { canUserSignIn, type SignInCandidate } from \"./sign-in-policy\";\n\nexport const PHANTOM_USER_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport function isPhantomUser(id: string | null | undefined): boolean {\n return id === PHANTOM_USER_ID;\n}\n\ntype UserRow = typeof users.$inferSelect;\ntype Candidate = SignInCandidate & { user: UserRow };\n\nasync function selectUser(where: ReturnType<typeof eq>): Promise<Candidate | null> {\n const [row] = await getDb()\n .select({ user: users, tenantStatus: tenants.status })\n .from(users)\n .innerJoin(tenants, eq(users.tenantId, tenants.id))\n .where(where)\n .limit(1);\n if (!row) return null;\n return {\n user: row.user,\n isActive: row.user.isActive,\n signInEnabled: row.user.signInEnabled,\n tenantStatus: row.tenantStatus,\n };\n}\n\n/** Used by the send gate and the click-time gate. */\nexport function findSignInCandidate(email: string): Promise<Candidate | null> {\n return selectUser(eq(users.email, email.toLowerCase()));\n}\n\nexport function findSignInCandidateById(id: string): Promise<Candidate | null> {\n return selectUser(eq(users.id, id));\n}\n\n/**\n * Unexpired login tokens, counting only rows whose address belongs to an\n * active, invited user. Unknown addresses still get token rows (Auth.js\n * writes one for every request) but never count against anyone's budget.\n */\nexport async function countOutstandingLoginLinks(\n email: string,\n): Promise<{ forEmail: number; global: number }> {\n const db = getDb();\n const now = new Date();\n const [forEmail] = await db\n .select({ n: count() })\n .from(verificationTokens)\n .where(and(eq(verificationTokens.identifier, email.toLowerCase()), gt(verificationTokens.expires, now)));\n const [global] = await db\n .select({ n: count() })\n .from(verificationTokens)\n .innerJoin(\n users,\n and(eq(users.email, verificationTokens.identifier), eq(users.isActive, true), eq(users.signInEnabled, true)),\n )\n .where(gt(verificationTokens.expires, now));\n return { forEmail: forEmail?.n ?? 0, global: global?.n ?? 0 };\n}\n\nfunction toAdapterUser(user: UserRow): AdapterUser {\n return {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerifiedAt,\n name: user.name,\n };\n}\n\nfunction phantom(email: string): AdapterUser {\n return { id: PHANTOM_USER_ID, email: email.toLowerCase(), emailVerified: null };\n}\n\nexport function createAdapter(): Adapter {\n return {\n async getUserByEmail(email) {\n const candidate = await findSignInCandidate(email);\n return candidate && canUserSignIn(candidate) ? toAdapterUser(candidate.user) : phantom(email);\n },\n\n async getUser(id) {\n if (isPhantomUser(id)) return null;\n const candidate = await findSignInCandidateById(id);\n return candidate && canUserSignIn(candidate) ? toAdapterUser(candidate.user) : null;\n },\n\n async createUser() {\n throw new Error(\"createUser called: getUserByEmail must return a real or phantom user\");\n },\n\n async updateUser({ id, emailVerified }) {\n if (isPhantomUser(id)) throw new Error(\"updateUser called for the phantom user\");\n const db = getDb();\n if (emailVerified) {\n await db.update(users).set({ emailVerifiedAt: emailVerified }).where(eq(users.id, id));\n }\n const [user] = await db.select().from(users).where(eq(users.id, id)).limit(1);\n if (!user) throw new Error(\"updateUser called for a user id that does not exist\");\n return toAdapterUser(user);\n },\n\n async createVerificationToken(token) {\n const db = getDb();\n await db.insert(verificationTokens).values(token);\n // 🔴 Keep only the newest SIGN_IN_CODE_LIVE_MAX tokens for this address. Each\n // token is a typed 8-digit code (lib/auth/sign-in-code.ts), every live one is\n // something a guess can hit, and Auth.js mints one even when the send is\n // suppressed. Equal to the per-address send limit, which counts these rows.\n await db.execute(sql`\n DELETE FROM verification_tokens\n WHERE identifier = ${token.identifier}\n AND token NOT IN (\n SELECT token FROM verification_tokens\n WHERE identifier = ${token.identifier}\n ORDER BY expires DESC\n LIMIT ${SIGN_IN_CODE_LIVE_MAX}\n )\n `);\n return token;\n },\n\n async useVerificationToken({ identifier, token }): Promise<VerificationToken | null> {\n // Locked by too many wrong guesses: refuse even a correct code, or the cap\n // would only slow a guesser down. Checked BEFORE the delete, so a locked\n // attempt cannot burn the person's real code.\n if (await isSignInCodeLocked(identifier)) return null;\n // Single use: the row is deleted as it is read.\n const [row] = await getDb()\n .delete(verificationTokens)\n .where(and(eq(verificationTokens.identifier, identifier), eq(verificationTokens.token, token)))\n .returning();\n // A miss is a wrong typed code or a used/expired link; they carry the same\n // code, so both count.\n if (!row) await recordSignInCodeFailure(identifier);\n return row ?? null;\n },\n };\n}\n\n/** True when this address has used up its wrong guesses for the window. Fails CLOSED. */\nexport async function isSignInCodeLocked(identifier: string, now = new Date()): Promise<boolean> {\n try {\n const since = new Date(now.getTime() - SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS);\n const [row] = await getDb()\n .select({ n: count() })\n .from(signInCodeFailures)\n .where(and(eq(signInCodeFailures.identifier, identifier.toLowerCase()), gt(signInCodeFailures.failedAt, since)));\n return (row?.n ?? 0) >= SIGN_IN_CODE_WRONG_GUESS_LIMIT;\n } catch {\n return true;\n }\n}\n\n/** Counts one wrong code against this address, and clears rows older than a day. */\nexport async function recordSignInCodeFailure(identifier: string, now = new Date()): Promise<void> {\n const db = getDb();\n await db.insert(signInCodeFailures).values({ identifier: identifier.toLowerCase(), failedAt: now });\n await db.delete(signInCodeFailures).where(lt(signInCodeFailures.failedAt, new Date(now.getTime() - 24 * 60 * 60 * 1000)));\n}\n",
26
+ "lib/auth/client-ip.ts": "// The caller's IP address, for rate limiting the login-link send.\n//\n// Only headers the platform OVERWRITES are trusted. The first entry of\n// `x-forwarded-for` is whatever the caller typed, so keying a limit on it lets\n// an attacker dodge their own limit and fill someone else's. This assumes the\n// app runs on Vercel, whose edge sets `x-vercel-forwarded-for` and `x-real-ip`\n// itself. On another host, list the header that host overwrites.\n//\n// No trusted header → no address. The caller then gets no per-IP bucket and\n// only the global limit applies; one shared \"unknown\" bucket would let anyone\n// who strips headers lock everybody else out.\n\nimport { isIP } from \"node:net\";\n\nconst TRUSTED_HEADERS = [\"x-vercel-forwarded-for\", \"x-real-ip\"] as const;\n\nexport type ClientIp = {\n address: string | null;\n /** Which header answered, so a missing edge header is visible in logs. */\n source: (typeof TRUSTED_HEADERS)[number] | \"none\";\n};\n\nexport function clientIpFrom(headers: Headers): ClientIp {\n for (const name of TRUSTED_HEADERS) {\n // Vercel's value is a single address, but take the first entry defensively.\n const value = headers.get(name)?.split(\",\")[0]?.trim();\n if (value && isIP(value)) return { address: value, source: name };\n }\n return { address: null, source: \"none\" };\n}\n",
27
+ "lib/auth/hosts.ts": "// Which hosts may appear in a login link.\n//\n// Auth.js runs with `trustHost: true` and no AUTH_URL, so it builds every login\n// link from the request's Host header and validates nothing. Without this\n// check, anyone could request a link for someone else's address with a forged\n// Host, and that person would receive a genuine email pointing at the\n// attacker's server.\n//\n// The rule:\n// - A host listed in CANONICAL_HOSTS is allowed everywhere.\n// - On a production deployment, nothing else is.\n// - Off production, only LOOPBACK hosts are added (localhost, 127.0.0.1, [::1],\n// *.localhost), never \"anything\". A Vercel preview has a public URL, so\n// \"allow everything off production\" would reopen the hole there. A preview\n// that needs to send real login links lists its own host in CANONICAL_HOSTS.\n// - CANONICAL_HOSTS unset or empty means NO hosts, not all of them.\n//\n// Production is decided by VERCEL_ENV, not NODE_ENV: Vercel runs previews with\n// NODE_ENV=production.\n\ntype Env = Record<string, string | undefined>;\n\nexport function isProductionDeployment(env: Env = process.env): boolean {\n return env.VERCEL_ENV === \"production\";\n}\n\n/** Lower-cases and validates a `host[:port]` string. Returns null if malformed. */\nexport function normalizeHost(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const host = raw.trim().toLowerCase();\n // hostname or [ipv6], optional :port. Nothing else (no path, no userinfo).\n if (!/^(?:\\[[0-9a-f:.]+\\]|[a-z0-9.-]+)(?::\\d{1,5})?$/.test(host)) return null;\n return host;\n}\n\nexport function canonicalHosts(env: Env = process.env): Set<string> {\n const hosts = new Set<string>();\n for (const part of (env.CANONICAL_HOSTS ?? \"\").split(\",\")) {\n const host = normalizeHost(part);\n if (host) hosts.add(host);\n }\n return hosts;\n}\n\n/** A host only the machine running the app can reach. */\nexport function isLoopbackHost(host: string): boolean {\n const name = host.startsWith(\"[\") ? host.slice(0, host.indexOf(\"]\") + 1) : host.split(\":\")[0];\n return (\n name === \"localhost\" ||\n name === \"127.0.0.1\" ||\n name === \"[::1]\" ||\n name.endsWith(\".localhost\")\n );\n}\n\nexport function isKnownHost(rawHost: unknown, env: Env = process.env): boolean {\n const host = normalizeHost(rawHost);\n if (host === null) return false;\n if (canonicalHosts(env).has(host)) return true;\n if (isProductionDeployment(env)) return false;\n return isLoopbackHost(host);\n}\n",
28
+ "lib/auth/login-email.ts": "// The login email: a button AND the 8-digit code (lib/auth/sign-in-code.ts) for\n// typing into the installed app, where a tapped link would open the wrong browser.\n// It names the app and nothing else: never anything from the person's records.\n//\n// The button is a dark neutral with white text on purpose. A brand color behind\n// white text often fails contrast (a light green or gold does), and this is the\n// one button the person must find.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nimport { codeFromLoginUrl, formatSignInCode } from \"./sign-in-code\";\n\nexport const LOGIN_LINK_MAX_AGE_SECONDS = 60 * 60 * 24;\n\nconst INK = \"#1f2937\";\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\")\n .replace(/'/g, \"&#39;\");\n}\n\nexport function buildLoginEmail(url: string): { subject: string; text: string; html: string } {\n const subject = `Your ${SITE_NAME} login link`;\n const code = codeFromLoginUrl(url);\n const shown = code ? formatSignInCode(code) : null;\n const text = [\n `Here is your link to log in to ${SITE_NAME}:`,\n \"\",\n url,\n ...(shown ? [\"\", `Using ${SITE_NAME} from your home screen? Type this code into the app instead: ${shown}`] : []),\n \"\",\n \"It works once and expires in 24 hours.\",\n \"If you didn't ask for it, you can ignore this email; nobody can log in without it.\",\n \"\",\n `This email is from ${SITE_NAME}.`,\n ].join(\"\\n\");\n const name = escapeHtml(SITE_NAME);\n const href = escapeHtml(url);\n const codeBlock = shown\n ? `\n <p style=\"margin:0 0 8px\">Using ${name} from your home screen? Type this code into the app instead:</p>\n <p style=\"margin:0 0 24px;font-size:32px;font-weight:700;letter-spacing:4px;color:${INK};font-family:ui-monospace,Menlo,Consolas,monospace\">${escapeHtml(shown)}</p>`\n : \"\";\n const html = `<!doctype html>\n<html lang=\"en\">\n<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head>\n<body style=\"margin:0;padding:24px;background:#ffffff;font-family:system-ui,-apple-system,sans-serif;font-size:18px;line-height:1.5;color:${INK}\">\n <p style=\"margin:0 0 20px\">Here is your link to log in to ${name}:</p>\n <p style=\"margin:0 0 24px\">\n <a href=\"${href}\" style=\"display:inline-block;padding:14px 24px;background:${INK};color:#ffffff;text-decoration:none;font-weight:700;border-radius:8px\">Log in to ${name}</a>\n </p>${codeBlock}\n <p style=\"margin:0 0 12px\">It works once and expires in 24 hours.</p>\n <p style=\"margin:0 0 12px\">If you didn't ask for it, you can ignore this email; nobody can log in without it.</p>\n <p style=\"margin:24px 0 0;font-size:16px;color:#4b5563\">This email is from ${name}.</p>\n</body>\n</html>`;\n return { subject, text, html };\n}\n",
29
+ "lib/auth/rate-limit.ts": "// In-memory sliding-window rate limiter.\n//\n// Per serverless instance, so it is a first line against bursts, not a hard\n// cap: an attack spread across many cold instances partly gets through. The\n// per-EMAIL limit therefore does NOT live here; it is counted from\n// `verification_tokens`, which every instance shares (lib/auth/sign-in-policy.ts).\n//\n// Two details that matter:\n// - A rejected request is not recorded, so a steady attacker cannot keep\n// extending someone's lockout.\n// - The number of keys is capped (oldest evicted), so spraying unique keys\n// cannot grow memory without bound.\n\n/**\n * Pure: given the timestamps already in the window, may one more happen at\n * `now`? Returns the hits to keep (pruned, plus `now` if allowed).\n */\nexport function checkWindow(\n hits: readonly number[],\n limit: number,\n windowMs: number,\n now: number,\n): { allowed: boolean; hits: number[] } {\n const recent = hits.filter((t) => now - t < windowMs);\n if (recent.length >= limit) return { allowed: false, hits: recent };\n return { allowed: true, hits: [...recent, now] };\n}\n\nexport type RateLimiter = { attempt(key: string, now?: number): boolean };\n\nexport function createRateLimiter({\n limit,\n windowMs,\n maxKeys = 10_000,\n}: {\n limit: number;\n windowMs: number;\n maxKeys?: number;\n}): RateLimiter {\n const buckets = new Map<string, number[]>();\n return {\n attempt(key, now = Date.now()) {\n const result = checkWindow(buckets.get(key) ?? [], limit, windowMs, now);\n // Re-insert so Map order tracks most-recent use; evict the oldest.\n buckets.delete(key);\n buckets.set(key, result.hits);\n while (buckets.size > maxKeys) {\n const oldest = buckets.keys().next().value;\n if (oldest === undefined) break;\n buckets.delete(oldest);\n }\n return result.allowed;\n },\n };\n}\n",
30
+ "lib/auth/send-gate.ts": "// Decides whether a login email is sent, and sends it. Called by Auth.js's\n// `sendVerificationRequest` (auth.ts) with real dependencies; the tests call it\n// with fakes.\n//\n// From the outside every outcome looks the same: the person sees the same\n// \"check your email\" page whether the address can log in or not, so the page\n// can't be used to find out who has an account. That\n// is why this function NEVER throws. A provider error that escaped would turn\n// into a 500 for members only, which is exactly the leak.\n//\n// Order matters: the cheap in-memory checks run before anything touches the\n// database, so a flood of requests cannot keep the database awake.\n//\n// Every refusal is logged with the host and the address, because a suppressed\n// email looks exactly like a broken mailer to the person waiting for it.\n\nimport type { SendEmailParams, SendEmailResult } from \"@/lib/email/mailer\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { isKnownHost, isLoopbackHost, normalizeHost } from \"./hosts\";\nimport { buildLoginEmail } from \"./login-email\";\nimport type { RateLimiter } from \"./rate-limit\";\nimport { canUserSignIn, evaluateMagicLinkQuota, type SignInCandidate } from \"./sign-in-policy\";\n\nexport type SendGateDeps = {\n env: Record<string, string | undefined>;\n findUser(email: string): Promise<SignInCandidate | null>;\n /** Outstanding unexpired tokens, counting only addresses that can log in. */\n countOutstanding(email: string): Promise<{ forEmail: number; global: number }>;\n sendEmail(params: SendEmailParams): Promise<SendEmailResult>;\n ipLimiter: RateLimiter;\n instanceLimiter: RateLimiter;\n log: Pick<Console, \"warn\" | \"error\">;\n};\n\nexport type SendOutcome =\n | \"sent\"\n | \"unknown-host\"\n | \"rate-limited-ip\"\n | \"rate-limited-instance\"\n | \"not-allowed\"\n | \"quota-per-email\"\n | \"quota-global\"\n | \"lookup-failed\"\n | \"not-configured\"\n | \"provider-rejected\";\n\nexport async function deliverLoginLink(\n { identifier, url, headers }: { identifier: string; url: string; headers: Headers },\n deps: SendGateDeps,\n): Promise<SendOutcome> {\n const email = identifier.toLowerCase();\n const host = normalizeHost(safeHost(url)) ?? \"(unparseable)\";\n const ip = clientIpFrom(headers);\n const context = { host, email, ip: ip.address, ipSource: ip.source };\n const suppress = (outcome: SendOutcome, why: string): SendOutcome => {\n deps.log.warn(`[auth] login email SUPPRESSED (${outcome}): ${why}. No email sent.`, context);\n return outcome;\n };\n\n // 1. A link must point at a host we serve. Fail closed: send\n // nothing rather than rewriting the link to another host.\n if (!isKnownHost(host, deps.env)) {\n return suppress(\"unknown-host\", \"the link's host is not in CANONICAL_HOSTS\");\n }\n\n // 2. In-memory limits, before any database read.\n if (ip.address && !deps.ipLimiter.attempt(ip.address)) {\n return suppress(\"rate-limited-ip\", \"too many login requests from this IP\");\n }\n if (!deps.instanceLimiter.attempt(\"global\")) {\n return suppress(\"rate-limited-instance\", \"too many login requests on this server instance\");\n }\n\n // 3. Is this a person who can log in? Unknown addresses stop here, BEFORE\n // the quota, so made-up addresses never use up anyone's budget.\n let quota: { forEmail: number; global: number };\n try {\n const user = await deps.findUser(email);\n if (!canUserSignIn(user)) {\n return suppress(\"not-allowed\", \"no active, invited account with this address\");\n }\n quota = await deps.countOutstanding(email);\n } catch (error) {\n deps.log.error(\"[auth] login email SUPPRESSED (lookup-failed): database error.\", context, error);\n return \"lookup-failed\";\n }\n\n // 4. Shared limits, counted from verification_tokens.\n const verdict = evaluateMagicLinkQuota({\n outstandingForEmail: quota.forEmail,\n outstandingGlobal: quota.global,\n });\n if (!verdict.allowed) {\n return verdict.reason === \"per-email\"\n ? suppress(\"quota-per-email\", \"too many unused login links for this address\")\n : suppress(\"quota-global\", \"too many unused login links across all accounts\");\n }\n\n // 5. Send. A provider error is reported and swallowed, never thrown.\n const message = buildLoginEmail(url);\n let result: SendEmailResult;\n try {\n result = await deps.sendEmail({ to: email, ...message });\n } catch (error) {\n deps.log.error(\n \"[auth] login email REJECTED by the mail provider. Check, in this order: the SES \" +\n \"sender identity is verified IN SES_REGION (identities are per region); the address \" +\n \"is not on the SES account suppression list; the SES keys were not rotated.\",\n context,\n error,\n );\n return \"provider-rejected\";\n }\n\n if (!result.sent) {\n deps.log.warn(`[auth] login email NOT sent: mail is not configured (${result.skippedReason}).`, context);\n // So login can be tested with no mail provider. Only on a loopback\n // host: preview and production logs are shipped and kept, and a login link\n // is a live credential.\n if (isLoopbackHost(host)) {\n deps.log.warn(`[auth] LOCAL DEV ONLY — login link for ${email}:\\n${url}`);\n }\n return \"not-configured\";\n }\n return \"sent\";\n}\n\nfunction safeHost(url: string): string | null {\n try {\n return new URL(url).host;\n } catch {\n return null;\n }\n}\n",
31
+ "lib/auth/session-config.ts": "// Session settings, declared explicitly.\n//\n// - strategy \"jwt\": with an adapter configured, Auth.js would otherwise default\n// to database sessions, one query per request, which keeps a scale-to-zero\n// database (Neon) awake and burns its compute allowance.\n// - maxAge 7 days of INACTIVITY. The cookie is refreshed as the app is used, so\n// someone who opens the app every day is never logged out by this.\n//\n// Kept in its own dependency-free module so a future middleware Auth.js\n// instance imports the same object rather than silently using the 30-day default.\n\nexport const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;\n\nexport const sessionConfig = {\n strategy: \"jwt\",\n maxAge: SESSION_MAX_AGE_SECONDS,\n} as const;\n",
32
+ "lib/auth/sign-in-code.ts": "// The typed login code.\n//\n// WHY: an app installed on an iPhone home screen keeps its cookies apart from\n// Safari and Chrome, and a login link tapped in Mail opens in the phone's default\n// browser. So the link logs in the browser, not the installed app. A code the\n// person TYPES into the app logs in exactly where they are.\n//\n// HOW: the email provider's generateVerificationToken returns this code, so the\n// SAME secret is the link's `token=` and the code printed in the email. Typing it\n// just opens the address the link would have (buildCodeCallbackPath). No second\n// token store, no custom route: same single use, same allowlist, same audit.\n//\n// 🔴 WHY 8 DIGITS: Auth.js stores a token BEFORE our send gate decides to send,\n// so a suppressed request still leaves a live code behind; an attacker can mint\n// codes for an address without its owner getting any email. The guards\n// (lib/auth/adapter.ts): at most SIGN_IN_CODE_LIVE_MAX live codes per address,\n// and at most SIGN_IN_CODE_WRONG_GUESS_LIMIT wrong guesses per address per hour,\n// counted in the database (sign_in_code_failures) so every server instance\n// shares the count, fail-closed. 5 live × 240 guesses/day over 10^8 codes is\n// about 0.4% per YEAR of continuous invisible guessing; 6 digits would be ~1%\n// per WEEK.\n//\n// Pure (Web Crypto only), so the browser form and tests can import it.\n\nimport { MAX_OUTSTANDING_PER_EMAIL } from \"./sign-in-policy\";\n\nexport const SIGN_IN_CODE_LENGTH = 8;\n\n/**\n * Newest codes kept per address. EQUAL to the per-address send limit on purpose:\n * that limit counts live tokens, so keeping fewer would silently switch it off.\n */\nexport const SIGN_IN_CODE_LIVE_MAX = MAX_OUTSTANDING_PER_EMAIL;\n\n/** Wrong codes (or used/old links) allowed per address per window before locking. */\nexport const SIGN_IN_CODE_WRONG_GUESS_LIMIT = 10;\nexport const SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS = 60 * 60 * 1000;\n\n/**\n * A uniformly random 8-digit code (leading zeros kept). Rejection sampling, not\n * `% 1e8` on a raw Uint32, which would make low codes slightly likelier.\n */\nexport function generateSignInCode(): string {\n const space = 10 ** SIGN_IN_CODE_LENGTH;\n const limit = Math.floor(0x1_0000_0000 / space) * space;\n const buf = new Uint32Array(1);\n for (;;) {\n crypto.getRandomValues(buf);\n if (buf[0] < limit) return String(buf[0] % space).padStart(SIGN_IN_CODE_LENGTH, \"0\");\n }\n}\n\n/** \"12345678\" → \"1234 5678\", as the email prints it. */\nexport function formatSignInCode(code: string): string {\n const half = SIGN_IN_CODE_LENGTH / 2;\n return `${code.slice(0, half)} ${code.slice(half)}`;\n}\n\n/**\n * What a person typed → the bare code, or null. Spaces, dashes and dots are\n * dropped; anything else, or the wrong number of digits, is refused in the\n * browser so a typo doesn't spend one of the address's guesses.\n */\nexport function normalizeSignInCode(input: string): string | null {\n const digits = input.replace(/[\\s.\\-–—]/g, \"\");\n return new RegExp(`^\\\\d{${SIGN_IN_CODE_LENGTH}}$`).test(digits) ? digits : null;\n}\n\n/** The address the email's button opens, rebuilt from a typed code. Relative: stays in this app. */\nexport function buildCodeCallbackPath(email: string, code: string): string {\n const params = new URLSearchParams({ token: code, email: email.trim().toLowerCase() });\n return `/api/auth/callback/email?${params}`;\n}\n\n/** The code inside a login URL, if it is one (the email prints it beside the button). */\nexport function codeFromLoginUrl(url: string): string | null {\n try {\n return normalizeSignInCode(new URL(url).searchParams.get(\"token\") ?? \"\");\n } catch {\n return null;\n }\n}\n",
33
+ "lib/auth/sign-in-policy.ts": "// Who may log in, and how many login links may be outstanding.\n//\n// Login is invite-only. The allowlist is the `users.sign_in_enabled` column, not\n// an env var, so access can be granted in the app without a redeploy. There is\n// no env-var grant: the first owner is created by scripts/provision-user.ts with\n// sign-in on.\n//\n// canUserSignIn() is the ONE predicate. The adapter, the send gate and the\n// current-user helper all call it (test/auth-guards.test.ts checks the call sites).\n\nexport type SignInCandidate = {\n isActive: boolean;\n signInEnabled: boolean;\n tenantStatus: string;\n};\n\nexport function canUserSignIn(user: SignInCandidate | null | undefined): boolean {\n if (!user) return false;\n // Only exactly \"active\". An unknown status denies.\n return user.isActive && user.signInEnabled && user.tenantStatus === \"active\";\n}\n\n/**\n * Login links still outstanding, counted from `verification_tokens` (shared by\n * every serverless instance). This bounds unused links, not attempts per hour,\n * so it pairs with the in-memory per-IP limiter.\n *\n * Both counts must include ONLY addresses that can log in. Counting unknown\n * addresses would let anyone fill the global budget with made-up emails and\n * silently block every real login for a day.\n *\n * Accurate to ±1: Auth.js writes the token concurrently with the send, so the\n * current request's own row may or may not be counted yet. Don't \"fix\" that by\n * changing >= to >.\n */\nexport const MAX_OUTSTANDING_PER_EMAIL = 5;\nexport const MAX_OUTSTANDING_GLOBAL = 200;\n\nexport function evaluateMagicLinkQuota({\n outstandingForEmail,\n outstandingGlobal,\n}: {\n outstandingForEmail: number;\n outstandingGlobal: number;\n}): { allowed: true } | { allowed: false; reason: \"per-email\" | \"global\" } {\n if (outstandingForEmail >= MAX_OUTSTANDING_PER_EMAIL) return { allowed: false, reason: \"per-email\" };\n if (outstandingGlobal >= MAX_OUTSTANDING_GLOBAL) return { allowed: false, reason: \"global\" };\n return { allowed: true };\n}\n\n/** Lower-cased, trimmed, and shaped like an address; otherwise null. */\nexport function normalizeEmail(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const email = raw.normalize(\"NFKC\").trim().toLowerCase();\n if (email.length > 254) return null;\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : null;\n}\n",
34
+ "lib/current-user.ts": "// The ONLY way app code asks \"who is logged in, and which account is theirs?\"\n//\n// The tenant comes from the logged-in user's own row, never from a URL or a\n// form field. Every query on account data filters by the returned `tenantId`.\n//\n// This re-reads the user on each request, so turning off a person's sign-in or\n// deactivating them takes effect at once, even though their session cookie is\n// still valid.\n\nimport \"server-only\";\n\nimport { eq } from \"drizzle-orm\";\nimport { redirect } from \"next/navigation\";\n\nimport { auth } from \"@/auth\";\nimport { getDb } from \"@/db/client\";\nimport { tenants, users } from \"@/db/schema\";\nimport { isPhantomUser } from \"@/lib/auth/adapter\";\nimport { canUserSignIn } from \"@/lib/auth/sign-in-policy\";\nimport { AGREE_PATH, LOGIN_PATH } from \"@/lib/routes\";\nimport { hasAgreedToCurrentTerms } from \"@/lib/terms\";\n\nexport type CurrentUser = {\n user: typeof users.$inferSelect;\n tenant: typeof tenants.$inferSelect;\n tenantId: string;\n};\n\nexport async function getCurrentUser(): Promise<CurrentUser | null> {\n const session = await auth();\n const userId = session?.user?.id;\n if (!userId || isPhantomUser(userId)) return null;\n\n const [row] = await getDb()\n .select({ user: users, tenant: tenants })\n .from(users)\n .innerJoin(tenants, eq(users.tenantId, tenants.id))\n .where(eq(users.id, userId))\n .limit(1);\n if (!row) return null;\n const allowed = canUserSignIn({\n isActive: row.user.isActive,\n signInEnabled: row.user.signInEnabled,\n tenantStatus: row.tenant.status,\n });\n if (!allowed) return null;\n return { user: row.user, tenant: row.tenant, tenantId: row.tenant.id };\n}\n\n/**\n * Logged in, but maybe not yet agreed to the Terms. Only for /agree and its\n * submit handler, which must be reachable before agreeing. Every other page\n * uses requireAgreedUser().\n */\nexport async function requireCurrentUser(): Promise<CurrentUser> {\n const current = await getCurrentUser();\n if (!current) redirect(LOGIN_PATH);\n return current;\n}\n\n/**\n * For every logged-in PAGE. Not logged in → /login; not agreed to the current\n * Terms (lib/terms.ts) → /agree, whatever they asked for.\n */\nexport async function requireAgreedUser(): Promise<CurrentUser> {\n const current = await requireCurrentUser();\n if (!hasAgreedToCurrentTerms(current.user)) redirect(AGREE_PATH);\n return current;\n}\n\n/**\n * For every ROUTE HANDLER and server action that acts for a logged-in person.\n * A page guard alone is decorative: a direct POST skips the page. Returns null\n * for \"not logged in\" and \"not agreed\" alike; answer null with\n * seeOther(AGREE_PATH) (a logged-out visitor is then sent on to /login).\n *\n * Never use it on a caller that is not a person: webhooks, cron and job\n * endpoints, /api/health, /api/auth/*, and service-token APIs other apps call.\n * They have no session, and a redirect breaks them silently.\n */\nexport async function getAgreedUser(): Promise<CurrentUser | null> {\n const current = await getCurrentUser();\n if (!current || !hasAgreedToCurrentTerms(current.user)) return null;\n return current;\n}\n",
35
+ "lib/http.ts": "// Small helpers for the route handlers that receive this app's forms.\n//\n// Forms post to route handlers, not Server Actions. A Server Action is\n// addressed by an id that changes with every build, so a page left open in a\n// tab (or restored from the back/forward cache) would submit into nothing and\n// the person would only see that the email never came. A route handler's address is its URL, which every build has.\n//\n// A route handler gets no cross-site check from the framework, so it calls\n// isSameOriginPost() itself.\n\n/**\n * True unless the request carries an Origin from a different host. Origin is\n * checked only when present: some browsers omit it on same-origin form posts,\n * and refusing those would break the form for real people.\n */\nexport function isSameOriginPost(request: Request): boolean {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return true;\n const host = (request.headers.get(\"x-forwarded-host\") ?? request.headers.get(\"host\"))?.toLowerCase();\n if (!host) return false;\n try {\n return new URL(origin).host.toLowerCase() === host;\n } catch {\n return false; // includes the literal \"null\"\n }\n}\n\n/**\n * 303 to a path on this site. A RELATIVE Location keeps the browser on the\n * host it is already on, rather than one built from a request header.\n */\nexport function seeOther(path: string): Response {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) throw new Error(\"seeOther takes a site path\");\n return new Response(null, { status: 303, headers: { Location: path } });\n}\n",
36
+ "lib/provisioning.ts": "// Argument parsing for scripts/provision-user.ts. Pure, so it is unit-tested.\n// Relative .ts imports only: plain Node runs the script that imports this.\n\nimport { normalizeEmail } from \"./auth/sign-in-policy.ts\";\n\nexport type ProvisionArgs = {\n email: string;\n firstName: string;\n /** Null for someone with one name. Names are never split from a full name. */\n lastName: string | null;\n /** The account (tenant) this person owns. Defaults to their own name. */\n accountName: string;\n};\n\nconst MAX_NAME = 80;\n\n/** Trims and collapses spaces; null when empty or too long. */\nfunction tidy(value: string | undefined): string | null {\n if (value === undefined) return null;\n const out = value.normalize(\"NFC\").replace(/\\s+/g, \" \").trim();\n return out.length >= 1 && out.length <= MAX_NAME ? out : null;\n}\n\nexport function parseProvisionArgs(\n argv: readonly string[],\n): { ok: true; value: ProvisionArgs } | { ok: false; error: string } {\n const flags = new Map<string, string>();\n for (let i = 0; i < argv.length; i += 2) {\n const flag = argv[i];\n const value = argv[i + 1];\n if (!flag?.startsWith(\"--\") || value === undefined || value.startsWith(\"--\")) {\n return { ok: false, error: `expected \"--flag value\" pairs, got \"${flag ?? \"\"}\"` };\n }\n flags.set(flag.slice(2), value);\n }\n\n const email = normalizeEmail(flags.get(\"email\"));\n if (!email) return { ok: false, error: \"--email must be an email address\" };\n\n if (flags.has(\"name\")) return { ok: false, error: \"use --first-name and --last-name, not --name\" };\n const firstName = tidy(flags.get(\"first-name\"));\n if (!firstName) return { ok: false, error: `--first-name is required (up to ${MAX_NAME} characters)` };\n const lastRaw = flags.get(\"last-name\");\n const lastName = tidy(lastRaw);\n if (lastRaw !== undefined && !lastName) return { ok: false, error: `--last-name must be 1 to ${MAX_NAME} characters` };\n\n const accountRaw = flags.get(\"account-name\");\n const accountName = accountRaw === undefined ? displayName(firstName, lastName) : tidy(accountRaw);\n if (!accountName) return { ok: false, error: `--account-name must be 1 to ${MAX_NAME} characters` };\n\n return { ok: true, value: { email, firstName, lastName, accountName } };\n}\n\n/** First and last name joined. Only ever joined, never split. */\nexport function displayName(firstName: string, lastName: string | null): string {\n return lastName ? `${firstName} ${lastName}` : firstName;\n}\n",
37
+ "lib/routes.ts": "// Where login and logout land. Client-safe: imports nothing, because the login\n// form (a client component) reads these too.\n//\n// POST_LOGIN_DESTINATION is never a public page. A page that always shows a\n// \"Log in\" link, used as the post-login target, makes a returning user log in\n// twice or loop forever. test/auth-guards.test.ts pins this.\n\n/** The first screen a logged-in person sees. Replace with the app's real home. */\nexport const POST_LOGIN_DESTINATION = \"/dashboard\";\n\n/** Must render without a session, or logging out bounces. */\nexport const POST_LOGOUT_DESTINATION = \"/login\";\n\nexport const LOGIN_PATH = \"/login\";\nexport const CHECK_EMAIL_PATH = \"/login/check-email\";\n\n/** Where a logged-in person who has not agreed to the current Terms is sent, whatever they asked for. */\nexport const AGREE_PATH = \"/agree\";\nexport const TERMS_PATH = \"/terms\";\nexport const PRIVACY_PATH = \"/privacy\";\n\n/** Pages a visitor without a session can see. Add each new public page here. */\nexport const PUBLIC_ROUTES = [\n \"/\",\n \"/guide\",\n \"/guide/whats-new\",\n LOGIN_PATH,\n CHECK_EMAIL_PATH,\n \"/login/error\",\n TERMS_PATH,\n PRIVACY_PATH,\n] as const;\n",
38
+ "lib/terms.ts": "// The Terms every person must agree to before using the app: the version in\n// force, who runs the app, and the checks. Pure (no database), so it is\n// unit-tested and safe to import from a page, a route handler or a test.\n//\n// Why a VERSION and not a yes/no flag: when the wording changes, bump\n// CURRENT_TERMS_VERSION and everyone is asked again on their next visit, while\n// the record of what each person agreed to (and when) stays exact. Agreements\n// are recorded per USER, not per account, so a second person on an account\n// agrees for themselves.\n//\n// The wording lives in components/TermsText.tsx and components/PrivacyText.tsx.\n// ⚠️ Change the wording? Bump CURRENT_TERMS_VERSION AND TERMS_LAST_MODIFIED in\n// the same commit.\n\n/** The date the current wording took effect (YYYY-MM-DD). Bump it whenever the Terms wording changes. */\nexport const CURRENT_TERMS_VERSION = \"{{date}}\";\n\n/** When the Terms and Privacy pages were first published (YYYY-MM-DD). Never changes. */\nexport const TERMS_CREATED = \"{{date}}\";\n\n/** When either page's wording last changed (YYYY-MM-DD). */\nexport const TERMS_LAST_MODIFIED = \"{{date}}\";\n\n// ── Who runs this app. Replace all three before launch. ─────────────────────\n// The OPERATOR is whoever really runs the app and is responsible for it, which\n// is not always the brand on the page. These show on /terms and /privacy until\n// they are replaced, on purpose, so an unfilled page is obvious.\n\n/** The organization that runs the app, for example \"Zero2Webmaster LLC\". */\nexport const TERMS_OPERATOR = \"OPERATOR\";\n\n/** The operator's website. */\nexport const TERMS_OPERATOR_URL = \"https://OPERATOR-WEBSITE\";\n\n/** The page people use to contact the operator. The only contact detail on the Terms and Privacy pages. */\nexport const TERMS_CONTACT_URL = \"https://OPERATOR-WEBSITE/contact\";\n\nconst MONTHS = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\n/**\n * \"2026-11-04\" → \"November 4, 2026\". Read from the string itself, never through\n * a Date, so the label can't shift a day in another time zone.\n */\nexport function formatTermsDate(iso: string): string {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(iso);\n if (!m) return iso;\n const month = MONTHS[Number(m[2]) - 1];\n if (!month) return iso;\n return `${month} ${Number(m[3])}, ${m[1]}`;\n}\n\n/** Has this person agreed to the wording in force now? */\nexport function hasAgreedToCurrentTerms(user: { termsVersion: string | null }): boolean {\n return user.termsVersion === CURRENT_TERMS_VERSION;\n}\n\n/**\n * The agree form posts `agree=yes` from a required checkbox, plus the version\n * the person was shown. Both must match: a page left open across a wording\n * change must not record agreement to text the person never saw.\n */\nexport function parseAgreement({ agree, version }: { agree: unknown; version: unknown }): \"ok\" | \"unchecked\" | \"stale\" {\n if (agree !== \"yes\") return \"unchecked\";\n if (version !== CURRENT_TERMS_VERSION) return \"stale\";\n return \"ok\";\n}\n",
39
+ "scripts/provision-user.ts": "// Invite someone: create their account (tenant) and their owner login, with\n// sign-in ON. Login is invite-only, and this is the only place an account is\n// created; clicking a login link never creates one.\n//\n// Usage (Node 22.18+ runs TypeScript directly):\n// node --env-file=.env.local scripts/provision-user.ts --email person@example.com --first-name Pat --last-name Smith\n//\n// --last-name is optional (some people have one name). --account-name names the\n// account; it defaults to the person's name. Run against production by pointing\n// DATABASE_URL at it.\n//\n// Imports use relative .ts paths (no \"@/\" alias) so plain Node can run this.\n\nimport { neonConfig, Pool } from \"@neondatabase/serverless\";\nimport { eq } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/neon-serverless\";\nimport ws from \"ws\";\n\nimport { tenants, users } from \"../db/schema.ts\";\nimport { displayName, parseProvisionArgs } from \"../lib/provisioning.ts\";\n\nif (typeof WebSocket === \"undefined\") neonConfig.webSocketConstructor = ws as unknown as typeof WebSocket;\n\nasync function main(): Promise<void> {\n const args = parseProvisionArgs(process.argv.slice(2));\n if (!args.ok) {\n console.error(`provision-user: ${args.error}`);\n process.exit(2);\n }\n const { email, firstName, lastName, accountName } = args.value;\n const name = displayName(firstName, lastName);\n const url = process.env.DATABASE_URL;\n if (!url) {\n console.error(\"provision-user: DATABASE_URL is not set.\");\n process.exit(2);\n }\n\n const pool = new Pool({ connectionString: url, max: 1 });\n const db = drizzle(pool);\n try {\n const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.email, email)).limit(1);\n if (existing) {\n console.error(`provision-user: ${email} already has a login (user ${existing.id}). Nothing changed.`);\n process.exit(1);\n }\n\n const created = await db.transaction(async (tx) => {\n const [tenant] = await tx.insert(tenants).values({ name: accountName }).returning({ id: tenants.id });\n const [user] = await tx\n .insert(users)\n .values({ tenantId: tenant.id, email, name, firstName, lastName, role: \"owner\", isActive: true, signInEnabled: true })\n .returning({ id: users.id });\n return { tenantId: tenant.id, userId: user.id };\n });\n\n // Read back rather than assume: an owner created with sign-in off could\n // never log in to turn it on.\n const [check] = await db.select().from(users).where(eq(users.id, created.userId)).limit(1);\n if (!check?.signInEnabled || !check.isActive) {\n throw new Error(\"the new owner was not saved with sign-in on\");\n }\n console.log(`Created account ${created.tenantId} with owner ${email} (user ${created.userId}), sign-in on.`);\n console.log(\"They can now ask for a login link at /login on the deployed app.\");\n } finally {\n await pool.end();\n }\n}\n\nmain().catch((error) => {\n console.error(\"provision-user failed:\", error instanceof Error ? error.message : error);\n process.exit(1);\n});\n",
40
+ "snippets/globals-login.css": "\n/* Login pages (app/login, app/dashboard). Plain, readable, and on the brand\n pair already measured in test/contrast.test.ts: the button is\n --brand-primary with --brand-on-primary text. */\n.page {\n max-width: 36rem;\n margin: 0 auto;\n padding: 2rem 1rem;\n}\n\n.stack {\n display: grid;\n gap: 1rem;\n margin: 1.5rem 0;\n}\n\n.btn-primary {\n display: inline-block;\n padding: 0.75rem 1.5rem;\n border: 0;\n border-radius: 8px;\n background: var(--brand-primary);\n color: var(--brand-on-primary);\n font: inherit;\n font-weight: 700;\n text-decoration: none;\n cursor: pointer;\n justify-self: start;\n}\n\n.btn-primary:focus-visible {\n outline: 3px solid var(--brand-focus);\n outline-offset: 2px;\n}\n\n.text-link {\n color: var(--brand-ink);\n text-decoration: underline;\n}\n\n.fine-print {\n font-size: 1rem;\n}\n\n/* Body ink and a thick bar, not a red tint: every color in this file is held\n to a measured contrast pair (test/contrast.test.ts), and role=\"alert\" plus\n the bold text carry the meaning, which color alone must not. */\n.form-error {\n margin: 0;\n padding: 0.75rem 1rem;\n border-left: 6px solid var(--brand-ink);\n color: var(--brand-ink);\n font-weight: 700;\n}\n\n.code-form {\n margin-top: 2rem;\n}\n\n.code-form h2 {\n font-size: 1.25rem;\n margin: 0;\n}\n\n.code-input {\n font-family: ui-monospace, Menlo, Consolas, monospace;\n font-size: 1.5rem;\n letter-spacing: 0.15em;\n max-width: 12ch;\n}\n\n.typed-address {\n overflow-wrap: anywhere;\n}\n\n/* The Terms gate (app/agree) and the legal pages (app/terms, app/privacy).\n Same measured pairs as above: --brand-ink on the page, the button pair. */\n.btn-secondary {\n display: inline-block;\n padding: 0.75rem 1.5rem;\n border: 2px solid var(--brand-ink);\n border-radius: 8px;\n background: transparent;\n color: var(--brand-ink);\n font: inherit;\n font-weight: 700;\n cursor: pointer;\n justify-self: start;\n}\n\n.btn-secondary:focus-visible {\n outline: 3px solid var(--brand-focus);\n outline-offset: 2px;\n}\n\n.check-row {\n display: flex;\n gap: 0.75rem;\n align-items: flex-start;\n}\n\n.check-row input {\n width: 1.5rem;\n height: 1.5rem;\n margin-top: 0.15rem;\n flex: none;\n}\n\n.terms-text h2 {\n font-size: 1.25rem;\n margin: 1.75rem 0 0.5rem;\n}\n\n.terms-text a {\n color: var(--brand-ink);\n text-decoration: underline;\n}\n\n.legal-end {\n margin-top: 2.5rem;\n}\n\n/* Every page's footer (components/SiteFooter.tsx). Each link is a 48px tap target. */\n.site-footer {\n max-width: 36rem;\n margin: 3rem auto 0;\n padding: 1rem;\n}\n\n.site-footer nav {\n display: flex;\n gap: 1.5rem;\n}\n\n.site-footer a {\n display: inline-flex;\n align-items: center;\n min-height: 48px;\n color: var(--brand-ink);\n text-decoration: underline;\n}\n",
41
+ "test/auth-adapter.test.ts": "/**\n * The Auth.js adapter (lib/auth/adapter.ts) against a real in-memory Postgres.\n */\nimport { eq } from \"drizzle-orm\";\nimport { beforeAll, describe, expect, it, vi } from \"vitest\";\n\nimport { tenants, users, verificationTokens } from \"@/db/schema\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\n\nimport { countOutstandingLoginLinks, createAdapter, PHANTOM_USER_ID } from \"@/lib/auth/adapter\";\n\nlet db: TestDb;\nlet activeId: string;\nconst adapter = createAdapter();\nconst tomorrow = () => new Date(Date.now() + 86_400_000);\n\nbeforeAll(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n const [tenant] = await db.insert(tenants).values({ name: \"T\" }).returning();\n const [active] = await db\n .insert(users)\n .values({ tenantId: tenant.id, email: \"active@example.com\", signInEnabled: true })\n .returning();\n activeId = active.id;\n await db.insert(users).values({ tenantId: tenant.id, email: \"not-invited@example.com\", signInEnabled: false });\n});\n\ndescribe(\"getUserByEmail\", () => {\n it(\"returns the real user for an invited, active address\", async () => {\n expect((await adapter.getUserByEmail!(\"Active@Example.com\"))?.id).toBe(activeId);\n });\n\n it(\"returns the PHANTOM, never null, for unknown and not-invited addresses\", async () => {\n for (const email of [\"nobody@example.com\", \"not-invited@example.com\"]) {\n const user = await adapter.getUserByEmail!(email);\n expect(user?.id, email).toBe(PHANTOM_USER_ID);\n }\n });\n});\n\ndescribe(\"user methods\", () => {\n it(\"updateUser receives only { id, emailVerified } and still returns the right person\", async () => {\n const updated = await adapter.updateUser!({ id: activeId, emailVerified: new Date() });\n expect(updated.email).toBe(\"active@example.com\");\n const [row] = await db.select().from(users).where(eq(users.id, activeId));\n expect(row.emailVerifiedAt).not.toBeNull();\n });\n\n it(\"refuses to create users, or to update the phantom\", async () => {\n await expect(adapter.createUser!({ id: \"x\", email: \"new@example.com\", emailVerified: null })).rejects.toThrow();\n await expect(adapter.updateUser!({ id: PHANTOM_USER_ID, emailVerified: new Date() })).rejects.toThrow();\n });\n\n it(\"getUser returns nobody for the phantom\", async () => {\n expect(await adapter.getUser!(PHANTOM_USER_ID)).toBeNull();\n expect((await adapter.getUser!(activeId))?.email).toBe(\"active@example.com\");\n });\n});\n\ndescribe(\"tokens\", () => {\n it(\"a token can be used exactly once\", async () => {\n await adapter.createVerificationToken!({ identifier: \"active@example.com\", token: \"once\", expires: tomorrow() });\n expect(await adapter.useVerificationToken!({ identifier: \"active@example.com\", token: \"once\" })).not.toBeNull();\n expect(await adapter.useVerificationToken!({ identifier: \"active@example.com\", token: \"once\" })).toBeNull();\n });\n\n it(\"the global count ignores tokens for addresses that can't log in\", async () => {\n await db.delete(verificationTokens);\n for (let i = 0; i < 30; i++) {\n await db.insert(verificationTokens).values({ identifier: `fake${i}@example.com`, token: `f${i}`, expires: tomorrow() });\n }\n await db.insert(verificationTokens).values({ identifier: \"not-invited@example.com\", token: \"n\", expires: tomorrow() });\n await db.insert(verificationTokens).values({ identifier: \"active@example.com\", token: \"a\", expires: tomorrow() });\n await db\n .insert(verificationTokens)\n .values({ identifier: \"active@example.com\", token: \"old\", expires: new Date(Date.now() - 1000) });\n expect(await countOutstandingLoginLinks(\"active@example.com\")).toEqual({ forEmail: 1, global: 1 });\n });\n});\n",
42
+ "test/auth-flow.test.ts": "/**\n * The whole login flow, end to end, through Auth.js's real handlers and a real\n * (in-memory) Postgres built from db/schema.ts: request a link, read the\n * email, click the link, get a session. Only the mailer is replaced, so the\n * test can read the email instead of sending it.\n *\n * The negative cases matter as much as the happy path: an unknown address and\n * a forged host must get the SAME response as a real account, with nothing\n * sent and no session.\n */\nimport { eq } from \"drizzle-orm\";\nimport { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { auditEvents, signInCodeFailures, tenants, users, verificationTokens } from \"@/db/schema\";\nimport { buildCodeCallbackPath, SIGN_IN_CODE_LIVE_MAX, SIGN_IN_CODE_WRONG_GUESS_LIMIT } from \"@/lib/auth/sign-in-code\";\nimport { POST_LOGIN_DESTINATION } from \"@/lib/routes\";\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({\n db: null as unknown,\n sent: [] as { to: string; subject: string; text: string; html?: string }[],\n}));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/lib/email/mailer\", () => ({\n sendEmail: async (message: { to: string; subject: string; text: string; html?: string }) => {\n h.sent.push(message);\n return { sent: true };\n },\n}));\n\nconst HOST = \"app.example.test\";\nconst ORIGIN = `https://${HOST}`;\nconst MEMBER = \"pat@example.com\";\nlet db: TestDb;\nlet memberId: string;\nlet handlers: typeof import(\"@/auth\").handlers;\n\n/** A minimal cookie jar: name → value, from each response's Set-Cookie. */\nclass Jar {\n private cookies = new Map<string, string>();\n take(res: Response) {\n for (const line of res.headers.getSetCookie()) {\n const [pair] = line.split(\";\");\n const i = pair.indexOf(\"=\");\n const name = pair.slice(0, i);\n const value = pair.slice(i + 1);\n if (value === \"\" || /max-age=0/i.test(line)) this.cookies.delete(name);\n else this.cookies.set(name, value);\n }\n }\n header() {\n return [...this.cookies].map(([k, v]) => `${k}=${v}`).join(\"; \");\n }\n has(name: string) {\n return this.cookies.has(name);\n }\n}\n\nasync function call(url: string, jar: Jar, init: { method?: string; form?: Record<string, string> } = {}) {\n const headers = new Headers({ cookie: jar.header(), host: new URL(url).host, \"x-real-ip\": \"203.0.113.7\" });\n let body: string | undefined;\n if (init.form) {\n headers.set(\"content-type\", \"application/x-www-form-urlencoded\");\n body = new URLSearchParams(init.form).toString();\n }\n const req = new Request(url, { method: init.method ?? \"GET\", headers, body, redirect: \"manual\" });\n const res = await (req.method === \"POST\" ? handlers.POST : handlers.GET)(req as never);\n jar.take(res);\n return res;\n}\n\n/** Requests a login link the way the browser form does, on the given origin. */\nasync function requestLink(email: string, origin = ORIGIN) {\n const jar = new Jar();\n const csrf = await call(`${origin}/api/auth/csrf`, jar);\n const { csrfToken } = (await csrf.json()) as { csrfToken: string };\n const res = await call(`${origin}/api/auth/signin/email`, jar, {\n method: \"POST\",\n form: { csrfToken, email, callbackUrl: `${origin}${POST_LOGIN_DESTINATION}` },\n });\n // Auth.js answers with its own /api/auth/verify-request, which forwards to\n // pages.verifyRequest. Follow that hop so the test sees what the browser does.\n const first = res.headers.get(\"location\");\n const hop = first?.includes(\"/api/auth/verify-request\") ? await call(first, jar) : null;\n return { jar, res, location: hop?.headers.get(\"location\") ?? first };\n}\n\nfunction linkIn(text: string): string {\n const match = text.match(/https?:\\/\\/\\S+\\/api\\/auth\\/callback\\/email\\S+/);\n if (!match) throw new Error(\"no login link in the email\");\n return match[0];\n}\n\nconst sessionCookie = (jar: Jar) => jar.has(\"__Secure-authjs.session-token\");\n\n/** The 8-digit code printed in the email, as the person reads it (\"1234 5678\"). */\nfunction codeIn(text: string): string {\n const match = text.match(/type this code into the app instead: (\\d{4} \\d{4})/i);\n if (!match) throw new Error(\"no login code in the email\");\n return match[1].replace(\" \", \"\");\n}\n\nasync function invite(email: string) {\n const [tenant] = await db.insert(tenants).values({ name: email }).returning();\n await db.insert(users).values({ tenantId: tenant.id, email, role: \"owner\", signInEnabled: true });\n}\n\nbeforeAll(async () => {\n vi.stubEnv(\"AUTH_SECRET\", \"test-secret-test-secret-test-secret-0123456789\");\n vi.stubEnv(\"CANONICAL_HOSTS\", HOST);\n vi.stubEnv(\"VERCEL_ENV\", \"production\");\n vi.stubEnv(\"AUTH_URL\", \"\");\n ({ db } = await createTestDb());\n h.db = db;\n const [tenant] = await db.insert(tenants).values({ name: \"Pat\" }).returning();\n const [user] = await db\n .insert(users)\n .values({ tenantId: tenant.id, email: MEMBER, role: \"owner\", signInEnabled: true })\n .returning();\n memberId = user.id;\n ({ handlers } = await import(\"@/auth\"));\n});\n\nafterAll(() => {\n vi.unstubAllEnvs();\n});\n\nbeforeEach(() => {\n h.sent.length = 0;\n});\n\ndescribe(\"magic-link login, end to end\", () => {\n it(\"an invited member gets an email, the link logs them in, and the login is audited\", async () => {\n const { jar, location } = await requestLink(MEMBER);\n expect(location).toBe(\"/login/check-email?provider=email&type=email\");\n\n expect(h.sent).toHaveLength(1);\n expect(h.sent[0].to).toBe(MEMBER);\n expect(h.sent[0].subject).toBe(`Your ${SITE_NAME} login link`);\n const link = linkIn(h.sent[0].text);\n expect(new URL(link).host).toBe(HOST);\n\n const click = await call(link, jar);\n expect(click.status).toBe(302);\n expect(click.headers.get(\"location\")).toBe(`${ORIGIN}${POST_LOGIN_DESTINATION}`);\n expect(sessionCookie(jar)).toBe(true);\n\n // The cookie must carry the RIGHT person, not merely exist.\n const session = (await (await call(`${ORIGIN}/api/auth/session`, jar)).json()) as {\n user?: { id?: string; email?: string };\n };\n expect(session.user?.id).toBe(memberId);\n expect(session.user?.email).toBe(MEMBER);\n\n const [row] = await db.select().from(users).where(eq(users.id, memberId));\n expect(row.lastLoginAt).not.toBeNull();\n expect(row.emailVerifiedAt).not.toBeNull();\n const audit = await db.select().from(auditEvents).where(eq(auditEvents.userId, memberId));\n expect(audit.map((a) => a.action)).toContain(\"auth.login\");\n });\n\n it(\"a link works once: the second click logs nobody in\", async () => {\n await requestLink(MEMBER);\n const link = linkIn(h.sent[0].text);\n const first = new Jar();\n await call(link, first);\n expect(sessionCookie(first)).toBe(true);\n\n const second = new Jar();\n const res = await call(link, second);\n expect(res.headers.get(\"location\")).toBe(`${ORIGIN}/login/error?error=Verification`);\n expect(sessionCookie(second)).toBe(false);\n });\n\n it(\"an unknown address gets the identical response, and nothing is sent\", async () => {\n const member = await requestLink(MEMBER);\n h.sent.length = 0;\n const stranger = await requestLink(\"nobody@example.com\");\n expect(stranger.res.status).toBe(member.res.status);\n expect(stranger.location).toBe(member.location);\n expect(h.sent).toHaveLength(0);\n });\n\n it(\"a forged host gets the same-shaped response, and nothing is sent\", async () => {\n const forged = await requestLink(MEMBER, \"https://attacker.example\");\n expect(forged.location).toBe(\"/login/check-email?provider=email&type=email\");\n expect(h.sent).toHaveLength(0);\n });\n\n it(\"turning sign-in off after the link was sent makes the link useless\", async () => {\n await requestLink(MEMBER);\n const link = linkIn(h.sent[0].text);\n await db.update(users).set({ signInEnabled: false }).where(eq(users.id, memberId));\n try {\n const jar = new Jar();\n await call(link, jar);\n expect(sessionCookie(jar)).toBe(false);\n } finally {\n await db.update(users).set({ signInEnabled: true }).where(eq(users.id, memberId));\n }\n });\n\n it(\"a suspended account can't request or use a link\", async () => {\n const [user] = await db.select().from(users).where(eq(users.id, memberId));\n await requestLink(MEMBER);\n const link = linkIn(h.sent[0].text);\n h.sent.length = 0;\n await db.update(tenants).set({ status: \"suspended\" }).where(eq(tenants.id, user.tenantId));\n try {\n await requestLink(MEMBER);\n expect(h.sent).toHaveLength(0);\n const jar = new Jar();\n await call(link, jar);\n expect(sessionCookie(jar)).toBe(false);\n } finally {\n await db.update(tenants).set({ status: \"active\" }).where(eq(tenants.id, user.tenantId));\n }\n });\n\n it(\"the code in the email, typed into the app, logs in like the link (the home-screen app case)\", async () => {\n const { jar } = await requestLink(MEMBER);\n const code = codeIn(h.sent[0].text);\n expect(h.sent[0].html).toContain(`${code.slice(0, 4)} ${code.slice(4)}`);\n // The link carries the same code: one secret, two ways to use it.\n expect(new URL(linkIn(h.sent[0].text)).searchParams.get(\"token\")).toBe(code);\n\n const typed = await call(`${ORIGIN}${buildCodeCallbackPath(\" Pat@Example.com \", code)}`, jar);\n expect(typed.headers.get(\"location\")).toBe(`${ORIGIN}${POST_LOGIN_DESTINATION}`);\n expect(sessionCookie(jar)).toBe(true);\n });\n\n it(\"ten wrong codes lock the address for the hour: then even the right code is refused\", async () => {\n const email = \"guessed@example.com\";\n await invite(email);\n const { jar } = await requestLink(email);\n const code = codeIn(h.sent[0].text);\n const wrong = code === \"00000000\" ? \"11111111\" : \"00000000\";\n for (let i = 0; i < SIGN_IN_CODE_WRONG_GUESS_LIMIT; i++) {\n const res = await call(`${ORIGIN}${buildCodeCallbackPath(email, wrong)}`, new Jar());\n expect(res.headers.get(\"location\")).toContain(\"/login/error\");\n }\n const failures = await db.select().from(signInCodeFailures).where(eq(signInCodeFailures.identifier, email));\n expect(failures).toHaveLength(SIGN_IN_CODE_WRONG_GUESS_LIMIT);\n\n const right = await call(`${ORIGIN}${buildCodeCallbackPath(email, code)}`, jar);\n expect(right.headers.get(\"location\")).toContain(\"/login/error\");\n expect(sessionCookie(jar)).toBe(false);\n // The locked attempt did not burn the real code.\n expect(await db.select().from(verificationTokens).where(eq(verificationTokens.identifier, email))).toHaveLength(1);\n });\n\n it(`only the newest ${SIGN_IN_CODE_LIVE_MAX} codes per address stay live; an older one stops working`, async () => {\n const email = \"many@example.com\";\n await invite(email);\n await requestLink(email);\n const first = codeIn(h.sent[0].text);\n for (let i = 0; i < SIGN_IN_CODE_LIVE_MAX + 1; i++) await requestLink(email);\n const live = await db.select().from(verificationTokens).where(eq(verificationTokens.identifier, email));\n expect(live).toHaveLength(SIGN_IN_CODE_LIVE_MAX);\n // The per-address send limit still applies: no more than that many emails went out.\n expect(h.sent.filter((m) => m.to === email).length).toBeLessThanOrEqual(SIGN_IN_CODE_LIVE_MAX);\n const jar = new Jar();\n const old = await call(`${ORIGIN}${buildCodeCallbackPath(email, first)}`, jar);\n expect(old.headers.get(\"location\")).toContain(\"/login/error\");\n expect(sessionCookie(jar)).toBe(false);\n });\n});\n",
43
+ "test/auth-guards.test.ts": "/**\n * Source-level guards for login rules that no unit test of a function can\n * hold, because the regression would be in how the pieces are WIRED. Each one\n * is a mistake that has shipped in a real app before. Comments are stripped\n * before matching, so a comment\n * that explains a rule can't satisfy (or trip) the guard for it.\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { describe, expect, it } from \"vitest\";\n\nimport { sessionConfig } from \"@/lib/auth/session-config\";\nimport { POST_LOGIN_DESTINATION, POST_LOGOUT_DESTINATION, PUBLIC_ROUTES } from \"@/lib/routes\";\n\nconst ROOT = join(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst raw = (f: string) => readFileSync(join(ROOT, f), \"utf8\");\n\n/** Removes // and /* *\\/ comments and JSX {/* *\\/} comments. Not a parser; good enough for our own files. */\nfunction stripComments(src: string): string {\n return src\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:\"'`])\\/\\/.*$/gm, \"$1\");\n}\nconst code = (f: string) => stripComments(raw(f));\n\nfunction files(dir: string, ext: RegExp): string[] {\n const out: string[] = [];\n for (const name of readdirSync(join(ROOT, dir))) {\n const rel = join(dir, name);\n if (statSync(join(ROOT, rel)).isDirectory()) out.push(...files(rel, ext));\n else if (ext.test(name)) out.push(rel);\n }\n return out;\n}\n\ndescribe(\"comment stripper (the guards below depend on it)\", () => {\n it(\"removes comments but keeps code and URLs\", () => {\n const out = stripComments('const a = \"https://x.test\"; // sign in\\n/* sign in */ const b = 1;');\n expect(out).toContain('\"https://x.test\"');\n expect(out).toContain(\"const b = 1;\");\n expect(out).not.toMatch(/sign in/);\n });\n});\n\ndescribe(\"where login lands\", () => {\n it(\"post-login destination is never a public page, logout destination always is\", () => {\n expect(PUBLIC_ROUTES as readonly string[]).not.toContain(POST_LOGIN_DESTINATION);\n expect(PUBLIC_ROUTES as readonly string[]).toContain(POST_LOGOUT_DESTINATION);\n });\n\n it(\"every redirectTo in the app uses the named constant, never a literal\", () => {\n const sites = [...files(\"app\", /\\.tsx?$/), \"auth.ts\"].flatMap((f) =>\n [...code(f).matchAll(/redirectTo:\\s*([^,}\\n]+)/g)].map((m) => ({ f, value: m[1].trim() })),\n );\n expect(sites.length).toBeGreaterThan(0);\n for (const { f, value } of sites) {\n expect([`POST_LOGIN_DESTINATION`, `POST_LOGOUT_DESTINATION`], f).toContain(value);\n }\n });\n});\n\ndescribe(\"auth.ts wiring\", () => {\n const auth = code(\"auth.ts\");\n\n it(\"allows every address at SEND time, so the response can't reveal who has an account\", () => {\n expect(auth).toMatch(/if\\s*\\(\\s*email\\?\\.verificationRequest\\s*\\)\\s*return true;/);\n });\n\n it(\"re-checks the person with canUserSignIn when the link is clicked\", () => {\n expect(auth).toMatch(/return canUserSignIn\\(await findSignInCandidateById\\(user\\.id\\)\\)/);\n });\n\n it(\"trusts the request host and is never pinned to a base URL\", () => {\n expect(auth).toMatch(/trustHost:\\s*true/);\n expect(raw(\".env.example\")).not.toMatch(/^\\s*(AUTH_URL|NEXTAUTH_URL)\\s*=/m);\n });\n\n it(\"no pages.* value carries a query string (Auth.js appends its own)\", () => {\n expect(auth).not.toMatch(/(signIn|verifyRequest|error|signOut|newUser)\\s*:\\s*\"[^\"]*\\?/);\n });\n\n it(\"declares JWT sessions with a 7-day idle limit, explicitly\", () => {\n expect(sessionConfig).toEqual({ strategy: \"jwt\", maxAge: 60 * 60 * 24 * 7 });\n expect(auth).toMatch(/session:\\s*sessionConfig/);\n });\n\n it(\"there is exactly one Auth.js instance, so there is one session config\", () => {\n const all = [...files(\"app\", /\\.tsx?$/), ...files(\"lib\", /\\.tsx?$/), \"auth.ts\"];\n expect(all.filter((f) => /NextAuth\\(/.test(code(f)))).toEqual([\"auth.ts\"]);\n });\n});\n\ndescribe(\"one sign-in predicate\", () => {\n it(\"the adapter, the send gate and the current-user helper all use canUserSignIn\", () => {\n for (const f of [\"lib/auth/adapter.ts\", \"lib/auth/send-gate.ts\", \"lib/current-user.ts\"]) {\n expect(code(f), f).toMatch(/canUserSignIn\\(/);\n expect(code(f), f).not.toMatch(/signInEnabled\\s*&&|\\.signInEnabled\\s*===\\s*true/);\n }\n });\n\n it(\"only auth.ts and lib/current-user.ts call auth()\", () => {\n const callers = [...files(\"app\", /\\.tsx?$/), ...files(\"lib\", /\\.tsx?$/)].filter((f) =>\n /\\bawait auth\\(\\)/.test(code(f)),\n );\n expect(callers).toEqual([\"lib/current-user.ts\"]);\n });\n});\n\ndescribe(\"forms post to route handlers, not Server Actions\", () => {\n it(\"no 'use server' anywhere in app/\", () => {\n expect(files(\"app\", /\\.tsx?$/).filter((f) => /[\"']use server[\"']/.test(code(f)))).toEqual([]);\n });\n\n it(\"the login form is a plain POST to /login/submit\", () => {\n expect(code(\"app/login/LoginForm.tsx\")).toMatch(/<form method=\"post\" action=\"\\/login\\/submit\"/);\n });\n});\n\ndescribe(\"wording\", () => {\n it(\"user-facing pages say 'Log in', never 'Sign in'\", () => {\n const offenders = files(\"app\", /\\.tsx$/).filter((f) => {\n // Strip identifiers like signIn()/signOut() and import paths\n // (\"@/lib/auth/sign-in-code\"); match only words a person reads.\n const text = code(f)\n .replace(/\\bsign(In|Out)\\b/g, \"\")\n .replace(/from\\s+\"[^\"]*\"/g, \"\");\n return /\\bsign(ed)?[ -]?(in|out)\\b/i.test(text);\n });\n expect(offenders).toEqual([]);\n });\n\n it(\"the check-email page states a condition, never that an email was sent\", () => {\n const page = code(\"app/login/check-email/page.tsx\") + code(\"app/login/check-email/TypedAddress.tsx\");\n // Every sentence promising a link carries the \"has access\" condition.\n const promises = page.split(\"on its way\").slice(0, -1);\n expect(promises.length).toBeGreaterThan(0);\n for (const before of promises) expect(before.slice(-120)).toMatch(/has access, a login link is $/);\n expect(page).toMatch(/If <strong[^>]*>\\{email\\}<\\/strong> has access/);\n expect(page).toMatch(/If the address you entered has access/);\n });\n});\n",
44
+ "test/auth-hosts.test.ts": "/**\n * The login-link host allowlist (lib/auth/hosts.ts). The security cases come\n * with a NEGATIVE CONTROL: local development must still work in every shape a\n * dev server answers on, or a hard-coded `false` would pass every other test.\n */\nimport { describe, expect, it } from \"vitest\";\n\nimport { canonicalHosts, isKnownHost, isLoopbackHost, isProductionDeployment, normalizeHost } from \"@/lib/auth/hosts\";\n\nconst PROD = { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst PREVIEW = { VERCEL_ENV: \"preview\", NODE_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst LOCAL = { NODE_ENV: \"development\" };\n\ndescribe(\"isKnownHost\", () => {\n it(\"allows the canonical host, case-insensitively\", () => {\n expect(isKnownHost(\"app.example.test\", PROD)).toBe(true);\n expect(isKnownHost(\"App.Example.TEST\", PROD)).toBe(true);\n });\n\n it(\"refuses any other host in production, including localhost\", () => {\n expect(isKnownHost(\"attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"app.example.test.attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"localhost:3000\", PROD)).toBe(false);\n });\n\n it(\"CANONICAL_HOSTS unset in production means nobody, not everybody\", () => {\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\" })).toBe(false);\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \" , \" })).toBe(false);\n });\n\n it(\"refuses a forged host on a PREVIEW deployment, which has a public URL\", () => {\n expect(isKnownHost(\"attacker.example\", PREVIEW)).toBe(false);\n expect(isKnownHost(\"app-git-main-team.vercel.app\", PREVIEW)).toBe(false);\n });\n\n it(\"a preview that lists its own host may send links\", () => {\n const env = { ...PREVIEW, CANONICAL_HOSTS: \"app.example.test,app-git-main-team.vercel.app\" };\n expect(isKnownHost(\"app-git-main-team.vercel.app\", env)).toBe(true);\n });\n\n it(\"NEGATIVE CONTROL: local development works in every loopback shape\", () => {\n for (const host of [\"localhost\", \"localhost:3000\", \"127.0.0.1:3000\", \"[::1]:3000\", \"app.localhost:3000\"]) {\n expect(isKnownHost(host, LOCAL), host).toBe(true);\n }\n });\n\n it(\"refuses malformed hosts\", () => {\n for (const host of [\"\", \"evil.example/path\", \"user@evil.example\", \"evil example\", null, 42]) {\n expect(isKnownHost(host, LOCAL)).toBe(false);\n }\n });\n});\n\ndescribe(\"isProductionDeployment\", () => {\n it(\"is decided by VERCEL_ENV, because Vercel previews run with NODE_ENV=production\", () => {\n expect(isProductionDeployment({ VERCEL_ENV: \"production\" })).toBe(true);\n expect(isProductionDeployment({ VERCEL_ENV: \"preview\", NODE_ENV: \"production\" })).toBe(false);\n expect(isProductionDeployment({ NODE_ENV: \"production\" })).toBe(false);\n });\n});\n\ndescribe(\"helpers\", () => {\n it(\"parses CANONICAL_HOSTS into a normalized set\", () => {\n expect([...canonicalHosts({ CANONICAL_HOSTS: \" App.example.test , bad host,x.test:8443\" })]).toEqual([\n \"app.example.test\",\n \"x.test:8443\",\n ]);\n });\n\n it(\"recognizes loopback hosts and nothing else\", () => {\n expect(isLoopbackHost(\"localhost:3000\")).toBe(true);\n expect(isLoopbackHost(\"[::1]\")).toBe(true);\n expect(isLoopbackHost(\"localhost.attacker.example\")).toBe(false);\n expect(isLoopbackHost(\"127.0.0.2\")).toBe(false);\n });\n\n it(\"normalizeHost lower-cases and rejects junk\", () => {\n expect(normalizeHost(\" Example.COM:443 \")).toBe(\"example.com:443\");\n expect(normalizeHost(\"https://example.com\")).toBeNull();\n });\n});\n",
45
+ "test/auth-send-gate.test.ts": "/**\n * The send gate (lib/auth/send-gate.ts): every reason an email is or isn't\n * sent, with fake dependencies so each branch is exercised directly. The two\n * properties that matter most: it never throws (a throw would leak who has an\n * account), and refused requests never reach the database or a quota.\n */\nimport { describe, expect, it, vi } from \"vitest\";\n\nimport { createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport { deliverLoginLink, type SendGateDeps } from \"@/lib/auth/send-gate\";\nimport type { SignInCandidate } from \"@/lib/auth/sign-in-policy\";\n\nconst ACTIVE: SignInCandidate = { isActive: true, signInEnabled: true, tenantStatus: \"active\" };\nconst LINK = \"https://app.example.test/api/auth/callback/email?callbackUrl=%2Fdashboard&token=abc&email=pat%40example.com\";\n\nfunction deps(overrides: Partial<SendGateDeps> = {}) {\n const log = { warn: vi.fn(), error: vi.fn() };\n const d: SendGateDeps = {\n env: { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" },\n findUser: vi.fn(async (email: string) => (email === \"pat@example.com\" ? ACTIVE : null)),\n countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 0 })),\n sendEmail: vi.fn(async () => ({ sent: true })),\n ipLimiter: createRateLimiter({ limit: 20, windowMs: 3_600_000 }),\n instanceLimiter: createRateLimiter({ limit: 300, windowMs: 3_600_000 }),\n log,\n ...overrides,\n };\n return { d, log };\n}\n\nconst req = (identifier = \"pat@example.com\", url = LINK, ip = \"203.0.113.7\") => ({\n identifier,\n url,\n headers: new Headers({ \"x-real-ip\": ip }),\n});\n\ndescribe(\"deliverLoginLink\", () => {\n it(\"sends the email to an invited, active member\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"Pat@Example.com\"), d)).toBe(\"sent\");\n expect(d.sendEmail).toHaveBeenCalledOnce();\n const message = vi.mocked(d.sendEmail).mock.calls[0][0];\n expect(message.to).toBe(\"pat@example.com\");\n expect(message.text).toContain(LINK);\n });\n\n it(\"refuses a forged host before touching the database\", async () => {\n const { d } = deps();\n const forged = LINK.replace(\"app.example.test\", \"attacker.example\");\n expect(await deliverLoginLink(req(undefined, forged), d)).toBe(\"unknown-host\");\n expect(d.findUser).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"sends nothing to an address without an account, and never counts it against a quota\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"stranger@example.com\"), d)).toBe(\"not-allowed\");\n expect(d.countOutstanding).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it.each([\n [\"sign-in turned off\", { ...ACTIVE, signInEnabled: false }],\n [\"user deactivated\", { ...ACTIVE, isActive: false }],\n [\"account suspended\", { ...ACTIVE, tenantStatus: \"suspended\" }],\n ])(\"sends nothing when %s\", async (_label, candidate) => {\n const { d } = deps({ findUser: vi.fn(async () => candidate) });\n expect(await deliverLoginLink(req(), d)).toBe(\"not-allowed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"60 requests for made-up addresses do not block a real member\", async () => {\n const { d } = deps();\n for (let i = 0; i < 60; i++) await deliverLoginLink(req(`fake${i}@example.com`, LINK, `198.51.100.${i}`), d);\n expect(await deliverLoginLink(req(), d)).toBe(\"sent\");\n });\n\n it(\"stops at the per-address quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 5, global: 5 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-per-email\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"stops at the global quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 200 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-global\");\n });\n\n it(\"rate-limits one IP before reading the database\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 2, windowMs: 3_600_000 }) });\n await deliverLoginLink(req(), d);\n await deliverLoginLink(req(), d);\n vi.mocked(d.findUser).mockClear();\n expect(await deliverLoginLink(req(), d)).toBe(\"rate-limited-ip\");\n expect(d.findUser).not.toHaveBeenCalled();\n });\n\n it(\"a request with no trusted IP header is not lumped into one shared bucket\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 1, windowMs: 3_600_000 }) });\n const noIp = { ...req(), headers: new Headers({ \"x-forwarded-for\": \"1.2.3.4\" }) };\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n });\n\n it(\"NEVER throws when the mail provider rejects the send\", async () => {\n const { d, log } = deps({ sendEmail: vi.fn(async () => Promise.reject(new Error(\"MessageRejected\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"provider-rejected\");\n expect(log.error).toHaveBeenCalled();\n });\n\n it(\"NEVER throws when the database is down\", async () => {\n const { d } = deps({ findUser: vi.fn(async () => Promise.reject(new Error(\"connection refused\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"lookup-failed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"logs every refusal with the host and the address (a silent refusal looks like a broken mailer)\", async () => {\n const { d, log } = deps();\n await deliverLoginLink(req(\"stranger@example.com\"), d);\n expect(log.warn).toHaveBeenCalledWith(\n expect.stringContaining(\"SUPPRESSED (not-allowed)\"),\n expect.objectContaining({ host: \"app.example.test\", email: \"stranger@example.com\" }),\n );\n });\n\n describe(\"when mail is not configured\", () => {\n const unconfigured = { sendEmail: vi.fn(async () => ({ sent: false, skippedReason: \"SES creds not set\" })) };\n\n it(\"prints the link on a local dev server, so login can be tested with no mail provider\", async () => {\n const { d, log } = deps({ ...unconfigured, env: { CANONICAL_HOSTS: \"\" } });\n const local = LINK.replace(\"https://app.example.test\", \"http://localhost:3000\");\n expect(await deliverLoginLink(req(undefined, local), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).toContain(local);\n });\n\n it(\"never prints the link off loopback: production and preview logs are kept\", async () => {\n const { d, log } = deps(unconfigured);\n expect(await deliverLoginLink(req(), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).not.toContain(\"token=abc\");\n });\n });\n});\n",
46
+ "test/auth-units.test.ts": "/**\n * Small pure pieces of login: the sign-in predicate, the quota, email\n * normalization, the IP reader, the rate limiter, the login email, the\n * same-origin check and provisioning input.\n */\nimport { describe, expect, it } from \"vitest\";\n\nimport { clientIpFrom } from \"@/lib/auth/client-ip\";\nimport { buildLoginEmail } from \"@/lib/auth/login-email\";\nimport { checkWindow, createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport {\n canUserSignIn,\n evaluateMagicLinkQuota,\n MAX_OUTSTANDING_GLOBAL,\n MAX_OUTSTANDING_PER_EMAIL,\n normalizeEmail,\n} from \"@/lib/auth/sign-in-policy\";\nimport { isSameOriginPost, seeOther } from \"@/lib/http\";\nimport { displayName, parseProvisionArgs } from \"@/lib/provisioning\";\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\n\ndescribe(\"canUserSignIn\", () => {\n const ok = { isActive: true, signInEnabled: true, tenantStatus: \"active\" };\n it(\"allows only an active, invited user in an active account\", () => {\n expect(canUserSignIn(ok)).toBe(true);\n expect(canUserSignIn({ ...ok, isActive: false })).toBe(false);\n expect(canUserSignIn({ ...ok, signInEnabled: false })).toBe(false);\n expect(canUserSignIn(null)).toBe(false);\n });\n it(\"denies any account status other than exactly 'active'\", () => {\n for (const status of [\"suspended\", \"Active\", \"active \", \"\"]) {\n expect(canUserSignIn({ ...ok, tenantStatus: status })).toBe(false);\n }\n });\n});\n\ndescribe(\"evaluateMagicLinkQuota\", () => {\n it(\"allows under both limits and names the limit that stopped it\", () => {\n expect(evaluateMagicLinkQuota({ outstandingForEmail: 0, outstandingGlobal: 0 }).allowed).toBe(true);\n expect(evaluateMagicLinkQuota({ outstandingForEmail: MAX_OUTSTANDING_PER_EMAIL, outstandingGlobal: 0 })).toEqual({\n allowed: false,\n reason: \"per-email\",\n });\n expect(evaluateMagicLinkQuota({ outstandingForEmail: 0, outstandingGlobal: MAX_OUTSTANDING_GLOBAL })).toEqual({\n allowed: false,\n reason: \"global\",\n });\n });\n});\n\ndescribe(\"normalizeEmail\", () => {\n it(\"trims and lower-cases\", () => {\n expect(normalizeEmail(\" Pat@Example.COM \")).toBe(\"pat@example.com\");\n });\n it(\"rejects things that are not addresses\", () => {\n for (const bad of [\"\", \"pat\", \"pat@\", \"@example.com\", \"pat @example.com\", \"a@b\", null, 7, \"x\".repeat(250) + \"@e.co\"]) {\n expect(normalizeEmail(bad)).toBeNull();\n }\n });\n});\n\ndescribe(\"clientIpFrom\", () => {\n it(\"never trusts the caller-controlled first x-forwarded-for entry\", () => {\n const h = new Headers({ \"x-forwarded-for\": \"6.6.6.6, 203.0.113.7\" });\n expect(clientIpFrom(h)).toEqual({ address: null, source: \"none\" });\n });\n it(\"uses the platform-set headers, in order\", () => {\n expect(clientIpFrom(new Headers({ \"x-vercel-forwarded-for\": \"203.0.113.7\", \"x-real-ip\": \"198.51.100.1\" }))).toEqual({\n address: \"203.0.113.7\",\n source: \"x-vercel-forwarded-for\",\n });\n expect(clientIpFrom(new Headers({ \"x-real-ip\": \"2001:db8::1\" })).address).toBe(\"2001:db8::1\");\n });\n it(\"ignores a value that is not an IP address\", () => {\n expect(clientIpFrom(new Headers({ \"x-real-ip\": \"'; drop table users\" })).address).toBeNull();\n });\n});\n\ndescribe(\"rate limiter\", () => {\n it(\"checkWindow drops hits older than the window\", () => {\n expect(checkWindow([0, 10], 2, 100, 50).allowed).toBe(false);\n expect(checkWindow([0, 10], 2, 100, 105)).toEqual({ allowed: true, hits: [10, 105] });\n });\n it(\"does not record rejected attempts, so a lockout cannot be extended\", () => {\n const limiter = createRateLimiter({ limit: 1, windowMs: 100 });\n expect(limiter.attempt(\"k\", 0)).toBe(true);\n expect(limiter.attempt(\"k\", 50)).toBe(false);\n expect(limiter.attempt(\"k\", 99)).toBe(false);\n expect(limiter.attempt(\"k\", 101)).toBe(true);\n });\n it(\"caps how many keys it remembers\", () => {\n const limiter = createRateLimiter({ limit: 1, windowMs: 1000, maxKeys: 2 });\n limiter.attempt(\"a\", 0);\n limiter.attempt(\"b\", 0);\n limiter.attempt(\"c\", 0); // evicts \"a\"\n expect(limiter.attempt(\"a\", 1)).toBe(true);\n });\n});\n\ndescribe(\"login email\", () => {\n const url = \"https://app.example.test/api/auth/callback/email?token=t&email=pat%40example.com\";\n it(\"contains the link, names the app, and escapes the link in HTML\", () => {\n const email = buildLoginEmail(url);\n expect(email.text).toContain(url);\n expect(email.text).toContain(SITE_NAME);\n expect(email.html).toContain('href=\"https://app.example.test/api/auth/callback/email?token=t&amp;email=pat%40example.com\"');\n });\n it(\"uses 'log in' wording, never 'sign in'\", () => {\n const { subject, text, html } = buildLoginEmail(url);\n expect(`${subject} ${text} ${html}`).not.toMatch(/sign[ -]?in/i);\n });\n});\n\ndescribe(\"isSameOriginPost / seeOther\", () => {\n const post = (headers: Record<string, string>) => new Request(\"https://app.example.test/login/submit\", { method: \"POST\", headers });\n it(\"accepts a same-origin post, and one with no Origin header\", () => {\n expect(isSameOriginPost(post({ host: \"app.example.test\", origin: \"https://app.example.test\" }))).toBe(true);\n expect(isSameOriginPost(post({ host: \"app.example.test\" }))).toBe(true);\n });\n it(\"refuses a cross-site or opaque origin\", () => {\n expect(isSameOriginPost(post({ host: \"app.example.test\", origin: \"https://attacker.example\" }))).toBe(false);\n expect(isSameOriginPost(post({ host: \"app.example.test\", origin: \"null\" }))).toBe(false);\n });\n it(\"redirects with a relative 303 and refuses off-site targets\", () => {\n const res = seeOther(\"/login/check-email\");\n expect(res.status).toBe(303);\n expect(res.headers.get(\"location\")).toBe(\"/login/check-email\");\n expect(() => seeOther(\"//attacker.example\")).toThrow();\n expect(() => seeOther(\"https://attacker.example\")).toThrow();\n });\n});\n\ndescribe(\"parseProvisionArgs\", () => {\n it(\"parses the flags; the account name defaults to the person's name\", () => {\n expect(parseProvisionArgs([\"--email\", \"Pat@Example.com\", \"--first-name\", \"Pat\", \"--last-name\", \"Smith\"])).toEqual({\n ok: true,\n value: { email: \"pat@example.com\", firstName: \"Pat\", lastName: \"Smith\", accountName: \"Pat Smith\" },\n });\n expect(parseProvisionArgs([\"--email\", \"m@example.com\", \"--first-name\", \"Madonna\", \"--account-name\", \" Acme Ltd \"])).toEqual({\n ok: true,\n value: { email: \"m@example.com\", firstName: \"Madonna\", lastName: null, accountName: \"Acme Ltd\" },\n });\n });\n it(\"refuses a bad email, a missing or split name, or malformed flags\", () => {\n expect(parseProvisionArgs([\"--email\", \"nope\", \"--first-name\", \"Pat\"]).ok).toBe(false);\n expect(parseProvisionArgs([\"--email\", \"pat@example.com\", \"--name\", \"Pat Smith\"]).ok).toBe(false);\n expect(parseProvisionArgs([\"--email\", \"pat@example.com\"]).ok).toBe(false);\n expect(parseProvisionArgs([\"--email\", \"pat@example.com\", \"--first-name\", \"x\".repeat(81)]).ok).toBe(false);\n expect(parseProvisionArgs([\"--email\", \"pat@example.com\", \"--first-name\", \"Pat\", \"--account-name\", \" \"]).ok).toBe(false);\n expect(parseProvisionArgs([\"--email\"]).ok).toBe(false);\n });\n it(\"never splits a name: the display name is only ever joined\", () => {\n expect(displayName(\"Pat\", \"van Dyke\")).toBe(\"Pat van Dyke\");\n expect(displayName(\"Madonna\", null)).toBe(\"Madonna\");\n });\n});\n",
47
+ "test/helpers/test-db.ts": "// An in-memory Postgres (PGlite) built from db/schema.ts. Tests that need a\n// real database use this instead of mocking queries, so they exercise the same\n// SQL, constraints and foreign keys that production runs.\n//\n// The SQL comes from drizzle-kit's own generator (the code behind\n// `npm run db:generate`), diffing an empty schema against db/schema.ts. So a\n// new table needs no change here, and a schema that drizzle-kit can't turn into\n// SQL fails here first, not on the production database.\n\nimport { PGlite } from \"@electric-sql/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { generateDrizzleJson, generateMigration } from \"drizzle-kit/api\";\n\nimport * as schema from \"@/db/schema\";\n\nexport async function createTestDb() {\n const client = new PGlite();\n const statements = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(schema));\n for (const statement of statements) await client.exec(statement);\n return { client, db: drizzle(client, { schema }) };\n}\n\nexport type TestDb = Awaited<ReturnType<typeof createTestDb>>[\"db\"];\n",
48
+ "test/sign-in-code.test.ts": "/** The typed login code (lib/auth/sign-in-code.ts) and its place in the email. */\nimport { describe, expect, it } from \"vitest\";\n\nimport { buildLoginEmail } from \"@/lib/auth/login-email\";\nimport {\n buildCodeCallbackPath,\n codeFromLoginUrl,\n formatSignInCode,\n generateSignInCode,\n normalizeSignInCode,\n SIGN_IN_CODE_LIVE_MAX,\n} from \"@/lib/auth/sign-in-code\";\nimport { MAX_OUTSTANDING_PER_EMAIL } from \"@/lib/auth/sign-in-policy\";\n\ndescribe(\"the login code\", () => {\n it(\"is always 8 digits, leading zeros kept, and varies\", () => {\n const codes = new Set(Array.from({ length: 200 }, generateSignInCode));\n for (const c of codes) expect(c).toMatch(/^\\d{8}$/);\n expect(codes.size).toBeGreaterThan(195);\n });\n\n it(\"accepts what people type, refuses the rest before it costs a guess\", () => {\n expect(normalizeSignInCode(\"1234 5678\")).toBe(\"12345678\");\n expect(normalizeSignInCode(\" 1234-5678 \")).toBe(\"12345678\");\n expect(normalizeSignInCode(\"1234567\")).toBeNull();\n expect(normalizeSignInCode(\"123456789\")).toBeNull();\n expect(normalizeSignInCode(\"1234abcd\")).toBeNull();\n expect(formatSignInCode(\"01234567\")).toBe(\"0123 4567\");\n });\n\n it(\"builds a relative callback with the address lower-cased, so it stays in this app\", () => {\n expect(buildCodeCallbackPath(\" Pat@Example.COM \", \"01234567\")).toBe(\n \"/api/auth/callback/email?token=01234567&email=pat%40example.com\",\n );\n });\n\n it(\"keeps exactly as many live codes as the per-address send limit counts\", () => {\n expect(SIGN_IN_CODE_LIVE_MAX).toBe(MAX_OUTSTANDING_PER_EMAIL);\n });\n\n it(\"the email prints the link's own code, and no code when the token isn't one\", () => {\n const url = \"https://app.example.test/api/auth/callback/email?callbackUrl=x&token=01234567&email=pat%40example.com\";\n expect(codeFromLoginUrl(url)).toBe(\"01234567\");\n const mail = buildLoginEmail(url);\n expect(mail.text).toContain(\"0123 4567\");\n expect(mail.html).toContain(\"0123 4567\");\n const legacy = buildLoginEmail(\"https://app.example.test/api/auth/callback/email?token=\" + \"a\".repeat(64));\n expect(legacy.text).not.toContain(\"code into the app\");\n });\n});\n",
49
+ "test/terms-guard.test.ts": "/**\n * The Terms gate is enforced on the SERVER, in both places a person can act:\n * every logged-in page (requireAgreedUser) and every route handler that acts\n * for a person (getAgreedUser). A page guard alone is decorative: a direct\n * POST skips the page.\n *\n * The guards run against an in-memory Postgres with only the session replaced.\n * The sweeps below read the source, so a NEW page or handler that forgets the\n * guard turns this file red. Comments are stripped before matching.\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { eq } from \"drizzle-orm\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { tenants, users } from \"@/db/schema\";\nimport { PUBLIC_ROUTES } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION } from \"@/lib/terms\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, userId: null as string | null }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/auth\", () => ({ auth: async () => (h.userId ? { user: { id: h.userId } } : null) }));\n\nconst { getAgreedUser, requireAgreedUser } = await import(\"@/lib/current-user\");\n\nlet db: TestDb;\n\n/** The path a Next.js redirect() call would send the browser to, or null if it returned normally. */\nasync function redirectOf(work: Promise<unknown>): Promise<string | null> {\n try {\n await work;\n return null;\n } catch (e) {\n const digest = String((e as { digest?: unknown }).digest ?? \"\");\n const m = /^NEXT_REDIRECT;[^;]*;([^;]+);/.exec(digest);\n if (!m) throw e;\n return m[1];\n }\n}\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n const [tenant] = await db.insert(tenants).values({ name: \"T\" }).returning();\n const [user] = await db.insert(users).values({ tenantId: tenant.id, email: \"pat@example.com\", signInEnabled: true }).returning();\n h.userId = user.id;\n});\n\ndescribe(\"the guards\", () => {\n it(\"a logged-in person who has not agreed is sent to /agree, and a handler gets null\", async () => {\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n expect(await getAgreedUser()).toBeNull();\n });\n\n it(\"an old version is not agreement\", async () => {\n await db.update(users).set({ termsVersion: \"2020-01-01\" }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n });\n\n it(\"the current version lets them through\", async () => {\n await db.update(users).set({ termsVersion: CURRENT_TERMS_VERSION }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBeNull();\n expect((await getAgreedUser())?.user.id).toBe(h.userId);\n });\n\n it(\"nobody logged in goes to /login, not /agree\", async () => {\n h.userId = null;\n expect(await redirectOf(requireAgreedUser())).toBe(\"/login\");\n expect(await getAgreedUser()).toBeNull();\n });\n});\n\nconst ROOT = join(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst code = (f: string) =>\n readFileSync(join(ROOT, f), \"utf8\")\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:\"'`])\\/\\/.*$/gm, \"$1\");\n\nfunction files(dir: string, name: RegExp): string[] {\n const out: string[] = [];\n for (const entry of readdirSync(join(ROOT, dir))) {\n const rel = join(dir, entry);\n if (statSync(join(ROOT, rel)).isDirectory()) out.push(...files(rel, name));\n else if (name.test(entry)) out.push(rel);\n }\n return out;\n}\n\n/** \"app/guide/whats-new/page.tsx\" → \"/guide/whats-new\". Route groups like (app) are dropped. */\nfunction routeOf(file: string): string {\n const parts = dirname(file).split(\"/\").slice(1).filter((p) => !/^\\(.*\\)$/.test(p));\n return \"/\" + parts.join(\"/\");\n}\n\n/**\n * Route handlers whose caller is not a logged-in person who has agreed, so they\n * must NOT use getAgreedUser. Add a webhook, cron job or service-token API here\n * ON PURPOSE, with the reason, never by default: a redirect breaks it silently.\n */\nconst NOT_A_PERSON_WHO_AGREED: Record<string, string> = {\n \"/api/auth/[...nextauth]\": \"Auth.js itself: logging in happens before agreeing.\",\n \"/api/health\": \"The uptime monitor. No session, ever.\",\n \"/login/submit\": \"Sends the login email; nobody is logged in yet.\",\n \"/logout\": \"Logging out must work for someone who will not agree.\",\n \"/agree/submit\": \"Records agreement, so it must work before it.\",\n};\n\ndescribe(\"every page and handler is guarded\", () => {\n it(\"every logged-in page calls requireAgreedUser()\", () => {\n const exempt = new Set<string>([...PUBLIC_ROUTES, \"/agree\"]);\n const unguarded = files(\"app\", /^page\\.tsx$/)\n .filter((f) => !exempt.has(routeOf(f)))\n .filter((f) => !/\\brequireAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"every route handler calls getAgreedUser(), unless it is listed as not a person\", () => {\n const unguarded = files(\"app\", /^route\\.ts$/)\n .filter((f) => !(routeOf(f) in NOT_A_PERSON_WHO_AGREED))\n .filter((f) => !/\\bgetAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"the exempt list names only handlers that exist\", () => {\n const routes = new Set(files(\"app\", /^route\\.ts$/).map(routeOf));\n expect(Object.keys(NOT_A_PERSON_WHO_AGREED).filter((r) => !routes.has(r))).toEqual([]);\n });\n\n it(\"the root layout mounts the footer, so every page links the Terms\", () => {\n expect(code(\"app/layout.tsx\")).toMatch(/<SiteFooter\\s*\\/>/);\n });\n});\n",
50
+ "test/terms.test.ts": "/**\n * The Terms every person must agree to before using the app: the rules\n * (lib/terms.ts), the agree handler against an in-memory Postgres (only \"who is\n * logged in\" is replaced), the wording, and the footer that keeps the Terms and\n * the Privacy Policy one tap away on every page.\n */\nimport { createElement } from \"react\";\nimport { renderToStaticMarkup } from \"react-dom/server\";\nimport { eq } from \"drizzle-orm\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { auditEvents, tenants, users } from \"@/db/schema\";\nimport { PUBLIC_ROUTES } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION, formatTermsDate, hasAgreedToCurrentTerms, parseAgreement } from \"@/lib/terms\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, current: null as unknown }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/lib/current-user\", () => ({ getCurrentUser: async () => h.current, requireCurrentUser: async () => h.current }));\n\nconst { POST: agree } = await import(\"@/app/agree/submit/route\");\nconst { TermsText } = await import(\"@/components/TermsText\");\nconst { PrivacyText } = await import(\"@/components/PrivacyText\");\nconst { SiteFooter } = await import(\"@/components/SiteFooter\");\nconst { default: TermsPage } = await import(\"@/app/terms/page\");\nconst { default: PrivacyPage } = await import(\"@/app/privacy/page\");\nconst { default: AgreePage } = await import(\"@/app/agree/page\");\n\nconst HOST = \"app.example.test\";\nconst ORIGIN = `https://${HOST}`;\nlet db: TestDb;\n\nasync function newPerson(email: string) {\n const [tenant] = await db.insert(tenants).values({ name: email }).returning();\n const [user] = await db.insert(users).values({ tenantId: tenant.id, email, signInEnabled: true }).returning();\n return { user, tenant, tenantId: tenant.id };\n}\n\nfunction post(fields: Record<string, string>, origin = ORIGIN) {\n return new Request(`${ORIGIN}/agree/submit`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\", host: HOST, origin },\n body: new URLSearchParams(fields),\n });\n}\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n h.current = null;\n});\n\ndescribe(\"the rules\", () => {\n it(\"only the current version counts as agreed\", () => {\n expect(hasAgreedToCurrentTerms({ termsVersion: CURRENT_TERMS_VERSION })).toBe(true);\n expect(hasAgreedToCurrentTerms({ termsVersion: null })).toBe(false);\n expect(hasAgreedToCurrentTerms({ termsVersion: \"2020-01-01\" })).toBe(false);\n });\n\n it(\"needs the box ticked AND the version the person was shown\", () => {\n expect(parseAgreement({ agree: \"yes\", version: CURRENT_TERMS_VERSION })).toBe(\"ok\");\n expect(parseAgreement({ agree: null, version: CURRENT_TERMS_VERSION })).toBe(\"unchecked\");\n expect(parseAgreement({ agree: \"on\", version: CURRENT_TERMS_VERSION })).toBe(\"unchecked\");\n expect(parseAgreement({ agree: \"yes\", version: \"2020-01-01\" })).toBe(\"stale\");\n expect(parseAgreement({ agree: \"yes\", version: null })).toBe(\"stale\");\n });\n\n it(\"formats a date from the string itself, so no time zone can move it a day\", () => {\n expect(formatTermsDate(\"2026-01-01\")).toBe(\"January 1, 2026\");\n expect(formatTermsDate(\"2026-12-31\")).toBe(\"December 31, 2026\");\n expect(formatTermsDate(\"not a date\")).toBe(\"not a date\");\n });\n});\n\ndescribe(\"the agree handler\", () => {\n it(\"refuses a cross-site post and sends a logged-out visitor to login\", async () => {\n expect((await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }, \"https://evil.test\"))).status).toBe(403);\n const res = await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }));\n expect(res.headers.get(\"location\")).toBe(\"/login\");\n });\n\n it(\"an unticked box or an old version records nothing and says why\", async () => {\n const me = await newPerson(\"pat@example.com\");\n h.current = me;\n expect((await agree(post({ version: CURRENT_TERMS_VERSION }))).headers.get(\"location\")).toBe(\"/agree?error=unchecked\");\n expect((await agree(post({ agree: \"yes\", version: \"2020-01-01\" }))).headers.get(\"location\")).toBe(\"/agree?error=stale\");\n const [row] = await db.select().from(users).where(eq(users.id, me.user.id));\n expect(row.termsVersion).toBeNull();\n expect(row.termsAcceptedAt).toBeNull();\n expect(await db.select().from(auditEvents)).toHaveLength(0);\n });\n\n it(\"records the version and the time, writes an audit event, and changes nobody else\", async () => {\n const me = await newPerson(\"pat@example.com\");\n const other = await newPerson(\"sam@example.com\");\n h.current = me;\n const before = Date.now();\n const res = await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }));\n expect(res.status).toBe(303);\n expect(res.headers.get(\"location\")).toBe(\"/dashboard\");\n\n const [row] = await db.select().from(users).where(eq(users.id, me.user.id));\n expect(row.termsVersion).toBe(CURRENT_TERMS_VERSION);\n expect(row.termsAcceptedAt!.getTime()).toBeGreaterThanOrEqual(before - 1000);\n const audit = await db.select().from(auditEvents);\n expect(audit).toHaveLength(1);\n expect(audit[0]).toMatchObject({ action: \"user.terms_agreed\", userId: me.user.id, tenantId: me.tenant.id });\n\n const [untouched] = await db.select().from(users).where(eq(users.id, other.user.id));\n expect(untouched.termsVersion).toBeNull();\n });\n});\n\ndescribe(\"the wording and where it is shown\", () => {\n it(\"carries the hold-harmless clause and links the Privacy Policy\", () => {\n const html = renderToStaticMarkup(createElement(TermsText));\n expect(html).toContain(\"hold them harmless\");\n expect(html).toContain(\"own free will\");\n expect(html).toContain(\"not arrive at all\");\n expect(html).toContain('href=\"/privacy\"');\n });\n\n it(\"the Privacy Policy names every outside service, and says nothing is sold\", () => {\n const html = renderToStaticMarkup(createElement(PrivacyText));\n for (const name of [\"Vercel\", \"Neon\", \"Amazon SES\", \"Fathom\"]) expect(html).toContain(name);\n expect(html).toContain(\"We do not sell or rent your information.\");\n });\n\n it(\"the Terms and Privacy pages are public, each with one h1 and one Contact Us\", () => {\n for (const path of [\"/terms\", \"/privacy\"]) expect(PUBLIC_ROUTES as readonly string[]).toContain(path);\n expect(PUBLIC_ROUTES as readonly string[]).not.toContain(\"/agree\");\n for (const Page of [TermsPage, PrivacyPage]) {\n const html = renderToStaticMarkup(createElement(Page));\n expect(html.match(/<h1/g)).toHaveLength(1);\n expect(html.match(/Contact Us/g)).toHaveLength(1);\n }\n });\n\n it(\"the agree page shows the full Terms, an UNticked required box, the version shown, and a way out\", async () => {\n h.current = await newPerson(\"pat@example.com\");\n const html = renderToStaticMarkup(await AgreePage({ searchParams: Promise.resolve({}) }));\n expect(html).toContain(\"hold them harmless\");\n // Read the one checkbox's attributes, in whatever order React writes them.\n const box = (html.match(/<input[^>]*name=\"agree\"[^>]*>/g) ?? [])[0] ?? \"\";\n expect(box).toMatch(/type=\"checkbox\"/);\n expect(box).toMatch(/\\brequired\\b/);\n expect(box).not.toMatch(/\\bchecked\\b/);\n expect(html).toContain(`name=\"version\" value=\"${CURRENT_TERMS_VERSION}\"`);\n expect(html).toContain('action=\"/logout\"');\n expect(html).not.toContain('role=\"alert\"');\n\n const refused = renderToStaticMarkup(await AgreePage({ searchParams: Promise.resolve({ error: \"unchecked\" }) }));\n expect(refused).toContain('role=\"alert\"');\n expect(refused).toContain(\"Please tick the box\");\n });\n\n it(\"every page's footer links the Terms and the Privacy Policy\", () => {\n const html = renderToStaticMarkup(createElement(SiteFooter));\n expect(html).toContain('href=\"/terms\"');\n expect(html).toContain('href=\"/privacy\"');\n });\n});\n",
51
+ };
@@ -48,6 +48,7 @@
48
48
  // see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
49
49
  import { prePushHookFiles, withHookScripts } from "./pre-push-hook.js";
50
50
  import { GUIDE_MODULE_TEMPLATE, GUIDE_PAGE_TEMPLATE, GUIDE_TEST_TEMPLATE, WHATS_NEW_PAGE_TEMPLATE, } from "./nextjs-guide.js";
51
+ import { LOGIN_DEPS, LOGIN_DEV_DEPS, LOGIN_ENV_BLOCK, LOGIN_SCRIPTS, loginFiles, loginGlobalsCss, loginSchema, wantsLogin, withLoginGuideExemptions, withNextAuthInlined, withSiteFooter, withTsExtensionImports, } from "./nextjs-auth/index.js";
51
52
  import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
52
53
  const NARRATIVE = `## What this is
53
54
 
@@ -431,6 +432,29 @@ export const securityHeaders = [
431
432
  { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), interest-cohort=()" },
432
433
  { key: "Content-Security-Policy", value: contentSecurityPolicy() },
433
434
  ];
435
+
436
+ /**
437
+ * The headers for THIS process. Identical to securityHeaders except under
438
+ * next dev, whose React Refresh and webpack runtime evaluate strings: without
439
+ * 'unsafe-eval' the dev page never hydrates, so no client component runs (a
440
+ * form's JavaScript, an autofocus effect, an auto-submitting code box) and a
441
+ * local check of anything interactive quietly tests a dead page. Found by
442
+ * booking, 2026-11-04.
443
+ *
444
+ * Gated on NODE_ENV === "development", which ONLY next dev sets: next build
445
+ * forces "production" for every build, Vercel previews included, so no
446
+ * deployed page ever carries 'unsafe-eval'. test/security-headers.test.ts pins
447
+ * both directions.
448
+ *
449
+ * @param {Record<string, string | undefined>} [env]
450
+ */
451
+ export function securityHeadersFor(env = process.env) {
452
+ if (env.NODE_ENV !== "development") return securityHeaders;
453
+ const dev = { ...cspDirectives, "script-src": [...cspDirectives["script-src"], "'unsafe-eval'"] };
454
+ return securityHeaders.map((h) =>
455
+ h.key === "Content-Security-Policy" ? { ...h, value: contentSecurityPolicy(dev) } : h,
456
+ );
457
+ }
434
458
  `;
435
459
  }
436
460
  /**
@@ -524,7 +548,7 @@ import { describe, it, expect } from "vitest";
524
548
  import { readFileSync } from "node:fs";
525
549
  import { join, dirname } from "node:path";
526
550
  import { fileURLToPath } from "node:url";
527
- import { cspDirectives, contentSecurityPolicy, securityHeaders } from "../lib/security-headers.mjs";
551
+ import { cspDirectives, contentSecurityPolicy, securityHeaders, securityHeadersFor } from "../lib/security-headers.mjs";
528
552
 
529
553
  const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
530
554
 
@@ -598,10 +622,23 @@ describe("security headers", () => {
598
622
  // browser.
599
623
  const config = readFileSync(join(ROOT, "next.config.mjs"), "utf8");
600
624
  expect(config).toContain("./lib/security-headers.mjs");
601
- expect(config).toContain("securityHeaders");
625
+ expect(config).toContain("securityHeadersFor(process.env)");
602
626
  expect(config).toContain("async headers()");
603
627
  });
604
628
 
629
+ it("next dev may eval, or the page never hydrates", () => {
630
+ const csp = securityHeadersFor({ NODE_ENV: "development" }).find((h) => h.key === "Content-Security-Policy");
631
+ expect(parseCsp(csp!.value)["script-src"]).toContain("'unsafe-eval'");
632
+ });
633
+
634
+ it("no build ever does: production, test and unset all get the shipped headers unchanged", () => {
635
+ for (const NODE_ENV of ["production", "test", undefined]) {
636
+ expect(securityHeadersFor({ NODE_ENV })).toBe(securityHeaders);
637
+ }
638
+ const shipped = securityHeaders.find((h) => h.key === "Content-Security-Policy");
639
+ expect(parseCsp(shipped!.value)["script-src"]).not.toContain("'unsafe-eval'");
640
+ });
641
+
605
642
  it("POSITIVE CONTROL: the parser detects a directive it should reject", () => {
606
643
  // Without this, deleting an assertion above leaves a suite that passes while
607
644
  // measuring nothing. Prove the parser can actually see a bad policy.
@@ -707,7 +744,7 @@ describe("JSON-LD escaping gate", () => {
707
744
  const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
708
745
 
709
746
  import { canonicalHost } from "./lib/seo/canonical-host.mjs";
710
- import { securityHeaders } from "./lib/security-headers.mjs";
747
+ import { securityHeadersFor } from "./lib/security-headers.mjs";
711
748
 
712
749
  // SEO: redirect EVERY auto-assigned PRODUCTION *.vercel.app alias to the custom
713
750
  // domain so none is crawled as an indexable duplicate of the whole site
@@ -739,7 +776,9 @@ const nextConfig = {
739
776
  // Applied from lib/security-headers.mjs so test/security-headers.test.ts can
740
777
  // EXECUTE the same values this config serves, rather than re-describing them.
741
778
  async headers() {
742
- return [{ source: "/:path*", headers: securityHeaders }];
779
+ // securityHeadersFor adds 'unsafe-eval' under next dev ONLY, or the dev page
780
+ // never hydrates; every build gets securityHeaders unchanged.
781
+ return [{ source: "/:path*", headers: securityHeadersFor(process.env) }];
743
782
  },
744
783
  async redirects() {
745
784
  const host = canonicalHost(process.env.NEXT_PUBLIC_SITE_URL);
@@ -809,7 +848,7 @@ export default nextConfig;
809
848
  */
810
849
  const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig} */
811
850
 
812
- import { securityHeaders } from "./lib/security-headers.mjs";
851
+ import { securityHeadersFor } from "./lib/security-headers.mjs";
813
852
 
814
853
  // HOST-ROUTED MULTI-TENANT APP — the incoming Host selects the tenant.
815
854
  //
@@ -827,7 +866,9 @@ const nextConfig = {
827
866
  // Applied from lib/security-headers.mjs so test/security-headers.test.ts can
828
867
  // EXECUTE the same values this config serves, rather than re-describing them.
829
868
  async headers() {
830
- return [{ source: "/:path*", headers: securityHeaders }];
869
+ // securityHeadersFor adds 'unsafe-eval' under next dev ONLY, or the dev page
870
+ // never hydrates; every build gets securityHeaders unchanged.
871
+ return [{ source: "/:path*", headers: securityHeadersFor(process.env) }];
831
872
  },
832
873
  };
833
874
 
@@ -5772,7 +5813,10 @@ describe("vercel.json Ignored Build Step", () => {
5772
5813
  export function scaffoldNextjs(inputs, opts) {
5773
5814
  const spec = resolveBrandSpec(inputs);
5774
5815
  const base = commonBaseFiles(inputs, opts, NARRATIVE);
5775
- const sendsEmail = inputs.sendsEmail === true;
5816
+ // Login (Step 57) sends its link by email, so it turns email on: the mailer,
5817
+ // its env block and its deps all key off `sendsEmail` below.
5818
+ const hasLogin = wantsLogin(inputs);
5819
+ const sendsEmail = inputs.sendsEmail === true || hasLogin;
5776
5820
  const hostRouted = inputs.hostRoutedTenancy === true;
5777
5821
  // Sentry is the default runtime-error tool for a customer-facing web app, and
5778
5822
  // `hasObservability` is where that intent is already recorded (it is the same
@@ -5818,6 +5862,11 @@ export function scaffoldNextjs(inputs, opts) {
5818
5862
  else if (durableLimit) {
5819
5863
  packageJson = withExtraDeps(packageJson, NEON_DRIVER_DEP);
5820
5864
  }
5865
+ if (hasLogin) {
5866
+ packageJson = withExtraDeps(packageJson, LOGIN_DEPS);
5867
+ packageJson = withExtraDevDeps(packageJson, LOGIN_DEV_DEPS);
5868
+ packageJson = withExtraScripts(packageJson, LOGIN_SCRIPTS);
5869
+ }
5821
5870
  // A test script nothing runs is not a gate (ROADMAP Step 52).
5822
5871
  packageJson = withHookScripts(packageJson);
5823
5872
  let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
@@ -5832,8 +5881,10 @@ export function scaffoldNextjs(inputs, opts) {
5832
5881
  envExample += EMAIL_ENV_BLOCK;
5833
5882
  // The host allowlist serves auth email (magic links derive URLs from the Host)
5834
5883
  // and Host-routed tenancy (the Host selects the tenant). Emitted once for both.
5884
+ // With login, the login block carries CANONICAL_HOSTS and describes the code
5885
+ // that is actually emitted; without it, the generic seam block does.
5835
5886
  if (sendsEmail || hostRouted)
5836
- envExample += CANONICAL_HOSTS_ENV_BLOCK;
5887
+ envExample += hasLogin ? LOGIN_ENV_BLOCK : CANONICAL_HOSTS_ENV_BLOCK;
5837
5888
  if (acceptsCards)
5838
5889
  envExample += CARD_PATH_ENV_BLOCK;
5839
5890
  const typeSpecific = [
@@ -5855,14 +5906,23 @@ export function scaffoldNextjs(inputs, opts) {
5855
5906
  path: "lib/seo/page-metadata.ts",
5856
5907
  content: sub(PAGE_METADATA_MODULE_TEMPLATE, inputs, opts, spec),
5857
5908
  },
5858
- { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
5859
- { path: "vitest.config.ts", content: VITEST_CONFIG_TEMPLATE },
5909
+ {
5910
+ path: "tsconfig.json",
5911
+ content: sub(hasLogin ? withTsExtensionImports(TSCONFIG_TEMPLATE) : TSCONFIG_TEMPLATE, inputs, opts, spec),
5912
+ },
5913
+ {
5914
+ path: "vitest.config.ts",
5915
+ content: hasLogin ? withNextAuthInlined(VITEST_CONFIG_TEMPLATE) : VITEST_CONFIG_TEMPLATE,
5916
+ },
5860
5917
  // Skip Vercel builds for prose-only pushes; the test guards the one case
5861
5918
  // where that would lose a deploy (a project that builds pages from Markdown).
5862
5919
  { path: "vercel.json", content: VERCEL_JSON },
5863
5920
  { path: "test/vercel-ignore.test.ts", content: VERCEL_IGNORE_TEST_TEMPLATE },
5864
5921
  { path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
5865
- { path: "app/globals.css", content: globalsCss(spec.primaryColor) },
5922
+ {
5923
+ path: "app/globals.css",
5924
+ content: globalsCss(spec.primaryColor) + (hasLogin ? loginGlobalsCss() : ""),
5925
+ },
5866
5926
  { path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
5867
5927
  { path: "components/InfoHintCloser.tsx", content: INFO_HINT_CLOSER_TEMPLATE },
5868
5928
  // The contrast pair table and the math it uses. Emitted unconditionally: the
@@ -5903,7 +5963,7 @@ export function scaffoldNextjs(inputs, opts) {
5903
5963
  : []),
5904
5964
  {
5905
5965
  path: "app/layout.tsx",
5906
- content: sub(pwa ? withPwaWiring(APP_LAYOUT_TEMPLATE) : APP_LAYOUT_TEMPLATE, inputs, opts, spec),
5966
+ content: sub(((layout) => (hasLogin ? withSiteFooter(layout) : layout))(pwa ? withPwaWiring(APP_LAYOUT_TEMPLATE) : APP_LAYOUT_TEMPLATE), inputs, opts, spec),
5907
5967
  },
5908
5968
  { path: "app/page.tsx", content: sub(APP_PAGE_TEMPLATE, inputs, opts, spec) },
5909
5969
  // The in-app user guide MECHANISM (Kerry, 2026-10-12: always, internal tools
@@ -5915,7 +5975,10 @@ export function scaffoldNextjs(inputs, opts) {
5915
5975
  path: "app/guide/whats-new/page.tsx",
5916
5976
  content: sub(WHATS_NEW_PAGE_TEMPLATE, inputs, opts, spec),
5917
5977
  },
5918
- { path: "test/guide.test.ts", content: sub(GUIDE_TEST_TEMPLATE, inputs, opts, spec) },
5978
+ {
5979
+ path: "test/guide.test.ts",
5980
+ content: sub(hasLogin ? withLoginGuideExemptions(GUIDE_TEST_TEMPLATE) : GUIDE_TEST_TEMPLATE, inputs, opts, spec),
5981
+ },
5919
5982
  { path: "lib/analytics/utm.ts", content: sub(ANALYTICS_UTM_TEMPLATE, inputs, opts, spec) },
5920
5983
  {
5921
5984
  path: "lib/analytics/Analytics.tsx",
@@ -5994,8 +6057,13 @@ export function scaffoldNextjs(inputs, opts) {
5994
6057
  typeSpecific.push({ path: "db/client.ts", content: sub(DB_CLIENT_TEMPLATE, inputs, opts, spec) }, { path: "db/pool-errors.ts", content: sub(DB_POOL_ERRORS_TEMPLATE, inputs, opts, spec) }, {
5995
6058
  path: "db/pool-errors.test.ts",
5996
6059
  content: sub(DB_POOL_ERRORS_TEST_TEMPLATE, inputs, opts, spec),
5997
- }, { path: "db/schema.ts", content: sub(DB_SCHEMA_TEMPLATE, inputs, opts, spec) }, { path: "db/client.test.ts", content: sub(DB_CLIENT_TEST_TEMPLATE, inputs, opts, spec) }, { path: "drizzle.config.ts", content: sub(DRIZZLE_CONFIG_TEMPLATE, inputs, opts, spec) });
6060
+ }, {
6061
+ path: "db/schema.ts",
6062
+ content: hasLogin ? loginSchema(inputs, opts, spec) : sub(DB_SCHEMA_TEMPLATE, inputs, opts, spec),
6063
+ }, { path: "db/client.test.ts", content: sub(DB_CLIENT_TEST_TEMPLATE, inputs, opts, spec) }, { path: "drizzle.config.ts", content: sub(DRIZZLE_CONFIG_TEMPLATE, inputs, opts, spec) });
5998
6064
  }
6065
+ if (hasLogin)
6066
+ typeSpecific.push(...loginFiles(inputs, opts, spec));
5999
6067
  return [...base, ...typeSpecific];
6000
6068
  }
6001
6069
  /**
package/dist/summary.js CHANGED
@@ -139,6 +139,26 @@ function buildNextActions(inputs, result, repoAutoCreated) {
139
139
  note: "see [[neon-postgres]] new-project checklist — a fixed 1 CU bills 1 CU for every awake second (up to 4x a 0.25 floor); keep /health DB-free, pool size 1 in monitoring contexts",
140
140
  });
141
141
  }
142
+ // The login needs three things before anyone can sign in, and none of them
143
+ // fails loudly when missing: no AUTH_SECRET and Auth.js refuses to start; no
144
+ // tables and the send gate quietly sends nothing; no provisioned user and
145
+ // every address gets the same "check your email" screen (invite-only by
146
+ // design, so it never says why).
147
+ if (inputs.hasLogin === true && inputs.projectType === "nextjs") {
148
+ actions.push({
149
+ label: `Set AUTH_SECRET in .env.local, and a different one in each Vercel environment: openssl rand -base64 33`,
150
+ note: "Auth.js refuses to start without it. Set CANONICAL_HOSTS in production to the hostnames login links may point at (no https://); unset means NONE, not all. Never set AUTH_URL.",
151
+ }, {
152
+ label: `npm run db:push`,
153
+ note: "creates the users, tenants and login tables in DATABASE_URL (run it against each database: local, then production)",
154
+ }, {
155
+ label: `npm run user:provision -- --email YOUR-EMAIL --first-name YOUR-FIRST-NAME`,
156
+ note: "login is invite-only: until this runs, every address gets the same \"check your email\" screen and no email. Run it against production by pointing DATABASE_URL there.",
157
+ }, {
158
+ label: `Before launch, replace OPERATOR, OPERATOR-WEBSITE and the contact URL in lib/terms.ts, and have the operator approve the Terms and Privacy text`,
159
+ note: "the text in components/TermsText.tsx and components/PrivacyText.tsx is a plain-English draft, NOT reviewed by a lawyer. Add a section when the app gains reminders, content other people see, payments, or anything that reads as medical or legal help; bump CURRENT_TERMS_VERSION whenever the Terms wording changes.",
160
+ });
161
+ }
142
162
  if (isDecisionInserted(result.decisions, "uptime-kuma")) {
143
163
  actions.push({
144
164
  // The keyword is the project's own identity token. This line said
package/dist/wizard.js CHANGED
@@ -176,6 +176,17 @@ export async function runWizard(opts) {
176
176
  // search index, which is slow to undo and has already happened by then. So
177
177
  // the operator must say yes on purpose.
178
178
  const hasPublicSurface = await askValidated(prompter, "8h. Public surface — should search engines index this, or is it an internal/staff tool (yes/no):", parseYesNo, "no", out);
179
+ // Asked only where login can be emitted (nextjs + neon-postgres + web UI);
180
+ // anywhere else the write path would refuse it, so asking would only offer a
181
+ // dead end. Default NO: whether an app has accounts is a product decision.
182
+ // A yes turns email on, because a login link has to be sent.
183
+ let hasLogin = false;
184
+ if (projectType === "nextjs" && dbStrategy === "neon-postgres" && hasWebUi) {
185
+ hasLogin = await askValidated(prompter, "8i. Invite-only login — magic link plus a typed 8-digit code (yes/no):", parseYesNo, "no", out);
186
+ if (hasLogin && !sendsEmail) {
187
+ out.write("\n → Email turned on (8d): a login link has to be sent.\n");
188
+ }
189
+ }
179
190
  const result = {
180
191
  slug,
181
192
  description,
@@ -187,12 +198,15 @@ export async function runWizard(opts) {
187
198
  hasWebUi,
188
199
  hasCron,
189
200
  participateInBulletin,
190
- sendsEmail,
201
+ sendsEmail: sendsEmail || hasLogin,
191
202
  hasUserContent,
192
203
  hasObservability,
193
204
  acceptsCards,
194
205
  hasPublicSurface,
195
206
  };
207
+ if (hasLogin) {
208
+ result.hasLogin = true;
209
+ }
196
210
  if (customBrand) {
197
211
  result.customBrand = customBrand;
198
212
  }
package/dist/writer.js CHANGED
@@ -27,6 +27,7 @@ import { applyGateToDecisions, classifyUnfoundSections, EXTERNAL_DROPPED_SECTION
27
27
  import { AGENT_COORDINATION_BLOCK_MARKER, AGENTS_BODY_MARKER, STANDARDS_BLOCK_MARKER, } from "./scaffolders/common.js";
28
28
  import { buildProSeoExtension, proSeoApplies, } from "./scaffolders/pro-seo-extension.js";
29
29
  import { scaffoldByType } from "./scaffolders/index.js";
30
+ import { validateLoginInputs } from "./scaffolders/nextjs-auth/index.js";
30
31
  import { applyAgentCoordinationBlock, applyCaptureLearningsBlock, applyStandardsBlock, literalReplacement, resolveStandards, } from "./standards.js";
31
32
  import { resolveAgentsTemplate, } from "./templates.js";
32
33
  export class WriterError extends Error {
@@ -192,6 +193,10 @@ export async function writeScaffold(inputs, targetPath, opts = {}) {
192
193
  if (!path.isAbsolute(targetPath)) {
193
194
  throw new WriterError(`targetPath must be absolute. Got: ${JSON.stringify(targetPath)}.`);
194
195
  }
196
+ // Refuse login where it cannot work, before any file is read or written.
197
+ const loginProblem = validateLoginInputs(inputs);
198
+ if (loginProblem)
199
+ throw new WriterError(loginProblem);
195
200
  const resolvedTarget = path.resolve(targetPath);
196
201
  // Resolve the canonical AGENTS body FIRST — its filename is the single source
197
202
  // of truth for {{framework_version}}, which Layer 1 substitutes into the
@@ -557,6 +562,15 @@ export function parseScaffoldInputs(json) {
557
562
  }
558
563
  inputs.sendsEmail = obj["sendsEmail"];
559
564
  }
565
+ // Optional: invite-only magic-link login with the typed 8-digit code (Step 57).
566
+ // Defaults to false. nextjs + neon-postgres + hasWebUi only; writeScaffold
567
+ // refuses any other combination.
568
+ if (obj["hasLogin"] !== undefined) {
569
+ if (typeof obj["hasLogin"] !== "boolean") {
570
+ throw new WriterError(`--input field "hasLogin" must be a boolean, got ${typeof obj["hasLogin"]}.`);
571
+ }
572
+ inputs.hasLogin = obj["hasLogin"];
573
+ }
560
574
  // Optional: whether this project accepts user-generated content. Defaults to
561
575
  // false (no moderation standard). Gates the [[moderation-system]] standard for
562
576
  // non-WP app types (skipped for wp-plugin / library / protocol-repo).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.51.1",
3
+ "version": "0.54.1",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",