@codelitdev/platform-cli 0.1.0-alpha.1 → 0.3.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 (53) hide show
  1. package/README.md +77 -0
  2. package/dist/bin.js +7 -9
  3. package/dist/create.js +11 -20
  4. package/dist/doctor.js +1 -1
  5. package/dist/git.js +2 -2
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +1 -2
  8. package/dist/manifest.d.ts +8 -4
  9. package/dist/manifest.js +27 -5
  10. package/dist/preset.d.ts +26 -0
  11. package/dist/preset.js +110 -0
  12. package/dist/preset.json +70 -0
  13. package/dist/sync.d.ts +20 -0
  14. package/dist/sync.js +87 -0
  15. package/dist/template.d.ts +15 -0
  16. package/dist/template.js +33 -1
  17. package/package.json +14 -7
  18. package/template/.github/dependabot.yml +15 -0
  19. package/template/.github/workflows/code-quality.yml +31 -0
  20. package/template/.github/workflows/platform-conformance.yml +4 -3
  21. package/template/README.md +3 -2
  22. package/template/apps/api/.env.example +2 -1
  23. package/template/apps/api/README.md +3 -0
  24. package/template/apps/api/package.json +20 -17
  25. package/template/apps/api/scripts/generate-auth-schema.mjs +2 -2
  26. package/template/apps/api/src/app.test.ts +118 -1
  27. package/template/apps/api/src/auth/authenticate.ts +3 -2
  28. package/template/apps/api/src/auth/options.ts +32 -6
  29. package/template/apps/api/src/billing.ts +1 -1
  30. package/template/apps/api/src/db/migrations/0000_auth.sql +0 -1
  31. package/template/apps/api/src/db/schema/auth.generated.ts +1 -2
  32. package/template/apps/api/src/dispatch.ts +8 -1
  33. package/template/apps/api/src/express-app.ts +29 -2
  34. package/template/apps/api/src/main.ts +3 -10
  35. package/template/apps/api/src/permissions.ts +20 -0
  36. package/template/apps/api/src/runtime.ts +2 -2
  37. package/template/apps/api/src/seed.ts +10 -7
  38. package/template/apps/api/src/tenancy.ts +28 -3
  39. package/template/apps/web/app/globals.css +0 -10
  40. package/template/apps/web/app/layout.tsx +1 -1
  41. package/template/apps/web/app/login/page.tsx +6 -45
  42. package/template/apps/web/app/page.tsx +1 -1
  43. package/template/apps/web/next-env.d.ts +4 -0
  44. package/template/apps/web/package.json +8 -8
  45. package/template/apps/web/tsconfig.json +1 -1
  46. package/template/package.json +0 -1
  47. package/template/packages/api-contract/package.json +3 -3
  48. package/dist/codemod-readme-title.d.ts +0 -5
  49. package/dist/codemod-readme-title.js +0 -21
  50. package/dist/upgrade.d.ts +0 -13
  51. package/dist/upgrade.js +0 -97
  52. package/template/apps/api/src/logger.ts +0 -26
  53. package/template/tooling/platform/config.ts +0 -2
