nerdsystem 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/api.d.ts +58 -0
  4. package/dist/api.js +59 -0
  5. package/dist/commands/agents.d.ts +9 -0
  6. package/dist/commands/agents.js +45 -0
  7. package/dist/commands/auth.d.ts +7 -0
  8. package/dist/commands/auth.js +25 -0
  9. package/dist/commands/billing.d.ts +14 -0
  10. package/dist/commands/billing.js +42 -0
  11. package/dist/commands/builds.d.ts +12 -0
  12. package/dist/commands/builds.js +40 -0
  13. package/dist/commands/check.d.ts +20 -0
  14. package/dist/commands/check.js +145 -0
  15. package/dist/commands/db.d.ts +9 -0
  16. package/dist/commands/db.js +32 -0
  17. package/dist/commands/deploy.d.ts +27 -0
  18. package/dist/commands/deploy.js +119 -0
  19. package/dist/commands/dev.d.ts +3 -0
  20. package/dist/commands/dev.js +38 -0
  21. package/dist/commands/doctor.d.ts +4 -0
  22. package/dist/commands/doctor.js +42 -0
  23. package/dist/commands/github.d.ts +17 -0
  24. package/dist/commands/github.js +49 -0
  25. package/dist/commands/init.d.ts +15 -0
  26. package/dist/commands/init.js +107 -0
  27. package/dist/commands/login.d.ts +7 -0
  28. package/dist/commands/login.js +21 -0
  29. package/dist/commands/ops.d.ts +29 -0
  30. package/dist/commands/ops.js +113 -0
  31. package/dist/commands/org.d.ts +47 -0
  32. package/dist/commands/org.js +121 -0
  33. package/dist/commands/verify.d.ts +24 -0
  34. package/dist/commands/verify.js +50 -0
  35. package/dist/config.d.ts +7 -0
  36. package/dist/config.js +22 -0
  37. package/dist/gates/attempts.d.ts +18 -0
  38. package/dist/gates/attempts.js +38 -0
  39. package/dist/gates/code.d.ts +15 -0
  40. package/dist/gates/code.js +179 -0
  41. package/dist/gates/fs.d.ts +7 -0
  42. package/dist/gates/fs.js +35 -0
  43. package/dist/gates/index.d.ts +26 -0
  44. package/dist/gates/index.js +68 -0
  45. package/dist/gates/rules.d.ts +19 -0
  46. package/dist/gates/rules.js +58 -0
  47. package/dist/gates/secrets.d.ts +11 -0
  48. package/dist/gates/secrets.js +98 -0
  49. package/dist/gates/suppressions.d.ts +2 -0
  50. package/dist/gates/suppressions.js +57 -0
  51. package/dist/gates/text.d.ts +31 -0
  52. package/dist/gates/text.js +72 -0
  53. package/dist/gates/tools.d.ts +5 -0
  54. package/dist/gates/tools.js +69 -0
  55. package/dist/gates/types.d.ts +72 -0
  56. package/dist/gates/types.js +18 -0
  57. package/dist/index.d.ts +2 -0
  58. package/dist/index.js +268 -0
  59. package/dist/project.d.ts +11 -0
  60. package/dist/project.js +51 -0
  61. package/dist/util.d.ts +21 -0
  62. package/dist/util.js +39 -0
  63. package/package.json +55 -3
  64. package/rules/semgrep.yml +77 -0
  65. package/template/.claude/settings.json +12 -0
  66. package/template/.claude/skills/nerdsystem/SKILL.md +123 -0
  67. package/template/.cursor/mcp.json +8 -0
  68. package/template/.cursor/rules/nerdsystem.mdc +124 -0
  69. package/template/.gemini/settings.json +8 -0
  70. package/template/.github/copilot-instructions.md +120 -0
  71. package/template/.github/dependabot.yml +14 -0
  72. package/template/.mcp.json +8 -0
  73. package/template/.vscode/mcp.json +9 -0
  74. package/template/AGENTS.md +120 -0
  75. package/template/CLAUDE.md +32 -0
  76. package/template/GEMINI.md +120 -0
  77. package/template/drizzle.config.ts +7 -0
  78. package/template/gitignore +7 -0
  79. package/template/index.html +12 -0
  80. package/template/migrations/0000_init.sql +7 -0
  81. package/template/nerd.json +5 -0
  82. package/template/package.json +33 -0
  83. package/template/scripts/sync-agents.mjs +28 -0
  84. package/template/src/client/App.tsx +182 -0
  85. package/template/src/client/api.ts +42 -0
  86. package/template/src/client/main.tsx +10 -0
  87. package/template/src/client/styles.css +16 -0
  88. package/template/src/client/vite-env.d.ts +1 -0
  89. package/template/src/server/db/index.ts +7 -0
  90. package/template/src/server/db/schema.ts +14 -0
  91. package/template/src/server/index.ts +23 -0
  92. package/template/src/server/routes/todos.ts +57 -0
  93. package/template/tsconfig.client.json +18 -0
  94. package/template/tsconfig.json +4 -0
  95. package/template/tsconfig.worker.json +18 -0
  96. package/template/vite.config.ts +7 -0
  97. package/template/wrangler.jsonc +18 -0
