@codelitdev/platform-cli 0.1.0-alpha.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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.d.ts +2 -0
  3. package/dist/bin.js +43 -0
  4. package/dist/codemod-readme-title.d.ts +5 -0
  5. package/dist/codemod-readme-title.js +21 -0
  6. package/dist/create.d.ts +6 -0
  7. package/dist/create.js +124 -0
  8. package/dist/doctor.d.ts +12 -0
  9. package/dist/doctor.js +111 -0
  10. package/dist/fs.d.ts +5 -0
  11. package/dist/fs.js +42 -0
  12. package/dist/git.d.ts +1 -0
  13. package/dist/git.js +19 -0
  14. package/dist/hash.d.ts +2 -0
  15. package/dist/hash.js +8 -0
  16. package/dist/index.d.ts +4 -0
  17. package/dist/index.js +4 -0
  18. package/dist/manifest.d.ts +12 -0
  19. package/dist/manifest.js +31 -0
  20. package/dist/template.d.ts +2 -0
  21. package/dist/template.js +23 -0
  22. package/dist/upgrade.d.ts +13 -0
  23. package/dist/upgrade.js +97 -0
  24. package/package.json +41 -0
  25. package/template/.github/workflows/platform-conformance.yml +28 -0
  26. package/template/README.md +5 -0
  27. package/template/apps/api/.env.example +18 -0
  28. package/template/apps/api/README.md +3 -0
  29. package/template/apps/api/billing.config.ts +25 -0
  30. package/template/apps/api/drizzle.config.ts +7 -0
  31. package/template/apps/api/package.json +53 -0
  32. package/template/apps/api/scripts/generate-auth-schema.mjs +173 -0
  33. package/template/apps/api/scripts/migrate.mjs +15 -0
  34. package/template/apps/api/src/app.test.ts +479 -0
  35. package/template/apps/api/src/auth/api-keys.ts +131 -0
  36. package/template/apps/api/src/auth/authenticate.ts +166 -0
  37. package/template/apps/api/src/auth/better-auth.ts +38 -0
  38. package/template/apps/api/src/auth/oauth.ts +9 -0
  39. package/template/apps/api/src/auth/options.ts +69 -0
  40. package/template/apps/api/src/billing.ts +58 -0
  41. package/template/apps/api/src/conformance-adapter.ts +335 -0
  42. package/template/apps/api/src/db/migrate.ts +26 -0
  43. package/template/apps/api/src/db/migrations/0000_application.sql +72 -0
  44. package/template/apps/api/src/db/migrations/0000_auth.sql +178 -0
  45. package/template/apps/api/src/db/migrations/0001_billing.sql +234 -0
  46. package/template/apps/api/src/db/schema/auth.generated.ts +185 -0
  47. package/template/apps/api/src/db/schema/billing.generated.ts +447 -0
  48. package/template/apps/api/src/db/schema/index.ts +3 -0
  49. package/template/apps/api/src/db/schema/notes.ts +31 -0
  50. package/template/apps/api/src/db/schema/tenants.ts +83 -0
  51. package/template/apps/api/src/deps.ts +12 -0
  52. package/template/apps/api/src/dispatch.ts +476 -0
  53. package/template/apps/api/src/express-app.ts +161 -0
  54. package/template/apps/api/src/invitations.ts +217 -0
  55. package/template/apps/api/src/logger.ts +26 -0
  56. package/template/apps/api/src/main.ts +98 -0
  57. package/template/apps/api/src/mcp.ts +127 -0
  58. package/template/apps/api/src/notes.ts +251 -0
  59. package/template/apps/api/src/openapi.ts +12 -0
  60. package/template/apps/api/src/permissions.ts +35 -0
  61. package/template/apps/api/src/runtime.ts +167 -0
  62. package/template/apps/api/src/seed.ts +340 -0
  63. package/template/apps/api/src/tenancy.ts +116 -0
  64. package/template/apps/api/src/types.ts +20 -0
  65. package/template/apps/api/src/worker.ts +57 -0
  66. package/template/apps/api/tsconfig.json +14 -0
  67. package/template/apps/web/.env.example +7 -0
  68. package/template/apps/web/app/api/[...path]/route.ts +51 -0
  69. package/template/apps/web/app/globals.css +156 -0
  70. package/template/apps/web/app/layout.tsx +34 -0
  71. package/template/apps/web/app/login/page.tsx +127 -0
  72. package/template/apps/web/app/notes/page.tsx +93 -0
  73. package/template/apps/web/app/page.tsx +80 -0
  74. package/template/apps/web/components/auth-gate.tsx +34 -0
  75. package/template/apps/web/components/browser-observability.tsx +53 -0
  76. package/template/apps/web/components/tenant-switcher.tsx +51 -0
  77. package/template/apps/web/lib/observability-config.ts +15 -0
  78. package/template/apps/web/next-env.d.ts +2 -0
  79. package/template/apps/web/next.config.ts +7 -0
  80. package/template/apps/web/package.json +26 -0
  81. package/template/apps/web/tsconfig.json +21 -0
  82. package/template/biome.template.json +50 -0
  83. package/template/docker-compose.yml +14 -0
  84. package/template/package.json +40 -0
  85. package/template/packages/api-contract/package.json +23 -0
  86. package/template/packages/api-contract/src/index.ts +256 -0
  87. package/template/packages/api-contract/src/mcp-parity.ts +158 -0
  88. package/template/packages/api-contract/tsconfig.json +11 -0
  89. package/template/patches/@anatine__zod-openapi@1.14.2.patch +14 -0
  90. package/template/tooling/platform/config.ts +2 -0
