@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,217 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import {
3
+ type Clock,
4
+ createPlatformError,
5
+ type PlatformError,
6
+ type PlatformRequestContext,
7
+ uuidv7,
8
+ } from "@codelitdev/platform";
9
+ import { and, eq, gt, isNull } from "drizzle-orm";
10
+ import * as schema from "./db/schema/index.js";
11
+ import { type ReferencePermission, serializePermissions } from "./permissions.js";
12
+ import type { AppDb } from "./types.js";
13
+
14
+ type Ctx = PlatformRequestContext<string, string, ReferencePermission>;
15
+
16
+ function digestToken(token: string): string {
17
+ return createHash("sha256").update(token, "utf8").digest("hex");
18
+ }
19
+
20
+ function equalHex(left: string, right: string): boolean {
21
+ const a = Buffer.from(left, "hex");
22
+ const b = Buffer.from(right, "hex");
23
+ return a.length === b.length && timingSafeEqual(a, b);
24
+ }
25
+
26
+ export function normalizeEmail(email: string): string {
27
+ return email.trim().toLowerCase();
28
+ }
29
+
30
+ export async function createInvitation(
31
+ db: AppDb,
32
+ ctx: Ctx,
33
+ input: {
34
+ email: string;
35
+ role: string;
36
+ permissions: readonly ReferencePermission[];
37
+ },
38
+ clock: Clock,
39
+ ): Promise<
40
+ { ok: true; token: string; id: string } | { ok: false; error: PlatformError }
41
+ > {
42
+ if (!ctx.permissions.has("tenant:admin") || !ctx.tenantId) {
43
+ return { ok: false, error: createPlatformError("forbidden") };
44
+ }
45
+ const token = randomBytes(32).toString("base64url");
46
+ const id = uuidv7(clock);
47
+ const now = clock.now();
48
+ await db.transaction(async (tx) => {
49
+ await tx
50
+ .update(schema.invitations)
51
+ .set({ revokedAt: now })
52
+ .where(
53
+ and(
54
+ eq(schema.invitations.tenantId, ctx.tenantId!),
55
+ eq(schema.invitations.email, normalizeEmail(input.email)),
56
+ isNull(schema.invitations.acceptedAt),
57
+ isNull(schema.invitations.revokedAt),
58
+ ),
59
+ );
60
+ await tx.insert(schema.invitations).values({
61
+ id,
62
+ tenantId: ctx.tenantId!,
63
+ email: normalizeEmail(input.email),
64
+ role: input.role,
65
+ permissions: serializePermissions(input.permissions),
66
+ tokenDigest: digestToken(token),
67
+ inviterId: ctx.principalId,
68
+ expiresAt: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000),
69
+ createdAt: now,
70
+ });
71
+ await tx.insert(schema.auditEvents).values({
72
+ id: uuidv7(clock),
73
+ tenantId: ctx.tenantId,
74
+ actorId: ctx.principalId,
75
+ action: "invitation.created",
76
+ resourceType: "invitation",
77
+ resourceId: id,
78
+ requestId: ctx.requestId,
79
+ createdAt: now,
80
+ });
81
+ });
82
+ return { ok: true, token, id };
83
+ }
84
+
85
+ export async function acceptInvitation(
86
+ db: AppDb,
87
+ ctx: Ctx,
88
+ token: string,
89
+ actorEmail: string,
90
+ clock: Clock,
91
+ ): Promise<{ ok: true; tenantId: string } | { ok: false; error: PlatformError }> {
92
+ const digest = digestToken(token);
93
+ const now = clock.now();
94
+ return db.transaction(async (tx) => {
95
+ const rows = await tx.select().from(schema.invitations);
96
+ const invitation = rows.find((row) => equalHex(row.tokenDigest, digest));
97
+ if (
98
+ !invitation ||
99
+ invitation.revokedAt ||
100
+ invitation.acceptedAt ||
101
+ invitation.expiresAt.getTime() <= now.getTime()
102
+ ) {
103
+ return {
104
+ ok: false as const,
105
+ error: createPlatformError("not_found"),
106
+ };
107
+ }
108
+ const users = await tx
109
+ .select({
110
+ email: schema.user.email,
111
+ emailVerified: schema.user.emailVerified,
112
+ })
113
+ .from(schema.user)
114
+ .where(eq(schema.user.id, ctx.principalId))
115
+ .limit(1);
116
+ const actor = users[0];
117
+ if (
118
+ !actor?.emailVerified ||
119
+ normalizeEmail(actor.email) !== invitation.email ||
120
+ normalizeEmail(actorEmail) !== invitation.email
121
+ ) {
122
+ return {
123
+ ok: false as const,
124
+ error: createPlatformError("forbidden"),
125
+ };
126
+ }
127
+ const consumed = await tx
128
+ .update(schema.invitations)
129
+ .set({ acceptedAt: now })
130
+ .where(
131
+ and(
132
+ eq(schema.invitations.id, invitation.id),
133
+ isNull(schema.invitations.acceptedAt),
134
+ isNull(schema.invitations.revokedAt),
135
+ gt(schema.invitations.expiresAt, now),
136
+ ),
137
+ )
138
+ .returning();
139
+ if (!consumed[0]) {
140
+ return {
141
+ ok: false as const,
142
+ error: createPlatformError("not_found"),
143
+ };
144
+ }
145
+ const existing = await tx
146
+ .select()
147
+ .from(schema.memberships)
148
+ .where(
149
+ and(
150
+ eq(schema.memberships.tenantId, invitation.tenantId),
151
+ eq(schema.memberships.userId, ctx.principalId),
152
+ ),
153
+ )
154
+ .limit(1);
155
+ if (!existing[0]) {
156
+ await tx.insert(schema.memberships).values({
157
+ id: uuidv7(clock),
158
+ tenantId: invitation.tenantId,
159
+ userId: ctx.principalId,
160
+ role: invitation.role,
161
+ isOwner: false,
162
+ permissions: invitation.permissions,
163
+ createdAt: now,
164
+ });
165
+ }
166
+ await tx.insert(schema.auditEvents).values({
167
+ id: uuidv7(clock),
168
+ tenantId: invitation.tenantId,
169
+ actorId: ctx.principalId,
170
+ action: "invitation.accepted",
171
+ resourceType: "invitation",
172
+ resourceId: invitation.id,
173
+ requestId: ctx.requestId,
174
+ createdAt: now,
175
+ });
176
+ return { ok: true as const, tenantId: invitation.tenantId };
177
+ });
178
+ }
179
+
180
+ export async function revokeInvitation(
181
+ db: AppDb,
182
+ ctx: Ctx,
183
+ invitationId: string,
184
+ clock: Clock,
185
+ ): Promise<{ ok: true } | { ok: false; error: PlatformError }> {
186
+ if (!ctx.permissions.has("tenant:admin") || !ctx.tenantId) {
187
+ return { ok: false, error: createPlatformError("forbidden") };
188
+ }
189
+ const tenantId = ctx.tenantId;
190
+ const now = clock.now();
191
+ return db.transaction(async (tx) => {
192
+ const rows = await tx
193
+ .update(schema.invitations)
194
+ .set({ revokedAt: now })
195
+ .where(
196
+ and(
197
+ eq(schema.invitations.id, invitationId),
198
+ eq(schema.invitations.tenantId, tenantId),
199
+ isNull(schema.invitations.acceptedAt),
200
+ isNull(schema.invitations.revokedAt),
201
+ ),
202
+ )
203
+ .returning({ id: schema.invitations.id });
204
+ if (!rows[0]) return { ok: false, error: createPlatformError("not_found") };
205
+ await tx.insert(schema.auditEvents).values({
206
+ id: uuidv7(clock),
207
+ tenantId,
208
+ actorId: ctx.principalId,
209
+ action: "invitation.revoked",
210
+ resourceType: "invitation",
211
+ resourceId: invitationId,
212
+ requestId: ctx.requestId,
213
+ createdAt: now,
214
+ });
215
+ return { ok: true as const };
216
+ });
217
+ }
@@ -0,0 +1,26 @@
1
+ import pinoModule, { type Logger } from "pino";
2
+
3
+ // Pino 9.6 exposes its callable default through a namespace-shaped ESM type,
4
+ // while newer Pino releases use `export =`. Keep the runtime default import
5
+ // and normalize the type so generated products compile against either pin.
6
+ const createPino = pinoModule as unknown as (options: {
7
+ level: string;
8
+ redact: { paths: string[]; remove: boolean };
9
+ }) => Logger;
10
+
11
+ export function createLogger(options: { level?: string } = {}): Logger {
12
+ return createPino({
13
+ level: options.level ?? "info",
14
+ redact: {
15
+ paths: [
16
+ "req.headers.authorization",
17
+ "req.headers.cookie",
18
+ 'req.headers["x-api-key"]',
19
+ "digest",
20
+ "pepper",
21
+ "secret",
22
+ ],
23
+ remove: true,
24
+ },
25
+ });
26
+ }
@@ -0,0 +1,98 @@
1
+ import { createObservability } from "@codelitdev/observability";
2
+ import { createExpressApp } from "./express-app.js";
3
+ import { createPostgresRuntime } from "./runtime.js";
4
+ import { hasSeededWorld, seedWorld } from "./seed.js";
5
+
6
+ const port = Number(process.env.PORT ?? "4000");
7
+ const posthogApiKey = process.env.POSTHOG_API_KEY;
8
+ const posthogHost = process.env.POSTHOG_HOST;
9
+ const otlpEndpoint = process.env.OTLP_LOGS_ENDPOINT;
10
+ const otlpAuthorization = process.env.OTLP_LOGS_AUTHORIZATION;
11
+ const observability = createObservability({
12
+ serviceName: "__PRODUCT_SLUG__-api",
13
+ environment: process.env.NODE_ENV ?? "development",
14
+ logs: {
15
+ level: process.env.LOG_LEVEL ?? "info",
16
+ ...(otlpEndpoint
17
+ ? {
18
+ otlp: {
19
+ endpoint: otlpEndpoint,
20
+ ...(otlpAuthorization
21
+ ? { headers: { authorization: otlpAuthorization } }
22
+ : {}),
23
+ },
24
+ }
25
+ : {}),
26
+ },
27
+ ...(posthogApiKey
28
+ ? {
29
+ posthog: {
30
+ apiKey: posthogApiKey,
31
+ ...(posthogHost ? { host: posthogHost } : {}),
32
+ },
33
+ }
34
+ : {}),
35
+ contextPolicy: {
36
+ propertyAllowlist: new Set(["path", "method", "job_id"]),
37
+ },
38
+ });
39
+ const logger = observability.logger;
40
+
41
+ const publicApiUrl = process.env.PUBLIC_API_URL ?? `http://127.0.0.1:${port}`;
42
+ const webOrigin = process.env.WEB_ORIGIN ?? "http://localhost:3000";
43
+ const databaseUrl = process.env.DATABASE_URL;
44
+ const authSecret = process.env.AUTH_SECRET;
45
+ const apiKeyPepper = process.env.API_KEY_PEPPER;
46
+ if (!databaseUrl || !authSecret || !apiKeyPepper) {
47
+ throw new Error("DATABASE_URL_AUTH_SECRET_AND_API_KEY_PEPPER_REQUIRED");
48
+ }
49
+ const runtime = await createPostgresRuntime({
50
+ logger,
51
+ observability,
52
+ publicApiUrl,
53
+ webOrigin,
54
+ databaseUrl,
55
+ authSecret,
56
+ apiKeyPepper,
57
+ });
58
+
59
+ const app = createExpressApp(runtime);
60
+ const server = await new Promise<ReturnType<typeof app.listen>>((resolve) => {
61
+ const listening = app.listen(port, () => resolve(listening));
62
+ });
63
+ logger.info({ port }, "reference api listening");
64
+
65
+ if (process.env.SEED === "1") {
66
+ if (await hasSeededWorld(runtime)) {
67
+ logger.info("reference world already seeded; skipping seed");
68
+ } else {
69
+ const world = await seedWorld(runtime, runtime.clock);
70
+ logger.info(
71
+ {
72
+ tenantA: world.tenantA.publicId,
73
+ apiKeyHint: world.apiKeyA.publicId,
74
+ note: world.noteA.publicId,
75
+ },
76
+ "seeded reference world",
77
+ );
78
+ process.stdout.write(
79
+ `REFERENCE_SEED ${JSON.stringify({
80
+ seeded: true,
81
+ tenantA: world.tenantA.publicId,
82
+ noteId: world.noteA.publicId,
83
+ })}\n`,
84
+ );
85
+ }
86
+ }
87
+
88
+ const shutdown = () => {
89
+ server.close(() => {
90
+ void observability
91
+ .shutdown(1000)
92
+ .then(() => runtime.close())
93
+ .finally(() => process.exit(0));
94
+ });
95
+ setTimeout(() => process.exit(0), 1500).unref();
96
+ };
97
+ process.on("SIGTERM", shutdown);
98
+ process.on("SIGINT", shutdown);
@@ -0,0 +1,127 @@
1
+ import {
2
+ createNoteBodySchema,
3
+ updateNoteBodySchema,
4
+ } from "@__PRODUCT_SLUG__/api-contract";
5
+ import { createMcpServerKit, type McpServerKit } from "@codelitdev/mcp-server-kit";
6
+ import {
7
+ type PlatformRequestContext,
8
+ readOrCreateRequestId,
9
+ } from "@codelitdev/platform";
10
+ import { z } from "zod";
11
+ import { authenticateMcpRequest } from "./auth/authenticate.js";
12
+ import type { DispatchDeps } from "./deps.js";
13
+ import { createNote, deleteNote, listNotes, updateNote } from "./notes.js";
14
+ import type { ReferencePermission } from "./permissions.js";
15
+ import { headerTenantId, resolveTenantContext } from "./tenancy.js";
16
+
17
+ type Ctx = PlatformRequestContext<string, string, ReferencePermission> & {
18
+ publicTenantId: string;
19
+ };
20
+
21
+ export function createReferenceMcp(deps: DispatchDeps): McpServerKit<Ctx> {
22
+ return createMcpServerKit<Ctx>({
23
+ name: "__PRODUCT_SLUG__",
24
+ version: "0.0.0",
25
+ onError: ({ error, source }) =>
26
+ deps.observability?.captureException({ error, source }),
27
+ authenticate: (headers) => authenticateMcpRequest(headers, deps),
28
+ async resolveContext({ principalId, credential, headers }) {
29
+ const tenant = await resolveTenantContext({
30
+ db: deps.db,
31
+ principalId,
32
+ credential: credential.credential,
33
+ requestedPublicTenantId: headerTenantId(
34
+ headers as Record<string, string | string[] | undefined>,
35
+ ),
36
+ });
37
+ if (!tenant.ok) return tenant;
38
+ return {
39
+ ok: true,
40
+ context: {
41
+ requestId: readOrCreateRequestId(
42
+ typeof headers["x-request-id"] === "string"
43
+ ? headers["x-request-id"]
44
+ : undefined,
45
+ deps.clock,
46
+ ),
47
+ principalId,
48
+ tenantId: tenant.value.tenantId,
49
+ credential: credential.credential,
50
+ permissions: tenant.value.permissions,
51
+ publicTenantId: tenant.value.publicId,
52
+ },
53
+ };
54
+ },
55
+ tools: [
56
+ {
57
+ name: "notes.list",
58
+ description: "List notes for the selected tenant",
59
+ risk: "read",
60
+ inputSchema: z.object({}),
61
+ async handler({ context }) {
62
+ const result = await listNotes(deps.db, context, context.publicTenantId);
63
+ if (!result.ok) return { error: result.error };
64
+ return { items: result.value };
65
+ },
66
+ },
67
+ {
68
+ name: "notes.create",
69
+ description: "Create a note",
70
+ risk: "write",
71
+ inputSchema: createNoteBodySchema,
72
+ async handler({ context, args }) {
73
+ const parsed = args as { title: string; body: string };
74
+ const result = await createNote(
75
+ deps.db,
76
+ context,
77
+ context.publicTenantId,
78
+ parsed,
79
+ deps.clock,
80
+ );
81
+ if (!result.ok) return { error: result.error };
82
+ return result.value;
83
+ },
84
+ },
85
+ {
86
+ name: "notes.update",
87
+ description: "Update a note",
88
+ risk: "write",
89
+ inputSchema: updateNoteBodySchema.extend({
90
+ noteId: z.string(),
91
+ }),
92
+ async handler({ context, args }) {
93
+ const parsed = args as {
94
+ noteId: string;
95
+ title?: string;
96
+ body?: string;
97
+ };
98
+ const result = await updateNote(
99
+ deps.db,
100
+ context,
101
+ context.publicTenantId,
102
+ parsed.noteId,
103
+ parsed,
104
+ deps.clock,
105
+ );
106
+ if (!result.ok) return { error: result.error };
107
+ return result.value;
108
+ },
109
+ },
110
+ {
111
+ name: "notes.delete",
112
+ description: "Delete a note",
113
+ risk: "destructive",
114
+ inputSchema: z.object({
115
+ noteId: z.string(),
116
+ confirm: z.boolean().optional(),
117
+ }),
118
+ async handler({ context, args }) {
119
+ const parsed = args as { noteId: string };
120
+ const result = await deleteNote(deps.db, context, parsed.noteId, deps.clock);
121
+ if (!result.ok) return { error: result.error };
122
+ return result.value;
123
+ },
124
+ },
125
+ ],
126
+ });
127
+ }