@@ -0,0 +1,120 @@
1
+ <!-- generated from .claude/skills/nerdsystem/SKILL.md (2834c4c81f7f); edit the skill, then run: nerd agents sync -->
2
+
3
+ # Building on nerdsystem
4
+
5
+ This app is deployed by nerdsystem, which also provides authentication, authorization, a D1 database, and an R2 bucket. You never touch Cloudflare directly. Everything goes through the `nerd` CLI, which wraps the platform API. Every `nerd` command accepts `--json`; prefer it when you need to parse output.
6
+
7
+ ## First session with a new project
8
+
9
+ If this project still has the template's todo app (the `todos` table and `src/server/routes/todos.ts`), treat the person as new and offer a short walkthrough before building anything:
10
+
11
+ 1. Ask one question: what should the app do, in a sentence or two. Do not ask about stacks, databases, or hosting; those are decided.
12
+ 2. Say what you will build first, in plain words: the one table and the one screen that make the idea real. Keep the first feature small enough to deploy within the session.
13
+ 3. Replace the todo example with that feature: schema, migration (`pnpm db:generate`), a router under `/api/...`, and the client screen. Keep signup and login as they are; they already work.
14
+ 4. Run `nerd check`, then `nerd dev`, and tell the person to open the local URL, create an account, and try it. Fix what they report.
15
+ 5. Run `nerd deploy` and give them the live URL. Explain in two lines that every deploy is checked for leaked secrets and vulnerable dependencies, and that they can run `nerd verify` any time.
16
+ 6. Offer the next steps once, briefly: link the GitHub repo for previews on pull requests (`nerd github connect`), add a custom domain, or invite a teammate from the dashboard.
17
+
18
+ Throughout, show commands rather than describing them, and never ask the person to edit config files; the platform owns `wrangler.jsonc` and `nerd.json`.
19
+
20
+ ## The loop
21
+
22
+ 1. Make the change.
23
+ 2. `nerd check` (static rules, then typecheck). Fix anything it reports.
24
+ 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.
25
+ 4. `nerd deploy` when it is ready. It runs the checks, builds, applies pending migrations, uploads, and prints the URL.
26
+ 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.
27
+
28
+ Run `nerd check --json` when you want a machine-readable list of problems.
29
+
30
+ ## Deploying from GitHub
31
+
32
+ Once the repo is linked (`nerd github connect`, then `nerd github link owner/repo`), every push to the production branch builds and deploys automatically, and every pull request gets a preview at its own URL, posted as a PR comment. `nerd builds` lists builds; `nerd builds show <id>` prints the log when one fails. A failing build reports the same `nerd check` problems you would see locally, so fix and push again. Previews share the production database and do not run migrations; a PR that changes the schema will only work in full after it merges.
33
+
34
+ ## Where things go
35
+
36
+ | Concern | Location |
37
+ | --- | --- |
38
+ | API routes | `src/server/index.ts` mounts routers under `/api/...`. Put each resource in `src/server/routes/<name>.ts`. |
39
+ | Database schema | `src/server/db/schema.ts` (Drizzle). Then `pnpm db:generate` to produce a migration in `migrations/`. |
40
+ | Queries | `db(c.env.DB)` from `src/server/db/index.ts`. Drizzle query builder, D1 dialect (SQLite). |
41
+ | Files | `c.env.STORAGE` is an R2 bucket. `put`, `get`, `delete`, `list`. Key files by user id. |
42
+ | Frontend | `src/client/` React, built by Vite. `src/client/api.ts` has a fetch wrapper that sends the session cookie. |
43
+ | Roles and signup policy | `nerd auth config`. Not in code. |
44
+
45
+ ## Auth and authorization
46
+
47
+ The SDK handles sessions. There is no login code to write.
48
+
49
+ - `c.var.user` is `{ id, email, name, roles }` or `null` on every request.
50
+ - `requireAuth()` middleware returns 401 when signed out.
51
+ - `requireRole("admin")` returns 403 unless the user has one of the given roles. Multiple roles are OR.
52
+ - The frontend calls `/api/auth/signup`, `/api/auth/login`, `/api/auth/logout`, `/api/auth/me`, `/api/auth/forgot`, and `/api/auth/reset`. The template's `auth` helper in `src/client/api.ts` wraps them. Password reset emails link to `/reset-password?token=...`, which the template client renders; keep that route if you restructure the client.
53
+ - Roles are a list the platform owns. See the current list with `nerd auth config`. Add one with `nerd auth config --roles admin,member,editor`. The default role for new signups is set with `--default-role`. Turn public signup off with `--signup off`.
54
+ - To promote a user from code, use the admin client: `new AuthServiceClient(c.env).users.setRoles(userId, ["admin"])`. Guard that route with `requireRole("admin")`.
55
+
56
+ Example of a protected resource router:
57
+
58
+ ```ts
59
+ import { Hono } from "hono";
60
+ import { eq } from "drizzle-orm";
61
+ import { requireAuth, type NerdHonoEnv } from "@nerdsystem/sdk";
62
+ import { db, schema } from "../db";
63
+
64
+ const notes = new Hono<NerdHonoEnv>();
65
+ notes.use("*", requireAuth());
66
+ notes.get("/", async (c) => {
67
+ const rows = await db(c.env.DB).select().from(schema.notes).where(eq(schema.notes.userId, c.var.user!.id)).all();
68
+ return c.json({ notes: rows });
69
+ });
70
+ export default notes;
71
+ ```
72
+
73
+ Then in `src/server/index.ts`: `app.route("/api/notes", notes);`
74
+
75
+ ## Data rules
76
+
77
+ - 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.
78
+ - Schema changes are migrations. Edit `schema.ts`, run `pnpm db:generate`, commit the new file in `migrations/`. Never hand-write SQL into production; `nerd deploy` applies migrations in name order and records which ran.
79
+ - Migrations are forward-only. To undo, write another migration.
80
+ - Prefer small, additive migrations. SQLite cannot alter columns in place.
81
+
82
+ ## Errors
83
+
84
+ API errors are `{ error: { code, message } }` with a matching HTTP status. Use the same shape in your routes so the frontend's `ApiError` keeps working. Codes in use: `bad_request`, `unauthorized`, `forbidden`, `not_found`, `conflict`, `internal`.
85
+
86
+ ## Security gates
87
+
88
+ The `nerdsystem` MCP server (configured in `.mcp.json`) gives you two tools; prefer them over shelling out:
89
+
90
+ - `run_gates` runs every gate a deploy runs (secrets in source and in the built bundle, vulnerable dependencies, platform rules, static analysis, acceptable-use policy, personal-data heuristics, typecheck, and scanner suppressions) and returns `failures`. Each has `rule_id`, `file`, `line`, `risk` (what could happen), `fix` (what to change), `verify` (the command that confirms it), `attempt`, and `audience`.
91
+ - `explain_failure` takes a `rule_id` and returns the risk, the fix, and a wrong/right example.
92
+
93
+ The loop: run `run_gates`, fix every failure with `audience: "agent"`, run `run_gates` again (it re-runs every gate, not just the one that failed), repeat. Rules you cannot clear:
94
+
95
+ - `audience: "human"` means a person must act: a secret that was committed must be rotated at the provider before you remove it; an ignore comment, ignore file, or gate setting you added is a suppression that only a person can approve in the dashboard. Never add `nosemgrep`, `gitleaks:allow`, `nerd-ignore`, or a `gates` key in `nerd.json` to make a finding go away.
96
+ - When `stop` is non-empty, the same rule has failed three runs in a row. Stop, summarize what you tried in plain words, and hand it to the person.
97
+
98
+ Without MCP, `nerd verify --json` returns the same shape, and `nerd verify --rule <rule_id>` runs one rule. Secrets are reported masked (`sk_live_****4f2a`); never print a credential yourself. Keep secrets in `.dev.vars` locally and in platform settings in production; never prefix a secret with `VITE_`, because those values are compiled into the public client bundle.
99
+
100
+ ## What `nerd check` rejects
101
+
102
+ - A root app that is not `createNerdApp()` from `@nerdsystem/sdk`.
103
+ - Any route outside `/api/`. Other paths serve the static client and never reach the Worker.
104
+ - New bindings in `wrangler.jsonc`. Only `DB`, `STORAGE`, and `ASSETS` exist. Durable Objects are not available.
105
+ - Scripts that call `wrangler deploy`, `wrangler secret`, or remote `wrangler d1` commands.
106
+ - Typecheck failures in either `src/server` or `src/client`.
107
+
108
+ ## Scheduled jobs and email
109
+
110
+ - **Scheduled jobs**: put the work in the `POST /api/cron` handler (already in `src/server/index.ts`, guarded by `verifyCron()`), then turn the schedule on with `nerd cron hourly` or `nerd cron daily`. The platform calls it; the app never needs its own timer.
111
+ - **Secrets** (Stripe keys, API tokens): never in code or in the client. Locally they live in `.dev.vars` (gitignored). For production, ask the person to run `nerd secret set NAME` and paste the value; it reaches the app as `c.env.NAME` on the next deploy. `nerd secret list` shows names only. Do not put a real secret value in any command you run yourself.
112
+ - **Email**: `sendEmail(c.env, { to, subject, text, html? })` from `@nerdsystem/sdk` sends through the platform. It is limited per day by plan (50 on Free, 2,000 on Pro at $39 a month, 10,000 on Studio), so use it for transactional mail such as receipts and notifications, not bulk. Plans can be paid monthly or yearly at ten times the monthly price.
113
+
114
+ ## Debugging production
115
+
116
+ When something is wrong on the deployed app: `nerd logs --since 1h` (add `--q "text"` to search, `--pr 12` for a preview) shows errors with the request that caused them. Reproduce locally with `nerd dev` using the same input, fix it, run `nerd verify`, and deploy or open a pull request. If a deploy made things worse, `nerd rollback` puts the previous production bundle back without touching the database. Write a one-line note on every deploy (`nerd deploy --note "fix: todos query filtered by user"`); the dashboard shows these as a changelog people can read.
117
+
118
+ ## Not available yet
119
+
120
+ Queues, Durable Objects, and log streaming. If the task needs one, say so instead of working around it with an unsupported binding.
@@ -0,0 +1,7 @@
1
+ import { defineConfig } from "drizzle-kit";
2
+
3
+ export default defineConfig({
4
+ dialect: "sqlite",
5
+ schema: "./src/server/db/schema.ts",
6
+ out: "./migrations",
7
+ });
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ .wrangler/
4
+ .dev.vars
5
+ .dev.vars.*
6
+ *.tsbuildinfo
7
+ .nerd/
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>nerd-app</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/client/main.tsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,7 @@
1
+ CREATE TABLE `todos` (
2
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
3
+ `user_id` text NOT NULL,
4
+ `title` text NOT NULL,
5
+ `done` integer DEFAULT false NOT NULL,
6
+ `created_at` text NOT NULL
7
+ );
@@ -0,0 +1,5 @@
1
+ {
2
+ "$schema": "https://nerdsystem.com/schemas/nerd.json",
3
+ "org": "",
4
+ "project": ""
5
+ }
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "nerd-app",
3
+ "version": "0.0.1",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "nerd dev",
8
+ "build": "vite build",
9
+ "check": "nerd check",
10
+ "deploy": "nerd deploy",
11
+ "typecheck": "tsc -p tsconfig.worker.json --noEmit && tsc -p tsconfig.client.json --noEmit",
12
+ "db:generate": "drizzle-kit generate",
13
+ "agents:sync": "node scripts/sync-agents.mjs"
14
+ },
15
+ "dependencies": {
16
+ "@nerdsystem/sdk": "workspace:*",
17
+ "drizzle-orm": "^0.45.4",
18
+ "hono": "^4.13.16",
19
+ "react": "^19.3.1",
20
+ "react-dom": "^19.3.1"
21
+ },
22
+ "devDependencies": {
23
+ "@cloudflare/vite-plugin": "^1.67.0",
24
+ "@cloudflare/workers-types": "^5.20261102.1",
25
+ "@types/react": "^19.3.0",
26
+ "@types/react-dom": "^19.3.0",
27
+ "@vitejs/plugin-react": "^6.2.1",
28
+ "drizzle-kit": "^0.31.11",
29
+ "typescript": "^5.9.3",
30
+ "vite": "^8.3.5",
31
+ "wrangler": "^4.156.2"
32
+ }
33
+ }
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // Generates per-agent instruction files from the single source of truth, the nerdsystem skill.
3
+ // Run after editing .claude/skills/nerdsystem/SKILL.md (or let `nerd agents sync` do it).
4
+ import { createHash } from "node:crypto";
5
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
10
+ const skillPath = path.join(root, ".claude/skills/nerdsystem/SKILL.md");
11
+ const skill = readFileSync(skillPath, "utf8");
12
+ const body = skill.replace(/^---[\s\S]*?---\s*/, ""); // drop the skill front matter
13
+ const hash = createHash("sha256").update(body).digest("hex").slice(0, 12);
14
+ const stamp = `<!-- generated from .claude/skills/nerdsystem/SKILL.md (${hash}); edit the skill, then run: nerd agents sync -->`;
15
+
16
+ const targets = {
17
+ "AGENTS.md": `${stamp}\n\n${body}`,
18
+ "GEMINI.md": `${stamp}\n\n${body}`,
19
+ ".github/copilot-instructions.md": `${stamp}\n\n${body}`,
20
+ ".cursor/rules/nerdsystem.mdc": `---\ndescription: How to build, run, and deploy this app on nerdsystem. Applies to server, database, auth, and deploy work.\nalwaysApply: true\n---\n${stamp}\n\n${body}`,
21
+ };
22
+
23
+ for (const [file, content] of Object.entries(targets)) {
24
+ const p = path.join(root, file);
25
+ mkdirSync(path.dirname(p), { recursive: true });
26
+ writeFileSync(p, content);
27
+ }
28
+ console.log(`synced ${Object.keys(targets).length} agent files from the skill (${hash})`);
@@ -0,0 +1,182 @@
1
+ import { useEffect, useRef, useState, type FormEvent } from "react";
2
+
3
+ // Optional bot protection on signup: set VITE_TURNSTILE_SITE_KEY (client) and NERD_TURNSTILE_SECRET
4
+ // (server, via `nerd secrets`) from a Cloudflare Turnstile widget. Without them, signup is open.
5
+ const TURNSTILE_SITE_KEY = import.meta.env.VITE_TURNSTILE_SITE_KEY as string | undefined;
6
+
7
+ function Turnstile({ onToken }: { onToken: (t: string) => void }) {
8
+ const ref = useRef<HTMLDivElement>(null);
9
+ useEffect(() => {
10
+ if (!TURNSTILE_SITE_KEY || !ref.current) return;
11
+ const w = window as unknown as { turnstile?: { render: (el: HTMLElement, opts: { sitekey: string; callback: (t: string) => void }) => void } };
12
+ const render = () => w.turnstile?.render(ref.current!, { sitekey: TURNSTILE_SITE_KEY, callback: onToken });
13
+ if (w.turnstile) render();
14
+ else {
15
+ const s = document.createElement("script");
16
+ s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
17
+ s.async = true;
18
+ s.onload = render;
19
+ document.head.appendChild(s);
20
+ }
21
+ }, [onToken]);
22
+ return TURNSTILE_SITE_KEY ? <div ref={ref} /> : null;
23
+ }
24
+ import { api, auth, ApiError, type User } from "./api";
25
+
26
+ interface Todo {
27
+ id: number;
28
+ title: string;
29
+ done: boolean;
30
+ }
31
+
32
+ export default function App() {
33
+ const [user, setUser] = useState<User | null | undefined>(undefined);
34
+
35
+ useEffect(() => {
36
+ auth.me().then((r) => setUser(r.user)).catch(() => setUser(null));
37
+ }, []);
38
+
39
+ if (user === undefined) return <main className="shell">Loading…</main>;
40
+ if (window.location.pathname === "/reset-password") return <ResetPassword onSignedIn={(u) => { window.history.replaceState(null, "", "/"); setUser(u); }} />;
41
+ if (!user) return <AuthScreen onSignedIn={setUser} />;
42
+ return <Todos user={user} onSignedOut={() => setUser(null)} />;
43
+ }
44
+
45
+ function AuthScreen({ onSignedIn }: { onSignedIn: (u: User) => void }) {
46
+ const [mode, setMode] = useState<"login" | "signup" | "forgot">("login");
47
+ const [error, setError] = useState<string | null>(null);
48
+ const [notice, setNotice] = useState<string | null>(null);
49
+ const [busy, setBusy] = useState(false);
50
+ const [turnstileToken, setTurnstileToken] = useState<string | undefined>(undefined);
51
+
52
+ async function submit(e: FormEvent<HTMLFormElement>) {
53
+ e.preventDefault();
54
+ const form = new FormData(e.currentTarget);
55
+ const email = String(form.get("email"));
56
+ const password = String(form.get("password"));
57
+ setBusy(true);
58
+ setError(null);
59
+ try {
60
+ if (mode === "forgot") {
61
+ await auth.forgot(email);
62
+ setNotice("If that email has an account, a reset link is on its way.");
63
+ return;
64
+ }
65
+ const r = mode === "login" ? await auth.login(email, password) : await auth.signup(email, password, String(form.get("name")), turnstileToken);
66
+ onSignedIn(r.user);
67
+ } catch (err) {
68
+ setError(err instanceof ApiError ? err.message : "Something went wrong");
69
+ } finally {
70
+ setBusy(false);
71
+ }
72
+ }
73
+
74
+ return (
75
+ <main className="shell">
76
+ <h1>nerd-app</h1>
77
+ <form onSubmit={submit} className="card">
78
+ {mode === "signup" && <input name="name" placeholder="Your name" required />}
79
+ <input name="email" type="email" placeholder="Email" required />
80
+ {mode !== "forgot" && <input name="password" type="password" placeholder="Password (8+ characters)" minLength={8} required />}
81
+ {mode === "signup" && <Turnstile onToken={setTurnstileToken} />}
82
+ {error && <p className="error">{error}</p>}
83
+ {notice && <p className="muted">{notice}</p>}
84
+ <button disabled={busy}>{mode === "login" ? "Sign in" : mode === "signup" ? "Create account" : "Email me a reset link"}</button>
85
+ <button type="button" className="link" onClick={() => { setNotice(null); setMode(mode === "login" ? "signup" : "login"); }}>
86
+ {mode === "login" ? "Need an account? Sign up" : "Have an account? Sign in"}
87
+ </button>
88
+ {mode === "login" && (
89
+ <button type="button" className="link" onClick={() => { setNotice(null); setMode("forgot"); }}>Forgot your password?</button>
90
+ )}
91
+ </form>
92
+ </main>
93
+ );
94
+ }
95
+
96
+ function ResetPassword({ onSignedIn }: { onSignedIn: (u: User) => void }) {
97
+ const token = new URLSearchParams(window.location.search).get("token") ?? "";
98
+ const [error, setError] = useState<string | null>(null);
99
+ const [busy, setBusy] = useState(false);
100
+ async function submit(e: FormEvent<HTMLFormElement>) {
101
+ e.preventDefault();
102
+ setBusy(true);
103
+ setError(null);
104
+ try {
105
+ const r = await auth.reset(token, String(new FormData(e.currentTarget).get("password")));
106
+ onSignedIn(r.user);
107
+ } catch (err) {
108
+ setError(err instanceof ApiError ? err.message : "Something went wrong");
109
+ } finally {
110
+ setBusy(false);
111
+ }
112
+ }
113
+ return (
114
+ <main className="shell">
115
+ <h1>Choose a new password</h1>
116
+ <form onSubmit={submit} className="card">
117
+ <input name="password" type="password" placeholder="New password (8+ characters)" minLength={8} required autoFocus />
118
+ {error && <p className="error">{error}</p>}
119
+ <button disabled={busy || !token}>Set password and sign in</button>
120
+ </form>
121
+ </main>
122
+ );
123
+ }
124
+
125
+ function Todos({ user, onSignedOut }: { user: User; onSignedOut: () => void }) {
126
+ const [todos, setTodos] = useState<Todo[]>([]);
127
+ const [title, setTitle] = useState("");
128
+
129
+ const load = () => api<{ todos: Todo[] }>("/api/todos").then((r) => setTodos(r.todos));
130
+ useEffect(() => {
131
+ load();
132
+ }, []);
133
+
134
+ async function add(e: FormEvent) {
135
+ e.preventDefault();
136
+ if (!title.trim()) return;
137
+ await api("/api/todos", { method: "POST", body: JSON.stringify({ title }) });
138
+ setTitle("");
139
+ load();
140
+ }
141
+
142
+ async function toggle(t: Todo) {
143
+ await api(`/api/todos/${t.id}`, { method: "PATCH", body: JSON.stringify({ done: !t.done }) });
144
+ load();
145
+ }
146
+
147
+ async function remove(t: Todo) {
148
+ await api(`/api/todos/${t.id}`, { method: "DELETE" });
149
+ load();
150
+ }
151
+
152
+ return (
153
+ <main className="shell">
154
+ <header>
155
+ <h1>Todos</h1>
156
+ <span>
157
+ {user.name} · {user.roles.join(", ")}{" "}
158
+ <button className="link" onClick={() => auth.logout().then(onSignedOut)}>
159
+ Sign out
160
+ </button>
161
+ </span>
162
+ </header>
163
+ <form onSubmit={add} className="row">
164
+ <input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="What needs doing?" />
165
+ <button>Add</button>
166
+ </form>
167
+ <ul className="list">
168
+ {todos.map((t) => (
169
+ <li key={t.id} className={t.done ? "done" : ""}>
170
+ <label>
171
+ <input type="checkbox" checked={t.done} onChange={() => toggle(t)} /> {t.title}
172
+ </label>
173
+ <button className="link" onClick={() => remove(t)}>
174
+ ×
175
+ </button>
176
+ </li>
177
+ ))}
178
+ {todos.length === 0 && <li className="muted">Nothing yet.</li>}
179
+ </ul>
180
+ </main>
181
+ );
182
+ }
@@ -0,0 +1,42 @@
1
+ // Small fetch wrapper. Cookies carry the session, so there is nothing to attach by hand.
2
+ export interface User {
3
+ id: string;
4
+ email: string;
5
+ name: string;
6
+ roles: string[];
7
+ }
8
+
9
+ export class ApiError extends Error {
10
+ constructor(
11
+ public readonly status: number,
12
+ public readonly code: string,
13
+ message: string,
14
+ ) {
15
+ super(message);
16
+ }
17
+ }
18
+
19
+ export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
20
+ const res = await fetch(path, {
21
+ ...init,
22
+ headers: { ...(init.body ? { "content-type": "application/json" } : {}), ...init.headers },
23
+ credentials: "same-origin",
24
+ });
25
+ const text = await res.text();
26
+ const json = text ? JSON.parse(text) : null;
27
+ if (!res.ok) {
28
+ throw new ApiError(res.status, json?.error?.code ?? "error", json?.error?.message ?? `Request failed (${res.status})`);
29
+ }
30
+ return json as T;
31
+ }
32
+
33
+ export const auth = {
34
+ me: () => api<{ user: User | null }>("/api/auth/me"),
35
+ login: (email: string, password: string) =>
36
+ api<{ user: User }>("/api/auth/login", { method: "POST", body: JSON.stringify({ email, password }) }),
37
+ signup: (email: string, password: string, name: string, turnstileToken?: string) =>
38
+ api<{ user: User }>("/api/auth/signup", { method: "POST", body: JSON.stringify({ email, password, name, ...(turnstileToken ? { turnstileToken } : {}) }) }),
39
+ logout: () => api<{ ok: true }>("/api/auth/logout", { method: "POST" }),
40
+ forgot: (email: string) => api<{ ok: true }>("/api/auth/forgot", { method: "POST", body: JSON.stringify({ email }) }),
41
+ reset: (token: string, password: string) => api<{ user: User }>("/api/auth/reset", { method: "POST", body: JSON.stringify({ token, password }) }),
42
+ };
@@ -0,0 +1,10 @@
1
+ import { StrictMode } from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import App from "./App";
4
+ import "./styles.css";
5
+
6
+ createRoot(document.getElementById("root")!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>,
10
+ );
@@ -0,0 +1,16 @@
1
+ :root { color-scheme: light dark; font-family: system-ui, sans-serif; }
2
+ body { margin: 0; }
3
+ .shell { max-width: 32rem; margin: 4rem auto; padding: 0 1rem; }
4
+ header { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; }
5
+ h1 { margin: 0 0 1rem; }
6
+ .card, .row { display: flex; flex-direction: column; gap: 0.5rem; }
7
+ .row { flex-direction: row; }
8
+ .row input { flex: 1; }
9
+ input { padding: 0.5rem; font: inherit; }
10
+ button { padding: 0.5rem 0.75rem; font: inherit; cursor: pointer; }
11
+ button.link { background: none; border: none; color: inherit; text-decoration: underline; padding: 0; }
12
+ .list { list-style: none; padding: 0; }
13
+ .list li { display: flex; justify-content: space-between; padding: 0.4rem 0; border-bottom: 1px solid #8884; }
14
+ .list li.done label { text-decoration: line-through; opacity: 0.6; }
15
+ .error { color: #c33; margin: 0; }
16
+ .muted { opacity: 0.6; }
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />
@@ -0,0 +1,7 @@
1
+ import { drizzle } from "drizzle-orm/d1";
2
+ import * as schema from "./schema";
3
+
4
+ export function db(d1: D1Database) {
5
+ return drizzle(d1, { schema });
6
+ }
7
+ export { schema };
@@ -0,0 +1,14 @@
1
+ import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
2
+
3
+ // Add your tables here, then run `pnpm db:generate` to create a migration.
4
+ // Rows that belong to a user should carry their id from c.var.user.
5
+
6
+ export const todos = sqliteTable("todos", {
7
+ id: integer("id").primaryKey({ autoIncrement: true }),
8
+ userId: text("user_id").notNull(),
9
+ title: text("title").notNull(),
10
+ done: integer("done", { mode: "boolean" }).notNull().default(false),
11
+ createdAt: text("created_at")
12
+ .notNull()
13
+ .$defaultFn(() => new Date().toISOString()),
14
+ });
@@ -0,0 +1,23 @@
1
+ import { createNerdApp, cronEvent, requireRole, verifyCron } from "@nerdsystem/sdk";
2
+ import todos from "./routes/todos";
3
+
4
+ // createNerdApp gives you a Hono app with sessions at /api/auth and c.var.user on every request.
5
+ // Static assets (the React client) are served by the platform for every path outside /api.
6
+ const app = createNerdApp();
7
+
8
+ app.get("/api/health", (c) => c.json({ ok: true, user: c.var.user?.email ?? null }));
9
+
10
+ app.route("/api/todos", todos);
11
+
12
+ // Scheduled job. Turn it on with `nerd cron hourly` (or daily); the platform then POSTs here on
13
+ // schedule with a signed header. Put periodic work in this handler: digests, cleanup, syncing.
14
+ app.post("/api/cron", verifyCron(), async (c) => {
15
+ const event = await cronEvent(c);
16
+ console.log(`cron ${event.schedule} at ${event.at}`);
17
+ return c.json({ ok: true });
18
+ });
19
+
20
+ // Example of a role-gated route. Roles are managed in the nerdsystem dashboard or `nerd auth`.
21
+ app.get("/api/admin/ping", requireRole("admin"), (c) => c.json({ pong: true, admin: c.var.user!.email }));
22
+
23
+ export default app;
@@ -0,0 +1,57 @@
1
+ import { Hono } from "hono";
2
+ import { and, desc, eq } from "drizzle-orm";
3
+ import { requireAuth, type NerdHonoEnv } from "@nerdsystem/sdk";
4
+ import { db, schema } from "../db";
5
+
6
+ // Every route here needs a signed-in user. c.var.user is set by the SDK.
7
+ const todos = new Hono<NerdHonoEnv>();
8
+ todos.use("*", requireAuth());
9
+
10
+ todos.get("/", async (c) => {
11
+ const rows = await db(c.env.DB)
12
+ .select()
13
+ .from(schema.todos)
14
+ .where(eq(schema.todos.userId, c.var.user!.id))
15
+ .orderBy(desc(schema.todos.createdAt))
16
+ .all();
17
+ return c.json({ todos: rows });
18
+ });
19
+
20
+ 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
+ }
25
+ const row = await db(c.env.DB)
26
+ .insert(schema.todos)
27
+ .values({ userId: c.var.user!.id, title: body.title.trim() })
28
+ .returning()
29
+ .get();
30
+ return c.json({ todo: row }, 201);
31
+ });
32
+
33
+ todos.patch("/:id", async (c) => {
34
+ const id = Number(c.req.param("id"));
35
+ const body = (await c.req.json().catch(() => ({}))) as { done?: unknown };
36
+ const row = await db(c.env.DB)
37
+ .update(schema.todos)
38
+ .set({ done: Boolean(body.done) })
39
+ .where(and(eq(schema.todos.id, id), eq(schema.todos.userId, c.var.user!.id)))
40
+ .returning()
41
+ .get();
42
+ if (!row) return c.json({ error: { code: "not_found", message: "Todo not found" } }, 404);
43
+ return c.json({ todo: row });
44
+ });
45
+
46
+ todos.delete("/:id", async (c) => {
47
+ const id = Number(c.req.param("id"));
48
+ const row = await db(c.env.DB)
49
+ .delete(schema.todos)
50
+ .where(and(eq(schema.todos.id, id), eq(schema.todos.userId, c.var.user!.id)))
51
+ .returning({ id: schema.todos.id })
52
+ .get();
53
+ if (!row) return c.json({ error: { code: "not_found", message: "Todo not found" } }, 404);
54
+ return c.json({ deleted: true });
55
+ });
56
+
57
+ export default todos;
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
7
+ "jsx": "react-jsx",
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "verbatimModuleSyntax": true,
11
+ "isolatedModules": true,
12
+ "skipLibCheck": true,
13
+ "noEmit": true,
14
+ "composite": true,
15
+ "rootDir": "."
16
+ },
17
+ "include": ["src/client"]
18
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "files": [],
3
+ "references": [{ "path": "./tsconfig.worker.json" }, { "path": "./tsconfig.client.json" }]
4
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "ESNext",
5
+ "moduleResolution": "Bundler",
6
+ "lib": ["ES2022"],
7
+ "types": ["@cloudflare/workers-types"],
8
+ "strict": true,
9
+ "noUncheckedIndexedAccess": true,
10
+ "verbatimModuleSyntax": true,
11
+ "isolatedModules": true,
12
+ "skipLibCheck": true,
13
+ "noEmit": true,
14
+ "composite": true,
15
+ "rootDir": "."
16
+ },
17
+ "include": ["src/server", "vite.config.ts", "drizzle.config.ts"]
18
+ }
@@ -0,0 +1,7 @@
1
+ import { cloudflare } from "@cloudflare/vite-plugin";
2
+ import react from "@vitejs/plugin-react";
3
+ import { defineConfig } from "vite";
4
+
5
+ export default defineConfig({
6
+ plugins: [react(), cloudflare()],
7
+ });