@zero2webmaster/starter-kit 0.52.0 → 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 +2 -2
- package/dist/confirm.d.ts +1 -0
- package/dist/confirm.js +47 -9
- package/dist/parse-brief.d.ts +8 -0
- package/dist/parse-brief.js +29 -2
- package/dist/scaffolders/nextjs-auth/index.d.ts +6 -0
- package/dist/scaffolders/nextjs-auth/index.js +31 -2
- package/dist/scaffolders/nextjs-auth/templates.generated.js +16 -6
- package/dist/scaffolders/nextjs.js +48 -8
- package/dist/summary.js +20 -0
- package/dist/wizard.js +15 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# z2w-starter-kit
|
|
2
2
|
|
|
3
|
-
**Version:** 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
|
|
|
@@ -154,4 +154,4 @@ Inquiries: kerry@zero2webmaster.com.
|
|
|
154
154
|
---
|
|
155
155
|
|
|
156
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.*
|
|
157
|
-
*Version: 0.
|
|
157
|
+
*Version: 0.54.1 | Last Updated: 2026-11-04*
|
package/dist/confirm.d.ts
CHANGED
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
|
|
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
|
-
?
|
|
383
|
-
:
|
|
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
|
-
|
|
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 >
|
|
401
|
-
output.write(`\n ✗ "${reply}" is not a line number (1
|
|
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
|
-
|
|
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/parse-brief.d.ts
CHANGED
|
@@ -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;
|
package/dist/parse-brief.js
CHANGED
|
@@ -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
|
|
799
|
+
dbStrategy,
|
|
775
800
|
hasWebUi,
|
|
776
801
|
hasCron: inferHasCron(trimmed),
|
|
777
802
|
participateInBulletin: inferParticipateInBulletin(trimmed, brand),
|
|
778
|
-
|
|
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
|
};
|
|
@@ -29,6 +29,12 @@ export declare function withTsExtensionImports(tsconfig: string): string;
|
|
|
29
29
|
* describes the code that is actually emitted.
|
|
30
30
|
*/
|
|
31
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;
|
|
32
38
|
/**
|
|
33
39
|
* vitest runs `next-auth` through Node's own resolver, which refuses its bare
|
|
34
40
|
* `next/server` import (no extension). Inlining it makes vite resolve it, as
|
|
@@ -109,6 +109,21 @@ CANONICAL_HOSTS=
|
|
|
109
109
|
# CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on
|
|
110
110
|
# several domains.
|
|
111
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
|
+
}
|
|
112
127
|
/**
|
|
113
128
|
* vitest runs `next-auth` through Node's own resolver, which refuses its bare
|
|
114
129
|
* `next/server` import (no extension). Inlining it makes vite resolve it, as
|
|
@@ -117,11 +132,22 @@ CANONICAL_HOSTS=
|
|
|
117
132
|
*/
|
|
118
133
|
export function withNextAuthInlined(vitestConfig) {
|
|
119
134
|
const anchor = ' exclude: ["node_modules/**", ".next/**", "dist/**"],\n';
|
|
120
|
-
if (!vitestConfig.includes(anchor))
|
|
121
|
-
throw new Error("vitest config template changed: cannot inline next-auth");
|
|
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
|
+
}
|
|
122
138
|
return vitestConfig.replace(anchor, `${anchor} // next-auth imports the bare specifier \`next/server\`, which Node's resolver
|
|
123
139
|
// refuses; inlined, vite resolves it the way \`next build\` does.
|
|
124
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: {
|
|
125
151
|
`);
|
|
126
152
|
}
|
|
127
153
|
/** The login pages explain themselves; the guide test is told so, with reasons. */
|
|
@@ -136,6 +162,9 @@ export function withLoginGuideExemptions(guideTest) {
|
|
|
136
162
|
' "/login/check-email": "Reached only from the login form; it explains itself.",',
|
|
137
163
|
' "/login/error": "Reached only from a failed login link; it explains itself.",',
|
|
138
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.",',
|
|
139
168
|
];
|
|
140
169
|
return guideTest.slice(0, lineEnd) + rows.join("\n") + "\n" + guideTest.slice(lineEnd);
|
|
141
170
|
}
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// edit src/scaffolders/nextjs-auth/templates/ and run
|
|
3
3
|
// `node scripts/embed-login-templates.mjs`.
|
|
4
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’t agree, please don’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",
|
|
5
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",
|
|
6
|
-
"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//
|
|
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’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",
|
|
7
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",
|
|
8
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",
|
|
9
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,9 +14,14 @@ export const LOGIN_TEMPLATES = {
|
|
|
12
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’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",
|
|
13
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",
|
|
14
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",
|
|
15
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",
|
|
16
|
-
"
|
|
17
|
-
"
|
|
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 “Last modified” 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",
|
|
18
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",
|
|
19
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",
|
|
20
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",
|
|
@@ -24,12 +31,13 @@ export const LOGIN_TEMPLATES = {
|
|
|
24
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",
|
|
25
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",
|
|
26
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",
|
|
27
|
-
"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 { LOGIN_PATH } from \"@/lib/routes\";\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
|
|
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",
|
|
28
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",
|
|
29
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",
|
|
30
|
-
"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/** Pages a visitor without a session can see. Add each new public page here. */\nexport const PUBLIC_ROUTES = [\"/\"
|
|
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",
|
|
31
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",
|
|
32
|
-
"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",
|
|
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",
|
|
33
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",
|
|
34
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",
|
|
35
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",
|
|
@@ -38,4 +46,6 @@ export const LOGIN_TEMPLATES = {
|
|
|
38
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&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",
|
|
39
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",
|
|
40
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",
|
|
41
51
|
};
|
|
@@ -48,7 +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, withTsExtensionImports, } from "./nextjs-auth/index.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";
|
|
52
52
|
import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
|
|
53
53
|
const NARRATIVE = `## What this is
|
|
54
54
|
|
|
@@ -432,6 +432,29 @@ export const securityHeaders = [
|
|
|
432
432
|
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), interest-cohort=()" },
|
|
433
433
|
{ key: "Content-Security-Policy", value: contentSecurityPolicy() },
|
|
434
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
|
+
}
|
|
435
458
|
`;
|
|
436
459
|
}
|
|
437
460
|
/**
|
|
@@ -525,7 +548,7 @@ import { describe, it, expect } from "vitest";
|
|
|
525
548
|
import { readFileSync } from "node:fs";
|
|
526
549
|
import { join, dirname } from "node:path";
|
|
527
550
|
import { fileURLToPath } from "node:url";
|
|
528
|
-
import { cspDirectives, contentSecurityPolicy, securityHeaders } from "../lib/security-headers.mjs";
|
|
551
|
+
import { cspDirectives, contentSecurityPolicy, securityHeaders, securityHeadersFor } from "../lib/security-headers.mjs";
|
|
529
552
|
|
|
530
553
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
531
554
|
|
|
@@ -599,10 +622,23 @@ describe("security headers", () => {
|
|
|
599
622
|
// browser.
|
|
600
623
|
const config = readFileSync(join(ROOT, "next.config.mjs"), "utf8");
|
|
601
624
|
expect(config).toContain("./lib/security-headers.mjs");
|
|
602
|
-
expect(config).toContain("
|
|
625
|
+
expect(config).toContain("securityHeadersFor(process.env)");
|
|
603
626
|
expect(config).toContain("async headers()");
|
|
604
627
|
});
|
|
605
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
|
+
|
|
606
642
|
it("POSITIVE CONTROL: the parser detects a directive it should reject", () => {
|
|
607
643
|
// Without this, deleting an assertion above leaves a suite that passes while
|
|
608
644
|
// measuring nothing. Prove the parser can actually see a bad policy.
|
|
@@ -708,7 +744,7 @@ describe("JSON-LD escaping gate", () => {
|
|
|
708
744
|
const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
|
|
709
745
|
|
|
710
746
|
import { canonicalHost } from "./lib/seo/canonical-host.mjs";
|
|
711
|
-
import {
|
|
747
|
+
import { securityHeadersFor } from "./lib/security-headers.mjs";
|
|
712
748
|
|
|
713
749
|
// SEO: redirect EVERY auto-assigned PRODUCTION *.vercel.app alias to the custom
|
|
714
750
|
// domain so none is crawled as an indexable duplicate of the whole site
|
|
@@ -740,7 +776,9 @@ const nextConfig = {
|
|
|
740
776
|
// Applied from lib/security-headers.mjs so test/security-headers.test.ts can
|
|
741
777
|
// EXECUTE the same values this config serves, rather than re-describing them.
|
|
742
778
|
async headers() {
|
|
743
|
-
|
|
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) }];
|
|
744
782
|
},
|
|
745
783
|
async redirects() {
|
|
746
784
|
const host = canonicalHost(process.env.NEXT_PUBLIC_SITE_URL);
|
|
@@ -810,7 +848,7 @@ export default nextConfig;
|
|
|
810
848
|
*/
|
|
811
849
|
const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig} */
|
|
812
850
|
|
|
813
|
-
import {
|
|
851
|
+
import { securityHeadersFor } from "./lib/security-headers.mjs";
|
|
814
852
|
|
|
815
853
|
// HOST-ROUTED MULTI-TENANT APP — the incoming Host selects the tenant.
|
|
816
854
|
//
|
|
@@ -828,7 +866,9 @@ const nextConfig = {
|
|
|
828
866
|
// Applied from lib/security-headers.mjs so test/security-headers.test.ts can
|
|
829
867
|
// EXECUTE the same values this config serves, rather than re-describing them.
|
|
830
868
|
async headers() {
|
|
831
|
-
|
|
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) }];
|
|
832
872
|
},
|
|
833
873
|
};
|
|
834
874
|
|
|
@@ -5923,7 +5963,7 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5923
5963
|
: []),
|
|
5924
5964
|
{
|
|
5925
5965
|
path: "app/layout.tsx",
|
|
5926
|
-
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),
|
|
5927
5967
|
},
|
|
5928
5968
|
{ path: "app/page.tsx", content: sub(APP_PAGE_TEMPLATE, inputs, opts, spec) },
|
|
5929
5969
|
// The in-app user guide MECHANISM (Kerry, 2026-10-12: always, internal tools
|
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
|
}
|