@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,340 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { grant as billingGrant } from "@codelitdev/billing/testing";
3
+ import { verifyOAuthAccessToken } from "@codelitdev/oauth-server-kit";
4
+ import { resolveBetterAuthSession } from "@codelitdev/oauth-server-kit/better-auth";
5
+ import { type Clock, createPublicId, uuidv7 } from "@codelitdev/platform";
6
+ import { eq } from "drizzle-orm";
7
+ import {
8
+ digestApiKeySecret,
9
+ formatApiKey,
10
+ generateApiKeySecret,
11
+ } from "./auth/api-keys.js";
12
+ import * as schema from "./db/schema/index.js";
13
+ import {
14
+ MEMBER_PERMISSIONS,
15
+ OWNER_PERMISSIONS,
16
+ serializePermissions,
17
+ } from "./permissions.js";
18
+ import type { Runtime } from "./runtime.js";
19
+
20
+ export type SeededWorld = {
21
+ owner: {
22
+ id: string;
23
+ email: string;
24
+ sessionCookie: string;
25
+ oauthToken: string;
26
+ };
27
+ member: { id: string; email: string; sessionCookie: string };
28
+ outsider: { id: string; email: string; sessionCookie: string };
29
+ tenantA: { id: string; publicId: string };
30
+ tenantB: { id: string; publicId: string };
31
+ apiKeyA: { publicId: string; raw: string };
32
+ noteA: { publicId: string };
33
+ };
34
+
35
+ const PASSWORD = "reference-password-1";
36
+ const SEEDED_TENANT_A_ID = "11111111-1111-4111-8111-111111111111";
37
+ const SEEDED_TENANT_B_ID = "22222222-2222-4222-8222-222222222222";
38
+
39
+ export async function hasSeededWorld(runtime: Runtime): Promise<boolean> {
40
+ const rows = await runtime.db
41
+ .select({ id: schema.tenants.id })
42
+ .from(schema.tenants)
43
+ .where(eq(schema.tenants.id, SEEDED_TENANT_A_ID))
44
+ .limit(1);
45
+ return rows.length > 0;
46
+ }
47
+
48
+ function cookiesFromResponse(response: Response): string {
49
+ const listed =
50
+ typeof response.headers.getSetCookie === "function"
51
+ ? response.headers.getSetCookie()
52
+ : [];
53
+ if (listed.length > 0) {
54
+ return listed.map((entry) => entry.split(";", 1)[0]!).join("; ");
55
+ }
56
+ const header = response.headers.get("set-cookie");
57
+ if (!header) throw new Error("missing_set_cookie");
58
+ return header.split(";", 1)[0]!;
59
+ }
60
+
61
+ async function signUp(
62
+ runtime: Runtime,
63
+ name: string,
64
+ email: string,
65
+ ): Promise<{ id: string; sessionCookie: string }> {
66
+ const response = await runtime.auth.auth.api.signUpEmail({
67
+ body: { name, email, password: PASSWORD },
68
+ asResponse: true,
69
+ });
70
+ if (!response.ok) {
71
+ throw new Error(`signup_failed:${email}:${response.status}`);
72
+ }
73
+ const sessionCookie = cookiesFromResponse(response);
74
+ const resolved = await resolveBetterAuthSession(
75
+ { auth: runtime.auth.auth, issuer: runtime.auth.issuer },
76
+ new Headers({ cookie: sessionCookie }),
77
+ );
78
+ if (resolved.status !== "authenticated") {
79
+ throw new Error(`session_missing:${email}`);
80
+ }
81
+ return { id: resolved.identity.subject, sessionCookie };
82
+ }
83
+
84
+ function pkce() {
85
+ const verifier = randomBytes(32).toString("base64url");
86
+ return {
87
+ verifier,
88
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
89
+ };
90
+ }
91
+
92
+ async function mintOAuthToken(
93
+ runtime: Runtime,
94
+ sessionCookie: string,
95
+ ): Promise<string> {
96
+ const redirectUri = "com.example.reference:/oauth/callback";
97
+ const client = await runtime.auth.auth.api.createOAuthClient({
98
+ headers: new Headers({ cookie: sessionCookie }),
99
+ body: {
100
+ client_name: "Reference test client",
101
+ redirect_uris: [redirectUri],
102
+ token_endpoint_auth_method: "none",
103
+ grant_types: ["authorization_code", "refresh_token"],
104
+ response_types: ["code"],
105
+ application_type: "native",
106
+ },
107
+ });
108
+ await runtime.auth.auth.api.adminGetOAuthResource({
109
+ headers: new Headers({ cookie: sessionCookie }),
110
+ params: { identifier: runtime.auth.mcpResource },
111
+ });
112
+ await runtime.auth.auth.api.adminLinkClientResource({
113
+ headers: new Headers({ cookie: sessionCookie }),
114
+ params: {
115
+ identifier: runtime.auth.mcpResource,
116
+ client_id: client.client_id,
117
+ },
118
+ });
119
+ const proof = pkce();
120
+ const query = new URLSearchParams({
121
+ client_id: client.client_id,
122
+ redirect_uri: redirectUri,
123
+ response_type: "code",
124
+ scope: "openid profile email offline_access data:read",
125
+ state: "state-123",
126
+ code_challenge: proof.challenge,
127
+ code_challenge_method: "S256",
128
+ resource: runtime.auth.mcpResource,
129
+ });
130
+ const authorization = await runtime.auth.auth.handler(
131
+ new Request(`${runtime.auth.issuer}/oauth2/authorize?${query}`, {
132
+ headers: { cookie: sessionCookie },
133
+ redirect: "manual",
134
+ }),
135
+ );
136
+ let code: string | null;
137
+ const location = authorization.headers.get("location");
138
+ if (authorization.status === 302 && location?.startsWith(redirectUri)) {
139
+ code = new URL(location).searchParams.get("code");
140
+ } else {
141
+ const consentLocation =
142
+ location ?? ((await authorization.json()) as { url?: string }).url ?? null;
143
+ if (!consentLocation) {
144
+ throw new Error(`authorize_failed:${authorization.status}`);
145
+ }
146
+ const oauthQuery = new URL(consentLocation).search.slice(1);
147
+ const consent = await runtime.auth.auth.handler(
148
+ new Request(`${runtime.auth.issuer}/oauth2/consent`, {
149
+ method: "POST",
150
+ headers: {
151
+ cookie: sessionCookie,
152
+ origin: runtime.auth.publicApiUrl,
153
+ "content-type": "application/json",
154
+ },
155
+ body: JSON.stringify({ accept: true, oauth_query: oauthQuery }),
156
+ }),
157
+ );
158
+ const body = (await consent.json()) as { url?: string };
159
+ code = body.url ? new URL(body.url).searchParams.get("code") : null;
160
+ }
161
+ if (!code) throw new Error("oauth_code_missing");
162
+ const tokenResponse = await runtime.auth.auth.handler(
163
+ new Request(`${runtime.auth.issuer}/oauth2/token`, {
164
+ method: "POST",
165
+ headers: { "content-type": "application/x-www-form-urlencoded" },
166
+ body: new URLSearchParams({
167
+ grant_type: "authorization_code",
168
+ code,
169
+ redirect_uri: redirectUri,
170
+ client_id: client.client_id,
171
+ code_verifier: proof.verifier,
172
+ resource: runtime.auth.mcpResource,
173
+ }),
174
+ }),
175
+ );
176
+ const token = (await tokenResponse.json()) as {
177
+ access_token?: string;
178
+ error?: string;
179
+ error_description?: string;
180
+ };
181
+ if (!token.access_token) {
182
+ throw new Error(
183
+ `oauth_token_failed:${tokenResponse.status}:${token.error}:${token.error_description}`,
184
+ );
185
+ }
186
+ const verified = await verifyOAuthAccessToken(
187
+ {
188
+ oauthResourceClient: runtime.auth.oauthResourceClient,
189
+ issuer: runtime.auth.issuer,
190
+ audiences: [runtime.auth.mcpResource],
191
+ },
192
+ token.access_token,
193
+ );
194
+ if (verified.status !== "authenticated") {
195
+ throw new Error(`oauth_verify_failed:${verified.status}`);
196
+ }
197
+ return token.access_token;
198
+ }
199
+
200
+ export async function seedWorld(runtime: Runtime, clock: Clock): Promise<SeededWorld> {
201
+ const now = clock.now();
202
+ const owner = await signUp(runtime, "Owner", "owner@example.com");
203
+ const member = await signUp(runtime, "Member", "member@example.com");
204
+ const outsider = await signUp(runtime, "Outsider", "outsider@example.com");
205
+ const oauthToken = await mintOAuthToken(runtime, owner.sessionCookie);
206
+
207
+ const tenantAId = SEEDED_TENANT_A_ID;
208
+ const tenantBId = SEEDED_TENANT_B_ID;
209
+ const tenantAPublic = createPublicId("tnt", clock);
210
+ const tenantBPublic = createPublicId("tnt", clock);
211
+
212
+ await runtime.db.insert(schema.tenants).values([
213
+ {
214
+ id: tenantAId,
215
+ publicId: tenantAPublic,
216
+ name: "Tenant A",
217
+ createdAt: now,
218
+ },
219
+ {
220
+ id: tenantBId,
221
+ publicId: tenantBPublic,
222
+ name: "Tenant B",
223
+ createdAt: now,
224
+ },
225
+ ]);
226
+ await runtime.db.insert(schema.memberships).values([
227
+ {
228
+ id: uuidv7(clock),
229
+ tenantId: tenantAId,
230
+ userId: owner.id,
231
+ role: "owner",
232
+ isOwner: true,
233
+ permissions: serializePermissions(OWNER_PERMISSIONS),
234
+ createdAt: now,
235
+ },
236
+ {
237
+ id: uuidv7(clock),
238
+ tenantId: tenantAId,
239
+ userId: member.id,
240
+ role: "member",
241
+ isOwner: false,
242
+ permissions: serializePermissions(MEMBER_PERMISSIONS),
243
+ createdAt: now,
244
+ },
245
+ {
246
+ id: uuidv7(clock),
247
+ tenantId: tenantBId,
248
+ userId: owner.id,
249
+ role: "owner",
250
+ isOwner: true,
251
+ permissions: serializePermissions(OWNER_PERMISSIONS),
252
+ createdAt: now,
253
+ },
254
+ ]);
255
+ await runtime.db.insert(schema.selectedTenants).values({
256
+ userId: owner.id,
257
+ tenantId: tenantAId,
258
+ });
259
+
260
+ const keyPublicId = createPublicId("key", clock);
261
+ const secret = generateApiKeySecret();
262
+ await runtime.db.insert(schema.apiKeys).values({
263
+ id: uuidv7(clock),
264
+ publicId: keyPublicId,
265
+ tenantId: tenantAId,
266
+ userId: owner.id,
267
+ digest: digestApiKeySecret(runtime.apiKeyPepper, secret),
268
+ permissions: serializePermissions(OWNER_PERMISSIONS),
269
+ createdAt: now,
270
+ });
271
+
272
+ const notePublicId = createPublicId("note", clock);
273
+ await runtime.db.insert(schema.notes).values({
274
+ id: uuidv7(clock),
275
+ publicId: notePublicId,
276
+ tenantId: tenantAId,
277
+ title: "Seed note",
278
+ body: "hello",
279
+ createdBy: owner.id,
280
+ createdAt: now,
281
+ updatedAt: now,
282
+ });
283
+
284
+ await runtime.billing.billing.verifyRequestedCatalog();
285
+ const token = {
286
+ ...billingGrant("checkout", tenantAId, owner.id, now),
287
+ target: { kind: "tenant", id: tenantAId },
288
+ };
289
+ runtime.billing.authorization.issue(token);
290
+ const checkout = await runtime.billing.billing.startCheckout({
291
+ grant: token,
292
+ entity: { kind: "tenant", id: tenantAId },
293
+ payer: { id: owner.id, email: "owner@example.com", name: "Owner" },
294
+ offerKey: "pro_month",
295
+ catalogRevision: 1,
296
+ returnUrl: "https://app.test/billing",
297
+ });
298
+ const paid = await runtime.billing.fake.simulatePayment(
299
+ checkout.attempt.providerCheckoutSessionId!,
300
+ );
301
+ const signed = runtime.billing.fake.signWebhook(
302
+ JSON.stringify({
303
+ type: "subscription.active",
304
+ data: {
305
+ subscription_id: paid.providerSubscriptionId,
306
+ metadata: { checkoutAttemptId: checkout.attempt.attemptId },
307
+ },
308
+ }),
309
+ );
310
+ await runtime.billing.billing.ingestWebhook({
311
+ provider: "fake",
312
+ raw: signed,
313
+ });
314
+ await runtime.billing.billing.runWebhookInboxBatch({
315
+ workerId: "seed-webhooks",
316
+ });
317
+
318
+ return {
319
+ owner: {
320
+ id: owner.id,
321
+ email: "owner@example.com",
322
+ sessionCookie: owner.sessionCookie,
323
+ oauthToken,
324
+ },
325
+ member: {
326
+ id: member.id,
327
+ email: "member@example.com",
328
+ sessionCookie: member.sessionCookie,
329
+ },
330
+ outsider: {
331
+ id: outsider.id,
332
+ email: "outsider@example.com",
333
+ sessionCookie: outsider.sessionCookie,
334
+ },
335
+ tenantA: { id: tenantAId, publicId: tenantAPublic },
336
+ tenantB: { id: tenantBId, publicId: tenantBPublic },
337
+ apiKeyA: { publicId: keyPublicId, raw: formatApiKey(keyPublicId, secret) },
338
+ noteA: { publicId: notePublicId },
339
+ };
340
+ }
@@ -0,0 +1,116 @@
1
+ import {
2
+ createPlatformError,
3
+ type PlatformCredential,
4
+ type PlatformError,
5
+ } from "@codelitdev/platform";
6
+ import { and, eq } from "drizzle-orm";
7
+ import * as schema from "./db/schema/index.js";
8
+ import { parsePermissions, type ReferencePermission } from "./permissions.js";
9
+ import type { AppDb } from "./types.js";
10
+
11
+ export type ResolvedTenant = {
12
+ tenantId: string;
13
+ publicId: string;
14
+ permissions: ReadonlySet<ReferencePermission>;
15
+ };
16
+
17
+ export async function resolveTenantContext(input: {
18
+ db: AppDb;
19
+ principalId: string;
20
+ credential: PlatformCredential;
21
+ requestedPublicTenantId: string | null;
22
+ }): Promise<{ ok: true; value: ResolvedTenant } | { ok: false; error: PlatformError }> {
23
+ if (input.credential.kind === "api_key") {
24
+ if (!input.credential.credentialId) {
25
+ return { ok: false, error: createPlatformError("unauthenticated") };
26
+ }
27
+ const keys = await input.db
28
+ .select()
29
+ .from(schema.apiKeys)
30
+ .where(eq(schema.apiKeys.id, input.credential.credentialId))
31
+ .limit(1);
32
+ const key = keys[0];
33
+ if (!key) {
34
+ return { ok: false, error: createPlatformError("unauthenticated") };
35
+ }
36
+ const tenants = await input.db
37
+ .select()
38
+ .from(schema.tenants)
39
+ .where(eq(schema.tenants.id, key.tenantId))
40
+ .limit(1);
41
+ const tenant = tenants[0];
42
+ if (!tenant) {
43
+ return { ok: false, error: createPlatformError("tenant_forbidden") };
44
+ }
45
+ return {
46
+ ok: true,
47
+ value: {
48
+ tenantId: tenant.id,
49
+ publicId: tenant.publicId,
50
+ permissions: parsePermissions(key.permissions),
51
+ },
52
+ };
53
+ }
54
+ if (!input.requestedPublicTenantId) {
55
+ const selected = await input.db
56
+ .select()
57
+ .from(schema.selectedTenants)
58
+ .where(eq(schema.selectedTenants.userId, input.principalId))
59
+ .limit(1);
60
+ if (!selected[0]) {
61
+ return { ok: false, error: createPlatformError("tenant_required") };
62
+ }
63
+ return loadMembership(input.db, input.principalId, selected[0].tenantId);
64
+ }
65
+ const tenants = await input.db
66
+ .select()
67
+ .from(schema.tenants)
68
+ .where(eq(schema.tenants.publicId, input.requestedPublicTenantId))
69
+ .limit(1);
70
+ const tenant = tenants[0];
71
+ if (!tenant) {
72
+ return { ok: false, error: createPlatformError("tenant_forbidden") };
73
+ }
74
+ return loadMembership(input.db, input.principalId, tenant.id);
75
+ }
76
+
77
+ async function loadMembership(
78
+ db: AppDb,
79
+ principalId: string,
80
+ tenantId: string,
81
+ ): Promise<{ ok: true; value: ResolvedTenant } | { ok: false; error: PlatformError }> {
82
+ const rows = await db
83
+ .select({
84
+ membership: schema.memberships,
85
+ tenant: schema.tenants,
86
+ })
87
+ .from(schema.memberships)
88
+ .innerJoin(schema.tenants, eq(schema.tenants.id, schema.memberships.tenantId))
89
+ .where(
90
+ and(
91
+ eq(schema.memberships.tenantId, tenantId),
92
+ eq(schema.memberships.userId, principalId),
93
+ ),
94
+ )
95
+ .limit(1);
96
+ const row = rows[0];
97
+ if (!row) {
98
+ return { ok: false, error: createPlatformError("tenant_forbidden") };
99
+ }
100
+ return {
101
+ ok: true,
102
+ value: {
103
+ tenantId: row.tenant.id,
104
+ publicId: row.tenant.publicId,
105
+ permissions: parsePermissions(row.membership.permissions),
106
+ },
107
+ };
108
+ }
109
+
110
+ export function headerTenantId(
111
+ headers: Record<string, string | string[] | undefined>,
112
+ ): string | null {
113
+ const raw = headers["x-tenant-id"] ?? headers["X-Tenant-ID"];
114
+ const value = Array.isArray(raw) ? raw[0] : raw;
115
+ return value && value.trim().length > 0 ? value.trim() : null;
116
+ }
@@ -0,0 +1,20 @@
1
+ import type { PgliteDatabase } from "drizzle-orm/pglite";
2
+ import type * as schema from "./db/schema/index.js";
3
+ import type { ReferencePermission } from "./permissions.js";
4
+
5
+ export type AppDb = PgliteDatabase<typeof schema>;
6
+
7
+ export type { ReferencePermission };
8
+
9
+ export type IncomingRequest = {
10
+ method: string;
11
+ path: string;
12
+ headers: Record<string, string | string[] | undefined>;
13
+ body?: unknown;
14
+ };
15
+
16
+ export type DispatchResponse = {
17
+ status: number;
18
+ body: unknown;
19
+ headers?: Record<string, string>;
20
+ };
@@ -0,0 +1,57 @@
1
+ import { createObservability } from "@codelitdev/observability";
2
+ import { runBoundedMaintenance } from "./billing.js";
3
+ import { createPostgresRuntime } from "./runtime.js";
4
+
5
+ const databaseUrl = process.env.DATABASE_URL;
6
+ const authSecret = process.env.AUTH_SECRET;
7
+ const apiKeyPepper = process.env.API_KEY_PEPPER;
8
+ if (!databaseUrl || !authSecret || !apiKeyPepper) {
9
+ throw new Error("DATABASE_URL_AUTH_SECRET_AND_API_KEY_PEPPER_REQUIRED");
10
+ }
11
+ const observability = createObservability({
12
+ serviceName: "__PRODUCT_SLUG__-worker",
13
+ environment: process.env.NODE_ENV ?? "development",
14
+ logs: {
15
+ level: process.env.LOG_LEVEL ?? "info",
16
+ ...(process.env.OTLP_LOGS_ENDPOINT
17
+ ? {
18
+ otlp: {
19
+ endpoint: process.env.OTLP_LOGS_ENDPOINT,
20
+ ...(process.env.OTLP_LOGS_AUTHORIZATION
21
+ ? {
22
+ headers: {
23
+ authorization: process.env.OTLP_LOGS_AUTHORIZATION,
24
+ },
25
+ }
26
+ : {}),
27
+ },
28
+ }
29
+ : {}),
30
+ },
31
+ ...(process.env.POSTHOG_API_KEY
32
+ ? {
33
+ posthog: {
34
+ apiKey: process.env.POSTHOG_API_KEY,
35
+ ...(process.env.POSTHOG_HOST ? { host: process.env.POSTHOG_HOST } : {}),
36
+ },
37
+ }
38
+ : {}),
39
+ contextPolicy: { propertyAllowlist: new Set(["job_id"]) },
40
+ });
41
+ const runtime = await createPostgresRuntime({
42
+ databaseUrl,
43
+ authSecret,
44
+ apiKeyPepper,
45
+ publicApiUrl: process.env.PUBLIC_API_URL ?? "http://127.0.0.1:4000",
46
+ observability,
47
+ });
48
+ try {
49
+ const processed = await runBoundedMaintenance(runtime.billing.billing);
50
+ observability.logger.info({ processed }, "billing maintenance complete");
51
+ } catch (error) {
52
+ observability.captureException({ error, source: "worker.maintenance" });
53
+ throw error;
54
+ } finally {
55
+ await observability.shutdown(1_000);
56
+ await runtime.close();
57
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2022",
4
+ "module": "nodenext",
5
+ "moduleResolution": "nodenext",
6
+ "strict": true,
7
+ "skipLibCheck": true,
8
+ "esModuleInterop": true,
9
+ "noEmit": true,
10
+ "rootDir": ".",
11
+ "types": ["node", "bun"]
12
+ },
13
+ "include": ["src", "billing.config.ts"]
14
+ }
@@ -0,0 +1,7 @@
1
+ # URL of the product API used by the server-side BFF route.
2
+ API_URL=http://127.0.0.1:4000
3
+
4
+ # Optional request-time browser observability configuration.
5
+ # POSTHOG_API_KEY=
6
+ # POSTHOG_HOST=https://app.posthog.com
7
+ # DEPLOY_ENV=development
@@ -0,0 +1,51 @@
1
+ import { type NextRequest, NextResponse } from "next/server";
2
+
3
+ const API_URL = (process.env.API_URL ?? "http://127.0.0.1:4000").replace(/\/$/, "");
4
+
5
+ async function proxy(
6
+ request: NextRequest,
7
+ context: { params: Promise<{ path: string[] }> },
8
+ ) {
9
+ const { path } = await context.params;
10
+ const suffix = path.join("/");
11
+ // The BFF strips its own `/api` segment. Restore it for Better Auth and
12
+ // account-scoped routes; versioned product APIs live at `/v1/*` upstream.
13
+ const upstreamPath =
14
+ path[0] === "auth" || path[0] === "tenant" ? `/api/${suffix}` : `/${suffix}`;
15
+ const target = `${API_URL}${upstreamPath}${request.nextUrl.search}`;
16
+ const headers = new Headers(request.headers);
17
+ headers.delete("host");
18
+ let body: BodyInit | undefined;
19
+ if (request.method !== "GET" && request.method !== "HEAD") {
20
+ const contentType = request.headers.get("content-type") ?? "";
21
+ if (contentType.includes("application/x-www-form-urlencoded")) {
22
+ const form = await request.formData();
23
+ body = JSON.stringify(Object.fromEntries(form.entries()));
24
+ headers.set("content-type", "application/json");
25
+ headers.delete("content-length");
26
+ } else {
27
+ body = await request.text();
28
+ }
29
+ }
30
+ const response = await fetch(target, {
31
+ method: request.method,
32
+ headers,
33
+ body,
34
+ redirect: "manual",
35
+ });
36
+ const outputHeaders = new Headers();
37
+ for (const name of ["content-type", "set-cookie", "location", "x-request-id"]) {
38
+ const value = response.headers.get(name);
39
+ if (value) outputHeaders.set(name, value);
40
+ }
41
+ outputHeaders.set("cache-control", "no-store");
42
+ return new NextResponse(response.body, {
43
+ status: response.status,
44
+ headers: outputHeaders,
45
+ });
46
+ }
47
+
48
+ export const GET = proxy;
49
+ export const POST = proxy;
50
+ export const PATCH = proxy;
51
+ export const DELETE = proxy;