@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
@@ -18,6 +18,26 @@ export const MEMBER_PERMISSIONS: readonly ReferencePermission[] = [
18
18
  "billing:read",
19
19
  ];
20
20
 
21
+ /**
22
+ * What each OAuth data scope allows. An OAuth request keeps only the
23
+ * member's permissions that its granted scopes cover, so a token approved
24
+ * as read-only cannot write even when the member could.
25
+ */
26
+ export const SCOPE_PERMISSIONS: Readonly<
27
+ Record<string, readonly ReferencePermission[]>
28
+ > = {
29
+ "data:read": ["notes:read", "billing:read"],
30
+ "data:write": ["notes:write", "notes:delete", "tenant:admin"],
31
+ };
32
+
33
+ export function narrowToScopes(
34
+ permissions: ReadonlySet<ReferencePermission>,
35
+ scopes: readonly string[],
36
+ ): Set<ReferencePermission> {
37
+ const allowed = new Set(scopes.flatMap((scope) => SCOPE_PERMISSIONS[scope] ?? []));
38
+ return new Set([...permissions].filter((permission) => allowed.has(permission)));
39
+ }
40
+
21
41
  export function parsePermissions(value: string): Set<ReferencePermission> {
22
42
  const allowed = new Set<string>(REFERENCE_PERMISSIONS);
23
43
  const parsed = new Set<ReferencePermission>();
@@ -136,7 +136,7 @@ export async function createPostgresRuntime(options: {
136
136
  const observability =
137
137
  options.observability ??
138
138
  createObservability({
139
- serviceName: options.serviceName ?? "reference-api",
139
+ serviceName: options.serviceName ?? "__PRODUCT_SLUG__-api",
140
140
  environment: "production",
141
141
  contextPolicy: {
142
142
  propertyAllowlist: new Set(["path", "method", "job_id"]),
@@ -148,7 +148,7 @@ export async function createPostgresRuntime(options: {
148
148
  clock,
149
149
  apiKeyPepper: options.apiKeyPepper,
150
150
  billing,
151
- serviceName: options.serviceName ?? "reference-api",
151
+ serviceName: options.serviceName ?? "__PRODUCT_SLUG__-api",
152
152
  databaseReady: true,
153
153
  logger: options.logger ?? observability.logger,
154
154
  observability,
@@ -32,7 +32,6 @@ export type SeededWorld = {
32
32
  noteA: { publicId: string };
33
33
  };
34
34
 
35
- const PASSWORD = "reference-password-1";
36
35
  const SEEDED_TENANT_A_ID = "11111111-1111-4111-8111-111111111111";
37
36
  const SEEDED_TENANT_B_ID = "22222222-2222-4222-8222-222222222222";
38
37
 
@@ -63,8 +62,11 @@ async function signUp(
63
62
  name: string,
64
63
  email: string,
65
64
  ): Promise<{ id: string; sessionCookie: string }> {
66
- const response = await runtime.auth.auth.api.signUpEmail({
67
- body: { name, email, password: PASSWORD },
65
+ const otp = await runtime.auth.auth.api.createVerificationOTP({
66
+ body: { email, type: "sign-in" },
67
+ });
68
+ const response = await runtime.auth.auth.api.signInEmailOTP({
69
+ body: { email, otp, name },
68
70
  asResponse: true,
69
71
  });
70
72
  if (!response.ok) {
@@ -89,15 +91,16 @@ function pkce() {
89
91
  };
90
92
  }
91
93
 
92
- async function mintOAuthToken(
94
+ export async function mintOAuthToken(
93
95
  runtime: Runtime,
94
96
  sessionCookie: string,
97
+ scope = "openid profile email offline_access data:read data:write",
95
98
  ): Promise<string> {
96
- const redirectUri = "com.example.reference:/oauth/callback";
99
+ const redirectUri = "com.example.__PRODUCT_SLUG__:/oauth/callback";
97
100
  const client = await runtime.auth.auth.api.createOAuthClient({
98
101
  headers: new Headers({ cookie: sessionCookie }),
99
102
  body: {
100
- client_name: "Reference test client",
103
+ client_name: "__PRODUCT_SLUG__ test client",
101
104
  redirect_uris: [redirectUri],
102
105
  token_endpoint_auth_method: "none",
103
106
  grant_types: ["authorization_code", "refresh_token"],
@@ -121,7 +124,7 @@ async function mintOAuthToken(
121
124
  client_id: client.client_id,
122
125
  redirect_uri: redirectUri,
123
126
  response_type: "code",
124
- scope: "openid profile email offline_access data:read",
127
+ scope,
125
128
  state: "state-123",
126
129
  code_challenge: proof.challenge,
127
130
  code_challenge_method: "S256",
@@ -5,7 +5,11 @@ import {
5
5
  } from "@codelitdev/platform";
6
6
  import { and, eq } from "drizzle-orm";
7
7
  import * as schema from "./db/schema/index.js";
8
- import { parsePermissions, type ReferencePermission } from "./permissions.js";
8
+ import {
9
+ narrowToScopes,
10
+ parsePermissions,
11
+ type ReferencePermission,
12
+ } from "./permissions.js";
9
13
  import type { AppDb } from "./types.js";
10
14
 
11
15
  export type ResolvedTenant = {
@@ -14,12 +18,33 @@ export type ResolvedTenant = {
14
18
  permissions: ReadonlySet<ReferencePermission>;
15
19
  };
16
20
 
17
- export async function resolveTenantContext(input: {
21
+ type TenantInput = {
18
22
  db: AppDb;
19
23
  principalId: string;
20
24
  credential: PlatformCredential;
21
25
  requestedPublicTenantId: string | null;
22
- }): Promise<{ ok: true; value: ResolvedTenant } | { ok: false; error: PlatformError }> {
26
+ };
27
+
28
+ export async function resolveTenantContext(
29
+ input: TenantInput,
30
+ ): Promise<{ ok: true; value: ResolvedTenant } | { ok: false; error: PlatformError }> {
31
+ const resolved = await resolveTenant(input);
32
+ if (!resolved.ok || input.credential.kind !== "oauth") return resolved;
33
+ return {
34
+ ok: true,
35
+ value: {
36
+ ...resolved.value,
37
+ permissions: narrowToScopes(
38
+ resolved.value.permissions,
39
+ input.credential.scopes ?? [],
40
+ ),
41
+ },
42
+ };
43
+ }
44
+
45
+ async function resolveTenant(
46
+ input: TenantInput,
47
+ ): Promise<{ ok: true; value: ResolvedTenant } | { ok: false; error: PlatformError }> {
23
48
  if (input.credential.kind === "api_key") {
24
49
  if (!input.credential.credentialId) {
25
50
  return { ok: false, error: createPlatformError("unauthenticated") };
@@ -141,16 +141,6 @@ textarea:focus {
141
141
  display: grid;
142
142
  align-items: stretch;
143
143
  }
144
- .auth-card details {
145
- margin-top: 20px;
146
- padding-top: 18px;
147
- border-top: 1px solid var(--line);
148
- }
149
- .auth-card summary {
150
- cursor: pointer;
151
- color: #9a5a12;
152
- font-weight: 700;
153
- }
154
144
  .auth-card small {
155
145
  color: var(--muted);
156
146
  }
@@ -6,7 +6,7 @@ import { BrowserObservabilityProvider } from "../components/browser-observabilit
6
6
  import { getBrowserObservabilityConfig } from "../lib/observability-config";
7
7
 
8
8
  export const metadata = {
9
- title: "Reference product",
9
+ title: "__PRODUCT_SLUG__",
10
10
  };
11
11
 
12
12
  export default async function RootLayout({ children }: { children: ReactNode }) {
@@ -6,7 +6,6 @@ import { type FormEvent, useState } from "react";
6
6
  export default function SignInPage() {
7
7
  const [email, setEmail] = useState("");
8
8
  const [otp, setOtp] = useState("");
9
- const [password, setPassword] = useState("");
10
9
  const [sent, setSent] = useState(false);
11
10
  const [error, setError] = useState<string | null>(null);
12
11
 
@@ -40,27 +39,12 @@ export default function SignInPage() {
40
39
  window.location.assign("/");
41
40
  }
42
41
 
43
- async function signInWithPassword(event: FormEvent<HTMLFormElement>) {
44
- event.preventDefault();
45
- setError(null);
46
- const response = await fetch("/api/auth/sign-in/email", {
47
- method: "POST",
48
- headers: { "content-type": "application/json" },
49
- body: JSON.stringify({ email, password }),
50
- });
51
- if (!response.ok) {
52
- setError("That email or password is invalid.");
53
- return;
54
- }
55
- window.location.assign("/");
56
- }
57
-
58
42
  return (
59
43
  <main className="auth-page">
60
44
  <section className="card auth-card stack">
61
45
  <p className="eyebrow">CodeLit Platform</p>
62
46
  <h1>Sign in</h1>
63
- <p className="subtitle">Access your reference workspace.</p>
47
+ <p className="subtitle">We'll email you a one-time sign-in code.</p>
64
48
  {!sent ? (
65
49
  <form onSubmit={sendCode}>
66
50
  <label>
@@ -68,7 +52,7 @@ export default function SignInPage() {
68
52
  <input
69
53
  type="email"
70
54
  name="email"
71
- autoComplete="username"
55
+ autoComplete="email"
72
56
  value={email}
73
57
  onChange={(event) => setEmail(event.target.value)}
74
58
  required
@@ -79,11 +63,15 @@ export default function SignInPage() {
79
63
  ) : (
80
64
  <form onSubmit={verifyCode}>
81
65
  <p>Enter the code sent to {email}.</p>
66
+ <p className="subtitle">
67
+ In local development, the API process prints the code to the console.
68
+ </p>
82
69
  <label>
83
70
  Sign-in code
84
71
  <input
85
72
  inputMode="numeric"
86
73
  name="otp"
74
+ autoComplete="one-time-code"
87
75
  value={otp}
88
76
  onChange={(event) => setOtp(event.target.value)}
89
77
  required
@@ -93,33 +81,6 @@ export default function SignInPage() {
93
81
  </form>
94
82
  )}
95
83
  {error ? <p role="alert">{error}</p> : null}
96
- <details>
97
- <summary>Local demo password sign-in</summary>
98
- <p>
99
- When started with SEED=1, use owner@example.com and reference-password-1.
100
- </p>
101
- <form onSubmit={signInWithPassword}>
102
- <label>
103
- Email
104
- <input
105
- type="email"
106
- value={email}
107
- onChange={(event) => setEmail(event.target.value)}
108
- required
109
- />
110
- </label>
111
- <label>
112
- Password
113
- <input
114
- type="password"
115
- value={password}
116
- onChange={(event) => setPassword(event.target.value)}
117
- required
118
- />
119
- </label>
120
- <Button type="submit">Sign in with password</Button>
121
- </form>
122
- </details>
123
84
  <small>Same-origin BFF cookies are set by the API after verification.</small>
124
85
  </section>
125
86
  </main>
@@ -51,7 +51,7 @@ export default function HomePage() {
51
51
  <header className="app-header">
52
52
  <div>
53
53
  <p className="eyebrow">CodeLit Platform</p>
54
- <h1>Reference workspace</h1>
54
+ <h1>__PRODUCT_SLUG__ workspace</h1>
55
55
  <p className="subtitle">Manage your teams and shared notes.</p>
56
56
  </div>
57
57
  </header>
@@ -1,2 +1,6 @@
1
1
  /// <reference types="next" />
2
2
  /// <reference types="next/image-types/global" />
3
+ /// <reference path="./.next/types/routes.d.ts" />
4
+
5
+ // NOTE: This file should not be edited
6
+ // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
@@ -12,15 +12,15 @@
12
12
  "dependencies": {
13
13
  "@codelitdev/design-system": "workspace:*",
14
14
  "@codelitdev/observability": "workspace:*",
15
- "next": "^15.5.4",
16
- "posthog-js": "^1.425.1",
17
- "react": "^19.1.1",
18
- "react-dom": "^19.1.1"
15
+ "next": "16.3.6",
16
+ "posthog-js": "^1.427.2",
17
+ "react": "19.2.8",
18
+ "react-dom": "19.2.8"
19
19
  },
20
20
  "devDependencies": {
21
- "@types/node": "^22.14.1",
22
- "@types/react": "^19.1.13",
23
- "@types/react-dom": "^19.1.9",
24
- "typescript": "^5.9.3"
21
+ "@types/node": "^26.4.1",
22
+ "@types/react": "^19.2.18",
23
+ "@types/react-dom": "^19.2.7",
24
+ "typescript": "5.9.3"
25
25
  }
26
26
  }
@@ -16,6 +16,6 @@
16
16
  "plugins": [{ "name": "next" }],
17
17
  "paths": { "@/*": ["./*"] }
18
18
  },
19
- "include": ["**/*.ts", "**/*.tsx"],
19
+ "include": ["**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
20
20
  "exclude": ["node_modules"]
21
21
  }
@@ -34,7 +34,6 @@
34
34
  "typecheck": "bun run --workspaces --if-present typecheck",
35
35
  "test": "bun run --workspaces --if-present test",
36
36
  "build": "bun run --workspaces --if-present build",
37
- "generate:check": "bun run --filter @__PRODUCT_SLUG__/api check:drift",
38
37
  "migrate": "bun apps/api/scripts/migrate.mjs"
39
38
  }
40
39
  }
@@ -14,10 +14,10 @@
14
14
  "typecheck": "tsc -p tsconfig.json --noEmit"
15
15
  },
16
16
  "dependencies": {
17
- "@ts-rest/core": "^3.52.1",
18
- "zod": "^3.25.76"
17
+ "@ts-rest/core": "3.52.1",
18
+ "zod": "3.25.76"
19
19
  },
20
20
  "devDependencies": {
21
- "typescript": "^5.9.3"
21
+ "typescript": "5.9.3"
22
22
  }
23
23
  }
@@ -1,5 +0,0 @@
1
- export declare const README_TITLE_CODEMOD = "set-api-readme-title";
2
- export declare function applyReadmeTitleCodemod(root: string, productName: string): {
3
- changed: boolean;
4
- path: string;
5
- };
@@ -1,21 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- const TARGET = path.join("apps", "api", "README.md");
4
- export const README_TITLE_CODEMOD = "set-api-readme-title";
5
- export function applyReadmeTitleCodemod(root, productName) {
6
- const file = path.join(root, TARGET);
7
- if (!existsSync(file))
8
- throw new Error("codemod_input_unsupported");
9
- const current = readFileSync(file, "utf8");
10
- const nextTitle = `# ${productName} API`;
11
- const lines = current.split("\n");
12
- if (lines[0] === nextTitle) {
13
- return { changed: false, path: TARGET };
14
- }
15
- if (!lines[0]?.startsWith("# ")) {
16
- throw new Error("codemod_input_unsupported");
17
- }
18
- lines[0] = nextTitle;
19
- writeFileSync(file, lines.join("\n"));
20
- return { changed: true, path: TARGET };
21
- }
package/dist/upgrade.d.ts DELETED
@@ -1,13 +0,0 @@
1
- export type UpgradeResult = {
2
- dryRun: boolean;
3
- changed: string[];
4
- conflicts: string[];
5
- restored?: string[];
6
- };
7
- export declare function upgradeProduct(input: {
8
- root: string;
9
- version?: string;
10
- dryRun?: boolean;
11
- allowDirty?: boolean;
12
- failAfterWrite?: boolean;
13
- }): UpgradeResult;
package/dist/upgrade.js DELETED
@@ -1,97 +0,0 @@
1
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { assertGitClean } from "./git.js";
4
- import { sha256File } from "./hash.js";
5
- import { readManifest, writeManifest } from "./manifest.js";
6
- export function upgradeProduct(input) {
7
- const root = path.resolve(input.root);
8
- if (!input.dryRun && !input.allowDirty) {
9
- assertGitClean(root);
10
- }
11
- const manifest = readManifest(root);
12
- const changed = [];
13
- const conflicts = [];
14
- const plannedWrites = new Map();
15
- const upgradeVersion = input.version ?? "1.1.0";
16
- // Compute and validate the complete plan before touching any file. A
17
- // managed hash mismatch is a conflict, not a best-effort warning.
18
- for (const [rel, expected] of Object.entries(manifest.managedFiles)) {
19
- const current = path.join(root, rel);
20
- if (!existsSync(current) || sha256File(current) !== expected) {
21
- conflicts.push(rel);
22
- continue;
23
- }
24
- // Managed files are not automatically source files. A version marker is
25
- // intentionally owned by the managed TypeScript config only; appending it
26
- // to every managed file corrupts assets such as GitHub Actions YAML.
27
- if (rel !== "tooling/platform/config.ts")
28
- continue;
29
- const currentText = readFileSync(current, "utf8");
30
- const marker = /export const platformTemplateVersion = "[^"]*";\n?/;
31
- const nextText = marker.test(currentText)
32
- ? currentText.replace(marker, `export const platformTemplateVersion = "${upgradeVersion}";\n`)
33
- : `${currentText.trimEnd()}\nexport const platformTemplateVersion = "${upgradeVersion}";\n`;
34
- if (nextText !== currentText) {
35
- plannedWrites.set(rel, nextText);
36
- changed.push(rel);
37
- }
38
- }
39
- const productName = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).name ?? "product";
40
- const readme = path.join(root, "apps/api/README.md");
41
- if (!existsSync(readme)) {
42
- throw new Error("codemod_input_unsupported");
43
- }
44
- const readmeText = readFileSync(readme, "utf8");
45
- const expectedTitle = `# ${String(productName)} API`;
46
- const readmeLines = readmeText.split("\n");
47
- if (!readmeLines[0]?.startsWith("# ")) {
48
- throw new Error("codemod_input_unsupported");
49
- }
50
- if (readmeLines[0] !== expectedTitle) {
51
- changed.push("apps/api/README.md");
52
- if (!input.dryRun) {
53
- readmeLines[0] = expectedTitle;
54
- plannedWrites.set("apps/api/README.md", readmeLines.join("\n"));
55
- }
56
- }
57
- // Never mutate anything if any managed file is conflicted. This also makes
58
- // the result deterministic for callers that use dry-run to gate a write.
59
- if (conflicts.length > 0) {
60
- return { dryRun: Boolean(input.dryRun), changed: [], conflicts };
61
- }
62
- if (input.dryRun) {
63
- return { dryRun: true, changed, conflicts };
64
- }
65
- const backups = new Map();
66
- const manifestPath = path.join(root, ".codelit-platform.json");
67
- backups.set(".codelit-platform.json", readFileSync(manifestPath, "utf8"));
68
- try {
69
- for (const [rel, content] of plannedWrites) {
70
- const file = path.join(root, rel);
71
- backups.set(rel, readFileSync(file, "utf8"));
72
- writeFileSync(file, content);
73
- if (rel in manifest.managedFiles) {
74
- manifest.managedFiles[rel] = sha256File(file);
75
- }
76
- }
77
- if (input.failAfterWrite)
78
- throw new Error("upgrade_forced_failure");
79
- if (!manifest.appliedUpgrades.includes(upgradeVersion)) {
80
- manifest.appliedUpgrades.push(upgradeVersion);
81
- }
82
- manifest.templateVersion = upgradeVersion;
83
- writeManifest(root, manifest);
84
- return { dryRun: false, changed, conflicts };
85
- }
86
- catch (error) {
87
- const restored = [];
88
- for (const [rel, content] of backups) {
89
- writeFileSync(path.join(root, rel), content);
90
- restored.push(rel);
91
- }
92
- const message = error instanceof Error ? error.message : String(error);
93
- throw new Error(`${message}; upgrade_rolled_back:${restored.join(",")}`, {
94
- cause: error,
95
- });
96
- }
97
- }
@@ -1,26 +0,0 @@
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
- }
@@ -1,2 +0,0 @@
1
- /** Managed by @codelitdev/platform-cli. Do not edit unless you accept upgrade conflicts. */
2
- export const platformHealthService = "__PRODUCT_SLUG__-api";