package/dist/template.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  export function resolveTemplateDir() {
@@ -21,3 +21,35 @@ export function slugify(name) {
21
21
  throw new Error("product_name_invalid");
22
22
  return slug;
23
23
  }
24
+ export function productNameFromTarget(targetDir) {
25
+ const name = path.basename(path.resolve(targetDir));
26
+ if (!name)
27
+ throw new Error("product_name_invalid");
28
+ return name;
29
+ }
30
+ /** The CLI release that renders managed files, pinned in the managed workflow. */
31
+ export function cliVersion() {
32
+ const here = path.dirname(fileURLToPath(import.meta.url));
33
+ const pkg = JSON.parse(readFileSync(path.join(here, "..", "package.json"), "utf8"));
34
+ return pkg.version;
35
+ }
36
+ /**
37
+ * Files the CLI owns in every product. `sync` rewrites them from the current
38
+ * template; everything else in a product, including `code-quality.yml`, is
39
+ * product-owned after `create`.
40
+ */
41
+ export const MANAGED_FILES = [".github/workflows/platform-conformance.yml"];
42
+ export function templateTokens(product) {
43
+ return {
44
+ __PRODUCT_NAME__: product.name,
45
+ __PRODUCT_SLUG__: product.slug,
46
+ __PLATFORM_CLI_VERSION__: cliVersion(),
47
+ };
48
+ }
49
+ export function renderTemplateFile(rel, product) {
50
+ let text = readFileSync(path.join(resolveTemplateDir(), rel), "utf8");
51
+ for (const [token, value] of Object.entries(templateTokens(product))) {
52
+ text = text.split(token).join(value);
53
+ }
54
+ return text;
55
+ }
package/package.json CHANGED
@@ -1,10 +1,19 @@
1
1
  {
2
2
  "name": "@codelitdev/platform-cli",
3
- "version": "0.1.0-alpha.1",
4
- "description": "Create, doctor, and upgrade CodeLit Platform products",
3
+ "version": "0.3.0",
4
+ "description": "Create, check, and sync CodeLit Platform products",
5
5
  "author": "CodeLit",
6
6
  "type": "module",
7
7
  "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/codelitdev/platform.git",
11
+ "directory": "packages/platform-cli"
12
+ },
13
+ "homepage": "https://github.com/codelitdev/platform/tree/main/packages/platform-cli#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/codelitdev/platform/issues"
16
+ },
8
17
  "bin": {
9
18
  "codelit-platform": "./dist/bin.js"
10
19
  },
@@ -17,10 +26,11 @@
17
26
  },
18
27
  "files": [
19
28
  "dist",
20
- "template"
29
+ "template",
30
+ "README.md"
21
31
  ],
22
32
  "scripts": {
23
- "build": "tsc -p tsconfig.json && bun -e \"import('node:fs').then(fs=>{fs.rmSync('template',{recursive:true,force:true});fs.cpSync('../../templates/saas-product','template',{recursive:true})})\"",
33
+ "build": "tsc -p tsconfig.json && bun -e \"import('node:fs').then(fs=>{fs.copyFileSync('src/preset.json','dist/preset.json');fs.rmSync('template',{recursive:true,force:true});fs.cpSync('../../templates/saas-product','template',{recursive:true})})\"",
24
34
  "test": "bun test --timeout 60000 src --path-ignore-patterns=**/template/**",
25
35
  "test:packed": "bun scripts/packed-consumer.mjs",
26
36
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
@@ -30,9 +40,6 @@
30
40
  "access": "public",
31
41
  "tag": "latest"
32
42
  },
