nerdsystem 0.0.14 → 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.
- package/dist/commands/init.js +1 -1
- package/dist/gates/index.js +2 -1
- package/dist/gates/rules.js +10 -0
- package/dist/gates/static.d.ts +2 -0
- package/dist/gates/static.js +58 -0
- package/package.json +1 -1
- package/template/.claude/skills/nerdsystem/SKILL.md +3 -2
- package/template/.cursor/rules/nerdsystem.mdc +4 -3
- package/template/.github/copilot-instructions.md +4 -3
- package/template/AGENTS.md +4 -3
- package/template/CLAUDE.md +2 -1
- package/template/GEMINI.md +4 -3
- package/template/package.json +2 -1
- package/template/src/server/index.ts +5 -1
- package/template/src/server/routes/todos.ts +10 -8
- package/template/test/todos.test.ts +3 -0
package/dist/commands/init.js
CHANGED
|
@@ -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.
|
|
186
|
+
const SDK_VERSION = "0.0.15";
|
package/dist/gates/index.js
CHANGED
|
@@ -2,6 +2,7 @@ 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";
|
|
5
6
|
import { testsGate } from "./tests.js";
|
|
6
7
|
import { applyAttempts, MAX_ATTEMPTS } from "./attempts.js";
|
|
7
8
|
export { gateSummary, skippedGates } from "./types.js";
|
|
@@ -10,7 +11,7 @@ export { mask } from "./secrets.js";
|
|
|
10
11
|
export { MAX_ATTEMPTS, readAttempts } from "./attempts.js";
|
|
11
12
|
export { probeDeployment, skippedProbe, waitForDeployment } from "./smoke.js";
|
|
12
13
|
/** Gates that run on source, before the build. Suppressions first so a human sees them before anything else. */
|
|
13
|
-
export const SOURCE_GATES = [suppressionsGate, secretsGate, gitleaksGate, depsGate, rulesGate, semgrepGate, policyGate, piiGate, typecheckGate, testsGate];
|
|
14
|
+
export const SOURCE_GATES = [suppressionsGate, secretsGate, gitleaksGate, depsGate, rulesGate, staticGate, semgrepGate, policyGate, piiGate, typecheckGate, testsGate];
|
|
14
15
|
/** Gates that need the built output. */
|
|
15
16
|
export const BUILD_GATES = [bundleGate, policyGate];
|
|
16
17
|
function selectGates(gates, onlyRules) {
|
package/dist/gates/rules.js
CHANGED
|
@@ -36,6 +36,16 @@ 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." },
|
|
39
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`." },
|
|
40
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." },
|
|
41
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." },
|
|
@@ -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
|
+
};
|
package/package.json
CHANGED
|
@@ -99,10 +99,10 @@ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
|
|
|
99
99
|
|
|
100
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
101
|
|
|
102
|
-
1. **
|
|
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
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
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.**
|
|
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
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
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
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 } }`.
|
|
@@ -161,6 +161,7 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
|
|
|
161
161
|
- New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
|
|
162
162
|
- Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
|
|
163
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`.
|
|
164
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).
|
|
165
166
|
|
|
166
167
|
## Scheduled jobs and email
|
|
@@ -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 (
|
|
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
|
|
|
@@ -100,10 +100,10 @@ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
|
|
|
100
100
|
|
|
101
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
102
|
|
|
103
|
-
1. **
|
|
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
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
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.**
|
|
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
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
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
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 } }`.
|
|
@@ -162,6 +162,7 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
|
|
|
162
162
|
- New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
|
|
163
163
|
- Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
|
|
164
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`.
|
|
165
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).
|
|
166
167
|
|
|
167
168
|
## Scheduled jobs and email
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- generated from .claude/skills/nerdsystem/SKILL.md (
|
|
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
|
|
|
@@ -96,10 +96,10 @@ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
|
|
|
96
96
|
|
|
97
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
98
|
|
|
99
|
-
1. **
|
|
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
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
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.**
|
|
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
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
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
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 } }`.
|
|
@@ -158,6 +158,7 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
|
|
|
158
158
|
- New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
|
|
159
159
|
- Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
|
|
160
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`.
|
|
161
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).
|
|
162
163
|
|
|
163
164
|
## Scheduled jobs and email
|
package/template/AGENTS.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- generated from .claude/skills/nerdsystem/SKILL.md (
|
|
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
|
|
|
@@ -96,10 +96,10 @@ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
|
|
|
96
96
|
|
|
97
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
98
|
|
|
99
|
-
1. **
|
|
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
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
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.**
|
|
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
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
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
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 } }`.
|
|
@@ -158,6 +158,7 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
|
|
|
158
158
|
- New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
|
|
159
159
|
- Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
|
|
160
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`.
|
|
161
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).
|
|
162
163
|
|
|
163
164
|
## Scheduled jobs and email
|
package/template/CLAUDE.md
CHANGED
|
@@ -28,7 +28,8 @@ nerdsystem deploys this app to Cloudflare and provides authentication and author
|
|
|
28
28
|
5. Keep every API route under `/api/`. Other paths are served from static assets and never reach the Worker.
|
|
29
29
|
6. Do not add Cloudflare bindings to `wrangler.jsonc`, and do not run `wrangler deploy`. Bindings are provisioned by the platform.
|
|
30
30
|
7. Secrets and environment variables for the deployed app are managed with `nerd` commands, never committed.
|
|
31
|
-
8. Every route is
|
|
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.
|
|
32
33
|
|
|
33
34
|
## Roles
|
|
34
35
|
|
package/template/GEMINI.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
<!-- generated from .claude/skills/nerdsystem/SKILL.md (
|
|
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
|
|
|
@@ -96,10 +96,10 @@ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
|
|
|
96
96
|
|
|
97
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
98
|
|
|
99
|
-
1. **
|
|
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
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
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.**
|
|
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
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
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
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 } }`.
|
|
@@ -158,6 +158,7 @@ Without MCP, `nerd check --json` returns the same shape, and `nerd check --rule
|
|
|
158
158
|
- New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
|
|
159
159
|
- Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
|
|
160
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`.
|
|
161
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).
|
|
162
163
|
|
|
163
164
|
## Scheduled jobs and email
|
package/template/package.json
CHANGED
|
@@ -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
|
-
|
|
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 {
|
|
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
|
|
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:
|
|
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
|
|
37
|
+
const input = await readBody(c, TodoChange);
|
|
36
38
|
const row = await db(c.env.DB)
|
|
37
39
|
.update(schema.todos)
|
|
38
|
-
.set({ 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();
|
|
@@ -26,6 +26,9 @@ describe("todos", () => {
|
|
|
26
26
|
const erin = await t.as("erin");
|
|
27
27
|
expect((await erin.post("/api/todos", {})).status).toBe(400);
|
|
28
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);
|
|
29
32
|
expect((await erin.patch("/api/todos/999999", { done: true })).status).toBe(404);
|
|
30
33
|
});
|
|
31
34
|
});
|