@zero2webmaster/starter-kit 0.51.1 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/index.d.ts +13 -0
- package/dist/index.js +4 -0
- package/dist/scaffolders/nextjs-auth/index.d.ts +40 -0
- package/dist/scaffolders/nextjs-auth/index.js +141 -0
- package/dist/scaffolders/nextjs-auth/templates.generated.d.ts +1 -0
- package/dist/scaffolders/nextjs-auth/templates.generated.js +41 -0
- package/dist/scaffolders/nextjs.js +35 -7
- package/dist/writer.js +14 -0
- 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.52.0 | **Framework:** 2.19.0
|
|
4
4
|
|
|
5
5
|
> Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
|
|
6
6
|
|
|
@@ -84,7 +84,8 @@ The Claude Code skill at `~/.claude/skills/instantiate-z2w-project/SKILL.md` and
|
|
|
84
84
|
|
|
85
85
|
## Status
|
|
86
86
|
|
|
87
|
-
- **v0.
|
|
87
|
+
- **v0.52.0 (current)** can give a `nextjs` project invite-only login (`hasLogin`, through `--input` or the programmatic API). The login email has a button and an 8-digit code; the code can be typed into the app when it is installed on a phone's home screen, where a tapped link would open the wrong browser. The scaffold gets the login pages, Auth.js setup, the user and account tables, a script to invite the first owner, and tests that log in end to end against an in-memory database. Requires `neon-postgres` and a web UI, and turns email on.
|
|
88
|
+
- **v0.51.1** stops outside customers' scaffolds from naming us in four `nextjs` database comments, drops comment lines that only pointed at a private skill, and credits only `@zero2webmaster/starter-kit` in the footer. Its coordination pointer names the bulletin clone's new `AI/Projects` path.
|
|
88
89
|
- **v0.51.0** gets ready for the portfolio folder `~/Desktop/Zero2Webmaster/AI/Cursor Projects/` to be renamed `~/Desktop/Zero2Webmaster/AI/Projects/`. It looks for the Templates folder at `AI/Projects/agent-framework/` first, then at `AI/Cursor Projects/agent-framework/`, then at the old `AI/Templates/`. The portfolio sweeps and the bulletin lookups follow the rename too, and never count the same folder twice once the old name is a symlink.
|
|
89
90
|
- **v0.50.0** looks for the Templates folder at `~/Desktop/Zero2Webmaster/AI/Cursor Projects/agent-framework/` first and falls back to the old `~/Desktop/Zero2Webmaster/AI/Templates/`, so the folder can move without breaking project creation. If neither folder is usable, the error names both.
|
|
90
91
|
- **v0.49.0** gives the Uptime Kuma next-action the project's own keyword (it still said `"status":"ok"`), tells bulletin projects to report each new monitor to `kuma-watchdog` and to notify `audit-engine` when a project is scaffolded, and extends the American English rule to internal labels such as form and database names.
|
|
@@ -153,4 +154,4 @@ Inquiries: kerry@zero2webmaster.com.
|
|
|
153
154
|
---
|
|
154
155
|
|
|
155
156
|
*Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
|
|
156
|
-
*Version: 0.
|
|
157
|
+
*Version: 0.52.0 | Last Updated: 2026-11-02*
|
package/dist/index.d.ts
CHANGED
|
@@ -157,6 +157,19 @@ export interface ScaffoldInputs {
|
|
|
157
157
|
* `python-service` is a different language, so those types ignore this flag.
|
|
158
158
|
*/
|
|
159
159
|
sendsEmail?: boolean;
|
|
160
|
+
/**
|
|
161
|
+
* Invite-only magic-link login (ROADMAP Step 57, Kerry 2026-11-02), ported
|
|
162
|
+
* from `pharmies`: Auth.js v5, JWT sessions, a send gate that never reveals
|
|
163
|
+
* who has an account, and the login code printed in the email as 8 digits so
|
|
164
|
+
* an app installed on a phone's home screen can be logged into by typing it.
|
|
165
|
+
* Emits the login pages, `auth.ts`, `lib/auth/*`, the users/tenants tables in
|
|
166
|
+
* `db/schema.ts`, `scripts/provision-user.ts` and their tests.
|
|
167
|
+
*
|
|
168
|
+
* Optional, defaults to `false`. Requires `projectType: "nextjs"`,
|
|
169
|
+
* `dbStrategy: "neon-postgres"` and `hasWebUi`; the write path refuses
|
|
170
|
+
* anything else. Turns `sendsEmail` on, because a login link must be sent.
|
|
171
|
+
*/
|
|
172
|
+
hasLogin?: boolean;
|
|
160
173
|
/**
|
|
161
174
|
* Whether this project accepts user-generated content (UGC) — a community
|
|
162
175
|
* platform, events app with public listings, marketplace, comments/forum,
|
package/dist/index.js
CHANGED
|
@@ -22,6 +22,7 @@ import * as path from "node:path";
|
|
|
22
22
|
import { Writable } from "node:stream";
|
|
23
23
|
import { isValidSlug } from "./parse-brief.js";
|
|
24
24
|
import { writeScaffold } from "./writer.js";
|
|
25
|
+
import { validateLoginInputs } from "./scaffolders/nextjs-auth/index.js";
|
|
25
26
|
/**
|
|
26
27
|
* This package's version, READ FROM `package.json` at load time rather than
|
|
27
28
|
* written here by hand.
|
|
@@ -161,6 +162,9 @@ export function validateScaffoldInputs(inputs) {
|
|
|
161
162
|
if (typeof inputs.targetPath !== "string" || !path.isAbsolute(inputs.targetPath)) {
|
|
162
163
|
errors.push(`targetPath must be an absolute path. Got: ${JSON.stringify(inputs.targetPath)}.`);
|
|
163
164
|
}
|
|
165
|
+
const loginProblem = validateLoginInputs(inputs);
|
|
166
|
+
if (loginProblem)
|
|
167
|
+
errors.push(loginProblem);
|
|
164
168
|
if (inputs.brand === "custom") {
|
|
165
169
|
const cb = inputs.customBrand;
|
|
166
170
|
if (!cb || typeof cb !== "object") {
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { BrandPresetSpec } from "../../brand.js";
|
|
2
|
+
import type { ScaffoldInputs } from "../../index.js";
|
|
3
|
+
import { type ScaffoldFile, type ScaffolderOptions } from "../common.js";
|
|
4
|
+
/** True when this scaffold gets login. */
|
|
5
|
+
export declare function wantsLogin(inputs: ScaffoldInputs): boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Refuses an input set that asks for login where it cannot work. Returns an
|
|
8
|
+
* error message, or null when the inputs are fine (or login is off).
|
|
9
|
+
*/
|
|
10
|
+
export declare function validateLoginInputs(inputs: ScaffoldInputs): string | null;
|
|
11
|
+
/** Every emitted login file, substituted. Excludes the schema and the CSS block, which merge into other files. */
|
|
12
|
+
export declare function loginFiles(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): ScaffoldFile[];
|
|
13
|
+
/** `db/schema.ts` with the login tables, replacing the placeholder `example` table. */
|
|
14
|
+
export declare function loginSchema(inputs: ScaffoldInputs, opts: ScaffolderOptions | undefined, spec: BrandPresetSpec): string;
|
|
15
|
+
/** Appended to `app/globals.css`: the few classes the login pages use. */
|
|
16
|
+
export declare function loginGlobalsCss(): string;
|
|
17
|
+
export declare const LOGIN_DEPS: Readonly<Record<string, string>>;
|
|
18
|
+
export declare const LOGIN_DEV_DEPS: Readonly<Record<string, string>>;
|
|
19
|
+
export declare const LOGIN_SCRIPTS: Readonly<Record<string, string>>;
|
|
20
|
+
/**
|
|
21
|
+
* scripts/provision-user.ts runs under plain Node, which needs real `.ts`
|
|
22
|
+
* import paths; tsconfig must allow them. `noEmit` is already on, which this
|
|
23
|
+
* option requires.
|
|
24
|
+
*/
|
|
25
|
+
export declare function withTsExtensionImports(tsconfig: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* The env block for login. Replaces the generic CANONICAL_HOSTS block, whose
|
|
28
|
+
* prose describes a seam for an app that writes its own auth; this one
|
|
29
|
+
* describes the code that is actually emitted.
|
|
30
|
+
*/
|
|
31
|
+
export declare const LOGIN_ENV_BLOCK = "\n# Login (magic link + 8-digit code)\n\nAUTH_SECRET=\nCANONICAL_HOSTS=\n\n# AUTH_SECRET signs the session cookie. Required: Auth.js refuses to run\n# without it. Make one with:\n# openssl rand -base64 33\n# Use a different value in each environment (local, preview, production).\n#\n# CANONICAL_HOSTS is the comma-separated list of hostnames a login link may\n# point at, such as app.example.com,www.example.com (no https://, no path).\n# Unset or empty means NONE, not all. Off production, loopback hosts\n# (localhost, 127.0.0.1) are also allowed, so local login works without it. A\n# preview deployment that must send real login links lists its own host here.\n#\n# Do NOT set AUTH_URL. The app trusts the request's Host and checks it against\n# CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on\n# several domains.\n";
|
|
32
|
+
/**
|
|
33
|
+
* vitest runs `next-auth` through Node's own resolver, which refuses its bare
|
|
34
|
+
* `next/server` import (no extension). Inlining it makes vite resolve it, as
|
|
35
|
+
* `next build` does. Without this, test/auth-flow.test.ts fails to LOAD while
|
|
36
|
+
* `tsc` and `next build` both pass.
|
|
37
|
+
*/
|
|
38
|
+
export declare function withNextAuthInlined(vitestConfig: string): string;
|
|
39
|
+
/** The login pages explain themselves; the guide test is told so, with reasons. */
|
|
40
|
+
export declare function withLoginGuideExemptions(guideTest: string): string;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Invite-only magic-link login for `nextjs` scaffolds (`hasLogin`, ROADMAP Step 57).
|
|
2
|
+
//
|
|
3
|
+
// Ported from `pharmies`, the reference implementation: Auth.js v5 with an
|
|
4
|
+
// email provider whose token IS an 8-digit code, printed in the email beside
|
|
5
|
+
// the button, so a person using the app from a phone's home screen can type it
|
|
6
|
+
// instead of tapping a link that opens the wrong browser. JWT sessions, a
|
|
7
|
+
// create-refusing adapter with a phantom user, a send gate that never reveals
|
|
8
|
+
// who has an account, a host allowlist, shared limits on live codes and wrong
|
|
9
|
+
// guesses, and audit rows for login and logout.
|
|
10
|
+
//
|
|
11
|
+
// The emitted files live as real source under ./templates/ and are embedded by
|
|
12
|
+
// scripts/embed-login-templates.mjs into ./templates.generated.ts. Edit the
|
|
13
|
+
// templates, never the generated file.
|
|
14
|
+
//
|
|
15
|
+
// Preconditions (checked by validateLoginInputs, called from scaffold()):
|
|
16
|
+
// `nextjs`, `dbStrategy: "neon-postgres"`, and `hasWebUi`. Login also turns
|
|
17
|
+
// email on, because a login link has to be sent.
|
|
18
|
+
import { sub } from "../common.js";
|
|
19
|
+
import { LOGIN_TEMPLATES } from "./templates.generated.js";
|
|
20
|
+
/** Template keys that are not emitted as files of their own. */
|
|
21
|
+
const SCHEMA_KEY = "db/schema.ts";
|
|
22
|
+
const CSS_KEY = "snippets/globals-login.css";
|
|
23
|
+
function template(key) {
|
|
24
|
+
const body = LOGIN_TEMPLATES[key];
|
|
25
|
+
if (body === undefined)
|
|
26
|
+
throw new Error(`login template missing: ${key}`);
|
|
27
|
+
return body;
|
|
28
|
+
}
|
|
29
|
+
/** True when this scaffold gets login. */
|
|
30
|
+
export function wantsLogin(inputs) {
|
|
31
|
+
return inputs.hasLogin === true;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Refuses an input set that asks for login where it cannot work. Returns an
|
|
35
|
+
* error message, or null when the inputs are fine (or login is off).
|
|
36
|
+
*/
|
|
37
|
+
export function validateLoginInputs(inputs) {
|
|
38
|
+
if (!wantsLogin(inputs))
|
|
39
|
+
return null;
|
|
40
|
+
const problems = [];
|
|
41
|
+
if (inputs.projectType !== "nextjs")
|
|
42
|
+
problems.push(`the project type is "${inputs.projectType}", and login is built for "nextjs" only`);
|
|
43
|
+
if (inputs.dbStrategy !== "neon-postgres")
|
|
44
|
+
problems.push(`the database is "${inputs.dbStrategy}", and login stores its users in "neon-postgres"`);
|
|
45
|
+
if (inputs.hasWebUi !== true)
|
|
46
|
+
problems.push("the project has no web UI, and login is a set of pages");
|
|
47
|
+
if (problems.length === 0)
|
|
48
|
+
return null;
|
|
49
|
+
return `hasLogin is on, but ${problems.join("; ")}. Turn hasLogin off, or change those inputs.`;
|
|
50
|
+
}
|
|
51
|
+
/** Every emitted login file, substituted. Excludes the schema and the CSS block, which merge into other files. */
|
|
52
|
+
export function loginFiles(inputs, opts, spec) {
|
|
53
|
+
return Object.keys(LOGIN_TEMPLATES)
|
|
54
|
+
.filter((key) => key !== SCHEMA_KEY && !key.startsWith("snippets/"))
|
|
55
|
+
.map((path) => ({ path, content: sub(template(path), inputs, opts, spec) }));
|
|
56
|
+
}
|
|
57
|
+
/** `db/schema.ts` with the login tables, replacing the placeholder `example` table. */
|
|
58
|
+
export function loginSchema(inputs, opts, spec) {
|
|
59
|
+
return sub(template(SCHEMA_KEY), inputs, opts, spec);
|
|
60
|
+
}
|
|
61
|
+
/** Appended to `app/globals.css`: the few classes the login pages use. */
|
|
62
|
+
export function loginGlobalsCss() {
|
|
63
|
+
return template(CSS_KEY);
|
|
64
|
+
}
|
|
65
|
+
export const LOGIN_DEPS = {
|
|
66
|
+
"next-auth": "^5.0.0-beta.32",
|
|
67
|
+
};
|
|
68
|
+
export const LOGIN_DEV_DEPS = {
|
|
69
|
+
// An in-memory Postgres for test/auth-adapter.test.ts and test/auth-flow.test.ts.
|
|
70
|
+
"@electric-sql/pglite": "^0.5.14",
|
|
71
|
+
};
|
|
72
|
+
export const LOGIN_SCRIPTS = {
|
|
73
|
+
"user:provision": "node --env-file=.env.local scripts/provision-user.ts",
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* scripts/provision-user.ts runs under plain Node, which needs real `.ts`
|
|
77
|
+
* import paths; tsconfig must allow them. `noEmit` is already on, which this
|
|
78
|
+
* option requires.
|
|
79
|
+
*/
|
|
80
|
+
export function withTsExtensionImports(tsconfig) {
|
|
81
|
+
const anchor = '"noEmit": true,';
|
|
82
|
+
if (!tsconfig.includes(anchor))
|
|
83
|
+
throw new Error("tsconfig template changed: cannot add allowImportingTsExtensions");
|
|
84
|
+
return tsconfig.replace(anchor, `${anchor}\n "allowImportingTsExtensions": true,`);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The env block for login. Replaces the generic CANONICAL_HOSTS block, whose
|
|
88
|
+
* prose describes a seam for an app that writes its own auth; this one
|
|
89
|
+
* describes the code that is actually emitted.
|
|
90
|
+
*/
|
|
91
|
+
export const LOGIN_ENV_BLOCK = `
|
|
92
|
+
# Login (magic link + 8-digit code)
|
|
93
|
+
|
|
94
|
+
AUTH_SECRET=
|
|
95
|
+
CANONICAL_HOSTS=
|
|
96
|
+
|
|
97
|
+
# AUTH_SECRET signs the session cookie. Required: Auth.js refuses to run
|
|
98
|
+
# without it. Make one with:
|
|
99
|
+
# openssl rand -base64 33
|
|
100
|
+
# Use a different value in each environment (local, preview, production).
|
|
101
|
+
#
|
|
102
|
+
# CANONICAL_HOSTS is the comma-separated list of hostnames a login link may
|
|
103
|
+
# point at, such as app.example.com,www.example.com (no https://, no path).
|
|
104
|
+
# Unset or empty means NONE, not all. Off production, loopback hosts
|
|
105
|
+
# (localhost, 127.0.0.1) are also allowed, so local login works without it. A
|
|
106
|
+
# preview deployment that must send real login links lists its own host here.
|
|
107
|
+
#
|
|
108
|
+
# Do NOT set AUTH_URL. The app trusts the request's Host and checks it against
|
|
109
|
+
# CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on
|
|
110
|
+
# several domains.
|
|
111
|
+
`;
|
|
112
|
+
/**
|
|
113
|
+
* vitest runs `next-auth` through Node's own resolver, which refuses its bare
|
|
114
|
+
* `next/server` import (no extension). Inlining it makes vite resolve it, as
|
|
115
|
+
* `next build` does. Without this, test/auth-flow.test.ts fails to LOAD while
|
|
116
|
+
* `tsc` and `next build` both pass.
|
|
117
|
+
*/
|
|
118
|
+
export function withNextAuthInlined(vitestConfig) {
|
|
119
|
+
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");
|
|
122
|
+
return vitestConfig.replace(anchor, `${anchor} // next-auth imports the bare specifier \`next/server\`, which Node's resolver
|
|
123
|
+
// refuses; inlined, vite resolves it the way \`next build\` does.
|
|
124
|
+
server: { deps: { inline: ["next-auth", "@auth/core"] } },
|
|
125
|
+
`);
|
|
126
|
+
}
|
|
127
|
+
/** The login pages explain themselves; the guide test is told so, with reasons. */
|
|
128
|
+
export function withLoginGuideExemptions(guideTest) {
|
|
129
|
+
const anchor = ' "/": "The scaffold\'s placeholder home page.';
|
|
130
|
+
const at = guideTest.indexOf(anchor);
|
|
131
|
+
if (at < 0)
|
|
132
|
+
throw new Error("guide test template changed: cannot add the login pages");
|
|
133
|
+
const lineEnd = guideTest.indexOf("\n", at) + 1;
|
|
134
|
+
const rows = [
|
|
135
|
+
' "/login": "The login page explains itself, and a person reads the guide only after logging in.",',
|
|
136
|
+
' "/login/check-email": "Reached only from the login form; it explains itself.",',
|
|
137
|
+
' "/login/error": "Reached only from a failed login link; it explains itself.",',
|
|
138
|
+
' "/dashboard": "The scaffold\'s placeholder logged-in page. When it becomes a real screen, explain it in a guide section and delete this line.",',
|
|
139
|
+
];
|
|
140
|
+
return guideTest.slice(0, lineEnd) + rows.join("\n") + "\n" + guideTest.slice(lineEnd);
|
|
141
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const LOGIN_TEMPLATES: Readonly<Record<string, string>>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// GENERATED by scripts/embed-login-templates.mjs. Do not edit by hand:
|
|
2
|
+
// edit src/scaffolders/nextjs-auth/templates/ and run
|
|
3
|
+
// `node scripts/embed-login-templates.mjs`.
|
|
4
|
+
export const LOGIN_TEMPLATES = {
|
|
5
|
+
"app/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// requireCurrentUser() call at the top of every page that needs a login.\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 { requireCurrentUser } 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 requireCurrentUser();\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
|
+
"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
|
+
"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
|
+
"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",
|
|
10
|
+
"app/login/check-email/page.tsx": "// Shown after every login request, whatever happened. The wording states a\n// CONDITION (\"if this address has access\"), never an outcome, because this\n// page can't know whether an email went out, and an invited person waiting for\n// a link that will never come needs to know that's possible.\n\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { CodeForm } from \"./CodeForm\";\nimport { TypedAddress } from \"./TypedAddress\";\n\nexport const metadata = pageMetadata({\n title: \"Check your email\",\n description: \"If the address you entered has access, a login link is on its way.\",\n path: \"/login/check-email\",\n});\n\nexport default function CheckEmailPage() {\n return (\n <main className=\"page\">\n <h1>Check your email</h1>\n <TypedAddress />\n <p>Tap the button in the email, or, if you are using {SITE_NAME} from your home screen, type its code below. Either works once and expires in 24 hours.</p>\n <CodeForm />\n <p>\n Not seeing it? Check the spelling of the address above, then your spam folder. If needed, we can{\" \"}\n <a href=\"/login\" className=\"text-link\">\n send another link\n </a>\n .\n </p>\n <p className=\"fine-print\">\n {SITE_NAME} is by invitation, so nothing is sent to an address that hasn’t been invited. For your\n privacy, this page looks the same either way.\n </p>\n </main>\n );\n}\n",
|
|
11
|
+
"app/login/error/page.tsx": "// Where Auth.js sends a failed login. The commonest way to get here is opening\n// a login link a second time (a restored tab, a mail app that pre-opened the\n// link, a second device) while already logged in. So check for a session\n// FIRST: telling a logged-in person their link \"expired\" sends them to request\n// a link they don't need.\n//\n// The wording never says whether an address has an account.\n\nimport { getCurrentUser } from \"@/lib/current-user\";\nimport { POST_LOGIN_DESTINATION } from \"@/lib/routes\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Login link problem\",\n description: `This ${SITE_NAME} login link could not log you in.`,\n path: \"/login/error\",\n});\n\nexport default async function LoginErrorPage() {\n const current = await getCurrentUser();\n\n if (current) {\n return (\n <main className=\"page\">\n <h1>You’re already logged in</h1>\n <p>\n You’re logged in as <strong>{current.user.email}</strong>. Each login link works only once, so\n opening it again did nothing.\n </p>\n <p>\n <a href={POST_LOGIN_DESTINATION} className=\"btn-primary\">\n Go to {SITE_NAME}\n </a>\n </p>\n </main>\n );\n }\n\n return (\n <main className=\"page\">\n <h1>That didn’t log you in</h1>\n <p>\n The code may be mistyped, or the link or code was already used or is more than 24 hours old. After too many\n wrong codes, logging in pauses for up to an hour.\n </p>\n <p>\n <a href=\"/login\" className=\"btn-primary\">\n Get a new code\n </a>\n </p>\n <p className=\"fine-print\">\n Using {SITE_NAME} from your home screen? Type the code from the email into the app rather than tapping the\n button, which opens your phone’s browser instead.\n </p>\n </main>\n );\n}\n",
|
|
12
|
+
"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
|
+
"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
|
+
"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",
|
|
15
|
+
"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
|
+
"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 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",
|
|
17
|
+
"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} as const;\n\nexport type AuditAction = (typeof AUDIT_ACTIONS)[keyof typeof AUDIT_ACTIONS];\n",
|
|
18
|
+
"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
|
+
"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
|
+
"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",
|
|
21
|
+
"lib/auth/login-email.ts": "// The login email: a button AND the 8-digit code (lib/auth/sign-in-code.ts) for\n// typing into the installed app, where a tapped link would open the wrong browser.\n// It names the app and nothing else: never anything from the person's records.\n//\n// The button is a dark neutral with white text on purpose. A brand color behind\n// white text often fails contrast (a light green or gold does), and this is the\n// one button the person must find.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nimport { codeFromLoginUrl, formatSignInCode } from \"./sign-in-code\";\n\nexport const LOGIN_LINK_MAX_AGE_SECONDS = 60 * 60 * 24;\n\nconst INK = \"#1f2937\";\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\");\n}\n\nexport function buildLoginEmail(url: string): { subject: string; text: string; html: string } {\n const subject = `Your ${SITE_NAME} login link`;\n const code = codeFromLoginUrl(url);\n const shown = code ? formatSignInCode(code) : null;\n const text = [\n `Here is your link to log in to ${SITE_NAME}:`,\n \"\",\n url,\n ...(shown ? [\"\", `Using ${SITE_NAME} from your home screen? Type this code into the app instead: ${shown}`] : []),\n \"\",\n \"It works once and expires in 24 hours.\",\n \"If you didn't ask for it, you can ignore this email; nobody can log in without it.\",\n \"\",\n `This email is from ${SITE_NAME}.`,\n ].join(\"\\n\");\n const name = escapeHtml(SITE_NAME);\n const href = escapeHtml(url);\n const codeBlock = shown\n ? `\n <p style=\"margin:0 0 8px\">Using ${name} from your home screen? Type this code into the app instead:</p>\n <p style=\"margin:0 0 24px;font-size:32px;font-weight:700;letter-spacing:4px;color:${INK};font-family:ui-monospace,Menlo,Consolas,monospace\">${escapeHtml(shown)}</p>`\n : \"\";\n const html = `<!doctype html>\n<html lang=\"en\">\n<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head>\n<body style=\"margin:0;padding:24px;background:#ffffff;font-family:system-ui,-apple-system,sans-serif;font-size:18px;line-height:1.5;color:${INK}\">\n <p style=\"margin:0 0 20px\">Here is your link to log in to ${name}:</p>\n <p style=\"margin:0 0 24px\">\n <a href=\"${href}\" style=\"display:inline-block;padding:14px 24px;background:${INK};color:#ffffff;text-decoration:none;font-weight:700;border-radius:8px\">Log in to ${name}</a>\n </p>${codeBlock}\n <p style=\"margin:0 0 12px\">It works once and expires in 24 hours.</p>\n <p style=\"margin:0 0 12px\">If you didn't ask for it, you can ignore this email; nobody can log in without it.</p>\n <p style=\"margin:24px 0 0;font-size:16px;color:#4b5563\">This email is from ${name}.</p>\n</body>\n</html>`;\n return { subject, text, html };\n}\n",
|
|
22
|
+
"lib/auth/rate-limit.ts": "// In-memory sliding-window rate limiter.\n//\n// Per serverless instance, so it is a first line against bursts, not a hard\n// cap: an attack spread across many cold instances partly gets through. The\n// per-EMAIL limit therefore does NOT live here; it is counted from\n// `verification_tokens`, which every instance shares (lib/auth/sign-in-policy.ts).\n//\n// Two details that matter:\n// - A rejected request is not recorded, so a steady attacker cannot keep\n// extending someone's lockout.\n// - The number of keys is capped (oldest evicted), so spraying unique keys\n// cannot grow memory without bound.\n\n/**\n * Pure: given the timestamps already in the window, may one more happen at\n * `now`? Returns the hits to keep (pruned, plus `now` if allowed).\n */\nexport function checkWindow(\n hits: readonly number[],\n limit: number,\n windowMs: number,\n now: number,\n): { allowed: boolean; hits: number[] } {\n const recent = hits.filter((t) => now - t < windowMs);\n if (recent.length >= limit) return { allowed: false, hits: recent };\n return { allowed: true, hits: [...recent, now] };\n}\n\nexport type RateLimiter = { attempt(key: string, now?: number): boolean };\n\nexport function createRateLimiter({\n limit,\n windowMs,\n maxKeys = 10_000,\n}: {\n limit: number;\n windowMs: number;\n maxKeys?: number;\n}): RateLimiter {\n const buckets = new Map<string, number[]>();\n return {\n attempt(key, now = Date.now()) {\n const result = checkWindow(buckets.get(key) ?? [], limit, windowMs, now);\n // Re-insert so Map order tracks most-recent use; evict the oldest.\n buckets.delete(key);\n buckets.set(key, result.hits);\n while (buckets.size > maxKeys) {\n const oldest = buckets.keys().next().value;\n if (oldest === undefined) break;\n buckets.delete(oldest);\n }\n return result.allowed;\n },\n };\n}\n",
|
|
23
|
+
"lib/auth/send-gate.ts": "// Decides whether a login email is sent, and sends it. Called by Auth.js's\n// `sendVerificationRequest` (auth.ts) with real dependencies; the tests call it\n// with fakes.\n//\n// From the outside every outcome looks the same: the person sees the same\n// \"check your email\" page whether the address can log in or not, so the page\n// can't be used to find out who has an account. That\n// is why this function NEVER throws. A provider error that escaped would turn\n// into a 500 for members only, which is exactly the leak.\n//\n// Order matters: the cheap in-memory checks run before anything touches the\n// database, so a flood of requests cannot keep the database awake.\n//\n// Every refusal is logged with the host and the address, because a suppressed\n// email looks exactly like a broken mailer to the person waiting for it.\n\nimport type { SendEmailParams, SendEmailResult } from \"@/lib/email/mailer\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { isKnownHost, isLoopbackHost, normalizeHost } from \"./hosts\";\nimport { buildLoginEmail } from \"./login-email\";\nimport type { RateLimiter } from \"./rate-limit\";\nimport { canUserSignIn, evaluateMagicLinkQuota, type SignInCandidate } from \"./sign-in-policy\";\n\nexport type SendGateDeps = {\n env: Record<string, string | undefined>;\n findUser(email: string): Promise<SignInCandidate | null>;\n /** Outstanding unexpired tokens, counting only addresses that can log in. */\n countOutstanding(email: string): Promise<{ forEmail: number; global: number }>;\n sendEmail(params: SendEmailParams): Promise<SendEmailResult>;\n ipLimiter: RateLimiter;\n instanceLimiter: RateLimiter;\n log: Pick<Console, \"warn\" | \"error\">;\n};\n\nexport type SendOutcome =\n | \"sent\"\n | \"unknown-host\"\n | \"rate-limited-ip\"\n | \"rate-limited-instance\"\n | \"not-allowed\"\n | \"quota-per-email\"\n | \"quota-global\"\n | \"lookup-failed\"\n | \"not-configured\"\n | \"provider-rejected\";\n\nexport async function deliverLoginLink(\n { identifier, url, headers }: { identifier: string; url: string; headers: Headers },\n deps: SendGateDeps,\n): Promise<SendOutcome> {\n const email = identifier.toLowerCase();\n const host = normalizeHost(safeHost(url)) ?? \"(unparseable)\";\n const ip = clientIpFrom(headers);\n const context = { host, email, ip: ip.address, ipSource: ip.source };\n const suppress = (outcome: SendOutcome, why: string): SendOutcome => {\n deps.log.warn(`[auth] login email SUPPRESSED (${outcome}): ${why}. No email sent.`, context);\n return outcome;\n };\n\n // 1. A link must point at a host we serve. Fail closed: send\n // nothing rather than rewriting the link to another host.\n if (!isKnownHost(host, deps.env)) {\n return suppress(\"unknown-host\", \"the link's host is not in CANONICAL_HOSTS\");\n }\n\n // 2. In-memory limits, before any database read.\n if (ip.address && !deps.ipLimiter.attempt(ip.address)) {\n return suppress(\"rate-limited-ip\", \"too many login requests from this IP\");\n }\n if (!deps.instanceLimiter.attempt(\"global\")) {\n return suppress(\"rate-limited-instance\", \"too many login requests on this server instance\");\n }\n\n // 3. Is this a person who can log in? Unknown addresses stop here, BEFORE\n // the quota, so made-up addresses never use up anyone's budget.\n let quota: { forEmail: number; global: number };\n try {\n const user = await deps.findUser(email);\n if (!canUserSignIn(user)) {\n return suppress(\"not-allowed\", \"no active, invited account with this address\");\n }\n quota = await deps.countOutstanding(email);\n } catch (error) {\n deps.log.error(\"[auth] login email SUPPRESSED (lookup-failed): database error.\", context, error);\n return \"lookup-failed\";\n }\n\n // 4. Shared limits, counted from verification_tokens.\n const verdict = evaluateMagicLinkQuota({\n outstandingForEmail: quota.forEmail,\n outstandingGlobal: quota.global,\n });\n if (!verdict.allowed) {\n return verdict.reason === \"per-email\"\n ? suppress(\"quota-per-email\", \"too many unused login links for this address\")\n : suppress(\"quota-global\", \"too many unused login links across all accounts\");\n }\n\n // 5. Send. A provider error is reported and swallowed, never thrown.\n const message = buildLoginEmail(url);\n let result: SendEmailResult;\n try {\n result = await deps.sendEmail({ to: email, ...message });\n } catch (error) {\n deps.log.error(\n \"[auth] login email REJECTED by the mail provider. Check, in this order: the SES \" +\n \"sender identity is verified IN SES_REGION (identities are per region); the address \" +\n \"is not on the SES account suppression list; the SES keys were not rotated.\",\n context,\n error,\n );\n return \"provider-rejected\";\n }\n\n if (!result.sent) {\n deps.log.warn(`[auth] login email NOT sent: mail is not configured (${result.skippedReason}).`, context);\n // So login can be tested with no mail provider. Only on a loopback\n // host: preview and production logs are shipped and kept, and a login link\n // is a live credential.\n if (isLoopbackHost(host)) {\n deps.log.warn(`[auth] LOCAL DEV ONLY — login link for ${email}:\\n${url}`);\n }\n return \"not-configured\";\n }\n return \"sent\";\n}\n\nfunction safeHost(url: string): string | null {\n try {\n return new URL(url).host;\n } catch {\n return null;\n }\n}\n",
|
|
24
|
+
"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
|
+
"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
|
+
"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/** For every page that needs a logged-in person. Anyone else goes to /login. */\nexport async function requireCurrentUser(): Promise<CurrentUser> {\n const current = await getCurrentUser();\n if (!current) redirect(LOGIN_PATH);\n return current;\n}\n",
|
|
28
|
+
"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
|
+
"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 = [\"/\", \"/guide\", \"/guide/whats-new\", LOGIN_PATH, CHECK_EMAIL_PATH, \"/login/error\"] as const;\n",
|
|
31
|
+
"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",
|
|
33
|
+
"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
|
+
"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
|
+
"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",
|
|
36
|
+
"test/auth-hosts.test.ts": "/**\n * The login-link host allowlist (lib/auth/hosts.ts). The security cases come\n * with a NEGATIVE CONTROL: local development must still work in every shape a\n * dev server answers on, or a hard-coded `false` would pass every other test.\n */\nimport { describe, expect, it } from \"vitest\";\n\nimport { canonicalHosts, isKnownHost, isLoopbackHost, isProductionDeployment, normalizeHost } from \"@/lib/auth/hosts\";\n\nconst PROD = { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst PREVIEW = { VERCEL_ENV: \"preview\", NODE_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst LOCAL = { NODE_ENV: \"development\" };\n\ndescribe(\"isKnownHost\", () => {\n it(\"allows the canonical host, case-insensitively\", () => {\n expect(isKnownHost(\"app.example.test\", PROD)).toBe(true);\n expect(isKnownHost(\"App.Example.TEST\", PROD)).toBe(true);\n });\n\n it(\"refuses any other host in production, including localhost\", () => {\n expect(isKnownHost(\"attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"app.example.test.attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"localhost:3000\", PROD)).toBe(false);\n });\n\n it(\"CANONICAL_HOSTS unset in production means nobody, not everybody\", () => {\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\" })).toBe(false);\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \" , \" })).toBe(false);\n });\n\n it(\"refuses a forged host on a PREVIEW deployment, which has a public URL\", () => {\n expect(isKnownHost(\"attacker.example\", PREVIEW)).toBe(false);\n expect(isKnownHost(\"app-git-main-team.vercel.app\", PREVIEW)).toBe(false);\n });\n\n it(\"a preview that lists its own host may send links\", () => {\n const env = { ...PREVIEW, CANONICAL_HOSTS: \"app.example.test,app-git-main-team.vercel.app\" };\n expect(isKnownHost(\"app-git-main-team.vercel.app\", env)).toBe(true);\n });\n\n it(\"NEGATIVE CONTROL: local development works in every loopback shape\", () => {\n for (const host of [\"localhost\", \"localhost:3000\", \"127.0.0.1:3000\", \"[::1]:3000\", \"app.localhost:3000\"]) {\n expect(isKnownHost(host, LOCAL), host).toBe(true);\n }\n });\n\n it(\"refuses malformed hosts\", () => {\n for (const host of [\"\", \"evil.example/path\", \"user@evil.example\", \"evil example\", null, 42]) {\n expect(isKnownHost(host, LOCAL)).toBe(false);\n }\n });\n});\n\ndescribe(\"isProductionDeployment\", () => {\n it(\"is decided by VERCEL_ENV, because Vercel previews run with NODE_ENV=production\", () => {\n expect(isProductionDeployment({ VERCEL_ENV: \"production\" })).toBe(true);\n expect(isProductionDeployment({ VERCEL_ENV: \"preview\", NODE_ENV: \"production\" })).toBe(false);\n expect(isProductionDeployment({ NODE_ENV: \"production\" })).toBe(false);\n });\n});\n\ndescribe(\"helpers\", () => {\n it(\"parses CANONICAL_HOSTS into a normalized set\", () => {\n expect([...canonicalHosts({ CANONICAL_HOSTS: \" App.example.test , bad host,x.test:8443\" })]).toEqual([\n \"app.example.test\",\n \"x.test:8443\",\n ]);\n });\n\n it(\"recognizes loopback hosts and nothing else\", () => {\n expect(isLoopbackHost(\"localhost:3000\")).toBe(true);\n expect(isLoopbackHost(\"[::1]\")).toBe(true);\n expect(isLoopbackHost(\"localhost.attacker.example\")).toBe(false);\n expect(isLoopbackHost(\"127.0.0.2\")).toBe(false);\n });\n\n it(\"normalizeHost lower-cases and rejects junk\", () => {\n expect(normalizeHost(\" Example.COM:443 \")).toBe(\"example.com:443\");\n expect(normalizeHost(\"https://example.com\")).toBeNull();\n });\n});\n",
|
|
37
|
+
"test/auth-send-gate.test.ts": "/**\n * The send gate (lib/auth/send-gate.ts): every reason an email is or isn't\n * sent, with fake dependencies so each branch is exercised directly. The two\n * properties that matter most: it never throws (a throw would leak who has an\n * account), and refused requests never reach the database or a quota.\n */\nimport { describe, expect, it, vi } from \"vitest\";\n\nimport { createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport { deliverLoginLink, type SendGateDeps } from \"@/lib/auth/send-gate\";\nimport type { SignInCandidate } from \"@/lib/auth/sign-in-policy\";\n\nconst ACTIVE: SignInCandidate = { isActive: true, signInEnabled: true, tenantStatus: \"active\" };\nconst LINK = \"https://app.example.test/api/auth/callback/email?callbackUrl=%2Fdashboard&token=abc&email=pat%40example.com\";\n\nfunction deps(overrides: Partial<SendGateDeps> = {}) {\n const log = { warn: vi.fn(), error: vi.fn() };\n const d: SendGateDeps = {\n env: { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" },\n findUser: vi.fn(async (email: string) => (email === \"pat@example.com\" ? ACTIVE : null)),\n countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 0 })),\n sendEmail: vi.fn(async () => ({ sent: true })),\n ipLimiter: createRateLimiter({ limit: 20, windowMs: 3_600_000 }),\n instanceLimiter: createRateLimiter({ limit: 300, windowMs: 3_600_000 }),\n log,\n ...overrides,\n };\n return { d, log };\n}\n\nconst req = (identifier = \"pat@example.com\", url = LINK, ip = \"203.0.113.7\") => ({\n identifier,\n url,\n headers: new Headers({ \"x-real-ip\": ip }),\n});\n\ndescribe(\"deliverLoginLink\", () => {\n it(\"sends the email to an invited, active member\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"Pat@Example.com\"), d)).toBe(\"sent\");\n expect(d.sendEmail).toHaveBeenCalledOnce();\n const message = vi.mocked(d.sendEmail).mock.calls[0][0];\n expect(message.to).toBe(\"pat@example.com\");\n expect(message.text).toContain(LINK);\n });\n\n it(\"refuses a forged host before touching the database\", async () => {\n const { d } = deps();\n const forged = LINK.replace(\"app.example.test\", \"attacker.example\");\n expect(await deliverLoginLink(req(undefined, forged), d)).toBe(\"unknown-host\");\n expect(d.findUser).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"sends nothing to an address without an account, and never counts it against a quota\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"stranger@example.com\"), d)).toBe(\"not-allowed\");\n expect(d.countOutstanding).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it.each([\n [\"sign-in turned off\", { ...ACTIVE, signInEnabled: false }],\n [\"user deactivated\", { ...ACTIVE, isActive: false }],\n [\"account suspended\", { ...ACTIVE, tenantStatus: \"suspended\" }],\n ])(\"sends nothing when %s\", async (_label, candidate) => {\n const { d } = deps({ findUser: vi.fn(async () => candidate) });\n expect(await deliverLoginLink(req(), d)).toBe(\"not-allowed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"60 requests for made-up addresses do not block a real member\", async () => {\n const { d } = deps();\n for (let i = 0; i < 60; i++) await deliverLoginLink(req(`fake${i}@example.com`, LINK, `198.51.100.${i}`), d);\n expect(await deliverLoginLink(req(), d)).toBe(\"sent\");\n });\n\n it(\"stops at the per-address quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 5, global: 5 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-per-email\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"stops at the global quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 200 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-global\");\n });\n\n it(\"rate-limits one IP before reading the database\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 2, windowMs: 3_600_000 }) });\n await deliverLoginLink(req(), d);\n await deliverLoginLink(req(), d);\n vi.mocked(d.findUser).mockClear();\n expect(await deliverLoginLink(req(), d)).toBe(\"rate-limited-ip\");\n expect(d.findUser).not.toHaveBeenCalled();\n });\n\n it(\"a request with no trusted IP header is not lumped into one shared bucket\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 1, windowMs: 3_600_000 }) });\n const noIp = { ...req(), headers: new Headers({ \"x-forwarded-for\": \"1.2.3.4\" }) };\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n });\n\n it(\"NEVER throws when the mail provider rejects the send\", async () => {\n const { d, log } = deps({ sendEmail: vi.fn(async () => Promise.reject(new Error(\"MessageRejected\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"provider-rejected\");\n expect(log.error).toHaveBeenCalled();\n });\n\n it(\"NEVER throws when the database is down\", async () => {\n const { d } = deps({ findUser: vi.fn(async () => Promise.reject(new Error(\"connection refused\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"lookup-failed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"logs every refusal with the host and the address (a silent refusal looks like a broken mailer)\", async () => {\n const { d, log } = deps();\n await deliverLoginLink(req(\"stranger@example.com\"), d);\n expect(log.warn).toHaveBeenCalledWith(\n expect.stringContaining(\"SUPPRESSED (not-allowed)\"),\n expect.objectContaining({ host: \"app.example.test\", email: \"stranger@example.com\" }),\n );\n });\n\n describe(\"when mail is not configured\", () => {\n const unconfigured = { sendEmail: vi.fn(async () => ({ sent: false, skippedReason: \"SES creds not set\" })) };\n\n it(\"prints the link on a local dev server, so login can be tested with no mail provider\", async () => {\n const { d, log } = deps({ ...unconfigured, env: { CANONICAL_HOSTS: \"\" } });\n const local = LINK.replace(\"https://app.example.test\", \"http://localhost:3000\");\n expect(await deliverLoginLink(req(undefined, local), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).toContain(local);\n });\n\n it(\"never prints the link off loopback: production and preview logs are kept\", async () => {\n const { d, log } = deps(unconfigured);\n expect(await deliverLoginLink(req(), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).not.toContain(\"token=abc\");\n });\n });\n});\n",
|
|
38
|
+
"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
|
+
"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
|
+
"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",
|
|
41
|
+
};
|
|
@@ -48,6 +48,7 @@
|
|
|
48
48
|
// see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
|
|
49
49
|
import { prePushHookFiles, withHookScripts } from "./pre-push-hook.js";
|
|
50
50
|
import { GUIDE_MODULE_TEMPLATE, GUIDE_PAGE_TEMPLATE, GUIDE_TEST_TEMPLATE, WHATS_NEW_PAGE_TEMPLATE, } from "./nextjs-guide.js";
|
|
51
|
+
import { LOGIN_DEPS, LOGIN_DEV_DEPS, LOGIN_ENV_BLOCK, LOGIN_SCRIPTS, loginFiles, loginGlobalsCss, loginSchema, wantsLogin, withLoginGuideExemptions, withNextAuthInlined, withTsExtensionImports, } from "./nextjs-auth/index.js";
|
|
51
52
|
import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
|
|
52
53
|
const NARRATIVE = `## What this is
|
|
53
54
|
|
|
@@ -5772,7 +5773,10 @@ describe("vercel.json Ignored Build Step", () => {
|
|
|
5772
5773
|
export function scaffoldNextjs(inputs, opts) {
|
|
5773
5774
|
const spec = resolveBrandSpec(inputs);
|
|
5774
5775
|
const base = commonBaseFiles(inputs, opts, NARRATIVE);
|
|
5775
|
-
|
|
5776
|
+
// Login (Step 57) sends its link by email, so it turns email on: the mailer,
|
|
5777
|
+
// its env block and its deps all key off `sendsEmail` below.
|
|
5778
|
+
const hasLogin = wantsLogin(inputs);
|
|
5779
|
+
const sendsEmail = inputs.sendsEmail === true || hasLogin;
|
|
5776
5780
|
const hostRouted = inputs.hostRoutedTenancy === true;
|
|
5777
5781
|
// Sentry is the default runtime-error tool for a customer-facing web app, and
|
|
5778
5782
|
// `hasObservability` is where that intent is already recorded (it is the same
|
|
@@ -5818,6 +5822,11 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5818
5822
|
else if (durableLimit) {
|
|
5819
5823
|
packageJson = withExtraDeps(packageJson, NEON_DRIVER_DEP);
|
|
5820
5824
|
}
|
|
5825
|
+
if (hasLogin) {
|
|
5826
|
+
packageJson = withExtraDeps(packageJson, LOGIN_DEPS);
|
|
5827
|
+
packageJson = withExtraDevDeps(packageJson, LOGIN_DEV_DEPS);
|
|
5828
|
+
packageJson = withExtraScripts(packageJson, LOGIN_SCRIPTS);
|
|
5829
|
+
}
|
|
5821
5830
|
// A test script nothing runs is not a gate (ROADMAP Step 52).
|
|
5822
5831
|
packageJson = withHookScripts(packageJson);
|
|
5823
5832
|
let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
|
|
@@ -5832,8 +5841,10 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5832
5841
|
envExample += EMAIL_ENV_BLOCK;
|
|
5833
5842
|
// The host allowlist serves auth email (magic links derive URLs from the Host)
|
|
5834
5843
|
// and Host-routed tenancy (the Host selects the tenant). Emitted once for both.
|
|
5844
|
+
// With login, the login block carries CANONICAL_HOSTS and describes the code
|
|
5845
|
+
// that is actually emitted; without it, the generic seam block does.
|
|
5835
5846
|
if (sendsEmail || hostRouted)
|
|
5836
|
-
envExample += CANONICAL_HOSTS_ENV_BLOCK;
|
|
5847
|
+
envExample += hasLogin ? LOGIN_ENV_BLOCK : CANONICAL_HOSTS_ENV_BLOCK;
|
|
5837
5848
|
if (acceptsCards)
|
|
5838
5849
|
envExample += CARD_PATH_ENV_BLOCK;
|
|
5839
5850
|
const typeSpecific = [
|
|
@@ -5855,14 +5866,23 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5855
5866
|
path: "lib/seo/page-metadata.ts",
|
|
5856
5867
|
content: sub(PAGE_METADATA_MODULE_TEMPLATE, inputs, opts, spec),
|
|
5857
5868
|
},
|
|
5858
|
-
{
|
|
5859
|
-
|
|
5869
|
+
{
|
|
5870
|
+
path: "tsconfig.json",
|
|
5871
|
+
content: sub(hasLogin ? withTsExtensionImports(TSCONFIG_TEMPLATE) : TSCONFIG_TEMPLATE, inputs, opts, spec),
|
|
5872
|
+
},
|
|
5873
|
+
{
|
|
5874
|
+
path: "vitest.config.ts",
|
|
5875
|
+
content: hasLogin ? withNextAuthInlined(VITEST_CONFIG_TEMPLATE) : VITEST_CONFIG_TEMPLATE,
|
|
5876
|
+
},
|
|
5860
5877
|
// Skip Vercel builds for prose-only pushes; the test guards the one case
|
|
5861
5878
|
// where that would lose a deploy (a project that builds pages from Markdown).
|
|
5862
5879
|
{ path: "vercel.json", content: VERCEL_JSON },
|
|
5863
5880
|
{ path: "test/vercel-ignore.test.ts", content: VERCEL_IGNORE_TEST_TEMPLATE },
|
|
5864
5881
|
{ path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
|
|
5865
|
-
{
|
|
5882
|
+
{
|
|
5883
|
+
path: "app/globals.css",
|
|
5884
|
+
content: globalsCss(spec.primaryColor) + (hasLogin ? loginGlobalsCss() : ""),
|
|
5885
|
+
},
|
|
5866
5886
|
{ path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
|
|
5867
5887
|
{ path: "components/InfoHintCloser.tsx", content: INFO_HINT_CLOSER_TEMPLATE },
|
|
5868
5888
|
// The contrast pair table and the math it uses. Emitted unconditionally: the
|
|
@@ -5915,7 +5935,10 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5915
5935
|
path: "app/guide/whats-new/page.tsx",
|
|
5916
5936
|
content: sub(WHATS_NEW_PAGE_TEMPLATE, inputs, opts, spec),
|
|
5917
5937
|
},
|
|
5918
|
-
{
|
|
5938
|
+
{
|
|
5939
|
+
path: "test/guide.test.ts",
|
|
5940
|
+
content: sub(hasLogin ? withLoginGuideExemptions(GUIDE_TEST_TEMPLATE) : GUIDE_TEST_TEMPLATE, inputs, opts, spec),
|
|
5941
|
+
},
|
|
5919
5942
|
{ path: "lib/analytics/utm.ts", content: sub(ANALYTICS_UTM_TEMPLATE, inputs, opts, spec) },
|
|
5920
5943
|
{
|
|
5921
5944
|
path: "lib/analytics/Analytics.tsx",
|
|
@@ -5994,8 +6017,13 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
5994
6017
|
typeSpecific.push({ path: "db/client.ts", content: sub(DB_CLIENT_TEMPLATE, inputs, opts, spec) }, { path: "db/pool-errors.ts", content: sub(DB_POOL_ERRORS_TEMPLATE, inputs, opts, spec) }, {
|
|
5995
6018
|
path: "db/pool-errors.test.ts",
|
|
5996
6019
|
content: sub(DB_POOL_ERRORS_TEST_TEMPLATE, inputs, opts, spec),
|
|
5997
|
-
}, {
|
|
6020
|
+
}, {
|
|
6021
|
+
path: "db/schema.ts",
|
|
6022
|
+
content: hasLogin ? loginSchema(inputs, opts, spec) : sub(DB_SCHEMA_TEMPLATE, inputs, opts, spec),
|
|
6023
|
+
}, { path: "db/client.test.ts", content: sub(DB_CLIENT_TEST_TEMPLATE, inputs, opts, spec) }, { path: "drizzle.config.ts", content: sub(DRIZZLE_CONFIG_TEMPLATE, inputs, opts, spec) });
|
|
5998
6024
|
}
|
|
6025
|
+
if (hasLogin)
|
|
6026
|
+
typeSpecific.push(...loginFiles(inputs, opts, spec));
|
|
5999
6027
|
return [...base, ...typeSpecific];
|
|
6000
6028
|
}
|
|
6001
6029
|
/**
|
package/dist/writer.js
CHANGED
|
@@ -27,6 +27,7 @@ import { applyGateToDecisions, classifyUnfoundSections, EXTERNAL_DROPPED_SECTION
|
|
|
27
27
|
import { AGENT_COORDINATION_BLOCK_MARKER, AGENTS_BODY_MARKER, STANDARDS_BLOCK_MARKER, } from "./scaffolders/common.js";
|
|
28
28
|
import { buildProSeoExtension, proSeoApplies, } from "./scaffolders/pro-seo-extension.js";
|
|
29
29
|
import { scaffoldByType } from "./scaffolders/index.js";
|
|
30
|
+
import { validateLoginInputs } from "./scaffolders/nextjs-auth/index.js";
|
|
30
31
|
import { applyAgentCoordinationBlock, applyCaptureLearningsBlock, applyStandardsBlock, literalReplacement, resolveStandards, } from "./standards.js";
|
|
31
32
|
import { resolveAgentsTemplate, } from "./templates.js";
|
|
32
33
|
export class WriterError extends Error {
|
|
@@ -192,6 +193,10 @@ export async function writeScaffold(inputs, targetPath, opts = {}) {
|
|
|
192
193
|
if (!path.isAbsolute(targetPath)) {
|
|
193
194
|
throw new WriterError(`targetPath must be absolute. Got: ${JSON.stringify(targetPath)}.`);
|
|
194
195
|
}
|
|
196
|
+
// Refuse login where it cannot work, before any file is read or written.
|
|
197
|
+
const loginProblem = validateLoginInputs(inputs);
|
|
198
|
+
if (loginProblem)
|
|
199
|
+
throw new WriterError(loginProblem);
|
|
195
200
|
const resolvedTarget = path.resolve(targetPath);
|
|
196
201
|
// Resolve the canonical AGENTS body FIRST — its filename is the single source
|
|
197
202
|
// of truth for {{framework_version}}, which Layer 1 substitutes into the
|
|
@@ -557,6 +562,15 @@ export function parseScaffoldInputs(json) {
|
|
|
557
562
|
}
|
|
558
563
|
inputs.sendsEmail = obj["sendsEmail"];
|
|
559
564
|
}
|
|
565
|
+
// Optional: invite-only magic-link login with the typed 8-digit code (Step 57).
|
|
566
|
+
// Defaults to false. nextjs + neon-postgres + hasWebUi only; writeScaffold
|
|
567
|
+
// refuses any other combination.
|
|
568
|
+
if (obj["hasLogin"] !== undefined) {
|
|
569
|
+
if (typeof obj["hasLogin"] !== "boolean") {
|
|
570
|
+
throw new WriterError(`--input field "hasLogin" must be a boolean, got ${typeof obj["hasLogin"]}.`);
|
|
571
|
+
}
|
|
572
|
+
inputs.hasLogin = obj["hasLogin"];
|
|
573
|
+
}
|
|
560
574
|
// Optional: whether this project accepts user-generated content. Defaults to
|
|
561
575
|
// false (no moderation standard). Gates the [[moderation-system]] standard for
|
|
562
576
|
// non-WP app types (skipped for wp-plugin / library / protocol-repo).
|