@zero2webmaster/starter-kit 0.56.1 → 0.57.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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# z2w-starter-kit
|
|
2
2
|
|
|
3
|
-
**Version:** 0.
|
|
3
|
+
**Version:** 0.57.0 | **Framework:** 2.19.0
|
|
4
4
|
|
|
5
5
|
> Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
|
|
6
6
|
|
|
@@ -154,4 +154,4 @@ Inquiries: kerry@zero2webmaster.com.
|
|
|
154
154
|
---
|
|
155
155
|
|
|
156
156
|
*Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
|
|
157
|
-
*Version: 0.
|
|
157
|
+
*Version: 0.57.0 | Last Updated: 2026-11-22*
|
|
@@ -30,7 +30,7 @@ export declare function withTsExtensionImports(tsconfig: string): string;
|
|
|
30
30
|
*/
|
|
31
31
|
export declare const LOGIN_ENV_BLOCK = "\n# Login (magic link + 8-digit code)\n\nAUTH_SECRET=\nCANONICAL_HOSTS=\n\n# AUTH_SECRET signs the session cookie. Required: Auth.js refuses to run\n# without it. Make one with:\n# openssl rand -base64 33\n# Use a different value in each environment (local, preview, production).\n#\n# CANONICAL_HOSTS is the comma-separated list of hostnames a login link may\n# point at, such as app.example.com,www.example.com (no https://, no path).\n# Unset or empty means NONE, not all. Off production, loopback hosts\n# (localhost, 127.0.0.1) are also allowed, so local login works without it. A\n# preview deployment that must send real login links lists its own host here.\n#\n# Do NOT set AUTH_URL. The app trusts the request's Host and checks it against\n# CANONICAL_HOSTS instead (lib/auth/hosts.ts), so one deployment can answer on\n# several domains.\n";
|
|
32
32
|
/**
|
|
33
|
-
* Mounts the Terms/Privacy footer once in the root layout, after the page
|
|
33
|
+
* Mounts the Contact/Terms/Privacy footer once in the root layout, after the page
|
|
34
34
|
* content, so every page (logged in or not) links both. Login scaffolds only:
|
|
35
35
|
* without login there are no /terms and /privacy pages to link.
|
|
36
36
|
*/
|
|
@@ -110,19 +110,21 @@ CANONICAL_HOSTS=
|
|
|
110
110
|
# several domains.
|
|
111
111
|
`;
|
|
112
112
|
/**
|
|
113
|
-
* Mounts the Terms/Privacy footer once in the root layout, after the page
|
|
113
|
+
* Mounts the Contact/Terms/Privacy footer once in the root layout, after the page
|
|
114
114
|
* content, so every page (logged in or not) links both. Login scaffolds only:
|
|
115
115
|
* without login there are no /terms and /privacy pages to link.
|
|
116
116
|
*/
|
|
117
117
|
export function withSiteFooter(layout) {
|
|
118
118
|
const importAnchor = 'import { InfoHintCloser } from "@/components/InfoHintCloser";';
|
|
119
119
|
const bodyAnchor = " {children}\n";
|
|
120
|
-
|
|
120
|
+
const fnAnchor = "export default function RootLayout(";
|
|
121
|
+
if (!layout.includes(importAnchor) || !layout.includes(bodyAnchor) || !layout.includes(fnAnchor)) {
|
|
121
122
|
throw new Error("layout template changed: cannot mount the site footer");
|
|
122
123
|
}
|
|
123
124
|
return layout
|
|
124
|
-
.replace(importAnchor, `${importAnchor}\nimport { SiteFooter } from "@/components/SiteFooter";`)
|
|
125
|
-
.replace(
|
|
125
|
+
.replace(importAnchor, `${importAnchor}\nimport { SiteFooter } from "@/components/SiteFooter";\nimport { footerContactUrl } from "@/lib/footer-contact";`)
|
|
126
|
+
.replace(fnAnchor, "export default async function RootLayout(")
|
|
127
|
+
.replace(bodyAnchor, `${bodyAnchor} {/* Contact (when the organization has a contact page), Terms and Privacy on every page (components/SiteFooter.tsx). */}\n <SiteFooter contactUrl={await footerContactUrl()} />\n`);
|
|
126
128
|
}
|
|
127
129
|
/**
|
|
128
130
|
* vitest runs `next-auth` through Node's own resolver, which refuses its bare
|
|
@@ -18,9 +18,9 @@ export const LOGIN_TEMPLATES = {
|
|
|
18
18
|
"app/terms/page.tsx": "// The Terms, public and linked from the footer of every page, so anyone can\n// read them at any time without logging in. The same text a person agrees to\n// on /agree (components/TermsText.tsx).\n\nimport { LegalPageEnd, TermsText } from \"@/components/TermsText\";\nimport { pageMetadata, SITE_NAME } from \"@/lib/seo/page-metadata\";\n\nexport const metadata = pageMetadata({\n title: \"Terms\",\n description: `The ${SITE_NAME} Terms: what the app promises, and your responsibility.`,\n path: \"/terms\",\n});\n\nexport default function TermsPage() {\n return (\n <main className=\"page\">\n <h1>{SITE_NAME} Terms</h1>\n <TermsText />\n <LegalPageEnd />\n </main>\n );\n}\n",
|
|
19
19
|
"auth.ts": "// Auth.js (NextAuth v5) configuration: invite-only magic-link login, with the\n// same secret also printed in the email as an 8-digit code.\n//\n// - trustHost: true and NO AUTH_URL env var, so one deployment can serve\n// several domains. The link host is checked against CANONICAL_HOSTS in\n// lib/auth/send-gate.ts instead.\n// - The allowlist is checked twice: before sending (send-gate) and again when\n// the link is clicked (the signIn callback below), so a link sent before\n// access was removed no longer works.\n// - At SEND time the signIn callback allows everyone. Refusing there would\n// change the redirect for unknown addresses and reveal who has an account.\n// The send gate still sends nothing to them.\n// - Sessions are JWTs (lib/auth/session-config.ts).\n// - Function form NextAuth(() => config): env is read per request, so\n// `next build` works without secrets.\n//\n// Only this file and lib/current-user.ts call auth(). Everything else asks\n// lib/current-user.ts who is logged in.\n\nimport NextAuth from \"next-auth\";\nimport type { EmailConfig } from \"next-auth/providers\";\nimport { eq } from \"drizzle-orm\";\n\nimport { getDb } from \"@/db/client\";\nimport { auditEvents, users } from \"@/db/schema\";\nimport { AUDIT_ACTIONS } from \"@/lib/audit\";\nimport { generateSignInCode } from \"@/lib/auth/sign-in-code\";\nimport { sendEmail } from \"@/lib/email/mailer\";\nimport {\n countOutstandingLoginLinks,\n createAdapter,\n findSignInCandidate,\n findSignInCandidateById,\n isPhantomUser,\n} from \"@/lib/auth/adapter\";\nimport { LOGIN_LINK_MAX_AGE_SECONDS } from \"@/lib/auth/login-email\";\nimport { createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport { deliverLoginLink } from \"@/lib/auth/send-gate\";\nimport { sessionConfig } from \"@/lib/auth/session-config\";\nimport { canUserSignIn } from \"@/lib/auth/sign-in-policy\";\n\n/**\n * Where login events are recorded: an audit_events\n * row, written in the same transaction as users.last_login_at.\n */\nexport const AUTH_AUDIT_SINK = \"audit_events\" as const;\n\nconst HOUR = 60 * 60 * 1000;\n// Per server instance. The per-address limit is shared (verification_tokens).\nconst ipLimiter = createRateLimiter({ limit: 20, windowMs: HOUR });\nconst instanceLimiter = createRateLimiter({ limit: 300, windowMs: HOUR });\n\nconst emailProvider: EmailConfig = {\n id: \"email\",\n type: \"email\",\n name: \"Email\",\n maxAge: LOGIN_LINK_MAX_AGE_SECONDS,\n // The token IS the 8-digit code printed in the email (lib/auth/sign-in-code.ts).\n generateVerificationToken: generateSignInCode,\n async sendVerificationRequest({ identifier, url, request }) {\n await deliverLoginLink(\n { identifier, url, headers: request.headers },\n {\n env: process.env,\n findUser: findSignInCandidate,\n countOutstanding: countOutstandingLoginLinks,\n sendEmail,\n ipLimiter,\n instanceLimiter,\n log: console,\n },\n );\n },\n options: {},\n};\n\nexport const { handlers, auth, signIn, signOut } = NextAuth(() => ({\n trustHost: true,\n adapter: createAdapter(),\n providers: [emailProvider],\n session: sessionConfig,\n // Path-only values: Auth.js appends its own query string to each (Trap 2).\n pages: {\n signIn: \"/login\",\n verifyRequest: \"/login/check-email\",\n error: \"/login/error\",\n },\n callbacks: {\n async signIn({ user, email }) {\n // SEND time: allow everyone, so every address gets the same response.\n if (email?.verificationRequest) return true;\n // CLICK time: the real gate. Re-read the row, so access removed after\n // the link was sent is honored.\n if (!user?.id || isPhantomUser(user.id)) return false;\n return canUserSignIn(await findSignInCandidateById(user.id));\n },\n jwt({ token, user }) {\n if (user?.id) {\n token.sub = user.id;\n token.email = (user.email ?? \"\").toLowerCase();\n }\n return token;\n },\n session({ session, token }) {\n if (token.sub && session.user) session.user.id = token.sub;\n return session;\n },\n },\n events: {\n async signIn({ user }) {\n if (!user?.id || isPhantomUser(user.id)) return;\n const db = getDb();\n const [row] = await db.select().from(users).where(eq(users.id, user.id)).limit(1);\n if (!row) return;\n // The audit row and last_login_at land together or not at all.\n await db.transaction(async (tx) => {\n await tx.insert(auditEvents).values({\n tenantId: row.tenantId,\n userId: row.id,\n action: AUDIT_ACTIONS.AUTH_LOGIN,\n targetType: \"user\",\n targetId: row.id,\n });\n await tx.update(users).set({ lastLoginAt: new Date() }).where(eq(users.id, row.id));\n });\n },\n async signOut(message) {\n // JWT sessions: the event carries { token }, not { session }.\n const userId = \"token\" in message ? message.token?.sub : undefined;\n if (!userId || isPhantomUser(userId)) return;\n const db = getDb();\n const [row] = await db.select().from(users).where(eq(users.id, userId)).limit(1);\n if (!row) return;\n await db.insert(auditEvents).values({\n tenantId: row.tenantId,\n userId: row.id,\n action: AUDIT_ACTIONS.AUTH_LOGOUT,\n targetType: \"user\",\n targetId: row.id,\n });\n },\n },\n}));\n",
|
|
20
20
|
"components/PrivacyText.tsx": "// The Privacy Policy, shown on /privacy (public) and linked from the Terms, the\n// agree page and the footer of every page. Not a separate agreement: people\n// agree to the Terms, which link it.\n//\n// 🔴 Every sentence must be true of the code on the day it ships. SERVICES is\n// the list of outside services this app's code sends personal information to,\n// as scaffolded: Vercel (hosting), Neon (database), Amazon SES (the mailer's\n// default; change the line if you set EMAIL_PROVIDER=resend) and Fathom\n// (analytics). Add a row the day you wire another one (Sentry, a payment\n// processor, file storage, an AI service), and change the \"AI\" section if\n// anything a person enters is ever sent to one.\n//\n// ⚠️ Changing the wording? Bump TERMS_LAST_MODIFIED in lib/terms.ts. A plain-\n// English draft, NOT reviewed by a lawyer.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { TERMS_OPERATOR } from \"@/lib/terms\";\n\nconst SERVICES: { name: string; receives: string }[] = [\n { name: \"Vercel\", receives: \"hosts the app, so it handles every request, including your IP address and browser details.\" },\n { name: \"Neon\", receives: \"stores the app's database: your account and everything you enter.\" },\n { name: \"Amazon Web Services (Amazon SES)\", receives: \"sends the app's emails, so it receives your email address and each email.\" },\n { name: \"Fathom Analytics\", receives: \"counts page visits without cookies and without identifying you.\" },\n];\n\nexport function PrivacyText({ headingLevel = 2 }: { headingLevel?: 2 | 3 }) {\n const H = headingLevel === 2 ? \"h2\" : \"h3\";\n return (\n <div className=\"terms-text\">\n <H>What we collect</H>\n <ul>\n <li>What you enter: your name, your email address, and what you add in the app.</li>\n <li>What is created when you use it: when you log in and out, and a record of changes to your account.</li>\n <li>What your browser sends: your IP address and the kind of device and browser you use.</li>\n <li>From whoever invited you: the name and email address they gave us to create your account.</li>\n </ul>\n\n <H>Why</H>\n <p>\n To run {SITE_NAME}, to log you in, and to keep it secure and stop abuse. Agreeing to the Terms does not sign you\n up for any newsletter or marketing email.\n </p>\n\n <H>Who else receives it</H>\n <ul>\n {SERVICES.map((s) => (\n <li key={s.name}>\n <strong>{s.name}</strong> {s.receives}\n </li>\n ))}\n </ul>\n <p>We do not sell or rent your information.</p>\n\n <H>AI</H>\n <p>Nothing you enter in {SITE_NAME} is sent to an AI service.</p>\n\n <H>How long we keep it</H>\n <p>\n We keep your information while you have an account. When an account is closed, {TERMS_OPERATOR} deletes it,\n except where the law requires us to keep a record.\n </p>\n\n <H>Your choices</H>\n <p>\n You can ask to see, correct or delete your information. Use the contact information at the bottom of this page.\n </p>\n\n <H>Changes</H>\n <p>If this policy changes, the new version will be posted here with a new “Last modified” date.</p>\n </div>\n );\n}\n",
|
|
21
|
-
"components/SiteFooter.tsx": "// The footer on every page, mounted once in app/layout.tsx: links to the Terms\n// and the Privacy Policy, so both are one tap away whether or not anyone is\n// logged in
|
|
21
|
+
"components/SiteFooter.tsx": "// The footer on every page, mounted once in app/layout.tsx: links to the Terms\n// and the Privacy Policy, so both are one tap away whether or not anyone is\n// logged in, and a Contact link whenever the organization has a contact page.\n// Each link is a 48px tap target and underlined.\n//\n// Contact: the URL comes\n// from the organization's own record (tenants.contact_url, read by\n// lib/footer-contact.ts), never built from its domain, because a guessed\n// /contact/ is a dead link for an organization without one. No page, no link;\n// the moment one is stored, every page shows it.\n\nimport { PRIVACY_PATH, TERMS_PATH } from \"@/lib/routes\";\n\nexport function SiteFooter({ contactUrl = null }: { contactUrl?: string | null } = {}) {\n return (\n <footer className=\"site-footer\">\n <nav aria-label=\"Footer\">\n {contactUrl ? <a href={contactUrl}>Contact</a> : null}\n <a href={TERMS_PATH}>Terms</a>\n <a href={PRIVACY_PATH}>Privacy</a>\n </nav>\n </footer>\n );\n}\n",
|
|
22
22
|
"components/TermsText.tsx": "// Sections: base\n//\n// The wording of the Terms, shown in full on /terms (public) and on /agree\n// (where a person agrees before first use). One component, so the text a\n// person agrees to is byte-for-byte the text the public page shows.\n//\n// ⚠️ Changing the wording? Bump CURRENT_TERMS_VERSION and TERMS_LAST_MODIFIED\n// in lib/terms.ts in the same commit, so everyone is asked to agree again.\n//\n// This is the BASE every app with a login gets. Add a section when the app\n// gains a reason for one (reminders, content other people see, anything that\n// could be read as medical or legal help, payments) and list it on the\n// \"Sections:\" line above. The wording is a plain-English draft, NOT reviewed\n// by a lawyer: have the operator approve it, and a lawyer review it if they\n// choose, before the app is offered to the public.\n\nimport { SITE_NAME } from \"@/lib/seo/page-metadata\";\nimport { PRIVACY_PATH } from \"@/lib/routes\";\nimport {\n formatTermsDate,\n TERMS_CONTACT_URL,\n TERMS_CREATED,\n TERMS_LAST_MODIFIED,\n TERMS_OPERATOR,\n TERMS_OPERATOR_URL,\n} from \"@/lib/terms\";\n\n/** \"SITE is run by OPERATOR\", with the operator linked. The first line of both legal pages. */\nexport function RunBy() {\n return (\n <p className=\"lead\">\n {SITE_NAME} is run by{\" \"}\n <a href={TERMS_OPERATOR_URL} target=\"_blank\" rel=\"noopener noreferrer\">\n {TERMS_OPERATOR}\n </a>\n .\n </p>\n );\n}\n\n/** The one place contact details appear, and the page's dates. The last thing on both legal pages. */\nexport function LegalPageEnd() {\n return (\n <div className=\"legal-end\">\n <p>\n <a className=\"btn-primary\" href={TERMS_CONTACT_URL} target=\"_blank\" rel=\"noopener noreferrer\">\n Contact Us\n </a>\n </p>\n <p className=\"fine-print\">\n Created {formatTermsDate(TERMS_CREATED)} · Last modified {formatTermsDate(TERMS_LAST_MODIFIED)}\n </p>\n </div>\n );\n}\n\nexport function TermsText({ headingLevel = 2 }: { headingLevel?: 2 | 3 }) {\n const H = headingLevel === 2 ? \"h2\" : \"h3\";\n return (\n <div className=\"terms-text\">\n <RunBy />\n\n <H>{SITE_NAME} is provided as-is</H>\n <p>\n We work to keep {SITE_NAME} running and correct, but we do not promise it will always be available, accurate,\n complete or free of errors, or that it suits any particular purpose.\n </p>\n\n <H>Do not rely on emails</H>\n <p>\n Emails and notifications from {SITE_NAME} can be delayed, filtered as spam, or not arrive at all. Do not rely on\n them for anything important; check the app itself.\n </p>\n\n <H>Your choice, your responsibility</H>\n <p>\n You use {SITE_NAME} of your own free will and at your own risk. To the fullest extent the law allows,{\" \"}\n {TERMS_OPERATOR} and the people who build and run {SITE_NAME} are not responsible for any harm, loss or cost\n that comes from using the app or relying on it, and you agree to hold them harmless for it.\n </p>\n\n <H>Your account</H>\n <p>\n Keep access to your email account secure, because that is how you log in. You are responsible for what is done\n through your account. If you think someone else has used it, tell us using the contact information at the bottom\n of this page.\n </p>\n\n <H>Be decent</H>\n <p>\n Do not use {SITE_NAME} to break the law, harass or deceive anyone, try to reach data that is not yours, overload\n or attack the service, or get around its limits. We may suspend or close an account that does.\n </p>\n\n <H>Your information</H>\n <p>\n How we handle it is in our <a href={PRIVACY_PATH}>Privacy Policy</a>.\n </p>\n\n <H>Changes</H>\n <p>\n If these terms change, {SITE_NAME} will show you the new version and ask you to agree again before you carry on.\n Questions are welcome; use the contact information at the bottom of this page.\n </p>\n </div>\n );\n}\n",
|
|
23
|
-
"db/schema.ts": "// Drizzle schema for {{slug}}.\n//\n// Standard Postgres types only, so the schema ports to any Postgres host.\n// Apply it with `npm run db:push` (or `npm run db:generate` for SQL migrations).\n//\n// The tables below are login. Add the app's own tables underneath. Every table\n// that holds an account's data carries `tenant_id NOT NULL` with an index that\n// starts with it, and every query on it filters by the tenantId that\n// lib/current-user.ts returns.\n\nimport { sql } from \"drizzle-orm\";\nimport { boolean, check, index, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from \"drizzle-orm/pg-core\";\n\nconst createdAt = () => timestamp(\"created_at\", { withTimezone: true }).defaultNow().notNull();\n\n/** One account. A single-organization app has one row. */\nexport const tenants = pgTable(\"tenants\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n /** `active` | `suspended`. Text, not an enum, so values can evolve. Anything but `active` blocks login. */\n status: text(\"status\").notNull().default(\"active\"),\n createdAt: createdAt(),\n});\n\n/**\n * People who can log in. Pre-provisioned only (scripts/provision-user.ts):\n * Auth.js never creates a user. The allowlist lives HERE as `sign_in_enabled`,\n * editable in the app, rather than in an env var that needs a redeploy.\n *\n * `email` is unique across ALL tenants, not per tenant: login starts from an\n * email address alone, and one address in two tenants would make \"which\n * account is this?\" unanswerable before the person is even logged in.\n */\nexport const users = pgTable(\n \"users\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n /** Stored lower-cased. */\n email: text(\"email\").notNull(),\n /** Display name, always built from firstName + lastName, never split from it. */\n name: text(\"name\"),\n firstName: text(\"first_name\"),\n /** Null for someone with one name. */\n lastName: text(\"last_name\"),\n /** `owner` to start; add roles as the app needs them. */\n role: text(\"role\").notNull().default(\"owner\"),\n isActive: boolean(\"is_active\").notNull().default(true),\n signInEnabled: boolean(\"sign_in_enabled\").notNull().default(false),\n emailVerifiedAt: timestamp(\"email_verified_at\", { withTimezone: true }),\n lastLoginAt: timestamp(\"last_login_at\", { withTimezone: true }),\n /** The Terms version this person last agreed to (lib/terms.ts). Null = never agreed. */\n termsVersion: text(\"terms_version\"),\n /** When they agreed to `termsVersion`. */\n termsAcceptedAt: timestamp(\"terms_accepted_at\", { withTimezone: true }),\n createdAt: createdAt(),\n },\n (t) => [\n uniqueIndex(\"users_email_uidx\").on(t.email),\n index(\"users_tenant_idx\").on(t.tenantId),\n check(\"users_email_lowercase\", sql`${t.email} = lower(${t.email})`),\n ],\n);\n\n/** Auth.js login tokens: each one is the 8-digit code in a login email. Keyed by email, not by tenant. */\nexport const verificationTokens = pgTable(\n \"verification_tokens\",\n {\n identifier: text(\"identifier\").notNull(),\n token: text(\"token\").notNull(),\n expires: timestamp(\"expires\", { withTimezone: true }).notNull(),\n },\n (t) => [primaryKey({ columns: [t.identifier, t.token] })],\n);\n\n/**\n * Wrong login codes (and used or expired links, which carry the same code), one\n * row per miss. Counted per address over the last hour to lock out guessing\n * (lib/auth/sign-in-code.ts). Keyed by email, not by tenant.\n */\nexport const signInCodeFailures = pgTable(\n \"sign_in_code_failures\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n identifier: text(\"identifier\").notNull(),\n failedAt: timestamp(\"failed_at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => [index(\"sign_in_code_failures_identifier_idx\").on(t.identifier, t.failedAt)],\n);\n\n/** Append-only. Records ids and actions only (lib/audit.ts), never the content of a record. */\nexport const auditEvents = pgTable(\n \"audit_events\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n userId: uuid(\"user_id\").references(() => users.id, { onDelete: \"set null\" }),\n action: text(\"action\").notNull(),\n targetType: text(\"target_type\"),\n targetId: uuid(\"target_id\"),\n createdAt: createdAt(),\n },\n (t) => [index(\"audit_events_tenant_time_idx\").on(t.tenantId, t.createdAt)],\n);\n",
|
|
23
|
+
"db/schema.ts": "// Drizzle schema for {{slug}}.\n//\n// Standard Postgres types only, so the schema ports to any Postgres host.\n// Apply it with `npm run db:push` (or `npm run db:generate` for SQL migrations).\n//\n// The tables below are login. Add the app's own tables underneath. Every table\n// that holds an account's data carries `tenant_id NOT NULL` with an index that\n// starts with it, and every query on it filters by the tenantId that\n// lib/current-user.ts returns.\n\nimport { sql } from \"drizzle-orm\";\nimport { boolean, check, index, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from \"drizzle-orm/pg-core\";\n\nconst createdAt = () => timestamp(\"created_at\", { withTimezone: true }).defaultNow().notNull();\n\n/** One account. A single-organization app has one row. */\nexport const tenants = pgTable(\"tenants\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n /** `active` | `suspended`. Text, not an enum, so values can evolve. Anything but `active` blocks login. */\n status: text(\"status\").notNull().default(\"active\"),\n /**\n * The organization's own contact page (https), shown as \"Contact\" in every\n * page's footer. Null means it has none, and then no link is shown: never\n * build it from the organization's domain (lib/footer-contact.ts).\n */\n contactUrl: text(\"contact_url\"),\n createdAt: createdAt(),\n});\n\n/**\n * People who can log in. Pre-provisioned only (scripts/provision-user.ts):\n * Auth.js never creates a user. The allowlist lives HERE as `sign_in_enabled`,\n * editable in the app, rather than in an env var that needs a redeploy.\n *\n * `email` is unique across ALL tenants, not per tenant: login starts from an\n * email address alone, and one address in two tenants would make \"which\n * account is this?\" unanswerable before the person is even logged in.\n */\nexport const users = pgTable(\n \"users\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n /** Stored lower-cased. */\n email: text(\"email\").notNull(),\n /** Display name, always built from firstName + lastName, never split from it. */\n name: text(\"name\"),\n firstName: text(\"first_name\"),\n /** Null for someone with one name. */\n lastName: text(\"last_name\"),\n /** `owner` to start; add roles as the app needs them. */\n role: text(\"role\").notNull().default(\"owner\"),\n isActive: boolean(\"is_active\").notNull().default(true),\n signInEnabled: boolean(\"sign_in_enabled\").notNull().default(false),\n emailVerifiedAt: timestamp(\"email_verified_at\", { withTimezone: true }),\n lastLoginAt: timestamp(\"last_login_at\", { withTimezone: true }),\n /** The Terms version this person last agreed to (lib/terms.ts). Null = never agreed. */\n termsVersion: text(\"terms_version\"),\n /** When they agreed to `termsVersion`. */\n termsAcceptedAt: timestamp(\"terms_accepted_at\", { withTimezone: true }),\n createdAt: createdAt(),\n },\n (t) => [\n uniqueIndex(\"users_email_uidx\").on(t.email),\n index(\"users_tenant_idx\").on(t.tenantId),\n check(\"users_email_lowercase\", sql`${t.email} = lower(${t.email})`),\n ],\n);\n\n/** Auth.js login tokens: each one is the 8-digit code in a login email. Keyed by email, not by tenant. */\nexport const verificationTokens = pgTable(\n \"verification_tokens\",\n {\n identifier: text(\"identifier\").notNull(),\n token: text(\"token\").notNull(),\n expires: timestamp(\"expires\", { withTimezone: true }).notNull(),\n },\n (t) => [primaryKey({ columns: [t.identifier, t.token] })],\n);\n\n/**\n * Wrong login codes (and used or expired links, which carry the same code), one\n * row per miss. Counted per address over the last hour to lock out guessing\n * (lib/auth/sign-in-code.ts). Keyed by email, not by tenant.\n */\nexport const signInCodeFailures = pgTable(\n \"sign_in_code_failures\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n identifier: text(\"identifier\").notNull(),\n failedAt: timestamp(\"failed_at\", { withTimezone: true }).notNull().defaultNow(),\n },\n (t) => [index(\"sign_in_code_failures_identifier_idx\").on(t.identifier, t.failedAt)],\n);\n\n/** Append-only. Records ids and actions only (lib/audit.ts), never the content of a record. */\nexport const auditEvents = pgTable(\n \"audit_events\",\n {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n tenantId: uuid(\"tenant_id\")\n .notNull()\n .references(() => tenants.id),\n userId: uuid(\"user_id\").references(() => users.id, { onDelete: \"set null\" }),\n action: text(\"action\").notNull(),\n targetType: text(\"target_type\"),\n targetId: uuid(\"target_id\"),\n createdAt: createdAt(),\n },\n (t) => [index(\"audit_events_tenant_time_idx\").on(t.tenantId, t.createdAt)],\n);\n",
|
|
24
24
|
"lib/audit.ts": "// Audit action names. One constant per action so a typo can't silently create\n// a new kind of event. Audit rows hold ids and actions only, never the content\n// of a person's records. Add a constant here for each new action you record.\n\nexport const AUDIT_ACTIONS = {\n AUTH_LOGIN: \"auth.login\",\n AUTH_LOGOUT: \"auth.logout\",\n TERMS_AGREED: \"user.terms_agreed\",\n} as const;\n\nexport type AuditAction = (typeof AUDIT_ACTIONS)[keyof typeof AUDIT_ACTIONS];\n",
|
|
25
25
|
"lib/auth/adapter.ts": "// The Auth.js adapter: the small set of methods magic-link login needs\n// No session methods, because sessions are JWTs.\n//\n// Three rules:\n// 1. getUserByEmail NEVER returns null. An address that can't log in gets the\n// PHANTOM user, so Auth.js takes the same path for every address and the\n// response can't reveal who has an account. The click-time signIn\n// callback refuses the phantom.\n// 2. createUser throws. Accounts are created by scripts/provision-user.ts,\n// never by clicking a link. If it is ever called, rule 1 has broken.\n// 3. updateUser receives only { id, emailVerified }: no email. It\n// looks the person up by id.\n\nimport \"server-only\";\n\nimport { and, count, eq, gt, lt, sql } from \"drizzle-orm\";\nimport type { Adapter, AdapterUser, VerificationToken } from \"next-auth/adapters\";\n\nimport { getDb } from \"@/db/client\";\nimport { signInCodeFailures, tenants, users, verificationTokens } from \"@/db/schema\";\nimport {\n SIGN_IN_CODE_LIVE_MAX,\n SIGN_IN_CODE_WRONG_GUESS_LIMIT,\n SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS,\n} from \"./sign-in-code\";\nimport { canUserSignIn, type SignInCandidate } from \"./sign-in-policy\";\n\nexport const PHANTOM_USER_ID = \"00000000-0000-0000-0000-000000000000\";\n\nexport function isPhantomUser(id: string | null | undefined): boolean {\n return id === PHANTOM_USER_ID;\n}\n\ntype UserRow = typeof users.$inferSelect;\ntype Candidate = SignInCandidate & { user: UserRow };\n\nasync function selectUser(where: ReturnType<typeof eq>): Promise<Candidate | null> {\n const [row] = await getDb()\n .select({ user: users, tenantStatus: tenants.status })\n .from(users)\n .innerJoin(tenants, eq(users.tenantId, tenants.id))\n .where(where)\n .limit(1);\n if (!row) return null;\n return {\n user: row.user,\n isActive: row.user.isActive,\n signInEnabled: row.user.signInEnabled,\n tenantStatus: row.tenantStatus,\n };\n}\n\n/** Used by the send gate and the click-time gate. */\nexport function findSignInCandidate(email: string): Promise<Candidate | null> {\n return selectUser(eq(users.email, email.toLowerCase()));\n}\n\nexport function findSignInCandidateById(id: string): Promise<Candidate | null> {\n return selectUser(eq(users.id, id));\n}\n\n/**\n * Unexpired login tokens, counting only rows whose address belongs to an\n * active, invited user. Unknown addresses still get token rows (Auth.js\n * writes one for every request) but never count against anyone's budget.\n */\nexport async function countOutstandingLoginLinks(\n email: string,\n): Promise<{ forEmail: number; global: number }> {\n const db = getDb();\n const now = new Date();\n const [forEmail] = await db\n .select({ n: count() })\n .from(verificationTokens)\n .where(and(eq(verificationTokens.identifier, email.toLowerCase()), gt(verificationTokens.expires, now)));\n const [global] = await db\n .select({ n: count() })\n .from(verificationTokens)\n .innerJoin(\n users,\n and(eq(users.email, verificationTokens.identifier), eq(users.isActive, true), eq(users.signInEnabled, true)),\n )\n .where(gt(verificationTokens.expires, now));\n return { forEmail: forEmail?.n ?? 0, global: global?.n ?? 0 };\n}\n\nfunction toAdapterUser(user: UserRow): AdapterUser {\n return {\n id: user.id,\n email: user.email,\n emailVerified: user.emailVerifiedAt,\n name: user.name,\n };\n}\n\nfunction phantom(email: string): AdapterUser {\n return { id: PHANTOM_USER_ID, email: email.toLowerCase(), emailVerified: null };\n}\n\nexport function createAdapter(): Adapter {\n return {\n async getUserByEmail(email) {\n const candidate = await findSignInCandidate(email);\n return candidate && canUserSignIn(candidate) ? toAdapterUser(candidate.user) : phantom(email);\n },\n\n async getUser(id) {\n if (isPhantomUser(id)) return null;\n const candidate = await findSignInCandidateById(id);\n return candidate && canUserSignIn(candidate) ? toAdapterUser(candidate.user) : null;\n },\n\n async createUser() {\n throw new Error(\"createUser called: getUserByEmail must return a real or phantom user\");\n },\n\n async updateUser({ id, emailVerified }) {\n if (isPhantomUser(id)) throw new Error(\"updateUser called for the phantom user\");\n const db = getDb();\n if (emailVerified) {\n await db.update(users).set({ emailVerifiedAt: emailVerified }).where(eq(users.id, id));\n }\n const [user] = await db.select().from(users).where(eq(users.id, id)).limit(1);\n if (!user) throw new Error(\"updateUser called for a user id that does not exist\");\n return toAdapterUser(user);\n },\n\n async createVerificationToken(token) {\n const db = getDb();\n await db.insert(verificationTokens).values(token);\n // 🔴 Keep only the newest SIGN_IN_CODE_LIVE_MAX tokens for this address. Each\n // token is a typed 8-digit code (lib/auth/sign-in-code.ts), every live one is\n // something a guess can hit, and Auth.js mints one even when the send is\n // suppressed. Equal to the per-address send limit, which counts these rows.\n await db.execute(sql`\n DELETE FROM verification_tokens\n WHERE identifier = ${token.identifier}\n AND token NOT IN (\n SELECT token FROM verification_tokens\n WHERE identifier = ${token.identifier}\n ORDER BY expires DESC\n LIMIT ${SIGN_IN_CODE_LIVE_MAX}\n )\n `);\n return token;\n },\n\n async useVerificationToken({ identifier, token }): Promise<VerificationToken | null> {\n // Locked by too many wrong guesses: refuse even a correct code, or the cap\n // would only slow a guesser down. Checked BEFORE the delete, so a locked\n // attempt cannot burn the person's real code.\n if (await isSignInCodeLocked(identifier)) return null;\n // Single use: the row is deleted as it is read.\n const [row] = await getDb()\n .delete(verificationTokens)\n .where(and(eq(verificationTokens.identifier, identifier), eq(verificationTokens.token, token)))\n .returning();\n // A miss is a wrong typed code or a used/expired link; they carry the same\n // code, so both count.\n if (!row) await recordSignInCodeFailure(identifier);\n return row ?? null;\n },\n };\n}\n\n/** True when this address has used up its wrong guesses for the window. Fails CLOSED. */\nexport async function isSignInCodeLocked(identifier: string, now = new Date()): Promise<boolean> {\n try {\n const since = new Date(now.getTime() - SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS);\n const [row] = await getDb()\n .select({ n: count() })\n .from(signInCodeFailures)\n .where(and(eq(signInCodeFailures.identifier, identifier.toLowerCase()), gt(signInCodeFailures.failedAt, since)));\n return (row?.n ?? 0) >= SIGN_IN_CODE_WRONG_GUESS_LIMIT;\n } catch {\n return true;\n }\n}\n\n/** Counts one wrong code against this address, and clears rows older than a day. */\nexport async function recordSignInCodeFailure(identifier: string, now = new Date()): Promise<void> {\n const db = getDb();\n await db.insert(signInCodeFailures).values({ identifier: identifier.toLowerCase(), failedAt: now });\n await db.delete(signInCodeFailures).where(lt(signInCodeFailures.failedAt, new Date(now.getTime() - 24 * 60 * 60 * 1000)));\n}\n",
|
|
26
26
|
"lib/auth/client-ip.ts": "// The caller's IP address, for rate limiting the login-link send.\n//\n// Only headers the platform OVERWRITES are trusted. The first entry of\n// `x-forwarded-for` is whatever the caller typed, so keying a limit on it lets\n// an attacker dodge their own limit and fill someone else's. This assumes the\n// app runs on Vercel, whose edge sets `x-vercel-forwarded-for` and `x-real-ip`\n// itself. On another host, list the header that host overwrites.\n//\n// No trusted header → no address. The caller then gets no per-IP bucket and\n// only the global limit applies; one shared \"unknown\" bucket would let anyone\n// who strips headers lock everybody else out.\n\nimport { isIP } from \"node:net\";\n\nconst TRUSTED_HEADERS = [\"x-vercel-forwarded-for\", \"x-real-ip\"] as const;\n\nexport type ClientIp = {\n address: string | null;\n /** Which header answered, so a missing edge header is visible in logs. */\n source: (typeof TRUSTED_HEADERS)[number] | \"none\";\n};\n\nexport function clientIpFrom(headers: Headers): ClientIp {\n for (const name of TRUSTED_HEADERS) {\n // Vercel's value is a single address, but take the first entry defensively.\n const value = headers.get(name)?.split(\",\")[0]?.trim();\n if (value && isIP(value)) return { address: value, source: name };\n }\n return { address: null, source: \"none\" };\n}\n",
|
|
@@ -31,7 +31,9 @@ export const LOGIN_TEMPLATES = {
|
|
|
31
31
|
"lib/auth/session-config.ts": "// Session settings, declared explicitly.\n//\n// - strategy \"jwt\": with an adapter configured, Auth.js would otherwise default\n// to database sessions, one query per request, which keeps a scale-to-zero\n// database (Neon) awake and burns its compute allowance.\n// - maxAge 7 days of INACTIVITY. The cookie is refreshed as the app is used, so\n// someone who opens the app every day is never logged out by this.\n//\n// Kept in its own dependency-free module so a future middleware Auth.js\n// instance imports the same object rather than silently using the 30-day default.\n\nexport const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;\n\nexport const sessionConfig = {\n strategy: \"jwt\",\n maxAge: SESSION_MAX_AGE_SECONDS,\n} as const;\n",
|
|
32
32
|
"lib/auth/sign-in-code.ts": "// The typed login code.\n//\n// WHY: an app installed on an iPhone home screen keeps its cookies apart from\n// Safari and Chrome, and a login link tapped in Mail opens in the phone's default\n// browser. So the link logs in the browser, not the installed app. A code the\n// person TYPES into the app logs in exactly where they are.\n//\n// HOW: the email provider's generateVerificationToken returns this code, so the\n// SAME secret is the link's `token=` and the code printed in the email. Typing it\n// just opens the address the link would have (buildCodeCallbackPath). No second\n// token store, no custom route: same single use, same allowlist, same audit.\n//\n// 🔴 WHY 8 DIGITS: Auth.js stores a token BEFORE our send gate decides to send,\n// so a suppressed request still leaves a live code behind; an attacker can mint\n// codes for an address without its owner getting any email. The guards\n// (lib/auth/adapter.ts): at most SIGN_IN_CODE_LIVE_MAX live codes per address,\n// and at most SIGN_IN_CODE_WRONG_GUESS_LIMIT wrong guesses per address per hour,\n// counted in the database (sign_in_code_failures) so every server instance\n// shares the count, fail-closed. 5 live × 240 guesses/day over 10^8 codes is\n// about 0.4% per YEAR of continuous invisible guessing; 6 digits would be ~1%\n// per WEEK.\n//\n// Pure (Web Crypto only), so the browser form and tests can import it.\n\nimport { MAX_OUTSTANDING_PER_EMAIL } from \"./sign-in-policy\";\n\nexport const SIGN_IN_CODE_LENGTH = 8;\n\n/**\n * Newest codes kept per address. EQUAL to the per-address send limit on purpose:\n * that limit counts live tokens, so keeping fewer would silently switch it off.\n */\nexport const SIGN_IN_CODE_LIVE_MAX = MAX_OUTSTANDING_PER_EMAIL;\n\n/** Wrong codes (or used/old links) allowed per address per window before locking. */\nexport const SIGN_IN_CODE_WRONG_GUESS_LIMIT = 10;\nexport const SIGN_IN_CODE_WRONG_GUESS_WINDOW_MS = 60 * 60 * 1000;\n\n/**\n * A uniformly random 8-digit code (leading zeros kept). Rejection sampling, not\n * `% 1e8` on a raw Uint32, which would make low codes slightly likelier.\n */\nexport function generateSignInCode(): string {\n const space = 10 ** SIGN_IN_CODE_LENGTH;\n const limit = Math.floor(0x1_0000_0000 / space) * space;\n const buf = new Uint32Array(1);\n for (;;) {\n crypto.getRandomValues(buf);\n if (buf[0] < limit) return String(buf[0] % space).padStart(SIGN_IN_CODE_LENGTH, \"0\");\n }\n}\n\n/** \"12345678\" → \"1234 5678\", as the email prints it. */\nexport function formatSignInCode(code: string): string {\n const half = SIGN_IN_CODE_LENGTH / 2;\n return `${code.slice(0, half)} ${code.slice(half)}`;\n}\n\n/**\n * What a person typed → the bare code, or null. Spaces, dashes and dots are\n * dropped; anything else, or the wrong number of digits, is refused in the\n * browser so a typo doesn't spend one of the address's guesses.\n */\nexport function normalizeSignInCode(input: string): string | null {\n const digits = input.replace(/[\\s.\\-–—]/g, \"\");\n return new RegExp(`^\\\\d{${SIGN_IN_CODE_LENGTH}}$`).test(digits) ? digits : null;\n}\n\n/** The address the email's button opens, rebuilt from a typed code. Relative: stays in this app. */\nexport function buildCodeCallbackPath(email: string, code: string): string {\n const params = new URLSearchParams({ token: code, email: email.trim().toLowerCase() });\n return `/api/auth/callback/email?${params}`;\n}\n\n/** The code inside a login URL, if it is one (the email prints it beside the button). */\nexport function codeFromLoginUrl(url: string): string | null {\n try {\n return normalizeSignInCode(new URL(url).searchParams.get(\"token\") ?? \"\");\n } catch {\n return null;\n }\n}\n",
|
|
33
33
|
"lib/auth/sign-in-policy.ts": "// Who may log in, and how many login links may be outstanding.\n//\n// Login is invite-only. The allowlist is the `users.sign_in_enabled` column, not\n// an env var, so access can be granted in the app without a redeploy. There is\n// no env-var grant: the first owner is created by scripts/provision-user.ts with\n// sign-in on.\n//\n// canUserSignIn() is the ONE predicate. The adapter, the send gate and the\n// current-user helper all call it (test/auth-guards.test.ts checks the call sites).\n\nexport type SignInCandidate = {\n isActive: boolean;\n signInEnabled: boolean;\n tenantStatus: string;\n};\n\nexport function canUserSignIn(user: SignInCandidate | null | undefined): boolean {\n if (!user) return false;\n // Only exactly \"active\". An unknown status denies.\n return user.isActive && user.signInEnabled && user.tenantStatus === \"active\";\n}\n\n/**\n * Login links still outstanding, counted from `verification_tokens` (shared by\n * every serverless instance). This bounds unused links, not attempts per hour,\n * so it pairs with the in-memory per-IP limiter.\n *\n * Both counts must include ONLY addresses that can log in. Counting unknown\n * addresses would let anyone fill the global budget with made-up emails and\n * silently block every real login for a day.\n *\n * Accurate to ±1: Auth.js writes the token concurrently with the send, so the\n * current request's own row may or may not be counted yet. Don't \"fix\" that by\n * changing >= to >.\n */\nexport const MAX_OUTSTANDING_PER_EMAIL = 5;\nexport const MAX_OUTSTANDING_GLOBAL = 200;\n\nexport function evaluateMagicLinkQuota({\n outstandingForEmail,\n outstandingGlobal,\n}: {\n outstandingForEmail: number;\n outstandingGlobal: number;\n}): { allowed: true } | { allowed: false; reason: \"per-email\" | \"global\" } {\n if (outstandingForEmail >= MAX_OUTSTANDING_PER_EMAIL) return { allowed: false, reason: \"per-email\" };\n if (outstandingGlobal >= MAX_OUTSTANDING_GLOBAL) return { allowed: false, reason: \"global\" };\n return { allowed: true };\n}\n\n/** Lower-cased, trimmed, and shaped like an address; otherwise null. */\nexport function normalizeEmail(raw: unknown): string | null {\n if (typeof raw !== \"string\") return null;\n const email = raw.normalize(\"NFKC\").trim().toLowerCase();\n if (email.length > 254) return null;\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : null;\n}\n",
|
|
34
|
+
"lib/contact-url.ts": "// The organization's contact page as a safe link, or null.\n//\n// https only: this lands in an href on every page, and a `javascript:` or\n// plain-http value stored by mistake must never become a link. Anything that\n// does not parse as a URL is treated as \"no contact page\".\n\nexport function safeContactUrl(raw: unknown): string | null {\n if (typeof raw !== \"string\" || raw.trim() === \"\") return null;\n try {\n const url = new URL(raw.trim());\n return url.protocol === \"https:\" ? url.toString() : null;\n } catch {\n return null;\n }\n}\n",
|
|
34
35
|
"lib/current-user.ts": "// The ONLY way app code asks \"who is logged in, and which account is theirs?\"\n//\n// The tenant comes from the logged-in user's own row, never from a URL or a\n// form field. Every query on account data filters by the returned `tenantId`.\n//\n// This re-reads the user on each request, so turning off a person's sign-in or\n// deactivating them takes effect at once, even though their session cookie is\n// still valid.\n\nimport \"server-only\";\n\nimport { eq } from \"drizzle-orm\";\nimport { redirect } from \"next/navigation\";\n\nimport { auth } from \"@/auth\";\nimport { getDb } from \"@/db/client\";\nimport { tenants, users } from \"@/db/schema\";\nimport { isPhantomUser } from \"@/lib/auth/adapter\";\nimport { canUserSignIn } from \"@/lib/auth/sign-in-policy\";\nimport { AGREE_PATH, LOGIN_PATH } from \"@/lib/routes\";\nimport { hasAgreedToCurrentTerms } from \"@/lib/terms\";\n\nexport type CurrentUser = {\n user: typeof users.$inferSelect;\n tenant: typeof tenants.$inferSelect;\n tenantId: string;\n};\n\nexport async function getCurrentUser(): Promise<CurrentUser | null> {\n const session = await auth();\n const userId = session?.user?.id;\n if (!userId || isPhantomUser(userId)) return null;\n\n const [row] = await getDb()\n .select({ user: users, tenant: tenants })\n .from(users)\n .innerJoin(tenants, eq(users.tenantId, tenants.id))\n .where(eq(users.id, userId))\n .limit(1);\n if (!row) return null;\n const allowed = canUserSignIn({\n isActive: row.user.isActive,\n signInEnabled: row.user.signInEnabled,\n tenantStatus: row.tenant.status,\n });\n if (!allowed) return null;\n return { user: row.user, tenant: row.tenant, tenantId: row.tenant.id };\n}\n\n/**\n * Logged in, but maybe not yet agreed to the Terms. Only for /agree and its\n * submit handler, which must be reachable before agreeing. Every other page\n * uses requireAgreedUser().\n */\nexport async function requireCurrentUser(): Promise<CurrentUser> {\n const current = await getCurrentUser();\n if (!current) redirect(LOGIN_PATH);\n return current;\n}\n\n/**\n * For every logged-in PAGE. Not logged in → /login; not agreed to the current\n * Terms (lib/terms.ts) → /agree, whatever they asked for.\n */\nexport async function requireAgreedUser(): Promise<CurrentUser> {\n const current = await requireCurrentUser();\n if (!hasAgreedToCurrentTerms(current.user)) redirect(AGREE_PATH);\n return current;\n}\n\n/**\n * For every ROUTE HANDLER and server action that acts for a logged-in person.\n * A page guard alone is decorative: a direct POST skips the page. Returns null\n * for \"not logged in\" and \"not agreed\" alike; answer null with\n * seeOther(AGREE_PATH) (a logged-out visitor is then sent on to /login).\n *\n * Never use it on a caller that is not a person: webhooks, cron and job\n * endpoints, /api/health, /api/auth/*, and service-token APIs other apps call.\n * They have no session, and a redirect breaks them silently.\n */\nexport async function getAgreedUser(): Promise<CurrentUser | null> {\n const current = await getCurrentUser();\n if (!current || !hasAgreedToCurrentTerms(current.user)) return null;\n return current;\n}\n",
|
|
36
|
+
"lib/footer-contact.ts": "// Which organization's contact page the footer shows.\n//\n// * Logged in: the person's own organization (from lib/current-user.ts).\n// * Not logged in, and the app has exactly ONE organization: that one, so a\n// single-organization app shows Contact on its public pages too.\n// * Otherwise: none. With several organizations and nobody logged in there\n// is no honest answer to \"whose contact page?\", so no link is shown.\n//\n// Set an organization's page by storing it in tenants.contact_url (build the\n// field into the organization's settings page). A failure here never breaks a\n// page: the footer simply has no Contact link.\n\nimport \"server-only\";\n\nimport { getDb } from \"@/db/client\";\nimport { tenants } from \"@/db/schema\";\nimport { safeContactUrl } from \"@/lib/contact-url\";\nimport { getCurrentUser } from \"@/lib/current-user\";\n\nexport async function footerContactUrl(): Promise<string | null> {\n try {\n const current = await getCurrentUser();\n if (current) return safeContactUrl(current.tenant.contactUrl);\n const rows = await getDb().select({ contactUrl: tenants.contactUrl }).from(tenants).limit(2);\n return rows.length === 1 ? safeContactUrl(rows[0].contactUrl) : null;\n } catch {\n return null;\n }\n}\n",
|
|
35
37
|
"lib/http.ts": "// Small helpers for the route handlers that receive this app's forms.\n//\n// Forms post to route handlers, not Server Actions. A Server Action is\n// addressed by an id that changes with every build, so a page left open in a\n// tab (or restored from the back/forward cache) would submit into nothing and\n// the person would only see that the email never came. A route handler's address is its URL, which every build has.\n//\n// A route handler gets no cross-site check from the framework, so it calls\n// isSameOriginPost() itself.\n\n/**\n * True unless the request carries an Origin from a different host. Origin is\n * checked only when present: some browsers omit it on same-origin form posts,\n * and refusing those would break the form for real people.\n */\nexport function isSameOriginPost(request: Request): boolean {\n const origin = request.headers.get(\"origin\");\n if (origin === null) return true;\n const host = (request.headers.get(\"x-forwarded-host\") ?? request.headers.get(\"host\"))?.toLowerCase();\n if (!host) return false;\n try {\n return new URL(origin).host.toLowerCase() === host;\n } catch {\n return false; // includes the literal \"null\"\n }\n}\n\n/**\n * 303 to a path on this site. A RELATIVE Location keeps the browser on the\n * host it is already on, rather than one built from a request header.\n */\nexport function seeOther(path: string): Response {\n if (!path.startsWith(\"/\") || path.startsWith(\"//\")) throw new Error(\"seeOther takes a site path\");\n return new Response(null, { status: 303, headers: { Location: path } });\n}\n",
|
|
36
38
|
"lib/provisioning.ts": "// Argument parsing for scripts/provision-user.ts. Pure, so it is unit-tested.\n// Relative .ts imports only: plain Node runs the script that imports this.\n\nimport { normalizeEmail } from \"./auth/sign-in-policy.ts\";\n\nexport type ProvisionArgs = {\n email: string;\n firstName: string;\n /** Null for someone with one name. Names are never split from a full name. */\n lastName: string | null;\n /** The account (tenant) this person owns. Defaults to their own name. */\n accountName: string;\n};\n\nconst MAX_NAME = 80;\n\n/** Trims and collapses spaces; null when empty or too long. */\nfunction tidy(value: string | undefined): string | null {\n if (value === undefined) return null;\n const out = value.normalize(\"NFC\").replace(/\\s+/g, \" \").trim();\n return out.length >= 1 && out.length <= MAX_NAME ? out : null;\n}\n\nexport function parseProvisionArgs(\n argv: readonly string[],\n): { ok: true; value: ProvisionArgs } | { ok: false; error: string } {\n const flags = new Map<string, string>();\n for (let i = 0; i < argv.length; i += 2) {\n const flag = argv[i];\n const value = argv[i + 1];\n if (!flag?.startsWith(\"--\") || value === undefined || value.startsWith(\"--\")) {\n return { ok: false, error: `expected \"--flag value\" pairs, got \"${flag ?? \"\"}\"` };\n }\n flags.set(flag.slice(2), value);\n }\n\n const email = normalizeEmail(flags.get(\"email\"));\n if (!email) return { ok: false, error: \"--email must be an email address\" };\n\n if (flags.has(\"name\")) return { ok: false, error: \"use --first-name and --last-name, not --name\" };\n const firstName = tidy(flags.get(\"first-name\"));\n if (!firstName) return { ok: false, error: `--first-name is required (up to ${MAX_NAME} characters)` };\n const lastRaw = flags.get(\"last-name\");\n const lastName = tidy(lastRaw);\n if (lastRaw !== undefined && !lastName) return { ok: false, error: `--last-name must be 1 to ${MAX_NAME} characters` };\n\n const accountRaw = flags.get(\"account-name\");\n const accountName = accountRaw === undefined ? displayName(firstName, lastName) : tidy(accountRaw);\n if (!accountName) return { ok: false, error: `--account-name must be 1 to ${MAX_NAME} characters` };\n\n return { ok: true, value: { email, firstName, lastName, accountName } };\n}\n\n/** First and last name joined. Only ever joined, never split. */\nexport function displayName(firstName: string, lastName: string | null): string {\n return lastName ? `${firstName} ${lastName}` : firstName;\n}\n",
|
|
37
39
|
"lib/routes.ts": "// Where login and logout land. Client-safe: imports nothing, because the login\n// form (a client component) reads these too.\n//\n// POST_LOGIN_DESTINATION is never a public page. A page that always shows a\n// \"Log in\" link, used as the post-login target, makes a returning user log in\n// twice or loop forever. test/auth-guards.test.ts pins this.\n\n/** The first screen a logged-in person sees. Replace with the app's real home. */\nexport const POST_LOGIN_DESTINATION = \"/dashboard\";\n\n/** Must render without a session, or logging out bounces. */\nexport const POST_LOGOUT_DESTINATION = \"/login\";\n\nexport const LOGIN_PATH = \"/login\";\nexport const CHECK_EMAIL_PATH = \"/login/check-email\";\n\n/** Where a logged-in person who has not agreed to the current Terms is sent, whatever they asked for. */\nexport const AGREE_PATH = \"/agree\";\nexport const TERMS_PATH = \"/terms\";\nexport const PRIVACY_PATH = \"/privacy\";\n\n/** Pages a visitor without a session can see. Add each new public page here. */\nexport const PUBLIC_ROUTES = [\n \"/\",\n \"/guide\",\n \"/guide/whats-new\",\n LOGIN_PATH,\n CHECK_EMAIL_PATH,\n \"/login/error\",\n TERMS_PATH,\n PRIVACY_PATH,\n] as const;\n",
|
|
@@ -44,8 +46,9 @@ export const LOGIN_TEMPLATES = {
|
|
|
44
46
|
"test/auth-hosts.test.ts": "/**\n * The login-link host allowlist (lib/auth/hosts.ts). The security cases come\n * with a NEGATIVE CONTROL: local development must still work in every shape a\n * dev server answers on, or a hard-coded `false` would pass every other test.\n */\nimport { describe, expect, it } from \"vitest\";\n\nimport { canonicalHosts, isKnownHost, isLoopbackHost, isProductionDeployment, normalizeHost } from \"@/lib/auth/hosts\";\n\nconst PROD = { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst PREVIEW = { VERCEL_ENV: \"preview\", NODE_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" };\nconst LOCAL = { NODE_ENV: \"development\" };\n\ndescribe(\"isKnownHost\", () => {\n it(\"allows the canonical host, case-insensitively\", () => {\n expect(isKnownHost(\"app.example.test\", PROD)).toBe(true);\n expect(isKnownHost(\"App.Example.TEST\", PROD)).toBe(true);\n });\n\n it(\"refuses any other host in production, including localhost\", () => {\n expect(isKnownHost(\"attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"app.example.test.attacker.example\", PROD)).toBe(false);\n expect(isKnownHost(\"localhost:3000\", PROD)).toBe(false);\n });\n\n it(\"CANONICAL_HOSTS unset in production means nobody, not everybody\", () => {\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\" })).toBe(false);\n expect(isKnownHost(\"app.example.test\", { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \" , \" })).toBe(false);\n });\n\n it(\"refuses a forged host on a PREVIEW deployment, which has a public URL\", () => {\n expect(isKnownHost(\"attacker.example\", PREVIEW)).toBe(false);\n expect(isKnownHost(\"app-git-main-team.vercel.app\", PREVIEW)).toBe(false);\n });\n\n it(\"a preview that lists its own host may send links\", () => {\n const env = { ...PREVIEW, CANONICAL_HOSTS: \"app.example.test,app-git-main-team.vercel.app\" };\n expect(isKnownHost(\"app-git-main-team.vercel.app\", env)).toBe(true);\n });\n\n it(\"NEGATIVE CONTROL: local development works in every loopback shape\", () => {\n for (const host of [\"localhost\", \"localhost:3000\", \"127.0.0.1:3000\", \"[::1]:3000\", \"app.localhost:3000\"]) {\n expect(isKnownHost(host, LOCAL), host).toBe(true);\n }\n });\n\n it(\"refuses malformed hosts\", () => {\n for (const host of [\"\", \"evil.example/path\", \"user@evil.example\", \"evil example\", null, 42]) {\n expect(isKnownHost(host, LOCAL)).toBe(false);\n }\n });\n});\n\ndescribe(\"isProductionDeployment\", () => {\n it(\"is decided by VERCEL_ENV, because Vercel previews run with NODE_ENV=production\", () => {\n expect(isProductionDeployment({ VERCEL_ENV: \"production\" })).toBe(true);\n expect(isProductionDeployment({ VERCEL_ENV: \"preview\", NODE_ENV: \"production\" })).toBe(false);\n expect(isProductionDeployment({ NODE_ENV: \"production\" })).toBe(false);\n });\n});\n\ndescribe(\"helpers\", () => {\n it(\"parses CANONICAL_HOSTS into a normalized set\", () => {\n expect([...canonicalHosts({ CANONICAL_HOSTS: \" App.example.test , bad host,x.test:8443\" })]).toEqual([\n \"app.example.test\",\n \"x.test:8443\",\n ]);\n });\n\n it(\"recognizes loopback hosts and nothing else\", () => {\n expect(isLoopbackHost(\"localhost:3000\")).toBe(true);\n expect(isLoopbackHost(\"[::1]\")).toBe(true);\n expect(isLoopbackHost(\"localhost.attacker.example\")).toBe(false);\n expect(isLoopbackHost(\"127.0.0.2\")).toBe(false);\n });\n\n it(\"normalizeHost lower-cases and rejects junk\", () => {\n expect(normalizeHost(\" Example.COM:443 \")).toBe(\"example.com:443\");\n expect(normalizeHost(\"https://example.com\")).toBeNull();\n });\n});\n",
|
|
45
47
|
"test/auth-send-gate.test.ts": "/**\n * The send gate (lib/auth/send-gate.ts): every reason an email is or isn't\n * sent, with fake dependencies so each branch is exercised directly. The two\n * properties that matter most: it never throws (a throw would leak who has an\n * account), and refused requests never reach the database or a quota.\n */\nimport { describe, expect, it, vi } from \"vitest\";\n\nimport { createRateLimiter } from \"@/lib/auth/rate-limit\";\nimport { deliverLoginLink, type SendGateDeps } from \"@/lib/auth/send-gate\";\nimport type { SignInCandidate } from \"@/lib/auth/sign-in-policy\";\n\nconst ACTIVE: SignInCandidate = { isActive: true, signInEnabled: true, tenantStatus: \"active\" };\nconst LINK = \"https://app.example.test/api/auth/callback/email?callbackUrl=%2Fdashboard&token=abc&email=pat%40example.com\";\n\nfunction deps(overrides: Partial<SendGateDeps> = {}) {\n const log = { warn: vi.fn(), error: vi.fn() };\n const d: SendGateDeps = {\n env: { VERCEL_ENV: \"production\", CANONICAL_HOSTS: \"app.example.test\" },\n findUser: vi.fn(async (email: string) => (email === \"pat@example.com\" ? ACTIVE : null)),\n countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 0 })),\n sendEmail: vi.fn(async () => ({ sent: true })),\n ipLimiter: createRateLimiter({ limit: 20, windowMs: 3_600_000 }),\n instanceLimiter: createRateLimiter({ limit: 300, windowMs: 3_600_000 }),\n log,\n ...overrides,\n };\n return { d, log };\n}\n\nconst req = (identifier = \"pat@example.com\", url = LINK, ip = \"203.0.113.7\") => ({\n identifier,\n url,\n headers: new Headers({ \"x-real-ip\": ip }),\n});\n\ndescribe(\"deliverLoginLink\", () => {\n it(\"sends the email to an invited, active member\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"Pat@Example.com\"), d)).toBe(\"sent\");\n expect(d.sendEmail).toHaveBeenCalledOnce();\n const message = vi.mocked(d.sendEmail).mock.calls[0][0];\n expect(message.to).toBe(\"pat@example.com\");\n expect(message.text).toContain(LINK);\n });\n\n it(\"refuses a forged host before touching the database\", async () => {\n const { d } = deps();\n const forged = LINK.replace(\"app.example.test\", \"attacker.example\");\n expect(await deliverLoginLink(req(undefined, forged), d)).toBe(\"unknown-host\");\n expect(d.findUser).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"sends nothing to an address without an account, and never counts it against a quota\", async () => {\n const { d } = deps();\n expect(await deliverLoginLink(req(\"stranger@example.com\"), d)).toBe(\"not-allowed\");\n expect(d.countOutstanding).not.toHaveBeenCalled();\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it.each([\n [\"sign-in turned off\", { ...ACTIVE, signInEnabled: false }],\n [\"user deactivated\", { ...ACTIVE, isActive: false }],\n [\"account suspended\", { ...ACTIVE, tenantStatus: \"suspended\" }],\n ])(\"sends nothing when %s\", async (_label, candidate) => {\n const { d } = deps({ findUser: vi.fn(async () => candidate) });\n expect(await deliverLoginLink(req(), d)).toBe(\"not-allowed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"60 requests for made-up addresses do not block a real member\", async () => {\n const { d } = deps();\n for (let i = 0; i < 60; i++) await deliverLoginLink(req(`fake${i}@example.com`, LINK, `198.51.100.${i}`), d);\n expect(await deliverLoginLink(req(), d)).toBe(\"sent\");\n });\n\n it(\"stops at the per-address quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 5, global: 5 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-per-email\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"stops at the global quota\", async () => {\n const { d } = deps({ countOutstanding: vi.fn(async () => ({ forEmail: 0, global: 200 })) });\n expect(await deliverLoginLink(req(), d)).toBe(\"quota-global\");\n });\n\n it(\"rate-limits one IP before reading the database\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 2, windowMs: 3_600_000 }) });\n await deliverLoginLink(req(), d);\n await deliverLoginLink(req(), d);\n vi.mocked(d.findUser).mockClear();\n expect(await deliverLoginLink(req(), d)).toBe(\"rate-limited-ip\");\n expect(d.findUser).not.toHaveBeenCalled();\n });\n\n it(\"a request with no trusted IP header is not lumped into one shared bucket\", async () => {\n const { d } = deps({ ipLimiter: createRateLimiter({ limit: 1, windowMs: 3_600_000 }) });\n const noIp = { ...req(), headers: new Headers({ \"x-forwarded-for\": \"1.2.3.4\" }) };\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n expect(await deliverLoginLink(noIp, d)).toBe(\"sent\");\n });\n\n it(\"NEVER throws when the mail provider rejects the send\", async () => {\n const { d, log } = deps({ sendEmail: vi.fn(async () => Promise.reject(new Error(\"MessageRejected\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"provider-rejected\");\n expect(log.error).toHaveBeenCalled();\n });\n\n it(\"NEVER throws when the database is down\", async () => {\n const { d } = deps({ findUser: vi.fn(async () => Promise.reject(new Error(\"connection refused\"))) });\n await expect(deliverLoginLink(req(), d)).resolves.toBe(\"lookup-failed\");\n expect(d.sendEmail).not.toHaveBeenCalled();\n });\n\n it(\"logs every refusal with the host and the address (a silent refusal looks like a broken mailer)\", async () => {\n const { d, log } = deps();\n await deliverLoginLink(req(\"stranger@example.com\"), d);\n expect(log.warn).toHaveBeenCalledWith(\n expect.stringContaining(\"SUPPRESSED (not-allowed)\"),\n expect.objectContaining({ host: \"app.example.test\", email: \"stranger@example.com\" }),\n );\n });\n\n describe(\"when mail is not configured\", () => {\n const unconfigured = { sendEmail: vi.fn(async () => ({ sent: false, skippedReason: \"SES creds not set\" })) };\n\n it(\"prints the link on a local dev server, so login can be tested with no mail provider\", async () => {\n const { d, log } = deps({ ...unconfigured, env: { CANONICAL_HOSTS: \"\" } });\n const local = LINK.replace(\"https://app.example.test\", \"http://localhost:3000\");\n expect(await deliverLoginLink(req(undefined, local), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).toContain(local);\n });\n\n it(\"never prints the link off loopback: production and preview logs are kept\", async () => {\n const { d, log } = deps(unconfigured);\n expect(await deliverLoginLink(req(), d)).toBe(\"not-configured\");\n expect(log.warn.mock.calls.flat().join(\" \")).not.toContain(\"token=abc\");\n });\n });\n});\n",
|
|
46
48
|
"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",
|
|
49
|
+
"test/contact-link.test.ts": "/**\n * The footer's Contact link:\n * shown on every page whenever the organization has a contact page, read from\n * its own record (tenants.contact_url), never guessed from its domain, https only.\n *\n * Runs against an in-memory Postgres with only the session replaced.\n */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { renderToStaticMarkup } from \"react-dom/server\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { tenants, users } from \"@/db/schema\";\nimport { safeContactUrl } from \"@/lib/contact-url\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, userId: null as string | null }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/auth\", () => ({ auth: async () => (h.userId ? { user: { id: h.userId } } : null) }));\n\nconst { footerContactUrl } = await import(\"@/lib/footer-contact\");\nconst { SiteFooter } = await import(\"@/components/SiteFooter\");\n\nlet db: TestDb;\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n h.userId = null;\n});\n\ndescribe(\"safeContactUrl\", () => {\n it(\"keeps an https contact page\", () => {\n expect(safeContactUrl(\"https://example.org/contact/\")).toBe(\"https://example.org/contact/\");\n expect(safeContactUrl(\" https://example.org/contact \")).toBe(\"https://example.org/contact\");\n });\n\n it(\"no page means no link\", () => {\n for (const raw of [null, undefined, \"\", \" \", 42]) expect(safeContactUrl(raw)).toBeNull();\n });\n\n it(\"refuses anything that is not https\", () => {\n for (const raw of [\"javascript:alert(1)\", \"http://example.org/contact\", \"not a url\", \"/contact\"]) {\n expect(safeContactUrl(raw)).toBeNull();\n }\n });\n});\n\ndescribe(\"which organization's page the footer shows\", () => {\n it(\"logged in: the person's own organization\", async () => {\n await db.insert(tenants).values({ name: \"Other\", contactUrl: \"https://other.example/contact\" });\n const [mine] = await db.insert(tenants).values({ name: \"Mine\", contactUrl: \"https://mine.example/contact\" }).returning();\n const [user] = await db.insert(users).values({ tenantId: mine.id, email: \"pat@example.com\", signInEnabled: true }).returning();\n h.userId = user.id;\n expect(await footerContactUrl()).toBe(\"https://mine.example/contact\");\n });\n\n it(\"logged in, organization has no page: no link\", async () => {\n const [mine] = await db.insert(tenants).values({ name: \"Mine\" }).returning();\n const [user] = await db.insert(users).values({ tenantId: mine.id, email: \"pat@example.com\", signInEnabled: true }).returning();\n h.userId = user.id;\n expect(await footerContactUrl()).toBeNull();\n });\n\n it(\"not logged in, ONE organization: its page\", async () => {\n await db.insert(tenants).values({ name: \"Only\", contactUrl: \"https://only.example/contact\" });\n expect(await footerContactUrl()).toBe(\"https://only.example/contact\");\n });\n\n it(\"not logged in, several organizations: no link (whose would it be?)\", async () => {\n await db.insert(tenants).values([\n { name: \"A\", contactUrl: \"https://a.example/contact\" },\n { name: \"B\", contactUrl: \"https://b.example/contact\" },\n ]);\n expect(await footerContactUrl()).toBeNull();\n });\n\n it(\"a stored javascript: value never becomes a link\", async () => {\n await db.insert(tenants).values({ name: \"Only\", contactUrl: \"javascript:alert(1)\" });\n expect(await footerContactUrl()).toBeNull();\n });\n});\n\ndescribe(\"the footer\", () => {\n it(\"shows Contact first when there is a page, and not otherwise\", () => {\n const withPage = renderToStaticMarkup(SiteFooter({ contactUrl: \"https://example.org/contact\" }));\n expect(withPage).toMatch(/<a href=\"https:\\/\\/example\\.org\\/contact\">Contact<\\/a>/);\n const without = renderToStaticMarkup(SiteFooter({ contactUrl: null }));\n expect(without).not.toContain(\"Contact\");\n expect(without).toContain('href=\"/terms\"');\n });\n\n it(\"the root layout passes the organization's page to the footer\", () => {\n const root = join(dirname(fileURLToPath(import.meta.url)), \"..\");\n const layout = readFileSync(join(root, \"app/layout.tsx\"), \"utf8\");\n expect(layout).toMatch(/<SiteFooter contactUrl=\\{await footerContactUrl\\(\\)\\} \\/>/);\n });\n\n it(\"nothing builds a contact URL from a domain\", () => {\n const root = join(dirname(fileURLToPath(import.meta.url)), \"..\");\n for (const f of [\"components/SiteFooter.tsx\", \"lib/footer-contact.ts\", \"app/layout.tsx\"]) {\n expect(readFileSync(join(root, f), \"utf8\")).not.toMatch(/\\/contact\\/?[\"'`]/);\n }\n });\n});\n",
|
|
47
50
|
"test/helpers/test-db.ts": "// An in-memory Postgres (PGlite) built from db/schema.ts. Tests that need a\n// real database use this instead of mocking queries, so they exercise the same\n// SQL, constraints and foreign keys that production runs.\n//\n// The SQL comes from drizzle-kit's own generator (the code behind\n// `npm run db:generate`), diffing an empty schema against db/schema.ts. So a\n// new table needs no change here, and a schema that drizzle-kit can't turn into\n// SQL fails here first, not on the production database.\n\nimport { PGlite } from \"@electric-sql/pglite\";\nimport { drizzle } from \"drizzle-orm/pglite\";\nimport { generateDrizzleJson, generateMigration } from \"drizzle-kit/api\";\n\nimport * as schema from \"@/db/schema\";\n\nexport async function createTestDb() {\n const client = new PGlite();\n const statements = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(schema));\n for (const statement of statements) await client.exec(statement);\n return { client, db: drizzle(client, { schema }) };\n}\n\nexport type TestDb = Awaited<ReturnType<typeof createTestDb>>[\"db\"];\n",
|
|
48
51
|
"test/sign-in-code.test.ts": "/** The typed login code (lib/auth/sign-in-code.ts) and its place in the email. */\nimport { describe, expect, it } from \"vitest\";\n\nimport { buildLoginEmail } from \"@/lib/auth/login-email\";\nimport {\n buildCodeCallbackPath,\n codeFromLoginUrl,\n formatSignInCode,\n generateSignInCode,\n normalizeSignInCode,\n SIGN_IN_CODE_LIVE_MAX,\n} from \"@/lib/auth/sign-in-code\";\nimport { MAX_OUTSTANDING_PER_EMAIL } from \"@/lib/auth/sign-in-policy\";\n\ndescribe(\"the login code\", () => {\n it(\"is always 8 digits, leading zeros kept, and varies\", () => {\n const codes = new Set(Array.from({ length: 200 }, generateSignInCode));\n for (const c of codes) expect(c).toMatch(/^\\d{8}$/);\n expect(codes.size).toBeGreaterThan(195);\n });\n\n it(\"accepts what people type, refuses the rest before it costs a guess\", () => {\n expect(normalizeSignInCode(\"1234 5678\")).toBe(\"12345678\");\n expect(normalizeSignInCode(\" 1234-5678 \")).toBe(\"12345678\");\n expect(normalizeSignInCode(\"1234567\")).toBeNull();\n expect(normalizeSignInCode(\"123456789\")).toBeNull();\n expect(normalizeSignInCode(\"1234abcd\")).toBeNull();\n expect(formatSignInCode(\"01234567\")).toBe(\"0123 4567\");\n });\n\n it(\"builds a relative callback with the address lower-cased, so it stays in this app\", () => {\n expect(buildCodeCallbackPath(\" Pat@Example.COM \", \"01234567\")).toBe(\n \"/api/auth/callback/email?token=01234567&email=pat%40example.com\",\n );\n });\n\n it(\"keeps exactly as many live codes as the per-address send limit counts\", () => {\n expect(SIGN_IN_CODE_LIVE_MAX).toBe(MAX_OUTSTANDING_PER_EMAIL);\n });\n\n it(\"the email prints the link's own code, and no code when the token isn't one\", () => {\n const url = \"https://app.example.test/api/auth/callback/email?callbackUrl=x&token=01234567&email=pat%40example.com\";\n expect(codeFromLoginUrl(url)).toBe(\"01234567\");\n const mail = buildLoginEmail(url);\n expect(mail.text).toContain(\"0123 4567\");\n expect(mail.html).toContain(\"0123 4567\");\n const legacy = buildLoginEmail(\"https://app.example.test/api/auth/callback/email?token=\" + \"a\".repeat(64));\n expect(legacy.text).not.toContain(\"code into the app\");\n });\n});\n",
|
|
49
|
-
"test/terms-guard.test.ts": "/**\n * The Terms gate is enforced on the SERVER, in both places a person can act:\n * every logged-in page (requireAgreedUser) and every route handler that acts\n * for a person (getAgreedUser). A page guard alone is decorative: a direct\n * POST skips the page.\n *\n * The guards run against an in-memory Postgres with only the session replaced.\n * The sweeps below read the source, so a NEW page or handler that forgets the\n * guard turns this file red. Comments are stripped before matching.\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { eq } from \"drizzle-orm\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { tenants, users } from \"@/db/schema\";\nimport { PUBLIC_ROUTES } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION } from \"@/lib/terms\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, userId: null as string | null }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/auth\", () => ({ auth: async () => (h.userId ? { user: { id: h.userId } } : null) }));\n\nconst { getAgreedUser, requireAgreedUser } = await import(\"@/lib/current-user\");\n\nlet db: TestDb;\n\n/** The path a Next.js redirect() call would send the browser to, or null if it returned normally. */\nasync function redirectOf(work: Promise<unknown>): Promise<string | null> {\n try {\n await work;\n return null;\n } catch (e) {\n const digest = String((e as { digest?: unknown }).digest ?? \"\");\n const m = /^NEXT_REDIRECT;[^;]*;([^;]+);/.exec(digest);\n if (!m) throw e;\n return m[1];\n }\n}\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n const [tenant] = await db.insert(tenants).values({ name: \"T\" }).returning();\n const [user] = await db.insert(users).values({ tenantId: tenant.id, email: \"pat@example.com\", signInEnabled: true }).returning();\n h.userId = user.id;\n});\n\ndescribe(\"the guards\", () => {\n it(\"a logged-in person who has not agreed is sent to /agree, and a handler gets null\", async () => {\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n expect(await getAgreedUser()).toBeNull();\n });\n\n it(\"an old version is not agreement\", async () => {\n await db.update(users).set({ termsVersion: \"2020-01-01\" }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n });\n\n it(\"the current version lets them through\", async () => {\n await db.update(users).set({ termsVersion: CURRENT_TERMS_VERSION }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBeNull();\n expect((await getAgreedUser())?.user.id).toBe(h.userId);\n });\n\n it(\"nobody logged in goes to /login, not /agree\", async () => {\n h.userId = null;\n expect(await redirectOf(requireAgreedUser())).toBe(\"/login\");\n expect(await getAgreedUser()).toBeNull();\n });\n});\n\nconst ROOT = join(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst code = (f: string) =>\n readFileSync(join(ROOT, f), \"utf8\")\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:\"'`])\\/\\/.*$/gm, \"$1\");\n\nfunction files(dir: string, name: RegExp): string[] {\n const out: string[] = [];\n for (const entry of readdirSync(join(ROOT, dir))) {\n const rel = join(dir, entry);\n if (statSync(join(ROOT, rel)).isDirectory()) out.push(...files(rel, name));\n else if (name.test(entry)) out.push(rel);\n }\n return out;\n}\n\n/** \"app/guide/whats-new/page.tsx\" → \"/guide/whats-new\". Route groups like (app) are dropped. */\nfunction routeOf(file: string): string {\n const parts = dirname(file).split(\"/\").slice(1).filter((p) => !/^\\(.*\\)$/.test(p));\n return \"/\" + parts.join(\"/\");\n}\n\n/**\n * Route handlers whose caller is not a logged-in person who has agreed, so they\n * must NOT use getAgreedUser. Add a webhook, cron job or service-token API here\n * ON PURPOSE, with the reason, never by default: a redirect breaks it silently.\n */\nconst NOT_A_PERSON_WHO_AGREED: Record<string, string> = {\n \"/api/auth/[...nextauth]\": \"Auth.js itself: logging in happens before agreeing.\",\n \"/api/health\": \"The uptime monitor. No session, ever.\",\n \"/login/submit\": \"Sends the login email; nobody is logged in yet.\",\n \"/logout\": \"Logging out must work for someone who will not agree.\",\n \"/agree/submit\": \"Records agreement, so it must work before it.\",\n};\n\ndescribe(\"every page and handler is guarded\", () => {\n it(\"every logged-in page calls requireAgreedUser()\", () => {\n const exempt = new Set<string>([...PUBLIC_ROUTES, \"/agree\"]);\n const unguarded = files(\"app\", /^page\\.tsx$/)\n .filter((f) => !exempt.has(routeOf(f)))\n .filter((f) => !/\\brequireAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"every route handler calls getAgreedUser(), unless it is listed as not a person\", () => {\n const unguarded = files(\"app\", /^route\\.ts$/)\n .filter((f) => !(routeOf(f) in NOT_A_PERSON_WHO_AGREED))\n .filter((f) => !/\\bgetAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"the exempt list names only handlers that exist\", () => {\n const routes = new Set(files(\"app\", /^route\\.ts$/).map(routeOf));\n expect(Object.keys(NOT_A_PERSON_WHO_AGREED).filter((r) => !routes.has(r))).toEqual([]);\n });\n\n it(\"the root layout mounts the footer, so every page links the Terms\", () => {\n expect(code(\"app/layout.tsx\")).toMatch(/<SiteFooter\\
|
|
52
|
+
"test/terms-guard.test.ts": "/**\n * The Terms gate is enforced on the SERVER, in both places a person can act:\n * every logged-in page (requireAgreedUser) and every route handler that acts\n * for a person (getAgreedUser). A page guard alone is decorative: a direct\n * POST skips the page.\n *\n * The guards run against an in-memory Postgres with only the session replaced.\n * The sweeps below read the source, so a NEW page or handler that forgets the\n * guard turns this file red. Comments are stripped before matching.\n */\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { eq } from \"drizzle-orm\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { tenants, users } from \"@/db/schema\";\nimport { PUBLIC_ROUTES } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION } from \"@/lib/terms\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, userId: null as string | null }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/auth\", () => ({ auth: async () => (h.userId ? { user: { id: h.userId } } : null) }));\n\nconst { getAgreedUser, requireAgreedUser } = await import(\"@/lib/current-user\");\n\nlet db: TestDb;\n\n/** The path a Next.js redirect() call would send the browser to, or null if it returned normally. */\nasync function redirectOf(work: Promise<unknown>): Promise<string | null> {\n try {\n await work;\n return null;\n } catch (e) {\n const digest = String((e as { digest?: unknown }).digest ?? \"\");\n const m = /^NEXT_REDIRECT;[^;]*;([^;]+);/.exec(digest);\n if (!m) throw e;\n return m[1];\n }\n}\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n const [tenant] = await db.insert(tenants).values({ name: \"T\" }).returning();\n const [user] = await db.insert(users).values({ tenantId: tenant.id, email: \"pat@example.com\", signInEnabled: true }).returning();\n h.userId = user.id;\n});\n\ndescribe(\"the guards\", () => {\n it(\"a logged-in person who has not agreed is sent to /agree, and a handler gets null\", async () => {\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n expect(await getAgreedUser()).toBeNull();\n });\n\n it(\"an old version is not agreement\", async () => {\n await db.update(users).set({ termsVersion: \"2020-01-01\" }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBe(\"/agree\");\n });\n\n it(\"the current version lets them through\", async () => {\n await db.update(users).set({ termsVersion: CURRENT_TERMS_VERSION }).where(eq(users.id, h.userId!));\n expect(await redirectOf(requireAgreedUser())).toBeNull();\n expect((await getAgreedUser())?.user.id).toBe(h.userId);\n });\n\n it(\"nobody logged in goes to /login, not /agree\", async () => {\n h.userId = null;\n expect(await redirectOf(requireAgreedUser())).toBe(\"/login\");\n expect(await getAgreedUser()).toBeNull();\n });\n});\n\nconst ROOT = join(dirname(fileURLToPath(import.meta.url)), \"..\");\nconst code = (f: string) =>\n readFileSync(join(ROOT, f), \"utf8\")\n .replace(/\\{\\/\\*[\\s\\S]*?\\*\\/\\}/g, \"\")\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:\"'`])\\/\\/.*$/gm, \"$1\");\n\nfunction files(dir: string, name: RegExp): string[] {\n const out: string[] = [];\n for (const entry of readdirSync(join(ROOT, dir))) {\n const rel = join(dir, entry);\n if (statSync(join(ROOT, rel)).isDirectory()) out.push(...files(rel, name));\n else if (name.test(entry)) out.push(rel);\n }\n return out;\n}\n\n/** \"app/guide/whats-new/page.tsx\" → \"/guide/whats-new\". Route groups like (app) are dropped. */\nfunction routeOf(file: string): string {\n const parts = dirname(file).split(\"/\").slice(1).filter((p) => !/^\\(.*\\)$/.test(p));\n return \"/\" + parts.join(\"/\");\n}\n\n/**\n * Route handlers whose caller is not a logged-in person who has agreed, so they\n * must NOT use getAgreedUser. Add a webhook, cron job or service-token API here\n * ON PURPOSE, with the reason, never by default: a redirect breaks it silently.\n */\nconst NOT_A_PERSON_WHO_AGREED: Record<string, string> = {\n \"/api/auth/[...nextauth]\": \"Auth.js itself: logging in happens before agreeing.\",\n \"/api/health\": \"The uptime monitor. No session, ever.\",\n \"/login/submit\": \"Sends the login email; nobody is logged in yet.\",\n \"/logout\": \"Logging out must work for someone who will not agree.\",\n \"/agree/submit\": \"Records agreement, so it must work before it.\",\n};\n\ndescribe(\"every page and handler is guarded\", () => {\n it(\"every logged-in page calls requireAgreedUser()\", () => {\n const exempt = new Set<string>([...PUBLIC_ROUTES, \"/agree\"]);\n const unguarded = files(\"app\", /^page\\.tsx$/)\n .filter((f) => !exempt.has(routeOf(f)))\n .filter((f) => !/\\brequireAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"every route handler calls getAgreedUser(), unless it is listed as not a person\", () => {\n const unguarded = files(\"app\", /^route\\.ts$/)\n .filter((f) => !(routeOf(f) in NOT_A_PERSON_WHO_AGREED))\n .filter((f) => !/\\bgetAgreedUser\\(\\)/.test(code(f)));\n expect(unguarded).toEqual([]);\n });\n\n it(\"the exempt list names only handlers that exist\", () => {\n const routes = new Set(files(\"app\", /^route\\.ts$/).map(routeOf));\n expect(Object.keys(NOT_A_PERSON_WHO_AGREED).filter((r) => !routes.has(r))).toEqual([]);\n });\n\n it(\"the root layout mounts the footer, so every page links the Terms\", () => {\n expect(code(\"app/layout.tsx\")).toMatch(/<SiteFooter\\b[^>]*\\/>/);\n });\n});\n",
|
|
50
53
|
"test/terms.test.ts": "/**\n * The Terms every person must agree to before using the app: the rules\n * (lib/terms.ts), the agree handler against an in-memory Postgres (only \"who is\n * logged in\" is replaced), the wording, and the footer that keeps the Terms and\n * the Privacy Policy one tap away on every page.\n */\nimport { createElement } from \"react\";\nimport { renderToStaticMarkup } from \"react-dom/server\";\nimport { eq } from \"drizzle-orm\";\nimport { beforeEach, describe, expect, it, vi } from \"vitest\";\n\nimport { auditEvents, tenants, users } from \"@/db/schema\";\nimport { PUBLIC_ROUTES } from \"@/lib/routes\";\nimport { CURRENT_TERMS_VERSION, formatTermsDate, hasAgreedToCurrentTerms, parseAgreement } from \"@/lib/terms\";\nimport { createTestDb, type TestDb } from \"./helpers/test-db\";\n\nconst h = vi.hoisted(() => ({ db: null as unknown, current: null as unknown }));\nvi.mock(\"@/db/client\", () => ({ getDb: () => h.db }));\nvi.mock(\"@/lib/current-user\", () => ({ getCurrentUser: async () => h.current, requireCurrentUser: async () => h.current }));\n\nconst { POST: agree } = await import(\"@/app/agree/submit/route\");\nconst { TermsText } = await import(\"@/components/TermsText\");\nconst { PrivacyText } = await import(\"@/components/PrivacyText\");\nconst { SiteFooter } = await import(\"@/components/SiteFooter\");\nconst { default: TermsPage } = await import(\"@/app/terms/page\");\nconst { default: PrivacyPage } = await import(\"@/app/privacy/page\");\nconst { default: AgreePage } = await import(\"@/app/agree/page\");\n\nconst HOST = \"app.example.test\";\nconst ORIGIN = `https://${HOST}`;\nlet db: TestDb;\n\nasync function newPerson(email: string) {\n const [tenant] = await db.insert(tenants).values({ name: email }).returning();\n const [user] = await db.insert(users).values({ tenantId: tenant.id, email, signInEnabled: true }).returning();\n return { user, tenant, tenantId: tenant.id };\n}\n\nfunction post(fields: Record<string, string>, origin = ORIGIN) {\n return new Request(`${ORIGIN}/agree/submit`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\", host: HOST, origin },\n body: new URLSearchParams(fields),\n });\n}\n\nbeforeEach(async () => {\n ({ db } = await createTestDb());\n h.db = db;\n h.current = null;\n});\n\ndescribe(\"the rules\", () => {\n it(\"only the current version counts as agreed\", () => {\n expect(hasAgreedToCurrentTerms({ termsVersion: CURRENT_TERMS_VERSION })).toBe(true);\n expect(hasAgreedToCurrentTerms({ termsVersion: null })).toBe(false);\n expect(hasAgreedToCurrentTerms({ termsVersion: \"2020-01-01\" })).toBe(false);\n });\n\n it(\"needs the box ticked AND the version the person was shown\", () => {\n expect(parseAgreement({ agree: \"yes\", version: CURRENT_TERMS_VERSION })).toBe(\"ok\");\n expect(parseAgreement({ agree: null, version: CURRENT_TERMS_VERSION })).toBe(\"unchecked\");\n expect(parseAgreement({ agree: \"on\", version: CURRENT_TERMS_VERSION })).toBe(\"unchecked\");\n expect(parseAgreement({ agree: \"yes\", version: \"2020-01-01\" })).toBe(\"stale\");\n expect(parseAgreement({ agree: \"yes\", version: null })).toBe(\"stale\");\n });\n\n it(\"formats a date from the string itself, so no time zone can move it a day\", () => {\n expect(formatTermsDate(\"2026-01-01\")).toBe(\"January 1, 2026\");\n expect(formatTermsDate(\"2026-12-31\")).toBe(\"December 31, 2026\");\n expect(formatTermsDate(\"not a date\")).toBe(\"not a date\");\n });\n});\n\ndescribe(\"the agree handler\", () => {\n it(\"refuses a cross-site post and sends a logged-out visitor to login\", async () => {\n expect((await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }, \"https://evil.test\"))).status).toBe(403);\n const res = await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }));\n expect(res.headers.get(\"location\")).toBe(\"/login\");\n });\n\n it(\"an unticked box or an old version records nothing and says why\", async () => {\n const me = await newPerson(\"pat@example.com\");\n h.current = me;\n expect((await agree(post({ version: CURRENT_TERMS_VERSION }))).headers.get(\"location\")).toBe(\"/agree?error=unchecked\");\n expect((await agree(post({ agree: \"yes\", version: \"2020-01-01\" }))).headers.get(\"location\")).toBe(\"/agree?error=stale\");\n const [row] = await db.select().from(users).where(eq(users.id, me.user.id));\n expect(row.termsVersion).toBeNull();\n expect(row.termsAcceptedAt).toBeNull();\n expect(await db.select().from(auditEvents)).toHaveLength(0);\n });\n\n it(\"records the version and the time, writes an audit event, and changes nobody else\", async () => {\n const me = await newPerson(\"pat@example.com\");\n const other = await newPerson(\"sam@example.com\");\n h.current = me;\n const before = Date.now();\n const res = await agree(post({ agree: \"yes\", version: CURRENT_TERMS_VERSION }));\n expect(res.status).toBe(303);\n expect(res.headers.get(\"location\")).toBe(\"/dashboard\");\n\n const [row] = await db.select().from(users).where(eq(users.id, me.user.id));\n expect(row.termsVersion).toBe(CURRENT_TERMS_VERSION);\n expect(row.termsAcceptedAt!.getTime()).toBeGreaterThanOrEqual(before - 1000);\n const audit = await db.select().from(auditEvents);\n expect(audit).toHaveLength(1);\n expect(audit[0]).toMatchObject({ action: \"user.terms_agreed\", userId: me.user.id, tenantId: me.tenant.id });\n\n const [untouched] = await db.select().from(users).where(eq(users.id, other.user.id));\n expect(untouched.termsVersion).toBeNull();\n });\n});\n\ndescribe(\"the wording and where it is shown\", () => {\n it(\"carries the hold-harmless clause and links the Privacy Policy\", () => {\n const html = renderToStaticMarkup(createElement(TermsText));\n expect(html).toContain(\"hold them harmless\");\n expect(html).toContain(\"own free will\");\n expect(html).toContain(\"not arrive at all\");\n expect(html).toContain('href=\"/privacy\"');\n });\n\n it(\"the Privacy Policy names every outside service, and says nothing is sold\", () => {\n const html = renderToStaticMarkup(createElement(PrivacyText));\n for (const name of [\"Vercel\", \"Neon\", \"Amazon SES\", \"Fathom\"]) expect(html).toContain(name);\n expect(html).toContain(\"We do not sell or rent your information.\");\n });\n\n it(\"the Terms and Privacy pages are public, each with one h1 and one Contact Us\", () => {\n for (const path of [\"/terms\", \"/privacy\"]) expect(PUBLIC_ROUTES as readonly string[]).toContain(path);\n expect(PUBLIC_ROUTES as readonly string[]).not.toContain(\"/agree\");\n for (const Page of [TermsPage, PrivacyPage]) {\n const html = renderToStaticMarkup(createElement(Page));\n expect(html.match(/<h1/g)).toHaveLength(1);\n expect(html.match(/Contact Us/g)).toHaveLength(1);\n }\n });\n\n it(\"the agree page shows the full Terms, an UNticked required box, the version shown, and a way out\", async () => {\n h.current = await newPerson(\"pat@example.com\");\n const html = renderToStaticMarkup(await AgreePage({ searchParams: Promise.resolve({}) }));\n expect(html).toContain(\"hold them harmless\");\n // Read the one checkbox's attributes, in whatever order React writes them.\n const box = (html.match(/<input[^>]*name=\"agree\"[^>]*>/g) ?? [])[0] ?? \"\";\n expect(box).toMatch(/type=\"checkbox\"/);\n expect(box).toMatch(/\\brequired\\b/);\n expect(box).not.toMatch(/\\bchecked\\b/);\n expect(html).toContain(`name=\"version\" value=\"${CURRENT_TERMS_VERSION}\"`);\n expect(html).toContain('action=\"/logout\"');\n expect(html).not.toContain('role=\"alert\"');\n\n const refused = renderToStaticMarkup(await AgreePage({ searchParams: Promise.resolve({ error: \"unchecked\" }) }));\n expect(refused).toContain('role=\"alert\"');\n expect(refused).toContain(\"Please tick the box\");\n });\n\n it(\"every page's footer links the Terms and the Privacy Policy\", () => {\n const html = renderToStaticMarkup(createElement(SiteFooter));\n expect(html).toContain('href=\"/terms\"');\n expect(html).toContain('href=\"/privacy\"');\n });\n});\n",
|
|
51
54
|
};
|