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.
@@ -0,0 +1,132 @@
1
+ # Access rules
2
+
3
+ Every route has exactly one access rule: its own `access` option, or the module default set with
4
+ `createModule(prefix, { access })` or `.access(rule)` (which covers the routes declared after it). There is
5
+ no implicit public route: without a rule the route is a type error and `register` throws with a message
6
+ that names the route and the fix.
7
+
8
+ ## The forms
9
+
10
+ | Rule | Who passes | `ctx.principal` | Denial |
11
+ | --- | --- | --- | --- |
12
+ | `'public'` | everyone; `authenticate` does not run | `null` | none |
13
+ | `'authenticated'` | a principal from `authenticate` | the principal | 401 |
14
+ | `(ctx) => boolean \| Response` (policy) | a principal for whom the policy returns `true` | the principal | 401, then 403 (or the returned `Response`) |
15
+ | `{ check, owner, ownerMismatch }` | a principal, then `check`, then `owner` | the principal | 401, 403, then 404 |
16
+ | `{ auth: 'optional', check? }` | everyone; the principal is resolved when present | principal or `null` | 403 from `check` |
17
+
18
+ `owner` returns the owner id of the requested record. `undefined`/`null` means "no such record" (404). An id
19
+ different from the principal id answers 404 by default, so the existence of someone else's record is not
20
+ revealed; `ownerMismatch: 403` changes that. The principal id is `principal.id`, or what
21
+ `createApp({ principalId })` returns. `owner` cannot be combined with `auth: 'optional'`.
22
+
23
+ Access runs after the middleware, so a session or JWT middleware can prepare what `authenticate` reads, and
24
+ CORS, logging and rate limiting see the 401/403 responses. Validation runs before access: an invalid request
25
+ gets its 400 before the 401.
26
+
27
+ ## The principal
28
+
29
+ ```ts compile
30
+ import { createApp, createModule } from '@tupik/core';
31
+
32
+ interface User {
33
+ id: string;
34
+ role: 'member' | 'admin';
35
+ }
36
+
37
+ // Declared once: every module types ctx.principal with it.
38
+ declare module '@tupik/core' {
39
+ interface TupikRegister {
40
+ principal: User;
41
+ }
42
+ }
43
+
44
+ const users = new Map<string, User>([['token-ana', { id: 'ana', role: 'admin' }]]);
45
+
46
+ const admin = createModule('/admin', { access: (ctx) => ctx.principal.role === 'admin' })
47
+ .get('/stats', { handler: () => ({ users: users.size }) })
48
+ // A route's own rule wins over the module default.
49
+ .get('/ping', { access: 'authenticated', handler: (ctx) => ({ pong: ctx.principal.id }) });
50
+
51
+ export const app = createApp({
52
+ // Return the principal or null; never throw for a missing or bad credential.
53
+ authenticate: (ctx) => {
54
+ const token = ctx.req.headers.get('authorization')?.replace(/^Bearer /, '');
55
+ return token === undefined ? null : users.get(token) ?? null;
56
+ },
57
+ }).register(admin);
58
+ ```
59
+
60
+ ## Owner checks (BOLA)
61
+
62
+ Reading or changing a record by id without checking who owns it is the first item of the OWASP API Top 10.
63
+ Three correct shapes:
64
+
65
+ ```ts compile
66
+ import { createApp, createModule } from '@tupik/core';
67
+ import { z } from 'zod';
68
+
69
+ interface User { id: string }
70
+ declare module '@tupik/core' {
71
+ interface TupikRegister { principal: User }
72
+ }
73
+
74
+ interface Doc { id: string; ownerId: string; title: string }
75
+ const docs = new Map<string, Doc>();
76
+ const Params = z.object({ id: z.string().min(1).max(64) });
77
+
78
+ const documents = createModule('/docs')
79
+ // 1. owner rule: 404 for anyone but the owner, before the handler runs.
80
+ .get('/:id', {
81
+ access: { owner: (ctx) => docs.get(ctx.params.id)?.ownerId },
82
+ schema: { params: Params },
83
+ handler: (ctx) => docs.get(ctx.params.id), // a missing record already got 404 from owner
84
+ })
85
+ // 2. list scoped by the principal: there is no id to check.
86
+ .get('/', {
87
+ access: 'authenticated',
88
+ handler: (ctx) => [...docs.values()].filter((doc) => doc.ownerId === ctx.principal.id),
89
+ })
90
+ // 3. owner rule as the module default for every route below.
91
+ .access({ owner: (ctx) => docs.get(String(ctx.params['id']))?.ownerId })
92
+ .delete('/:id', {
93
+ schema: { params: Params },
94
+ handler: (ctx) => {
95
+ docs.delete(ctx.params.id);
96
+ return new Response(null, { status: 204 });
97
+ },
98
+ });
99
+
100
+ export const app = createApp({ authenticate: (): User | null => null }).register(documents);
101
+ ```
102
+
103
+ The owner rule may be `async` (a database lookup). When the handler needs the same row, read it again or keep
104
+ it in `ctx.rawStore`; do not skip the rule to save a query.
105
+
106
+ ## Optional auth
107
+
108
+ ```ts compile
109
+ import { createApp, createModule } from '@tupik/core';
110
+
111
+ interface User { id: string }
112
+ declare module '@tupik/core' {
113
+ interface TupikRegister { principal: User }
114
+ }
115
+
116
+ const feed = createModule('/feed').get('/', {
117
+ access: { auth: 'optional' },
118
+ // ctx.principal is User | null here.
119
+ handler: (ctx) => ({ personalized: ctx.principal !== null }),
120
+ });
121
+
122
+ export const app = createApp({ authenticate: (): User | null => null }).register(feed);
123
+ ```
124
+
125
+ ## Choosing a rule
126
+
127
+ - Anyone may call it and it touches no user data: `'public'` (health, sign-in, sign-up, public catalog, a webhook
128
+ whose signature is checked by `webhookSignature`).
129
+ - Any signed-in user, no record id: `'authenticated'`.
130
+ - A record that belongs to a user: `{ owner }`.
131
+ - A role, a plan, a tenant membership: a policy, or `{ check, owner }` for both.
132
+ - Behind `tenant()`: the tenant is already verified; still filter every query by the tenant id.
@@ -0,0 +1,121 @@
1
+ # Validation, data classes and errors
2
+
3
+ ## Validation
4
+
5
+ `schema` takes any Standard Schema v1 validator (Zod, Valibot, ArkType, or `fromAjv`/`fromTypeBox`/`fromTypia`
6
+ from `@tupik/schema` for precompiled validators). The engine validates `body`, `query`, `params` and `headers`
7
+ before the handler and answers `400 application/problem+json` with JSON Pointer paths on failure. The handler
8
+ reads the typed output: `ctx.body`, `ctx.query`, `ctx.params`, `ctx.headers`.
9
+
10
+ - Header schemas see lower-case names (`'x-api-key'`).
11
+ - Bodies above `createApp({ bodyLimit })` (default 1 MiB) get 413.
12
+ - A validator that throws is a 500 with a generic body, never its message.
13
+ - Bound every string and array (`.max(...)`): the fuzzer sends 64 KiB strings.
14
+
15
+ ## Data classes
16
+
17
+ `classify(schema, classes, options?)` records how sensitive each field is. The class is stored on the
18
+ field's schema, so every schema built from a classified one keeps it: `z.array(Patient)`, `Patient.extend()`,
19
+ `.pick()`, `.partial()`, `.optional()`, nesting (`z.object({ patient: Patient })`) and unions, in Zod 4 and
20
+ Valibot. Classify once; do not classify the derived schemas again. Paths use dots and see through arrays
21
+ (`'items.label'`).
22
+
23
+ - One field: `email: classify(z.email(), 'pii')`.
24
+ - Plain JSON Schema: `'x-data-class': 'pii'` on the property (also behind `$ref`).
25
+ - A field schema instance shared by two fields carries its class in both (it fails closed). An opaque schema
26
+ (no walkable fields) keeps the classes on the classified object only: classify what you actually use.
27
+
28
+ | Class | Meaning | Effect |
29
+ | --- | --- | --- |
30
+ | `pii` | personal data (name, e-mail, phone, address, document numbers) | listed by `tupik audit` and `tupik data-map`; error if the route is public; masked in traces; removed by `@tupik/mcp` unless released |
31
+ | `health` | health data (LGPD art. 11, GDPR art. 9) | same as `pii`; the fuzzer flags it when served to a non-owner |
32
+ | `secret` | hashes, tokens, keys | never leaves the API: removed from every response (with `dev: true`, returning one throws) |
33
+
34
+ ## Response shaping
35
+
36
+ `createApp({ response })`:
37
+
38
+ - `'strip'` (default): fields the response schema does not declare are cut. The engine needs the schema's
39
+ fields: a JSON Schema on the schema, Standard JSON Schema, `createApp({ schemaConverter })`, or
40
+ `classify(schema, classes, { fields: [...] })`. Without any of them nothing is cut (only `secret` fields).
41
+ - `'validate'`: also runs the schema on the response (synchronous schemas only) and sends its output.
42
+ - `'off'`: sends what the handler returned (secret fields are still removed).
43
+
44
+ ```ts compile
45
+ import { classify, createApp, createModule } from '@tupik/core';
46
+ import { z } from 'zod';
47
+
48
+ interface User { id: string }
49
+ declare module '@tupik/core' {
50
+ interface TupikRegister { principal: User }
51
+ }
52
+
53
+ const Patient = classify(
54
+ z.object({
55
+ id: z.string(),
56
+ name: z.string(),
57
+ email: z.string(),
58
+ diagnosis: z.string(),
59
+ passwordHash: z.string(),
60
+ }),
61
+ { name: 'pii', email: 'pii', diagnosis: 'health', passwordHash: 'secret' },
62
+ );
63
+
64
+ interface PatientRow { id: string; doctorId: string; name: string; email: string; diagnosis: string; passwordHash: string }
65
+ const patients = new Map<string, PatientRow>();
66
+
67
+ const module = createModule('/patients').get('/:id', {
68
+ access: { owner: (ctx) => patients.get(ctx.params.id)?.doctorId },
69
+ schema: { params: z.object({ id: z.string().max(64) }), response: { 200: Patient } },
70
+ // doctorId is cut (not declared); passwordHash is removed (secret).
71
+ handler: (ctx) => patients.get(ctx.params.id),
72
+ });
73
+
74
+ export const app = createApp({
75
+ authenticate: (): User | null => null,
76
+ dev: process.env['NODE_ENV'] !== 'production',
77
+ schemaConverter: (schema) => (schema instanceof z.ZodType ? z.toJSONSchema(schema) : undefined),
78
+ }).register(module);
79
+ ```
80
+
81
+ Prefer a dedicated response schema without the secret field over relying on the removal: the removal logs a
82
+ warning in production and throws in `dev`, so it is a safety net, not the design.
83
+
84
+ ## Error catalog
85
+
86
+ ```ts compile
87
+ import { createApp, createModule, defineErrors } from '@tupik/core';
88
+ import { z } from 'zod';
89
+
90
+ interface User { id: string; verified: boolean }
91
+ declare module '@tupik/core' {
92
+ interface TupikRegister { principal: User }
93
+ }
94
+
95
+ // One catalog for the app, imported by every module.
96
+ export const Errors = defineErrors({
97
+ EMAIL_NOT_VERIFIED: { status: 403, title: 'Confirm your e-mail first' },
98
+ PLAN_LIMIT_REACHED: { status: 402, title: 'Plan limit reached', type: 'https://example.com/problems/plan-limit' },
99
+ });
100
+
101
+ const projects = createModule('/projects').post('/', {
102
+ access: 'authenticated',
103
+ schema: { body: z.object({ name: z.string().min(1).max(100) }) },
104
+ errors: [Errors.EMAIL_NOT_VERIFIED, Errors.PLAN_LIMIT_REACHED],
105
+ handler: (ctx) => {
106
+ if (!ctx.principal.verified) return ctx.fail('EMAIL_NOT_VERIFIED');
107
+ if (ctx.body.name === 'over-limit') return ctx.fail('PLAN_LIMIT_REACHED', 'Upgrade to create more projects');
108
+ return ctx.status(201).json({ name: ctx.body.name });
109
+ },
110
+ });
111
+
112
+ export const app = createApp({ authenticate: (): User | null => null }).register(projects);
113
+ ```
114
+
115
+ - `ctx.fail(code, detail?)` only accepts the codes in the route `errors` (type error otherwise) and answers
116
+ RFC 9457 `application/problem+json` with `status`, `title`, `code` and the optional `type` and `detail`.
117
+ - The typed client (`@tupik/client`) sees `error.code` as the union of those codes plus the access denials
118
+ (`UNAUTHORIZED`, `FORBIDDEN`, `NOT_FOUND`); OpenAPI lists them per status.
119
+ - Unexpected exceptions become a generic 500 and go to `onError` (or `console.error` when there is none).
120
+ Do not catch and rethrow them as custom JSON.
121
+ - `detail` is sent to the client: never put internal messages, ids of other users or stack traces in it.
@@ -0,0 +1,74 @@
1
+ # Middleware
2
+
3
+ All middleware comes from `@tupik/middleware` (Web Standards only; runs on Node, Bun and Workers). Order
4
+ matters twice:
5
+
6
+ - `app.use(...)` runs for every route (and for 404/405/OPTIONS, so CORS can answer preflights); `module.use(...)`
7
+ runs only for that module's routes **declared after the call**.
8
+ - Middleware runs before access: `authenticate` can read what a session, JWT or API key middleware stored.
9
+
10
+ ## A production stack
11
+
12
+ ```ts compile
13
+ import { createApp, createModule } from '@tupik/core';
14
+ import { defineEnv, secret, url } from '@tupik/env';
15
+ import { bodyLimit, clientIp, cors, errorReporter, helmet, jwt, logger, rateLimit, requestId, timeout } from '@tupik/middleware';
16
+ import type { JwtPayload } from '@tupik/middleware';
17
+
18
+ interface User { id: string }
19
+ declare module '@tupik/core' {
20
+ interface TupikRegister { principal: User }
21
+ }
22
+
23
+ const env = defineEnv({ JWT_SECRET: secret({ minLength: 32 }), ERRORS_DSN: url() }).parse();
24
+
25
+ const api = createModule('/api')
26
+ .use(jwt({ secret: env.JWT_SECRET, audience: 'api', issuer: 'https://auth.example.com' }))
27
+ .use(rateLimit({ windowMs: 60_000, limit: 300, trust: 'proxy', trustedHops: 1 }))
28
+ .get('/me', { access: 'authenticated', handler: (ctx) => ({ id: ctx.principal.id }) });
29
+
30
+ export const app = createApp({
31
+ authenticate: (ctx) => {
32
+ const payload = ctx.rawStore.get('jwt') as JwtPayload | undefined; // set by jwt() after verification
33
+ return typeof payload?.sub === 'string' ? { id: payload.sub } : null;
34
+ },
35
+ })
36
+ .use(requestId())
37
+ .use(helmet())
38
+ .use(cors({ origin: ['https://app.example.com'], credentials: true }))
39
+ .use(clientIp({ trust: 'proxy', trustedHops: 1 }))
40
+ .use(logger()) // one JSON line per request; redacts credentials and masks IPs by default
41
+ .use(errorReporter({ dsn: env.ERRORS_DSN }))
42
+ .use(bodyLimit({ maxBytes: 256 * 1024 }))
43
+ .use(timeout({ ms: 10_000 }))
44
+ .register(api);
45
+ ```
46
+
47
+ ## Reference
48
+
49
+ | Middleware | Safe use | Never |
50
+ | --- | --- | --- |
51
+ | `rateLimit({ windowMs, limit, trust \| keyGenerator, store? })` | `trust: 'cloudflare'` on Workers, `'proxy'` behind a proxy you run; `keyGenerator: getClientIp` with `clientIp()`, or per user `async (ctx) => (await ctx.getPrincipal())?.id`; on Workers a shared store (`DurableObjectRateLimitStore`, `CloudflareRateLimitStore`) | trust `x-forwarded-for` without a proxy; rely on `MemoryStore` across isolates |
52
+ | `clientIp({ trust, trustedHops? })`, `getClientIp(ctx)` | one trusted client IP for `logger`, `audit`, `captcha`, `ipAllow` | read `x-forwarded-for` yourself |
53
+ | `session({ store, idleTimeoutMs?, absoluteTimeoutMs? })` | `D1SessionStore`/`KVSessionStore` in production; `create` after login, `rotate` after privilege change | store user data you do not need; put the session id in logs |
54
+ | `csrf({ secret, session, origins })` | every cookie-authenticated app; register after `session` | skip it because the API "is JSON" |
55
+ | `jwt({ secret, audience?, issuer? })`, `signJwt`, `verifyJwt` | secret of 32+ bytes from env; short `expiresInSec`; `kid` map for rotation | tokens without `exp`; secrets in code |
56
+ | `apiKey({ prefix, lookup, scopes? })`, `generateApiKey`, `hashApiKey` | store only `hashApiKey(key)`; scopes per key | store or log the raw key |
57
+ | `tenant({ from, verify })`, `getTenantId(ctx)` | `verify` checks membership of `(await ctx.getPrincipal())?.id`; filter queries by the tenant id | trust the header without `verify` |
58
+ | `cors({ origin: [...], credentials? })` | explicit origin list | `'*'` with credentials (throws); reflecting any origin |
59
+ | `helmet()` | always, at app level | turn headers off without a reason |
60
+ | `bodyLimit({ maxBytes })`, `getRawBody(ctx)` | small limits on public routes | read unbounded bodies |
61
+ | `timeout({ ms })`, `getSignal(ctx)` | pass `getSignal(ctx)` to `fetch` and database calls | long work without a signal |
62
+ | `webhookSignature({ preset \| secret, header, store? })` | presets `github`, `stripe`, `asaas`; a `D1TtlStore` for dedup | parse the body before verifying; compare signatures with `===` |
63
+ | `idempotency({ store, principal, required? })` | payments and other non-repeatable `POST`s; `principal: async (ctx) => (await ctx.getPrincipal())?.id` | `KVTtlStore` when races matter (use `D1TtlStore`) |
64
+ | `captcha({ secret, production: true })` | sign-up and public forms; fails closed | `allowMissingSecretInDev` in production |
65
+ | `audit({ sink, principal?, params? })` | trail of who touched which record (LGPD/GDPR); never logs bodies | log bodies "for audit" |
66
+ | `errorReporter({ dsn })` | Sentry-compatible, redacted before sending | send raw errors with request data |
67
+ | `logger({ redact? })` | add your own sensitive keys to `redact` | `includeHeaders: true` without need |
68
+ | `tracing({ tracer, app })`, `setTraceAttributes` | OpenTelemetry spans that respect data classes | put ids of other users or bodies in attributes |
69
+ | `cacheControl({ value })`, `etag()` | public, cacheable reads | caching authenticated responses (it forces `no-store` for them) |
70
+ | `compress({ filter? })` | large public payloads | compressing responses that mix secrets and user input (BREACH) |
71
+ | `basicAuth`, `ipAllow`, `maintenance`, `locale`, `requestId`, `timing`, `cookies` | internal tools, allow-lists, maintenance windows, i18n, tracing ids | `basicAuth` as the auth of a public product |
72
+
73
+ New middleware answers errors as RFC 9457 problems with a `code` (`TENANT_FORBIDDEN`, `CSRF_INVALID`,
74
+ `RATE_LIMITED`...). `rateLimit` tags its routes as rate limited, which is what `tupik audit` checks for writes.
@@ -0,0 +1,203 @@
1
+ # Common mistakes and their fixes
2
+
3
+ Each block shows the wrong code (marked `wrong`) next to the fix. Where Tupik rejects the wrong code at
4
+ compile time, the block carries `@ts-expect-error`, which proves the type error exists.
5
+
6
+ ## Missing access
7
+
8
+ ```ts compile
9
+ import { createModule } from '@tupik/core';
10
+
11
+ createModule('/reports')
12
+ // wrong: no access rule. Type error, and register() throws "GET /reports has no access rule".
13
+ // @ts-expect-error access is required
14
+ .get('/', { handler: () => [] });
15
+
16
+ // fix: say who may call it.
17
+ createModule('/reports').get('/', { access: 'authenticated', handler: () => [] });
18
+ ```
19
+
20
+ ## Public to silence a 401
21
+
22
+ ```ts compile
23
+ import { createApp, createModule } from '@tupik/core';
24
+ import { z } from 'zod';
25
+
26
+ interface User { id: string }
27
+ declare module '@tupik/core' {
28
+ interface TupikRegister { principal: User }
29
+ }
30
+
31
+ const invoices = new Map<string, { id: string; ownerId: string; total: number }>();
32
+ const schema = { params: z.object({ id: z.string().max(64) }) };
33
+
34
+ // wrong: compiles and runs, and anyone on the internet reads every invoice. tupik audit lists it as public.
35
+ const leaky = createModule('/invoices').get('/:id', { access: 'public', schema, handler: (ctx) => invoices.get(ctx.params.id) });
36
+
37
+ // fix: the owner of the invoice, nobody else (404 for others).
38
+ const safe = createModule('/invoices').get('/:id', {
39
+ access: { owner: (ctx) => invoices.get(ctx.params.id)?.ownerId },
40
+ schema,
41
+ handler: (ctx) => invoices.get(ctx.params.id),
42
+ });
43
+
44
+ export const apps = [leaky, safe].map((module) => createApp({ authenticate: (): User | null => null }).register(module));
45
+ ```
46
+
47
+ When a test gets 401, fix the credentials of the test (`principals` in `generateAccessTests`/`fuzz`), not the rule.
48
+
49
+ ## Authenticated is not authorized
50
+
51
+ ```ts compile
52
+ import { createModule } from '@tupik/core';
53
+ import { z } from 'zod';
54
+
55
+ interface User { id: string }
56
+ declare module '@tupik/core' {
57
+ interface TupikRegister { principal: User }
58
+ }
59
+
60
+ const schema = { params: z.object({ id: z.string().max(64) }) };
61
+ const files = new Map<string, { ownerId: string; name: string }>();
62
+
63
+ // wrong: any signed-in user reads any file by changing the id (BOLA). tupik audit: id-without-owner;
64
+ // tupik-lint: no-unscoped-lookup; tupik fuzz: cross-access with --foreign-ids.
65
+ export const wrong = createModule('/files').get('/:id', { access: 'authenticated', schema, handler: (ctx) => files.get(ctx.params.id) });
66
+
67
+ // fix
68
+ export const fixed = createModule('/files').get('/:id', {
69
+ access: { owner: (ctx) => files.get(ctx.params.id)?.ownerId },
70
+ schema,
71
+ handler: (ctx) => files.get(ctx.params.id),
72
+ });
73
+ ```
74
+
75
+ ## Middleware after the routes
76
+
77
+ ```ts compile
78
+ import { createModule } from '@tupik/core';
79
+ import { rateLimit } from '@tupik/middleware';
80
+
81
+ const limit = rateLimit({ windowMs: 60_000, limit: 10, trust: 'cloudflare' });
82
+
83
+ // wrong: POST /comments was declared before .use, so it is not rate limited (audit: write-without-rate-limit).
84
+ export const wrong = createModule('/comments').post('/', { access: 'authenticated', handler: () => ({}) }).use(limit);
85
+
86
+ // fix: .use first.
87
+ export const fixed = createModule('/comments').use(limit).post('/', { access: 'authenticated', handler: () => ({}) });
88
+ ```
89
+
90
+ ## Hand-made errors and unvalidated input
91
+
92
+ ```ts compile
93
+ import { createModule, defineErrors } from '@tupik/core';
94
+ import { z } from 'zod';
95
+
96
+ const Errors = defineErrors({ EMAIL_TAKEN: { status: 409, title: 'E-mail already registered' } });
97
+ const taken = new Set<string>();
98
+
99
+ // wrong: body read by hand (no validation, no 400, no OpenAPI) and an ad hoc error shape the client cannot type.
100
+ export const wrong = createModule('/sign-up').post('/', {
101
+ access: 'public',
102
+ handler: async (ctx) => {
103
+ const body = (await ctx.req.json()) as { email: string };
104
+ if (taken.has(body.email)) return ctx.status(409).json({ error: 'taken' });
105
+ return ctx.status(201).json({ ok: true });
106
+ },
107
+ });
108
+
109
+ // fix: schema for the body, catalog for the error.
110
+ export const fixed = createModule('/sign-up').post('/', {
111
+ access: 'public',
112
+ schema: { body: z.object({ email: z.email().max(254), password: z.string().min(12).max(256) }) },
113
+ errors: [Errors.EMAIL_TAKEN],
114
+ handler: (ctx) => {
115
+ if (taken.has(ctx.body.email)) return ctx.fail('EMAIL_TAKEN');
116
+ return ctx.status(201).json({ ok: true });
117
+ },
118
+ });
119
+ ```
120
+
121
+ `ctx.fail` only accepts the declared codes:
122
+
123
+ ```ts compile
124
+ import { createModule, defineErrors } from '@tupik/core';
125
+
126
+ const Errors = defineErrors({ OUT_OF_STOCK: { status: 409, title: 'Out of stock' } });
127
+
128
+ createModule('/cart').post('/', {
129
+ access: 'authenticated',
130
+ errors: [Errors.OUT_OF_STOCK],
131
+ // @ts-expect-error 'SOLD_OUT' is not in the route errors
132
+ handler: (ctx) => ctx.fail('SOLD_OUT'),
133
+ });
134
+ ```
135
+
136
+ ## Rate limit without a trusted key
137
+
138
+ ```ts compile
139
+ import { rateLimit } from '@tupik/middleware';
140
+
141
+ // wrong: no trust and no keyGenerator. Type-valid, but the factory throws at startup.
142
+ export const wrong = () => rateLimit({ windowMs: 60_000, limit: 100 });
143
+
144
+ // fix: the header of the proxy you really run behind, or your own key.
145
+ export const onWorkers = rateLimit({ windowMs: 60_000, limit: 100, trust: 'cloudflare' });
146
+ export const perUser = rateLimit({
147
+ windowMs: 60_000,
148
+ limit: 100,
149
+ keyGenerator: (ctx) => ctx.req.headers.get('x-api-key-id') ?? undefined,
150
+ });
151
+ ```
152
+
153
+ ## Secrets, logs and passwords
154
+
155
+ ```ts compile
156
+ import { defineEnv, secret } from '@tupik/env';
157
+ import { createLogger } from '@tupik/infra';
158
+ import { hashPassword, verifyPassword } from '@tupik/password';
159
+
160
+ // wrong: a literal secret (tupik-lint: no-hardcoded-secret), a fast hash, a log line with the request body.
161
+ // const JWT_SECRET = 'sk_live_...';
162
+ // const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(password));
163
+ // console.log('sign-in', ctx.body);
164
+
165
+ // fix: secrets from the validated env, Argon2id, and an allow-list in a redacting logger.
166
+ const env = defineEnv({ JWT_SECRET: secret({ minLength: 32 }) }).parse();
167
+ const log = createLogger({ base: { service: 'api' } });
168
+
169
+ export async function register(email: string, password: string): Promise<string> {
170
+ const phc = await hashPassword(password);
171
+ log.info('account created', { domain: email.split('@')[1] });
172
+ return phc;
173
+ }
174
+
175
+ export const check = (phc: string, password: string) => verifyPassword(phc, password);
176
+ export const secretLength = env.JWT_SECRET.length;
177
+ ```
178
+
179
+ ## Returning the row
180
+
181
+ ```ts compile
182
+ import { classify, createModule } from '@tupik/core';
183
+ import { z } from 'zod';
184
+
185
+ interface User { id: string }
186
+ declare module '@tupik/core' {
187
+ interface TupikRegister { principal: User }
188
+ }
189
+
190
+ interface UserRow { id: string; name: string; email: string; passwordHash: string; resetToken: string | null }
191
+ const rows = new Map<string, UserRow>();
192
+
193
+ // wrong: every column leaves, including the ones added next year (tupik-lint: no-raw-row-response).
194
+ export const wrong = createModule('/me').get('/', { access: 'authenticated', handler: (ctx) => rows.get(ctx.principal.id) });
195
+
196
+ // fix: a response schema; undeclared fields are cut and classified fields are tracked.
197
+ const Me = classify(z.object({ id: z.string(), name: z.string(), email: z.string() }), { name: 'pii', email: 'pii' });
198
+ export const fixed = createModule('/me').get('/', {
199
+ access: 'authenticated',
200
+ schema: { response: { 200: Me } },
201
+ handler: (ctx) => rows.get(ctx.principal.id),
202
+ });
203
+ ```