33
- "dependencies": {
34
- "@codelitdev/platform-preset": "0.1.0-alpha.1"
35
- },
36
43
  "devDependencies": {
37
44
  "@types/bun": "^1.4.1",
38
45
  "@types/node": "^22.14.1",
@@ -0,0 +1,15 @@
1
+ # Product-owned. Opens one grouped pull request when a CodeLit Platform
2
+ # release is published; all @codelitdev packages release under one version.
3
+ # The platform conformance workflow gates the pull request.
4
+ version: 2
5
+ updates:
6
+ - package-ecosystem: "bun"
7
+ directory: "/"
8
+ schedule:
9
+ interval: "daily"
10
+ allow:
11
+ - dependency-name: "@codelitdev/*"
12
+ groups:
13
+ codelit-platform:
14
+ patterns:
15
+ - "@codelitdev/*"
@@ -0,0 +1,31 @@
1
+ # Product-owned: edit freely. `platform-cli sync` never touches this file.
2
+ # Steps match what template-smoke verifies on a fresh product. Add
3
+ # `bun run format:check` after formatting the product once with `bun run format`.
4
+ name: Code quality
5
+
6
+ on:
7
+ pull_request:
8
+ push:
9
+ branches: [main]
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ quality:
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
19
+ - uses: oven-sh/setup-bun@v2
20
+ with:
21
+ bun-version: 1.4.1
22
+ # `platform-cli create` intentionally does not resolve dependencies.
23
+ # Bootstrap the product lockfile on its first run; all subsequent CI
24
+ # installs are immutable and use the frozen lockfile below.
25
+ - run: bun install
26
+ if: ${{ !hashFiles('bun.lock') }}
27
+ - run: bun install --frozen-lockfile
28
+ - run: bun run lint
29
+ - run: bun run typecheck
30
+ - run: bun run test
31
+ - run: bun run build
@@ -22,7 +22,8 @@ jobs:
22
22
  - run: bun install
23
23
  if: ${{ !hashFiles('bun.lock') }}
24
24
  - run: bun install --frozen-lockfile
25
+ # Pinned to the CLI release that wrote this file. `sync` moves it.
26
+ - run: bunx @codelitdev/platform-cli@__PLATFORM_CLI_VERSION__ doctor
25
27
  - run: bun run --filter "*/api" check:drift
26
- - run: bun run test
27
- - run: bun run typecheck
28
- - run: bun run build
28
+ # Fails when the API package has no `test:conformance` script.
29
+ - run: bun run --filter "*/api" test:conformance
@@ -1,5 +1,6 @@
1
1
  # __PRODUCT_NAME__
2
2
 
3
3
  Generated from CodeLit Platform `templates/saas-product`. Product-owned
4
- application code lives in `apps/**` and `packages/api-contract/**`. Managed
5
- Platform files live under `tooling/platform/**`.
4
+ application code lives in `apps/**` and `packages/api-contract/**`. The
5
+ Platform CLI manages only `.github/workflows/platform-conformance.yml`; see
6
+ `.codelit-platform.json`.
@@ -3,7 +3,8 @@ PORT=4000
3
3
  PUBLIC_API_URL=http://127.0.0.1:4000
4
4
  WEB_ORIGIN=http://localhost:3000
5
5
  NODE_ENV=development
6
- DATABASE_URL=postgres://postgres:postgres@127.0.0.1:5432/__PRODUCT_SLUG__
6
+ # Matches the Postgres service in docker-compose.yml (`docker compose up -d`).
7
+ DATABASE_URL=postgres://__PRODUCT_SLUG__:__PRODUCT_SLUG__@127.0.0.1:5433/__PRODUCT_SLUG__
7
8
 
8
9
  # Generate local random values; AUTH_SECRET must be at least 32 characters.
9
10
  AUTH_SECRET=replace-with-a-random-secret-at-least-32-characters
@@ -1,3 +1,6 @@
1
1
  # __PRODUCT_NAME__ API
2
2
 
3
3
  Product-owned application services live here.
4
+
5
+ Open the interactive Swagger UI at `GET /docs`, or fetch the generated OpenAPI
6
+ document directly from `GET /openapi.json`.
@@ -8,6 +8,7 @@
8
8
  "build": "tsc -p tsconfig.json --noEmit",
9
9
  "typecheck": "tsc -p tsconfig.json --noEmit",
10
10
  "test": "bun test --timeout 60000 src",
11
+ "test:conformance": "bun test --timeout 60000 src --test-name-pattern \"platform conformance\"",
11
12
  "lint": "biome lint .",
12
13
  "start": "bun src/main.ts",
13
14
  "worker": "bun src/worker.ts",
@@ -20,34 +21,36 @@
20
21
  "pretest": "bun run check:auth-schema"
21
22
  },
22
23
  "dependencies": {
23
- "@better-auth/core": "1.7.2",
24
+ "@better-auth/core": "1.7.7",
24
25
  "@codelitdev/billing": "workspace:*",
25
26
  "@codelitdev/oauth-server-kit": "workspace:*",
26
27
  "@codelitdev/mcp-server-kit": "workspace:*",
27
28
  "@codelitdev/platform-conformance": "workspace:*",
28
29
  "@codelitdev/observability": "workspace:*",
29
- "@better-auth/oauth-provider": "1.7.2",
30
+ "@better-auth/oauth-provider": "1.7.7",
30
31
  "@better-auth/utils": "0.4.2",
31
- "@better-fetch/fetch": "1.3.1",
32
+ "@better-fetch/fetch": "1.3.2",
32
33
  "@ts-rest/express": "3.52.1",
33
- "@ts-rest/open-api": "^3.52.1",
34
+ "@ts-rest/open-api": "3.52.1",
34
35
  "@codelitdev/platform": "workspace:*",
35
36
  "@__PRODUCT_SLUG__/api-contract": "workspace:*",
36
- "@types/pg": "^8.23.1",
37
+ "@types/pg": "8.23.1",
37
38
  "better-call": "1.4.0",
38
- "better-auth": "1.7.2",
39
- "drizzle-orm": "^0.45.2",
40
- "express": "^4.21.2",
41
- "pg": "^8.23.0",
42
- "pino": "^9.6.0",
43
- "zod": "^3.25.76"
39
+ "better-auth": "1.7.7",
40
+ "drizzle-orm": "0.45.2",
41
+ "express": "4.21.2",
42
+ "pg": "8.23.0",
43
+ "pino": "9.6.0",
44
+ "swagger-ui-express": "^5.0.1",
45
+ "zod": "3.25.76"
44
46
  },
