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 +21 -0
- package/README.md +35 -2
- package/dist/index.d.mts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +391 -0
- package/dist/skill/SKILL.md +173 -0
- package/dist/skill/references/access.md +132 -0
- package/dist/skill/references/data-and-errors.md +121 -0
- package/dist/skill/references/middleware.md +74 -0
- package/dist/skill/references/mistakes.md +203 -0
- package/dist/skill/references/recipes.md +366 -0
- package/dist/skill/references/tooling.md +117 -0
- package/package.json +44 -3
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
# Recipes
|
|
2
|
+
|
|
3
|
+
Each recipe is a complete module that compiles. Storage is an in-memory `Map` so the access logic stays
|
|
4
|
+
visible; swap it for your database and keep the filters.
|
|
5
|
+
|
|
6
|
+
## CRUD with owner
|
|
7
|
+
|
|
8
|
+
```ts compile
|
|
9
|
+
import { classify, createApp, createModule, defineErrors } from '@tupik/core';
|
|
10
|
+
import { rateLimit } from '@tupik/middleware';
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
|
|
13
|
+
interface User { id: string }
|
|
14
|
+
declare module '@tupik/core' {
|
|
15
|
+
interface TupikRegister { principal: User }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface TaskRow { id: string; ownerId: string; title: string; notes: string; done: boolean }
|
|
19
|
+
const tasks = new Map<string, TaskRow>();
|
|
20
|
+
|
|
21
|
+
const Task = classify(z.object({ id: z.string(), title: z.string(), notes: z.string(), done: z.boolean() }), { notes: 'pii' });
|
|
22
|
+
const TaskInput = z.object({ title: z.string().min(1).max(200), notes: z.string().max(5_000).default(''), done: z.boolean().default(false) });
|
|
23
|
+
const TaskParams = z.object({ id: z.string().uuid() });
|
|
24
|
+
const ListQuery = z.object({ done: z.enum(['true', 'false']).optional() });
|
|
25
|
+
const Errors = defineErrors({ TASK_NOT_FOUND: { status: 404, title: 'Task not found' } });
|
|
26
|
+
|
|
27
|
+
const ownerOf = (id: string): string | undefined => tasks.get(id)?.ownerId;
|
|
28
|
+
|
|
29
|
+
const taskModule = createModule('/tasks')
|
|
30
|
+
// Before the routes: middleware covers only the routes declared after it.
|
|
31
|
+
.use(rateLimit({ windowMs: 60_000, limit: 120, trust: 'cloudflare' }))
|
|
32
|
+
.get('/', {
|
|
33
|
+
access: 'authenticated',
|
|
34
|
+
schema: { query: ListQuery, response: { 200: z.array(Task) } },
|
|
35
|
+
handler: (ctx) =>
|
|
36
|
+
[...tasks.values()].filter(
|
|
37
|
+
(task) => task.ownerId === ctx.principal.id && (ctx.query.done === undefined || String(task.done) === ctx.query.done),
|
|
38
|
+
),
|
|
39
|
+
})
|
|
40
|
+
.post('/', {
|
|
41
|
+
access: 'authenticated',
|
|
42
|
+
schema: { body: TaskInput, response: { 201: Task } },
|
|
43
|
+
handler: (ctx) => {
|
|
44
|
+
const task: TaskRow = { id: crypto.randomUUID(), ownerId: ctx.principal.id, ...ctx.body };
|
|
45
|
+
tasks.set(task.id, task);
|
|
46
|
+
return ctx.status(201).json(task);
|
|
47
|
+
},
|
|
48
|
+
})
|
|
49
|
+
// Every route below needs the owner of :id.
|
|
50
|
+
.access({ owner: (ctx) => ownerOf(String(ctx.params['id'])) })
|
|
51
|
+
.get('/:id', { schema: { params: TaskParams, response: { 200: Task } }, handler: (ctx) => tasks.get(ctx.params.id) })
|
|
52
|
+
.patch('/:id', {
|
|
53
|
+
schema: { params: TaskParams, body: TaskInput.partial(), response: { 200: Task } },
|
|
54
|
+
errors: [Errors.TASK_NOT_FOUND],
|
|
55
|
+
handler: (ctx) => {
|
|
56
|
+
const task = tasks.get(ctx.params.id);
|
|
57
|
+
if (task === undefined) return ctx.fail('TASK_NOT_FOUND');
|
|
58
|
+
Object.assign(task, ctx.body);
|
|
59
|
+
return task;
|
|
60
|
+
},
|
|
61
|
+
})
|
|
62
|
+
.delete('/:id', {
|
|
63
|
+
schema: { params: TaskParams },
|
|
64
|
+
handler: (ctx) => {
|
|
65
|
+
tasks.delete(ctx.params.id);
|
|
66
|
+
return new Response(null, { status: 204 });
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
export const app = createApp({
|
|
71
|
+
authenticate: (): User | null => null, // see "Session and CSRF"
|
|
72
|
+
schemaConverter: (schema) => (schema instanceof z.ZodType ? z.toJSONSchema(schema) : undefined),
|
|
73
|
+
}).register(taskModule);
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Session and CSRF
|
|
77
|
+
|
|
78
|
+
Cookie sessions for a browser app on the same site. The store keeps only `sha256(sessionId)`; the cookie is
|
|
79
|
+
`__Host-tupik_session` (Secure, HttpOnly, SameSite=Lax). `csrf` binds its token to the session and checks
|
|
80
|
+
`Origin`. Any `GET` sets the token cookie; the browser code sends its value back in the `x-csrf-token` header
|
|
81
|
+
on every write, sign-in included.
|
|
82
|
+
|
|
83
|
+
```ts compile
|
|
84
|
+
import { createApp, createModule, defineErrors } from '@tupik/core';
|
|
85
|
+
import { defineEnv, secret } from '@tupik/env';
|
|
86
|
+
import { csrf, MemorySessionStore, rateLimit, session } from '@tupik/middleware';
|
|
87
|
+
import { hashPassword, needsRehash, verifyPassword } from '@tupik/password';
|
|
88
|
+
import { z } from 'zod';
|
|
89
|
+
|
|
90
|
+
interface User { id: string }
|
|
91
|
+
declare module '@tupik/core' {
|
|
92
|
+
interface TupikRegister { principal: User }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const env = defineEnv({ CSRF_SECRET: secret({ minLength: 32 }) }).parse();
|
|
96
|
+
|
|
97
|
+
interface Account { id: string; email: string; passwordHash: string }
|
|
98
|
+
const accounts = new Map<string, Account>();
|
|
99
|
+
// Verified when the e-mail is unknown, so both paths cost the same time.
|
|
100
|
+
const DUMMY_HASH = await hashPassword(crypto.randomUUID());
|
|
101
|
+
|
|
102
|
+
const sessions = session<{ signedInAt: number }>({ store: new MemorySessionStore() }); // D1SessionStore / KVSessionStore in production
|
|
103
|
+
const Errors = defineErrors({ INVALID_CREDENTIALS: { status: 401, title: 'Invalid e-mail or password' } });
|
|
104
|
+
const Credentials = z.object({ email: z.email().max(254), password: z.string().min(12).max(256) });
|
|
105
|
+
|
|
106
|
+
const auth = createModule('/auth')
|
|
107
|
+
.use(rateLimit({ windowMs: 15 * 60_000, limit: 10, trust: 'cloudflare' }))
|
|
108
|
+
.post('/sign-in', {
|
|
109
|
+
access: 'public',
|
|
110
|
+
schema: { body: Credentials },
|
|
111
|
+
errors: [Errors.INVALID_CREDENTIALS],
|
|
112
|
+
handler: async (ctx) => {
|
|
113
|
+
const account = accounts.get(ctx.body.email);
|
|
114
|
+
const valid = await verifyPassword(account?.passwordHash ?? DUMMY_HASH, ctx.body.password);
|
|
115
|
+
if (account === undefined || !valid) return ctx.fail('INVALID_CREDENTIALS');
|
|
116
|
+
if (needsRehash(account.passwordHash)) account.passwordHash = await hashPassword(ctx.body.password);
|
|
117
|
+
await sessions.get(ctx).create({ signedInAt: Date.now() }, { userId: account.id }); // fresh id: no fixation
|
|
118
|
+
return { id: account.id };
|
|
119
|
+
},
|
|
120
|
+
})
|
|
121
|
+
// Any GET sets the CSRF cookie; the front end calls this one first.
|
|
122
|
+
.get('/session', { access: { auth: 'optional' }, handler: (ctx) => ({ signedIn: ctx.principal !== null }) })
|
|
123
|
+
.post('/sign-out', {
|
|
124
|
+
access: 'authenticated',
|
|
125
|
+
handler: async (ctx) => {
|
|
126
|
+
await sessions.get(ctx).destroy();
|
|
127
|
+
return new Response(null, { status: 204 });
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
export const app = createApp({
|
|
132
|
+
authenticate: (ctx) => {
|
|
133
|
+
const userId = sessions.get(ctx).userId;
|
|
134
|
+
return userId === undefined ? null : { id: userId };
|
|
135
|
+
},
|
|
136
|
+
})
|
|
137
|
+
.use(sessions)
|
|
138
|
+
.use(csrf({ secret: env.CSRF_SECRET, session: sessions, origins: ['https://app.example.com'] }))
|
|
139
|
+
.register(auth);
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
The token is bound to the session, so it changes at sign-in: call `GET /auth/session` again before the next
|
|
143
|
+
write. Call `sessions.get(ctx).rotate()` after a privilege change and `revokeAll()` for "sign out everywhere".
|
|
144
|
+
For APIs called with a bearer token (mobile apps, other servers) use `jwt` or `apiKey` instead; CSRF is a
|
|
145
|
+
cookie problem.
|
|
146
|
+
|
|
147
|
+
## Multi-tenant
|
|
148
|
+
|
|
149
|
+
`tenant()` reads the workspace id from a header, a subdomain or a function and calls the mandatory `verify`
|
|
150
|
+
before anything else runs; a forged `x-workspace-id` never reaches a handler. The handler still filters every
|
|
151
|
+
query by the tenant id.
|
|
152
|
+
|
|
153
|
+
```ts compile
|
|
154
|
+
import { createApp, createModule, defineErrors } from '@tupik/core';
|
|
155
|
+
import { MemorySessionStore, session, tenant } from '@tupik/middleware';
|
|
156
|
+
import { z } from 'zod';
|
|
157
|
+
|
|
158
|
+
interface User { id: string }
|
|
159
|
+
declare module '@tupik/core' {
|
|
160
|
+
interface TupikRegister { principal: User }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
interface Workspace { id: string; role: 'owner' | 'member' }
|
|
164
|
+
interface Project { id: string; workspaceId: string; name: string }
|
|
165
|
+
const memberships = new Map<string, Map<string, Workspace['role']>>(); // workspaceId -> userId -> role
|
|
166
|
+
const projects = new Map<string, Project>();
|
|
167
|
+
|
|
168
|
+
const sessions = session<{ signedInAt: number }>({ store: new MemorySessionStore() });
|
|
169
|
+
const workspaces = tenant<Workspace>({
|
|
170
|
+
from: 'header', // x-workspace-id
|
|
171
|
+
verify: (ctx, workspaceId) => {
|
|
172
|
+
const userId = sessions.get(ctx).userId;
|
|
173
|
+
const role = userId === undefined ? undefined : memberships.get(workspaceId)?.get(userId);
|
|
174
|
+
return role === undefined ? false : { id: workspaceId, role }; // false answers 403 TENANT_FORBIDDEN
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
const Errors = defineErrors({ PROJECT_NOT_FOUND: { status: 404, title: 'Project not found' } });
|
|
178
|
+
|
|
179
|
+
const projectModule = createModule('/projects')
|
|
180
|
+
.use(workspaces)
|
|
181
|
+
.get('/', {
|
|
182
|
+
access: 'authenticated',
|
|
183
|
+
handler: (ctx) => [...projects.values()].filter((project) => project.workspaceId === workspaces.get(ctx)?.id),
|
|
184
|
+
})
|
|
185
|
+
.get('/:id', {
|
|
186
|
+
access: 'authenticated',
|
|
187
|
+
schema: { params: z.object({ id: z.string().max(64) }) },
|
|
188
|
+
errors: [Errors.PROJECT_NOT_FOUND],
|
|
189
|
+
handler: (ctx) => {
|
|
190
|
+
const project = projects.get(ctx.params.id);
|
|
191
|
+
// Same answer for "missing" and "other workspace".
|
|
192
|
+
if (project === undefined || project.workspaceId !== workspaces.get(ctx)?.id) return ctx.fail('PROJECT_NOT_FOUND');
|
|
193
|
+
return project;
|
|
194
|
+
},
|
|
195
|
+
})
|
|
196
|
+
.delete('/:id', {
|
|
197
|
+
access: (ctx) => workspaces.get(ctx)?.role === 'owner',
|
|
198
|
+
schema: { params: z.object({ id: z.string().max(64) }) },
|
|
199
|
+
handler: (ctx) => {
|
|
200
|
+
const project = projects.get(ctx.params.id);
|
|
201
|
+
if (project?.workspaceId === workspaces.get(ctx)?.id) projects.delete(ctx.params.id);
|
|
202
|
+
return new Response(null, { status: 204 });
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
export const app = createApp({
|
|
207
|
+
authenticate: (ctx) => {
|
|
208
|
+
const userId = sessions.get(ctx).userId;
|
|
209
|
+
return userId === undefined ? null : { id: userId };
|
|
210
|
+
},
|
|
211
|
+
})
|
|
212
|
+
.use(sessions)
|
|
213
|
+
.register(projectModule);
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
## Webhook and idempotency
|
|
217
|
+
|
|
218
|
+
`webhookSignature` checks the provider signature in constant time over the raw body, enforces the timestamp
|
|
219
|
+
window and drops repeated deliveries (with `store`). The route is `'public'` because the signature is the
|
|
220
|
+
credential. `idempotency` makes client retries of a `POST` safe: the first response is replayed for the same
|
|
221
|
+
`Idempotency-Key`, a different body with the same key gets 422.
|
|
222
|
+
|
|
223
|
+
```ts compile
|
|
224
|
+
import { createApp, createModule } from '@tupik/core';
|
|
225
|
+
import { defineEnv, secret } from '@tupik/env';
|
|
226
|
+
import { idempotency, MemoryTtlStore, rateLimit, webhookSignature } from '@tupik/middleware';
|
|
227
|
+
import { z } from 'zod';
|
|
228
|
+
|
|
229
|
+
interface User { id: string }
|
|
230
|
+
declare module '@tupik/core' {
|
|
231
|
+
interface TupikRegister { principal: User }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const env = defineEnv({ STRIPE_WEBHOOK_SECRET: secret({ minLength: 16 }) }).parse();
|
|
235
|
+
const StripeEvent = z.object({ id: z.string().max(255), type: z.string().max(255), data: z.object({ object: z.record(z.string(), z.unknown()) }) });
|
|
236
|
+
|
|
237
|
+
const webhooks = createModule('/webhooks')
|
|
238
|
+
.use(rateLimit({ windowMs: 60_000, limit: 600, trust: 'cloudflare' }))
|
|
239
|
+
.use(webhookSignature({ preset: 'stripe', secret: env.STRIPE_WEBHOOK_SECRET, store: new MemoryTtlStore() })) // D1TtlStore in production
|
|
240
|
+
.post('/stripe', {
|
|
241
|
+
access: 'public', // the signature is the credential
|
|
242
|
+
schema: { body: StripeEvent },
|
|
243
|
+
handler: (ctx) => ({ received: ctx.body.type }),
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
const userIdOf = (request: Request): string | undefined => request.headers.get('authorization')?.replace(/^Bearer /, '');
|
|
247
|
+
|
|
248
|
+
const payments = createModule('/payments')
|
|
249
|
+
.use(rateLimit({ windowMs: 60_000, limit: 30, trust: 'cloudflare' }))
|
|
250
|
+
.use(idempotency({ store: new MemoryTtlStore(), principal: (ctx) => userIdOf(ctx.req), required: true }))
|
|
251
|
+
.post('/', {
|
|
252
|
+
access: 'authenticated',
|
|
253
|
+
schema: { body: z.object({ amountCents: z.number().int().positive().max(10_000_000) }) },
|
|
254
|
+
handler: (ctx) => ctx.status(201).json({ charged: ctx.body.amountCents, by: ctx.principal.id }),
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
export const app = createApp({
|
|
258
|
+
authenticate: (ctx) => {
|
|
259
|
+
const id = userIdOf(ctx.req);
|
|
260
|
+
return id === undefined ? null : { id };
|
|
261
|
+
},
|
|
262
|
+
}).register(webhooks, payments);
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
`userIdOf` stands in for your real token check; never use a raw header as identity in production.
|
|
266
|
+
|
|
267
|
+
## Cloudflare Workers and D1
|
|
268
|
+
|
|
269
|
+
Declare the bindings and secrets with `@tupik/env`; `withEnv` validates them once per isolate and refuses to
|
|
270
|
+
serve with a broken configuration. Handlers read the bindings with `getEnv`. Always bind parameters (`?`),
|
|
271
|
+
never interpolate.
|
|
272
|
+
|
|
273
|
+
```ts compile
|
|
274
|
+
import { createApp, createModule } from '@tupik/core';
|
|
275
|
+
import type { ExecutionContextLike } from '@tupik/core';
|
|
276
|
+
import { getEnv } from '@tupik/edge';
|
|
277
|
+
import { binding, defineEnv, secret, withEnv } from '@tupik/env';
|
|
278
|
+
import type { InferEnv } from '@tupik/env';
|
|
279
|
+
import { z } from 'zod';
|
|
280
|
+
|
|
281
|
+
// In a Worker, use D1Database from @cloudflare/workers-types instead of this slice.
|
|
282
|
+
interface D1Database {
|
|
283
|
+
prepare(query: string): { bind(...values: unknown[]): { first<T>(): Promise<T | null>; all<T>(): Promise<{ results: T[] }> } };
|
|
284
|
+
batch(statements: unknown[]): Promise<unknown>;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
interface User { id: string }
|
|
288
|
+
declare module '@tupik/core' {
|
|
289
|
+
interface TupikRegister { principal: User }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const env = defineEnv({ DB: binding.d1<D1Database>(), SESSION_SECRET: secret({ minLength: 32 }) });
|
|
293
|
+
type Env = InferEnv<typeof env>;
|
|
294
|
+
const db = (ctx: Parameters<typeof getEnv>[0]): D1Database => getEnv<Env>(ctx).DB;
|
|
295
|
+
|
|
296
|
+
interface NoteRow { id: string; title: string }
|
|
297
|
+
|
|
298
|
+
const notes = createModule('/notes')
|
|
299
|
+
.get('/', {
|
|
300
|
+
access: 'authenticated',
|
|
301
|
+
handler: async (ctx) =>
|
|
302
|
+
(await db(ctx).prepare('SELECT id, title FROM notes WHERE owner_id = ?').bind(ctx.principal.id).all<NoteRow>()).results,
|
|
303
|
+
})
|
|
304
|
+
.get('/:id', {
|
|
305
|
+
access: {
|
|
306
|
+
owner: async (ctx) =>
|
|
307
|
+
(await db(ctx).prepare('SELECT owner_id FROM notes WHERE id = ?').bind(ctx.params.id).first<{ owner_id: string }>())?.owner_id,
|
|
308
|
+
},
|
|
309
|
+
schema: { params: z.object({ id: z.string().max(64) }) },
|
|
310
|
+
handler: async (ctx) => (await db(ctx).prepare('SELECT id, title FROM notes WHERE id = ?').bind(ctx.params.id).first<NoteRow>()) ?? undefined,
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
const app = createApp({ authenticate: (): User | null => null }).register(notes);
|
|
314
|
+
|
|
315
|
+
export default {
|
|
316
|
+
fetch: withEnv(env, (request, vars, ctx: ExecutionContextLike) => app.fetch(request, vars, ctx)),
|
|
317
|
+
};
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
Select the columns you return (`no-raw-row-response` flags `SELECT *`). For sessions on D1 use
|
|
321
|
+
`new D1SessionStore({ database: (env) => (env as Env).DB })` and run `D1SessionStore.schema()` as a migration.
|
|
322
|
+
`@tupik/password` on Workers: import from `@tupik/password/workers`; the `owasp` profile needs the paid plan's
|
|
323
|
+
CPU budget, `light` fits the free plan (see the package README).
|
|
324
|
+
|
|
325
|
+
## OpenAPI and typed client
|
|
326
|
+
|
|
327
|
+
```ts compile
|
|
328
|
+
import { createTypedClient } from '@tupik/client';
|
|
329
|
+
import { classify, createApp, createModule, defineErrors } from '@tupik/core';
|
|
330
|
+
import { generateOpenApiDocument } from '@tupik/openapi';
|
|
331
|
+
import { z } from 'zod';
|
|
332
|
+
|
|
333
|
+
interface User { id: string }
|
|
334
|
+
declare module '@tupik/core' {
|
|
335
|
+
interface TupikRegister { principal: User }
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// One converter for the engine and the generator; `{}` (any) for a schema that is not Zod.
|
|
339
|
+
const toJsonSchema = (schema: unknown) => (schema instanceof z.ZodType ? z.toJSONSchema(schema) : {});
|
|
340
|
+
const Note = classify(z.object({ id: z.string(), title: z.string() }), {});
|
|
341
|
+
const Errors = defineErrors({ NOTE_ARCHIVED: { status: 410, title: 'The note is archived' } });
|
|
342
|
+
|
|
343
|
+
const notes = createModule('/notes').get('/:id', {
|
|
344
|
+
access: { owner: () => 'u1' },
|
|
345
|
+
schema: { params: z.object({ id: z.string().max(64) }), response: { 200: Note } },
|
|
346
|
+
errors: [Errors.NOTE_ARCHIVED],
|
|
347
|
+
handler: (ctx) => ({ id: ctx.params.id, title: 'Hello' }),
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
export const app = createApp({ authenticate: (): User | null => null, schemaConverter: toJsonSchema }).register(notes);
|
|
351
|
+
|
|
352
|
+
// Served by a public route or written at build time: security, x-access, x-data-class and problems per route.
|
|
353
|
+
export const openapi = generateOpenApiDocument(app, {
|
|
354
|
+
info: { title: 'Notes API', version: '1.0.0' },
|
|
355
|
+
schemaConverter: toJsonSchema,
|
|
356
|
+
securitySchemes: { session: { type: 'apiKey', in: 'cookie', name: '__Host-tupik_session' } },
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
// In the front end: no code generation, types come from `typeof app`.
|
|
360
|
+
const client = createTypedClient<typeof app>({ baseUrl: 'https://api.example.com', credentials: 'include', timeout: 10_000 });
|
|
361
|
+
const result = await client.get('/notes/:id', { params: { id: 'n1' } });
|
|
362
|
+
if (result.ok) console.log(result.data.title);
|
|
363
|
+
else if (result.kind === 'problem') console.log(result.error.code); // 'NOTE_ARCHIVED' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND'
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
Import the app type only (`import type { app }`) in browser code so no server code ships to the client.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# Tooling: prove the rules hold
|
|
2
|
+
|
|
3
|
+
Types catch a missing `access`. These tools catch the rest. Run all of them before finishing a change.
|
|
4
|
+
|
|
5
|
+
| Tool | Package | Catches |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| `tupik audit <module>` | `@tupik/openapi` | public routes, `pii`/`health` on public routes (error; accept per route with a reason), writes without rate limit, `:id` routes without owner or policy, breaking contract changes with `--baseline` |
|
|
8
|
+
| `tupik fuzz <module>` | `@tupik/testing` (also `tupik-fuzz`) | 5xx on hostile input, leaked `secret`/`health` fields, cross-principal access, prototype pollution |
|
|
9
|
+
| `tupik-lint <paths>` | `@tupik/lint` | unscoped lookups by id (BOLA), raw rows returned, request data in logs, hard-coded secrets |
|
|
10
|
+
| `generateAccessTests(app, ...)` | `@tupik/testing` | 401 without principal; owner served; other principal gets 403/404 |
|
|
11
|
+
| `tupik data-map <module>` | `@tupik/openapi` | personal data inventory (LGPD/GDPR) per route |
|
|
12
|
+
| `tupik contract check` | `@tupik/openapi` | removed routes, new required inputs, access changes against a baseline |
|
|
13
|
+
|
|
14
|
+
`<module>` is a file that exports the app as `default` or `app` (built JS, or `src/app.ts` through `tsx`/`bun`).
|
|
15
|
+
|
|
16
|
+
## Commands
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx tupik audit src/app.ts --fail-on error # --format sarif --out audit.sarif for code scanning
|
|
20
|
+
npx tupik fuzz src/app.ts --principals test/principals.json --fixtures test/fixtures.json --seed 7
|
|
21
|
+
npx tupik-lint src # --format sarif for GitHub code scanning
|
|
22
|
+
npx tupik data-map src/app.ts --out docs/data-map.md
|
|
23
|
+
npx tupik contract check src/app.ts --baseline contract.json --fail-on-breaking
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Exit codes: `0` clean, `1` findings (or failures), `2` bad usage, `3` error (audit, fuzz, contract).
|
|
27
|
+
`tupik-lint` exits `1` only on `error` findings; treat its warnings as review items, not noise.
|
|
28
|
+
|
|
29
|
+
`principals.json` holds two signed-in callers and, optionally, `anonymous`: what a request without a principal
|
|
30
|
+
still sends (for example an anonymous CSRF cookie and header, so it passes `csrf()` and gets its 401 from
|
|
31
|
+
`access`). `fixtures.json` holds one valid request per route, keyed by `'METHOD /path'`, whose params name a
|
|
32
|
+
record owned by `owner`:
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{ "owner": { "headers": { "authorization": "Bearer ana" } }, "other": { "headers": { "authorization": "Bearer bia" } } }
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
{ "GET /notes/:id": { "params": { "id": "note-of-ana" } }, "POST /notes": { "body": { "title": "t", "text": "x" } } }
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
## In the test suite
|
|
43
|
+
|
|
44
|
+
```ts compile
|
|
45
|
+
import { createApp, createModule } from '@tupik/core';
|
|
46
|
+
import { fuzz, generateAccessTests } from '@tupik/testing';
|
|
47
|
+
import { describe, expect, it } from 'vitest';
|
|
48
|
+
import { z } from 'zod';
|
|
49
|
+
|
|
50
|
+
interface User { id: string }
|
|
51
|
+
declare module '@tupik/core' {
|
|
52
|
+
interface TupikRegister { principal: User }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const notes = new Map([['note-of-ana', { id: 'note-of-ana', ownerId: 'ana', title: 'hi' }]]);
|
|
56
|
+
const app = createApp({
|
|
57
|
+
authenticate: (ctx) => {
|
|
58
|
+
const id = ctx.req.headers.get('authorization')?.replace(/^Bearer /, '');
|
|
59
|
+
return id === 'ana' || id === 'bia' ? { id } : null;
|
|
60
|
+
},
|
|
61
|
+
}).register(
|
|
62
|
+
createModule('/notes').get('/:id', {
|
|
63
|
+
access: { owner: (ctx) => notes.get(ctx.params.id)?.ownerId },
|
|
64
|
+
schema: { params: z.object({ id: z.string().max(64) }) },
|
|
65
|
+
handler: (ctx) => notes.get(ctx.params.id),
|
|
66
|
+
}),
|
|
67
|
+
);
|
|
68
|
+
|
|
69
|
+
const principals = { owner: { headers: { authorization: 'Bearer ana' } }, other: { headers: { authorization: 'Bearer bia' } } };
|
|
70
|
+
const fixtures = { 'GET /notes/:id': { params: { id: 'note-of-ana' } } };
|
|
71
|
+
|
|
72
|
+
describe('access rules', () => {
|
|
73
|
+
for (const test of generateAccessTests(app, { principals, fixtures })) (test.skip ? it.skip : it)(test.name, test.run);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('survives hostile input', async () => {
|
|
77
|
+
const report = await fuzz(app, { principals, fixtures, foreignIds: ['note-of-bia'], seed: 1 });
|
|
78
|
+
expect(report.failures).toEqual([]);
|
|
79
|
+
});
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
A skipped access case means a fixture is missing: add it instead of leaving the skip. When middleware such as
|
|
83
|
+
`csrf()` answers a request without a principal before `access` (403 instead of 401), give
|
|
84
|
+
`principals.anonymous` the credentials of a guest (`{ headers: { cookie, 'x-csrf-token' } }`), not the fixtures.
|
|
85
|
+
|
|
86
|
+
## Accepting an audit finding
|
|
87
|
+
|
|
88
|
+
Some findings are true and intended: sign-up and sign-in must be public and receive the e-mail. Accept them on
|
|
89
|
+
the route, with the reason; the report keeps them as `note` with `accepted: <reason>` (SARIF: suppressed in
|
|
90
|
+
source). There is no global switch.
|
|
91
|
+
|
|
92
|
+
```ts compile
|
|
93
|
+
import { classify, createModule } from '@tupik/core';
|
|
94
|
+
import { acceptAudit } from '@tupik/openapi';
|
|
95
|
+
import { z } from 'zod';
|
|
96
|
+
|
|
97
|
+
const Credentials = classify(z.object({ email: z.email().max(254), password: z.string().min(12).max(1024) }), { email: 'pii', password: 'secret' });
|
|
98
|
+
|
|
99
|
+
export const auth = createModule('/auth', { access: 'public' }).post('/login', {
|
|
100
|
+
tags: [acceptAudit('public-sensitive-data', 'sign-in must be public and receive the e-mail; rate limited per IP')],
|
|
101
|
+
schema: { body: Credentials },
|
|
102
|
+
handler: () => ({ ok: true }),
|
|
103
|
+
});
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## Other helpers from `@tupik/testing`
|
|
107
|
+
|
|
108
|
+
- `createTestApp(app)`: `get`/`post`/`put`/`patch`/`delete`/`inject` through `app.fetch`, no socket.
|
|
109
|
+
- `expectContract(app, { method, path, request, expect })`: the response matches `schema.response[status]`.
|
|
110
|
+
- `expectProblem(response, { status, type })`: an RFC 9457 problem; takes a `Response` or the result of `createTestApp`.
|
|
111
|
+
|
|
112
|
+
## MCP
|
|
113
|
+
|
|
114
|
+
`createMcpServer(app, { name, version })` from `@tupik/mcp` exposes routes tagged `tags: ['mcp']` as MCP tools.
|
|
115
|
+
Calls go through `app.fetch` with the caller's `authorization`/`cookie`, so access rules apply unchanged, and
|
|
116
|
+
`pii`/`health` fields are removed unless `allowDataClasses` releases them. Do not tag a route for MCP to bypass
|
|
117
|
+
its access rule; there is no bypass.
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-tupik",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Scaffold a new Tupik app: pnpm create tupik.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"tupik",
|
|
8
|
+
"typescript",
|
|
9
|
+
"web-framework",
|
|
10
|
+
"scaffold",
|
|
11
|
+
"cli",
|
|
12
|
+
"create"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/CodeHamper/tupikjs/tree/main/packages/create-tupik#readme",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/CodeHamper/tupikjs.git",
|
|
18
|
+
"directory": "packages/create-tupik"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/CodeHamper/tupikjs/issues"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"bin": {
|
|
31
|
+
"create-tupik": "./dist/index.mjs"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=22.12"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"typescript": "^5.6.0",
|
|
39
|
+
"unbuild": "^3.0.0",
|
|
40
|
+
"vitest": "^2.1.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "unbuild",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "vitest run"
|
|
46
|
+
}
|
|
6
47
|
}
|