@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.
- package/LICENSE +21 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +43 -0
- package/dist/codemod-readme-title.d.ts +5 -0
- package/dist/codemod-readme-title.js +21 -0
- package/dist/create.d.ts +6 -0
- package/dist/create.js +124 -0
- package/dist/doctor.d.ts +12 -0
- package/dist/doctor.js +111 -0
- package/dist/fs.d.ts +5 -0
- package/dist/fs.js +42 -0
- package/dist/git.d.ts +1 -0
- package/dist/git.js +19 -0
- package/dist/hash.d.ts +2 -0
- package/dist/hash.js +8 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/manifest.d.ts +12 -0
- package/dist/manifest.js +31 -0
- package/dist/template.d.ts +2 -0
- package/dist/template.js +23 -0
- package/dist/upgrade.d.ts +13 -0
- package/dist/upgrade.js +97 -0
- package/package.json +41 -0
- package/template/.github/workflows/platform-conformance.yml +28 -0
- package/template/README.md +5 -0
- package/template/apps/api/.env.example +18 -0
- package/template/apps/api/README.md +3 -0
- package/template/apps/api/billing.config.ts +25 -0
- package/template/apps/api/drizzle.config.ts +7 -0
- package/template/apps/api/package.json +53 -0
- package/template/apps/api/scripts/generate-auth-schema.mjs +173 -0
- package/template/apps/api/scripts/migrate.mjs +15 -0
- package/template/apps/api/src/app.test.ts +479 -0
- package/template/apps/api/src/auth/api-keys.ts +131 -0
- package/template/apps/api/src/auth/authenticate.ts +166 -0
- package/template/apps/api/src/auth/better-auth.ts +38 -0
- package/template/apps/api/src/auth/oauth.ts +9 -0
- package/template/apps/api/src/auth/options.ts +69 -0
- package/template/apps/api/src/billing.ts +58 -0
- package/template/apps/api/src/conformance-adapter.ts +335 -0
- package/template/apps/api/src/db/migrate.ts +26 -0
- package/template/apps/api/src/db/migrations/0000_application.sql +72 -0
- package/template/apps/api/src/db/migrations/0000_auth.sql +178 -0
- package/template/apps/api/src/db/migrations/0001_billing.sql +234 -0
- package/template/apps/api/src/db/schema/auth.generated.ts +185 -0
- package/template/apps/api/src/db/schema/billing.generated.ts +447 -0
- package/template/apps/api/src/db/schema/index.ts +3 -0
- package/template/apps/api/src/db/schema/notes.ts +31 -0
- package/template/apps/api/src/db/schema/tenants.ts +83 -0
- package/template/apps/api/src/deps.ts +12 -0
- package/template/apps/api/src/dispatch.ts +476 -0
- package/template/apps/api/src/express-app.ts +161 -0
- package/template/apps/api/src/invitations.ts +217 -0
- package/template/apps/api/src/logger.ts +26 -0
- package/template/apps/api/src/main.ts +98 -0
- package/template/apps/api/src/mcp.ts +127 -0
- package/template/apps/api/src/notes.ts +251 -0
- package/template/apps/api/src/openapi.ts +12 -0
- package/template/apps/api/src/permissions.ts +35 -0
- package/template/apps/api/src/runtime.ts +167 -0
- package/template/apps/api/src/seed.ts +340 -0
- package/template/apps/api/src/tenancy.ts +116 -0
- package/template/apps/api/src/types.ts +20 -0
- package/template/apps/api/src/worker.ts +57 -0
- package/template/apps/api/tsconfig.json +14 -0
- package/template/apps/web/.env.example +7 -0
- package/template/apps/web/app/api/[...path]/route.ts +51 -0
- package/template/apps/web/app/globals.css +156 -0
- package/template/apps/web/app/layout.tsx +34 -0
- package/template/apps/web/app/login/page.tsx +127 -0
- package/template/apps/web/app/notes/page.tsx +93 -0
- package/template/apps/web/app/page.tsx +80 -0
- package/template/apps/web/components/auth-gate.tsx +34 -0
- package/template/apps/web/components/browser-observability.tsx +53 -0
- package/template/apps/web/components/tenant-switcher.tsx +51 -0
- package/template/apps/web/lib/observability-config.ts +15 -0
- package/template/apps/web/next-env.d.ts +2 -0
- package/template/apps/web/next.config.ts +7 -0
- package/template/apps/web/package.json +26 -0
- package/template/apps/web/tsconfig.json +21 -0
- package/template/biome.template.json +50 -0
- package/template/docker-compose.yml +14 -0
- package/template/package.json +40 -0
- package/template/packages/api-contract/package.json +23 -0
- package/template/packages/api-contract/src/index.ts +256 -0
- package/template/packages/api-contract/src/mcp-parity.ts +158 -0
- package/template/packages/api-contract/tsconfig.json +11 -0
- package/template/patches/@anatine__zod-openapi@1.14.2.patch +14 -0
- package/template/tooling/platform/config.ts +2 -0
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
import { contract } from "@__PRODUCT_SLUG__/api-contract";
|
|
2
|
+
import { describe, expect, it } from "bun:test";
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
import { createReferenceAuth } from "./auth/better-auth.js";
|
|
5
|
+
import { composeOAuthProviderOptions } from "./auth/oauth.js";
|
|
6
|
+
import * as schema from "./db/schema/index.js";
|
|
7
|
+
import { dispatch } from "./dispatch.js";
|
|
8
|
+
import { createExpressApp } from "./express-app.js";
|
|
9
|
+
import { createPgliteRuntime, freezeRuntimeClock } from "./runtime.js";
|
|
10
|
+
import { seedWorld } from "./seed.js";
|
|
11
|
+
|
|
12
|
+
describe.serial("reference API adapters", () => {
|
|
13
|
+
it("does not run DDL when oauth-server-kit options and schema modules are imported", async () => {
|
|
14
|
+
const { PGlite } = await import("@electric-sql/pglite");
|
|
15
|
+
const client = new PGlite();
|
|
16
|
+
composeOAuthProviderOptions("http://127.0.0.1:4000");
|
|
17
|
+
await import("./db/schema/index.js");
|
|
18
|
+
await import("./db/schema/billing.generated.js");
|
|
19
|
+
const tables = await client.query(
|
|
20
|
+
"select tablename from pg_tables where schemaname = 'public'",
|
|
21
|
+
);
|
|
22
|
+
expect(tables.rows).toEqual([]);
|
|
23
|
+
const { drizzle } = await import("drizzle-orm/pglite");
|
|
24
|
+
const db = drizzle(client);
|
|
25
|
+
const auth = createReferenceAuth({
|
|
26
|
+
db: db as never,
|
|
27
|
+
publicApiUrl: "http://127.0.0.1:4000",
|
|
28
|
+
secret: "test-secret-that-is-at-least-thirty-two-characters",
|
|
29
|
+
});
|
|
30
|
+
await auth.auth.$context.catch(() => undefined);
|
|
31
|
+
const after = await client.query(
|
|
32
|
+
"select tablename from pg_tables where schemaname = 'public'",
|
|
33
|
+
);
|
|
34
|
+
expect(after.rows).toEqual([]);
|
|
35
|
+
await client.close();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("rejects multiple credential mechanisms as credential_ambiguous", async () => {
|
|
39
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
40
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
41
|
+
const world = await seedWorld(runtime, clock);
|
|
42
|
+
const response = await dispatch(runtime, {
|
|
43
|
+
method: "GET",
|
|
44
|
+
path: "/v1/notes",
|
|
45
|
+
headers: {
|
|
46
|
+
cookie: world.owner.sessionCookie,
|
|
47
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
expect(response.status).toBe(400);
|
|
51
|
+
expect(response.body).toMatchObject({ code: "credential_ambiguous" });
|
|
52
|
+
await runtime.close();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("returns unauthenticated for invalid API keys and bearer tokens with no fallback", async () => {
|
|
56
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
57
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
58
|
+
await seedWorld(runtime, clock);
|
|
59
|
+
const invalidKey = await dispatch(runtime, {
|
|
60
|
+
method: "GET",
|
|
61
|
+
path: "/v1/notes",
|
|
62
|
+
headers: { "x-api-key": "key_missing.not-a-secret" },
|
|
63
|
+
});
|
|
64
|
+
expect(invalidKey.status).toBe(401);
|
|
65
|
+
expect(invalidKey.body).toMatchObject({ code: "unauthenticated" });
|
|
66
|
+
const invalidBearer = await dispatch(runtime, {
|
|
67
|
+
method: "GET",
|
|
68
|
+
path: "/v1/notes",
|
|
69
|
+
headers: { authorization: "Bearer totally-invalid" },
|
|
70
|
+
});
|
|
71
|
+
expect(invalidBearer.status).toBe(401);
|
|
72
|
+
expect(invalidBearer.body).toMatchObject({ code: "unauthenticated" });
|
|
73
|
+
const anonymous = await dispatch(runtime, {
|
|
74
|
+
method: "GET",
|
|
75
|
+
path: "/v1/notes",
|
|
76
|
+
headers: {},
|
|
77
|
+
});
|
|
78
|
+
expect(anonymous.status).toBe(401);
|
|
79
|
+
expect(anonymous.body).toMatchObject({ code: "unauthenticated" });
|
|
80
|
+
await runtime.close();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("binds an API key to its tenant and ignores X-Tenant-ID", async () => {
|
|
84
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
85
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
86
|
+
const world = await seedWorld(runtime, clock);
|
|
87
|
+
const response = await dispatch(runtime, {
|
|
88
|
+
method: "GET",
|
|
89
|
+
path: "/v1/notes",
|
|
90
|
+
headers: {
|
|
91
|
+
"x-api-key": world.apiKeyA.raw,
|
|
92
|
+
"x-tenant-id": world.tenantB.publicId,
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
expect(response.status).toBe(200);
|
|
96
|
+
const body = response.body as {
|
|
97
|
+
items: Array<{ tenantId: string; id: string }>;
|
|
98
|
+
};
|
|
99
|
+
expect(body.items.every((item) => item.tenantId === world.tenantA.publicId)).toBe(
|
|
100
|
+
true,
|
|
101
|
+
);
|
|
102
|
+
expect(body.items.some((item) => item.id === world.noteA.publicId)).toBe(true);
|
|
103
|
+
await runtime.close();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it("supports one-time API-key creation, metadata listing, scoped revocation, and expiry", async () => {
|
|
107
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
108
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
109
|
+
const world = await seedWorld(runtime, clock);
|
|
110
|
+
const created = await dispatch(runtime, {
|
|
111
|
+
method: "POST",
|
|
112
|
+
path: "/v1/api-keys",
|
|
113
|
+
headers: {
|
|
114
|
+
cookie: world.owner.sessionCookie,
|
|
115
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
116
|
+
},
|
|
117
|
+
body: {
|
|
118
|
+
permissions: ["notes:read"],
|
|
119
|
+
expiresAt: "2026-04-01T00:00:00.000Z",
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
expect(created.status).toBe(201);
|
|
123
|
+
const key = created.body as { publicId: string; raw: string };
|
|
124
|
+
expect(key.raw).toContain(`${key.publicId}.`);
|
|
125
|
+
const listed = await dispatch(runtime, {
|
|
126
|
+
method: "GET",
|
|
127
|
+
path: "/v1/api-keys",
|
|
128
|
+
headers: {
|
|
129
|
+
cookie: world.owner.sessionCookie,
|
|
130
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
expect(JSON.stringify(listed.body)).not.toContain(key.raw);
|
|
134
|
+
const wrongTenant = await dispatch(runtime, {
|
|
135
|
+
method: "DELETE",
|
|
136
|
+
path: `/v1/api-keys/${key.publicId}`,
|
|
137
|
+
headers: {
|
|
138
|
+
cookie: world.owner.sessionCookie,
|
|
139
|
+
"x-tenant-id": world.tenantB.publicId,
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
expect(wrongTenant.status).toBe(404);
|
|
143
|
+
const revoked = await dispatch(runtime, {
|
|
144
|
+
method: "DELETE",
|
|
145
|
+
path: `/v1/api-keys/${key.publicId}`,
|
|
146
|
+
headers: {
|
|
147
|
+
cookie: world.owner.sessionCookie,
|
|
148
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
expect(revoked.status).toBe(204);
|
|
152
|
+
const unusable = await dispatch(runtime, {
|
|
153
|
+
method: "GET",
|
|
154
|
+
path: "/v1/notes",
|
|
155
|
+
headers: { "x-api-key": key.raw },
|
|
156
|
+
});
|
|
157
|
+
expect(unusable.status).toBe(401);
|
|
158
|
+
await runtime.close();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
it("denies a tenant A member mutating tenant B's note", async () => {
|
|
162
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
163
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
164
|
+
const world = await seedWorld(runtime, clock);
|
|
165
|
+
const response = await dispatch(runtime, {
|
|
166
|
+
method: "PATCH",
|
|
167
|
+
path: `/v1/notes/${world.noteA.publicId}`,
|
|
168
|
+
headers: {
|
|
169
|
+
cookie: world.member.sessionCookie,
|
|
170
|
+
"x-tenant-id": world.tenantB.publicId,
|
|
171
|
+
},
|
|
172
|
+
body: { title: "hijack" },
|
|
173
|
+
});
|
|
174
|
+
expect(response.status).toBe(403);
|
|
175
|
+
expect(response.body).toMatchObject({ code: "tenant_forbidden" });
|
|
176
|
+
const still = await runtime.db
|
|
177
|
+
.select()
|
|
178
|
+
.from(schema.notes)
|
|
179
|
+
.where(eq(schema.notes.publicId, world.noteA.publicId));
|
|
180
|
+
expect(still[0]?.title).toBe("Seed note");
|
|
181
|
+
await runtime.close();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("writes an application audit event for an authorized mutation", async () => {
|
|
185
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
186
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
187
|
+
const world = await seedWorld(runtime, clock);
|
|
188
|
+
const response = await dispatch(runtime, {
|
|
189
|
+
method: "PATCH",
|
|
190
|
+
path: `/v1/notes/${world.noteA.publicId}`,
|
|
191
|
+
headers: {
|
|
192
|
+
cookie: world.owner.sessionCookie,
|
|
193
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
194
|
+
},
|
|
195
|
+
body: { title: "Updated note" },
|
|
196
|
+
});
|
|
197
|
+
expect(response.status).toBe(200);
|
|
198
|
+
expect(response.body).toMatchObject({
|
|
199
|
+
id: world.noteA.publicId,
|
|
200
|
+
title: "Updated note",
|
|
201
|
+
});
|
|
202
|
+
const events = await runtime.db
|
|
203
|
+
.select()
|
|
204
|
+
.from(schema.auditEvents)
|
|
205
|
+
.where(eq(schema.auditEvents.action, "note.updated"));
|
|
206
|
+
expect(events).toHaveLength(1);
|
|
207
|
+
expect(events[0]?.resourceId).toBe(world.noteA.publicId);
|
|
208
|
+
expect(events[0]?.actorId).toBe(world.owner.id);
|
|
209
|
+
await runtime.close();
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("returns a billing entitlement from the public billing composition", async () => {
|
|
213
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
214
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
215
|
+
const world = await seedWorld(runtime, clock);
|
|
216
|
+
const response = await dispatch(runtime, {
|
|
217
|
+
method: "GET",
|
|
218
|
+
path: "/v1/billing/entitlement",
|
|
219
|
+
headers: {
|
|
220
|
+
cookie: world.owner.sessionCookie,
|
|
221
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
222
|
+
},
|
|
223
|
+
});
|
|
224
|
+
expect(response.status).toBe(200);
|
|
225
|
+
expect(response.body).toMatchObject({
|
|
226
|
+
tenantId: world.tenantA.publicId,
|
|
227
|
+
entitled: true,
|
|
228
|
+
activePaidPlan: "pro",
|
|
229
|
+
});
|
|
230
|
+
const direct = await runtime.billing.billing.commercialState(world.tenantA.id);
|
|
231
|
+
expect(direct.activePaidPlan).toBe(
|
|
232
|
+
(response.body as { activePaidPlan: string }).activePaidPlan,
|
|
233
|
+
);
|
|
234
|
+
await runtime.close();
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it("authenticates OAuth bearer tokens through oauth-server-kit", async () => {
|
|
238
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
239
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
240
|
+
const world = await seedWorld(runtime, clock);
|
|
241
|
+
const response = await dispatch(runtime, {
|
|
242
|
+
method: "GET",
|
|
243
|
+
path: "/v1/notes",
|
|
244
|
+
headers: {
|
|
245
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
246
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
expect(response.status).toBe(200);
|
|
250
|
+
expect(response.body).toMatchObject({
|
|
251
|
+
items: [{ id: world.noteA.publicId }],
|
|
252
|
+
});
|
|
253
|
+
await runtime.close();
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
it("serves the same notes service over MCP with parity, isolation, and confirmation", async () => {
|
|
257
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
258
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
259
|
+
const world = await seedWorld(runtime, clock);
|
|
260
|
+
const { validateParityManifest } = await import("@codelitdev/mcp-server-kit");
|
|
261
|
+
const { mcpParityManifest } = await import("@__PRODUCT_SLUG__/api-contract");
|
|
262
|
+
const { createReferenceMcp } = await import("./mcp.js");
|
|
263
|
+
const mcp = createReferenceMcp(runtime);
|
|
264
|
+
const issues = validateParityManifest([...mcpParityManifest], {
|
|
265
|
+
restOperationIds: new Set(Object.keys(contract)),
|
|
266
|
+
mcpToolNames: new Set(mcp.listTools().map((tool) => tool.name)),
|
|
267
|
+
mcpToolRisks: new Map(
|
|
268
|
+
mcp.listTools().map((tool) => [tool.name, tool.risk] as const),
|
|
269
|
+
),
|
|
270
|
+
now: new Date("2026-09-02T00:00:00.000Z"),
|
|
271
|
+
});
|
|
272
|
+
expect(issues).toEqual([]);
|
|
273
|
+
|
|
274
|
+
const restList = await dispatch(runtime, {
|
|
275
|
+
method: "GET",
|
|
276
|
+
path: "/v1/notes",
|
|
277
|
+
headers: {
|
|
278
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
279
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
const mcpList = await dispatch(runtime, {
|
|
283
|
+
method: "POST",
|
|
284
|
+
path: "/mcp",
|
|
285
|
+
headers: {
|
|
286
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
287
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
288
|
+
},
|
|
289
|
+
body: {
|
|
290
|
+
jsonrpc: "2.0",
|
|
291
|
+
id: 1,
|
|
292
|
+
method: "tools/call",
|
|
293
|
+
params: { name: "notes.list", arguments: {} },
|
|
294
|
+
},
|
|
295
|
+
});
|
|
296
|
+
expect(restList.status).toBe(200);
|
|
297
|
+
expect(mcpList.status).toBe(200);
|
|
298
|
+
const restItems = (restList.body as { items: Array<{ id: string }> }).items;
|
|
299
|
+
const mcpJson = (
|
|
300
|
+
mcpList.body as {
|
|
301
|
+
result: { content: Array<{ json: { items: Array<{ id: string }> } }> };
|
|
302
|
+
}
|
|
303
|
+
).result.content[0]?.json;
|
|
304
|
+
expect(mcpJson?.items.map((item) => item.id)).toEqual(
|
|
305
|
+
restItems.map((item) => item.id),
|
|
306
|
+
);
|
|
307
|
+
|
|
308
|
+
const initialized = await dispatch(runtime, {
|
|
309
|
+
method: "POST",
|
|
310
|
+
path: "/mcp",
|
|
311
|
+
headers: {
|
|
312
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
313
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
314
|
+
accept: "application/json",
|
|
315
|
+
},
|
|
316
|
+
body: {
|
|
317
|
+
jsonrpc: "2.0",
|
|
318
|
+
id: 10,
|
|
319
|
+
method: "initialize",
|
|
320
|
+
params: {
|
|
321
|
+
protocolVersion: "2025-03-26",
|
|
322
|
+
capabilities: {},
|
|
323
|
+
clientInfo: { name: "reference-test", version: "0" },
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
expect(initialized.headers?.["Mcp-Session-Id"]).toEqual(expect.any(String));
|
|
328
|
+
expect(initialized.headers?.["Access-Control-Expose-Headers"]).toBe(
|
|
329
|
+
"Mcp-Session-Id",
|
|
330
|
+
);
|
|
331
|
+
|
|
332
|
+
const cross = await dispatch(runtime, {
|
|
333
|
+
method: "POST",
|
|
334
|
+
path: "/mcp",
|
|
335
|
+
headers: {
|
|
336
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
337
|
+
"x-tenant-id": world.tenantB.publicId,
|
|
338
|
+
},
|
|
339
|
+
body: {
|
|
340
|
+
jsonrpc: "2.0",
|
|
341
|
+
id: 2,
|
|
342
|
+
method: "tools/call",
|
|
343
|
+
params: {
|
|
344
|
+
name: "notes.update",
|
|
345
|
+
arguments: { noteId: world.noteA.publicId, title: "hijack" },
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
});
|
|
349
|
+
expect((cross.body as { error: { code: string } }).error.code).toBe("not_found");
|
|
350
|
+
|
|
351
|
+
const denied = await dispatch(runtime, {
|
|
352
|
+
method: "POST",
|
|
353
|
+
path: "/mcp",
|
|
354
|
+
headers: {
|
|
355
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
356
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
357
|
+
},
|
|
358
|
+
body: {
|
|
359
|
+
jsonrpc: "2.0",
|
|
360
|
+
id: 3,
|
|
361
|
+
method: "tools/call",
|
|
362
|
+
params: {
|
|
363
|
+
name: "notes.delete",
|
|
364
|
+
arguments: { noteId: world.noteA.publicId },
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
expect((denied.body as { error: { code: string } }).error.code).toBe("forbidden");
|
|
369
|
+
|
|
370
|
+
const deleted = await dispatch(runtime, {
|
|
371
|
+
method: "POST",
|
|
372
|
+
path: "/mcp",
|
|
373
|
+
headers: {
|
|
374
|
+
authorization: `Bearer ${world.owner.oauthToken}`,
|
|
375
|
+
"x-tenant-id": world.tenantA.publicId,
|
|
376
|
+
},
|
|
377
|
+
body: {
|
|
378
|
+
jsonrpc: "2.0",
|
|
379
|
+
id: 4,
|
|
380
|
+
method: "tools/call",
|
|
381
|
+
params: {
|
|
382
|
+
name: "notes.delete",
|
|
383
|
+
arguments: { noteId: world.noteA.publicId, confirm: true },
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
});
|
|
387
|
+
expect(deleted.status).toBe(200);
|
|
388
|
+
const events = await runtime.db
|
|
389
|
+
.select()
|
|
390
|
+
.from(schema.auditEvents)
|
|
391
|
+
.where(eq(schema.auditEvents.action, "note.deleted"));
|
|
392
|
+
expect(events).toHaveLength(1);
|
|
393
|
+
expect(events[0]?.resourceId).toBe(world.noteA.publicId);
|
|
394
|
+
await runtime.close();
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it("protects the last owner from removal", async () => {
|
|
398
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
399
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
400
|
+
const world = await seedWorld(runtime, clock);
|
|
401
|
+
const { removeMember } = await import("./notes.js");
|
|
402
|
+
const result = await removeMember(
|
|
403
|
+
runtime.db,
|
|
404
|
+
{
|
|
405
|
+
requestId: "req_last_owner",
|
|
406
|
+
principalId: world.owner.id,
|
|
407
|
+
tenantId: world.tenantA.id,
|
|
408
|
+
credential: { kind: "session", credentialId: "sess_owner" },
|
|
409
|
+
permissions: new Set(["tenant:admin"]),
|
|
410
|
+
},
|
|
411
|
+
world.owner.id,
|
|
412
|
+
clock,
|
|
413
|
+
);
|
|
414
|
+
expect(result.ok).toBe(false);
|
|
415
|
+
if (result.ok) throw new Error("expected failure");
|
|
416
|
+
expect(result.error.code).toBe("conflict");
|
|
417
|
+
expect(result.error.safeDetails).toEqual({ reason: "last_owner" });
|
|
418
|
+
await runtime.close();
|
|
419
|
+
});
|
|
420
|
+
|
|
421
|
+
it("passes platform conformance suites against the real adapter", async () => {
|
|
422
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
423
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
424
|
+
const world = await seedWorld(runtime, clock);
|
|
425
|
+
const { runReferenceConformance } = await import("./conformance-adapter.js");
|
|
426
|
+
const result = await runReferenceConformance(runtime, world);
|
|
427
|
+
expect(result.failures).toEqual([]);
|
|
428
|
+
await runtime.close();
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
it("serves health and readiness bodies", async () => {
|
|
432
|
+
const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
|
|
433
|
+
const runtime = await createPgliteRuntime({ clock });
|
|
434
|
+
const health = await dispatch(runtime, {
|
|
435
|
+
method: "GET",
|
|
436
|
+
path: "/health",
|
|
437
|
+
headers: {},
|
|
438
|
+
});
|
|
439
|
+
expect(health).toEqual({
|
|
440
|
+
status: 200,
|
|
441
|
+
body: {
|
|
442
|
+
status: "ok",
|
|
443
|
+
service: "__PRODUCT_SLUG__-api",
|
|
444
|
+
time: "2026-03-01T00:00:00.000Z",
|
|
445
|
+
},
|
|
446
|
+
});
|
|
447
|
+
const ready = await dispatch(runtime, {
|
|
448
|
+
method: "GET",
|
|
449
|
+
path: "/ready",
|
|
450
|
+
headers: {},
|
|
451
|
+
});
|
|
452
|
+
expect(ready).toEqual({
|
|
453
|
+
status: 200,
|
|
454
|
+
body: { status: "ready", checks: { database: true } },
|
|
455
|
+
});
|
|
456
|
+
await runtime.close();
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
it("mounts the shared contract through the Express ts-rest adapter", async () => {
|
|
460
|
+
const runtime = await createPgliteRuntime({
|
|
461
|
+
clock: freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z")),
|
|
462
|
+
});
|
|
463
|
+
const app = createExpressApp(runtime);
|
|
464
|
+
const server = await new Promise<ReturnType<typeof app.listen>>((resolve) => {
|
|
465
|
+
const listening = app.listen(0, () => resolve(listening));
|
|
466
|
+
});
|
|
467
|
+
const address = server.address();
|
|
468
|
+
if (!address || typeof address === "string") throw new Error("listen_failed");
|
|
469
|
+
const response = await fetch(`http://127.0.0.1:${address.port}/health`);
|
|
470
|
+
expect(response.status).toBe(200);
|
|
471
|
+
expect(response.headers.get("x-content-type-options")).toBe("nosniff");
|
|
472
|
+
expect(response.headers.get("x-request-id")).toEqual(expect.any(String));
|
|
473
|
+
const openapi = await fetch(`http://127.0.0.1:${address.port}/openapi.json`);
|
|
474
|
+
expect(openapi.status).toBe(200);
|
|
475
|
+
expect((await openapi.json()).paths["/v1/notes"]).toBeDefined();
|
|
476
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
477
|
+
await runtime.close();
|
|
478
|
+
});
|
|
479
|
+
});
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { type Clock, createPublicId, uuidv7 } from "@codelitdev/platform";
|
|
3
|
+
import { and, eq, isNull } from "drizzle-orm";
|
|
4
|
+
import * as schema from "../db/schema/index.js";
|
|
5
|
+
import type { AppDb } from "../types.js";
|
|
6
|
+
|
|
7
|
+
const SECRET_BYTES = 32;
|
|
8
|
+
|
|
9
|
+
export function generateApiKeySecret(): string {
|
|
10
|
+
return randomBytes(SECRET_BYTES).toString("base64url");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function digestApiKeySecret(pepper: string, secret: string): string {
|
|
14
|
+
return createHmac("sha256", pepper).update(secret, "utf8").digest("hex");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function apiKeyDigestMatches(
|
|
18
|
+
pepper: string,
|
|
19
|
+
secret: string,
|
|
20
|
+
storedHex: string,
|
|
21
|
+
): boolean {
|
|
22
|
+
const actual = Buffer.from(digestApiKeySecret(pepper, secret), "hex");
|
|
23
|
+
const expected = Buffer.from(storedHex, "hex");
|
|
24
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function formatApiKey(publicId: string, secret: string): string {
|
|
28
|
+
return `${publicId}.${secret}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function parseApiKey(
|
|
32
|
+
value: string,
|
|
33
|
+
): { publicId: string; secret: string } | null {
|
|
34
|
+
const sep = value.indexOf(".");
|
|
35
|
+
if (sep <= 0) return null;
|
|
36
|
+
const publicId = value.slice(0, sep);
|
|
37
|
+
const secret = value.slice(sep + 1);
|
|
38
|
+
if (!publicId || secret.length < 43) return null;
|
|
39
|
+
return { publicId, secret };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function createApiKeyRecord(input: {
|
|
43
|
+
db: AppDb;
|
|
44
|
+
tenantId: string;
|
|
45
|
+
userId: string;
|
|
46
|
+
permissions: readonly string[];
|
|
47
|
+
pepper: string;
|
|
48
|
+
clock: Clock;
|
|
49
|
+
expiresAt?: Date;
|
|
50
|
+
audit?: { requestId: string };
|
|
51
|
+
}): Promise<{ id: string; publicId: string; raw: string }> {
|
|
52
|
+
const id = uuidv7(input.clock);
|
|
53
|
+
const publicId = createPublicId("key", input.clock);
|
|
54
|
+
const secret = generateApiKeySecret();
|
|
55
|
+
const now = input.clock.now();
|
|
56
|
+
await input.db.transaction(async (tx) => {
|
|
57
|
+
await tx.insert(schema.apiKeys).values({
|
|
58
|
+
id,
|
|
59
|
+
publicId,
|
|
60
|
+
tenantId: input.tenantId,
|
|
61
|
+
userId: input.userId,
|
|
62
|
+
digest: digestApiKeySecret(input.pepper, secret),
|
|
63
|
+
permissions: input.permissions.join(","),
|
|
64
|
+
...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),
|
|
65
|
+
createdAt: now,
|
|
66
|
+
});
|
|
67
|
+
if (input.audit) {
|
|
68
|
+
await tx.insert(schema.auditEvents).values({
|
|
69
|
+
id: uuidv7(input.clock),
|
|
70
|
+
tenantId: input.tenantId,
|
|
71
|
+
actorId: input.userId,
|
|
72
|
+
action: "api_key.created",
|
|
73
|
+
resourceType: "api_key",
|
|
74
|
+
resourceId: publicId,
|
|
75
|
+
requestId: input.audit.requestId,
|
|
76
|
+
createdAt: now,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
return { id, publicId, raw: formatApiKey(publicId, secret) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function listApiKeyRecords(db: AppDb, tenantId: string) {
|
|
84
|
+
return db
|
|
85
|
+
.select({
|
|
86
|
+
id: schema.apiKeys.id,
|
|
87
|
+
publicId: schema.apiKeys.publicId,
|
|
88
|
+
expiresAt: schema.apiKeys.expiresAt,
|
|
89
|
+
revokedAt: schema.apiKeys.revokedAt,
|
|
90
|
+
lastUsedAt: schema.apiKeys.lastUsedAt,
|
|
91
|
+
createdAt: schema.apiKeys.createdAt,
|
|
92
|
+
})
|
|
93
|
+
.from(schema.apiKeys)
|
|
94
|
+
.where(eq(schema.apiKeys.tenantId, tenantId));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export async function revokeApiKey(
|
|
98
|
+
db: AppDb,
|
|
99
|
+
publicId: string,
|
|
100
|
+
tenantId: string,
|
|
101
|
+
clock: Clock,
|
|
102
|
+
audit?: { actorId: string; requestId: string },
|
|
103
|
+
): Promise<boolean> {
|
|
104
|
+
const now = clock.now();
|
|
105
|
+
return db.transaction(async (tx) => {
|
|
106
|
+
const rows = await tx
|
|
107
|
+
.update(schema.apiKeys)
|
|
108
|
+
.set({ revokedAt: now })
|
|
109
|
+
.where(
|
|
110
|
+
and(
|
|
111
|
+
eq(schema.apiKeys.publicId, publicId),
|
|
112
|
+
eq(schema.apiKeys.tenantId, tenantId),
|
|
113
|
+
isNull(schema.apiKeys.revokedAt),
|
|
114
|
+
),
|
|
115
|
+
)
|
|
116
|
+
.returning({ id: schema.apiKeys.id });
|
|
117
|
+
if (rows.length > 0 && audit) {
|
|
118
|
+
await tx.insert(schema.auditEvents).values({
|
|
119
|
+
id: uuidv7(clock),
|
|
120
|
+
tenantId,
|
|
121
|
+
actorId: audit.actorId,
|
|
122
|
+
action: "api_key.revoked",
|
|
123
|
+
resourceType: "api_key",
|
|
124
|
+
resourceId: publicId,
|
|
125
|
+
requestId: audit.requestId,
|
|
126
|
+
createdAt: now,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return rows.length > 0;
|
|
130
|
+
});
|
|
131
|
+
}
|