45
47
  "devDependencies": {
46
- "@electric-sql/pglite": "^0.2.17",
47
- "@types/express": "^4.17.21",
48
- "@types/node": "^22.14.1",
49
- "drizzle-kit": "0.31.4",
50
- "typescript": "^5.9.3",
51
- "@types/bun": "^1.4.1"
48
+ "@electric-sql/pglite": "0.5.8",
49
+ "@types/express": "^5.0.6",
50
+ "@types/node": "^26.4.1",
51
+ "@types/swagger-ui-express": "^4.1.8",
52
+ "drizzle-kit": "0.31.10",
53
+ "typescript": "5.9.3",
54
+ "@types/bun": "1.4.1"
52
55
  }
53
56
  }
@@ -19,7 +19,7 @@ const options = {
19
19
  baseURL: publicApiUrl,
20
20
  basePath: "/api/auth",
21
21
  secret: "schema-generation-secret-at-least-32-chars",
22
- emailAndPassword: { enabled: true },
22
+ emailAndPassword: { enabled: false },
23
23
  plugins: [
24
24
  jwt(),
25
25
  emailOTP({
@@ -90,7 +90,7 @@ const tables = Object.entries(schema)
90
90
  const ts = [
91
91
  "/**",
92
92
  " * AUTO-GENERATED FILE. DO NOT EDIT.",
93
- " * Generated by Better Auth getSchema (better-auth/db) from the reference",
93
+ " * Generated by Better Auth getSchema (better-auth/db) from the product's",
94
94
  " * Better Auth options (jwt + oauth-server-kit oauthProvider).",
95
95
  " * Importing this module performs no DDL.",
96
96
  " */",
@@ -7,7 +7,7 @@ import * as schema from "./db/schema/index.js";
7
7
  import { dispatch } from "./dispatch.js";
8
8
  import { createExpressApp } from "./express-app.js";
9
9
  import { createPgliteRuntime, freezeRuntimeClock } from "./runtime.js";
10
- import { seedWorld } from "./seed.js";
10
+ import { mintOAuthToken, seedWorld } from "./seed.js";
11
11
 
12
12
  describe.serial("reference API adapters", () => {
13
13
  it("does not run DDL when oauth-server-kit options and schema modules are imported", async () => {
@@ -253,6 +253,40 @@ describe.serial("reference API adapters", () => {
253
253
  await runtime.close();
254
254
  });
255
255
 
256
+ it("limits an OAuth token to the data scopes it was granted", 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 readOnly = await mintOAuthToken(
261
+ runtime,
262
+ world.owner.sessionCookie,
263
+ "openid profile email data:read",
264
+ );
265
+ const headers = {
266
+ authorization: `Bearer ${readOnly}`,
267
+ "x-tenant-id": world.tenantA.publicId,
268
+ };
269
+ const list = await dispatch(runtime, { method: "GET", path: "/v1/notes", headers });
270
+ expect(list.status).toBe(200);
271
+ // The owner may write, but this token was only granted data:read.
272
+ const update = await dispatch(runtime, {
273
+ method: "PATCH",
274
+ path: `/v1/notes/${world.noteA.publicId}`,
275
+ headers,
276
+ body: { title: "read-only token" },
277
+ });
278
+ expect(update.status).toBe(403);
279
+ expect(update.body).toMatchObject({ code: "forbidden" });
280
+ const fullAccess = await dispatch(runtime, {
281
+ method: "PATCH",
282
+ path: `/v1/notes/${world.noteA.publicId}`,
283
+ headers: { ...headers, authorization: `Bearer ${world.owner.oauthToken}` },
284
+ body: { title: "read-write token" },
285
+ });
286
+ expect(fullAccess.status).toBe(200);
287
+ await runtime.close();
288
+ });
289
+
256
290
  it("serves the same notes service over MCP with parity, isolation, and confirmation", async () => {
257
291
  const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
258
292
  const runtime = await createPgliteRuntime({ clock });
@@ -473,7 +507,90 @@ describe.serial("reference API adapters", () => {
473
507
  const openapi = await fetch(`http://127.0.0.1:${address.port}/openapi.json`);
474
508
  expect(openapi.status).toBe(200);
475
509
  expect((await openapi.json()).paths["/v1/notes"]).toBeDefined();
510
+ const docs = await fetch(`http://127.0.0.1:${address.port}/docs`);
511
+ expect(docs.status).toBe(200);
512
+ expect(docs.headers.get("content-type")).toContain("text/html");
513
+ expect(await docs.text()).toContain("Swagger UI");
514
+ const docsInitializer = await fetch(
515
+ `http://127.0.0.1:${address.port}/docs/swagger-ui-init.js`,
516
+ );
517
+ expect(docsInitializer.status).toBe(200);
518
+ expect(await docsInitializer.text()).toContain('"/v1/notes"');
519
+ const protectedResource = await fetch(
520
+ `http://127.0.0.1:${address.port}/.well-known/oauth-protected-resource/mcp`,
521
+ );
522
+ expect(protectedResource.status).toBe(200);
523
+ expect(await protectedResource.json()).toMatchObject({
524
+ resource: runtime.auth.mcpResource,
525
+ authorization_servers: [runtime.auth.issuer],
526
+ });
527
+ const authorizationServer = await fetch(
528
+ `http://127.0.0.1:${address.port}/.well-known/oauth-authorization-server`,
529
+ );
530
+ expect(authorizationServer.status).toBe(200);
531
+ expect(await authorizationServer.json()).toMatchObject({
532
+ registration_endpoint: `${runtime.auth.issuer}/oauth2/register`,
533
+ });
534
+ const dcr = await fetch(
535
+ `http://127.0.0.1:${address.port}${runtime.auth.authBasePath}/oauth2/register`,
536
+ {
537
+ method: "POST",
538
+ headers: { "content-type": "application/json" },
539
+ body: JSON.stringify({
540
+ client_name: "local MCP client",
541
+ redirect_uris: ["http://127.0.0.1:33418"],
542
+ token_endpoint_auth_method: "none",
543
+ grant_types: ["authorization_code", "refresh_token"],
544
+ response_types: ["code"],
545
+ application_type: "native",
546
+ scope: "openid profile email data:read",
547
+ }),
548
+ },
549
+ );
550
+ expect(dcr.status).toBe(201);
551
+ expect(await dcr.json()).toMatchObject({
552
+ token_endpoint_auth_method: "none",
553
+ });
554
+ const mcpUnauthorized = await fetch(`http://127.0.0.1:${address.port}/mcp`, {
555
+ method: "POST",
556
+ headers: { "content-type": "application/json" },
557
+ body: JSON.stringify({
558
+ jsonrpc: "2.0",
559
+ id: 1,
560
+ method: "initialize",
561
+ params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: {} },
562
+ }),
563
+ });
564
+ expect(mcpUnauthorized.status).toBe(401);
565
+ expect(mcpUnauthorized.headers.get("www-authenticate")).toBe(
566
+ `Bearer resource_metadata="${runtime.auth.publicApiUrl}/.well-known/oauth-protected-resource/mcp"`,
567
+ );
476
568
  await new Promise<void>((resolve) => server.close(() => resolve()));
477
569
  await runtime.close();
478
570
  });
571
+
572
+ it("signs in with email OTP and rejects email-password credentials", async () => {
573
+ const clock = freezeRuntimeClock(new Date("2026-03-01T00:00:00.000Z"));
574
+ const runtime = await createPgliteRuntime({ clock });
575
+ const otp = await runtime.auth.auth.api.createVerificationOTP({
576
+ body: { email: "otp-user@example.com", type: "sign-in" },
577
+ });
578
+ const signedIn = await runtime.auth.auth.api.signInEmailOTP({
579
+ body: { email: "otp-user@example.com", otp, name: "OTP User" },
580
+ asResponse: true,
581
+ });
582
+ expect(signedIn.ok).toBe(true);
583
+ const password = await runtime.auth.auth.handler(
584
+ new Request(`${runtime.auth.issuer}/sign-in/email`, {
585
+ method: "POST",
586
+ headers: { "content-type": "application/json" },
587
+ body: JSON.stringify({
588
+ email: "otp-user@example.com",
589
+ password: "reference-password-1",
590
+ }),
591
+ }),
592
+ );
593
+ expect(password.ok).toBe(false);
594
+ await runtime.close();
595
+ });
479
596
  });
@@ -37,7 +37,7 @@ export async function authenticateHttpRequest(
37
37
  if (selected.kind === "absent") {
38
38
  return mapTransportAuthentication({ kind: "absent" }, { transport: "http" });
39
39
  }
40
- if (selected.kind === "ambiguous") {
40
+ if (selected.kind === "ambiguous" || selected.kind === "malformed") {
41
41
  return { kind: "rejected", error: selected.error };
42
42
  }
43
43
  const presented = selected.credential;
@@ -91,6 +91,7 @@ export async function authenticateHttpRequest(
91
91
  credential: {
92
92
  kind: "oauth",
93
93
  credentialId: resolved.identity.clientId,
94
+ scopes: resolved.identity.scopes,
94
95
  },
95
96
  };
96
97
  }
@@ -143,7 +144,7 @@ export async function authenticateMcpRequest(
143
144
  if (selected.kind === "absent") {
144
145
  return mapTransportAuthentication({ kind: "absent" }, { transport: "mcp" });
145
146
  }
146
- if (selected.kind === "ambiguous") {
147
+ if (selected.kind === "ambiguous" || selected.kind === "malformed") {
147
148
  return { kind: "rejected", error: selected.error };
148
149
  }
149
150
  if (selected.credential.kind === "session") {
@@ -1,11 +1,22 @@
1
1
  import { oauthProvider } from "@better-auth/oauth-provider";
2
2
  import { createOAuthProviderOptions } from "@codelitdev/oauth-server-kit/better-auth";
3
+ import type { BetterAuthOptions } from "better-auth";
3
4
  import { emailOTP } from "better-auth/plugins/email-otp";
4
5
  import { jwt } from "better-auth/plugins/jwt";
5
6
 
6
7
  export const AUTH_BASE_PATH = "/api/auth";
7
8
  export const AUTH_SECRET_MIN_LENGTH = 32;
8
9
 
10
+ export const DATA_READ_SCOPE = "data:read";
11
+ export const DATA_WRITE_SCOPE = "data:write";
12
+ // MCP clients request exactly these. `offline_access` gets them a refresh
13
+ // token instead of a new consent every time the access token expires.
14
+ export const MCP_SCOPES_SUPPORTED = [
15
+ DATA_READ_SCOPE,
16
+ DATA_WRITE_SCOPE,
17
+ "offline_access",
18
+ ] as const;
19
+
9
20
  export type ReferenceAuthUrls = {
10
21
  publicApiUrl: string;
11
22
  webOrigin: string;
@@ -33,10 +44,23 @@ export function oauthProviderInput(urls: ReturnType<typeof authUrls>) {
33
44
  return createOAuthProviderOptions({
34
45
  loginPage: `${urls.publicApiUrl}/oauth/login`,
35
46
  consentPage: `${urls.publicApiUrl}/oauth/consent`,
36
- scopes: ["openid", "profile", "email", "offline_access", "data:read"],
47
+ scopes: [
48
+ "openid",
49
+ "profile",
50
+ "email",
51
+ "offline_access",
52
+ DATA_READ_SCOPE,
53
+ DATA_WRITE_SCOPE,
54
+ ],
37
55
  validAudiences: [urls.restResource, urls.mcpResource],
56
+ allowDynamicClientRegistration: true,
57
+ allowUnauthenticatedDynamicClientRegistration: true,
38
58
  clientRegistrationDefaultScopes: ["openid", "profile", "email"],
39
- clientRegistrationAllowedScopes: ["offline_access", "data:read"],
59
+ clientRegistrationAllowedScopes: [
60
+ "offline_access",
61
+ DATA_READ_SCOPE,
62
+ DATA_WRITE_SCOPE,
63
+ ],
40
64
  });
41
65
  }
42
66
 
@@ -45,7 +69,7 @@ export function referenceAuthOptions(input: {
45
69
  publicApiUrl: string;
46
70
  secret: string;
47
71
  webOrigin?: string;
48
- database?: unknown;
72
+ database?: BetterAuthOptions["database"];
49
73
  }) {
50
74
  const urls = authUrls(input.publicApiUrl, input.webOrigin);
51
75
  return {
@@ -54,13 +78,15 @@ export function referenceAuthOptions(input: {
54
78
  basePath: AUTH_BASE_PATH,
55
79
  secret: input.secret,
56
80
  trustedOrigins: [urls.webOrigin, urls.publicApiUrl],
57
- emailAndPassword: { enabled: true },
81
+ emailAndPassword: { enabled: false },
58
82
  ...(input.database ? { database: input.database } : {}),
59
83
  plugins: [
60
84
  jwt(),
61
85
  emailOTP({
62
- async sendVerificationOTP() {
63
- /* Product mail is application-owned; OTP still issues locally. */
86
+ async sendVerificationOTP({ email, otp, type }) {
87
+ if ((process.env.NODE_ENV ?? "development") === "development") {
88
+ console.info(`[auth] ${type} OTP for ${email}: ${otp}`);
89
+ }
64
90
  },
65
91
  }),
66
92
  oauthProvider(oauthProviderInput(urls)),
@@ -53,6 +53,6 @@ export function composeBilling(db: AppDb, clock: Clock): BillingBundle {
53
53
  export async function runBoundedMaintenance(billing: BillingEngine): Promise<number> {
54
54
  return billing.runWebhookInboxBatch({
55
55
  limit: 25,
56
- workerId: "reference-maintenance",
56
+ workerId: "__PRODUCT_SLUG__-maintenance",
57
57
  });
58
58
  }
@@ -22,7 +22,6 @@ CREATE TABLE IF NOT EXISTS "session" (
22
22
  --> statement-breakpoint
23
23
  CREATE TABLE IF NOT EXISTS "account" (
24
24
  id text PRIMARY KEY,
25
- "issuer" text NOT NULL,
26
25
  "account_id" text NOT NULL,
27
26
  "provider_id" text NOT NULL,
28
27
  "user_id" text NOT NULL REFERENCES "user"("id") ON DELETE CASCADE,
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * AUTO-GENERATED FILE. DO NOT EDIT.
3
- * Generated by Better Auth getSchema (better-auth/db) from the reference
3
+ * Generated by Better Auth getSchema (better-auth/db) from the product's
4
4
  * Better Auth options (jwt + oauth-server-kit oauthProvider).
5
5
  * Importing this module performs no DDL.
6
6
  */
@@ -29,7 +29,6 @@ export const session = pgTable("session", {
29
29
 
30
30
  export const account = pgTable("account", {
31
31
  id: text("id").primaryKey(),
32
- issuer: text("issuer").notNull(),
33
32
  accountId: text("account_id").notNull(),
34
33
  providerId: text("provider_id").notNull(),
35
34
  userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade" }),
@@ -89,7 +89,14 @@ export async function dispatch(
89
89
  return {
90
90
  status: result.status,
91
91
  body: result.body,
92
- headers: result.headers,
92
+ headers: {
93
+ ...result.headers,
94
+ ...(result.status === 401
95
+ ? {
96
+ "WWW-Authenticate": `Bearer resource_metadata="${deps.auth.publicApiUrl}/.well-known/oauth-protected-resource/mcp"`,
97
+ }
98
+ : {}),
99
+ },
93
100
  };
94
101
  }
95
102
 
@@ -1,12 +1,15 @@
1
1
  import { contract } from "@__PRODUCT_SLUG__/api-contract";
2
2
  import { createOAuthPagesRouter } from "@codelitdev/oauth-server-kit/express";
3
+ import { createMcpOAuthDiscoveryRoutes } from "@codelitdev/oauth-server-kit/mcp";
3
4
  import { readOrCreateRequestId } from "@codelitdev/platform";
4
5
  import { createExpressEndpoints, initServer } from "@ts-rest/express";
5
6
  import { toNodeHandler } from "better-auth/node";
6
- import express, { type Express } from "express";
7
- import { AUTH_BASE_PATH } from "./auth/options.js";
7
+ import express, { type Express, type RequestHandler } from "express";
8
+ import swaggerUi from "swagger-ui-express";
9
+ import { AUTH_BASE_PATH, MCP_SCOPES_SUPPORTED } from "./auth/options.js";
8
10
  import type { DispatchDeps } from "./deps.js";
9
11
  import { dispatch } from "./dispatch.js";
12
+ import { createOpenApiDocument } from "./openapi.js";
10
13
 
11
14
  export function createExpressApp(deps: DispatchDeps): Express {
12
15
  const app = express();
@@ -44,6 +47,15 @@ export function createExpressApp(deps: DispatchDeps): Express {
44
47
  }
45
48
  next();
46
49
  });
50
+ app.use(
51
+ createMcpOAuthDiscoveryRoutes({
52
+ auth: deps.auth.auth,
53
+ oauthResourceClient: deps.auth.oauthResourceClient,
54
+ resourceUrl: deps.auth.mcpResource,
55
+ scopesSupported: [...MCP_SCOPES_SUPPORTED],
56
+ allowedOrigins: "*",
57
+ }),
58
+ );
47
59
  app.all(`${AUTH_BASE_PATH}/*`, toNodeHandler(deps.auth.auth));
48
60
  app.use(
49
61
  createOAuthPagesRouter({
@@ -54,6 +66,21 @@ export function createExpressApp(deps: DispatchDeps): Express {
54
66
  loginMethods: [{ type: "email-otp" }],
55
67
  }),
56
68
  );
69
+ // The Swagger typings can resolve a separate Express type version in a
70
+ // freshly generated workspace, so normalize its handlers at this boundary.
71
+ app.use(
72
+ "/docs",
73
+ ...(swaggerUi.serve as unknown as RequestHandler[]),
74
+ swaggerUi.setup(createOpenApiDocument(deps.auth.publicApiUrl), {
75
+ explorer: true,
76
+ swaggerOptions: {
77
+ persistAuthorization: true,
78
+ displayRequestDuration: true,
79
+ docExpansion: "none",
80
+ defaultModelsExpandDepth: -1,
81
+ },
82
+ }) as unknown as RequestHandler,
83
+ );
57
84
  app.use(express.json({ limit: "32kb" }));
58
85
 
59
86
  const server = initServer();
@@ -60,11 +60,11 @@ const app = createExpressApp(runtime);
60
60
  const server = await new Promise<ReturnType<typeof app.listen>>((resolve) => {
61
61
  const listening = app.listen(port, () => resolve(listening));
62
62
  });
63
- logger.info({ port }, "reference api listening");
63
+ logger.info({ port }, "api listening");
64
64
 
65
65
  if (process.env.SEED === "1") {
66
66
  if (await hasSeededWorld(runtime)) {
67
- logger.info("reference world already seeded; skipping seed");
67
+ logger.info("demo data already seeded; skipping seed");
68
68
  } else {
69
69
  const world = await seedWorld(runtime, runtime.clock);
70
70
  logger.info(
@@ -73,14 +73,7 @@ if (process.env.SEED === "1") {
73
73
  apiKeyHint: world.apiKeyA.publicId,
74
74
  note: world.noteA.publicId,
75
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`,
76
+ "seeded demo data",
84
77
  );
85
78
  }
86
79
  }