nerdsystem 0.0.13 → 0.0.15

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.
@@ -29,7 +29,7 @@ async function pickOrg(api, wanted) {
29
29
  return me.orgs[0].slug;
30
30
  if (me.orgs.length === 0)
31
31
  throw new CliError("You have no orgs. Create one in the dashboard first.");
32
- throw new CliError(`Pick an org with --org. Yours: ${me.orgs.map((o) => o.slug).join(", ")}`);
32
+ throw new CliError(`Pick an org with --org. Yours: ${me.orgs.map((o) => o.slug).join(", ")}`, 1, { code: "org_required" });
33
33
  }
34
34
  /** Creates the remote project and writes nerd.json. Shared by init and link. */
35
35
  export async function linkProject(root, args) {
@@ -171,7 +171,7 @@ export async function init(dir, args) {
171
171
  const reason = err instanceof Error ? err.message : String(err);
172
172
  const code = err instanceof CliError && err.code ? err.code : "error";
173
173
  // A plan limit is not something to fix in the folder: the API's message says how to free a slot.
174
- const link = `cd ${dir} && nerd link --slug ${slug}${args.org ? ` --org ${args.org}` : ""}`;
174
+ const link = `cd ${dir} && nerd link --slug ${slug}${args.org ? ` --org ${args.org}` : code === "org_required" ? " --org <one of yours>" : ""}`;
175
175
  const next = code === "plan_limit" ? `When a slot is free, run: ${link}` : `Fix that, then run: ${link}`;
176
176
  const message = `The folder is ready but the project was not created: ${reason}`;
177
177
  // Same pattern as `nerd check --json`: the JSON goes to stdout, the exit code stays non-zero.
@@ -183,4 +183,4 @@ export async function init(dir, args) {
183
183
  log.ok(`Ready. Next:\n cd ${dir}\n pnpm install\n nerd dev\n\nThen open the folder in your coding agent and ask it to build the first feature; the nerdsystem skill walks it through.\nDeploys go to ${project.url}`);
184
184
  }
185
185
  // Kept in sync with packages/sdk/package.json by the release script.
186
- const SDK_VERSION = "0.0.13";
186
+ const SDK_VERSION = "0.0.15";
@@ -2,6 +2,8 @@ import { bundleGate, finding, secretsGate } from "./secrets.js";
2
2
  import { depsGate, piiGate, policyGate, rulesGate, typecheckGate } from "./code.js";
3
3
  import { gitleaksGate, semgrepGate } from "./tools.js";
4
4
  import { suppressionsGate } from "./suppressions.js";
5
+ import { staticGate } from "./static.js";
6
+ import { testsGate } from "./tests.js";
5
7
  import { applyAttempts, MAX_ATTEMPTS } from "./attempts.js";
6
8
  export { gateSummary, skippedGates } from "./types.js";
7
9
  export { RULES, ruleFor } from "./rules.js";
@@ -9,7 +11,7 @@ export { mask } from "./secrets.js";
9
11
  export { MAX_ATTEMPTS, readAttempts } from "./attempts.js";
10
12
  export { probeDeployment, skippedProbe, waitForDeployment } from "./smoke.js";
11
13
  /** Gates that run on source, before the build. Suppressions first so a human sees them before anything else. */
12
- export const SOURCE_GATES = [suppressionsGate, secretsGate, gitleaksGate, depsGate, rulesGate, semgrepGate, policyGate, piiGate, typecheckGate];
14
+ export const SOURCE_GATES = [suppressionsGate, secretsGate, gitleaksGate, depsGate, rulesGate, staticGate, semgrepGate, policyGate, piiGate, typecheckGate, testsGate];
13
15
  /** Gates that need the built output. */
14
16
  export const BUILD_GATES = [bundleGate, policyGate];
15
17
  function selectGates(gates, onlyRules) {
@@ -36,6 +36,23 @@ export const RULES = {
36
36
  "rules/advisory": { title: "Platform advisory", severity: "warn", audience: "agent", risk: "Not blocking, but the project is missing something the platform expects.", fix: "Follow the instruction in the finding." },
37
37
  "rules/shape": { title: "Not in the nerdsystem shape", severity: "warn", audience: "human", risk: "Every app on nerdsystem is one shape: a Vite client, a Hono server on @nerdsystem/sdk, SQLite on D1, and a bucket. This repository is not in that shape. A clean scan says nothing about whether it would deploy here.", fix: "Start a project with `nerd init` and have the agent port the screens into it. The server and the login are rebuilt on the platform's sign-in and database. The compare pages on nerdsystem.com say what carries over." },
38
38
  "typecheck/error": { title: "TypeScript error", severity: "block", audience: "agent", risk: "The code would not compile reliably; the build may fail or behave unexpectedly.", fix: "Fix the type error at the file and line shown. Run `npx tsc -b` for the full message." },
39
+ "code/raw-sql": { title: "SQL built from values", severity: "block", audience: "agent", risk: "A value from a request placed straight into SQL lets a visitor rewrite the query and read or delete other people's data.", fix: "Use the Drizzle query builder, or bind values as parameters (`.prepare(\"... where id = ?\").bind(id)`). Never put a variable inside the SQL text.", example: { wrong: "c.env.DB.prepare(`select * from notes where id = ${id}`)", right: "db(c.env.DB).select().from(schema.notes).where(eq(schema.notes.id, id))" } },
40
+ "code/eval": { title: "eval or new Function", severity: "block", audience: "agent", risk: "Running text as code lets anyone who can influence that text run their own code in the app.", fix: "Remove it. Parse data with JSON.parse and choose behaviour with ordinary code." },
41
+ "code/password-in-app": { title: "Password handling in app code", severity: "block", audience: "agent", risk: "Storing or comparing passwords yourself is unnecessary here and easy to get wrong.", fix: "Remove it. Sign-in is provided by the platform: read the signed-in user from `c.var.user` and protect routes with `requireAuth()`.", example: { wrong: "if (user.password === body.password) { ... }", right: "app.get(\"/api/me\", requireAuth(), (c) => c.json(c.var.user));" } },
42
+ "code/tokens-in-app": { title: "Signing or verifying tokens in app code", severity: "warn", audience: "agent", risk: "A second token system beside the platform's sessions is a second way in, and a common source of mistakes.", fix: "Use the session the SDK provides (`c.var.user`). If a third-party service requires its own signed token, keep that code in one file and say so to the person." },
43
+ "code/html-from-data": { title: "HTML built from data", severity: "warn", audience: "agent", risk: "Text a user typed, rendered as HTML, can carry a script that runs in other users' browsers.", fix: "Render the value as text and let React escape it. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything that is not a fixed string." },
44
+ "code/open-redirect": { title: "Redirect to an address from the request", severity: "warn", audience: "agent", risk: "A link to your app could send people on to a look-alike site.", fix: "Redirect only to paths inside the app: check that the value starts with a single `/` and is one of the pages you expect." },
45
+ "code/fetch-user-url": { title: "Fetching an address from the request", severity: "warn", audience: "agent", risk: "A visitor could make the server fetch addresses it should not reach.", fix: "Fetch only fixed addresses, or check the host against a short list you wrote." },
46
+ "code/weak-random": { title: "Math.random used for a secret", severity: "warn", audience: "agent", risk: "Math.random is predictable, so a token or code made with it can be guessed.", fix: "Use `crypto.randomUUID()` or `crypto.getRandomValues()`." },
47
+ "code/unvalidated-body": { title: "A request body read without a check", severity: "warn", audience: "agent", risk: "Fields of any type or size reach the route, which is how bad data and oversized input get into the database.", fix: "Read it with `readBody(c, schema)` from `@nerdsystem/sdk` and a zod schema that gives every field a type and a limit. It answers 400 for anything else.", example: { wrong: "const body = await c.req.json();", right: "const input = await readBody(c, z.object({ title: z.string().trim().min(1).max(200) }));" } },
48
+ "code/routes-open-by-default": { title: "Routes are open unless each one is protected", severity: "warn", audience: "agent", risk: "A route added without `requireAuth()` answers everyone on the internet.", fix: "Pass the list of public routes to `createNerdApp({ public: [\"GET /api/health\"] })` (needs @nerdsystem/sdk 0.0.15 or later). Every other route then requires sign-in automatically. Run the tests afterwards: a route that was meant to be public must be on the list." },
49
+ "tests/missing": { title: "No access tests", severity: "warn", audience: "agent", risk: "Nothing checks that a signed-out visitor is refused, or that one user cannot reach another user's data. Those are the two mistakes that expose people's records, and nobody looking at the screen can see them.", fix: "Add the access tests: update @nerdsystem/sdk to the latest version, add vitest as a dev dependency with a `test` script (`vitest run`), and copy `test/setup.ts`, `test/global-setup.ts`, `test/access.test.ts`, and `vitest.config.ts` from a fresh `npx nerdsystem init` app. Then write one owner test for each route with an id in its path, set `\"tests\": \"required\"` in nerd.json, and run `nerd check`." },
50
+ "tests/required-missing": { title: "Access tests are missing", severity: "block", audience: "agent", risk: "This app is set to require access tests and has none, so nothing checks that a signed-out visitor is refused or that one user cannot reach another user's data.", fix: "Restore `test/access.test.ts` and the `test` script (`vitest run`) in package.json. Do not remove `\"tests\": \"required\"` from nerd.json to get past this." },
51
+ "tests/not-installed": { title: "Dependencies are not installed", severity: "block", audience: "agent", risk: "The tests cannot run, so nothing has been checked.", fix: "Run `pnpm install`, then `nerd check` again." },
52
+ "tests/failing": { title: "A test fails", severity: "block", audience: "agent", risk: "The app does not do what its tests say it should, or lets someone reach something they should not.", fix: "Run `pnpm test` and read which test failed and why. Fix the app's code. Change a test only when the behaviour it describes was meant to change, and never weaken an access test to make it pass." },
53
+ "tests/routes-not-checked": { title: "No test tried every route as a signed-out visitor", severity: "block", audience: "agent", risk: "A route added without a sign-in check would go live readable by anyone.", fix: "Keep the test in `test/access.test.ts` that calls `await t.expectEveryRouteLocked({ public: [...] })`. It covers every route automatically; list a route as public only when everyone on the internet is meant to reach it." },
54
+ "tests/owner-not-checked": { title: "A route with an id was not tried by a second user", severity: "block", audience: "agent", risk: "One signed-in user may be able to read, change, or delete another user's data by guessing its id.", fix: "Add an owner test for the route in `test/access.test.ts` using `t.expectHiddenFrom`.", example: { wrong: "// no test: nothing shows a second user is refused on /api/notes/:id", right: 'const note = await (await alice.post("/api/notes", { title: "mine" })).json();\nawait t.expectHiddenFrom(bob, "DELETE", `/api/notes/${note.note.id}`);' } },
55
+ "tests/harness-in-app": { title: "The test harness is imported by app code", severity: "block", audience: "agent", risk: "The test harness can sign in as anyone. In deployed code it would be a way around the login.", fix: "Remove the import of `@nerdsystem/sdk/testing` from files under `src/`. It belongs only in `test/`." },
39
56
  "typecheck/failed": { title: "Typecheck failed", severity: "block", audience: "agent", risk: "The project does not compile.", fix: "Run `npx tsc -b` and fix the errors it prints." },
40
57
  "policy/blocked-package": { title: "Package not allowed", severity: "block", audience: "agent", risk: "The package is a miner, proxy, or headless browser, which the acceptable use policy forbids and the platform cannot run.", fix: "Remove the package and the code that uses it. If the app genuinely needs a browser or scraping, say so to the person; it is not supported here." },
41
58
  "policy/mining-pool": { title: "Mining pool reference", severity: "block", audience: "human", risk: "The code references a cryptocurrency mining pool, which is forbidden by the acceptable use policy.", fix: "Remove it. If this is unexpected, inspect the file: it may have been added by a compromised dependency." },
@@ -0,0 +1,2 @@
1
+ import { type Gate } from "./types.js";
2
+ export declare const staticGate: Gate;
@@ -0,0 +1,58 @@
1
+ import { lineOf, sourceFiles } from "./fs.js";
2
+ import { finding } from "./secrets.js";
3
+ import { counts, result, verdict } from "./types.js";
4
+ const SERVER = /^src\/server\//;
5
+ /**
6
+ * The patterns semgrep's nerdsystem rules look for (packages/cli/rules/semgrep.yml), as plain text
7
+ * matching, so they run on every machine and every deploy without anything installed. Semgrep reads the
8
+ * code's structure and stays the more exact tool where it runs; these are deliberately narrow so they
9
+ * do not cry wolf. Three block, as the same semgrep rules do; the rest warn.
10
+ */
11
+ const CHECKS = [
12
+ // SQL assembled from values: a template with ${} or a string joined with +, handed to prepare/exec/sql.raw.
13
+ { rule: "code/raw-sql", re: /(\.prepare|\.exec|sql\.raw)\(\s*(`[^`]*\$\{|["'][^"'\n]*["']\s*\+)/g },
14
+ { rule: "code/eval", re: /(^|[^.\w])eval\s*\(|\bnew\s+Function\s*\(/g },
15
+ { rule: "code/password-in-app", re: /\.password\s*={2,3}|={2,3}\s*\w+\.password\b|\b(bcrypt|bcryptjs|argon2)\.(compare|hash|verify)\w*\s*\(|from\s+["'](bcrypt|bcryptjs|argon2)["']/g, files: SERVER },
16
+ { rule: "code/tokens-in-app", re: /\bjwt\.(sign|verify)\s*\(|from\s+["'](jsonwebtoken|jose|hono\/jwt)["']/g, files: SERVER },
17
+ { rule: "code/html-from-data", re: /dangerouslySetInnerHTML\s*=\s*\{\{\s*__html\s*:(?!\s*["'][^"'\n]*["']\s*\}\})|\.innerHTML\s*\+?=(?![=])(?!\s*["'][^"'\n]*["']\s*(;|\n|$))/g },
18
+ { rule: "code/open-redirect", re: /\.redirect\(\s*(c\.req\.(query|param|header)\(|\(?await\s+c\.req\.)/g, files: SERVER },
19
+ { rule: "code/fetch-user-url", re: /\bfetch\(\s*(c\.req\.(query|param|header)\(|\(?await\s+c\.req\.)/g, files: SERVER },
20
+ { rule: "code/weak-random", re: /\b\w*(token|secret|nonce|otp|passcode|apikey|api_key)\w*\s*[:=][^;\n]*Math\.random\(\)/gi },
21
+ // An unchecked body: c.req.json() used directly instead of readBody(c, schema).
22
+ { rule: "code/unvalidated-body", re: /\bc\.req\.(json|parseBody|formData)\(\)/g, files: SERVER },
23
+ ];
24
+ /** Blanks out comments, keeping every character position, so a pattern inside a comment is not a finding. */
25
+ function withoutComments(text) {
26
+ return text.replace(/\/\*[\s\S]*?\*\/|(^|[^:"'`\\])\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, " "));
27
+ }
28
+ export const staticGate = {
29
+ name: "static",
30
+ title: "Unsafe code patterns",
31
+ blocking: true,
32
+ rulePrefixes: ["code/"],
33
+ async run(ctx) {
34
+ const t = Date.now();
35
+ const findings = [];
36
+ for (const f of sourceFiles(ctx.root)) {
37
+ if (!/\.(ts|tsx|js|jsx|mjs)$/.test(f.rel) || !f.rel.startsWith("src/"))
38
+ continue;
39
+ const text = withoutComments(f.text);
40
+ for (const c of CHECKS) {
41
+ if (c.files && !c.files.test(f.rel))
42
+ continue;
43
+ c.re.lastIndex = 0;
44
+ let m;
45
+ let perFile = 0;
46
+ while ((m = c.re.exec(text)) && perFile < 10) {
47
+ findings.push(finding(c.rule, { file: f.rel, line: lineOf(text, m.index) }));
48
+ perFile++;
49
+ }
50
+ }
51
+ // Sign-in for every route is opt-in for apps created before it existed; say so until it is on.
52
+ if (f.rel === "src/server/index.ts" && /createNerdApp\s*(<[^>]*>)?\s*\(/.test(text) && !/createNerdApp\s*(<[^>]*>)?\s*\(\s*\{[\s\S]*?\bpublic\s*:/.test(text)) {
53
+ findings.push(finding("code/routes-open-by-default", { file: f.rel }));
54
+ }
55
+ }
56
+ return result(this, verdict(findings), findings.length ? counts(findings) : "Nothing unsafe found", findings, t);
57
+ },
58
+ };
@@ -0,0 +1,14 @@
1
+ import { type Gate } from "./types.js";
2
+ /**
3
+ * Route names come from the app's own code, and findings are read by a coding agent, so only the
4
+ * characters a "METHOD /path" needs survive and the length is capped: a route cannot carry a sentence.
5
+ */
6
+ export declare function safeRoute(name: unknown): string | null;
7
+ /**
8
+ * Runs the app's own tests and reads what they checked about access. The person who owns the app cannot
9
+ * read the code, and the agent that forgot a sign-in check tends to forget the test for it too, so the
10
+ * gate does not trust that tests exist: the harness calls every route the app declares, and this gate
11
+ * refuses the deploy unless that sweep ran, every route with an id in its path was tried by a second user,
12
+ * and everything passed.
13
+ */
14
+ export declare const testsGate: Gate;
@@ -0,0 +1,103 @@
1
+ import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { exec } from "./code.js";
4
+ import { sourceFiles } from "./fs.js";
5
+ import { finding } from "./secrets.js";
6
+ import { result } from "./types.js";
7
+ const HARNESS = "@nerdsystem/sdk/testing";
8
+ const REPORT = ".nerd/access-report.json";
9
+ /**
10
+ * Route names come from the app's own code, and findings are read by a coding agent, so only the
11
+ * characters a "METHOD /path" needs survive and the length is capped: a route cannot carry a sentence.
12
+ */
13
+ export function safeRoute(name) {
14
+ if (typeof name !== "string")
15
+ return null;
16
+ const m = /^(GET|POST|PUT|PATCH|DELETE) (\/[A-Za-z0-9/:_.*-]{0,120})$/.exec(name);
17
+ return m ? `${m[1]} ${m[2]}` : null;
18
+ }
19
+ const list = (v) => (Array.isArray(v) ? v.map(safeRoute).filter((r) => r !== null) : []);
20
+ const hasId = (route) => route.split(" ")[1].split("/").some((seg) => seg.startsWith(":"));
21
+ function readJson(file) {
22
+ try {
23
+ return JSON.parse(readFileSync(file, "utf8"));
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ /** True when a file under test/ uses the SDK's harness, which is what writes the access report. */
30
+ function hasHarnessTests(root) {
31
+ const dir = path.join(root, "test");
32
+ if (!existsSync(dir))
33
+ return false;
34
+ const walk = (d) => readdirSync(d, { withFileTypes: true }).some((e) => (e.isDirectory() ? walk(path.join(d, e.name)) : /\.(ts|tsx|mts|js|mjs)$/.test(e.name) && readFileSync(path.join(d, e.name), "utf8").includes(HARNESS)));
35
+ return walk(dir);
36
+ }
37
+ /**
38
+ * Runs the app's own tests and reads what they checked about access. The person who owns the app cannot
39
+ * read the code, and the agent that forgot a sign-in check tends to forget the test for it too, so the
40
+ * gate does not trust that tests exist: the harness calls every route the app declares, and this gate
41
+ * refuses the deploy unless that sweep ran, every route with an id in its path was tried by a second user,
42
+ * and everything passed.
43
+ */
44
+ export const testsGate = {
45
+ name: "tests",
46
+ title: "Tests and access checks",
47
+ blocking: true,
48
+ rulePrefixes: ["tests/"],
49
+ async run(ctx) {
50
+ const t = Date.now();
51
+ const findings = [];
52
+ // The harness can sign in anyone. It must never be reachable from the code that is deployed.
53
+ for (const f of sourceFiles(ctx.root)) {
54
+ if (f.rel.startsWith("src/") && f.text.includes(HARNESS))
55
+ findings.push(finding("tests/harness-in-app", { file: f.rel }));
56
+ }
57
+ if (findings.length)
58
+ return result(this, "fail", "The test harness is imported by app code", findings, t);
59
+ const pkg = readJson(path.join(ctx.root, "package.json"));
60
+ const required = readJson(path.join(ctx.root, "nerd.json"))?.tests === "required";
61
+ if (!pkg?.scripts?.test || !hasHarnessTests(ctx.root)) {
62
+ const f = finding(required ? "tests/required-missing" : "tests/missing", { file: "test/access.test.ts" });
63
+ return result(this, required ? "fail" : "warn", "No access tests in this app", [f], t);
64
+ }
65
+ // Git builds do not run this yet (the build container has not been proven to run the local database);
66
+ // the terminal path, which every `nerd deploy` takes, does.
67
+ if (ctx.committed)
68
+ return result(this, "skip", "Runs before `nerd deploy`; not yet part of git builds", [], t);
69
+ if (!existsSync(path.join(ctx.root, "node_modules"))) {
70
+ return result(this, "fail", "Dependencies are not installed", [finding("tests/not-installed", {})], t);
71
+ }
72
+ rmSync(path.join(ctx.root, REPORT), { force: true });
73
+ const run = await exec("npx", ["vitest", "run"], ctx.root);
74
+ if (run.code !== 0) {
75
+ const files = new Set();
76
+ for (const line of `${run.stdout}\n${run.stderr}`.split("\n")) {
77
+ const m = /FAIL\s+(test\/[A-Za-z0-9_./-]{1,120}\.test\.[a-z]{2,3})/.exec(line);
78
+ if (m)
79
+ files.add(m[1]);
80
+ }
81
+ for (const file of [...files].slice(0, 10))
82
+ findings.push(finding("tests/failing", { file }));
83
+ if (!findings.length)
84
+ findings.push(finding("tests/failing", {}));
85
+ return result(this, "fail", `${findings.length} test file(s) failing`, findings, t, "vitest");
86
+ }
87
+ const report = readJson(path.join(ctx.root, REPORT));
88
+ const routes = list(report?.routes);
89
+ const open = list(report?.public);
90
+ if (!report || report.everyRouteChecked !== true) {
91
+ return result(this, "fail", "No test checked every route as a signed-out visitor", [finding("tests/routes-not-checked", { file: "test/access.test.ts" })], t, "vitest");
92
+ }
93
+ const covered = new Set([...list(report.ownerChecked), ...list(report.shared), ...open]);
94
+ for (const route of routes.filter(hasId)) {
95
+ if (!covered.has(route))
96
+ findings.push(finding("tests/owner-not-checked", { file: "test/access.test.ts", fix: `Add a test for ${route}: one user creates the thing, then \`await t.expectHiddenFrom(otherUser, "${route.split(" ")[0]}", <the path with the real id>)\`. If every signed-in user is meant to reach it, declare \`t.shared("${route}", "<why>")\` instead.`, fingerprint: `tests/owner-not-checked:${route}` }));
97
+ }
98
+ if (findings.length)
99
+ return result(this, "fail", `${findings.length} route(s) with an id were not tried by a second user`, findings, t, "vitest");
100
+ const locked = routes.length - open.length;
101
+ return result(this, "pass", `Tests passed; ${locked} route(s) refuse a signed-out visitor, ${open.length} public${open.length ? ` (${open.join(", ")})` : ""}`, [], t, "vitest");
102
+ },
103
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nerdsystem",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
4
4
  "description": "nerd: start, check, and deploy a web app on nerdsystem from the terminal or a coding agent.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,8 +33,8 @@ Tell the person plainly what does not carry. Their users sign up again on the ne
33
33
 
34
34
  ## The loop
35
35
 
36
- 1. Make the change.
37
- 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
36
+ 1. Make the change, and write or update its tests in the same step (see "Build it so it is safe and it works").
37
+ 2. `nerd check` (static rules, typecheck, then the tests and access checks). Fix anything it reports.
38
38
  3. `nerd dev` to run locally when you need to try it. The local app talks to the real auth service, so signup and login work exactly as in production.
39
39
  4. `nerd deploy` when it is ready. It runs the checks, builds, stores a copy of the code, applies pending migrations, uploads, prints the URL, and probes the live URL (headers and the sign-in routes). With `--json` the output carries `probes`, the same shape as a check result, with `status: "skip"` and the reason when it did not run; probe findings never fail the deploy.
40
40
  5. If something is wrong after deploying: `nerd logs` shows recent output from the deployed app (`--q` to search, `--pr 12` for a preview), `nerd deployments` shows status and errors, `nerd db query "..."` inspects production data.
@@ -95,6 +95,37 @@ export default notes;
95
95
 
96
96
  Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
97
97
 
98
+ ## Build it so it is safe and it works
99
+
100
+ The person you are building for usually cannot read code. They will not spot a missing sign-in check or a query that returns someone else's rows, and neither will anyone looking at the screen. So the standard is yours to hold, every time, without being asked:
101
+
102
+ 1. **Every route is locked unless you open it.** `createNerdApp({ public: [...] })` in `src/server/index.ts` makes every route require a signed-in user except the ones named in that list, so a route you forget to protect answers 401 instead of answering everyone. Still put `requireAuth()` on each router (`router.use("*", requireAuth())`) and `requireRole(...)` where a role is needed: it says what the route expects and gives TypeScript a user. A route is public only when everyone on the internet is meant to reach it and it returns nothing private; then add it to the `public` list in `src/server/index.ts` and to the same list in `test/access.test.ts`, and tell the person in plain words that it is open. Never remove the `public` option or widen it to get something working.
103
+ 2. **Scope every query to the signed-in user.** Reads, updates, and deletes on user data filter on `c.var.user.id`. On a route with an id in its path, put the id and the user id in the same `where`, and answer 404 when nothing matches, so someone else's row looks like it does not exist.
104
+ 3. **Take identity from the session, never from the request.** The user id, the role, a price, an owner: none of these come from the body, the query string, or a header the browser sends. Read the user from `c.var.user` and look the rest up on the server.
105
+ 4. **Check every input on the server.** Read a body with `readBody(c, schema)` and a query string with `readQuery(c, schema)` from `@nerdsystem/sdk`, with a zod schema that gives every field a type, a length, a range, or a list of allowed values (see `src/server/routes/todos.ts`). They answer 400 in the usual error shape for anything else, before your code runs. Do not call `c.req.json()` directly; `nerd check` flags it. Path parameters get the same care: turn an id into a number and let a missing row be a 404. The client's own checks are for the person's convenience; they protect nothing.
106
+ 5. **Hiding a button is not access control.** If only admins may do something, the route says `requireRole("admin")`. What the page shows is decoration.
107
+ 6. **Files:** check the type and the size before writing to `c.env.STORAGE`, store under a key that starts with the owner's user id, and serve them through a route that checks the owner. Never build a key from a name the browser sent without cleaning it.
108
+ 7. **Say nothing useful in an error.** No stack traces, SQL, or internal ids in responses; log them with `console.error` and answer with `{ error: { code, message } }`.
109
+ 8. **No raw HTML from data.** Let React render text. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything a user typed.
110
+
111
+ ### Tests are part of the feature
112
+
113
+ The project ships with a test harness (`test/setup.ts`, from `@nerdsystem/sdk/testing`) that runs the real server code against a fresh local database and signs in made-up users. `pnpm test` runs it; `nerd check` and `nerd deploy` run it too and refuse the deploy when:
114
+
115
+ - a test fails (`tests/failing`);
116
+ - the test that calls `t.expectEveryRouteLocked({ public: [...] })` is gone (`tests/routes-not-checked`). That one call tries every route the app has as a signed-out visitor, so a new route is covered the moment it exists and fails until it is locked or deliberately listed as public;
117
+ - a route with an id in its path has not been tried by a second user (`tests/owner-not-checked`).
118
+
119
+ For every feature you build:
120
+
121
+ - **One owner test per route with an id**, in `test/access.test.ts`: one user creates the thing, then `await t.expectHiddenFrom(otherUser, "PATCH", `/api/things/${id}`, body)` for each method. For lists, `await t.expectNotListed(otherUser, "/api/things", "a title only the owner has")`. If every signed-in user is truly meant to reach it (a shared catalogue, a public profile), declare `t.shared("GET /api/things/:id", "why")` instead and tell the person.
122
+ - **One test file per feature** (`test/<feature>.test.ts`, like `test/todos.test.ts`): the main path a person takes from start to finish, and the inputs it must refuse.
123
+ - **A role test** for anything behind `requireRole`: a signed-in user without the role gets 403, one with it gets through (`await t.as("dana", { roles: ["admin"] })`).
124
+
125
+ When a test fails, fix the app. Change a test only when the behaviour it describes was meant to change. Never delete or weaken an access test, widen the `public` list, add `t.shared`, or remove `"tests": "required"` from `nerd.json` to get a deploy through; if you believe one of those is right, stop and ask the person in plain words first. Never import `@nerdsystem/sdk/testing` from anything under `src/`: it can sign in as anyone, and `nerd check` refuses it.
126
+
127
+ What the tests do not prove: that the feature is the one the person wanted, or that its rules (who may book which slot, what a discount applies to) are right. Say what you built and what is public when you hand it over, so they can tell you if it is wrong.
128
+
98
129
  ## Data rules
99
130
 
100
131
  - Every table holding user data has a `user_id` text column, and every read and write filters on `c.var.user.id`. This is how users are kept apart.
@@ -130,6 +161,8 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
130
161
  - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
131
162
  - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
132
163
  - Typecheck failures in either `src/server` or `src/client`.
164
+ - SQL built from values, `eval` or `new Function`, and password handling in server code (the `code/` rules; they block). It also flags, without blocking: tokens signed in app code, HTML built from data, redirects and fetches to an address from the request, `Math.random` for a secret, a body read without `readBody`, and an app that has not turned on `public` in `createNerdApp`.
165
+ - A failing test, a missing access sweep, or a route with an id that no second user was tried against (the `tests/` rules above).
133
166
 
134
167
  ## Scheduled jobs and email
135
168
 
@@ -2,7 +2,7 @@
2
2
  description: How to build, run, and deploy this app on nerdsystem. Applies to server, database, auth, and deploy work.
3
3
  alwaysApply: true
4
4
  ---
5
- <!-- generated from .claude/skills/nerdsystem/SKILL.md (497090779572); edit the skill, then run: nerd agents sync -->
5
+ <!-- generated from .claude/skills/nerdsystem/SKILL.md (f851c99006a8); edit the skill, then run: nerd agents sync -->
6
6
 
7
7
  # Building on nerdsystem
8
8
 
@@ -34,8 +34,8 @@ Tell the person plainly what does not carry. Their users sign up again on the ne
34
34
 
35
35
  ## The loop
36
36
 
37
- 1. Make the change.
38
- 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
37
+ 1. Make the change, and write or update its tests in the same step (see "Build it so it is safe and it works").
38
+ 2. `nerd check` (static rules, typecheck, then the tests and access checks). Fix anything it reports.
39
39
  3. `nerd dev` to run locally when you need to try it. The local app talks to the real auth service, so signup and login work exactly as in production.
40
40
  4. `nerd deploy` when it is ready. It runs the checks, builds, stores a copy of the code, applies pending migrations, uploads, prints the URL, and probes the live URL (headers and the sign-in routes). With `--json` the output carries `probes`, the same shape as a check result, with `status: "skip"` and the reason when it did not run; probe findings never fail the deploy.
41
41
  5. If something is wrong after deploying: `nerd logs` shows recent output from the deployed app (`--q` to search, `--pr 12` for a preview), `nerd deployments` shows status and errors, `nerd db query "..."` inspects production data.
@@ -96,6 +96,37 @@ export default notes;
96
96
 
97
97
  Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
98
98
 
99
+ ## Build it so it is safe and it works
100
+
101
+ The person you are building for usually cannot read code. They will not spot a missing sign-in check or a query that returns someone else's rows, and neither will anyone looking at the screen. So the standard is yours to hold, every time, without being asked:
102
+
103
+ 1. **Every route is locked unless you open it.** `createNerdApp({ public: [...] })` in `src/server/index.ts` makes every route require a signed-in user except the ones named in that list, so a route you forget to protect answers 401 instead of answering everyone. Still put `requireAuth()` on each router (`router.use("*", requireAuth())`) and `requireRole(...)` where a role is needed: it says what the route expects and gives TypeScript a user. A route is public only when everyone on the internet is meant to reach it and it returns nothing private; then add it to the `public` list in `src/server/index.ts` and to the same list in `test/access.test.ts`, and tell the person in plain words that it is open. Never remove the `public` option or widen it to get something working.
104
+ 2. **Scope every query to the signed-in user.** Reads, updates, and deletes on user data filter on `c.var.user.id`. On a route with an id in its path, put the id and the user id in the same `where`, and answer 404 when nothing matches, so someone else's row looks like it does not exist.
105
+ 3. **Take identity from the session, never from the request.** The user id, the role, a price, an owner: none of these come from the body, the query string, or a header the browser sends. Read the user from `c.var.user` and look the rest up on the server.
106
+ 4. **Check every input on the server.** Read a body with `readBody(c, schema)` and a query string with `readQuery(c, schema)` from `@nerdsystem/sdk`, with a zod schema that gives every field a type, a length, a range, or a list of allowed values (see `src/server/routes/todos.ts`). They answer 400 in the usual error shape for anything else, before your code runs. Do not call `c.req.json()` directly; `nerd check` flags it. Path parameters get the same care: turn an id into a number and let a missing row be a 404. The client's own checks are for the person's convenience; they protect nothing.
107
+ 5. **Hiding a button is not access control.** If only admins may do something, the route says `requireRole("admin")`. What the page shows is decoration.
108
+ 6. **Files:** check the type and the size before writing to `c.env.STORAGE`, store under a key that starts with the owner's user id, and serve them through a route that checks the owner. Never build a key from a name the browser sent without cleaning it.
109
+ 7. **Say nothing useful in an error.** No stack traces, SQL, or internal ids in responses; log them with `console.error` and answer with `{ error: { code, message } }`.
110
+ 8. **No raw HTML from data.** Let React render text. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything a user typed.
111
+
112
+ ### Tests are part of the feature
113
+
114
+ The project ships with a test harness (`test/setup.ts`, from `@nerdsystem/sdk/testing`) that runs the real server code against a fresh local database and signs in made-up users. `pnpm test` runs it; `nerd check` and `nerd deploy` run it too and refuse the deploy when:
115
+
116
+ - a test fails (`tests/failing`);
117
+ - the test that calls `t.expectEveryRouteLocked({ public: [...] })` is gone (`tests/routes-not-checked`). That one call tries every route the app has as a signed-out visitor, so a new route is covered the moment it exists and fails until it is locked or deliberately listed as public;
118
+ - a route with an id in its path has not been tried by a second user (`tests/owner-not-checked`).
119
+
120
+ For every feature you build:
121
+
122
+ - **One owner test per route with an id**, in `test/access.test.ts`: one user creates the thing, then `await t.expectHiddenFrom(otherUser, "PATCH", `/api/things/${id}`, body)` for each method. For lists, `await t.expectNotListed(otherUser, "/api/things", "a title only the owner has")`. If every signed-in user is truly meant to reach it (a shared catalogue, a public profile), declare `t.shared("GET /api/things/:id", "why")` instead and tell the person.
123
+ - **One test file per feature** (`test/<feature>.test.ts`, like `test/todos.test.ts`): the main path a person takes from start to finish, and the inputs it must refuse.
124
+ - **A role test** for anything behind `requireRole`: a signed-in user without the role gets 403, one with it gets through (`await t.as("dana", { roles: ["admin"] })`).
125
+
126
+ When a test fails, fix the app. Change a test only when the behaviour it describes was meant to change. Never delete or weaken an access test, widen the `public` list, add `t.shared`, or remove `"tests": "required"` from `nerd.json` to get a deploy through; if you believe one of those is right, stop and ask the person in plain words first. Never import `@nerdsystem/sdk/testing` from anything under `src/`: it can sign in as anyone, and `nerd check` refuses it.
127
+
128
+ What the tests do not prove: that the feature is the one the person wanted, or that its rules (who may book which slot, what a discount applies to) are right. Say what you built and what is public when you hand it over, so they can tell you if it is wrong.
129
+
99
130
  ## Data rules
100
131
 
101
132
  - Every table holding user data has a `user_id` text column, and every read and write filters on `c.var.user.id`. This is how users are kept apart.
@@ -131,6 +162,8 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
131
162
  - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
132
163
  - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
133
164
  - Typecheck failures in either `src/server` or `src/client`.
165
+ - SQL built from values, `eval` or `new Function`, and password handling in server code (the `code/` rules; they block). It also flags, without blocking: tokens signed in app code, HTML built from data, redirects and fetches to an address from the request, `Math.random` for a secret, a body read without `readBody`, and an app that has not turned on `public` in `createNerdApp`.
166
+ - A failing test, a missing access sweep, or a route with an id that no second user was tried against (the `tests/` rules above).
134
167
 
135
168
  ## Scheduled jobs and email
136
169
 
@@ -1,4 +1,4 @@
1
- <!-- generated from .claude/skills/nerdsystem/SKILL.md (497090779572); edit the skill, then run: nerd agents sync -->
1
+ <!-- generated from .claude/skills/nerdsystem/SKILL.md (f851c99006a8); edit the skill, then run: nerd agents sync -->
2
2
 
3
3
  # Building on nerdsystem
4
4
 
@@ -30,8 +30,8 @@ Tell the person plainly what does not carry. Their users sign up again on the ne
30
30
 
31
31
  ## The loop
32
32
 
33
- 1. Make the change.
34
- 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
33
+ 1. Make the change, and write or update its tests in the same step (see "Build it so it is safe and it works").
34
+ 2. `nerd check` (static rules, typecheck, then the tests and access checks). Fix anything it reports.
35
35
  3. `nerd dev` to run locally when you need to try it. The local app talks to the real auth service, so signup and login work exactly as in production.
36
36
  4. `nerd deploy` when it is ready. It runs the checks, builds, stores a copy of the code, applies pending migrations, uploads, prints the URL, and probes the live URL (headers and the sign-in routes). With `--json` the output carries `probes`, the same shape as a check result, with `status: "skip"` and the reason when it did not run; probe findings never fail the deploy.
37
37
  5. If something is wrong after deploying: `nerd logs` shows recent output from the deployed app (`--q` to search, `--pr 12` for a preview), `nerd deployments` shows status and errors, `nerd db query "..."` inspects production data.
@@ -92,6 +92,37 @@ export default notes;
92
92
 
93
93
  Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
94
94
 
95
+ ## Build it so it is safe and it works
96
+
97
+ The person you are building for usually cannot read code. They will not spot a missing sign-in check or a query that returns someone else's rows, and neither will anyone looking at the screen. So the standard is yours to hold, every time, without being asked:
98
+
99
+ 1. **Every route is locked unless you open it.** `createNerdApp({ public: [...] })` in `src/server/index.ts` makes every route require a signed-in user except the ones named in that list, so a route you forget to protect answers 401 instead of answering everyone. Still put `requireAuth()` on each router (`router.use("*", requireAuth())`) and `requireRole(...)` where a role is needed: it says what the route expects and gives TypeScript a user. A route is public only when everyone on the internet is meant to reach it and it returns nothing private; then add it to the `public` list in `src/server/index.ts` and to the same list in `test/access.test.ts`, and tell the person in plain words that it is open. Never remove the `public` option or widen it to get something working.
100
+ 2. **Scope every query to the signed-in user.** Reads, updates, and deletes on user data filter on `c.var.user.id`. On a route with an id in its path, put the id and the user id in the same `where`, and answer 404 when nothing matches, so someone else's row looks like it does not exist.
101
+ 3. **Take identity from the session, never from the request.** The user id, the role, a price, an owner: none of these come from the body, the query string, or a header the browser sends. Read the user from `c.var.user` and look the rest up on the server.
102
+ 4. **Check every input on the server.** Read a body with `readBody(c, schema)` and a query string with `readQuery(c, schema)` from `@nerdsystem/sdk`, with a zod schema that gives every field a type, a length, a range, or a list of allowed values (see `src/server/routes/todos.ts`). They answer 400 in the usual error shape for anything else, before your code runs. Do not call `c.req.json()` directly; `nerd check` flags it. Path parameters get the same care: turn an id into a number and let a missing row be a 404. The client's own checks are for the person's convenience; they protect nothing.
103
+ 5. **Hiding a button is not access control.** If only admins may do something, the route says `requireRole("admin")`. What the page shows is decoration.
104
+ 6. **Files:** check the type and the size before writing to `c.env.STORAGE`, store under a key that starts with the owner's user id, and serve them through a route that checks the owner. Never build a key from a name the browser sent without cleaning it.
105
+ 7. **Say nothing useful in an error.** No stack traces, SQL, or internal ids in responses; log them with `console.error` and answer with `{ error: { code, message } }`.
106
+ 8. **No raw HTML from data.** Let React render text. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything a user typed.
107
+
108
+ ### Tests are part of the feature
109
+
110
+ The project ships with a test harness (`test/setup.ts`, from `@nerdsystem/sdk/testing`) that runs the real server code against a fresh local database and signs in made-up users. `pnpm test` runs it; `nerd check` and `nerd deploy` run it too and refuse the deploy when:
111
+
112
+ - a test fails (`tests/failing`);
113
+ - the test that calls `t.expectEveryRouteLocked({ public: [...] })` is gone (`tests/routes-not-checked`). That one call tries every route the app has as a signed-out visitor, so a new route is covered the moment it exists and fails until it is locked or deliberately listed as public;
114
+ - a route with an id in its path has not been tried by a second user (`tests/owner-not-checked`).
115
+
116
+ For every feature you build:
117
+
118
+ - **One owner test per route with an id**, in `test/access.test.ts`: one user creates the thing, then `await t.expectHiddenFrom(otherUser, "PATCH", `/api/things/${id}`, body)` for each method. For lists, `await t.expectNotListed(otherUser, "/api/things", "a title only the owner has")`. If every signed-in user is truly meant to reach it (a shared catalogue, a public profile), declare `t.shared("GET /api/things/:id", "why")` instead and tell the person.
119
+ - **One test file per feature** (`test/<feature>.test.ts`, like `test/todos.test.ts`): the main path a person takes from start to finish, and the inputs it must refuse.
120
+ - **A role test** for anything behind `requireRole`: a signed-in user without the role gets 403, one with it gets through (`await t.as("dana", { roles: ["admin"] })`).
121
+
122
+ When a test fails, fix the app. Change a test only when the behaviour it describes was meant to change. Never delete or weaken an access test, widen the `public` list, add `t.shared`, or remove `"tests": "required"` from `nerd.json` to get a deploy through; if you believe one of those is right, stop and ask the person in plain words first. Never import `@nerdsystem/sdk/testing` from anything under `src/`: it can sign in as anyone, and `nerd check` refuses it.
123
+
124
+ What the tests do not prove: that the feature is the one the person wanted, or that its rules (who may book which slot, what a discount applies to) are right. Say what you built and what is public when you hand it over, so they can tell you if it is wrong.
125
+
95
126
  ## Data rules
96
127
 
97
128
  - Every table holding user data has a `user_id` text column, and every read and write filters on `c.var.user.id`. This is how users are kept apart.
@@ -127,6 +158,8 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
127
158
  - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
128
159
  - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
129
160
  - Typecheck failures in either `src/server` or `src/client`.
161
+ - SQL built from values, `eval` or `new Function`, and password handling in server code (the `code/` rules; they block). It also flags, without blocking: tokens signed in app code, HTML built from data, redirects and fetches to an address from the request, `Math.random` for a secret, a body read without `readBody`, and an app that has not turned on `public` in `createNerdApp`.
162
+ - A failing test, a missing access sweep, or a route with an id that no second user was tried against (the `tests/` rules above).
130
163
 
131
164
  ## Scheduled jobs and email
132
165
 
@@ -0,0 +1,29 @@
1
+ {
2
+ "version": 1,
3
+ "routes": [
4
+ "DELETE /api/todos/:id",
5
+ "GET /api/admin/ping",
6
+ "GET /api/health",
7
+ "GET /api/todos",
8
+ "PATCH /api/todos/:id",
9
+ "POST /api/cron",
10
+ "POST /api/todos"
11
+ ],
12
+ "locked": [
13
+ "DELETE /api/todos/:id",
14
+ "GET /api/admin/ping",
15
+ "GET /api/todos",
16
+ "PATCH /api/todos/:id",
17
+ "POST /api/cron",
18
+ "POST /api/todos"
19
+ ],
20
+ "public": [
21
+ "GET /api/health"
22
+ ],
23
+ "ownerChecked": [
24
+ "DELETE /api/todos/:id",
25
+ "PATCH /api/todos/:id"
26
+ ],
27
+ "shared": [],
28
+ "everyRouteChecked": true
29
+ }
@@ -1,4 +1,4 @@
1
- <!-- generated from .claude/skills/nerdsystem/SKILL.md (497090779572); edit the skill, then run: nerd agents sync -->
1
+ <!-- generated from .claude/skills/nerdsystem/SKILL.md (f851c99006a8); edit the skill, then run: nerd agents sync -->
2
2
 
3
3
  # Building on nerdsystem
4
4
 
@@ -30,8 +30,8 @@ Tell the person plainly what does not carry. Their users sign up again on the ne
30
30
 
31
31
  ## The loop
32
32
 
33
- 1. Make the change.
34
- 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
33
+ 1. Make the change, and write or update its tests in the same step (see "Build it so it is safe and it works").
34
+ 2. `nerd check` (static rules, typecheck, then the tests and access checks). Fix anything it reports.
35
35
  3. `nerd dev` to run locally when you need to try it. The local app talks to the real auth service, so signup and login work exactly as in production.
36
36
  4. `nerd deploy` when it is ready. It runs the checks, builds, stores a copy of the code, applies pending migrations, uploads, prints the URL, and probes the live URL (headers and the sign-in routes). With `--json` the output carries `probes`, the same shape as a check result, with `status: "skip"` and the reason when it did not run; probe findings never fail the deploy.
37
37
  5. If something is wrong after deploying: `nerd logs` shows recent output from the deployed app (`--q` to search, `--pr 12` for a preview), `nerd deployments` shows status and errors, `nerd db query "..."` inspects production data.
@@ -92,6 +92,37 @@ export default notes;
92
92
 
93
93
  Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
94
94
 
95
+ ## Build it so it is safe and it works
96
+
97
+ The person you are building for usually cannot read code. They will not spot a missing sign-in check or a query that returns someone else's rows, and neither will anyone looking at the screen. So the standard is yours to hold, every time, without being asked:
98
+
99
+ 1. **Every route is locked unless you open it.** `createNerdApp({ public: [...] })` in `src/server/index.ts` makes every route require a signed-in user except the ones named in that list, so a route you forget to protect answers 401 instead of answering everyone. Still put `requireAuth()` on each router (`router.use("*", requireAuth())`) and `requireRole(...)` where a role is needed: it says what the route expects and gives TypeScript a user. A route is public only when everyone on the internet is meant to reach it and it returns nothing private; then add it to the `public` list in `src/server/index.ts` and to the same list in `test/access.test.ts`, and tell the person in plain words that it is open. Never remove the `public` option or widen it to get something working.
100
+ 2. **Scope every query to the signed-in user.** Reads, updates, and deletes on user data filter on `c.var.user.id`. On a route with an id in its path, put the id and the user id in the same `where`, and answer 404 when nothing matches, so someone else's row looks like it does not exist.
101
+ 3. **Take identity from the session, never from the request.** The user id, the role, a price, an owner: none of these come from the body, the query string, or a header the browser sends. Read the user from `c.var.user` and look the rest up on the server.
102
+ 4. **Check every input on the server.** Read a body with `readBody(c, schema)` and a query string with `readQuery(c, schema)` from `@nerdsystem/sdk`, with a zod schema that gives every field a type, a length, a range, or a list of allowed values (see `src/server/routes/todos.ts`). They answer 400 in the usual error shape for anything else, before your code runs. Do not call `c.req.json()` directly; `nerd check` flags it. Path parameters get the same care: turn an id into a number and let a missing row be a 404. The client's own checks are for the person's convenience; they protect nothing.
103
+ 5. **Hiding a button is not access control.** If only admins may do something, the route says `requireRole("admin")`. What the page shows is decoration.
104
+ 6. **Files:** check the type and the size before writing to `c.env.STORAGE`, store under a key that starts with the owner's user id, and serve them through a route that checks the owner. Never build a key from a name the browser sent without cleaning it.
105
+ 7. **Say nothing useful in an error.** No stack traces, SQL, or internal ids in responses; log them with `console.error` and answer with `{ error: { code, message } }`.
106
+ 8. **No raw HTML from data.** Let React render text. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything a user typed.
107
+
108
+ ### Tests are part of the feature
109
+
110
+ The project ships with a test harness (`test/setup.ts`, from `@nerdsystem/sdk/testing`) that runs the real server code against a fresh local database and signs in made-up users. `pnpm test` runs it; `nerd check` and `nerd deploy` run it too and refuse the deploy when:
111
+
112
+ - a test fails (`tests/failing`);
113
+ - the test that calls `t.expectEveryRouteLocked({ public: [...] })` is gone (`tests/routes-not-checked`). That one call tries every route the app has as a signed-out visitor, so a new route is covered the moment it exists and fails until it is locked or deliberately listed as public;
114
+ - a route with an id in its path has not been tried by a second user (`tests/owner-not-checked`).
115
+
116
+ For every feature you build:
117
+
118
+ - **One owner test per route with an id**, in `test/access.test.ts`: one user creates the thing, then `await t.expectHiddenFrom(otherUser, "PATCH", `/api/things/${id}`, body)` for each method. For lists, `await t.expectNotListed(otherUser, "/api/things", "a title only the owner has")`. If every signed-in user is truly meant to reach it (a shared catalogue, a public profile), declare `t.shared("GET /api/things/:id", "why")` instead and tell the person.
119
+ - **One test file per feature** (`test/<feature>.test.ts`, like `test/todos.test.ts`): the main path a person takes from start to finish, and the inputs it must refuse.
120
+ - **A role test** for anything behind `requireRole`: a signed-in user without the role gets 403, one with it gets through (`await t.as("dana", { roles: ["admin"] })`).
121
+
122
+ When a test fails, fix the app. Change a test only when the behaviour it describes was meant to change. Never delete or weaken an access test, widen the `public` list, add `t.shared`, or remove `"tests": "required"` from `nerd.json` to get a deploy through; if you believe one of those is right, stop and ask the person in plain words first. Never import `@nerdsystem/sdk/testing` from anything under `src/`: it can sign in as anyone, and `nerd check` refuses it.
123
+
124
+ What the tests do not prove: that the feature is the one the person wanted, or that its rules (who may book which slot, what a discount applies to) are right. Say what you built and what is public when you hand it over, so they can tell you if it is wrong.
125
+
95
126
  ## Data rules
96
127
 
97
128
  - Every table holding user data has a `user_id` text column, and every read and write filters on `c.var.user.id`. This is how users are kept apart.
@@ -127,6 +158,8 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
127
158
  - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
128
159
  - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
129
160
  - Typecheck failures in either `src/server` or `src/client`.
161
+ - SQL built from values, `eval` or `new Function`, and password handling in server code (the `code/` rules; they block). It also flags, without blocking: tokens signed in app code, HTML built from data, redirects and fetches to an address from the request, `Math.random` for a secret, a body read without `readBody`, and an app that has not turned on `public` in `createNerdApp`.
162
+ - A failing test, a missing access sweep, or a route with an id that no second user was tried against (the `tests/` rules above).
130
163
 
131
164
  ## Scheduled jobs and email
132
165
 
@@ -5,7 +5,8 @@ nerdsystem deploys this app to Cloudflare and provides authentication and author
5
5
  ## Commands
6
6
 
7
7
  - `nerd dev` starts the app locally with a real session flow against the platform auth service.
8
- - `nerd check` typechecks both sides and verifies the platform rules below. Run it before `nerd deploy`.
8
+ - `nerd check` typechecks both sides, verifies the platform rules below, and runs the tests in `test/`. Run it before `nerd deploy`.
9
+ - `pnpm test` runs the tests alone: the real server code against a fresh local database, with made-up signed-in users.
9
10
  - `nerd deploy` builds, stores a copy of the code, applies pending migrations to the production database, and ships the app. Prints the URL.
10
11
  - `nerd save` keeps a copy of the code on nerdsystem without deploying; `nerd pull <org>/<project>` restores it on another computer.
11
12
  - `nerd db query "select ..."` runs SQL against the production database. `nerd deployments` lists recent deploys.
@@ -27,6 +28,8 @@ nerdsystem deploys this app to Cloudflare and provides authentication and author
27
28
  5. Keep every API route under `/api/`. Other paths are served from static assets and never reach the Worker.
28
29
  6. Do not add Cloudflare bindings to `wrangler.jsonc`, and do not run `wrangler deploy`. Bindings are provisioned by the platform.
29
30
  7. Secrets and environment variables for the deployed app are managed with `nerd` commands, never committed.
31
+ 8. Every route requires a signed-in user unless it is named in `createNerdApp({ public: [...] })` and in the same list in `test/access.test.ts`, and every route with an id in its path has a test showing a second user cannot reach it. Write the tests with the feature. `nerd check` refuses a deploy when they fail or are missing; never weaken one to get through.
32
+ 9. Read request bodies with `readBody(c, schema)` and a zod schema, never `c.req.json()` directly.
30
33
 
31
34
  ## Roles
32
35
 
@@ -1,4 +1,4 @@
1
- <!-- generated from .claude/skills/nerdsystem/SKILL.md (497090779572); edit the skill, then run: nerd agents sync -->
1
+ <!-- generated from .claude/skills/nerdsystem/SKILL.md (f851c99006a8); edit the skill, then run: nerd agents sync -->
2
2
 
3
3
  # Building on nerdsystem
4
4
 
@@ -30,8 +30,8 @@ Tell the person plainly what does not carry. Their users sign up again on the ne
30
30
 
31
31
  ## The loop
32
32
 
33
- 1. Make the change.
34
- 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
33
+ 1. Make the change, and write or update its tests in the same step (see "Build it so it is safe and it works").
34
+ 2. `nerd check` (static rules, typecheck, then the tests and access checks). Fix anything it reports.
35
35
  3. `nerd dev` to run locally when you need to try it. The local app talks to the real auth service, so signup and login work exactly as in production.
36
36
  4. `nerd deploy` when it is ready. It runs the checks, builds, stores a copy of the code, applies pending migrations, uploads, prints the URL, and probes the live URL (headers and the sign-in routes). With `--json` the output carries `probes`, the same shape as a check result, with `status: "skip"` and the reason when it did not run; probe findings never fail the deploy.
37
37
  5. If something is wrong after deploying: `nerd logs` shows recent output from the deployed app (`--q` to search, `--pr 12` for a preview), `nerd deployments` shows status and errors, `nerd db query "..."` inspects production data.
@@ -92,6 +92,37 @@ export default notes;
92
92
 
93
93
  Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
94
94
 
95
+ ## Build it so it is safe and it works
96
+
97
+ The person you are building for usually cannot read code. They will not spot a missing sign-in check or a query that returns someone else's rows, and neither will anyone looking at the screen. So the standard is yours to hold, every time, without being asked:
98
+
99
+ 1. **Every route is locked unless you open it.** `createNerdApp({ public: [...] })` in `src/server/index.ts` makes every route require a signed-in user except the ones named in that list, so a route you forget to protect answers 401 instead of answering everyone. Still put `requireAuth()` on each router (`router.use("*", requireAuth())`) and `requireRole(...)` where a role is needed: it says what the route expects and gives TypeScript a user. A route is public only when everyone on the internet is meant to reach it and it returns nothing private; then add it to the `public` list in `src/server/index.ts` and to the same list in `test/access.test.ts`, and tell the person in plain words that it is open. Never remove the `public` option or widen it to get something working.
100
+ 2. **Scope every query to the signed-in user.** Reads, updates, and deletes on user data filter on `c.var.user.id`. On a route with an id in its path, put the id and the user id in the same `where`, and answer 404 when nothing matches, so someone else's row looks like it does not exist.
101
+ 3. **Take identity from the session, never from the request.** The user id, the role, a price, an owner: none of these come from the body, the query string, or a header the browser sends. Read the user from `c.var.user` and look the rest up on the server.
102
+ 4. **Check every input on the server.** Read a body with `readBody(c, schema)` and a query string with `readQuery(c, schema)` from `@nerdsystem/sdk`, with a zod schema that gives every field a type, a length, a range, or a list of allowed values (see `src/server/routes/todos.ts`). They answer 400 in the usual error shape for anything else, before your code runs. Do not call `c.req.json()` directly; `nerd check` flags it. Path parameters get the same care: turn an id into a number and let a missing row be a 404. The client's own checks are for the person's convenience; they protect nothing.
103
+ 5. **Hiding a button is not access control.** If only admins may do something, the route says `requireRole("admin")`. What the page shows is decoration.
104
+ 6. **Files:** check the type and the size before writing to `c.env.STORAGE`, store under a key that starts with the owner's user id, and serve them through a route that checks the owner. Never build a key from a name the browser sent without cleaning it.
105
+ 7. **Say nothing useful in an error.** No stack traces, SQL, or internal ids in responses; log them with `console.error` and answer with `{ error: { code, message } }`.
106
+ 8. **No raw HTML from data.** Let React render text. Do not use `dangerouslySetInnerHTML` or `innerHTML` with anything a user typed.
107
+
108
+ ### Tests are part of the feature
109
+
110
+ The project ships with a test harness (`test/setup.ts`, from `@nerdsystem/sdk/testing`) that runs the real server code against a fresh local database and signs in made-up users. `pnpm test` runs it; `nerd check` and `nerd deploy` run it too and refuse the deploy when:
111
+
112
+ - a test fails (`tests/failing`);
113
+ - the test that calls `t.expectEveryRouteLocked({ public: [...] })` is gone (`tests/routes-not-checked`). That one call tries every route the app has as a signed-out visitor, so a new route is covered the moment it exists and fails until it is locked or deliberately listed as public;
114
+ - a route with an id in its path has not been tried by a second user (`tests/owner-not-checked`).
115
+
116
+ For every feature you build:
117
+
118
+ - **One owner test per route with an id**, in `test/access.test.ts`: one user creates the thing, then `await t.expectHiddenFrom(otherUser, "PATCH", `/api/things/${id}`, body)` for each method. For lists, `await t.expectNotListed(otherUser, "/api/things", "a title only the owner has")`. If every signed-in user is truly meant to reach it (a shared catalogue, a public profile), declare `t.shared("GET /api/things/:id", "why")` instead and tell the person.
119
+ - **One test file per feature** (`test/<feature>.test.ts`, like `test/todos.test.ts`): the main path a person takes from start to finish, and the inputs it must refuse.
120
+ - **A role test** for anything behind `requireRole`: a signed-in user without the role gets 403, one with it gets through (`await t.as("dana", { roles: ["admin"] })`).
121
+
122
+ When a test fails, fix the app. Change a test only when the behaviour it describes was meant to change. Never delete or weaken an access test, widen the `public` list, add `t.shared`, or remove `"tests": "required"` from `nerd.json` to get a deploy through; if you believe one of those is right, stop and ask the person in plain words first. Never import `@nerdsystem/sdk/testing` from anything under `src/`: it can sign in as anyone, and `nerd check` refuses it.
123
+
124
+ What the tests do not prove: that the feature is the one the person wanted, or that its rules (who may book which slot, what a discount applies to) are right. Say what you built and what is public when you hand it over, so they can tell you if it is wrong.
125
+
95
126
  ## Data rules
96
127
 
97
128
  - Every table holding user data has a `user_id` text column, and every read and write filters on `c.var.user.id`. This is how users are kept apart.
@@ -127,6 +158,8 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
127
158
  - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
128
159
  - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
129
160
  - Typecheck failures in either `src/server` or `src/client`.
161
+ - SQL built from values, `eval` or `new Function`, and password handling in server code (the `code/` rules; they block). It also flags, without blocking: tokens signed in app code, HTML built from data, redirects and fetches to an address from the request, `Math.random` for a secret, a body read without `readBody`, and an app that has not turned on `public` in `createNerdApp`.
162
+ - A failing test, a missing access sweep, or a route with an id that no second user was tried against (the `tests/` rules above).
130
163
 
131
164
  ## Scheduled jobs and email
132
165
 
@@ -0,0 +1,64 @@
1
+ {
2
+ "version": "6",
3
+ "dialect": "sqlite",
4
+ "id": "a804e9fb-b416-462b-a3e2-0349c283a4b7",
5
+ "prevId": "00000000-0000-0000-0000-000000000000",
6
+ "tables": {
7
+ "todos": {
8
+ "name": "todos",
9
+ "columns": {
10
+ "id": {
11
+ "name": "id",
12
+ "type": "integer",
13
+ "primaryKey": true,
14
+ "notNull": true,
15
+ "autoincrement": true
16
+ },
17
+ "user_id": {
18
+ "name": "user_id",
19
+ "type": "text",
20
+ "primaryKey": false,
21
+ "notNull": true,
22
+ "autoincrement": false
23
+ },
24
+ "title": {
25
+ "name": "title",
26
+ "type": "text",
27
+ "primaryKey": false,
28
+ "notNull": true,
29
+ "autoincrement": false
30
+ },
31
+ "done": {
32
+ "name": "done",
33
+ "type": "integer",
34
+ "primaryKey": false,
35
+ "notNull": true,
36
+ "autoincrement": false,
37
+ "default": false
38
+ },
39
+ "created_at": {
40
+ "name": "created_at",
41
+ "type": "text",
42
+ "primaryKey": false,
43
+ "notNull": true,
44
+ "autoincrement": false
45
+ }
46
+ },
47
+ "indexes": {},
48
+ "foreignKeys": {},
49
+ "compositePrimaryKeys": {},
50
+ "uniqueConstraints": {},
51
+ "checkConstraints": {}
52
+ }
53
+ },
54
+ "views": {},
55
+ "enums": {},
56
+ "_meta": {
57
+ "schemas": {},
58
+ "tables": {},
59
+ "columns": {}
60
+ },
61
+ "internal": {
62
+ "indexes": {}
63
+ }
64
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "version": "7",
3
+ "dialect": "sqlite",
4
+ "entries": [
5
+ {
6
+ "idx": 0,
7
+ "version": "6",
8
+ "when": 1794323561793,
9
+ "tag": "0000_init",
10
+ "breakpoints": true
11
+ }
12
+ ]
13
+ }
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "$schema": "https://nerdsystem.com/schemas/nerd.json",
3
3
  "org": "",
4
- "project": ""
4
+ "project": "",
5
+ "tests": "required"
5
6
  }
@@ -7,6 +7,7 @@
7
7
  "dev": "nerd dev",
8
8
  "build": "vite build",
9
9
  "check": "nerd check",
10
+ "test": "vitest run",
10
11
  "deploy": "nerd deploy",
11
12
  "typecheck": "tsc -p tsconfig.worker.json --noEmit && tsc -p tsconfig.client.json --noEmit",
12
13
  "db:generate": "drizzle-kit generate",
@@ -17,7 +18,8 @@
17
18
  "drizzle-orm": "^0.45.4",
18
19
  "hono": "^4.13.16",
19
20
  "react": "^19.3.1",
20
- "react-dom": "^19.3.1"
21
+ "react-dom": "^19.3.1",
22
+ "zod": "^4.6.7"
21
23
  },
22
24
  "pnpm": {
23
25
  "onlyBuiltDependencies": [
@@ -34,6 +36,7 @@
34
36
  "drizzle-kit": "^0.31.11",
35
37
  "typescript": "^5.9.3",
36
38
  "vite": "^8.3.5",
39
+ "vitest": "^4.1.0",
37
40
  "wrangler": "^4.156.2"
38
41
  }
39
42
  }
@@ -3,7 +3,11 @@ import todos from "./routes/todos";
3
3
 
4
4
  // createNerdApp gives you a Hono app with sessions at /api/auth and c.var.user on every request.
5
5
  // Static assets (the React client) are served by the platform for every path outside /api.
6
- const app = createNerdApp();
6
+ //
7
+ // Every route needs a signed-in user unless it is named in `public`. A route you forget to protect
8
+ // answers 401, not everyone. Add a route here only when the whole internet is meant to reach it and it
9
+ // returns nothing private, and add it to the same list in test/access.test.ts.
10
+ const app = createNerdApp({ public: ["GET /api/health"] });
7
11
 
8
12
  app.get("/api/health", (c) => c.json({ ok: true, user: c.var.user?.email ?? null }));
9
13
 
@@ -1,8 +1,13 @@
1
1
  import { Hono } from "hono";
2
2
  import { and, desc, eq } from "drizzle-orm";
3
- import { requireAuth, type NerdHonoEnv } from "@nerdsystem/sdk";
3
+ import { z } from "zod";
4
+ import { readBody, requireAuth, type NerdHonoEnv } from "@nerdsystem/sdk";
4
5
  import { db, schema } from "../db";
5
6
 
7
+ // What each request may contain. readBody() answers 400 for anything else, before the route runs.
8
+ const NewTodo = z.object({ title: z.string().trim().min(1, "title is required").max(200) });
9
+ const TodoChange = z.object({ done: z.boolean() });
10
+
6
11
  // Every route here needs a signed-in user. c.var.user is set by the SDK.
7
12
  const todos = new Hono<NerdHonoEnv>();
8
13
  todos.use("*", requireAuth());
@@ -18,13 +23,10 @@ todos.get("/", async (c) => {
18
23
  });
19
24
 
20
25
  todos.post("/", async (c) => {
21
- const body = (await c.req.json().catch(() => ({}))) as { title?: unknown };
22
- if (typeof body.title !== "string" || !body.title.trim()) {
23
- return c.json({ error: { code: "bad_request", message: "title is required" } }, 400);
24
- }
26
+ const input = await readBody(c, NewTodo);
25
27
  const row = await db(c.env.DB)
26
28
  .insert(schema.todos)
27
- .values({ userId: c.var.user!.id, title: body.title.trim() })
29
+ .values({ userId: c.var.user!.id, title: input.title })
28
30
  .returning()
29
31
  .get();
30
32
  return c.json({ todo: row }, 201);
@@ -32,10 +34,10 @@ todos.post("/", async (c) => {
32
34
 
33
35
  todos.patch("/:id", async (c) => {
34
36
  const id = Number(c.req.param("id"));
35
- const body = (await c.req.json().catch(() => ({}))) as { done?: unknown };
37
+ const input = await readBody(c, TodoChange);
36
38
  const row = await db(c.env.DB)
37
39
  .update(schema.todos)
38
- .set({ done: Boolean(body.done) })
40
+ .set({ done: input.done })
39
41
  .where(and(eq(schema.todos.id, id), eq(schema.todos.userId, c.var.user!.id)))
40
42
  .returning()
41
43
  .get();
@@ -0,0 +1,42 @@
1
+ // Who can reach what. `nerd check` runs these before every deploy and refuses the deploy when one fails,
2
+ // when the first test is missing, or when a route with an id in its path has no owner test below.
3
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
4
+ import type { TestHarness } from "@nerdsystem/sdk/testing";
5
+ import { startTestApp } from "./setup";
6
+
7
+ let t: TestHarness;
8
+ let stop: () => Promise<void>;
9
+ beforeAll(async () => ({ t, stop } = await startTestApp()));
10
+ afterAll(() => stop());
11
+
12
+ describe("a signed-out visitor", () => {
13
+ it("is refused on every route that is not public", async () => {
14
+ // This calls every route the app has, including ones added later. A new route fails here until it
15
+ // has requireAuth() or requireRole() in front of it. Only list a route as public when everyone on
16
+ // the internet is meant to reach it, and it returns nothing private.
17
+ await t.expectEveryRouteLocked({ public: ["GET /api/health"] });
18
+ });
19
+ });
20
+
21
+ describe("one person's todos", () => {
22
+ it("cannot be seen, changed, or deleted by someone else", async () => {
23
+ const alice = await t.as("alice");
24
+ const bob = await t.as("bob");
25
+ const created = (await (await alice.post("/api/todos", { title: "only-alice-sees-this" })).json()) as { todo: { id: number } };
26
+
27
+ await t.expectNotListed(bob, "/api/todos", "only-alice-sees-this");
28
+ await t.expectHiddenFrom(bob, "PATCH", `/api/todos/${created.todo.id}`, { done: true });
29
+ await t.expectHiddenFrom(bob, "DELETE", `/api/todos/${created.todo.id}`);
30
+
31
+ // And it is still there, unchanged, for the person who owns it.
32
+ const mine = (await (await alice.get("/api/todos")).json()) as { todos: { id: number; done: boolean }[] };
33
+ expect(mine.todos).toEqual([expect.objectContaining({ id: created.todo.id, done: false })]);
34
+ });
35
+ });
36
+
37
+ describe("the admin route", () => {
38
+ it("needs the admin role, not just a sign-in", async () => {
39
+ expect((await (await t.as("carol")).get("/api/admin/ping")).status).toBe(403);
40
+ expect((await (await t.as("dana", { roles: ["admin"] })).get("/api/admin/ping")).status).toBe(200);
41
+ });
42
+ });
@@ -0,0 +1,7 @@
1
+ // Runs once before the tests: a report from an earlier run must not vouch for this one.
2
+ import { rmSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ export default function setup(): void {
6
+ rmSync(path.resolve(import.meta.dirname, "..", ".nerd", "access-report.json"), { force: true });
7
+ }
@@ -0,0 +1,40 @@
1
+ // Starts the app for tests: the real server code, a fresh local database with every migration applied,
2
+ // and the nerdsystem test harness. Nothing here talks to the network or to the live app.
3
+ // You should not need to change this file. Add tests next to it.
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { getPlatformProxy } from "wrangler";
7
+ import { testApp, type AccessReport, type TestHarness } from "@nerdsystem/sdk/testing";
8
+ import app from "../src/server";
9
+
10
+ const root = path.resolve(import.meta.dirname, "..");
11
+ const reportFile = path.join(root, ".nerd", "access-report.json");
12
+
13
+ /** Each test file adds what it checked to the one report `nerd check` reads. */
14
+ function mergeReport(next: AccessReport): void {
15
+ const prev: AccessReport | null = existsSync(reportFile) ? JSON.parse(readFileSync(reportFile, "utf8")) : null;
16
+ const union = <T,>(a: T[] | undefined, b: T[]) => [...new Set([...(a ?? []), ...b])].sort();
17
+ const merged: AccessReport = {
18
+ version: 1,
19
+ routes: next.routes,
20
+ locked: union(prev?.locked, next.locked),
21
+ public: union(prev?.public, next.public),
22
+ ownerChecked: union(prev?.ownerChecked, next.ownerChecked),
23
+ shared: union(prev?.shared, next.shared),
24
+ everyRouteChecked: Boolean(prev?.everyRouteChecked) || next.everyRouteChecked,
25
+ };
26
+ mkdirSync(path.dirname(reportFile), { recursive: true });
27
+ writeFileSync(reportFile, `${JSON.stringify(merged, null, 2)}\n`);
28
+ }
29
+
30
+ export async function startTestApp(): Promise<{ t: TestHarness; env: { DB: D1Database; STORAGE: R2Bucket }; stop: () => Promise<void> }> {
31
+ const platform = await getPlatformProxy<{ DB: D1Database; STORAGE: R2Bucket }>({ configPath: path.join(root, "wrangler.jsonc"), persist: false });
32
+ const dir = path.join(root, "migrations");
33
+ for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
34
+ for (const statement of readFileSync(path.join(dir, file), "utf8").split("--> statement-breakpoint")) {
35
+ if (statement.trim()) await platform.env.DB.prepare(statement).run();
36
+ }
37
+ }
38
+ const t = await testApp(app, { env: platform.env, onReport: mergeReport });
39
+ return { t, env: platform.env, stop: () => platform.dispose() };
40
+ }
@@ -0,0 +1,34 @@
1
+ // Does the feature work? One test file per feature: the main path a person takes, and the input it must refuse.
2
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
3
+ import type { TestHarness } from "@nerdsystem/sdk/testing";
4
+ import { startTestApp } from "./setup";
5
+
6
+ let t: TestHarness;
7
+ let stop: () => Promise<void>;
8
+ beforeAll(async () => ({ t, stop } = await startTestApp()));
9
+ afterAll(() => stop());
10
+
11
+ describe("todos", () => {
12
+ it("adds a todo, lists it, marks it done, and deletes it", async () => {
13
+ const erin = await t.as("erin");
14
+ const added = await erin.post("/api/todos", { title: " Buy milk " });
15
+ expect(added.status).toBe(201);
16
+ const { todo } = (await added.json()) as { todo: { id: number; title: string; done: boolean } };
17
+ expect(todo).toMatchObject({ title: "Buy milk", done: false });
18
+
19
+ expect(((await (await erin.get("/api/todos")).json()) as { todos: unknown[] }).todos).toHaveLength(1);
20
+ expect(((await (await erin.patch(`/api/todos/${todo.id}`, { done: true })).json()) as { todo: { done: boolean } }).todo.done).toBe(true);
21
+ expect((await erin.delete(`/api/todos/${todo.id}`)).status).toBe(200);
22
+ expect(((await (await erin.get("/api/todos")).json()) as { todos: unknown[] }).todos).toHaveLength(0);
23
+ });
24
+
25
+ it("refuses a todo with no title, and answers 404 for one that does not exist", async () => {
26
+ const erin = await t.as("erin");
27
+ expect((await erin.post("/api/todos", {})).status).toBe(400);
28
+ expect((await erin.post("/api/todos", { title: " " })).status).toBe(400);
29
+ expect((await erin.post("/api/todos", { title: "x".repeat(201) })).status).toBe(400);
30
+ expect((await erin.post("/api/todos", { title: 42 })).status).toBe(400);
31
+ expect((await erin.patch("/api/todos/1", { done: "yes" })).status).toBe(400);
32
+ expect((await erin.patch("/api/todos/999999", { done: true })).status).toBe(404);
33
+ });
34
+ });
@@ -0,0 +1,16 @@
1
+ // Tests run the server code in Node against a local database. This file keeps them apart from vite.config.ts,
2
+ // whose Cloudflare plugin is for building and for `nerd dev`.
3
+ import { defineConfig } from "vitest/config";
4
+
5
+ export default defineConfig({
6
+ test: {
7
+ include: ["test/**/*.test.ts"],
8
+ // The SDK is published for bundlers, so let Vite load it instead of Node.
9
+ server: { deps: { inline: ["@nerdsystem/sdk"] } },
10
+ globalSetup: ["test/global-setup.ts"],
11
+ // One file at a time: each starts its own local database, and they share one access report.
12
+ fileParallelism: false,
13
+ testTimeout: 20_000,
14
+ hookTimeout: 30_000,
15
+ },
16
+ });