create-tupik 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # create-tupik
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Scaffold a new **Tupik** app for Node.js, Bun or Cloudflare Workers.
4
+
5
+ ## Usage
6
+
7
+ ```bash
8
+ pnpm create tupik my-api --template node
9
+ # or
10
+ npm create tupik@latest my-api -- --template bun
11
+ npx create-tupik edge-api -t workers
12
+ ```
13
+
14
+ ```text
15
+ Usage: create-tupik [directory] [options]
16
+
17
+ -t, --template <name> node | bun | workers
18
+ -f, --force write into a non-empty directory
19
+ -h, --help show this help
20
+ -v, --version print the version
21
+ ```
22
+
23
+ Missing directory or template are asked interactively. The CLI only writes files; it never runs
24
+ `install`, so it works offline. Then:
25
+
26
+ ```bash
27
+ cd my-api
28
+ npm install
29
+ npm run dev
30
+ ```
31
+
32
+ Requires Node.js 22.12 or later.
33
+
34
+ ## License
35
+
36
+ MIT
@@ -0,0 +1 @@
1
+
@@ -0,0 +1 @@
1
+
package/dist/index.mjs ADDED
@@ -0,0 +1,391 @@
1
+ #!/usr/bin/env node
2
+ import process from 'node:process';
3
+ import { mkdir, writeFile, readdir } from 'node:fs/promises';
4
+ import { resolve, join, dirname, relative, basename } from 'node:path';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { readFileSync, existsSync, readdirSync } from 'node:fs';
7
+
8
+ const SKILL_DIR = ".claude/skills/tupik";
9
+ const SKILL_PATH = `${SKILL_DIR}/SKILL.md`;
10
+ const SKILL_SOURCES = [new URL("./skill/", import.meta.url), new URL("../../../skills/tupik/", import.meta.url)];
11
+ function skillRoot() {
12
+ const root = SKILL_SOURCES.find((candidate) => existsSync(new URL("SKILL.md", candidate)));
13
+ if (root === void 0) throw new Error("create-tupik: the Tupik skill is missing from the package; reinstall create-tupik");
14
+ return root;
15
+ }
16
+ function readSkill(root = skillRoot()) {
17
+ const files = { "SKILL.md": readFileSync(new URL("SKILL.md", root), "utf8") };
18
+ const references = new URL("references/", root);
19
+ if (existsSync(references)) {
20
+ for (const name of readdirSync(references).filter((entry) => entry.endsWith(".md")).sort()) {
21
+ files[`references/${name}`] = readFileSync(new URL(name, references), "utf8");
22
+ }
23
+ }
24
+ return files;
25
+ }
26
+ function section(markdown, heading) {
27
+ const lines = markdown.split("\n");
28
+ const start = lines.indexOf(`## ${heading}`);
29
+ if (start === -1) throw new Error(`create-tupik: the Tupik skill has no "## ${heading}" section`);
30
+ const end = lines.findIndex((line, index) => index > start && line.startsWith("## "));
31
+ return lines.slice(start + 1, end === -1 ? void 0 : end).join("\n").trim();
32
+ }
33
+ function agents(skill) {
34
+ return `# AGENTS.md
35
+
36
+ Rules for coding agents (and people) working on this Tupik API. They come from the Tupik skill in
37
+ \`${SKILL_PATH}\`, which also has recipes, the middleware list and common mistakes with their fixes.
38
+
39
+ ## Non-negotiable rules
40
+
41
+ ${section(skill, "Non-negotiable rules")}
42
+
43
+ ## Commands
44
+
45
+ | Command | What it does |
46
+ | --- | --- |
47
+ | \`npm run typecheck\` | Type-checks the app (a route without \`access\` does not compile) |
48
+ | \`npm run audit\` | \`tupik audit\`: security report of the routes; fails on errors |
49
+ | \`npm run data-map\` | Personal data map (LGPD/GDPR) in \`docs/data-map.md\` |
50
+
51
+ ## Before you finish
52
+
53
+ ${section(skill, "Before you finish")}
54
+ `;
55
+ }
56
+ function llms(name, runtime, skill) {
57
+ const references = Object.keys(skill).filter((path) => path.startsWith("references/")).map((path) => `- [${path.slice("references/".length, -".md".length)}](${SKILL_DIR}/${path})`).join("\n");
58
+ return `# ${name}
59
+
60
+ > A Tupik API for ${runtime}. Routes declare who may call them (\`access\`), validate their input and
61
+ > classify personal data; \`tupik audit\` checks them.
62
+
63
+ Read \`AGENTS.md\` first: it lists the rules every change must follow.
64
+
65
+ ## Code
66
+
67
+ - [src/app.ts](src/app.ts): routes (\`createModule\`) and the app (\`createApp\`, \`authenticate\`)
68
+ - [src/index.ts](src/index.ts): runtime entry point
69
+ - [AGENTS.md](AGENTS.md): rules and commands
70
+
71
+ ## Tupik skill
72
+
73
+ - [SKILL.md](${SKILL_PATH}): how to write Tupik routes correctly
74
+ ${references}
75
+
76
+ ## Tupik docs
77
+
78
+ - [Tupik](https://tupik.org/llms.txt): framework documentation for language models
79
+ `;
80
+ }
81
+ function agentFiles(name, runtime, skill = readSkill()) {
82
+ const main = skill["SKILL.md"];
83
+ if (main === void 0) throw new Error("create-tupik: the Tupik skill has no SKILL.md");
84
+ const files = { "AGENTS.md": agents(main), "llms.txt": llms(name, runtime, skill) };
85
+ for (const [path, contents] of Object.entries(skill)) files[`${SKILL_DIR}/${path}`] = contents;
86
+ return files;
87
+ }
88
+
89
+ const TEMPLATES = ["node", "bun", "workers"];
90
+ const TUPIK_RANGE = "^1.0.0";
91
+ const COMPATIBILITY_DATE = "2025-11-01";
92
+ const TUPIK_BIN = "node_modules/@tupik/openapi/bin/tupik.mjs";
93
+ function isTemplate(value) {
94
+ return TEMPLATES.includes(value);
95
+ }
96
+ const SPECS = {
97
+ node: {
98
+ adapter: "@tupik/node",
99
+ scripts: { dev: "tsx watch src/index.ts", build: "tsc", start: "node dist/index.js", typecheck: "tsc --noEmit" },
100
+ devDependencies: { "@types/node": "^22.0.0", tsx: "^4.19.0", typescript: "^5.6.0" },
101
+ types: ["node"],
102
+ tsRunner: "tsx",
103
+ runtime: "Node.js",
104
+ run: "npm run dev",
105
+ entry: `import { serve } from '@tupik/node';
106
+ import { app } from './app.js';
107
+
108
+ const port = Number(process.env['PORT'] ?? 3000);
109
+ const server = serve(app, { port });
110
+
111
+ server.on('listening', () => {
112
+ console.log('Tupik listening on http://127.0.0.1:' + port);
113
+ });
114
+ `
115
+ },
116
+ bun: {
117
+ adapter: "@tupik/bun",
118
+ scripts: { dev: "bun --watch run src/index.ts", start: "bun run src/index.ts", typecheck: "tsc --noEmit" },
119
+ devDependencies: { "@types/bun": "latest", typescript: "^5.6.0" },
120
+ types: ["bun"],
121
+ tsRunner: "bun",
122
+ runtime: "Bun",
123
+ run: "bun run src/index.ts",
124
+ entry: `import { serveBun } from '@tupik/bun';
125
+ import { app } from './app.js';
126
+
127
+ // serveBun wraps Bun.serve with the app's fetch handler.
128
+ const port = Number(process.env['PORT'] ?? 3000);
129
+ serveBun(app, { port });
130
+
131
+ console.log('Tupik listening on http://localhost:' + port);
132
+ `
133
+ },
134
+ workers: {
135
+ adapter: "@tupik/edge",
136
+ scripts: { dev: "wrangler dev", deploy: "wrangler deploy", typecheck: "tsc --noEmit" },
137
+ devDependencies: { "@cloudflare/workers-types": "^4.0.0", tsx: "^4.19.0", typescript: "^5.6.0", wrangler: "^4.0.0" },
138
+ types: ["@cloudflare/workers-types"],
139
+ tsRunner: "tsx",
140
+ runtime: "Cloudflare Workers",
141
+ run: "npm run dev",
142
+ entry: `import { createEdgeWorker } from '@tupik/edge';
143
+ import { app } from './app.js';
144
+
145
+ export default createEdgeWorker(app);
146
+ `
147
+ }
148
+ };
149
+ function appSource(spec) {
150
+ return `import { createApp, createModule } from '@tupik/core';
151
+
152
+ interface User {
153
+ id: string;
154
+ }
155
+
156
+ // The principal type every route sees as \`ctx.principal\`.
157
+ declare module '@tupik/core' {
158
+ interface TupikRegister {
159
+ principal: User;
160
+ }
161
+ }
162
+
163
+ // Every route declares who may call it (\`access\`): see AGENTS.md.
164
+ const hello = createModule()
165
+ .get('/', { access: 'public', handler: () => ({ message: 'Hello from Tupik on ${spec.runtime}' }) })
166
+ .get('/hello/:name', { access: 'public', handler: (ctx) => ctx.json({ hello: ctx.params.name }) });
167
+
168
+ const me = createModule('/me').get('/', {
169
+ access: 'authenticated',
170
+ handler: (ctx) => ({ id: ctx.principal.id }),
171
+ });
172
+
173
+ export const app = createApp({
174
+ // Return the signed-in principal (from a session cookie or a verified JWT) or null.
175
+ // While it returns null, routes with access 'authenticated' answer 401.
176
+ authenticate: (): User | null => null,
177
+ }).register(hello, me);
178
+ `;
179
+ }
180
+ function json(value) {
181
+ return JSON.stringify(value, null, 2) + "\n";
182
+ }
183
+ function packageJson(name, spec) {
184
+ return json({
185
+ name,
186
+ version: "0.0.0",
187
+ private: true,
188
+ type: "module",
189
+ scripts: {
190
+ ...spec.scripts,
191
+ audit: `${spec.tsRunner} ${TUPIK_BIN} audit src/app.ts`,
192
+ "data-map": `${spec.tsRunner} ${TUPIK_BIN} data-map src/app.ts --out docs/data-map.md`
193
+ },
194
+ dependencies: { "@tupik/core": TUPIK_RANGE, [spec.adapter]: TUPIK_RANGE },
195
+ devDependencies: { ...spec.devDependencies, "@tupik/openapi": TUPIK_RANGE, "@tupik/testing": TUPIK_RANGE }
196
+ });
197
+ }
198
+ function tsconfig(spec) {
199
+ return json({
200
+ compilerOptions: {
201
+ target: "ES2022",
202
+ module: "NodeNext",
203
+ moduleResolution: "NodeNext",
204
+ lib: ["ES2023", "DOM", "DOM.Iterable"],
205
+ types: spec.types,
206
+ strict: true,
207
+ noUncheckedIndexedAccess: true,
208
+ exactOptionalPropertyTypes: true,
209
+ noImplicitOverride: true,
210
+ skipLibCheck: true,
211
+ outDir: "dist",
212
+ rootDir: "src"
213
+ },
214
+ include: ["src"]
215
+ });
216
+ }
217
+ function readme(name, template, spec) {
218
+ const install = template === "bun" ? "bun install" : "npm install";
219
+ return `# ${name}
220
+
221
+ A [Tupik](https://tupik.org) app for ${spec.runtime} (template \`${template}\`).
222
+
223
+ \`\`\`sh
224
+ ${install}
225
+ ${spec.run}
226
+ \`\`\`
227
+
228
+ Then open http://localhost:${template === "workers" ? "8787" : "3000"}/hello/tupik.
229
+
230
+ Routes live in \`src/app.ts\`, built with \`createModule()\` and mounted with \`createApp().register()\`;
231
+ \`src/index.ts\` serves the app on ${spec.runtime}.
232
+ Every route declares \`access\` (\`'public'\`, \`'authenticated'\` or a policy); a route without it does not compile.
233
+
234
+ \`npm run audit\` checks the routes (public routes, personal data, writes without rate limit, ids without an owner rule);
235
+ \`npm run data-map\` writes the personal data map to \`docs/data-map.md\`. Rules for coding agents: \`AGENTS.md\`.
236
+ `;
237
+ }
238
+ const GITIGNORE = `node_modules
239
+ dist
240
+ .wrangler
241
+ .dev.vars
242
+ .env
243
+ *.log
244
+ `;
245
+ function wrangler(name) {
246
+ return `{
247
+ // Cloudflare Workers configuration: https://developers.cloudflare.com/workers/wrangler/configuration/
248
+ "$schema": "node_modules/wrangler/config-schema.json",
249
+ "name": ${JSON.stringify(name)},
250
+ "main": "src/index.ts",
251
+ "compatibility_date": "${COMPATIBILITY_DATE}"
252
+ }
253
+ `;
254
+ }
255
+ function renderTemplate(template, name) {
256
+ const spec = SPECS[template];
257
+ const files = {
258
+ "package.json": packageJson(name, spec),
259
+ "tsconfig.json": tsconfig(spec),
260
+ "src/app.ts": appSource(spec),
261
+ "src/index.ts": spec.entry,
262
+ "README.md": readme(name, template, spec),
263
+ ".gitignore": GITIGNORE,
264
+ ...agentFiles(name, spec.runtime)
265
+ };
266
+ if (template === "workers") files["wrangler.jsonc"] = wrangler(name);
267
+ return files;
268
+ }
269
+
270
+ const VERSION = "1.0.0";
271
+ const DEFAULT_NAME = "tupik-app";
272
+ const DEFAULT_TEMPLATE = "node";
273
+ class CliError extends Error {
274
+ constructor(message) {
275
+ super(message);
276
+ this.name = "CliError";
277
+ }
278
+ }
279
+ const HELP = `Usage: create-tupik [directory] [options]
280
+
281
+ Scaffold a new Tupik app.
282
+
283
+ Options:
284
+ -t, --template <name> ${TEMPLATES.join(" | ")}
285
+ -f, --force write into a non-empty directory
286
+ -h, --help show this help
287
+ -v, --version print the version
288
+
289
+ Missing directory or template are asked interactively.
290
+
291
+ Examples:
292
+ pnpm create tupik my-api --template node
293
+ npx create-tupik edge-api -t workers
294
+ `;
295
+ function parseArgs(argv) {
296
+ const options = { force: false, help: false, version: false };
297
+ for (let i = 0; i < argv.length; i++) {
298
+ const arg = argv[i];
299
+ if (arg === void 0) continue;
300
+ if (arg === "-h" || arg === "--help") options.help = true;
301
+ else if (arg === "-v" || arg === "--version") options.version = true;
302
+ else if (arg === "-f" || arg === "--force") options.force = true;
303
+ else if (arg === "-t" || arg === "--template") {
304
+ const value = argv[++i];
305
+ if (value === void 0 || value.startsWith("-")) throw new CliError("Option " + arg + " requires a value");
306
+ options.template = value;
307
+ } else if (arg.startsWith("--template=")) options.template = arg.slice("--template=".length);
308
+ else if (arg.startsWith("-")) throw new CliError("Unknown option: " + arg);
309
+ else if (options.dir === void 0) options.dir = arg;
310
+ else throw new CliError("Unexpected argument: " + arg);
311
+ }
312
+ return options;
313
+ }
314
+ function toPackageName(dir) {
315
+ const slug = basename(resolve(dir)).toLowerCase().replace(/[^a-z0-9._~-]+/g, "-").replace(/^[._-]+|-+$/g, "");
316
+ return slug === "" ? DEFAULT_NAME : slug;
317
+ }
318
+ function assertTemplate(value) {
319
+ if (!isTemplate(value)) {
320
+ throw new CliError('Invalid template "' + value + '". Use one of: ' + TEMPLATES.join(", "));
321
+ }
322
+ return value;
323
+ }
324
+ async function prompt(options, io) {
325
+ if (options.dir !== void 0 && options.template !== void 0) {
326
+ return { dir: options.dir, template: assertTemplate(options.template) };
327
+ }
328
+ const rl = createInterface({ input: io.input, terminal: false });
329
+ const lines = rl[Symbol.asyncIterator]();
330
+ const ask = async (question) => {
331
+ io.stdout.write(question);
332
+ const next = await lines.next();
333
+ return next.done === true ? "" : String(next.value).trim();
334
+ };
335
+ try {
336
+ const dir = options.dir ?? (await ask("Project name (" + DEFAULT_NAME + "): ") || DEFAULT_NAME);
337
+ const template = options.template ?? (await ask("Template [" + TEMPLATES.join("/") + "] (" + DEFAULT_TEMPLATE + "): ") || DEFAULT_TEMPLATE);
338
+ return { dir, template: assertTemplate(template) };
339
+ } finally {
340
+ rl.close();
341
+ }
342
+ }
343
+ async function isEmptyDir(path) {
344
+ try {
345
+ return (await readdir(path)).length === 0;
346
+ } catch (error) {
347
+ if (error.code === "ENOENT") return true;
348
+ throw error;
349
+ }
350
+ }
351
+ async function run(argv, io) {
352
+ try {
353
+ const options = parseArgs(argv);
354
+ if (options.help) {
355
+ io.stdout.write(HELP);
356
+ return 0;
357
+ }
358
+ if (options.version) {
359
+ io.stdout.write(VERSION + "\n");
360
+ return 0;
361
+ }
362
+ if (options.template !== void 0) assertTemplate(options.template);
363
+ const { dir, template } = await prompt(options, io);
364
+ const target = resolve(io.cwd, dir);
365
+ if (!options.force && !await isEmptyDir(target)) {
366
+ throw new CliError('Directory "' + dir + '" is not empty. Use --force to write into it.');
367
+ }
368
+ const files = renderTemplate(template, toPackageName(target));
369
+ for (const [file, contents] of Object.entries(files)) {
370
+ const path = join(target, file);
371
+ await mkdir(dirname(path), { recursive: true });
372
+ await writeFile(path, contents);
373
+ }
374
+ const shown = relative(io.cwd, target) || ".";
375
+ io.stdout.write(
376
+ "Created " + template + " app in " + shown + "\n\nNext steps:\n cd " + shown + "\n " + (template === "bun" ? "bun install\n bun run src/index.ts" : "npm install\n npm run dev") + "\n"
377
+ );
378
+ return 0;
379
+ } catch (error) {
380
+ const message = error instanceof Error ? error.message : String(error);
381
+ io.stderr.write("create-tupik: " + message + "\n");
382
+ return 1;
383
+ }
384
+ }
385
+
386
+ process.exitCode = await run(process.argv.slice(2), {
387
+ cwd: process.cwd(),
388
+ input: process.stdin,
389
+ stdout: process.stdout,
390
+ stderr: process.stderr
391
+ });
@@ -0,0 +1,173 @@
1
+ ---
2
+ name: tupik
3
+ description: Write and review TypeScript APIs built with the Tupik framework (@tupik/core, @tupik/middleware, @tupik/schema, @tupik/testing and the other @tupik/* packages). Use when adding or changing routes, middleware, auth, sessions, data classes, error catalogs, webhooks or tests in a Tupik app, or when reviewing code that imports @tupik/*.
4
+ ---
5
+
6
+ # Tupik
7
+
8
+ Tupik is a TypeScript web framework that is secure by construction: every route says who may call it,
9
+ validates its input, classifies sensitive fields and raises typed errors. The rules below are what make
10
+ that true. Code that breaks them may still compile; it is still wrong.
11
+
12
+ ## Mental model
13
+
14
+ - **Module** (`createModule(prefix)`): a fluent builder of routes. `.use(middleware)` and `.access(rule)`
15
+ apply to the routes declared **after** the call, so put them first.
16
+ - **App** (`createApp(options).register(...modules)`): owns `authenticate` (request to principal or `null`),
17
+ response shaping and the error handling. `app.fetch(request, env?, ctx?)` is the only entry point; drivers
18
+ (`@tupik/node`, `@tupik/bun`, `@tupik/edge`, `@tupik/hono`) and tests all call it.
19
+ - **Request order:** app `onRequest`, module `onRequest`, body parse, **validation (400)**, `preHandler` hooks,
20
+ app middleware, module middleware, **access** (`authenticate` then 401, `check` then 403, `owner` then 404),
21
+ handler, response shaping (undeclared fields cut, `secret` fields removed), `onSend` hooks. Middleware that
22
+ needs the caller (rate limit or idempotency per user, tenant membership) uses `await ctx.getPrincipal()`:
23
+ it runs `authenticate` once per request and `access` reuses the result.
24
+ - **Principal:** declare its type once with `TupikRegister`; `ctx.principal` is then typed per route
25
+ (`null` on public routes, always set on authenticated ones).
26
+
27
+ ## Non-negotiable rules
28
+
29
+ 1. **Every route declares `access`.** Use `'authenticated'`, a policy `(ctx) => boolean`, or
30
+ `{ auth, check, owner }`. A route without it does not compile and `register` throws.
31
+ 2. **Never `access: 'public'` for convenience.** Public is a decision for routes anyone may call
32
+ (health, sign-in, sign-up, signed webhooks, public catalog). If the route touches user data, it is not public.
33
+ 3. **Records of a user check their owner.** A route that reads or changes a record by id uses
34
+ `access: { owner: (ctx) => ownerIdOf(ctx.params.id) }` (anyone else gets 404) or scopes the query by
35
+ `ctx.principal.id` / the tenant. Never trust an id from the request alone.
36
+ 4. **Validate every input.** Give `schema.body`, `schema.query` and `schema.params` a Standard Schema
37
+ (Zod, Valibot, ArkType, `@tupik/schema` adapters). Never read `ctx.req.json()` by hand.
38
+ 5. **Declare the response and classify sensitive fields.** `schema.response[status]` plus
39
+ `classify(schema, { email: 'pii', diagnosis: 'health', passwordHash: 'secret' })`. Undeclared fields
40
+ are cut; `secret` fields never leave the API. The classes live on the fields: `z.array(schema)`,
41
+ `.extend()`, `.pick()` and nesting keep them.
42
+ 6. **Errors come from the catalog.** Declare codes once with `defineErrors`, list them in the route
43
+ `errors` and raise them with `return ctx.fail('CODE')`. Do not build error JSON by hand.
44
+ 7. **Rate limit writes and sign-in.** `rateLimit({ windowMs, limit, trust })` with `trust: 'cloudflare'` or
45
+ `'proxy'` only when that proxy is really in front of the app; otherwise pass `keyGenerator`.
46
+ 8. **Secrets come from the environment.** Read them through `@tupik/env` (`defineEnv`, `secret()`), never
47
+ as literals in the code.
48
+ 9. **Never log request bodies, headers, tokens or classified fields.** Log an allow-list of fields or use the
49
+ redacting loggers (`logger()` from `@tupik/middleware`, `createLogger` from `@tupik/infra`).
50
+ 10. **Passwords use `@tupik/password`** (Argon2id). Never SHA-256, never a homemade hash.
51
+
52
+ ## Minimal app
53
+
54
+ ```ts compile
55
+ import { classify, createApp, createModule, defineErrors } from '@tupik/core';
56
+ import { rateLimit } from '@tupik/middleware';
57
+ import { z } from 'zod';
58
+
59
+ interface User {
60
+ id: string;
61
+ }
62
+
63
+ declare module '@tupik/core' {
64
+ interface TupikRegister {
65
+ principal: User;
66
+ }
67
+ }
68
+
69
+ interface NoteRow { id: string; ownerId: string; title: string; text: string; locked: boolean }
70
+ const notes = new Map<string, NoteRow>();
71
+
72
+ const Note = classify(z.object({ id: z.string(), title: z.string(), text: z.string() }), { text: 'pii' });
73
+ const NoteInput = z.object({ title: z.string().min(1).max(200), text: z.string().max(10_000) });
74
+ const NoteParams = z.object({ id: z.string().min(1).max(64) });
75
+ const Errors = defineErrors({
76
+ NOTE_NOT_FOUND: { status: 404, title: 'Note not found' },
77
+ NOTE_LOCKED: { status: 409, title: 'The note is locked' },
78
+ });
79
+
80
+ const health = createModule().get('/health', { access: 'public', handler: () => ({ ok: true }) });
81
+
82
+ const notesModule = createModule('/notes')
83
+ .use(rateLimit({ windowMs: 60_000, limit: 60, trust: 'cloudflare' }))
84
+ .post('/', {
85
+ access: 'authenticated',
86
+ schema: { body: NoteInput, response: { 201: Note } },
87
+ handler: (ctx) => {
88
+ const note: NoteRow = { id: crypto.randomUUID(), ownerId: ctx.principal.id, locked: false, ...ctx.body };
89
+ notes.set(note.id, note);
90
+ return ctx.status(201).json(note); // ownerId and locked are cut: Note does not declare them
91
+ },
92
+ })
93
+ .patch('/:id', {
94
+ access: { owner: (ctx) => notes.get(ctx.params.id)?.ownerId },
95
+ schema: { params: NoteParams, body: NoteInput.partial(), response: { 200: Note } },
96
+ errors: [Errors.NOTE_NOT_FOUND, Errors.NOTE_LOCKED],
97
+ handler: (ctx) => {
98
+ const note = notes.get(ctx.params.id);
99
+ if (note === undefined) return ctx.fail('NOTE_NOT_FOUND'); // deleted between the owner check and now
100
+ if (note.locked) return ctx.fail('NOTE_LOCKED');
101
+ Object.assign(note, ctx.body);
102
+ return note;
103
+ },
104
+ });
105
+
106
+ export const app = createApp({
107
+ authenticate: (ctx): User | null => (ctx.req.headers.get('authorization') === 'Bearer demo' ? { id: 'u1' } : null),
108
+ schemaConverter: (schema) => (schema instanceof z.ZodType ? z.toJSONSchema(schema) : undefined),
109
+ }).register(health, notesModule);
110
+ ```
111
+
112
+ `schemaConverter` lets the engine learn the fields of a Zod response schema so it can cut the rest. Without a
113
+ converter (or a schema that exposes JSON Schema), list the fields: `classify(schema, classes, { fields: [...] })`.
114
+
115
+ ## Recipes
116
+
117
+ Short, compiling versions live in the references; use them as the starting point.
118
+
119
+ | Need | Use | Reference |
120
+ | --- | --- | --- |
121
+ | CRUD where each user sees only their records | `access: { owner }`, list scoped by `ctx.principal.id` | [recipes.md](references/recipes.md#crud-with-owner) |
122
+ | Cookie sign-in for a browser app | `session()` + `csrf({ session })` + `@tupik/password` | [recipes.md](references/recipes.md#session-and-csrf) |
123
+ | Workspaces / SaaS tenants | `tenant({ verify })`, queries filtered by tenant id | [recipes.md](references/recipes.md#multi-tenant) |
124
+ | Provider webhooks and retries | `webhookSignature` + `idempotency` | [recipes.md](references/recipes.md#webhook-and-idempotency) |
125
+ | Cloudflare Workers + D1 | `defineEnv` with `binding.d1()`, `withEnv`, `getEnv` | [recipes.md](references/recipes.md#cloudflare-workers-and-d1) |
126
+ | OpenAPI and a typed client | `generateOpenApiDocument`, `createTypedClient<typeof app>` | [recipes.md](references/recipes.md#openapi-and-typed-client) |
127
+ | Access rules in depth | keywords, policies, `auth: 'optional'`, `ownerMismatch` | [access.md](references/access.md) |
128
+ | Data classes, response shaping, errors | `classify`, `response` modes, `defineErrors` | [data-and-errors.md](references/data-and-errors.md) |
129
+ | Which middleware, with which safe options | the full list | [middleware.md](references/middleware.md) |
130
+ | Audit, fuzz, lint, generated tests | `tupik audit`, `tupik fuzz`, `tupik-lint` | [tooling.md](references/tooling.md) |
131
+
132
+ ## Before you finish
133
+
134
+ Run these and fix every finding before calling the change done:
135
+
136
+ 1. Typecheck passes (a route without `access` is a type error).
137
+ 2. `tupik audit <app module>` has no `error` (in a create-tupik project: `npm run audit`). Read each `warning`:
138
+ `id-without-owner` and `write-without-rate-limit` are almost always real bugs. Accept a finding only on the
139
+ route and with a reason: `tags: [acceptAudit('public-sensitive-data', 'sign-up receives the e-mail')]`.
140
+ 3. `tupik fuzz <app module> --principals principals.json --fixtures fixtures.json` reports 0 failures.
141
+ 4. `tupik-lint src` is clean (`tupik/no-unscoped-lookup`, `no-raw-row-response`, `no-log-request-data`,
142
+ `no-hardcoded-secret`).
143
+ 5. The access tests from `generateAccessTests(app, { principals, fixtures })` run in the test suite and pass,
144
+ and every new `owner` route has a fixture.
145
+ 6. Every new route has `access`, input schemas, a response schema, and classified `pii`/`health`/`secret` fields.
146
+
147
+ ## Common AI mistakes
148
+
149
+ | Mistake | Correction |
150
+ | --- | --- |
151
+ | `access: 'public'` to make a 401 go away | Fix `authenticate` or the test credentials; keep `'authenticated'` or an owner rule |
152
+ | `access: 'authenticated'` on `GET /things/:id` | `access: { owner: (ctx) => ownerOf(ctx.params.id) }` or filter by `ctx.principal.id` |
153
+ | `.use(mw)` after the routes | Middleware covers only routes declared after `.use`; move it up |
154
+ | Returning the database row as is | Declare `schema.response`; the shaper cuts fields it does not declare |
155
+ | `ctx.status(409).json({ error: '...' })` | `defineErrors` + `errors: [...]` + `return ctx.fail('CODE')` |
156
+ | `rateLimit({ windowMs, limit })` with no key | Add `trust` (only behind that proxy) or `keyGenerator` |
157
+ | `const SECRET = 'abc...'` or `process.env.X!` | `defineEnv({ X: secret({ minLength: 32 }) }).parse()` |
158
+ | `console.log(ctx.body)` / logging headers | Log ids and an allow-list; use the redacting loggers |
159
+ | `crypto.subtle.digest('SHA-256', password)` | `hashPassword` / `verifyPassword` / `needsRehash` from `@tupik/password` |
160
+ | Trusting `x-workspace-id` directly | `tenant({ from: 'header', verify })`; `verify` checks membership |
161
+ | `cors({ origin: '*', credentials: true })` | List the origins; Tupik throws on this combination |
162
+ | Parsing the body with `await ctx.req.json()` | `schema.body` and read the typed `ctx.body` |
163
+
164
+ The same mistakes with code, and what Tupik reports for each, are in [mistakes.md](references/mistakes.md).
165
+
166
+ ## References
167
+
168
+ - [references/access.md](references/access.md): access rules, principal, owner checks, policies.
169
+ - [references/data-and-errors.md](references/data-and-errors.md): validation, data classes, response shaping, error catalog.
170
+ - [references/recipes.md](references/recipes.md): CRUD with owner, session and CSRF, multi-tenant, webhooks, D1, passwords, OpenAPI and client.
171
+ - [references/middleware.md](references/middleware.md): every middleware and its safe configuration.
172
+ - [references/tooling.md](references/tooling.md): audit, fuzz, lint, access tests, contract checks, MCP.
173
+ - [references/mistakes.md](references/mistakes.md): wrong code next to the fix.