@@ -0,0 +1,476 @@
1
+ import {
2
+ createNoteBodySchema,
3
+ updateNoteBodySchema,
4
+ } from "@__PRODUCT_SLUG__/api-contract";
5
+ import {
6
+ captureAndMapException,
7
+ createPlatformError,
8
+ createPublicId,
9
+ healthReport,
10
+ type PlatformRequestContext,
11
+ readinessReport,
12
+ readOrCreateRequestId,
13
+ toPublicHttpError,
14
+ uuidv7,
15
+ } from "@codelitdev/platform";
16
+ import { eq } from "drizzle-orm";
17
+ import {
18
+ createApiKeyRecord,
19
+ listApiKeyRecords,
20
+ revokeApiKey,
21
+ } from "./auth/api-keys.js";
22
+ import { authenticateHttpRequest } from "./auth/authenticate.js";
23
+ import * as schema from "./db/schema/index.js";
24
+ import type { DispatchDeps } from "./deps.js";
25
+ import { acceptInvitation, createInvitation, revokeInvitation } from "./invitations.js";
26
+ import { createReferenceMcp } from "./mcp.js";
27
+ import { createNote, deleteNote, listNotes, updateNote } from "./notes.js";
28
+ import { createOpenApiDocument } from "./openapi.js";
29
+ import { REFERENCE_PERMISSIONS, type ReferencePermission } from "./permissions.js";
30
+ import { headerTenantId, resolveTenantContext } from "./tenancy.js";
31
+ import type { DispatchResponse, IncomingRequest } from "./types.js";
32
+
33
+ export type { DispatchDeps };
34
+
35
+ const mcpKits = new WeakMap<DispatchDeps, ReturnType<typeof createReferenceMcp>>();
36
+
37
+ export function mcpFor(deps: DispatchDeps) {
38
+ const existing = mcpKits.get(deps);
39
+ if (existing) return existing;
40
+ const created = createReferenceMcp(deps);
41
+ mcpKits.set(deps, created);
42
+ return created;
43
+ }
44
+
45
+ function requestHeaders(request: IncomingRequest) {
46
+ return request.headers;
47
+ }
48
+
49
+ function errorResponse(
50
+ error: ReturnType<typeof createPlatformError>,
51
+ ): DispatchResponse {
52
+ const mapped = toPublicHttpError(error);
53
+ return { status: mapped.status, body: mapped.body };
54
+ }
55
+
56
+ export async function dispatch(
57
+ deps: DispatchDeps,
58
+ request: IncomingRequest,
59
+ ): Promise<DispatchResponse> {
60
+ try {
61
+ const path = request.path.split("?")[0] ?? request.path;
62
+ if (request.method === "GET" && path === "/health") {
63
+ return {
64
+ status: 200,
65
+ body: healthReport(deps.serviceName, deps.clock),
66
+ };
67
+ }
68
+ if (request.method === "GET" && path === "/ready") {
69
+ const report = readinessReport([{ name: "database", ready: deps.databaseReady }]);
70
+ return {
71
+ status: report.status === "ready" ? 200 : 503,
72
+ body: report,
73
+ };
74
+ }
75
+ if (request.method === "GET" && path === "/openapi.json") {
76
+ return {
77
+ status: 200,
78
+ body: createOpenApiDocument(deps.auth.publicApiUrl),
79
+ };
80
+ }
81
+
82
+ if (path === "/mcp") {
83
+ const mcp = mcpFor(deps);
84
+ const result = await mcp.handle({
85
+ method: request.method,
86
+ headers: request.headers,
87
+ body: request.body,
88
+ });
89
+ return {
90
+ status: result.status,
91
+ body: result.body,
92
+ headers: result.headers,
93
+ };
94
+ }
95
+
96
+ const auth = await authenticateHttpRequest(requestHeaders(request), deps);
97
+ if (auth.kind !== "authenticated") {
98
+ const error =
99
+ auth.kind === "rejected" ? auth.error : createPlatformError("unauthenticated");
100
+ return errorResponse(error);
101
+ }
102
+
103
+ if (request.method === "POST" && path === "/api/tenant/select") {
104
+ if (auth.credential.kind === "api_key") {
105
+ return errorResponse(createPlatformError("forbidden"));
106
+ }
107
+ const tenantId =
108
+ request.body &&
109
+ typeof request.body === "object" &&
110
+ typeof (request.body as { tenantId?: unknown }).tenantId === "string"
111
+ ? (request.body as { tenantId: string }).tenantId
112
+ : "";
113
+ if (!tenantId) return errorResponse(createPlatformError("validation_failed"));
114
+ const resolved = await resolveTenantContext({
115
+ db: deps.db,
116
+ principalId: auth.principalId,
117
+ credential: auth.credential,
118
+ requestedPublicTenantId: tenantId,
119
+ });
120
+ if (!resolved.ok) return errorResponse(resolved.error);
121
+ const requestId = readOrCreateRequestId(
122
+ typeof request.headers["x-request-id"] === "string"
123
+ ? request.headers["x-request-id"]
124
+ : undefined,
125
+ deps.clock,
126
+ );
127
+ await deps.db.transaction(async (tx) => {
128
+ await tx
129
+ .delete(schema.selectedTenants)
130
+ .where(eq(schema.selectedTenants.userId, auth.principalId));
131
+ await tx.insert(schema.selectedTenants).values({
132
+ userId: auth.principalId,
133
+ tenantId: resolved.value.tenantId,
134
+ });
135
+ await tx.insert(schema.auditEvents).values({
136
+ id: uuidv7(deps.clock),
137
+ tenantId: resolved.value.tenantId,
138
+ actorId: auth.principalId,
139
+ action: "tenant.selected",
140
+ resourceType: "tenant",
141
+ resourceId: resolved.value.publicId,
142
+ requestId,
143
+ createdAt: deps.clock.now(),
144
+ });
145
+ });
146
+ return { status: 204, body: undefined };
147
+ }
148
+ if (request.method === "GET" && path === "/v1/tenants") {
149
+ if (auth.credential.kind === "api_key") {
150
+ return errorResponse(createPlatformError("forbidden"));
151
+ }
152
+ const selectedRows = await deps.db
153
+ .select({ publicId: schema.tenants.publicId })
154
+ .from(schema.selectedTenants)
155
+ .innerJoin(
156
+ schema.tenants,
157
+ eq(schema.tenants.id, schema.selectedTenants.tenantId),
158
+ )
159
+ .where(eq(schema.selectedTenants.userId, auth.principalId))
160
+ .limit(1);
161
+ const selectedTenantPublicId = selectedRows[0]?.publicId;
162
+ const rows = await deps.db
163
+ .select({
164
+ publicId: schema.tenants.publicId,
165
+ name: schema.tenants.name,
166
+ })
167
+ .from(schema.memberships)
168
+ .innerJoin(schema.tenants, eq(schema.tenants.id, schema.memberships.tenantId))
169
+ .where(eq(schema.memberships.userId, auth.principalId));
170
+ return {
171
+ status: 200,
172
+ body: {
173
+ items: rows.map((row) => ({
174
+ id: row.publicId,
175
+ name: row.name,
176
+ selected: row.publicId === selectedTenantPublicId,
177
+ })),
178
+ },
179
+ };
180
+ }
181
+ if (request.method === "POST" && path === "/v1/tenants") {
182
+ if (auth.credential.kind === "api_key") {
183
+ return errorResponse(createPlatformError("forbidden"));
184
+ }
185
+ const name =
186
+ request.body &&
187
+ typeof request.body === "object" &&
188
+ typeof (request.body as { name?: unknown }).name === "string"
189
+ ? (request.body as { name: string }).name.trim()
190
+ : "";
191
+ if (!name || name.length > 200)
192
+ return errorResponse(createPlatformError("validation_failed"));
193
+ const now = deps.clock.now();
194
+ const tenantId = uuidv7(deps.clock);
195
+ const publicId = createPublicId("tnt", deps.clock);
196
+ const requestId = readOrCreateRequestId(
197
+ typeof request.headers["x-request-id"] === "string"
198
+ ? request.headers["x-request-id"]
199
+ : undefined,
200
+ deps.clock,
201
+ );
202
+ await deps.db.transaction(async (tx) => {
203
+ await tx
204
+ .insert(schema.tenants)
205
+ .values({ id: tenantId, publicId, name, createdAt: now });
206
+ await tx.insert(schema.memberships).values({
207
+ id: uuidv7(deps.clock),
208
+ tenantId,
209
+ userId: auth.principalId,
210
+ role: "owner",
211
+ isOwner: true,
212
+ permissions: "notes:read,notes:write,notes:delete,tenant:admin,billing:read",
213
+ createdAt: now,
214
+ });
215
+ await tx.insert(schema.auditEvents).values({
216
+ id: uuidv7(deps.clock),
217
+ tenantId,
218
+ actorId: auth.principalId,
219
+ action: "tenant.created",
220
+ resourceType: "tenant",
221
+ resourceId: publicId,
222
+ requestId,
223
+ createdAt: now,
224
+ });
225
+ await tx
226
+ .delete(schema.selectedTenants)
227
+ .where(eq(schema.selectedTenants.userId, auth.principalId));
228
+ await tx
229
+ .insert(schema.selectedTenants)
230
+ .values({ userId: auth.principalId, tenantId });
231
+ });
232
+ return { status: 201, body: { id: publicId, name, selected: true } };
233
+ }
234
+ if (request.method === "POST" && path === "/v1/invitations/accept") {
235
+ if (auth.credential.kind === "api_key") {
236
+ return errorResponse(createPlatformError("forbidden"));
237
+ }
238
+ const input = request.body as { token?: unknown; email?: unknown } | undefined;
239
+ if (typeof input?.token !== "string" || typeof input.email !== "string") {
240
+ return errorResponse(createPlatformError("validation_failed"));
241
+ }
242
+ const result = await acceptInvitation(
243
+ deps.db,
244
+ {
245
+ requestId: readOrCreateRequestId(
246
+ typeof request.headers["x-request-id"] === "string"
247
+ ? request.headers["x-request-id"]
248
+ : undefined,
249
+ deps.clock,
250
+ ),
251
+ principalId: auth.principalId,
252
+ tenantId: null,
253
+ credential: auth.credential,
254
+ permissions: new Set(),
255
+ },
256
+ input.token,
257
+ input.email,
258
+ deps.clock,
259
+ );
260
+ return result.ok ? { status: 200, body: result } : errorResponse(result.error);
261
+ }
262
+
263
+ const tenant = await resolveTenantContext({
264
+ db: deps.db,
265
+ principalId: auth.principalId,
266
+ credential: auth.credential,
267
+ requestedPublicTenantId: headerTenantId(request.headers),
268
+ });
269
+ if (!tenant.ok) return errorResponse(tenant.error);
270
+
271
+ const context: PlatformRequestContext<string, string, ReferencePermission> = {
272
+ requestId: readOrCreateRequestId(
273
+ typeof request.headers["x-request-id"] === "string"
274
+ ? request.headers["x-request-id"]
275
+ : undefined,
276
+ deps.clock,
277
+ ),
278
+ principalId: auth.principalId,
279
+ tenantId: tenant.value.tenantId,
280
+ credential: auth.credential,
281
+ permissions: tenant.value.permissions,
282
+ };
283
+
284
+ if (request.method === "POST" && path === "/v1/api-keys") {
285
+ if (!context.permissions.has("tenant:admin")) {
286
+ return errorResponse(createPlatformError("forbidden"));
287
+ }
288
+ const input = request.body as
289
+ | {
290
+ permissions?: unknown;
291
+ expiresAt?: unknown;
292
+ }
293
+ | undefined;
294
+ const permissions = Array.isArray(input?.permissions) ? input.permissions : [];
295
+ const expiresAt =
296
+ typeof input?.expiresAt === "string" ? new Date(input.expiresAt) : undefined;
297
+ if (
298
+ expiresAt &&
299
+ (Number.isNaN(expiresAt.getTime()) || expiresAt <= deps.clock.now())
300
+ ) {
301
+ return errorResponse(createPlatformError("validation_failed"));
302
+ }
303
+ if (
304
+ !permissions.every(
305
+ (value): value is string =>
306
+ typeof value === "string" &&
307
+ (REFERENCE_PERMISSIONS as readonly string[]).includes(value),
308
+ )
309
+ ) {
310
+ return errorResponse(createPlatformError("validation_failed"));
311
+ }
312
+ const key = await createApiKeyRecord({
313
+ db: deps.db,
314
+ tenantId: context.tenantId!,
315
+ userId: context.principalId,
316
+ permissions,
317
+ pepper: deps.apiKeyPepper,
318
+ clock: deps.clock,
319
+ expiresAt,
320
+ audit: { requestId: context.requestId },
321
+ });
322
+ return { status: 201, body: key };
323
+ }
324
+ if (request.method === "GET" && path === "/v1/api-keys") {
325
+ if (!context.permissions.has("tenant:admin")) {
326
+ return errorResponse(createPlatformError("forbidden"));
327
+ }
328
+ const keys = await listApiKeyRecords(deps.db, context.tenantId!);
329
+ return {
330
+ status: 200,
331
+ body: {
332
+ items: keys.map((key) => ({
333
+ id: key.id,
334
+ publicId: key.publicId,
335
+ expiresAt: key.expiresAt?.toISOString() ?? null,
336
+ revokedAt: key.revokedAt?.toISOString() ?? null,
337
+ lastUsedAt: key.lastUsedAt?.toISOString() ?? null,
338
+ createdAt: key.createdAt.toISOString(),
339
+ })),
340
+ },
341
+ };
342
+ }
343
+ const revokeMatch = /^\/v1\/api-keys\/([^/]+)$/.exec(path);
344
+ if (request.method === "DELETE" && revokeMatch) {
345
+ if (!context.permissions.has("tenant:admin")) {
346
+ return errorResponse(createPlatformError("forbidden"));
347
+ }
348
+ const revoked = await revokeApiKey(
349
+ deps.db,
350
+ decodeURIComponent(revokeMatch[1]!),
351
+ context.tenantId!,
352
+ deps.clock,
353
+ { actorId: context.principalId, requestId: context.requestId },
354
+ );
355
+ return revoked
356
+ ? { status: 204, body: null }
357
+ : errorResponse(createPlatformError("not_found"));
358
+ }
359
+ if (request.method === "POST" && path === "/v1/invitations") {
360
+ const input = request.body as
361
+ | {
362
+ email?: unknown;
363
+ role?: unknown;
364
+ permissions?: unknown;
365
+ }
366
+ | undefined;
367
+ const permissions = Array.isArray(input?.permissions) ? input.permissions : [];
368
+ if (
369
+ typeof input?.email !== "string" ||
370
+ typeof input.role !== "string" ||
371
+ !permissions.every(
372
+ (value): value is ReferencePermission =>
373
+ typeof value === "string" &&
374
+ (REFERENCE_PERMISSIONS as readonly string[]).includes(value),
375
+ )
376
+ ) {
377
+ return errorResponse(createPlatformError("validation_failed"));
378
+ }
379
+ const result = await createInvitation(
380
+ deps.db,
381
+ context,
382
+ { email: input.email, role: input.role, permissions },
383
+ deps.clock,
384
+ );
385
+ return result.ok ? { status: 201, body: result } : errorResponse(result.error);
386
+ }
387
+ const invitationMatch = /^\/v1\/invitations\/([^/]+)$/.exec(path);
388
+ if (request.method === "DELETE" && invitationMatch) {
389
+ const result = await revokeInvitation(
390
+ deps.db,
391
+ context,
392
+ decodeURIComponent(invitationMatch[1]!),
393
+ deps.clock,
394
+ );
395
+ return result.ok ? { status: 204, body: null } : errorResponse(result.error);
396
+ }
397
+
398
+ if (request.method === "GET" && path === "/v1/notes") {
399
+ const result = await listNotes(deps.db, context, tenant.value.publicId);
400
+ if (!result.ok) return errorResponse(result.error);
401
+ return { status: 200, body: { items: result.value } };
402
+ }
403
+
404
+ if (request.method === "POST" && path === "/v1/notes") {
405
+ const parsed = createNoteBodySchema.safeParse(request.body ?? {});
406
+ if (!parsed.success) {
407
+ return errorResponse(createPlatformError("validation_failed"));
408
+ }
409
+ const result = await createNote(
410
+ deps.db,
411
+ context,
412
+ tenant.value.publicId,
413
+ parsed.data,
414
+ deps.clock,
415
+ );
416
+ if (!result.ok) return errorResponse(result.error);
417
+ return { status: 201, body: result.value };
418
+ }
419
+
420
+ const noteMatch = /^\/v1\/notes\/([^/]+)$/.exec(path);
421
+ if (request.method === "PATCH" && noteMatch) {
422
+ const parsed = updateNoteBodySchema.safeParse(request.body ?? {});
423
+ if (!parsed.success) {
424
+ return errorResponse(createPlatformError("validation_failed"));
425
+ }
426
+ const result = await updateNote(
427
+ deps.db,
428
+ context,
429
+ tenant.value.publicId,
430
+ decodeURIComponent(noteMatch[1]!),
431
+ parsed.data,
432
+ deps.clock,
433
+ );
434
+ if (!result.ok) return errorResponse(result.error);
435
+ return { status: 200, body: result.value };
436
+ }
437
+ if (request.method === "DELETE" && noteMatch) {
438
+ const result = await deleteNote(
439
+ deps.db,
440
+ context,
441
+ decodeURIComponent(noteMatch[1]!),
442
+ deps.clock,
443
+ );
444
+ if (!result.ok) return errorResponse(result.error);
445
+ return { status: 200, body: result.value };
446
+ }
447
+
448
+ if (request.method === "GET" && path === "/v1/billing/entitlement") {
449
+ if (!context.permissions.has("billing:read")) {
450
+ return errorResponse(createPlatformError("forbidden"));
451
+ }
452
+ const state = await deps.billing.billing.commercialState(context.tenantId!);
453
+ return {
454
+ status: 200,
455
+ body: {
456
+ tenantId: tenant.value.publicId,
457
+ activePaidPlan: state.activePaidPlan,
458
+ entitled: state.activePaidPlan !== null,
459
+ subscriptionStatus: state.subscriptionStatus,
460
+ },
461
+ };
462
+ }
463
+
464
+ return errorResponse(createPlatformError("not_found"));
465
+ } catch (thrown) {
466
+ return errorResponse(
467
+ captureAndMapException(thrown, (error) =>
468
+ deps.observability?.captureException({
469
+ error,
470
+ source: "http.dispatch",
471
+ context: { method: request.method, path: request.path },
472
+ }),
473
+ ),
474
+ );
475
+ }
476
+ }
@@ -0,0 +1,161 @@
1
+ import { contract } from "@__PRODUCT_SLUG__/api-contract";
2
+ import { createOAuthPagesRouter } from "@codelitdev/oauth-server-kit/express";
3
+ import { readOrCreateRequestId } from "@codelitdev/platform";
4
+ import { createExpressEndpoints, initServer } from "@ts-rest/express";
5
+ import { toNodeHandler } from "better-auth/node";
6
+ import express, { type Express } from "express";
7
+ import { AUTH_BASE_PATH } from "./auth/options.js";
8
+ import type { DispatchDeps } from "./deps.js";
9
+ import { dispatch } from "./dispatch.js";
10
+
11
+ export function createExpressApp(deps: DispatchDeps): Express {
12
+ const app = express();
13
+ app.disable("x-powered-by");
14
+ const buckets = new Map<string, { window: number; count: number }>();
15
+ app.use((req, res, next) => {
16
+ res.setHeader("X-Content-Type-Options", "nosniff");
17
+ res.setHeader("X-Frame-Options", "DENY");
18
+ res.setHeader("Referrer-Policy", "no-referrer");
19
+ const requestId = readOrCreateRequestId(
20
+ typeof req.headers["x-request-id"] === "string"
21
+ ? req.headers["x-request-id"]
22
+ : undefined,
23
+ deps.clock,
24
+ );
25
+ // Keep the generated correlation ID on the request as well as the
26
+ // response so ts-rest and the fallback dispatcher audit the same value.
27
+ req.headers["x-request-id"] = requestId;
28
+ res.setHeader("X-Request-ID", requestId);
29
+ const now = Date.now();
30
+ const key = req.ip || req.socket.remoteAddress || "unknown";
31
+ const window = Math.floor(now / 60_000);
32
+ if (buckets.size > 10_000) buckets.clear();
33
+ const current = buckets.get(key);
34
+ if (!current || current.window !== window) {
35
+ buckets.set(key, { window, count: 1 });
36
+ } else if (current.count >= 120) {
37
+ res.status(429).json({
38
+ code: "rate_limited",
39
+ message: "The request was rate limited.",
40
+ });
41
+ return;
42
+ } else {
43
+ current.count += 1;
44
+ }
45
+ next();
46
+ });
47
+ app.all(`${AUTH_BASE_PATH}/*`, toNodeHandler(deps.auth.auth));
48
+ app.use(
49
+ createOAuthPagesRouter({
50
+ appName: "__PRODUCT_NAME__",
51
+ authBasePath: AUTH_BASE_PATH,
52
+ allowedRedirectOrigins: [new URL(deps.auth.webOrigin).origin],
53
+ defaultRedirectUrl: `${deps.auth.webOrigin}/`,
54
+ loginMethods: [{ type: "email-otp" }],
55
+ }),
56
+ );
57
+ app.use(express.json({ limit: "32kb" }));
58
+
59
+ const server = initServer();
60
+ const forward = async (input: {
61
+ req: {
62
+ method: string;
63
+ path: string;
64
+ headers: Record<string, string | string[] | undefined>;
65
+ body?: unknown;
66
+ };
67
+ res: { setHeader(name: string, value: string): void };
68
+ }) => {
69
+ const response = await dispatch(deps, {
70
+ method: input.req.method,
71
+ path: input.req.path,
72
+ headers: input.req.headers,
73
+ body: input.req.body,
74
+ });
75
+ for (const [name, value] of Object.entries(response.headers ?? {})) {
76
+ input.res.setHeader(name, value);
77
+ }
78
+ return { status: response.status, body: response.body } as never;
79
+ };
80
+ const router = server.router(contract, {
81
+ health: forward,
82
+ ready: forward,
83
+ listNotes: forward,
84
+ createNote: forward,
85
+ updateNote: forward,
86
+ deleteNote: forward,
87
+ getEntitlement: forward,
88
+ listTenants: forward,
89
+ createTenant: forward,
90
+ selectTenant: forward,
91
+ listApiKeys: forward,
92
+ createApiKey: forward,
93
+ revokeApiKey: forward,
94
+ createInvitation: forward,
95
+ acceptInvitation: forward,
96
+ revokeInvitation: forward,
97
+ } as never);
98
+ createExpressEndpoints(contract, router, app, {
99
+ logInitialization: false,
100
+ responseValidation: true,
101
+ requestValidationErrorHandler: (_error, _req, res) => {
102
+ res.status(400).json({
103
+ code: "validation_failed",
104
+ message: "The request body is invalid.",
105
+ });
106
+ },
107
+ });
108
+ app.use(async (req, res, next) => {
109
+ try {
110
+ const requestId = readOrCreateRequestId(
111
+ typeof req.headers["x-request-id"] === "string"
112
+ ? req.headers["x-request-id"]
113
+ : undefined,
114
+ deps.clock,
115
+ );
116
+ res.setHeader("X-Request-ID", requestId);
117
+ const response = await dispatch(deps, {
118
+ method: req.method,
119
+ path: req.path,
120
+ headers: req.headers as Record<string, string | string[] | undefined>,
121
+ body: req.body,
122
+ });
123
+ for (const [name, value] of Object.entries(response.headers ?? {})) {
124
+ res.setHeader(name, value);
125
+ }
126
+ if (response.body === null || response.body === undefined) {
127
+ res.status(response.status).end();
128
+ return;
129
+ }
130
+ res.status(response.status).json(response.body);
131
+ } catch (error) {
132
+ next(error);
133
+ }
134
+ });
135
+ app.use(
136
+ (
137
+ error: unknown,
138
+ req: express.Request,
139
+ res: express.Response,
140
+ next: express.NextFunction,
141
+ ) => {
142
+ deps.observability?.captureException({
143
+ error,
144
+ source: "express",
145
+ context: { method: req.method, path: req.path },
146
+ });
147
+ if (res.headersSent) {
148
+ next(error);
149
+ return;
150
+ }
151
+ const isSyntax = error instanceof SyntaxError;
152
+ res.status(isSyntax ? 400 : 500).json({
153
+ code: isSyntax ? "validation_failed" : "internal_error",
154
+ message: isSyntax
155
+ ? "The request body is invalid."
156
+ : "The request could not be completed.",
157
+ });
158
+ },
159
+ );
160
+ return app;
161
+ }