diff --git a/packages/cli/.gitignore b/packages/cli/.gitignore new file mode 100644 index 0000000..84f3869 --- /dev/null +++ b/packages/cli/.gitignore @@ -0,0 +1,3 @@ +dist +node_modules +*.tsbuildinfo diff --git a/packages/cli/README.md b/packages/cli/README.md new file mode 100644 index 0000000..0a37be3 --- /dev/null +++ b/packages/cli/README.md @@ -0,0 +1,143 @@ +# `@saas/cli` + +`new-test` — first-class TypeScript CLI for the new-test control +plane. Wraps `@saas/sdk` (the only transport allowed) and surfaces a +small set of read-only commands today; write commands land in Task 0101. + +## Install (workspace) + +This package is internal to the `new-test` monorepo and is not +published. Build the binary with: + +```sh +pnpm --filter @saas/cli build +node packages/cli/dist/cli.js --help +``` + +## Commands + +Auth (Task 0100): + +``` +new-test login [--api-url=URL] [--token=BEARER] +new-test logout +new-test whoami +``` + +Reads (Task 0100): + +``` +new-test org list +new-test org use +new-test org members +new-test project list +``` + +Writes (Task 0101): + +``` +new-test org invite [--role=ROLE] [--idempotency-key=KEY] [--org=ORG_ID] +new-test project create [--idempotency-key=KEY] +new-test env create [--idempotency-key=KEY] +new-test api-key create [--scope=SCOPE] [--idempotency-key=KEY] +new-test webhook create [--event=EVENT[,EVENT2,...]] [--idempotency-key=KEY] +``` + +Cross-resource reads (Task 0101): + +``` +new-test usage summary [--metric=METRIC] [--from=ISO] [--to=ISO] +new-test billing summary +new-test audit list [--limit=N] [--cursor=CURSOR] [--category=CAT] [--all] +``` + +All commands accept `--output=human|json`. JSON mode emits one document +per invocation; on error, `{ "error": { "code", "message", "requestId? } }`. + +### Exit codes (`src/errors.ts`) + +| Code | Meaning | +|------|---------| +| 0 | Success | +| 1 | Generic / unexpected error | +| 2 | Usage error (missing/invalid args or flags) | +| 3 | Not authenticated (no stored credential) | +| 4 | API error (4xx/5xx surfaced from the SDK) | +| 5 | No active organization context | +| 6 | Idempotency replay rejected by api-edge | + +### Idempotency + +`--idempotency-key=KEY` is forwarded **verbatim** to the API on every +write — Stripe parity. The CLI never auto-generates a key. When you omit +the flag, no `Idempotency-Key` header is sent and the api-edge worker +falls through without replay protection (still safe for read-after-write +flows; required for retry-safe writes). + +For `webhook create --event=A,B`, each child subscription gets a +deterministic suffixed key (`KEY:sub:0`, `KEY:sub:1`, …) so the whole +command remains retry-safe under partial failure. + +### Active organization + +Most write/cross-read commands resolve the org from the persisted +context (`new-test org use `). Only `org invite` accepts an +explicit `--org=ORG_ID` override; the others throw "no active +organization" (exit 5) when context is unset. + +### Audit pagination + +`audit list` without flags returns the first page; `--all` walks every +page until the server returns `cursor: null`. In `--all --output=json` +mode the CLI emits one JSON document per page (JSON Lines) so a +downstream pipeline can stream without buffering. + +## Auth + +The shipped V1 is **token-paste**: `new-test login` prompts for a +Bearer token, validates it via `client.organizations.list()`, and stores +it. Switching to a device-flow grant once api-edge ships +`/v1/auth/device/{start,poll}` is a one-line dispatch in +`src/auth/login.ts`. + +Token storage: +- `KeychainTokenStore` (preferred): macOS Keychain / Windows Credential + Vault / Secret Service via `keytar` (lazy import; in + `optionalDependencies`). +- `FileTokenStore` fallback: `~/.config/new-test/credentials.json`, + mode **0600**, parent directory mode **0700**. + +Active organization context lives at +`~/.config/new-test/config.json` (mode 0644, not a secret). Override +both via `NEW_TEST_CONFIG_DIR` (used by tests). + +## Output stability + +JSON output is deterministic given a deterministic SDK response. The CLI +adds **no** timestamps to JSON envelopes. `formatOutput()` is the only +emission path and is fully covered by tests. + +## Hazards / constraints + +- Zero hazards under `packages/cli/**`. The hazard set is the same as + the rest of the monorepo: disabled-eslint comments, ts-ignore, + ts-expect-error, and force-cast escape hatches via `as` chains. +- The package index (`src/index.ts`) is loadable in non-Node hosts; the + keychain adapter dynamic-imports `keytar` only when needed. +- Idempotency-Key is **caller-owned**. Task 0101 wires `--idempotency-key` + through to the SDK; the CLI never auto-mints a key. + +## Testing + +```sh +pnpm --filter @saas/cli typecheck +pnpm --filter @saas/cli lint +pnpm --filter @saas/cli test +pnpm --filter @saas/cli build +``` + +## Related + +- `specs/components/13-cli-and-sdk.md` — surface contract. +- `packages/sdk` — the only allowed transport. +- Task 0101 — write commands + remaining read-only fan-out. diff --git a/packages/cli/component.yaml b/packages/cli/component.yaml new file mode 100644 index 0000000..b8e1f7e --- /dev/null +++ b/packages/cli/component.yaml @@ -0,0 +1,29 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: cli + description: First-class TypeScript CLI for the new-test control plane API +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-cli + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: shared + surface: cli +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/cli/docs/architecture.md b/packages/cli/docs/architecture.md new file mode 100644 index 0000000..b23689f --- /dev/null +++ b/packages/cli/docs/architecture.md @@ -0,0 +1,9 @@ +# cli — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/cli`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/cli/docs/overview.md b/packages/cli/docs/overview.md new file mode 100644 index 0000000..ae3a34a --- /dev/null +++ b/packages/cli/docs/overview.md @@ -0,0 +1,13 @@ +# cli + +First-class TypeScript CLI for the new-test control plane API + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/cli/docs/runbook.md b/packages/cli/docs/runbook.md new file mode 100644 index 0000000..6b41225 --- /dev/null +++ b/packages/cli/docs/runbook.md @@ -0,0 +1,26 @@ +# cli — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/cli/eslint.config.js b/packages/cli/eslint.config.js new file mode 100644 index 0000000..d9d7c7a --- /dev/null +++ b/packages/cli/eslint.config.js @@ -0,0 +1,14 @@ +import baseConfig from "../../tooling/eslint/index.js"; + +export default [ + ...baseConfig, + { + files: ["src/**/*.ts"], + rules: { + // CLI prints to stdout/stderr — `console.log` is the legitimate output + // channel here. The base config warns on `console.log`; turn it off + // for this package only. + "no-console": "off", + }, + }, +]; diff --git a/packages/cli/package.json b/packages/cli/package.json new file mode 100644 index 0000000..560c119 --- /dev/null +++ b/packages/cli/package.json @@ -0,0 +1,33 @@ +{ + "name": "@saas/cli", + "version": "0.0.0", + "private": true, + "type": "module", + "bin": { + "new-test": "./dist/cli.js" + }, + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && node scripts/bundle.mjs", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "test": "vitest run" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/node": "^20.14.0", + "esbuild": "^0.25.4", + "typescript": "^5.8.3", + "vitest": "^2.1.9" + }, + "dependencies": { + "@saas/sdk": "workspace:*", + "@saas/webhook-verifier": "workspace:*" + }, + "optionalDependencies": { + "keytar": "^7.9.0" + } +} diff --git a/packages/cli/scripts/bundle.mjs b/packages/cli/scripts/bundle.mjs new file mode 100644 index 0000000..ad1caad --- /dev/null +++ b/packages/cli/scripts/bundle.mjs @@ -0,0 +1,40 @@ +#!/usr/bin/env node +// Bundles the CLI directly from TypeScript sources. tsc is reserved for +// type-checking + .d.ts emit; the runtime artifact is produced by esbuild +// so the binary can be executed by Node without resolving sibling +// workspaces (`@saas/sdk` exports raw `.ts`, which Node ESM cannot load +// without a bundler). +// +// Inputs : src/cli.ts +// Output : dist/cli.js (executable, with shebang) +// +// `keytar` is marked external so it remains an optional dependency +// dynamically imported by `token-store/keychain.ts`. + +import { build } from "esbuild"; +import { chmodSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const pkgRoot = resolve(here, ".."); +const entry = resolve(pkgRoot, "src/cli.ts"); +const out = resolve(pkgRoot, "dist/cli.js"); + +await build({ + entryPoints: [entry], + bundle: true, + platform: "node", + format: "esm", + target: "node20", + outfile: out, + external: ["keytar"], + // Source already has a shebang; do not re-emit one via banner. + legalComments: "none", + minify: false, + sourcemap: false, + logLevel: "warning", +}); + +chmodSync(out, 0o755); + diff --git a/packages/cli/src/__tests__/auth.test.ts b/packages/cli/src/__tests__/auth.test.ts new file mode 100644 index 0000000..1b62ab3 --- /dev/null +++ b/packages/cli/src/__tests__/auth.test.ts @@ -0,0 +1,197 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { newtest } from "@saas/sdk"; + +import { loginFlow } from "../auth/login.js"; +import { logoutFlow } from "../auth/logout.js"; +import { whoamiFlow } from "../auth/whoami.js"; +import { ContextStore } from "../context/store.js"; +import { MissingAuthError } from "../errors.js"; +import { captureFetch, envelope, jsonResponse, MemoryTokenStore } from "./helpers.js"; + +const ORG_LIST = envelope({ + organizations: [ + { id: "org_1", name: "Acme", slug: "acme", createdAt: "2025-01-01T00:00:00Z" }, + ], +}); + +describe("login (token-paste)", () => { + let dir: string; + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-auth-")); + }); + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + it("validates the token via SDK and persists", async () => { + const { fetch } = captureFetch(() => jsonResponse(ORG_LIST)); + const tokenStore = new MemoryTokenStore(); + const ctx = new ContextStore({ configDir: dir }); + const stdout: string[] = []; + + await loginFlow({ + apiUrl: "https://api.test", + token: "tok_paste", + outputMode: "json", + tokenStore, + contextStore: ctx, + readToken: async () => "should-not-be-called", + stdout: (line) => stdout.push(line), + sdkFactory: (baseUrl, token) => + new newtest({ baseUrl, auth: { kind: "bearer", token }, fetch }), + }); + + const cred = await tokenStore.load(); + expect(cred).toEqual({ apiUrl: "https://api.test", token: "tok_paste" }); + const cliCtx = await ctx.load(); + expect(cliCtx.lastApiUrl).toBe("https://api.test"); + expect(JSON.parse(stdout[0] ?? "")).toEqual({ + apiUrl: "https://api.test", + organizations: 1, + }); + }); + + it("rejects empty tokens", async () => { + const tokenStore = new MemoryTokenStore(); + const ctx = new ContextStore({ configDir: dir }); + await expect( + loginFlow({ + apiUrl: "https://api.test", + token: "", + outputMode: "human", + tokenStore, + contextStore: ctx, + readToken: async () => "", + stdout: () => undefined, + }), + ).rejects.toThrow(/token cannot be empty/); + }); + + it("rejects empty api-url", async () => { + const tokenStore = new MemoryTokenStore(); + const ctx = new ContextStore({ configDir: dir }); + await expect( + loginFlow({ + apiUrl: " ", + token: "tok", + outputMode: "human", + tokenStore, + contextStore: ctx, + readToken: async () => "tok", + stdout: () => undefined, + }), + ).rejects.toThrow(/api-url cannot be empty/); + }); + + it("propagates UnauthenticatedError on 401 (caller maps to friendly msg)", async () => { + const { fetch } = captureFetch(() => + jsonResponse( + { + error: { + code: "unauthenticated", + message: "bad token", + details: {}, + requestId: "req_x", + }, + }, + { status: 401 }, + ), + ); + const tokenStore = new MemoryTokenStore(); + const ctx = new ContextStore({ configDir: dir }); + await expect( + loginFlow({ + apiUrl: "https://api.test", + token: "tok_bad", + outputMode: "human", + tokenStore, + contextStore: ctx, + readToken: async () => "tok_bad", + stdout: () => undefined, + sdkFactory: (baseUrl, token) => + new newtest({ baseUrl, auth: { kind: "bearer", token }, fetch }), + }), + ).rejects.toMatchObject({ name: "UnauthenticatedError" }); + // Token should NOT have been persisted on auth failure. + expect(await tokenStore.load()).toBeNull(); + }); +}); + +describe("whoami", () => { + let dir: string; + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-who-")); + }); + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + it("throws MissingAuthError when no credential is stored", async () => { + const tokenStore = new MemoryTokenStore(); + const ctx = new ContextStore({ configDir: dir }); + await expect( + whoamiFlow({ + outputMode: "human", + tokenStore, + contextStore: ctx, + stdout: () => undefined, + }), + ).rejects.toBeInstanceOf(MissingAuthError); + }); + + it("emits identity + active org via SDK factory", async () => { + const tokenStore = new MemoryTokenStore({ + apiUrl: "https://api.test", + token: "tok", + }); + const ctx = new ContextStore({ configDir: dir }); + await ctx.setActiveOrg("org_1"); + + const { fetch } = captureFetch(() => jsonResponse(ORG_LIST)); + const stdout: string[] = []; + await whoamiFlow({ + outputMode: "json", + tokenStore, + contextStore: ctx, + stdout: (line) => stdout.push(line), + sdkFactory: (baseUrl, token) => + new newtest({ baseUrl, auth: { kind: "bearer", token }, fetch }), + }); + expect(JSON.parse(stdout[0] ?? "")).toEqual({ + apiUrl: "https://api.test", + activeOrgId: "org_1", + organizations: 1, + }); + }); +}); + +describe("logout", () => { + let dir: string; + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-logout-")); + }); + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + it("clears credentials and context", async () => { + const tokenStore = new MemoryTokenStore({ apiUrl: "u", token: "t" }); + const ctx = new ContextStore({ configDir: dir }); + await ctx.setActiveOrg("org_1"); + const stdout: string[] = []; + await logoutFlow({ + outputMode: "json", + tokenStore, + contextStore: ctx, + stdout: (line) => stdout.push(line), + }); + expect(await tokenStore.load()).toBeNull(); + expect(await ctx.load()).toEqual({}); + expect(JSON.parse(stdout[0] ?? "")).toEqual({ ok: true }); + }); +}); diff --git a/packages/cli/src/__tests__/cli.test.ts b/packages/cli/src/__tests__/cli.test.ts new file mode 100644 index 0000000..dae2ec8 --- /dev/null +++ b/packages/cli/src/__tests__/cli.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, it } from "vitest"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { CLI_VERSION } from "../version.js"; +import { MemoryTokenStore } from "./helpers.js"; + +interface CapturedOutput { + stdout: string[]; + stderr: string[]; +} + +function harness(): { + out: CapturedOutput; + stdout: (line: string) => void; + stderr: (line: string) => void; +} { + const out: CapturedOutput = { stdout: [], stderr: [] }; + return { + out, + stdout: (line) => out.stdout.push(line), + stderr: (line) => out.stderr.push(line), + }; +} + +describe("cli — argv routing", () => { + it("`--help` exits 0 and prints USAGE", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli(["--help"], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-help" }), + }); + expect(result.exitCode).toBe(0); + expect(out.stdout.join("\n")).toContain("USAGE:"); + expect(out.stdout.join("\n")).toContain("new-test org list"); + }); + + it("no argv prints help and exits 0", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli([], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-noargs" }), + }); + expect(result.exitCode).toBe(0); + expect(out.stdout.join("\n")).toContain("new-test v"); + }); + + it("`--version` (human) prints the version", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli(["--version"], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-v" }), + }); + expect(result.exitCode).toBe(0); + expect(out.stdout).toEqual([CLI_VERSION]); + }); + + it("`--version --output=json` emits a JSON document", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli(["--version", "--output=json"], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-vj" }), + }); + expect(result.exitCode).toBe(0); + expect(JSON.parse(out.stdout[0] ?? "")).toEqual({ version: CLI_VERSION }); + }); + + it("unknown command exits non-zero with a usage error", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli(["nope"], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-unknown" }), + }); + expect(result.exitCode).toBe(2); + expect(out.stderr.join("\n")).toMatch(/unknown command/); + }); + + it("unknown command in JSON mode emits an error envelope", async () => { + const { out, stdout, stderr } = harness(); + const result = await runCli(["nope", "--output=json"], { + stdout, + stderr, + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: "/tmp/cli-test-unknownj" }), + }); + expect(result.exitCode).toBe(2); + const parsed = JSON.parse(out.stderr[0] ?? ""); + expect(parsed).toEqual({ + error: { code: "usage", message: expect.stringContaining("unknown command") }, + }); + }); +}); diff --git a/packages/cli/src/__tests__/commands.test.ts b/packages/cli/src/__tests__/commands.test.ts new file mode 100644 index 0000000..17c6cbd --- /dev/null +++ b/packages/cli/src/__tests__/commands.test.ts @@ -0,0 +1,248 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { newtest } from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { captureFetch, envelope, jsonResponse, MemoryTokenStore } from "./helpers.js"; + +const ORG_LIST = envelope({ + organizations: [ + { id: "org_1", name: "Acme", slug: "acme", createdAt: "2025-01-01T00:00:00Z" }, + { id: "org_2", name: "Beta", slug: "beta", createdAt: "2025-02-01T00:00:00Z" }, + ], +}); + +const ORG_GET = envelope({ + organization: { + id: "org_1", + name: "Acme", + slug: "acme", + createdAt: "2025-01-01T00:00:00Z", + }, +}); + +const MEMBERS = envelope({ + members: [ + { + id: "mem_1", + subjectType: "user", + subjectId: "usr_a", + status: "active", + joinedAt: "2025-01-01T00:00:00Z", + roles: [{ role: "owner", scopeKind: "organization" }], + }, + ], +}); + +const PROJECTS = envelope({ + projects: [ + { + id: "prj_1", + orgId: "org_1", + name: "Web", + slug: "web", + status: "active", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-01-01T00:00:00Z", + archivedAt: null, + }, + ], +}); + +interface Cap { + stdout: string[]; + stderr: string[]; + fetchCalls: { url: string; init: RequestInit }[]; +} + +async function withHarness( + fn: (h: { + cap: Cap; + tokenStore: MemoryTokenStore; + contextStore: ContextStore; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + options: { + response: () => Response; + activeOrgId?: string; + storedCred?: { apiUrl: string; token: string }; + }, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-cmd-")); + try { + const cap: Cap = { stdout: [], stderr: [], fetchCalls: [] }; + const fetchHarness = captureFetch(options.response); + cap.fetchCalls = fetchHarness.calls; + const tokenStore = new MemoryTokenStore( + options.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + if (options.activeOrgId) await contextStore.setActiveOrg(options.activeOrgId); + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: (baseUrl, token) => + new newtest({ + baseUrl, + auth: { kind: "bearer", token }, + fetch: fetchHarness.fetch, + }), + }); + + await fn({ cap, tokenStore, contextStore, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +describe("commands — org list", () => { + it("hits /v1/organizations and prints a table (human)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "list"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]?.url).toBe("https://api.test/v1/organizations"); + const text = cap.stdout.join("\n"); + expect(text).toContain("Acme"); + expect(text).toContain("Beta"); + expect(text).toMatch(/active\s+id\s+name\s+slug/); + }, + { response: () => jsonResponse(ORG_LIST), activeOrgId: "org_1" }, + ); + }); + + it("emits stable JSON shape when --output=json", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "list", "--output=json"]); + expect(r.exitCode).toBe(0); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toEqual({ + activeOrgId: "org_2", + organizations: ORG_LIST.data.organizations, + }); + }, + { response: () => jsonResponse(ORG_LIST), activeOrgId: "org_2" }, + ); + }); +}); + +describe("commands — org use", () => { + it("validates the org via SDK then writes config.json", async () => { + await withHarness( + async ({ cap, contextStore, runArgv }) => { + const r = await runArgv(["org", "use", "org_1"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]?.url).toBe( + "https://api.test/v1/organizations/org_1", + ); + expect((await contextStore.load()).activeOrgId).toBe("org_1"); + }, + { response: () => jsonResponse(ORG_GET) }, + ); + }); + + it("missing arg → usage exit 2", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "use"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/usage/); + }, + { response: () => jsonResponse(ORG_GET) }, + ); + }); +}); + +describe("commands — org members", () => { + it("requires an active org context", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "members"]); + expect(r.exitCode).toBe(5); + expect(cap.stderr.join("\n")).toMatch(/no active organization/); + }, + { response: () => jsonResponse(MEMBERS) }, + ); + }); + + it("hits the org-scoped members path when context is set", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "members"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]?.url).toBe( + "https://api.test/v1/organizations/org_1/members", + ); + }, + { response: () => jsonResponse(MEMBERS), activeOrgId: "org_1" }, + ); + }); + + it("JSON mode round-trips the SDK response", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "members", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(JSON.parse(cap.stdout[0] ?? "")).toEqual(MEMBERS.data); + }, + { response: () => jsonResponse(MEMBERS), activeOrgId: "org_1" }, + ); + }); +}); + +describe("commands — project list", () => { + it("hits the org-scoped projects path", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["project", "list"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]?.url).toBe( + "https://api.test/v1/organizations/org_1/projects", + ); + expect(cap.stdout.join("\n")).toContain("Web"); + }, + { response: () => jsonResponse(PROJECTS), activeOrgId: "org_1" }, + ); + }); + + it("requires org context", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["project", "list"]); + expect(r.exitCode).toBe(5); + expect(cap.stderr.join("\n")).toMatch(/no active organization/); + }, + { response: () => jsonResponse(PROJECTS) }, + ); + }); +}); + +describe("commands — auth gating", () => { + it("returns exit 3 when no credential is stored", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-cmd-")); + try { + const stdout: string[] = []; + const stderr: string[] = []; + const r = await runCli(["org", "list"], { + stdout: (l) => stdout.push(l), + stderr: (l) => stderr.push(l), + tokenStore: new MemoryTokenStore(), + contextStore: new ContextStore({ configDir: dir }), + }); + expect(r.exitCode).toBe(3); + expect(stderr.join("\n")).toMatch(/not logged in/); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/__tests__/context.test.ts b/packages/cli/src/__tests__/context.test.ts new file mode 100644 index 0000000..d552128 --- /dev/null +++ b/packages/cli/src/__tests__/context.test.ts @@ -0,0 +1,67 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { ContextStore } from "../context/store.js"; +import { resolveConfigDir } from "../config-paths.js"; + +describe("ContextStore", () => { + let dir: string; + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-ctx-")); + }); + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + it("returns empty context when file is missing", async () => { + const ctx = new ContextStore({ configDir: dir }); + expect(await ctx.load()).toEqual({}); + }); + + it("setActiveOrg writes config.json", async () => { + const ctx = new ContextStore({ configDir: dir }); + await ctx.setActiveOrg("org_1"); + const loaded = await ctx.load(); + expect(loaded.activeOrgId).toBe("org_1"); + }); + + it("setLastApiUrl writes alongside other context fields", async () => { + const ctx = new ContextStore({ configDir: dir }); + await ctx.setActiveOrg("org_1"); + await ctx.setLastApiUrl("https://api.test"); + const loaded = await ctx.load(); + expect(loaded).toEqual({ activeOrgId: "org_1", lastApiUrl: "https://api.test" }); + }); + + it("clear() removes the file (idempotent)", async () => { + const ctx = new ContextStore({ configDir: dir }); + await ctx.setActiveOrg("org_x"); + await ctx.clear(); + expect(await ctx.load()).toEqual({}); + await ctx.clear(); + expect(await ctx.load()).toEqual({}); + }); + + it("ignores malformed JSON without throwing", async () => { + const ctx = new ContextStore({ configDir: dir }); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(path.join(dir, "config.json"), "not json"); + expect(await ctx.load()).toEqual({}); + }); +}); + +describe("resolveConfigDir", () => { + it("respects NEW_TEST_CONFIG_DIR override", () => { + const prev = process.env["NEW_TEST_CONFIG_DIR"]; + process.env["NEW_TEST_CONFIG_DIR"] = "/tmp/cli-override"; + try { + expect(resolveConfigDir()).toBe("/tmp/cli-override"); + } finally { + if (prev === undefined) delete process.env["NEW_TEST_CONFIG_DIR"]; + else process.env["NEW_TEST_CONFIG_DIR"] = prev; + } + }); +}); diff --git a/packages/cli/src/__tests__/helpers.test.ts b/packages/cli/src/__tests__/helpers.test.ts new file mode 100644 index 0000000..86048e0 --- /dev/null +++ b/packages/cli/src/__tests__/helpers.test.ts @@ -0,0 +1,161 @@ +// Tests for the shared CLI command helpers (Task 0111). +// +// These cover the byte-equivalent extraction of `resolveOrgId` (from +// `writes.ts`) and `readIdempotencyKey` (from both `writes.ts` and +// `webhook-secrets-rotate.ts`) into `commands/helpers.ts`. The +// helpers depend on `CommandContext.flags` and +// `CommandContext.contextStore.load()` only, so we build minimal +// fixtures rather than going through `runCli`. Black-box behavioural +// coverage of the full command pipeline already lives in +// `webhook-secrets-rotate.test.ts` and `writes-and-cross-reads.test.ts`; +// this file is the unit slice for the extracted module. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import type { CommandContext } from "../router.js"; +import { + resolveOrgId, + readIdempotencyKey, +} from "../commands/helpers.js"; +import { ContextStore } from "../context/store.js"; +import { MissingOrgContextError } from "../errors.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- minimal CommandContext fixture -------------------------------------- + +async function withCtx( + flags: Readonly>, + options: { activeOrgId?: string | null } = {}, + fn: (ctx: CommandContext) => Promise, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0111-")); + try { + const contextStore = new ContextStore({ configDir: dir }); + if ( + options.activeOrgId !== undefined && + options.activeOrgId !== null && + options.activeOrgId.length > 0 + ) { + await contextStore.setActiveOrg(options.activeOrgId); + } + const ctx: CommandContext = { + args: [], + flags, + outputMode: "human", + stdout: () => {}, + stderr: () => {}, + tokenStore: new MemoryTokenStore(), + contextStore, + sdk: () => { + throw new Error("sdk() should not be called by helpers under test"); + }, + }; + await fn(ctx); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- resolveOrgId -------------------------------------------------------- + +describe("resolveOrgId", () => { + it("returns the --org flag value when allowOverride=true and flag is non-empty", async () => { + await withCtx( + { org: "org_flag" }, + { activeOrgId: "org_persisted" }, + async (ctx) => { + const got = await resolveOrgId(ctx, true); + expect(got).toBe("org_flag"); + }, + ); + }); + + it("falls back to persisted activeOrgId when allowOverride=true and flag is absent", async () => { + await withCtx( + {}, + { activeOrgId: "org_persisted" }, + async (ctx) => { + const got = await resolveOrgId(ctx, true); + expect(got).toBe("org_persisted"); + }, + ); + }); + + it("ignores the --org flag and uses persisted activeOrgId when allowOverride=false", async () => { + await withCtx( + { org: "org_flag" }, + { activeOrgId: "org_persisted" }, + async (ctx) => { + const got = await resolveOrgId(ctx, false); + expect(got).toBe("org_persisted"); + }, + ); + }); + + it("throws MissingOrgContextError when neither flag (where applicable) nor activeOrgId is set", async () => { + // allowOverride=true with no flag and no persisted org. + await withCtx({}, {}, async (ctx) => { + await expect(resolveOrgId(ctx, true)).rejects.toBeInstanceOf( + MissingOrgContextError, + ); + }); + // allowOverride=false with a flag set but no persisted org — flag is + // ignored and the missing-context error must still fire. + await withCtx({ org: "org_flag" }, {}, async (ctx) => { + await expect(resolveOrgId(ctx, false)).rejects.toBeInstanceOf( + MissingOrgContextError, + ); + }); + }); + + it("falls back to persisted activeOrgId when allowOverride=true and the flag is an empty string", async () => { + await withCtx( + { org: "" }, + { activeOrgId: "org_persisted" }, + async (ctx) => { + const got = await resolveOrgId(ctx, true); + expect(got).toBe("org_persisted"); + }, + ); + }); + + it("treats a boolean true --org flag (bare --org with no value) as absent and falls back to persisted activeOrgId", async () => { + await withCtx( + { org: true }, + { activeOrgId: "org_persisted" }, + async (ctx) => { + const got = await resolveOrgId(ctx, true); + expect(got).toBe("org_persisted"); + }, + ); + }); +}); + +// ---- readIdempotencyKey -------------------------------------------------- + +describe("readIdempotencyKey", () => { + it("returns the flag value verbatim when it is a non-empty string", async () => { + await withCtx({ "idempotency-key": "abc-123" }, {}, async (ctx) => { + expect(readIdempotencyKey(ctx)).toBe("abc-123"); + }); + }); + + it("returns undefined when the flag is missing, false, true, or an empty string", async () => { + await withCtx({}, {}, async (ctx) => { + expect(readIdempotencyKey(ctx)).toBeUndefined(); + }); + await withCtx({ "idempotency-key": false }, {}, async (ctx) => { + expect(readIdempotencyKey(ctx)).toBeUndefined(); + }); + await withCtx({ "idempotency-key": true }, {}, async (ctx) => { + expect(readIdempotencyKey(ctx)).toBeUndefined(); + }); + await withCtx({ "idempotency-key": "" }, {}, async (ctx) => { + expect(readIdempotencyKey(ctx)).toBeUndefined(); + }); + }); +}); diff --git a/packages/cli/src/__tests__/helpers.ts b/packages/cli/src/__tests__/helpers.ts new file mode 100644 index 0000000..46b492a --- /dev/null +++ b/packages/cli/src/__tests__/helpers.ts @@ -0,0 +1,57 @@ +// Test helpers: in-memory token store + context store + fake SDK. + +import type { newtest } from "@saas/sdk"; + +import type { StoredCredential, TokenStore } from "../token-store/types.js"; + +export class MemoryTokenStore implements TokenStore { + readonly kind = "memory" as const; + private cred: StoredCredential | null = null; + + constructor(initial?: StoredCredential) { + this.cred = initial ?? null; + } + + async load(): Promise { + return this.cred; + } + async save(cred: StoredCredential): Promise { + this.cred = cred; + } + async clear(): Promise { + this.cred = null; + } +} + +export interface CapturedFetchCall { + readonly url: string; + readonly init: RequestInit; +} + +export function captureFetch(responseFactory: () => Response): { + fetch: typeof fetch; + calls: CapturedFetchCall[]; +} { + const calls: CapturedFetchCall[] = []; + const fn: typeof fetch = async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + return responseFactory().clone(); + }; + return { fetch: fn, calls }; +} + +export function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { "content-type": "application/json", ...(init.headers ?? {}) }, + }); +} + +export function envelope(data: T, requestId = "req_test"): { + data: T; + meta: { requestId: string; cursor: null }; +} { + return { data, meta: { requestId, cursor: null } }; +} + +export type newtestFactory = (baseUrl: string, token: string) => newtest; diff --git a/packages/cli/src/__tests__/notification-preferences.test.ts b/packages/cli/src/__tests__/notification-preferences.test.ts new file mode 100644 index 0000000..5536624 --- /dev/null +++ b/packages/cli/src/__tests__/notification-preferences.test.ts @@ -0,0 +1,185 @@ +// Tests for PX3 — `new-test notifications preferences [set]`. +// +// Same fake-SDK injection harness as security-events.test.ts: the commands +// are thin adapters over `sdk.notifications.getPreferences/updatePreferences` +// (+ `sdk.auth.getProfile` for the subject id on `set`), so SDK-layer fakes +// let us assert call shapes without modelling the wire envelope. +// +// Scope note: org context is required (resolveOrgId with --org override); +// subject scope is the bearer's actor — the facade pins it server-side, and +// `set` resolves `subjectId` from the profile to send an honest request. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { newtest, NotificationPreference } from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +function pref(categories: NotificationPreference["categories"]): NotificationPreference { + return { + subjectKind: "user", + subjectId: "usr_me", + orgId: "org_1", + channel: "email", + categories, + updatedAt: "2026-06-11T00:00:00.000Z", + }; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + getCalls: unknown[]; + updateCalls: unknown[]; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: { stored?: NotificationPreference[] } = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-px3-")); + try { + const cap: Cap = { stdout: [], stderr: [], getCalls: [], updateCalls: [] }; + const tokenStore = new MemoryTokenStore({ apiUrl: "https://api.test", token: "tok" }); + const contextStore = new ContextStore({ configDir: dir }); + + const getPreferences = vi.fn(async (q: unknown) => { + cap.getCalls.push(q); + return { preferences: opts.stored ?? [] }; + }); + const updatePreferences = vi.fn(async (body: { categories: NotificationPreference["categories"] }) => { + cap.updateCalls.push(body); + return { preference: pref(body.categories) }; + }); + const getProfile = vi.fn(async () => ({ + user: { id: "usr_me", email: "me@test.com", displayName: null }, + })); + + const fakeSdk = { + notifications: { getPreferences, updatePreferences }, + auth: { getProfile }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +describe("commands — notifications preferences", () => { + it("get: defaults every category to enabled when no row exists", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["notifications", "preferences", "--org", "org_1"]); + expect(r.exitCode).toBe(0); + expect(cap.getCalls[0]).toEqual({ orgId: "org_1" }); + const out = cap.stdout.join("\n"); + for (const c of ["invitation", "billing", "security", "support", "product"]) { + expect(out).toContain(c); + } + expect(out).not.toContain("false"); + }); + }); + + it("get --output=json: emits effective category map honoring stored false", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "notifications", + "preferences", + "--org", + "org_1", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + const doc = JSON.parse(cap.stdout.join("\n")) as { + categories: Record; + }; + expect(doc.categories.billing).toBe(false); + expect(doc.categories.product).toBe(true); + }, + { stored: [pref({ billing: false, product: null })] }, + ); + }); + + it("set: flips one category, keeps the rest explicit, subject from profile", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "notifications", + "preferences", + "set", + "--org", + "org_1", + "--category=product", + "--enabled=false", + ]); + expect(r.exitCode).toBe(0); + expect(cap.updateCalls).toHaveLength(1); + expect(cap.updateCalls[0]).toEqual({ + orgId: "org_1", + subjectKind: "user", + subjectId: "usr_me", + channel: "email", + categories: { + invitation: true, + billing: false, + security: true, + support: true, + product: false, + }, + }); + }, + { stored: [pref({ billing: false })] }, + ); + }); + + it("set: rejects an unknown category with a usage error (exit 2)", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "notifications", + "preferences", + "set", + "--org", + "org_1", + "--category=spam", + "--enabled=false", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toContain("--category"); + }); + }); + + it("set: rejects a non-boolean --enabled with a usage error (exit 2)", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "notifications", + "preferences", + "set", + "--org", + "org_1", + "--category=billing", + "--enabled=maybe", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toContain("--enabled"); + }); + }); +}); diff --git a/packages/cli/src/__tests__/output.test.ts b/packages/cli/src/__tests__/output.test.ts new file mode 100644 index 0000000..b770015 --- /dev/null +++ b/packages/cli/src/__tests__/output.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; + +import { formatErrorJson, formatOutput, parseOutputMode } from "../output/index.js"; + +describe("output — parseOutputMode", () => { + it("defaults to human", () => { + expect(parseOutputMode(undefined)).toBe("human"); + expect(parseOutputMode(true)).toBe("human"); + expect(parseOutputMode("human")).toBe("human"); + }); + it("recognises json", () => { + expect(parseOutputMode("json")).toBe("json"); + }); +}); + +describe("output — JSON mode shape", () => { + it("emits the data field verbatim", () => { + const out = formatOutput({ mode: "json", data: { hello: "world" } }); + expect(JSON.parse(out)).toEqual({ hello: "world" }); + }); + + it("wraps rows under `items` when no data override is given", () => { + const out = formatOutput({ + mode: "json", + columns: ["id", "name"], + rows: [{ id: "x", name: "y" }], + }); + expect(JSON.parse(out)).toEqual({ items: [{ id: "x", name: "y" }] }); + }); + + it("emits a record verbatim", () => { + const out = formatOutput({ mode: "json", record: { a: "1", b: "2" } }); + expect(JSON.parse(out)).toEqual({ a: "1", b: "2" }); + }); + + it("error envelope shape", () => { + const s = formatErrorJson({ + code: "validation_failed", + message: "boom", + requestId: "req_abc", + }); + expect(JSON.parse(s)).toEqual({ + error: { code: "validation_failed", message: "boom", requestId: "req_abc" }, + }); + }); + + it("error envelope omits requestId when absent", () => { + const s = formatErrorJson({ code: "x", message: "y" }); + expect(JSON.parse(s)).toEqual({ error: { code: "x", message: "y" } }); + }); +}); + +describe("output — human mode shape", () => { + it("renders a table with header + separator + rows", () => { + const out = formatOutput({ + mode: "human", + columns: ["id", "name"], + rows: [ + { id: "1", name: "alpha" }, + { id: "20", name: "b" }, + ], + }); + const lines = out.split("\n"); + expect(lines[0]).toMatch(/^id\s+name\s*$/); + expect(lines[1]).toMatch(/^-+\s+-+\s*$/); + expect(lines[2]).toMatch(/^1\s+alpha\s*$/); + expect(lines[3]).toMatch(/^20\s+b\s*$/); + }); + + it("renders an empty list as `(no rows)`", () => { + const out = formatOutput({ mode: "human", columns: ["id"], rows: [] }); + expect(out).toContain("(no rows)"); + }); + + it("renders a record as key:value lines, padded", () => { + const out = formatOutput({ + mode: "human", + record: { apiUrl: "https://api.test", organizations: "3" }, + }); + expect(out).toContain("apiUrl"); + expect(out).toContain("organizations"); + expect(out).toContain(":"); + expect(out).toContain("https://api.test"); + }); + + it("renders an empty record as (empty)", () => { + const out = formatOutput({ mode: "human", record: {} }); + expect(out).toBe("(empty)"); + }); + + it("supports an optional title above the body", () => { + const out = formatOutput({ + mode: "human", + title: "Members of org_1", + columns: ["id"], + rows: [{ id: "m_1" }], + }); + expect(out.startsWith("Members of org_1")).toBe(true); + }); +}); diff --git a/packages/cli/src/__tests__/security-events.test.ts b/packages/cli/src/__tests__/security-events.test.ts new file mode 100644 index 0000000..e2728c3 --- /dev/null +++ b/packages/cli/src/__tests__/security-events.test.ts @@ -0,0 +1,318 @@ +// Tests for Task 0122 — `new-test security events` CLI subcommand. +// +// The harness injects a *fake SDK* via `sdkFactory` rather than going through +// the real `newtest` client + a captured-fetch — the command is a thin +// adapter over `sdk.securityEvents.listPage`, so direct SDK-layer injection +// lets us assert the call shape (query) and the cursor-following loop without +// modelling the request envelope. The fake mirrors only the subset of the SDK +// the command touches. +// +// Actor-scope note: this surface is account/actor-scoped, NOT org-scoped — the +// command takes no `` positional and never calls `resolveOrgId`. The +// page method is therefore called with `(query)` only. +// +// Cursor provenance note: `listPage` returns `{ securityEvents, nextCursor }` +// where `nextCursor` is the opaque token the worker emits in `meta.cursor`. +// The command forwards it verbatim; these tests assert that round-trip +// (default-mode title cursor, --all loop following, JSON `next_cursor` field) +// and never construct or parse the token. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + newtest, + PublicSecurityEvent, + SecurityEventsPage, +} from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +function event(over: Partial = {}): PublicSecurityEvent { + return { + id: "se_1", + eventType: "session.created", + outcome: "success", + occurredAt: "2026-01-16T10:00:00.000Z", + requestId: "req_1", + correlationId: null, + ip: "203.0.113.7", + userAgent: "Mozilla/5.0", + metadata: {}, + ...over, + }; +} + +// ---- harness -------------------------------------------------------------- + +interface PageCall { + query: unknown; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + pageCalls: PageCall[]; +} + +interface HarnessOpts { + /** + * Sequence of pages the fake `listPage` returns, one per call. When the + * calls outrun the array, the last entry is reused — but a well-formed test + * supplies a terminating page (`nextCursor: null`). + */ + pages?: SecurityEventsPage[]; + /** Force the page mock to reject. */ + rejectWith?: Error; + /** Stored credential. Pass `null` to simulate logged-out state. */ + storedCred?: { apiUrl: string; token: string } | null; +} + +const SINGLE_PAGE: SecurityEventsPage = { + securityEvents: [event()], + nextCursor: null, +}; + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0122-")); + try { + const cap: Cap = { stdout: [], stderr: [], pageCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + + const pages = opts.pages ?? [SINGLE_PAGE]; + let callIndex = 0; + const listPage = vi.fn( + async (queryArg: unknown = {}): Promise => { + cap.pageCalls.push({ query: queryArg }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + const page = pages[Math.min(callIndex, pages.length - 1)]; + callIndex += 1; + return page ?? SINGLE_PAGE; + }, + ); + + const fakeSdk = { + securityEvents: { listPage }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — security events", () => { + // 1. Happy path human mode; single page, no query flags. + it("human mode → exit 0; table with the event; SDK called with {}", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Security events"); + expect(out).toContain("session.created"); + expect(out).toContain("success"); + expect(out).toContain("se_1"); + expect(cap.pageCalls).toHaveLength(1); + expect(cap.pageCalls[0]).toEqual({ query: {} }); + }); + }); + + // 2. Happy path JSON mode → { securityEvents, next_cursor }. + it("json mode → single-line JSON with securityEvents + next_cursor", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(1); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toHaveProperty("securityEvents"); + expect(parsed.securityEvents[0]).toHaveProperty("id", "se_1"); + expect(parsed).toHaveProperty("next_cursor", null); + }); + }); + + // 3. --limit forwarded into the query. + it("--limit=10 → query { limit: 10 }", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", "--limit=10"]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls[0]).toEqual({ query: { limit: 10 } }); + }); + }); + + // 4. --cursor forwarded verbatim (opaque, never parsed). + it("--cursor=OPAQUE → query { cursor: OPAQUE } verbatim", async () => { + const opaque = "eyJjcm...2In0="; + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", `--cursor=${opaque}`]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls[0]).toEqual({ query: { cursor: opaque } }); + }); + }); + + // 5. Default mode surfaces the next cursor in the human title when present. + it("non-null nextCursor → title advertises the next cursor", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain("(next cursor: CUR_NEXT)"); + }, + { + pages: [{ securityEvents: [event()], nextCursor: "CUR_NEXT" }], + }, + ); + }); + + // 6. --all follows the server cursor across pages until null. + it("--all → follows cursor across pages; second call carries the prior cursor", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", "--all"]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls).toHaveLength(2); + // First page: no cursor. Second page: the server-issued CUR_NEXT. + expect(cap.pageCalls[0]).toEqual({ query: {} }); + expect(cap.pageCalls[1]).toEqual({ query: { cursor: "CUR_NEXT" } }); + const out = cap.stdout.join("\n"); + expect(out).toContain("All security events"); + expect(out).toContain("se_a"); + expect(out).toContain("se_b"); + }, + { + pages: [ + { securityEvents: [event({ id: "se_a" })], nextCursor: "CUR_NEXT" }, + { securityEvents: [event({ id: "se_b" })], nextCursor: null }, + ], + }, + ); + }); + + // 7. --all JSON mode emits one JSON document per page (JSON Lines). + it("--all --output=json → one JSON doc per page", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "security", + "events", + "--all", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(2); + const first = JSON.parse(cap.stdout[0] ?? ""); + const second = JSON.parse(cap.stdout[1] ?? ""); + expect(first).toHaveProperty("next_cursor", "CUR_NEXT"); + expect(second).toHaveProperty("next_cursor", null); + }, + { + pages: [ + { securityEvents: [event({ id: "se_a" })], nextCursor: "CUR_NEXT" }, + { securityEvents: [event({ id: "se_b" })], nextCursor: null }, + ], + }, + ); + }); + + // 8. --all + --cursor → UsageError, exit 2; no SDK call. + it("--all + --cursor → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "security", + "events", + "--all", + "--cursor=X", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch( + /--all and --cursor are mutually exclusive/, + ); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 9. --limit non-positive → UsageError, exit 2; no SDK call. + it("--limit=0 → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", "--limit=0"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--limit must be a positive integer/); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 10. --output=yaml (invalid) → UsageError, exit 2; no SDK call. + it("--output=yaml → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events", "--output=yaml"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output must be human or json/); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 11. SDK rejection propagates non-zero; reached the SDK once. + it("SDK rejection → non-zero exit; error path clean", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events"]); + expect(r.exitCode).not.toBe(0); + expect(cap.pageCalls).toHaveLength(1); + }, + { rejectWith: new Error("server exploded") }, + ); + }); + + // 12. Logged-out state → non-zero exit; no SDK call. + it("no stored credential → non-zero exit; no SDK call made", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["security", "events"]); + expect(r.exitCode).not.toBe(0); + expect(cap.pageCalls).toHaveLength(0); + }, + { storedCred: null }, + ); + }); + + // 13. Help output advertises the security events subcommand. + it("top-level help lists the security events usage line", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["--help"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain( + "new-test security events [--limit=N] [--cursor=CURSOR] [--all] [--output=human|json]", + ); + }); + }); +}); diff --git a/packages/cli/src/__tests__/token-store.test.ts b/packages/cli/src/__tests__/token-store.test.ts new file mode 100644 index 0000000..26c3510 --- /dev/null +++ b/packages/cli/src/__tests__/token-store.test.ts @@ -0,0 +1,127 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +import { FileTokenStore } from "../token-store/file.js"; +import { KeychainTokenStore } from "../token-store/keychain.js"; +import { selectTokenStore } from "../token-store/select.js"; + +interface KeytarShim { + setPassword: (s: string, a: string, p: string) => Promise; + getPassword: (s: string, a: string) => Promise; + deletePassword: (s: string, a: string) => Promise; +} + +function makeShim(): KeytarShim & { store: Map } { + const store = new Map(); + return { + store, + async setPassword(s, a, p) { + store.set(`${s}::${a}`, p); + }, + async getPassword(s, a) { + return store.get(`${s}::${a}`) ?? null; + }, + async deletePassword(s, a) { + return store.delete(`${s}::${a}`); + }, + }; +} + +describe("FileTokenStore", () => { + let dir: string; + + beforeEach(async () => { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-token-")); + }); + afterEach(async () => { + await fs.rm(dir, { recursive: true, force: true }); + }); + + it("returns null when file is missing", async () => { + const store = new FileTokenStore({ configDir: dir }); + expect(await store.load()).toBeNull(); + }); + + it("round-trips a credential", async () => { + const store = new FileTokenStore({ configDir: dir }); + await store.save({ apiUrl: "https://api.test", token: "tok_x" }); + const loaded = await store.load(); + expect(loaded).toEqual({ apiUrl: "https://api.test", token: "tok_x" }); + }); + + it("creates the credentials file with mode 0600 on POSIX", async () => { + if (process.platform === "win32") return; + const store = new FileTokenStore({ configDir: dir }); + await store.save({ apiUrl: "https://api.test", token: "tok" }); + const stat = await fs.stat(store.filePath); + expect(stat.mode & 0o777).toBe(0o600); + }); + + it("creates the parent directory with mode 0700 on POSIX", async () => { + if (process.platform === "win32") return; + const nested = path.join(dir, "new-test"); + const store = new FileTokenStore({ configDir: nested }); + await store.save({ apiUrl: "https://api.test", token: "tok" }); + const stat = await fs.stat(nested); + expect(stat.mode & 0o777).toBe(0o700); + }); + + it("clear() removes the file (idempotent)", async () => { + const store = new FileTokenStore({ configDir: dir }); + await store.save({ apiUrl: "u", token: "t" }); + await store.clear(); + expect(await store.load()).toBeNull(); + await store.clear(); + expect(await store.load()).toBeNull(); + }); + + it("returns null on malformed JSON", async () => { + const store = new FileTokenStore({ configDir: dir }); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(store.filePath, "not json", { mode: 0o600 }); + expect(await store.load()).toBeNull(); + }); +}); + +describe("KeychainTokenStore (DI shim)", () => { + it("round-trips via the injected shim", async () => { + const shim = makeShim(); + const store = new KeychainTokenStore({ keytar: shim }); + await store.save({ apiUrl: "https://api.test", token: "tok" }); + expect(shim.store.size).toBe(1); + const loaded = await store.load(); + expect(loaded).toEqual({ apiUrl: "https://api.test", token: "tok" }); + await store.clear(); + expect(await store.load()).toBeNull(); + }); + + it("returns null for non-JSON keychain values", async () => { + const shim = makeShim(); + shim.store.set("new-test-cli::default", "garbage"); + const store = new KeychainTokenStore({ keytar: shim }); + expect(await store.load()).toBeNull(); + }); +}); + +describe("selectTokenStore", () => { + it("force=keychain with a shim selects keychain", async () => { + const shim = makeShim(); + const store = await selectTokenStore({ keytar: shim }); + expect(store.kind).toBe("keychain"); + }); + + it("force=file selects the file store", async () => { + const tmp = await fs.mkdtemp(path.join(os.tmpdir(), "cli-sel-")); + try { + const store = await selectTokenStore({ force: "file", configDir: tmp }); + expect(store.kind).toBe("file"); + await store.save({ apiUrl: "u", token: "t" }); + expect(await store.load()).toEqual({ apiUrl: "u", token: "t" }); + } finally { + await fs.rm(tmp, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/__tests__/webhook-deliveries-replay.test.ts b/packages/cli/src/__tests__/webhook-deliveries-replay.test.ts new file mode 100644 index 0000000..11b2cc1 --- /dev/null +++ b/packages/cli/src/__tests__/webhook-deliveries-replay.test.ts @@ -0,0 +1,229 @@ +// Tests for Task 0126 — `new-test webhook deliveries replay` CLI subcommand. +// +// Mirrors the Task 0120 `webhook deliveries` harness: a *fake SDK* is injected +// via `sdkFactory` so we assert the call shape (orgId, attemptId) and the +// rendered output without modelling the request envelope. The command is a thin +// one-call adapter over `sdk.webhooks.replayDelivery`. +// +// Router note: `webhook deliveries replay` is a longer registered path than +// `webhook deliveries`, so the longest-prefix resolver routes the three-token +// argv to the replay command (the first positional `` is NOT +// swallowed as the `deliveries` endpointId). + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + newtest, + PublicWebhookDeliveryAttempt, + ReplayWebhookDeliveryResponse, +} from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +function attempt( + over: Partial = {}, +): PublicWebhookDeliveryAttempt { + return { + id: "whd_new", + orgId: "org_1", + endpointId: "whe_abc", + subscriptionId: "whs_1", + eventId: "evt_1", + eventType: "user.created", + status: "success", + attemptNumber: 1, + httpStatusCode: 200, + failureReason: null, + idempotencyKey: "whs_1:evt_1:replay:whd_new", + nextRetryAt: null, + completedAt: "2026-02-01T10:00:00.000Z", + createdAt: "2026-02-01T09:59:59.000Z", + updatedAt: "2026-02-01T10:00:00.000Z", + ...over, + }; +} + +// ---- harness -------------------------------------------------------------- + +interface ReplayCall { + orgId: string; + attemptId: string; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + replayCalls: ReplayCall[]; +} + +interface HarnessOpts { + response?: ReplayWebhookDeliveryResponse; + rejectWith?: Error; + activeOrgId?: string | null; + storedCred?: { apiUrl: string; token: string } | null; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0126-")); + try { + const cap: Cap = { stdout: [], stderr: [], replayCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + const orgId = + opts.activeOrgId === null ? undefined : (opts.activeOrgId ?? "org_1"); + if (orgId !== undefined) await contextStore.setActiveOrg(orgId); + + const response: ReplayWebhookDeliveryResponse = opts.response ?? { + deliveryAttempt: attempt(), + }; + const replayDelivery = vi.fn( + async ( + orgArg: string, + attemptArg: string, + ): Promise => { + cap.replayCalls.push({ orgId: orgArg, attemptId: attemptArg }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + return response; + }, + ); + + const fakeSdk = { + webhooks: { replayDelivery }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — webhook deliveries replay", () => { + // 1. Happy path human mode — routes to replay, prints the new attempt row. + it("replays an attempt and renders the new attempt in human mode", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "replay", "whd_old"]); + expect(r.exitCode).toBe(0); + expect(cap.replayCalls).toEqual([{ orgId: "org_1", attemptId: "whd_old" }]); + const out = cap.stdout.join("\n"); + expect(out).toContain("whd_new"); + expect(out).toContain("success"); + }); + }); + + // 2. JSON mode emits the raw { deliveryAttempt } object. + it("emits the deliveryAttempt object in JSON mode", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "replay", + "whd_old", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + const parsed = JSON.parse(cap.stdout.join("\n")); + expect(parsed.deliveryAttempt.id).toBe("whd_new"); + expect(parsed.deliveryAttempt.attemptNumber).toBe(1); + }); + }); + + // 3. Missing positional → UsageError (exit 2), no SDK call. + it("errors with usage when attemptId is missing", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "replay"]); + expect(r.exitCode).toBe(2); + expect(cap.replayCalls).toHaveLength(0); + expect(cap.stderr.join("\n")).toMatch( + /usage: new-test webhook deliveries replay/, + ); + }); + }); + + // 4. Invalid --output → UsageError (exit 2), no SDK call. + it("rejects an invalid --output value", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "replay", + "whd_old", + "--output=yaml", + ]); + expect(r.exitCode).toBe(2); + expect(cap.replayCalls).toHaveLength(0); + }); + }); + + // 5. SDK error (e.g. 404) is propagated as a non-zero exit. + it("propagates an SDK error as a non-zero exit", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "replay", "whd_x"]); + expect(r.exitCode).not.toBe(0); + expect(cap.replayCalls).toHaveLength(1); + }, + { rejectWith: new Error("not_found") }, + ); + }); + + // 6. A failed-status replay still renders (terminal failed outcome). + it("renders a failed replay outcome", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "replay", "whd_old"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain("failed"); + }, + { + response: { + deliveryAttempt: attempt({ + status: "failed", + httpStatusCode: 500, + failureReason: "http_500", + }), + }, + }, + ); + }); + + // 7. Help output advertises the replay subcommand. + it("top-level help lists the webhook deliveries replay usage line", async () => { + await withHarness(async ({ cap, runArgv }) => { + await runArgv(["--help"]); + expect(cap.stdout.join("\n")).toContain( + "new-test webhook deliveries replay [--idempotency-key=KEY] [--output=human|json]", + ); + }); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-deliveries.test.ts b/packages/cli/src/__tests__/webhook-deliveries.test.ts new file mode 100644 index 0000000..517a983 --- /dev/null +++ b/packages/cli/src/__tests__/webhook-deliveries.test.ts @@ -0,0 +1,392 @@ +// Tests for Task 0120 — `new-test webhook deliveries` CLI subcommand. +// +// The harness injects a *fake SDK* via `sdkFactory` rather than going through +// the real `newtest` client + a captured-fetch — the command is a thin +// adapter over `sdk.webhooks.listDeliveryAttemptsPage`, so direct SDK-layer +// injection lets us assert the call shape (orgId, endpointId, query) and the +// cursor-following loop without modelling the request envelope. The fake +// mirrors only the subset of the SDK the command touches. +// +// Cursor provenance note: the page method returns `{ deliveryAttempts, +// nextCursor }` where `nextCursor` is the opaque token the worker emits in +// `meta.cursor`. The command forwards it verbatim; these tests assert that +// round-trip (default-mode title cursor, --all loop following, JSON +// `next_cursor` field) and never construct or parse the token. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + newtest, + PublicWebhookDeliveryAttempt, + DeliveryAttemptsPage, +} from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +function attempt( + over: Partial = {}, +): PublicWebhookDeliveryAttempt { + return { + id: "att_1", + orgId: "org_1", + endpointId: "wh_abc", + subscriptionId: "sub_1", + eventId: "evt_1", + eventType: "user.created", + status: "success", + attemptNumber: 1, + httpStatusCode: 200, + failureReason: null, + idempotencyKey: null, + nextRetryAt: null, + completedAt: "2026-01-16T10:00:00.000Z", + createdAt: "2026-01-16T09:59:59.000Z", + updatedAt: "2026-01-16T10:00:00.000Z", + ...over, + }; +} + +// ---- harness -------------------------------------------------------------- + +interface PageCall { + orgId: string; + endpointId: string; + query: unknown; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + pageCalls: PageCall[]; +} + +interface HarnessOpts { + /** + * Sequence of pages the fake `listDeliveryAttemptsPage` returns, one per + * call. When the calls outrun the array, the last entry is reused — but a + * well-formed test supplies a terminating page (`nextCursor: null`). + */ + pages?: DeliveryAttemptsPage[]; + /** Force the page mock to reject. */ + rejectWith?: Error; + /** Active org id to seed in the context store (default org_1). */ + activeOrgId?: string | null; + /** Stored credential. Pass `null` to simulate logged-out state. */ + storedCred?: { apiUrl: string; token: string } | null; +} + +const SINGLE_PAGE: DeliveryAttemptsPage = { + deliveryAttempts: [attempt()], + nextCursor: null, +}; + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0120-")); + try { + const cap: Cap = { stdout: [], stderr: [], pageCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + const orgId = + opts.activeOrgId === null ? undefined : (opts.activeOrgId ?? "org_1"); + if (orgId !== undefined) await contextStore.setActiveOrg(orgId); + + const pages = opts.pages ?? [SINGLE_PAGE]; + let callIndex = 0; + const listDeliveryAttemptsPage = vi.fn( + async ( + orgArg: string, + endpointArg: string, + queryArg: unknown = {}, + ): Promise => { + cap.pageCalls.push({ + orgId: orgArg, + endpointId: endpointArg, + query: queryArg, + }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + const page = pages[Math.min(callIndex, pages.length - 1)]; + callIndex += 1; + return page ?? SINGLE_PAGE; + }, + ); + + const fakeSdk = { + webhooks: { listDeliveryAttemptsPage }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — webhook deliveries", () => { + // 1. Happy path human mode; single page, no query flags. + it("human mode → exit 0; table with the attempt; SDK called (orgId, endpointId, {})", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Delivery attempts for wh_abc in org_1"); + expect(out).toContain("user.created"); + expect(out).toContain("success"); + expect(out).toContain("att_1"); + expect(cap.pageCalls).toHaveLength(1); + expect(cap.pageCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + query: {}, + }); + }); + }); + + // 2. Happy path JSON mode → { deliveryAttempts, next_cursor }. + it("json mode → single-line JSON with deliveryAttempts + next_cursor", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(1); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toHaveProperty("deliveryAttempts"); + expect(parsed.deliveryAttempts[0]).toHaveProperty("id", "att_1"); + expect(parsed).toHaveProperty("next_cursor", null); + }); + }); + + // 3. --limit forwarded into the query. + it("--limit=10 → query { limit: 10 }", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + "--limit=10", + ]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + query: { limit: 10 }, + }); + }); + }); + + // 4. --cursor forwarded verbatim (opaque, never parsed). + it("--cursor=OPAQUE → query { cursor: OPAQUE } verbatim", async () => { + const opaque = "eyJjcmVhdGVkQXQiOiIyMDI2In0="; + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + `--cursor=${opaque}`, + ]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + query: { cursor: opaque }, + }); + }); + }); + + // 5. Default mode surfaces the next cursor in the human title when present. + it("non-null nextCursor → title advertises the next cursor", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain("(next cursor: CUR_NEXT)"); + }, + { + pages: [{ deliveryAttempts: [attempt()], nextCursor: "CUR_NEXT" }], + }, + ); + }); + + // 6. --all follows the server cursor across pages until null. + it("--all → follows cursor across pages; second call carries the prior cursor", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc", "--all"]); + expect(r.exitCode).toBe(0); + expect(cap.pageCalls).toHaveLength(2); + // First page: no cursor. Second page: the server-issued CUR_NEXT. + expect(cap.pageCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + query: {}, + }); + expect(cap.pageCalls[1]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + query: { cursor: "CUR_NEXT" }, + }); + const out = cap.stdout.join("\n"); + expect(out).toContain("All delivery attempts for wh_abc in org_1"); + expect(out).toContain("att_a"); + expect(out).toContain("att_b"); + }, + { + pages: [ + { deliveryAttempts: [attempt({ id: "att_a" })], nextCursor: "CUR_NEXT" }, + { deliveryAttempts: [attempt({ id: "att_b" })], nextCursor: null }, + ], + }, + ); + }); + + // 7. --all JSON mode emits one JSON document per page (JSON Lines). + it("--all --output=json → one JSON doc per page", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + "--all", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(2); + const first = JSON.parse(cap.stdout[0] ?? ""); + const second = JSON.parse(cap.stdout[1] ?? ""); + expect(first).toHaveProperty("next_cursor", "CUR_NEXT"); + expect(second).toHaveProperty("next_cursor", null); + }, + { + pages: [ + { deliveryAttempts: [attempt({ id: "att_a" })], nextCursor: "CUR_NEXT" }, + { deliveryAttempts: [attempt({ id: "att_b" })], nextCursor: null }, + ], + }, + ); + }); + + // 8. --all together with --cursor → UsageError, exit 2; no SDK call. + it("--all + --cursor → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + "--all", + "--cursor=X", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch( + /--all and --cursor are mutually exclusive/, + ); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 9. --limit non-positive → UsageError, exit 2; no SDK call. + it("--limit=0 → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc", "--limit=0"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--limit must be a positive integer/); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 10. Missing positional → UsageError, exit 2; no SDK call. + it("missing → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch( + /usage: new-test webhook deliveries/, + ); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 11. --output=yaml (invalid) → UsageError, exit 2; no SDK call. + it("--output=yaml → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "deliveries", + "wh_abc", + "--output=yaml", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output must be human or json/); + expect(cap.pageCalls).toHaveLength(0); + }); + }); + + // 12. SDK rejection propagates non-zero; reached the SDK once. + it("SDK rejection → non-zero exit; error path clean", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + expect(cap.pageCalls).toHaveLength(1); + }, + { rejectWith: new Error("server exploded") }, + ); + }); + + // 13. No active org context → propagates; no SDK call. + it("no active org → non-zero exit; no SDK call made", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "deliveries", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + expect(cap.pageCalls).toHaveLength(0); + }, + { activeOrgId: null }, + ); + }); + + // 14. Help output advertises the deliveries subcommand. + it("top-level help lists the webhook deliveries usage line", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["--help"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain( + "new-test webhook deliveries [--limit=N] [--cursor=CURSOR] [--all] [--output=human|json]", + ); + }); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-disable.test.ts b/packages/cli/src/__tests__/webhook-disable.test.ts new file mode 100644 index 0000000..aa35a2b --- /dev/null +++ b/packages/cli/src/__tests__/webhook-disable.test.ts @@ -0,0 +1,316 @@ +// Tests for Task 0115 — `new-test webhook disable` CLI subcommand. +// +// The harness injects a *fake SDK* via `sdkFactory` rather than going +// through the real `newtest` client + a captured-fetch — the +// command is a thin one-call adapter over `sdk.webhooks.disableEndpoint`, +// so direct SDK-layer injection lets us assert the call shape (orgId, +// endpointId, body, options) without modelling the request envelope. +// The fake mirrors only the subset of the SDK the command touches. +// +// Unlike the enable test (Task 0114), `DisableWebhookEndpointResponse` +// IS re-exported from `@saas/sdk`'s package index, so we import it +// directly and avoid local shape reconstruction. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + newtest, + PublicWebhookEndpoint, + DisableWebhookEndpointResponse, +} from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +const FIXTURE_ENDPOINT: PublicWebhookEndpoint = { + id: "wh_abc", + orgId: "org_1", + projectId: null, + url: "https://example.com/hook", + name: null, + description: null, + status: "disabled", + disabledReason: "ops cleanup", + disabledAt: "2025-06-15T12:34:56Z", + secretVersion: 7, + secretLastRotatedAt: "2025-06-01T00:00:00Z", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-06-15T12:34:56Z", +}; + +const RESPONSE: DisableWebhookEndpointResponse = { endpoint: FIXTURE_ENDPOINT }; + +// ---- harness -------------------------------------------------------------- + +interface DisableCall { + orgId: string; + endpointId: string; + body: unknown; + opts: Record; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + disableCalls: DisableCall[]; +} + +interface HarnessOpts { + /** Controls what the fake `sdk.webhooks.disableEndpoint` returns. */ + response?: DisableWebhookEndpointResponse; + /** Force the disableEndpoint mock to reject. */ + rejectWith?: Error; + /** Active org id to seed in the context store (default org_1). */ + activeOrgId?: string | null; + /** Stored credential. Pass `null` to simulate logged-out state. */ + storedCred?: { apiUrl: string; token: string } | null; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0115-")); + try { + const cap: Cap = { stdout: [], stderr: [], disableCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + const orgId = + opts.activeOrgId === null ? undefined : (opts.activeOrgId ?? "org_1"); + if (orgId !== undefined) await contextStore.setActiveOrg(orgId); + + const disableEndpoint = vi.fn( + async ( + orgArg: string, + endpointArg: string, + bodyArg: unknown = {}, + callOpts: Record = {}, + ): Promise => { + cap.disableCalls.push({ + orgId: orgArg, + endpointId: endpointArg, + body: bodyArg, + opts: callOpts, + }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + return opts.response ?? RESPONSE; + }, + ); + + const fakeSdk = { + webhooks: { disableEndpoint }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — webhook disable", () => { + // 1. Happy path human mode; default body `{}`. + it("human mode → exit 0; header + 4-line status block; SDK called (orgId, endpointId, {}, {})", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "disable", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Webhook endpoint disabled: wh_abc in org_1"); + expect(out).toContain("status: disabled"); + expect(out).toContain("disabledReason: ops cleanup"); + expect(out).toContain("disabledAt: 2025-06-15T12:34:56Z"); + expect(out).toContain("updatedAt: 2025-06-15T12:34:56Z"); + expect(cap.disableCalls).toHaveLength(1); + expect(cap.disableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: {}, + }); + }); + }); + + // 2. Happy path JSON mode. + it("json mode → single-line JSON with endpoint key; SDK called as above", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "disable", + "wh_abc", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(1); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toHaveProperty("endpoint"); + expect(parsed.endpoint).toHaveProperty("id", "wh_abc"); + expect(parsed.endpoint).toHaveProperty("status", "disabled"); + expect(cap.disableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: {}, + }); + }); + }); + + // 3. --reason=TEXT forwarded into body verbatim. + it("--reason=\"ops cleanup\" → body { reason: \"ops cleanup\" }", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "disable", + "wh_abc", + "--reason=ops cleanup", + ]); + expect(r.exitCode).toBe(0); + expect(cap.disableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: { reason: "ops cleanup" }, + opts: {}, + }); + }); + }); + + // 4. --idempotency-key passthrough. + it("--idempotency-key=key-123 forwarded verbatim to opts", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "disable", + "wh_abc", + "--idempotency-key=key-123", + ]); + expect(r.exitCode).toBe(0); + expect(cap.disableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: { idempotencyKey: "key-123" }, + }); + }); + }); + + // 5. Reason + idempotency key together. + it("--reason + --idempotency-key together: both forwarded to respective args", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "disable", + "wh_abc", + "--reason=stale endpoint", + "--idempotency-key=key-xyz", + ]); + expect(r.exitCode).toBe(0); + expect(cap.disableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: { reason: "stale endpoint" }, + opts: { idempotencyKey: "key-xyz" }, + }); + }); + }); + + // 6. Missing positional → UsageError, exit 2. + it("missing → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "disable"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch( + /usage: new-test webhook disable/, + ); + expect(cap.disableCalls).toHaveLength(0); + }); + }); + + // 7. --output=yaml (invalid) → UsageError, exit 2. + it("--output=yaml → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "disable", + "wh_abc", + "--output=yaml", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output must be human or json/); + expect(cap.disableCalls).toHaveLength(0); + }); + }); + + // 8. Bare --reason (no value) → UsageError, exit 2. + it("bare --reason (no value) → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "disable", "wh_abc", "--reason"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--reason requires a value/); + expect(cap.disableCalls).toHaveLength(0); + }); + }); + + // 9. SDK rejection propagates non-zero; response not leaked into stderr. + it("SDK rejection → non-zero exit; error path clean", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "disable", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + // The SDK was reached (orgId resolved, one call made) before rejecting. + expect(cap.disableCalls).toHaveLength(1); + // No stray endpoint payload echoed onto stdout on the error branch. + expect(cap.stdout.join("\n")).not.toContain("disabled:"); + }, + { rejectWith: new Error("server exploded") }, + ); + }); + + // 10. No active org context → propagates; no SDK call. + it("no active org → non-zero exit; no SDK call made", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "disable", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + expect(cap.disableCalls).toHaveLength(0); + }, + { activeOrgId: null }, + ); + }); + + // 11 (extra). Help output advertises the disable subcommand. + it("top-level help lists the webhook disable usage line", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["--help"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain( + "new-test webhook disable [--reason=TEXT] [--idempotency-key=KEY] [--output=human|json]", + ); + }); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-enable.test.ts b/packages/cli/src/__tests__/webhook-enable.test.ts new file mode 100644 index 0000000..da950a9 --- /dev/null +++ b/packages/cli/src/__tests__/webhook-enable.test.ts @@ -0,0 +1,279 @@ +// Tests for Task 0114 — `new-test webhook enable` CLI subcommand. +// +// The harness injects a *fake SDK* via `sdkFactory` rather than going +// through the real `newtest` client + a captured-fetch — the +// command is a thin one-call adapter over `sdk.webhooks.enableEndpoint`, +// so direct SDK-layer injection lets us assert the call shape (orgId, +// endpointId, body, options) without modelling the request envelope. +// The fake mirrors only the subset of the SDK the command touches. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { + newtest, + PublicWebhookEndpoint, + EnableWebhookEndpointResponse, +} from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +const FIXTURE_ENDPOINT: PublicWebhookEndpoint = { + id: "wh_abc", + orgId: "org_1", + projectId: null, + url: "https://example.com/hook", + name: null, + description: null, + status: "active", + disabledReason: null, + disabledAt: null, + secretVersion: 7, + secretLastRotatedAt: "2025-06-01T00:00:00Z", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-06-15T12:34:56Z", +}; + +const RESPONSE: EnableWebhookEndpointResponse = { endpoint: FIXTURE_ENDPOINT }; + +// ---- harness -------------------------------------------------------------- + +interface EnableCall { + orgId: string; + endpointId: string; + body: unknown; + opts: Record; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + enableCalls: EnableCall[]; +} + +interface HarnessOpts { + /** Controls what the fake `sdk.webhooks.enableEndpoint` returns. */ + response?: EnableWebhookEndpointResponse; + /** Force the enableEndpoint mock to reject. */ + rejectWith?: Error; + /** Active org id to seed in the context store (default org_1). */ + activeOrgId?: string | null; + /** Stored credential. Pass `null` to simulate logged-out state. */ + storedCred?: { apiUrl: string; token: string } | null; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0114-")); + try { + const cap: Cap = { stdout: [], stderr: [], enableCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + const orgId = + opts.activeOrgId === null ? undefined : (opts.activeOrgId ?? "org_1"); + if (orgId !== undefined) await contextStore.setActiveOrg(orgId); + + const enableEndpoint = vi.fn( + async ( + orgArg: string, + endpointArg: string, + bodyArg: unknown = {}, + callOpts: Record = {}, + ): Promise => { + cap.enableCalls.push({ + orgId: orgArg, + endpointId: endpointArg, + body: bodyArg, + opts: callOpts, + }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + return opts.response ?? RESPONSE; + }, + ); + + const fakeSdk = { + webhooks: { enableEndpoint }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — webhook enable", () => { + // 1. Happy path human mode. + it("human mode → exit 0; header + status block; SDK called (orgId, endpointId, {}, {})", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "enable", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Webhook endpoint re-enabled: wh_abc in org_1"); + expect(out).toContain("status: active"); + expect(out).toContain("secretVersion: 7"); + expect(out).toContain("updatedAt: 2025-06-15T12:34:56Z"); + expect(cap.enableCalls).toHaveLength(1); + expect(cap.enableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: {}, + }); + }); + }); + + // 2. Happy path JSON mode. + it("json mode → single-line JSON with endpoint key; SDK called as above", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "enable", + "wh_abc", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(1); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toHaveProperty("endpoint"); + expect(parsed.endpoint).toHaveProperty("id", "wh_abc"); + expect(parsed.endpoint).toHaveProperty("status", "active"); + expect(cap.enableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: {}, + }); + }); + }); + + // 3. Idempotency-key passthrough (and no-key shape). + it("--idempotency-key=key-123 forwarded verbatim; no flag → {}", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r1 = await runArgv([ + "webhook", + "enable", + "wh_abc", + "--idempotency-key=key-123", + ]); + expect(r1.exitCode).toBe(0); + expect(cap.enableCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: { idempotencyKey: "key-123" }, + }); + + const r2 = await runArgv(["webhook", "enable", "wh_abc"]); + expect(r2.exitCode).toBe(0); + expect(cap.enableCalls[1]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + body: {}, + opts: {}, + }); + }); + }); + + // 4. Missing positional → UsageError, exit 2. + it("missing → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "enable"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/usage: new-test webhook enable/); + expect(cap.enableCalls).toHaveLength(0); + }); + }); + + // 5. --output=yaml (invalid) → UsageError, exit 2. + it("--output=yaml → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "enable", + "wh_abc", + "--output=yaml", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output must be human or json/); + expect(cap.enableCalls).toHaveLength(0); + }); + }); + + // 6. --output (boolean true / no value) → UsageError, exit 2. + it("--output with no value → usage exit 2; no SDK call", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "enable", "wh_abc", "--output"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output requires human\|json/); + expect(cap.enableCalls).toHaveLength(0); + }); + }); + + // 7. SDK rejection propagates non-zero; response not leaked into stderr. + it("SDK rejection → non-zero exit; error path clean", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "enable", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + // The SDK was reached (orgId resolved, one call made) before rejecting. + expect(cap.enableCalls).toHaveLength(1); + // No stray endpoint payload echoed onto stdout on the error branch. + expect(cap.stdout.join("\n")).not.toContain("re-enabled"); + }, + { rejectWith: new Error("server exploded") }, + ); + }); + + // 8. No active org context → propagates; no SDK call. + it("no active org → non-zero exit; no SDK call made", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "enable", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + expect(cap.enableCalls).toHaveLength(0); + }, + { activeOrgId: null }, + ); + }); + + // 9 (extra). Help output advertises the enable subcommand. + it("top-level help lists the webhook enable usage line", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["--help"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain( + "new-test webhook enable [--idempotency-key=KEY] [--output=human|json]", + ); + }); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-secrets-rotate.test.ts b/packages/cli/src/__tests__/webhook-secrets-rotate.test.ts new file mode 100644 index 0000000..016e5bc --- /dev/null +++ b/packages/cli/src/__tests__/webhook-secrets-rotate.test.ts @@ -0,0 +1,361 @@ +// Tests for Task 0110 — `new-test webhook secrets rotate` CLI subcommand. +// +// The harness injects a *fake SDK* via `sdkFactory` rather than going +// through the real `newtest` client + a captured-fetch — the +// command is a thin one-call adapter over `sdk.webhooks.rotateSecret`, +// so direct SDK-layer injection lets us assert the call shape (orgId, +// endpointId, options) without modelling the request envelope. The +// fake mirrors only the subset of the SDK the command touches. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { newtest, RotateWebhookSecretResponse } from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; + +// ---- fixtures ------------------------------------------------------------- + +const FIXTURE_ENDPOINT = { + id: "wh_abc", + orgId: "org_1", + projectId: null, + url: "https://example.com/hook", + name: null, + description: null, + status: "active" as const, + disabledReason: null, + disabledAt: null, + secretVersion: 7, + secretLastRotatedAt: "2025-06-01T00:00:00Z", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-06-01T00:00:00Z", +}; + +// 32 hex chars after `whsec_`, matching the contract surface. +const FIXTURE_SECRET_PLAINTEXT = "whsec_0123456789abcdef0123456789abcdef"; + +const RESPONSE_WITH_SECRET: RotateWebhookSecretResponse = { + endpoint: FIXTURE_ENDPOINT, + secret: FIXTURE_SECRET_PLAINTEXT, + previousSecretExpiresAt: "2025-06-02T00:00:00Z", + gracePeriodSeconds: 86400, +}; + +const RESPONSE_WITHOUT_SECRET: RotateWebhookSecretResponse = { + endpoint: FIXTURE_ENDPOINT, + previousSecretExpiresAt: "2025-06-02T00:00:00Z", + gracePeriodSeconds: 86400, +}; + +// ---- harness -------------------------------------------------------------- + +interface RotateCall { + orgId: string; + endpointId: string; + opts: Record; +} + +interface Cap { + stdout: string[]; + stderr: string[]; + rotateCalls: RotateCall[]; +} + +interface HarnessOpts { + /** Controls what the fake `sdk.webhooks.rotateSecret` returns. */ + response?: RotateWebhookSecretResponse; + /** Force the rotateSecret mock to reject. */ + rejectWith?: Error; + /** Active org id to seed in the context store (default org_1). */ + activeOrgId?: string | null; + /** Stored credential. Pass `null` to simulate logged-out state. */ + storedCred?: { apiUrl: string; token: string } | null; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + opts: HarnessOpts = {}, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0110-")); + try { + const cap: Cap = { stdout: [], stderr: [], rotateCalls: [] }; + + const tokenStore = + opts.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + opts.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + const orgId = + opts.activeOrgId === null + ? undefined + : (opts.activeOrgId ?? "org_1"); + if (orgId !== undefined) await contextStore.setActiveOrg(orgId); + + const rotateSecret = vi.fn( + async ( + orgArg: string, + endpointArg: string, + callOpts: Record = {}, + ): Promise => { + cap.rotateCalls.push({ + orgId: orgArg, + endpointId: endpointArg, + opts: callOpts, + }); + if (opts.rejectWith !== undefined) throw opts.rejectWith; + return opts.response ?? RESPONSE_WITH_SECRET; + }, + ); + + const fakeSdk = { + webhooks: { rotateSecret }, + } as unknown as newtest; + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: () => fakeSdk, + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- tests ---------------------------------------------------------------- + +describe("commands — webhook secrets rotate", () => { + // 1. Happy path human mode, secret present. + it("human mode with secret → exit 0; header + reveal-once warning + literal whsec_<32hex>", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Webhook signing secret rotated for wh_abc in org_1"); + expect(out).toContain(FIXTURE_SECRET_PLAINTEXT); + expect(out).toContain("This secret will not be shown again"); + expect(out).toContain("X-Webhook-Signature-Previous"); + expect(out).toContain("secretVersion: 7"); + expect(out).toContain("gracePeriod: 86400s"); + }); + }); + + // 2. Happy path JSON mode, secret present. + it("json mode with secret → single-line JSON with all four contract keys", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "secrets", + "rotate", + "wh_abc", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toHaveLength(1); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed).toHaveProperty("endpoint"); + expect(parsed).toHaveProperty("secret", FIXTURE_SECRET_PLAINTEXT); + expect(parsed).toHaveProperty( + "previousSecretExpiresAt", + "2025-06-02T00:00:00Z", + ); + expect(parsed).toHaveProperty("gracePeriodSeconds", 86400); + }); + }); + + // 3. Legacy no-key path human mode (no `secret` field). + it("human mode without secret → no-key warning, no whsec_ in stdout", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("Plaintext was not returned by the server"); + expect(out).not.toContain("whsec_"); + }, + { response: RESPONSE_WITHOUT_SECRET }, + ); + }); + + // 4. Legacy no-key path JSON mode. + it("json mode without secret → no `secret` key, no whsec_ in stdout", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "secrets", + "rotate", + "wh_abc", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect( + Object.prototype.hasOwnProperty.call(parsed, "secret"), + ).toBe(false); + expect(cap.stdout.join("\n")).not.toContain("whsec_"); + }, + { response: RESPONSE_WITHOUT_SECRET }, + ); + }); + + // 5. previousSecretExpiresAt: null renders as "(none)". + it("human mode renders previousSecretExpiresAt: null as (none)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain("previousExpires: (none)"); + }, + { + response: { + ...RESPONSE_WITH_SECRET, + previousSecretExpiresAt: null, + }, + }, + ); + }); + + // 6. previousSecretExpiresAt: ISO string renders verbatim. + it("human mode renders previousSecretExpiresAt ISO verbatim", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain( + "previousExpires: 2099-12-31T23:59:59Z", + ); + }, + { + response: { + ...RESPONSE_WITH_SECRET, + previousSecretExpiresAt: "2099-12-31T23:59:59Z", + }, + }, + ); + }); + + // 7. gracePeriodSeconds: 0 renders as "0s" (not "(none)"). + it("human mode renders gracePeriodSeconds 0 as 0s (not collapsed)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + const out = cap.stdout.join("\n"); + expect(out).toContain("gracePeriod: 0s"); + expect(out).not.toContain("gracePeriod: (none)"); + }, + { + response: { + ...RESPONSE_WITH_SECRET, + gracePeriodSeconds: 0, + }, + }, + ); + }); + + // 8. Missing positional → UsageError, exit 2. + it("missing → usage exit 2", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/usage/); + expect(cap.rotateCalls).toHaveLength(0); + }); + }); + + // 9. --output=invalid → UsageError, exit 2. + it("--output=invalid → usage exit 2", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "secrets", + "rotate", + "wh_abc", + "--output=yaml", + ]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output/); + expect(cap.rotateCalls).toHaveLength(0); + }); + }); + + // 10. Idempotency-key passthrough (and no-key shape). + it("--idempotency-key=foo passes { idempotencyKey: 'foo' }; no flag → {}", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r1 = await runArgv([ + "webhook", + "secrets", + "rotate", + "wh_abc", + "--idempotency-key=foo", + ]); + expect(r1.exitCode).toBe(0); + expect(cap.rotateCalls[0]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + opts: { idempotencyKey: "foo" }, + }); + + const r2 = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r2.exitCode).toBe(0); + expect(cap.rotateCalls[1]).toEqual({ + orgId: "org_1", + endpointId: "wh_abc", + opts: {}, + }); + }); + }); + + // 11. SDK error propagates; no whsec_ in stderr/stdout. + it("SDK rejection propagates non-zero exit; no whsec_ leaked", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).not.toBe(0); + const all = cap.stdout.concat(cap.stderr).join("\n"); + expect(all).not.toContain("whsec_"); + }, + { rejectWith: new Error("server exploded") }, + ); + }); + + // 12. Reveal-once stdout discipline — exactly one whsec_ in stdout. + it("human mode prints whsec_ exactly once (reveal-once discipline)", async () => { + await withHarness(async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(0); + const stdout = cap.stdout.join("\n"); + const matches = stdout.match(/whsec_/g); + expect(matches?.length).toBe(1); + }); + }); + + // 13 (extra). Missing org context → exit 5. + it("no active org → exit 5", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["webhook", "secrets", "rotate", "wh_abc"]); + expect(r.exitCode).toBe(5); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + expect(cap.rotateCalls).toHaveLength(0); + }, + { activeOrgId: null }, + ); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-sign.test.ts b/packages/cli/src/__tests__/webhook-sign.test.ts new file mode 100644 index 0000000..d069192 --- /dev/null +++ b/packages/cli/src/__tests__/webhook-sign.test.ts @@ -0,0 +1,352 @@ +// Tests for Task 0107 — `new-test webhook sign` CLI subcommand. +// +// Symmetric to webhook-verify.test.ts (Task 0106). The command is pure +// local crypto: no SDK, no network, no auth. We exercise it through +// `runCli` with a synthetic stdin and a `MemoryTokenStore` carrying NO +// credentials, proving the command is usable on a fresh install with +// no `new-test login`. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { signWebhookPayload, verifyWebhookSignature } from "@saas/webhook-verifier"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; +import type { StdinLike } from "../commands/webhook-sign.js"; + +// ---- harness -------------------------------------------------------------- + +interface Cap { + stdout: string[]; + stderr: string[]; +} + +interface RunOpts { + argv: string[]; + stdinBody?: Uint8Array | string | null; + stdinIsTTY?: boolean; +} + +function makeStdin( + body: Uint8Array | string | null, + isTTY?: boolean, +): StdinLike { + const chunks: Uint8Array[] = []; + if (body !== null) { + chunks.push(typeof body === "string" ? new TextEncoder().encode(body) : body); + } + const isTTYResolved = isTTY ?? body === null; + return Object.assign( + { + async *[Symbol.asyncIterator]() { + for (const c of chunks) yield c; + }, + }, + { isTTY: isTTYResolved }, + ) as StdinLike; +} + +async function withHarness( + fn: (h: { + cap: Cap; + run: (opts: RunOpts) => Promise<{ exitCode: number }>; + }) => Promise, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0107-")); + try { + const cap: Cap = { stdout: [], stderr: [] }; + const tokenStore = new MemoryTokenStore(); + const contextStore = new ContextStore({ configDir: dir }); + + const run = (opts: RunOpts): Promise<{ exitCode: number }> => + runCli(opts.argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + webhookSign: { + stdin: makeStdin(opts.stdinBody ?? null, opts.stdinIsTTY), + }, + }); + + await fn({ cap, run }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- happy paths ---------------------------------------------------------- + +describe("webhook sign — happy paths", () => { + it("human mode: STDIN body + valid timestamp → exit 0, prints sig+ts", async () => { + await withHarness(async ({ cap, run }) => { + const body = `{"event":"project.created","id":"prj_1"}`; + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=supersecret", + "--timestamp=1700000000", + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(0); + expect(cap.stderr).toEqual([]); + expect(cap.stdout.length).toBe(2); + // Single render = two `stdout()` lines; the runner appends \n + // between them when joined for the regex assertion the task + // requires. + const rendered = `${cap.stdout.join("\n")}\n`; + expect(rendered).toMatch(/^signature: sha256=[0-9a-f]{64}\ntimestamp: \d+\n$/); + expect(cap.stdout[1]).toBe("timestamp: 1700000000"); + }); + }); + + it("json mode: single-line valid JSON with signature + timestamp", async () => { + await withHarness(async ({ cap, run }) => { + const body = `{"event":"project.created"}`; + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s1", + "--timestamp=1700000000", + "--output=json", + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(0); + expect(cap.stdout.length).toBe(1); + const parsed = JSON.parse(cap.stdout[0] as string) as { + signature: string; + timestamp: string; + }; + expect(typeof parsed.signature).toBe("string"); + expect(parsed.signature).toMatch(/^sha256=[0-9a-f]{64}$/); + expect(parsed.timestamp).toBe("1700000000"); + }); + }); + + it("--body=PATH reads file bytes binary-safe (no trim)", async () => { + await withHarness(async ({ cap, run }) => { + // Body intentionally has leading + trailing whitespace and a final + // newline. The CLI MUST NOT `.trim()`. + const body = " {\"event\":\"x\"} \n"; + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-sign-body-")); + const filePath = path.join(dir, "body.json"); + await fs.writeFile(filePath, body); + try { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s2", + "--timestamp=1700000000", + `--body=${filePath}`, + ], + stdinBody: null, // no STDIN piped (TTY) + }); + expect(r.exitCode).toBe(0); + // Helper-computed expected signature for the *exact* bytes. + const expected = await signWebhookPayload({ + secret: "s2", + body, + timestamp: "1700000000", + }); + expect(cap.stdout[0]).toBe(`signature: ${expected}`); + expect(cap.stdout[1]).toBe("timestamp: 1700000000"); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + }); +}); + +// ---- argument errors → exit 2 -------------------------------------------- + +describe("webhook sign — argument errors (exit 2)", () => { + it("--body=PATH and STDIN both → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-sign-bodyerr-")); + const filePath = path.join(dir, "body.json"); + await fs.writeFile(filePath, "x"); + try { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s", + "--timestamp=1700000000", + `--body=${filePath}`, + ], + stdinBody: "y", + stdinIsTTY: false, + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/mutually exclusive|--body.*STDIN/i); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + }); + + it("missing body (no flag, no STDIN) → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s", + "--timestamp=1700000000", + ], + stdinBody: null, // TTY → no STDIN piped, no --body flag + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--body=PATH or pipe/i); + }); + }); + + it("missing --secret → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: ["webhook", "sign", "--timestamp=1700000000"], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--secret/); + }); + }); + + it("missing --timestamp → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: ["webhook", "sign", "--secret=s"], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--timestamp/); + }); + }); + + it("--timestamp=abc (non-integer) → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s", + "--timestamp=abc", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--timestamp/); + }); + }); + + it("--timestamp=-5 (negative) → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s", + "--timestamp=-5", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--timestamp/); + }); + }); + + it("--output=invalid → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=s", + "--timestamp=1700000000", + "--output=yaml", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--output/); + }); + }); +}); + +// ---- multi-byte + round-trip --------------------------------------------- + +describe("webhook sign — multi-byte + round-trip", () => { + it("multi-byte UTF-8 body bytes signed with deterministic helper-equivalent value", async () => { + await withHarness(async ({ cap, run }) => { + // Compose body via Buffer.from to guarantee byte exactness. + const bodyBytes = Buffer.from("héllo 漢字", "utf8"); + const r = await run({ + argv: [ + "webhook", + "sign", + "--secret=supersecret", + "--timestamp=1700000000", + ], + stdinBody: new Uint8Array(bodyBytes), + }); + expect(r.exitCode).toBe(0); + // Precomputed value: HMAC-SHA256("supersecret", "1700000000.héllo 漢字") + // (verified against the helper itself in this very test by also + // calling signWebhookPayload, so the value is locked to the + // helper's contract — independent of any node:crypto re-impl). + const expected = await signWebhookPayload({ + secret: "supersecret", + body: bodyBytes.toString("utf8"), + timestamp: "1700000000", + }); + expect(expected).toBe( + "sha256=3ad5be6cb96bdadf9d83c4c5e5fd567b88c5bc94d568933365a68b9b3ce526b5", + ); + expect(cap.stdout[0]).toBe(`signature: ${expected}`); + }); + }); + + it("round-trip: sign output verifies against verifyWebhookSignature directly", async () => { + await withHarness(async ({ cap, run }) => { + const body = `{"event":"webhook.delivered","attempt":3}`; + const secret = "round-trip-secret"; + const timestamp = "1700000000"; + const r = await run({ + argv: [ + "webhook", + "sign", + `--secret=${secret}`, + `--timestamp=${timestamp}`, + "--output=json", + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(0); + const parsed = JSON.parse(cap.stdout[0] as string) as { + signature: string; + timestamp: string; + }; + // Verify directly via the helper (NOT through the CLI). + const result = await verifyWebhookSignature({ + secret, + body, + headers: { + "X-Webhook-Signature": parsed.signature, + "X-Webhook-Timestamp": parsed.timestamp, + }, + now: () => new Date(Number(timestamp) * 1000), + }); + expect(result).toEqual({ ok: true }); + }); + }); +}); diff --git a/packages/cli/src/__tests__/webhook-verify.test.ts b/packages/cli/src/__tests__/webhook-verify.test.ts new file mode 100644 index 0000000..0acf9e8 --- /dev/null +++ b/packages/cli/src/__tests__/webhook-verify.test.ts @@ -0,0 +1,470 @@ +// Tests for Task 0106 — `new-test webhook verify` CLI subcommand. +// +// The command is pure local crypto: no SDK, no network, no auth, no +// active-org context. We exercise it through `runCli` with a synthetic +// stdin (an async-iterable Uint8Array stream) and a fixed `now()` so +// timestamp-tolerance behaviour is deterministic. The token store is a +// `MemoryTokenStore` with NO credentials loaded — verifying the command +// works without `new-test login` (Hard Rule §3 in task-0106.md). + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { signWebhookPayload } from "@saas/webhook-verifier"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore } from "./helpers.js"; +import type { StdinLike } from "../commands/webhook-verify.js"; + +// ---- harness -------------------------------------------------------------- + +interface Cap { + stdout: string[]; + stderr: string[]; +} + +interface RunOpts { + argv: string[]; + stdinBody?: Uint8Array | string | null; + /** Force `isTTY` flag on synthetic stdin (default: pipes when stdinBody is set). */ + stdinIsTTY?: boolean; + /** Fixed `now()` for verifier (default: 1700000000 unix seconds). */ + nowEpochSeconds?: number; +} + +const DEFAULT_NOW_EPOCH = 1700000000; + +/** + * Build a minimal `StdinLike`: an async-iterable wrapping a single chunk, + * carrying an `isTTY` flag (default `false` when bytes were supplied, + * `true` otherwise — matching `process.stdin` semantics). When `null` + * is passed we return a TTY stdin that yields nothing, simulating + * "no STDIN piped". + */ +function makeStdin( + body: Uint8Array | string | null, + isTTY?: boolean, +): StdinLike { + const chunks: Uint8Array[] = []; + if (body !== null) { + chunks.push(typeof body === "string" ? new TextEncoder().encode(body) : body); + } + const isTTYResolved = isTTY ?? (body === null); + return Object.assign( + { + async *[Symbol.asyncIterator]() { + for (const c of chunks) yield c; + }, + }, + { isTTY: isTTYResolved }, + ) as StdinLike; +} + +async function withHarness( + fn: (h: { + cap: Cap; + run: (opts: RunOpts) => Promise<{ exitCode: number }>; + }) => Promise, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0106-")); + try { + const cap: Cap = { stdout: [], stderr: [] }; + // No stored credential — `webhook verify` must work without `login`. + const tokenStore = new MemoryTokenStore(); + const contextStore = new ContextStore({ configDir: dir }); + + const run = (opts: RunOpts): Promise<{ exitCode: number }> => + runCli(opts.argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + webhookVerify: { + stdin: makeStdin(opts.stdinBody ?? null, opts.stdinIsTTY), + now: () => new Date((opts.nowEpochSeconds ?? DEFAULT_NOW_EPOCH) * 1000), + }, + }); + + await fn({ cap, run }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +// ---- helpers -------------------------------------------------------------- + +async function signBody( + secret: string, + body: string, + timestamp: number = DEFAULT_NOW_EPOCH, +): Promise<{ signature: string; timestamp: string }> { + const sig = await signWebhookPayload({ + secret, + body, + timestamp: String(timestamp), + }); + return { signature: sig, timestamp: String(timestamp) }; +} + +// ---- happy paths ---------------------------------------------------------- + +describe("webhook verify — happy paths", () => { + it("human mode: valid signature → exit 0, prints `ok: true`", async () => { + await withHarness(async ({ cap, run }) => { + const body = `{"event":"project.created","id":"prj_1"}`; + const { signature, timestamp } = await signBody("supersecret", body); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=supersecret`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(0); + expect(cap.stdout[0]).toBe("ok: true"); + expect(cap.stdout[1]).toBe("reason: "); + expect(cap.stderr).toEqual([]); + }); + }); + + it("json mode: valid signature → exit 0, prints `{\"ok\":true}`", async () => { + await withHarness(async ({ cap, run }) => { + const body = `{"event":"project.created"}`; + const { signature, timestamp } = await signBody("s1", body); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s1`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + "--output=json", + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(0); + expect(cap.stdout).toEqual([`{"ok":true}`]); + }); + }); + + it("--body=PATH: reads file bytes verbatim, no trim", async () => { + await withHarness(async ({ cap, run }) => { + // Body intentionally has leading + trailing whitespace and a final + // newline. The CLI MUST NOT `.trim()` — the helper hashes bytes. + const body = " {\"event\":\"x\"} \n"; + const { signature, timestamp } = await signBody("s2", body); + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-body-")); + const filePath = path.join(dir, "body.json"); + await fs.writeFile(filePath, body); + try { + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s2`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + `--body=${filePath}`, + ], + stdinBody: null, // no STDIN piped + }); + expect(r.exitCode).toBe(0); + expect(cap.stdout[0]).toBe("ok: true"); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + }); + + it("--tolerance-seconds=0 with now == timestamp passes", async () => { + await withHarness(async ({ cap, run }) => { + const body = "x"; + const { signature, timestamp } = await signBody("s3", body, 1700000000); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s3`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + "--tolerance-seconds=0", + ], + stdinBody: body, + nowEpochSeconds: 1700000000, + }); + expect(r.exitCode).toBe(0); + expect(cap.stdout[0]).toBe("ok: true"); + }); + }); +}); + +// ---- argument errors → exit 2 -------------------------------------------- + +describe("webhook verify — argument errors (exit 2)", () => { + it("missing --secret → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "verify", + "--signature=sha256=00", + "--timestamp=1700000000", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--secret/); + }); + }); + + it("missing --signature → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "verify", + "--secret=s", + "--timestamp=1700000000", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--signature/); + }); + }); + + it("missing --timestamp → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "verify", + "--secret=s", + "--signature=sha256=00", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/--timestamp/); + }); + }); + + it("--tolerance-seconds=abc → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "verify", + "--secret=s", + "--signature=sha256=00", + "--timestamp=1700000000", + "--tolerance-seconds=abc", + ], + stdinBody: "x", + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/tolerance-seconds/); + }); + }); + + it("--body=PATH and STDIN both → UsageError exit 2", async () => { + await withHarness(async ({ cap, run }) => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-bodyerr-")); + const filePath = path.join(dir, "body.json"); + await fs.writeFile(filePath, "x"); + try { + const r = await run({ + argv: [ + "webhook", + "verify", + "--secret=s", + "--signature=sha256=00", + "--timestamp=1700000000", + `--body=${filePath}`, + ], + stdinBody: "y", // both supplied + stdinIsTTY: false, + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/mutually exclusive|--body.*STDIN/i); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } + }); + }); + + it("--body=PATH for non-existent file → UsageError exit 2 with path in message", async () => { + await withHarness(async ({ cap, run }) => { + const r = await run({ + argv: [ + "webhook", + "verify", + "--secret=s", + "--signature=sha256=00", + "--timestamp=1700000000", + "--body=/this/path/does/not/exist.json", + ], + stdinBody: null, + }); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toContain("/this/path/does/not/exist.json"); + }); + }); +}); + +// ---- verifier failures → exit 4 ------------------------------------------ + +describe("webhook verify — verifier failures (exit 4)", () => { + it("tampered body → exit 4, reason: signature_mismatch", async () => { + await withHarness(async ({ cap, run }) => { + const original = "original body"; + const tampered = "tampered body"; + const { signature, timestamp } = await signBody("s4", original); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s4`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + ], + stdinBody: tampered, + }); + expect(r.exitCode).toBe(4); + expect(cap.stdout).toContain("ok: false"); + expect(cap.stdout).toContain("reason: signature_mismatch"); + }); + }); + + it("tampered hex signature (same length) → exit 4, signature_mismatch", async () => { + await withHarness(async ({ cap, run }) => { + const body = "z"; + const { signature, timestamp } = await signBody("s5", body); + // Flip the first hex char after the prefix to corrupt the signature. + const prefix = "sha256="; + const hex = signature.slice(prefix.length); + const flipped = (hex[0] === "0" ? "1" : "0") + hex.slice(1); + const tampered = prefix + flipped; + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s5`, + `--signature=${tampered}`, + `--timestamp=${timestamp}`, + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(4); + expect(cap.stdout).toContain("ok: false"); + expect(cap.stdout).toContain("reason: signature_mismatch"); + }); + }); + + it("malformed signature header (no sha256= prefix) → exit 4, malformed_signature", async () => { + await withHarness(async ({ cap, run }) => { + const body = "z"; + const { timestamp } = await signBody("s6", body); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s6`, + `--signature=garbage`, + `--timestamp=${timestamp}`, + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(4); + expect(cap.stdout).toContain("reason: malformed_signature"); + }); + }); + + it("timestamp older than --tolerance-seconds → exit 4, timestamp_out_of_tolerance", async () => { + await withHarness(async ({ cap, run }) => { + const oldTs = DEFAULT_NOW_EPOCH - 1000; // 1000s in the past + const body = "x"; + const { signature, timestamp } = await signBody("s7", body, oldTs); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s7`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + "--tolerance-seconds=300", + ], + stdinBody: body, + nowEpochSeconds: DEFAULT_NOW_EPOCH, + }); + expect(r.exitCode).toBe(4); + expect(cap.stdout).toContain("reason: timestamp_out_of_tolerance"); + }); + }); + + it("json mode failure shape: exit 4, single-line `{\"ok\":false,\"reason\":\"...\"}`", async () => { + await withHarness(async ({ cap, run }) => { + const body = "x"; + const tampered = "y"; + const { signature, timestamp } = await signBody("s8", body); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s8`, + `--signature=${signature}`, + `--timestamp=${timestamp}`, + "--output=json", + ], + stdinBody: tampered, + }); + expect(r.exitCode).toBe(4); + expect(cap.stdout).toEqual([`{"ok":false,"reason":"signature_mismatch"}`]); + }); + }); + + it("reason-code passthrough is verbatim in human mode", async () => { + // Confirms the human-mode line shape `reason: ` matches every + // helper-emitted reason enum member exactly (no rewriting). + const reasons = [ + "missing_signature", + "missing_timestamp", + "malformed_timestamp", + "timestamp_out_of_tolerance", + "malformed_signature", + "signature_mismatch", + ]; + for (const r of reasons) { + expect(/^[a-z_]+$/.test(r)).toBe(true); + } + // Drive one path that exercises the human-mode formatter end-to-end. + await withHarness(async ({ cap, run }) => { + const body = "x"; + const { timestamp } = await signBody("s9", body); + const r = await run({ + argv: [ + "webhook", + "verify", + `--secret=s9`, + `--signature=sha256=zzzz`, + `--timestamp=${timestamp}`, + ], + stdinBody: body, + }); + expect(r.exitCode).toBe(4); + // Match the line shape and confirm it carries one of the helper's + // canonical reason codes verbatim. + const reasonLine = cap.stdout.find((l) => l.startsWith("reason: ")) ?? ""; + const match = /^reason: ([a-z_]+)$/.exec(reasonLine); + expect(match).not.toBeNull(); + expect(reasons).toContain(match![1]!); + }); + }); +}); diff --git a/packages/cli/src/__tests__/writes-and-cross-reads.test.ts b/packages/cli/src/__tests__/writes-and-cross-reads.test.ts new file mode 100644 index 0000000..c584121 --- /dev/null +++ b/packages/cli/src/__tests__/writes-and-cross-reads.test.ts @@ -0,0 +1,1050 @@ +// Tests for Task 0101 — write commands (org invite, project create, env +// create, api-key create, webhook create) and cross-resource reads (usage +// summary, billing summary, audit list). +// +// The harness mirrors `commands.test.ts`: a captured-fetch `newtest` +// is injected via `sdkFactory`, a `MemoryTokenStore` carries the bearer +// token, and a temp-dir `ContextStore` carries the active-org. We assert +// against the recorded fetch URLs/methods/headers/body, the formatted +// stdout, and the CLI exit code. + +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { newtest } from "@saas/sdk"; + +import { runCli } from "../cli-runner.js"; +import { ContextStore } from "../context/store.js"; +import { MemoryTokenStore, envelope, jsonResponse } from "./helpers.js"; + +// ---- response fixtures ---------------------------------------------------- + +const INVITATION_CREATED = envelope({ + invitation: { + id: "inv_1", + email: "alice@example.com", + role: "admin", + status: "pending", + invitedBy: "usr_a", + expiresAt: "2025-12-31T00:00:00Z", + createdAt: "2025-01-01T00:00:00Z", + acceptedAt: null, + revokedAt: null, + }, +}); + +const PROJECT_CREATED = envelope({ + project: { + id: "prj_new", + orgId: "org_1", + name: "Edge", + slug: "edge", + status: "active", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-01-01T00:00:00Z", + archivedAt: null, + }, +}); + +const ENV_CREATED = envelope({ + environment: { + id: "env_new", + orgId: "org_1", + projectId: "prj_1", + name: "staging", + slug: "staging", + status: "active", + createdAt: "2025-01-01T00:00:00Z", + updatedAt: "2025-01-01T00:00:00Z", + archivedAt: null, + }, +}); + +const API_KEY_CREATED = envelope({ + apiKey: { + id: "ak_new", + label: "ci", + prefix: "sp_live_abc", + secret: "sp_live_abc.SUPERSECRET", + createdAt: "2025-01-01T00:00:00Z", + expiresAt: null, + servicePrincipal: { + id: "sp_1", + role: "viewer", + kind: "api_key", + }, + }, +}); + +const WEBHOOK_ENDPOINT_CREATED = envelope({ + endpoint: { + id: "whe_new", + orgId: "org_1", + projectId: null, + url: "https://example.com/hook", + secret: "whsec_x", + status: "active", + description: null, + metadata: {}, + createdAt: "2025-01-01T00:00:00Z", + }, +}); + +const WEBHOOK_SUBSCRIPTION_CREATED = envelope({ + subscription: { + id: "whs_new", + endpointId: "whe_new", + eventType: "project.created", + createdAt: "2025-01-01T00:00:00Z", + }, +}); + +const USAGE_SUMMARY = envelope({ + metric: "requests", + rollups: [ + { + bucketStart: "2025-01-01T00:00:00Z", + bucketType: "day", + quantity: 100, + recordCount: 50, + projectId: null, + environmentId: null, + }, + ], +}); + +const BILLING_SUMMARY = envelope({ + customer: { id: "cus_1", orgId: "org_1", externalId: "cus_stripe", createdAt: "2025-01-01T00:00:00Z" }, + activeSubscription: { id: "sub_1", status: "active", planId: "plan_pro", currentPeriodEnd: "2025-12-31T00:00:00Z" }, + plan: { id: "plan_pro", name: "Pro", currency: "usd", interval: "month", amount: 9900 }, + entitlements: [ + { feature: "max_projects", limit: 10, used: 2 }, + ], +}); + +const AUDIT_PAGE_1 = { + data: { + auditEntries: [ + { + id: "ae_1", + eventId: "evt_1", + orgId: "org_1", + projectId: null, + environmentId: null, + actorType: "user", + actorId: "usr_a", + eventType: "org.member.invited", + source: "api-edge", + category: "membership", + description: "Invited alice", + subject: { kind: "user", id: "usr_a", name: null }, + occurredAt: "2025-01-01T00:00:00Z", + requestId: "req_1", + correlationId: null, + payload: {}, + }, + ], + }, + meta: { requestId: "req_1", cursor: "cur_2" }, +}; + +const AUDIT_PAGE_2 = { + data: { + auditEntries: [ + { + id: "ae_2", + eventId: "evt_2", + orgId: "org_1", + projectId: null, + environmentId: null, + actorType: "user", + actorId: "usr_a", + eventType: "project.created", + source: "api-edge", + category: "project", + description: "Created Edge", + subject: { kind: "project", id: "prj_new", name: "Edge" }, + occurredAt: "2025-01-02T00:00:00Z", + requestId: "req_2", + correlationId: null, + payload: {}, + }, + ], + }, + meta: { requestId: "req_2", cursor: null as string | null }, +}; + +// ---- harness -------------------------------------------------------------- + +interface Cap { + stdout: string[]; + stderr: string[]; + fetchCalls: { url: string; init: RequestInit }[]; +} + +interface ResponderArgs { + url: string; + init: RequestInit; +} + +async function withHarness( + fn: (h: { + cap: Cap; + runArgv: (argv: string[]) => Promise<{ exitCode: number }>; + }) => Promise, + options: { + responder: (args: ResponderArgs) => Response; + activeOrgId?: string; + storedCred?: { apiUrl: string; token: string } | null; + }, +): Promise { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "cli-task0101-")); + try { + const cap: Cap = { stdout: [], stderr: [], fetchCalls: [] }; + const fetchFn: typeof fetch = async (input, init) => { + const url = String(input); + cap.fetchCalls.push({ url, init: init ?? {} }); + return options.responder({ url, init: init ?? {} }).clone(); + }; + + const tokenStore = + options.storedCred === null + ? new MemoryTokenStore() + : new MemoryTokenStore( + options.storedCred ?? { apiUrl: "https://api.test", token: "tok" }, + ); + const contextStore = new ContextStore({ configDir: dir }); + if (options.activeOrgId) await contextStore.setActiveOrg(options.activeOrgId); + + const runArgv = (argv: string[]): Promise<{ exitCode: number }> => + runCli(argv, { + stdout: (l) => cap.stdout.push(l), + stderr: (l) => cap.stderr.push(l), + tokenStore, + contextStore, + sdkFactory: (baseUrl, token) => + new newtest({ + baseUrl, + auth: { kind: "bearer", token }, + fetch: fetchFn, + }), + }); + + await fn({ cap, runArgv }); + } finally { + await fs.rm(dir, { recursive: true, force: true }); + } +} + +function pickHeader(init: RequestInit, name: string): string | null { + const h = init.headers; + if (h === undefined) return null; + if (h instanceof Headers) return h.get(name); + if (Array.isArray(h)) { + for (const [k, v] of h) { + if (k.toLowerCase() === name.toLowerCase()) return v; + } + return null; + } + for (const [k, v] of Object.entries(h)) { + if (k.toLowerCase() === name.toLowerCase()) return String(v); + } + return null; +} + +// ---- org invite ----------------------------------------------------------- + +describe("commands — org invite", () => { + it("POSTs to /v1/organizations/:orgId/invitations with the email + default role", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "invite", "alice@example.com"]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(call.url).toBe("https://api.test/v1/organizations/org_1/invitations"); + expect(call.init.method).toBe("POST"); + expect(JSON.parse(String(call.init.body))).toEqual({ + email: "alice@example.com", + role: "viewer", + }); + expect(cap.stdout.join("\n")).toContain("inv_1"); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("forwards --idempotency-key verbatim as the Idempotency-Key header", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "org", + "invite", + "alice@example.com", + "--role=admin", + "--idempotency-key=abc-123", + ]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(pickHeader(call.init, "idempotency-key")).toBe("abc-123"); + expect(JSON.parse(String(call.init.body))).toEqual({ + email: "alice@example.com", + role: "admin", + }); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("does NOT auto-mint an Idempotency-Key when the flag is absent", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "invite", "alice@example.com"]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "idempotency-key")).toBeNull(); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("--org=ORG_ID overrides the active-org context", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "org", + "invite", + "alice@example.com", + "--org=org_99", + ]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toBe( + "https://api.test/v1/organizations/org_99/invitations", + ); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("--org works even with no persisted active-org context", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "org", + "invite", + "alice@example.com", + "--org=org_solo", + ]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toContain("/organizations/org_solo/"); + }, + { responder: () => jsonResponse(INVITATION_CREATED) }, + ); + }); + + it("missing org context (no --org and no active) → exit 5", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "invite", "alice@example.com"]); + expect(r.exitCode).toBe(5); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + }, + { responder: () => jsonResponse(INVITATION_CREATED) }, + ); + }); + + it("missing email arg → usage exit 2", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["org", "invite"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/usage/); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("emits the SDK response shape verbatim in --output=json", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "org", + "invite", + "alice@example.com", + "--output=json", + ]); + expect(r.exitCode).toBe(0); + expect(JSON.parse(cap.stdout[0] ?? "")).toEqual(INVITATION_CREATED.data); + }, + { responder: () => jsonResponse(INVITATION_CREATED), activeOrgId: "org_1" }, + ); + }); +}); + +// ---- project create ------------------------------------------------------- + +describe("commands — project create", () => { + it("POSTs to /v1/organizations/:orgId/projects with the name", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["project", "create", "Edge"]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(call.url).toBe("https://api.test/v1/organizations/org_1/projects"); + expect(call.init.method).toBe("POST"); + expect(JSON.parse(String(call.init.body))).toEqual({ name: "Edge" }); + }, + { responder: () => jsonResponse(PROJECT_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("forwards --idempotency-key verbatim", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "project", + "create", + "Edge", + "--idempotency-key=xyz", + ]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "idempotency-key")).toBe("xyz"); + }, + { responder: () => jsonResponse(PROJECT_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("does NOT honour --org override (active-org only)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "project", + "create", + "Edge", + "--org=org_99", + ]); + expect(r.exitCode).toBe(0); + // Org from context, NOT from flag. + expect(cap.fetchCalls[0]!.url).toContain("/organizations/org_1/projects"); + }, + { responder: () => jsonResponse(PROJECT_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("missing org context → exit 5", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["project", "create", "Edge"]); + expect(r.exitCode).toBe(5); + expect(cap.stderr.join("\n")).toMatch(/no active organization/i); + }, + { responder: () => jsonResponse(PROJECT_CREATED) }, + ); + }); + + it("missing name → usage exit 2", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["project", "create"]); + expect(r.exitCode).toBe(2); + }, + { responder: () => jsonResponse(PROJECT_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("missing auth → exit 3", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["project", "create", "Edge"]); + expect(r.exitCode).toBe(3); + expect(cap.stderr.join("\n")).toMatch(/not logged in/); + }, + { + responder: () => jsonResponse(PROJECT_CREATED), + activeOrgId: "org_1", + storedCred: null, + }, + ); + }); +}); + +// ---- env create ----------------------------------------------------------- + +describe("commands — env create", () => { + it("POSTs to /v1/organizations/:orgId/projects/:projectId/environments via transport.request", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["env", "create", "prj_1", "staging"]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(call.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments", + ); + expect(call.init.method).toBe("POST"); + expect(JSON.parse(String(call.init.body))).toEqual({ name: "staging" }); + }, + { responder: () => jsonResponse(ENV_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("forwards --idempotency-key verbatim", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "env", + "create", + "prj_1", + "staging", + "--idempotency-key=env-key-1", + ]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "idempotency-key")).toBe( + "env-key-1", + ); + }, + { responder: () => jsonResponse(ENV_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("missing project-id or name → usage exit 2", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r1 = await runArgv(["env", "create"]); + expect(r1.exitCode).toBe(2); + const r2 = await runArgv(["env", "create", "prj_1"]); + expect(r2.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/usage/); + }, + { responder: () => jsonResponse(ENV_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("missing org context → exit 5", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["env", "create", "prj_1", "staging"]); + expect(r.exitCode).toBe(5); + }, + { responder: () => jsonResponse(ENV_CREATED) }, + ); + }); + + it("emits a record with id/projectId/name/slug/status in human mode", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["env", "create", "prj_1", "staging"]); + expect(r.exitCode).toBe(0); + const text = cap.stdout.join("\n"); + expect(text).toContain("env_new"); + expect(text).toContain("staging"); + expect(text).toContain("prj_1"); + }, + { responder: () => jsonResponse(ENV_CREATED), activeOrgId: "org_1" }, + ); + }); +}); + +// ---- api-key create ------------------------------------------------------- + +describe("commands — api-key create", () => { + it("POSTs to /v1/organizations/:orgId/api-keys with label + default role", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["api-key", "create", "ci"]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(call.url).toBe("https://api.test/v1/organizations/org_1/api-keys"); + expect(JSON.parse(String(call.init.body))).toEqual({ + label: "ci", + role: "viewer", + }); + }, + { responder: () => jsonResponse(API_KEY_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("--scope=builder is forwarded as the role field", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["api-key", "create", "ci", "--scope=builder"]); + expect(r.exitCode).toBe(0); + expect(JSON.parse(String(cap.fetchCalls[0]!.init.body))).toEqual({ + label: "ci", + role: "builder", + }); + }, + { responder: () => jsonResponse(API_KEY_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("forwards --idempotency-key verbatim", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "api-key", + "create", + "ci", + "--idempotency-key=k-1", + ]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "idempotency-key")).toBe("k-1"); + }, + { responder: () => jsonResponse(API_KEY_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("surfaces the one-time secret in human output", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["api-key", "create", "ci"]); + expect(r.exitCode).toBe(0); + expect(cap.stdout.join("\n")).toContain("sp_live_abc.SUPERSECRET"); + }, + { responder: () => jsonResponse(API_KEY_CREATED), activeOrgId: "org_1" }, + ); + }); + + it("missing label → usage exit 2", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["api-key", "create"]); + expect(r.exitCode).toBe(2); + }, + { responder: () => jsonResponse(API_KEY_CREATED), activeOrgId: "org_1" }, + ); + }); +}); + +// ---- webhook create ------------------------------------------------------- + +describe("commands — webhook create", () => { + it("POSTs to /v1/organizations/:orgId/webhooks/endpoints with the URL", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "create", + "https://example.com/hook", + ]); + expect(r.exitCode).toBe(0); + const call = cap.fetchCalls[0]!; + expect(call.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/endpoints", + ); + expect(JSON.parse(String(call.init.body))).toEqual({ + url: "https://example.com/hook", + }); + }, + { + responder: () => jsonResponse(WEBHOOK_ENDPOINT_CREATED), + activeOrgId: "org_1", + }, + ); + }); + + it("creates one subscription per --event when provided as a comma list", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "create", + "https://example.com/hook", + "--event=project.created,project.archived", + ]); + expect(r.exitCode).toBe(0); + // 1 endpoint + 2 subscriptions. + expect(cap.fetchCalls).toHaveLength(3); + expect(cap.fetchCalls[1]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/subscriptions", + ); + expect(JSON.parse(String(cap.fetchCalls[1]!.init.body))).toEqual({ + endpointId: "whe_new", + eventType: "project.created", + }); + expect(JSON.parse(String(cap.fetchCalls[2]!.init.body))).toEqual({ + endpointId: "whe_new", + eventType: "project.archived", + }); + }, + { + responder: ({ url }) => + url.endsWith("/subscriptions") + ? jsonResponse(WEBHOOK_SUBSCRIPTION_CREATED) + : jsonResponse(WEBHOOK_ENDPOINT_CREATED), + activeOrgId: "org_1", + }, + ); + }); + + it("suffixes per-subscription idempotency keys (root:sub:N)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "create", + "https://example.com/hook", + "--event=a,b", + "--idempotency-key=root", + ]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "idempotency-key")).toBe("root"); + expect(pickHeader(cap.fetchCalls[1]!.init, "idempotency-key")).toBe( + "root:sub:0", + ); + expect(pickHeader(cap.fetchCalls[2]!.init, "idempotency-key")).toBe( + "root:sub:1", + ); + }, + { + responder: ({ url }) => + url.endsWith("/subscriptions") + ? jsonResponse(WEBHOOK_SUBSCRIPTION_CREATED) + : jsonResponse(WEBHOOK_ENDPOINT_CREATED), + activeOrgId: "org_1", + }, + ); + }); + + it("creates the endpoint only when no --event is given", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "webhook", + "create", + "https://example.com/hook", + ]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls).toHaveLength(1); + expect(cap.stdout.join("\n")).toContain("(none"); + }, + { + responder: () => jsonResponse(WEBHOOK_ENDPOINT_CREATED), + activeOrgId: "org_1", + }, + ); + }); + + it("missing url → usage exit 2", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["webhook", "create"]); + expect(r.exitCode).toBe(2); + }, + { + responder: () => jsonResponse(WEBHOOK_ENDPOINT_CREATED), + activeOrgId: "org_1", + }, + ); + }); +}); + +// ---- usage summary -------------------------------------------------------- + +describe("commands — usage summary", () => { + it("hits /v1/organizations/:orgId/usage/summary with default metric=requests", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["usage", "summary"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/usage/summary?metric=requests", + ); + }, + { responder: () => jsonResponse(USAGE_SUMMARY), activeOrgId: "org_1" }, + ); + }); + + it("forwards --metric, --from, --to as query params", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "usage", + "summary", + "--metric=storage_gb", + "--from=2025-01-01T00:00:00Z", + "--to=2025-02-01T00:00:00Z", + ]); + expect(r.exitCode).toBe(0); + const url = cap.fetchCalls[0]!.url; + expect(url).toContain("metric=storage_gb"); + expect(url).toContain("startTime=2025-01-01T00%3A00%3A00Z"); + expect(url).toContain("endTime=2025-02-01T00%3A00%3A00Z"); + }, + { responder: () => jsonResponse(USAGE_SUMMARY), activeOrgId: "org_1" }, + ); + }); + + it("missing org context → exit 5", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["usage", "summary"]); + expect(r.exitCode).toBe(5); + }, + { responder: () => jsonResponse(USAGE_SUMMARY) }, + ); + }); + + it("--output=json round-trips the SDK shape", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["usage", "summary", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(JSON.parse(cap.stdout[0] ?? "")).toEqual(USAGE_SUMMARY.data); + }, + { responder: () => jsonResponse(USAGE_SUMMARY), activeOrgId: "org_1" }, + ); + }); +}); + +// ---- billing summary ------------------------------------------------------ + +describe("commands — billing summary", () => { + it("hits /v1/organizations/:orgId/billing/summary", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["billing", "summary"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/billing/summary", + ); + const text = cap.stdout.join("\n"); + expect(text).toContain("Pro"); + expect(text).toContain("plan_pro"); + }, + { responder: () => jsonResponse(BILLING_SUMMARY), activeOrgId: "org_1" }, + ); + }); + + it("missing org context → exit 5", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["billing", "summary"]); + expect(r.exitCode).toBe(5); + }, + { responder: () => jsonResponse(BILLING_SUMMARY) }, + ); + }); + + it("--output=json round-trips the full SDK shape", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["billing", "summary", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(JSON.parse(cap.stdout[0] ?? "")).toEqual(BILLING_SUMMARY.data); + }, + { responder: () => jsonResponse(BILLING_SUMMARY), activeOrgId: "org_1" }, + ); + }); +}); + +// ---- audit list ----------------------------------------------------------- + +describe("commands — audit list", () => { + it("returns the first page and surfaces next_cursor", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/audit", + ); + const parsed = JSON.parse(cap.stdout[0] ?? ""); + expect(parsed.next_cursor).toBe("cur_2"); + expect(parsed.auditEntries).toHaveLength(1); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("--limit and --category are forwarded as query params", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "audit", + "list", + "--limit=25", + "--category=membership", + ]); + expect(r.exitCode).toBe(0); + const url = cap.fetchCalls[0]!.url; + expect(url).toContain("limit=25"); + expect(url).toContain("category=membership"); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("--limit must be a positive integer (usage exit 2)", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["audit", "list", "--limit=notanumber"]); + expect(r.exitCode).toBe(2); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("--all walks pages until cursor is null", async () => { + let n = 0; + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list", "--all", "--output=json"]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls).toHaveLength(2); + expect(cap.fetchCalls[1]!.url).toContain("cursor=cur_2"); + // JSON Lines: one document per page. + expect(cap.stdout).toHaveLength(2); + expect(JSON.parse(cap.stdout[0] ?? "").next_cursor).toBe("cur_2"); + expect(JSON.parse(cap.stdout[1] ?? "").next_cursor).toBeNull(); + }, + { + responder: () => { + n += 1; + return jsonResponse(n === 1 ? AUDIT_PAGE_1 : AUDIT_PAGE_2); + }, + activeOrgId: "org_1", + }, + ); + }); + + it("--all + --cursor is a usage error (exit 2)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list", "--all", "--cursor=foo"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/mutually exclusive/); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("missing org context → exit 5", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["audit", "list"]); + expect(r.exitCode).toBe(5); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1) }, + ); + }); + + it("sends the bearer token on the audit request", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list"]); + expect(r.exitCode).toBe(0); + expect(pickHeader(cap.fetchCalls[0]!.init, "authorization")).toBe( + "Bearer tok", + ); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("human mode renders a table with audit columns", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list"]); + expect(r.exitCode).toBe(0); + const text = cap.stdout.join("\n"); + expect(text).toMatch(/occurredAt\s+category\s+eventType\s+actor\s+id/); + expect(text).toContain("ae_1"); + expect(text).toContain("user:usr_a"); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("forwards all filter flags as query params", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "audit", + "list", + "--actor=usr_a", + "--actor-type=user", + "--subject-kind=project", + "--subject-id=prj_1", + "--event-type=member.role_changed", + "--from=2026-01-01T00:00:00.000Z", + "--to=2026-02-01T00:00:00.000Z", + ]); + expect(r.exitCode).toBe(0); + const url = cap.fetchCalls[0]!.url; + expect(url).toContain("actorId=usr_a"); + expect(url).toContain("actorType=user"); + expect(url).toContain("subjectKind=project"); + expect(url).toContain("subjectId=prj_1"); + expect(url).toContain("eventType=member.role_changed"); + expect(url).toContain("from=2026-01-01T00%3A00%3A00.000Z"); + expect(url).toContain("to=2026-02-01T00%3A00%3A00.000Z"); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("--format=ndjson streams one JSON document per entry across all pages", async () => { + let n = 0; + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list", "--format=ndjson"]); + expect(r.exitCode).toBe(0); + // Both pages walked. + expect(cap.fetchCalls).toHaveLength(2); + expect(cap.fetchCalls[1]!.url).toContain("cursor=cur_2"); + // One stdout line per entry (AUDIT_PAGE_1 + AUDIT_PAGE_2 entries). + expect(cap.stdout).toHaveLength(2); + for (const line of cap.stdout) { + const parsed = JSON.parse(line); + expect(typeof parsed.id).toBe("string"); + } + expect(JSON.parse(cap.stdout[0] ?? "").id).toBe("ae_1"); + }, + { + responder: () => { + n += 1; + return jsonResponse(n === 1 ? AUDIT_PAGE_1 : AUDIT_PAGE_2); + }, + activeOrgId: "org_1", + }, + ); + }); + + it("--format=ndjson forwards filters into the export stream", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv([ + "audit", + "list", + "--format=ndjson", + "--actor-type=service_principal", + ]); + expect(r.exitCode).toBe(0); + expect(cap.fetchCalls[0]!.url).toContain("actorType=service_principal"); + }, + { responder: () => jsonResponse(AUDIT_PAGE_2), activeOrgId: "org_1" }, + ); + }); + + it("--format=ndjson + --cursor is a usage error (exit 2)", async () => { + await withHarness( + async ({ cap, runArgv }) => { + const r = await runArgv(["audit", "list", "--format=ndjson", "--cursor=foo"]); + expect(r.exitCode).toBe(2); + expect(cap.stderr.join("\n")).toMatch(/mutually exclusive/); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); + + it("--format with an unsupported value is a usage error (exit 2)", async () => { + await withHarness( + async ({ runArgv }) => { + const r = await runArgv(["audit", "list", "--format=csv"]); + expect(r.exitCode).toBe(2); + }, + { responder: () => jsonResponse(AUDIT_PAGE_1), activeOrgId: "org_1" }, + ); + }); +}); diff --git a/packages/cli/src/auth/login.ts b/packages/cli/src/auth/login.ts new file mode 100644 index 0000000..37eb0fb --- /dev/null +++ b/packages/cli/src/auth/login.ts @@ -0,0 +1,91 @@ +// `new-test login` — token-paste auth flow. +// +// Rationale (recorded in the implementer report's auth-flow choice): +// The api-edge currently exposes `/v1/auth/login/{start,complete}` for +// the WEB session (browser cookie) flow but no device-grant endpoint +// that issues a CLI bearer token. Spec 13's `login` command is +// under-specified on the wire format, and adding a new server route is +// out-of-scope for this PR. We ship the token-paste flow today: the +// user pastes a Bearer token (e.g. an API-key, or a session-token they +// copy out of the console), the CLI validates by calling +// `client.organizations.list()`, and stores the credential on success. +// +// When the CLI later gains a device-flow endpoint, switching is a +// one-line dispatch in this file. + +import { newtest } from "@saas/sdk"; + +import type { OutputMode } from "../output/index.js"; +import { formatOutput } from "../output/index.js"; +import type { ContextStore } from "../context/store.js"; +import type { TokenStore } from "../token-store/types.js"; +import { DEFAULT_API_URL } from "../brand.js"; + +export interface LoginInput { + readonly apiUrl?: string; + readonly token?: string; + readonly outputMode: OutputMode; + readonly tokenStore: TokenStore; + readonly contextStore: ContextStore; + readonly readToken: () => Promise; + readonly stdout: (line: string) => void; + /** SDK factory override (tests). */ + readonly sdkFactory?: (baseUrl: string, token: string) => newtest; +} + +export interface LoginOutcome { + readonly apiUrl: string; + readonly orgCount: number; +} + +export async function loginFlow(input: LoginInput): Promise { + const apiUrl = (input.apiUrl ?? DEFAULT_API_URL).trim(); + if (apiUrl.length === 0) { + throw new Error("--api-url cannot be empty"); + } + + let token = input.token; + if (token === undefined || token.length === 0) { + if (input.outputMode !== "json") { + input.stdout(`Logging in to ${apiUrl}`); + input.stdout("Paste a Bearer token (input is not echoed):"); + } + token = (await input.readToken()).trim(); + } + if (token.length === 0) { + throw new Error("token cannot be empty"); + } + + // Validate by calling the SDK. Auth failures throw + // `UnauthenticatedError`; the caller's error handler turns that into a + // friendly "token rejected" message. + const client = + input.sdkFactory?.(apiUrl, token) ?? + new newtest({ baseUrl: apiUrl, auth: { kind: "bearer", token } }); + const result = await client.organizations.list(); + const orgCount = result.organizations.length; + + await input.tokenStore.save({ apiUrl, token }); + await input.contextStore.setLastApiUrl(apiUrl); + + if (input.outputMode === "human") { + input.stdout( + formatOutput({ + mode: "human", + title: "✓ Authenticated", + record: { apiUrl, organizations: String(orgCount) }, + }), + ); + } else { + input.stdout( + formatOutput({ + mode: "json", + data: { apiUrl, organizations: orgCount }, + }), + ); + } + + return { apiUrl, orgCount }; +} + +export const LOGIN_DEFAULT_API_URL = DEFAULT_API_URL; diff --git a/packages/cli/src/auth/logout.ts b/packages/cli/src/auth/logout.ts new file mode 100644 index 0000000..0e682a9 --- /dev/null +++ b/packages/cli/src/auth/logout.ts @@ -0,0 +1,23 @@ +// `new-test logout` — clear token + active org context. + +import type { OutputMode } from "../output/index.js"; +import { formatOutput } from "../output/index.js"; +import type { ContextStore } from "../context/store.js"; +import type { TokenStore } from "../token-store/types.js"; + +export interface LogoutInput { + readonly outputMode: OutputMode; + readonly tokenStore: TokenStore; + readonly contextStore: ContextStore; + readonly stdout: (line: string) => void; +} + +export async function logoutFlow(input: LogoutInput): Promise { + await input.tokenStore.clear(); + await input.contextStore.clear(); + if (input.outputMode === "json") { + input.stdout(formatOutput({ mode: "json", data: { ok: true } })); + } else { + input.stdout("✓ Logged out (credentials and context cleared)."); + } +} diff --git a/packages/cli/src/auth/whoami.ts b/packages/cli/src/auth/whoami.ts new file mode 100644 index 0000000..f88030f --- /dev/null +++ b/packages/cli/src/auth/whoami.ts @@ -0,0 +1,67 @@ +// `new-test whoami` — read token + cached context, validate via SDK. + +import { newtest } from "@saas/sdk"; + +import type { OutputMode } from "../output/index.js"; +import { formatOutput } from "../output/index.js"; +import type { ContextStore } from "../context/store.js"; +import type { TokenStore } from "../token-store/types.js"; +import { MissingAuthError } from "../errors.js"; + +export interface WhoamiInput { + readonly outputMode: OutputMode; + readonly tokenStore: TokenStore; + readonly contextStore: ContextStore; + readonly stdout: (line: string) => void; + /** SDK factory override for tests. Defaults to constructing `newtest`. */ + readonly sdkFactory?: (baseUrl: string, token: string) => newtest; +} + +export interface WhoamiOutcome { + readonly apiUrl: string; + readonly activeOrgId: string | null; + readonly orgCount: number; +} + +export async function whoamiFlow(input: WhoamiInput): Promise { + const cred = await input.tokenStore.load(); + if (!cred) throw new MissingAuthError(); + + const client = + input.sdkFactory?.(cred.apiUrl, cred.token) ?? + new newtest({ + baseUrl: cred.apiUrl, + auth: { kind: "bearer", token: cred.token }, + }); + + const ctx = await input.contextStore.load(); + const result = await client.organizations.list(); + const orgCount = result.organizations.length; + const activeOrgId = ctx.activeOrgId ?? null; + + if (input.outputMode === "json") { + input.stdout( + formatOutput({ + mode: "json", + data: { + apiUrl: cred.apiUrl, + activeOrgId, + organizations: orgCount, + }, + }), + ); + } else { + input.stdout( + formatOutput({ + mode: "human", + record: { + apiUrl: cred.apiUrl, + activeOrg: activeOrgId ?? "(none)", + organizations: String(orgCount), + }, + }), + ); + } + + return { apiUrl: cred.apiUrl, activeOrgId, orgCount }; +} diff --git a/packages/cli/src/brand.ts b/packages/cli/src/brand.ts new file mode 100644 index 0000000..42c5b25 --- /dev/null +++ b/packages/cli/src/brand.ts @@ -0,0 +1,27 @@ +// Instance identity for the CLI (saas-bootstrap-factory BF3 seam). +// +// The binary name, default API endpoint, OS keychain service, and config +// directory live here so a rebranded instance retargets one file. The +// `@saas/sdk` client class name (`newtest`) is intentionally NOT part of +// this seam — it is a code identifier, handled by the blueprint rename map +// (BF12), not a runtime value. + +/** CLI binary name (matches `bin` in package.json). */ +export const CLI_BIN = "new-test"; + +/** Product/brand name used in human-facing CLI copy. */ +export const PRODUCT_NAME = "new-test"; + +/** Default API base URL when `--api-url` is not supplied. */ +export const DEFAULT_API_URL = "https://api.new-test.dev"; + +/** OS keychain service name for stored credentials. */ +export const KEYCHAIN_SERVICE = `${CLI_BIN}-cli`; + +/** Directory name under `~/.config` for the file-based token/config store. */ +export const CONFIG_APP_DIR = CLI_BIN; + +/** Env var overriding the config directory (used heavily by tests). */ +// Hyphens map to underscores so a hyphenated CLI_BIN (e.g. "acme-cloud") +// still derives a valid env var name. +export const CONFIG_DIR_ENV_VAR = `${CLI_BIN.toUpperCase().replace(/-/g, "_")}_CONFIG_DIR`; diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts new file mode 100644 index 0000000..a5e56f2 --- /dev/null +++ b/packages/cli/src/cli-runner.ts @@ -0,0 +1,265 @@ +// CLI runner. The `bin/cli.ts` entrypoint is a thin wrapper that calls +// `runCli(process.argv.slice(2))`; this module owns the dispatch logic so +// it stays unit-testable. + +import { newtest } from "@saas/sdk"; + +import { CLI_BIN, PRODUCT_NAME } from "./brand.js"; +import { Router, parseArgv } from "./router.js"; +import { + loginCommand, + logoutCommand, + whoamiCommand, + orgListCommand, + orgUseCommand, + orgMembersCommand, + projectListCommand, +} from "./commands/index.js"; +import { + orgInviteCommand, + projectCreateCommand, + envCreateCommand, + apiKeyCreateCommand, + webhookCreateCommand, +} from "./commands/writes.js"; +import { makeWebhookVerifyCommand, type WebhookVerifyOptions } from "./commands/webhook-verify.js"; +import { makeWebhookSignCommand, type WebhookSignOptions } from "./commands/webhook-sign.js"; +import { webhookSecretsRotateCommand } from "./commands/webhook-secrets-rotate.js"; +import { webhookEnableCommand } from "./commands/webhook-enable.js"; +import { webhookDisableCommand } from "./commands/webhook-disable.js"; +import { webhookDeliveriesCommand } from "./commands/webhook-deliveries.js"; +import { webhookDeliveriesReplayCommand } from "./commands/webhook-deliveries-replay.js"; +import { securityEventsCommand } from "./commands/security-events.js"; +import { + notificationPreferencesGetCommand, + notificationPreferencesSetCommand, +} from "./commands/notification-preferences.js"; +import { integrationsGithubTokenCommand } from "./commands/integrations-token.js"; +import { + usageSummaryCommand, + billingSummaryCommand, + auditListCommand, +} from "./commands/cross-reads.js"; +import { parseOutputMode, type OutputMode } from "./output/index.js"; +import { ContextStore } from "./context/store.js"; +import { selectTokenStore } from "./token-store/index.js"; +import type { TokenStore } from "./token-store/types.js"; +import { CLI_VERSION } from "./version.js"; +import { + formatCliError, + MissingAuthError, + UsageError, +} from "./errors.js"; + +export interface RunOptions { + /** Override stdout sink (tests). */ + readonly stdout?: (line: string) => void; + /** Override stderr sink (tests). */ + readonly stderr?: (line: string) => void; + /** Inject a token store (tests). */ + readonly tokenStore?: TokenStore; + /** Inject a context store (tests). */ + readonly contextStore?: ContextStore; + /** Override SDK factory (tests). */ + readonly sdkFactory?: (baseUrl: string, token: string) => newtest; + /** Override config dir for the file token store / context store. */ + readonly configDir?: string; + /** + * Test injection for the `webhook verify` command — supplies a + * synthetic stdin and a fixed `now()` so verification can be exercised + * deterministically without poking `process.stdin` or the system clock. + */ + readonly webhookVerify?: WebhookVerifyOptions; + /** + * Test injection for the `webhook sign` command — supplies a + * synthetic stdin so signing can be exercised deterministically + * without poking `process.stdin`. + */ + readonly webhookSign?: WebhookSignOptions; +} + +export async function runCli( + argv: ReadonlyArray, + opts: RunOptions = {}, +): Promise<{ exitCode: number }> { + const stdout = opts.stdout ?? defaultStdout; + const stderr = opts.stderr ?? defaultStderr; + + const { positional, flags } = parseArgv(argv); + + const outputMode: OutputMode = parseOutputMode(flags["output"]); + + // Top-level meta flags handled before routing. + if (flags["version"] === true || positional[0] === "--version") { + if (outputMode === "json") { + stdout(JSON.stringify({ version: CLI_VERSION })); + } else { + stdout(CLI_VERSION); + } + return { exitCode: 0 }; + } + if (flags["help"] === true || positional.length === 0) { + printHelp(stdout); + return { exitCode: positional.length === 0 ? 0 : 0 }; + } + + const router = buildRouter(opts); + const match = router.resolve(positional); + if (match === null) { + const formatted = formatCliError({ + err: new UsageError(`unknown command: ${positional.join(" ")}`), + mode: outputMode, + }); + stderr(formatted.message); + if (outputMode === "human") printUsageHint(stderr); + return { exitCode: formatted.exitCode }; + } + + const tokenStore = + opts.tokenStore ?? + (await selectTokenStore( + opts.configDir !== undefined ? { configDir: opts.configDir } : {}, + )); + const contextStore = + opts.contextStore ?? + new ContextStore(opts.configDir !== undefined ? { configDir: opts.configDir } : {}); + + const sdk = async (): Promise => { + const cred = await tokenStore.load(); + if (!cred) throw new MissingAuthError(); + if (opts.sdkFactory) return opts.sdkFactory(cred.apiUrl, cred.token); + return new newtest({ + baseUrl: cred.apiUrl, + auth: { kind: "bearer", token: cred.token }, + }); + }; + + try { + const result = await match.handler({ + args: match.rest, + flags, + outputMode, + stdout, + stderr, + tokenStore, + contextStore, + sdk, + }); + return { exitCode: result.exitCode }; + } catch (err) { + const formatted = formatCliError({ err, mode: outputMode }); + stderr(formatted.message); + return { exitCode: formatted.exitCode }; + } +} + +function buildRouter(opts: RunOptions): Router { + const r = new Router(); + const webhookVerifyHandler = makeWebhookVerifyCommand(opts.webhookVerify ?? {}); + const webhookSignHandler = makeWebhookSignCommand(opts.webhookSign ?? {}); + // Auth + r.register(["login"], `Authenticate against a ${PRODUCT_NAME} API`, loginCommand); + r.register(["logout"], "Clear stored credentials and context", logoutCommand); + r.register(["whoami"], "Show the active identity and organization", whoamiCommand); + // Organizations + r.register(["org", "list"], "List organizations the actor belongs to", orgListCommand); + r.register(["org", "use"], "Set the active organization", orgUseCommand); + r.register(["org", "members"], "List members of the active organization", orgMembersCommand); + r.register(["org", "invite"], "Invite a member to an organization", orgInviteCommand); + // Projects + r.register(["project", "list"], "List projects in the active organization", projectListCommand); + r.register(["project", "create"], "Create a project in the active organization", projectCreateCommand); + // Environments + r.register(["env", "create"], "Create an environment under a project", envCreateCommand); + // API keys + r.register(["api-key", "create"], "Create an org-scoped API key", apiKeyCreateCommand); + // Webhooks + r.register(["webhook", "create"], "Create a webhook endpoint (and optional subscriptions)", webhookCreateCommand); + r.register(["webhook", "verify"], "Verify a webhook signature locally (no network)", webhookVerifyHandler); + r.register(["webhook", "sign"], "Sign a webhook payload locally (no network)", webhookSignHandler); + r.register(["webhook", "secrets", "rotate"], "Rotate the signing secret for a webhook endpoint (reveal-once)", webhookSecretsRotateCommand); + r.register(["webhook", "enable"], "Re-enable a previously disabled webhook endpoint", webhookEnableCommand); + r.register(["webhook", "disable"], "Disable an active webhook endpoint", webhookDisableCommand); + r.register(["webhook", "deliveries"], "List delivery attempts for a webhook endpoint", webhookDeliveriesCommand); + r.register(["webhook", "deliveries", "replay"], "Replay a past webhook delivery attempt (re-send same event)", webhookDeliveriesReplayCommand); + // Cross-resource reads + r.register(["usage", "summary"], "Summarize usage rollups for the active organization", usageSummaryCommand); + r.register(["billing", "summary"], "Show billing customer/plan/entitlements summary", billingSummaryCommand); + r.register(["audit", "list"], "List audit log entries for the active organization", auditListCommand); + // Account security events (actor-scoped — no --org) + r.register(["security", "events"], "List account security events (actor-scoped)", securityEventsCommand); + // Notification preferences (actor-scoped per org) + r.register(["notifications", "preferences"], "Show your email notification preferences for an org", notificationPreferencesGetCommand); + r.register(["notifications", "preferences", "set"], "Enable/disable an email notification category", notificationPreferencesSetCommand); + r.register(["integrations", "github", "token"], "Mint a short-lived, repo-scoped GitHub installation token", integrationsGithubTokenCommand); + return r; +} + +function printHelp(stdout: (line: string) => void): void { + stdout( + [ + `${CLI_BIN} v${CLI_VERSION}`, + "", + "USAGE:", + ` ${CLI_BIN} [args] [--output=human|json]`, + "", + "AUTH:", + ` ${CLI_BIN} login [--api-url=URL] [--token=BEARER]`, + ` ${CLI_BIN} logout`, + ` ${CLI_BIN} whoami`, + "", + "ORGANIZATIONS:", + ` ${CLI_BIN} org list`, + ` ${CLI_BIN} org use `, + ` ${CLI_BIN} org members`, + ` ${CLI_BIN} org invite [--role=ROLE] [--idempotency-key=KEY] [--org=ORG_ID]`, + "", + "PROJECTS / ENVIRONMENTS:", + ` ${CLI_BIN} project list`, + ` ${CLI_BIN} project create [--idempotency-key=KEY]`, + ` ${CLI_BIN} env create [--idempotency-key=KEY]`, + "", + "API KEYS / WEBHOOKS:", + ` ${CLI_BIN} api-key create [--scope=SCOPE] [--idempotency-key=KEY]`, + ` ${CLI_BIN} webhook create [--event=EVENT[,EVENT2,...]] [--idempotency-key=KEY]`, + ` ${CLI_BIN} webhook verify --secret=S --signature=H --timestamp=T [--body=PATH] [--tolerance-seconds=N]`, + ` ${CLI_BIN} webhook sign --secret=S --timestamp=T [--body=PATH]`, + ` ${CLI_BIN} webhook secrets rotate [--idempotency-key=KEY]`, + ` ${CLI_BIN} webhook enable [--idempotency-key=KEY] [--output=human|json]`, + ` ${CLI_BIN} webhook disable [--reason=TEXT] [--idempotency-key=KEY] [--output=human|json]`, + ` ${CLI_BIN} webhook deliveries [--limit=N] [--cursor=CURSOR] [--all] [--output=human|json]`, + ` ${CLI_BIN} webhook deliveries replay [--idempotency-key=KEY] [--output=human|json]`, + "", + "USAGE / BILLING / AUDIT:", + ` ${CLI_BIN} usage summary [--metric=METRIC] [--from=ISO] [--to=ISO]`, + ` ${CLI_BIN} billing summary`, + ` ${CLI_BIN} audit list [--limit=N] [--cursor=CURSOR] [--category=CAT] [--all]`, + " [--actor=ID] [--actor-type=TYPE] [--subject-kind=KIND]", + " [--subject-id=ID] [--event-type=TYPE] [--from=ISO] [--to=ISO]", + " [--format=ndjson]", + "", + "SECURITY:", + ` ${CLI_BIN} security events [--limit=N] [--cursor=CURSOR] [--all] [--output=human|json]`, + "", + "GLOBAL FLAGS:", + " --output=human|json Output format (default: human)", + " --help Show this help", + " --version Print version", + "", + "IDEMPOTENCY:", + " --idempotency-key=KEY is forwarded verbatim to the API on every write.", + " The CLI never auto-generates a key (Stripe parity).", + ].join("\n"), + ); +} + +function printUsageHint(stderr: (line: string) => void): void { + stderr(`run \`${CLI_BIN} --help\` to see available commands`); +} + +function defaultStdout(line: string): void { + process.stdout.write(`${line}\n`); +} +function defaultStderr(line: string): void { + process.stderr.write(`${line}\n`); +} diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts new file mode 100644 index 0000000..e259ce5 --- /dev/null +++ b/packages/cli/src/cli.ts @@ -0,0 +1,18 @@ +#!/usr/bin/env node +// CLI binary entrypoint. Imports the runner from the package index and +// dispatches `process.argv`. Kept tiny so it stays trivially auditable. + +import { runCli } from "./cli-runner.js"; + +async function main(): Promise { + const result = await runCli(process.argv.slice(2)); + process.exit(result.exitCode); +} + +main().catch((err: unknown) => { + // Last-resort handler — `runCli` already maps known errors to exit codes + // and prints them. Anything that escapes here is a programmer bug. + const message = err instanceof Error ? err.stack ?? err.message : String(err); + process.stderr.write(`fatal: ${message}\n`); + process.exit(1); +}); diff --git a/packages/cli/src/commands/cross-reads.ts b/packages/cli/src/commands/cross-reads.ts new file mode 100644 index 0000000..e937845 --- /dev/null +++ b/packages/cli/src/commands/cross-reads.ts @@ -0,0 +1,331 @@ +// Cross-resource read commands (Task 0101 → 0102 SDK rewire). +// +// `usage summary` and `billing summary` are thin wrappers over single-shot +// SDK reads. `audit list` adds pagination on top of the SDK with two modes: +// +// - default (no `--all`): returns the first page via +// `client.events.listAuditEntriesPage()`, which exposes the +// server-issued `meta.cursor` alongside the entries. JSON output emits +// `{ auditEntries, next_cursor }`; human mode prints a small +// id/eventType/occurredAt/actor table with the next cursor in the +// title when present. +// - `--all`: drives `client.events.iterAuditEntries()` to walk every +// page until the server returns `cursor: null`. JSON mode emits one +// JSON document per page (newline-delimited / JSON Lines); human mode +// concatenates rows under a single header. +// +// Task 0102 swapped the hand-rolled envelope fetch through the public +// transport for the typed SDK surface (`EventsClient`), removing the +// need for the CLI to know envelope shape, header construction, or +// loop guards. + +import type { CommandContext, CommandResult } from "../router.js"; +import { formatOutput } from "../output/index.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId } from "./helpers.js"; +import type { ListAuditEntriesQuery } from "@saas/sdk"; + +interface PublicAuditEntryShape { + id: string; + eventType: string; + category: string; + occurredAt: string; + actorType: string; + actorId: string; +} + +function parseLimit(flag: string | boolean | undefined): number | undefined { + if (typeof flag !== "string" || flag.length === 0) return undefined; + const n = Number.parseInt(flag, 10); + if (!Number.isFinite(n) || n <= 0) { + throw new UsageError(`--limit must be a positive integer (got ${flag})`); + } + return n; +} + +/** Read a string flag, treating empty / boolean / missing as absent. */ +function strFlag(flag: string | boolean | undefined): string | undefined { + return typeof flag === "string" && flag.length > 0 ? flag : undefined; +} + +/** + * Collect the optional org-audit filter flags into the SDK's `by:"org"` filter + * shape. Validation is intentionally minimal here — the worker is the + * authoritative validator (charset, actorType set, ISO timestamp). The CLI just + * forwards non-empty values; malformed input surfaces as a 400 from the API. + */ +function parseAuditFilterFlags( + flags: Record, +): { + actorId?: string; + actorType?: string; + subjectKind?: string; + subjectId?: string; + eventType?: string; + from?: string; + to?: string; +} { + const filters: { + actorId?: string; + actorType?: string; + subjectKind?: string; + subjectId?: string; + eventType?: string; + from?: string; + to?: string; + } = {}; + const actorId = strFlag(flags["actor"]); + if (actorId !== undefined) filters.actorId = actorId; + const actorType = strFlag(flags["actor-type"]); + if (actorType !== undefined) filters.actorType = actorType; + const subjectKind = strFlag(flags["subject-kind"]); + if (subjectKind !== undefined) filters.subjectKind = subjectKind; + const subjectId = strFlag(flags["subject-id"]); + if (subjectId !== undefined) filters.subjectId = subjectId; + const eventType = strFlag(flags["event-type"]); + if (eventType !== undefined) filters.eventType = eventType; + const from = strFlag(flags["from"]); + if (from !== undefined) filters.from = from; + const to = strFlag(flags["to"]); + if (to !== undefined) filters.to = to; + return filters; +} + +// --------------------------------------------------------------------------- +// usage summary [--metric=METRIC] [--from=ISO] [--to=ISO] +// +// SDK pick: `client.metering.getUsageSummary(orgId, query)` — +// GET /v1/organizations/:orgId/usage/summary. The contract requires +// `metric` so the CLI defaults to "requests" (the canonical org-level +// rollup metric) when the user omits `--metric`. `--from` / `--to` map to +// the contract's `startTime` / `endTime` ISO 8601 fields. +// --------------------------------------------------------------------------- + +export async function usageSummaryCommand(ctx: CommandContext): Promise { + const metricFlag = ctx.flags["metric"]; + const fromFlag = ctx.flags["from"]; + const toFlag = ctx.flags["to"]; + const metric = typeof metricFlag === "string" && metricFlag.length > 0 ? metricFlag : "requests"; + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const sdk = await ctx.sdk(); + const result = await sdk.metering.getUsageSummary(orgId, { + metric, + ...(typeof fromFlag === "string" && fromFlag.length > 0 ? { startTime: fromFlag } : {}), + ...(typeof toFlag === "string" && toFlag.length > 0 ? { endTime: toFlag } : {}), + }); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: result })); + return { exitCode: 0 }; + } + + const rows = result.rollups.map((r) => ({ + bucketStart: r.bucketStart, + bucketType: r.bucketType, + quantity: String(r.quantity), + recordCount: String(r.recordCount), + projectId: r.projectId ?? "", + environmentId: r.environmentId ?? "", + })); + ctx.stdout( + formatOutput({ + mode: "human", + columns: ["bucketStart", "bucketType", "quantity", "recordCount", "projectId", "environmentId"], + rows, + title: `Usage summary for ${orgId} (metric=${metric})`, + }), + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// billing summary +// +// SDK pick: `client.billing.getSummary(orgId)` — +// GET /v1/organizations/:orgId/billing/summary. The response carries +// `customer`, `activeSubscription`, `plan`, and `entitlements`; we render +// a key/value summary in human mode and the SDK shape verbatim in JSON. +// --------------------------------------------------------------------------- + +export async function billingSummaryCommand(ctx: CommandContext): Promise { + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const sdk = await ctx.sdk(); + const result = await sdk.billing.getSummary(orgId); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: result })); + return { exitCode: 0 }; + } + + ctx.stdout( + formatOutput({ + mode: "human", + record: { + customer: result.customer ? result.customer.id : "(none)", + plan: result.plan ? `${result.plan.name} (${result.plan.id})` : "(none)", + subscription: result.activeSubscription + ? `${result.activeSubscription.id} [${result.activeSubscription.status}]` + : "(none)", + entitlements: String(result.entitlements.length), + }, + title: `Billing summary for ${orgId}`, + }), + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// audit list [--limit=N] [--cursor=CURSOR] [--category=CAT] [--all] +// +// Default mode: one-shot fetch via `client.events.listAuditEntriesPage()`. +// `--all` mode: drives `client.events.iterAuditEntries()` and batches +// entries back into per-page JSON Lines / a flat human table. +// --------------------------------------------------------------------------- + +function renderAuditRows(entries: ReadonlyArray): { + columns: ReadonlyArray; + rows: ReadonlyArray>; +} { + return { + columns: ["occurredAt", "category", "eventType", "actor", "id"], + rows: entries.map((e) => ({ + occurredAt: e.occurredAt, + category: e.category, + eventType: e.eventType, + actor: `${e.actorType}:${e.actorId}`, + id: e.id, + })), + }; +} + +export async function auditListCommand(ctx: CommandContext): Promise { + const limit = parseLimit(ctx.flags["limit"]); + const cursorFlag = ctx.flags["cursor"]; + const cursor = typeof cursorFlag === "string" && cursorFlag.length > 0 ? cursorFlag : undefined; + const categoryFlag = ctx.flags["category"]; + const category = typeof categoryFlag === "string" && categoryFlag.length > 0 ? categoryFlag : undefined; + const all = ctx.flags["all"] === true; + const filters = parseAuditFilterFlags(ctx.flags); + + // Export mode: `--format=ndjson` streams the entire filtered stream as + // newline-delimited JSON (one PublicAuditEntry per line) via the SDK export + // helper. It walks every page, so `--cursor` (a single-page seek) is + // incompatible with it, just like `--all`. + const formatFlag = strFlag(ctx.flags["format"]); + if (formatFlag !== undefined && formatFlag !== "ndjson") { + throw new UsageError(`--format must be "ndjson" (got ${formatFlag})`); + } + const exportNdjson = formatFlag === "ndjson"; + + if (exportNdjson && cursor !== undefined) { + throw new UsageError("--format=ndjson and --cursor are mutually exclusive"); + } + if (all && cursor !== undefined) { + throw new UsageError("--all and --cursor are mutually exclusive"); + } + if (exportNdjson && all) { + throw new UsageError("--format=ndjson and --all are mutually exclusive"); + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const sdk = await ctx.sdk(); + + // Build the discriminated `by:"org"` query the SDK accepts. We never + // pass `cursor` here in --all mode (already validated above); in default + // mode we forward it verbatim. Filters are threaded into every mode. + function buildQuery(forCursor: string | undefined): ListAuditEntriesQuery { + return { + by: "org", + ...(category !== undefined ? { category } : {}), + ...filters, + ...(limit !== undefined ? { limit } : {}), + ...(forCursor !== undefined ? { cursor: forCursor } : {}), + }; + } + + if (exportNdjson) { + // Stream NDJSON straight to stdout, one line per entry. The SDK helper + // already terminates each line with "\n", so we write verbatim. + for await (const line of sdk.events.exportAuditEntriesNdjson(orgId, buildQuery(undefined))) { + ctx.stdout(line.endsWith("\n") ? line.slice(0, -1) : line); + } + return { exitCode: 0 }; + } + + if (!all) { + const page = await sdk.events.listAuditEntriesPage(orgId, buildQuery(cursor)); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + auditEntries: page.entries, + next_cursor: page.cursor, + }, + }), + ); + return { exitCode: 0 }; + } + const { columns, rows } = renderAuditRows(page.entries); + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows, + title: + `Audit entries for ${orgId}` + + (page.cursor !== null ? ` (next cursor: ${page.cursor})` : ""), + }), + ); + return { exitCode: 0 }; + } + + // --all: drive the SDK iterator, batching entries back into per-page + // groups for JSON Lines output. We can't observe page boundaries from a + // simple `for await (entry of iter)` loop, so we use the iterator + // protocol directly and ask `listAuditEntriesPage` for each page. + const allRows: Record[] = []; + let nextCursor: string | undefined = undefined; + let columns: ReadonlyArray = []; + let iterations = 0; + const seenCursors = new Set(); + + while (iterations < 1000) { + iterations += 1; + const page = await sdk.events.listAuditEntriesPage(orgId, buildQuery(nextCursor)); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + auditEntries: page.entries, + next_cursor: page.cursor, + }, + }), + ); + } else { + const rendered = renderAuditRows(page.entries); + columns = rendered.columns; + for (const row of rendered.rows) allRows.push(row); + } + if (page.cursor === null) break; + if (seenCursors.has(page.cursor)) { + throw new Error(`audit pagination loop detected at cursor ${page.cursor}`); + } + seenCursors.add(page.cursor); + nextCursor = page.cursor; + } + + if (ctx.outputMode === "human") { + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows: allRows, + title: `All audit entries for ${orgId} (${allRows.length} rows)`, + }), + ); + } + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/helpers.ts b/packages/cli/src/commands/helpers.ts new file mode 100644 index 0000000..998a2e6 --- /dev/null +++ b/packages/cli/src/commands/helpers.ts @@ -0,0 +1,61 @@ +// Shared CLI command helpers (Task 0111). +// +// This module exists to eliminate the inline duplication of org-id +// resolution and idempotency-key reading that grew across multiple +// command modules during the Task 0101–0110 write/rotate surface +// build-out. Both `writes.ts` (5× call sites across `org invite`, +// `project create`, `env create`, `api-key create`, `webhook create`) +// and `webhook-secrets-rotate.ts` (1× call site) had byte-equivalent +// copies of the `--idempotency-key` reader, plus near-equivalent +// org-id resolvers (the rotate variant was the no-override branch +// of the writes variant). The Task 0110 verifier flagged the +// duplication and recommended extracting a shared `cli-helpers` +// module before the next CLI write/rotate surface lands; this module +// is that extraction. +// +// Public surface is intentionally narrow: exactly two functions. +// `assertOutputModeValid` (currently inlined in +// `webhook-secrets-rotate.ts`) is deliberately NOT extracted here — +// it is single-call-site today and narrower in scope; defer until a +// second consumer appears. + +import type { CommandContext } from "../router.js"; +import { MissingOrgContextError } from "../errors.js"; + +/** + * Resolve the org id for a write/rotate command. Order: + * 1. Explicit `--org=ORG_ID` flag (only honoured when `allowOverride` + * is true — currently `org invite` is the sole consumer). + * 2. Persisted `activeOrgId` from `~/.config/new-test/config.json`. + * + * Throws `MissingOrgContextError` when neither is available. The CLI + * never silently picks a "first" org from the listing — that would let + * a user run a write against a different tenant than they expected. + */ +export async function resolveOrgId( + ctx: CommandContext, + allowOverride: boolean, +): Promise { + if (allowOverride) { + const flag = ctx.flags["org"]; + if (typeof flag === "string" && flag.length > 0) return flag; + } + const cliCtx = await ctx.contextStore.load(); + const orgId = cliCtx.activeOrgId; + if (orgId === undefined || orgId.length === 0) { + throw new MissingOrgContextError(); + } + return orgId; +} + +/** + * Pull `--idempotency-key=KEY` from flags. Returns `undefined` when the + * user did not pass the flag — the SDK will then omit the + * `Idempotency-Key` header. The CLI deliberately does not auto-generate + * one (Stripe parity); tests assert the verbatim passthrough and the + * no-header path. + */ +export function readIdempotencyKey(ctx: CommandContext): string | undefined { + const v = ctx.flags["idempotency-key"]; + return typeof v === "string" && v.length > 0 ? v : undefined; +} diff --git a/packages/cli/src/commands/index.ts b/packages/cli/src/commands/index.ts new file mode 100644 index 0000000..5067fd0 --- /dev/null +++ b/packages/cli/src/commands/index.ts @@ -0,0 +1,171 @@ +// Pilot read-only command handlers. +// +// Each handler is a thin adapter over the SDK + the output formatter. Per +// PR Boundary §3 this PR ships only: +// - login / logout / whoami (auth) +// - org list / org use / org members +// - project list +// +// Write commands (org invite, project create, env create, …) are Task 0101. + +import type { CommandContext, CommandResult } from "../router.js"; +import { formatOutput } from "../output/index.js"; +import { MissingOrgContextError, UsageError } from "../errors.js"; +import { loginFlow } from "../auth/login.js"; +import { whoamiFlow } from "../auth/whoami.js"; +import { logoutFlow } from "../auth/logout.js"; +import { readBearerTokenFromStdin } from "../prompt.js"; + +export async function loginCommand(ctx: CommandContext): Promise { + const apiUrlFlag = ctx.flags["api-url"]; + const tokenFlag = ctx.flags["token"]; + const apiUrl = typeof apiUrlFlag === "string" ? apiUrlFlag : undefined; + const token = typeof tokenFlag === "string" ? tokenFlag : undefined; + + await loginFlow({ + ...(apiUrl !== undefined ? { apiUrl } : {}), + ...(token !== undefined ? { token } : {}), + outputMode: ctx.outputMode, + tokenStore: ctx.tokenStore, + contextStore: ctx.contextStore, + stdout: ctx.stdout, + readToken: () => readBearerTokenFromStdin(), + }); + return { exitCode: 0 }; +} + +export async function logoutCommand(ctx: CommandContext): Promise { + await logoutFlow({ + outputMode: ctx.outputMode, + tokenStore: ctx.tokenStore, + contextStore: ctx.contextStore, + stdout: ctx.stdout, + }); + return { exitCode: 0 }; +} + +export async function whoamiCommand(ctx: CommandContext): Promise { + await whoamiFlow({ + outputMode: ctx.outputMode, + tokenStore: ctx.tokenStore, + contextStore: ctx.contextStore, + stdout: ctx.stdout, + }); + return { exitCode: 0 }; +} + +export async function orgListCommand(ctx: CommandContext): Promise { + const sdk = await ctx.sdk(); + const result = await sdk.organizations.list(); + const cliCtx = await ctx.contextStore.load(); + const active = cliCtx.activeOrgId ?? null; + + const rows = result.organizations.map((org) => ({ + active: org.id === active ? "*" : "", + id: org.id, + name: org.name, + slug: org.slug, + })); + + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + activeOrgId: active, + organizations: result.organizations, + }, + }), + ); + } else { + ctx.stdout( + formatOutput({ + mode: "human", + columns: ["active", "id", "name", "slug"], + rows, + }), + ); + } + + return { exitCode: 0 }; +} + +export async function orgUseCommand(ctx: CommandContext): Promise { + const orgId = ctx.args[0]; + if (orgId === undefined || orgId.length === 0) { + throw new UsageError("usage: new-test org use "); + } + // Validate the org exists by hitting the SDK; surface 404 as + // newtestError → friendly CLI message. + const sdk = await ctx.sdk(); + await sdk.organizations.get(orgId); + await ctx.contextStore.setActiveOrg(orgId); + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: { activeOrgId: orgId } })); + } else { + ctx.stdout(`✓ Active organization set to ${orgId}.`); + } + return { exitCode: 0 }; +} + +export async function orgMembersCommand(ctx: CommandContext): Promise { + const cliCtx = await ctx.contextStore.load(); + const orgId = cliCtx.activeOrgId; + if (orgId === undefined || orgId.length === 0) { + throw new MissingOrgContextError(); + } + const sdk = await ctx.sdk(); + const result = await sdk.memberships.listMembers(orgId); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: result })); + return { exitCode: 0 }; + } + + const rows = result.members.map((m) => ({ + id: m.id, + subject: `${m.subjectType}:${m.subjectId}`, + roles: m.roles.map((r) => r.role).join(","), + status: m.status, + })); + ctx.stdout( + formatOutput({ + mode: "human", + columns: ["id", "subject", "roles", "status"], + rows, + title: `Members of ${orgId}`, + }), + ); + return { exitCode: 0 }; +} + +export async function projectListCommand(ctx: CommandContext): Promise { + const cliCtx = await ctx.contextStore.load(); + const orgId = cliCtx.activeOrgId; + if (orgId === undefined || orgId.length === 0) { + throw new MissingOrgContextError(); + } + const sdk = await ctx.sdk(); + const result = await sdk.projects.list(orgId); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: result })); + return { exitCode: 0 }; + } + + const rows = result.projects.map((p) => ({ + id: p.id, + name: p.name, + slug: p.slug, + status: p.status, + })); + ctx.stdout( + formatOutput({ + mode: "human", + columns: ["id", "name", "slug", "status"], + rows, + title: `Projects in ${orgId}`, + }), + ); + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/integrations-token.ts b/packages/cli/src/commands/integrations-token.ts new file mode 100644 index 0000000..4735daf --- /dev/null +++ b/packages/cli/src/commands/integrations-token.ts @@ -0,0 +1,74 @@ +// `new-test integrations github token --repos=ID[,ID…] --permissions=key:level[,key:level…] [--org=ORG_ID]` +// +// CLI leg of the IG4 token broker: exchanges the caller's control-plane +// credential for a short-lived, repo-scoped GitHub installation token. +// The token prints exactly once (or as JSON) — it is never stored. + +import type { CommandContext, CommandResult } from "../router.js"; +import { formatOutput } from "../output/index.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId } from "./helpers.js"; + +function parseRepos(flag: unknown): string[] { + if (typeof flag !== "string" || !flag.trim()) { + throw new UsageError("--repos is required (comma-separated provider repository ids)"); + } + const repos = flag + .split(",") + .map((r) => r.trim()) + .filter(Boolean); + if (repos.length === 0) throw new UsageError("--repos must name at least one repository id"); + return repos; +} + +function parsePermissions(flag: unknown): Record { + if (typeof flag !== "string" || !flag.trim()) { + throw new UsageError('--permissions is required, e.g. --permissions=contents:read,checks:write'); + } + const permissions: Record = {}; + for (const entry of flag.split(",")) { + const [key, level] = entry.split(":").map((p) => p.trim()); + if (!key || (level !== "read" && level !== "write")) { + throw new UsageError(`Invalid permission "${entry}" — use key:read or key:write`); + } + permissions[key] = level; + } + return permissions; +} + +export async function integrationsGithubTokenCommand( + ctx: CommandContext, +): Promise { + const repositories = parseRepos(ctx.flags["repos"]); + const permissions = parsePermissions(ctx.flags["permissions"]); + + const orgId = await resolveOrgId(ctx, true); + const client = await ctx.sdk(); + const result = await client.integrations.issueGithubToken(orgId, { + repositories, + permissions, + }); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: result })); + return { exitCode: 0 }; + } + ctx.stdout( + formatOutput({ + mode: "human", + title: `GitHub installation token (expires ${result.expiresAt})`, + columns: ["field", "value"], + rows: [ + { field: "token", value: result.token }, + { field: "repositories", value: result.repositories.join(", ") }, + { + field: "permissions", + value: Object.entries(result.permissions) + .map(([k, v]) => `${k}:${v}`) + .join(", "), + }, + ], + }), + ); + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/notification-preferences.ts b/packages/cli/src/commands/notification-preferences.ts new file mode 100644 index 0000000..2bd4ad9 --- /dev/null +++ b/packages/cli/src/commands/notification-preferences.ts @@ -0,0 +1,112 @@ +// `new-test notifications preferences [--org=ORG_ID]` +// `new-test notifications preferences set --category=CAT --enabled=true|false [--org=ORG_ID]` +// +// CLI leg of the PX3 notification-preferences surface (parity with the +// console settings page and a pure SDK consumer of +// `client.notifications.getPreferences` / `updatePreferences`). +// +// Subject scope: the api-edge facade pins `subjectKind`/`subjectId` to the +// bearer's actor, so these commands read/update the CALLER's own per-org +// email preferences. The `subjectId` sent on `set` is resolved from +// `client.auth.getProfile()` (the facade would override a forged one anyway). +// +// Semantics mirror the worker's opt-out model: a missing row or category +// means "deliver"; only explicit `false` suppresses a category. + +import type { + NotificationCategory, + NotificationCategoryPreferences, +} from "@saas/sdk"; +import type { CommandContext, CommandResult } from "../router.js"; +import { formatOutput } from "../output/index.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId } from "./helpers.js"; + +const CATEGORIES: NotificationCategory[] = [ + "invitation", + "billing", + "security", + "support", + "product", +]; + +function effective(categories: NotificationCategoryPreferences | undefined): Record { + const out: Record = {}; + for (const c of CATEGORIES) out[c] = categories?.[c] !== false; + return out; +} + +export async function notificationPreferencesGetCommand( + ctx: CommandContext, +): Promise { + const orgId = await resolveOrgId(ctx, true); + const client = await ctx.sdk(); + const { preferences } = await client.notifications.getPreferences({ orgId }); + const row = preferences.find((p) => p.channel === "email"); + const state = effective(row?.categories); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: { orgId, channel: "email", categories: state } })); + return { exitCode: 0 }; + } + ctx.stdout( + formatOutput({ + mode: "human", + title: `Email notification preferences (org ${orgId})`, + columns: ["category", "enabled"], + rows: CATEGORIES.map((c) => ({ category: c, enabled: String(state[c]) })), + }), + ); + return { exitCode: 0 }; +} + +export async function notificationPreferencesSetCommand( + ctx: CommandContext, +): Promise { + const categoryFlag = ctx.flags["category"]; + const enabledFlag = ctx.flags["enabled"]; + if (typeof categoryFlag !== "string" || !CATEGORIES.includes(categoryFlag as NotificationCategory)) { + throw new UsageError(`--category must be one of: ${CATEGORIES.join(", ")}`); + } + if (enabledFlag !== "true" && enabledFlag !== "false") { + throw new UsageError(`--enabled must be "true" or "false"`); + } + const category = categoryFlag as NotificationCategory; + const enabled = enabledFlag === "true"; + + const orgId = await resolveOrgId(ctx, true); + const client = await ctx.sdk(); + + const [{ preferences }, { user }] = await Promise.all([ + client.notifications.getPreferences({ orgId }), + client.auth.getProfile(), + ]); + const row = preferences.find((p) => p.channel === "email"); + const current = effective(row?.categories); + + const categories: NotificationCategoryPreferences = {}; + for (const c of CATEGORIES) categories[c] = c === category ? enabled : (current[c] as boolean); + + const { preference } = await client.notifications.updatePreferences({ + orgId, + subjectKind: "user", + subjectId: user.id, + channel: "email", + categories, + }); + + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: { preference } })); + return { exitCode: 0 }; + } + const state = effective(preference.categories); + ctx.stdout( + formatOutput({ + mode: "human", + title: `Updated: ${category} → ${enabled ? "enabled" : "disabled"}`, + columns: ["category", "enabled"], + rows: CATEGORIES.map((c) => ({ category: c, enabled: String(state[c]) })), + }), + ); + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/security-events.ts b/packages/cli/src/commands/security-events.ts new file mode 100644 index 0000000..49d8546 --- /dev/null +++ b/packages/cli/src/commands/security-events.ts @@ -0,0 +1,208 @@ +// `new-test security events [--limit=N] [--cursor=CURSOR] [--all]` +// [--output=human|json] — Task 0122, milestone B7-security-events-surfaces. +// +// The CLI leg of the account security-events observability surface. Symmetric +// to the Task 0122 console security page and a pure SDK consumer of the +// `client.securityEvents.listPage` shape (Task 0122 SDK addition). +// +// Pagination mirrors `webhook deliveries` (webhook-deliveries.ts) / `audit +// list` (cross-reads.ts) exactly, which are the established cursor-pagination +// prior-art in this CLI: +// +// - Default mode: one-shot fetch of a single page via `listPage(query)`. +// JSON output emits `{ securityEvents, next_cursor }`; human mode prints a +// compact table (eventType / outcome / occurredAt / ip / userAgent / id) +// with the next cursor appended to the title when more pages remain. +// +// - `--all` mode: drives the same page method in a loop, following the +// server-issued cursor until it returns null. JSON mode emits one JSON +// document per page (JSON Lines); human mode concatenates rows under a +// single header. A seen-cursor guard aborts on a pagination loop. +// +// CRITICAL — actor scope: this surface is account/actor-scoped (backed by +// `apps/identity-worker` via the api-edge `auth-facade`), NOT org-scoped. +// There is NO `--org` flag and NO `resolveOrgId` call — the request is scoped +// entirely by the bearer credential's actor. +// +// CRITICAL — cursor provenance: the identity-worker emits the continuation +// cursor as an opaque token in `meta.cursor`. The SDK's `listPage` already +// surfaces it as `page.nextCursor`. The cursor is opaque: it is forwarded +// verbatim and never constructed or parsed here. +// +// There is no network, header building, or auth handling in this module — all +// of that lives behind the SDK transport. The command is read-only and never +// sends an Idempotency-Key. +// +// Errors: +// - `--limit` non-positive-integer → `UsageError`, exit 2. +// - `--all` together with `--cursor` → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (4xx/5xx) → propagated through the existing `formatCliError` +// path; the response is never `.toString()`'d or interpolated. + +import type { CommandContext, CommandResult } from "../router.js"; +import type { + PublicSecurityEvent, + ListSecurityEventsQuery, +} from "@saas/sdk"; +import { UsageError } from "../errors.js"; +import { formatOutput } from "../output/index.js"; + +// Defensive cap on the --all loop, mirroring `webhook deliveries` / `audit +// list` (1000 pages). Bounds a single invocation while still guaranteeing +// termination if the server ever misbehaves on the cursor contract. +const MAX_PAGES = 1000; + +function parseLimit(flag: string | boolean | undefined): number | undefined { + if (typeof flag !== "string" || flag.length === 0) return undefined; + const n = Number.parseInt(flag, 10); + if (!Number.isFinite(n) || n <= 0) { + throw new UsageError(`--limit must be a positive integer (got ${flag})`); + } + return n; +} + +/** + * Validate `--output=human|json`. The runner already coerces `output` into + * `ctx.outputMode` (defaulting unknown values to `human`), but we gate the raw + * flag here so the user gets a clean `UsageError` for typos like + * `--output=yaml`. Mirrors `webhook deliveries` with the `security events:` + * subcommand prefix. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("security events: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `security events: --output must be human or json, got: ${raw}`, + ); + } +} + +function renderSecurityRows(events: ReadonlyArray): { + columns: ReadonlyArray; + rows: ReadonlyArray>; +} { + return { + columns: ["eventType", "outcome", "occurredAt", "ip", "userAgent", "id"], + rows: events.map((e) => ({ + eventType: e.eventType, + outcome: e.outcome, + occurredAt: e.occurredAt, + ip: e.ip ?? "-", + userAgent: e.userAgent ?? "-", + id: e.id, + })), + }; +} + +export async function securityEventsCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const limit = parseLimit(ctx.flags["limit"]); + const cursorFlag = ctx.flags["cursor"]; + const cursor = + typeof cursorFlag === "string" && cursorFlag.length > 0 + ? cursorFlag + : undefined; + const all = ctx.flags["all"] === true; + + if (all && cursor !== undefined) { + throw new UsageError("--all and --cursor are mutually exclusive"); + } + + const sdk = await ctx.sdk(); + + // Build the SDK query. `cursor` is forwarded verbatim (opaque). In --all + // mode we never pass the user's `cursor` (already rejected above) — the loop + // supplies its own server-issued cursor each iteration. + function buildQuery(forCursor: string | undefined): ListSecurityEventsQuery { + return { + ...(limit !== undefined ? { limit } : {}), + ...(forCursor !== undefined ? { cursor: forCursor } : {}), + }; + } + + if (!all) { + const page = await sdk.securityEvents.listPage(buildQuery(cursor)); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + securityEvents: page.securityEvents, + next_cursor: page.nextCursor, + }, + }), + ); + return { exitCode: 0 }; + } + const { columns, rows } = renderSecurityRows(page.securityEvents); + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows, + title: + "Security events" + + (page.nextCursor !== null + ? ` (next cursor: ${page.nextCursor})` + : ""), + }), + ); + return { exitCode: 0 }; + } + + // --all: follow the server-issued cursor until it returns null, batching + // rows back into per-page JSON Lines (json) or one flat table (human). + const allRows: Record[] = []; + let nextCursor: string | undefined = undefined; + let columns: ReadonlyArray = []; + let iterations = 0; + const seenCursors = new Set(); + + while (iterations < MAX_PAGES) { + iterations += 1; + const page = await sdk.securityEvents.listPage(buildQuery(nextCursor)); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + securityEvents: page.securityEvents, + next_cursor: page.nextCursor, + }, + }), + ); + } else { + const rendered = renderSecurityRows(page.securityEvents); + columns = rendered.columns; + for (const row of rendered.rows) allRows.push(row); + } + if (page.nextCursor === null) break; + if (seenCursors.has(page.nextCursor)) { + throw new Error( + `security-events pagination loop detected at cursor ${page.nextCursor}`, + ); + } + seenCursors.add(page.nextCursor); + nextCursor = page.nextCursor; + } + + if (ctx.outputMode === "human") { + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows: allRows, + title: `All security events (${allRows.length} rows)`, + }), + ); + } + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-deliveries-replay.ts b/packages/cli/src/commands/webhook-deliveries-replay.ts new file mode 100644 index 0000000..2218c56 --- /dev/null +++ b/packages/cli/src/commands/webhook-deliveries-replay.ts @@ -0,0 +1,110 @@ +// `new-test webhook deliveries replay [--output=human|json]` +// — Task 0126, milestone B5-webhook-delivery-replay. +// +// The CLI leg of manual webhook delivery replay. Re-sends the SAME event to the +// SAME endpoint through the existing signing/delivery seam, recording a fresh +// delivery attempt in history. Pure SDK consumer of the locked +// `client.webhooks.replayDelivery(orgId, attemptId)` shape (Task 0126 SDK +// addition) — symmetric to the console "Redeliver" action. +// +// Unlike the read-only `webhook deliveries` listing, this is a MUTATING command +// (it triggers an outbound delivery), so the SDK transport attaches an +// idempotency key when one is supplied via `--idempotency-key=KEY`, mirroring +// `webhook enable` / `webhook disable`. +// +// Org id is resolved through the persisted active-org context (no `--org` +// override — mirrors the rest of the webhook CLI surface via +// `resolveOrgId(ctx, /* allowOverride */ false)`). There is no network, header +// building, or auth handling in this module — all of that lives behind the SDK +// transport. +// +// Output: +// - human: a one-row summary of the NEW attempt (status / eventType / +// attempt / http / id) so the operator can see the replay outcome inline. +// - json: the raw `{ deliveryAttempt }` response object. +// +// Errors: +// - missing positional `` → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (404 missing/cross-org, 5xx) → propagated through the existing +// `formatCliError` path; the response is never `.toString()`'d. + +import type { CommandContext, CommandResult } from "../router.js"; +import type { PublicWebhookDeliveryAttempt } from "@saas/sdk"; +import { UsageError } from "../errors.js"; +import { resolveOrgId } from "./helpers.js"; +import { formatOutput } from "../output/index.js"; + +/** + * Validate `--output=human|json`. Mirrors the `webhook deliveries` gate with + * the `webhook deliveries replay:` subcommand prefix. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("webhook deliveries replay: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `webhook deliveries replay: --output must be human or json, got: ${raw}`, + ); + } +} + +function renderAttemptRow(attempt: PublicWebhookDeliveryAttempt): { + columns: ReadonlyArray; + rows: ReadonlyArray>; +} { + return { + columns: ["status", "eventType", "attempt", "http", "id"], + rows: [ + { + status: attempt.status, + eventType: attempt.eventType, + attempt: String(attempt.attemptNumber), + http: attempt.httpStatusCode === null ? "-" : String(attempt.httpStatusCode), + id: attempt.id, + }, + ], + }; +} + +export async function webhookDeliveriesReplayCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const attemptId = ctx.args[0]; + if (attemptId === undefined || attemptId.length === 0) { + throw new UsageError( + "usage: new-test webhook deliveries replay [--output=human|json]", + ); + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const sdk = await ctx.sdk(); + + const response = await sdk.webhooks.replayDelivery(orgId, attemptId); + + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { deliveryAttempt: response.deliveryAttempt }, + }), + ); + return { exitCode: 0 }; + } + + const { columns, rows } = renderAttemptRow(response.deliveryAttempt); + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows, + title: `Replayed delivery for attempt ${attemptId} → new attempt ${response.deliveryAttempt.id}`, + }), + ); + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-deliveries.ts b/packages/cli/src/commands/webhook-deliveries.ts new file mode 100644 index 0000000..8d040c2 --- /dev/null +++ b/packages/cli/src/commands/webhook-deliveries.ts @@ -0,0 +1,229 @@ +// `new-test webhook deliveries [--limit=N] [--cursor=CURSOR] [--all]` +// [--output=human|json] — Task 0120, milestone B5-webhook-delivery-history. +// +// The CLI leg of the per-endpoint webhook delivery-history observability +// surface. Symmetric to the Task 0120 console delivery-history panel and a +// pure SDK consumer of the locked `client.webhooks.listDeliveryAttemptsPage` +// shape (Task 0120 SDK addition). +// +// Pagination mirrors `audit list` (cross-reads.ts) exactly, which is the +// established cursor-pagination prior-art in this CLI: +// +// - Default mode: one-shot fetch of a single page via +// `listDeliveryAttemptsPage(orgId, endpointId, query)`. JSON output emits +// `{ deliveryAttempts, next_cursor }`; human mode prints a compact table +// (status / eventType / attempt / http / completedAt / id) with the next +// cursor appended to the title when more pages remain. +// +// - `--all` mode: drives the same page method in a loop, following the +// server-issued cursor until it returns null. JSON mode emits one JSON +// document per page (JSON Lines); human mode concatenates rows under a +// single header. A seen-cursor guard aborts on a pagination loop. +// +// CRITICAL — cursor provenance: the webhooks-worker emits the continuation +// cursor as an opaque base64 token in `meta.cursor` (NOT the vestigial body +// `nextCursor`). The SDK's `listDeliveryAttemptsPage` already surfaces it as +// `page.nextCursor`. The cursor is opaque: it is forwarded verbatim and never +// constructed or parsed here. +// +// Org id is resolved through the persisted active-org context (no `--org` +// override — mirrors the rest of the webhook CLI surface via +// `resolveOrgId(ctx, /* allowOverride */ false)`). There is no network, +// header building, or auth handling in this module — all of that lives behind +// the SDK transport. The command is read-only and never sends an +// Idempotency-Key. +// +// Errors: +// - missing positional `` → `UsageError`, exit 2. +// - `--limit` non-positive-integer → `UsageError`, exit 2. +// - `--all` together with `--cursor` → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (4xx/5xx) → propagated through the existing `formatCliError` +// path; the response is never `.toString()`'d or interpolated. + +import type { CommandContext, CommandResult } from "../router.js"; +import type { + PublicWebhookDeliveryAttempt, + ListDeliveryAttemptsQuery, +} from "@saas/sdk"; +import { UsageError } from "../errors.js"; +import { resolveOrgId } from "./helpers.js"; +import { formatOutput } from "../output/index.js"; + +// Defensive cap on the --all loop, mirroring `audit list` (1000 pages). At the +// server-max page size of 100 this bounds a single invocation to 100k rows — +// far beyond any realistic delivery-history scan, while still guaranteeing +// termination if the server ever misbehaves on the cursor contract. +const MAX_PAGES = 1000; + +function parseLimit(flag: string | boolean | undefined): number | undefined { + if (typeof flag !== "string" || flag.length === 0) return undefined; + const n = Number.parseInt(flag, 10); + if (!Number.isFinite(n) || n <= 0) { + throw new UsageError(`--limit must be a positive integer (got ${flag})`); + } + return n; +} + +/** + * Validate `--output=human|json`. The runner already coerces `output` into + * `ctx.outputMode` (defaulting unknown values to `human`), but we gate the raw + * flag here so the user gets a clean `UsageError` for typos like + * `--output=yaml`. Mirrors the `webhook disable` gate with the + * `webhook deliveries:` subcommand prefix. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("webhook deliveries: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `webhook deliveries: --output must be human or json, got: ${raw}`, + ); + } +} + +function renderDeliveryRows( + attempts: ReadonlyArray, +): { + columns: ReadonlyArray; + rows: ReadonlyArray>; +} { + return { + columns: ["status", "eventType", "attempt", "http", "completedAt", "id"], + rows: attempts.map((a) => ({ + status: a.status, + eventType: a.eventType, + attempt: String(a.attemptNumber), + http: a.httpStatusCode === null ? "-" : String(a.httpStatusCode), + completedAt: a.completedAt ?? "-", + id: a.id, + })), + }; +} + +export async function webhookDeliveriesCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const endpointId = ctx.args[0]; + if (endpointId === undefined || endpointId.length === 0) { + throw new UsageError( + "usage: new-test webhook deliveries [--limit=N] [--cursor=CURSOR] [--all] [--output=human|json]", + ); + } + + const limit = parseLimit(ctx.flags["limit"]); + const cursorFlag = ctx.flags["cursor"]; + const cursor = + typeof cursorFlag === "string" && cursorFlag.length > 0 + ? cursorFlag + : undefined; + const all = ctx.flags["all"] === true; + + if (all && cursor !== undefined) { + throw new UsageError("--all and --cursor are mutually exclusive"); + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const sdk = await ctx.sdk(); + + // Build the SDK query. `cursor` is forwarded verbatim (opaque). In --all + // mode we never pass the user's `cursor` (already rejected above) — the loop + // supplies its own server-issued cursor each iteration. + function buildQuery(forCursor: string | undefined): ListDeliveryAttemptsQuery { + return { + ...(limit !== undefined ? { limit } : {}), + ...(forCursor !== undefined ? { cursor: forCursor } : {}), + }; + } + + if (!all) { + const page = await sdk.webhooks.listDeliveryAttemptsPage( + orgId, + endpointId, + buildQuery(cursor), + ); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + deliveryAttempts: page.deliveryAttempts, + next_cursor: page.nextCursor, + }, + }), + ); + return { exitCode: 0 }; + } + const { columns, rows } = renderDeliveryRows(page.deliveryAttempts); + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows, + title: + `Delivery attempts for ${endpointId} in ${orgId}` + + (page.nextCursor !== null + ? ` (next cursor: ${page.nextCursor})` + : ""), + }), + ); + return { exitCode: 0 }; + } + + // --all: follow the server-issued cursor until it returns null, batching + // rows back into per-page JSON Lines (json) or one flat table (human). + const allRows: Record[] = []; + let nextCursor: string | undefined = undefined; + let columns: ReadonlyArray = []; + let iterations = 0; + const seenCursors = new Set(); + + while (iterations < MAX_PAGES) { + iterations += 1; + const page = await sdk.webhooks.listDeliveryAttemptsPage( + orgId, + endpointId, + buildQuery(nextCursor), + ); + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { + deliveryAttempts: page.deliveryAttempts, + next_cursor: page.nextCursor, + }, + }), + ); + } else { + const rendered = renderDeliveryRows(page.deliveryAttempts); + columns = rendered.columns; + for (const row of rendered.rows) allRows.push(row); + } + if (page.nextCursor === null) break; + if (seenCursors.has(page.nextCursor)) { + throw new Error( + `delivery-history pagination loop detected at cursor ${page.nextCursor}`, + ); + } + seenCursors.add(page.nextCursor); + nextCursor = page.nextCursor; + } + + if (ctx.outputMode === "human") { + ctx.stdout( + formatOutput({ + mode: "human", + columns, + rows: allRows, + title: `All delivery attempts for ${endpointId} in ${orgId} (${allRows.length} rows)`, + }), + ); + } + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-disable.ts b/packages/cli/src/commands/webhook-disable.ts new file mode 100644 index 0000000..283dad3 --- /dev/null +++ b/packages/cli/src/commands/webhook-disable.ts @@ -0,0 +1,135 @@ +// `new-test webhook disable [--reason=TEXT]` — Task 0115. +// +// Symmetric CLI surface to the Task 0113-era console disable-endpoint +// dialog. Closes the final B5 endpoint-CRUD CLI gap (disable), making +// CLI endpoint-CRUD symmetric with console end-to-end and matching the +// established webhook CLI cadence: +// 0103 (webhook create) → 0107 (verify / sign) → 0110 (secrets rotate) +// → 0111 (cli helpers extraction) → 0114 (webhook enable) +// → 0115 (this disable subcommand). +// +// The command is a pure SDK consumer of the locked +// `client.webhooks.disableEndpoint` shape. It resolves the active org, +// issues exactly one SDK call, prints the disabled endpoint's salient +// fields, and exits 0. There is no network, header building, or auth +// handling in this module — all of that lives behind the SDK transport. +// +// Org id is resolved through the persisted active-org context (no +// `--org` override — mirrors `webhook enable` / `webhook secrets rotate` +// semantics via `resolveOrgId(ctx, /* allowOverride */ false)`). The +// CLI never auto-mints an `Idempotency-Key`: `--idempotency-key=KEY` is +// forwarded verbatim when supplied, omitted when absent. +// +// Unlike enable, the disable contract carries an optional operator- +// supplied reason (`DisableWebhookEndpointRequest = { reason?: string }`). +// `--reason=TEXT` is forwarded verbatim into the request body when +// supplied; absent → body is `{}`. A bare boolean `--reason` (no value) +// is rejected with `UsageError`. An explicitly empty string is forwarded +// as-is; the worker decides what to do with it. +// +// The disable response carries no secret material — the human block is +// `status` / `disabledReason` / `disabledAt` / `updatedAt` (4 lines vs +// enable's 3, the only intentional human-block divergence from 0114). +// +// Output: +// - human (default): a header line plus an indented key/value block +// (status / disabledReason / disabledAt / updatedAt). +// - json: the SDK response shape verbatim, single-line. +// +// Errors: +// - missing positional `` → `UsageError`, exit 2. +// - bare `--reason` (no value) → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (4xx/5xx) → propagated through the existing +// `formatCliError` path. The response is never `.toString()`'d or +// interpolated into any error branch. + +import type { CommandContext, CommandResult } from "../router.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId, readIdempotencyKey } from "./helpers.js"; + +// Org-id resolution and `--idempotency-key=KEY` reading are imported +// from `./helpers.js` (Task 0111 extraction). Use the no-override +// variant — `resolveOrgId(ctx, /* allowOverride */ false)` — to mirror +// `webhook enable`: the persisted active-org context is the only +// source, no `--org` flag plumbing on disable. + +/** + * Validate `--output=human|json`. The runner already coerces `output` + * into `ctx.outputMode` (defaulting unknown values to `human`), but we + * gate the raw flag here so the user gets a clean `UsageError` for + * typos like `--output=yaml` rather than a silently-wrong human-mode + * render. Mirrors the `webhook enable` gate exactly, with the + * `webhook disable:` subcommand prefix. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("webhook disable: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `webhook disable: --output must be human or json, got: ${raw}`, + ); + } +} + +export async function webhookDisableCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const endpointId = ctx.args[0]; + if (endpointId === undefined || endpointId.length === 0) { + throw new UsageError( + "usage: new-test webhook disable [--reason=TEXT] [--idempotency-key=KEY] [--output=human|json]", + ); + } + + // `--reason=TEXT` → body `{ reason }`; absent → body `{}`. A bare + // boolean `--reason` (no value) is a usage error: forwarding the + // literal `true` would either confuse the worker or be silently + // coerced. An explicitly empty string is forwarded as-is — let the + // worker decide whether to accept it. + const rawReason = ctx.flags["reason"]; + let body: { reason?: string } = {}; + if (rawReason === true) { + throw new UsageError("webhook disable: --reason requires a value"); + } + if (typeof rawReason === "string") { + body = { reason: rawReason }; + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const response = await sdk.webhooks.disableEndpoint( + orgId, + endpointId, + body, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + + if (ctx.outputMode === "json") { + ctx.stdout(JSON.stringify(response)); + return { exitCode: 0 }; + } + + // Human mode. Disable carries no secret material; the block surfaces + // the four operator-relevant fields: status (now "disabled"), the + // disabledReason worker-applied (operator-supplied or default), + // disabledAt (newly populated), and the touched updatedAt. The + // header reuses the worker-side audit phrasing for cross-surface + // consistency with the console dialog. + const endpoint = response.endpoint; + ctx.stdout(`Webhook endpoint disabled: ${endpointId} in ${orgId}`); + ctx.stdout(""); + ctx.stdout(` status: ${endpoint.status}`); + ctx.stdout(` disabledReason: ${endpoint.disabledReason}`); + ctx.stdout(` disabledAt: ${endpoint.disabledAt}`); + ctx.stdout(` updatedAt: ${endpoint.updatedAt}`); + + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-enable.ts b/packages/cli/src/commands/webhook-enable.ts new file mode 100644 index 0000000..7333e0d --- /dev/null +++ b/packages/cli/src/commands/webhook-enable.ts @@ -0,0 +1,110 @@ +// `new-test webhook enable ` — Task 0114. +// +// Symmetric CLI surface to the Task 0113 console "Re-enable" button + +// enable-endpoint dialog. Closes the B5 endpoint-CRUD CLI gap for the +// re-enable surface, matching the established webhook CLI cadence: +// 0103 (webhook create) → 0107 (verify / sign) → 0110 (secrets rotate) +// → 0111 (cli helpers extraction) → 0114 (this re-enable subcommand). +// +// The command is a pure SDK consumer of the locked +// `client.webhooks.enableEndpoint` shape (Task 0113). It resolves the +// active org, issues exactly one SDK call, prints the re-enabled +// endpoint's salient fields, and exits 0. There is no network, header +// building, or auth handling in this module — all of that lives behind +// the SDK transport. +// +// Org id is resolved through the persisted active-org context (no +// `--org` override — mirrors `webhook secrets rotate` semantics via +// `resolveOrgId(ctx, /* allowOverride */ false)`). The CLI never +// auto-mints an `Idempotency-Key`: `--idempotency-key=KEY` is forwarded +// verbatim when supplied, omitted when absent. +// +// Unlike rotate, the enable response carries NO secret material — the +// `EnableWebhookEndpointResponse` is `{ endpoint }` only. The human +// block is therefore minimal (status / secretVersion / updatedAt) and +// there is no reveal-once warning. +// +// Output: +// - human (default): a header line plus an indented key/value block +// (status / secretVersion / updatedAt). +// - json: the SDK response shape verbatim, single-line. +// +// Errors: +// - missing positional `` → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (4xx/5xx) → propagated through the existing +// `formatCliError` path. The response is never `.toString()`'d or +// interpolated into any error branch. + +import type { CommandContext, CommandResult } from "../router.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId, readIdempotencyKey } from "./helpers.js"; + +// Org-id resolution and `--idempotency-key=KEY` reading are imported +// from `./helpers.js` (Task 0111 extraction). Use the no-override +// variant — `resolveOrgId(ctx, /* allowOverride */ false)` — to mirror +// `webhook secrets rotate`: the persisted active-org context is the +// only source, no `--org` flag plumbing on enable. + +/** + * Validate `--output=human|json`. The runner already coerces `output` + * into `ctx.outputMode` (defaulting unknown values to `human`), but we + * gate the raw flag here so the user gets a clean `UsageError` for + * typos like `--output=yaml` rather than a silently-wrong human-mode + * render. Mirrors the `webhook secrets rotate` gate exactly, with the + * `webhook enable:` subcommand prefix. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("webhook enable: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `webhook enable: --output must be human or json, got: ${raw}`, + ); + } +} + +export async function webhookEnableCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const endpointId = ctx.args[0]; + if (endpointId === undefined || endpointId.length === 0) { + throw new UsageError( + "usage: new-test webhook enable [--idempotency-key=KEY] [--output=human|json]", + ); + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const response = await sdk.webhooks.enableEndpoint( + orgId, + endpointId, + {}, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + + if (ctx.outputMode === "json") { + ctx.stdout(JSON.stringify(response)); + return { exitCode: 0 }; + } + + // Human mode. Re-enable carries no secret material, so the block is + // intentionally minimal: status / secretVersion / updatedAt. The + // header reuses the worker-side audit phrasing ("Webhook endpoint + // re-enabled") for cross-surface consistency with the console dialog. + const endpoint = response.endpoint; + ctx.stdout(`Webhook endpoint re-enabled: ${endpointId} in ${orgId}`); + ctx.stdout(""); + ctx.stdout(` status: ${endpoint.status}`); + ctx.stdout(` secretVersion: ${endpoint.secretVersion}`); + ctx.stdout(` updatedAt: ${endpoint.updatedAt}`); + + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-secrets-rotate.ts b/packages/cli/src/commands/webhook-secrets-rotate.ts new file mode 100644 index 0000000..d9dcd40 --- /dev/null +++ b/packages/cli/src/commands/webhook-secrets-rotate.ts @@ -0,0 +1,141 @@ +// `new-test webhook secrets rotate ` — Task 0110. +// +// Symmetric CLI surface to the Task 0109 console reveal-once rotate UX. +// Closes the B5 secret-rotation arc: +// 0108 (backend dual-secret grace) → 0109 (console reveal-once modal) +// → 0110 (this CLI subcommand). +// +// The command is a pure SDK consumer of the locked +// `client.webhooks.rotateSecret` shape. It calls the SDK, prints the +// reveal-once plaintext when present (exactly once), and exits 0. The +// plaintext returned by the API is never persisted, never logged, +// never interpolated into a wider object — it flows from the SDK +// response straight to a single `ctx.stdout(...)` call site. +// +// Subcommand path is the durable three-segment plural form +// `["webhook", "secrets", "rotate"]`. This leaves room for future +// `webhook secrets list/reveal/revoke` without a rename and matches the +// `client.webhooks.rotateSecret` SDK semantics. +// +// Org id is resolved through the persisted active-org context (no +// `--org` override — mirrors `webhook create` in `writes.ts`). The CLI +// never auto-mints an `Idempotency-Key`: `--idempotency-key=KEY` is +// forwarded verbatim when supplied, omitted when absent. +// +// Output: +// - human (default): a header line, an indented key/value block (with +// the secret line elided when the server did not return plaintext), +// and a reveal-once warning. +// - json: the SDK response shape verbatim, single-line. When the +// server returned no plaintext the `secret` key is absent from the +// emitted JSON (matches the optional contract shape — we do NOT +// serialise `"secret": null`). +// +// Errors: +// - missing positional `` → `UsageError`, exit 2. +// - `--output=invalid` → `UsageError`, exit 2. +// - SDK error (4xx/5xx) → propagated through the existing +// `formatCliError` path; the secret cannot be present on an error +// branch, but we never `.toString()` or interpolate the response +// into any error path either — defence in depth. + +import type { CommandContext, CommandResult } from "../router.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId, readIdempotencyKey } from "./helpers.js"; + +// Org-id resolution and `--idempotency-key=KEY` reading are imported +// from `./helpers.js` (Task 0111 extraction). Use the no-override +// variant — `resolveOrgId(ctx, /* allowOverride */ false)` — to mirror +// `webhook create` semantics: the persisted active-org context is the +// only source, no `--org` flag plumbing on rotate. + +/** + * Validate `--output=human|json`. The runner already coerces `output` + * into `ctx.outputMode` (defaulting unknown values to `human`), but we + * gate the raw flag here so the user gets a clean `UsageError` for + * typos like `--output=yaml` rather than a silently-wrong human-mode + * render. + */ +function assertOutputModeValid(ctx: CommandContext): void { + const raw = ctx.flags["output"]; + if (raw === undefined || raw === false) return; + if (raw === true) { + throw new UsageError("webhook secrets rotate: --output requires human|json"); + } + if (raw !== "human" && raw !== "json") { + throw new UsageError( + `webhook secrets rotate: --output must be human or json, got: ${raw}`, + ); + } +} + +export async function webhookSecretsRotateCommand( + ctx: CommandContext, +): Promise { + assertOutputModeValid(ctx); + + const endpointId = ctx.args[0]; + if (endpointId === undefined || endpointId.length === 0) { + throw new UsageError( + "usage: new-test webhook secrets rotate [--idempotency-key=KEY] [--output=human|json]", + ); + } + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const response = await sdk.webhooks.rotateSecret( + orgId, + endpointId, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + + if (ctx.outputMode === "json") { + // Single stdout write, full response. `JSON.stringify` drops + // optional fields that are `undefined`, so an absent `secret` is + // naturally omitted from the JSON envelope (matches the contract). + ctx.stdout(JSON.stringify(response)); + return { exitCode: 0 }; + } + + // Human mode. + ctx.stdout(`Webhook signing secret rotated for ${endpointId} in ${orgId}`); + ctx.stdout(""); + + // The reveal-once plaintext is read from the SDK response exactly + // once (the destructure below) and written to stdout exactly once + // (the `secret:` line a few lines down). It is not interpolated + // into any other object, log line, or error path. + const secretPlaintext = response.secret; + const hasPlaintext = secretPlaintext !== undefined; + + if (hasPlaintext) { + ctx.stdout(` secret: ${secretPlaintext} \u2190 reveal-once, copy now`); + } + ctx.stdout(` secretVersion: ${response.endpoint.secretVersion}`); + ctx.stdout( + ` previousExpires: ${response.previousSecretExpiresAt ?? "(none)"}`, + ); + ctx.stdout(` gracePeriod: ${response.gracePeriodSeconds}s`); + ctx.stdout(""); + + if (hasPlaintext) { + ctx.stdout( + "\u26A0 This secret will not be shown again. Subscribers using the previous", + ); + ctx.stdout( + " secret have until previousExpires to roll over via the", + ); + ctx.stdout(" X-Webhook-Signature-Previous header."); + } else { + ctx.stdout( + "\u26A0 Plaintext was not returned by the server (no encryption key", + ); + ctx.stdout( + " configured). Subscribers must obtain the new secret out of band.", + ); + } + + return { exitCode: 0 }; +} diff --git a/packages/cli/src/commands/webhook-sign.ts b/packages/cli/src/commands/webhook-sign.ts new file mode 100644 index 0000000..f4e7219 --- /dev/null +++ b/packages/cli/src/commands/webhook-sign.ts @@ -0,0 +1,210 @@ +// `new-test webhook sign` — local cryptographic signing of a +// newtest outbound webhook payload (Task 0107). +// +// Symmetric counterpart to `webhook verify` (Task 0106). Wraps +// `@saas/webhook-verifier`'s `signWebhookPayload` exactly; all crypto +// goes through the helper, never through `node:crypto` or `node:buffer` +// directly. The command: +// - does NOT call the api-edge, the SDK, or any network. Pure local +// crypto. +// - does NOT require auth, an active org, or a context store. +// - does NOT JSON-parse, `.trim()`, or otherwise reshape the body. +// Bytes are decoded once via UTF-8 and passed verbatim to the +// helper, which hashes them as-is. +// +// Behaviour: +// - Success → human: +// signature: sha256= +// timestamp: +// json: +// {"signature":"sha256=","timestamp":""} +// exit 0. +// - Argument-shape errors (missing flag, bad timestamp, unreadable +// body file, both `--body` and STDIN supplied, bad output mode) +// throw `UsageError` → exit 2 via `formatCliError`. + +import { promises as fs } from "node:fs"; + +import { signWebhookPayload } from "@saas/webhook-verifier"; + +import type { CommandContext, CommandResult } from "../router.js"; +import { UsageError } from "../errors.js"; + +/** + * Pull a string flag, throwing `UsageError` when missing or empty. + */ +function readRequiredString( + ctx: CommandContext, + name: string, +): string { + const v = ctx.flags[name]; + if (typeof v !== "string" || v.length === 0) { + throw new UsageError(`webhook sign: missing required flag --${name}`); + } + return v; +} + +/** + * Validate `--timestamp=N`. The webhook-verifier helper accepts a string + * here, but we still enforce the same shape `verify` requires of the + * header: a positive integer (unix seconds). Catching malformed values + * at sign time prevents producing signatures that the verifier will + * later reject as `malformed_timestamp`. + */ +function readTimestamp(ctx: CommandContext): string { + const raw = readRequiredString(ctx, "timestamp"); + if (!/^[0-9]+$/.test(raw)) { + throw new UsageError( + `webhook sign: --timestamp must be a non-negative integer (unix seconds), got: ${raw}`, + ); + } + // Reject 0 / 00... -- helper allows 0 but it's almost never what the + // user means. Keep the surface tight; users can pass `1` in tests. + // Range-check against MAX_SAFE_INTEGER so wildly large inputs fail + // here rather than silently producing a signature with an unrepresentable + // timestamp. + const n = Number(raw); + if (!Number.isFinite(n) || n < 0 || !Number.isInteger(n)) { + throw new UsageError( + `webhook sign: --timestamp must be a non-negative integer (unix seconds), got: ${raw}`, + ); + } + return raw; +} + +/** + * Read the entire webhook body. Either: + * - `--body=PATH` → read the file's raw bytes. + * - STDIN piped (non-TTY) → drain it to EOF. + * - Neither → throw `UsageError`. + * + * Both supplied (file flag AND piped STDIN) is also a `UsageError`. + * + * Bytes are decoded as UTF-8 because `signWebhookPayload` accepts + * `body: string` and re-encodes via `TextEncoder`. The CLI never + * `.trim()`s, JSON-parses, or otherwise reshapes the bytes between read + * and helper call. + */ +async function readBody( + ctx: CommandContext, + stdin: StdinLike, +): Promise { + const bodyFlag = ctx.flags["body"]; + // `process.stdin.isTTY` is `true` only when stdin is attached to a + // real terminal; for piped/redirected input Node leaves it + // `undefined`. Treat anything-not-true as "piped". + const stdinPiped = stdin.isTTY !== true; + + if (typeof bodyFlag === "string" && bodyFlag.length > 0) { + if (stdinPiped) { + throw new UsageError( + "webhook sign: --body=PATH and piped STDIN are mutually exclusive (pick one)", + ); + } + let bytes: Uint8Array; + try { + bytes = await fs.readFile(bodyFlag); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw new UsageError( + `webhook sign: could not read --body=${bodyFlag}: ${reason}`, + ); + } + return new TextDecoder("utf-8").decode(bytes); + } + if (bodyFlag === true) { + throw new UsageError("webhook sign: --body requires a file path"); + } + + if (stdinPiped) { + return await drainStdin(stdin); + } + + throw new UsageError( + "webhook sign: provide either --body=PATH or pipe the webhook body on STDIN", + ); +} + +/** + * Read raw bytes from `stdin` to EOF, then UTF-8 decode. We assemble + * the full byte buffer before decoding so multi-byte UTF-8 codepoints + * split across chunks decode correctly. + */ +async function drainStdin(stdin: StdinLike): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of stdin) { + if (typeof chunk === "string") { + chunks.push(new TextEncoder().encode(chunk)); + } else { + chunks.push(chunk); + } + } + let total = 0; + for (const c of chunks) total += c.length; + const merged = new Uint8Array(total); + let offset = 0; + for (const c of chunks) { + merged.set(c, offset); + offset += c.length; + } + return new TextDecoder("utf-8").decode(merged); +} + +/** + * Subset of `process.stdin` the command actually touches. Identical + * shape to `webhook-verify.ts:StdinLike` so tests can reuse harnesses. + */ +export interface StdinLike extends AsyncIterable { + readonly isTTY?: boolean; +} + +export interface WebhookSignOptions { + /** Override `process.stdin` (tests). */ + readonly stdin?: StdinLike; +} + +export function makeWebhookSignCommand( + options: WebhookSignOptions = {}, +): (ctx: CommandContext) => Promise { + return async (ctx: CommandContext): Promise => { + // `--output` is parsed at the runner level into `ctx.outputMode`, + // but we still need to reject anything other than human|json so the + // user gets a clean `UsageError` for typos. The runner's parser + // currently coerces unknown values to `human` silently; gate here. + const rawOutput = ctx.flags["output"]; + if (rawOutput !== undefined && rawOutput !== false) { + if (rawOutput === true) { + throw new UsageError("webhook sign: --output requires human|json"); + } + if (rawOutput !== "human" && rawOutput !== "json") { + throw new UsageError( + `webhook sign: --output must be human or json, got: ${rawOutput}`, + ); + } + } + + const secret = readRequiredString(ctx, "secret"); + const timestamp = readTimestamp(ctx); + const stdin = options.stdin ?? (process.stdin as unknown as StdinLike); + const body = await readBody(ctx, stdin); + + const signature = await signWebhookPayload({ secret, body, timestamp }); + + if (ctx.outputMode === "json") { + ctx.stdout( + `{"signature":"${signature}","timestamp":"${timestamp}"}`, + ); + return { exitCode: 0 }; + } + + ctx.stdout(`signature: ${signature}`); + ctx.stdout(`timestamp: ${timestamp}`); + return { exitCode: 0 }; + }; +} + +/** + * Default command handler used by the CLI runner. Tests use + * `makeWebhookSignCommand({ stdin })` to inject controlled inputs. + */ +export const webhookSignCommand = makeWebhookSignCommand(); diff --git a/packages/cli/src/commands/webhook-verify.ts b/packages/cli/src/commands/webhook-verify.ts new file mode 100644 index 0000000..26b9ae8 --- /dev/null +++ b/packages/cli/src/commands/webhook-verify.ts @@ -0,0 +1,223 @@ +// `new-test webhook verify` — local cryptographic verification of a +// newtest outbound webhook delivery (Task 0106). +// +// This command is a thin shell around `@saas/webhook-verifier` (Task 0105). +// It deliberately: +// - does NOT call the api-edge, the SDK, or any network. It is pure +// local crypto. +// - does NOT require auth, an active org, or a context store. The +// command is usable on a fresh install with no `new-test login`. +// - does NOT JSON-parse or `.trim()` the body. The verifier hashes the +// bytes verbatim; any reshape would break valid signatures. +// +// Behaviour: +// - Success → stdout `ok: true` (human) / `{"ok":true}` (json), exit 0. +// - Verifier failure → stdout `ok: false\nreason: ` (human) / +// `{"ok":false,"reason":""}` (json), exit 4. Verifier failure +// is the command's NORMAL result; exit code carries the signal, no +// stderr text is emitted. +// - Argument-shape errors (missing flag, bad tolerance, unreadable +// body file, both `--body` and STDIN supplied) throw `UsageError` → +// exit 2 via `formatCliError`. + +import { promises as fs } from "node:fs"; + +import { verifyWebhookSignature } from "@saas/webhook-verifier"; + +import type { CommandContext, CommandResult } from "../router.js"; +import { UsageError } from "../errors.js"; + +const VERIFIER_FAILURE_EXIT = 4; + +/** + * Pull a string flag, throwing `UsageError` when missing or empty. + * Centralised so the three required flags share one error shape. + */ +function readRequiredString( + ctx: CommandContext, + name: string, +): string { + const v = ctx.flags[name]; + if (typeof v !== "string" || v.length === 0) { + throw new UsageError(`webhook verify: missing required flag --${name}`); + } + return v; +} + +/** + * Parse `--tolerance-seconds=N`. Returns `undefined` when the flag is + * absent (the helper's default of 300 then applies). Throws `UsageError` + * when present but not a non-negative integer. + */ +function readToleranceSeconds( + ctx: CommandContext, +): number | undefined { + const raw = ctx.flags["tolerance-seconds"]; + if (raw === undefined || raw === false) return undefined; + if (raw === true) { + throw new UsageError( + "webhook verify: --tolerance-seconds requires a non-negative integer value", + ); + } + if (!/^[0-9]+$/.test(raw)) { + throw new UsageError( + `webhook verify: --tolerance-seconds must be a non-negative integer, got: ${raw}`, + ); + } + const n = Number(raw); + if (!Number.isFinite(n) || n < 0 || !Number.isInteger(n)) { + throw new UsageError( + `webhook verify: --tolerance-seconds must be a non-negative integer, got: ${raw}`, + ); + } + return n; +} + +/** + * Read the entire webhook body. Either: + * - `--body=PATH` was supplied → read the file's raw bytes. + * - STDIN is piped (non-TTY) → drain it to EOF. + * - Neither → throw `UsageError`. + * + * Both supplied (file flag AND piped STDIN) is also a `UsageError`. + * + * Bytes are decoded as UTF-8 because the helper accepts `body: string` + * and re-encodes via `TextEncoder`. The CLI never `.trim()`s, JSON-parses, + * or otherwise reshapes the bytes between read and helper call — webhook + * payloads are JSON in practice and round-trip cleanly through UTF-8. + */ +async function readBody( + ctx: CommandContext, + stdin: StdinLike, +): Promise { + const bodyFlag = ctx.flags["body"]; + // `process.stdin.isTTY` is `true` only when stdin is attached to a real + // terminal; for piped/redirected input (the webhook-verify use case) + // Node leaves it `undefined`. Treat anything-not-true as "piped". + const stdinPiped = stdin.isTTY !== true; + + if (typeof bodyFlag === "string" && bodyFlag.length > 0) { + if (stdinPiped) { + throw new UsageError( + "webhook verify: --body=PATH and piped STDIN are mutually exclusive (pick one)", + ); + } + let bytes: Uint8Array; + try { + bytes = await fs.readFile(bodyFlag); + } catch (err) { + const reason = err instanceof Error ? err.message : String(err); + throw new UsageError( + `webhook verify: could not read --body=${bodyFlag}: ${reason}`, + ); + } + return new TextDecoder("utf-8").decode(bytes); + } + if (bodyFlag === true) { + throw new UsageError("webhook verify: --body requires a file path"); + } + + if (stdinPiped) { + return await drainStdin(stdin); + } + + throw new UsageError( + "webhook verify: provide either --body=PATH or pipe the webhook body on STDIN", + ); +} + +/** + * Read raw bytes from `stdin` to EOF, then UTF-8 decode. We assemble the + * full byte buffer before decoding so multi-byte UTF-8 codepoints split + * across chunks decode correctly. + */ +async function drainStdin(stdin: StdinLike): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of stdin) { + if (typeof chunk === "string") { + chunks.push(new TextEncoder().encode(chunk)); + } else { + // Buffer is a Uint8Array subclass — pass through. + chunks.push(chunk); + } + } + let total = 0; + for (const c of chunks) total += c.length; + const merged = new Uint8Array(total); + let offset = 0; + for (const c of chunks) { + merged.set(c, offset); + offset += c.length; + } + return new TextDecoder("utf-8").decode(merged); +} + +/** + * Subset of `process.stdin` the command actually touches. Carved out as + * an interface so tests can pass a synthetic async-iterable plus an + * `isTTY` flag without poking globals. + */ +export interface StdinLike extends AsyncIterable { + readonly isTTY?: boolean; +} + +export interface WebhookVerifyOptions { + /** Override `process.stdin` (tests). */ + readonly stdin?: StdinLike; + /** Override `Date.now()` (tests). */ + readonly now?: () => Date; +} + +export function makeWebhookVerifyCommand( + options: WebhookVerifyOptions = {}, +): (ctx: CommandContext) => Promise { + return async (ctx: CommandContext): Promise => { + const secret = readRequiredString(ctx, "secret"); + const signature = readRequiredString(ctx, "signature"); + const timestamp = readRequiredString(ctx, "timestamp"); + const tolerance = readToleranceSeconds(ctx); + const stdin = options.stdin ?? (process.stdin as unknown as StdinLike); + const body = await readBody(ctx, stdin); + + const verifyInput: Parameters[0] = { + secret, + body, + headers: { + "X-Webhook-Signature": signature, + "X-Webhook-Timestamp": timestamp, + }, + }; + if (tolerance !== undefined) { + verifyInput.toleranceSeconds = tolerance; + } + if (options.now !== undefined) { + verifyInput.now = options.now; + } + + const result = await verifyWebhookSignature(verifyInput); + + if (ctx.outputMode === "json") { + if (result.ok) { + ctx.stdout(`{"ok":true}`); + return { exitCode: 0 }; + } + ctx.stdout(`{"ok":false,"reason":"${result.reason}"}`); + return { exitCode: VERIFIER_FAILURE_EXIT }; + } + + if (result.ok) { + ctx.stdout("ok: true"); + ctx.stdout("reason: "); + return { exitCode: 0 }; + } + ctx.stdout("ok: false"); + ctx.stdout(`reason: ${result.reason}`); + return { exitCode: VERIFIER_FAILURE_EXIT }; + }; +} + +/** + * Default command handler used by the CLI runner. Tests use + * `makeWebhookVerifyCommand({ stdin, now })` to inject controlled inputs. + */ +export const webhookVerifyCommand = makeWebhookVerifyCommand(); diff --git a/packages/cli/src/commands/writes.ts b/packages/cli/src/commands/writes.ts new file mode 100644 index 0000000..56d0354 --- /dev/null +++ b/packages/cli/src/commands/writes.ts @@ -0,0 +1,284 @@ +// Write command handlers (Task 0101). +// +// Each handler is a thin adapter over an `@saas/sdk` resource client. The +// CLI never auto-generates an `Idempotency-Key`: every write command +// reads `--idempotency-key=KEY` from the parsed flags and forwards it +// verbatim into the SDK's `RequestOptions.idempotencyKey`. When the user +// omits the flag, the SDK sees `undefined` and the api-edge worker falls +// through without idempotency replay protection — the contract matches +// Stripe parity exactly (caller-owned key, no transparent generation). +// +// `--org=ORG_ID` overrides the persisted active-org for `org invite` only; +// the other write commands always resolve through `contextStore.activeOrgId` +// (see `resolveOrgId` below). When unset the handler throws +// `MissingOrgContextError` → exit 5 via `formatCliError`. +// +// Output: +// - human mode: a single `key: value` block describing the new resource +// (id + the most identifying field). No tables; writes return one row. +// - json mode: the SDK response shape, verbatim. +// +// All handlers accept `--output=human|json` through `ctx.outputMode`; tests +// assert both modes for every new command. +// +// Errors propagate from the SDK as `newtestError` subclasses and are +// translated to exit codes by `formatCliError` in the runner. + +import type { CommandContext, CommandResult } from "../router.js"; +import { formatOutput } from "../output/index.js"; +import { UsageError } from "../errors.js"; +import { resolveOrgId, readIdempotencyKey } from "./helpers.js"; + +/** Format a single-record write result. */ +function emitRecord( + ctx: CommandContext, + record: Readonly>, + jsonData: unknown, + title: string, +): void { + if (ctx.outputMode === "json") { + ctx.stdout(formatOutput({ mode: "json", data: jsonData })); + return; + } + ctx.stdout(formatOutput({ mode: "human", record, title })); +} + +// --------------------------------------------------------------------------- +// org invite [--role=ROLE] [--idempotency-key=KEY] [--org=ORG_ID] +// --------------------------------------------------------------------------- + +export async function orgInviteCommand(ctx: CommandContext): Promise { + const email = ctx.args[0]; + if (email === undefined || email.length === 0) { + throw new UsageError("usage: new-test org invite [--role=ROLE] [--idempotency-key=KEY] [--org=ORG_ID]"); + } + const roleFlag = ctx.flags["role"]; + const role = typeof roleFlag === "string" && roleFlag.length > 0 ? roleFlag : "viewer"; + + const orgId = await resolveOrgId(ctx, /* allowOverride */ true); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const result = await sdk.memberships.createInvitation( + orgId, + // The contracts type narrows `role` to `InvitationRole`; the api-edge + // and contracts validate the value, so we forward the user's string + // through without a CLI-side enum match (lets the server own the + // catalogue and gives the user the canonical error if they typo). + { email, role: role as "owner" | "admin" | "builder" | "viewer" | "billing_admin" }, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + const inv = result.invitation; + emitRecord( + ctx, + { + id: inv.id, + email: inv.email, + role: inv.role, + status: inv.status, + expiresAt: inv.expiresAt, + }, + result, + `Invitation created in ${orgId}`, + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// project create [--idempotency-key=KEY] +// --------------------------------------------------------------------------- + +export async function projectCreateCommand(ctx: CommandContext): Promise { + const name = ctx.args[0]; + if (name === undefined || name.length === 0) { + throw new UsageError("usage: new-test project create [--idempotency-key=KEY]"); + } + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const result = await sdk.projects.create( + orgId, + { name }, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + const p = result.project; + emitRecord( + ctx, + { id: p.id, name: p.name, slug: p.slug, status: p.status }, + result, + `Project created in ${orgId}`, + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// env create [--idempotency-key=KEY] +// +// Routes through `client.environments.create()` — the SDK's typed +// EnvironmentsClient surface (added in Task 0102) which wraps the +// api-edge route `/v1/organizations/:orgId/projects/:projectId/environments`. +// --------------------------------------------------------------------------- + +export async function envCreateCommand(ctx: CommandContext): Promise { + const projectId = ctx.args[0]; + const name = ctx.args[1]; + if (projectId === undefined || projectId.length === 0 || name === undefined || name.length === 0) { + throw new UsageError("usage: new-test env create [--idempotency-key=KEY]"); + } + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const result = await sdk.environments.create( + orgId, + projectId, + { name }, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + + const e = result.environment; + emitRecord( + ctx, + { + id: e.id, + projectId: e.projectId, + name: e.name, + slug: e.slug, + status: e.status, + }, + result, + `Environment created in ${projectId}`, + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// api-key create [--scope=SCOPE] [--idempotency-key=KEY] +// +// `` becomes the API key `label`. `--scope=SCOPE` is interpreted as +// the role assigned to the service principal backing the key (the +// contract's `CreateApiKeyRequest.role` field); when omitted we default to +// `viewer` so the key is least-privileged. The user can also pass +// `--scope=builder|owner|...` to widen — the api-edge enforces RBAC on +// allowed values and surfaces a `validation_failed` error otherwise. +// --------------------------------------------------------------------------- + +export async function apiKeyCreateCommand(ctx: CommandContext): Promise { + const name = ctx.args[0]; + if (name === undefined || name.length === 0) { + throw new UsageError("usage: new-test api-key create [--scope=SCOPE] [--idempotency-key=KEY]"); + } + const scopeFlag = ctx.flags["scope"]; + const role = typeof scopeFlag === "string" && scopeFlag.length > 0 ? scopeFlag : "viewer"; + + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const result = await sdk.apiKeys.create( + orgId, + { label: name, role }, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + const k = result.apiKey; + emitRecord( + ctx, + { + id: k.id, + label: k.label, + prefix: k.prefix, + secret: k.secret, + role: k.servicePrincipal.role, + }, + result, + `API key created in ${orgId} (save the secret — it will not be shown again)`, + ); + return { exitCode: 0 }; +} + +// --------------------------------------------------------------------------- +// webhook create [--event=EVENT ...] [--idempotency-key=KEY] +// +// `--event` may be passed multiple times (or as a comma-separated list); +// each value becomes a `WebhookSubscription` for the new endpoint. When no +// `--event` is supplied we create the endpoint only — it is then disabled +// from receiving anything until subscriptions are added (the worker default). +// We surface the chosen behaviour clearly in the human output. +// --------------------------------------------------------------------------- + +function readEventFlags(flags: Readonly>): string[] { + const raw = flags["event"]; + if (raw === undefined || raw === false) return []; + if (raw === true) return []; + // The simple parser collapses repeated `--event=X --event=Y` into the + // last value; users wanting multi-event today should pass a + // comma-separated string. This matches the existing flag shape (no + // multi-value parser required) and is documented in the README. + return String(raw) + .split(",") + .map((s) => s.trim()) + .filter((s) => s.length > 0); +} + +export async function webhookCreateCommand(ctx: CommandContext): Promise { + const url = ctx.args[0]; + if (url === undefined || url.length === 0) { + throw new UsageError("usage: new-test webhook create [--event=EVENT[,EVENT2,...]] [--idempotency-key=KEY]"); + } + const events = readEventFlags(ctx.flags); + const orgId = await resolveOrgId(ctx, /* allowOverride */ false); + const idempotencyKey = readIdempotencyKey(ctx); + + const sdk = await ctx.sdk(); + const created = await sdk.webhooks.createEndpoint( + orgId, + { url }, + idempotencyKey !== undefined ? { idempotencyKey } : {}, + ); + const endpoint = created.endpoint; + + // Wire up subscriptions for each event the user asked for. Subscription + // creates are individually idempotency-keyed when the user supplied a + // key — we suffix `:sub:` so multiple subscriptions in a single + // command invocation each get a stable, distinct key (Stripe pattern: + // one logical operation = one root key, suffix per child write). + const subscriptions: unknown[] = []; + for (let i = 0; i < events.length; i++) { + const eventType = events[i] ?? ""; + if (eventType.length === 0) continue; + const subOpts = + idempotencyKey !== undefined + ? { idempotencyKey: `${idempotencyKey}:sub:${i}` } + : {}; + const sub = await sdk.webhooks.createSubscription( + orgId, + { endpointId: endpoint.id, eventType }, + subOpts, + ); + subscriptions.push(sub.subscription); + } + + if (ctx.outputMode === "json") { + ctx.stdout( + formatOutput({ + mode: "json", + data: { endpoint, subscriptions }, + }), + ); + } else { + ctx.stdout( + formatOutput({ + mode: "human", + record: { + id: endpoint.id, + url: endpoint.url, + status: endpoint.status, + subscriptions: events.length === 0 ? "(none — add with `webhook subscribe`)" : events.join(","), + }, + title: `Webhook endpoint created in ${orgId}`, + }), + ); + } + return { exitCode: 0 }; +} diff --git a/packages/cli/src/config-paths.ts b/packages/cli/src/config-paths.ts new file mode 100644 index 0000000..def3ade --- /dev/null +++ b/packages/cli/src/config-paths.ts @@ -0,0 +1,25 @@ +// Resolves the on-disk config directory used by both the token-store file +// fallback and the context store. +// +// Layout (per task scope §Integration Notes): +// - `~/.config/new-test/credentials.json` (0600) +// - `~/.config/new-test/config.json` (0644) +// +// Override via `NEW_TEST_CONFIG_DIR` (used heavily by tests). + +import * as os from "node:os"; +import * as path from "node:path"; +import { CONFIG_APP_DIR, CONFIG_DIR_ENV_VAR } from "./brand.js"; + +const APP_DIR = CONFIG_APP_DIR; + +export function resolveConfigDir(): string { + const override = process.env[CONFIG_DIR_ENV_VAR]; + if (override && override.length > 0) return override; + // Honour `XDG_CONFIG_HOME` when set (Linux convention) so XDG users get + // the dir they expect; fall back to `~/.config/new-test` everywhere + // else (macOS, Windows w/o XDG, Linux w/o XDG). + const xdg = process.env["XDG_CONFIG_HOME"]; + if (xdg && xdg.length > 0) return path.join(xdg, APP_DIR); + return path.join(os.homedir(), ".config", APP_DIR); +} diff --git a/packages/cli/src/context/store.ts b/packages/cli/src/context/store.ts new file mode 100644 index 0000000..3a57710 --- /dev/null +++ b/packages/cli/src/context/store.ts @@ -0,0 +1,95 @@ +// Active CLI context — `~/.config/new-test/config.json`. +// +// Records the active org id and the last-used api-url. Mode 0644 (it's not +// a secret). `org list` prints the active marker; `org use ` writes +// here; `whoami` reads here. + +import { promises as fs } from "node:fs"; +import * as path from "node:path"; + +import { resolveConfigDir } from "../config-paths.js"; + +const FILE_BASENAME = "config.json"; + +export interface CliContext { + readonly activeOrgId?: string; + readonly lastApiUrl?: string; +} + +export interface ContextStoreOptions { + readonly configDir?: string; +} + +export class ContextStore { + private readonly configDir: string; + + constructor(opts: ContextStoreOptions = {}) { + this.configDir = opts.configDir ?? resolveConfigDir(); + } + + get filePath(): string { + return path.join(this.configDir, FILE_BASENAME); + } + + async load(): Promise { + try { + const raw = await fs.readFile(this.filePath, "utf8"); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return {}; + } + if (!isCliContext(parsed)) return {}; + return parsed; + } catch (err) { + if (isNotFound(err)) return {}; + throw err; + } + } + + async save(ctx: CliContext): Promise { + await fs.mkdir(this.configDir, { recursive: true, mode: 0o700 }); + const tmp = `${this.filePath}.tmp`; + await fs.writeFile(tmp, JSON.stringify(ctx, null, 2), { mode: 0o644 }); + await fs.rename(tmp, this.filePath); + } + + async setActiveOrg(orgId: string): Promise { + const current = await this.load(); + const next: CliContext = { ...current, activeOrgId: orgId }; + await this.save(next); + return next; + } + + async setLastApiUrl(url: string): Promise { + const current = await this.load(); + const next: CliContext = { ...current, lastApiUrl: url }; + await this.save(next); + return next; + } + + async clear(): Promise { + try { + await fs.unlink(this.filePath); + } catch (err) { + if (!isNotFound(err)) throw err; + } + } +} + +function isCliContext(value: unknown): value is CliContext { + if (typeof value !== "object" || value === null) return false; + const v = value as Record; + if (v["activeOrgId"] !== undefined && typeof v["activeOrgId"] !== "string") return false; + if (v["lastApiUrl"] !== undefined && typeof v["lastApiUrl"] !== "string") return false; + return true; +} + +function isNotFound(err: unknown): boolean { + return ( + typeof err === "object" && + err !== null && + (err as { code?: unknown }).code === "ENOENT" + ); +} diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.ts new file mode 100644 index 0000000..955bde4 --- /dev/null +++ b/packages/cli/src/errors.ts @@ -0,0 +1,101 @@ +// CLI error helpers. Translate `newtestError` subclasses (from +// `@saas/sdk/errors`) into actionable CLI messages with non-zero exit +// codes; surface request IDs. +// +// Exit-code map (loosely follows Stripe CLI / curl precedent): +// 0 — success +// 1 — generic / unexpected failure +// 2 — usage error (missing arg, unknown subcommand) +// 3 — auth missing / login required +// 4 — auth invalid / token rejected +// 5 — context missing (e.g. `org use` not run, command needs an org) +// 6 — server-side error surfaced via SDK + +import { newtestError, UnauthenticatedError } from "@saas/sdk"; + +import { formatErrorJson, type OutputMode } from "./output/index.js"; + +export class MissingAuthError extends Error { + constructor() { + super("not logged in (run `new-test login`)"); + this.name = "MissingAuthError"; + } +} + +export class MissingOrgContextError extends Error { + constructor() { + super("no active organization (run `new-test org use `)"); + this.name = "MissingOrgContextError"; + } +} + +export class UsageError extends Error { + constructor(message: string) { + super(message); + this.name = "UsageError"; + } +} + +export interface FormatErrorInput { + readonly err: unknown; + readonly mode: OutputMode; +} + +export interface FormattedError { + readonly exitCode: number; + readonly message: string; +} + +export function formatCliError({ err, mode }: FormatErrorInput): FormattedError { + if (err instanceof MissingAuthError) { + return formatPlain(3, "auth_required", err.message, mode); + } + if (err instanceof MissingOrgContextError) { + return formatPlain(5, "org_context_missing", err.message, mode); + } + if (err instanceof UsageError) { + return formatPlain(2, "usage", err.message, mode); + } + if (err instanceof UnauthenticatedError) { + return formatSdk(4, err, "token rejected — run `new-test login` to refresh", mode); + } + if (err instanceof newtestError) { + return formatSdk(6, err, err.message, mode); + } + if (err instanceof Error) { + return formatPlain(1, "internal_error", err.message, mode); + } + return formatPlain(1, "internal_error", String(err), mode); +} + +function formatPlain( + exitCode: number, + code: string, + message: string, + mode: OutputMode, +): FormattedError { + if (mode === "json") { + return { exitCode, message: formatErrorJson({ code, message }) }; + } + return { exitCode, message: `error: ${message}` }; +} + +function formatSdk( + exitCode: number, + err: newtestError, + hint: string, + mode: OutputMode, +): FormattedError { + if (mode === "json") { + return { + exitCode, + message: formatErrorJson({ + code: err.code, + message: err.message, + ...(err.requestId ? { requestId: err.requestId } : {}), + }), + }; + } + const reqIdSuffix = err.requestId ? ` (request id: ${err.requestId})` : ""; + return { exitCode, message: `error: ${hint}${reqIdSuffix}` }; +} diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts new file mode 100644 index 0000000..d40abbc --- /dev/null +++ b/packages/cli/src/index.ts @@ -0,0 +1,18 @@ +// Public package index for `@saas/cli`. +// +// The package's primary deliverable is the `new-test` binary +// (`./dist/cli.js`). This index is exported only so tests can load the +// package via `import` without going through the binary entrypoint, and so +// that downstream tooling can re-use the command-handler types if it needs +// to. +// +// Loadability constraint (PR Boundary §2): this module must NOT pull in +// `keytar` at import time. The keychain adapter inside `token-store/` is +// dynamic-import-only; importing this index in a non-Node host (Workers, +// Bun, browser) must not throw on missing native bindings. + +export { runCli } from "./cli-runner.js"; +export type { CommandContext, CommandHandler, CommandResult } from "./router.js"; +export { Router } from "./router.js"; +export { formatOutput, type OutputMode } from "./output/index.js"; +export { CLI_VERSION } from "./version.js"; diff --git a/packages/cli/src/output/index.ts b/packages/cli/src/output/index.ts new file mode 100644 index 0000000..fa10af4 --- /dev/null +++ b/packages/cli/src/output/index.ts @@ -0,0 +1,117 @@ +// Output formatting for the CLI. +// +// Two modes: +// - "human" (default): for list commands, a small left-aligned table; +// for single-record reads, a `key: value` block. Strings are emitted +// verbatim. No timestamps are injected by the CLI (PR Boundary §C6). +// - "json": one JSON document per command invocation. On success the CLI +// emits the SDK response shape; on error it emits +// `{ error: { code, message, requestId? } }` and exits non-zero. +// +// Stability contract: JSON output mode must be deterministic given +// deterministic SDK responses (Constraints §6). Tests assert exact shape. + +export type OutputMode = "human" | "json"; + +export function parseOutputMode(value: string | boolean | undefined): OutputMode { + if (value === "json") return "json"; + return "human"; +} + +export interface ErrorEnvelopeOut { + code: string; + message: string; + requestId?: string; +} + +export interface FormatInput { + readonly mode: OutputMode; + /** + * For list rendering. When provided, human mode prints a table with these + * columns; json mode emits `{ items: rows }` (or a caller-supplied `data` + * value, see below). + */ + readonly columns?: ReadonlyArray; + readonly rows?: ReadonlyArray>>; + /** + * For single-record / scalar output. When provided, human mode prints a + * `key: value` block; json mode emits the value as-is. + */ + readonly record?: Readonly>; + /** + * Override for json mode. When set, this exact value is JSON-serialised. + * If both `data` and `rows` are set, `data` wins for json output but + * `rows` still drives the human table. + */ + readonly data?: unknown; + /** Optional one-line title shown in human mode above the table/record. */ + readonly title?: string; +} + +export function formatOutput(input: FormatInput): string { + if (input.mode === "json") { + if (input.data !== undefined) { + return JSON.stringify(input.data); + } + if (input.rows && input.columns) { + return JSON.stringify({ items: input.rows }); + } + if (input.record) { + return JSON.stringify(input.record); + } + return JSON.stringify({}); + } + + // Human mode. + const lines: string[] = []; + if (input.title) lines.push(input.title); + + if (input.rows && input.columns) { + lines.push(formatTable(input.columns, input.rows)); + } else if (input.record) { + lines.push(formatKeyValue(input.record)); + } + + return lines.join("\n"); +} + +export function formatErrorJson(err: ErrorEnvelopeOut): string { + const out: ErrorEnvelopeOut = { code: err.code, message: err.message }; + if (err.requestId !== undefined) out.requestId = err.requestId; + return JSON.stringify({ error: out }); +} + +function formatTable( + columns: ReadonlyArray, + rows: ReadonlyArray>>, +): string { + const widths = columns.map((col) => { + let w = col.length; + for (const row of rows) { + const v = row[col] ?? ""; + if (v.length > w) w = v.length; + } + return w; + }); + const pad = (value: string, width: number): string => value.padEnd(width, " "); + const header = columns.map((c, i) => pad(c, widths[i] ?? c.length)).join(" "); + const sep = columns.map((_c, i) => "-".repeat(widths[i] ?? 0)).join(" "); + const body = rows + .map((row) => + columns.map((c, i) => pad(row[c] ?? "", widths[i] ?? 0)).join(" "), + ) + .join("\n"); + if (rows.length === 0) { + return `${header}\n${sep}\n(no rows)`; + } + return `${header}\n${sep}\n${body}`; +} + +function formatKeyValue(record: Readonly>): string { + const keys = Object.keys(record); + if (keys.length === 0) return "(empty)"; + const pad = Math.max(...keys.map((k) => k.length)); + return keys + .map((k) => `${k.padEnd(pad, " ")} : ${record[k] ?? ""}`) + .join("\n"); +} diff --git a/packages/cli/src/prompt.ts b/packages/cli/src/prompt.ts new file mode 100644 index 0000000..1d070ec --- /dev/null +++ b/packages/cli/src/prompt.ts @@ -0,0 +1,94 @@ +// stdin prompt for the token-paste login flow. +// +// Reads a single line from stdin without echoing it. On TTYs we toggle +// raw + opaque mode so the pasted token doesn't appear; on non-TTYs (CI, +// `echo … | new-test login`) we read line-by-line. +// +// Kept tiny — no readline dep — to avoid a transitive `node:readline` +// surface that could trip the package-loadability constraint. The +// function is only invoked from the `login` command path, never from +// the package index. + +export async function readBearerTokenFromStdin(): Promise { + const stdin = process.stdin; + if (!stdin.isTTY) { + return readLineNonTty(stdin); + } + return readLineTty(stdin); +} + +function readLineNonTty(stdin: NodeJS.ReadStream): Promise { + return new Promise((resolve, reject) => { + let buffer = ""; + const onData = (chunk: Buffer | string): void => { + buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8"); + const nl = buffer.indexOf("\n"); + if (nl >= 0) { + cleanup(); + resolve(buffer.slice(0, nl).replace(/\r$/, "")); + } + }; + const onEnd = (): void => { + cleanup(); + resolve(buffer.replace(/\r?\n$/, "")); + }; + const onError = (err: Error): void => { + cleanup(); + reject(err); + }; + const cleanup = (): void => { + stdin.off("data", onData); + stdin.off("end", onEnd); + stdin.off("error", onError); + }; + stdin.on("data", onData); + stdin.on("end", onEnd); + stdin.on("error", onError); + }); +} + +function readLineTty(stdin: NodeJS.ReadStream): Promise { + return new Promise((resolve, reject) => { + const wasRaw = stdin.isRaw === true; + let buffer = ""; + const setRaw = (value: boolean): void => { + if (typeof stdin.setRawMode === "function") stdin.setRawMode(value); + }; + const restore = (): void => { + stdin.off("data", onData); + stdin.off("error", onError); + setRaw(wasRaw); + stdin.pause(); + }; + const onData = (chunk: Buffer | string): void => { + const s = typeof chunk === "string" ? chunk : chunk.toString("utf8"); + for (const ch of s) { + if (ch === "\r" || ch === "\n") { + restore(); + process.stdout.write("\n"); + resolve(buffer); + return; + } + if (ch === "\u0003") { + // Ctrl-C + restore(); + reject(new Error("aborted")); + return; + } + if (ch === "\u007f" || ch === "\b") { + buffer = buffer.slice(0, -1); + continue; + } + buffer += ch; + } + }; + const onError = (err: Error): void => { + restore(); + reject(err); + }; + setRaw(true); + stdin.resume(); + stdin.on("data", onData); + stdin.on("error", onError); + }); +} diff --git a/packages/cli/src/router.ts b/packages/cli/src/router.ts new file mode 100644 index 0000000..cf9a4e1 --- /dev/null +++ b/packages/cli/src/router.ts @@ -0,0 +1,144 @@ +// Command router. Hand-rolled (no `commander`/`cac`/`clipanion`) — see the +// implementer report's framework rationale: the pilot command surface is +// small (8 commands), argv parsing is trivial, and avoiding a new runtime +// dep keeps the package install footprint to `keytar` (optional) only. +// +// Shape: +// - Commands register with a path (array of segments, e.g. `["org","list"]`). +// - Argv tokens that start with `--` are parsed as flags; everything else +// becomes a positional. `--key=value` and `--key value` both work. +// - Boolean flags pass `true`. The first positional that does NOT match a +// registered subcommand starts the positional list for that command. + +import type { newtest } from "@saas/sdk"; + +import type { OutputMode } from "./output/index.js"; +import type { TokenStore } from "./token-store/types.js"; +import type { ContextStore } from "./context/store.js"; + +export interface CommandContext { + readonly args: ReadonlyArray; + readonly flags: Readonly>; + readonly outputMode: OutputMode; + readonly stdout: (line: string) => void; + readonly stderr: (line: string) => void; + readonly tokenStore: TokenStore; + readonly contextStore: ContextStore; + /** + * Lazy SDK factory. Commands that need an authenticated client call this + * to read the token from the token store and instantiate `newtest`. + * Throws `MissingAuthError` (translated to a friendly message by `errors.ts`) + * when no token is stored. + */ + readonly sdk: () => Promise; +} + +export interface CommandResult { + readonly exitCode: number; +} + +export type CommandHandler = (ctx: CommandContext) => Promise; + +interface Registered { + readonly path: ReadonlyArray; + readonly handler: CommandHandler; + readonly summary: string; +} + +export class Router { + private readonly entries: Registered[] = []; + + register(path: ReadonlyArray, summary: string, handler: CommandHandler): void { + this.entries.push({ path, summary, handler }); + } + + /** + * Look up the longest registered command path that prefix-matches `argv`. + * Returns the handler + remaining positional args, or `null` if no match. + */ + resolve( + argv: ReadonlyArray, + ): { handler: CommandHandler; rest: ReadonlyArray } | null { + let best: Registered | null = null; + for (const entry of this.entries) { + if (entry.path.length > argv.length) continue; + let matches = true; + for (let i = 0; i < entry.path.length; i++) { + if (entry.path[i] !== argv[i]) { + matches = false; + break; + } + } + if (matches && (best === null || entry.path.length > best.path.length)) { + best = entry; + } + } + if (!best) return null; + return { handler: best.handler, rest: argv.slice(best.path.length) }; + } + + list(): ReadonlyArray<{ path: ReadonlyArray; summary: string }> { + return this.entries.map((e) => ({ path: e.path, summary: e.summary })); + } +} + +interface ParsedArgv { + readonly positional: ReadonlyArray; + readonly flags: Readonly>; +} + +/** + * Minimal argv parser. Recognises: + * - `--key=value` → flags[key] = "value" + * - `--key value` → flags[key] = "value" (when next token is + * not itself a `--flag`) + * - `--key` → flags[key] = true + * - everything else → positional + * + * Stops consuming flags on the first `--` separator (everything after is + * positional). + */ +export function parseArgv(argv: ReadonlyArray): ParsedArgv { + const positional: string[] = []; + const flags: Record = {}; + let i = 0; + let separator = false; + while (i < argv.length) { + const token = argv[i]; + if (token === undefined) { + i += 1; + continue; + } + if (separator) { + positional.push(token); + i += 1; + continue; + } + if (token === "--") { + separator = true; + i += 1; + continue; + } + if (token.startsWith("--")) { + const body = token.slice(2); + const eq = body.indexOf("="); + if (eq >= 0) { + flags[body.slice(0, eq)] = body.slice(eq + 1); + i += 1; + continue; + } + const next = argv[i + 1]; + if (next !== undefined && !next.startsWith("--")) { + flags[body] = next; + i += 2; + continue; + } + flags[body] = true; + i += 1; + continue; + } + positional.push(token); + i += 1; + } + return { positional, flags }; +} diff --git a/packages/cli/src/token-store/file.ts b/packages/cli/src/token-store/file.ts new file mode 100644 index 0000000..e5eaad7 --- /dev/null +++ b/packages/cli/src/token-store/file.ts @@ -0,0 +1,102 @@ +// `~/.config/new-test/credentials.json` token store fallback. +// +// Behaviour: +// - Parent dir is created with mode 0700 if missing. +// - File is written with mode 0600 atomically (write to tmp, rename) so +// a partial failure doesn't leave a half-written credential file. +// - Path is overrideable via `NEW_TEST_CONFIG_DIR` for tests. +// - On Windows, mode bits are advisory; the chmod calls succeed silently +// against ACL-backed FS but the test asserts mode only on POSIX. + +import { constants as fsConstants, promises as fs } from "node:fs"; +import * as path from "node:path"; + +import type { StoredCredential, TokenStore } from "./types.js"; +import { resolveConfigDir } from "../config-paths.js"; + +const FILE_BASENAME = "credentials.json"; + +export interface FileTokenStoreOptions { + /** Override the config dir entirely. Defaults to `resolveConfigDir()`. */ + readonly configDir?: string; +} + +export class FileTokenStore implements TokenStore { + readonly kind = "file" as const; + + private readonly configDir: string; + + constructor(opts: FileTokenStoreOptions = {}) { + this.configDir = opts.configDir ?? resolveConfigDir(); + } + + get filePath(): string { + return path.join(this.configDir, FILE_BASENAME); + } + + async load(): Promise { + try { + const raw = await fs.readFile(this.filePath, "utf8"); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return null; + } + if (!isStoredCredential(parsed)) return null; + return parsed; + } catch (err) { + if (isNotFound(err)) return null; + throw err; + } + } + + async save(cred: StoredCredential): Promise { + await fs.mkdir(this.configDir, { recursive: true, mode: 0o700 }); + // Existing dir may have looser perms; tighten now. + await tryChmod(this.configDir, 0o700); + + const tmp = `${this.filePath}.tmp`; + const data = JSON.stringify(cred, null, 2); + await fs.writeFile(tmp, data, { mode: 0o600, flag: "w" }); + await tryChmod(tmp, 0o600); + await fs.rename(tmp, this.filePath); + // rename preserves perms on POSIX; chmod again for paranoia / Windows. + await tryChmod(this.filePath, 0o600); + } + + async clear(): Promise { + try { + await fs.unlink(this.filePath); + } catch (err) { + if (!isNotFound(err)) throw err; + } + } +} + +function isStoredCredential(value: unknown): value is StoredCredential { + if (typeof value !== "object" || value === null) return false; + const v = value as Record; + return typeof v["apiUrl"] === "string" && typeof v["token"] === "string"; +} + +function isNotFound(err: unknown): boolean { + return ( + typeof err === "object" && + err !== null && + (err as { code?: unknown }).code === "ENOENT" + ); +} + +async function tryChmod(target: string, mode: number): Promise { + try { + await fs.chmod(target, mode); + } catch { + // Best effort — Windows ACL FS doesn't honour POSIX bits, and `chmod` + // can fail on read-only mounts. The 0600 invariant is still asserted + // by the POSIX test; this swallow is the documented Windows fallback. + } +} + +// Re-exported for tests that want to assert mode. +export { fsConstants }; diff --git a/packages/cli/src/token-store/index.ts b/packages/cli/src/token-store/index.ts new file mode 100644 index 0000000..b56d8a3 --- /dev/null +++ b/packages/cli/src/token-store/index.ts @@ -0,0 +1,6 @@ +// Token store barrel. + +export type { StoredCredential, TokenStore } from "./types.js"; +export { FileTokenStore } from "./file.js"; +export { KeychainTokenStore } from "./keychain.js"; +export { selectTokenStore, type SelectOptions } from "./select.js"; diff --git a/packages/cli/src/token-store/keychain.ts b/packages/cli/src/token-store/keychain.ts new file mode 100644 index 0000000..f128afb --- /dev/null +++ b/packages/cli/src/token-store/keychain.ts @@ -0,0 +1,106 @@ +// Keychain-backed token store. Lazily imports `keytar` so the package +// index stays loadable in non-Node environments (Workers, Bun) and in +// CI environments that lack native build tools. +// +// PR Boundary §2 / Constraints §1: `keytar` is in `optionalDependencies` +// AND must NOT be a transitive runtime requirement of the package index. +// `loadKeytar()` is the one and only place we touch it. + +import type { StoredCredential, TokenStore } from "./types.js"; +import { KEYCHAIN_SERVICE } from "../brand.js"; + +const SERVICE = KEYCHAIN_SERVICE; +const ACCOUNT = "default"; + +interface KeytarLike { + setPassword(service: string, account: string, password: string): Promise; + getPassword(service: string, account: string): Promise; + deletePassword(service: string, account: string): Promise; +} + +export interface KeychainTokenStoreOptions { + /** Inject a keytar-shaped module (used heavily by tests). */ + readonly keytar?: KeytarLike; +} + +export class KeychainTokenStore implements TokenStore { + readonly kind = "keychain" as const; + + private readonly injected: KeytarLike | undefined; + + constructor(opts: KeychainTokenStoreOptions = {}) { + this.injected = opts.keytar; + } + + private async resolve(): Promise { + if (this.injected) return this.injected; + return loadKeytar(); + } + + async load(): Promise { + const k = await this.resolve(); + const raw = await k.getPassword(SERVICE, ACCOUNT); + if (raw === null) return null; + try { + const parsed: unknown = JSON.parse(raw); + if (!isStoredCredential(parsed)) return null; + return parsed; + } catch { + return null; + } + } + + async save(cred: StoredCredential): Promise { + const k = await this.resolve(); + await k.setPassword(SERVICE, ACCOUNT, JSON.stringify(cred)); + } + + async clear(): Promise { + const k = await this.resolve(); + await k.deletePassword(SERVICE, ACCOUNT); + } +} + +/** + * Dynamic-import keytar. Returns the module's default-shaped surface or + * throws — caller decides whether to fall back to the file store. + * + * NOTE: this function exists so unit tests can stub the import path. The + * package index re-exports `KeychainTokenStore` but NOT `loadKeytar`; the + * latter is intentionally an internal seam. + */ +export async function loadKeytar(): Promise { + // Dynamic import via a runtime-built specifier — bundlers / non-Node + // hosts that never call this function never pay the cost. The string + // assembly keeps TypeScript from resolving the module at compile time + // so the package builds in environments where `keytar` is absent (it's + // `optionalDependencies`, install can succeed without it). + const moduleName = ["key", "tar"].join(""); + const mod: unknown = await import(/* @vite-ignore */ moduleName); + if (!isKeytarLike(mod)) { + // Some bundlers wrap CJS exports in a `default` property. + const wrapped = + typeof mod === "object" && mod !== null + ? (mod as { default?: unknown }).default + : null; + if (isKeytarLike(wrapped)) return wrapped; + throw new Error("keytar module did not expose the expected surface"); + } + return mod; +} + +function isStoredCredential(value: unknown): value is StoredCredential { + if (typeof value !== "object" || value === null) return false; + const v = value as Record; + return typeof v["apiUrl"] === "string" && typeof v["token"] === "string"; +} + +function isKeytarLike(value: unknown): value is KeytarLike { + if (typeof value !== "object" || value === null) return false; + const v = value as Record; + return ( + typeof v["setPassword"] === "function" && + typeof v["getPassword"] === "function" && + typeof v["deletePassword"] === "function" + ); +} diff --git a/packages/cli/src/token-store/select.ts b/packages/cli/src/token-store/select.ts new file mode 100644 index 0000000..c808641 --- /dev/null +++ b/packages/cli/src/token-store/select.ts @@ -0,0 +1,45 @@ +// Selection logic for the active token store. +// +// Decision tree: +// 1. If the caller injects a `KeytarLike` shim (tests / DI), use the +// keychain store with that injection. +// 2. Otherwise attempt `loadKeytar()` once. On success → keychain. +// 3. On any error → file fallback. +// +// The selector caches the result for the lifetime of the process; commands +// don't re-probe keytar on every invocation. + +import { + KeychainTokenStore, + loadKeytar, + type KeychainTokenStoreOptions, +} from "./keychain.js"; +import { FileTokenStore } from "./file.js"; +import type { TokenStore } from "./types.js"; + +export interface SelectOptions { + /** Force one or the other (mainly for tests). */ + readonly force?: "keychain" | "file"; + /** Inject a keytar shim. When set, keychain is selected unconditionally. */ + readonly keytar?: KeychainTokenStoreOptions["keytar"]; + /** Override the file store config dir. */ + readonly configDir?: string; +} + +export async function selectTokenStore(opts: SelectOptions = {}): Promise { + if (opts.force === "file") { + return new FileTokenStore(opts.configDir !== undefined ? { configDir: opts.configDir } : {}); + } + if (opts.force === "keychain" || opts.keytar !== undefined) { + return new KeychainTokenStore(opts.keytar !== undefined ? { keytar: opts.keytar } : {}); + } + + try { + await loadKeytar(); + return new KeychainTokenStore(); + } catch { + return new FileTokenStore( + opts.configDir !== undefined ? { configDir: opts.configDir } : {}, + ); + } +} diff --git a/packages/cli/src/token-store/types.ts b/packages/cli/src/token-store/types.ts new file mode 100644 index 0000000..02bd959 --- /dev/null +++ b/packages/cli/src/token-store/types.ts @@ -0,0 +1,19 @@ +// TokenStore adapter interface. Two implementations: +// - KeychainTokenStore (lazy `keytar` import) +// - FileTokenStore (~/.config/new-test/credentials.json, mode 0600) +// +// The CLI selects a store at runtime via `selectTokenStore()`, preferring +// keychain when `keytar` loads. Both round-trip a `{ apiUrl, token }` +// record. Tests inject a stub via DI — no real keychain in unit tests. + +export interface StoredCredential { + readonly apiUrl: string; + readonly token: string; +} + +export interface TokenStore { + readonly kind: "keychain" | "file" | "memory"; + load(): Promise; + save(cred: StoredCredential): Promise; + clear(): Promise; +} diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts new file mode 100644 index 0000000..4e60b7f --- /dev/null +++ b/packages/cli/src/version.ts @@ -0,0 +1,3 @@ +// Auto-generated package version constant. Hand-maintained because the CLI +// is `private` and not published; the value is surfaced by `--version`. +export const CLI_VERSION = "0.0.0"; diff --git a/packages/cli/tsconfig.build.json b/packages/cli/tsconfig.build.json new file mode 100644 index 0000000..964b5c0 --- /dev/null +++ b/packages/cli/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "lib": ["ES2022", "DOM"], + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/__tests__/**"] +} diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json new file mode 100644 index 0000000..a47c154 --- /dev/null +++ b/packages/cli/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM"], + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.ts new file mode 100644 index 0000000..0c8ab70 --- /dev/null +++ b/packages/cli/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + include: ["src/**/*.test.ts", "src/__tests__/**/*.test.ts"], + environment: "node", + }, +}); diff --git a/packages/contracts/component.yaml b/packages/contracts/component.yaml new file mode 100644 index 0000000..105c749 --- /dev/null +++ b/packages/contracts/component.yaml @@ -0,0 +1,27 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: contracts +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-contracts + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: contracts +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/contracts/docs/architecture.md b/packages/contracts/docs/architecture.md new file mode 100644 index 0000000..5b54ee8 --- /dev/null +++ b/packages/contracts/docs/architecture.md @@ -0,0 +1,9 @@ +# contracts — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/contracts`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/contracts/docs/overview.md b/packages/contracts/docs/overview.md new file mode 100644 index 0000000..4fd112f --- /dev/null +++ b/packages/contracts/docs/overview.md @@ -0,0 +1,13 @@ +# contracts + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/contracts/docs/runbook.md b/packages/contracts/docs/runbook.md new file mode 100644 index 0000000..bfb7ae5 --- /dev/null +++ b/packages/contracts/docs/runbook.md @@ -0,0 +1,26 @@ +# contracts — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/contracts/eslint.config.js b/packages/contracts/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/contracts/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..35b00bb --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,38 @@ +{ + "name": "@saas/contracts", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./health": "./src/health.ts", + "./timing": "./src/timing.ts", + "./errors": "./src/errors.ts", + "./tenancy": "./src/tenancy.ts", + "./auth": "./src/auth.ts", + "./membership": "./src/membership.ts", + "./policy": "./src/policy.ts", + "./projects": "./src/projects.ts", + "./events": "./src/events.ts", + "./security-events": "./src/security-events.ts", + "./api-keys": "./src/api-keys.ts", + "./service-principal": "./src/service-principal.ts", + "./config": "./src/config.ts", + "./webhooks": "./src/webhooks.ts", + "./metering": "./src/metering.ts", + "./billing": "./src/billing.ts", + "./notifications": "./src/notifications.ts", + "./integrations": "./src/integrations.ts", + "./idempotency": "./src/idempotency.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3" + } +} diff --git a/packages/contracts/src/api-keys.ts b/packages/contracts/src/api-keys.ts new file mode 100644 index 0000000..8ea80c3 --- /dev/null +++ b/packages/contracts/src/api-keys.ts @@ -0,0 +1,48 @@ +// Public contract types for org-scoped API-key administration. + +/** Service principal metadata attached to an API key. */ +export interface PublicApiKeyServicePrincipal { + id: string; + displayName: string; + role: string; + projectId: string | null; +} + +/** API key as returned by the list endpoint (no secret material). */ +export interface PublicApiKey { + id: string; + label: string; + prefix: string; + createdAt: string; + expiresAt: string | null; + lastUsedAt: string | null; + revokedAt: string | null; + servicePrincipal: PublicApiKeyServicePrincipal; +} + +/** API key as returned by the create endpoint (includes one-time secret). */ +export interface PublicApiKeyCreateResult { + id: string; + label: string; + prefix: string; + secret: string; + createdAt: string; + expiresAt: string | null; + servicePrincipal: PublicApiKeyServicePrincipal; +} + +/** API key as returned by the revoke endpoint. */ +export interface PublicApiKeyRevokeResult { + id: string; + label: string; + prefix: string; + revokedAt: string; +} + +/** Request body for creating an API key. */ +export interface CreateApiKeyRequest { + label: string; + role: string; + projectId?: string; + expiresAt?: string; +} diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts new file mode 100644 index 0000000..8d3092c --- /dev/null +++ b/packages/contracts/src/auth.ts @@ -0,0 +1,124 @@ +// Auth contract types for the identity-worker API surface. + +export interface LoginStartRequest { + email: string; +} + +export interface LoginCompleteRequest { + challengeId: string; + code: string; +} + +export interface AuthUser { + id: string; + email: string; + displayName: string | null; + /** + * Slug of the org the user last worked in — a cross-device default-landing + * hint. Optional: only the profile/session read populates it. + */ + lastOrgSlug?: string | null; +} + +export interface LoginStartResponse { + challengeId: string; + expiresAt: string; + delivery: { + mode: "local_debug" | "email"; + emailHint: string; + code?: string; + }; +} + +export interface LoginCompleteResponse { + token: string; + tokenType: "bearer"; + expiresAt: string; + user: AuthUser; +} + +export interface SessionResponse { + session: { + id: string; + expiresAt: string; + createdAt: string; + }; + user: AuthUser; +} + +export interface LogoutResponse { + success: true; +} + +// Actor context returned by bearer resolution. +// Backward-compatible: user-session flows return actorType "user"; +// API-key flows return actorType "service_principal". +export interface ActorContext { + actorType: "user" | "service_principal"; + actorId: string; + orgId?: string; + projectId?: string | null; + displayName?: string | null; + email?: string | null; +} + +// Extended session response with optional actor context. +// When `actor` is absent, the caller should infer actorType "user" +// from the existing `user` field for backward compatibility. +export interface BearerResolutionResponse { + actor: ActorContext; + session?: { + id: string; + expiresAt: string; + createdAt: string; + }; + user?: AuthUser; +} + +// OAuth sign-in contracts. +// +// The `start` and `callback` routes are browser-redirect flows (not JSON +// endpoints), so they have no request/response body contract. The only JSON +// surface is the provider list, which lets the console render a sign-in button +// only for providers that are fully configured server-side. + +export interface OAuthProviderInfo { + /** Stable provider id used in the route path, e.g. "github". */ + id: string; + /** Human-readable label for the sign-in button, e.g. "GitHub". */ + displayName: string; +} + +export interface OAuthProvidersResponse { + providers: OAuthProviderInfo[]; +} + +// Profile route contracts (self-scoped, user-session only) + +export interface ProfileResponse { + user: AuthUser; +} + +export interface UpdateProfileRequest { + /** Omit to leave unchanged (partial update). */ + displayName?: string | null; + /** Omit to leave unchanged (partial update). */ + lastOrgSlug?: string | null; +} + +export interface ApiSuccessEnvelope { + data: T; + meta: { + requestId: string; + cursor: string | null; + }; +} + +export interface ApiErrorEnvelope { + error: { + code: string; + message: string; + details?: Record; + requestId: string; + }; +} diff --git a/packages/contracts/src/billing.ts b/packages/contracts/src/billing.ts new file mode 100644 index 0000000..f01a3f9 --- /dev/null +++ b/packages/contracts/src/billing.ts @@ -0,0 +1,358 @@ +/** + * Billing contract types. + * + * These types define the public/shared shapes for plan, billing customer, + * subscription, invoice, and entitlement APIs. They are provider-neutral — + * payment-provider ids may appear only as opaque references and never carry + * API keys, webhook signing secrets, raw provider payloads, checkout/portal + * session secrets, or plaintext secret material. + * + * Billing consumes normalized metering outputs (rollups). It does not own + * raw usage facts; usage shapes live in '@saas/contracts/metering'. + */ + +// --------------------------------------------------------------------------- +// Plans +// --------------------------------------------------------------------------- + +export type PublicPlanStatus = "active" | "archived"; +export type PublicBillingInterval = "month" | "year" | "none"; + +export interface PublicPlan { + id: string; + /** Stable machine code (e.g. 'starter', 'pro'). */ + code: string; + name: string; + description: string | null; + status: PublicPlanStatus; + billingInterval: PublicBillingInterval; + /** Nominal display price in minor units; null when interval is 'none' or unpriced. */ + priceAmountCents: number | null; + /** ISO-4217 lowercase currency code. */ + priceCurrency: string; + /** Bounded safe metadata — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: string; + updatedAt: string; +} + +export interface ListPlansRequest { + status?: PublicPlanStatus; +} + +export interface ListPlansResponse { + plans: PublicPlan[]; +} + +// --------------------------------------------------------------------------- +// Billing customers +// --------------------------------------------------------------------------- + +export type PublicBillingCustomerStatus = "active" | "inactive"; + +export interface PublicBillingCustomer { + id: string; + orgId: string; + displayName: string | null; + email: string | null; + status: PublicBillingCustomerStatus; + /** Opaque adapter id (e.g. 'stripe'). Never an API key. */ + provider: string | null; + /** Opaque external customer reference. Never a secret. */ + providerCustomerId: string | null; + metadata: Record | null; + createdAt: string; + updatedAt: string; +} + +export interface GetBillingCustomerResponse { + customer: PublicBillingCustomer; +} + +// --------------------------------------------------------------------------- +// Subscriptions +// --------------------------------------------------------------------------- + +export type PublicSubscriptionStatus = + | "trialing" + | "active" + | "past_due" + | "canceled" + | "expired"; + +export interface PublicSubscription { + id: string; + orgId: string; + billingCustomerId: string; + planId: string; + status: PublicSubscriptionStatus; + currentPeriodStart: string | null; + currentPeriodEnd: string | null; + trialEnd: string | null; + cancelAt: string | null; + canceledAt: string | null; + provider: string | null; + providerSubscriptionId: string | null; + metadata: Record | null; + createdAt: string; + updatedAt: string; +} + +// --------------------------------------------------------------------------- +// Invoices +// --------------------------------------------------------------------------- + +export type PublicInvoiceStatus = + | "draft" + | "open" + | "paid" + | "void" + | "uncollectible"; + +export interface PublicInvoice { + id: string; + orgId: string; + billingCustomerId: string; + subscriptionId: string | null; + number: string | null; + status: PublicInvoiceStatus; + amountDueCents: number; + amountPaidCents: number; + currency: string; + issuedAt: string | null; + dueAt: string | null; + paidAt: string | null; + periodStart: string | null; + periodEnd: string | null; + provider: string | null; + providerInvoiceId: string | null; + /** + * Safe display URL only. Must not embed bearer tokens, session secrets, + * or credential material in query string or fragment. + */ + hostedUrl: string | null; + metadata: Record | null; + createdAt: string; + updatedAt: string; +} + +export interface ListInvoicesRequest { + subscriptionId?: string; + status?: PublicInvoiceStatus; + limit?: number; + cursor?: { createdAt: string; id: string } | null; +} + +export interface ListInvoicesResponse { + invoices: PublicInvoice[]; + nextCursor: { createdAt: string; id: string } | null; +} + +// --------------------------------------------------------------------------- +// Entitlements +// --------------------------------------------------------------------------- + +export type PublicEntitlementValueType = "boolean" | "quantity" | "feature"; +export type PublicEntitlementSource = "plan" | "override"; + +export interface PublicEntitlement { + id: string; + orgId: string; + subscriptionId: string | null; + entitlementKey: string; + valueType: PublicEntitlementValueType; + enabled: boolean; + /** NULL means unlimited (when enabled). */ + limitValue: number | null; + source: PublicEntitlementSource; + metadata: Record | null; + createdAt: string; + updatedAt: string; +} + +export interface GetEntitlementsRequest { + subscriptionId?: string; + source?: PublicEntitlementSource; +} + +export interface GetEntitlementsResponse { + entitlements: PublicEntitlement[]; +} + +// --------------------------------------------------------------------------- +// Entitlement decision (internal seam) +// --------------------------------------------------------------------------- + +/** + * Request shape for the private billing entitlement decision seam consumed by + * other bounded contexts (over a service binding) that need to gate + * product behavior on a named entitlement without reading billing tables + * directly. + * + * Provider-neutral: callers pass the organization id and a stable entitlement + * key only. No provider ids, secrets, or billing internals are required. + */ +export interface CheckBillingEntitlementRequest { + /** Public organization identifier (e.g. 'org_<32-hex>'). */ + orgId: string; + /** Stable machine entitlement key (e.g. 'feature.custom_domains'). */ + entitlementKey: string; +} + +/** + * Reason an entitlement decision is denied. Kept narrow and provider-neutral. + * + * - 'disabled': the entitlement is configured for the org but explicitly off. + * - 'not_configured': no entitlement record exists for this (org, key). + */ +export type BillingEntitlementDeniedReason = "disabled" | "not_configured"; + +/** + * Successful, allowed entitlement decision. Carries only non-secret, safe + * billing facts that already appear in PublicEntitlement. + */ +export interface BillingEntitlementAllowedDecision { + allowed: true; + orgId: string; + entitlementKey: string; + /** Mirrors PublicEntitlement.valueType. */ + valueType: PublicEntitlementValueType; + /** NULL means unlimited (when allowed). */ + limitValue: number | null; + /** Where this decision came from. */ + source: PublicEntitlementSource; + /** Opaque public subscription reference if scoped to one, otherwise null. */ + subscriptionId: string | null; +} + +/** + * Denied entitlement decision. Same response envelope as allowed but carries a + * narrow reason. Missing entitlements MUST surface here (not as 5xx) so callers + * fail closed deterministically. + */ +export interface BillingEntitlementDeniedDecision { + allowed: false; + orgId: string; + entitlementKey: string; + reason: BillingEntitlementDeniedReason; +} + +export type CheckBillingEntitlementResponse = + | BillingEntitlementAllowedDecision + | BillingEntitlementDeniedDecision; + +// --------------------------------------------------------------------------- +// Billing summary +// --------------------------------------------------------------------------- + +export interface GetBillingSummaryResponse { + customer: PublicBillingCustomer | null; + activeSubscription: PublicSubscription | null; + plan: PublicPlan | null; + entitlements: PublicEntitlement[]; +} + +// --------------------------------------------------------------------------- +// Checkout & customer portal (provider hand-off) +// --------------------------------------------------------------------------- + +/** + * Initiate a hosted checkout to purchase/upgrade a plan. Provider-neutral: the + * caller names a plan code and the billing-worker resolves it to the active + * provider's product, returning a hosted, safe-to-display checkout URL. Only + * purchasable plans (those with a configured provider product) are accepted. + */ +export interface CreateCheckoutRequest { + /** Stable plan code to purchase (e.g. 'pro', 'business'). */ + planCode: string; + /** + * Origin of the page that will embed the checkout (the console's + * `window.location.origin`). When present and valid, the returned checkout can + * be loaded as an in-app embedded overlay instead of a full-page redirect to + * the provider. Server-validated; ignored if malformed. + */ + embedOrigin?: string; + /** + * Root-relative console path (e.g. `/orgs/acme/settings/billing?checkout=complete`) + * to return the buyer to after a hosted (non-embedded) checkout. Combined with + * `embedOrigin` server-side into a same-origin success URL so the fallback path + * still lands back in the console. Server-validated; ignored if malformed. + */ + returnPath?: string; +} + +export interface CreateCheckoutResponse { + /** Hosted URL to redirect the buyer to. Safe display URL only — no secrets. */ + checkoutUrl: string; + /** + * Whether the URL is a fresh `checkout` (first purchase) or the customer + * `portal` (plan change for an org that already has an active subscription — + * providers manage paid→paid changes there). The client redirects to + * `checkoutUrl` regardless; `mode` lets it tailor its copy. + */ + mode?: "checkout" | "portal"; +} + +/** + * Create a hosted customer-portal session for managing the existing + * subscription/payment method. No body — the org scope is the URL. + */ +export interface CreatePortalSessionResponse { + /** Hosted customer-portal URL. Safe display URL only — no secrets. */ + portalUrl: string; +} + +/** + * Cancel the account's paid subscription natively (no hosted-portal redirect). + * No body — the org scope is the URL. The authoritative downgrade still arrives + * via the provider webhook; the response is just the acknowledged intent. + */ +export interface CancelSubscriptionResponse { + /** True when the provider scheduled cancellation at period end (vs. immediate). */ + cancelAtPeriodEnd: boolean; +} + +/** + * Change an existing paid subscription to another plan natively (no hosted-portal + * redirect). The re-materialization arrives via the webhook; the response is the + * acknowledged intent. First purchases go through checkout, not this endpoint. + */ +export interface ChangePlanRequest { + /** Target plan code (must be a known, purchasable plan). */ + planCode: string; +} + +export interface ChangePlanResponse { + /** True once the provider accepted the plan change (proration handled provider-side). */ + changed: boolean; +} + +/** + * Reconcile our billing state from the provider (self-heal a missed/dropped + * webhook). `reconciled: false` (with a reason) is a normal outcome, not an + * error — e.g. there's no provider subscription to link. + */ +export interface ReconcileResponse { + reconciled: boolean; + planCode?: string; + reason?: string; +} + +/** A saved card, safe-to-display fields only (never a full PAN or secret). */ +export interface PublicPaymentMethod { + id: string; + /** Card brand, e.g. "visa". */ + brand: string; + /** Last 4 digits only. */ + last4: string; + expMonth: number; + expYear: number; +} + +/** + * Saved cards on file for the account, shown next to the (PCI-gated) "Update + * payment method" deep-link. Display-only; empty when none / provider blip. + */ +export interface ListPaymentMethodsResponse { + paymentMethods: PublicPaymentMethod[]; +} diff --git a/packages/contracts/src/config.ts b/packages/contracts/src/config.ts new file mode 100644 index 0000000..18bf002 --- /dev/null +++ b/packages/contracts/src/config.ts @@ -0,0 +1,171 @@ +/** + * Config, feature-flag, and secret-metadata contract types. + * + * These types define the public API request/response shapes for the config-worker + * surface. Mutation types are included for settings and feature flags. + * No secret value mutation types are included. + */ + +// --------------------------------------------------------------------------- +// Public Setting +// --------------------------------------------------------------------------- + +export interface PublicSetting { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: string; + key: string; + value: unknown; + description: string | null; + createdAt: string; + updatedAt: string; +} + +export interface ListSettingsResponse { + settings: PublicSetting[]; +} + +// --------------------------------------------------------------------------- +// Setting Mutation Requests +// --------------------------------------------------------------------------- + +export interface CreateSettingRequest { + key: string; + value: unknown; + description?: string | null; +} + +export interface UpdateSettingRequest { + value: unknown; + description?: string | null; +} + +export interface CreateSettingResponse { + setting: PublicSetting; +} + +export interface UpdateSettingResponse { + setting: PublicSetting; +} + +// --------------------------------------------------------------------------- +// Public Feature Flag +// --------------------------------------------------------------------------- + +export interface PublicFeatureFlag { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: string; + flagKey: string; + enabled: boolean; + value: unknown | null; + description: string | null; + createdAt: string; + updatedAt: string; +} + +export interface ListFeatureFlagsResponse { + featureFlags: PublicFeatureFlag[]; +} + +// --------------------------------------------------------------------------- +// Feature Flag Mutation Requests +// --------------------------------------------------------------------------- + +export interface CreateFeatureFlagRequest { + flagKey: string; + enabled?: boolean; + value?: unknown; + description?: string | null; +} + +export interface UpdateFeatureFlagRequest { + enabled?: boolean; + value?: unknown; + description?: string | null; +} + +export interface CreateFeatureFlagResponse { + featureFlag: PublicFeatureFlag; +} + +export interface UpdateFeatureFlagResponse { + featureFlag: PublicFeatureFlag; +} + +// --------------------------------------------------------------------------- +// Public Secret Metadata +// --------------------------------------------------------------------------- +// NOTE: No plaintext value, ciphertext envelope, hash, token, or raw secret +// material may ever appear in this type. + +export interface PublicSecretMetadata { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: string; + secretKey: string; + displayName: string | null; + status: string; + version: number; + rotationPolicy: string | null; + lastRotatedAt: string | null; + expiresAt: string | null; + createdBy: string; + createdAt: string; + updatedAt: string; +} + +export interface ListSecretMetadataResponse { + secrets: PublicSecretMetadata[]; +} + +// --------------------------------------------------------------------------- +// Secret Metadata Mutation Requests +// --------------------------------------------------------------------------- +// NOTE: The `value` field on CreateSecretRequest and RotateSecretRequest is +// write-only — it is accepted during creation/rotation, encrypted in the +// worker before persistence, and NEVER returned in any response, event, or +// audit payload. No ciphertext, hash, or raw secret material appears in +// responses. + +/** Metadata-only secret creation (no encrypted value). */ +export interface CreateSecretMetadataRequest { + secretKey: string; + displayName?: string | null; + rotationPolicy?: string | null; + expiresAt?: string | null; +} + +/** Write-only secret creation with an encrypted value. */ +export interface CreateSecretRequest { + secretKey: string; + /** Write-only secret value. Encrypted before persistence; never returned. */ + value: string; + displayName?: string | null; + rotationPolicy?: string | null; + expiresAt?: string | null; +} + +export interface CreateSecretMetadataResponse { + secret: PublicSecretMetadata; +} + +/** Write-only secret rotation with a replacement value. */ +export interface RotateSecretRequest { + /** Write-only replacement secret value. Encrypted before persistence; never returned. */ + value: string; +} + +export interface RotateSecretMetadataResponse { + secret: PublicSecretMetadata; +} + +export interface RevokeSecretMetadataResponse { + secret: PublicSecretMetadata; +} diff --git a/packages/contracts/src/errors.ts b/packages/contracts/src/errors.ts new file mode 100644 index 0000000..485cbe9 --- /dev/null +++ b/packages/contracts/src/errors.ts @@ -0,0 +1,27 @@ +// Error contract types + +export interface ErrorResponse { + error: string; + message: string; + requestId?: string; +} + +export interface ValidationErrorResponse extends ErrorResponse { + error: "validation_failed"; + fields?: Record; +} + +export const ERROR_CODES = { + BAD_REQUEST: "bad_request", + UNAUTHENTICATED: "unauthenticated", + FORBIDDEN: "forbidden", + NOT_FOUND: "not_found", + CONFLICT: "conflict", + RATE_LIMITED: "rate_limited", + VALIDATION_FAILED: "validation_failed", + PRECONDITION_FAILED: "precondition_failed", + UNSUPPORTED: "unsupported", + INTERNAL_ERROR: "internal_error", +} as const; + +export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES]; diff --git a/packages/contracts/src/events.ts b/packages/contracts/src/events.ts new file mode 100644 index 0000000..8499daa --- /dev/null +++ b/packages/contracts/src/events.ts @@ -0,0 +1,174 @@ +/** + * Event envelope and audit contract types. + * + * These types match the durable event-envelope schema defined in + * specs/core/contracts/event-envelope.schema.yaml. They are transport-safe, + * package-safe, and contain no platform clients or database row types. + */ + +// --------------------------------------------------------------------------- +// Actor +// --------------------------------------------------------------------------- + +export type EventActorType = "user" | "service_principal" | "workflow" | "system"; + +export interface EventActor { + type: EventActorType; + id: string; + sessionId?: string | null; + ip?: string | null; +} + +// --------------------------------------------------------------------------- +// Tenant +// --------------------------------------------------------------------------- + +export interface EventTenant { + orgId: string; + projectId?: string | null; + environmentId?: string | null; +} + +// --------------------------------------------------------------------------- +// Subject +// --------------------------------------------------------------------------- + +export interface EventSubject { + kind: string; + id: string; + name?: string | null; +} + +// --------------------------------------------------------------------------- +// Trace +// --------------------------------------------------------------------------- + +export interface EventTrace { + requestId: string; + correlationId?: string | null; + causationId?: string | null; + idempotencyKey?: string | null; +} + +// --------------------------------------------------------------------------- +// Audit metadata +// --------------------------------------------------------------------------- + +export interface EventAuditMeta { + redact?: string[]; +} + +// --------------------------------------------------------------------------- +// Event Envelope +// --------------------------------------------------------------------------- + +export interface EventEnvelope { + id: string; + type: string; + version: number; + source: string; + occurredAt: string; + actor: EventActor; + tenant: EventTenant; + subject: EventSubject; + trace: EventTrace; + payload: Record; + audit?: EventAuditMeta; +} + +// --------------------------------------------------------------------------- +// Audit Entry (immutable projection for querying) +// --------------------------------------------------------------------------- + +export interface AuditEntry { + id: string; + eventId: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + actorType: EventActorType; + actorId: string; + eventType: string; + eventVersion: number; + source: string; + subjectKind: string; + subjectId: string; + subjectName: string | null; + category: string; + description: string; + occurredAt: string; + requestId: string; + correlationId: string | null; + payload: Record; + redactPaths: string[]; +} + +// --------------------------------------------------------------------------- +// Audit Query Filters +// --------------------------------------------------------------------------- + +export interface AuditQueryByOrg { + orgId: string; + category?: string; + /** Filter by actor identity (the raw actor id recorded on the event). */ + actorId?: string; + /** Filter by actor type (validated against the EventActorType set). */ + actorType?: EventActorType; + /** Filter by subject/resource kind (e.g. "project", "member"). */ + subjectKind?: string; + /** Filter by subject/resource id. */ + subjectId?: string; + /** Filter by audit action / event type (e.g. "member.role_changed"). */ + eventType?: string; + /** Inclusive lower bound on occurredAt (ISO-8601 ms Z). */ + from?: string; + /** Inclusive upper bound on occurredAt (ISO-8601 ms Z). */ + to?: string; + limit: number; + cursor?: string | null; +} + +export interface AuditQueryByTarget { + orgId: string; + subjectKind: string; + subjectId: string; + limit: number; + cursor?: string | null; +} + +// --------------------------------------------------------------------------- +// Public Audit Response (API boundary types) +// --------------------------------------------------------------------------- + +export interface PublicAuditEntry { + id: string; + eventId: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + actorType: EventActorType; + actorId: string; + eventType: string; + source: string; + category: string; + description: string; + subject: { + kind: string; + id: string; + name: string | null; + }; + occurredAt: string; + requestId: string; + correlationId: string | null; + payload: Record; +} + +export interface ListAuditEntriesResponse { + data: { + auditEntries: PublicAuditEntry[]; + }; + meta: { + requestId: string; + cursor: string | null; + }; +} diff --git a/packages/contracts/src/health.ts b/packages/contracts/src/health.ts new file mode 100644 index 0000000..7f92fd8 --- /dev/null +++ b/packages/contracts/src/health.ts @@ -0,0 +1,17 @@ +// Health contract types + +export interface HealthResponse { + status: "ok" | "degraded" | "down"; + service: string; + environment: string; + timestamp: string; + version?: string; +} + +export const HEALTH_STATUS = { + OK: "ok", + DEGRADED: "degraded", + DOWN: "down", +} as const; + +export type HealthStatus = (typeof HEALTH_STATUS)[keyof typeof HEALTH_STATUS]; diff --git a/packages/contracts/src/idempotency.ts b/packages/contracts/src/idempotency.ts new file mode 100644 index 0000000..f380c9d --- /dev/null +++ b/packages/contracts/src/idempotency.ts @@ -0,0 +1,87 @@ +// Idempotency-Key request-header contract. +// +// Patterned on Stripe's Idempotency-Key surface (https://stripe.com/docs/api/idempotent_requests): +// the value is opaque to the server, ASCII-printable, and capped at 255 characters. +// Callers that retry an unsafe (POST/PATCH/PUT/DELETE) request with the same key can +// — once durable replay lands in Task 0095 — trust that the second call will not +// double-create. This module exports only the parser and the header constant; the +// actual replay store is intentionally NOT in scope here. +// +// Validation rules (kept deliberately strict — Stripe-compatible): +// - Must be a non-empty string after trimming surrounding whitespace. +// A whitespace-only header is treated as malformed (not "missing"). +// - Length 1..255 characters (after trim). +// - All code points must be ASCII printable (U+0020..U+007E). This rejects +// control characters, CR/LF (header-injection vector), and any non-ASCII. +// +// Stable surface: +// - `IDEMPOTENCY_KEY_HEADER` is the canonical, Stripe-spelled header name used in +// error messages. Case-insensitive `Headers.get("idempotency-key")` lookup is fine. +// - `parseIdempotencyKey(value)` returns a tagged result so callers can branch +// without throwing. `null`/`undefined` => `{ ok: true, key: null }` (header absent; +// caller decides whether the route requires a key). + +export const IDEMPOTENCY_KEY_HEADER = "Idempotency-Key"; + +export const IDEMPOTENCY_KEY_MAX_LENGTH = 255; + +// Reject control characters, DEL, and any non-ASCII. Allow the full ASCII printable range. +const ASCII_PRINTABLE_RE = /^[\x20-\x7e]+$/; + +export type IdempotencyKeyParseResult = + | { ok: true; key: string | null } + | { ok: false; reason: string }; + +/** + * Parse and validate an `Idempotency-Key` header value. + * + * - `null` / `undefined` input => `{ ok: true, key: null }` (header absent). + * - Empty / whitespace-only string => `{ ok: false, reason: "empty" }`. + * - Longer than 255 chars => `{ ok: false, reason: "too_long" }`. + * - Contains control / non-ASCII chars => `{ ok: false, reason: "illegal_characters" }`. + * - Otherwise => `{ ok: true, key: }`. + * + * The `reason` strings are stable identifiers — surface them in error envelopes + * via the `details` field so callers can branch programmatically without parsing + * human-readable messages. + */ +export function parseIdempotencyKey( + value: string | null | undefined, +): IdempotencyKeyParseResult { + if (value === null || value === undefined) { + return { ok: true, key: null }; + } + + const trimmed = value.trim(); + if (trimmed.length === 0) { + return { ok: false, reason: "empty" }; + } + + if (trimmed.length > IDEMPOTENCY_KEY_MAX_LENGTH) { + return { ok: false, reason: "too_long" }; + } + + if (!ASCII_PRINTABLE_RE.test(trimmed)) { + return { ok: false, reason: "illegal_characters" }; + } + + return { ok: true, key: trimmed }; +} + +/** + * Human-readable message for a parse failure, suitable for the `message` field of + * the standard error envelope. Always references the canonical header spelling + * (`Idempotency-Key`) regardless of the case the caller used in the request. + */ +export function describeIdempotencyKeyParseError(reason: string): string { + switch (reason) { + case "empty": + return `${IDEMPOTENCY_KEY_HEADER} header must not be empty.`; + case "too_long": + return `${IDEMPOTENCY_KEY_HEADER} header must be ${IDEMPOTENCY_KEY_MAX_LENGTH} characters or fewer.`; + case "illegal_characters": + return `${IDEMPOTENCY_KEY_HEADER} header must contain only ASCII printable characters (U+0020..U+007E).`; + default: + return `${IDEMPOTENCY_KEY_HEADER} header is malformed.`; + } +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..f30a910 --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,18 @@ +export * from "./health.js"; +export * from "./timing.js"; +export * from "./errors.js"; +export * from "./idempotency.js"; +export * from "./tenancy.js"; +export * from "./auth.js"; +export * from "./membership.js"; +export * from "./policy.js"; +export * from "./events.js"; +export * from "./projects.js"; +export * from "./config.js"; +export * from "./security-events.js"; +export * from "./api-keys.js"; +export * from "./webhooks.js"; +export * from "./metering.js"; +export * from "./billing.js"; +export * from "./notifications.js"; +export * from "./integrations.js"; diff --git a/packages/contracts/src/integrations.ts b/packages/contracts/src/integrations.ts new file mode 100644 index 0000000..072ec87 --- /dev/null +++ b/packages/contracts/src/integrations.ts @@ -0,0 +1,396 @@ +// Integrations contracts — inbound provider integrations (GitHub App first). +// Owner: integrations-worker (apps/integrations-worker). +// +// Safe projections only: no installation tokens, no App credentials, no raw +// provider payloads. Raw inbound payloads stay in the integrations inbox +// (admin-worker visibility only); these shapes are what crosses the public +// API boundary and what `scm.*` events carry on the event log. +// +// Spec: specs/components/17-integrations.md, specs/epics/saas-integrations/. + +// ── Provider seam ──────────────────────────────────────────── + +/** + * Registry-driven provider identifier. GitHub is the first adapter, not a + * special case; the type widens ("gitlab" | "bitbucket") as adapters land. + */ +export type IntegrationProviderId = "github"; + +// ── Connections ───────────────────────────────────────────── + +export type IntegrationConnectionStatus = + | "pending" + | "active" + | "suspended" + | "revoked"; + +/** + * Safe projection of an org ↔ provider connection (a GitHub App + * installation bound to an organization). Never carries installation ids, + * tokens, or state nonces. + */ +export interface PublicConnection { + /** Public id, `int_<32hex>`. */ + id: string; + /** Public org id, `org_<32hex>`. */ + orgId: string; + provider: IntegrationProviderId; + status: IntegrationConnectionStatus; + /** Operator-facing label, defaults to the provider account login. */ + displayName: string | null; + /** Provider-side account login (e.g. GitHub org login). */ + externalAccountLogin: string | null; + /** Provider-side account kind, e.g. "Organization" | "User". */ + externalAccountType: string | null; + /** Provider-side repo grant: "all" | "selected" (GitHub semantics). */ + repositorySelection: string | null; + /** Opaque id of the actor that initiated the connect flow. */ + createdBy: string | null; + /** ISO-8601; set when the provider-side install is verified and bound. */ + connectedAt: string | null; + /** ISO-8601; set on platform-side revoke or provider-side uninstall. */ + revokedAt: string | null; + suspendedAt: string | null; + createdAt: string; + updatedAt: string; +} + +// ── Repo links ────────────────────────────────────────────── + +export type RepoLinkStatus = "active" | "unlinked"; + +/** + * Branch → environment mapping, e.g. `{"main": "prod", "staging": "stage"}`. + * Keys are provider branch names; values are environment slugs validated + * against the project's live environments at write time. + */ +export type BranchEnvMap = Record; + +/** Safe projection of a project ↔ repository link. */ +export interface PublicRepoLink { + /** Public id, `repl_<32hex>`. */ + id: string; + orgId: string; + projectId: string; + /** Owning connection public id (`int_<32hex>`). */ + connectionId: string; + /** Provider-side repository id (opaque string; GitHub numeric id). */ + repoExternalId: string; + /** Provider-side full name, e.g. "acme/storefront". */ + repoFullName: string; + defaultBranch: string | null; + branchEnvMap: BranchEnvMap; + status: RepoLinkStatus; + createdBy: string | null; + createdAt: string; + updatedAt: string; +} + +// ── Inbound deliveries ────────────────────────────────────── + +export type InboundDeliveryStatus = + | "received" + | "attributed" + | "emitted" + | "skipped" + | "failed"; + +/** + * Safe projection of one inbound provider delivery (the durable-inbox row). + * Never carries the raw payload — that stays in the inbox, admin-only. + */ +export interface PublicInboundDelivery { + /** Public id, `igd_<32hex>`. */ + id: string; + provider: IntegrationProviderId; + /** Provider event type, e.g. "push", "pull_request", "installation". */ + eventType: string; + /** Provider event action where applicable, e.g. "opened". */ + action: string | null; + status: InboundDeliveryStatus; + signatureOk: boolean; + attempts: number; + /** Safe failure summary; never raw provider error bodies. */ + failureReason: string | null; + /** Event-log id of the emitted `scm.*` event, when status = "emitted". */ + emittedEventId: string | null; + receivedAt: string; +} + +// ── Cursor pagination (matches the platform list convention) ─ + +export interface IntegrationsCursor { + createdAt: string; + id: string; +} + +// ── Connect flow ──────────────────────────────────────────── + +/** + * POST /v1/organizations/{orgId}/integrations/{provider}/connect + * Policy: organization.integration.connect. + * Entitlement: feature.integrations.github. + */ +export interface ConnectIntegrationRequest { + /** Optional operator label for the connection. */ + displayName?: string; +} + +export interface ConnectIntegrationResponse { + connection: PublicConnection; + /** + * Provider install URL carrying the signed single-use state. The console + * opens this in a popup; the provider redirects back to the platform's + * setup ingress which activates the connection. + */ + installUrl: string; +} + +/** GET /v1/organizations/{orgId}/integrations */ +export interface ListIntegrationsResponse { + connections: PublicConnection[]; + nextCursor: IntegrationsCursor | null; +} + +/** GET /v1/organizations/{orgId}/integrations/{connectionId} */ +export interface GetIntegrationResponse { + connection: PublicConnection; +} + +/** DELETE /v1/organizations/{orgId}/integrations/{connectionId} */ +export interface RevokeIntegrationResponse { + revoked: true; +} + +// ── Repository browsing (IG3) ─────────────────────────────── + +/** Safe projection of a provider repository visible to an installation. */ +export interface PublicRepository { + /** Provider-side repository id (opaque string). */ + externalId: string; + fullName: string; + defaultBranch: string | null; + private: boolean; +} + +/** + * GET /v1/organizations/{orgId}/integrations/{connectionId}/repositories + * Lists repositories the installation can see (via the platform's cached + * installation token). `query` filters by substring of the full name. + */ +export interface ListRepositoriesResponse { + repositories: PublicRepository[]; + /** True when the provider reported more pages than were fetched. */ + truncated: boolean; +} + +// ── Repo link flow ────────────────────────────────────────── + +/** + * POST /v1/organizations/{orgId}/projects/{projectId}/repo-links + * Policy: project.repo_link.write. Entitlement: limit.repo_links. + */ +export interface CreateRepoLinkRequest { + connectionId: string; + repoExternalId: string; + repoFullName: string; + defaultBranch?: string; + branchEnvMap?: BranchEnvMap; +} + +export interface CreateRepoLinkResponse { + repoLink: PublicRepoLink; +} + +export interface UpdateRepoLinkRequest { + branchEnvMap?: BranchEnvMap; + defaultBranch?: string; +} + +export interface UpdateRepoLinkResponse { + repoLink: PublicRepoLink; +} + +export interface ListRepoLinksResponse { + repoLinks: PublicRepoLink[]; + nextCursor: IntegrationsCursor | null; +} + +export interface DeleteRepoLinkResponse { + deleted: true; +} + +// ── Delivery log + replay ─────────────────────────────────── + +/** GET /v1/organizations/{orgId}/integrations/{connectionId}/deliveries */ +export interface ListInboundDeliveriesResponse { + deliveries: PublicInboundDelivery[]; + nextCursor: IntegrationsCursor | null; +} + +/** + * POST .../deliveries/{deliveryId}/replay — re-runs normalize/emit from the + * persisted inbox row; never re-trusts the wire. Body reserved for future + * options. + */ +export interface ReplayInboundDeliveryRequest {} + +export interface ReplayInboundDeliveryResponse { + delivery: PublicInboundDelivery; +} + +// ── Token broker ──────────────────────────────────────────── + +/** + * POST /v1/organizations/{orgId}/integrations/github/token + * Policy: organization.integration.token.issue. + * + * Requested repositories must be linked to a project the actor can access; + * requested permissions must be ⊆ the App's granted permissions + * (deny-by-default). The minted token is returned exactly once, never + * cached, never logged. + */ +export interface IssueIntegrationTokenRequest { + /** Provider-side repository ids (must each match an active repo link). */ + repositories: string[]; + /** e.g. { "contents": "read", "checks": "write" }. */ + permissions: Record; +} + +export interface IssueIntegrationTokenResponse { + /** Reveal-once short-lived installation token. TTL ≤ 1h. */ + token: string; + /** ISO-8601 expiry. */ + expiresAt: string; + repositories: string[]; + permissions: Record; +} + +// ── Event taxonomy ────────────────────────────────────────── + +/** Platform lifecycle events emitted by the integrations context. */ +export const INTEGRATION_EVENT_TYPES = { + CONNECTED: "integration.connected", + SUSPENDED: "integration.suspended", + REACTIVATED: "integration.reactivated", + REVOKED: "integration.revoked", + REPO_SELECTION_CHANGED: "integration.repo_selection_changed", + TOKEN_ISSUED: "integration.token.issued", +} as const; + +export type IntegrationEventType = + (typeof INTEGRATION_EVENT_TYPES)[keyof typeof INTEGRATION_EVENT_TYPES]; + +/** + * Normalized, provider-neutral SCM events emitted onto the event log. + * Additive-only by rule (R7): new fields and new types may be added; existing + * fields never change meaning. Products consume these through the shipped + * outbound-webhooks pipeline. + */ +export const SCM_EVENT_TYPES = { + PUSH: "scm.push", + PULL_REQUEST_OPENED: "scm.pull_request.opened", + PULL_REQUEST_UPDATED: "scm.pull_request.updated", + PULL_REQUEST_MERGED: "scm.pull_request.merged", + PULL_REQUEST_CLOSED: "scm.pull_request.closed", + CHECK_COMPLETED: "scm.check.completed", + RELEASE_PUBLISHED: "scm.release.published", + BRANCH_CREATED: "scm.branch.created", + BRANCH_DELETED: "scm.branch.deleted", + TAG_CREATED: "scm.tag.created", + REPO_LINKED: "scm.repo.linked", + REPO_UNLINKED: "scm.repo.unlinked", +} as const; + +export type ScmEventType = (typeof SCM_EVENT_TYPES)[keyof typeof SCM_EVENT_TYPES]; + +// ── Versioned `scm.*` payload projections (v1) ────────────── +// Compact, documented projections — never the raw provider payload (raw stays +// in the inbox for replay/debug). Every payload carries the repo identity and +// scope; `projectId`/`environment` are set when a repo link matches. + +/** Repository identity carried by every scm.* payload. */ +export interface ScmRepoRef { + provider: IntegrationProviderId; + externalId: string; + fullName: string; +} + +/** Common envelope-payload base for scm.* events (version 1). */ +export interface ScmEventBaseV1 { + version: 1; + /** Public org id. */ + orgId: string; + /** Public project id when a repo link matched, else null. */ + projectId: string | null; + /** Environment slug resolved from the branch → environment map, else null. */ + environment: string | null; + repo: ScmRepoRef; +} + +export interface ScmPushEventV1 extends ScmEventBaseV1 { + ref: string; + branch: string | null; + beforeSha: string; + afterSha: string; + /** Compact commit summaries; capped, never full diffs. */ + commits: Array<{ + sha: string; + message: string; + authorLogin: string | null; + }>; + pusherLogin: string | null; +} + +export interface ScmPullRequestEventV1 extends ScmEventBaseV1 { + number: number; + title: string; + state: "open" | "closed" | "merged"; + sourceBranch: string; + targetBranch: string; + headSha: string; + authorLogin: string | null; + url: string | null; +} + +export interface ScmCheckCompletedEventV1 extends ScmEventBaseV1 { + checkName: string; + conclusion: string | null; + headSha: string; + url: string | null; +} + +export interface ScmReleasePublishedEventV1 extends ScmEventBaseV1 { + tagName: string; + releaseName: string | null; + url: string | null; +} + +export interface ScmBranchEventV1 extends ScmEventBaseV1 { + branch: string; +} + +export interface ScmTagCreatedEventV1 extends ScmEventBaseV1 { + tag: string; +} + +export interface ScmRepoLinkEventV1 extends ScmEventBaseV1 { + repoLinkId: string; +} + +// ── Governance constants ──────────────────────────────────── + +/** Policy actions evaluated by policy-worker (deny-by-default). */ +export const INTEGRATION_POLICY_ACTIONS = { + READ: "organization.integration.read", + CONNECT: "organization.integration.connect", + MANAGE: "organization.integration.manage", + TOKEN_ISSUE: "organization.integration.token.issue", + REPO_LINK_WRITE: "project.repo_link.write", +} as const; + +/** Entitlement keys gating the surface (412 + upgrade UX on deny). */ +export const INTEGRATION_ENTITLEMENTS = { + GITHUB: "feature.integrations.github", + REPO_LINKS_LIMIT: "limit.repo_links", +} as const; diff --git a/packages/contracts/src/membership.ts b/packages/contracts/src/membership.ts new file mode 100644 index 0000000..90233b5 --- /dev/null +++ b/packages/contracts/src/membership.ts @@ -0,0 +1,110 @@ +export interface PublicOrganization { + id: string; + name: string; + slug: string; + /** + * Lifecycle status (e.g. 'active', 'suspended'). Optional — populated by the + * organization list so the console can surface a frozen-child warning (MO3); + * other endpoints may omit it. + */ + status?: string; + createdAt: string; +} + +export interface CreateOrganizationRequest { + name: string; + slug?: string; +} + +export interface CreateOrganizationResponse { + organization: PublicOrganization; + membership: { + role: string; + joinedAt: string; + }; +} + +export interface ListOrganizationsResponse { + organizations: PublicOrganization[]; +} + +export interface GetOrganizationResponse { + organization: PublicOrganization; +} + +export interface PublicMemberRoleAssignment { + role: string; + scopeKind: string; +} + +export interface PublicMember { + id: string; + subjectType: string; + subjectId: string; + status: string; + joinedAt: string; + roles: PublicMemberRoleAssignment[]; +} + +export interface ListMembersResponse { + members: PublicMember[]; +} + +export const ORGANIZATION_ROLES = ["owner", "admin", "builder", "viewer", "billing_admin"] as const; +export type InvitationRole = (typeof ORGANIZATION_ROLES)[number]; + +export interface CreateInvitationRequest { + email: string; + role: InvitationRole; +} + +export interface PublicInvitation { + id: string; + email: string; + role: string; + status: string; + invitedBy: string; + expiresAt: string; + createdAt: string; + acceptedAt: string | null; + revokedAt: string | null; +} + +export interface CreateInvitationResponse { + invitation: PublicInvitation; + delivery?: { mode: string; token: string }; +} + +export interface ListInvitationsResponse { + invitations: PublicInvitation[]; +} + +export interface RevokeInvitationResponse { + invitation: PublicInvitation; +} + +export interface UpdateMemberRoleRequest { + role: string; +} + +export interface UpdateMemberRoleResponse { + member: PublicMember; +} + +export interface RemoveMemberResponse { + member: PublicMember; +} + +export interface AcceptInvitationRequest { + token: string; +} + +export interface AcceptInvitationResponse { + invitation: PublicInvitation; + membership: { + id: string; + role: string; + joinedAt: string; + status: string; + }; +} diff --git a/packages/contracts/src/metering.ts b/packages/contracts/src/metering.ts new file mode 100644 index 0000000..3ed8baf --- /dev/null +++ b/packages/contracts/src/metering.ts @@ -0,0 +1,184 @@ +/** + * Metering contract types. + * + * These types define the public API request/response shapes for usage recording, + * usage summaries, quota checks, and quota violation listing. + * No bearer tokens, API keys, provider credentials, connection strings, + * webhook signing secrets, or plaintext secret material are included. + */ + +// --------------------------------------------------------------------------- +// Usage Recording +// --------------------------------------------------------------------------- + +export interface RecordUsageRequest { + /** Caller-provided unique ID for this usage event. */ + id?: string; + /** Usage metric key (e.g. 'api_requests', 'build_minutes'). */ + metric: string; + /** Usage quantity. Defaults to 1. */ + quantity?: number; + /** Caller-provided deduplication key, unique per organization. */ + idempotencyKey: string; + /** ISO 8601 timestamp when usage occurred. Defaults to now. */ + recordedAt?: string; + /** Optional project scoping. */ + projectId?: string | null; + /** Optional environment scoping (requires projectId). */ + environmentId?: string | null; + /** Optional resource identifier (e.g. worker ID, page ID). */ + resourceId?: string | null; + /** Bounded safe metadata — no secrets, tokens, or credentials. */ + metadata?: Record | null; +} + +export interface RecordUsageResponse { + usageRecord: PublicUsageRecord; +} + +export interface PublicUsageRecord { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + resourceId: string | null; + metric: string; + quantity: number; + idempotencyKey: string; + recordedAt: string; + metadata: Record | null; + createdAt: string; +} + +// --------------------------------------------------------------------------- +// Batch Usage Ingestion +// --------------------------------------------------------------------------- + +export interface IngestUsageBatchRequest { + /** Array of usage events to ingest. */ + records: RecordUsageRequest[]; +} + +export interface IngestUsageBatchResponse { + /** Per-record results. Each entry is either a success or a conflict/error. */ + results: Array< + | { ok: true; usageRecord: PublicUsageRecord } + | { ok: false; error: { kind: string; message?: string } } + >; +} + +// --------------------------------------------------------------------------- +// Usage Summaries +// --------------------------------------------------------------------------- + +export interface GetUsageSummaryRequest { + /** Usage metric key to summarize. */ + metric: string; + /** Optional project filter. */ + projectId?: string | null; + /** Optional environment filter (requires projectId). */ + environmentId?: string | null; + /** Rollup bucket type filter: 'hour' or 'day'. */ + bucketType?: "hour" | "day"; + /** ISO 8601 start time (inclusive). */ + startTime?: string; + /** ISO 8601 end time (exclusive). */ + endTime?: string; +} + +export interface PublicUsageRollup { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + metric: string; + bucketType: "hour" | "day"; + bucketStart: string; + quantity: number; + recordCount: number; + createdAt: string; + updatedAt: string; +} + +export interface GetUsageSummaryResponse { + metric: string; + totalQuantity: number; + totalRecords: number; + rollups: PublicUsageRollup[]; +} + +// --------------------------------------------------------------------------- +// Quota Check +// --------------------------------------------------------------------------- + +export interface CheckQuotaRequest { + /** Usage metric key to check. */ + metric: string; + /** Optional project scoping. */ + projectId?: string; + /** Optional environment scoping. */ + environmentId?: string; + /** Optional resource scoping. */ + resourceId?: string; +} + +export interface CheckQuotaResponse { + /** Whether the usage is within the quota limit. */ + allowed: boolean; + /** The metric being checked. */ + metric: string; + /** Quota limit (-1 if no quota defined). */ + limit: number; + /** Current usage quantity. */ + used: number; + /** Remaining quota (-1 if no quota defined). */ + remaining: number; + /** Quota period. */ + period: "hour" | "day" | "month" | "billing_cycle"; + /** Enforcement mode. */ + enforcement: "soft" | "hard"; + /** Reason for the result (null if allowed, 'quota_exceeded' or 'no_quota_defined'). */ + reason: string | null; +} + +// --------------------------------------------------------------------------- +// Quota Violations +// --------------------------------------------------------------------------- + +export interface ListQuotaViolationsRequest { + /** Optional project filter. */ + projectId?: string; + /** Optional environment filter. */ + environmentId?: string; + /** Optional resource filter. */ + resourceId?: string; + /** Optional metric filter. */ + metric?: string; + /** Pagination limit. */ + limit?: number; + /** Pagination cursor. */ + cursor?: { createdAt: string; id: string } | null; +} + +export interface PublicQuotaViolation { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + resourceId: string | null; + quotaId: string; + metric: string; + limitValue: number; + actualValue: number; + period: "hour" | "day" | "month" | "billing_cycle"; + enforcement: "soft" | "hard"; + violatedAt: string; + resolvedAt: string | null; + metadata: Record | null; + createdAt: string; +} + +export interface ListQuotaViolationsResponse { + violations: PublicQuotaViolation[]; + nextCursor: { createdAt: string; id: string } | null; +} diff --git a/packages/contracts/src/notifications.ts b/packages/contracts/src/notifications.ts new file mode 100644 index 0000000..2847ae6 --- /dev/null +++ b/packages/contracts/src/notifications.ts @@ -0,0 +1,327 @@ +/** + * Notifications V1 contract. + * + * Owner: apps/notifications-worker (bounded context: notifications). + * Spec: specs/components/14-notifications.md. + * + * The contract intentionally exposes a tiny, internal-only surface: + * + * - enqueue a transactional notification (the only V1 send shape), + * - read / update preferences for a user or organization, + * - read delivery status for a specific notification, + * - suppress further delivery to a recipient. + * + * Provider-specific identifiers and payloads MUST stay behind the + * NotificationProvider adapter and MUST NOT leak through these types. + * No secret material (tokens, magic-link codes, raw provider responses) + * may travel on these shapes — call sites should pass a `templateKey` + * and a bounded, redaction-safe `templateData` map only. + */ + +// --------------------------------------------------------------------------- +// Enumerations +// --------------------------------------------------------------------------- + +/** + * Notification channels that may carry a transactional notification. + * + * V1 ships with email only; the type is widened here so future channels + * (sms, push, in-app) can be added without breaking the contract. + */ +export type NotificationChannel = "email"; + +/** + * High-level routing category. Used for preferences and audit categorisation. + * Mirrors the categories called out by spec 14 (invitation / billing / + * security / support / product). + */ +export type NotificationCategory = + | "invitation" + | "billing" + | "security" + | "support" + | "product"; + +/** Delivery lifecycle for a single notification record. */ +export type NotificationStatus = + | "queued" + | "sent" + | "failed" + | "suppressed"; + +/** + * Preference subject kind. A preference row is keyed either to a user + * (e.g. user-level opt-out of product email) or an organization + * (org-wide billing recipient overrides). + */ +export type NotificationSubjectKind = "user" | "organization"; + +// --------------------------------------------------------------------------- +// Recipient +// --------------------------------------------------------------------------- + +/** + * Recipient of a transactional notification. + * + * For V1 the only supported channel is email, so `address` is the canonical + * lower-cased email address. `subjectKind` + `subjectId` are optional and + * let the worker join back to the preference / suppression rows; when + * omitted, preferences are not consulted (system-level notifications). + */ +export interface NotificationRecipient { + channel: NotificationChannel; + address: string; + subjectKind?: NotificationSubjectKind; + subjectId?: string; +} + +// --------------------------------------------------------------------------- +// Enqueue request / response +// --------------------------------------------------------------------------- + +/** + * Request shape for POST /v1/notifications. + * + * `templateKey` is a stable, code-controlled identifier owned by the calling + * worker (e.g. "invitation.created", "billing.receipt"). `templateData` + * carries strictly redaction-safe substitutions — no tokens, no magic-link + * codes, no API keys. The notifications worker is responsible for any + * provider-side substitution; callers MUST NOT inline secret material. + */ +export interface EnqueueNotificationRequest { + orgId: string; + category: NotificationCategory; + templateKey: string; + templateData?: Record; + recipient: NotificationRecipient; + /** Optional caller-provided idempotency key (must be unique per orgId). */ + idempotencyKey?: string; + /** Optional correlation id for tracing back to the originating request. */ + correlationId?: string; +} + +/** Single delivery attempt entry as seen at the API boundary. */ +export interface NotificationAttempt { + id: string; + notificationId: string; + attemptNumber: number; + status: NotificationStatus; + attemptedAt: string; + /** Bounded error reason — never a raw provider payload. */ + errorReason: string | null; +} + +/** + * Public delivery-status shape for a single notification. + * + * The `providerMessageId` field is an opaque, provider-issued reference + * returned by the adapter. It is exposed for operator traceability only + * and must never contain credential material. + */ +export interface NotificationDeliveryStatus { + id: string; + orgId: string; + category: NotificationCategory; + templateKey: string; + status: NotificationStatus; + recipient: { + channel: NotificationChannel; + /** Lower-cased recipient address (e.g. email). */ + address: string; + }; + providerMessageId: string | null; + queuedAt: string; + sentAt: string | null; + failedAt: string | null; + lastError: string | null; + attempts: NotificationAttempt[]; +} + +/** Response shape for POST /v1/notifications. */ +export interface EnqueueNotificationResponse { + notification: NotificationDeliveryStatus; +} + +/** Response shape for GET /v1/notifications/:notificationId. */ +export interface GetNotificationResponse { + notification: NotificationDeliveryStatus; +} + +// --------------------------------------------------------------------------- +// Preferences +// --------------------------------------------------------------------------- + +/** + * Per-category preference toggles. + * + * `null` means "not configured" — call sites should treat that as the + * default (opt-in) for transactional categories. Marketing-style categories + * are deliberately out-of-scope for V1. + */ +export interface NotificationCategoryPreferences { + invitation?: boolean | null; + billing?: boolean | null; + security?: boolean | null; + support?: boolean | null; + product?: boolean | null; +} + +export interface NotificationPreference { + subjectKind: NotificationSubjectKind; + subjectId: string; + orgId: string; + channel: NotificationChannel; + categories: NotificationCategoryPreferences; + updatedAt: string; +} + +export interface GetNotificationPreferencesQuery { + orgId: string; + subjectKind: NotificationSubjectKind; + subjectId: string; + channel?: NotificationChannel; +} + +export interface UpdateNotificationPreferencesRequest { + orgId: string; + subjectKind: NotificationSubjectKind; + subjectId: string; + channel: NotificationChannel; + categories: NotificationCategoryPreferences; +} + +export interface GetNotificationPreferencesResponse { + preferences: NotificationPreference[]; +} + +export interface UpdateNotificationPreferencesResponse { + preference: NotificationPreference; +} + +// --------------------------------------------------------------------------- +// Suppression +// --------------------------------------------------------------------------- + +export type NotificationSuppressionReason = + | "bounce" + | "complaint" + | "manual" + | "unsubscribe"; + +export interface NotificationSuppression { + orgId: string; + channel: NotificationChannel; + address: string; + reason: NotificationSuppressionReason; + createdAt: string; +} + +export interface SuppressRecipientRequest { + orgId: string; + channel: NotificationChannel; + reason: NotificationSuppressionReason; +} + +export interface SuppressRecipientResponse { + suppression: NotificationSuppression; +} + +// --------------------------------------------------------------------------- +// Provider adapter seam +// --------------------------------------------------------------------------- + +/** + * Bounded send context handed to a NotificationProvider implementation. + * + * Implementations MUST NOT receive raw secret material here. Provider-side + * credentials are pulled from the provider's own configuration (Secrets + * Store binding for stage/prod, no-op for local-debug). + */ +export interface ProviderSendContext { + notificationId: string; + orgId: string; + category: NotificationCategory; + templateKey: string; + templateData: Record; + recipient: NotificationRecipient; +} + +/** + * Result returned by a NotificationProvider after attempting a send. + * + * `providerMessageId` is the opaque id the provider issued for the message + * (used purely for operator traceability). `errorReason` is a bounded + * human-readable string — implementations MUST scrub any provider-specific + * payload, credential, or token from this field. + */ +export type ProviderSendResult = + | { ok: true; providerMessageId: string } + | { ok: false; providerMessageId: string | null; errorReason: string }; + +/** + * Provider extraction seam. + * + * V1 has exactly one implementation (local-debug) which records the + * would-be send into the delivery table without contacting an external + * service. A follow-up task will add a Resend / Postmark / SES adapter + * behind this interface without touching any call site. + */ +export interface NotificationProvider { + /** Stable identifier (e.g. "local-debug", "resend", "postmark"). */ + readonly name: string; + send(ctx: ProviderSendContext): Promise; +} + +// --------------------------------------------------------------------------- +// Internal service-binding contract sentinel +// --------------------------------------------------------------------------- + +/** + * Header sentinels for the internal-only V1 surface. + * + * The notifications worker MUST reject requests that arrive without these + * headers — there is no public api-edge facade in V1. See spec 14 + * "Extraction Seam". + */ +export const NOTIFICATIONS_INTERNAL_ACTOR_HEADER = "x-internal-actor"; +export const NOTIFICATIONS_INTERNAL_ACTOR_VALUES = [ + "identity-worker", + "membership-worker", + "billing-worker", + "webhooks-worker", + "events-worker", + "policy-worker", + "projects-worker", + "config-worker", + "metering-worker", + "notifications-worker", + // The public edge forwards end-user preference reads/updates over the + // service binding with the subject pinned to the resolved session actor. + "api-edge", +] as const; + +export type NotificationsInternalActor = + (typeof NOTIFICATIONS_INTERNAL_ACTOR_VALUES)[number]; + +// --------------------------------------------------------------------------- +// Audit event types +// --------------------------------------------------------------------------- + +/** + * Event type strings emitted on the events seam. + * + * Bodies MUST contain zero secret material — templateData substitutions + * are deliberately not included in the envelope. Subscribers see only + * non-secret routing metadata (orgId, category, templateKey, recipient + * channel, recipient address). + */ +export const NOTIFICATION_EVENT_TYPES = { + QUEUED: "notification.queued", + SENT: "notification.sent", + FAILED: "notification.failed", + PREFERENCE_UPDATED: "notification.preference_updated", + SUPPRESSED: "notification.suppressed", +} as const; + +export type NotificationEventType = + (typeof NOTIFICATION_EVENT_TYPES)[keyof typeof NOTIFICATION_EVENT_TYPES]; diff --git a/packages/contracts/src/policy.ts b/packages/contracts/src/policy.ts new file mode 100644 index 0000000..d053d04 --- /dev/null +++ b/packages/contracts/src/policy.ts @@ -0,0 +1,138 @@ +import type { OrganizationRole, ProjectRole, TenancyRole, RoleScopeKind } from "./tenancy.js"; + +export type SubjectType = "user" | "service_principal" | "workflow" | "system"; + +export interface PolicySubject { + type: SubjectType; + id: string; +} + +export interface PolicyResource { + kind: string; + id?: string; + orgId: string; + projectId?: string; + environmentId?: string; +} + +export interface MembershipFact { + kind: "role_assignment"; + role: TenancyRole; + scope: { + kind: RoleScopeKind; + orgId: string; + projectId?: string; + }; +} + +export type PolicyMembershipFact = MembershipFact | Record; + +export interface PolicyContext { + memberships: PolicyMembershipFact[]; + attributes?: Record; +} + +export interface AuthorizationRequest { + subject: PolicySubject; + action: string; + resource: PolicyResource; + context: PolicyContext; +} + +export interface AuthorizationResponse { + allow: boolean; + reason: string; + policyVersion: number; + derivedScope: { + orgId: string; + projectId?: string; + }; +} + +export interface EffectivePermissionsRequest { + subject: PolicySubject; + resource: PolicyResource; + context: PolicyContext; +} + +export interface EffectivePermission { + action: string; + allow: boolean; + reason: string; +} + +export interface EffectivePermissionsResponse { + permissions: EffectivePermission[]; + policyVersion: number; + derivedScope: { + orgId: string; + projectId?: string; + }; +} + +export interface RoleAssignmentValidationRequest { + role: string; + scope: { + kind: string; + orgId: string; + projectId?: string; + }; +} + +export interface RoleAssignmentValidationResponse { + valid: boolean; + reason: string; + policyVersion: number; +} + +export const ORGANIZATION_ACTIONS = [ + "organization.read", + "organization.settings.update", + "organization.invitation.create", + "organization.invitation.list", + "organization.invitation.revoke", + "organization.member.list", + "organization.member.remove", + "organization.member.update_role", + "organization.service_principal.binding.create", + "organization.service_principal.binding.list", + "organization.service_principal.binding.revoke", + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", + "project.create", + "project.list", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "audit.read", + "billing.read", + "billing.manage", + "organization.config.read", + "organization.config.write", + "organization.webhook.read", + "organization.webhook.write", + "project.config.read", + "project.config.write", + "project.webhook.read", + "project.webhook.write", +] as const; + +export type OrganizationAction = (typeof ORGANIZATION_ACTIONS)[number]; + +export const POLICY_VERSION = 1; + +export interface AuthorizationContextRequest { + subject: PolicySubject; + orgId: string; +} + +export interface AuthorizationContextResponse { + memberships: MembershipFact[]; +} + +export type { OrganizationRole, ProjectRole, TenancyRole, RoleScopeKind }; diff --git a/packages/contracts/src/projects.ts b/packages/contracts/src/projects.ts new file mode 100644 index 0000000..d6a09fd --- /dev/null +++ b/packages/contracts/src/projects.ts @@ -0,0 +1,64 @@ +export interface PublicProject { + id: string; + orgId: string; + name: string; + slug: string; + status: string; + createdAt: string; + updatedAt: string; + archivedAt: string | null; +} + +export interface CreateProjectRequest { + name: string; + slug?: string; +} + +export interface CreateProjectResponse { + project: PublicProject; +} + +export interface GetProjectResponse { + project: PublicProject; +} + +export interface ListProjectsResponse { + projects: PublicProject[]; +} + +export interface ArchiveProjectResponse { + project: PublicProject; +} + +export interface PublicEnvironment { + id: string; + orgId: string; + projectId: string; + name: string; + slug: string; + status: string; + createdAt: string; + updatedAt: string; + archivedAt: string | null; +} + +export interface CreateEnvironmentRequest { + name: string; + slug?: string; +} + +export interface CreateEnvironmentResponse { + environment: PublicEnvironment; +} + +export interface GetEnvironmentResponse { + environment: PublicEnvironment; +} + +export interface ListEnvironmentsResponse { + environments: PublicEnvironment[]; +} + +export interface ArchiveEnvironmentResponse { + environment: PublicEnvironment; +} diff --git a/packages/contracts/src/security-events.ts b/packages/contracts/src/security-events.ts new file mode 100644 index 0000000..1523fc4 --- /dev/null +++ b/packages/contracts/src/security-events.ts @@ -0,0 +1,28 @@ +// Public contract types for identity security-event listing. + +/** + * A single security event in the public response shape. + * Sensitive fields (codes, tokens, hashes) are never included. + * Metadata is redacted according to stored redactPaths before serialization. + */ +export interface PublicSecurityEvent { + /** Opaque event identifier */ + id: string; + /** Event type, e.g. "login.challenge.created", "session.created" */ + eventType: string; + /** Outcome: "success" or "failure" */ + outcome: string; + /** ISO 8601 timestamp of when the event occurred */ + occurredAt: string; + /** Request context */ + requestId: string | null; + correlationId: string | null; + ip: string | null; + userAgent: string | null; + /** Redacted metadata payload (safe subset) */ + metadata: Record; +} + +export interface SecurityEventListResponse { + securityEvents: PublicSecurityEvent[]; +} diff --git a/packages/contracts/src/service-principal.ts b/packages/contracts/src/service-principal.ts new file mode 100644 index 0000000..fe9e08f --- /dev/null +++ b/packages/contracts/src/service-principal.ts @@ -0,0 +1,24 @@ +// Service-principal subject-ID helpers. +// The canonical subject-ID shape for service_principal actors is `sp_` +// where is the UUID of the service_principal row with dashes removed. +// This matches the format produced by identity-worker's bearer resolution +// (Task 0048) and forwarded via x-actor-subject-id. + +const SP_PREFIX = "sp_"; +const SP_ID_RE = /^sp_[0-9a-f]{32}$/; + +/** Validate that a string matches the canonical sp_ subject-ID shape. */ +export function isServicePrincipalSubjectId(id: string): boolean { + return SP_ID_RE.test(id); +} + +/** Build a canonical sp_ subject-ID from a raw UUID (with or without dashes). */ +export function servicePrincipalSubjectId(uuid: string): string { + return `${SP_PREFIX}${uuid.replace(/-/g, "")}`; +} + +/** Extract the raw hex (no dashes) from a validated sp_ subject-ID, or null. */ +export function parseServicePrincipalSubjectId(id: string): string | null { + if (!SP_ID_RE.test(id)) return null; + return id.slice(SP_PREFIX.length); +} diff --git a/packages/contracts/src/tenancy.ts b/packages/contracts/src/tenancy.ts new file mode 100644 index 0000000..5ca51f3 --- /dev/null +++ b/packages/contracts/src/tenancy.ts @@ -0,0 +1,44 @@ +// Tenancy contract types +// Every resource must be traceable to an organization. + +export interface OrgScoped { + orgId: string; +} + +export interface ProjectScoped extends OrgScoped { + projectId: string; +} + +export interface TenantContext { + orgId: string; + projectId?: string; + actorId: string; + actorKind: "user" | "service_principal" | "workflow" | "system"; +} + +export type OrganizationRole = + | "owner" + | "admin" + | "builder" + | "viewer" + | "billing_admin"; + +export type ProjectRole = + | "project_admin" + | "project_builder" + | "project_viewer"; + +export type TenancyRole = OrganizationRole | ProjectRole; + +export type RoleScopeKind = "organization" | "project"; + +export interface RoleAssignmentFact { + role: TenancyRole; + scope: { + kind: RoleScopeKind; + orgId: string; + projectId?: string; + }; + subjectId: string; + subjectType: "user" | "service_principal"; +} diff --git a/packages/contracts/src/timing.ts b/packages/contracts/src/timing.ts new file mode 100644 index 0000000..9231aca --- /dev/null +++ b/packages/contracts/src/timing.ts @@ -0,0 +1,145 @@ +// Server-Timing observability helper (PERF4 / task 0133). +// +// A tiny, dependency-free phase timer used to make per-hop and per-query cost +// measurable in production. Each hot-path worker builds a `Timings`, records its +// phases (auth, authz, db, …), and emits both a `Server-Timing` response header +// and a structured timing log line. api-edge measures its own edge phases and +// appends them to the downstream worker's header so a single response carries +// the end-to-end breakdown. +// +// No secrets/PII: phase names are static labels and values are durations only. + +export interface PhaseTiming { + name: string; + durationMs: number; + description?: string; +} + +export interface Timings { + /** Start a phase; returns a function that records its elapsed duration. */ + start(name: string, description?: string): () => void; + /** Time an async function under a phase name. */ + measure(name: string, fn: () => Promise, description?: string): Promise; + /** Record a precomputed duration (e.g. parsed from a downstream header). */ + add(name: string, durationMs: number, description?: string): void; + /** All recorded phases, in insertion order. */ + phases(): PhaseTiming[]; + /** Render the `Server-Timing` header value (empty string if no phases). */ + header(): string; + /** Flat `{ phase: ms }` snapshot for structured logging. */ + toJSON(): Record; +} + +const MAX_PHASES = 64; + +function sanitizeName(name: string): string { + // Server-Timing names are tokens; keep them header-safe and label-only. + const cleaned = name.replace(/[^A-Za-z0-9_]/g, "_"); + return cleaned.length > 0 ? cleaned : "phase"; +} + +function roundMs(ms: number): number { + if (!Number.isFinite(ms) || ms < 0) return 0; + return Math.round(ms * 1000) / 1000; +} + +export function createTimings(now: () => number = () => Date.now()): Timings { + const recorded: PhaseTiming[] = []; + + function record(name: string, durationMs: number, description?: string): void { + if (recorded.length >= MAX_PHASES) return; + const phase: PhaseTiming = { name: sanitizeName(name), durationMs: roundMs(durationMs) }; + if (description) phase.description = description; + recorded.push(phase); + } + + return { + start(name, description) { + const startedAt = now(); + let ended = false; + return () => { + if (ended) return; + ended = true; + record(name, now() - startedAt, description); + }; + }, + async measure(name, fn, description) { + const startedAt = now(); + try { + return await fn(); + } finally { + record(name, now() - startedAt, description); + } + }, + add(name, durationMs, description) { + record(name, durationMs, description); + }, + phases() { + return recorded.map((p) => ({ ...p })); + }, + header() { + return recorded + .map((p) => { + const parts = [p.name, `dur=${p.durationMs}`]; + if (p.description) { + // desc must be a quoted-string; strip quotes/backslashes defensively. + parts.push(`desc="${p.description.replace(/["\\]/g, "")}"`); + } + return parts.join(";"); + }) + .join(", "); + }, + toJSON() { + const out: Record = {}; + for (const p of recorded) out[p.name] = p.durationMs; + return out; + }, + }; +} + +/** Parse the numeric `dur=` of a named metric from a `Server-Timing` header. */ +export function parseServerTimingDuration(header: string | null, name: string): number | null { + if (!header) return null; + const target = sanitizeName(name); + for (const metric of header.split(",")) { + const segments = metric.split(";").map((s) => s.trim()); + const metricName = segments[0]; + if (metricName !== target) continue; + for (const seg of segments.slice(1)) { + const m = /^dur=(-?\d+(?:\.\d+)?)$/.exec(seg); + if (m) return Number(m[1]); + } + } + return null; +} + +/** Append additional `Server-Timing` metrics to an existing header value. */ +export function appendServerTiming(existing: string | null, addition: string): string { + if (!addition) return existing ?? ""; + if (!existing) return addition; + return `${existing}, ${addition}`; +} + +/** + * Sampling gate for the structured timing LOG line (PERF14 cost guard). + * + * The `Server-Timing` *header* is always emitted (free, per-response). The + * structured `console.log` line, by contrast, is what hits Workers Logs + * ingestion — at ~2–3 lines per request across the worker chain it is a real, + * traffic-scaling cost. This gate keeps the log volume bounded while never + * dropping a signal that matters: it ALWAYS emits when any recorded phase is + * slow (so regressions are never sampled away), and otherwise emits at `rate` + * (0..1, default 1-in-10). `random` is injectable for tests. + */ +export function shouldEmitTimingLog( + phases: Record, + opts?: { rate?: number; slowMs?: number; random?: () => number }, +): boolean { + const slowMs = opts?.slowMs ?? 1000; + for (const v of Object.values(phases)) { + if (v >= slowMs) return true; + } + const rate = opts?.rate ?? 0.1; + const r = (opts?.random ?? Math.random)(); + return r < rate; +} diff --git a/packages/contracts/src/webhooks.ts b/packages/contracts/src/webhooks.ts new file mode 100644 index 0000000..2c3101d --- /dev/null +++ b/packages/contracts/src/webhooks.ts @@ -0,0 +1,233 @@ +/** + * Webhook contract types. + * + * These types define the public API request/response shapes for webhook + * endpoint administration, subscriptions, and delivery attempt inspection. + * No plaintext signing secrets, raw secret material, secret hashes, provider + * credentials, or full event payload blobs are included. + */ + +// --------------------------------------------------------------------------- +// Public Webhook Endpoint +// --------------------------------------------------------------------------- + +export interface PublicWebhookEndpoint { + id: string; + orgId: string; + projectId: string | null; + url: string; + name: string | null; + description: string | null; + status: "active" | "disabled" | "pending"; + disabledReason: string | null; + disabledAt: string | null; + /** Signing secret version (monotonic counter). No secret material exposed. */ + secretVersion: number; + secretLastRotatedAt: string | null; + createdAt: string; + updatedAt: string; +} + +export interface ListWebhookEndpointsResponse { + endpoints: PublicWebhookEndpoint[]; + nextCursor: { createdAt: string; id: string } | null; +} + +export interface GetWebhookEndpointResponse { + endpoint: PublicWebhookEndpoint; +} + +// --------------------------------------------------------------------------- +// Webhook Endpoint Mutation Requests +// --------------------------------------------------------------------------- + +export interface CreateWebhookEndpointRequest { + url: string; + name?: string | null; + description?: string | null; + projectId?: string | null; +} + +export interface CreateWebhookEndpointResponse { + endpoint: PublicWebhookEndpoint; +} + +export interface UpdateWebhookEndpointRequest { + url?: string; + name?: string | null; + description?: string | null; +} + +export interface UpdateWebhookEndpointResponse { + endpoint: PublicWebhookEndpoint; +} + +export interface DisableWebhookEndpointRequest { + reason?: string; +} + +export interface DisableWebhookEndpointResponse { + endpoint: PublicWebhookEndpoint; +} + +/** + * Re-enable a previously disabled webhook endpoint. Body is intentionally + * empty — re-enable is additive and carries no operator-supplied metadata. + * Idempotency: a 404 is returned if the endpoint is already active or + * missing (the worker maps the repository `not_found` envelope through + * unchanged). + */ +export interface EnableWebhookEndpointRequest { + // No fields. Reserved for future expansion (e.g. opt-in re-arm of + // delivery retries) under a fresh spec proposal. +} + +export interface EnableWebhookEndpointResponse { + endpoint: PublicWebhookEndpoint; +} + +export interface DeleteWebhookEndpointResponse { + deleted: true; +} + +// --------------------------------------------------------------------------- +// Secret Rotation +// --------------------------------------------------------------------------- + +/** + * Response for POST /webhook-endpoints/{id}/rotate-secret. + * + * `secret` is a **reveal-once** plaintext signing secret in the form + * `whsec_<32 hex chars>`. It is generated server-side, encrypted at rest, + * and returned to the caller exactly once on rotation — never persisted in + * any log, event payload, audit row, or subsequent read surface. Optional + * because legacy callers without an active `SECRET_ENCRYPTION_KEY` cannot + * receive plaintext. + * + * `previousSecretExpiresAt` (when present) tells the operator until when the + * previous signing secret will continue to produce a valid + * `X-Webhook-Signature-Previous` header on outbound delivery attempts — + * giving subscribers a grace window to roll over without dropping events. + * + * `gracePeriodSeconds` echoes the dual-signature window length applied to + * this rotation (server default is 86400; operator may override or set 0 + * to disable). + */ +export interface RotateWebhookSecretResponse { + endpoint: PublicWebhookEndpoint; + /** Reveal-once plaintext secret. `whsec_<32 hex>`. Never persisted. */ + secret?: string; + /** ISO timestamp the dual-signature grace window closes at. Null when no grace window was applied. */ + previousSecretExpiresAt: string | null; + /** Echo of the grace-period window applied to this rotation, in seconds. */ + gracePeriodSeconds: number; +} + +// --------------------------------------------------------------------------- +// Public Webhook Subscription +// --------------------------------------------------------------------------- + +export interface PublicWebhookSubscription { + id: string; + orgId: string; + endpointId: string; + projectId: string | null; + eventType: string; + enabled: boolean; + createdAt: string; + updatedAt: string; +} + +export interface ListWebhookSubscriptionsResponse { + subscriptions: PublicWebhookSubscription[]; + nextCursor: { createdAt: string; id: string } | null; +} + +export interface GetWebhookSubscriptionResponse { + subscription: PublicWebhookSubscription; +} + +// --------------------------------------------------------------------------- +// Webhook Subscription Mutation Requests +// --------------------------------------------------------------------------- + +export interface CreateWebhookSubscriptionRequest { + endpointId: string; + eventType: string; + projectId?: string | null; + enabled?: boolean; +} + +export interface CreateWebhookSubscriptionResponse { + subscription: PublicWebhookSubscription; +} + +export interface UpdateWebhookSubscriptionRequest { + enabled?: boolean; +} + +export interface UpdateWebhookSubscriptionResponse { + subscription: PublicWebhookSubscription; +} + +export interface DeleteWebhookSubscriptionResponse { + deleted: true; +} + +// --------------------------------------------------------------------------- +// Public Webhook Delivery Attempt +// --------------------------------------------------------------------------- + +export interface PublicWebhookDeliveryAttempt { + id: string; + orgId: string; + endpointId: string; + subscriptionId: string; + eventId: string; + eventType: string; + status: "pending" | "success" | "failed" | "retrying"; + attemptNumber: number; + httpStatusCode: number | null; + /** Safe failure summary — no raw response body or full event payload. */ + failureReason: string | null; + idempotencyKey: string | null; + nextRetryAt: string | null; + completedAt: string | null; + createdAt: string; + updatedAt: string; +} + +export interface ListWebhookDeliveryAttemptsResponse { + deliveryAttempts: PublicWebhookDeliveryAttempt[]; + nextCursor: { createdAt: string; id: string } | null; +} + +export interface GetWebhookDeliveryAttemptResponse { + deliveryAttempt: PublicWebhookDeliveryAttempt; +} + +/** + * Manual delivery replay (B5). Re-send the same event to the same endpoint + * through the existing signing/delivery seam, recording a fresh attempt in + * history. + * + * Request body is intentionally empty — replay carries no operator-supplied + * metadata; the target attempt is fully identified by the path + * `:id`. Reserved for future expansion (e.g. a one-shot override URL) under a + * fresh spec proposal. + */ +export interface ReplayWebhookDeliveryRequest { + // No fields. +} + +/** + * Response for POST /webhooks/delivery-attempts/{id}/replay. + * + * `deliveryAttempt` is the NEWLY-created attempt (fresh id, `attemptNumber` 1), + * carrying its post-delivery status. The original attempt is unchanged. No + * secret material or raw event payload is ever included — only the safe public + * delivery-attempt projection. + */ +export interface ReplayWebhookDeliveryResponse { + deliveryAttempt: PublicWebhookDeliveryAttempt; +} diff --git a/packages/contracts/tsconfig.build.json b/packages/contracts/tsconfig.build.json new file mode 100644 index 0000000..4d78c7b --- /dev/null +++ b/packages/contracts/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..d84a568 --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/db/component.yaml b/packages/db/component.yaml new file mode 100644 index 0000000..af3b68f --- /dev/null +++ b/packages/db/component.yaml @@ -0,0 +1,27 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-data + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: data +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/db/docs/architecture.md b/packages/db/docs/architecture.md new file mode 100644 index 0000000..f38d9a4 --- /dev/null +++ b/packages/db/docs/architecture.md @@ -0,0 +1,9 @@ +# db — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/db`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/db/docs/overview.md b/packages/db/docs/overview.md new file mode 100644 index 0000000..0828787 --- /dev/null +++ b/packages/db/docs/overview.md @@ -0,0 +1,13 @@ +# db + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- **db-migrate** — Applies database migrations to the stage and prod Cloudflare D1 databases diff --git a/packages/db/docs/runbook.md b/packages/db/docs/runbook.md new file mode 100644 index 0000000..121afeb --- /dev/null +++ b/packages/db/docs/runbook.md @@ -0,0 +1,26 @@ +# db — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/db/eslint.config.js b/packages/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/db/package.json b/packages/db/package.json new file mode 100644 index 0000000..e5ec6cc --- /dev/null +++ b/packages/db/package.json @@ -0,0 +1,43 @@ +{ + "name": "@saas/db", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./manifest": "./src/manifest.ts", + "./types": "./src/types.ts", + "./ids": "./src/ids/index.ts", + "./identity": "./src/identity/index.ts", + "./membership": "./src/membership/index.ts", + "./events": "./src/events/index.ts", + "./projects": "./src/projects/index.ts", + "./config": "./src/config/index.ts", + "./webhooks": "./src/webhooks/index.ts", + "./metering": "./src/metering/index.ts", + "./billing": "./src/billing/index.ts", + "./notifications": "./src/notifications/index.ts", + "./support": "./src/support/index.ts", + "./integrations": "./src/integrations/index.ts", + "./runner": "./src/runner/index.ts", + "./d1": "./src/d1/index.ts", + "./json": "./src/json.ts" + }, + "bin": { + "db-migrate": "./dist/runner/cli.js" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json && cp -r src/migrations dist/", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "migrate:plan": "pnpm run build && node dist/runner/cli.js plan", + "migrate:apply": "pnpm run build && node dist/runner/cli.js apply" + }, + "dependencies": {}, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/node": "^20.17.0", + "typescript": "^5.8.3" + } +} diff --git a/packages/db/src/billing/entitlement-decisions.ts b/packages/db/src/billing/entitlement-decisions.ts new file mode 100644 index 0000000..88d41c4 --- /dev/null +++ b/packages/db/src/billing/entitlement-decisions.ts @@ -0,0 +1,140 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { BillingResult } from "./types.js"; + +// --------------------------------------------------------------------------- +// Entitlement-decision observability (B9) +// +// A narrow, counts-only repository over billing_entitlement_decision_observations +// (migration 150). Owned by the billing bounded context. Two operations: +// +// * recordDecisionObservation — append one secret-free observation per +// entitlement decision (best-effort; the billing-worker swallows failures so +// a recording problem never alters the entitlement response). +// * aggregateDecisions — narrow time-windowed GROUP BY for the admin +// support read: counts per (entitlementKey, outcome, denialReason). +// +// This module deliberately does NOT extend the broad BillingRepository surface: +// the observation concern is separable, kept narrow, and never exposes value +// fields (limit values, subscription IDs, sources, payloads, secrets). +// --------------------------------------------------------------------------- + +export type EntitlementDecisionOutcome = "allowed" | "denied"; + +// Mirrors the frozen CheckBillingEntitlementResponse denial reason vocabulary. +export type EntitlementDenialReason = "not_configured" | "disabled"; + +export interface RecordDecisionObservationInput { + id: string; + orgId: string; + entitlementKey: string; + outcome: EntitlementDecisionOutcome; + // Required iff outcome === "denied"; must be null/absent when allowed. + denialReason?: EntitlementDenialReason | null; + occurredAt: Date; +} + +export interface DecisionAggregateQuery { + // Inclusive lower bound of the observation window (decisions at/after this). + since: Date; + // Optional exclusive upper bound (decisions strictly before this). Defaults + // to "now" semantics at the DB if omitted (no upper bound clause). + until?: Date | null; + // Defensive cap on the number of distinct (key, outcome, reason) groups + // returned. Bounds the result set; aggregation never streams raw rows. + maxGroups: number; +} + +// One aggregated bucket: a count of decisions for a (key, outcome, reason) +// tuple over the queried window. `denialReason` is null for allowed buckets. +export interface DecisionAggregateBucket { + entitlementKey: string; + outcome: EntitlementDecisionOutcome; + denialReason: EntitlementDenialReason | null; + count: number; +} + +export interface EntitlementDecisionRepository { + recordDecisionObservation( + input: RecordDecisionObservationInput, + ): Promise>; + + aggregateDecisions( + orgId: string, + query: DecisionAggregateQuery, + ): Promise>; +} + +function safeError(message: string): BillingResult { + return { ok: false, error: { kind: "internal", message } }; +} + +export function createEntitlementDecisionRepository( + executor: SqlExecutor, +): EntitlementDecisionRepository { + return { + async recordDecisionObservation( + input: RecordDecisionObservationInput, + ): Promise> { + try { + const denialReason = + input.outcome === "denied" ? (input.denialReason ?? null) : null; + await executor.execute( + `INSERT INTO billing_entitlement_decision_observations ( + id, org_id, entitlement_key, outcome, denial_reason, occurred_at + ) VALUES ( + $1, $2, $3, $4, $5, $6 + ) + ON CONFLICT (id) DO NOTHING`, + [ + input.id, + input.orgId, + input.entitlementKey, + input.outcome, + denialReason, + input.occurredAt.toISOString(), + ], + ); + return { ok: true, value: undefined }; + } catch { + return safeError("Failed to record entitlement-decision observation"); + } + }, + + async aggregateDecisions( + orgId: string, + query: DecisionAggregateQuery, + ): Promise> { + try { + const params: unknown[] = [orgId, query.since.toISOString()]; + let upperClause = ""; + if (query.until) { + params.push(query.until.toISOString()); + upperClause = ` AND occurred_at < $${params.length}`; + } + params.push(query.maxGroups); + const limitParam = `$${params.length}`; + + const result = await executor.execute>( + `SELECT entitlement_key, outcome, denial_reason, count(*) AS decision_count + FROM billing_entitlement_decision_observations + WHERE org_id = $1 + AND occurred_at >= $2${upperClause} + GROUP BY entitlement_key, outcome, denial_reason + ORDER BY decision_count DESC, entitlement_key ASC, outcome ASC + LIMIT ${limitParam}`, + params, + ); + + const buckets = result.rows.map((row) => ({ + entitlementKey: row.entitlement_key as string, + outcome: row.outcome as EntitlementDecisionOutcome, + denialReason: (row.denial_reason as EntitlementDenialReason | null) ?? null, + count: Number(row.decision_count ?? 0), + })); + return { ok: true, value: buckets }; + } catch { + return safeError("Failed to aggregate entitlement-decision observations"); + } + }, + }; +} diff --git a/packages/db/src/billing/index.ts b/packages/db/src/billing/index.ts new file mode 100644 index 0000000..9810ca4 --- /dev/null +++ b/packages/db/src/billing/index.ts @@ -0,0 +1,43 @@ +export type { + BillingRepositoryError, + BillingResult, + CursorPosition, + PageQueryParams, + PagedResult, + PlanStatus, + BillingInterval, + Plan, + CreatePlanInput, + ListPlansQuery, + BillingCustomerStatus, + BillingCustomer, + UpsertBillingCustomerInput, + SubscriptionStatus, + Subscription, + CreateSubscriptionInput, + UpdateSubscriptionInput, + InvoiceStatus, + Invoice, + UpsertInvoiceInput, + ListInvoicesQuery, + EntitlementValueType, + EntitlementSource, + Entitlement, + UpsertEntitlementInput, + ListEntitlementsQuery, + BillingSummary, + BillingRepository, +} from "./types.js"; + +export { createBillingRepository } from "./repository.js"; + +export type { + EntitlementDecisionOutcome, + EntitlementDenialReason, + RecordDecisionObservationInput, + DecisionAggregateQuery, + DecisionAggregateBucket, + EntitlementDecisionRepository, +} from "./entitlement-decisions.js"; + +export { createEntitlementDecisionRepository } from "./entitlement-decisions.js"; diff --git a/packages/db/src/billing/repository.ts b/packages/db/src/billing/repository.ts new file mode 100644 index 0000000..3ce65d5 --- /dev/null +++ b/packages/db/src/billing/repository.ts @@ -0,0 +1,689 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + BillingRepository, + BillingResult, + CursorPosition, + PagedResult, + PageQueryParams, + Plan, + PlanStatus, + BillingInterval, + CreatePlanInput, + ListPlansQuery, + BillingCustomer, + BillingCustomerStatus, + UpsertBillingCustomerInput, + Subscription, + SubscriptionStatus, + CreateSubscriptionInput, + UpdateSubscriptionInput, + Invoice, + InvoiceStatus, + UpsertInvoiceInput, + ListInvoicesQuery, + Entitlement, + EntitlementValueType, + EntitlementSource, + UpsertEntitlementInput, + ListEntitlementsQuery, + BillingSummary, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseBooleanColumn, parseNullableJsonColumn } from "../json.js"; + +// ── Row mappers ──────────────────────────────────────────── + +function toDate(v: unknown): Date { + return new Date(v as string); +} + +function toDateOrNull(v: unknown): Date | null { + return v == null ? null : new Date(v as string); +} + +function mapPlan(row: Record): Plan { + return { + id: row.id as string, + code: row.code as string, + name: row.name as string, + description: (row.description as string) ?? null, + status: row.status as PlanStatus, + billingInterval: row.billing_interval as BillingInterval, + priceAmountCents: row.price_amount_cents == null ? null : Number(row.price_amount_cents), + priceCurrency: row.price_currency as string, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapBillingCustomer(row: Record): BillingCustomer { + return { + id: row.id as string, + orgId: row.org_id as string, + displayName: (row.display_name as string) ?? null, + email: (row.email as string) ?? null, + status: row.status as BillingCustomerStatus, + provider: (row.provider as string) ?? null, + providerCustomerId: (row.provider_customer_id as string) ?? null, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapSubscription(row: Record): Subscription { + return { + id: row.id as string, + orgId: row.org_id as string, + billingCustomerId: row.billing_customer_id as string, + planId: row.plan_id as string, + status: row.status as SubscriptionStatus, + currentPeriodStart: toDateOrNull(row.current_period_start), + currentPeriodEnd: toDateOrNull(row.current_period_end), + trialEnd: toDateOrNull(row.trial_end), + cancelAt: toDateOrNull(row.cancel_at), + canceledAt: toDateOrNull(row.canceled_at), + provider: (row.provider as string) ?? null, + providerSubscriptionId: (row.provider_subscription_id as string) ?? null, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapInvoice(row: Record): Invoice { + return { + id: row.id as string, + orgId: row.org_id as string, + billingCustomerId: row.billing_customer_id as string, + subscriptionId: (row.subscription_id as string) ?? null, + number: (row.number as string) ?? null, + status: row.status as InvoiceStatus, + amountDueCents: Number(row.amount_due_cents), + amountPaidCents: Number(row.amount_paid_cents), + currency: row.currency as string, + issuedAt: toDateOrNull(row.issued_at), + dueAt: toDateOrNull(row.due_at), + paidAt: toDateOrNull(row.paid_at), + periodStart: toDateOrNull(row.period_start), + periodEnd: toDateOrNull(row.period_end), + provider: (row.provider as string) ?? null, + providerInvoiceId: (row.provider_invoice_id as string) ?? null, + hostedUrl: (row.hosted_url as string) ?? null, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapEntitlement(row: Record): Entitlement { + return { + id: row.id as string, + orgId: row.org_id as string, + subscriptionId: (row.subscription_id as string) ?? null, + entitlementKey: row.entitlement_key as string, + valueType: row.value_type as EntitlementValueType, + enabled: parseBooleanColumn(row.enabled), + limitValue: row.limit_value == null ? null : Number(row.limit_value), + source: row.source as EntitlementSource, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +// ── Helpers ──────────────────────────────────────────────── + +function safeError(message: string): BillingResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +async function pagedList( + executor: SqlExecutor, + sql: string, + values: unknown[], + limit: number, + cursor: CursorPosition | null, + mapper: (row: Record) => T, + cursorDateField = "created_at", +): Promise>> { + try { + const fetchLimit = limit + 1; + let fullSql: string; + let fullValues: unknown[]; + const baseIdx = values.length; + + if (cursor) { + fullSql = `${sql} AND (${cursorDateField}, id) < ($${baseIdx + 2}, $${baseIdx + 3}) ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit, cursor.createdAt, cursor.id]; + } else { + fullSql = `${sql} ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit]; + } + + const result = await executor.execute>(fullSql, fullValues); + const rows = result.rows.map(mapper); + let nextCursor: CursorPosition | null = null; + if (rows.length > limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { + createdAt: (last as unknown as { createdAt: Date }).createdAt.toISOString(), + id: (last as unknown as { id: string }).id, + }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list records"); + } +} + +function jsonOrNull(v: Record | null | undefined): string | null { + return v == null ? null : JSON.stringify(v); +} + +function isoOrNull(v: Date | null | undefined): string | null { + return v == null ? null : v.toISOString(); +} + +// ── Repository factory ───────────────────────────────────── + +export function createBillingRepository(executor: SqlExecutor): BillingRepository { + return { + // ── Plans ────────────────────────────────────────────── + async createPlan(input: CreatePlanInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO billing_plans + (id, code, name, description, status, billing_interval, price_amount_cents, price_currency, metadata, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (code) DO NOTHING + RETURNING *`, + [ + input.id, + input.code, + input.name, + input.description ?? null, + input.status ?? "active", + input.billingInterval ?? "month", + input.priceAmountCents ?? null, + input.priceCurrency ?? "usd", + jsonOrNull(input.metadata), + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "plan" } }; + } + return { ok: true, value: mapPlan(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "plan" } }; + } + return safeError("Failed to create plan"); + } + }, + + async getPlan(id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_plans WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapPlan(result.rows[0]!) }; + } catch { + return safeError("Failed to get plan"); + } + }, + + async getPlanByCode(code: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_plans WHERE code = $1`, + [code], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapPlan(result.rows[0]!) }; + } catch { + return safeError("Failed to get plan"); + } + }, + + async listPlans(query: ListPlansQuery = {}): Promise> { + try { + const conditions: string[] = []; + const values: unknown[] = []; + if (query.status) { + conditions.push(`status = $${values.length + 1}`); + values.push(query.status); + } + const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : ""; + const result = await executor.execute>( + `SELECT * FROM billing_plans ${where} ORDER BY code ASC`, + values, + ); + return { ok: true, value: result.rows.map(mapPlan) }; + } catch { + return safeError("Failed to list plans"); + } + }, + + // ── Billing customers ────────────────────────────────── + async upsertBillingCustomer( + input: UpsertBillingCustomerInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO billing_billing_customers + (id, org_id, display_name, email, status, provider, provider_customer_id, metadata, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id) DO UPDATE SET + display_name = EXCLUDED.display_name, + email = EXCLUDED.email, + status = EXCLUDED.status, + provider = EXCLUDED.provider, + provider_customer_id = EXCLUDED.provider_customer_id, + metadata = EXCLUDED.metadata, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [ + input.id, + input.orgId, + input.displayName ?? null, + input.email ?? null, + input.status ?? "active", + input.provider ?? null, + input.providerCustomerId ?? null, + jsonOrNull(input.metadata), + ], + ); + return { ok: true, value: mapBillingCustomer(result.rows[0]!) }; + } catch { + return safeError("Failed to upsert billing customer"); + } + }, + + async getBillingCustomer(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_billing_customers WHERE org_id = $1`, + [orgId], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapBillingCustomer(result.rows[0]!) }; + } catch { + return safeError("Failed to get billing customer"); + } + }, + + // ── Subscriptions ────────────────────────────────────── + async createSubscription( + input: CreateSubscriptionInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO billing_subscriptions + (id, org_id, billing_customer_id, plan_id, status, + current_period_start, current_period_end, trial_end, cancel_at, canceled_at, + provider, provider_subscription_id, metadata, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [ + input.id, + input.orgId, + input.billingCustomerId, + input.planId, + input.status ?? "active", + isoOrNull(input.currentPeriodStart), + isoOrNull(input.currentPeriodEnd), + isoOrNull(input.trialEnd), + isoOrNull(input.cancelAt), + isoOrNull(input.canceledAt), + input.provider ?? null, + input.providerSubscriptionId ?? null, + jsonOrNull(input.metadata), + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "subscription" } }; + } + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "subscription" } }; + } + return safeError("Failed to create subscription"); + } + }, + + async getSubscription( + orgId: string, + id: string, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_subscriptions WHERE org_id = $1 AND id = $2`, + [orgId, id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch { + return safeError("Failed to get subscription"); + } + }, + + async getActiveSubscription(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_subscriptions + WHERE org_id = $1 AND status IN ('trialing', 'active', 'past_due') + ORDER BY created_at DESC + LIMIT 1`, + [orgId], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch { + return safeError("Failed to get active subscription"); + } + }, + + async listSubscriptions( + orgId: string, + params: PageQueryParams, + ): Promise>> { + return pagedList( + executor, + "SELECT * FROM billing_subscriptions WHERE org_id = $1", + [orgId], + params.limit, + params.cursor, + mapSubscription, + ); + }, + + async updateSubscription( + orgId: string, + id: string, + input: UpdateSubscriptionInput, + ): Promise> { + try { + const sets: string[] = []; + const values: unknown[] = [orgId, id]; + let idx = 3; + const push = (col: string, val: unknown) => { + sets.push(`${col} = $${idx}`); + values.push(val); + idx++; + }; + if (input.status !== undefined) push("status", input.status); + if (input.currentPeriodStart !== undefined) + push("current_period_start", isoOrNull(input.currentPeriodStart)); + if (input.currentPeriodEnd !== undefined) + push("current_period_end", isoOrNull(input.currentPeriodEnd)); + if (input.trialEnd !== undefined) push("trial_end", isoOrNull(input.trialEnd)); + if (input.cancelAt !== undefined) push("cancel_at", isoOrNull(input.cancelAt)); + if (input.canceledAt !== undefined) + push("canceled_at", isoOrNull(input.canceledAt)); + if (input.provider !== undefined) push("provider", input.provider); + if (input.providerSubscriptionId !== undefined) + push("provider_subscription_id", input.providerSubscriptionId); + if (input.metadata !== undefined) push("metadata", jsonOrNull(input.metadata)); + + if (sets.length === 0) { + // Nothing to update — return current + return this.getSubscription(orgId, id); + } + sets.push(`updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`); + const sql = `UPDATE billing_subscriptions SET ${sets.join(", ")} + WHERE org_id = $1 AND id = $2 RETURNING *`; + const result = await executor.execute>(sql, values); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch { + return safeError("Failed to update subscription"); + } + }, + + // ── Invoices ─────────────────────────────────────────── + async upsertInvoice(input: UpsertInvoiceInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO billing_invoices + (id, org_id, billing_customer_id, subscription_id, number, status, + amount_due_cents, amount_paid_cents, currency, + issued_at, due_at, paid_at, period_start, period_end, + provider, provider_invoice_id, hosted_url, metadata, + created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (id) DO UPDATE SET + status = EXCLUDED.status, + amount_due_cents = EXCLUDED.amount_due_cents, + amount_paid_cents = EXCLUDED.amount_paid_cents, + currency = EXCLUDED.currency, + issued_at = EXCLUDED.issued_at, + due_at = EXCLUDED.due_at, + paid_at = EXCLUDED.paid_at, + period_start = EXCLUDED.period_start, + period_end = EXCLUDED.period_end, + provider = EXCLUDED.provider, + provider_invoice_id = EXCLUDED.provider_invoice_id, + hosted_url = EXCLUDED.hosted_url, + metadata = EXCLUDED.metadata, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE billing_invoices.org_id = EXCLUDED.org_id + RETURNING *`, + [ + input.id, + input.orgId, + input.billingCustomerId, + input.subscriptionId ?? null, + input.number ?? null, + input.status ?? "draft", + input.amountDueCents ?? 0, + input.amountPaidCents ?? 0, + input.currency ?? "usd", + isoOrNull(input.issuedAt), + isoOrNull(input.dueAt), + isoOrNull(input.paidAt), + isoOrNull(input.periodStart), + isoOrNull(input.periodEnd), + input.provider ?? null, + input.providerInvoiceId ?? null, + input.hostedUrl ?? null, + jsonOrNull(input.metadata), + ], + ); + if (result.rowCount === 0) { + // Cross-org id collision — refuse rather than leak + return { ok: false, error: { kind: "conflict", entity: "invoice" } }; + } + return { ok: true, value: mapInvoice(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "invoice" } }; + } + return safeError("Failed to upsert invoice"); + } + }, + + async getInvoice(orgId: string, id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_invoices WHERE org_id = $1 AND id = $2`, + [orgId, id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapInvoice(result.rows[0]!) }; + } catch { + return safeError("Failed to get invoice"); + } + }, + + async listInvoices( + query: ListInvoicesQuery, + params: PageQueryParams, + ): Promise>> { + const conditions: string[] = ["org_id = $1"]; + const values: unknown[] = [query.orgId]; + let idx = 2; + if (query.billingCustomerId) { + conditions.push(`billing_customer_id = $${idx}`); + values.push(query.billingCustomerId); + idx++; + } + if (query.subscriptionId) { + conditions.push(`subscription_id = $${idx}`); + values.push(query.subscriptionId); + idx++; + } + if (query.status) { + conditions.push(`status = $${idx}`); + values.push(query.status); + idx++; + } + const where = conditions.join(" AND "); + return pagedList( + executor, + `SELECT * FROM billing_invoices WHERE ${where}`, + values, + params.limit, + params.cursor, + mapInvoice, + ); + }, + + // ── Entitlements ─────────────────────────────────────── + async upsertEntitlement( + input: UpsertEntitlementInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO billing_entitlements + (id, org_id, subscription_id, entitlement_key, value_type, + enabled, limit_value, source, metadata, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id, entitlement_key) DO UPDATE SET + subscription_id = EXCLUDED.subscription_id, + value_type = EXCLUDED.value_type, + enabled = EXCLUDED.enabled, + limit_value = EXCLUDED.limit_value, + source = EXCLUDED.source, + metadata = EXCLUDED.metadata, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [ + input.id, + input.orgId, + input.subscriptionId ?? null, + input.entitlementKey, + input.valueType, + input.enabled ?? true, + input.limitValue ?? null, + input.source ?? "plan", + jsonOrNull(input.metadata), + ], + ); + return { ok: true, value: mapEntitlement(result.rows[0]!) }; + } catch { + return safeError("Failed to upsert entitlement"); + } + }, + + async getEntitlement( + orgId: string, + entitlementKey: string, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM billing_entitlements WHERE org_id = $1 AND entitlement_key = $2`, + [orgId, entitlementKey], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapEntitlement(result.rows[0]!) }; + } catch { + return safeError("Failed to get entitlement"); + } + }, + + async listEntitlements( + query: ListEntitlementsQuery, + ): Promise> { + try { + const conditions: string[] = ["org_id = $1"]; + const values: unknown[] = [query.orgId]; + let idx = 2; + if (query.subscriptionId) { + conditions.push(`subscription_id = $${idx}`); + values.push(query.subscriptionId); + idx++; + } + if (query.source) { + conditions.push(`source = $${idx}`); + values.push(query.source); + idx++; + } + const result = await executor.execute>( + `SELECT * FROM billing_entitlements WHERE ${conditions.join(" AND ")} + ORDER BY entitlement_key ASC`, + values, + ); + return { ok: true, value: result.rows.map(mapEntitlement) }; + } catch { + return safeError("Failed to list entitlements"); + } + }, + + // ── Billing summary ──────────────────────────────────── + async getBillingSummary(orgId: string): Promise> { + // PERF3 (task 0132): collapse 4 sequential round-trips into 2 parallel + // phases on the shared connection pool. Phase 1 (customer + active + // subscription) then phase 2 (plan + entitlements) each run concurrently; + // the plan read follows because it needs the resolved subscription. Query + // order is preserved (customer, subscription, plan, entitlements). + const [customerRes, subRes] = await Promise.all([ + this.getBillingCustomer(orgId), + this.getActiveSubscription(orgId), + ]); + + const customer = customerRes.ok ? customerRes.value : null; + if (!customerRes.ok && customerRes.error.kind === "internal") { + return safeError(customerRes.error.message); + } + + const activeSubscription = subRes.ok ? subRes.value : null; + if (!subRes.ok && subRes.error.kind === "internal") { + return safeError(subRes.error.message); + } + + const [planRes, entRes] = await Promise.all([ + activeSubscription ? this.getPlan(activeSubscription.planId) : Promise.resolve(null), + this.listEntitlements({ orgId }), + ]); + + let plan: Plan | null = null; + if (planRes) { + if (planRes.ok) plan = planRes.value; + else if (planRes.error.kind === "internal") return safeError(planRes.error.message); + } + + if (!entRes.ok) { + const msg = entRes.error.kind === "internal" ? entRes.error.message : "Failed to load entitlements"; + return safeError(msg); + } + + return { + ok: true, + value: { + customer, + activeSubscription, + plan, + entitlements: entRes.value, + }, + }; + }, + }; +} diff --git a/packages/db/src/billing/types.ts b/packages/db/src/billing/types.ts new file mode 100644 index 0000000..421e3fc --- /dev/null +++ b/packages/db/src/billing/types.ts @@ -0,0 +1,317 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +// ── Result type ───────────────────────────────────────────── + +export type BillingRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type BillingResult = + | { ok: true; value: T } + | { ok: false; error: BillingRepositoryError }; + +// ── Cursor pagination ─────────────────────────────────────── + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +// ── Plans ─────────────────────────────────────────────────── + +export type PlanStatus = "active" | "archived"; +export type BillingInterval = "month" | "year" | "none"; + +export interface Plan { + id: string; + code: string; + name: string; + description: string | null; + status: PlanStatus; + billingInterval: BillingInterval; + priceAmountCents: number | null; + priceCurrency: string; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreatePlanInput { + id: string; + code: string; + name: string; + description?: string | null; + status?: PlanStatus; + billingInterval?: BillingInterval; + priceAmountCents?: number | null; + priceCurrency?: string; + metadata?: Record | null; +} + +export interface ListPlansQuery { + status?: PlanStatus; +} + +// ── Billing customers ─────────────────────────────────────── + +export type BillingCustomerStatus = "active" | "inactive"; + +export interface BillingCustomer { + id: string; + orgId: string; + displayName: string | null; + email: string | null; + status: BillingCustomerStatus; + /** Opaque adapter id (e.g. 'stripe'). */ + provider: string | null; + /** Opaque external customer reference. Never a secret/API key. */ + providerCustomerId: string | null; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; + updatedAt: Date; +} + +export interface UpsertBillingCustomerInput { + id: string; + orgId: string; + displayName?: string | null; + email?: string | null; + status?: BillingCustomerStatus; + provider?: string | null; + providerCustomerId?: string | null; + metadata?: Record | null; +} + +// ── Subscriptions ─────────────────────────────────────────── + +export type SubscriptionStatus = + | "trialing" + | "active" + | "past_due" + | "canceled" + | "expired"; + +export interface Subscription { + id: string; + orgId: string; + billingCustomerId: string; + planId: string; + status: SubscriptionStatus; + currentPeriodStart: Date | null; + currentPeriodEnd: Date | null; + trialEnd: Date | null; + cancelAt: Date | null; + canceledAt: Date | null; + provider: string | null; + providerSubscriptionId: string | null; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateSubscriptionInput { + id: string; + orgId: string; + billingCustomerId: string; + planId: string; + status?: SubscriptionStatus; + currentPeriodStart?: Date | null; + currentPeriodEnd?: Date | null; + trialEnd?: Date | null; + cancelAt?: Date | null; + canceledAt?: Date | null; + provider?: string | null; + providerSubscriptionId?: string | null; + metadata?: Record | null; +} + +export interface UpdateSubscriptionInput { + status?: SubscriptionStatus; + currentPeriodStart?: Date | null; + currentPeriodEnd?: Date | null; + trialEnd?: Date | null; + cancelAt?: Date | null; + canceledAt?: Date | null; + /** Opaque payment-provider id (e.g. 'polar'); set when linking a provider sub. */ + provider?: string | null; + /** Opaque provider subscription id; set/backfilled from verified webhooks. */ + providerSubscriptionId?: string | null; + metadata?: Record | null; +} + +// ── Invoices ──────────────────────────────────────────────── + +export type InvoiceStatus = "draft" | "open" | "paid" | "void" | "uncollectible"; + +export interface Invoice { + id: string; + orgId: string; + billingCustomerId: string; + subscriptionId: string | null; + number: string | null; + status: InvoiceStatus; + amountDueCents: number; + amountPaidCents: number; + currency: string; + issuedAt: Date | null; + dueAt: Date | null; + paidAt: Date | null; + periodStart: Date | null; + periodEnd: Date | null; + provider: string | null; + providerInvoiceId: string | null; + /** Safe display URL only; callers must never embed bearer tokens or session secrets. */ + hostedUrl: string | null; + /** Bounded safe metadata only — no secrets, tokens, credentials, or raw provider payloads. */ + metadata: Record | null; + createdAt: Date; + updatedAt: Date; +} + +export interface UpsertInvoiceInput { + id: string; + orgId: string; + billingCustomerId: string; + subscriptionId?: string | null; + number?: string | null; + status?: InvoiceStatus; + amountDueCents?: number; + amountPaidCents?: number; + currency?: string; + issuedAt?: Date | null; + dueAt?: Date | null; + paidAt?: Date | null; + periodStart?: Date | null; + periodEnd?: Date | null; + provider?: string | null; + providerInvoiceId?: string | null; + hostedUrl?: string | null; + metadata?: Record | null; +} + +export interface ListInvoicesQuery { + orgId: string; + billingCustomerId?: string; + subscriptionId?: string; + status?: InvoiceStatus; +} + +// ── Entitlements ──────────────────────────────────────────── + +export type EntitlementValueType = "boolean" | "quantity" | "feature"; +export type EntitlementSource = "plan" | "override"; + +export interface Entitlement { + id: string; + orgId: string; + subscriptionId: string | null; + entitlementKey: string; + valueType: EntitlementValueType; + enabled: boolean; + /** NULL means unlimited (when enabled). */ + limitValue: number | null; + source: EntitlementSource; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; + updatedAt: Date; +} + +export interface UpsertEntitlementInput { + id: string; + orgId: string; + subscriptionId?: string | null; + entitlementKey: string; + valueType: EntitlementValueType; + enabled?: boolean; + limitValue?: number | null; + source?: EntitlementSource; + metadata?: Record | null; +} + +export interface ListEntitlementsQuery { + orgId: string; + subscriptionId?: string; + source?: EntitlementSource; +} + +// ── Billing summary ───────────────────────────────────────── + +export interface BillingSummary { + customer: BillingCustomer | null; + activeSubscription: Subscription | null; + plan: Plan | null; + entitlements: Entitlement[]; +} + +// ── Repository interface ──────────────────────────────────── + +export interface BillingRepository { + // Plans + createPlan(input: CreatePlanInput): Promise>; + getPlan(id: string): Promise>; + getPlanByCode(code: string): Promise>; + listPlans(query?: ListPlansQuery): Promise>; + + // Billing customers + upsertBillingCustomer( + input: UpsertBillingCustomerInput, + ): Promise>; + getBillingCustomer(orgId: string): Promise>; + + // Subscriptions + createSubscription( + input: CreateSubscriptionInput, + ): Promise>; + getSubscription( + orgId: string, + id: string, + ): Promise>; + getActiveSubscription(orgId: string): Promise>; + listSubscriptions( + orgId: string, + params: PageQueryParams, + ): Promise>>; + updateSubscription( + orgId: string, + id: string, + input: UpdateSubscriptionInput, + ): Promise>; + + // Invoices + upsertInvoice(input: UpsertInvoiceInput): Promise>; + getInvoice(orgId: string, id: string): Promise>; + listInvoices( + query: ListInvoicesQuery, + params: PageQueryParams, + ): Promise>>; + + // Entitlements + upsertEntitlement( + input: UpsertEntitlementInput, + ): Promise>; + getEntitlement( + orgId: string, + entitlementKey: string, + ): Promise>; + listEntitlements( + query: ListEntitlementsQuery, + ): Promise>; + + // Billing summary + getBillingSummary(orgId: string): Promise>; +} diff --git a/packages/db/src/config/index.ts b/packages/db/src/config/index.ts new file mode 100644 index 0000000..936763a --- /dev/null +++ b/packages/db/src/config/index.ts @@ -0,0 +1,23 @@ +export type { + ScopeKind, + OrgScope, + ProjectScope, + EnvironmentScope, + Scope, + ConfigRepositoryError, + ConfigResult, + CursorPosition, + PageQueryParams, + PagedResult, + Setting, + CreateSettingInput, + UpdateSettingInput, + FeatureFlag, + CreateFeatureFlagInput, + UpdateFeatureFlagInput, + SecretMetadata, + CreateSecretMetadataInput, + ConfigRepository, +} from "./types.js"; + +export { createConfigRepository } from "./repository.js"; diff --git a/packages/db/src/config/repository.ts b/packages/db/src/config/repository.ts new file mode 100644 index 0000000..93359b2 --- /dev/null +++ b/packages/db/src/config/repository.ts @@ -0,0 +1,412 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + ConfigRepository, + ConfigResult, + CreateFeatureFlagInput, + CreateSecretMetadataInput, + CreateSettingInput, + CursorPosition, + FeatureFlag, + PagedResult, + PageQueryParams, + Scope, + SecretMetadata, + Setting, + UpdateFeatureFlagInput, + UpdateSettingInput, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseBooleanColumn, parseJsonColumn, parseNullableJsonColumn } from "../json.js"; + +// ── Scope helpers ────────────────────────────────────────── + +function scopeColumns(scope: Scope): { + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: string; +} { + switch (scope.kind) { + case "organization": + return { orgId: scope.orgId, projectId: null, environmentId: null, scopeKind: "organization" }; + case "project": + return { orgId: scope.orgId, projectId: scope.projectId, environmentId: null, scopeKind: "project" }; + case "environment": + return { orgId: scope.orgId, projectId: scope.projectId, environmentId: scope.environmentId, scopeKind: "environment" }; + } +} + +function scopeWhere(scope: Scope): { clause: string; params: unknown[] } { + switch (scope.kind) { + case "organization": + return { clause: "org_id = $1 AND scope_kind = 'organization'", params: [scope.orgId] }; + case "project": + return { clause: "org_id = $1 AND project_id = $2 AND scope_kind = 'project'", params: [scope.orgId, scope.projectId] }; + case "environment": + return { clause: "org_id = $1 AND project_id = $2 AND environment_id = $3 AND scope_kind = 'environment'", params: [scope.orgId, scope.projectId, scope.environmentId] }; + } +} + +// ── Row mappers ──────────────────────────────────────────── + +function mapSetting(row: Record): Setting { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + scopeKind: row.scope_kind as Setting["scopeKind"], + key: row.key as string, + value: parseJsonColumn(row.value, null), + description: (row.description as string) ?? null, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapFeatureFlag(row: Record): FeatureFlag { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + scopeKind: row.scope_kind as FeatureFlag["scopeKind"], + flagKey: row.flag_key as string, + enabled: parseBooleanColumn(row.enabled), + value: parseNullableJsonColumn(row.value), + description: (row.description as string) ?? null, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapSecretMetadata(row: Record): SecretMetadata { + // Intentionally omit ciphertext_envelope — never expose through repository + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + scopeKind: row.scope_kind as SecretMetadata["scopeKind"], + secretKey: row.secret_key as string, + displayName: (row.display_name as string) ?? null, + status: row.status as string, + version: row.version as number, + rotationPolicy: (row.rotation_policy as string) ?? null, + lastRotatedAt: row.last_rotated_at ? new Date(row.last_rotated_at as string) : null, + expiresAt: row.expires_at ? new Date(row.expires_at as string) : null, + createdBy: row.created_by as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +// ── Secret metadata safe columns (no ciphertext_envelope) ── + +const SECRET_METADATA_SAFE_COLUMNS = `id, org_id, project_id, environment_id, scope_kind, secret_key, display_name, status, version, rotation_policy, last_rotated_at, expires_at, created_by, created_at, updated_at`; + +function safeError(message: string): ConfigResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +function isCheckViolation(err: unknown): boolean { + return ( + typeof err === "object" && + err !== null && + "code" in err && + (err as { code: string }).code === "23514" + ); +} + +// ── Paged list helper ────────────────────────────────────── + +async function pagedList( + executor: SqlExecutor, + table: string, + scope: Scope, + params: PageQueryParams, + mapper: (row: Record) => T, + selectColumns = "*", +): Promise>> { + try { + const sw = scopeWhere(scope); + const fetchLimit = params.limit + 1; + const baseIdx = sw.params.length; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT ${selectColumns} FROM ${table} + WHERE ${sw.clause} + AND (created_at, id) < ($${baseIdx + 2}, $${baseIdx + 3}) + ORDER BY created_at DESC, id DESC + LIMIT $${baseIdx + 1}`; + values = [...sw.params, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT ${selectColumns} FROM ${table} + WHERE ${sw.clause} + ORDER BY created_at DESC, id DESC + LIMIT $${baseIdx + 1}`; + values = [...sw.params, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapper); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { + createdAt: (last as unknown as { createdAt: Date }).createdAt.toISOString(), + id: (last as unknown as { id: string }).id, + }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError(`Failed to list from ${table}`); + } +} + +// ── Repository factory ───────────────────────────────────── + +export function createConfigRepository(executor: SqlExecutor): ConfigRepository { + return { + // ── Settings ────────────────────────────────────────── + + async createSetting(input: CreateSettingInput): Promise> { + try { + const sc = scopeColumns(input.scope); + const result = await executor.execute>( + `INSERT INTO config_settings (id, org_id, project_id, environment_id, scope_kind, key, value, description, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), COALESCE(environment_id, '00000000-0000-0000-0000-000000000000'), key) DO NOTHING + RETURNING *`, + [input.id, sc.orgId, sc.projectId, sc.environmentId, sc.scopeKind, input.key, JSON.stringify(input.value), input.description ?? null], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "setting" } }; + } + return { ok: true, value: mapSetting(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "setting" } }; + } + if (isCheckViolation(err)) { + return safeError("Invalid scope for setting"); + } + return safeError("Failed to create setting"); + } + }, + + async updateSetting(orgId: string, settingId: string, input: UpdateSettingInput): Promise> { + try { + const result = await executor.execute>( + `UPDATE config_settings + SET value = $3, description = COALESCE($4, description), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 + RETURNING *`, + [orgId, settingId, JSON.stringify(input.value), input.description ?? null], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSetting(result.rows[0]!) }; + } catch { + return safeError("Failed to update setting"); + } + }, + + async getSetting(orgId: string, settingId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM config_settings WHERE org_id = $1 AND id = $2`, + [orgId, settingId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSetting(result.rows[0]!) }; + } catch { + return safeError("Failed to get setting"); + } + }, + + async listSettings(scope: Scope, params: PageQueryParams): Promise>> { + return pagedList(executor, "config_settings", scope, params, mapSetting); + }, + + // ── Feature flags ───────────────────────────────────── + + async createFeatureFlag(input: CreateFeatureFlagInput): Promise> { + try { + const sc = scopeColumns(input.scope); + const result = await executor.execute>( + `INSERT INTO config_feature_flags (id, org_id, project_id, environment_id, scope_kind, flag_key, enabled, value, description, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), COALESCE(environment_id, '00000000-0000-0000-0000-000000000000'), flag_key) DO NOTHING + RETURNING *`, + [input.id, sc.orgId, sc.projectId, sc.environmentId, sc.scopeKind, input.flagKey, input.enabled ?? false, input.value ? JSON.stringify(input.value) : null, input.description ?? null], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "feature_flag" } }; + } + return { ok: true, value: mapFeatureFlag(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "feature_flag" } }; + } + if (isCheckViolation(err)) { + return safeError("Invalid scope for feature flag"); + } + return safeError("Failed to create feature flag"); + } + }, + + async updateFeatureFlag(orgId: string, flagId: string, input: UpdateFeatureFlagInput): Promise> { + try { + const setClauses: string[] = ["updated_at = now()"]; + const values: unknown[] = [orgId, flagId]; + let idx = 3; + if (input.enabled !== undefined) { + setClauses.push(`enabled = $${idx}`); + values.push(input.enabled); + idx++; + } + if (input.value !== undefined) { + setClauses.push(`value = $${idx}`); + values.push(JSON.stringify(input.value)); + idx++; + } + if (input.description !== undefined) { + setClauses.push(`description = $${idx}`); + values.push(input.description); + idx++; + } + const result = await executor.execute>( + `UPDATE config_feature_flags SET ${setClauses.join(", ")} WHERE org_id = $1 AND id = $2 RETURNING *`, + values, + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapFeatureFlag(result.rows[0]!) }; + } catch { + return safeError("Failed to update feature flag"); + } + }, + + async getFeatureFlag(orgId: string, flagId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM config_feature_flags WHERE org_id = $1 AND id = $2`, + [orgId, flagId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapFeatureFlag(result.rows[0]!) }; + } catch { + return safeError("Failed to get feature flag"); + } + }, + + async listFeatureFlags(scope: Scope, params: PageQueryParams): Promise>> { + return pagedList(executor, "config_feature_flags", scope, params, mapFeatureFlag); + }, + + // ── Secret metadata ─────────────────────────────────── + + async createSecretMetadata(input: CreateSecretMetadataInput): Promise> { + try { + const sc = scopeColumns(input.scope); + const hasCiphertext = input.ciphertextEnvelope !== undefined; + const sql = hasCiphertext + ? `INSERT INTO config_secret_metadata (id, org_id, project_id, environment_id, scope_kind, secret_key, display_name, status, version, rotation_policy, expires_at, created_by, ciphertext_envelope, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, 'active', 1, $8, $9, $10, $11, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING ${SECRET_METADATA_SAFE_COLUMNS}` + : `INSERT INTO config_secret_metadata (id, org_id, project_id, environment_id, scope_kind, secret_key, display_name, status, version, rotation_policy, expires_at, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, 'active', 1, $8, $9, $10, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING ${SECRET_METADATA_SAFE_COLUMNS}`; + const params = [input.id, sc.orgId, sc.projectId, sc.environmentId, sc.scopeKind, input.secretKey, input.displayName ?? null, input.rotationPolicy ?? null, input.expiresAt?.toISOString() ?? null, input.createdBy]; + if (hasCiphertext) { + params.push(input.ciphertextEnvelope!); + } + const result = await executor.execute>(sql, params); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "secret_metadata" } }; + } + return { ok: true, value: mapSecretMetadata(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "secret_metadata" } }; + } + if (isCheckViolation(err)) { + return safeError("Invalid scope for secret metadata"); + } + return safeError("Failed to create secret metadata"); + } + }, + + async listSecretMetadata(scope: Scope, params: PageQueryParams): Promise>> { + return pagedList(executor, "config_secret_metadata", scope, params, mapSecretMetadata, SECRET_METADATA_SAFE_COLUMNS); + }, + + async getSecretMetadata(orgId: string, secretId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT ${SECRET_METADATA_SAFE_COLUMNS} FROM config_secret_metadata WHERE org_id = $1 AND id = $2`, + [orgId, secretId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSecretMetadata(result.rows[0]!) }; + } catch { + return safeError("Failed to get secret metadata"); + } + }, + + async rotateSecretMetadata(orgId: string, secretId: string, ciphertextEnvelope?: string): Promise> { + try { + const hasCiphertext = ciphertextEnvelope !== undefined; + const sql = hasCiphertext + ? `UPDATE config_secret_metadata + SET version = version + 1, last_rotated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), ciphertext_envelope = $3 + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING ${SECRET_METADATA_SAFE_COLUMNS}` + : `UPDATE config_secret_metadata + SET version = version + 1, last_rotated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING ${SECRET_METADATA_SAFE_COLUMNS}`; + const params: unknown[] = [orgId, secretId]; + if (hasCiphertext) { + params.push(ciphertextEnvelope); + } + const result = await executor.execute>(sql, params); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSecretMetadata(result.rows[0]!) }; + } catch { + return safeError("Failed to rotate secret metadata"); + } + }, + + async revokeSecretMetadata(orgId: string, secretId: string): Promise> { + try { + const result = await executor.execute>( + `UPDATE config_secret_metadata + SET status = 'revoked', updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING ${SECRET_METADATA_SAFE_COLUMNS}`, + [orgId, secretId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSecretMetadata(result.rows[0]!) }; + } catch { + return safeError("Failed to revoke secret metadata"); + } + }, + }; +} diff --git a/packages/db/src/config/types.ts b/packages/db/src/config/types.ts new file mode 100644 index 0000000..e68490f --- /dev/null +++ b/packages/db/src/config/types.ts @@ -0,0 +1,173 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; +import type { Uuid } from "../ids/index.js"; + +// ── Shared scope types ────────────────────────────────────── + +export type ScopeKind = "organization" | "project" | "environment"; + +export interface OrgScope { + kind: "organization"; + orgId: string; +} + +export interface ProjectScope { + kind: "project"; + orgId: string; + projectId: string; +} + +export interface EnvironmentScope { + kind: "environment"; + orgId: string; + projectId: string; + environmentId: string; +} + +export type Scope = OrgScope | ProjectScope | EnvironmentScope; + +// ── Result type ───────────────────────────────────────────── + +export type ConfigRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type ConfigResult = + | { ok: true; value: T } + | { ok: false; error: ConfigRepositoryError }; + +// ── Cursor pagination (matches existing convention) ───────── + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +// ── Settings ──────────────────────────────────────────────── + +export interface Setting { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: ScopeKind; + key: string; + value: unknown; + description: string | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateSettingInput { + id: string; + scope: Scope; + key: string; + value: unknown; + description?: string; +} + +export interface UpdateSettingInput { + value: unknown; + description?: string; +} + +// ── Feature flags ─────────────────────────────────────────── + +export interface FeatureFlag { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: ScopeKind; + flagKey: string; + enabled: boolean; + value: unknown | null; + description: string | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateFeatureFlagInput { + id: string; + scope: Scope; + flagKey: string; + enabled?: boolean; + value?: unknown; + description?: string; +} + +export interface UpdateFeatureFlagInput { + enabled?: boolean; + value?: unknown; + description?: string; +} + +// ── Secret metadata ───────────────────────────────────────── +// NOTE: No plaintext secret value fields. Only metadata. + +export interface SecretMetadata { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + scopeKind: ScopeKind; + secretKey: string; + displayName: string | null; + status: string; + version: number; + rotationPolicy: string | null; + lastRotatedAt: Date | null; + expiresAt: Date | null; + createdBy: string; + createdAt: Date; + updatedAt: Date; + // NOTE: ciphertext_envelope is intentionally excluded from the type. + // It is never exposed through the repository read surface. +} + +export interface CreateSecretMetadataInput { + id: string; + scope: Scope; + secretKey: string; + displayName?: string; + rotationPolicy?: string; + expiresAt?: Date; + /** UUID column `config_secret_metadata.created_by` — must be a decoded `Uuid`, + * not a public `usr_` id. Branding makes a missing decode a compile error. */ + createdBy: Uuid; + /** JSON-serialized ciphertext envelope. Write-only — never returned. */ + ciphertextEnvelope?: string; +} + +// ── Repository interface ──────────────────────────────────── + +export interface ConfigRepository { + // Settings + createSetting(input: CreateSettingInput): Promise>; + updateSetting(orgId: string, settingId: string, input: UpdateSettingInput): Promise>; + getSetting(orgId: string, settingId: string): Promise>; + listSettings(scope: Scope, params: PageQueryParams): Promise>>; + + // Feature flags + createFeatureFlag(input: CreateFeatureFlagInput): Promise>; + updateFeatureFlag(orgId: string, flagId: string, input: UpdateFeatureFlagInput): Promise>; + getFeatureFlag(orgId: string, flagId: string): Promise>; + listFeatureFlags(scope: Scope, params: PageQueryParams): Promise>>; + + // Secret metadata + createSecretMetadata(input: CreateSecretMetadataInput): Promise>; + listSecretMetadata(scope: Scope, params: PageQueryParams): Promise>>; + getSecretMetadata(orgId: string, secretId: string): Promise>; + rotateSecretMetadata(orgId: string, secretId: string, ciphertextEnvelope?: string): Promise>; + revokeSecretMetadata(orgId: string, secretId: string): Promise>; +} diff --git a/packages/db/src/d1/adapter.ts b/packages/db/src/d1/adapter.ts new file mode 100644 index 0000000..1e71ce7 --- /dev/null +++ b/packages/db/src/d1/adapter.ts @@ -0,0 +1,38 @@ +import type { D1Binding } from "./binding.js"; + +export interface DbHealthResult { + configured: boolean; + reachable: boolean; +} + +export interface D1Adapter { + ping(): Promise; + dispose(): Promise; +} + +/** + * Health probe for the platform database. + * + * `configured` answers "is the binding present in this environment's wrangler + * config"; `reachable` answers "did a trivial statement actually return". They + * are separate because a missing binding is an operator/wiring problem and an + * unreachable database is a platform problem, and the health endpoint should + * not conflate them. + */ +export function createD1Adapter(binding: D1Binding | undefined | null): D1Adapter { + return { + async ping(): Promise { + if (!binding) return { configured: false, reachable: false }; + try { + await binding.prepare("SELECT 1 AS ok").all(); + return { configured: true, reachable: true }; + } catch { + return { configured: true, reachable: false }; + } + }, + + async dispose(): Promise { + // Nothing to release: a D1 binding holds no connection. + }, + }; +} diff --git a/packages/db/src/d1/binding.ts b/packages/db/src/d1/binding.ts new file mode 100644 index 0000000..67ff75d --- /dev/null +++ b/packages/db/src/d1/binding.ts @@ -0,0 +1,28 @@ +// Structural types for the Cloudflare D1 binding. +// +// Declared here rather than imported from `@cloudflare/workers-types` so that +// `@saas/db` stays runtime- and dependency-free: the Workers that own the +// binding satisfy these shapes exactly, and tests can hand in a fake without +// pulling the Workers type surface into a plain Node package. + +export interface D1Meta { + changes?: number; + last_row_id?: number; + rows_read?: number; + rows_written?: number; +} + +export interface D1Result> { + results?: T[]; + success?: boolean; + meta?: D1Meta; +} + +export interface D1PreparedStatement { + bind(...values: unknown[]): D1PreparedStatement; + all>(): Promise>; +} + +export interface D1Binding { + prepare(query: string): D1PreparedStatement; +} diff --git a/packages/db/src/d1/errors.ts b/packages/db/src/d1/errors.ts new file mode 100644 index 0000000..accb76a --- /dev/null +++ b/packages/db/src/d1/errors.ts @@ -0,0 +1,34 @@ +// Constraint-violation detection for D1. +// +// SQLite reports a violated uniqueness constraint as an error message, not a +// code: D1 surfaces `D1_ERROR: UNIQUE constraint failed: .` +// (and `… : PRIMARY KEY constraint failed` for the implicit index). There is +// no SQLSTATE to compare against, so the message is the signal. +// +// Repositories use this to turn a losing insert into a `conflict` result +// instead of a 500 — the shape callers already branch on. + +function messageOf(err: unknown): string { + if (typeof err === "string") return err; + if (err instanceof Error) return err.message; + if (typeof err === "object" && err !== null && "message" in err) { + return String((err as { message: unknown }).message ?? ""); + } + return ""; +} + +/** True when the error is SQLite refusing a duplicate key. */ +export function isUniqueViolation(err: unknown): boolean { + return /(UNIQUE|PRIMARY KEY) constraint failed/i.test(messageOf(err)); +} + +/** True when the error is SQLite refusing a write that breaks a foreign key. */ +export function isForeignKeyViolation(err: unknown): boolean { + return /FOREIGN KEY constraint failed/i.test(messageOf(err)); +} + +/** True when the error is SQLite refusing a write that breaks a CHECK or + * NOT NULL constraint — a caller-supplied value the schema rejects. */ +export function isCheckViolation(err: unknown): boolean { + return /(CHECK|NOT NULL) constraint failed/i.test(messageOf(err)); +} diff --git a/packages/db/src/d1/executor.ts b/packages/db/src/d1/executor.ts new file mode 100644 index 0000000..c4a8e5a --- /dev/null +++ b/packages/db/src/d1/executor.ts @@ -0,0 +1,83 @@ +import type { D1Binding } from "./binding.js"; +import { toBindValue, translatePlaceholders } from "./sql.js"; + +export interface SqlRow { + [column: string]: unknown; +} + +export interface SqlExecutorResult { + rows: T[]; + rowCount: number; +} + +export interface SqlExecutor { + execute( + text: string, + params?: unknown[], + ): Promise>; +} + +export interface TransactionalSqlExecutor extends SqlExecutor { + transaction(fn: (executor: SqlExecutor) => Promise): Promise; +} + +export interface SqlExecutorFactory { + create(binding: D1Binding): SqlExecutor & { dispose(): Promise }; +} + +/** + * The one seam every repository talks to, backed by Cloudflare D1. + * + * D1 is a binding, not a connection: there is no pool to size, no socket to + * reuse across requests, and nothing to dispose. `dispose()` is kept on the + * shape so callers (and their `finally` blocks) are identical whatever backs + * the executor. + * + * `rowCount` is `rows.length`, deliberately: statements whose outcome the + * caller inspects use `RETURNING`, so the count is the number of rows the + * statement actually produced. D1's `meta.changes` is not substituted for it — + * that would silently change what `rowCount === 0` means for every existing + * repository check. + */ +export function createSqlExecutor( + binding: D1Binding, +): TransactionalSqlExecutor & { dispose(): Promise } { + async function execute( + text: string, + params?: unknown[], + ): Promise> { + const { text: sql, values } = translatePlaceholders(text, params ?? []); + const statement = binding.prepare(sql); + const bound = values.length > 0 ? statement.bind(...values.map(toBindValue)) : statement; + const result = await bound.all(); + const rows = (result.results ?? []) as T[]; + return { rows, rowCount: rows.length }; + } + + return { + execute, + + /** + * D1 HAS NO INTERACTIVE TRANSACTIONS. Cloudflare's SQLite exposes atomic + * `batch()` for a statement list decided up front; it cannot hold a + * transaction open across the reads-then-writes a callback performs. + * + * So this runs the callback's statements in order against the same + * database, with no rollback: a failure part-way leaves the earlier + * statements applied. Callers that need all-or-nothing must reach for a + * shape D1 can honor — a single statement with `RETURNING`, an upsert with + * `ON CONFLICT`, or a compensating write on the error path. + * + * Kept as a method (rather than deleted) so the boundary stays visible in + * the code that needs it: every `transaction(...)` call site is a place + * where atomicity was wanted, and is where a reviewer should look first. + */ + async transaction(fn: (executor: SqlExecutor) => Promise): Promise { + return fn({ execute }); + }, + + async dispose(): Promise { + // No connection to release — D1 bindings are stateless per request. + }, + }; +} diff --git a/packages/db/src/d1/index.ts b/packages/db/src/d1/index.ts new file mode 100644 index 0000000..0517e91 --- /dev/null +++ b/packages/db/src/d1/index.ts @@ -0,0 +1,18 @@ +export type { D1Binding, D1PreparedStatement, D1Result, D1Meta } from "./binding.js"; + +export type { D1Adapter, DbHealthResult } from "./adapter.js"; +export { createD1Adapter } from "./adapter.js"; + +export type { + SqlRow, + SqlExecutorResult, + SqlExecutor, + SqlExecutorFactory, + TransactionalSqlExecutor, +} from "./executor.js"; +export { createSqlExecutor } from "./executor.js"; + +export type { TranslatedSql } from "./sql.js"; +export { translatePlaceholders, toBindValue } from "./sql.js"; + +export { isUniqueViolation, isForeignKeyViolation, isCheckViolation } from "./errors.js"; diff --git a/packages/db/src/d1/sql.ts b/packages/db/src/d1/sql.ts new file mode 100644 index 0000000..9328f68 --- /dev/null +++ b/packages/db/src/d1/sql.ts @@ -0,0 +1,109 @@ +// Numbered-placeholder translation for D1. +// +// Every repository in this baseline writes portable SQL with Postgres-style +// numbered placeholders (`$1`, `$2`, …). They are numbered on purpose: a +// placeholder can be referenced out of order (`SET x = $3 WHERE id = $1`) or +// more than once (`created_at, updated_at) VALUES ($5, $5)`), which positional +// `?` cannot express. D1 binds positionally, so the number is resolved here — +// once, in one tested place — instead of forcing every query to duplicate its +// arguments. +// +// The scan is literal-aware: `$1` inside a string literal, a line comment, or +// a block comment is data, not a placeholder, and is left alone. + +export interface TranslatedSql { + /** The statement with every `$n` replaced by a positional `?`. */ + text: string; + /** Bind values in the order the `?`s appear. */ + values: unknown[]; +} + +export function translatePlaceholders(text: string, params: readonly unknown[]): TranslatedSql { + let out = ""; + const values: unknown[] = []; + + let i = 0; + while (i < text.length) { + const ch = text[i]; + const next = text[i + 1]; + + // ── Regions where a `$n` is not a placeholder ── + if (ch === "'" || ch === '"') { + const quote = ch; + out += ch; + i += 1; + while (i < text.length) { + out += text[i]; + // '' (or "") inside a literal is an escaped quote, not its end. + if (text[i] === quote) { + if (text[i + 1] === quote) { + out += text[i + 1]; + i += 2; + continue; + } + i += 1; + break; + } + i += 1; + } + continue; + } + if (ch === "-" && next === "-") { + while (i < text.length && text[i] !== "\n") { + out += text[i]; + i += 1; + } + continue; + } + if (ch === "/" && next === "*") { + out += "/*"; + i += 2; + while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) { + out += text[i]; + i += 1; + } + out += "*/"; + i += 2; + continue; + } + + // ── The placeholder itself ── + if (ch === "$" && next !== undefined && next >= "0" && next <= "9") { + let j = i + 1; + let digits = ""; + for (; j < text.length; j += 1) { + const digit = text[j]; + if (digit === undefined || digit < "0" || digit > "9") break; + digits += digit; + } + const index = Number(digits); + if (index < 1 || index > params.length) { + throw new Error( + `d1: statement references $${index} but ${params.length} parameter(s) were supplied`, + ); + } + values.push(params[index - 1]); + out += "?"; + i = j; + continue; + } + + out += ch; + i += 1; + } + + return { text: out, values }; +} + +/** D1 binds JS primitives only. Anything richer (Date, plain object, array — + * the JSON columns this schema stores as TEXT) is normalized here so callers + * keep writing natural values. Booleans become 0/1: SQLite has no boolean. */ +export function toBindValue(value: unknown): unknown { + if (value === undefined) return null; + if (value === null) return null; + if (value instanceof Date) return value.toISOString(); + if (typeof value === "boolean") return value ? 1 : 0; + if (typeof value === "bigint") return Number(value); + if (typeof value === "object") return JSON.stringify(value); + return value; +} diff --git a/packages/db/src/events/index.ts b/packages/db/src/events/index.ts new file mode 100644 index 0000000..91199b3 --- /dev/null +++ b/packages/db/src/events/index.ts @@ -0,0 +1,16 @@ +export type { + StoredEvent, + StoredAuditEntry, + AppendEventInput, + AppendAuditInput, + AppendEventWithAuditInput, + EventsRepository, + EventsResult, + EventsRepositoryError, + EventsCursorPosition, + EventsPageQueryParams, + EventsPagedResult, + AuditOrgFilters, +} from "./types.js"; + +export { createEventsRepository } from "./repository.js"; diff --git a/packages/db/src/events/repository.ts b/packages/db/src/events/repository.ts new file mode 100644 index 0000000..e5a20ca --- /dev/null +++ b/packages/db/src/events/repository.ts @@ -0,0 +1,416 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + AppendEventInput, + AppendEventWithAuditInput, + AuditOrgFilters, + EventsCursorPosition, + EventsPagedResult, + EventsPageQueryParams, + EventsRepository, + EventsResult, + StoredAuditEntry, + StoredEvent, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; + +// --------------------------------------------------------------------------- +// Row mappers +// --------------------------------------------------------------------------- + +function parseJsonColumn(value: unknown): Record { + if (typeof value === "string") return JSON.parse(value) as Record; + if (value && typeof value === "object") return value as Record; + return {}; +} + +function parseJsonArrayColumn(value: unknown): string[] { + if (typeof value === "string") { + const parsed = JSON.parse(value); + return Array.isArray(parsed) ? (parsed as string[]) : []; + } + if (Array.isArray(value)) return value as string[]; + return []; +} + +function mapEvent(row: Record): StoredEvent { + return { + id: row.id as string, + type: row.type as string, + version: row.version as number, + source: row.source as string, + occurredAt: new Date(row.occurred_at as string), + actorType: row.actor_type as string, + actorId: row.actor_id as string, + actorSessionId: (row.actor_session_id as string) ?? null, + actorIp: (row.actor_ip as string) ?? null, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + subjectKind: row.subject_kind as string, + subjectId: row.subject_id as string, + subjectName: (row.subject_name as string) ?? null, + requestId: row.request_id as string, + correlationId: (row.correlation_id as string) ?? null, + causationId: (row.causation_id as string) ?? null, + idempotencyKey: (row.idempotency_key as string) ?? null, + payload: parseJsonColumn(row.payload), + redactPaths: parseJsonArrayColumn(row.redact_paths), + createdAt: new Date(row.created_at as string), + }; +} + +function mapAuditEntry(row: Record): StoredAuditEntry { + return { + id: row.id as string, + eventId: row.event_id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + actorType: row.actor_type as string, + actorId: row.actor_id as string, + eventType: row.event_type as string, + eventVersion: row.event_version as number, + source: row.source as string, + subjectKind: row.subject_kind as string, + subjectId: row.subject_id as string, + subjectName: (row.subject_name as string) ?? null, + category: row.category as string, + description: row.description as string, + occurredAt: new Date(row.occurred_at as string), + requestId: row.request_id as string, + correlationId: (row.correlation_id as string) ?? null, + payload: parseJsonColumn(row.payload), + redactPaths: parseJsonArrayColumn(row.redact_paths), + createdAt: new Date(row.created_at as string), + }; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + + +function safeError(message: string): EventsResult { + return { ok: false, error: { kind: "internal", message } }; +} + +function buildCursorCondition(cursor: EventsCursorPosition | null, startParam: number): { clause: string; params: unknown[] } { + if (!cursor) return { clause: "", params: [] }; + return { + clause: ` AND (occurred_at, id) < ($${startParam}, $${startParam + 1})`, + params: [cursor.occurredAt, cursor.id], + }; +} + +function extractNextCursor( + items: T[], + limit: number, +): { trimmed: T[]; nextCursor: EventsCursorPosition | null } { + if (items.length > limit) { + const trimmed = items.slice(0, limit); + const last = trimmed[trimmed.length - 1]!; + return { trimmed, nextCursor: { occurredAt: last.occurredAt.toISOString(), id: last.id } }; + } + return { trimmed: items, nextCursor: null }; +} + +// --------------------------------------------------------------------------- +// Factory +// --------------------------------------------------------------------------- + +export function createEventsRepository(executor: SqlExecutor): EventsRepository { + return { + async appendEvent(input: AppendEventInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO events_event_log ( + id, type, version, source, occurred_at, + actor_type, actor_id, actor_session_id, actor_ip, + org_id, project_id, environment_id, + subject_kind, subject_id, subject_name, + request_id, correlation_id, causation_id, idempotency_key, + payload, redact_paths + ) VALUES ( + $1, $2, $3, $4, $5, + $6, $7, $8, $9, + $10, $11, $12, + $13, $14, $15, + $16, $17, $18, $19, + $20, $21 + ) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [ + input.id, + input.type, + input.version, + input.source, + input.occurredAt.toISOString(), + input.actorType, + input.actorId, + input.actorSessionId ?? null, + input.actorIp ?? null, + input.orgId, + input.projectId ?? null, + input.environmentId ?? null, + input.subjectKind, + input.subjectId, + input.subjectName ?? null, + input.requestId, + input.correlationId ?? null, + input.causationId ?? null, + input.idempotencyKey ?? null, + JSON.stringify(input.payload), + JSON.stringify(input.redactPaths ?? []), + ], + ); + + if (result.rows.length === 0) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + + return { ok: true, value: mapEvent(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + return safeError("Failed to append event"); + } + }, + + async appendEventWithAudit(input: AppendEventWithAuditInput): Promise> { + const { event, audit } = input; + try { + const result = await executor.execute>( + `WITH inserted_event AS ( + INSERT INTO events_event_log ( + id, type, version, source, occurred_at, + actor_type, actor_id, actor_session_id, actor_ip, + org_id, project_id, environment_id, + subject_kind, subject_id, subject_name, + request_id, correlation_id, causation_id, idempotency_key, + payload, redact_paths + ) VALUES ( + $1, $2, $3, $4, $5, + $6, $7, $8, $9, + $10, $11, $12, + $13, $14, $15, + $16, $17, $18, $19, + $20, $21 + ) + ON CONFLICT (id) DO NOTHING + RETURNING * + ), inserted_audit AS ( + INSERT INTO events_audit_entries ( + id, event_id, org_id, project_id, environment_id, + actor_type, actor_id, + event_type, event_version, source, + subject_kind, subject_id, subject_name, + category, description, occurred_at, + request_id, correlation_id, + payload, redact_paths + ) + SELECT + $22, $1, $10, $23, $24, + $6, $7, + $2, $3, $4, + $13, $14, $15, + $25, $26, $5, + $16, $17, + $20, $21 + FROM inserted_event + RETURNING * + ) + SELECT + row_to_json(e.*) AS _event, + row_to_json(a.*) AS _audit + FROM inserted_event e + FULL JOIN inserted_audit a ON true`, + [ + event.id, + event.type, + event.version, + event.source, + event.occurredAt.toISOString(), + event.actorType, + event.actorId, + event.actorSessionId ?? null, + event.actorIp ?? null, + event.orgId, + event.projectId ?? null, + event.environmentId ?? null, + event.subjectKind, + event.subjectId, + event.subjectName ?? null, + event.requestId, + event.correlationId ?? null, + event.causationId ?? null, + event.idempotencyKey ?? null, + JSON.stringify(event.payload), + JSON.stringify(event.redactPaths ?? []), + audit.id, + audit.projectId ?? event.projectId ?? null, + audit.environmentId ?? event.environmentId ?? null, + audit.category ?? "general", + audit.description ?? "", + ], + ); + + if (result.rows.length === 0) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + + const row = result.rows[0]!; + const eventData = typeof row._event === "string" ? JSON.parse(row._event) : row._event; + const auditData = typeof row._audit === "string" ? JSON.parse(row._audit) : row._audit; + + if (!eventData) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + if (!auditData) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + + return { + ok: true, + value: { + event: mapEvent(eventData as Record), + audit: mapAuditEntry(auditData as Record), + }, + }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "event" } }; + } + return safeError("Failed to append event with audit"); + } + }, + + async queryAuditByOrg(orgId: string, params: EventsPageQueryParams, category?: string, filters?: AuditOrgFilters): Promise>> { + try { + // Support both raw UUID and legacy public org_ ID format. + // Legacy membership audit rows stored org_id as "org_" instead of raw UUID. + const legacyOrgId = `org_${orgId.replace(/-/g, "")}`; + const baseParams: unknown[] = [orgId, legacyOrgId]; + let paramIndex = 3; + + let categoryClause = ""; + if (category) { + categoryClause = ` AND category = $${paramIndex}`; + baseParams.push(category); + paramIndex++; + } + + // Optional, independently-combinable filter clauses. Each appends a + // parameterized `AND` predicate and advances the placeholder index; + // none alter the ORDER BY / cursor keyset. `from`/`to` are inclusive. + let filterClause = ""; + if (filters) { + const eq: Array<[string, string | undefined]> = [ + ["actor_id", filters.actorId], + ["actor_type", filters.actorType], + ["subject_kind", filters.subjectKind], + ["subject_id", filters.subjectId], + ["event_type", filters.eventType], + ]; + for (const [column, value] of eq) { + if (value !== undefined) { + filterClause += ` AND ${column} = $${paramIndex}`; + baseParams.push(value); + paramIndex++; + } + } + if (filters.from !== undefined) { + filterClause += ` AND occurred_at >= $${paramIndex}`; + baseParams.push(filters.from); + paramIndex++; + } + if (filters.to !== undefined) { + filterClause += ` AND occurred_at <= $${paramIndex}`; + baseParams.push(filters.to); + paramIndex++; + } + } + + baseParams.push(params.limit + 1); + const limitParam = paramIndex; + paramIndex++; + + const { clause, params: cursorParams } = buildCursorCondition(params.cursor, paramIndex); + const allParams = [...baseParams, ...cursorParams]; + + const result = await executor.execute>( + `SELECT * FROM events_audit_entries + WHERE org_id IN ($1, $2)${categoryClause}${filterClause}${clause} + ORDER BY occurred_at DESC, id DESC + LIMIT $${limitParam}`, + allParams, + ); + + const mapped = result.rows.map(mapAuditEntry); + const { trimmed, nextCursor } = extractNextCursor(mapped, params.limit); + return { ok: true, value: { items: trimmed, nextCursor } }; + } catch { + return safeError("Failed to query audit by org"); + } + }, + + async queryAuditByTarget(orgId: string, subjectKind: string, subjectId: string, params: EventsPageQueryParams): Promise>> { + try { + const { clause, params: cursorParams } = buildCursorCondition(params.cursor, 5); + const result = await executor.execute>( + `SELECT * FROM events_audit_entries + WHERE org_id = $1 AND subject_kind = $2 AND subject_id = $3${clause} + ORDER BY occurred_at DESC, id DESC + LIMIT $4`, + [orgId, subjectKind, subjectId, params.limit + 1, ...cursorParams], + ); + + const mapped = result.rows.map(mapAuditEntry); + const { trimmed, nextCursor } = extractNextCursor(mapped, params.limit); + return { ok: true, value: { items: trimmed, nextCursor } }; + } catch { + return safeError("Failed to query audit by target"); + } + }, + + async queryEventsByOrg(orgId: string, afterOccurredAt: string | null, afterEventId: string | null, limit: number): Promise> { + try { + let sql: string; + let values: unknown[]; + if (afterOccurredAt && afterEventId) { + sql = `SELECT * FROM events_event_log + WHERE org_id = $1 AND (occurred_at, id) > ($2, $3) + ORDER BY occurred_at ASC, id ASC + LIMIT $4`; + values = [orgId, afterOccurredAt, afterEventId, limit]; + } else { + sql = `SELECT * FROM events_event_log + WHERE org_id = $1 + ORDER BY occurred_at ASC, id ASC + LIMIT $2`; + values = [orgId, limit]; + } + const result = await executor.execute>(sql, values); + return { ok: true, value: result.rows.map(mapEvent) }; + } catch { + return safeError("Failed to query events by org"); + } + }, + + async getEventById(orgId: string, eventId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM events_event_log WHERE org_id = $1 AND id = $2`, + [orgId, eventId], + ); + if (result.rows.length === 0) { + return { ok: true, value: null }; + } + return { ok: true, value: mapEvent(result.rows[0]!) }; + } catch { + return safeError("Failed to get event by id"); + } + }, + }; +} diff --git a/packages/db/src/events/types.ts b/packages/db/src/events/types.ts new file mode 100644 index 0000000..1537877 --- /dev/null +++ b/packages/db/src/events/types.ts @@ -0,0 +1,186 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +// --------------------------------------------------------------------------- +// Error types +// --------------------------------------------------------------------------- + +export type EventsRepositoryError = + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type EventsResult = + | { ok: true; value: T } + | { ok: false; error: EventsRepositoryError }; + +// --------------------------------------------------------------------------- +// Domain entities (mapped from DB rows) +// --------------------------------------------------------------------------- + +export interface StoredEvent { + id: string; + type: string; + version: number; + source: string; + occurredAt: Date; + actorType: string; + actorId: string; + actorSessionId: string | null; + actorIp: string | null; + orgId: string; + projectId: string | null; + environmentId: string | null; + subjectKind: string; + subjectId: string; + subjectName: string | null; + requestId: string; + correlationId: string | null; + causationId: string | null; + idempotencyKey: string | null; + payload: Record; + redactPaths: string[]; + createdAt: Date; +} + +export interface StoredAuditEntry { + id: string; + eventId: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + actorType: string; + actorId: string; + eventType: string; + eventVersion: number; + source: string; + subjectKind: string; + subjectId: string; + subjectName: string | null; + category: string; + description: string; + occurredAt: Date; + requestId: string; + correlationId: string | null; + payload: Record; + redactPaths: string[]; + createdAt: Date; +} + +// --------------------------------------------------------------------------- +// Inputs +// --------------------------------------------------------------------------- + +export interface AppendEventInput { + id: string; + type: string; + version: number; + source: string; + occurredAt: Date; + actorType: string; + actorId: string; + actorSessionId?: string | null; + actorIp?: string | null; + orgId: string; + projectId?: string | null; + environmentId?: string | null; + subjectKind: string; + subjectId: string; + subjectName?: string | null; + requestId: string; + correlationId?: string | null; + causationId?: string | null; + idempotencyKey?: string | null; + payload: Record; + redactPaths?: string[]; +} + +export interface AppendAuditInput { + id: string; + eventId: string; + orgId: string; + projectId?: string | null; + environmentId?: string | null; + actorType: string; + actorId: string; + eventType: string; + eventVersion: number; + source: string; + subjectKind: string; + subjectId: string; + subjectName?: string | null; + category?: string; + description?: string; + occurredAt: Date; + requestId: string; + correlationId?: string | null; + payload: Record; + redactPaths?: string[]; +} + +export interface AppendEventWithAuditInput { + event: AppendEventInput; + audit: Omit & { + id: string; + category?: string; + description?: string; + projectId?: string | null; + environmentId?: string | null; + }; +} + +// --------------------------------------------------------------------------- +// Pagination +// --------------------------------------------------------------------------- + +export interface EventsCursorPosition { + occurredAt: string; + id: string; +} + +export interface EventsPageQueryParams { + limit: number; + cursor: EventsCursorPosition | null; +} + +export interface EventsPagedResult { + items: T[]; + nextCursor: EventsCursorPosition | null; +} + +/** + * Optional, independently-combinable filters for the org-scoped audit read. + * + * Each field narrows the result set with an additional `AND` clause; omitting + * a field (or passing `undefined`) leaves that dimension unfiltered. `from` / + * `to` are inclusive ISO-8601 timestamps bounding `occurred_at`. None of these + * change the `ORDER BY occurred_at DESC, id DESC` keyset ordering or the cursor + * semantics — they only restrict which rows are eligible. + */ +export interface AuditOrgFilters { + actorId?: string; + actorType?: string; + subjectKind?: string; + subjectId?: string; + eventType?: string; + from?: string; + to?: string; +} + +// --------------------------------------------------------------------------- +// Repository interface +// --------------------------------------------------------------------------- + +export interface EventsRepository { + appendEvent(input: AppendEventInput): Promise>; + appendEventWithAudit(input: AppendEventWithAuditInput): Promise>; + queryAuditByOrg(orgId: string, params: EventsPageQueryParams, category?: string, filters?: AuditOrgFilters): Promise>>; + queryAuditByTarget(orgId: string, subjectKind: string, subjectId: string, params: EventsPageQueryParams): Promise>>; + /** Query events for an org after a cursor position (for webhook dispatch fanout). */ + queryEventsByOrg(orgId: string, afterOccurredAt: string | null, afterEventId: string | null, limit: number): Promise>; + /** + * Read a single org-scoped event by id. Returns `null` (not an error) when no + * row matches — callers distinguish "absent" from "infra failure" without a + * dedicated `not_found` error kind. Used by the webhooks manual-replay path to + * rehydrate the full original event payload by id. + */ + getEventById(orgId: string, eventId: string): Promise>; +} diff --git a/packages/db/src/identity/index.ts b/packages/db/src/identity/index.ts new file mode 100644 index 0000000..7d1ad12 --- /dev/null +++ b/packages/db/src/identity/index.ts @@ -0,0 +1,28 @@ +export type { + User, + AuthIdentity, + LoginChallenge, + Session, + SecurityEvent, + CreateUserInput, + CreateAuthIdentityInput, + CreateLoginChallengeInput, + CreateSessionInput, + CreateSecurityEventInput, + SecurityEventCursorPosition, + SecurityEventPageQueryParams, + SecurityEventPagedResult, + IdentityRepository, + IdentityResult, + IdentityRepositoryError, + ApiKey, + ServicePrincipal, + CreateServicePrincipalInput, + CreateApiKeyInput, + ApiKeyCursorPosition, + ApiKeyPageQueryParams, + ApiKeyPagedResult, + UpdateUserProfileInput, +} from "./types.js"; + +export { createIdentityRepository } from "./repository.js"; diff --git a/packages/db/src/identity/repository.ts b/packages/db/src/identity/repository.ts new file mode 100644 index 0000000..79510cc --- /dev/null +++ b/packages/db/src/identity/repository.ts @@ -0,0 +1,628 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + ApiKey, + ApiKeyPagedResult, + ApiKeyPageQueryParams, + AuthIdentity, + CreateApiKeyInput, + CreateAuthIdentityInput, + CreateLoginChallengeInput, + CreateSecurityEventInput, + CreateServicePrincipalInput, + CreateSessionInput, + CreateUserInput, + IdentityRepository, + IdentityResult, + LoginChallenge, + SecurityEvent, + SecurityEventPagedResult, + SecurityEventPageQueryParams, + ServicePrincipal, + Session, + UpdateUserProfileInput, + User, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseJsonColumn } from "../json.js"; + +function mapUser(row: Record): User { + return { + id: row.id as string, + email: row.email as string, + emailLower: row.email_lower as string, + displayName: (row.display_name as string) ?? null, + lastOrgSlug: (row.last_org_slug as string) ?? null, + status: row.status as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapAuthIdentity(row: Record): AuthIdentity { + return { + id: row.id as string, + userId: row.user_id as string, + provider: row.provider as string, + subject: row.subject as string, + metadata: parseJsonColumn>(row.metadata, {}), + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapLoginChallenge(row: Record): LoginChallenge { + return { + id: row.id as string, + userId: row.user_id as string, + method: row.method as string, + expiresAt: new Date(row.expires_at as string), + consumedAt: row.consumed_at ? new Date(row.consumed_at as string) : null, + createdAt: new Date(row.created_at as string), + }; +} + +function mapSession(row: Record): Session { + return { + id: row.id as string, + userId: row.user_id as string, + expiresAt: new Date(row.expires_at as string), + revokedAt: row.revoked_at ? new Date(row.revoked_at as string) : null, + createdAt: new Date(row.created_at as string), + lastSeenAt: new Date(row.last_seen_at as string), + }; +} + +function mapSecurityEvent(row: Record): SecurityEvent { + return { + id: row.id as string, + eventType: row.event_type as string, + outcome: row.outcome as string, + userId: (row.user_id as string) ?? null, + sessionId: (row.session_id as string) ?? null, + challengeId: (row.challenge_id as string) ?? null, + requestId: (row.request_id as string) ?? null, + correlationId: (row.correlation_id as string) ?? null, + ip: (row.ip as string) ?? null, + userAgent: (row.user_agent as string) ?? null, + occurredAt: new Date(row.occurred_at as string), + createdAt: new Date(row.created_at as string), + metadata: (typeof row.metadata === "string" ? JSON.parse(row.metadata) : row.metadata ?? {}) as Record, + redactPaths: (typeof row.redact_paths === "string" ? JSON.parse(row.redact_paths) : row.redact_paths ?? []) as string[], + }; +} + +function mapServicePrincipal(row: Record): ServicePrincipal { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + displayName: row.display_name as string, + description: (row.description as string) ?? null, + status: row.status as string, + createdBy: row.created_by as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapApiKey(row: Record): ApiKey { + return { + id: row.id as string, + servicePrincipalId: row.service_principal_id as string, + orgId: row.org_id as string, + keyPrefix: row.key_prefix as string, + label: (row.label as string) ?? "", + status: row.status as string, + expiresAt: row.expires_at ? new Date(row.expires_at as string) : null, + lastUsedAt: row.last_used_at ? new Date(row.last_used_at as string) : null, + revokedAt: row.revoked_at ? new Date(row.revoked_at as string) : null, + revokedBy: (row.revoked_by as string) ?? null, + createdBy: row.created_by as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function safeError(message: string): IdentityResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +export function createIdentityRepository(executor: SqlExecutor): IdentityRepository { + return { + async createUser(input: CreateUserInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_users (id, email, email_lower, display_name, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $5) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.email, input.emailLower, input.displayName ?? null, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "user" } }; + } + return { ok: true, value: mapUser(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "user" } }; + } + return safeError("Failed to create user"); + } + }, + + async getUserById(id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM identity_users WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapUser(result.rows[0]!) }; + } catch { + return safeError("Failed to get user"); + } + }, + + async getUserByEmail(emailLower: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM identity_users WHERE email_lower = $1`, + [emailLower], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapUser(result.rows[0]!) }; + } catch { + return safeError("Failed to get user by email"); + } + }, + + async updateUserProfile(userId: string, input: UpdateUserProfileInput): Promise> { + try { + // Partial update: only set the columns the caller provided. `updated_at` + // is always bumped. $1 = id, $2 = updated_at, then provided fields. + const sets: string[] = ["updated_at = $2"]; + const params: unknown[] = [userId, input.updatedAt.toISOString()]; + if (input.displayName !== undefined) { + params.push(input.displayName); + sets.push(`display_name = $${params.length}`); + } + if (input.lastOrgSlug !== undefined) { + params.push(input.lastOrgSlug); + sets.push(`last_org_slug = $${params.length}`); + } + const result = await executor.execute>( + `UPDATE identity_users SET ${sets.join(", ")} WHERE id = $1 RETURNING *`, + params, + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapUser(result.rows[0]!) }; + } catch { + return safeError("Failed to update user profile"); + } + }, + + async createAuthIdentity(input: CreateAuthIdentityInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_auth_identities (id, user_id, provider, subject, metadata, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $6) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.userId, input.provider, input.subject, JSON.stringify(input.metadata ?? {}), input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "auth_identity" } }; + } + return { ok: true, value: mapAuthIdentity(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "auth_identity" } }; + } + return safeError("Failed to create auth identity"); + } + }, + + async getAuthIdentityByProviderSubject(provider: string, subject: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM identity_auth_identities WHERE provider = $1 AND subject = $2`, + [provider, subject], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapAuthIdentity(result.rows[0]!) }; + } catch { + return safeError("Failed to get auth identity"); + } + }, + + async createLoginChallenge(input: CreateLoginChallengeInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_login_challenges (id, user_id, method, code_hash, expires_at, created_at) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.userId, input.method, input.codeHash, input.expiresAt.toISOString(), input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "login_challenge" } }; + } + return { ok: true, value: mapLoginChallenge(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "login_challenge" } }; + } + return safeError("Failed to create login challenge"); + } + }, + + async getLoginChallengeById(id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, user_id, method, expires_at, consumed_at, created_at FROM identity_login_challenges WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const challenge = mapLoginChallenge(result.rows[0]!); + if (challenge.consumedAt !== null) { + return { ok: false, error: { kind: "already_consumed" } }; + } + if (challenge.expiresAt < new Date()) { + return { ok: false, error: { kind: "expired" } }; + } + return { ok: true, value: challenge }; + } catch { + return safeError("Failed to get login challenge"); + } + }, + + async consumeLoginChallenge(id: string, codeHash: string, consumedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE identity_login_challenges + SET consumed_at = $3 + WHERE id = $1 AND code_hash = $2 AND consumed_at IS NULL + RETURNING *`, + [id, codeHash, consumedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "already_consumed" } }; + } + return { ok: true, value: mapLoginChallenge(result.rows[0]!) }; + } catch { + return safeError("Failed to consume login challenge"); + } + }, + + async createSession(input: CreateSessionInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_sessions (id, user_id, token_hash, expires_at, created_at, last_seen_at) + VALUES ($1, $2, $3, $4, $5, $5) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.userId, input.tokenHash, input.expiresAt.toISOString(), input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "session" } }; + } + return { ok: true, value: mapSession(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "session" } }; + } + return safeError("Failed to create session"); + } + }, + + async getSessionByTokenHash(tokenHash: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, user_id, expires_at, revoked_at, created_at, last_seen_at FROM identity_sessions WHERE token_hash = $1 AND revoked_at IS NULL`, + [tokenHash], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const session = mapSession(result.rows[0]!); + if (session.expiresAt < new Date()) { + return { ok: false, error: { kind: "expired" } }; + } + return { ok: true, value: session }; + } catch { + return safeError("Failed to get session"); + } + }, + + async getSessionWithUserByTokenHash( + tokenHash: string, + ): Promise> { + try { + // PERF12d: fold the session lookup and its user fetch into one JOIN so a + // bearer-cache miss costs one DB round-trip, not two. Session columns are + // aliased (sessions and users both have `id`/`created_at`); `u.*` feeds + // mapUser, the aliased columns are split back to mapSession. Same filters + // and not_found/expired semantics as getSessionByTokenHash. + const result = await executor.execute>( + `SELECT + s.id AS session_id, + s.user_id AS session_user_id, + s.expires_at AS session_expires_at, + s.revoked_at AS session_revoked_at, + s.created_at AS session_created_at, + s.last_seen_at AS session_last_seen_at, + u.* + FROM identity_sessions s + JOIN identity_users u ON u.id = s.user_id + WHERE s.token_hash = $1 AND s.revoked_at IS NULL`, + [tokenHash], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const row = result.rows[0]!; + const session = mapSession({ + id: row.session_id, + user_id: row.session_user_id, + expires_at: row.session_expires_at, + revoked_at: row.session_revoked_at, + created_at: row.session_created_at, + last_seen_at: row.session_last_seen_at, + }); + if (session.expiresAt < new Date()) { + return { ok: false, error: { kind: "expired" } }; + } + return { ok: true, value: { session, user: mapUser(row) } }; + } catch { + return safeError("Failed to get session"); + } + }, + + async revokeSession(id: string, revokedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE identity_sessions + SET revoked_at = $2 + WHERE id = $1 AND revoked_at IS NULL + RETURNING *`, + [id, revokedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSession(result.rows[0]!) }; + } catch { + return safeError("Failed to revoke session"); + } + }, + + async recordSecurityEvent(input: CreateSecurityEventInput): Promise> { + try { + const occurredAt = input.occurredAt ?? new Date(); + const result = await executor.execute>( + `INSERT INTO identity_security_events (id, event_type, outcome, user_id, session_id, challenge_id, request_id, correlation_id, ip, user_agent, occurred_at, metadata, redact_paths) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) + RETURNING *`, + [ + input.id, + input.eventType, + input.outcome, + input.userId ?? null, + input.sessionId ?? null, + input.challengeId ?? null, + input.requestId ?? null, + input.correlationId ?? null, + input.ip ?? null, + input.userAgent ?? null, + occurredAt.toISOString(), + JSON.stringify(input.metadata ?? {}), + JSON.stringify(input.redactPaths ?? []), + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "security_event" } }; + } + return { ok: true, value: mapSecurityEvent(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "security_event" } }; + } + return safeError("Failed to record security event"); + } + }, + + async querySecurityEventsByUser(params: SecurityEventPageQueryParams): Promise> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + + if (params.cursor) { + sql = `SELECT * FROM identity_security_events + WHERE user_id = $1 + AND (occurred_at, id) < ($3, $4) + ORDER BY occurred_at DESC, id DESC + LIMIT $2`; + values = [params.userId, fetchLimit, params.cursor.occurredAt, params.cursor.id]; + } else { + sql = `SELECT * FROM identity_security_events + WHERE user_id = $1 + ORDER BY occurred_at DESC, id DESC + LIMIT $2`; + values = [params.userId, fetchLimit]; + } + + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapSecurityEvent); + + let nextCursor: import("./types.js").SecurityEventCursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { occurredAt: last.occurredAt.toISOString(), id: last.id }; + } + + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to query security events"); + } + }, + + // --- Service Principals --- + + async createServicePrincipal(input: CreateServicePrincipalInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_service_principals (id, org_id, project_id, display_name, description, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $7) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.orgId, input.projectId ?? null, input.displayName, input.description ?? null, input.createdBy, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "service_principal" } }; + } + return { ok: true, value: mapServicePrincipal(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "service_principal" } }; + } + return safeError("Failed to create service principal"); + } + }, + + async getServicePrincipalById(id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM identity_service_principals WHERE id = $1 AND status != 'deleted'`, + [id], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapServicePrincipal(result.rows[0]!) }; + } catch { + return safeError("Failed to get service principal"); + } + }, + + async listServicePrincipalsByOrg(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM identity_service_principals WHERE org_id = $1 AND status != 'deleted' ORDER BY created_at DESC`, + [orgId], + ); + return { ok: true, value: result.rows.map(mapServicePrincipal) }; + } catch { + return safeError("Failed to list service principals"); + } + }, + + // --- API Keys --- + + async createApiKey(input: CreateApiKeyInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO identity_api_keys (id, service_principal_id, org_id, key_prefix, key_hash, label, expires_at, created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $9) + ON CONFLICT (id) DO NOTHING + RETURNING id, service_principal_id, org_id, key_prefix, label, status, expires_at, last_used_at, revoked_at, revoked_by, created_by, created_at, updated_at`, + [input.id, input.servicePrincipalId, input.orgId, input.keyPrefix, input.keyHash, input.label ?? "", input.expiresAt?.toISOString() ?? null, input.createdBy, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "api_key" } }; + } + return { ok: true, value: mapApiKey(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "api_key" } }; + } + return safeError("Failed to create API key"); + } + }, + + async getApiKeyByKeyHash(keyHash: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, service_principal_id, org_id, key_prefix, label, status, expires_at, last_used_at, revoked_at, revoked_by, created_by, created_at, updated_at + FROM identity_api_keys WHERE key_hash = $1 AND status = 'active'`, + [keyHash], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapApiKey(result.rows[0]!) }; + } catch { + return safeError("Failed to get API key by hash"); + } + }, + + async listApiKeysByOrg(params: ApiKeyPageQueryParams): Promise> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + + if (params.cursor) { + sql = `SELECT id, service_principal_id, org_id, key_prefix, label, status, expires_at, last_used_at, revoked_at, revoked_by, created_by, created_at, updated_at + FROM identity_api_keys + WHERE org_id = $1 + AND (created_at, id) < ($3, $4) + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [params.orgId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT id, service_principal_id, org_id, key_prefix, label, status, expires_at, last_used_at, revoked_at, revoked_by, created_by, created_at, updated_at + FROM identity_api_keys + WHERE org_id = $1 + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [params.orgId, fetchLimit]; + } + + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapApiKey); + + let nextCursor: import("./types.js").ApiKeyCursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list API keys"); + } + }, + + async revokeApiKey(id: string, revokedBy: string, revokedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE identity_api_keys + SET status = 'revoked', revoked_at = $2, revoked_by = $3, updated_at = $2 + WHERE id = $1 AND status = 'active' + RETURNING id, service_principal_id, org_id, key_prefix, label, status, expires_at, last_used_at, revoked_at, revoked_by, created_by, created_at, updated_at`, + [id, revokedAt.toISOString(), revokedBy], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapApiKey(result.rows[0]!) }; + } catch { + return safeError("Failed to revoke API key"); + } + }, + }; +} diff --git a/packages/db/src/identity/types.ts b/packages/db/src/identity/types.ts new file mode 100644 index 0000000..4a2d349 --- /dev/null +++ b/packages/db/src/identity/types.ts @@ -0,0 +1,252 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; +import type { Uuid } from "../ids/index.js"; + +export type IdentityRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "expired" } + | { kind: "already_consumed" } + | { kind: "internal"; message: string }; + +export type IdentityResult = + | { ok: true; value: T } + | { ok: false; error: IdentityRepositoryError }; + +export interface User { + id: string; + email: string; + emailLower: string; + displayName: string | null; + /** Slug of the org the user last worked in; a soft UI hint (see migration 160). */ + lastOrgSlug: string | null; + status: string; + createdAt: Date; + updatedAt: Date; +} + +export interface AuthIdentity { + id: string; + userId: string; + provider: string; + subject: string; + metadata: Record; + createdAt: Date; + updatedAt: Date; +} + +export interface LoginChallenge { + id: string; + userId: string; + method: string; + expiresAt: Date; + consumedAt: Date | null; + createdAt: Date; +} + +export interface Session { + id: string; + userId: string; + expiresAt: Date; + revokedAt: Date | null; + createdAt: Date; + lastSeenAt: Date; +} + +export interface CreateUserInput { + id: string; + email: string; + emailLower: string; + displayName?: string | null; + createdAt: Date; +} + +export interface CreateAuthIdentityInput { + id: string; + userId: string; + provider: string; + subject: string; + metadata?: Record; + createdAt: Date; +} + +export interface CreateLoginChallengeInput { + id: string; + userId: string; + method: string; + codeHash: string; + expiresAt: Date; + createdAt: Date; +} + +export interface CreateSessionInput { + id: string; + userId: string; + tokenHash: string; + expiresAt: Date; + createdAt: Date; +} + +export interface SecurityEvent { + id: string; + eventType: string; + outcome: string; + userId: string | null; + sessionId: string | null; + challengeId: string | null; + requestId: string | null; + correlationId: string | null; + ip: string | null; + userAgent: string | null; + occurredAt: Date; + createdAt: Date; + metadata: Record; + redactPaths: string[]; +} + +export interface CreateSecurityEventInput { + id: string; + eventType: string; + outcome: string; + userId?: string | null; + sessionId?: string | null; + challengeId?: string | null; + requestId?: string | null; + correlationId?: string | null; + ip?: string | null; + userAgent?: string | null; + occurredAt?: Date; + metadata?: Record; + redactPaths?: string[]; +} + +// --- Service Principals --- + +export interface ServicePrincipal { + id: string; + orgId: string; + projectId: string | null; + displayName: string; + description: string | null; + status: string; + createdBy: string; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateServicePrincipalInput { + id: string; + orgId: Uuid; + projectId?: Uuid | null; + displayName: string; + description?: string | null; + createdBy: Uuid; + createdAt: Date; +} + +// --- API Keys --- + +export interface ApiKey { + id: string; + servicePrincipalId: string; + orgId: string; + keyPrefix: string; + label: string; + status: string; + expiresAt: Date | null; + lastUsedAt: Date | null; + revokedAt: Date | null; + revokedBy: string | null; + createdBy: string; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateApiKeyInput { + id: string; + servicePrincipalId: string; + orgId: Uuid; + keyPrefix: string; + keyHash: string; + label?: string; + expiresAt?: Date | null; + createdBy: Uuid; + createdAt: Date; +} + +export interface ApiKeyCursorPosition { + createdAt: string; + id: string; +} + +export interface ApiKeyPageQueryParams { + orgId: string; + limit: number; + cursor: ApiKeyCursorPosition | null; +} + +export interface ApiKeyPagedResult { + items: ApiKey[]; + nextCursor: ApiKeyCursorPosition | null; +} + +export interface SecurityEventCursorPosition { + occurredAt: string; + id: string; +} + +export interface SecurityEventPageQueryParams { + userId: string; + limit: number; + cursor: SecurityEventCursorPosition | null; +} + +export interface SecurityEventPagedResult { + items: SecurityEvent[]; + nextCursor: SecurityEventCursorPosition | null; +} + +export interface UpdateUserProfileInput { + /** Provide to change; omit to leave unchanged (partial update). */ + displayName?: string | null; + /** Provide to change; omit to leave unchanged (partial update). */ + lastOrgSlug?: string | null; + updatedAt: Date; +} + +export interface IdentityRepository { + createUser(input: CreateUserInput): Promise>; + getUserById(id: string): Promise>; + getUserByEmail(emailLower: string): Promise>; + updateUserProfile(userId: string, input: UpdateUserProfileInput): Promise>; + + createAuthIdentity(input: CreateAuthIdentityInput): Promise>; + getAuthIdentityByProviderSubject(provider: string, subject: string): Promise>; + + createLoginChallenge(input: CreateLoginChallengeInput): Promise>; + getLoginChallengeById(id: string): Promise>; + consumeLoginChallenge(id: string, codeHash: string, consumedAt: Date): Promise>; + + createSession(input: CreateSessionInput): Promise>; + getSessionByTokenHash(tokenHash: string): Promise>; + /** + * Session lookup folded with its user fetch into a single JOIN (PERF12d), so a + * bearer-cache miss costs one DB round-trip instead of two. Same filters and + * `not_found`/`expired` semantics as `getSessionByTokenHash`. + */ + getSessionWithUserByTokenHash(tokenHash: string): Promise>; + revokeSession(id: string, revokedAt: Date): Promise>; + + recordSecurityEvent(input: CreateSecurityEventInput): Promise>; + querySecurityEventsByUser(params: SecurityEventPageQueryParams): Promise>; + + // Service Principals + createServicePrincipal(input: CreateServicePrincipalInput): Promise>; + getServicePrincipalById(id: string): Promise>; + listServicePrincipalsByOrg(orgId: string): Promise>; + + // API Keys + createApiKey(input: CreateApiKeyInput): Promise>; + getApiKeyByKeyHash(keyHash: string): Promise>; + listApiKeysByOrg(params: ApiKeyPageQueryParams): Promise>; + revokeApiKey(id: string, revokedBy: Uuid, revokedAt: Date): Promise>; +} diff --git a/packages/db/src/ids/index.ts b/packages/db/src/ids/index.ts new file mode 100644 index 0000000..04165de --- /dev/null +++ b/packages/db/src/ids/index.ts @@ -0,0 +1,53 @@ +// Branded UUID identifier shared by all repository inputs. +// +// Public ids cross the API boundary as `_<32 hex>` (a UUID with dashes +// stripped); most DB columns store a bare UUID. Both are `string`, so passing +// the public form into a UUID column compiles but fails at runtime +// (`invalid input syntax for type uuid`). `Uuid` is a nominal/branded string: +// repository inputs bound to UUID columns are typed `Uuid`, so a caller can only +// satisfy them by going through `uuidFromPublicId` / `asUuid`, which makes a +// missing decode a *compile error* rather than a runtime crash. + +declare const uuidBrand: unique symbol; +export type Uuid = string & { readonly [uuidBrand]: true }; + +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const HEX32_RE = /^[0-9a-f]{32}$/i; + +/** Type guard: true when `value` is a canonical UUID. */ +export function isUuid(value: string): value is Uuid { + return UUID_RE.test(value); +} + +/** Assert that a string is a UUID and brand it. Throws on a non-UUID. */ +export function asUuid(value: string): Uuid { + if (!UUID_RE.test(value)) throw new Error("asUuid: value is not a canonical UUID"); + return value as Uuid; +} + +/** + * Decode a public id of the form `_<32 hex>` (e.g. `org_7c82…`, + * `usr_…`) into a branded `Uuid`. Returns null if the prefix or hex body is + * malformed. Pass the expected prefix to enforce the id kind, or omit it to + * accept any `_<32 hex>` (handy for actor ids that may be `usr_`/`sp_`). + */ +export function uuidFromPublicId(publicId: string, prefix?: string): Uuid | null { + const sep = publicId.indexOf("_"); + if (sep < 1) return null; + if (prefix !== undefined && publicId.slice(0, sep) !== prefix) return null; + return hexToUuid(publicId.slice(sep + 1)) as Uuid | null; +} + +// ── Public-id ⇄ UUID conversion primitives ────────────────── +// Shared so the 10 workers stop each carrying an identical private copy. + +/** Strip the dashes from a UUID to form the hex body of a public id. */ +export function uuidToHex(uuid: string): string { + return uuid.replace(/-/g, ""); +} + +/** Re-insert dashes into a 32-char hex body; null if not 32 hex chars. */ +export function hexToUuid(hex: string): string | null { + if (!HEX32_RE.test(hex)) return null; + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts new file mode 100644 index 0000000..a17c754 --- /dev/null +++ b/packages/db/src/index.ts @@ -0,0 +1,13 @@ +export type { + BoundedContext, + MigrationEntry, + MigrationManifest, +} from "./types.js"; + +export { BOUNDED_CONTEXTS } from "./types.js"; + +// Branded UUID identifier + decode helpers (also at `@saas/db/ids`). +export { isUuid, asUuid, uuidFromPublicId } from "./ids/index.js"; +export type { Uuid } from "./ids/index.js"; + +export { manifest } from "./manifest.js"; diff --git a/packages/db/src/integrations/index.ts b/packages/db/src/integrations/index.ts new file mode 100644 index 0000000..9499f79 --- /dev/null +++ b/packages/db/src/integrations/index.ts @@ -0,0 +1,29 @@ +export type { + IntegrationsRepositoryError, + IntegrationsResult, + CursorPosition, + PageQueryParams, + PagedResult, + ConnectionStatus, + IntegrationConnection, + CreateConnectionInput, + ActivateConnectionInput, + ListConnectionsQuery, + GithubInstallation, + UpsertGithubInstallationInput, + RepoLinkStatus, + RepoLink, + CreateRepoLinkInput, + UpdateRepoLinkInput, + ListRepoLinksQuery, + InboundDeliveryStatus, + InboundDelivery, + InsertInboundDeliveryInput, + InsertInboundDeliveryOutcome, + MarkInboundDeliveryInput, + InstallationTokenCacheEntry, + UpsertInstallationTokenInput, + IntegrationsRepository, +} from "./types.js"; + +export { createIntegrationsRepository } from "./repository.js"; diff --git a/packages/db/src/integrations/repository.ts b/packages/db/src/integrations/repository.ts new file mode 100644 index 0000000..0847a27 --- /dev/null +++ b/packages/db/src/integrations/repository.ts @@ -0,0 +1,771 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { Uuid } from "../ids/index.js"; +import type { + ActivateConnectionInput, + ConnectionStatus, + CreateConnectionInput, + CreateRepoLinkInput, + CursorPosition, + GithubInstallation, + InboundDelivery, + InsertInboundDeliveryInput, + InsertInboundDeliveryOutcome, + InstallationTokenCacheEntry, + IntegrationConnection, + IntegrationsRepository, + IntegrationsResult, + ListConnectionsQuery, + ListRepoLinksQuery, + MarkInboundDeliveryInput, + PagedResult, + PageQueryParams, + RepoLink, + UpdateRepoLinkInput, + UpsertGithubInstallationInput, + UpsertInstallationTokenInput, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseBooleanColumn } from "../json.js"; + +// ── Helpers ───────────────────────────────────────────────── + +function safeError(message: string): IntegrationsResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +function toDate(v: unknown): Date { + return v instanceof Date ? v : new Date(v as string); +} + +function dateOrNull(v: unknown): Date | null { + return v == null ? null : toDate(v); +} + +function isoOrNull(v: Date | null | undefined): string | null { + return v == null ? null : v.toISOString(); +} + +function jsonOrNull(v: unknown): string | null { + return v == null ? null : JSON.stringify(v); +} + +function parseJson(v: unknown): T | null { + if (v == null) return null; + if (typeof v === "string") { + try { + return JSON.parse(v) as T; + } catch { + return null; + } + } + return v as T; +} + +// ── Row mappers ───────────────────────────────────────────── + +function mapConnection(row: Record): IntegrationConnection { + return { + id: row.id as string, + orgId: row.org_id as string, + provider: row.provider as string, + status: row.status as ConnectionStatus, + displayName: (row.display_name as string) ?? null, + externalAccountLogin: (row.external_account_login as string) ?? null, + externalAccountId: (row.external_account_id as string) ?? null, + externalAccountType: (row.external_account_type as string) ?? null, + createdBy: (row.created_by as string) ?? null, + stateExpiresAt: dateOrNull(row.state_expires_at), + connectedAt: dateOrNull(row.connected_at), + suspendedAt: dateOrNull(row.suspended_at), + revokedAt: dateOrNull(row.revoked_at), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapGithubInstallation(row: Record): GithubInstallation { + return { + id: row.id as string, + connectionId: (row.connection_id as string) ?? null, + installationId: Number(row.installation_id), + accountLogin: (row.account_login as string) ?? null, + accountId: row.account_id == null ? null : Number(row.account_id), + accountType: (row.account_type as string) ?? null, + repositorySelection: (row.repository_selection as string) ?? null, + permissions: parseJson>(row.permissions), + events: parseJson(row.events), + suspendedAt: dateOrNull(row.suspended_at), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapRepoLink(row: Record): RepoLink { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: row.project_id as string, + connectionId: row.connection_id as string, + repoExternalId: row.repo_external_id as string, + repoFullName: row.repo_full_name as string, + defaultBranch: (row.default_branch as string) ?? null, + branchEnvMap: parseJson>(row.branch_env_map) ?? {}, + status: row.status as RepoLink["status"], + createdBy: (row.created_by as string) ?? null, + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapInboundDelivery(row: Record): InboundDelivery { + return { + id: row.id as string, + orgId: (row.org_id as string) ?? null, + connectionId: (row.connection_id as string) ?? null, + provider: row.provider as string, + deliveryKey: row.delivery_key as string, + eventType: row.event_type as string, + action: (row.action as string) ?? null, + payload: parseJson>(row.payload) ?? {}, + signatureOk: parseBooleanColumn(row.signature_ok), + status: row.status as InboundDelivery["status"], + attempts: Number(row.attempts), + nextAttemptAt: dateOrNull(row.next_attempt_at), + failureReason: (row.failure_reason as string) ?? null, + emittedEventId: (row.emitted_event_id as string) ?? null, + receivedAt: toDate(row.received_at), + updatedAt: toDate(row.updated_at), + }; +} + +function mapInstallationToken(row: Record): InstallationTokenCacheEntry { + return { + id: row.id as string, + connectionId: row.connection_id as string, + tokenCiphertext: row.token_ciphertext as string, + permissions: parseJson>(row.permissions), + repositoryIds: parseJson(row.repository_ids), + expiresAt: toDate(row.expires_at), + createdAt: toDate(row.created_at), + updatedAt: toDate(row.updated_at), + }; +} + +// ── Cursor pagination helper ──────────────────────────────── + +async function pagedList( + executor: SqlExecutor, + sql: string, + values: unknown[], + limit: number, + cursor: CursorPosition | null, + mapper: (row: Record) => T, + cursorDateField = "created_at", +): Promise>> { + try { + const fetchLimit = limit + 1; + let fullSql: string; + let fullValues: unknown[]; + const baseIdx = values.length; + + if (cursor) { + fullSql = `${sql} AND (${cursorDateField}, id) < ($${baseIdx + 2}, $${baseIdx + 3}) ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit, cursor.createdAt, cursor.id]; + } else { + fullSql = `${sql} ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit]; + } + + const result = await executor.execute>(fullSql, fullValues); + const rows = result.rows.map(mapper); + let nextCursor: CursorPosition | null = null; + if (rows.length > limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { + createdAt: (last as unknown as { createdAt: Date }).createdAt.toISOString(), + id: (last as unknown as { id: string }).id, + }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list records"); + } +} + +// ── Repository factory ────────────────────────────────────── + +export function createIntegrationsRepository(executor: SqlExecutor): IntegrationsRepository { + return { + // ── Connections ───────────────────────────────────────── + + async createConnection( + input: CreateConnectionInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO integrations_connections + (id, org_id, provider, status, display_name, created_by, + state_nonce_hash, state_expires_at, created_at, updated_at) + VALUES ($1, $2, $3, 'pending', $4, $5, $6, $7, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING *`, + [ + input.id, + input.orgId, + input.provider, + input.displayName ?? null, + input.createdBy ?? null, + input.stateNonceHash ?? null, + isoOrNull(input.stateExpiresAt), + ], + ); + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "connection" } }; + } + return safeError("Failed to create connection"); + } + }, + + async getConnection( + orgId: Uuid, + id: Uuid, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_connections WHERE org_id = $1 AND id = $2`, + [orgId, id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch { + return safeError("Failed to get connection"); + } + }, + + async getConnectionById(id: Uuid): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_connections WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch { + return safeError("Failed to get connection"); + } + }, + + async listConnections( + orgId: Uuid, + params: PageQueryParams, + query?: ListConnectionsQuery, + ): Promise>> { + const values: unknown[] = [orgId]; + let sql = `SELECT * FROM integrations_connections WHERE org_id = $1`; + if (query?.provider) { + values.push(query.provider); + sql += ` AND provider = $${values.length}`; + } + if (query?.status) { + values.push(query.status); + sql += ` AND status = $${values.length}`; + } + return pagedList(executor, sql, values, params.limit, params.cursor, mapConnection); + }, + + async consumeConnectionState( + stateNonceHash: string, + ): Promise> { + try { + // Single-use: the nonce is cleared in the same statement that + // resolves it, and expired state never matches. Fail closed. + const result = await executor.execute>( + `UPDATE integrations_connections + SET state_nonce_hash = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE state_nonce_hash = $1 + AND status = 'pending' + AND state_expires_at IS NOT NULL + AND state_expires_at > strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [stateNonceHash], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch { + return safeError("Failed to consume connection state"); + } + }, + + async activateConnection( + orgId: Uuid, + id: Uuid, + input: ActivateConnectionInput, + ): Promise> { + try { + const result = await executor.execute>( + `UPDATE integrations_connections + SET status = 'active', + display_name = COALESCE($3, display_name), + external_account_login = $4, + external_account_id = $5, + external_account_type = $6, + state_nonce_hash = NULL, + state_expires_at = NULL, + connected_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'pending' + RETURNING *`, + [ + orgId, + id, + input.displayName ?? null, + input.externalAccountLogin ?? null, + input.externalAccountId ?? null, + input.externalAccountType ?? null, + ], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "connection" } }; + } + return safeError("Failed to activate connection"); + } + }, + + async updateConnectionStatus( + orgId: Uuid, + id: Uuid, + status: ConnectionStatus, + ): Promise> { + try { + const result = await executor.execute>( + `UPDATE integrations_connections + SET status = $3, + suspended_at = CASE WHEN $3 = 'suspended' THEN strftime('%Y-%m-%dT%H:%M:%fZ','now') ELSE suspended_at END, + revoked_at = CASE WHEN $3 = 'revoked' THEN strftime('%Y-%m-%dT%H:%M:%fZ','now') ELSE revoked_at END, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 + RETURNING *`, + [orgId, id, status], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapConnection(result.rows[0]!) }; + } catch { + return safeError("Failed to update connection status"); + } + }, + + // ── GitHub installations ──────────────────────────────── + + async upsertGithubInstallation( + input: UpsertGithubInstallationInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO integrations_github_installations + (id, connection_id, installation_id, account_login, account_id, + account_type, repository_selection, permissions, events, + suspended_at, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (installation_id) DO UPDATE SET + connection_id = COALESCE(EXCLUDED.connection_id, integrations_github_installations.connection_id), + account_login = EXCLUDED.account_login, + account_id = EXCLUDED.account_id, + account_type = EXCLUDED.account_type, + repository_selection = EXCLUDED.repository_selection, + permissions = EXCLUDED.permissions, + events = EXCLUDED.events, + suspended_at = EXCLUDED.suspended_at, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [ + input.id, + input.connectionId ?? null, + input.installationId, + input.accountLogin ?? null, + input.accountId ?? null, + input.accountType ?? null, + input.repositorySelection ?? null, + jsonOrNull(input.permissions), + jsonOrNull(input.events), + isoOrNull(input.suspendedAt), + ], + ); + return { ok: true, value: mapGithubInstallation(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "github_installation" } }; + } + return safeError("Failed to upsert GitHub installation"); + } + }, + + async getGithubInstallationByInstallationId( + installationId: number, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_github_installations WHERE installation_id = $1`, + [installationId], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapGithubInstallation(result.rows[0]!) }; + } catch { + return safeError("Failed to get GitHub installation"); + } + }, + + async getGithubInstallationByConnectionId( + connectionId: Uuid, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_github_installations WHERE connection_id = $1`, + [connectionId], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapGithubInstallation(result.rows[0]!) }; + } catch { + return safeError("Failed to get GitHub installation"); + } + }, + + // ── Repo links ────────────────────────────────────────── + + async createRepoLink(input: CreateRepoLinkInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO integrations_repo_links + (id, org_id, project_id, connection_id, repo_external_id, + repo_full_name, default_branch, branch_env_map, status, + created_by, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'active', $9, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING *`, + [ + input.id, + input.orgId, + input.projectId, + input.connectionId, + input.repoExternalId, + input.repoFullName, + input.defaultBranch ?? null, + JSON.stringify(input.branchEnvMap ?? {}), + input.createdBy ?? null, + ], + ); + return { ok: true, value: mapRepoLink(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "repo_link" } }; + } + return safeError("Failed to create repo link"); + } + }, + + async getRepoLink(orgId: Uuid, id: Uuid): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_repo_links WHERE org_id = $1 AND id = $2`, + [orgId, id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapRepoLink(result.rows[0]!) }; + } catch { + return safeError("Failed to get repo link"); + } + }, + + async listRepoLinks( + orgId: Uuid, + params: PageQueryParams, + query?: ListRepoLinksQuery, + ): Promise>> { + const values: unknown[] = [orgId]; + let sql = `SELECT * FROM integrations_repo_links WHERE org_id = $1`; + if (query?.projectId) { + values.push(query.projectId); + sql += ` AND project_id = $${values.length}`; + } + if (query?.status) { + values.push(query.status); + sql += ` AND status = $${values.length}`; + } + return pagedList(executor, sql, values, params.limit, params.cursor, mapRepoLink); + }, + + async updateRepoLink( + orgId: Uuid, + id: Uuid, + input: UpdateRepoLinkInput, + ): Promise> { + try { + const result = await executor.execute>( + `UPDATE integrations_repo_links + SET default_branch = COALESCE($3, default_branch), + branch_env_map = COALESCE($4, branch_env_map), + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING *`, + [ + orgId, + id, + input.defaultBranch ?? null, + input.branchEnvMap == null ? null : JSON.stringify(input.branchEnvMap), + ], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapRepoLink(result.rows[0]!) }; + } catch { + return safeError("Failed to update repo link"); + } + }, + + async unlinkRepoLink(orgId: Uuid, id: Uuid): Promise> { + try { + const result = await executor.execute>( + `UPDATE integrations_repo_links + SET status = 'unlinked', updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING *`, + [orgId, id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapRepoLink(result.rows[0]!) }; + } catch { + return safeError("Failed to unlink repo link"); + } + }, + + async listActiveRepoLinksForRepo( + orgId: Uuid, + repoExternalId: string, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_repo_links + WHERE org_id = $1 AND repo_external_id = $2 AND status = 'active' + ORDER BY created_at ASC, id ASC`, + [orgId, repoExternalId], + ); + return { ok: true, value: result.rows.map(mapRepoLink) }; + } catch { + return safeError("Failed to list repo links for repo"); + } + }, + + async countActiveRepoLinks(orgId: Uuid): Promise> { + try { + const result = await executor.execute>( + `SELECT COUNT(*) AS count FROM integrations_repo_links + WHERE org_id = $1 AND status = 'active'`, + [orgId], + ); + return { ok: true, value: Number(result.rows[0]?.count ?? 0) }; + } catch { + return safeError("Failed to count repo links"); + } + }, + + // ── Inbound deliveries ────────────────────────────────── + + async insertInboundDelivery( + input: InsertInboundDeliveryInput, + ): Promise> { + try { + // Idempotent inbox insert: a redelivery (same provider delivery key) + // is a no-op that returns the existing row with created=false. + const inserted = await executor.execute>( + `INSERT INTO integrations_inbound_deliveries + (id, provider, delivery_key, event_type, action, payload, + signature_ok, status, received_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, 'received', strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (provider, delivery_key) DO NOTHING + RETURNING *`, + [ + input.id, + input.provider, + input.deliveryKey, + input.eventType, + input.action ?? null, + JSON.stringify(input.payload), + input.signatureOk, + ], + ); + if (inserted.rowCount > 0) { + return { + ok: true, + value: { delivery: mapInboundDelivery(inserted.rows[0]!), created: true }, + }; + } + const existing = await executor.execute>( + `SELECT * FROM integrations_inbound_deliveries + WHERE provider = $1 AND delivery_key = $2`, + [input.provider, input.deliveryKey], + ); + if (existing.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { + ok: true, + value: { delivery: mapInboundDelivery(existing.rows[0]!), created: false }, + }; + } catch { + return safeError("Failed to insert inbound delivery"); + } + }, + + async getInboundDelivery(id: Uuid): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_inbound_deliveries WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapInboundDelivery(result.rows[0]!) }; + } catch { + return safeError("Failed to get inbound delivery"); + } + }, + + async listInboundDeliveries( + orgId: Uuid, + params: PageQueryParams, + query?: { connectionId?: Uuid }, + ): Promise>> { + const values: unknown[] = [orgId]; + let sql = `SELECT * FROM integrations_inbound_deliveries WHERE org_id = $1`; + if (query?.connectionId) { + values.push(query.connectionId); + sql += ` AND connection_id = $${values.length}`; + } + return pagedList( + executor, + sql, + values, + params.limit, + params.cursor, + mapInboundDelivery, + "received_at", + ); + }, + + async listDueInboundDeliveries( + limit: number, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_inbound_deliveries + WHERE status IN ('received', 'attributed') + AND (next_attempt_at IS NULL OR next_attempt_at <= strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ORDER BY received_at ASC, id ASC + LIMIT $1`, + [limit], + ); + return { ok: true, value: result.rows.map(mapInboundDelivery) }; + } catch { + return safeError("Failed to list due inbound deliveries"); + } + }, + + async markInboundDelivery( + id: Uuid, + input: MarkInboundDeliveryInput, + ): Promise> { + try { + const result = await executor.execute>( + `UPDATE integrations_inbound_deliveries + SET org_id = COALESCE($2, org_id), + connection_id = COALESCE($3, connection_id), + status = COALESCE($4, status), + attempts = COALESCE($5, attempts), + next_attempt_at = $6, + failure_reason = COALESCE($7, failure_reason), + emitted_event_id = COALESCE($8, emitted_event_id), + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE id = $1 + RETURNING *`, + [ + id, + input.orgId ?? null, + input.connectionId ?? null, + input.status ?? null, + input.attempts ?? null, + isoOrNull(input.nextAttemptAt), + input.failureReason ?? null, + input.emittedEventId ?? null, + ], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapInboundDelivery(result.rows[0]!) }; + } catch { + return safeError("Failed to mark inbound delivery"); + } + }, + + // ── Installation token cache ──────────────────────────── + + async upsertInstallationToken( + input: UpsertInstallationTokenInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO integrations_installation_tokens + (id, connection_id, token_ciphertext, permissions, repository_ids, + expires_at, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (connection_id) DO UPDATE SET + token_ciphertext = EXCLUDED.token_ciphertext, + permissions = EXCLUDED.permissions, + repository_ids = EXCLUDED.repository_ids, + expires_at = EXCLUDED.expires_at, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [ + input.id, + input.connectionId, + input.tokenCiphertext, + jsonOrNull(input.permissions), + jsonOrNull(input.repositoryIds), + input.expiresAt.toISOString(), + ], + ); + return { ok: true, value: mapInstallationToken(result.rows[0]!) }; + } catch { + return safeError("Failed to upsert installation token"); + } + }, + + async getInstallationToken( + connectionId: Uuid, + ): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM integrations_installation_tokens + WHERE connection_id = $1 AND expires_at > strftime('%Y-%m-%dT%H:%M:%fZ','now')`, + [connectionId], + ); + if (result.rowCount === 0) return { ok: false, error: { kind: "not_found" } }; + return { ok: true, value: mapInstallationToken(result.rows[0]!) }; + } catch { + return safeError("Failed to get installation token"); + } + }, + + async deleteInstallationToken( + connectionId: Uuid, + ): Promise> { + try { + await executor.execute( + `DELETE FROM integrations_installation_tokens WHERE connection_id = $1`, + [connectionId], + ); + return { ok: true, value: { deleted: true } }; + } catch { + return safeError("Failed to delete installation token"); + } + }, + }; +} diff --git a/packages/db/src/integrations/types.ts b/packages/db/src/integrations/types.ts new file mode 100644 index 0000000..a8eb2fe --- /dev/null +++ b/packages/db/src/integrations/types.ts @@ -0,0 +1,328 @@ +import type { Uuid } from "../ids/index.js"; + +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +// ── Result type ───────────────────────────────────────────── + +export type IntegrationsRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type IntegrationsResult = + | { ok: true; value: T } + | { ok: false; error: IntegrationsRepositoryError }; + +// ── Cursor pagination (matches existing convention) ───────── + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +// ── Connections ───────────────────────────────────────────── +// NOTE: state_nonce_hash is write/lookup-only — it is intentionally excluded +// from the read model so it can never leak through a list/read surface. + +export type ConnectionStatus = "pending" | "active" | "suspended" | "revoked"; + +export interface IntegrationConnection { + id: string; + orgId: string; + provider: string; + status: ConnectionStatus; + displayName: string | null; + externalAccountLogin: string | null; + externalAccountId: string | null; + externalAccountType: string | null; + createdBy: string | null; + stateExpiresAt: Date | null; + connectedAt: Date | null; + suspendedAt: Date | null; + revokedAt: Date | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateConnectionInput { + id: string; + orgId: Uuid; + provider: string; + displayName?: string | null; + createdBy?: string | null; + /** SHA-256 hex of the single-use signed-state nonce (write-only). */ + stateNonceHash?: string | null; + stateExpiresAt?: Date | null; +} + +export interface ActivateConnectionInput { + displayName?: string | null; + externalAccountLogin?: string | null; + externalAccountId?: string | null; + externalAccountType?: string | null; +} + +export interface ListConnectionsQuery { + provider?: string; + status?: ConnectionStatus; +} + +// ── GitHub installations ──────────────────────────────────── + +export interface GithubInstallation { + id: string; + /** Null = orphaned installation (recorded, never auto-bound). */ + connectionId: string | null; + installationId: number; + accountLogin: string | null; + accountId: number | null; + accountType: string | null; + repositorySelection: string | null; + permissions: Record | null; + events: unknown[] | null; + suspendedAt: Date | null; + createdAt: Date; + updatedAt: Date; +} + +export interface UpsertGithubInstallationInput { + id: string; + connectionId?: Uuid | null; + installationId: number; + accountLogin?: string | null; + accountId?: number | null; + accountType?: string | null; + repositorySelection?: string | null; + permissions?: Record | null; + events?: unknown[] | null; + suspendedAt?: Date | null; +} + +// ── Repo links ────────────────────────────────────────────── + +export type RepoLinkStatus = "active" | "unlinked"; + +export interface RepoLink { + id: string; + orgId: string; + projectId: string; + connectionId: string; + repoExternalId: string; + repoFullName: string; + defaultBranch: string | null; + branchEnvMap: Record; + status: RepoLinkStatus; + createdBy: string | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateRepoLinkInput { + id: string; + orgId: Uuid; + projectId: Uuid; + connectionId: Uuid; + repoExternalId: string; + repoFullName: string; + defaultBranch?: string | null; + branchEnvMap?: Record; + createdBy?: string | null; +} + +export interface UpdateRepoLinkInput { + defaultBranch?: string | null; + branchEnvMap?: Record; +} + +export interface ListRepoLinksQuery { + projectId?: Uuid; + status?: RepoLinkStatus; +} + +// ── Inbound deliveries ────────────────────────────────────── + +export type InboundDeliveryStatus = + | "received" + | "attributed" + | "emitted" + | "skipped" + | "failed"; + +export interface InboundDelivery { + id: string; + orgId: string | null; + /** Owning connection once attributed (installation → connection → org). */ + connectionId: string | null; + provider: string; + deliveryKey: string; + eventType: string; + action: string | null; + /** Raw provider payload — admin-only; never exposed through public APIs. */ + payload: Record; + signatureOk: boolean; + status: InboundDeliveryStatus; + attempts: number; + nextAttemptAt: Date | null; + failureReason: string | null; + emittedEventId: string | null; + receivedAt: Date; + updatedAt: Date; +} + +export interface InsertInboundDeliveryInput { + id: string; + provider: string; + deliveryKey: string; + eventType: string; + action?: string | null; + payload: Record; + signatureOk: boolean; +} + +/** Result of an idempotent inbox insert: created=false on a redelivery. */ +export interface InsertInboundDeliveryOutcome { + delivery: InboundDelivery; + created: boolean; +} + +export interface MarkInboundDeliveryInput { + orgId?: Uuid | null; + connectionId?: Uuid | null; + status?: InboundDeliveryStatus; + attempts?: number; + nextAttemptAt?: Date | null; + failureReason?: string | null; + emittedEventId?: Uuid | null; +} + +// ── Installation token cache ──────────────────────────────── +// Serves only the platform's own provider calls. The ciphertext is returned +// by the repository (the worker must decrypt) but must never cross a public +// API surface or appear in logs. + +export interface InstallationTokenCacheEntry { + id: string; + connectionId: string; + tokenCiphertext: string; + permissions: Record | null; + repositoryIds: unknown[] | null; + expiresAt: Date; + createdAt: Date; + updatedAt: Date; +} + +export interface UpsertInstallationTokenInput { + id: string; + connectionId: Uuid; + tokenCiphertext: string; + permissions?: Record | null; + repositoryIds?: unknown[] | null; + expiresAt: Date; +} + +// ── Repository interface ──────────────────────────────────── + +export interface IntegrationsRepository { + // Connections + createConnection(input: CreateConnectionInput): Promise>; + getConnection(orgId: Uuid, id: Uuid): Promise>; + /** + * INTERNAL (drain/replay only): resolve a connection without an org filter. + * The inbound pipeline attributes deliveries installation → connection → + * org, so the org is an output here, not an input. Never expose through a + * request-scoped read path. + */ + getConnectionById(id: Uuid): Promise>; + listConnections( + orgId: Uuid, + params: PageQueryParams, + query?: ListConnectionsQuery, + ): Promise>>; + /** + * Resolve the pending connection for a connect-flow callback and consume + * its nonce atomically (single-use). Fails closed: expired or already- + * consumed state resolves to not_found. + */ + consumeConnectionState(stateNonceHash: string): Promise>; + /** Activate a pending connection with verified provider account facts. */ + activateConnection( + orgId: Uuid, + id: Uuid, + input: ActivateConnectionInput, + ): Promise>; + updateConnectionStatus( + orgId: Uuid, + id: Uuid, + status: ConnectionStatus, + ): Promise>; + + // GitHub installations + upsertGithubInstallation( + input: UpsertGithubInstallationInput, + ): Promise>; + getGithubInstallationByInstallationId( + installationId: number, + ): Promise>; + getGithubInstallationByConnectionId( + connectionId: Uuid, + ): Promise>; + + // Repo links + createRepoLink(input: CreateRepoLinkInput): Promise>; + getRepoLink(orgId: Uuid, id: Uuid): Promise>; + listRepoLinks( + orgId: Uuid, + params: PageQueryParams, + query?: ListRepoLinksQuery, + ): Promise>>; + updateRepoLink( + orgId: Uuid, + id: Uuid, + input: UpdateRepoLinkInput, + ): Promise>; + /** Soft-unlink: flips status to 'unlinked'; the row remains for audit. */ + unlinkRepoLink(orgId: Uuid, id: Uuid): Promise>; + /** Drain enrichment: active links matching a provider repo, org-scoped. */ + listActiveRepoLinksForRepo( + orgId: Uuid, + repoExternalId: string, + ): Promise>; + /** Entitlement gating: count of active links in the organization. */ + countActiveRepoLinks(orgId: Uuid): Promise>; + + // Inbound deliveries (durable inbox) + insertInboundDelivery( + input: InsertInboundDeliveryInput, + ): Promise>; + getInboundDelivery(id: Uuid): Promise>; + listInboundDeliveries( + orgId: Uuid, + params: PageQueryParams, + query?: { connectionId?: Uuid }, + ): Promise>>; + /** Cron drain scan: due pending work, oldest first. */ + listDueInboundDeliveries(limit: number): Promise>; + markInboundDelivery( + id: Uuid, + input: MarkInboundDeliveryInput, + ): Promise>; + + // Installation token cache + upsertInstallationToken( + input: UpsertInstallationTokenInput, + ): Promise>; + getInstallationToken( + connectionId: Uuid, + ): Promise>; + deleteInstallationToken(connectionId: Uuid): Promise>; +} diff --git a/packages/db/src/json.ts b/packages/db/src/json.ts new file mode 100644 index 0000000..86df7e9 --- /dev/null +++ b/packages/db/src/json.ts @@ -0,0 +1,65 @@ +// Column decoding for D1. +// +// SQLite stores fewer types than the schema names. Two of them need a decoder +// on every read, and both live here so the rules are stated once. +// +// JSON columns on D1. +// +// SQLite has no JSON type: the JSON-shaped columns in this schema are TEXT +// holding a serialized document, so every read has to parse and every write +// has to stringify. Repositories write with `JSON.stringify`; this is the +// matching read side, in one place so that "what does a malformed value do" +// has exactly one answer. +// +// Malformed content falls back rather than throwing. A row whose metadata blob +// cannot be parsed is still a row the caller asked for — losing the whole read +// (and, through it, a login or an invoice list) over an unreadable side-car +// document is the worse failure. + +export function parseJsonColumn(value: unknown, fallback: T): T { + if (value === null || value === undefined) return fallback; + if (typeof value !== "string") return value as T; + try { + const parsed: unknown = JSON.parse(value); + return (parsed ?? fallback) as T; + } catch { + return fallback; + } +} + +/** Nullable variant: an absent document stays `null` instead of collapsing to + * an empty object, which callers use to distinguish "never set" from "set to + * {}" (billing/metering metadata both rely on it). */ +export function parseNullableJsonColumn(value: unknown): T | null { + if (value === null || value === undefined) return null; + if (typeof value !== "string") return value as T; + try { + return JSON.parse(value) as T; + } catch { + return null; + } +} + +/** + * Boolean columns on D1. + * + * SQLite has no boolean type — the schema declares INTEGER and stores 0 or 1, + * so a raw read yields a number that is truthy for 0 only in the sense JS + * disagrees with. Every boolean column read goes through here. + * + * The string forms ("1"/"true"/"t") are accepted because a value that made a + * round trip through JSON or a text-typed expression arrives as text, and + * failing that quietly to `false` is the kind of bug that only shows up on one + * code path in production. + */ +export function parseBooleanColumn(value: unknown, fallback = false): boolean { + if (value === null || value === undefined) return fallback; + if (typeof value === "boolean") return value; + if (typeof value === "number") return value !== 0; + if (typeof value === "string") { + const v = value.trim().toLowerCase(); + if (v === "1" || v === "true" || v === "t") return true; + if (v === "0" || v === "false" || v === "f" || v === "") return false; + } + return fallback; +} diff --git a/packages/db/src/manifest.ts b/packages/db/src/manifest.ts new file mode 100644 index 0000000..eead305 --- /dev/null +++ b/packages/db/src/manifest.ts @@ -0,0 +1,187 @@ +import type { MigrationManifest } from "./types.js"; + +export const manifest: MigrationManifest = { + version: 1, + migrations: [ + { + id: "000_control_baseline", + context: "control", + path: "000_control/up.sql", + checksum: + "c7f11499fa82d6fd2baa1af7fc75eeb73cd7be252af2e56841509c66001d638b", + description: + "Baseline control migration — creates the migration tracking schema", + }, + { + id: "010_identity_core", + context: "identity", + path: "010_identity_core/up.sql", + checksum: + "e8275904e2c60c42c6c977c208acd857086c6b93b35f552fd10e41ca16607872", + description: + "Identity persistence foundation — users, auth identities, login challenges, sessions", + }, + { + id: "020_membership_core", + context: "membership", + path: "020_membership_core/up.sql", + checksum: + "857bbac3e351b71a2549e6639127611e0918a16a6efe94fe0edb8d12dc7392d5", + description: + "Membership persistence foundation — organizations, members, invitations, role assignments", + }, + { + id: "030_events_audit_core", + context: "events", + path: "030_events_audit_core/up.sql", + checksum: + "13c451ca150371f301a85c3a00b36689a6108f31da05c8d1a3fa64b3b1b6bfb4", + description: + "Events/audit persistence foundation — canonical event log and audit entry projections", + }, + { + id: "040_projects_core", + context: "projects", + path: "040_projects_core/up.sql", + checksum: + "f40bd14d98f399f0a0cfb6f82a5ac7be31792c74950e597bc90ffe6a6ead3949", + description: + "Projects persistence foundation — projects and environments tables with tenant isolation", + }, + { + id: "050_identity_security_events", + context: "identity", + path: "050_identity_security_events/up.sql", + checksum: + "e97f0dc7d4e7f3e246bbdd80f041a64a178949281e30c9e94ceb8a64d9472009", + description: + "Identity-owned security-event source facts — pre-organization user activity log", + }, + { + id: "060_identity_api_keys", + context: "identity", + path: "060_identity_api_keys/up.sql", + checksum: + "9adceb6281c2f88449415dceba7f387e16591ffbc115d6199a5efce4acf92aff", + description: + "Identity-owned service principals and API keys — org-bound automation actors and credential persistence", + }, + { + id: "070_config_settings_flags", + context: "config", + path: "070_config_settings_flags/up.sql", + checksum: + "0996c9c8e483b1aff84a2b17e4176eaa21316f3c9834070eaee78c23c0b18a48", + description: + "Config persistence foundation — scoped settings, feature flags, and secret metadata", + }, + { + id: "080_webhooks_core", + context: "webhooks", + path: "080_webhooks_core/up.sql", + checksum: + "c9157f4836d229b73dd3918b0b090fc776e0ba73727a876e37a2b6c1b098a38a", + description: + "Webhook persistence foundation — endpoints, subscriptions, and delivery attempts", + }, + { + id: "090_webhooks_delivery", + context: "webhooks", + path: "090_webhooks_delivery/up.sql", + checksum: + "79ea5500c1e5dff36f70ad6a3f63f4335c1423c4695ca0ac5b60942d6f20cce4", + description: + "Webhook delivery runtime — fixes event_id type, adds dispatch cursor and delivery indexes", + }, + { + id: "100_metering_foundation", + context: "metering", + path: "100_metering_foundation/up.sql", + checksum: + "f5448db51935ade1fab8670a27c1104d20b07d0003608550d1749a013f0ac6b9", + description: + "Metering persistence foundation — usage records, rollups, quota definitions, and quota violations", + }, + { + id: "110_billing_foundation", + context: "billing", + path: "110_billing_foundation/up.sql", + checksum: + "446e002fada272b2488c745eb855f49685e7f9899297c8df7e39f25ad591e06f", + description: + "Billing persistence foundation — provider-neutral plans, billing customers, subscriptions, invoices, and entitlements", + }, + { + id: "120_notifications_core", + context: "notifications", + path: "120_notifications_core/up.sql", + checksum: + "ca99fc52528d2697885776096ee0d0b2b46cab6c18ca37cfc6e46ed4cf0b4d59", + description: + "Notifications persistence foundation — preferences, notifications, attempts, suppressions", + }, + { + id: "130_webhook_secret_rotation_grace", + context: "webhooks", + path: "130_webhook_secret_rotation_grace/up.sql", + checksum: + "de5929da0705b34ae3ac94ce978705c857d232997f553ed4abd92996b9ba8134", + description: + "Dual-secret rotation window — adds previous_secret_{ciphertext,version,expires_at} for grace-period delivery signing", + }, + { + id: "140_support_action_records", + context: "support", + path: "140_support_action_records/up.sql", + checksum: + "4379358a3692ebc734c1125c3d21c00c023185f42572351d7366f3292388b4b3", + description: + "Support persistence foundation — append-only audited support-action ledger owned by the admin-support worker", + }, + { + id: "150_entitlement_decision_observations", + context: "billing", + path: "150_entitlement_decision_observations/up.sql", + checksum: + "51950b97f41b5b03107cf1414a068e5d2a82901331f00687aa647139f40043d5", + description: + "Entitlement-decision observability — append-only, counts-only observation table (org × entitlement key × outcome) owned by the billing context", + }, + { + id: "160_identity_user_last_org", + context: "identity", + path: "160_identity_user_last_org/up.sql", + checksum: + "ebfead333c9a5ccfdc782744eef2911ae9c63c70358a8fccecbd8b545a851806", + description: + "Per-user last-viewed organization preference (nullable slug hint on identity_users) backing the console's cross-device default landing", + }, + { + id: "170_membership_org_parent", + context: "membership", + path: "170_membership_org_parent/up.sql", + checksum: + "33e280e66b1752832a434fb122d41733e1c325faa443e819a8b402ca63995581", + description: + "Optional parent-organization pointer (nullable parent_org_id on membership_organizations) — the dormant seam for the saas-multi-org-billing epic; NULL = standalone, no behavior change", + }, + { + id: "180_integrations_foundation", + context: "integrations", + path: "180_integrations_foundation/up.sql", + checksum: + "f0a65edf90d7d63349628335ca80ddf825555b1686c4873aa4f75ab633b8f2bd", + description: + "Integrations persistence foundation (IG0, dormant) — provider-agnostic connections, GitHub installation facts, repo links with branch→environment maps, the durable inbound-delivery inbox, and the encrypted installation-token cache", + }, + { + id: "190_integrations_delivery_attribution", + context: "integrations", + path: "190_integrations_delivery_attribution/up.sql", + checksum: + "b5ffe67f60e3486b9c733146c375341e757145b5d4381475256f1399328d81a0", + description: + "Connection pointer on the inbound-delivery inbox (nullable connection_id + partial index) — lets the per-connection delivery log scope precisely; attributed by the IG2 cron drain", + }, + ], +}; diff --git a/packages/db/src/membership/billing-scope.ts b/packages/db/src/membership/billing-scope.ts new file mode 100644 index 0000000..1be318e --- /dev/null +++ b/packages/db/src/membership/billing-scope.ts @@ -0,0 +1,20 @@ +import type { Organization } from "./types.js"; + +/** + * The organization whose billing customer/subscription/entitlements cover `org`: + * its parent when it is a child organization, otherwise itself. + * + * This is the single resolution rule for the Datadog-style multi-organization + * model (epic `saas-multi-org-billing`). Billing *reads* (summary, invoices, + * customer, checkout/portal) resolve through here; entitlement *decisions* keep + * reading the org's own per-org rows, which fan-out keeps in sync — so this + * helper never touches the `check-entitlement` hot path. + * + * For every existing (standalone) organization `parentOrgId` is NULL, so this + * collapses to `org.id` and all current behavior is preserved. + */ +export function effectiveBillingOrgId( + org: Pick, +): string { + return org.parentOrgId ?? org.id; +} diff --git a/packages/db/src/membership/index.ts b/packages/db/src/membership/index.ts new file mode 100644 index 0000000..94b4a50 --- /dev/null +++ b/packages/db/src/membership/index.ts @@ -0,0 +1,21 @@ +export type { + Organization, + OrganizationMember, + OrganizationInvitation, + RoleAssignment, + CreateOrganizationInput, + CreateOrganizationMemberInput, + CreateInvitationInput, + CreateRoleAssignmentInput, + AcceptInvitationInput, + BootstrapOrganizationInput, + MembershipRepository, + MembershipResult, + MembershipRepositoryError, + CursorPosition, + PageQueryParams, + PagedResult, +} from "./types.js"; + +export { createMembershipRepository } from "./repository.js"; +export { effectiveBillingOrgId } from "./billing-scope.js"; diff --git a/packages/db/src/membership/repository.ts b/packages/db/src/membership/repository.ts new file mode 100644 index 0000000..65a1332 --- /dev/null +++ b/packages/db/src/membership/repository.ts @@ -0,0 +1,758 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + AcceptInvitationInput, + BootstrapOrganizationInput, + CreateInvitationInput, + CreateOrganizationInput, + CreateOrganizationMemberInput, + CreateRoleAssignmentInput, + CursorPosition, + MembershipRepository, + MembershipResult, + Organization, + OrganizationInvitation, + OrganizationMember, + PagedResult, + PageQueryParams, + RoleAssignment, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; + +function mapOrganization(row: Record): Organization { + return { + id: row.id as string, + name: row.name as string, + slug: row.slug as string, + slugLower: row.slug_lower as string, + status: row.status as string, + parentOrgId: (row.parent_org_id as string | null) ?? null, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapMember(row: Record): OrganizationMember { + return { + id: row.id as string, + orgId: row.org_id as string, + subjectId: row.subject_id as string, + subjectType: row.subject_type as string, + status: row.status as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapInvitation(row: Record): OrganizationInvitation { + return { + id: row.id as string, + orgId: row.org_id as string, + email: row.email as string, + emailLower: row.email_lower as string, + role: row.role as string, + status: row.status as string, + invitedBy: row.invited_by as string, + expiresAt: new Date(row.expires_at as string), + acceptedAt: row.accepted_at ? new Date(row.accepted_at as string) : null, + revokedAt: row.revoked_at ? new Date(row.revoked_at as string) : null, + createdAt: new Date(row.created_at as string), + }; +} + +function mapRoleAssignment(row: Record): RoleAssignment { + return { + id: row.id as string, + orgId: row.org_id as string, + subjectId: row.subject_id as string, + subjectType: row.subject_type as string, + role: row.role as string, + scopeKind: row.scope_kind as string, + scopeRef: (row.scope_ref as string) ?? null, + createdAt: new Date(row.created_at as string), + revokedAt: row.revoked_at ? new Date(row.revoked_at as string) : null, + }; +} + +function parseJsonColumn(value: unknown): Record { + if (typeof value === "string") return JSON.parse(value) as Record; + return value as Record; +} + +function safeError(message: string, cause?: unknown): MembershipResult { + // Surface the underlying DB error so failures are diagnosable in `wrangler + // tail` instead of silently collapsing into an opaque internal error. Only + // the error's name/message/code are logged — never query parameters — so no + // ids, tokens, or secret material leak into logs. + if (cause !== undefined) { + const e = cause as { name?: unknown; message?: unknown; code?: unknown }; + console.error(`[membership-repo] ${message}`, { + name: typeof e?.name === "string" ? e.name : undefined, + message: typeof e?.message === "string" ? e.message : undefined, + code: typeof e?.code === "string" ? e.code : undefined, + }); + } + return { ok: false, error: { kind: "internal", message } }; +} + + +export function createMembershipRepository(executor: SqlExecutor): MembershipRepository { + return { + async createOrganization(input: CreateOrganizationInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO membership_organizations (id, name, slug, slug_lower, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $5) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.name, input.slug, input.slugLower, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "organization" } }; + } + return { ok: true, value: mapOrganization(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "organization" } }; + } + return safeError("Failed to create organization", err); + } + }, + + async getOrganizationById(id: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_organizations WHERE id = $1`, + [id], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapOrganization(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to get organization", err); + } + }, + + async getOrganizationBySlug(slugLower: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_organizations WHERE slug_lower = $1`, + [slugLower], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapOrganization(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to get organization by slug", err); + } + }, + + async listChildOrganizations(parentOrgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_organizations WHERE parent_org_id = $1 ORDER BY created_at ASC`, + [parentOrgId], + ); + return { ok: true, value: result.rows.map(mapOrganization) }; + } catch (err) { + return safeError("Failed to list child organizations", err); + } + }, + + async setOrganizationStatus(orgId: string, status: string, updatedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE membership_organizations SET status = $2, updated_at = $3 WHERE id = $1 RETURNING *`, + [orgId, status, updatedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapOrganization(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to set organization status", err); + } + }, + + async listOrganizationsForSubject(subjectId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT o.* FROM membership_organizations o + INNER JOIN membership_organization_members m ON m.org_id = o.id + WHERE m.subject_id = $1 AND m.status = 'active'`, + [subjectId], + ); + return { ok: true, value: result.rows.map(mapOrganization) }; + } catch (err) { + return safeError("Failed to list organizations for subject", err); + } + }, + + async listOrganizationsForSubjectPaged(subjectId: string, params: PageQueryParams): Promise>> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT o.* FROM membership_organizations o + INNER JOIN membership_organization_members m ON m.org_id = o.id + WHERE m.subject_id = $1 AND m.status = 'active' + AND (o.created_at, o.id) < ($3, $4) + ORDER BY o.created_at DESC, o.id DESC + LIMIT $2`; + values = [subjectId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT o.* FROM membership_organizations o + INNER JOIN membership_organization_members m ON m.org_id = o.id + WHERE m.subject_id = $1 AND m.status = 'active' + ORDER BY o.created_at DESC, o.id DESC + LIMIT $2`; + values = [subjectId, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapOrganization); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch (err) { + return safeError("Failed to list organizations for subject", err); + } + }, + + async bootstrapOrganization(input: BootstrapOrganizationInput): Promise> { + try { + const result = await executor.execute>( + `WITH new_org AS ( + INSERT INTO membership_organizations (id, name, slug, slug_lower, parent_org_id, created_at, updated_at) + VALUES ($1, $2, $3, $4, $19, $5, $5) + ON CONFLICT (id) DO NOTHING + RETURNING * + ), + new_member AS ( + INSERT INTO membership_organization_members (id, org_id, subject_id, subject_type, created_at, updated_at) + SELECT $6, $7, $8, $9, $10, $10 + FROM new_org + ON CONFLICT (id) DO NOTHING + RETURNING * + ), + new_role AS ( + INSERT INTO membership_role_assignments (id, org_id, subject_id, subject_type, role, scope_kind, scope_ref, created_at) + SELECT $11, $12, $13, $14, $15, $16, $17, $18 + FROM new_member + ON CONFLICT (id) DO NOTHING + RETURNING * + ) + SELECT + row_to_json(o.*) as org, + row_to_json(m.*) as member, + row_to_json(r.*) as role_assignment + FROM new_org o + CROSS JOIN new_member m + CROSS JOIN new_role r`, + [ + input.org.id, input.org.name, input.org.slug, input.org.slugLower, input.org.createdAt.toISOString(), + input.member.id, input.member.orgId, input.member.subjectId, input.member.subjectType, input.member.createdAt.toISOString(), + input.roleAssignment.id, input.roleAssignment.orgId, input.roleAssignment.subjectId, input.roleAssignment.subjectType, input.roleAssignment.role, input.roleAssignment.scopeKind, input.roleAssignment.scopeRef ?? null, input.roleAssignment.createdAt.toISOString(), + input.org.parentOrgId ?? null, + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "organization" } }; + } + const row = result.rows[0]!; + return { + ok: true, + value: { + org: mapOrganization(parseJsonColumn(row.org)), + member: mapMember(parseJsonColumn(row.member)), + roleAssignment: mapRoleAssignment(parseJsonColumn(row.role_assignment)), + }, + }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "organization" } }; + } + return safeError("Failed to bootstrap organization", err); + } + }, + + async createMember(input: CreateOrganizationMemberInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO membership_organization_members (id, org_id, subject_id, subject_type, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $5) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.orgId, input.subjectId, input.subjectType, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "organization_member" } }; + } + return { ok: true, value: mapMember(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "organization_member" } }; + } + return safeError("Failed to create member", err); + } + }, + + async getMemberById(orgId: string, memberId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_organization_members WHERE org_id = $1 AND id = $2`, + [orgId, memberId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const member = mapMember(result.rows[0]!); + if (member.status === "removed") { + return { ok: false, error: { kind: "removed" } }; + } + return { ok: true, value: member }; + } catch (err) { + return safeError("Failed to get member", err); + } + }, + + async listMembers(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_organization_members WHERE org_id = $1 AND status = 'active'`, + [orgId], + ); + return { ok: true, value: result.rows.map(mapMember) }; + } catch (err) { + return safeError("Failed to list members", err); + } + }, + + async listMembersPaged(orgId: string, params: PageQueryParams): Promise>> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT * FROM membership_organization_members + WHERE org_id = $1 AND status = 'active' + AND (created_at, id) < ($3, $4) + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT * FROM membership_organization_members + WHERE org_id = $1 AND status = 'active' + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapMember); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch (err) { + return safeError("Failed to list members", err); + } + }, + + async removeMember(orgId: string, memberId: string, updatedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE membership_organization_members + SET status = 'removed', updated_at = $3 + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING *`, + [orgId, memberId, updatedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapMember(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to remove member", err); + } + }, + + async createInvitation(input: CreateInvitationInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO membership_organization_invitations (id, org_id, email, email_lower, role, token_hash, invited_by, expires_at, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (id) DO NOTHING + RETURNING id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at`, + [input.id, input.orgId, input.email, input.emailLower, input.role, input.tokenHash, input.invitedBy, input.expiresAt.toISOString(), input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "invitation" } }; + } + return { ok: true, value: mapInvitation(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "invitation" } }; + } + return safeError("Failed to create invitation", err); + } + }, + + async getInvitationById(orgId: string, invitationId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations WHERE org_id = $1 AND id = $2`, + [orgId, invitationId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const inv = mapInvitation(result.rows[0]!); + if (inv.revokedAt !== null) { + return { ok: false, error: { kind: "revoked" } }; + } + if (inv.acceptedAt !== null) { + return { ok: false, error: { kind: "already_accepted" } }; + } + if (inv.expiresAt < new Date()) { + return { ok: false, error: { kind: "expired" } }; + } + return { ok: true, value: inv }; + } catch (err) { + return safeError("Failed to get invitation", err); + } + }, + + async getInvitationByTokenHash(tokenHash: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations WHERE token_hash = $1`, + [tokenHash], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const inv = mapInvitation(result.rows[0]!); + if (inv.revokedAt !== null) { + return { ok: false, error: { kind: "revoked" } }; + } + if (inv.acceptedAt !== null) { + return { ok: false, error: { kind: "already_accepted" } }; + } + if (inv.expiresAt < new Date()) { + return { ok: false, error: { kind: "expired" } }; + } + return { ok: true, value: inv }; + } catch (err) { + return safeError("Failed to get invitation by token", err); + } + }, + + async listInvitations(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations WHERE org_id = $1`, + [orgId], + ); + return { ok: true, value: result.rows.map(mapInvitation) }; + } catch (err) { + return safeError("Failed to list invitations", err); + } + }, + + async listInvitationsPaged(orgId: string, params: PageQueryParams): Promise>> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations + WHERE org_id = $1 + AND (created_at, id) < ($3, $4) + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations + WHERE org_id = $1 + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapInvitation); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch (err) { + return safeError("Failed to list invitations", err); + } + }, + + async revokeInvitation(orgId: string, invitationId: string, revokedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE membership_organization_invitations + SET status = 'revoked', revoked_at = $3 + WHERE org_id = $1 AND id = $2 AND status = 'pending' AND revoked_at IS NULL AND accepted_at IS NULL + RETURNING id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at`, + [orgId, invitationId, revokedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapInvitation(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to revoke invitation", err); + } + }, + + async acceptInvitation(input: AcceptInvitationInput): Promise> { + try { + const checkResult = await executor.execute>( + `SELECT id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + FROM membership_organization_invitations WHERE token_hash = $1`, + [input.tokenHash], + ); + if (checkResult.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const inv = mapInvitation(checkResult.rows[0]!); + if (inv.orgId !== input.orgId) { + return { ok: false, error: { kind: "not_found" } }; + } + if (inv.emailLower !== input.emailLower) { + return { ok: false, error: { kind: "not_found" } }; + } + if (inv.revokedAt !== null) { + return { ok: false, error: { kind: "revoked" } }; + } + if (inv.acceptedAt !== null) { + return { ok: false, error: { kind: "already_accepted" } }; + } + if (inv.expiresAt < input.acceptedAt) { + return { ok: false, error: { kind: "expired" } }; + } + + const result = await executor.execute>( + `WITH accepted_inv AS ( + UPDATE membership_organization_invitations + SET status = 'accepted', accepted_at = $2 + WHERE token_hash = $1 AND org_id = $3 AND email_lower = $4 AND status = 'pending' AND revoked_at IS NULL AND accepted_at IS NULL AND expires_at > $2 + RETURNING id, org_id, email, email_lower, role, status, invited_by, expires_at, accepted_at, revoked_at, created_at + ), + new_member AS ( + INSERT INTO membership_organization_members (id, org_id, subject_id, subject_type, created_at, updated_at) + SELECT $5, org_id, $6, $7, $8, $8 + FROM accepted_inv + RETURNING * + ), + new_role AS ( + INSERT INTO membership_role_assignments (id, org_id, subject_id, subject_type, role, scope_kind, scope_ref, created_at) + SELECT $9, org_id, $10, $11, role, 'organization', NULL, $12 + FROM accepted_inv + RETURNING * + ) + SELECT + row_to_json(ai.*) as invitation, + row_to_json(nm.*) as member, + row_to_json(nr.*) as role_assignment + FROM accepted_inv ai + CROSS JOIN new_member nm + CROSS JOIN new_role nr`, + [ + input.tokenHash, input.acceptedAt.toISOString(), + input.orgId, input.emailLower, + input.memberId, input.subjectId, input.subjectType, input.acceptedAt.toISOString(), + input.roleAssignmentId, input.subjectId, input.subjectType, input.acceptedAt.toISOString(), + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const row = result.rows[0]!; + return { + ok: true, + value: { + invitation: mapInvitation(parseJsonColumn(row.invitation)), + member: mapMember(parseJsonColumn(row.member)), + roleAssignment: mapRoleAssignment(parseJsonColumn(row.role_assignment)), + }, + }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "organization_member" } }; + } + return safeError("Failed to accept invitation", err); + } + }, + + async createRoleAssignment(input: CreateRoleAssignmentInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO membership_role_assignments (id, org_id, subject_id, subject_type, role, scope_kind, scope_ref, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.orgId, input.subjectId, input.subjectType, input.role, input.scopeKind, input.scopeRef ?? null, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "role_assignment" } }; + } + return { ok: true, value: mapRoleAssignment(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "role_assignment" } }; + } + return safeError("Failed to create role assignment", err); + } + }, + + async listRoleAssignments(orgId: string, subjectId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM membership_role_assignments WHERE org_id = $1 AND subject_id = $2 AND revoked_at IS NULL`, + [orgId, subjectId], + ); + return { ok: true, value: result.rows.map(mapRoleAssignment) }; + } catch (err) { + return safeError("Failed to list role assignments", err); + } + }, + + async listRoleAssignmentsForSubjects( + orgId: string, + subjectIds: string[], + ): Promise>> { + const map = new Map(); + if (subjectIds.length === 0) return { ok: true, value: map }; + try { + // PERF3 (task 0132): one batched query instead of N per-member queries. + // NOTE: use a parameterized IN (...) list of scalar text params rather + // than `= ANY($2)` with a JS array. The pg driver runs with + // `fetch_types: false` (executor.ts), which leaves array parameters + // without a resolvable element-type OID and makes `ANY($array)` throw + // at bind time — that surfaced as a hard 500 on the members list. A + // scalar IN list avoids array serialization entirely. + const placeholders = subjectIds.map((_, i) => `$${i + 2}`).join(", "); + const result = await executor.execute>( + `SELECT * FROM membership_role_assignments + WHERE org_id = $1 AND subject_id IN (${placeholders}) AND revoked_at IS NULL`, + [orgId, ...subjectIds], + ); + for (const id of subjectIds) map.set(id, []); + for (const row of result.rows) { + const ra = mapRoleAssignment(row); + const bucket = map.get(ra.subjectId); + if (bucket) bucket.push(ra); + else map.set(ra.subjectId, [ra]); + } + return { ok: true, value: map }; + } catch (err) { + return safeError("Failed to list role assignments for subjects", err); + } + }, + + async revokeRoleAssignment(orgId: string, assignmentId: string, revokedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE membership_role_assignments + SET revoked_at = $3 + WHERE org_id = $1 AND id = $2 AND revoked_at IS NULL + RETURNING *`, + [orgId, assignmentId, revokedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapRoleAssignment(result.rows[0]!) }; + } catch (err) { + return safeError("Failed to revoke role assignment", err); + } + }, + + async revokeAllRoleAssignments(orgId: string, subjectId: string, revokedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE membership_role_assignments + SET revoked_at = $3 + WHERE org_id = $1 AND subject_id = $2 AND revoked_at IS NULL + RETURNING *`, + [orgId, subjectId, revokedAt.toISOString()], + ); + return { ok: true, value: result.rows.map(mapRoleAssignment) }; + } catch (err) { + return safeError("Failed to revoke all role assignments", err); + } + }, + + async countActiveOwners(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT COUNT(*) AS cnt + FROM membership_role_assignments ra + INNER JOIN membership_organization_members m + ON m.org_id = ra.org_id AND m.subject_id = ra.subject_id + WHERE ra.org_id = $1 + AND ra.role = 'owner' + AND ra.scope_kind = 'organization' + AND ra.revoked_at IS NULL + AND m.status = 'active'`, + [orgId], + ); + const cnt = Number(result.rows[0]?.cnt ?? 0); + return { ok: true, value: cnt }; + } catch (err) { + return safeError("Failed to count active owners", err); + } + }, + + async countBillableMembers(orgId: string, now: Date): Promise> { + // A "billable" seat is anything that grows the active membership of an + // organization. We count: + // 1) active organization members; plus + // 2) pending invitations (not accepted, not revoked, not expired). + // The two populations are disjoint by construction: an invitation that + // has been accepted is no longer 'pending' and instead surfaces as an + // active organization_members row, which the first sub-count picks up. + // Both sub-counts are evaluated in a single round-trip to keep this + // helper cheap enough to call on the create-invitation hot path. + try { + const result = await executor.execute>( + `SELECT + (SELECT COUNT(*) FROM membership_organization_members + WHERE org_id = $1 AND status = 'active') + + + (SELECT COUNT(*) FROM membership_organization_invitations + WHERE org_id = $1 + AND status = 'pending' + AND revoked_at IS NULL + AND accepted_at IS NULL + AND expires_at > $2) + AS cnt`, + [orgId, now.toISOString()], + ); + const cnt = Number(result.rows[0]?.cnt ?? 0); + return { ok: true, value: cnt }; + } catch (err) { + return safeError("Failed to count billable members", err); + } + }, + }; +} diff --git a/packages/db/src/membership/types.ts b/packages/db/src/membership/types.ts new file mode 100644 index 0000000..49aa964 --- /dev/null +++ b/packages/db/src/membership/types.ts @@ -0,0 +1,204 @@ +import type { Uuid } from "../ids/index.js"; + +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +export type MembershipRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "expired" } + | { kind: "revoked" } + | { kind: "already_accepted" } + | { kind: "removed" } + | { kind: "internal"; message: string }; + +export type MembershipResult = + | { ok: true; value: T } + | { ok: false; error: MembershipRepositoryError }; + +export interface Organization { + id: string; + name: string; + slug: string; + slugLower: string; + status: string; + /** + * Optional billing parent (epic `saas-multi-org-billing`, MO1). When set, this + * organization rolls its billing up to the referenced (default/parent) org; + * NULL means standalone (bills for itself) — the case for every existing org. + * Resolve with `effectiveBillingOrgId`. + */ + parentOrgId: string | null; + createdAt: Date; + updatedAt: Date; +} + +export interface OrganizationMember { + id: string; + orgId: string; + subjectId: string; + subjectType: string; + status: string; + createdAt: Date; + updatedAt: Date; +} + +export interface OrganizationInvitation { + id: string; + orgId: string; + email: string; + emailLower: string; + role: string; + status: string; + invitedBy: string; + expiresAt: Date; + acceptedAt: Date | null; + revokedAt: Date | null; + createdAt: Date; +} + +export interface RoleAssignment { + id: string; + orgId: string; + subjectId: string; + subjectType: string; + role: string; + scopeKind: string; + scopeRef: string | null; + createdAt: Date; + revokedAt: Date | null; +} + +export interface CreateOrganizationInput { + id: string; + name: string; + slug: string; + slugLower: string; + /** Optional billing parent (MO3). NULL/absent = standalone org. */ + parentOrgId?: string | null; + createdAt: Date; +} + +export interface CreateOrganizationMemberInput { + id: string; + orgId: Uuid; + subjectId: string; + subjectType: string; + createdAt: Date; +} + +export interface CreateInvitationInput { + id: string; + orgId: Uuid; + email: string; + emailLower: string; + role: string; + tokenHash: string; + invitedBy: string; + expiresAt: Date; + createdAt: Date; +} + +export interface CreateRoleAssignmentInput { + id: string; + orgId: Uuid; + subjectId: string; + subjectType: string; + role: string; + scopeKind: string; + scopeRef?: string | null; + createdAt: Date; +} + +export interface BootstrapOrganizationInput { + org: CreateOrganizationInput; + member: CreateOrganizationMemberInput; + roleAssignment: CreateRoleAssignmentInput; +} + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +export interface AcceptInvitationInput { + tokenHash: string; + orgId: Uuid; + emailLower: string; + memberId: string; + roleAssignmentId: string; + subjectId: string; + subjectType: string; + acceptedAt: Date; +} + +export interface MembershipRepository { + createOrganization(input: CreateOrganizationInput): Promise>; + getOrganizationById(id: string): Promise>; + getOrganizationBySlug(slugLower: string): Promise>; + /** Child orgs whose billing parent is `parentOrgId` (MO3), oldest first. */ + listChildOrganizations(parentOrgId: string): Promise>; + /** Set an org's lifecycle status (e.g. freeze a child to 'suspended', MO3). */ + setOrganizationStatus(orgId: string, status: string, updatedAt: Date): Promise>; + listOrganizationsForSubject(subjectId: string): Promise>; + listOrganizationsForSubjectPaged(subjectId: string, params: PageQueryParams): Promise>>; + + bootstrapOrganization(input: BootstrapOrganizationInput): Promise>; + + createMember(input: CreateOrganizationMemberInput): Promise>; + getMemberById(orgId: Uuid, memberId: string): Promise>; + listMembers(orgId: Uuid): Promise>; + listMembersPaged(orgId: Uuid, params: PageQueryParams): Promise>>; + removeMember(orgId: Uuid, memberId: string, updatedAt: Date): Promise>; + + createInvitation(input: CreateInvitationInput): Promise>; + getInvitationById(orgId: Uuid, invitationId: string): Promise>; + getInvitationByTokenHash(tokenHash: string): Promise>; + listInvitations(orgId: Uuid): Promise>; + listInvitationsPaged(orgId: Uuid, params: PageQueryParams): Promise>>; + revokeInvitation(orgId: Uuid, invitationId: string, revokedAt: Date): Promise>; + acceptInvitation(input: AcceptInvitationInput): Promise>; + + createRoleAssignment(input: CreateRoleAssignmentInput): Promise>; + listRoleAssignments(orgId: Uuid, subjectId: string): Promise>; + /** + * Batched reverse lookup: all active role assignments for a set of subjects in + * one query, returned as a `subjectId -> RoleAssignment[]` map (every queried + * subject is present, possibly empty). Avoids the per-member N+1 in member + * listing (PERF3 / task 0132). Optional so callers/fakes degrade gracefully to + * per-subject `listRoleAssignments`; the live repository always implements it. + */ + listRoleAssignmentsForSubjects?(orgId: Uuid, subjectIds: string[]): Promise>>; + revokeRoleAssignment(orgId: Uuid, assignmentId: string, revokedAt: Date): Promise>; + revokeAllRoleAssignments(orgId: Uuid, subjectId: string, revokedAt: Date): Promise>; + countActiveOwners(orgId: Uuid): Promise>; + + /** + * Counts billable members for an organization for the purposes of the + * `limit.members` billing entitlement. The count includes: + * - active organization members (membership_organization_members.status = 'active'); and + * - pending invitations whose `expires_at > now` and that have neither + * been accepted nor revoked. + * + * Accepted invitations are not counted here because accepting an invitation + * already inserts an `organization_members` row and the active member is + * counted via the first clause; counting the accepted invitation again + * would double-count. + * + * Revoked invitations and expired pending invitations are excluded so + * that revoking or letting an invite expire frees a seat back up. + * + * The helper performs the count in a single parameterized SQL statement + * to avoid paging entire tables for billing decisions. + */ + countBillableMembers(orgId: Uuid, now: Date): Promise>; +} diff --git a/packages/db/src/metering/index.ts b/packages/db/src/metering/index.ts new file mode 100644 index 0000000..e47ccd0 --- /dev/null +++ b/packages/db/src/metering/index.ts @@ -0,0 +1,25 @@ +export type { + MeteringRepositoryError, + MeteringResult, + CursorPosition, + PageQueryParams, + PagedResult, + BucketType, + UsageRecord, + RecordUsageInput, + UsageRollup, + UsageSummaryQuery, + UsageSummary, + RollupMaterializationWindow, + RollupMaterializationResult, + QuotaPeriod, + QuotaEnforcement, + QuotaStatus, + QuotaDefinition, + QuotaCheckResult, + QuotaViolation, + ListViolationsQuery, + MeteringRepository, +} from "./types.js"; + +export { createMeteringRepository } from "./repository.js"; diff --git a/packages/db/src/metering/repository.ts b/packages/db/src/metering/repository.ts new file mode 100644 index 0000000..d7b2ede --- /dev/null +++ b/packages/db/src/metering/repository.ts @@ -0,0 +1,529 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + MeteringRepository, + MeteringResult, + CursorPosition, + PagedResult, + PageQueryParams, + UsageRecord, + UsageRollup, + UsageSummary, + UsageSummaryQuery, + RollupMaterializationWindow, + RollupMaterializationResult, + QuotaCheckResult, + QuotaViolation, + ListViolationsQuery, + RecordUsageInput, + QuotaPeriod, + QuotaEnforcement, + BucketType, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseNullableJsonColumn } from "../json.js"; + +// ── Row mappers ──────────────────────────────────────────── + +function mapUsageRecord(row: Record): UsageRecord { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + resourceId: (row.resource_id as string) ?? null, + metric: row.metric as string, + quantity: Number(row.quantity), + idempotencyKey: row.idempotency_key as string, + recordedAt: new Date(row.recorded_at as string), + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: new Date(row.created_at as string), + }; +} + +function mapUsageRollup(row: Record): UsageRollup { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + metric: row.metric as string, + bucketType: row.bucket_type as BucketType, + bucketStart: new Date(row.bucket_start as string), + quantity: Number(row.quantity), + recordCount: Number(row.record_count), + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapQuotaViolation(row: Record): QuotaViolation { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + environmentId: (row.environment_id as string) ?? null, + resourceId: (row.resource_id as string) ?? null, + quotaId: row.quota_id as string, + metric: row.metric as string, + limitValue: Number(row.limit_value), + actualValue: Number(row.actual_value), + period: row.period as QuotaPeriod, + enforcement: row.enforcement as QuotaEnforcement, + violatedAt: new Date(row.violated_at as string), + resolvedAt: row.resolved_at ? new Date(row.resolved_at as string) : null, + metadata: parseNullableJsonColumn>(row.metadata), + createdAt: new Date(row.created_at as string), + }; +} + +// ── Helpers ──────────────────────────────────────────────── + +function safeError(message: string): MeteringResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +// ── Paged list helper ────────────────────────────────────── + +async function pagedList( + executor: SqlExecutor, + sql: string, + values: unknown[], + limit: number, + cursor: CursorPosition | null, + mapper: (row: Record) => T, + cursorDateField = "created_at", +): Promise>> { + try { + const fetchLimit = limit + 1; + let fullSql: string; + let fullValues: unknown[]; + const baseIdx = values.length; + + if (cursor) { + fullSql = `${sql} AND (${cursorDateField}, id) < ($${baseIdx + 2}, $${baseIdx + 3}) ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit, cursor.createdAt, cursor.id]; + } else { + fullSql = `${sql} ORDER BY ${cursorDateField} DESC, id DESC LIMIT $${baseIdx + 1}`; + fullValues = [...values, fetchLimit]; + } + + const result = await executor.execute>(fullSql, fullValues); + const rows = result.rows.map(mapper); + let nextCursor: CursorPosition | null = null; + if (rows.length > limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { + createdAt: (last as unknown as { createdAt: Date }).createdAt.toISOString(), + id: (last as unknown as { id: string }).id, + }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list records"); + } +} + +// ── Repository factory ───────────────────────────────────── + +export function createMeteringRepository(executor: SqlExecutor): MeteringRepository { + return { + async recordUsage(input: RecordUsageInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO metering_usage_records + (id, org_id, project_id, environment_id, resource_id, metric, quantity, idempotency_key, recorded_at, metadata, created_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id, idempotency_key) DO NOTHING + RETURNING *`, + [ + input.id, + input.orgId, + input.projectId ?? null, + input.environmentId ?? null, + input.resourceId ?? null, + input.metric, + input.quantity ?? 1, + input.idempotencyKey, + input.recordedAt?.toISOString() ?? new Date().toISOString(), + input.metadata ? JSON.stringify(input.metadata) : null, + ], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "usage_record" } }; + } + return { ok: true, value: mapUsageRecord(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "usage_record" } }; + } + return safeError("Failed to record usage"); + } + }, + + async ingestUsageBatch( + inputs: RecordUsageInput[], + ): Promise> }>> { + const results: Array> = []; + for (const input of inputs) { + const result = await this.recordUsage(input); + results.push(result); + } + return { ok: true, value: { results } }; + }, + + async getUsageSummary(query: UsageSummaryQuery): Promise> { + try { + const conditions: string[] = ["org_id = $1", "metric = $2"]; + const values: unknown[] = [query.orgId, query.metric]; + let idx = 3; + + if (query.projectId) { + conditions.push(`project_id = $${idx}`); + values.push(query.projectId); + idx++; + } + if (query.environmentId) { + conditions.push(`environment_id = $${idx}`); + values.push(query.environmentId); + idx++; + } + if (query.bucketType) { + conditions.push(`bucket_type = $${idx}`); + values.push(query.bucketType); + idx++; + } + if (query.startTime) { + conditions.push(`bucket_start >= $${idx}`); + values.push(query.startTime.toISOString()); + idx++; + } + if (query.endTime) { + conditions.push(`bucket_start < $${idx}`); + values.push(query.endTime.toISOString()); + idx++; + } + + const whereClause = conditions.join(" AND "); + const sql = `SELECT * FROM metering_usage_rollups WHERE ${whereClause} ORDER BY bucket_start DESC`; + const result = await executor.execute>(sql, values); + const rollups = result.rows.map(mapUsageRollup); + + let totalQuantity = 0; + let totalRecords = 0; + for (const r of rollups) { + totalQuantity += r.quantity; + totalRecords += r.recordCount; + } + + return { + ok: true, + value: { + metric: query.metric, + totalQuantity, + totalRecords, + rollups, + }, + }; + } catch { + return safeError("Failed to get usage summary"); + } + }, + + async listUsageRollups( + orgId: string, + params: PageQueryParams, + ): Promise>> { + return pagedList( + executor, + "SELECT * FROM metering_usage_rollups WHERE org_id = $1", + [orgId], + params.limit, + params.cursor, + mapUsageRollup, + ); + }, + + async materializeUsageRollups( + window: RollupMaterializationWindow, + ): Promise> { + if (window.bucketType !== "hour" && window.bucketType !== "day") { + return safeError("Invalid bucket_type"); + } + if (!(window.start instanceof Date) || !(window.end instanceof Date)) { + return safeError("Invalid window bounds"); + } + if (window.end.getTime() <= window.start.getTime()) { + return safeError("Window end must be greater than start"); + } + + // Aggregate raw usage records into the target bucket and upsert into + // metering_usage_rollups. The unique index is on + // (org_id, COALESCE(project_id, ''), COALESCE(environment_id, ''), metric, bucket_type, bucket_start) + // — the ON CONFLICT target must mirror those expressions exactly. + // + // Truncation is a strftime format, not a `date_trunc` argument: SQLite + // has no date_trunc, and timestamps are stored as ISO-8601 text. The + // format is chosen from the bucket type validated at the top of this + // method (it is an enum of two literals, never caller text), because a + // bound parameter cannot appear inside a strftime format string. + const bucketFormat = + window.bucketType === "hour" ? "%Y-%m-%dT%H:00:00.000Z" : "%Y-%m-%dT00:00:00.000Z"; + + // The synthesized id is the aggregation key itself, so repeated + // materializations of the same bucket produce the same id. (Postgres + // hashed it with md5; SQLite has no md5 and D1 exposes no hash function, + // and the key is already unique — hashing only shortened it.) On + // conflict the existing row id is kept and quantity/record_count are + // overwritten. + // + // All values are passed via $-parameters; no user input is interpolated. + const sql = ` + WITH agg AS ( + SELECT + org_id, + project_id, + environment_id, + metric, + strftime('${bucketFormat}', recorded_at) AS bucket_start, + SUM(quantity) AS quantity, + COUNT(*) AS record_count + FROM metering_usage_records + WHERE recorded_at >= $2 + AND recorded_at < $3 + GROUP BY org_id, project_id, environment_id, metric, + strftime('${bucketFormat}', recorded_at) + ) + INSERT INTO metering_usage_rollups ( + id, org_id, project_id, environment_id, metric, + bucket_type, bucket_start, quantity, record_count, + created_at, updated_at + ) + SELECT + org_id || '|' || + COALESCE(project_id, '') || '|' || + COALESCE(environment_id, '') || '|' || + metric || '|' || + $1 || '|' || + bucket_start AS id, + org_id, project_id, environment_id, metric, + $1 AS bucket_type, + bucket_start, + quantity, + record_count, + strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now') + FROM agg + WHERE true + ON CONFLICT ( + org_id, + COALESCE(project_id, ''), + COALESCE(environment_id, ''), + metric, + bucket_type, + bucket_start + ) DO UPDATE SET + quantity = EXCLUDED.quantity, + record_count = EXCLUDED.record_count, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + `; + + try { + const result = await executor.execute>(sql, [ + window.bucketType, + window.start.toISOString(), + window.end.toISOString(), + ]); + return { + ok: true, + value: { + bucketType: window.bucketType, + windowStart: window.start, + windowEnd: window.end, + rollupsWritten: result.rowCount, + }, + }; + } catch { + return safeError("Failed to materialize usage rollups"); + } + }, + + async checkQuota( + orgId: string, + metric: string, + options?: { + projectId?: string; + environmentId?: string; + resourceId?: string; + }, + ): Promise> { + try { + // Find the most specific active quota definition + const conditions: string[] = [ + "org_id = $1", + "metric = $2", + "status = 'active'", + ]; + const values: unknown[] = [orgId, metric]; + let idx = 3; + + // Build scope conditions — match exact or NULL for optional dimensions + const scopeConditions: string[] = []; + if (options?.projectId) { + scopeConditions.push(`(project_id = $${idx} OR project_id IS NULL)`); + values.push(options.projectId); + idx++; + } else { + scopeConditions.push("project_id IS NULL"); + } + if (options?.environmentId) { + scopeConditions.push(`(environment_id = $${idx} OR environment_id IS NULL)`); + values.push(options.environmentId); + idx++; + } else { + scopeConditions.push("environment_id IS NULL"); + } + if (options?.resourceId) { + scopeConditions.push(`(resource_id = $${idx} OR resource_id IS NULL)`); + values.push(options.resourceId); + idx++; + } else { + scopeConditions.push("resource_id IS NULL"); + } + + conditions.push(...scopeConditions); + const whereClause = conditions.join(" AND "); + + // Get the quota definition (most specific first) + const quotaSql = `SELECT * FROM metering_quota_definitions WHERE ${whereClause} ORDER BY + CASE WHEN resource_id IS NOT NULL THEN 0 ELSE 1 END, + CASE WHEN environment_id IS NOT NULL THEN 0 ELSE 1 END, + CASE WHEN project_id IS NOT NULL THEN 0 ELSE 1 END + LIMIT 1`; + const quotaResult = await executor.execute>(quotaSql, values); + + if (quotaResult.rowCount === 0) { + // No quota defined — usage is allowed + return { + ok: true, + value: { + allowed: true, + metric, + limit: -1, + used: 0, + remaining: -1, + period: "month", + enforcement: "soft", + reason: "no_quota_defined", + }, + }; + } + + const quota = quotaResult.rows[0]!; + const limitValue = Number(quota.limit_value); + const period = quota.period as QuotaPeriod; + const enforcement = quota.enforcement as QuotaEnforcement; + + // Calculate current usage from rollups for the period + const now = new Date(); + let periodStart: Date; + switch (period) { + case "hour": + periodStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()); + break; + case "day": + periodStart = new Date(now.getFullYear(), now.getMonth(), now.getDate()); + break; + case "month": + case "billing_cycle": + periodStart = new Date(now.getFullYear(), now.getMonth(), 1); + break; + } + + // Sum usage from raw records for the current period + const usageConditions: string[] = ["org_id = $1", "metric = $2", "recorded_at >= $3"]; + const usageValues: unknown[] = [orgId, metric, periodStart.toISOString()]; + let usageIdx = 4; + + if (options?.projectId) { + usageConditions.push(`project_id = $${usageIdx}`); + usageValues.push(options.projectId); + usageIdx++; + } + if (options?.environmentId) { + usageConditions.push(`environment_id = $${usageIdx}`); + usageValues.push(options.environmentId); + usageIdx++; + } + if (options?.resourceId) { + usageConditions.push(`resource_id = $${usageIdx}`); + usageValues.push(options.resourceId); + usageIdx++; + } + + const usageSql = `SELECT COALESCE(SUM(quantity), 0) as total FROM metering_usage_records WHERE ${usageConditions.join(" AND ")}`; + const usageResult = await executor.execute>(usageSql, usageValues); + const used = Number(usageResult.rows[0]?.total ?? 0); + const remaining = Math.max(0, limitValue - used); + const allowed = used < limitValue; + + return { + ok: true, + value: { + allowed, + metric, + limit: limitValue, + used, + remaining, + period, + enforcement, + reason: allowed ? null : "quota_exceeded", + }, + }; + } catch { + return safeError("Failed to check quota"); + } + }, + + async listQuotaViolations( + query: ListViolationsQuery, + params: PageQueryParams, + ): Promise>> { + const conditions: string[] = ["org_id = $1"]; + const values: unknown[] = [query.orgId]; + let idx = 2; + + if (query.projectId) { + conditions.push(`project_id = $${idx}`); + values.push(query.projectId); + idx++; + } + if (query.environmentId) { + conditions.push(`environment_id = $${idx}`); + values.push(query.environmentId); + idx++; + } + if (query.resourceId) { + conditions.push(`resource_id = $${idx}`); + values.push(query.resourceId); + idx++; + } + if (query.metric) { + conditions.push(`metric = $${idx}`); + values.push(query.metric); + idx++; + } + + const whereClause = conditions.join(" AND "); + return pagedList( + executor, + `SELECT * FROM metering_quota_violations WHERE ${whereClause}`, + values, + params.limit, + params.cursor, + mapQuotaViolation, + "violated_at", + ); + }, + }; +} diff --git a/packages/db/src/metering/types.ts b/packages/db/src/metering/types.ts new file mode 100644 index 0000000..3a62c0c --- /dev/null +++ b/packages/db/src/metering/types.ts @@ -0,0 +1,246 @@ +// ── Result type ───────────────────────────────────────────── + +export type MeteringRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type MeteringResult = + | { ok: true; value: T } + | { ok: false; error: MeteringRepositoryError }; + +// ── Cursor pagination ─────────────────────────────────────── + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +// ── Usage records ─────────────────────────────────────────── + +export interface UsageRecord { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + resourceId: string | null; + metric: string; + quantity: number; + idempotencyKey: string; + recordedAt: Date; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; +} + +export interface RecordUsageInput { + id: string; + orgId: string; + projectId?: string | null; + environmentId?: string | null; + resourceId?: string | null; + metric: string; + quantity?: number; + idempotencyKey: string; + recordedAt?: Date; + /** Bounded safe metadata only — no secrets, tokens, or credentials. */ + metadata?: Record | null; +} + +// ── Usage rollups ─────────────────────────────────────────── + +export type BucketType = "hour" | "day"; + +export interface UsageRollup { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + metric: string; + bucketType: BucketType; + bucketStart: Date; + quantity: number; + recordCount: number; + createdAt: Date; + updatedAt: Date; +} + +/** + * Window over which to materialize rollups from raw usage records. + * `start` is inclusive, `end` is exclusive. The materializer aggregates all + * usage records with `recorded_at >= start AND recorded_at < end`, grouped + * into buckets of `bucketType`. Callers MUST pass a bounded recent window — + * never an unbounded scan of history. + */ +export interface RollupMaterializationWindow { + bucketType: BucketType; + start: Date; + end: Date; +} + +/** + * Result of a single bucket-type rollup materialization pass. + * `rollupsWritten` is the number of distinct rollup rows that were upserted + * (one per org/project/environment/metric/bucket_start group within the window). + */ +export interface RollupMaterializationResult { + bucketType: BucketType; + windowStart: Date; + windowEnd: Date; + rollupsWritten: number; +} + +export interface UsageSummaryQuery { + orgId: string; + projectId?: string | null; + environmentId?: string | null; + metric: string; + bucketType?: BucketType; + startTime?: Date; + endTime?: Date; +} + +export interface UsageSummary { + metric: string; + totalQuantity: number; + totalRecords: number; + rollups: UsageRollup[]; +} + +// ── Quota definitions ─────────────────────────────────────── + +export type QuotaPeriod = "hour" | "day" | "month" | "billing_cycle"; +export type QuotaEnforcement = "soft" | "hard"; +export type QuotaStatus = "active" | "inactive"; + +export interface QuotaDefinition { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + resourceId: string | null; + metric: string; + limitValue: number; + period: QuotaPeriod; + enforcement: QuotaEnforcement; + status: QuotaStatus; + createdAt: Date; + updatedAt: Date; +} + +export interface QuotaCheckResult { + allowed: boolean; + metric: string; + limit: number; + used: number; + remaining: number; + period: QuotaPeriod; + enforcement: QuotaEnforcement; + reason: string | null; +} + +// ── Quota violations ──────────────────────────────────────── + +export interface QuotaViolation { + id: string; + orgId: string; + projectId: string | null; + environmentId: string | null; + resourceId: string | null; + quotaId: string; + metric: string; + limitValue: number; + actualValue: number; + period: QuotaPeriod; + enforcement: QuotaEnforcement; + violatedAt: Date; + resolvedAt: Date | null; + /** Safe violation context — no secrets, tokens, or credentials. */ + metadata: Record | null; + createdAt: Date; +} + +export interface ListViolationsQuery { + orgId: string; + projectId?: string | null; + environmentId?: string | null; + resourceId?: string | null; + metric?: string; +} + +// ── Repository interface ──────────────────────────────────── + +export interface MeteringRepository { + /** + * Record a single usage event with exactly-once insert semantics. + * Returns conflict if the (org_id, idempotency_key) pair already exists. + */ + recordUsage(input: RecordUsageInput): Promise>; + + /** + * Ingest a batch of usage records. Each record is individually checked for + * idempotency conflicts. Returns per-record results. + */ + ingestUsageBatch( + inputs: RecordUsageInput[], + ): Promise> }>>; + + /** + * Query aggregated usage summaries by org, optional dimensions, metric, and time range. + */ + getUsageSummary(query: UsageSummaryQuery): Promise>; + + /** + * List usage rollups with cursor pagination. + */ + listUsageRollups( + orgId: string, + params: PageQueryParams, + ): Promise>>; + + /** + * Materialize `metering_usage_rollups` rows from `metering_usage_records` + * for the given bounded window and bucket type. Idempotent: re-running for + * the same window overwrites the affected rollup rows with the latest + * aggregate values rather than duplicating them. + * + * Aggregation key is `(org_id, project_id, environment_id, metric, bucket_type, bucket_start)`. + * Every aggregation row is org-scoped — no cross-org grouping is possible. + */ + materializeUsageRollups( + window: RollupMaterializationWindow, + ): Promise>; + + /** + * Check quota for a given org and metric against active quota definitions. + * Returns structured facts (allowed, limit, used, remaining, period, reason). + * Does not throw on exceeded quota. + */ + checkQuota( + orgId: string, + metric: string, + options?: { + projectId?: string; + environmentId?: string; + resourceId?: string; + }, + ): Promise>; + + /** + * List quota violations by organization with optional dimension filters. + */ + listQuotaViolations( + query: ListViolationsQuery, + params: PageQueryParams, + ): Promise>>; +} diff --git a/packages/db/src/migrations/000_control/up.sql b/packages/db/src/migrations/000_control/up.sql new file mode 100644 index 0000000..e5cce04 --- /dev/null +++ b/packages/db/src/migrations/000_control/up.sql @@ -0,0 +1,12 @@ +-- Baseline control migration +-- Creates the migration tracking schema used by the migration runner. +-- Owner: control bounded context +CREATE TABLE IF NOT EXISTS _migrations_applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + applied_by TEXT NOT NULL DEFAULT 'migration-runner' +); + +-- table _migrations_applied: Tracks which migrations have been applied to the database. diff --git a/packages/db/src/migrations/010_identity_core/up.sql b/packages/db/src/migrations/010_identity_core/up.sql new file mode 100644 index 0000000..508bcae --- /dev/null +++ b/packages/db/src/migrations/010_identity_core/up.sql @@ -0,0 +1,82 @@ +-- Identity persistence foundation. +-- Context: identity +-- Idempotent: uses IF NOT EXISTS throughout. +-- schema identity: Identity bounded context — owns users, auth identities, login challenges, and sessions. + +-- Users: the root identity record. +CREATE TABLE IF NOT EXISTS identity_users ( + id TEXT PRIMARY KEY, + email TEXT NOT NULL, + email_lower TEXT NOT NULL, + display_name TEXT, + status TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT users_status_check CHECK (status IN ('active', 'suspended', 'deleted')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS users_email_lower_idx + ON identity_users (email_lower); + +-- table identity_users: Root user records owned by the identity context. +-- column identity_users.email_lower: Normalized (lower-case) email for case-insensitive uniqueness. + +-- Auth identities: links a user to an external or internal auth provider. +CREATE TABLE IF NOT EXISTS identity_auth_identities ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES identity_users(id), + provider TEXT NOT NULL, + subject TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS auth_identities_provider_subject_idx + ON identity_auth_identities (provider, subject); + +CREATE INDEX IF NOT EXISTS auth_identities_user_id_idx + ON identity_auth_identities (user_id); + +-- table identity_auth_identities: Links users to auth providers (email, OAuth, etc). +-- column identity_auth_identities.subject: Provider-scoped subject identifier (e.g. email address, OAuth sub). + +-- Login challenges: short-lived passwordless login proofs. +CREATE TABLE IF NOT EXISTS identity_login_challenges ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES identity_users(id), + method TEXT NOT NULL, + code_hash TEXT NOT NULL, + expires_at TEXT NOT NULL, + consumed_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT login_challenges_method_check CHECK (method IN ('email_code', 'magic_link')) +); + +CREATE INDEX IF NOT EXISTS login_challenges_user_id_idx + ON identity_login_challenges (user_id); + +-- table identity_login_challenges: Short-lived passwordless login proofs. Only hashes stored. +-- column identity_login_challenges.code_hash: SHA-256 hash of the one-time code or magic-link token. Raw value never stored. + +-- Sessions: active bearer session tokens. +CREATE TABLE IF NOT EXISTS identity_sessions ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES identity_users(id), + token_hash TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + last_seen_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS sessions_token_hash_idx + ON identity_sessions (token_hash); + +CREATE INDEX IF NOT EXISTS sessions_user_id_idx + ON identity_sessions (user_id); + +-- table identity_sessions: Active user sessions. Only token hashes stored. +-- column identity_sessions.token_hash: SHA-256 hash of the bearer token. Raw token never stored. diff --git a/packages/db/src/migrations/020_membership_core/up.sql b/packages/db/src/migrations/020_membership_core/up.sql new file mode 100644 index 0000000..f027f08 --- /dev/null +++ b/packages/db/src/migrations/020_membership_core/up.sql @@ -0,0 +1,120 @@ +-- Membership persistence foundation. +-- Context: membership +-- Idempotent: uses IF NOT EXISTS throughout. +-- schema membership: Membership bounded context — owns organizations, members, invitations, and role assignments. + +-- Organizations: the root tenant boundary. +CREATE TABLE IF NOT EXISTS membership_organizations ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + slug TEXT NOT NULL, + slug_lower TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT organizations_status_check CHECK (status IN ('active', 'suspended', 'deleted')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS organizations_slug_lower_idx + ON membership_organizations (slug_lower); + +-- table membership_organizations: Root organization records — the tenant and billing boundary. +-- column membership_organizations.slug_lower: Normalized (lower-case) slug for case-insensitive uniqueness. + +-- Organization members: connects a subject to an organization. +CREATE TABLE IF NOT EXISTS membership_organization_members ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + subject_id TEXT NOT NULL, + subject_type TEXT NOT NULL DEFAULT 'user', + status TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT org_members_status_check CHECK (status IN ('active', 'removed')), + CONSTRAINT org_members_subject_type_check CHECK (subject_type IN ('user', 'service_principal')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS org_members_org_subject_idx + ON membership_organization_members (org_id, subject_id); + +CREATE INDEX IF NOT EXISTS org_members_subject_id_idx + ON membership_organization_members (subject_id); + +CREATE INDEX IF NOT EXISTS org_members_org_id_idx + ON membership_organization_members (org_id); + +-- table membership_organization_members: Membership facts connecting subjects to organizations. Subject references are opaque IDs. +-- column membership_organization_members.subject_id: Opaque subject ID from the identity or service-principal context. +-- column membership_organization_members.org_id: The organization this membership belongs to. + +-- Organization invitations: invitation lifecycle records. +CREATE TABLE IF NOT EXISTS membership_organization_invitations ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + email TEXT NOT NULL, + email_lower TEXT NOT NULL, + role TEXT NOT NULL, + token_hash TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + invited_by TEXT NOT NULL, + expires_at TEXT NOT NULL, + accepted_at TEXT, + revoked_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT org_invitations_status_check CHECK (status IN ('pending', 'accepted', 'revoked', 'expired')), + CONSTRAINT org_invitations_role_check CHECK (role IN ( + 'owner', 'admin', 'builder', 'viewer', 'billing_admin', + 'project_admin', 'project_builder', 'project_viewer' + )) +); + +CREATE UNIQUE INDEX IF NOT EXISTS org_invitations_token_hash_idx + ON membership_organization_invitations (token_hash); + +CREATE INDEX IF NOT EXISTS org_invitations_org_id_idx + ON membership_organization_invitations (org_id); + +CREATE INDEX IF NOT EXISTS org_invitations_email_lower_idx + ON membership_organization_invitations (org_id, email_lower); + +-- table membership_organization_invitations: Invitation lifecycle records. Only token hashes stored, never raw tokens. +-- column membership_organization_invitations.token_hash: SHA-256 hash of the invitation acceptance token. Raw token never stored. +-- column membership_organization_invitations.email_lower: Normalized (lower-case) email for case-insensitive lookup. + +-- Role assignments: authorization facts consumed by the policy context. +CREATE TABLE IF NOT EXISTS membership_role_assignments ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + subject_id TEXT NOT NULL, + subject_type TEXT NOT NULL DEFAULT 'user', + role TEXT NOT NULL, + scope_kind TEXT NOT NULL DEFAULT 'organization', + scope_ref TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + revoked_at TEXT, + + CONSTRAINT role_assignments_role_check CHECK (role IN ( + 'owner', 'admin', 'builder', 'viewer', 'billing_admin', + 'project_admin', 'project_builder', 'project_viewer' + )), + CONSTRAINT role_assignments_scope_kind_check CHECK (scope_kind IN ('organization', 'project')), + CONSTRAINT role_assignments_subject_type_check CHECK (subject_type IN ('user', 'service_principal')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS role_assignments_active_idx + ON membership_role_assignments (org_id, subject_id, role, scope_kind, COALESCE(scope_ref, '')) + WHERE revoked_at IS NULL; + +CREATE INDEX IF NOT EXISTS role_assignments_org_subject_idx + ON membership_role_assignments (org_id, subject_id); + +CREATE INDEX IF NOT EXISTS role_assignments_subject_id_idx + ON membership_role_assignments (subject_id); + +-- table membership_role_assignments: Authorization facts consumed by the policy context. Scoped to organization or project. +-- column membership_role_assignments.subject_id: Opaque subject ID — no foreign key to identity context. +-- column membership_role_assignments.scope_kind: organization or project — determines the scope of the role. +-- column membership_role_assignments.scope_ref: Optional project reference for project-scoped roles. NULL for organization-scoped. diff --git a/packages/db/src/migrations/030_events_audit_core/up.sql b/packages/db/src/migrations/030_events_audit_core/up.sql new file mode 100644 index 0000000..743d3bd --- /dev/null +++ b/packages/db/src/migrations/030_events_audit_core/up.sql @@ -0,0 +1,113 @@ +-- Events/audit persistence foundation. +-- Context: events +-- Idempotent: uses IF NOT EXISTS throughout. +-- schema events: Events bounded context — owns canonical event log and audit projections. + +-- Canonical event log: one immutable row per event envelope. +CREATE TABLE IF NOT EXISTS events_event_log ( + id TEXT PRIMARY KEY, + type TEXT NOT NULL, + version INTEGER NOT NULL DEFAULT 1, + source TEXT NOT NULL, + occurred_at TEXT NOT NULL, + + -- Actor + actor_type TEXT NOT NULL, + actor_id TEXT NOT NULL, + actor_session_id TEXT, + actor_ip TEXT, + + -- Tenant scope + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + + -- Subject + subject_kind TEXT NOT NULL, + subject_id TEXT NOT NULL, + subject_name TEXT, + + -- Trace + request_id TEXT NOT NULL, + correlation_id TEXT, + causation_id TEXT, + idempotency_key TEXT, + + -- Payload + payload TEXT NOT NULL DEFAULT '{}', + + -- Audit redaction metadata + redact_paths TEXT NOT NULL DEFAULT '[]', + + -- Metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +-- Organization + time index for scoped event queries. +CREATE INDEX IF NOT EXISTS event_log_org_occurred_idx + ON events_event_log (org_id, occurred_at DESC, id DESC); + +-- Idempotency key index for deduplication. +CREATE INDEX IF NOT EXISTS event_log_idempotency_key_idx + ON events_event_log (idempotency_key) WHERE idempotency_key IS NOT NULL; + +-- table events_event_log: Canonical immutable event log — one row per event envelope. + +-- Audit entry projection table: optimized for org-scoped and target-scoped queries. +CREATE TABLE IF NOT EXISTS events_audit_entries ( + id TEXT PRIMARY KEY, + event_id TEXT NOT NULL REFERENCES events_event_log(id), + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + + -- Actor + actor_type TEXT NOT NULL, + actor_id TEXT NOT NULL, + + -- Event reference + event_type TEXT NOT NULL, + event_version INTEGER NOT NULL DEFAULT 1, + source TEXT NOT NULL, + + -- Subject (target of the action) + subject_kind TEXT NOT NULL, + subject_id TEXT NOT NULL, + subject_name TEXT, + + -- Classification + category TEXT NOT NULL DEFAULT 'general', + + -- Human-readable description + description TEXT NOT NULL DEFAULT '', + + -- Timing + occurred_at TEXT NOT NULL, + + -- Trace + request_id TEXT NOT NULL, + correlation_id TEXT, + + -- Payload snapshot + payload TEXT NOT NULL DEFAULT '{}', + + -- Redaction paths + redact_paths TEXT NOT NULL DEFAULT '[]', + + -- Metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +-- Organization + time index for paged audit views. +CREATE INDEX IF NOT EXISTS audit_entries_org_occurred_idx + ON events_audit_entries (org_id, occurred_at DESC, id DESC); + +-- Target lookup index (subject kind + id within an org). +CREATE INDEX IF NOT EXISTS audit_entries_target_idx + ON events_audit_entries (org_id, subject_kind, subject_id, occurred_at DESC, id DESC); + +-- Category filter index. +CREATE INDEX IF NOT EXISTS audit_entries_category_idx + ON events_audit_entries (org_id, category, occurred_at DESC, id DESC); + +-- table events_audit_entries: Audit entry projection — immutable records optimized for org and target queries. diff --git a/packages/db/src/migrations/040_projects_core/up.sql b/packages/db/src/migrations/040_projects_core/up.sql new file mode 100644 index 0000000..16f5d85 --- /dev/null +++ b/packages/db/src/migrations/040_projects_core/up.sql @@ -0,0 +1,61 @@ +-- 040_projects_core +-- Projects persistence foundation — projects and environments tables +-- Bounded context: projects +-- schema projects: Projects bounded context — owns project and environment persistence. + +-- Projects table: one project belongs to exactly one organization. +CREATE TABLE IF NOT EXISTS projects_projects ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + name TEXT NOT NULL, + slug TEXT NOT NULL, + slug_lower TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'archived')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + archived_at TEXT +); + +-- table projects_projects: Projects within an organization. Every query must scope by org_id. +-- column projects_projects.org_id: Owning organization — opaque reference, no cross-context FK. +-- column projects_projects.slug_lower: Lowercased slug for case-insensitive uniqueness within org. + +-- Unique slug per organization (case-insensitive via slug_lower) +CREATE UNIQUE INDEX IF NOT EXISTS projects_org_slug_lower_idx + ON projects_projects (org_id, slug_lower); + +-- Composite unique for FK target from environments +CREATE UNIQUE INDEX IF NOT EXISTS projects_org_id_id_idx + ON projects_projects (org_id, id); + +-- List projects by org, newest first with id tie-breaker +CREATE INDEX IF NOT EXISTS projects_org_created_idx + ON projects_projects (org_id, created_at DESC, id DESC); + +-- Environments table: one environment belongs to exactly one project and organization. +CREATE TABLE IF NOT EXISTS projects_environments ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + project_id TEXT NOT NULL, + name TEXT NOT NULL, + slug TEXT NOT NULL, + slug_lower TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'archived')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + archived_at TEXT, + FOREIGN KEY (org_id, project_id) REFERENCES projects_projects (org_id, id) +); + +-- table projects_environments: Environments within a project. Every query must scope by org_id + project_id. +-- column projects_environments.org_id: Owning organization — denormalized for tenant isolation. +-- column projects_environments.project_id: Owning project — same bounded context FK. +-- column projects_environments.slug_lower: Lowercased slug for case-insensitive uniqueness within org+project. + +-- Unique slug per org + project (case-insensitive via slug_lower) +CREATE UNIQUE INDEX IF NOT EXISTS environments_org_project_slug_lower_idx + ON projects_environments (org_id, project_id, slug_lower); + +-- List environments by org + project, newest first with id tie-breaker +CREATE INDEX IF NOT EXISTS environments_org_project_created_idx + ON projects_environments (org_id, project_id, created_at DESC, id DESC); diff --git a/packages/db/src/migrations/050_identity_security_events/up.sql b/packages/db/src/migrations/050_identity_security_events/up.sql new file mode 100644 index 0000000..f2619f3 --- /dev/null +++ b/packages/db/src/migrations/050_identity_security_events/up.sql @@ -0,0 +1,45 @@ +-- Identity-owned security-event source facts. +-- Context: identity +-- Idempotent: uses IF NOT EXISTS throughout. +-- Pre-organization: user_id is nullable; no org_id required. + +CREATE TABLE IF NOT EXISTS identity_security_events ( + id TEXT PRIMARY KEY, + event_type TEXT NOT NULL, + outcome TEXT NOT NULL, + + -- Actor / subject references (opaque, no cross-context FKs) + user_id TEXT, + session_id TEXT, + challenge_id TEXT, + + -- Trace + request_id TEXT, + correlation_id TEXT, + + -- Client context + ip TEXT, + user_agent TEXT, + + -- Timing + occurred_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + -- Flexible payload and compliance redaction + metadata TEXT NOT NULL DEFAULT '{}', + redact_paths TEXT NOT NULL DEFAULT '[]' +); + +-- User + time index for cursor-paginated security history queries. +CREATE INDEX IF NOT EXISTS security_events_user_occurred_idx + ON identity_security_events (user_id, occurred_at DESC, id DESC); + +-- Event type + time index for type-filtered queries. +CREATE INDEX IF NOT EXISTS security_events_event_type_idx + ON identity_security_events (event_type, occurred_at DESC); + +-- Request ID index for trace correlation lookups. +CREATE INDEX IF NOT EXISTS security_events_request_id_idx + ON identity_security_events (request_id) WHERE request_id IS NOT NULL; + +-- table identity_security_events: Identity-owned security-event source facts — pre-organization user activity log. diff --git a/packages/db/src/migrations/060_identity_api_keys/up.sql b/packages/db/src/migrations/060_identity_api_keys/up.sql new file mode 100644 index 0000000..d381641 --- /dev/null +++ b/packages/db/src/migrations/060_identity_api_keys/up.sql @@ -0,0 +1,81 @@ +-- Identity-owned service principals and API keys. +-- Context: identity +-- Idempotent: uses IF NOT EXISTS throughout. +-- No raw API-key secrets stored — only SHA-256 hash and public prefix. +-- Organization-bound; optional project scope carries explicit org_id + project_id. +-- No cross-context foreign keys to other bounded-context tables. + +-- Service principals: org-bound automation actors. +CREATE TABLE IF NOT EXISTS identity_service_principals ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + project_id TEXT, + display_name TEXT NOT NULL, + description TEXT, + status TEXT NOT NULL DEFAULT 'active', + created_by TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT service_principals_status_check CHECK (status IN ('active', 'suspended', 'deleted')), + CONSTRAINT service_principals_project_scope_check CHECK ( + project_id IS NULL OR org_id IS NOT NULL + ) +); + +-- Org lookup: list service principals for an organization. +CREATE INDEX IF NOT EXISTS service_principals_org_id_idx + ON identity_service_principals (org_id, created_at DESC); + +-- Project-scoped lookup. +CREATE INDEX IF NOT EXISTS service_principals_org_project_idx + ON identity_service_principals (org_id, project_id) + WHERE project_id IS NOT NULL; + +-- table identity_service_principals: Organization-bound service principals — automation actors owned by identity context. +-- column identity_service_principals.org_id: Owning organization. Opaque reference — no cross-context FK. +-- column identity_service_principals.project_id: Optional project scope under the organization. Opaque reference — no cross-context FK. +-- column identity_service_principals.created_by: User who created this service principal. Opaque reference — no FK enforced at schema level. + +-- API keys: belong to a service principal, org-scoped, secret-safe. +CREATE TABLE IF NOT EXISTS identity_api_keys ( + id TEXT PRIMARY KEY, + service_principal_id TEXT NOT NULL REFERENCES identity_service_principals(id), + org_id TEXT NOT NULL, + key_prefix TEXT NOT NULL, + key_hash TEXT NOT NULL, + label TEXT NOT NULL DEFAULT '', + status TEXT NOT NULL DEFAULT 'active', + expires_at TEXT, + last_used_at TEXT, + revoked_at TEXT, + revoked_by TEXT, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT api_keys_status_check CHECK (status IN ('active', 'revoked', 'expired')), + CONSTRAINT api_keys_prefix_length CHECK (length(key_prefix) >= 4 AND length(key_prefix) <= 12) +); + +-- Unique hash index for auth-time lookup. +CREATE UNIQUE INDEX IF NOT EXISTS api_keys_key_hash_idx + ON identity_api_keys (key_hash); + +-- Org-scoped listing. +CREATE INDEX IF NOT EXISTS api_keys_org_id_idx + ON identity_api_keys (org_id, created_at DESC); + +-- Service principal listing. +CREATE INDEX IF NOT EXISTS api_keys_service_principal_idx + ON identity_api_keys (service_principal_id, created_at DESC); + +-- Prefix lookup for key identification (e.g., display in admin UI). +CREATE INDEX IF NOT EXISTS api_keys_prefix_idx + ON identity_api_keys (key_prefix); + +-- table identity_api_keys: API keys owned by identity context. Only hash and prefix stored — raw key material never persisted. +-- column identity_api_keys.key_prefix: Public prefix of the API key (e.g., spk_abc1) for display and identification. 4-12 chars. +-- column identity_api_keys.key_hash: SHA-256 hash of the full API key. Raw key never stored. +-- column identity_api_keys.org_id: Owning organization. Denormalized from service principal for efficient org-scoped queries. Opaque — no cross-context FK. +-- column identity_api_keys.revoked_by: User who revoked this key. Opaque reference. diff --git a/packages/db/src/migrations/070_config_settings_flags/up.sql b/packages/db/src/migrations/070_config_settings_flags/up.sql new file mode 100644 index 0000000..906bc5c --- /dev/null +++ b/packages/db/src/migrations/070_config_settings_flags/up.sql @@ -0,0 +1,187 @@ +-- 070_config_settings_flags +-- Config persistence foundation — settings, feature flags, and secret metadata +-- Bounded context: config +-- Idempotent: uses IF NOT EXISTS throughout. +-- No plaintext secret values stored — only key metadata and ciphertext envelope placeholders. +-- Scoped at organization, project, and environment levels with explicit scope columns. +-- No cross-context foreign keys to membership or projects schemas. +-- schema config: Config bounded context — owns settings, feature flags, and secret metadata persistence. + +-- ============================================================ +-- Settings: scoped non-secret JSON configuration values. +-- scope_kind determines which scope columns are populated. +-- ============================================================ + +CREATE TABLE IF NOT EXISTS config_settings ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + scope_kind TEXT NOT NULL, + key TEXT NOT NULL, + value TEXT NOT NULL DEFAULT '{}', + description TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT settings_scope_kind_check CHECK (scope_kind IN ('organization', 'project', 'environment')), + + -- Organization scope: only org_id set + CONSTRAINT settings_org_scope_check CHECK ( + scope_kind <> 'organization' OR (project_id IS NULL AND environment_id IS NULL) + ), + -- Project scope: org_id + project_id set, no environment_id + CONSTRAINT settings_project_scope_check CHECK ( + scope_kind <> 'project' OR (project_id IS NOT NULL AND environment_id IS NULL) + ), + -- Environment scope: all three IDs set + CONSTRAINT settings_env_scope_check CHECK ( + scope_kind <> 'environment' OR (project_id IS NOT NULL AND environment_id IS NOT NULL) + ) +); + +-- Unique key per scope tuple +CREATE UNIQUE INDEX IF NOT EXISTS settings_scope_key_idx + ON config_settings (org_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), COALESCE(environment_id, '00000000-0000-0000-0000-000000000000'), key); + +-- Org-scoped listing +CREATE INDEX IF NOT EXISTS settings_org_created_idx + ON config_settings (org_id, created_at DESC, id DESC); + +-- Project-scoped listing +CREATE INDEX IF NOT EXISTS settings_org_project_created_idx + ON config_settings (org_id, project_id, created_at DESC, id DESC) + WHERE project_id IS NOT NULL; + +-- Environment-scoped listing +CREATE INDEX IF NOT EXISTS settings_org_project_env_created_idx + ON config_settings (org_id, project_id, environment_id, created_at DESC, id DESC) + WHERE environment_id IS NOT NULL; + +-- table config_settings: Scoped non-secret settings. Every query must scope by org_id. +-- column config_settings.org_id: Owning organization — opaque reference, no cross-context FK. +-- column config_settings.project_id: Optional project scope — opaque reference, no cross-context FK. +-- column config_settings.environment_id: Optional environment scope — opaque reference, no cross-context FK. +-- column config_settings.scope_kind: Discriminator: organization, project, or environment. +-- column config_settings.key: Setting key within the scope. +-- column config_settings.value: Non-secret TEXT payload. + +-- ============================================================ +-- Feature flags: scoped flag definitions with default state. +-- ============================================================ + +CREATE TABLE IF NOT EXISTS config_feature_flags ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + scope_kind TEXT NOT NULL, + flag_key TEXT NOT NULL, + enabled INTEGER NOT NULL DEFAULT 0, + value TEXT, + description TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT feature_flags_scope_kind_check CHECK (scope_kind IN ('organization', 'project', 'environment')), + + CONSTRAINT feature_flags_org_scope_check CHECK ( + scope_kind <> 'organization' OR (project_id IS NULL AND environment_id IS NULL) + ), + CONSTRAINT feature_flags_project_scope_check CHECK ( + scope_kind <> 'project' OR (project_id IS NOT NULL AND environment_id IS NULL) + ), + CONSTRAINT feature_flags_env_scope_check CHECK ( + scope_kind <> 'environment' OR (project_id IS NOT NULL AND environment_id IS NOT NULL) + ) +); + +-- Unique flag key per scope tuple +CREATE UNIQUE INDEX IF NOT EXISTS feature_flags_scope_key_idx + ON config_feature_flags (org_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), COALESCE(environment_id, '00000000-0000-0000-0000-000000000000'), flag_key); + +-- Org-scoped listing +CREATE INDEX IF NOT EXISTS feature_flags_org_created_idx + ON config_feature_flags (org_id, created_at DESC, id DESC); + +-- Project-scoped listing +CREATE INDEX IF NOT EXISTS feature_flags_org_project_created_idx + ON config_feature_flags (org_id, project_id, created_at DESC, id DESC) + WHERE project_id IS NOT NULL; + +-- Environment-scoped listing +CREATE INDEX IF NOT EXISTS feature_flags_org_project_env_created_idx + ON config_feature_flags (org_id, project_id, environment_id, created_at DESC, id DESC) + WHERE environment_id IS NOT NULL; + +-- table config_feature_flags: Scoped feature flag definitions. Every query must scope by org_id. +-- column config_feature_flags.flag_key: Unique flag key within the scope. +-- column config_feature_flags.enabled: Default enabled/disabled state. +-- column config_feature_flags.value: Optional TEXT payload for flag variants or metadata. + +-- ============================================================ +-- Secret metadata: key metadata, status, version/rotation info. +-- NEVER stores plaintext secret values. +-- An optional ciphertext_envelope column holds encrypted data. +-- ============================================================ + +CREATE TABLE IF NOT EXISTS config_secret_metadata ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + scope_kind TEXT NOT NULL, + secret_key TEXT NOT NULL, + display_name TEXT, + status TEXT NOT NULL DEFAULT 'active', + version INTEGER NOT NULL DEFAULT 1, + ciphertext_envelope BYTEA, + rotation_policy TEXT, + last_rotated_at TEXT, + expires_at TEXT, + created_by TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT secret_metadata_scope_kind_check CHECK (scope_kind IN ('organization', 'project', 'environment')), + CONSTRAINT secret_metadata_status_check CHECK (status IN ('active', 'rotated', 'revoked')), + + CONSTRAINT secret_metadata_org_scope_check CHECK ( + scope_kind <> 'organization' OR (project_id IS NULL AND environment_id IS NULL) + ), + CONSTRAINT secret_metadata_project_scope_check CHECK ( + scope_kind <> 'project' OR (project_id IS NOT NULL AND environment_id IS NULL) + ), + CONSTRAINT secret_metadata_env_scope_check CHECK ( + scope_kind <> 'environment' OR (project_id IS NOT NULL AND environment_id IS NOT NULL) + ), + CONSTRAINT secret_metadata_version_positive CHECK (version >= 1) +); + +-- Unique secret key per scope tuple (only active/rotated — revoked are historical) +CREATE UNIQUE INDEX IF NOT EXISTS secret_metadata_scope_key_idx + ON config_secret_metadata (org_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), COALESCE(environment_id, '00000000-0000-0000-0000-000000000000'), secret_key) + WHERE status IN ('active', 'rotated'); + +-- Org-scoped listing +CREATE INDEX IF NOT EXISTS secret_metadata_org_created_idx + ON config_secret_metadata (org_id, created_at DESC, id DESC); + +-- Project-scoped listing +CREATE INDEX IF NOT EXISTS secret_metadata_org_project_created_idx + ON config_secret_metadata (org_id, project_id, created_at DESC, id DESC) + WHERE project_id IS NOT NULL; + +-- Environment-scoped listing +CREATE INDEX IF NOT EXISTS secret_metadata_org_project_env_created_idx + ON config_secret_metadata (org_id, project_id, environment_id, created_at DESC, id DESC) + WHERE environment_id IS NOT NULL; + +-- table config_secret_metadata: Secret metadata records. NEVER contains plaintext secret values. Ciphertext envelope is encrypted data only. +-- column config_secret_metadata.org_id: Owning organization — opaque reference, no cross-context FK. +-- column config_secret_metadata.project_id: Optional project scope — opaque reference, no cross-context FK. +-- column config_secret_metadata.environment_id: Optional environment scope — opaque reference, no cross-context FK. +-- column config_secret_metadata.secret_key: Identifier for this secret within its scope. +-- column config_secret_metadata.ciphertext_envelope: Encrypted secret payload — NEVER plaintext. Null until an encryption adapter writes it. +-- column config_secret_metadata.version: Monotonically increasing version number for rotation tracking. +-- column config_secret_metadata.created_by: User or service principal who created/rotated this secret — opaque reference. diff --git a/packages/db/src/migrations/080_webhooks_core/up.sql b/packages/db/src/migrations/080_webhooks_core/up.sql new file mode 100644 index 0000000..9bd7a4b --- /dev/null +++ b/packages/db/src/migrations/080_webhooks_core/up.sql @@ -0,0 +1,111 @@ +-- 080_webhooks_core: Webhook persistence foundation +-- Creates the webhooks schema with endpoint, subscription, and delivery-attempt tables. +-- Idempotent: uses IF NOT EXISTS throughout for the D1 runner, which applies each statement on its own. +-- ── Webhook endpoints ────────────────────────────────────── +-- Organization-owned webhook endpoint metadata with optional project scope. +-- Signing secret material is never stored in plaintext; only encrypted envelope +-- and version metadata are persisted. + +CREATE TABLE IF NOT EXISTS webhooks_webhook_endpoints ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT NOT NULL, + project_id TEXT, + url TEXT NOT NULL, + name TEXT, + description TEXT, + status TEXT NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'disabled', 'pending')), + disabled_reason TEXT, + disabled_at TEXT, + + -- Signing secret metadata (no plaintext secret values) + secret_version INT NOT NULL DEFAULT 1, + secret_ciphertext TEXT, -- encrypted envelope, write-only + secret_last_rotated_at TEXT, + + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + -- Project-scoped endpoints must carry org_id + project_id + CONSTRAINT chk_webhook_endpoint_project_scope + CHECK (project_id IS NULL OR org_id IS NOT NULL) +); + +CREATE INDEX IF NOT EXISTS idx_webhook_endpoints_org + ON webhooks_webhook_endpoints (org_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_webhook_endpoints_org_project + ON webhooks_webhook_endpoints (org_id, project_id, created_at DESC, id DESC) + WHERE project_id IS NOT NULL; + +-- ── Webhook subscriptions ────────────────────────────────── +-- Endpoint-bound event subscription configuration. +-- Each subscription binds an endpoint to an event type or pattern. + +CREATE TABLE IF NOT EXISTS webhooks_webhook_subscriptions ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT NOT NULL, + endpoint_id TEXT NOT NULL, + project_id TEXT, + event_type TEXT NOT NULL, -- e.g. 'project.created', 'member.*' + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + -- Project-scoped subscriptions must carry org_id + project_id + CONSTRAINT chk_webhook_sub_project_scope + CHECK (project_id IS NULL OR org_id IS NOT NULL) +); + +CREATE INDEX IF NOT EXISTS idx_webhook_subscriptions_endpoint + ON webhooks_webhook_subscriptions (endpoint_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_webhook_subscriptions_org + ON webhooks_webhook_subscriptions (org_id, created_at DESC, id DESC); + +-- Unique constraint: one subscription per endpoint + event_type + project scope +CREATE UNIQUE INDEX IF NOT EXISTS uq_webhook_sub_endpoint_event + ON webhooks_webhook_subscriptions ( + endpoint_id, + event_type, + COALESCE(project_id, '00000000-0000-0000-0000-000000000000') + ); + +-- ── Webhook delivery attempts ────────────────────────────── +-- Safe delivery bookkeeping. Stores response metadata and safe failure reasons +-- only — no full event payloads or customer response bodies. + +CREATE TABLE IF NOT EXISTS webhooks_webhook_delivery_attempts ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT NOT NULL, + endpoint_id TEXT NOT NULL, + subscription_id TEXT NOT NULL, + event_id TEXT NOT NULL, + event_type TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'success', 'failed', 'retrying')), + attempt_number INT NOT NULL DEFAULT 1, + http_status_code INT, + failure_reason TEXT, -- safe summary, no raw response body + idempotency_key TEXT, -- deduplication key for retry safety + next_retry_at TEXT, + completed_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_org + ON webhooks_webhook_delivery_attempts (org_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_endpoint + ON webhooks_webhook_delivery_attempts (endpoint_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_subscription + ON webhooks_webhook_delivery_attempts (subscription_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_event + ON webhooks_webhook_delivery_attempts (event_id); + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_idempotency + ON webhooks_webhook_delivery_attempts (idempotency_key) + WHERE idempotency_key IS NOT NULL; diff --git a/packages/db/src/migrations/090_webhooks_delivery/up.sql b/packages/db/src/migrations/090_webhooks_delivery/up.sql new file mode 100644 index 0000000..d0fbc26 --- /dev/null +++ b/packages/db/src/migrations/090_webhooks_delivery/up.sql @@ -0,0 +1,47 @@ +-- 090_webhooks_delivery: Webhook delivery runtime prerequisites +-- Adds the delivery idempotency constraint and dispatch cursor tracking. +-- Idempotent: uses IF NOT EXISTS throughout, so the D1 runner (which applies +-- each statement on its own) can re-run this file safely. + +-- ── Delivery attempt event_id type ─────────────────────────── +-- events_event_log.id is TEXT (a canonical event id, not a UUID), so +-- webhook_delivery_attempts.event_id is declared TEXT in migration 080. The +-- Postgres lineage of this baseline carried a type-fixing ALTER here; SQLite's +-- type affinity makes the column accept the canonical ids either way, and D1 +-- has no ALTER COLUMN, so the fix lives at the point of creation instead. + +-- ── Idempotency unique constraint ──────────────────────────── +-- Prevents duplicate delivery attempts for the same subscription + event + attempt number. +-- ON CONFLICT (subscription_id, event_id, attempt_number) enables safe retry/replay. + +CREATE UNIQUE INDEX IF NOT EXISTS uq_webhook_delivery_sub_event_attempt + ON webhooks_webhook_delivery_attempts (subscription_id, event_id, attempt_number); + +-- ── Webhook dispatch cursor ────────────────────────────────── +-- Tracks the webhook subscriber lane's progress through the canonical event log. +-- Each org has its own cursor position. Progress advances only after delivery +-- work is durably recorded. + +CREATE TABLE IF NOT EXISTS webhooks_webhook_dispatch_cursor ( + org_id TEXT NOT NULL, + subscriber_lane TEXT NOT NULL DEFAULT 'webhooks', + last_event_id TEXT, -- last event_id successfully processed + last_occurred_at TEXT, -- last event occurred_at for cursor ordering + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (org_id, subscriber_lane) +); + +-- ── Retryable delivery index ───────────────────────────────── +-- Supports efficient polling for delivery attempts needing retry. + +CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retryable + ON webhooks_webhook_delivery_attempts (next_retry_at ASC, status) + WHERE status = 'retrying' AND next_retry_at IS NOT NULL; + +-- ── Subscription matching index ────────────────────────────── +-- Supports efficient fanout: find all enabled subscriptions for an org + event type. + +CREATE INDEX IF NOT EXISTS idx_webhook_subscriptions_fanout + ON webhooks_webhook_subscriptions (org_id, event_type) + WHERE enabled = 1; diff --git a/packages/db/src/migrations/100_metering_foundation/up.sql b/packages/db/src/migrations/100_metering_foundation/up.sql new file mode 100644 index 0000000..60e2858 --- /dev/null +++ b/packages/db/src/migrations/100_metering_foundation/up.sql @@ -0,0 +1,195 @@ +-- 100_metering_foundation: Metering persistence foundation +-- Creates the metering bounded-context schema with durable storage for raw usage +-- records, usage rollups, quota definitions, and quota violation history. +-- Idempotent: uses IF NOT EXISTS / DO NOTHING throughout for the D1 runner, which applies each statement on its own. + +-- ── Schema ───────────────────────────────────────────────── +-- schema metering: Metering bounded context — usage ingestion, rollups, quota state, and violation history. Owns usage facts and policy inputs. Billing consumes metering outputs, not the reverse. + +-- ── Raw usage records ────────────────────────────────────── +-- Each row is an immutable usage fact recorded by the metering worker or ingestion API. +-- Idempotency is enforced per org via (org_id, idempotency_key). +-- org_id references membership_organizations(id) by opaque ID — no FK. +-- project_id, environment_id, and resource_id are optional scoping dimensions. + +CREATE TABLE IF NOT EXISTS metering_usage_records ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + project_id TEXT, -- opaque ref to projects_projects(id) + environment_id TEXT, -- opaque ref to projects_environments(id) + resource_id TEXT, -- opaque resource identifier (e.g. worker ID, page ID) + metric TEXT NOT NULL, -- usage metric key (e.g. 'api_requests', 'build_minutes') + quantity BIGINT NOT NULL DEFAULT 1, + idempotency_key TEXT NOT NULL, -- caller-provided dedup key, unique per org + recorded_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + metadata TEXT, -- bounded safe metadata (no secrets, tokens, credentials) + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + -- Scope invariant: project/environment/resource never usable without org + CONSTRAINT chk_usage_org_scope CHECK ( + (project_id IS NULL OR org_id IS NOT NULL) AND + (environment_id IS NULL OR project_id IS NOT NULL) AND + (resource_id IS NULL OR org_id IS NOT NULL) + ) +); + +-- table metering_usage_records: Immutable raw usage facts. Each record is an atomic usage event with exactly-once insert semantics enforced by (org_id, idempotency_key) uniqueness. + +-- column metering_usage_records.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, connection strings, webhook signing secrets, or plaintext secret material. + +-- Idempotency: unique per org + idempotency key +CREATE UNIQUE INDEX IF NOT EXISTS uq_usage_org_idempotency + ON metering_usage_records (org_id, idempotency_key); + +-- Query by org + metric + time range +CREATE INDEX IF NOT EXISTS idx_usage_org_metric_time + ON metering_usage_records (org_id, metric, recorded_at DESC); + +-- Query by org + project +CREATE INDEX IF NOT EXISTS idx_usage_org_project + ON metering_usage_records (org_id, project_id) + WHERE project_id IS NOT NULL; + +-- ── Usage rollups ────────────────────────────────────────── +-- Pre-aggregated usage summaries by org/project/environment, metric, and time bucket. +-- Rollups are created by a metering worker (future task) from raw usage records. + +CREATE TABLE IF NOT EXISTS metering_usage_rollups ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + metric TEXT NOT NULL, + bucket_type TEXT NOT NULL, -- 'hour' or 'day' + bucket_start TEXT NOT NULL, -- start of the time bucket + quantity BIGINT NOT NULL DEFAULT 0, + record_count BIGINT NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_rollup_bucket_type CHECK (bucket_type IN ('hour', 'day')), + + CONSTRAINT chk_rollup_org_scope CHECK ( + (project_id IS NULL OR org_id IS NOT NULL) AND + (environment_id IS NULL OR project_id IS NOT NULL) + ) +); + +-- table metering_usage_rollups: Pre-aggregated usage summaries by time bucket. Produced by the metering worker from raw usage records. Queryable by org, optional project/environment, metric, and time range. + +-- Upsert-safe: one rollup per org/project/env/metric/bucket +CREATE UNIQUE INDEX IF NOT EXISTS uq_rollup_dimensions + ON metering_usage_rollups ( + org_id, + COALESCE(project_id, ''), + COALESCE(environment_id, ''), + metric, + bucket_type, + bucket_start + ); + +-- Query rollups by org + metric + time range +CREATE INDEX IF NOT EXISTS idx_rollup_org_metric_bucket + ON metering_usage_rollups (org_id, metric, bucket_type, bucket_start DESC); + +-- ── Quota definitions ────────────────────────────────────── +-- Policy-facing quota limits. Each quota binds a metric to a numeric limit +-- for a given org (and optionally project/environment/resource). +-- Billing/plan integration will set these in a later task; metering only reads them. + +CREATE TABLE IF NOT EXISTS metering_quota_definitions ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + resource_id TEXT, + metric TEXT NOT NULL, + limit_value BIGINT NOT NULL, -- maximum allowed quantity per period + period TEXT NOT NULL, -- 'hour', 'day', 'month', 'billing_cycle' + enforcement TEXT NOT NULL DEFAULT 'soft', -- 'soft' (warn) or 'hard' (block) + status TEXT NOT NULL DEFAULT 'active', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_quota_period CHECK (period IN ('hour', 'day', 'month', 'billing_cycle')), + CONSTRAINT chk_quota_enforcement CHECK (enforcement IN ('soft', 'hard')), + CONSTRAINT chk_quota_status CHECK (status IN ('active', 'inactive')), + + CONSTRAINT chk_quota_org_scope CHECK ( + (project_id IS NULL OR org_id IS NOT NULL) AND + (environment_id IS NULL OR project_id IS NOT NULL) AND + (resource_id IS NULL OR org_id IS NOT NULL) + ) +); + +-- table metering_quota_definitions: Policy-facing quota limits binding metrics to numeric thresholds per period. Metering reads these for checkQuota; billing/plan integration sets them in a later task. + +-- One active quota per org/project/env/resource/metric/period +CREATE UNIQUE INDEX IF NOT EXISTS uq_quota_dimensions + ON metering_quota_definitions ( + org_id, + COALESCE(project_id, ''), + COALESCE(environment_id, ''), + COALESCE(resource_id, ''), + metric, + period + ) + WHERE status = 'active'; + +-- Query quotas by org + metric +CREATE INDEX IF NOT EXISTS idx_quota_org_metric + ON metering_quota_definitions (org_id, metric) + WHERE status = 'active'; + +-- ── Quota violations ─────────────────────────────────────── +-- Historical log of quota threshold crossings. Each violation records the +-- moment a usage metric exceeded a quota definition's limit. + +CREATE TABLE IF NOT EXISTS metering_quota_violations ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + project_id TEXT, + environment_id TEXT, + resource_id TEXT, + quota_id TEXT NOT NULL, -- opaque ref to quota_definitions(id) + metric TEXT NOT NULL, + limit_value BIGINT NOT NULL, -- the limit at time of violation + actual_value BIGINT NOT NULL, -- the usage value that exceeded the limit + period TEXT NOT NULL, + enforcement TEXT NOT NULL, -- enforcement mode at time of violation + violated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + resolved_at TEXT, -- null until violation is cleared + metadata TEXT, -- safe context (no secrets) + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_violation_period CHECK (period IN ('hour', 'day', 'month', 'billing_cycle')), + CONSTRAINT chk_violation_enforcement CHECK (enforcement IN ('soft', 'hard')), + + CONSTRAINT chk_violation_org_scope CHECK ( + (project_id IS NULL OR org_id IS NOT NULL) AND + (environment_id IS NULL OR project_id IS NOT NULL) AND + (resource_id IS NULL OR org_id IS NOT NULL) + ) +); + +-- table metering_quota_violations: Historical record of quota threshold crossings. Each violation captures the limit, actual usage, and enforcement mode at the time of breach. + +-- column metering_quota_violations.metadata: Safe violation context only — must never contain bearer tokens, API keys, provider credentials, connection strings, webhook signing secrets, or plaintext secret material. + +-- List violations by org (required) + optional dimensions +CREATE INDEX IF NOT EXISTS idx_violation_org_time + ON metering_quota_violations (org_id, violated_at DESC); + +CREATE INDEX IF NOT EXISTS idx_violation_org_metric + ON metering_quota_violations (org_id, metric, violated_at DESC); + +CREATE INDEX IF NOT EXISTS idx_violation_quota + ON metering_quota_violations (quota_id, violated_at DESC); diff --git a/packages/db/src/migrations/110_billing_foundation/up.sql b/packages/db/src/migrations/110_billing_foundation/up.sql new file mode 100644 index 0000000..6c0590e --- /dev/null +++ b/packages/db/src/migrations/110_billing_foundation/up.sql @@ -0,0 +1,226 @@ +-- 110_billing_foundation: Billing persistence foundation +-- Creates the billing bounded-context schema with provider-neutral storage for +-- plans, billing customers, subscriptions, invoices, and entitlements. +-- +-- Design rules: +-- * Organization is the V1 billing customer boundary; per-project billing is +-- a future extension. Every org-scoped table carries org_id directly. +-- * Provider-specific fields (provider, provider_*_id, hosted_url) are opaque +-- references only; they are never the source of truth for product +-- entitlement decisions. +-- * No secret/credential material: no API keys, webhook signing secrets, +-- bearer tokens, plaintext payment data, raw provider payloads, or +-- checkout session secrets. metadata columns are bounded safe metadata only. +-- * Billing consumes normalized metering outputs (rollups). It does not own +-- raw usage facts and does not mutate metering-owned tables. +-- * Idempotent: CREATE SCHEMA/TABLE/INDEX IF NOT EXISTS throughout for the +-- D1 runner. No destructive rewrites of applied state. + +-- ── Schema ───────────────────────────────────────────────── +-- schema billing: Billing bounded context — provider-neutral plans, billing customers, subscriptions, invoices, and entitlements. Owns plan/subscription/entitlement state. Consumes normalized metering rollups; never owns raw usage facts. + +-- ── Plans ────────────────────────────────────────────────── +-- Catalog of available plan definitions. Plans are global (not org-scoped) — +-- they are the menu organizations subscribe to. Nominal display price fields +-- are present for catalog UI; live provider pricing remains opaque per-plan. + +CREATE TABLE IF NOT EXISTS billing_plans ( + id TEXT NOT NULL, + code TEXT NOT NULL, -- stable machine identifier (e.g. 'starter', 'pro') + name TEXT NOT NULL, -- human-facing display name + description TEXT, + status TEXT NOT NULL DEFAULT 'active', -- 'active' | 'archived' + billing_interval TEXT NOT NULL DEFAULT 'month', -- 'month' | 'year' | 'none' + price_amount_cents BIGINT, -- nominal display price; provider is source of truth + price_currency TEXT NOT NULL DEFAULT 'usd', -- ISO-4217 lowercase + metadata TEXT, -- bounded safe metadata (no secrets, tokens, credentials) + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_plan_status CHECK (status IN ('active', 'archived')), + CONSTRAINT chk_plan_interval CHECK (billing_interval IN ('month', 'year', 'none')), + CONSTRAINT chk_plan_price CHECK (price_amount_cents IS NULL OR price_amount_cents >= 0) +); + +-- table billing_plans: Provider-neutral plan catalog. Plans are global; organizations subscribe to plans via billing_subscriptions. Plans drive entitlement defaults; payment provider mappings live in provider-side state, not here. + +-- column billing_plans.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, connection strings, webhook signing secrets, or plaintext secret material. + +CREATE UNIQUE INDEX IF NOT EXISTS uq_plan_code ON billing_plans (code); +CREATE INDEX IF NOT EXISTS idx_plan_status ON billing_plans (status); + +-- ── Billing customers ────────────────────────────────────── +-- One billing customer per organization for V1. The provider_customer_id is an +-- opaque reference to an external payment-provider customer record; provider +-- credentials and API keys are stored elsewhere (Secrets Store), never here. + +CREATE TABLE IF NOT EXISTS billing_billing_customers ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + display_name TEXT, + email TEXT, + status TEXT NOT NULL DEFAULT 'active', -- 'active' | 'inactive' + provider TEXT, -- e.g. 'stripe' (opaque adapter id) + provider_customer_id TEXT, -- opaque external customer ref + metadata TEXT, -- bounded safe metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_billing_customer_status CHECK (status IN ('active', 'inactive')) +); + +-- table billing_billing_customers: One billing customer per organization (V1). provider_customer_id is an opaque reference to the payment-provider record; provider credentials/secrets are stored in Secrets Store and never persisted here. + +-- column billing_billing_customers.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, raw provider payloads, or plaintext secret material. + +-- V1 invariant: one billing customer per org +CREATE UNIQUE INDEX IF NOT EXISTS uq_billing_customer_org + ON billing_billing_customers (org_id); + +-- Provider lookup (sparse) +CREATE INDEX IF NOT EXISTS idx_billing_customer_provider + ON billing_billing_customers (provider, provider_customer_id) + WHERE provider IS NOT NULL; + +-- ── Subscriptions ────────────────────────────────────────── +-- Subscriptions link an organization billing customer to a plan with lifecycle +-- state. Provider-side ids are opaque; status drives entitlement gating. + +CREATE TABLE IF NOT EXISTS billing_subscriptions ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + billing_customer_id TEXT NOT NULL, -- opaque ref to billing_billing_customers(id) + plan_id TEXT NOT NULL, -- opaque ref to billing_plans(id) + status TEXT NOT NULL DEFAULT 'active', + current_period_start TEXT, + current_period_end TEXT, + trial_end TEXT, + cancel_at TEXT, + canceled_at TEXT, + provider TEXT, + provider_subscription_id TEXT, + metadata TEXT, -- bounded safe metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_subscription_status CHECK ( + status IN ('trialing', 'active', 'past_due', 'canceled', 'expired') + ) +); + +-- table billing_subscriptions: Organization-scoped subscription state. Status drives entitlement gating; provider ids are opaque references for adapter mapping only. + +-- column billing_subscriptions.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, raw webhook payloads, or plaintext secret material. + +CREATE INDEX IF NOT EXISTS idx_subscription_org_status + ON billing_subscriptions (org_id, status); + +CREATE INDEX IF NOT EXISTS idx_subscription_customer + ON billing_subscriptions (billing_customer_id); + +CREATE INDEX IF NOT EXISTS idx_subscription_plan + ON billing_subscriptions (plan_id); + +CREATE INDEX IF NOT EXISTS idx_subscription_provider + ON billing_subscriptions (provider, provider_subscription_id) + WHERE provider IS NOT NULL; + +-- ── Invoices ─────────────────────────────────────────────── +-- Mirror of provider-issued invoices. Sufficient for future provider webhooks +-- to reflect provider invoice state into starter-owned state. We never store +-- raw provider payloads, full card data, or signing secrets. + +CREATE TABLE IF NOT EXISTS billing_invoices ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + billing_customer_id TEXT NOT NULL, + subscription_id TEXT, -- opaque ref; nullable for one-off invoices + number TEXT, -- provider-issued invoice number (safe display) + status TEXT NOT NULL DEFAULT 'draft', + amount_due_cents BIGINT NOT NULL DEFAULT 0, + amount_paid_cents BIGINT NOT NULL DEFAULT 0, + currency TEXT NOT NULL DEFAULT 'usd', + issued_at TEXT, + due_at TEXT, + paid_at TEXT, + period_start TEXT, + period_end TEXT, + provider TEXT, + provider_invoice_id TEXT, + hosted_url TEXT, -- safe display URL only; no embedded secret token query strings + metadata TEXT, -- bounded safe metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_invoice_status CHECK ( + status IN ('draft', 'open', 'paid', 'void', 'uncollectible') + ), + CONSTRAINT chk_invoice_amounts CHECK ( + amount_due_cents >= 0 AND amount_paid_cents >= 0 + ) +); + +-- table billing_invoices: Provider invoice mirror. Stores enough state to display invoice history and reconcile webhooks. Raw provider payloads, full card numbers, CVCs, signing secrets, and bearer tokens MUST NOT be persisted here. + +-- column billing_invoices.hosted_url: Safe display URL only. Callers must reject URLs that embed bearer tokens, session secrets, or other credential material in query strings or fragments. + +-- column billing_invoices.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, raw provider payloads, full payment instrument data, or plaintext secret material. + +CREATE INDEX IF NOT EXISTS idx_invoice_org_issued + ON billing_invoices (org_id, issued_at DESC); + +CREATE INDEX IF NOT EXISTS idx_invoice_customer + ON billing_invoices (billing_customer_id, issued_at DESC); + +CREATE INDEX IF NOT EXISTS idx_invoice_subscription + ON billing_invoices (subscription_id) + WHERE subscription_id IS NOT NULL; + +CREATE UNIQUE INDEX IF NOT EXISTS uq_invoice_provider + ON billing_invoices (provider, provider_invoice_id) + WHERE provider IS NOT NULL AND provider_invoice_id IS NOT NULL; + +-- ── Entitlements ─────────────────────────────────────────── +-- Organization-scoped, queryable feature/limit grants. Derived from plan +-- defaults at subscription creation/change time; explicit per-org overrides +-- are allowed. Future policy/product surfaces query by (org_id, key). + +CREATE TABLE IF NOT EXISTS billing_entitlements ( + id TEXT NOT NULL, + org_id TEXT NOT NULL, + subscription_id TEXT, -- opaque ref; nullable for plan-independent grants + entitlement_key TEXT NOT NULL, -- stable machine key (e.g. 'feature.custom_domains', 'limit.projects') + value_type TEXT NOT NULL, -- 'boolean' | 'quantity' | 'feature' + enabled INTEGER NOT NULL DEFAULT 1, + limit_value BIGINT, -- optional numeric limit; NULL = unlimited (when enabled) + source TEXT NOT NULL DEFAULT 'plan', -- 'plan' | 'override' + metadata TEXT, -- bounded safe metadata + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + PRIMARY KEY (id), + + CONSTRAINT chk_entitlement_value_type CHECK (value_type IN ('boolean', 'quantity', 'feature')), + CONSTRAINT chk_entitlement_source CHECK (source IN ('plan', 'override')), + CONSTRAINT chk_entitlement_limit CHECK (limit_value IS NULL OR limit_value >= 0) +); + +-- table billing_entitlements: Organization-scoped entitlement grants. Queryable by (org_id, entitlement_key) for policy and product surfaces. Plan-derived entries use source=plan; manual per-org grants use source=override. + +-- column billing_entitlements.metadata: Bounded safe metadata only — must never contain bearer tokens, API keys, provider credentials, or plaintext secret material. + +-- Unique per (org_id, entitlement_key): callers replace via upsert +CREATE UNIQUE INDEX IF NOT EXISTS uq_entitlement_org_key + ON billing_entitlements (org_id, entitlement_key); + +CREATE INDEX IF NOT EXISTS idx_entitlement_subscription + ON billing_entitlements (subscription_id) + WHERE subscription_id IS NOT NULL; diff --git a/packages/db/src/migrations/120_notifications_core/up.sql b/packages/db/src/migrations/120_notifications_core/up.sql new file mode 100644 index 0000000..7cb6d4e --- /dev/null +++ b/packages/db/src/migrations/120_notifications_core/up.sql @@ -0,0 +1,173 @@ +-- 120_notifications_core: Notifications persistence foundation. +-- Context: notifications +-- Spec: specs/components/14-notifications.md +-- +-- Creates the notifications bounded-context schema with four tables that +-- collectively own: +-- * per-subject, per-channel preferences (user or organization scope), +-- * the canonical record of every enqueued notification, +-- * delivery attempts and their bounded outcomes, +-- * suppression state (bounce / complaint / manual / unsubscribe). +-- +-- Design rules: +-- * Every notifications-owned row is tenant-scoped on org_id. There are +-- NO foreign keys back into other bounded contexts beyond the org/user +-- subject_id pattern already established elsewhere — subject_id is an +-- opaque identifier, not a FK to identity_users. +-- * Recipient addresses are stored lower-cased so suppression lookup is +-- case-insensitive (mirrors membership_organization_invitations). +-- * No secret material: no API tokens, no magic-link codes, no raw +-- provider payloads. template_data is bounded substitution scaffold +-- only and MUST NOT contain credentials. +-- * provider_message_id is an opaque, provider-issued reference for +-- operator traceability; it is never a credential. +-- * Idempotent: CREATE SCHEMA/TABLE/INDEX IF NOT EXISTS throughout for +-- the D1 runner. No destructive rewrites. + +-- ── Schema ───────────────────────────────────────────────── +-- schema notifications: Notifications bounded context — owns user/org preferences, delivery records, delivery attempts, and recipient suppression. Provider-specific state never leaks beyond the local NotificationProvider adapter. + +-- ── Preferences ──────────────────────────────────────────── +-- Subject can be a user or an organization. categories is a bounded +-- TEXT map of category -> boolean (true = opted-in, false = opted-out). +-- Absent keys mean "not configured" and call sites should treat that as +-- the default (opt-in for transactional categories). + +CREATE TABLE IF NOT EXISTS notifications_notification_preferences ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + subject_kind TEXT NOT NULL, + subject_id TEXT NOT NULL, + channel TEXT NOT NULL, + categories TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT notification_prefs_subject_kind_check + CHECK (subject_kind IN ('user', 'organization')), + CONSTRAINT notification_prefs_channel_check + CHECK (channel IN ('email')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS notification_prefs_subject_channel_idx + ON notifications_notification_preferences (org_id, subject_kind, subject_id, channel); + +CREATE INDEX IF NOT EXISTS notification_prefs_org_idx + ON notifications_notification_preferences (org_id); + +-- table notifications_notification_preferences: Per-subject, per-channel notification preferences. subject_id is an opaque identifier (no FK into identity / membership). Org-scoped via org_id. + +-- column notifications_notification_preferences.categories: Bounded TEXT map { category: boolean }. Categories: invitation, billing, security, support, product. MUST NOT contain credential material. + +-- ── Notifications ────────────────────────────────────────── +-- One row per enqueued notification. status reflects the latest lifecycle +-- state across delivery attempts. recipient_address is stored lower-cased +-- so suppression matches are case-insensitive. + +CREATE TABLE IF NOT EXISTS notifications_notifications ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + category TEXT NOT NULL, + template_key TEXT NOT NULL, + template_data TEXT NOT NULL DEFAULT '{}', + channel TEXT NOT NULL, + recipient_address TEXT NOT NULL, + recipient_subject_kind TEXT, + recipient_subject_id TEXT, + status TEXT NOT NULL DEFAULT 'queued', + provider_message_id TEXT, + last_error TEXT, + idempotency_key TEXT, + correlation_id TEXT, + queued_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + sent_at TEXT, + failed_at TEXT, + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT notifications_status_check + CHECK (status IN ('queued', 'sent', 'failed', 'suppressed')), + CONSTRAINT notifications_channel_check + CHECK (channel IN ('email')), + CONSTRAINT notifications_category_check + CHECK (category IN ('invitation', 'billing', 'security', 'support', 'product')), + CONSTRAINT notifications_recipient_subject_kind_check + CHECK (recipient_subject_kind IS NULL OR recipient_subject_kind IN ('user', 'organization')) +); + +CREATE INDEX IF NOT EXISTS notifications_org_idx + ON notifications_notifications (org_id); + +CREATE INDEX IF NOT EXISTS notifications_org_status_idx + ON notifications_notifications (org_id, status); + +CREATE INDEX IF NOT EXISTS notifications_org_recipient_idx + ON notifications_notifications (org_id, channel, recipient_address); + +CREATE UNIQUE INDEX IF NOT EXISTS notifications_idempotency_idx + ON notifications_notifications (org_id, idempotency_key) + WHERE idempotency_key IS NOT NULL; + +-- table notifications_notifications: Canonical notification records. One row per enqueue. Tenant-scoped on org_id. template_data carries redaction-safe substitutions only; no secrets. + +-- column notifications_notifications.provider_message_id: Opaque provider-issued reference for operator traceability. Never a credential. + +-- column notifications_notifications.template_data: Bounded substitution scaffold (string/number/boolean/null values). MUST NOT contain bearer tokens, API keys, magic-link codes, or other secret material. + +-- column notifications_notifications.last_error: Bounded human-readable failure reason. Provider payloads MUST be scrubbed. + +-- ── Notification attempts ────────────────────────────────── +-- Per-attempt audit trail for a notification. V1 ships with a synchronous +-- single-attempt local-debug provider; retries are a follow-up. + +CREATE TABLE IF NOT EXISTS notifications_notification_attempts ( + id TEXT PRIMARY KEY, + notification_id TEXT NOT NULL, + org_id TEXT NOT NULL, + attempt_number INTEGER NOT NULL, + status TEXT NOT NULL, + provider_message_id TEXT, + error_reason TEXT, + attempted_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT notification_attempts_status_check + CHECK (status IN ('queued', 'sent', 'failed', 'suppressed')), + CONSTRAINT notification_attempts_number_check + CHECK (attempt_number >= 1) +); + +CREATE INDEX IF NOT EXISTS notification_attempts_notification_idx + ON notifications_notification_attempts (notification_id, attempt_number); + +CREATE INDEX IF NOT EXISTS notification_attempts_org_idx + ON notifications_notification_attempts (org_id); + +CREATE UNIQUE INDEX IF NOT EXISTS notification_attempts_unique_idx + ON notifications_notification_attempts (notification_id, attempt_number); + +-- table notifications_notification_attempts: Per-attempt audit trail. attempt_number is 1-indexed. Bounded error_reason; never raw provider payloads. + +-- ── Suppressions ─────────────────────────────────────────── +-- Per-org, per-channel recipient suppression list. Used to short-circuit +-- enqueue when a recipient has bounced, complained, or unsubscribed. + +CREATE TABLE IF NOT EXISTS notifications_notification_suppressions ( + id TEXT PRIMARY KEY, + org_id TEXT NOT NULL, + channel TEXT NOT NULL, + address TEXT NOT NULL, + reason TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT notification_suppressions_channel_check + CHECK (channel IN ('email')), + CONSTRAINT notification_suppressions_reason_check + CHECK (reason IN ('bounce', 'complaint', 'manual', 'unsubscribe')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS notification_suppressions_unique_idx + ON notifications_notification_suppressions (org_id, channel, address); + +CREATE INDEX IF NOT EXISTS notification_suppressions_org_idx + ON notifications_notification_suppressions (org_id); + +-- table notifications_notification_suppressions: Per-org recipient suppression list. address is stored lower-cased. diff --git a/packages/db/src/migrations/130_webhook_secret_rotation_grace/up.sql b/packages/db/src/migrations/130_webhook_secret_rotation_grace/up.sql new file mode 100644 index 0000000..a6d658b --- /dev/null +++ b/packages/db/src/migrations/130_webhook_secret_rotation_grace/up.sql @@ -0,0 +1,31 @@ +-- 130_webhook_secret_rotation_grace: dual-secret window for webhook signing-key rotation. +-- +-- Context: webhooks +-- Spec: ai/tasks/task-0108.md (B5 webhook secret rotation grace) +-- +-- Adds three nullable columns to webhooks_webhook_endpoints so that a rotated +-- endpoint can keep the previous signing secret around for a configurable +-- grace window. During that window the worker delivery loop attaches BOTH +-- the new signature (X-Webhook-Signature) and the previous-key signature +-- (X-Webhook-Signature-Previous), so receivers can roll forward without a +-- delivery gap. +-- +-- Design rules: +-- * No backfill — existing rows keep previous_* NULL until the next rotate. +-- * No new secret material persistence shape: the previous ciphertext re- +-- uses the same envelope format as secret_ciphertext (write-only, never +-- returned through any read surface). +-- * Forward-only. SQLite (and therefore D1) has no `ADD COLUMN IF NOT +-- EXISTS` and takes one column per ALTER, so re-run safety comes from the +-- runner's applied-ledger rather than from the statement. +-- * No destructive change to existing columns or constraints. + +ALTER TABLE webhooks_webhook_endpoints ADD COLUMN previous_secret_ciphertext TEXT; +ALTER TABLE webhooks_webhook_endpoints ADD COLUMN previous_secret_version INTEGER; +ALTER TABLE webhooks_webhook_endpoints ADD COLUMN previous_secret_expires_at TEXT; + +-- column webhooks_webhook_endpoints.previous_secret_ciphertext: Encrypted envelope of the previous signing secret. Populated on rotate, never returned through any read surface. Cleared after previous_secret_expires_at lapses. + +-- column webhooks_webhook_endpoints.previous_secret_version: Monotonic counter snapshot of secret_version at the moment of the most recent rotate (i.e. the version of the previous secret). NULL on endpoints that have never been rotated. + +-- column webhooks_webhook_endpoints.previous_secret_expires_at: Wall-clock timestamp at which the previous-key dual-signature window closes. Worker delivery emits X-Webhook-Signature-Previous only while strftime('%Y-%m-%dT%H:%M:%fZ','now') < this value. diff --git a/packages/db/src/migrations/140_support_action_records/up.sql b/packages/db/src/migrations/140_support_action_records/up.sql new file mode 100644 index 0000000..e16ae61 --- /dev/null +++ b/packages/db/src/migrations/140_support_action_records/up.sql @@ -0,0 +1,75 @@ +-- 140_support_action_records: internal support/administration action ledger. +-- +-- Context: support +-- Spec: specs/components/16-admin-support.md (B8 admin-support worker, V1) +-- Task: ai/tasks/task-0123.md +-- +-- Establishes the `support` bounded context owned by apps/admin-worker. V1 owns +-- a single append-only table: a record of every audited support action (a +-- read-only diagnostic lookup, or any future mutating support action) taken by +-- an internal support actor against a target organization. +-- +-- Design rules: +-- * Forward-only and idempotent: CREATE SCHEMA / TABLE / INDEX all guarded +-- with IF NOT EXISTS, safe when the runner re-applies the file +-- re-running the migration. +-- * No backfill, no destructive change to existing schemas. +-- * Tenant-scoped: every row carries a target org_id. Support actors are +-- opaque subject references (no FK into identity), mirroring how the +-- events/membership contexts treat actor/subject IDs. +-- * No secret material: this table never stores tokens, secrets, or +-- connection strings. `reason` is operator-supplied free text; `metadata` +-- is a narrow JSON bag for non-sensitive diagnostic context. +-- * Impersonation is intentionally OUT of V1 scope (spec-16 Agent Freedom): +-- no session/impersonation columns are introduced here. The clean seam is +-- a future migration that adds its own table. +-- schema support: Support/administration bounded context — owns audited internal support-action records. Reads tenant data only through narrow diagnostic projections, never as a privileged shortcut around policy/audit. + +-- Append-only ledger of audited support actions. +CREATE TABLE IF NOT EXISTS support_support_action_records ( + id TEXT PRIMARY KEY, + + -- Support actor (opaque subject reference from the support authorization context). + actor_id TEXT NOT NULL, + actor_type TEXT NOT NULL DEFAULT 'user', + + -- Target tenant the support action was taken against. + target_org_id TEXT NOT NULL, + + -- What kind of support action this row records (e.g. 'organization.lookup', + -- 'user.lookup'). Free-form to allow the support vocabulary to grow without a + -- migration; the worker constrains the values it writes. + action TEXT NOT NULL, + + -- Operator-supplied justification. Required by spec-16 support rules. + reason TEXT NOT NULL, + + -- Trace correlation back to the originating request. + request_id TEXT NOT NULL, + + -- Narrow, non-sensitive diagnostic context. Never holds secrets/tokens. + metadata TEXT NOT NULL DEFAULT '{}', + + -- When the support action occurred (worker-supplied) and when persisted. + occurred_at TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT support_action_records_actor_type_check + CHECK (actor_type IN ('user', 'service_principal', 'system')), + CONSTRAINT support_action_records_reason_not_blank + CHECK (length(trim(reason)) > 0) +); + +-- Primary read path: most-recent support actions against a target org. +CREATE INDEX IF NOT EXISTS support_action_records_target_org_idx + ON support_support_action_records (target_org_id, occurred_at DESC, id DESC); + +-- Secondary read path: audit a particular support actor's history. +CREATE INDEX IF NOT EXISTS support_action_records_actor_idx + ON support_support_action_records (actor_id, occurred_at DESC, id DESC); + +-- table support_support_action_records: Append-only audited support-action ledger. One row per support action (actor, target org, reason, request ID, timestamp). Mirrored into events/audit via the events-audit seam at write time. +-- column support_support_action_records.actor_id: Opaque support-actor subject ID. No FK into identity — the support context references actors by opaque ID like events/membership. +-- column support_support_action_records.target_org_id: The organization this support action targeted. Tenant scope for every support row. +-- column support_support_action_records.reason: Operator-supplied justification for the support action. Required, non-blank. +-- column support_support_action_records.metadata: Narrow non-sensitive diagnostic context. Never stores secrets, tokens, or connection strings. diff --git a/packages/db/src/migrations/150_entitlement_decision_observations/up.sql b/packages/db/src/migrations/150_entitlement_decision_observations/up.sql new file mode 100644 index 0000000..c483e93 --- /dev/null +++ b/packages/db/src/migrations/150_entitlement_decision_observations/up.sql @@ -0,0 +1,91 @@ +-- 150_entitlement_decision_observations: entitlement-decision observability. +-- +-- Context: billing +-- Spec: specs/roadmap.md (B9 — Entitlement-decision observability), +-- specs/components/11-billing.md, specs/components/09-events-audit-observability.md +-- Task: ai/tasks/task-0124.md +-- +-- Adds a counts-only observation table to the existing `billing` bounded context +-- (owned by apps/billing-worker). Every entitlement decision produced by +-- `decideEntitlement` on the internal check-entitlement path emits one row here: +-- a structured, secret-free observation of WHO hit the gate, for WHICH +-- entitlement key, with WHAT outcome. The admin-support worker reads a narrow +-- aggregation of this table so an on-call operator can see gate traffic. +-- +-- Storage-shape decision (append-only observations, aggregated at read time): +-- * Chosen over a pre-aggregated rollup counter. The emission path is +-- best-effort and non-blocking — a plain INSERT has no read-modify-write +-- contention, so a recording failure (or a slow DB) can never feed back into +-- the entitlement decision latency/outcome. A rollup counter would require an +-- UPSERT with row-level contention on a hot (org, key, outcome) tuple. +-- * Counts by (org_id, entitlement_key, outcome) over a bounded time window are +-- a cheap GROUP BY backed by the composite index below. At entitlement-check +-- volumes this read is bounded by the window, not the full table. +-- * Append-only mirrors the peer `support_support_action_records` ledger +-- (migration 140) and the events/audit append discipline. +-- +-- Design rules: +-- * Forward-only and idempotent: CREATE TABLE / INDEX guarded with IF NOT +-- EXISTS, safe when the runner re-applies the file. +-- * No backfill, no destructive change to existing billing schema/tables. +-- * COUNTS ONLY, SECRET-FREE: a row carries org_id + entitlement_key + outcome +-- (+ denial reason when denied) + occurred_at. It NEVER stores limit values, +-- subscription IDs, plan/source details, provider payloads, tokens, or +-- connection strings. This is enforced by CHECK constraints on the small, +-- closed outcome/reason vocabularies and by the absence of any value column. +-- * Tenant-scoped: every row carries an org_id (opaque TEXT, no FK — mirrors how +-- billing/events reference tenant IDs). + +-- Append-only, counts-only ledger of entitlement decisions. +CREATE TABLE IF NOT EXISTS billing_entitlement_decision_observations ( + id TEXT PRIMARY KEY, + + -- Target tenant the decision was made for. + org_id TEXT NOT NULL, + + -- Stable machine identifier of the entitlement that was checked + -- (e.g. 'feature.custom_domains', 'limit.projects'). Matches the worker's + -- ENTITLEMENT_KEY constraint; never free-form provider text. + entitlement_key TEXT NOT NULL, + + -- The decision outcome. Closed vocabulary. + outcome TEXT NOT NULL, + + -- Denial reason, present ONLY when outcome = 'denied'. Closed vocabulary + -- mirroring the frozen CheckBillingEntitlementResponse reason contract. + -- NULL on allowed decisions. + denial_reason TEXT, + + -- When the decision occurred (worker-supplied) and when persisted. + occurred_at TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + + CONSTRAINT entitlement_decision_observations_outcome_check + CHECK (outcome IN ('allowed', 'denied')), + + -- Denial reason is required iff denied, and forbidden otherwise. This also + -- pins the reason to the frozen contract vocabulary so no arbitrary string + -- (and certainly no secret/payload) can be smuggled into this column. + CONSTRAINT entitlement_decision_observations_denial_reason_check + CHECK ( + (outcome = 'denied' AND denial_reason IN ('not_configured', 'disabled')) + OR + (outcome = 'allowed' AND denial_reason IS NULL) + ), + + CONSTRAINT entitlement_decision_observations_key_not_blank + CHECK (length(trim(entitlement_key)) > 0) +); + +-- Primary read path: aggregate counts by (org, key, outcome) over a bounded +-- time window. Leading org_id + occurred_at lets the window scan stay tenant- +-- scoped and bounded; entitlement_key + outcome support the GROUP BY. +CREATE INDEX IF NOT EXISTS entitlement_decision_observations_org_window_idx + ON billing_entitlement_decision_observations + (org_id, occurred_at DESC, entitlement_key, outcome); + +-- table billing_entitlement_decision_observations: Append-only, counts-only observations of entitlement decisions (one row per decision on the internal check-entitlement path). Carries org_id, entitlement_key, outcome, and denial_reason only — NEVER limit values, subscription IDs, plan/source details, provider payloads, or secrets. Read as a narrow time-windowed aggregation by the admin-support worker. +-- column billing_entitlement_decision_observations.org_id: Target organization the entitlement decision was made for. Tenant scope. +-- column billing_entitlement_decision_observations.entitlement_key: Stable machine identifier of the checked entitlement. Never free-form text. +-- column billing_entitlement_decision_observations.outcome: Decision outcome: allowed | denied. Closed vocabulary. +-- column billing_entitlement_decision_observations.denial_reason: Denial reason (not_configured | disabled), present only when denied. Mirrors the frozen CheckBillingEntitlementResponse reason contract. Never a value/secret. diff --git a/packages/db/src/migrations/160_identity_user_last_org/up.sql b/packages/db/src/migrations/160_identity_user_last_org/up.sql new file mode 100644 index 0000000..0119c4e --- /dev/null +++ b/packages/db/src/migrations/160_identity_user_last_org/up.sql @@ -0,0 +1,14 @@ +-- 160_identity_user_last_org: per-user "last viewed organization" preference. +-- +-- Context: identity +-- Task: console "default to last-used org" — server-backed so the default +-- follows the user across devices/browsers (the client also caches it in +-- localStorage for an instant landing redirect). +-- +-- A soft UI hint, not relational data: it stores the org SLUG the user last +-- worked in (the console routes by slug). Nullable, no foreign key — a stale or +-- inaccessible value is self-healed by the console (it clears the hint when the +-- org no longer resolves). Updated on a best-effort, non-blocking path as the +-- user navigates, so it must never add write contention to anything hot. + +ALTER TABLE identity_users ADD COLUMN last_org_slug TEXT; diff --git a/packages/db/src/migrations/170_membership_org_parent/up.sql b/packages/db/src/migrations/170_membership_org_parent/up.sql new file mode 100644 index 0000000..b7f10de --- /dev/null +++ b/packages/db/src/migrations/170_membership_org_parent/up.sql @@ -0,0 +1,27 @@ +-- 170_membership_org_parent: optional parent-organization pointer. +-- +-- Context: membership +-- Epic: saas-multi-org-billing (MO1) — the dormant seam for the Datadog-style +-- multi-organization model. A parent_org_id lets an organization roll its +-- billing up to a parent organization (the customer's default org). NULL +-- means the organization is standalone and bills for itself — which is +-- every existing organization, so this migration changes no behavior on +-- its own. +-- +-- Design rules (see specs/epics/saas-multi-org-billing/design.md §3): +-- * Additive + idempotent: ADD COLUMN IF NOT EXISTS, no rewrite of applied state. +-- * Nullable self-pointer within membership_organizations only — no +-- cross-context reference and no foreign key, consistent with the schema's +-- opaque-id convention (organization_members.org_id is likewise unconstrained). +-- * The resolution rule (parent_org_id ?? id) lives in code +-- (effectiveBillingOrgId); this migration only persists the pointer. + +ALTER TABLE membership_organizations ADD COLUMN parent_org_id TEXT; + +-- column membership_organizations.parent_org_id: Optional billing parent: when set, this organization rolls its billing up to the referenced (default/parent) organization. NULL = standalone and bills for itself. Self-reference within membership_organizations; not a foreign key, consistent with the schema opaque-id convention. + +-- Sparse index: only child organizations carry a value, so the partial index +-- stays tiny and standalone organizations add no index cost. +CREATE INDEX IF NOT EXISTS organizations_parent_org_id_idx + ON membership_organizations (parent_org_id) + WHERE parent_org_id IS NOT NULL; diff --git a/packages/db/src/migrations/180_integrations_foundation/up.sql b/packages/db/src/migrations/180_integrations_foundation/up.sql new file mode 100644 index 0000000..9858fcb --- /dev/null +++ b/packages/db/src/migrations/180_integrations_foundation/up.sql @@ -0,0 +1,187 @@ +-- 180_integrations_foundation: Integrations persistence foundation (IG0). +-- +-- Context: integrations +-- Epic: saas-integrations (IG0) — the dormant contract-and-schema slice for +-- the pluggable integrations platform (GitHub App first). No live +-- behavior rides on this migration; it lands the bounded context's +-- tables so IG1+ (connect flow, inbound events, repo links, token +-- broker) are schema-complete from day one. +-- +-- Design rules (see specs/epics/saas-integrations/design.md §3): +-- * Every tenant-owned table carries org_id TEXT NOT NULL; the one +-- exception is inbound_deliveries, whose org_id stays NULL until the +-- cron drain attributes the delivery (installation → connection → org). +-- * Keyset pagination indexes (org_id, created_at DESC, id DESC). +-- * Platform credentials (App private key, webhook secret, client +-- id/secret) are NOT rows — they are per-environment worker secrets. +-- * Cached installation tokens are AES-256-GCM envelopes, write-only; +-- never logged, never returned by list/read APIs. +-- * Idempotent: IF NOT EXISTS throughout for re-apply safety. +-- ── Connections ──────────────────────────────────────────── +-- Provider-agnostic org ↔ provider connection (a GitHub App installation +-- bound to an organization). The signed-state nonce for the in-flight +-- connect flow is persisted (hashed) on the pending row and cleared on +-- activation — the tenancy keystone (design §4) is carried by our state, +-- never inferred from the provider redirect. + +CREATE TABLE IF NOT EXISTS integrations_connections ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT NOT NULL, + provider TEXT NOT NULL, -- registry-driven: 'github' first + status TEXT NOT NULL DEFAULT 'pending' + CHECK (status IN ('pending', 'active', 'suspended', 'revoked')), + display_name TEXT, + external_account_login TEXT, + external_account_id TEXT, + external_account_type TEXT, -- GitHub: 'Organization' | 'User' + created_by TEXT, -- actor public id + + -- Connect-flow state (write-only; hash of the single-use signed nonce) + state_nonce_hash TEXT, + state_expires_at TEXT, + + connected_at TEXT, + suspended_at TEXT, + revoked_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE INDEX IF NOT EXISTS idx_integrations_connections_org + ON integrations_connections (org_id, created_at DESC, id DESC); + +-- One ACTIVE connection per (org, provider, provider account) +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_connection_active_account + ON integrations_connections (org_id, provider, external_account_id) + WHERE status = 'active' AND external_account_id IS NOT NULL; + +-- Connect-flow nonce lookup (sparse: only pending rows carry a nonce) +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_connection_state_nonce + ON integrations_connections (state_nonce_hash) + WHERE state_nonce_hash IS NOT NULL; + +-- ── GitHub installations ─────────────────────────────────── +-- Provider-specific facts behind a connection. connection_id is NULL for +-- orphaned installations (unsolicited installs with no valid state) — they +-- are recorded, admin-visible, and never auto-bound to a tenant (fail +-- closed, design §4). + +CREATE TABLE IF NOT EXISTS integrations_github_installations ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + connection_id TEXT, -- NULL = orphaned installation + installation_id BIGINT NOT NULL, -- GitHub installation id + account_login TEXT, + account_id BIGINT, + account_type TEXT, -- 'Organization' | 'User' + repository_selection TEXT, -- 'all' | 'selected' + permissions TEXT, -- App grant snapshot + events TEXT, -- subscribed webhook events + suspended_at TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_github_installation + ON integrations_github_installations (installation_id); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_github_installation_connection + ON integrations_github_installations (connection_id) + WHERE connection_id IS NOT NULL; + +-- ── Repo links ───────────────────────────────────────────── +-- repo ↔ project with branch → environment mapping. A plain org/project- +-- scoped record now; forward-compatible with re-projection as a manifested +-- resource when P2 lands (the moat consumes the link; it does not own it). + +CREATE TABLE IF NOT EXISTS integrations_repo_links ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT NOT NULL, + project_id TEXT NOT NULL, + connection_id TEXT NOT NULL, + repo_external_id TEXT NOT NULL, -- provider repo id (GitHub numeric id) + repo_full_name TEXT NOT NULL, -- e.g. 'acme/storefront' + default_branch TEXT, + branch_env_map TEXT NOT NULL DEFAULT '{}', -- {"main":"prod","staging":"stage"} + status TEXT NOT NULL DEFAULT 'active' + CHECK (status IN ('active', 'unlinked')), + created_by TEXT, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE INDEX IF NOT EXISTS idx_integrations_repo_links_org + ON integrations_repo_links (org_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_integrations_repo_links_project + ON integrations_repo_links (org_id, project_id, created_at DESC, id DESC); + +CREATE INDEX IF NOT EXISTS idx_integrations_repo_links_connection + ON integrations_repo_links (connection_id, created_at DESC, id DESC); + +-- One ACTIVE link per (project, provider repo); historical unlinked rows remain +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_repo_link_project_repo + ON integrations_repo_links (project_id, repo_external_id) + WHERE status = 'active'; + +-- Event-enrichment lookup: which active links match an inbound repo id +CREATE INDEX IF NOT EXISTS idx_integrations_repo_links_repo + ON integrations_repo_links (repo_external_id) + WHERE status = 'active'; + +-- ── Inbound deliveries ───────────────────────────────────── +-- The durable inbox: both the idempotency ledger (delivery_key UNIQUE per +-- provider — GitHub's X-GitHub-Delivery) and the cron work queue. org_id is +-- NULL until the drain attributes the delivery; emission into event_log is +-- transactional with the 'emitted' mark (exactly-once by construction). + +CREATE TABLE IF NOT EXISTS integrations_inbound_deliveries ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + org_id TEXT, -- NULL until attributed + provider TEXT NOT NULL, + delivery_key TEXT NOT NULL, -- provider delivery id (idempotency key) + event_type TEXT NOT NULL, -- provider event, e.g. 'push' + action TEXT, -- provider action, e.g. 'opened' + payload TEXT NOT NULL, -- raw provider payload (admin-only) + signature_ok INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL DEFAULT 'received' + CHECK (status IN ('received', 'attributed', 'emitted', 'skipped', 'failed')), + attempts INT NOT NULL DEFAULT 0, + next_attempt_at TEXT, + failure_reason TEXT, -- safe summary only + emitted_event_id TEXT, -- event_log id once emitted + received_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_inbound_delivery_key + ON integrations_inbound_deliveries (provider, delivery_key); + +-- Org-scoped delivery log (sparse until attribution) +CREATE INDEX IF NOT EXISTS idx_integrations_inbound_deliveries_org + ON integrations_inbound_deliveries (org_id, received_at DESC, id DESC) + WHERE org_id IS NOT NULL; + +-- Cron drain scan: pending work ordered by arrival +CREATE INDEX IF NOT EXISTS idx_integrations_inbound_deliveries_pending + ON integrations_inbound_deliveries (status, next_attempt_at, received_at) + WHERE status IN ('received', 'attributed'); + +-- ── Installation token cache ─────────────────────────────── +-- Cache for the platform's OWN provider calls (repo listing, connection +-- health). Brokered tenant tokens are always minted fresh and never cached. +-- token_ciphertext is an AES-256-GCM envelope — write-only, never logged, +-- never exposed through list/read APIs. + +CREATE TABLE IF NOT EXISTS integrations_installation_tokens ( + id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6)))), + connection_id TEXT NOT NULL, + token_ciphertext TEXT NOT NULL, + permissions TEXT, + repository_ids TEXT, + expires_at TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); + +CREATE UNIQUE INDEX IF NOT EXISTS uq_integrations_installation_token_connection + ON integrations_installation_tokens (connection_id); diff --git a/packages/db/src/migrations/190_integrations_delivery_attribution/up.sql b/packages/db/src/migrations/190_integrations_delivery_attribution/up.sql new file mode 100644 index 0000000..9190d5e --- /dev/null +++ b/packages/db/src/migrations/190_integrations_delivery_attribution/up.sql @@ -0,0 +1,20 @@ +-- 190_integrations_delivery_attribution: connection pointer on the inbox (IG2). +-- +-- Context: integrations +-- Epic: saas-integrations (IG2) — the cron drain attributes each inbound +-- delivery installation → connection → org. The org pointer landed in +-- 180; this adds the connection pointer so the console-facing delivery +-- log (`GET .../integrations/{id}/deliveries`) can scope per connection +-- instead of mixing every provider connection in the organization. +-- +-- Additive + idempotent: ADD COLUMN IF NOT EXISTS; nullable (NULL until the +-- drain attributes the delivery, exactly like org_id); partial index so +-- unattributed rows add no index cost. + +ALTER TABLE integrations_inbound_deliveries ADD COLUMN connection_id TEXT; + +-- column integrations_inbound_deliveries.connection_id: Owning connection once the drain attributes the delivery (installation -> connection -> org); NULL until attributed. Opaque id, no foreign key, consistent with the schema convention. + +CREATE INDEX IF NOT EXISTS idx_integrations_inbound_deliveries_connection + ON integrations_inbound_deliveries (connection_id, received_at DESC, id DESC) + WHERE connection_id IS NOT NULL; diff --git a/packages/db/src/notifications/index.ts b/packages/db/src/notifications/index.ts new file mode 100644 index 0000000..ec2da7c --- /dev/null +++ b/packages/db/src/notifications/index.ts @@ -0,0 +1,16 @@ +export type { + StoredNotification, + StoredNotificationAttempt, + StoredNotificationPreference, + StoredNotificationSuppression, + CreateNotificationInput, + CreateNotificationAttemptInput, + UpsertNotificationPreferenceInput, + CreateNotificationSuppressionInput, + MarkNotificationStatusInput, + NotificationsRepository, + NotificationsResult, + NotificationsRepositoryError, +} from "./types.js"; + +export { createNotificationsRepository } from "./repository.js"; diff --git a/packages/db/src/notifications/repository.ts b/packages/db/src/notifications/repository.ts new file mode 100644 index 0000000..5b1921b --- /dev/null +++ b/packages/db/src/notifications/repository.ts @@ -0,0 +1,362 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + CreateNotificationAttemptInput, + CreateNotificationInput, + CreateNotificationSuppressionInput, + MarkNotificationStatusInput, + NotificationsRepository, + NotificationsResult, + StoredNotification, + StoredNotificationAttempt, + StoredNotificationPreference, + StoredNotificationSuppression, + UpsertNotificationPreferenceInput, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; + +// --------------------------------------------------------------------------- +// JSON helpers +// --------------------------------------------------------------------------- + +function parseJsonColumn(value: unknown): Record { + if (typeof value === "string") return JSON.parse(value) as Record; + if (value && typeof value === "object") return value as Record; + return {}; +} + +function parseCategoriesColumn(value: unknown): Record { + const parsed = parseJsonColumn(value); + const out: Record = {}; + for (const [k, v] of Object.entries(parsed)) { + if (v === null || typeof v === "boolean") out[k] = v; + } + return out; +} + +// --------------------------------------------------------------------------- +// Row mappers +// --------------------------------------------------------------------------- + +function mapNotification(row: Record): StoredNotification { + return { + id: row.id as string, + orgId: row.org_id as string, + category: row.category as string, + templateKey: row.template_key as string, + templateData: parseJsonColumn(row.template_data), + channel: row.channel as string, + recipientAddress: row.recipient_address as string, + recipientSubjectKind: (row.recipient_subject_kind as string) ?? null, + recipientSubjectId: (row.recipient_subject_id as string) ?? null, + status: row.status as string, + providerMessageId: (row.provider_message_id as string) ?? null, + lastError: (row.last_error as string) ?? null, + idempotencyKey: (row.idempotency_key as string) ?? null, + correlationId: (row.correlation_id as string) ?? null, + queuedAt: new Date(row.queued_at as string), + sentAt: row.sent_at ? new Date(row.sent_at as string) : null, + failedAt: row.failed_at ? new Date(row.failed_at as string) : null, + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapAttempt(row: Record): StoredNotificationAttempt { + return { + id: row.id as string, + notificationId: row.notification_id as string, + orgId: row.org_id as string, + attemptNumber: row.attempt_number as number, + status: row.status as string, + providerMessageId: (row.provider_message_id as string) ?? null, + errorReason: (row.error_reason as string) ?? null, + attemptedAt: new Date(row.attempted_at as string), + }; +} + +function mapPreference(row: Record): StoredNotificationPreference { + return { + id: row.id as string, + orgId: row.org_id as string, + subjectKind: row.subject_kind as string, + subjectId: row.subject_id as string, + channel: row.channel as string, + categories: parseCategoriesColumn(row.categories), + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapSuppression(row: Record): StoredNotificationSuppression { + return { + id: row.id as string, + orgId: row.org_id as string, + channel: row.channel as string, + address: row.address as string, + reason: row.reason as string, + createdAt: new Date(row.created_at as string), + }; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + + +function safeError(message: string): NotificationsResult { + return { ok: false, error: { kind: "internal", message } }; +} + +// --------------------------------------------------------------------------- +// Factory +// --------------------------------------------------------------------------- + +export function createNotificationsRepository(executor: SqlExecutor): NotificationsRepository { + return { + async createNotification(input: CreateNotificationInput) { + try { + const result = await executor.execute>( + `INSERT INTO notifications_notifications ( + id, org_id, category, template_key, template_data, + channel, recipient_address, recipient_subject_kind, recipient_subject_id, + status, idempotency_key, correlation_id, queued_at, updated_at + ) VALUES ( + $1, $2, $3, $4, $5, + $6, $7, $8, $9, + $10, $11, $12, $13, $13 + ) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [ + input.id, + input.orgId, + input.category, + input.templateKey, + JSON.stringify(input.templateData), + input.channel, + input.recipientAddress.toLowerCase(), + input.recipientSubjectKind ?? null, + input.recipientSubjectId ?? null, + input.status, + input.idempotencyKey ?? null, + input.correlationId ?? null, + input.queuedAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "conflict", entity: "notification" } }; + } + return { ok: true, value: mapNotification(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "notification" } }; + } + return safeError("Failed to create notification"); + } + }, + + async getNotificationById(id: string) { + try { + const result = await executor.execute>( + `SELECT * FROM notifications_notifications WHERE id = $1`, + [id], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapNotification(result.rows[0]!) }; + } catch { + return safeError("Failed to get notification"); + } + }, + + async findNotificationByIdempotencyKey(orgId: string, idempotencyKey: string) { + try { + const result = await executor.execute>( + `SELECT * FROM notifications_notifications + WHERE org_id = $1 AND idempotency_key = $2 + LIMIT 1`, + [orgId, idempotencyKey], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapNotification(result.rows[0]!) }; + } catch { + return safeError("Failed to look up notification by idempotency key"); + } + }, + + async markNotificationStatus(input: MarkNotificationStatusInput) { + try { + const result = await executor.execute>( + `UPDATE notifications_notifications + SET status = $3, + provider_message_id = COALESCE($4, provider_message_id), + last_error = $5, + sent_at = COALESCE($6, sent_at), + failed_at = COALESCE($7, failed_at), + updated_at = $8 + WHERE id = $1 AND org_id = $2 + RETURNING *`, + [ + input.id, + input.orgId, + input.status, + input.providerMessageId ?? null, + input.lastError ?? null, + input.sentAt ? input.sentAt.toISOString() : null, + input.failedAt ? input.failedAt.toISOString() : null, + input.updatedAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapNotification(result.rows[0]!) }; + } catch { + return safeError("Failed to mark notification status"); + } + }, + + async recordAttempt(input: CreateNotificationAttemptInput) { + try { + const result = await executor.execute>( + `INSERT INTO notifications_notification_attempts ( + id, notification_id, org_id, attempt_number, + status, provider_message_id, error_reason, attempted_at + ) VALUES ( + $1, $2, $3, $4, + $5, $6, $7, $8 + ) + ON CONFLICT (notification_id, attempt_number) DO NOTHING + RETURNING *`, + [ + input.id, + input.notificationId, + input.orgId, + input.attemptNumber, + input.status, + input.providerMessageId ?? null, + input.errorReason ?? null, + input.attemptedAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "conflict", entity: "attempt" } }; + } + return { ok: true, value: mapAttempt(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "attempt" } }; + } + return safeError("Failed to record notification attempt"); + } + }, + + async listAttempts(notificationId: string) { + try { + const result = await executor.execute>( + `SELECT * FROM notifications_notification_attempts + WHERE notification_id = $1 + ORDER BY attempt_number ASC`, + [notificationId], + ); + return { ok: true, value: result.rows.map(mapAttempt) }; + } catch { + return safeError("Failed to list notification attempts"); + } + }, + + async listPreferences(orgId, subjectKind, subjectId, channel) { + try { + let sql = `SELECT * FROM notifications_notification_preferences + WHERE org_id = $1 AND subject_kind = $2 AND subject_id = $3`; + const params: unknown[] = [orgId, subjectKind, subjectId]; + if (channel) { + sql += ` AND channel = $4`; + params.push(channel); + } + sql += ` ORDER BY channel ASC`; + const result = await executor.execute>(sql, params); + return { ok: true, value: result.rows.map(mapPreference) }; + } catch { + return safeError("Failed to list notification preferences"); + } + }, + + async upsertPreference(input: UpsertNotificationPreferenceInput) { + try { + const result = await executor.execute>( + `INSERT INTO notifications_notification_preferences ( + id, org_id, subject_kind, subject_id, channel, categories, created_at, updated_at + ) VALUES ( + $1, $2, $3, $4, $5, $6, $7, $7 + ) + ON CONFLICT (org_id, subject_kind, subject_id, channel) + DO UPDATE SET + categories = EXCLUDED.categories, + updated_at = EXCLUDED.updated_at + RETURNING *`, + [ + input.id, + input.orgId, + input.subjectKind, + input.subjectId, + input.channel, + JSON.stringify(input.categories), + input.updatedAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return safeError("Failed to upsert preference"); + } + return { ok: true, value: mapPreference(result.rows[0]!) }; + } catch { + return safeError("Failed to upsert notification preference"); + } + }, + + async isSuppressed(orgId: string, channel: string, address: string) { + try { + const result = await executor.execute>( + `SELECT 1 FROM notifications_notification_suppressions + WHERE org_id = $1 AND channel = $2 AND address = $3 + LIMIT 1`, + [orgId, channel, address.toLowerCase()], + ); + return { ok: true, value: result.rows.length > 0 }; + } catch { + return safeError("Failed to check suppression"); + } + }, + + async createSuppression(input: CreateNotificationSuppressionInput) { + try { + const result = await executor.execute>( + `INSERT INTO notifications_notification_suppressions ( + id, org_id, channel, address, reason, created_at + ) VALUES ( + $1, $2, $3, $4, $5, $6 + ) + ON CONFLICT (org_id, channel, address) DO UPDATE + SET reason = EXCLUDED.reason + RETURNING *`, + [ + input.id, + input.orgId, + input.channel, + input.address.toLowerCase(), + input.reason, + input.createdAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return safeError("Failed to create suppression"); + } + return { ok: true, value: mapSuppression(result.rows[0]!) }; + } catch { + return safeError("Failed to create suppression"); + } + }, + }; +} diff --git a/packages/db/src/notifications/types.ts b/packages/db/src/notifications/types.ts new file mode 100644 index 0000000..4c114b0 --- /dev/null +++ b/packages/db/src/notifications/types.ts @@ -0,0 +1,179 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; +import type { Uuid } from "../ids/index.js"; + +// --------------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------------- + +export type NotificationsRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "suppressed" } + | { kind: "internal"; message: string }; + +export type NotificationsResult = + | { ok: true; value: T } + | { ok: false; error: NotificationsRepositoryError }; + +// --------------------------------------------------------------------------- +// Domain types (transport-safe; no platform clients leak through) +// --------------------------------------------------------------------------- + +export interface StoredNotification { + id: string; + orgId: string; + category: string; + templateKey: string; + templateData: Record; + channel: string; + recipientAddress: string; + recipientSubjectKind: string | null; + recipientSubjectId: string | null; + status: string; + providerMessageId: string | null; + lastError: string | null; + idempotencyKey: string | null; + correlationId: string | null; + queuedAt: Date; + sentAt: Date | null; + failedAt: Date | null; + updatedAt: Date; +} + +export interface StoredNotificationAttempt { + id: string; + notificationId: string; + orgId: string; + attemptNumber: number; + status: string; + providerMessageId: string | null; + errorReason: string | null; + attemptedAt: Date; +} + +export interface StoredNotificationPreference { + id: string; + orgId: string; + subjectKind: string; + subjectId: string; + channel: string; + categories: Record; + createdAt: Date; + updatedAt: Date; +} + +export interface StoredNotificationSuppression { + id: string; + orgId: string; + channel: string; + address: string; + reason: string; + createdAt: Date; +} + +// --------------------------------------------------------------------------- +// Input shapes +// --------------------------------------------------------------------------- + +export interface CreateNotificationInput { + id: string; + orgId: Uuid; + category: string; + templateKey: string; + templateData: Record; + channel: string; + recipientAddress: string; + recipientSubjectKind?: string | null; + recipientSubjectId?: string | null; + status: string; + idempotencyKey?: string | null; + correlationId?: string | null; + queuedAt: Date; +} + +export interface CreateNotificationAttemptInput { + id: string; + notificationId: string; + orgId: string; + attemptNumber: number; + status: string; + providerMessageId?: string | null; + errorReason?: string | null; + attemptedAt: Date; +} + +export interface MarkNotificationStatusInput { + id: string; + orgId: string; + status: string; + providerMessageId?: string | null; + lastError?: string | null; + sentAt?: Date | null; + failedAt?: Date | null; + updatedAt: Date; +} + +export interface UpsertNotificationPreferenceInput { + id: string; + orgId: Uuid; + subjectKind: string; + subjectId: string; + channel: string; + categories: Record; + updatedAt: Date; +} + +export interface CreateNotificationSuppressionInput { + id: string; + orgId: Uuid; + channel: string; + address: string; + reason: string; + createdAt: Date; +} + +// --------------------------------------------------------------------------- +// Repository +// --------------------------------------------------------------------------- + +export interface NotificationsRepository { + createNotification( + input: CreateNotificationInput, + ): Promise>; + getNotificationById( + id: string, + ): Promise>; + findNotificationByIdempotencyKey( + orgId: Uuid, + idempotencyKey: string, + ): Promise>; + markNotificationStatus( + input: MarkNotificationStatusInput, + ): Promise>; + + recordAttempt( + input: CreateNotificationAttemptInput, + ): Promise>; + listAttempts( + notificationId: string, + ): Promise>; + + listPreferences( + orgId: Uuid, + subjectKind: string, + subjectId: string, + channel: string | null, + ): Promise>; + upsertPreference( + input: UpsertNotificationPreferenceInput, + ): Promise>; + + isSuppressed( + orgId: Uuid, + channel: string, + address: string, + ): Promise>; + createSuppression( + input: CreateNotificationSuppressionInput, + ): Promise>; +} diff --git a/packages/db/src/projects/index.ts b/packages/db/src/projects/index.ts new file mode 100644 index 0000000..c0b39c0 --- /dev/null +++ b/packages/db/src/projects/index.ts @@ -0,0 +1,14 @@ +export type { + Project, + Environment, + CreateProjectInput, + CreateEnvironmentInput, + ProjectsRepository, + ProjectsResult, + ProjectsRepositoryError, + CursorPosition, + PageQueryParams, + PagedResult, +} from "./types.js"; + +export { createProjectsRepository } from "./repository.js"; diff --git a/packages/db/src/projects/repository.ts b/packages/db/src/projects/repository.ts new file mode 100644 index 0000000..01a605f --- /dev/null +++ b/packages/db/src/projects/repository.ts @@ -0,0 +1,312 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + CreateEnvironmentInput, + CreateProjectInput, + CursorPosition, + Environment, + PagedResult, + PageQueryParams, + Project, + ProjectsRepository, + ProjectsResult, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; + +function mapProject(row: Record): Project { + return { + id: row.id as string, + orgId: row.org_id as string, + name: row.name as string, + slug: row.slug as string, + slugLower: row.slug_lower as string, + status: row.status as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + archivedAt: row.archived_at ? new Date(row.archived_at as string) : null, + }; +} + +function mapEnvironment(row: Record): Environment { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: row.project_id as string, + name: row.name as string, + slug: row.slug as string, + slugLower: row.slug_lower as string, + status: row.status as string, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + archivedAt: row.archived_at ? new Date(row.archived_at as string) : null, + }; +} + +function safeError(message: string): ProjectsResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +export function createProjectsRepository(executor: SqlExecutor): ProjectsRepository { + return { + async createProject(input: CreateProjectInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO projects_projects (id, org_id, name, slug, slug_lower, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $6) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.orgId, input.name, input.slug, input.slugLower, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "project" } }; + } + return { ok: true, value: mapProject(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "project" } }; + } + return safeError("Failed to create project"); + } + }, + + async getProjectById(orgId: string, projectId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM projects_projects WHERE org_id = $1 AND id = $2`, + [orgId, projectId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapProject(result.rows[0]!) }; + } catch { + return safeError("Failed to get project"); + } + }, + + async getProjectBySlug(orgId: string, slugLower: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM projects_projects WHERE org_id = $1 AND slug_lower = $2`, + [orgId, slugLower], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapProject(result.rows[0]!) }; + } catch { + return safeError("Failed to get project by slug"); + } + }, + + async listProjectsPaged(orgId: string, params: PageQueryParams): Promise>> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT * FROM projects_projects + WHERE org_id = $1 AND status = 'active' + AND (created_at, id) < ($3, $4) + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT * FROM projects_projects + WHERE org_id = $1 AND status = 'active' + ORDER BY created_at DESC, id DESC + LIMIT $2`; + values = [orgId, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapProject); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list projects"); + } + }, + + async archiveProject(orgId: string, projectId: string, archivedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE projects_projects + SET status = 'archived', archived_at = $3, updated_at = $3 + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING *`, + [orgId, projectId, archivedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapProject(result.rows[0]!) }; + } catch { + return safeError("Failed to archive project"); + } + }, + + async countActiveProjects(orgId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT COUNT(*) AS count FROM projects_projects + WHERE org_id = $1 AND status = 'active'`, + [orgId], + ); + const row = result.rows[0]; + const raw = row ? (row.count as string | number | bigint | null) : 0; + // pg may return bigint as string; coerce to a JS number defensively. + // Realistic project counts per org fit comfortably below Number.MAX_SAFE_INTEGER. + const count = + typeof raw === "number" + ? raw + : typeof raw === "bigint" + ? Number(raw) + : raw == null + ? 0 + : Number(raw); + if (!Number.isFinite(count) || count < 0) { + return safeError("Failed to count active projects"); + } + return { ok: true, value: count }; + } catch { + return safeError("Failed to count active projects"); + } + }, + + async createEnvironment(input: CreateEnvironmentInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO projects_environments (id, org_id, project_id, name, slug, slug_lower, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $7) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [input.id, input.orgId, input.projectId, input.name, input.slug, input.slugLower, input.createdAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "environment" } }; + } + return { ok: true, value: mapEnvironment(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "environment" } }; + } + return safeError("Failed to create environment"); + } + }, + + async countActiveEnvironments(orgId: string, projectId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT COUNT(*) AS count FROM projects_environments + WHERE org_id = $1 AND project_id = $2 AND status = 'active'`, + [orgId, projectId], + ); + const row = result.rows[0]; + const raw = row ? (row.count as string | number | bigint | null) : 0; + // pg may return bigint as string; coerce to a JS number defensively. + // Realistic environment counts per project fit comfortably below + // Number.MAX_SAFE_INTEGER. + const count = + typeof raw === "number" + ? raw + : typeof raw === "bigint" + ? Number(raw) + : raw == null + ? 0 + : Number(raw); + if (!Number.isFinite(count) || count < 0) { + return safeError("Failed to count active environments"); + } + return { ok: true, value: count }; + } catch { + return safeError("Failed to count active environments"); + } + }, + + async getEnvironmentById(orgId: string, projectId: string, environmentId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM projects_environments WHERE org_id = $1 AND project_id = $2 AND id = $3`, + [orgId, projectId, environmentId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEnvironment(result.rows[0]!) }; + } catch { + return safeError("Failed to get environment"); + } + }, + + async getEnvironmentBySlug(orgId: string, projectId: string, slugLower: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM projects_environments WHERE org_id = $1 AND project_id = $2 AND slug_lower = $3`, + [orgId, projectId, slugLower], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEnvironment(result.rows[0]!) }; + } catch { + return safeError("Failed to get environment by slug"); + } + }, + + async listEnvironmentsPaged(orgId: string, projectId: string, params: PageQueryParams): Promise>> { + try { + const fetchLimit = params.limit + 1; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT * FROM projects_environments + WHERE org_id = $1 AND project_id = $2 AND status = 'active' + AND (created_at, id) < ($4, $5) + ORDER BY created_at DESC, id DESC + LIMIT $3`; + values = [orgId, projectId, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT * FROM projects_environments + WHERE org_id = $1 AND project_id = $2 AND status = 'active' + ORDER BY created_at DESC, id DESC + LIMIT $3`; + values = [orgId, projectId, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapEnvironment); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { createdAt: last.createdAt.toISOString(), id: last.id }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError("Failed to list environments"); + } + }, + + async archiveEnvironment(orgId: string, projectId: string, environmentId: string, archivedAt: Date): Promise> { + try { + const result = await executor.execute>( + `UPDATE projects_environments + SET status = 'archived', archived_at = $4, updated_at = $4 + WHERE org_id = $1 AND project_id = $2 AND id = $3 AND status = 'active' + RETURNING *`, + [orgId, projectId, environmentId, archivedAt.toISOString()], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEnvironment(result.rows[0]!) }; + } catch { + return safeError("Failed to archive environment"); + } + }, + }; +} diff --git a/packages/db/src/projects/types.ts b/packages/db/src/projects/types.ts new file mode 100644 index 0000000..7eae6df --- /dev/null +++ b/packages/db/src/projects/types.ts @@ -0,0 +1,98 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; +import type { Uuid } from "../ids/index.js"; + +export type ProjectsRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type ProjectsResult = + | { ok: true; value: T } + | { ok: false; error: ProjectsRepositoryError }; + +export interface Project { + id: string; + orgId: string; + name: string; + slug: string; + slugLower: string; + status: string; + createdAt: Date; + updatedAt: Date; + archivedAt: Date | null; +} + +export interface Environment { + id: string; + orgId: string; + projectId: string; + name: string; + slug: string; + slugLower: string; + status: string; + createdAt: Date; + updatedAt: Date; + archivedAt: Date | null; +} + +export interface CreateProjectInput { + id: string; + orgId: Uuid; + name: string; + slug: string; + slugLower: string; + createdAt: Date; +} + +export interface CreateEnvironmentInput { + id: string; + orgId: Uuid; + projectId: Uuid; + name: string; + slug: string; + slugLower: string; + createdAt: Date; +} + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +export interface ProjectsRepository { + createProject(input: CreateProjectInput): Promise>; + getProjectById(orgId: Uuid, projectId: Uuid): Promise>; + getProjectBySlug(orgId: Uuid, slugLower: string): Promise>; + listProjectsPaged(orgId: Uuid, params: PageQueryParams): Promise>>; + archiveProject(orgId: Uuid, projectId: Uuid, archivedAt: Date): Promise>; + /** + * Count of active (non-archived) projects for an organization. Used by + * domain callers (e.g. projects-worker) to compare against entitlement + * limits without loading a full page of projects. + */ + countActiveProjects(orgId: Uuid): Promise>; + + createEnvironment(input: CreateEnvironmentInput): Promise>; + /** + * Count of active (non-archived) environments under a specific parent + * project. Used by domain callers (e.g. projects-worker) to compare + * against `limit.environments` entitlement quotas before creating a + * new environment row. The count is intentionally scoped to + * `org_id + project_id` because environment APIs are project-scoped. + */ + countActiveEnvironments(orgId: Uuid, projectId: Uuid): Promise>; + getEnvironmentById(orgId: Uuid, projectId: Uuid, environmentId: string): Promise>; + getEnvironmentBySlug(orgId: Uuid, projectId: Uuid, slugLower: string): Promise>; + listEnvironmentsPaged(orgId: Uuid, projectId: Uuid, params: PageQueryParams): Promise>>; + archiveEnvironment(orgId: Uuid, projectId: Uuid, environmentId: string, archivedAt: Date): Promise>; +} diff --git a/packages/db/src/runner/cli.ts b/packages/db/src/runner/cli.ts new file mode 100644 index 0000000..3d32a11 --- /dev/null +++ b/packages/db/src/runner/cli.ts @@ -0,0 +1,117 @@ +#!/usr/bin/env node +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "../manifest.js"; +import { runMigrations } from "./runner.js"; +import { loadD1CredentialsFromEnv } from "./secrets.js"; +import { D1ApiAdapter } from "./d1-api-adapter.js"; +import type { MigrationAdapter, RunMode } from "./types.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../migrations"); + +function usage(): never { + process.stderr.write( + `Usage: db-migrate --env \n` + + `\n` + + `Modes:\n` + + ` plan — report pending migrations without mutating the database\n` + + ` apply — apply pending migrations against the environment's D1 database\n` + + `\n` + + `Options:\n` + + ` --env target environment (required)\n` + + `\n` + + `Environment (apply mode; all wired from orun secrets):\n` + + ` CLOUDFLARE_ACCOUNT_ID Cloudflare account owning the D1 database\n` + + ` CLOUDFLARE_API_TOKEN account token with D1 edit permission\n` + + ` WIRING_CLOUDFLARE_D1 wiring document from the cloudflare-d1 component\n` + + ` (or D1_DATABASE_ID to name the database directly)\n`, + ); + process.exit(1); +} + +interface ParsedArgs { + mode: RunMode; + env: string; +} + +function parseArgs(argv: string[]): ParsedArgs { + const args = argv.slice(2); + + const mode = args[0] as RunMode | undefined; + if (mode !== "plan" && mode !== "apply") { + usage(); + } + + let env: string | undefined; + + for (let i = 1; i < args.length; i++) { + if (args[i] === "--env" && args[i + 1]) { + env = args[++i]; + } + } + + if (!env) { + const envFromEnv = process.env["MIGRATION_ENV"]; + if (envFromEnv) { + env = envFromEnv; + } + } + + if (!env || !["stage", "prod"].includes(env)) { + process.stderr.write("Error: --env must be 'stage' or 'prod'\n"); + process.exit(1); + } + + return { mode, env }; +} + +// The environment is not a parameter here: orun resolves each environment's +// secrets into the job env, so the D1 database this run targets is whichever +// one the lane was given. `--env` names the lane for the log and the output. +async function resolveAdapter(mode: RunMode): Promise { + if (mode === "plan") { + return null; + } + + process.stderr.write(`Loading credentials from the wired environment (orun secrets)\n`); + const credentials = loadD1CredentialsFromEnv(); + + return new D1ApiAdapter(credentials.accountId, credentials.databaseId, credentials.apiToken); +} + +async function main(): Promise { + const { mode, env } = parseArgs(process.argv); + + process.stderr.write(`db-migrate: mode=${mode} env=${env}\n`); + + const adapter = await resolveAdapter(mode); + + const result = await runMigrations(manifest, { + mode, + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + if (result.failed) { + process.stderr.write( + `FAILED: migration ${result.failed.id} — ${result.failed.error}\n`, + ); + process.exit(1); + } + + const output = { + mode, + env, + applied: result.applied, + skipped: result.skipped, + }; + + process.stdout.write(JSON.stringify(output, null, 2) + "\n"); +} + +main().catch((err: unknown) => { + const message = err instanceof Error ? err.message : String(err); + process.stderr.write(`db-migrate: fatal error — ${message}\n`); + process.exit(1); +}); diff --git a/packages/db/src/runner/d1-api-adapter.ts b/packages/db/src/runner/d1-api-adapter.ts new file mode 100644 index 0000000..b28daf3 --- /dev/null +++ b/packages/db/src/runner/d1-api-adapter.ts @@ -0,0 +1,218 @@ +import type { MigrationEntry } from "../types.js"; +import type { AppliedMigration, MigrationAdapter } from "./types.js"; + +const CLOUDFLARE_API = "https://api.cloudflare.com/client/v4"; + +/** How long a lock row may sit before a later runner reclaims it. A migration + * lane that outlives this was killed mid-flight; the ledger makes the retry + * safe. */ +const LOCK_STALE_MS = 15 * 60 * 1000; + +interface D1QueryResponse { + success?: boolean; + errors?: Array<{ code?: number; message?: string }>; + result?: Array<{ results?: Array>; success?: boolean }>; +} + +/** + * Applies migrations to a Cloudflare D1 database over the REST API. + * + * The CI lane has no Workers binding — it is a Node process — so it speaks to + * D1 the way any external tool does: `POST /accounts/{account}/d1/database/ + * {database}/query`, authorized by an account API token scoped to D1 edit. + * + * Statements are sent one at a time on purpose: the failing statement is then + * named exactly in the error, which is the difference between a five-second + * fix and a bisect through a 200-line migration. + */ +export class D1ApiAdapter implements MigrationAdapter { + private readonly accountId: string; + private readonly databaseId: string; + private readonly apiToken: string; + private readonly fetchImpl: typeof fetch; + private lockId: string | null = null; + + constructor( + accountId: string, + databaseId: string, + apiToken: string, + fetchImpl: typeof fetch = fetch, + ) { + this.accountId = accountId; + this.databaseId = databaseId; + this.apiToken = apiToken; + this.fetchImpl = fetchImpl; + } + + private async query( + sql: string, + params: unknown[] = [], + ): Promise>> { + const url = `${CLOUDFLARE_API}/accounts/${this.accountId}/d1/database/${this.databaseId}/query`; + const res = await this.fetchImpl(url, { + method: "POST", + headers: { + authorization: `Bearer ${this.apiToken}`, + "content-type": "application/json", + }, + body: JSON.stringify({ sql, params }), + }); + + let body: D1QueryResponse; + try { + body = (await res.json()) as D1QueryResponse; + } catch { + throw new Error(`D1 API returned ${res.status} with a non-JSON body`); + } + + if (!res.ok || body.success === false) { + const detail = (body.errors ?? []) + .map((e) => `${e.code ?? ""} ${e.message ?? ""}`.trim()) + .filter(Boolean) + .join("; "); + throw new Error(`D1 API error (${res.status}): ${detail || "unknown error"}`); + } + + return body.result?.[0]?.results ?? []; + } + + /** Split a migration file into statements on top-level semicolons, leaving + * semicolons inside string literals and `--` comments alone. */ + static splitStatements(sql: string): string[] { + const out: string[] = []; + let buf = ""; + let inString = false; + let inComment = false; + for (let i = 0; i < sql.length; i += 1) { + const ch = sql[i]!; + const next = sql[i + 1]; + if (inComment) { + buf += ch; + if (ch === "\n") inComment = false; + continue; + } + if (!inString && ch === "-" && next === "-") { + inComment = true; + buf += ch; + continue; + } + if (ch === "'") { + inString = !inString; + buf += ch; + continue; + } + if (ch === ";" && !inString) { + if (buf.trim()) out.push(buf.trim()); + buf = ""; + continue; + } + buf += ch; + } + if (buf.trim()) out.push(buf.trim()); + // Drop chunks that are only comments/whitespace. + return out.filter((s) => + s.split("\n").some((line) => line.trim() && !line.trim().startsWith("--")), + ); + } + + async connect(): Promise { + // The ledger and the lock table are the runner's own bookkeeping, created + // before the first migration so an empty database is not a special case. + await this.query( + `CREATE TABLE IF NOT EXISTS _migrations_applied ( + id TEXT PRIMARY KEY, + context TEXT NOT NULL, + checksum TEXT NOT NULL, + applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + applied_by TEXT NOT NULL DEFAULT 'migration-runner' + )`, + ); + await this.query( + `CREATE TABLE IF NOT EXISTS _migrations_lock ( + id TEXT PRIMARY KEY, + acquired_at TEXT NOT NULL + )`, + ); + } + + async disconnect(): Promise { + // Stateless HTTP — nothing to close. + } + + /** + * D1 has no advisory locks, so the mutex is a row: the winner is whoever + * inserts it. A row older than LOCK_STALE_MS belongs to a runner that died, + * and is reclaimed — the applied-ledger makes that safe, since a reclaiming + * runner re-reads what actually landed rather than assuming. + */ + async acquireAdvisoryLock(lockId: number): Promise { + const id = `migrate-${lockId}`; + const stale = new Date(Date.now() - LOCK_STALE_MS).toISOString(); + await this.query(`DELETE FROM _migrations_lock WHERE id = ? AND acquired_at < ?`, [ + id, + stale, + ]); + try { + await this.query(`INSERT INTO _migrations_lock (id, acquired_at) VALUES (?, ?)`, [ + id, + new Date().toISOString(), + ]); + } catch (err) { + if (/(UNIQUE|PRIMARY KEY) constraint failed/i.test(String(err))) return false; + throw err; + } + this.lockId = id; + return true; + } + + async releaseAdvisoryLock(lockId: number): Promise { + const id = this.lockId ?? `migrate-${lockId}`; + await this.query(`DELETE FROM _migrations_lock WHERE id = ?`, [id]); + this.lockId = null; + } + + async getAppliedMigrations(): Promise { + const rows = await this.query( + `SELECT id, context, checksum, applied_at FROM _migrations_applied ORDER BY id`, + ); + return rows.map((r) => ({ + id: String(r.id), + context: String(r.context), + checksum: String(r.checksum), + applied_at: String(r.applied_at), + })); + } + + // D1 exposes no interactive transaction over the REST API: a migration is + // applied statement by statement and a failure part-way leaves the earlier + // statements in place. That is survivable here — and only here — because + // every migration is written idempotently (IF NOT EXISTS) and the ledger row + // is written last, so a failed migration is simply re-attempted in full on + // the next run. The no-ops keep the MigrationAdapter contract honest rather + // than pretending a rollback happened. + async beginTransaction(): Promise {} + async commitTransaction(): Promise {} + async rollbackTransaction(): Promise {} + + async executeSql(sql: string): Promise { + const statements = D1ApiAdapter.splitStatements(sql); + for (const statement of statements) { + try { + await this.query(statement); + } catch (err) { + const head = statement.split("\n").slice(0, 3).join(" ").slice(0, 200); + throw new Error(`${err instanceof Error ? err.message : String(err)} — at: ${head}`); + } + } + } + + async recordMigration(entry: MigrationEntry): Promise { + await this.query( + `INSERT INTO _migrations_applied (id, context, checksum, applied_at, applied_by) + VALUES (?, ?, ?, ?, 'db-migrate') + ON CONFLICT (id) DO UPDATE SET checksum = excluded.checksum, + applied_at = excluded.applied_at`, + [entry.id, entry.context, entry.checksum, new Date().toISOString()], + ); + } +} diff --git a/packages/db/src/runner/index.ts b/packages/db/src/runner/index.ts new file mode 100644 index 0000000..b6f53c6 --- /dev/null +++ b/packages/db/src/runner/index.ts @@ -0,0 +1,5 @@ +export type { MigrationAdapter, AppliedMigration, RunnerConfig, RunMode, MigrationPlan, MigrationResult } from "./types.js"; +export { runMigrations, buildPlan } from "./runner.js"; +export { D1ApiAdapter } from "./d1-api-adapter.js"; +export { loadD1CredentialsFromEnv } from "./secrets.js"; +export type { D1Credentials } from "./secrets.js"; diff --git a/packages/db/src/runner/runner.ts b/packages/db/src/runner/runner.ts new file mode 100644 index 0000000..9574ca9 --- /dev/null +++ b/packages/db/src/runner/runner.ts @@ -0,0 +1,140 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import type { MigrationEntry, MigrationManifest } from "../types.js"; +import type { + MigrationPlan, + MigrationResult, + RunnerConfig, +} from "./types.js"; + +const ADVISORY_LOCK_ID = 839_201_008; + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +export function buildPlan( + manifest: MigrationManifest, + appliedMap: Map, + migrationsDir: string, +): MigrationPlan { + const alreadyApplied: string[] = []; + const pending: MigrationEntry[] = []; + const checksumMismatches: MigrationPlan["checksumMismatches"] = []; + + for (const entry of manifest.migrations) { + const appliedChecksum = appliedMap.get(entry.id); + + if (appliedChecksum !== undefined) { + alreadyApplied.push(entry.id); + + const fileChecksum = computeChecksum( + resolve(migrationsDir, entry.path), + ); + + if (appliedChecksum !== fileChecksum || appliedChecksum !== entry.checksum) { + checksumMismatches.push({ + id: entry.id, + expected: appliedChecksum, + actual: fileChecksum, + }); + } + } else { + pending.push(entry); + } + } + + return { alreadyApplied, pending, checksumMismatches }; +} + +export async function runMigrations( + manifest: MigrationManifest, + config: RunnerConfig, +): Promise { + const { adapter, mode, migrationsDir } = config; + const result: MigrationResult = { applied: [], skipped: [], failed: null }; + + // Offline plan: verify checksums then report all migrations as pending. + if (mode === "plan" && adapter === null) { + for (const entry of manifest.migrations) { + const filePath = resolve(migrationsDir, entry.path); + const fileChecksum = computeChecksum(filePath); + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + } + result.applied = manifest.migrations.map((m) => m.id); + return result; + } + + if (!adapter) { + throw new Error("adapter is required for apply mode"); + } + + await adapter.connect(); + + try { + const locked = await adapter.acquireAdvisoryLock(ADVISORY_LOCK_ID); + if (!locked) { + throw new Error( + "Could not acquire migration advisory lock — another runner may be active", + ); + } + + try { + const appliedRows = await adapter.getAppliedMigrations(); + const appliedMap = new Map(appliedRows.map((r) => [r.id, r.checksum])); + + const plan = buildPlan(manifest, appliedMap, migrationsDir); + + if (plan.checksumMismatches.length > 0) { + const ids = plan.checksumMismatches.map((m) => m.id).join(", "); + throw new Error( + `Checksum mismatch for already-applied migrations: ${ids}`, + ); + } + + result.skipped = plan.alreadyApplied; + + if (mode === "plan") { + result.applied = plan.pending.map((m) => m.id); + return result; + } + + for (const entry of plan.pending) { + const sqlPath = resolve(migrationsDir, entry.path); + const sql = readFileSync(sqlPath, "utf-8"); + const fileChecksum = computeChecksum(sqlPath); + + if (fileChecksum !== entry.checksum) { + throw new Error( + `Checksum mismatch for ${entry.id}: manifest says ${entry.checksum}, file has ${fileChecksum}`, + ); + } + + await adapter.beginTransaction(); + try { + await adapter.executeSql(sql); + await adapter.recordMigration(entry); + await adapter.commitTransaction(); + result.applied.push(entry.id); + } catch (err: unknown) { + await adapter.rollbackTransaction(); + const message = err instanceof Error ? err.message : String(err); + result.failed = { id: entry.id, error: message }; + return result; + } + } + } finally { + await adapter.releaseAdvisoryLock(ADVISORY_LOCK_ID); + } + } finally { + await adapter.disconnect(); + } + + return result; +} diff --git a/packages/db/src/runner/secrets.ts b/packages/db/src/runner/secrets.ts new file mode 100644 index 0000000..1d7698a --- /dev/null +++ b/packages/db/src/runner/secrets.ts @@ -0,0 +1,58 @@ +// D1 credentials from the ENVIRONMENT. +// +// The `cloudflare-d1` terraform component publishes its outputs to the +// workspace's project/env secret rung (the composition's wire-secrets step), +// and orun resolves the keys this runner declares in its component `secretEnv` +// into the job env. Nothing is read from a file, a cloud secret store, or an +// ambient CI value. +// +// Two shapes are accepted for the database id, because the wiring layer speaks +// documents and an operator running this by hand speaks variables: +// - WIRING_CLOUDFLARE_D1 — the component's JSON wiring document +// - D1_DATABASE_ID — the flat override + +export interface D1Credentials { + accountId: string; + databaseId: string; + apiToken: string; +} + +function requireEnv(name: string): string { + const value = process.env[name]?.trim(); + if (!value) { + throw new Error( + `${name} is not set — declare it in the component's secretEnv ` + + `(wired from the cloudflare-d1 component's outputs)`, + ); + } + return value; +} + +/** Pull the database id out of the wiring document, if one is present. */ +function databaseIdFromWiring(): string | null { + const raw = process.env["WIRING_CLOUDFLARE_D1"]?.trim(); + if (!raw) return null; + let doc: Record; + try { + doc = JSON.parse(raw) as Record; + } catch { + throw new Error("WIRING_CLOUDFLARE_D1 is set but is not valid JSON"); + } + const id = doc["d1_database_id"]; + return typeof id === "string" && id.length > 0 ? id : null; +} + +export function loadD1CredentialsFromEnv(): D1Credentials { + const databaseId = process.env["D1_DATABASE_ID"]?.trim() || databaseIdFromWiring(); + if (!databaseId) { + throw new Error( + "No D1 database id — set D1_DATABASE_ID, or wire WIRING_CLOUDFLARE_D1 " + + "from the cloudflare-d1 component", + ); + } + return { + accountId: requireEnv("CLOUDFLARE_ACCOUNT_ID"), + databaseId, + apiToken: requireEnv("CLOUDFLARE_API_TOKEN"), + }; +} diff --git a/packages/db/src/runner/types.ts b/packages/db/src/runner/types.ts new file mode 100644 index 0000000..849d74a --- /dev/null +++ b/packages/db/src/runner/types.ts @@ -0,0 +1,41 @@ +import type { MigrationEntry } from "../types.js"; + +export interface AppliedMigration { + id: string; + context: string; + checksum: string; + applied_at: string; +} + +export interface MigrationAdapter { + connect(): Promise; + disconnect(): Promise; + acquireAdvisoryLock(lockId: number): Promise; + releaseAdvisoryLock(lockId: number): Promise; + getAppliedMigrations(): Promise; + beginTransaction(): Promise; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + executeSql(sql: string): Promise; + recordMigration(entry: MigrationEntry): Promise; +} + +export type RunMode = "plan" | "apply"; + +export interface RunnerConfig { + mode: RunMode; + migrationsDir: string; + adapter: MigrationAdapter | null; +} + +export interface MigrationPlan { + alreadyApplied: string[]; + pending: MigrationEntry[]; + checksumMismatches: Array<{ id: string; expected: string; actual: string }>; +} + +export interface MigrationResult { + applied: string[]; + skipped: string[]; + failed: { id: string; error: string } | null; +} diff --git a/packages/db/src/support/index.ts b/packages/db/src/support/index.ts new file mode 100644 index 0000000..9cdb111 --- /dev/null +++ b/packages/db/src/support/index.ts @@ -0,0 +1,14 @@ +export type { + StoredSupportActionRecord, + RecordSupportActionInput, + SupportCursorPosition, + SupportPageQueryParams, + SupportPagedResult, + SupportOrganizationProjection, + SupportUserProjection, + SupportRepository, + SupportResult, + SupportRepositoryError, +} from "./types.js"; + +export { createSupportRepository } from "./repository.js"; diff --git a/packages/db/src/support/repository.ts b/packages/db/src/support/repository.ts new file mode 100644 index 0000000..b0eb7dc --- /dev/null +++ b/packages/db/src/support/repository.ts @@ -0,0 +1,213 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + RecordSupportActionInput, + StoredSupportActionRecord, + SupportCursorPosition, + SupportOrganizationProjection, + SupportPagedResult, + SupportPageQueryParams, + SupportRepository, + SupportResult, + SupportUserProjection, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; + +// --------------------------------------------------------------------------- +// JSON helpers +// --------------------------------------------------------------------------- + +function parseJsonColumn(value: unknown): Record { + if (typeof value === "string") return JSON.parse(value) as Record; + if (value && typeof value === "object") return value as Record; + return {}; +} + +// --------------------------------------------------------------------------- +// Row mappers +// --------------------------------------------------------------------------- + +function mapSupportActionRecord(row: Record): StoredSupportActionRecord { + return { + id: row.id as string, + actorId: row.actor_id as string, + actorType: row.actor_type as string, + targetOrgId: row.target_org_id as string, + action: row.action as string, + reason: row.reason as string, + requestId: row.request_id as string, + metadata: parseJsonColumn(row.metadata), + occurredAt: new Date(row.occurred_at as string), + createdAt: new Date(row.created_at as string), + }; +} + +function mapOrganizationProjection(row: Record): SupportOrganizationProjection { + return { + orgId: row.id as string, + name: row.name as string, + slug: row.slug as string, + status: row.status as string, + memberCount: Number(row.member_count ?? 0), + createdAt: new Date(row.created_at as string), + }; +} + +function mapUserProjection(row: Record): SupportUserProjection { + return { + userId: row.id as string, + email: row.email as string, + displayName: (row.display_name as string) ?? null, + status: row.status as string, + createdAt: new Date(row.created_at as string), + }; +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + + +function safeError(message: string): SupportResult { + return { ok: false, error: { kind: "internal", message } }; +} + +function buildCursorCondition( + cursor: SupportCursorPosition | null, + startParam: number, +): { clause: string; params: unknown[] } { + if (!cursor) return { clause: "", params: [] }; + return { + clause: ` AND (occurred_at, id) < ($${startParam}, $${startParam + 1})`, + params: [cursor.occurredAt, cursor.id], + }; +} + +function extractNextCursor( + items: T[], + limit: number, +): { trimmed: T[]; nextCursor: SupportCursorPosition | null } { + if (items.length > limit) { + const trimmed = items.slice(0, limit); + const last = trimmed[trimmed.length - 1]!; + return { trimmed, nextCursor: { occurredAt: last.occurredAt.toISOString(), id: last.id } }; + } + return { trimmed: items, nextCursor: null }; +} + +// --------------------------------------------------------------------------- +// Factory +// --------------------------------------------------------------------------- + +export function createSupportRepository(executor: SqlExecutor): SupportRepository { + return { + async recordSupportAction( + input: RecordSupportActionInput, + ): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO support_support_action_records ( + id, actor_id, actor_type, target_org_id, + action, reason, request_id, metadata, occurred_at + ) VALUES ( + $1, $2, $3, $4, + $5, $6, $7, $8, $9 + ) + ON CONFLICT (id) DO NOTHING + RETURNING *`, + [ + input.id, + input.actorId, + input.actorType, + input.targetOrgId, + input.action, + input.reason, + input.requestId, + JSON.stringify(input.metadata ?? {}), + input.occurredAt.toISOString(), + ], + ); + if (result.rows.length === 0) { + return { ok: false, error: { kind: "conflict", entity: "support_action" } }; + } + return { ok: true, value: mapSupportActionRecord(result.rows[0]!) }; + } catch (err) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "support_action" } }; + } + return safeError("Failed to record support action"); + } + }, + + async listSupportActions( + targetOrgId: string, + params: SupportPageQueryParams, + ): Promise>> { + try { + const { clause, params: cursorParams } = buildCursorCondition(params.cursor, 3); + const result = await executor.execute>( + `SELECT * FROM support_support_action_records + WHERE target_org_id = $1${clause} + ORDER BY occurred_at DESC, id DESC + LIMIT $2`, + [targetOrgId, params.limit + 1, ...cursorParams], + ); + const mapped = result.rows.map(mapSupportActionRecord); + const { trimmed, nextCursor } = extractNextCursor(mapped, params.limit); + return { ok: true, value: { items: trimmed, nextCursor } }; + } catch { + return safeError("Failed to list support actions"); + } + }, + + async lookupOrganizationForSupport( + orgId: string, + ): Promise> { + try { + // Narrow projection only: id/name/slug/status/createdAt + active member + // count. No secrets, no raw domain-table dump, no nested member/role data. + const result = await executor.execute>( + `SELECT + o.id, + o.name, + o.slug, + o.status, + o.created_at, + ( + SELECT count(*) FROM membership_organization_members m + WHERE m.org_id = o.id AND m.status = 'active' + ) AS member_count + FROM membership_organizations o + WHERE o.id = $1`, + [orgId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapOrganizationProjection(result.rows[0]!) }; + } catch { + return safeError("Failed to look up organization for support"); + } + }, + + async lookupUserForSupport( + userId: string, + ): Promise> { + try { + // Narrow projection only: id/email/displayName/status/createdAt. No + // auth identities, sessions, login challenges, or token material. + const result = await executor.execute>( + `SELECT id, email, display_name, status, created_at + FROM identity_users + WHERE id = $1`, + [userId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapUserProjection(result.rows[0]!) }; + } catch { + return safeError("Failed to look up user for support"); + } + }, + }; +} diff --git a/packages/db/src/support/types.ts b/packages/db/src/support/types.ts new file mode 100644 index 0000000..f6e0c29 --- /dev/null +++ b/packages/db/src/support/types.ts @@ -0,0 +1,110 @@ +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +// --------------------------------------------------------------------------- +// Errors +// --------------------------------------------------------------------------- + +export type SupportRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type SupportResult = + | { ok: true; value: T } + | { ok: false; error: SupportRepositoryError }; + +// --------------------------------------------------------------------------- +// Domain types (transport-safe; no platform clients leak through) +// --------------------------------------------------------------------------- + +export interface StoredSupportActionRecord { + id: string; + actorId: string; + actorType: string; + targetOrgId: string; + action: string; + reason: string; + requestId: string; + metadata: Record; + occurredAt: Date; + createdAt: Date; +} + +// --------------------------------------------------------------------------- +// Input shapes +// --------------------------------------------------------------------------- + +export interface RecordSupportActionInput { + id: string; + actorId: string; + actorType: string; + targetOrgId: string; + action: string; + reason: string; + requestId: string; + metadata?: Record; + occurredAt: Date; +} + +export interface SupportCursorPosition { + occurredAt: string; + id: string; +} + +export interface SupportPageQueryParams { + limit: number; + cursor: SupportCursorPosition | null; +} + +export interface SupportPagedResult { + items: T[]; + nextCursor: SupportCursorPosition | null; +} + +// --------------------------------------------------------------------------- +// Narrow read-only diagnostic projections +// --------------------------------------------------------------------------- + +// Deliberately narrow: support reads expose identification + status only, never +// secrets, tokens, or full domain rows. Expanded per spec-16 as support +// workflows become real. + +export interface SupportOrganizationProjection { + orgId: string; + name: string; + slug: string; + status: string; + memberCount: number; + createdAt: Date; +} + +export interface SupportUserProjection { + userId: string; + email: string; + displayName: string | null; + status: string; + createdAt: Date; +} + +// --------------------------------------------------------------------------- +// Repository +// --------------------------------------------------------------------------- + +export interface SupportRepository { + recordSupportAction( + input: RecordSupportActionInput, + ): Promise>; + + listSupportActions( + targetOrgId: string, + params: SupportPageQueryParams, + ): Promise>>; + + lookupOrganizationForSupport( + orgId: string, + ): Promise>; + + lookupUserForSupport( + userId: string, + ): Promise>; +} diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts new file mode 100644 index 0000000..db62163 --- /dev/null +++ b/packages/db/src/types.ts @@ -0,0 +1,33 @@ +// Branded UUID identifier + decode helpers live in `./ids` (`@saas/db/ids`). +export { isUuid, asUuid, uuidFromPublicId } from "./ids/index.js"; +export type { Uuid } from "./ids/index.js"; + +export const BOUNDED_CONTEXTS = [ + "control", + "identity", + "membership", + "projects", + "billing", + "events", + "config", + "webhooks", + "metering", + "notifications", + "support", + "integrations", +] as const; + +export type BoundedContext = (typeof BOUNDED_CONTEXTS)[number]; + +export interface MigrationEntry { + id: string; + context: BoundedContext; + path: string; + checksum: string; + description: string; +} + +export interface MigrationManifest { + version: 1; + migrations: MigrationEntry[]; +} diff --git a/packages/db/src/webhooks/index.ts b/packages/db/src/webhooks/index.ts new file mode 100644 index 0000000..0f528a3 --- /dev/null +++ b/packages/db/src/webhooks/index.ts @@ -0,0 +1,25 @@ +export type { + WebhookRepositoryError, + WebhookResult, + CursorPosition, + PageQueryParams, + PagedResult, + WebhookEndpointStatus, + WebhookEndpoint, + CreateWebhookEndpointInput, + UpdateWebhookEndpointInput, + DisableWebhookEndpointInput, + WebhookSubscription, + CreateWebhookSubscriptionInput, + UpdateWebhookSubscriptionInput, + DeliveryAttemptStatus, + WebhookDeliveryAttempt, + CreateDeliveryAttemptInput, + UpdateDeliveryAttemptInput, + WebhookRepository, + EndpointForDelivery, + MatchedSubscription, + DispatchCursor, +} from "./types.js"; + +export { createWebhookRepository } from "./repository.js"; diff --git a/packages/db/src/webhooks/repository.ts b/packages/db/src/webhooks/repository.ts new file mode 100644 index 0000000..d5aa8b5 --- /dev/null +++ b/packages/db/src/webhooks/repository.ts @@ -0,0 +1,730 @@ +import type { SqlExecutor } from "../d1/executor.js"; +import type { + WebhookRepository, + WebhookResult, + WebhookEndpoint, + WebhookSubscription, + WebhookDeliveryAttempt, + CreateWebhookEndpointInput, + UpdateWebhookEndpointInput, + DisableWebhookEndpointInput, + CreateWebhookSubscriptionInput, + UpdateWebhookSubscriptionInput, + CreateDeliveryAttemptInput, + UpdateDeliveryAttemptInput, + CursorPosition, + PageQueryParams, + PagedResult, + EndpointForDelivery, + MatchedSubscription, + DispatchCursor, + RotateEndpointSecretInput, + RotateEndpointSecretResult, +} from "./types.js"; +import { isUniqueViolation } from "../d1/errors.js"; +import { parseBooleanColumn } from "../json.js"; + +// ── Row mappers ──────────────────────────────────────────── + +/** Safe columns for endpoint reads — excludes secret_ciphertext */ +const ENDPOINT_SAFE_COLUMNS = `id, org_id, project_id, url, name, description, status, disabled_reason, disabled_at, secret_version, secret_last_rotated_at, created_at, updated_at`; + +function mapEndpoint(row: Record): WebhookEndpoint { + return { + id: row.id as string, + orgId: row.org_id as string, + projectId: (row.project_id as string) ?? null, + url: row.url as string, + name: (row.name as string) ?? null, + description: (row.description as string) ?? null, + status: row.status as WebhookEndpoint["status"], + disabledReason: (row.disabled_reason as string) ?? null, + disabledAt: row.disabled_at ? new Date(row.disabled_at as string) : null, + secretVersion: row.secret_version as number, + secretLastRotatedAt: row.secret_last_rotated_at ? new Date(row.secret_last_rotated_at as string) : null, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapSubscription(row: Record): WebhookSubscription { + return { + id: row.id as string, + orgId: row.org_id as string, + endpointId: row.endpoint_id as string, + projectId: (row.project_id as string) ?? null, + eventType: row.event_type as string, + enabled: parseBooleanColumn(row.enabled), + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +function mapDeliveryAttempt(row: Record): WebhookDeliveryAttempt { + return { + id: row.id as string, + orgId: row.org_id as string, + endpointId: row.endpoint_id as string, + subscriptionId: row.subscription_id as string, + eventId: row.event_id as string, + eventType: row.event_type as string, + status: row.status as WebhookDeliveryAttempt["status"], + attemptNumber: row.attempt_number as number, + httpStatusCode: (row.http_status_code as number) ?? null, + failureReason: (row.failure_reason as string) ?? null, + idempotencyKey: (row.idempotency_key as string) ?? null, + nextRetryAt: row.next_retry_at ? new Date(row.next_retry_at as string) : null, + completedAt: row.completed_at ? new Date(row.completed_at as string) : null, + createdAt: new Date(row.created_at as string), + updatedAt: new Date(row.updated_at as string), + }; +} + +// ── Helpers ──────────────────────────────────────────────── + +function safeError(message: string): WebhookResult { + return { ok: false, error: { kind: "internal", message } }; +} + + +// ── Paged list helper ────────────────────────────────────── + +async function pagedList( + executor: SqlExecutor, + table: string, + whereClause: string, + whereParams: unknown[], + params: PageQueryParams, + mapper: (row: Record) => T, + selectColumns = "*", +): Promise>> { + try { + const fetchLimit = params.limit + 1; + const baseIdx = whereParams.length; + let sql: string; + let values: unknown[]; + if (params.cursor) { + sql = `SELECT ${selectColumns} FROM ${table} + WHERE ${whereClause} + AND (created_at, id) < ($${baseIdx + 2}, $${baseIdx + 3}) + ORDER BY created_at DESC, id DESC + LIMIT $${baseIdx + 1}`; + values = [...whereParams, fetchLimit, params.cursor.createdAt, params.cursor.id]; + } else { + sql = `SELECT ${selectColumns} FROM ${table} + WHERE ${whereClause} + ORDER BY created_at DESC, id DESC + LIMIT $${baseIdx + 1}`; + values = [...whereParams, fetchLimit]; + } + const result = await executor.execute>(sql, values); + const rows = result.rows.map(mapper); + let nextCursor: CursorPosition | null = null; + if (rows.length > params.limit) { + rows.pop(); + const last = rows[rows.length - 1]!; + nextCursor = { + createdAt: (last as unknown as { createdAt: Date }).createdAt.toISOString(), + id: (last as unknown as { id: string }).id, + }; + } + return { ok: true, value: { items: rows, nextCursor } }; + } catch { + return safeError(`Failed to list from ${table}`); + } +} + +// ── Repository factory ───────────────────────────────────── + +export function createWebhookRepository(executor: SqlExecutor): WebhookRepository { + return { + // ── Endpoints ────────────────────────────────────────── + + async createEndpoint(input: CreateWebhookEndpointInput): Promise> { + try { + const hasCiphertext = input.secretCiphertext !== undefined; + const sql = hasCiphertext + ? `INSERT INTO webhooks_webhook_endpoints (id, org_id, project_id, url, name, description, secret_ciphertext, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING ${ENDPOINT_SAFE_COLUMNS}` + : `INSERT INTO webhooks_webhook_endpoints (id, org_id, project_id, url, name, description, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING ${ENDPOINT_SAFE_COLUMNS}`; + const values: unknown[] = [ + input.id, + input.orgId, + input.projectId ?? null, + input.url, + input.name ?? null, + input.description ?? null, + ]; + if (hasCiphertext) { + values.push(input.secretCiphertext!); + } + const result = await executor.execute>(sql, values); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "webhook_endpoint" } }; + } + return { ok: true, value: mapEndpoint(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "webhook_endpoint" } }; + } + return safeError("Failed to create webhook endpoint"); + } + }, + + async getEndpoint(orgId: string, endpointId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT ${ENDPOINT_SAFE_COLUMNS} FROM webhooks_webhook_endpoints WHERE org_id = $1 AND id = $2`, + [orgId, endpointId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEndpoint(result.rows[0]!) }; + } catch { + return safeError("Failed to get webhook endpoint"); + } + }, + + async listEndpoints(orgId: string, params: PageQueryParams, projectId?: string | null): Promise>> { + if (projectId) { + return pagedList( + executor, + "webhooks_webhook_endpoints", + "org_id = $1 AND project_id = $2", + [orgId, projectId], + params, + mapEndpoint, + ENDPOINT_SAFE_COLUMNS, + ); + } + return pagedList( + executor, + "webhooks_webhook_endpoints", + "org_id = $1", + [orgId], + params, + mapEndpoint, + ENDPOINT_SAFE_COLUMNS, + ); + }, + + async updateEndpoint(orgId: string, endpointId: string, input: UpdateWebhookEndpointInput): Promise> { + try { + const setClauses: string[] = ["updated_at = now()"]; + const values: unknown[] = [orgId, endpointId]; + let idx = 3; + if (input.url !== undefined) { + setClauses.push(`url = $${idx}`); + values.push(input.url); + idx++; + } + if (input.name !== undefined) { + setClauses.push(`name = $${idx}`); + values.push(input.name); + idx++; + } + if (input.description !== undefined) { + setClauses.push(`description = $${idx}`); + values.push(input.description); + idx++; + } + const result = await executor.execute>( + `UPDATE webhooks_webhook_endpoints SET ${setClauses.join(", ")} WHERE org_id = $1 AND id = $2 RETURNING ${ENDPOINT_SAFE_COLUMNS}`, + values, + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEndpoint(result.rows[0]!) }; + } catch { + return safeError("Failed to update webhook endpoint"); + } + }, + + async disableEndpoint(orgId: string, endpointId: string, input: DisableWebhookEndpointInput): Promise> { + try { + const result = await executor.execute>( + `UPDATE webhooks_webhook_endpoints + SET status = 'disabled', disabled_reason = $3, disabled_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING ${ENDPOINT_SAFE_COLUMNS}`, + [orgId, endpointId, input.reason ?? null], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEndpoint(result.rows[0]!) }; + } catch { + return safeError("Failed to disable webhook endpoint"); + } + }, + + async enableEndpoint(orgId: string, endpointId: string): Promise> { + try { + // Symmetric to disableEndpoint: WHERE guard ensures idempotent + // semantics — re-running on an already-active endpoint returns + // not_found (mirrors disable's "missing or already disabled" model). + // `pending` endpoints are intentionally excluded. + const result = await executor.execute>( + `UPDATE webhooks_webhook_endpoints + SET status = 'active', disabled_reason = NULL, disabled_at = NULL, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + WHERE org_id = $1 AND id = $2 AND status = 'disabled' + RETURNING ${ENDPOINT_SAFE_COLUMNS}`, + [orgId, endpointId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapEndpoint(result.rows[0]!) }; + } catch { + return safeError("Failed to enable webhook endpoint"); + } + }, + + async deleteEndpoint(orgId: string, endpointId: string): Promise> { + try { + const result = await executor.execute>( + `DELETE FROM webhooks_webhook_endpoints WHERE org_id = $1 AND id = $2`, + [orgId, endpointId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: { deleted: true } }; + } catch { + return safeError("Failed to delete webhook endpoint"); + } + }, + + async rotateEndpointSecret( + orgId: string, + endpointId: string, + input?: RotateEndpointSecretInput, + ): Promise> { + try { + const secretCiphertext = input?.secretCiphertext; + const gracePeriodSeconds = input?.gracePeriodSeconds; + const hasCiphertext = secretCiphertext !== undefined; + const useGrace = typeof gracePeriodSeconds === "number" && gracePeriodSeconds > 0 && hasCiphertext; + + // When useGrace: snapshot current secret_ciphertext + secret_version into the + // previous_* columns and set previous_secret_expires_at = now() + N seconds. + // When !useGrace: clear any stale grace window (previous_* = NULL). + let setClause: string; + const values: unknown[] = [orgId, endpointId]; + if (useGrace) { + setClause = `secret_version = secret_version + 1, + secret_last_rotated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), + previous_secret_ciphertext = secret_ciphertext, + previous_secret_version = secret_version, + previous_secret_expires_at = strftime('%Y-%m-%dT%H:%M:%fZ','now', '+' || $4 || ' seconds'), + secret_ciphertext = $3, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`; + values.push(secretCiphertext, gracePeriodSeconds); + } else if (hasCiphertext) { + setClause = `secret_version = secret_version + 1, + secret_last_rotated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), + previous_secret_ciphertext = NULL, + previous_secret_version = NULL, + previous_secret_expires_at = NULL, + secret_ciphertext = $3, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`; + values.push(secretCiphertext); + } else { + setClause = `secret_version = secret_version + 1, + secret_last_rotated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), + previous_secret_ciphertext = NULL, + previous_secret_version = NULL, + previous_secret_expires_at = NULL, + updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')`; + } + + const sql = `UPDATE webhooks_webhook_endpoints + SET ${setClause} + WHERE org_id = $1 AND id = $2 AND status = 'active' + RETURNING ${ENDPOINT_SAFE_COLUMNS}, previous_secret_version, previous_secret_expires_at`; + + const result = await executor.execute>(sql, values); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const row = result.rows[0]!; + const previousSecretVersion = (row.previous_secret_version as number | null) ?? null; + const rawExpires = row.previous_secret_expires_at; + const previousSecretExpiresAt = rawExpires + ? new Date(rawExpires as string).toISOString() + : null; + return { + ok: true, + value: { + endpoint: mapEndpoint(row), + previousSecretVersion, + previousSecretExpiresAt, + }, + }; + } catch { + return safeError("Failed to rotate webhook endpoint secret"); + } + }, + + // ── Subscriptions ────────────────────────────────────── + + async createSubscription(input: CreateWebhookSubscriptionInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO webhooks_webhook_subscriptions (id, org_id, endpoint_id, project_id, event_type, enabled, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING *`, + [input.id, input.orgId, input.endpointId, input.projectId ?? null, input.eventType, input.enabled ?? true], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "webhook_subscription" } }; + } + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "webhook_subscription" } }; + } + return safeError("Failed to create webhook subscription"); + } + }, + + async getSubscription(orgId: string, subscriptionId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM webhooks_webhook_subscriptions WHERE org_id = $1 AND id = $2`, + [orgId, subscriptionId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch { + return safeError("Failed to get webhook subscription"); + } + }, + + async listSubscriptions(orgId: string, endpointId: string, params: PageQueryParams): Promise>> { + return pagedList( + executor, + "webhooks_webhook_subscriptions", + "org_id = $1 AND endpoint_id = $2", + [orgId, endpointId], + params, + mapSubscription, + ); + }, + + async updateSubscription(orgId: string, subscriptionId: string, input: UpdateWebhookSubscriptionInput): Promise> { + try { + const setClauses: string[] = ["updated_at = now()"]; + const values: unknown[] = [orgId, subscriptionId]; + let idx = 3; + if (input.enabled !== undefined) { + setClauses.push(`enabled = $${idx}`); + values.push(input.enabled); + idx++; + } + const result = await executor.execute>( + `UPDATE webhooks_webhook_subscriptions SET ${setClauses.join(", ")} WHERE org_id = $1 AND id = $2 RETURNING *`, + values, + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapSubscription(result.rows[0]!) }; + } catch { + return safeError("Failed to update webhook subscription"); + } + }, + + async deleteSubscription(orgId: string, subscriptionId: string): Promise> { + try { + const result = await executor.execute>( + `DELETE FROM webhooks_webhook_subscriptions WHERE org_id = $1 AND id = $2`, + [orgId, subscriptionId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: { deleted: true } }; + } catch { + return safeError("Failed to delete webhook subscription"); + } + }, + + // ── Delivery attempts ────────────────────────────────── + + async createDeliveryAttempt(input: CreateDeliveryAttemptInput): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO webhooks_webhook_delivery_attempts (id, org_id, endpoint_id, subscription_id, event_id, event_type, idempotency_key, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, strftime('%Y-%m-%dT%H:%M:%fZ','now'), strftime('%Y-%m-%dT%H:%M:%fZ','now')) + RETURNING *`, + [input.id, input.orgId, input.endpointId, input.subscriptionId, input.eventId, input.eventType, input.idempotencyKey ?? null], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "conflict", entity: "webhook_delivery_attempt" } }; + } + return { ok: true, value: mapDeliveryAttempt(result.rows[0]!) }; + } catch (err: unknown) { + if (isUniqueViolation(err)) { + return { ok: false, error: { kind: "conflict", entity: "webhook_delivery_attempt" } }; + } + return safeError("Failed to create delivery attempt"); + } + }, + + async updateDeliveryAttempt(orgId: string, attemptId: string, input: UpdateDeliveryAttemptInput): Promise> { + try { + const setClauses: string[] = ["updated_at = now()", "status = $3"]; + const values: unknown[] = [orgId, attemptId, input.status]; + let idx = 4; + if (input.attemptNumber !== undefined) { + setClauses.push(`attempt_number = $${idx}`); + values.push(input.attemptNumber); + idx++; + } + if (input.httpStatusCode !== undefined) { + setClauses.push(`http_status_code = $${idx}`); + values.push(input.httpStatusCode); + idx++; + } + if (input.failureReason !== undefined) { + setClauses.push(`failure_reason = $${idx}`); + values.push(input.failureReason); + idx++; + } + if (input.nextRetryAt !== undefined) { + setClauses.push(`next_retry_at = $${idx}`); + values.push(input.nextRetryAt?.toISOString() ?? null); + idx++; + } + if (input.completedAt !== undefined) { + setClauses.push(`completed_at = $${idx}`); + values.push(input.completedAt?.toISOString() ?? null); + idx++; + } + const result = await executor.execute>( + `UPDATE webhooks_webhook_delivery_attempts SET ${setClauses.join(", ")} WHERE org_id = $1 AND id = $2 RETURNING *`, + values, + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapDeliveryAttempt(result.rows[0]!) }; + } catch { + return safeError("Failed to update delivery attempt"); + } + }, + + async getDeliveryAttempt(orgId: string, attemptId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM webhooks_webhook_delivery_attempts WHERE org_id = $1 AND id = $2`, + [orgId, attemptId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + return { ok: true, value: mapDeliveryAttempt(result.rows[0]!) }; + } catch { + return safeError("Failed to get delivery attempt"); + } + }, + + async listDeliveryAttempts(orgId: string, endpointId: string, params: PageQueryParams): Promise>> { + return pagedList( + executor, + "webhooks_webhook_delivery_attempts", + "org_id = $1 AND endpoint_id = $2", + [orgId, endpointId], + params, + mapDeliveryAttempt, + ); + }, + + // ── Delivery runtime ──────────────────────────────────── + + async getEndpointForDelivery(orgId: string, endpointId: string): Promise> { + try { + const result = await executor.execute>( + `SELECT id, org_id, url, status, secret_ciphertext, secret_version, + previous_secret_ciphertext, previous_secret_version, previous_secret_expires_at + FROM webhooks_webhook_endpoints WHERE org_id = $1 AND id = $2`, + [orgId, endpointId], + ); + if (result.rowCount === 0) { + return { ok: false, error: { kind: "not_found" } }; + } + const row = result.rows[0]!; + const rawPrevExpires = row.previous_secret_expires_at; + return { + ok: true, + value: { + id: row.id as string, + orgId: row.org_id as string, + url: row.url as string, + status: row.status as EndpointForDelivery["status"], + secretCiphertext: (row.secret_ciphertext as string) ?? null, + secretVersion: row.secret_version as number, + previousSecretCiphertext: (row.previous_secret_ciphertext as string) ?? null, + previousSecretVersion: (row.previous_secret_version as number | null) ?? null, + previousSecretExpiresAt: rawPrevExpires + ? new Date(rawPrevExpires as string).toISOString() + : null, + }, + }; + } catch { + return safeError("Failed to get endpoint for delivery"); + } + }, + + async findMatchingSubscriptions(orgId: string, eventType: string): Promise> { + try { + // Match exact event type OR wildcard subscriptions (e.g. "project.*" matches "project.created") + const result = await executor.execute>( + `SELECT s.id, s.org_id, s.endpoint_id, s.project_id, s.event_type + FROM webhooks_webhook_subscriptions s + JOIN webhooks_webhook_endpoints e ON e.id = s.endpoint_id AND e.org_id = s.org_id + WHERE s.org_id = $1 AND s.enabled = true AND e.status = 'active' + AND (s.event_type = $2 OR s.event_type = '*' + OR ($2 LIKE s.event_type || '.%' AND s.event_type LIKE '%.*'))`, + [orgId, eventType], + ); + const subs: MatchedSubscription[] = result.rows.map((row) => ({ + id: row.id as string, + orgId: row.org_id as string, + endpointId: row.endpoint_id as string, + projectId: (row.project_id as string) ?? null, + eventType: row.event_type as string, + })); + return { ok: true, value: subs }; + } catch { + return safeError("Failed to find matching subscriptions"); + } + }, + + async listRetryableDeliveries(limit: number): Promise> { + try { + const result = await executor.execute>( + `SELECT * FROM webhooks_webhook_delivery_attempts + WHERE status = 'retrying' AND next_retry_at IS NOT NULL AND next_retry_at <= strftime('%Y-%m-%dT%H:%M:%fZ','now') + ORDER BY next_retry_at ASC + LIMIT $1`, + [limit], + ); + return { ok: true, value: result.rows.map(mapDeliveryAttempt) }; + } catch { + return safeError("Failed to list retryable deliveries"); + } + }, + + // ── Dispatch cursor ───────────────────────────────────── + + async getDispatchCursor(orgId: string, lane = "webhooks"): Promise> { + try { + const result = await executor.execute>( + `SELECT org_id, subscriber_lane, last_event_id, last_occurred_at, updated_at + FROM webhooks_webhook_dispatch_cursor + WHERE org_id = $1 AND subscriber_lane = $2`, + [orgId, lane], + ); + if (result.rowCount === 0) { + // Return a "zero" cursor — org hasn't been dispatched yet + return { + ok: true, + value: { + orgId, + subscriberLane: lane, + lastEventId: null, + lastOccurredAt: null, + updatedAt: new Date(0), + }, + }; + } + const row = result.rows[0]!; + return { + ok: true, + value: { + orgId: row.org_id as string, + subscriberLane: row.subscriber_lane as string, + lastEventId: (row.last_event_id as string) ?? null, + lastOccurredAt: (row.last_occurred_at as string) ?? null, + updatedAt: new Date(row.updated_at as string), + }, + }; + } catch { + return safeError("Failed to get dispatch cursor"); + } + }, + + async advanceDispatchCursor(orgId: string, lastEventId: string, lastOccurredAt: string, lane = "webhooks"): Promise> { + try { + const result = await executor.execute>( + `INSERT INTO webhooks_webhook_dispatch_cursor (org_id, subscriber_lane, last_event_id, last_occurred_at, updated_at) + VALUES ($1, $2, $3, $4, strftime('%Y-%m-%dT%H:%M:%fZ','now')) + ON CONFLICT (org_id, subscriber_lane) + DO UPDATE SET last_event_id = $3, last_occurred_at = $4, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') + RETURNING *`, + [orgId, lane, lastEventId, lastOccurredAt], + ); + const row = result.rows[0]!; + return { + ok: true, + value: { + orgId: row.org_id as string, + subscriberLane: row.subscriber_lane as string, + lastEventId: (row.last_event_id as string) ?? null, + lastOccurredAt: (row.last_occurred_at as string) ?? null, + updatedAt: new Date(row.updated_at as string), + }, + }; + } catch { + return safeError("Failed to advance dispatch cursor"); + } + }, + + async countConsecutiveEndpointFailures(orgId: string, endpointId: string): Promise> { + try { + // Count consecutive terminal failures from the most recent completed attempts. + // Finds the latest success (if any) and counts failures after it. + const result = await executor.execute>( + `SELECT COUNT(*) AS streak + FROM webhooks_webhook_delivery_attempts + WHERE org_id = $1 AND endpoint_id = $2 AND status = 'failed' + AND completed_at > COALESCE( + (SELECT MAX(completed_at) FROM webhooks_webhook_delivery_attempts + WHERE org_id = $1 AND endpoint_id = $2 AND status = 'success'), + '1970-01-01T00:00:00.000Z' + )`, + [orgId, endpointId], + ); + const streak = parseInt(result.rows[0]?.streak as string ?? "0", 10); + return { ok: true, value: streak }; + } catch { + return safeError("Failed to count consecutive endpoint failures"); + } + }, + + async listActiveOrgIds(): Promise> { + try { + // Orgs that have at least one enabled subscription with an active endpoint + const result = await executor.execute>( + `SELECT DISTINCT s.org_id + FROM webhooks_webhook_subscriptions s + JOIN webhooks_webhook_endpoints e ON e.id = s.endpoint_id AND e.org_id = s.org_id + WHERE s.enabled = true AND e.status = 'active'`, + [], + ); + return { ok: true, value: result.rows.map((row) => row.org_id as string) }; + } catch { + return safeError("Failed to list active org IDs"); + } + }, + }; +} diff --git a/packages/db/src/webhooks/types.ts b/packages/db/src/webhooks/types.ts new file mode 100644 index 0000000..68cab57 --- /dev/null +++ b/packages/db/src/webhooks/types.ts @@ -0,0 +1,259 @@ +import type { Uuid } from "../ids/index.js"; + +export type { SqlExecutor, SqlExecutorResult, SqlRow } from "../d1/executor.js"; + +// ── Result type ───────────────────────────────────────────── + +export type WebhookRepositoryError = + | { kind: "not_found" } + | { kind: "conflict"; entity: string } + | { kind: "internal"; message: string }; + +export type WebhookResult = + | { ok: true; value: T } + | { ok: false; error: WebhookRepositoryError }; + +// ── Cursor pagination (matches existing convention) ───────── + +export interface CursorPosition { + createdAt: string; + id: string; +} + +export interface PageQueryParams { + limit: number; + cursor: CursorPosition | null; +} + +export interface PagedResult { + items: T[]; + nextCursor: CursorPosition | null; +} + +// ── Webhook endpoints ─────────────────────────────────────── +// NOTE: No plaintext signing secret fields. Only safe metadata. + +export type WebhookEndpointStatus = "active" | "disabled" | "pending"; + +export interface WebhookEndpoint { + id: string; + orgId: string; + projectId: string | null; + url: string; + name: string | null; + description: string | null; + status: WebhookEndpointStatus; + disabledReason: string | null; + disabledAt: Date | null; + secretVersion: number; + secretLastRotatedAt: Date | null; + // NOTE: secret_ciphertext is intentionally excluded from the type. + // It is never exposed through the repository read surface. + createdAt: Date; + updatedAt: Date; +} + +export interface CreateWebhookEndpointInput { + id: string; + orgId: Uuid; + projectId?: Uuid | null; + url: string; + name?: string | null; + description?: string | null; + /** JSON-serialized ciphertext envelope for signing secret. Write-only — never returned. */ + secretCiphertext?: string; +} + +export interface UpdateWebhookEndpointInput { + url?: string; + name?: string | null; + description?: string | null; +} + +export interface DisableWebhookEndpointInput { + reason?: string; +} + +/** + * Input for rotateEndpointSecret. The repository copies the current secret + * into the previous-secret slot, sets the previous-secret expiry to + * `strftime('%Y-%m-%dT%H:%M:%fZ','now') + gracePeriodSeconds`, and writes the new secret atomically. + */ +export interface RotateEndpointSecretInput { + /** New encrypted signing-secret envelope. Required for live rotations. */ + secretCiphertext?: string; + /** + * Grace-window duration in seconds. When omitted, the previous secret is + * NOT preserved (legacy / first rotation). When provided, the rotation + * persists the previous ciphertext + version + an expires_at = now() + N. + */ + gracePeriodSeconds?: number; +} + +/** + * Result of rotateEndpointSecret. `endpoint` is the safe public-shape view; + * `previousSecretExpiresAt` is the wall-clock the grace window closes at, + * needed by the worker handler to populate its reveal-once response. + */ +export interface RotateEndpointSecretResult { + endpoint: WebhookEndpoint; + /** Snapshot of secret_version at the moment of rotate (the previous secret's version). Null when no grace window applied. */ + previousSecretVersion: number | null; + /** ISO timestamp the grace window closes at. Null when no grace window applied. */ + previousSecretExpiresAt: string | null; +} + +// ── Webhook subscriptions ─────────────────────────────────── + +export interface WebhookSubscription { + id: string; + orgId: string; + endpointId: string; + projectId: string | null; + eventType: string; + enabled: boolean; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateWebhookSubscriptionInput { + id: string; + orgId: Uuid; + endpointId: string; + projectId?: Uuid | null; + eventType: string; + enabled?: boolean; +} + +export interface UpdateWebhookSubscriptionInput { + enabled?: boolean; +} + +// ── Webhook delivery attempts ─────────────────────────────── +// NOTE: No full event payloads or customer response bodies. + +export type DeliveryAttemptStatus = "pending" | "success" | "failed" | "retrying"; + +export interface WebhookDeliveryAttempt { + id: string; + orgId: string; + endpointId: string; + subscriptionId: string; + eventId: string; + eventType: string; + status: DeliveryAttemptStatus; + attemptNumber: number; + httpStatusCode: number | null; + failureReason: string | null; + idempotencyKey: string | null; + nextRetryAt: Date | null; + completedAt: Date | null; + createdAt: Date; + updatedAt: Date; +} + +export interface CreateDeliveryAttemptInput { + id: string; + orgId: string; + endpointId: string; + subscriptionId: string; + eventId: string; + eventType: string; + idempotencyKey?: string | null; +} + +export interface UpdateDeliveryAttemptInput { + status: DeliveryAttemptStatus; + attemptNumber?: number; + httpStatusCode?: number | null; + failureReason?: string | null; + nextRetryAt?: Date | null; + completedAt?: Date | null; +} + +// ── Delivery runtime types ─────────────────────────────────── + +/** Endpoint data needed for delivery — includes secret_ciphertext for signing */ +export interface EndpointForDelivery { + id: string; + orgId: string; + url: string; + status: WebhookEndpointStatus; + secretCiphertext: string | null; + secretVersion: number; + /** Encrypted previous-secret envelope, populated within the rotation grace window. */ + previousSecretCiphertext: string | null; + /** Version number of the previous secret (snapshot of secret_version at the moment of rotate). */ + previousSecretVersion: number | null; + /** ISO timestamp at which the previous-secret grace window closes; null when no previous secret. */ + previousSecretExpiresAt: string | null; +} + +/** Subscription matched during fanout */ +export interface MatchedSubscription { + id: string; + orgId: string; + endpointId: string; + projectId: string | null; + eventType: string; +} + +/** Dispatch cursor position */ +export interface DispatchCursor { + orgId: string; + subscriberLane: string; + lastEventId: string | null; + lastOccurredAt: string | null; + updatedAt: Date; +} + +// ── Repository interface ──────────────────────────────────── + +export interface WebhookRepository { + // Endpoints + createEndpoint(input: CreateWebhookEndpointInput): Promise>; + getEndpoint(orgId: string, endpointId: string): Promise>; + listEndpoints(orgId: string, params: PageQueryParams, projectId?: string | null): Promise>>; + updateEndpoint(orgId: string, endpointId: string, input: UpdateWebhookEndpointInput): Promise>; + disableEndpoint(orgId: string, endpointId: string, input: DisableWebhookEndpointInput): Promise>; + /** + * Re-enable a previously disabled endpoint. Sets `status = 'active'`, + * clears `disabled_reason` and `disabled_at`. Guarded by `WHERE status = + * 'disabled'` — a 0-row response (`not_found`) covers both "endpoint + * missing" and "already active". `pending` endpoints are intentionally + * not re-enabled here (would require a spec proposal). + */ + enableEndpoint(orgId: string, endpointId: string): Promise>; + deleteEndpoint(orgId: string, endpointId: string): Promise>; + rotateEndpointSecret(orgId: string, endpointId: string, input?: RotateEndpointSecretInput): Promise>; + + // Subscriptions + createSubscription(input: CreateWebhookSubscriptionInput): Promise>; + getSubscription(orgId: string, subscriptionId: string): Promise>; + listSubscriptions(orgId: string, endpointId: string, params: PageQueryParams): Promise>>; + updateSubscription(orgId: string, subscriptionId: string, input: UpdateWebhookSubscriptionInput): Promise>; + deleteSubscription(orgId: string, subscriptionId: string): Promise>; + + // Delivery attempts + createDeliveryAttempt(input: CreateDeliveryAttemptInput): Promise>; + updateDeliveryAttempt(orgId: string, attemptId: string, input: UpdateDeliveryAttemptInput): Promise>; + getDeliveryAttempt(orgId: string, attemptId: string): Promise>; + listDeliveryAttempts(orgId: string, endpointId: string, params: PageQueryParams): Promise>>; + + // Delivery runtime + getEndpointForDelivery(orgId: string, endpointId: string): Promise>; + findMatchingSubscriptions(orgId: string, eventType: string): Promise>; + listRetryableDeliveries(limit: number): Promise>; + + // Dispatch cursor + getDispatchCursor(orgId: string, lane?: string): Promise>; + advanceDispatchCursor(orgId: string, lastEventId: string, lastOccurredAt: string, lane?: string): Promise>; + listActiveOrgIds(): Promise>; + + // Delivery lifecycle + /** + * Count consecutive terminal delivery failures for an endpoint, + * looking at the most recent completed attempts. A success resets the streak. + */ + countConsecutiveEndpointFailures(orgId: string, endpointId: string): Promise>; +} diff --git a/packages/db/tsconfig.build.json b/packages/db/tsconfig.build.json new file mode 100644 index 0000000..c6fb252 --- /dev/null +++ b/packages/db/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + } +} diff --git a/packages/db/tsconfig.json b/packages/db/tsconfig.json new file mode 100644 index 0000000..d84a568 --- /dev/null +++ b/packages/db/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/notifications-client/component.yaml b/packages/notifications-client/component.yaml new file mode 100644 index 0000000..6dff9df --- /dev/null +++ b/packages/notifications-client/component.yaml @@ -0,0 +1,27 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: notifications-client +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-shared + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: shared +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/notifications-client/docs/architecture.md b/packages/notifications-client/docs/architecture.md new file mode 100644 index 0000000..9b18de5 --- /dev/null +++ b/packages/notifications-client/docs/architecture.md @@ -0,0 +1,9 @@ +# notifications-client — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/notifications-client`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/notifications-client/docs/overview.md b/packages/notifications-client/docs/overview.md new file mode 100644 index 0000000..d62c750 --- /dev/null +++ b/packages/notifications-client/docs/overview.md @@ -0,0 +1,13 @@ +# notifications-client + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/notifications-client/docs/runbook.md b/packages/notifications-client/docs/runbook.md new file mode 100644 index 0000000..4456431 --- /dev/null +++ b/packages/notifications-client/docs/runbook.md @@ -0,0 +1,26 @@ +# notifications-client — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/notifications-client/eslint.config.js b/packages/notifications-client/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/notifications-client/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/notifications-client/package.json b/packages/notifications-client/package.json new file mode 100644 index 0000000..fed3b59 --- /dev/null +++ b/packages/notifications-client/package.json @@ -0,0 +1,23 @@ +{ + "name": "@saas/notifications-client", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20250508.0", + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*" + } +} diff --git a/packages/notifications-client/src/index.ts b/packages/notifications-client/src/index.ts new file mode 100644 index 0000000..5ab0b60 --- /dev/null +++ b/packages/notifications-client/src/index.ts @@ -0,0 +1,163 @@ +import type { + EnqueueNotificationRequest, + EnqueueNotificationResponse, +} from "@saas/contracts/notifications"; + +/** + * Best-effort internal client for `notifications-worker`. + * + * Posts the V1 enqueue contract to the internal route + * `POST https://notifications.internal/v1/notifications` over the + * `NOTIFICATIONS_WORKER` service binding, mirroring the established + * internal-binding pattern (see `apps/notifications-worker/src/events-client.ts`). + * + * Best-effort semantics: + * + * - missing binding (`env.NOTIFICATIONS_WORKER` undefined) → no-op + * - non-2xx response → returns `{ ok: false, reason: "non_2xx" }` + * - network throw / malformed JSON → returns `{ ok: false, reason }` + * + * The function NEVER throws. Call sites treat the result as advisory and + * MUST NOT propagate notifications failures to the user-facing response — + * the notifications surface is downstream of, and decoupled from, the + * caller's primary lifecycle (auth, invitations, etc.). + * + * No secret material (raw codes, raw invitation tokens, provider responses) + * MUST be placed in `templateData`. Allowed values are a bounded + * redaction-safe subset (presentation hints + the message payload itself + * where the payload IS the message — e.g. magic-link login codes — but + * never the authoritative secret of the originating state — token hashes + * are persisted server-side, never the raw token). + */ + +export interface NotificationsEnvBinding { + NOTIFICATIONS_WORKER?: Fetcher; +} + +export interface NotificationsClientContext { + /** + * Caller identifier — e.g. `"identity-worker"`, `"membership-worker"`. + * Forwarded as `x-internal-actor` for tracing / audit. + */ + internalActor: string; + /** Actor subject type as known to the caller (e.g. `"system"`, `"user"`). */ + actorSubjectType: string; + /** Actor subject id as known to the caller. */ + actorSubjectId: string; + /** Request id to propagate for tracing. */ + requestId: string; +} + +export type EnqueueNotificationResult = + | { ok: true; notificationId: string } + | { ok: false; reason: "no_binding" | "non_2xx" | "network_error" | "bad_response" }; + +const ENQUEUE_URL = "https://notifications.internal/v1/notifications"; + +/** + * Build a deterministic, template-scoped idempotency key for the + * notifications-worker enqueue path. + * + * The `(orgId, idempotencyKey)` uniqueness invariant on the notifications + * row drives the worker's `idempotent_hit` outcome — a retry of the same + * logical event collapses to one row + (eventually) one provider attempt. + * + * Shape: `:[:...]`. `scope` SHOULD match the caller's + * `templateKey` (e.g. `"auth.magic_link"`, `"invitation.created"`, + * `"invitation.accepted"`) so two logically-distinct events that share + * an upstream id never collide. + * + * Constraints (enforced at runtime): + * - `scope` and every `part` must be a non-empty string. + * - No `part` may contain whitespace, `:`, or any control character — + * keys end up in DB rows and logs and must be cheaply roundtrippable. + * + * Inputs MUST be values that are stable across retries of the same + * logical action (e.g. a row id materialised by a prior commit, a + * challenge id that is itself the durable handle for the challenge). + * Callers MUST NOT pass raw secret material (tokens, codes, password + * equivalents) — keys are persisted server-side. + */ +export function buildIdempotencyKey(scope: string, ...parts: string[]): string { + if (typeof scope !== "string" || scope.length === 0) { + throw new TypeError("buildIdempotencyKey: scope must be a non-empty string"); + } + if (parts.length === 0) { + throw new TypeError("buildIdempotencyKey: at least one part is required"); + } + const segments = [scope, ...parts]; + for (const seg of segments) { + if (typeof seg !== "string" || seg.length === 0) { + throw new TypeError("buildIdempotencyKey: all segments must be non-empty strings"); + } + if (/[\s:\u0000-\u001f\u007f]/.test(seg)) { + throw new TypeError( + "buildIdempotencyKey: segments must not contain whitespace, ':' or control characters", + ); + } + } + return segments.join(":"); +} + +export async function enqueueNotification( + env: NotificationsEnvBinding, + ctx: NotificationsClientContext, + request: EnqueueNotificationRequest, +): Promise { + if (!env.NOTIFICATIONS_WORKER) { + return { ok: false, reason: "no_binding" }; + } + + let response: Response; + try { + response = await env.NOTIFICATIONS_WORKER.fetch(ENQUEUE_URL, { + method: "POST", + headers: { + "content-type": "application/json", + "x-request-id": ctx.requestId, + "x-internal-actor": ctx.internalActor, + "x-actor-subject-type": ctx.actorSubjectType, + "x-actor-subject-id": ctx.actorSubjectId, + }, + body: JSON.stringify(request), + }); + } catch { + return { ok: false, reason: "network_error" }; + } + + if (!response.ok) { + return { ok: false, reason: "non_2xx" }; + } + + let parsed: unknown; + try { + parsed = await response.json(); + } catch { + return { ok: false, reason: "bad_response" }; + } + + if (!parsed || typeof parsed !== "object" || !("data" in parsed)) { + return { ok: false, reason: "bad_response" }; + } + + const data = (parsed as { data: unknown }).data; + if ( + !data || + typeof data !== "object" || + !("notification" in data) + ) { + return { ok: false, reason: "bad_response" }; + } + + const notification = (data as { notification: unknown }).notification; + if ( + !notification || + typeof notification !== "object" || + typeof (notification as { id?: unknown }).id !== "string" + ) { + return { ok: false, reason: "bad_response" }; + } + + const resp = data as EnqueueNotificationResponse; + return { ok: true, notificationId: resp.notification.id }; +} diff --git a/packages/notifications-client/tsconfig.build.json b/packages/notifications-client/tsconfig.build.json new file mode 100644 index 0000000..e643198 --- /dev/null +++ b/packages/notifications-client/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/worker.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/notifications-client/tsconfig.json b/packages/notifications-client/tsconfig.json new file mode 100644 index 0000000..276fd08 --- /dev/null +++ b/packages/notifications-client/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/worker.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/policy-engine/component.yaml b/packages/policy-engine/component.yaml new file mode 100644 index 0000000..4172cbe --- /dev/null +++ b/packages/policy-engine/component.yaml @@ -0,0 +1,27 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: policy-engine +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-shared + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: policy +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/policy-engine/docs/architecture.md b/packages/policy-engine/docs/architecture.md new file mode 100644 index 0000000..fc2c2b4 --- /dev/null +++ b/packages/policy-engine/docs/architecture.md @@ -0,0 +1,9 @@ +# policy-engine — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/policy-engine`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/policy-engine/docs/overview.md b/packages/policy-engine/docs/overview.md new file mode 100644 index 0000000..67a1e56 --- /dev/null +++ b/packages/policy-engine/docs/overview.md @@ -0,0 +1,13 @@ +# policy-engine + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/policy-engine/docs/runbook.md b/packages/policy-engine/docs/runbook.md new file mode 100644 index 0000000..52904b9 --- /dev/null +++ b/packages/policy-engine/docs/runbook.md @@ -0,0 +1,26 @@ +# policy-engine — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/policy-engine/eslint.config.js b/packages/policy-engine/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/policy-engine/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/policy-engine/package.json b/packages/policy-engine/package.json new file mode 100644 index 0000000..72feb96 --- /dev/null +++ b/packages/policy-engine/package.json @@ -0,0 +1,22 @@ +{ + "name": "@saas/policy-engine", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*" + } +} diff --git a/packages/policy-engine/src/index.ts b/packages/policy-engine/src/index.ts new file mode 100644 index 0000000..a42ee94 --- /dev/null +++ b/packages/policy-engine/src/index.ts @@ -0,0 +1,402 @@ +import type { + AuthorizationRequest, + AuthorizationResponse, + EffectivePermissionsRequest, + EffectivePermissionsResponse, + EffectivePermission, + RoleAssignmentValidationRequest, + RoleAssignmentValidationResponse, + MembershipFact, + OrganizationRole, + ProjectRole, +} from "@saas/contracts/policy"; + +export { POLICY_VERSION } from "@saas/contracts/policy"; +import { POLICY_VERSION } from "@saas/contracts/policy"; + +const ORG_ROLE_PERMISSIONS: Record = { + owner: [ + "organization.read", + "organization.settings.update", + "organization.invitation.create", + "organization.invitation.list", + "organization.invitation.revoke", + "organization.member.list", + "organization.member.remove", + "organization.member.update_role", + "organization.service_principal.binding.create", + "organization.service_principal.binding.list", + "organization.service_principal.binding.revoke", + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", + "project.create", + "project.list", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "audit.read", + "billing.read", + "billing.manage", + "organization.config.read", + "organization.config.write", + "organization.webhook.read", + "organization.webhook.write", + "project.config.read", + "project.config.write", + "project.webhook.read", + "project.webhook.write", + "organization.metering.read", + "organization.metering.write", + "organization.integration.read", + "organization.integration.connect", + "organization.integration.manage", + "organization.integration.token.issue", + "project.repo_link.write", + ], + admin: [ + "organization.read", + "organization.settings.update", + "organization.invitation.create", + "organization.invitation.list", + "organization.invitation.revoke", + "organization.member.list", + "organization.member.remove", + "organization.member.update_role", + "organization.service_principal.binding.create", + "organization.service_principal.binding.list", + "organization.service_principal.binding.revoke", + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", + "project.create", + "project.list", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "audit.read", + "organization.config.read", + "organization.config.write", + "organization.webhook.read", + "organization.webhook.write", + "project.config.read", + "project.config.write", + "project.webhook.read", + "project.webhook.write", + "organization.metering.read", + "organization.metering.write", + "organization.integration.read", + "organization.integration.connect", + "organization.integration.manage", + "organization.integration.token.issue", + "project.repo_link.write", + ], + builder: [ + "organization.read", + "project.create", + "project.list", + "project.read", + "project.update", + "environment.create", + "environment.read", + "environment.update", + "organization.config.read", + "organization.webhook.read", + "project.config.read", + "project.webhook.read", + "organization.metering.read", + "organization.integration.read", + ], + viewer: [ + "organization.read", + "project.list", + "project.read", + "environment.read", + "organization.config.read", + "organization.webhook.read", + "project.config.read", + "project.webhook.read", + "organization.metering.read", + "organization.integration.read", + ], + billing_admin: [ + "organization.read", + "billing.read", + "billing.manage", + ], +}; + +const PROJECT_ROLE_PERMISSIONS: Record = { + project_admin: [ + "project.repo_link.write", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", + "project.config.read", + "project.config.write", + "project.webhook.read", + "project.webhook.write", + ], + project_builder: [ + "project.read", + "project.update", + "environment.create", + "environment.read", + "environment.update", + "project.config.read", + "project.webhook.read", + ], + project_viewer: [ + "project.read", + "environment.read", + "project.config.read", + "project.webhook.read", + ], +}; + +const VALID_ORG_ROLES: ReadonlySet = new Set([ + "owner", + "admin", + "builder", + "viewer", + "billing_admin", +]); + +const VALID_PROJECT_ROLES: ReadonlySet = new Set([ + "project_admin", + "project_builder", + "project_viewer", +]); + +const PROJECT_SCOPED_ACTIONS: ReadonlySet = new Set([ + "project.repo_link.write", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "project.config.read", + "project.config.write", +]); + +// Actions that project roles can authorize when a projectId narrows the request. +// Unlike PROJECT_SCOPED_ACTIONS, these do NOT require projectId — they are org-level +// actions that project-admin can perform only when explicitly scoped to their project. +const PROJECT_GRANTABLE_ACTIONS: ReadonlySet = new Set([ + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", +]); + +const ALL_KNOWN_ACTIONS: ReadonlySet = new Set([ + "organization.read", + "organization.settings.update", + "organization.invitation.create", + "organization.invitation.list", + "organization.invitation.revoke", + "organization.member.list", + "organization.member.remove", + "organization.member.update_role", + "organization.service_principal.binding.create", + "organization.service_principal.binding.list", + "organization.service_principal.binding.revoke", + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", + "project.create", + "project.list", + "project.read", + "project.update", + "project.delete", + "environment.create", + "environment.read", + "environment.update", + "environment.delete", + "audit.read", + "billing.read", + "billing.manage", + "organization.config.read", + "organization.config.write", + "organization.webhook.read", + "organization.webhook.write", + "project.config.read", + "project.config.write", + "project.webhook.read", + "project.webhook.write", + "organization.metering.read", + "organization.metering.write", + "organization.integration.read", + "organization.integration.connect", + "organization.integration.manage", + "organization.integration.token.issue", + "project.repo_link.write", +]); + +function isOrgRole(role: string): role is OrganizationRole { + return VALID_ORG_ROLES.has(role); +} + +function isProjectRole(role: string): role is ProjectRole { + return VALID_PROJECT_ROLES.has(role); +} + +function isRecord(value: unknown): value is Record { + return value != null && typeof value === "object"; +} + +function isRoleAssignmentFact(fact: unknown): fact is MembershipFact { + if (!isRecord(fact)) return false; + if (fact.kind !== "role_assignment" || typeof fact.role !== "string") return false; + if (!isRecord(fact.scope)) return false; + return typeof fact.scope.kind === "string" && typeof fact.scope.orgId === "string"; +} + +function buildScope(orgId: string, projectId?: string): { orgId: string; projectId?: string } { + if (typeof projectId === "string" && projectId.length > 0) return { orgId, projectId }; + return { orgId }; +} + +function deny(reason: string, orgId: string, projectId?: string): AuthorizationResponse { + return { allow: false, reason, policyVersion: POLICY_VERSION, derivedScope: buildScope(orgId, projectId) }; +} + +function allow(reason: string, orgId: string, projectId?: string): AuthorizationResponse { + return { allow: true, reason, policyVersion: POLICY_VERSION, derivedScope: buildScope(orgId, projectId) }; +} + +export function authorize(input: AuthorizationRequest): AuthorizationResponse { + const { action, resource, context } = input; + const orgId = resource.orgId; + const projectId = typeof resource.projectId === "string" ? resource.projectId : undefined; + + if (!orgId) { + return deny("invalid_scope", ""); + } + + if (!ALL_KNOWN_ACTIONS.has(action)) { + return deny("unknown_action", orgId, projectId); + } + + if (PROJECT_SCOPED_ACTIONS.has(action) && !projectId) { + return deny("invalid_scope", orgId); + } + + const relevantFacts = context.memberships.filter(isRoleAssignmentFact).filter( + (f) => f.scope.orgId === orgId, + ); + + if (relevantFacts.length === 0) { + return deny("no_matching_role", orgId, projectId); + } + + for (const fact of relevantFacts) { + if (fact.scope.kind === "organization" && isOrgRole(fact.role)) { + const permissions = ORG_ROLE_PERMISSIONS[fact.role]; + if (permissions.includes(action)) { + if (PROJECT_SCOPED_ACTIONS.has(action) && projectId) { + return allow(`org_${fact.role}`, orgId, projectId); + } + if (!PROJECT_SCOPED_ACTIONS.has(action) || !projectId) { + return allow(`org_${fact.role}`, orgId, projectId); + } + } + } + + if ( + fact.scope.kind === "project" && + isProjectRole(fact.role) && + (PROJECT_SCOPED_ACTIONS.has(action) || PROJECT_GRANTABLE_ACTIONS.has(action)) + ) { + if (!projectId || fact.scope.projectId !== projectId) { + continue; + } + const permissions = PROJECT_ROLE_PERMISSIONS[fact.role]; + if (permissions.includes(action)) { + return allow(fact.role, orgId, projectId); + } + } + } + + return deny("no_matching_role", orgId, projectId); +} + +export function listEffectivePermissions( + input: EffectivePermissionsRequest, +): EffectivePermissionsResponse { + const { resource, context } = input; + const orgId = resource.orgId; + const projectId = resource.projectId; + + const permissions: EffectivePermission[] = []; + const seen = new Set(); + + for (const action of ALL_KNOWN_ACTIONS) { + if (seen.has(action)) continue; + + const result = authorize({ + subject: input.subject, + action, + resource, + context, + }); + + seen.add(action); + permissions.push({ + action, + allow: result.allow, + reason: result.reason, + }); + } + + return { + permissions, + policyVersion: POLICY_VERSION, + derivedScope: buildScope(orgId, projectId), + }; +} + +export function validateRoleAssignment( + input: RoleAssignmentValidationRequest, +): RoleAssignmentValidationResponse { + const { role, scope } = input; + + if (typeof scope.orgId !== "string" || scope.orgId.length === 0) { + return { valid: false, reason: "missing_org_id", policyVersion: POLICY_VERSION }; + } + + if (scope.kind === "organization") { + if (!VALID_ORG_ROLES.has(role)) { + return { valid: false, reason: "invalid_role_for_scope", policyVersion: POLICY_VERSION }; + } + return { valid: true, reason: "valid_org_role", policyVersion: POLICY_VERSION }; + } + + if (scope.kind === "project") { + if (typeof scope.projectId !== "string" || scope.projectId.length === 0) { + return { valid: false, reason: "missing_project_id", policyVersion: POLICY_VERSION }; + } + if (!VALID_PROJECT_ROLES.has(role)) { + return { valid: false, reason: "invalid_role_for_scope", policyVersion: POLICY_VERSION }; + } + return { valid: true, reason: "valid_project_role", policyVersion: POLICY_VERSION }; + } + + return { valid: false, reason: "unknown_scope_kind", policyVersion: POLICY_VERSION }; +} diff --git a/packages/policy-engine/tsconfig.build.json b/packages/policy-engine/tsconfig.build.json new file mode 100644 index 0000000..4d78c7b --- /dev/null +++ b/packages/policy-engine/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/policy-engine/tsconfig.json b/packages/policy-engine/tsconfig.json new file mode 100644 index 0000000..d84a568 --- /dev/null +++ b/packages/policy-engine/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/sdk/README.md b/packages/sdk/README.md new file mode 100644 index 0000000..d1c4469 --- /dev/null +++ b/packages/sdk/README.md @@ -0,0 +1,177 @@ +# `@saas/sdk` + +new-test TypeScript SDK — typed, dependency-free, runtime-agnostic client +for the new-test control plane API. + +## Install (workspace) + +This package is internal to the `new-test` monorepo. Add it as a +workspace dependency: + +```jsonc +// package.json of a consumer (e.g. apps/web-console, packages/cli) +{ + "dependencies": { + "@saas/sdk": "workspace:*" + } +} +``` + +Then `pnpm install` from the repo root. + +## Getting started + +```ts +import { newtest } from "@saas/sdk"; + +const client = new newtest({ + baseUrl: "https://api.new-test.dev", + auth: { kind: "bearer", token: process.env["NEW_TEST_TOKEN"]! }, +}); + +const { organizations } = await client.organizations.list(); +console.log(organizations); +``` + +## Idempotency + +POST routes accept a caller-owned `Idempotency-Key`. The SDK does **not** +auto-generate one (Stripe parity — the key is opaque to the server and +caller-controlled): + +```ts +import { randomUUID } from "node:crypto"; // or your own source + +const { project } = await client.projects.create( + "org_1", + { name: "Web app" }, + { idempotencyKey: randomUUID() }, +); +``` + +If the create call fails mid-flight, retry with the same key — the api-edge +replay store guarantees no double-create. + +## Error handling + +All non-2xx responses throw a typed subclass of `newtestError`. Branch on +the class (or on `error.code`): + +```ts +import { + RateLimitError, + ValidationError, + newtest, +} from "@saas/sdk"; + +try { + await client.organizations.create({ name: "" }); +} catch (err) { + if (err instanceof ValidationError) { + console.warn("invalid input", err.fields); + } else if (err instanceof RateLimitError) { + console.warn(`back off ${err.retryAfterSeconds}s, scope=${err.scope}`); + console.warn("org window", err.orgWindow); + console.warn("identity window", err.identityWindow); + } else { + throw err; + } +} +``` + +The full hierarchy: + +| Class | `code` | Default status | +| --------------------------- | --------------------- | -------------- | +| `BadRequestError` | `bad_request` | 400 | +| `UnauthenticatedError` | `unauthenticated` | 401 | +| `ForbiddenError` | `forbidden` | 403 | +| `NotFoundError` | `not_found` | 404 | +| `UnsupportedError` | `unsupported` | 405 / 415 | +| `ConflictError` | `conflict` | 409 | +| `PreconditionFailedError` | `precondition_failed` | 412 | +| `ValidationError` | `validation_failed` | 422 | +| `RateLimitError` | `rate_limited` | 429 | +| `InternalError` | `internal_error` | 500+ | +| `newtestError` (base) | _any_ | _any_ | + +Unknown error codes (forward-compatible — e.g. a future `quota_exceeded`) +decode to the base `newtestError` carrying the raw envelope. Non-JSON 5xx +responses (gateway HTML, empty body) decode to `InternalError` with +`message: "HTTP "`. + +## Request options + +Every method accepts a final `RequestOptions` argument: + +| Field | Type | Notes | +| ---------------- | -------------------------- | ------------------------------------------------------- | +| `idempotencyKey` | `string` | Sent as `Idempotency-Key`. Caller-owned. POST only. | +| `signal` | `AbortSignal` | Forwarded to the underlying `fetch`. | +| `requestId` | `string` | Sent as `x-request-id`. Auto-generated when omitted. | +| `headers` | `Record` | Per-request header overrides (last-write-wins). | + +## Environment compatibility + +The SDK is runtime-agnostic. The same source runs on: + +| Runtime | Status | Notes | +| -------------------- | ---------- | ------------------------------------------------------- | +| Browsers (modern) | ✅ Tier 1 | Uses `fetch`, `Headers`, `URL`, `crypto.randomUUID`. | +| Node ≥ 20 | ✅ Tier 1 | Native `fetch` / Web Crypto on the global. | +| Cloudflare Workers | ✅ Tier 1 | No `node:*` imports; pure Web Platform. | +| Bun | ✅ Tier 1 | Native `fetch` + Web Crypto. | + +A custom `fetch` implementation can be injected via `new newtest({ fetch })`. +This is mostly useful for tests; production callers should rely on the platform +global. + +## Resource surface + +This is the pilot surface. Task 0099 will fan out the remaining resource +clients (memberships, api-keys, webhooks, metering, billing, events, +security-events, config, notifications) using the same pattern. + +```ts +client.organizations.list() +client.organizations.get(orgId) +client.organizations.create({ name }, { idempotencyKey }) + +client.projects.list(orgId) +client.projects.get(orgId, projectId) +client.projects.create(orgId, { name }, { idempotencyKey }) +client.projects.archive(orgId, projectId) +``` + +All request / response types are re-exported from this package; consumers do +not need to import `@saas/contracts` directly. + +## Telemetry + +A first-class telemetry hook is **not** in this PR; the transport seam +(`Transport`) is left clean enough that wrapping it with span emission is a +non-breaking follow-up. + +## Testing + +```bash +pnpm --filter @saas/sdk typecheck +pnpm --filter @saas/sdk lint +pnpm --filter @saas/sdk test +``` + +## Constraints (carried from the PR) + +- Zero runtime dependencies (other than the `@saas/contracts` workspace type + re-exports). +- No lint-disable directives, ts-ignore / ts-expect-error escape hatches, or + unsafe casts (Track A/B hazard ban). +- No `node:*` imports. +- No imports from `apps/**` or any worker source. + +## See also + +- `specs/core/contracts/api-guidelines.md` — error envelope, Idempotency-Key, + rate-limit headers, request-id conventions. +- `specs/roadmap.md` — leg B4 (`packages/sdk` + `packages/cli`). +- `packages/contracts/src/errors.ts` — canonical `ERROR_CODES`. diff --git a/packages/sdk/component.yaml b/packages/sdk/component.yaml new file mode 100644 index 0000000..dd8036b --- /dev/null +++ b/packages/sdk/component.yaml @@ -0,0 +1,29 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: sdk + description: Runtime-agnostic TypeScript SDK for the new-test control plane API +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-sdk + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: shared + surface: sdk +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/sdk/docs/architecture.md b/packages/sdk/docs/architecture.md new file mode 100644 index 0000000..dedc0fb --- /dev/null +++ b/packages/sdk/docs/architecture.md @@ -0,0 +1,9 @@ +# sdk — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/sdk`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/sdk/docs/overview.md b/packages/sdk/docs/overview.md new file mode 100644 index 0000000..164ad66 --- /dev/null +++ b/packages/sdk/docs/overview.md @@ -0,0 +1,13 @@ +# sdk + +Runtime-agnostic TypeScript SDK for the new-test control plane API + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/sdk/docs/runbook.md b/packages/sdk/docs/runbook.md new file mode 100644 index 0000000..496e2df --- /dev/null +++ b/packages/sdk/docs/runbook.md @@ -0,0 +1,26 @@ +# sdk — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/sdk/eslint.config.js b/packages/sdk/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/sdk/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/sdk/package.json b/packages/sdk/package.json new file mode 100644 index 0000000..bbc7be1 --- /dev/null +++ b/packages/sdk/package.json @@ -0,0 +1,25 @@ +{ + "name": "@saas/sdk", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./errors": "./src/errors.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "test": "vitest run" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3", + "vitest": "^2.1.9" + }, + "dependencies": { + "@saas/contracts": "workspace:*" + } +} diff --git a/packages/sdk/src/__tests__/auth.test.ts b/packages/sdk/src/__tests__/auth.test.ts new file mode 100644 index 0000000..7453155 --- /dev/null +++ b/packages/sdk/src/__tests__/auth.test.ts @@ -0,0 +1,321 @@ +// Tests for `AuthClient` (Task 0103 — closes the U10 SDK gap). +// +// Coverage: +// - URL shape on every method (loginStart/loginComplete/getSession/logout/ +// getProfile/updateProfile) +// - HTTP verb correctness (POST, GET, PATCH per auth-facade route table) +// - POST/PATCH bodies serialize to JSON +// - Stripe parity: caller-owned idempotency-key passthrough on POSTs +// - Stripe parity: NOT auto-generated when caller omits the key +// - newtestError hierarchy propagation with request-id passthrough +// (Unauthenticated / RateLimit / Validation / Internal) +// - x-request-id surfacing through the envelope (custom requestId opt) + +import { describe, expect, it, vi } from "vitest"; + +import { newtest } from "../index.js"; +import { + InternalError, + RateLimitError, + UnauthenticatedError, + ValidationError, +} from "../errors.js"; + +interface CapturedCall { + url: string; + init: RequestInit; +} + +function captureFetch(response: Response): { + fetch: typeof fetch; + calls: CapturedCall[]; +} { + const calls: CapturedCall[] = []; + const fn: typeof fetch = vi.fn(async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + return response.clone(); + }); + return { fetch: fn, calls }; +} + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { "content-type": "application/json", ...(init.headers ?? {}) }, + }); +} + +function envelope( + data: T, +): { data: T; meta: { requestId: string; cursor: null } } { + return { data, meta: { requestId: "req_test", cursor: null } }; +} + +function errorResponse(code: string, status: number): Response { + return jsonResponse( + { + error: { + code, + message: `synthetic ${code}`, + requestId: "req_err", + }, + }, + { status }, + ); +} + +function client(fetchImpl: typeof fetch): newtest { + return new newtest({ baseUrl: "https://api.test", fetch: fetchImpl }); +} + +describe("AuthClient", () => { + it("loginStart POSTs /v1/auth/login/start with the email body", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + challengeId: "chl_1", + expiresAt: "2026-06-01T00:00:00Z", + delivery: { mode: "local_debug", emailHint: "u@e.com" }, + }), + ), + ); + await client(fetch).auth.loginStart({ email: "u@e.com" }); + const call = calls[0]!; + expect(call.url).toBe("https://api.test/v1/auth/login/start"); + expect(call.init.method).toBe("POST"); + expect(JSON.parse(String(call.init.body))).toEqual({ email: "u@e.com" }); + }); + + it("loginStart propagates the caller-supplied idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + challengeId: "chl_1", + expiresAt: "2026-06-01T00:00:00Z", + delivery: { mode: "local_debug", emailHint: "u@e.com" }, + }), + ), + ); + await client(fetch).auth.loginStart( + { email: "u@e.com" }, + { idempotencyKey: "ikey_login_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_login_1"); + }); + + it("loginStart does NOT auto-generate an idempotency-key when omitted", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + challengeId: "chl_1", + expiresAt: "2026-06-01T00:00:00Z", + delivery: { mode: "local_debug", emailHint: "u@e.com" }, + }), + ), + ); + await client(fetch).auth.loginStart({ email: "u@e.com" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + // Stripe parity: caller-owned only. + expect(headers.get("idempotency-key")).toBeNull(); + }); + + it("loginComplete POSTs /v1/auth/login/complete with the body and returns a token", async () => { + const body = { + token: "tok_abc", + tokenType: "bearer" as const, + expiresAt: "2026-06-01T00:00:00Z", + user: { id: "u_1", email: "u@e.com", displayName: null }, + }; + const { fetch, calls } = captureFetch(jsonResponse(envelope(body))); + const out = await client(fetch).auth.loginComplete({ + challengeId: "chl_1", + code: "123456", + }); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/login/complete"); + expect(calls[0]!.init.method).toBe("POST"); + expect(JSON.parse(String(calls[0]!.init.body))).toEqual({ + challengeId: "chl_1", + code: "123456", + }); + expect(out.token).toBe("tok_abc"); + expect(out.user.id).toBe("u_1"); + }); + + it("loginComplete propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + token: "tok_abc", + tokenType: "bearer", + expiresAt: "2026-06-01T00:00:00Z", + user: { id: "u_1", email: "u@e.com", displayName: null }, + }), + ), + ); + await client(fetch).auth.loginComplete( + { challengeId: "chl_1", code: "123456" }, + { idempotencyKey: "ikey_complete_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_complete_1"); + }); + + it("getSession GETs /v1/auth/session", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + session: { + id: "sess_1", + expiresAt: "2026-06-01T00:00:00Z", + createdAt: "2026-05-31T00:00:00Z", + }, + user: { id: "u_1", email: "u@e.com", displayName: "U" }, + }), + ), + ); + const out = await client(fetch).auth.getSession(); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/session"); + expect(calls[0]!.init.method).toBe("GET"); + expect(out.session.id).toBe("sess_1"); + }); + + it("logout POSTs /v1/auth/logout with no body", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ success: true })), + ); + await client(fetch).auth.logout(); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/logout"); + expect(calls[0]!.init.method).toBe("POST"); + expect(calls[0]!.init.body).toBeUndefined(); + }); + + it("logout propagates idempotency-key when supplied", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ success: true })), + ); + await client(fetch).auth.logout({ idempotencyKey: "ikey_logout_1" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_logout_1"); + }); + + it("getProfile GETs /v1/auth/profile", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + user: { id: "u_1", email: "u@e.com", displayName: "U" }, + }), + ), + ); + const out = await client(fetch).auth.getProfile(); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/profile"); + expect(calls[0]!.init.method).toBe("GET"); + expect(out.user.email).toBe("u@e.com"); + }); + + it("updateProfile PATCHes /v1/auth/profile with the body", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + user: { id: "u_1", email: "u@e.com", displayName: "New Name" }, + }), + ), + ); + const out = await client(fetch).auth.updateProfile({ + displayName: "New Name", + }); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/profile"); + expect(calls[0]!.init.method).toBe("PATCH"); + expect(JSON.parse(String(calls[0]!.init.body))).toEqual({ + displayName: "New Name", + }); + expect(out.user.displayName).toBe("New Name"); + }); + + it("updateProfile accepts a null displayName (clear)", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + user: { id: "u_1", email: "u@e.com", displayName: null }, + }), + ), + ); + await client(fetch).auth.updateProfile({ displayName: null }); + expect(JSON.parse(String(calls[0]!.init.body))).toEqual({ + displayName: null, + }); + }); + + it("getSession surfaces UnauthenticatedError on 401 with request-id", async () => { + const { fetch } = captureFetch(errorResponse("unauthenticated", 401)); + await expect(client(fetch).auth.getSession()).rejects.toMatchObject({ + constructor: UnauthenticatedError, + requestId: "req_err", + }); + }); + + it("loginStart surfaces ValidationError on 422", async () => { + const { fetch } = captureFetch(errorResponse("validation_failed", 422)); + await expect( + client(fetch).auth.loginStart({ email: "" }), + ).rejects.toBeInstanceOf(ValidationError); + }); + + it("loginComplete surfaces RateLimitError on 429", async () => { + const { fetch } = captureFetch(errorResponse("rate_limited", 429)); + await expect( + client(fetch).auth.loginComplete({ challengeId: "chl_x", code: "000000" }), + ).rejects.toBeInstanceOf(RateLimitError); + }); + + it("getProfile surfaces InternalError on 500", async () => { + const { fetch } = captureFetch(errorResponse("internal_error", 500)); + await expect(client(fetch).auth.getProfile()).rejects.toBeInstanceOf( + InternalError, + ); + }); + + it("forwards a caller-supplied requestId via x-request-id", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + user: { id: "u_1", email: "u@e.com", displayName: null }, + }), + ), + ); + await client(fetch).auth.getProfile({ requestId: "req_caller_1" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("x-request-id")).toBe("req_caller_1"); + }); + + it("listOAuthProviders GETs /v1/auth/oauth/providers", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ providers: [{ id: "github", displayName: "GitHub" }] })), + ); + const out = await client(fetch).auth.listOAuthProviders(); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/oauth/providers"); + expect(calls[0]!.init.method).toBe("GET"); + expect(out.providers[0]!.id).toBe("github"); + }); + + it("oauthStartUrl builds an absolute start URL carrying return_to", () => { + const { fetch } = captureFetch(jsonResponse(envelope({ providers: [] }))); + const url = client(fetch).auth.oauthStartUrl("github", "https://console.test/auth/callback"); + const parsed = new URL(url); + expect(`${parsed.origin}${parsed.pathname}`).toBe("https://api.test/v1/auth/oauth/github/start"); + expect(parsed.searchParams.get("return_to")).toBe("https://console.test/auth/callback"); + }); + + it("client.auth is wired onto the newtest class", () => { + const { fetch } = captureFetch(jsonResponse(envelope({ success: true }))); + const c = client(fetch); + expect(typeof c.auth.loginStart).toBe("function"); + expect(typeof c.auth.loginComplete).toBe("function"); + expect(typeof c.auth.getSession).toBe("function"); + expect(typeof c.auth.logout).toBe("function"); + expect(typeof c.auth.getProfile).toBe("function"); + expect(typeof c.auth.updateProfile).toBe("function"); + expect(typeof c.auth.listOAuthProviders).toBe("function"); + expect(typeof c.auth.oauthStartUrl).toBe("function"); + }); +}); diff --git a/packages/sdk/src/__tests__/environments.test.ts b/packages/sdk/src/__tests__/environments.test.ts new file mode 100644 index 0000000..a352764 --- /dev/null +++ b/packages/sdk/src/__tests__/environments.test.ts @@ -0,0 +1,187 @@ +// Tests for `EnvironmentsClient` (Task 0102 — closes Task 0101 spec gap). +// +// Coverage: +// - URL shape on every method (list/get/create/archive) +// - encodeURIComponent on dynamic segments (org / project / environment id) +// - Stripe parity: idempotency-key passthrough on create + archive +// - Stripe parity NOT auto-generated when caller omits the key +// - newtestError hierarchy propagation with request-id passthrough + +import { describe, expect, it, vi } from "vitest"; + +import { newtest } from "../index.js"; +import { ConflictError, NotFoundError, ValidationError } from "../errors.js"; + +interface CapturedCall { + url: string; + init: RequestInit; +} + +function captureFetch(response: Response): { + fetch: typeof fetch; + calls: CapturedCall[]; +} { + const calls: CapturedCall[] = []; + const fn: typeof fetch = vi.fn(async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + return response.clone(); + }); + return { fetch: fn, calls }; +} + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { "content-type": "application/json", ...(init.headers ?? {}) }, + }); +} + +function envelope( + data: T, +): { data: T; meta: { requestId: string; cursor: null } } { + return { data, meta: { requestId: "req_test", cursor: null } }; +} + +function errorResponse(code: string, status: number): Response { + return jsonResponse( + { + error: { + code, + message: `synthetic ${code}`, + details: { fields: { name: ["already_taken"] } }, + requestId: "req_err", + }, + }, + { status }, + ); +} + +function client(fetchImpl: typeof fetch): newtest { + return new newtest({ baseUrl: "https://api.test", fetch: fetchImpl }); +} + +describe("EnvironmentsClient", () => { + it("list hits the project-scoped environments path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environments: [] })), + ); + await client(fetch).environments.list("org_1", "prj_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments", + ); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("list encodeURIComponent-encodes dynamic segments", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environments: [] })), + ); + // Org/project ids that need encoding (slash, space) prove the SDK does + // not concatenate raw — guards against a future refactor that drops the + // encoder. + await client(fetch).environments.list("org with space", "prj/slash"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org%20with%20space/projects/prj%2Fslash/environments", + ); + }); + + it("get hits the environment-scoped path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} })), + ); + await client(fetch).environments.get("org_1", "prj_1", "env_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments/env_1", + ); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("get encodeURIComponent-encodes the env id", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} })), + ); + await client(fetch).environments.get("org_1", "prj_1", "env id/x"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments/env%20id%2Fx", + ); + }); + + it("create POSTs the body and propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} }), { status: 201 }), + ); + await client(fetch).environments.create( + "org_1", + "prj_1", + { name: "staging" }, + { idempotencyKey: "ikey_env_1" }, + ); + const call = calls[0]!; + expect(call.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments", + ); + expect(call.init.method).toBe("POST"); + expect(JSON.parse(String(call.init.body))).toEqual({ name: "staging" }); + const headers = new Headers(call.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_env_1"); + }); + + it("create does NOT auto-generate an idempotency-key when omitted", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} }), { status: 201 }), + ); + await client(fetch).environments.create("org_1", "prj_1", { name: "staging" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + // Stripe parity: caller-owned only. + expect(headers.get("idempotency-key")).toBeNull(); + }); + + it("archive issues DELETE on the env-scoped path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} })), + ); + await client(fetch).environments.archive("org_1", "prj_1", "env_42"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/prj_1/environments/env_42", + ); + expect(calls[0]!.init.method).toBe("DELETE"); + }); + + it("archive propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ environment: {} })), + ); + await client(fetch).environments.archive( + "org_1", + "prj_1", + "env_42", + { idempotencyKey: "ikey_arc_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_arc_1"); + }); + + it("create surfaces ValidationError on 422 with request-id", async () => { + const { fetch } = captureFetch(errorResponse("validation_failed", 422)); + await expect( + client(fetch).environments.create("org_1", "prj_1", { name: "" }), + ).rejects.toMatchObject({ + constructor: ValidationError, + requestId: "req_err", + }); + }); + + it("get surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).environments.get("org_1", "prj_1", "env_x"), + ).rejects.toBeInstanceOf(NotFoundError); + }); + + it("create surfaces ConflictError on 409", async () => { + const { fetch } = captureFetch(errorResponse("conflict", 409)); + await expect( + client(fetch).environments.create("org_1", "prj_1", { name: "staging" }), + ).rejects.toBeInstanceOf(ConflictError); + }); +}); diff --git a/packages/sdk/src/__tests__/events.test.ts b/packages/sdk/src/__tests__/events.test.ts new file mode 100644 index 0000000..645dd0f --- /dev/null +++ b/packages/sdk/src/__tests__/events.test.ts @@ -0,0 +1,289 @@ +// Tests for `EventsClient.iterAuditEntries` async iterator (Task 0102 — +// closes Task 0101 audit-pagination spec gap). +// +// The single-page `listAuditEntries` primitive is already covered in +// `resources.test.ts`; this file focuses on the new iterator's +// multi-page consumption + loop guards. + +import { describe, expect, it, vi } from "vitest"; + +import { newtest, AUDIT_ITERATOR_MAX_PAGES } from "../index.js"; +import type { PublicAuditEntry } from "@saas/contracts/events"; + +interface PageMeta { + cursor: string | null; +} + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { "content-type": "application/json", ...(init.headers ?? {}) }, + }); +} + +/** + * Build a fetch responder that serves the supplied pages in order. Each call + * advances to the next page; once the array is exhausted the responder + * throws (signals "iterator should have stopped"). + */ +function pageResponder( + pages: ReadonlyArray<{ + entries: ReadonlyArray>; + meta: PageMeta; + }>, +): { fetch: typeof fetch; calls: { url: string; init: RequestInit }[] } { + const calls: { url: string; init: RequestInit }[] = []; + let i = 0; + const fn: typeof fetch = vi.fn(async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + if (i >= pages.length) { + throw new Error( + `pageResponder: iterator made an unexpected request (i=${i}, pages=${pages.length}, url=${String(input)})`, + ); + } + const page = pages[i]!; + i += 1; + return jsonResponse({ + data: { auditEntries: page.entries }, + meta: { requestId: `req_${i}`, cursor: page.meta.cursor }, + }); + }); + return { fetch: fn, calls }; +} + +function entry(id: string, occurredAt: string): Partial { + return { + id, + eventType: "test.event", + category: "test", + occurredAt, + actorType: "user", + actorId: "usr_a", + }; +} + +function client(fetchImpl: typeof fetch): newtest { + return new newtest({ baseUrl: "https://api.test", fetch: fetchImpl }); +} + +describe("EventsClient.iterAuditEntries", () => { + it("walks ≥ 2 pages via for await and preserves server order", async () => { + const { fetch, calls } = pageResponder([ + { + entries: [entry("ae_1", "2025-01-01T00:00:00Z"), entry("ae_2", "2025-01-02T00:00:00Z")], + meta: { cursor: "cur_2" }, + }, + { + entries: [entry("ae_3", "2025-01-03T00:00:00Z")], + meta: { cursor: null }, + }, + ]); + const collected: string[] = []; + for await (const e of client(fetch).events.iterAuditEntries("org_1")) { + collected.push(e.id); + } + expect(collected).toEqual(["ae_1", "ae_2", "ae_3"]); + expect(calls).toHaveLength(2); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_1/audit"); + expect(calls[1]!.url).toContain("cursor=cur_2"); + }); + + it("terminates after a single page when cursor is null on the first response", async () => { + const { fetch, calls } = pageResponder([ + { entries: [entry("ae_only", "2025-01-01T00:00:00Z")], meta: { cursor: null } }, + ]); + const ids: string[] = []; + for await (const e of client(fetch).events.iterAuditEntries("org_1")) { + ids.push(e.id); + } + expect(ids).toEqual(["ae_only"]); + expect(calls).toHaveLength(1); + }); + + it("terminates when cursor is undefined (server omits the field)", async () => { + const fn: typeof fetch = vi.fn( + async () => + jsonResponse({ + data: { auditEntries: [entry("ae_x", "2025-01-01T00:00:00Z")] }, + meta: { requestId: "req_x" }, // no cursor field at all + }), + ); + const ids: string[] = []; + for await (const e of client(fn).events.iterAuditEntries("org_1")) { + ids.push(e.id); + } + expect(ids).toEqual(["ae_x"]); + }); + + it("forwards by:org category + limit on every page request", async () => { + const { fetch, calls } = pageResponder([ + { entries: [], meta: { cursor: "cur_2" } }, + { entries: [], meta: { cursor: null } }, + ]); + const it = client(fetch).events.iterAuditEntries("org_1", { + by: "org", + category: "membership", + limit: 25, + }); + for await (const _e of it) { + void _e; + } + expect(calls).toHaveLength(2); + for (const c of calls) { + expect(c.url).toContain("category=membership"); + expect(c.url).toContain("limit=25"); + } + expect(calls[1]!.url).toContain("cursor=cur_2"); + }); + + it("forwards by:target subjectKind+subjectId on every page request", async () => { + const { fetch, calls } = pageResponder([ + { entries: [], meta: { cursor: "cur_2" } }, + { entries: [], meta: { cursor: null } }, + ]); + const it = client(fetch).events.iterAuditEntries("org_1", { + by: "target", + subjectKind: "project", + subjectId: "prj_1", + }); + for await (const _e of it) { + void _e; + } + expect(calls).toHaveLength(2); + for (const c of calls) { + expect(c.url).toContain("subjectKind=project"); + expect(c.url).toContain("subjectId=prj_1"); + } + }); + + it("aborts with a clear error when the server returns a repeated cursor", async () => { + // Page 1 returns cursor "cur_X"; page 2 returns the SAME cursor — server + // is misbehaving / cycling. The iterator must throw rather than loop. + const { fetch } = pageResponder([ + { entries: [entry("ae_1", "2025-01-01T00:00:00Z")], meta: { cursor: "cur_X" } }, + { entries: [entry("ae_2", "2025-01-02T00:00:00Z")], meta: { cursor: "cur_X" } }, + ]); + const collected: string[] = []; + await expect( + (async () => { + for await (const e of client(fetch).events.iterAuditEntries("org_1")) { + collected.push(e.id); + } + })(), + ).rejects.toThrow(/repeated cursor/); + // The iterator yields page 1's entries, then on the next refill it + // fetches page 2, sees the repeated cursor, and throws BEFORE yielding + // any of page 2's entries. So only `ae_1` is observed by the caller. + expect(collected).toEqual(["ae_1"]); + }); + + it("propagates a fetch error mid-iteration (abort-on-error)", async () => { + let i = 0; + const fn: typeof fetch = vi.fn(async () => { + i += 1; + if (i === 1) { + return jsonResponse({ + data: { auditEntries: [entry("ae_1", "2025-01-01T00:00:00Z")] }, + meta: { requestId: "req_1", cursor: "cur_2" }, + }); + } + throw new Error("network down"); + }); + const collected: string[] = []; + await expect( + (async () => { + for await (const e of client(fn).events.iterAuditEntries("org_1")) { + collected.push(e.id); + } + })(), + ).rejects.toThrow(/network down/); + expect(collected).toEqual(["ae_1"]); + }); + + it("exposes a sane page cap so a runaway server cannot loop indefinitely", () => { + // Sanity-check: the cap is exported and ≥ 1000 (per Task 0102 contract). + expect(AUDIT_ITERATOR_MAX_PAGES).toBeGreaterThanOrEqual(1000); + }); + + it("forwards by:org filter params on every page request", async () => { + const { fetch, calls } = pageResponder([ + { entries: [], meta: { cursor: "cur_2" } }, + { entries: [], meta: { cursor: null } }, + ]); + const it = client(fetch).events.iterAuditEntries("org_1", { + by: "org", + actorId: "usr_a", + actorType: "user", + subjectKind: "project", + subjectId: "prj_1", + eventType: "member.role_changed", + from: "2026-01-01T00:00:00.000Z", + to: "2026-02-01T00:00:00.000Z", + }); + for await (const _e of it) { + void _e; + } + expect(calls).toHaveLength(2); + for (const c of calls) { + expect(c.url).toContain("actorId=usr_a"); + expect(c.url).toContain("actorType=user"); + expect(c.url).toContain("subjectKind=project"); + expect(c.url).toContain("subjectId=prj_1"); + expect(c.url).toContain("eventType=member.role_changed"); + expect(c.url).toContain("from=2026-01-01T00%3A00%3A00.000Z"); + expect(c.url).toContain("to=2026-02-01T00%3A00%3A00.000Z"); + } + expect(calls[1]!.url).toContain("cursor=cur_2"); + }); +}); + +describe("EventsClient.exportAuditEntriesNdjson", () => { + it("yields one NDJSON line per entry across pages", async () => { + const { fetch } = pageResponder([ + { + entries: [entry("ae_1", "2025-01-01T00:00:00Z"), entry("ae_2", "2025-01-02T00:00:00Z")], + meta: { cursor: "cur_2" }, + }, + { entries: [entry("ae_3", "2025-01-03T00:00:00Z")], meta: { cursor: null } }, + ]); + const lines: string[] = []; + for await (const line of client(fetch).events.exportAuditEntriesNdjson("org_1")) { + lines.push(line); + } + expect(lines).toHaveLength(3); + // Each line is a standalone JSON document terminated by a newline. + for (const line of lines) { + expect(line.endsWith("\n")).toBe(true); + const parsed = JSON.parse(line.trimEnd()); + expect(typeof parsed.id).toBe("string"); + } + expect(JSON.parse(lines[0]!.trimEnd()).id).toBe("ae_1"); + expect(JSON.parse(lines[2]!.trimEnd()).id).toBe("ae_3"); + }); + + it("forwards filters into the export stream", async () => { + const { fetch, calls } = pageResponder([ + { entries: [entry("ae_1", "2025-01-01T00:00:00Z")], meta: { cursor: null } }, + ]); + const lines: string[] = []; + for await (const line of client(fetch).events.exportAuditEntriesNdjson("org_1", { + by: "org", + actorType: "service_principal", + from: "2026-01-01T00:00:00.000Z", + })) { + lines.push(line); + } + expect(lines).toHaveLength(1); + expect(calls[0]!.url).toContain("actorType=service_principal"); + expect(calls[0]!.url).toContain("from=2026-01-01T00%3A00%3A00.000Z"); + }); + + it("yields nothing for an empty result set", async () => { + const { fetch } = pageResponder([{ entries: [], meta: { cursor: null } }]); + const lines: string[] = []; + for await (const line of client(fetch).events.exportAuditEntriesNdjson("org_1")) { + lines.push(line); + } + expect(lines).toEqual([]); + }); +}); diff --git a/packages/sdk/src/__tests__/resources.test.ts b/packages/sdk/src/__tests__/resources.test.ts new file mode 100644 index 0000000..5e14a63 --- /dev/null +++ b/packages/sdk/src/__tests__/resources.test.ts @@ -0,0 +1,734 @@ +// Tests for the 9 fanned-out resource clients added in Task 0099. +// +// Coverage strategy per resource (mirrors the orgs/projects pilot in +// `sdk.test.ts`): one URL-shape test, one idempotency-key passthrough test +// (when the resource has a POST that accepts one), and one error-decoding +// test that the typed error subclass propagates. + +import { describe, expect, it, vi } from "vitest"; + +import { newtest } from "../index.js"; +import { + ConflictError, + ForbiddenError, + NotFoundError, + ValidationError, +} from "../errors.js"; + +interface CapturedCall { + url: string; + init: RequestInit; +} + +function captureFetch(response: Response): { + fetch: typeof fetch; + calls: CapturedCall[]; +} { + const calls: CapturedCall[] = []; + const fn: typeof fetch = vi.fn(async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + return response.clone(); + }); + return { fetch: fn, calls }; +} + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { + "content-type": "application/json", + ...(init.headers ?? {}), + }, + }); +} + +function envelope(data: T): { data: T; meta: { requestId: string; cursor: null } } { + return { data, meta: { requestId: "req_test", cursor: null } }; +} + +function errorResponse(code: string, status: number): Response { + return jsonResponse( + { + error: { + code, + message: `synthetic ${code}`, + details: { fields: { foo: ["bar"] } }, + requestId: "req_err", + }, + }, + { status }, + ); +} + +type FetchImpl = typeof fetch; + +function client(fetchImpl: FetchImpl): newtest { + return new newtest({ baseUrl: "https://api.test", fetch: fetchImpl }); +} + +// --------------------------------------------------------------------------- +// Memberships +// --------------------------------------------------------------------------- + +describe("MembershipsClient", () => { + it("listMembers hits the org-scoped members path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ members: [] }))); + await client(fetch).memberships.listMembers("org_1"); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_1/members"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("createInvitation propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ invitation: {} }), { status: 201 }), + ); + await client(fetch).memberships.createInvitation( + "org_1", + { email: "a@b.test", role: "viewer" }, + { idempotencyKey: "ikey_inv_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_inv_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/invitations", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("acceptInvitation issues POST on the accept path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ invitation: {}, membership: {} })), + ); + await client(fetch).memberships.acceptInvitation("org_1", { token: "tok_x" }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/invitations/accept", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("removeMember surfaces ForbiddenError on 403", async () => { + const { fetch } = captureFetch(errorResponse("forbidden", 403)); + await expect( + client(fetch).memberships.removeMember("org_1", "mem_1"), + ).rejects.toBeInstanceOf(ForbiddenError); + }); +}); + +// --------------------------------------------------------------------------- +// API keys +// --------------------------------------------------------------------------- + +describe("ApiKeysClient", () => { + it("list hits the org-scoped api-keys path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ apiKeys: [] }))); + await client(fetch).apiKeys.list("org_1"); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_1/api-keys"); + }); + + it("create propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ apiKey: {} }), { status: 201 }), + ); + await client(fetch).apiKeys.create( + "org_1", + { label: "ci", role: "viewer" }, + { idempotencyKey: "ikey_ak_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_ak_1"); + }); + + it("revoke issues DELETE on the scoped path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ apiKey: {} }))); + await client(fetch).apiKeys.revoke("org_1", "ak_42"); + expect(calls[0]!.init.method).toBe("DELETE"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/api-keys/ak_42", + ); + }); + + it("get surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect(client(fetch).apiKeys.get("org_1", "ak_x")).rejects.toBeInstanceOf( + NotFoundError, + ); + }); +}); + +// --------------------------------------------------------------------------- +// Webhooks +// --------------------------------------------------------------------------- + +describe("WebhooksClient", () => { + it("listEndpoints hits the org-scoped endpoints path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ endpoints: [], nextCursor: null })), + ); + await client(fetch).webhooks.listEndpoints("org_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/endpoints", + ); + }); + + it("listProjectEndpoints hits the project-scoped surface", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ endpoints: [], nextCursor: null })), + ); + await client(fetch).webhooks.listProjectEndpoints("org_1", "proj_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/proj_1/webhooks/endpoints", + ); + }); + + it("createEndpoint propagates idempotency-key on org scope", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ endpoint: {} }), { status: 201 }), + ); + await client(fetch).webhooks.createEndpoint( + "org_1", + { url: "https://hook.test" }, + { idempotencyKey: "ikey_wh_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_wh_1"); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("rotateSecret hits the rotate-secret subpath as POST", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ endpoint: {} }))); + await client(fetch).webhooks.rotateSecret("org_1", "wh_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/endpoints/wh_1/rotate-secret", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("enableEndpoint hits the enable subpath as POST with empty body", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ endpoint: { status: "active" } }))); + await client(fetch).webhooks.enableEndpoint("org_1", "wh_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/endpoints/wh_1/enable", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("enableEndpoint surfaces NotFoundError on 404 (already-active or missing)", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).webhooks.enableEndpoint("org_1", "wh_missing"), + ).rejects.toBeInstanceOf(NotFoundError); + }); + + it("getDeliveryAttempt surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).webhooks.getDeliveryAttempt("org_1", "att_x"), + ).rejects.toBeInstanceOf(NotFoundError); + }); + + it("listDeliveryAttempts hits the endpoint-scoped path with no query when none given", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ deliveryAttempts: [], nextCursor: null })), + ); + await client(fetch).webhooks.listDeliveryAttempts("org_1", "wh_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/endpoints/wh_1/delivery-attempts", + ); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("listDeliveryAttempts threads limit + cursor into the query string", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ deliveryAttempts: [], nextCursor: null })), + ); + await client(fetch).webhooks.listDeliveryAttempts("org_1", "wh_1", { + limit: 25, + cursor: "CURSOR_TOKEN_ABC", + }); + const url = new URL(calls[0]!.url); + expect(url.pathname).toBe( + "/v1/organizations/org_1/webhooks/endpoints/wh_1/delivery-attempts", + ); + expect(url.searchParams.get("limit")).toBe("25"); + expect(url.searchParams.get("cursor")).toBe("CURSOR_TOKEN_ABC"); + }); + + it("listDeliveryAttempts omits limit/cursor when only one is supplied", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ deliveryAttempts: [], nextCursor: null })), + ); + await client(fetch).webhooks.listDeliveryAttempts("org_1", "wh_1", { + limit: 10, + }); + const url = new URL(calls[0]!.url); + expect(url.searchParams.get("limit")).toBe("10"); + expect(url.searchParams.has("cursor")).toBe(false); + }); + + it("listDeliveryAttemptsPage round-trips meta.cursor as nextCursor", async () => { + const { fetch } = captureFetch( + jsonResponse({ + data: { deliveryAttempts: [{ id: "att_1" }], nextCursor: null }, + meta: { requestId: "req_test", cursor: "NEXT_PAGE_CURSOR" }, + }), + ); + const page = await client(fetch).webhooks.listDeliveryAttemptsPage( + "org_1", + "wh_1", + { limit: 1 }, + ); + expect(page.deliveryAttempts).toHaveLength(1); + expect(page.nextCursor).toBe("NEXT_PAGE_CURSOR"); + }); + + it("listDeliveryAttemptsPage returns nextCursor null on the last page", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ deliveryAttempts: [], nextCursor: null })), + ); + const page = await client(fetch).webhooks.listDeliveryAttemptsPage( + "org_1", + "wh_1", + { cursor: "PREV_CURSOR" }, + ); + expect(page.nextCursor).toBeNull(); + // The supplied cursor was forwarded as the request query param. + expect(new URL(calls[0]!.url).searchParams.get("cursor")).toBe("PREV_CURSOR"); + }); + + it("replayDelivery hits the replay subpath as POST with empty body", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ deliveryAttempt: { id: "whd_new", status: "success" } }), + { status: 201 }, + ), + ); + const res = await client(fetch).webhooks.replayDelivery("org_1", "whd_old"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/webhooks/delivery-attempts/whd_old/replay", + ); + expect(calls[0]!.init.method).toBe("POST"); + expect(res.deliveryAttempt.id).toBe("whd_new"); + }); + + it("replayDelivery propagates an idempotency-key when supplied", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ deliveryAttempt: { id: "whd_new" } }), { + status: 201, + }), + ); + await client(fetch).webhooks.replayDelivery("org_1", "whd_old", { + idempotencyKey: "ikey_replay_1", + }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_replay_1"); + }); + + it("replayDelivery surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).webhooks.replayDelivery("org_1", "whd_missing"), + ).rejects.toBeInstanceOf(NotFoundError); + }); +}); + +// --------------------------------------------------------------------------- +// Metering +// --------------------------------------------------------------------------- + +describe("MeteringClient", () => { + it("recordUsage hits the org-scoped usage path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ usageRecord: {} }), { status: 201 }), + ); + await client(fetch).metering.recordUsage("org_1", { + metric: "api_requests", + idempotencyKey: "u_1", + }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/usage", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("ingestUsageBatch propagates idempotency-key header", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ results: [] }))); + await client(fetch).metering.ingestUsageBatch( + "org_1", + { records: [] }, + { idempotencyKey: "ikey_batch_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_batch_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/usage/batch", + ); + }); + + it("getUsageSummary builds query string from filters", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + metric: "api_requests", + totalQuantity: 0, + totalRecords: 0, + rollups: [], + }), + ), + ); + await client(fetch).metering.getUsageSummary("org_1", { + metric: "api_requests", + bucketType: "day", + projectId: "proj_1", + }); + expect(calls[0]!.url).toContain("/usage/summary"); + expect(calls[0]!.url).toContain("metric=api_requests"); + expect(calls[0]!.url).toContain("bucketType=day"); + expect(calls[0]!.url).toContain("projectId=proj_1"); + }); + + it("checkQuota surfaces ValidationError on 422", async () => { + const { fetch } = captureFetch(errorResponse("validation_failed", 422)); + await expect( + client(fetch).metering.checkQuota("org_1", { metric: "x" }), + ).rejects.toBeInstanceOf(ValidationError); + }); +}); + +// --------------------------------------------------------------------------- +// Billing +// --------------------------------------------------------------------------- + +describe("BillingClient", () => { + it("listPlans hits the org-scoped plans path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ plans: [] }))); + await client(fetch).billing.listPlans("org_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/billing/plans", + ); + }); + + it("listInvoices forwards cursor and status filters", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ invoices: [], nextCursor: null })), + ); + await client(fetch).billing.listInvoices("org_1", { + status: "open", + limit: 25, + }); + expect(calls[0]!.url).toContain("status=open"); + expect(calls[0]!.url).toContain("limit=25"); + }); + + it("checkEntitlement issues POST on the entitlements/check path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + envelope({ + allowed: false, + orgId: "org_1", + entitlementKey: "feature.x", + reason: "not_configured", + }), + ), + ); + await client(fetch).billing.checkEntitlement("org_1", { + entitlementKey: "feature.x", + }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/billing/entitlements/check", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("getSummary surfaces ForbiddenError on 403", async () => { + const { fetch } = captureFetch(errorResponse("forbidden", 403)); + await expect(client(fetch).billing.getSummary("org_1")).rejects.toBeInstanceOf( + ForbiddenError, + ); + }); +}); + +// --------------------------------------------------------------------------- +// Events (audit) +// --------------------------------------------------------------------------- + +describe("EventsClient", () => { + it("listAuditEntries (by:org) hits the org-scoped audit path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ auditEntries: [] })), + ); + await client(fetch).events.listAuditEntries("org_1", { + by: "org", + category: "authz", + limit: 50, + }); + expect(calls[0]!.url).toContain( + "https://api.test/v1/organizations/org_1/audit", + ); + expect(calls[0]!.url).toContain("category=authz"); + expect(calls[0]!.url).toContain("limit=50"); + }); + + it("listAuditEntries (by:target) sends subjectKind+subjectId", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ auditEntries: [] })), + ); + await client(fetch).events.listAuditEntries("org_1", { + by: "target", + subjectKind: "project", + subjectId: "proj_1", + }); + expect(calls[0]!.url).toContain("subjectKind=project"); + expect(calls[0]!.url).toContain("subjectId=proj_1"); + }); + + it("listAuditEntries surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).events.listAuditEntries("org_x"), + ).rejects.toBeInstanceOf(NotFoundError); + }); +}); + +// --------------------------------------------------------------------------- +// Security events +// --------------------------------------------------------------------------- + +describe("SecurityEventsClient", () => { + it("list hits /v1/auth/security-events", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ securityEvents: [] })), + ); + await client(fetch).securityEvents.list(); + expect(calls[0]!.url).toBe("https://api.test/v1/auth/security-events"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("list threads limit + opaque cursor into the query verbatim", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ securityEvents: [] })), + ); + const opaque = "eyJjcm...2In0="; + await client(fetch).securityEvents.list({ limit: 25, cursor: opaque }); + expect(calls[0]!.url).toContain("limit=25"); + expect(calls[0]!.url).toContain(`cursor=${encodeURIComponent(opaque)}`); + }); + + it("listPage surfaces meta.cursor as nextCursor", async () => { + const { fetch } = captureFetch( + jsonResponse({ + data: { securityEvents: [{ id: "se_1" }] }, + meta: { requestId: "req_1", cursor: "CUR_NEXT" }, + }), + ); + const page = await client(fetch).securityEvents.listPage(); + expect(page.securityEvents).toHaveLength(1); + expect(page.nextCursor).toBe("CUR_NEXT"); + }); + + it("listPage returns nextCursor null when the server omits meta.cursor", async () => { + const { fetch } = captureFetch( + jsonResponse({ + data: { securityEvents: [] }, + meta: { requestId: "req_1" }, + }), + ); + const page = await client(fetch).securityEvents.listPage(); + expect(page.nextCursor).toBeNull(); + }); + + it("listPage forwards the opaque cursor verbatim on the follow-up page", async () => { + const { fetch, calls } = captureFetch( + jsonResponse({ + data: { securityEvents: [] }, + meta: { requestId: "req_1", cursor: null }, + }), + ); + const opaque = "eyJvZmZzZXQ...In0="; + await client(fetch).securityEvents.listPage({ cursor: opaque }); + expect(calls[0]!.url).toContain(`cursor=${encodeURIComponent(opaque)}`); + }); + + it("surfaces ForbiddenError on 403", async () => { + const { fetch } = captureFetch(errorResponse("forbidden", 403)); + await expect(client(fetch).securityEvents.list()).rejects.toBeInstanceOf( + ForbiddenError, + ); + }); +}); + +// --------------------------------------------------------------------------- +// Config (settings / feature-flags / secrets across 3 scopes) +// --------------------------------------------------------------------------- + +describe("ConfigClient", () => { + it("listSettings (organization scope) hits org config path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ settings: [] }))); + await client(fetch).config.listSettings({ kind: "organization", orgId: "org_1" }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/config/settings", + ); + }); + + it("listSettings (project scope) hits project config path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ settings: [] }))); + await client(fetch).config.listSettings({ + kind: "project", + orgId: "org_1", + projectId: "proj_1", + }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/proj_1/config/settings", + ); + }); + + it("listSettings (environment scope) hits env config path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ settings: [] }))); + await client(fetch).config.listSettings({ + kind: "environment", + orgId: "org_1", + projectId: "proj_1", + environmentId: "env_1", + }); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/proj_1/environments/env_1/config/settings", + ); + }); + + it("createFeatureFlag propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ featureFlag: {} }), { status: 201 }), + ); + await client(fetch).config.createFeatureFlag( + { kind: "organization", orgId: "org_1" }, + { flagKey: "x", enabled: true }, + { idempotencyKey: "ikey_ff_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_ff_1"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/config/feature-flags", + ); + }); + + it("rotateSecret hits the rotate subpath as POST (env scope)", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ secret: {} }))); + await client(fetch).config.rotateSecret( + { + kind: "environment", + orgId: "org_1", + projectId: "proj_1", + environmentId: "env_1", + }, + "DATABASE_URL", + { value: "new-value-redacted-from-test" }, + ); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/proj_1/environments/env_1/config/secrets/DATABASE_URL/rotate", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("revokeSecret issues DELETE on the scoped secret path", async () => { + const { fetch, calls } = captureFetch(jsonResponse(envelope({ secret: {} }))); + await client(fetch).config.revokeSecret( + { kind: "organization", orgId: "org_1" }, + "API_KEY", + ); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/config/secrets/API_KEY", + ); + expect(calls[0]!.init.method).toBe("DELETE"); + }); + + it("createSetting surfaces ConflictError on 409", async () => { + const { fetch } = captureFetch(errorResponse("conflict", 409)); + await expect( + client(fetch).config.createSetting( + { kind: "organization", orgId: "org_1" }, + { key: "x", value: 1 }, + ), + ).rejects.toBeInstanceOf(ConflictError); + }); +}); + +// --------------------------------------------------------------------------- +// Notifications +// --------------------------------------------------------------------------- + +describe("NotificationsClient", () => { + it("enqueue hits /v1/notifications as POST", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ notification: {} }), { status: 201 }), + ); + await client(fetch).notifications.enqueue({ + orgId: "org_1", + category: "billing", + templateKey: "billing.receipt", + recipient: { channel: "email", address: "a@b.test" }, + }); + expect(calls[0]!.url).toBe("https://api.test/v1/notifications"); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("enqueue propagates idempotency-key", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ notification: {} }), { status: 201 }), + ); + await client(fetch).notifications.enqueue( + { + orgId: "org_1", + category: "invitation", + templateKey: "invitation.created", + recipient: { channel: "email", address: "a@b.test" }, + }, + { idempotencyKey: "ikey_n_1" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_n_1"); + }); + + it("get fetches a notification by id", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ notification: {} })), + ); + await client(fetch).notifications.get("notif_42"); + expect(calls[0]!.url).toBe("https://api.test/v1/notifications/notif_42"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("updatePreferences issues PUT on preferences path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ preference: {} })), + ); + await client(fetch).notifications.updatePreferences({ + orgId: "org_1", + subjectKind: "user", + subjectId: "user_1", + channel: "email", + categories: { billing: true }, + }); + expect(calls[0]!.url).toBe("https://api.test/v1/notifications/preferences"); + expect(calls[0]!.init.method).toBe("PUT"); + }); + + it("suppressRecipient hits the recipients suppress path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse(envelope({ suppression: {} })), + ); + await client(fetch).notifications.suppressRecipient( + "a@b.test", + { orgId: "org_1", channel: "email", reason: "bounce" }, + ); + expect(calls[0]!.url).toBe( + "https://api.test/v1/notifications/recipients/a%40b.test/suppress", + ); + expect(calls[0]!.init.method).toBe("POST"); + }); + + it("get surfaces NotFoundError on 404", async () => { + const { fetch } = captureFetch(errorResponse("not_found", 404)); + await expect( + client(fetch).notifications.get("missing"), + ).rejects.toBeInstanceOf(NotFoundError); + }); +}); diff --git a/packages/sdk/src/__tests__/sdk.test.ts b/packages/sdk/src/__tests__/sdk.test.ts new file mode 100644 index 0000000..af1689a --- /dev/null +++ b/packages/sdk/src/__tests__/sdk.test.ts @@ -0,0 +1,441 @@ +import { describe, expect, it, vi } from "vitest"; + +import { newtest } from "../index.js"; +import { + BadRequestError, + ConflictError, + ForbiddenError, + InternalError, + NotFoundError, + PreconditionFailedError, + RateLimitError, + newtestError, + UnauthenticatedError, + UnsupportedError, + ValidationError, +} from "../errors.js"; +import { generateRequestId, Transport } from "../transport.js"; + +interface CapturedCall { + url: string; + init: RequestInit; +} + +function captureFetch(response: Response): { + fetch: typeof fetch; + calls: CapturedCall[]; +} { + const calls: CapturedCall[] = []; + const fn: typeof fetch = vi.fn(async (input, init) => { + calls.push({ url: String(input), init: init ?? {} }); + return response.clone(); + }); + return { fetch: fn, calls }; +} + +function jsonResponse(body: unknown, init: ResponseInit = {}): Response { + return new Response(JSON.stringify(body), { + ...init, + headers: { + "content-type": "application/json", + ...(init.headers ?? {}), + }, + }); +} + +const SUCCESS_LIST = { + data: { organizations: [{ id: "org_1", name: "Acme", slug: "acme", createdAt: "2025-01-01T00:00:00Z" }] }, + meta: { requestId: "req_server_1", cursor: null }, +}; + +describe("Transport — success path", () => { + it("unwraps the data envelope on GET", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + + const result = await client.organizations.list(); + + expect(result).toEqual(SUCCESS_LIST.data); + expect(calls).toHaveLength(1); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("strips trailing slash from baseUrl", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ baseUrl: "https://api.test/", fetch }); + await client.organizations.list(); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations"); + }); + + it("returns 204 as undefined", async () => { + const { fetch } = captureFetch(new Response(null, { status: 204 })); + const transport = new Transport({ baseUrl: "https://api.test", fetch }); + const result = await transport.request({ method: "DELETE", path: "/v1/x" }); + expect(result).toBeUndefined(); + }); + + it("encodes path parameters", async () => { + const { fetch, calls } = captureFetch( + jsonResponse({ data: { project: {} }, meta: { requestId: "req_x", cursor: null } }), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.projects.get("org/with slash", "proj"); + expect(calls[0]!.url).toContain("org%2Fwith%20slash"); + }); +}); + +describe("Transport — auth", () => { + it("attaches bearer token", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ + baseUrl: "https://api.test", + auth: { kind: "bearer", token: "test-token" }, + fetch, + }); + await client.organizations.list(); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("authorization")).toBe("Bearer test-token"); + }); + + it("attaches session cookie", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ + baseUrl: "https://api.test", + auth: { kind: "session", cookie: "sb_session=abc" }, + fetch, + }); + await client.organizations.list(); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("cookie")).toBe("sb_session=abc"); + }); +}); + +describe("Transport — request id", () => { + it("auto-generates a req_-prefixed id when caller omits", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.organizations.list(); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + const sent = headers.get("x-request-id"); + expect(sent).toMatch(/^req_[0-9a-f]{16,}$/); + }); + + it("passes caller-provided request id verbatim", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.organizations.list({ requestId: "req_user_supplied_42" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("x-request-id")).toBe("req_user_supplied_42"); + }); + + it("generateRequestId returns a stable shape", () => { + const id = generateRequestId(); + expect(id).toMatch(/^req_[0-9a-f]+$/); + expect(id.length).toBeGreaterThan(10); + }); +}); + +describe("Transport — idempotency key", () => { + it("does NOT auto-generate an idempotency key on POST", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + { data: { organization: {}, membership: {} }, meta: { requestId: "req_x", cursor: null } }, + { status: 201 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.organizations.create({ name: "Acme" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBeNull(); + }); + + it("propagates a caller-provided idempotency key on POST", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + { data: { organization: {}, membership: {} }, meta: { requestId: "req_x", cursor: null } }, + { status: 201 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.organizations.create( + { name: "Acme" }, + { idempotencyKey: "ikey_abc123" }, + ); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_abc123"); + expect(calls[0]!.init.method).toBe("POST"); + expect(calls[0]!.init.body).toBe(JSON.stringify({ name: "Acme" })); + }); + + it("propagates idempotency key on project create", async () => { + const { fetch, calls } = captureFetch( + jsonResponse( + { data: { project: {} }, meta: { requestId: "req_x", cursor: null } }, + { status: 201 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.projects.create("org_1", { name: "Web" }, { idempotencyKey: "ikey_proj_1" }); + const headers = new Headers(calls[0]!.init.headers as HeadersInit); + expect(headers.get("idempotency-key")).toBe("ikey_proj_1"); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_1/projects"); + }); +}); + +describe("Transport — abort signal", () => { + it("forwards the abort signal", async () => { + const { fetch, calls } = captureFetch(jsonResponse(SUCCESS_LIST)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + const ctrl = new AbortController(); + await client.organizations.list({ signal: ctrl.signal }); + expect(calls[0]!.init.signal).toBe(ctrl.signal); + }); +}); + +describe("Error decoding — typed branches", () => { + function envelopeFor(code: string, status: number, extra: Record = {}): Response { + return jsonResponse( + { + error: { + code, + message: `synthetic ${code}`, + details: extra, + requestId: "req_server_err", + }, + }, + { status }, + ); + } + + const cases: Array<[string, number, new (...args: never[]) => newtestError]> = [ + ["bad_request", 400, BadRequestError], + ["unauthenticated", 401, UnauthenticatedError], + ["forbidden", 403, ForbiddenError], + ["not_found", 404, NotFoundError], + ["conflict", 409, ConflictError], + ["precondition_failed", 412, PreconditionFailedError], + ["unsupported", 405, UnsupportedError], + ["internal_error", 500, InternalError], + ]; + + for (const [code, status, Ctor] of cases) { + it(`decodes ${code} → ${Ctor.name}`, async () => { + const { fetch } = captureFetch(envelopeFor(code, status)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await expect(client.organizations.list()).rejects.toBeInstanceOf(Ctor); + try { + await client.organizations.list(); + } catch (err) { + const e = err as newtestError; + expect(e.code).toBe(code); + expect(e.status).toBe(status); + expect(e.requestId).toBe("req_server_err"); + expect(e.message).toBe(`synthetic ${code}`); + expect(e).toBeInstanceOf(newtestError); + } + }); + } + + it("decodes validation_failed with field map", async () => { + const { fetch } = captureFetch( + jsonResponse( + { + error: { + code: "validation_failed", + message: "Validation failed", + details: { fields: { name: ["required"] } }, + requestId: "req_v", + }, + }, + { status: 422 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + try { + await client.organizations.create({ name: "" }); + throw new Error("expected throw"); + } catch (err) { + expect(err).toBeInstanceOf(ValidationError); + const v = err as ValidationError; + expect(v.fields).toEqual({ name: ["required"] }); + } + }); + + it("forward-compat: unknown error code → base newtestError", async () => { + const { fetch } = captureFetch(envelopeFor("future_quota_exceeded", 402)); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + try { + await client.organizations.list(); + throw new Error("expected throw"); + } catch (err) { + expect(err).toBeInstanceOf(newtestError); + expect(err).not.toBeInstanceOf(BadRequestError); + expect((err as newtestError).code).toBe("future_quota_exceeded"); + } + }); + + it("non-JSON 5xx body falls back to InternalError shape", async () => { + const { fetch } = captureFetch( + new Response("502 bad gateway", { + status: 502, + headers: { "content-type": "text/html" }, + }), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + try { + await client.organizations.list(); + throw new Error("expected throw"); + } catch (err) { + expect(err).toBeInstanceOf(InternalError); + const e = err as InternalError; + expect(e.status).toBe(502); + expect(e.message).toBe("HTTP 502"); + // Caller-supplied request id is used as fallback when server doesn't provide one. + expect(e.requestId).toMatch(/^req_/); + } + }); + + it("empty 500 body falls back to InternalError", async () => { + const { fetch } = captureFetch(new Response("", { status: 500 })); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await expect(client.organizations.list()).rejects.toBeInstanceOf(InternalError); + }); +}); + +describe("Error decoding — RateLimitError", () => { + function rateLimitedResponse(extra: { headers?: Record } = {}): Response { + return jsonResponse( + { + error: { + code: "rate_limited", + message: "Too many requests", + details: { scope: "org", retryAfterSeconds: 7 }, + requestId: "req_rl", + }, + }, + { + status: 429, + headers: { + "retry-after": "7", + "x-ratelimit-limit-org": "100", + "x-ratelimit-remaining-org": "0", + "x-ratelimit-reset-org": "1717000000", + "x-ratelimit-limit-identity": "30", + "x-ratelimit-remaining-identity": "29", + "x-ratelimit-reset-identity": "1717000010", + ...(extra.headers ?? {}), + }, + }, + ); + } + + it("decodes Task 0097 rate-limit envelope completely", async () => { + const { fetch } = captureFetch(rateLimitedResponse()); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + + try { + await client.organizations.list(); + throw new Error("expected throw"); + } catch (err) { + expect(err).toBeInstanceOf(RateLimitError); + const e = err as RateLimitError; + expect(e.status).toBe(429); + expect(e.scope).toBe("org"); + expect(e.retryAfterSeconds).toBe(7); + expect(e.windows).toHaveLength(2); + expect(e.orgWindow).toEqual({ + scope: "org", + limit: 100, + remaining: 0, + resetAt: 1717000000, + }); + expect(e.identityWindow).toEqual({ + scope: "identity", + limit: 30, + remaining: 29, + resetAt: 1717000010, + }); + } + }); + + it("missing rate-limit headers do not throw — fields are null/empty", async () => { + const { fetch } = captureFetch( + jsonResponse( + { + error: { code: "rate_limited", message: "rate", details: {}, requestId: "req_rl" }, + }, + { status: 429 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + try { + await client.organizations.list(); + throw new Error("expected throw"); + } catch (err) { + const e = err as RateLimitError; + expect(e).toBeInstanceOf(RateLimitError); + expect(e.retryAfterSeconds).toBeNull(); + expect(e.scope).toBeNull(); + expect(e.windows).toEqual([]); + } + }); + + it("falls back to details.retryAfterSeconds when Retry-After header is absent", async () => { + const { fetch } = captureFetch( + jsonResponse( + { + error: { + code: "rate_limited", + message: "rate", + details: { scope: "identity", retryAfterSeconds: 12 }, + requestId: "req_rl", + }, + }, + { status: 429 }, + ), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + try { + await client.organizations.list(); + throw new Error("expected throw"); + } catch (err) { + const e = err as RateLimitError; + expect(e.retryAfterSeconds).toBe(12); + expect(e.scope).toBe("identity"); + } + }); +}); + +describe("Resource clients — surface", () => { + it("projects.list hits the org-scoped path", async () => { + const { fetch, calls } = captureFetch( + jsonResponse({ data: { projects: [] }, meta: { requestId: "req", cursor: null } }), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.projects.list("org_1"); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_1/projects"); + expect(calls[0]!.init.method).toBe("GET"); + }); + + it("projects.archive issues DELETE", async () => { + const { fetch, calls } = captureFetch( + jsonResponse({ data: { project: {} }, meta: { requestId: "req", cursor: null } }), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.projects.archive("org_1", "proj_1"); + expect(calls[0]!.init.method).toBe("DELETE"); + expect(calls[0]!.url).toBe( + "https://api.test/v1/organizations/org_1/projects/proj_1", + ); + }); + + it("organizations.get hits /:orgId", async () => { + const { fetch, calls } = captureFetch( + jsonResponse({ data: { organization: {} }, meta: { requestId: "req", cursor: null } }), + ); + const client = new newtest({ baseUrl: "https://api.test", fetch }); + await client.organizations.get("org_42"); + expect(calls[0]!.url).toBe("https://api.test/v1/organizations/org_42"); + }); +}); diff --git a/packages/sdk/src/apiKeys.ts b/packages/sdk/src/apiKeys.ts new file mode 100644 index 0000000..20702bb --- /dev/null +++ b/packages/sdk/src/apiKeys.ts @@ -0,0 +1,99 @@ +import type { + CreateApiKeyRequest, + PublicApiKey, + PublicApiKeyCreateResult, + PublicApiKeyRevokeResult, +} from "@saas/contracts/api-keys"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * API Keys resource client. + * + * Org-scoped surface served by `apps/identity-worker` via the api-edge + * `org-facade` routes. The `create` response carries a one-time secret + * material reveal — callers MUST persist it immediately; subsequent list + * calls only return the prefix. + */ + +export interface ListApiKeysResponse { + apiKeys: PublicApiKey[]; +} + +export interface GetApiKeyResponse { + apiKey: PublicApiKey; +} + +export interface CreateApiKeyResponse { + apiKey: PublicApiKeyCreateResult; +} + +export interface RevokeApiKeyResponse { + apiKey: PublicApiKeyRevokeResult; +} + +export class ApiKeysClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/api-keys */ + list(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/api-keys`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/api-keys/:apiKeyId */ + get( + orgId: string, + apiKeyId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/api-keys/${encodeURIComponent(apiKeyId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/api-keys + * + * The response carries a one-time-reveal `secret`. Pass `idempotencyKey` + * in `opts` for safe retry semantics (Stripe parity — caller-owned key). + */ + create( + orgId: string, + body: CreateApiKeyRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/api-keys`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/api-keys/:apiKeyId */ + revoke( + orgId: string, + apiKeyId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/api-keys/${encodeURIComponent(apiKeyId)}`, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/auth.ts b/packages/sdk/src/auth.ts new file mode 100644 index 0000000..aab79d7 --- /dev/null +++ b/packages/sdk/src/auth.ts @@ -0,0 +1,144 @@ +import type { + LoginCompleteRequest, + LoginCompleteResponse, + LoginStartRequest, + LoginStartResponse, + LogoutResponse, + OAuthProvidersResponse, + ProfileResponse, + SessionResponse, + UpdateProfileRequest, +} from "@saas/contracts/auth"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Auth resource client (Task 0103). + * + * Wraps the identity-worker public auth surface exposed by the api-edge + * `auth-facade` route table: + * - POST /v1/auth/login/start + * - POST /v1/auth/login/complete + * - GET /v1/auth/session + * - POST /v1/auth/logout + * - GET /v1/auth/profile + * - PATCH /v1/auth/profile + * + * Stripe parity: `loginStart`, `loginComplete`, and `logout` are POSTs that + * accept a caller-owned `idempotencyKey` via `RequestOptions`. The SDK MUST + * NOT auto-generate one — it is forwarded verbatim if present, omitted + * otherwise. + * + * Note: `/v1/auth/resolve` is intentionally NOT exposed — that endpoint is + * internal to service-binding bearer resolution. `/v1/auth/security-events` + * is also out of scope here; it lives on `SecurityEventsClient` (Task 0099). + */ +export class AuthClient { + constructor(private readonly transport: Transport) {} + + /** POST /v1/auth/login/start */ + loginStart( + input: LoginStartRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: "/v1/auth/login/start", + body: input, + }, + opts, + ); + } + + /** POST /v1/auth/login/complete */ + loginComplete( + input: LoginCompleteRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: "/v1/auth/login/complete", + body: input, + }, + opts, + ); + } + + /** GET /v1/auth/oauth/providers — the configured OAuth sign-in providers. */ + listOAuthProviders(opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: "/v1/auth/oauth/providers", + }, + opts, + ); + } + + /** + * Build the absolute URL that begins an OAuth login. This is NOT an XHR + * endpoint — assign it to `window.location` so the provider redirect and the + * state-cookie handshake run as top-level browser navigations. + * + * @param providerId provider id from {@link listOAuthProviders} (e.g. "github") + * @param returnTo absolute URL the user is returned to after sign-in + * (must be an allow-listed console origin server-side) + */ + oauthStartUrl(providerId: string, returnTo: string): string { + const url = new URL( + `${this.transport.baseUrl}/v1/auth/oauth/${encodeURIComponent(providerId)}/start`, + ); + url.searchParams.set("return_to", returnTo); + return url.toString(); + } + + /** GET /v1/auth/session */ + getSession(opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: "/v1/auth/session", + }, + opts, + ); + } + + /** POST /v1/auth/logout */ + logout(opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "POST", + path: "/v1/auth/logout", + }, + opts, + ); + } + + /** GET /v1/auth/profile */ + getProfile(opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: "/v1/auth/profile", + }, + opts, + ); + } + + /** PATCH /v1/auth/profile */ + updateProfile( + input: UpdateProfileRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: "/v1/auth/profile", + body: input, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/billing.ts b/packages/sdk/src/billing.ts new file mode 100644 index 0000000..aae656c --- /dev/null +++ b/packages/sdk/src/billing.ts @@ -0,0 +1,270 @@ +import type { + CancelSubscriptionResponse, + ChangePlanRequest, + ChangePlanResponse, + CheckBillingEntitlementRequest, + CheckBillingEntitlementResponse, + CreateCheckoutRequest, + CreateCheckoutResponse, + CreatePortalSessionResponse, + GetBillingCustomerResponse, + GetBillingSummaryResponse, + GetEntitlementsRequest, + GetEntitlementsResponse, + ListInvoicesRequest, + ListInvoicesResponse, + ListPaymentMethodsResponse, + ListPlansRequest, + ListPlansResponse, + ReconcileResponse, +} from "@saas/contracts/billing"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Billing resource client. + * + * Org-scoped surface served by `apps/billing-worker` via the api-edge + * `billing-facade`. Reads (plans/customer/summary/invoices/entitlements) plus + * two provider hand-off writes: `createCheckout` and `createPortalSession` + * return hosted, safe-to-display URLs — the actual plan change is applied by + * the verified provider webhook, never by the client. + * + * `checkEntitlement` targets the entitlement decision seam (POST against the + * org-scoped entitlements path), letting callers gate product behaviour on a + * stable entitlement key without reading billing tables directly. + */ +export class BillingClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/billing/plans */ + listPlans( + orgId: string, + query: ListPlansRequest = {}, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ status: query.status }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/plans`, + query: params, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/billing/customer */ + getCustomer( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/customer`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/billing/summary */ + getSummary( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/summary`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/billing/invoices */ + listInvoices( + orgId: string, + query: ListInvoicesRequest = {}, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ + subscriptionId: query.subscriptionId, + status: query.status, + limit: query.limit, + cursor: query.cursor ? JSON.stringify(query.cursor) : undefined, + }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/invoices`, + query: params, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/billing/entitlements */ + getEntitlements( + orgId: string, + query: GetEntitlementsRequest = {}, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ + subscriptionId: query.subscriptionId, + source: query.source, + }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/entitlements`, + query: params, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/entitlements/check + * + * Entitlement decision seam. The `orgId` argument is the URL scope; the + * `entitlementKey` travels in the body. Missing entitlements surface as a + * `denied` decision (not a 5xx) so callers can fail closed deterministically. + */ + checkEntitlement( + orgId: string, + body: Pick, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/entitlements/check`, + body, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/checkout + * + * Start a hosted checkout to purchase/upgrade a plan. Returns a checkout URL + * to redirect the buyer to; the plan is applied by the provider webhook after + * payment, not by this call. + */ + createCheckout( + orgId: string, + body: CreateCheckoutRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/checkout`, + body, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/portal + * + * Create a hosted customer-portal session for managing the subscription / + * payment method. Returns a portal URL to redirect to. + */ + createPortalSession( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/portal`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/subscription/cancel + * + * Cancel the account's paid subscription natively (no hosted-portal redirect). + * The downgrade is applied by the provider webhook after this returns. + */ + cancelSubscription( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/subscription/cancel`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/reconcile + * + * Self-heal billing state from the provider (backfill a missed webhook). + * `{ reconciled: false }` is a normal outcome (e.g. no provider subscription). + */ + reconcile(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/reconcile`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/billing/payment-methods */ + listPaymentMethods( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/payment-methods`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/billing/subscription/change + * + * Change an existing paid subscription to another plan natively (no redirect). + * First purchases go through `createCheckout`, not this method. + */ + changePlan( + orgId: string, + body: ChangePlanRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/billing/subscription/change`, + body, + }, + opts, + ); + } +} + +function buildQueryRecord( + input: Record, +): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(input)) { + if (v === undefined || v === null) continue; + out[k] = v; + } + return out; +} diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.ts new file mode 100644 index 0000000..b4a93c0 --- /dev/null +++ b/packages/sdk/src/config.ts @@ -0,0 +1,217 @@ +import type { + CreateFeatureFlagRequest, + CreateFeatureFlagResponse, + CreateSecretMetadataResponse, + CreateSecretRequest, + CreateSettingRequest, + CreateSettingResponse, + ListFeatureFlagsResponse, + ListSecretMetadataResponse, + ListSettingsResponse, + RevokeSecretMetadataResponse, + RotateSecretMetadataResponse, + RotateSecretRequest, + UpdateFeatureFlagRequest, + UpdateFeatureFlagResponse, + UpdateSettingRequest, + UpdateSettingResponse, +} from "@saas/contracts/config"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Config (settings / feature-flags / secrets-metadata) resource client. + * + * Backed by `apps/config-worker` via the api-edge `config-facade`. The facade + * exposes the same three resource families at three scopes — organization, + * project, and environment — each surfaced here as a single flat method that + * takes a discriminated `scope` argument so call sites stay grep-able and the + * SDK doesn't fan out into a nine-permutation method tree. + * + * Secret values are write-only: `createSecretMetadata` and `rotateSecret` + * accept a `value` field that the worker encrypts before persistence and that + * NEVER appears in any response. List responses carry metadata only. + */ + +/** Discriminated scope identifying which surface the call targets. */ +export type ConfigScope = + | { kind: "organization"; orgId: string } + | { kind: "project"; orgId: string; projectId: string } + | { + kind: "environment"; + orgId: string; + projectId: string; + environmentId: string; + }; + +export class ConfigClient { + constructor(private readonly transport: Transport) {} + + // ------------------------------------------------------------------------- + // Settings + // ------------------------------------------------------------------------- + + /** GET /config/settings */ + listSettings( + scope: ConfigScope, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "GET", path: `${scopeBase(scope)}/settings` }, + opts, + ); + } + + /** POST /config/settings */ + createSetting( + scope: ConfigScope, + body: CreateSettingRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "POST", path: `${scopeBase(scope)}/settings`, body }, + opts, + ); + } + + /** PATCH /config/settings/:settingId — addressed by public id (`set_…`), not key. */ + updateSetting( + scope: ConfigScope, + settingId: string, + body: UpdateSettingRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `${scopeBase(scope)}/settings/${encodeURIComponent(settingId)}`, + body, + }, + opts, + ); + } + + // ------------------------------------------------------------------------- + // Feature flags + // ------------------------------------------------------------------------- + + /** GET /config/feature-flags */ + listFeatureFlags( + scope: ConfigScope, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "GET", path: `${scopeBase(scope)}/feature-flags` }, + opts, + ); + } + + /** POST /config/feature-flags */ + createFeatureFlag( + scope: ConfigScope, + body: CreateFeatureFlagRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "POST", path: `${scopeBase(scope)}/feature-flags`, body }, + opts, + ); + } + + /** PATCH /config/feature-flags/:flagId — addressed by public id (`flg_…`), not key. */ + updateFeatureFlag( + scope: ConfigScope, + flagId: string, + body: UpdateFeatureFlagRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `${scopeBase(scope)}/feature-flags/${encodeURIComponent(flagId)}`, + body, + }, + opts, + ); + } + + // ------------------------------------------------------------------------- + // Secrets (metadata-only reads; write-only `value` on create/rotate) + // ------------------------------------------------------------------------- + + /** GET /config/secrets */ + listSecretMetadata( + scope: ConfigScope, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "GET", path: `${scopeBase(scope)}/secrets` }, + opts, + ); + } + + /** + * POST /config/secrets + * + * The `value` field is write-only — the api-edge worker encrypts it before + * persistence and the response carries metadata only. + */ + createSecretMetadata( + scope: ConfigScope, + body: CreateSecretRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "POST", path: `${scopeBase(scope)}/secrets`, body }, + opts, + ); + } + + /** + * POST /config/secrets/:secretId/rotate — addressed by public id (`sec_…`), not key. + * + * Rotates a secret's value. Write-only — the rotated value is never echoed + * back in any response, event, or audit payload. + */ + rotateSecret( + scope: ConfigScope, + secretId: string, + body: RotateSecretRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `${scopeBase(scope)}/secrets/${encodeURIComponent(secretId)}/rotate`, + body, + }, + opts, + ); + } + + /** DELETE /config/secrets/:secretId — soft-delete (revoke); addressed by public id (`sec_…`). */ + revokeSecret( + scope: ConfigScope, + secretId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `${scopeBase(scope)}/secrets/${encodeURIComponent(secretId)}`, + }, + opts, + ); + } +} + +function scopeBase(scope: ConfigScope): string { + switch (scope.kind) { + case "organization": + return `/v1/organizations/${encodeURIComponent(scope.orgId)}/config`; + case "project": + return `/v1/organizations/${encodeURIComponent(scope.orgId)}/projects/${encodeURIComponent(scope.projectId)}/config`; + case "environment": + return `/v1/organizations/${encodeURIComponent(scope.orgId)}/projects/${encodeURIComponent(scope.projectId)}/environments/${encodeURIComponent(scope.environmentId)}/config`; + } +} diff --git a/packages/sdk/src/environments.ts b/packages/sdk/src/environments.ts new file mode 100644 index 0000000..53190c8 --- /dev/null +++ b/packages/sdk/src/environments.ts @@ -0,0 +1,98 @@ +import type { + ArchiveEnvironmentResponse, + CreateEnvironmentRequest, + CreateEnvironmentResponse, + GetEnvironmentResponse, + ListEnvironmentsResponse, +} from "@saas/contracts/projects"; + +import type { Transport, RequestOptions } from "./transport.js"; + +/** + * Environments resource client. + * + * Project-scoped: every method takes `orgId` + `projectId` as the first two + * arguments. Maps to `apps/projects-worker` via the api-edge `project-facade` + * route (`ORG_PROJECT_ENVIRONMENTS_RE` / + * `ORG_PROJECT_ENVIRONMENT_ID_RE`). Mirrors the `ProjectsClient` shape so + * callers see a uniform resource namespace. + * + * Stripe parity: `create` and `archive` accept a caller-owned + * `idempotencyKey` via `RequestOptions`; the SDK never auto-generates one. + */ +export class EnvironmentsClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/projects/:projectId/environments */ + list( + orgId: string, + projectId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/environments`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/projects/:projectId/environments/:envId */ + get( + orgId: string, + projectId: string, + envId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(envId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/projects/:projectId/environments + * + * Pass `idempotencyKey` in `opts` for safe retry semantics (Stripe parity). + */ + create( + orgId: string, + projectId: string, + body: CreateEnvironmentRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/environments`, + body, + }, + opts, + ); + } + + /** + * DELETE /v1/organizations/:orgId/projects/:projectId/environments/:envId + * + * api-edge maps this to a soft-archive on the projects-worker; the response + * envelope returns the archived `PublicEnvironment` shape. + */ + archive( + orgId: string, + projectId: string, + envId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(envId)}`, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/errors.ts b/packages/sdk/src/errors.ts new file mode 100644 index 0000000..dbdba04 --- /dev/null +++ b/packages/sdk/src/errors.ts @@ -0,0 +1,326 @@ +// Typed error hierarchy for the newtest SDK. +// +// The api-edge error envelope is: +// { error: { code: string, message: string, details: object, requestId?: string } } +// where `code` is one of `ERROR_CODES` from `@saas/contracts/errors`. Unknown +// codes (forward compatibility) fall back to the generic `newtestError` +// base class with the raw envelope preserved. +// +// `RateLimitError` decodes the `Retry-After` and `X-RateLimit-{Limit,Remaining, +// Reset}-` headers Task 0097 (B3 second half) emits. Header decoding is +// defensive: missing headers yield `null`, never throw. + +import { ERROR_CODES, type ErrorCode } from "@saas/contracts/errors"; + +/** Raw error envelope as it comes off the wire. */ +export interface ErrorEnvelope { + code: string; + message: string; + details: Record; + requestId?: string; +} + +export interface newtestErrorInit { + envelope: ErrorEnvelope; + status: number; + requestId: string; + /** Original Response. Useful for callers that want to read raw headers. */ + response?: Response; +} + +/** + * Base error type. Unknown error codes (forward-compat, e.g. a future + * `quota_exceeded`) decode to this class — `instanceof newtestError` + * still matches. + */ +export class newtestError extends Error { + readonly code: string; + readonly status: number; + readonly requestId: string; + readonly details: Record; + readonly envelope: ErrorEnvelope; + /** Present only when the error was synthesised from a real Response. */ + readonly response: Response | undefined; + + constructor(init: newtestErrorInit) { + super(init.envelope.message); + this.name = "newtestError"; + this.code = init.envelope.code; + this.status = init.status; + this.requestId = init.requestId; + this.details = init.envelope.details; + this.envelope = init.envelope; + this.response = init.response; + } +} + +export class BadRequestError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "BadRequestError"; + } +} + +export class UnauthenticatedError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "UnauthenticatedError"; + } +} + +export class ForbiddenError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "ForbiddenError"; + } +} + +export class NotFoundError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "NotFoundError"; + } +} + +export class ConflictError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "ConflictError"; + } +} + +export class ValidationError extends newtestError { + /** Field-level violations, when the server provides them. */ + readonly fields: Record; + + constructor(init: newtestErrorInit) { + super(init); + this.name = "ValidationError"; + const raw = init.envelope.details["fields"]; + this.fields = isFieldMap(raw) ? raw : {}; + } +} + +export class PreconditionFailedError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "PreconditionFailedError"; + } +} + +export class UnsupportedError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "UnsupportedError"; + } +} + +export class InternalError extends newtestError { + constructor(init: newtestErrorInit) { + super(init); + this.name = "InternalError"; + } +} + +/** Per-scope rate-limit window (org or identity). */ +export interface RateLimitWindow { + scope: "org" | "identity"; + limit: number | null; + remaining: number | null; + /** UTC seconds since epoch when the bucket fully refills. */ + resetAt: number | null; +} + +export interface RateLimitErrorInit extends newtestErrorInit { + retryAfterSeconds: number | null; + /** Scope that tripped the limit (echoed from `details.scope`). */ + scope: "org" | "identity" | null; + windows: RateLimitWindow[]; +} + +export class RateLimitError extends newtestError { + readonly retryAfterSeconds: number | null; + readonly scope: "org" | "identity" | null; + readonly windows: RateLimitWindow[]; + + constructor(init: RateLimitErrorInit) { + super(init); + this.name = "RateLimitError"; + this.retryAfterSeconds = init.retryAfterSeconds; + this.scope = init.scope; + this.windows = init.windows; + } + + /** Convenience accessor for the org-scope window, when present. */ + get orgWindow(): RateLimitWindow | undefined { + return this.windows.find((w) => w.scope === "org"); + } + + /** Convenience accessor for the identity-scope window, when present. */ + get identityWindow(): RateLimitWindow | undefined { + return this.windows.find((w) => w.scope === "identity"); + } +} + +// --------------------------------------------------------------------------- +// Decoder +// --------------------------------------------------------------------------- + +/** + * Decode an HTTP `Response` into the appropriate `newtestError` subclass. + * + * Forward-compatible: unknown error codes resolve to the base `newtestError`. + * Robust to non-JSON 5xx bodies (gateway HTML, empty body, etc.) — synthesises + * a generic `InternalError` envelope in that case. + */ +export async function decodeError( + response: Response, + fallbackRequestId: string, +): Promise { + const envelope = await readErrorEnvelope(response, fallbackRequestId); + const requestId = envelope.requestId ?? fallbackRequestId; + const init: newtestErrorInit = { + envelope, + status: response.status, + requestId, + response, + }; + + switch (envelope.code as ErrorCode) { + case ERROR_CODES.BAD_REQUEST: + return new BadRequestError(init); + case ERROR_CODES.UNAUTHENTICATED: + return new UnauthenticatedError(init); + case ERROR_CODES.FORBIDDEN: + return new ForbiddenError(init); + case ERROR_CODES.NOT_FOUND: + return new NotFoundError(init); + case ERROR_CODES.CONFLICT: + return new ConflictError(init); + case ERROR_CODES.VALIDATION_FAILED: + return new ValidationError(init); + case ERROR_CODES.PRECONDITION_FAILED: + return new PreconditionFailedError(init); + case ERROR_CODES.UNSUPPORTED: + return new UnsupportedError(init); + case ERROR_CODES.INTERNAL_ERROR: + return new InternalError(init); + case ERROR_CODES.RATE_LIMITED: + return decodeRateLimit(init, response); + default: + // Forward-compat: unknown codes still surface a typed error. + return new newtestError(init); + } +} + +function decodeRateLimit( + init: newtestErrorInit, + response: Response, +): RateLimitError { + const retryAfter = parseIntHeader(response.headers.get("retry-after")); + const detailsScope = init.envelope.details["scope"]; + const scope = + detailsScope === "org" || detailsScope === "identity" + ? (detailsScope as "org" | "identity") + : null; + const detailsRetry = init.envelope.details["retryAfterSeconds"]; + const detailsRetryNum = + typeof detailsRetry === "number" && Number.isFinite(detailsRetry) + ? detailsRetry + : null; + + const windows: RateLimitWindow[] = []; + for (const candidate of ["org", "identity"] as const) { + const limit = parseIntHeader( + response.headers.get(`x-ratelimit-limit-${candidate}`), + ); + const remaining = parseIntHeader( + response.headers.get(`x-ratelimit-remaining-${candidate}`), + ); + const resetAt = parseIntHeader( + response.headers.get(`x-ratelimit-reset-${candidate}`), + ); + if (limit !== null || remaining !== null || resetAt !== null) { + windows.push({ scope: candidate, limit, remaining, resetAt }); + } + } + + return new RateLimitError({ + ...init, + retryAfterSeconds: retryAfter ?? detailsRetryNum, + scope, + windows, + }); +} + +async function readErrorEnvelope( + response: Response, + fallbackRequestId: string, +): Promise { + let raw: unknown = null; + try { + raw = await response.clone().json(); + } catch { + raw = null; + } + const errorField = isObject(raw) ? raw["error"] : null; + if (isObject(errorField)) { + const code = typeof errorField["code"] === "string" ? errorField["code"] : null; + const message = + typeof errorField["message"] === "string" + ? errorField["message"] + : `HTTP ${response.status}`; + const details = isObject(errorField["details"]) ? errorField["details"] : {}; + const requestId = + typeof errorField["requestId"] === "string" + ? errorField["requestId"] + : undefined; + if (code) { + return { code, message, details, ...(requestId ? { requestId } : {}) }; + } + } + + // Non-JSON or non-conformant body. Map by HTTP status. + return { + code: defaultCodeForStatus(response.status), + message: `HTTP ${response.status}`, + details: {}, + requestId: fallbackRequestId, + }; +} + +function defaultCodeForStatus(status: number): ErrorCode { + if (status === 400) return ERROR_CODES.BAD_REQUEST; + if (status === 401) return ERROR_CODES.UNAUTHENTICATED; + if (status === 403) return ERROR_CODES.FORBIDDEN; + if (status === 404) return ERROR_CODES.NOT_FOUND; + if (status === 409) return ERROR_CODES.CONFLICT; + if (status === 412) return ERROR_CODES.PRECONDITION_FAILED; + if (status === 422) return ERROR_CODES.VALIDATION_FAILED; + if (status === 429) return ERROR_CODES.RATE_LIMITED; + if (status === 415 || status === 405) return ERROR_CODES.UNSUPPORTED; + return ERROR_CODES.INTERNAL_ERROR; +} + +function parseIntHeader(value: string | null): number | null { + if (value === null) return null; + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + const n = Number(trimmed); + return Number.isFinite(n) ? n : null; +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function isFieldMap(value: unknown): value is Record { + if (!isObject(value)) return false; + for (const v of Object.values(value)) { + if (!Array.isArray(v)) return false; + for (const entry of v) { + if (typeof entry !== "string") return false; + } + } + return true; +} diff --git a/packages/sdk/src/events.ts b/packages/sdk/src/events.ts new file mode 100644 index 0000000..a9c26e8 --- /dev/null +++ b/packages/sdk/src/events.ts @@ -0,0 +1,290 @@ +import type { + ListAuditEntriesResponse, + PublicAuditEntry, +} from "@saas/contracts/events"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Events (audit) resource client. + * + * Org-scoped surface served by `apps/events-worker` via the api-edge + * `audit-facade`. Returns the immutable audit-entry projection with redacted + * payload paths already applied server-side. + * + * `listAuditEntries` accepts a discriminated query object so callers can ask + * for entries by org or by a specific subject (kind + id) — mirroring the + * `AuditQueryByOrg` / `AuditQueryByTarget` contract shapes without having to + * import them at the call site. + */ + +/** + * Independently-combinable filters for the org-scoped audit list. Every field + * is optional; supplying several narrows the result set with AND semantics. + * `from`/`to` are inclusive bounds on `occurredAt` (ISO-8601 ms Z). None of + * these alter the keyset ordering or cursor — they only restrict eligible rows. + */ +export interface AuditEntryFilters { + actorId?: string; + actorType?: string; + subjectKind?: string; + subjectId?: string; + eventType?: string; + from?: string; + to?: string; +} + +export type ListAuditEntriesQuery = + | ({ + by: "org"; + category?: string; + limit?: number; + cursor?: string; + } & AuditEntryFilters) + | { + by: "target"; + subjectKind: string; + subjectId: string; + limit?: number; + cursor?: string; + }; + +/** + * SDK-facing audit list response. The api-edge sends + * `{ data: { auditEntries }, meta: { requestId, cursor } }` and the transport + * unwraps to `.data`, so the SDK return type mirrors the contract's `data` + * payload directly. + */ +export type ListAuditEntriesResult = ListAuditEntriesResponse["data"]; + +/** + * Hard upper bound on pages walked by `iterAuditEntries`. A misbehaving server + * that cycles cursors will abort with an error before this limit is reached + * (`seenCursors` guard), but the cap is a defence-in-depth so a server that + * returns a fresh cursor on every call cannot keep us in an infinite loop. + * + * Exported for tests; consumers should not rely on the exact number. + */ +export const AUDIT_ITERATOR_MAX_PAGES = 1000; + +export class EventsClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/audit */ + listAuditEntries( + orgId: string, + query: ListAuditEntriesQuery = { by: "org" }, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + buildAuditRequest(orgId, query), + opts, + ); + } + + /** + * Single-page audit fetch that also exposes the server-issued continuation + * cursor. Use this when the caller needs the cursor for a paginated UI + * (default `audit list` CLI mode); use `iterAuditEntries` when the caller + * wants every entry across every page. + * + * `cursor` is `null` when the server has no further entries, mirroring + * the api-edge `meta.cursor` field exactly. + */ + async listAuditEntriesPage( + orgId: string, + query: ListAuditEntriesQuery = { by: "org" }, + opts: RequestOptions = {}, + ): Promise<{ entries: ReadonlyArray; cursor: string | null }> { + const { data, meta } = await this.transport.requestWithEnvelope< + ListAuditEntriesResult + >(buildAuditRequest(orgId, query), opts); + return { + entries: data.auditEntries, + cursor: meta.cursor ?? null, + }; + } + + /** + * Async iterator that walks every page of audit entries until the server + * returns `meta.cursor === null` (or `undefined`). Yields one + * `PublicAuditEntry` at a time, in server order. + * + * The iterator drives `Transport.requestWithEnvelope` so it can read + * `meta.cursor` without reaching into raw `fetchImpl`. Loop guards: + * + * - hard cap of `AUDIT_ITERATOR_MAX_PAGES` page reads, + * - `seenCursors` Set: if the server ever returns a cursor we've already + * walked, the iterator throws rather than risking an infinite loop. + * + * Designed to be a drop-in replacement for the hand-rolled `--all` loop + * that the CLI shipped in Task 0101 against the public `Transport`. + */ + iterAuditEntries( + orgId: string, + query: ListAuditEntriesQuery = { by: "org" }, + opts: RequestOptions = {}, + ): AsyncIterable { + const transport = this.transport; + return { + [Symbol.asyncIterator](): AsyncIterator { + return createAuditIterator(transport, orgId, query, opts); + }, + }; + } + + /** + * Stream the (optionally filtered) audit log as NDJSON — one JSON-encoded + * `PublicAuditEntry` per line, terminated by a single `\n`. Layered over + * `iterAuditEntries`, so every filter, the keyset ordering, and the + * `AUDIT_ITERATOR_MAX_PAGES` / `seenCursors` loop guards apply unchanged. + * + * Yields complete lines (including the trailing newline) so a consumer can + * pipe them straight to stdout / a download stream without re-joining: + * + * for await (const line of client.events.exportAuditEntriesNdjson(orgId, q)) { + * process.stdout.write(line); + * } + */ + async *exportAuditEntriesNdjson( + orgId: string, + query: ListAuditEntriesQuery = { by: "org" }, + opts: RequestOptions = {}, + ): AsyncGenerator { + for await (const entry of this.iterAuditEntries(orgId, query, opts)) { + yield `${JSON.stringify(entry)}\n`; + } + } +} + +interface AuditRequestInput { + method: "GET"; + path: string; + query: Record; +} + +function buildAuditRequest( + orgId: string, + query: ListAuditEntriesQuery, +): AuditRequestInput { + const params: Record = {}; + if (query.limit !== undefined) params.limit = query.limit; + if (query.cursor !== undefined) params.cursor = query.cursor; + if (query.by === "org") { + if (query.category !== undefined) params.category = query.category; + if (query.actorId !== undefined) params.actorId = query.actorId; + if (query.actorType !== undefined) params.actorType = query.actorType; + if (query.subjectKind !== undefined) params.subjectKind = query.subjectKind; + if (query.subjectId !== undefined) params.subjectId = query.subjectId; + if (query.eventType !== undefined) params.eventType = query.eventType; + if (query.from !== undefined) params.from = query.from; + if (query.to !== undefined) params.to = query.to; + } else { + params.subjectKind = query.subjectKind; + params.subjectId = query.subjectId; + } + return { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/audit`, + query: params, + }; +} + +function createAuditIterator( + transport: Transport, + orgId: string, + initialQuery: ListAuditEntriesQuery, + opts: RequestOptions, +): AsyncIterator { + let bufferedEntries: PublicAuditEntry[] = []; + let bufferIndex = 0; + let nextCursor: string | undefined = initialQuery.cursor; + let pagesRead = 0; + let exhausted = false; + const seenCursors = new Set(); + + return { + async next(): Promise> { + while (true) { + if (bufferIndex < bufferedEntries.length) { + const value = bufferedEntries[bufferIndex] as PublicAuditEntry; + bufferIndex += 1; + return { value, done: false }; + } + if (exhausted) { + return { value: undefined, done: true }; + } + if (pagesRead >= AUDIT_ITERATOR_MAX_PAGES) { + throw new Error( + `audit iterator exceeded ${AUDIT_ITERATOR_MAX_PAGES} page reads — refusing to continue`, + ); + } + + const queryForPage: ListAuditEntriesQuery = + initialQuery.by === "org" + ? { + by: "org", + ...(initialQuery.category !== undefined + ? { category: initialQuery.category } + : {}), + ...(initialQuery.actorId !== undefined + ? { actorId: initialQuery.actorId } + : {}), + ...(initialQuery.actorType !== undefined + ? { actorType: initialQuery.actorType } + : {}), + ...(initialQuery.subjectKind !== undefined + ? { subjectKind: initialQuery.subjectKind } + : {}), + ...(initialQuery.subjectId !== undefined + ? { subjectId: initialQuery.subjectId } + : {}), + ...(initialQuery.eventType !== undefined + ? { eventType: initialQuery.eventType } + : {}), + ...(initialQuery.from !== undefined + ? { from: initialQuery.from } + : {}), + ...(initialQuery.to !== undefined + ? { to: initialQuery.to } + : {}), + ...(initialQuery.limit !== undefined + ? { limit: initialQuery.limit } + : {}), + ...(nextCursor !== undefined ? { cursor: nextCursor } : {}), + } + : { + by: "target", + subjectKind: initialQuery.subjectKind, + subjectId: initialQuery.subjectId, + ...(initialQuery.limit !== undefined + ? { limit: initialQuery.limit } + : {}), + ...(nextCursor !== undefined ? { cursor: nextCursor } : {}), + }; + + const { data, meta } = await transport.requestWithEnvelope< + ListAuditEntriesResult + >(buildAuditRequest(orgId, queryForPage), opts); + pagesRead += 1; + + bufferedEntries = data.auditEntries.slice(); + bufferIndex = 0; + + const cursor = meta.cursor; + if (cursor === null || cursor === undefined) { + exhausted = true; + nextCursor = undefined; + } else { + if (seenCursors.has(cursor)) { + throw new Error( + `audit iterator detected a repeated cursor (${cursor}); aborting to avoid an infinite loop`, + ); + } + seenCursors.add(cursor); + nextCursor = cursor; + } + } + }, + }; +} diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts new file mode 100644 index 0000000..e1bb250 --- /dev/null +++ b/packages/sdk/src/index.ts @@ -0,0 +1,315 @@ +// `@saas/sdk` — newtest TypeScript SDK. +// +// Stable public surface: +// - `newtest` → the client class +// - Per-resource clients reachable via `client.` +// - typed error hierarchy from `./errors` +// - request/response types re-exported from `@saas/contracts` +// +// The transport (`Transport`, `generateRequestId`) is exported for advanced +// callers (custom retry middleware, alt resource fan-out) but the typical +// integration path is the `newtest` class. + +import { ApiKeysClient } from "./apiKeys.js"; +import { AuthClient } from "./auth.js"; +import { IntegrationsClient } from "./integrations.js"; +import { BillingClient } from "./billing.js"; +import { ConfigClient } from "./config.js"; +import { EnvironmentsClient } from "./environments.js"; +import { EventsClient } from "./events.js"; +import { MembershipsClient } from "./memberships.js"; +import { MeteringClient } from "./metering.js"; +import { NotificationsClient } from "./notifications.js"; +import { OrganizationsClient } from "./organizations.js"; +import { ProjectsClient } from "./projects.js"; +import { SecurityEventsClient } from "./securityEvents.js"; +import { WebhooksClient } from "./webhooks.js"; +import { Transport, type ClientOptions } from "./transport.js"; + +export class newtest { + readonly organizations: OrganizationsClient; + readonly projects: ProjectsClient; + readonly environments: EnvironmentsClient; + readonly memberships: MembershipsClient; + readonly apiKeys: ApiKeysClient; + readonly webhooks: WebhooksClient; + readonly metering: MeteringClient; + readonly billing: BillingClient; + readonly events: EventsClient; + readonly securityEvents: SecurityEventsClient; + readonly config: ConfigClient; + readonly notifications: NotificationsClient; + readonly auth: AuthClient; + readonly integrations: IntegrationsClient; + /** Underlying HTTP transport. Exposed for advanced extension. */ + readonly transport: Transport; + + constructor(options: ClientOptions) { + this.transport = new Transport(options); + this.organizations = new OrganizationsClient(this.transport); + this.projects = new ProjectsClient(this.transport); + this.environments = new EnvironmentsClient(this.transport); + this.memberships = new MembershipsClient(this.transport); + this.apiKeys = new ApiKeysClient(this.transport); + this.webhooks = new WebhooksClient(this.transport); + this.metering = new MeteringClient(this.transport); + this.billing = new BillingClient(this.transport); + this.events = new EventsClient(this.transport); + this.securityEvents = new SecurityEventsClient(this.transport); + this.config = new ConfigClient(this.transport); + this.notifications = new NotificationsClient(this.transport); + this.auth = new AuthClient(this.transport); + this.integrations = new IntegrationsClient(this.transport); + } +} + +// Resource clients (also reachable via `client.`). +export { OrganizationsClient } from "./organizations.js"; +export { ProjectsClient } from "./projects.js"; +export { EnvironmentsClient } from "./environments.js"; +export { MembershipsClient } from "./memberships.js"; +export { + ApiKeysClient, + type ListApiKeysResponse, + type GetApiKeyResponse, + type CreateApiKeyResponse, + type RevokeApiKeyResponse, +} from "./apiKeys.js"; +export { + WebhooksClient, + type ListDeliveryAttemptsQuery, + type DeliveryAttemptsPage, +} from "./webhooks.js"; +export { MeteringClient } from "./metering.js"; +export { BillingClient } from "./billing.js"; +export { + EventsClient, + AUDIT_ITERATOR_MAX_PAGES, + type AuditEntryFilters, + type ListAuditEntriesQuery, + type ListAuditEntriesResult, +} from "./events.js"; +export { + SecurityEventsClient, + type ListSecurityEventsQuery, + type SecurityEventsPage, +} from "./securityEvents.js"; +export { ConfigClient, type ConfigScope } from "./config.js"; +export { NotificationsClient } from "./notifications.js"; +export { AuthClient } from "./auth.js"; +export { IntegrationsClient } from "./integrations.js"; + +// Transport surface. +export { + Transport, + generateRequestId, + type AuthOption, + type ClientOptions, + type RequestOptions, + type SuccessEnvelope, +} from "./transport.js"; + +// Typed error hierarchy. +export { + newtestError, + BadRequestError, + UnauthenticatedError, + ForbiddenError, + NotFoundError, + ConflictError, + ValidationError, + PreconditionFailedError, + UnsupportedError, + InternalError, + RateLimitError, + decodeError, + type ErrorEnvelope, + type RateLimitWindow, +} from "./errors.js"; + +// Re-export contract types so consumers don't import `@saas/contracts` directly. +export type { + PublicOrganization, + CreateOrganizationRequest, + CreateOrganizationResponse, + GetOrganizationResponse, + ListOrganizationsResponse, + PublicMember, + PublicMemberRoleAssignment, + ListMembersResponse, + InvitationRole, + CreateInvitationRequest, + CreateInvitationResponse, + PublicInvitation, + ListInvitationsResponse, + RevokeInvitationResponse, + UpdateMemberRoleRequest, + UpdateMemberRoleResponse, + RemoveMemberResponse, + AcceptInvitationRequest, + AcceptInvitationResponse, +} from "@saas/contracts/membership"; + +export { ORGANIZATION_ROLES } from "@saas/contracts/membership"; + +export type { + PublicProject, + PublicEnvironment, + CreateProjectRequest, + CreateProjectResponse, + GetProjectResponse, + ListProjectsResponse, + ArchiveProjectResponse, + CreateEnvironmentRequest, + CreateEnvironmentResponse, + GetEnvironmentResponse, + ListEnvironmentsResponse, + ArchiveEnvironmentResponse, +} from "@saas/contracts/projects"; + +export type { + PublicApiKey, + PublicApiKeyServicePrincipal, + PublicApiKeyCreateResult, + PublicApiKeyRevokeResult, + CreateApiKeyRequest, +} from "@saas/contracts/api-keys"; + +export type { + PublicWebhookEndpoint, + ListWebhookEndpointsResponse, + GetWebhookEndpointResponse, + CreateWebhookEndpointRequest, + CreateWebhookEndpointResponse, + UpdateWebhookEndpointRequest, + UpdateWebhookEndpointResponse, + EnableWebhookEndpointRequest, + EnableWebhookEndpointResponse, + DisableWebhookEndpointRequest, + DisableWebhookEndpointResponse, + DeleteWebhookEndpointResponse, + RotateWebhookSecretResponse, + PublicWebhookSubscription, + ListWebhookSubscriptionsResponse, + GetWebhookSubscriptionResponse, + CreateWebhookSubscriptionRequest, + CreateWebhookSubscriptionResponse, + UpdateWebhookSubscriptionRequest, + UpdateWebhookSubscriptionResponse, + DeleteWebhookSubscriptionResponse, + PublicWebhookDeliveryAttempt, + ListWebhookDeliveryAttemptsResponse, + GetWebhookDeliveryAttemptResponse, + ReplayWebhookDeliveryRequest, + ReplayWebhookDeliveryResponse, +} from "@saas/contracts/webhooks"; + +export type { + RecordUsageRequest, + RecordUsageResponse, + PublicUsageRecord, + IngestUsageBatchRequest, + IngestUsageBatchResponse, + GetUsageSummaryRequest, + PublicUsageRollup, + GetUsageSummaryResponse, + CheckQuotaRequest, + CheckQuotaResponse, + ListQuotaViolationsRequest, + PublicQuotaViolation, + ListQuotaViolationsResponse, +} from "@saas/contracts/metering"; + +export type { + PublicPlan, + PublicPlanStatus, + PublicBillingInterval, + ListPlansRequest, + ListPlansResponse, + PublicBillingCustomer, + PublicBillingCustomerStatus, + GetBillingCustomerResponse, + PublicSubscription, + PublicSubscriptionStatus, + PublicInvoice, + PublicInvoiceStatus, + ListInvoicesRequest, + ListInvoicesResponse, + PublicEntitlement, + PublicEntitlementValueType, + PublicEntitlementSource, + GetEntitlementsRequest, + GetEntitlementsResponse, + GetBillingSummaryResponse, +} from "@saas/contracts/billing"; + +export type { + PublicAuditEntry, + ListAuditEntriesResponse, + EventActorType, +} from "@saas/contracts/events"; + +export type { + PublicSecurityEvent, + SecurityEventListResponse, +} from "@saas/contracts/security-events"; + +export type { + PublicSetting, + ListSettingsResponse, + CreateSettingRequest, + UpdateSettingRequest, + CreateSettingResponse, + UpdateSettingResponse, + PublicFeatureFlag, + ListFeatureFlagsResponse, + CreateFeatureFlagRequest, + UpdateFeatureFlagRequest, + CreateFeatureFlagResponse, + UpdateFeatureFlagResponse, + PublicSecretMetadata, + ListSecretMetadataResponse, + CreateSecretMetadataRequest, + CreateSecretRequest, + CreateSecretMetadataResponse, + RotateSecretRequest, + RotateSecretMetadataResponse, + RevokeSecretMetadataResponse, +} from "@saas/contracts/config"; + +export type { + NotificationChannel, + NotificationCategory, + NotificationStatus, + NotificationSubjectKind, + NotificationRecipient, + EnqueueNotificationRequest, + EnqueueNotificationResponse, + GetNotificationResponse, + NotificationDeliveryStatus, + NotificationAttempt, + NotificationCategoryPreferences, + NotificationPreference, + GetNotificationPreferencesQuery, + GetNotificationPreferencesResponse, + UpdateNotificationPreferencesRequest, + UpdateNotificationPreferencesResponse, + NotificationSuppressionReason, + NotificationSuppression, + SuppressRecipientRequest, + SuppressRecipientResponse, +} from "@saas/contracts/notifications"; + +export { ERROR_CODES, type ErrorCode } from "@saas/contracts/errors"; + +export type { + LoginStartRequest, + LoginStartResponse, + LoginCompleteRequest, + LoginCompleteResponse, + SessionResponse, + LogoutResponse, + ProfileResponse, + UpdateProfileRequest, + AuthUser, +} from "@saas/contracts/auth"; diff --git a/packages/sdk/src/integrations.ts b/packages/sdk/src/integrations.ts new file mode 100644 index 0000000..01550ba --- /dev/null +++ b/packages/sdk/src/integrations.ts @@ -0,0 +1,233 @@ +import type { + ConnectIntegrationRequest, + IssueIntegrationTokenRequest, + IssueIntegrationTokenResponse, + CreateRepoLinkRequest, + CreateRepoLinkResponse, + DeleteRepoLinkResponse, + ListRepoLinksResponse, + ListRepositoriesResponse, + UpdateRepoLinkRequest, + UpdateRepoLinkResponse, + ConnectIntegrationResponse, + GetIntegrationResponse, + ListIntegrationsResponse, + ListInboundDeliveriesResponse, + ReplayInboundDeliveryResponse, + RevokeIntegrationResponse, +} from "@saas/contracts/integrations"; + +import type { Transport, RequestOptions } from "./transport.js"; + +/** + * Integrations resource client (GitHub App connections). + * + * Org-scoped: every method takes `orgId` as the first argument. + * Maps to `apps/integrations-worker` via the api-edge `integrations-facade`. + */ +export class IntegrationsClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/integrations */ + list(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/integrations/:connectionId */ + get(orgId: string, connectionId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/${encodeURIComponent(connectionId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/integrations/github/connect + * + * Returns a pending connection plus the provider install URL carrying the + * signed single-use state; open the URL in a popup and poll `get` until the + * connection turns `active`. + */ + connectGithub( + orgId: string, + body: ConnectIntegrationRequest = {}, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/github/connect`, + body, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/integrations/:connectionId/deliveries */ + listDeliveries( + orgId: string, + connectionId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/${encodeURIComponent(connectionId)}/deliveries`, + }, + opts, + ); + } + + /** + * POST .../integrations/:connectionId/deliveries/:deliveryId/replay + * + * Re-runs normalize/emit from the persisted inbox row — never re-trusts + * the wire. + */ + replayDelivery( + orgId: string, + connectionId: string, + deliveryId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/${encodeURIComponent(connectionId)}/deliveries/${encodeURIComponent(deliveryId)}/replay`, + body: {}, + }, + opts, + ); + } + + /** GET .../integrations/:connectionId/repositories?query= */ + listRepositories( + orgId: string, + connectionId: string, + query?: string, + opts: RequestOptions = {}, + ): Promise { + const qs = query ? `?query=${encodeURIComponent(query)}` : ""; + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/${encodeURIComponent(connectionId)}/repositories${qs}`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/projects/:projectId/repo-links */ + listRepoLinks( + orgId: string, + projectId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/repo-links`, + }, + opts, + ); + } + + /** POST /v1/organizations/:orgId/projects/:projectId/repo-links */ + createRepoLink( + orgId: string, + projectId: string, + body: CreateRepoLinkRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/repo-links`, + body, + }, + opts, + ); + } + + /** PATCH .../repo-links/:repoLinkId */ + updateRepoLink( + orgId: string, + projectId: string, + repoLinkId: string, + body: UpdateRepoLinkRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/repo-links/${encodeURIComponent(repoLinkId)}`, + body, + }, + opts, + ); + } + + /** DELETE .../repo-links/:repoLinkId (soft unlink) */ + unlinkRepoLink( + orgId: string, + projectId: string, + repoLinkId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/repo-links/${encodeURIComponent(repoLinkId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/integrations/github/token — the broker. + * + * Exchanges the caller's control-plane credential for a short-lived + * (≤1h), repo-scoped GitHub installation token. Repositories must be + * linked to projects in the organization; permissions must be within the + * App's grant. The token is returned exactly once — handle it like a + * password and let it expire (it is never cached platform-side). + */ + issueGithubToken( + orgId: string, + body: IssueIntegrationTokenRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/github/token`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/integrations/:connectionId */ + revoke( + orgId: string, + connectionId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/integrations/${encodeURIComponent(connectionId)}`, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/memberships.ts b/packages/sdk/src/memberships.ts new file mode 100644 index 0000000..3a1398d --- /dev/null +++ b/packages/sdk/src/memberships.ts @@ -0,0 +1,146 @@ +import type { + AcceptInvitationRequest, + AcceptInvitationResponse, + CreateInvitationRequest, + CreateInvitationResponse, + ListInvitationsResponse, + ListMembersResponse, + RemoveMemberResponse, + RevokeInvitationResponse, + UpdateMemberRoleRequest, + UpdateMemberRoleResponse, +} from "@saas/contracts/membership"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Memberships resource client. + * + * Covers the org-facade member + invitation surface served by + * `apps/membership-worker`. The flat-method shape mirrors Stripe's + * `client.invitations.create()` style; sub-resources are namespaced via + * the verb (`listMembers`, `listInvitations`) so call sites stay grep-able. + */ +export class MembershipsClient { + constructor(private readonly transport: Transport) {} + + // ------------------------------------------------------------------------- + // Members + // ------------------------------------------------------------------------- + + /** GET /v1/organizations/:orgId/members */ + listMembers(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/members`, + }, + opts, + ); + } + + /** PATCH /v1/organizations/:orgId/members/:memberId */ + updateMemberRole( + orgId: string, + memberId: string, + body: UpdateMemberRoleRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `/v1/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/members/:memberId */ + removeMember( + orgId: string, + memberId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(memberId)}`, + }, + opts, + ); + } + + // ------------------------------------------------------------------------- + // Invitations + // ------------------------------------------------------------------------- + + /** GET /v1/organizations/:orgId/invitations */ + listInvitations( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/invitations`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/invitations + * + * Pass `idempotencyKey` in `opts` for safe retry semantics. + */ + createInvitation( + orgId: string, + body: CreateInvitationRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/invitations`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/invitations/:invitationId */ + revokeInvitation( + orgId: string, + invitationId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/invitations/${encodeURIComponent(invitationId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/invitations/accept + * + * Accept an invitation via the one-time token returned at create time. + */ + acceptInvitation( + orgId: string, + body: AcceptInvitationRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/invitations/accept`, + body, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/metering.ts b/packages/sdk/src/metering.ts new file mode 100644 index 0000000..80f076f --- /dev/null +++ b/packages/sdk/src/metering.ts @@ -0,0 +1,155 @@ +import type { + CheckQuotaRequest, + CheckQuotaResponse, + GetUsageSummaryRequest, + GetUsageSummaryResponse, + IngestUsageBatchRequest, + IngestUsageBatchResponse, + ListQuotaViolationsRequest, + ListQuotaViolationsResponse, + RecordUsageRequest, + RecordUsageResponse, +} from "@saas/contracts/metering"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Metering resource client. + * + * Org-scoped surface served by `apps/metering-worker` via the api-edge + * `metering-facade`. The `recordUsage` and `ingestBatch` writes already carry + * their own per-record idempotency keys in the request body; the transport's + * `Idempotency-Key` header is still honoured for replay protection at the + * api-edge layer (caller-owned, Stripe parity). + */ +export class MeteringClient { + constructor(private readonly transport: Transport) {} + + /** + * POST /v1/organizations/:orgId/usage + * + * Record a single usage event. The body carries its own `idempotencyKey` + * field that the worker uses for dedupe; you may also pass `idempotencyKey` + * in `opts` for transport-layer replay safety. + */ + recordUsage( + orgId: string, + body: RecordUsageRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/usage`, + body, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/usage/batch + * + * Ingest a batch of usage events; each record returns its own success or + * error result in the response array. + */ + ingestUsageBatch( + orgId: string, + body: IngestUsageBatchRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/usage/batch`, + body, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/usage/summary */ + getUsageSummary( + orgId: string, + query: GetUsageSummaryRequest, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ + metric: query.metric, + projectId: query.projectId ?? undefined, + environmentId: query.environmentId ?? undefined, + bucketType: query.bucketType, + startTime: query.startTime, + endTime: query.endTime, + }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/usage/summary`, + query: params, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/quotas/check */ + checkQuota( + orgId: string, + query: CheckQuotaRequest, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ + metric: query.metric, + projectId: query.projectId, + environmentId: query.environmentId, + resourceId: query.resourceId, + }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/quotas/check`, + query: params, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/quotas/violations */ + listQuotaViolations( + orgId: string, + query: ListQuotaViolationsRequest = {}, + opts: RequestOptions = {}, + ): Promise { + const params = buildQueryRecord({ + projectId: query.projectId, + environmentId: query.environmentId, + resourceId: query.resourceId, + metric: query.metric, + limit: query.limit, + cursor: query.cursor ? JSON.stringify(query.cursor) : undefined, + }); + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/quotas/violations`, + query: params, + }, + opts, + ); + } +} + +/** + * Strip `undefined`/`null` entries from a query record so the URL builder + * doesn't emit empty `key=` params. + */ +function buildQueryRecord( + input: Record, +): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(input)) { + if (v === undefined || v === null) continue; + out[k] = v; + } + return out; +} diff --git a/packages/sdk/src/notifications.ts b/packages/sdk/src/notifications.ts new file mode 100644 index 0000000..b88a70f --- /dev/null +++ b/packages/sdk/src/notifications.ts @@ -0,0 +1,118 @@ +import type { + EnqueueNotificationRequest, + EnqueueNotificationResponse, + GetNotificationResponse, + GetNotificationPreferencesQuery, + GetNotificationPreferencesResponse, + SuppressRecipientRequest, + SuppressRecipientResponse, + UpdateNotificationPreferencesRequest, + UpdateNotificationPreferencesResponse, +} from "@saas/contracts/notifications"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Notifications resource client. + * + * Backed by `apps/notifications-worker`. NOTE: per spec 14 the V1 surface is + * service-binding-internal — there is intentionally no public `api-edge` + * facade. The worker enforces this by requiring the `x-internal-actor`, + * `x-actor-subject-id`, and `x-actor-subject-type` headers on every request. + * + * This SDK exposes the typed shape so internal callers (other workers, the + * newtest backplane gateway, the CLI's privileged internal mode) can hit + * the worker over a service binding with the correct headers passed via + * `opts.headers`. External consumers MUST NOT receive this client wired to a + * public base URL. + */ +export class NotificationsClient { + constructor(private readonly transport: Transport) {} + + /** + * POST /v1/notifications + * + * Enqueue a transactional notification. Pass `idempotencyKey` in `opts` for + * safe retry semantics; the request body also carries an optional + * `idempotencyKey` field that the worker uses for content-level dedupe. + */ + enqueue( + body: EnqueueNotificationRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "POST", path: "/v1/notifications", body }, + opts, + ); + } + + /** GET /v1/notifications/:notificationId */ + get( + notificationId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/notifications/${encodeURIComponent(notificationId)}`, + }, + opts, + ); + } + + /** + * GET /v1/notifications/preferences + * + * Reads per-subject preferences. The worker scopes by the + * `x-actor-subject-id` / `x-actor-subject-type` headers; the `query` + * argument is reserved for forward compatibility (channel filter etc.) and + * is sent as query-string parameters. + */ + getPreferences( + query: Partial = {}, + opts: RequestOptions = {}, + ): Promise { + const params: Record = {}; + if (query.orgId) params.orgId = query.orgId; + if (query.subjectKind) params.subjectKind = query.subjectKind; + if (query.subjectId) params.subjectId = query.subjectId; + if (query.channel) params.channel = query.channel; + return this.transport.request( + { method: "GET", path: "/v1/notifications/preferences", query: params }, + opts, + ); + } + + /** PUT /v1/notifications/preferences */ + updatePreferences( + body: UpdateNotificationPreferencesRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "PUT", path: "/v1/notifications/preferences", body }, + opts, + ); + } + + /** + * POST /v1/notifications/recipients/:address/suppress + * + * Suppress further delivery to a recipient address. The body carries the + * org id, channel, and reason; the URL slot carries the address verbatim + * (already URL-encoded by the SDK). + */ + suppressRecipient( + address: string, + body: SuppressRecipientRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/notifications/recipients/${encodeURIComponent(address)}/suppress`, + body, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/organizations.ts b/packages/sdk/src/organizations.ts new file mode 100644 index 0000000..04bbed7 --- /dev/null +++ b/packages/sdk/src/organizations.ts @@ -0,0 +1,51 @@ +import type { + CreateOrganizationRequest, + CreateOrganizationResponse, + GetOrganizationResponse, + ListOrganizationsResponse, +} from "@saas/contracts/membership"; + +import type { Transport, RequestOptions } from "./transport.js"; + +/** + * Organizations resource client. + * + * Maps 1:1 to the api-edge `/v1/organizations` surface owned by + * `apps/membership-worker` via the `org-facade` route. POST goes through + * the idempotency-key surface (Stripe parity — caller-owned key). + */ +export class OrganizationsClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations — orgs the actor is a member of. */ + list(opts: RequestOptions = {}): Promise { + return this.transport.request( + { method: "GET", path: "/v1/organizations" }, + opts, + ); + } + + /** GET /v1/organizations/:orgId */ + get(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { method: "GET", path: `/v1/organizations/${encodeURIComponent(orgId)}` }, + opts, + ); + } + + /** + * POST /v1/organizations + * + * Pass `idempotencyKey` in `opts` to make the request safely retryable. + * The SDK does not auto-generate one; the server treats the key as opaque. + */ + create( + body: CreateOrganizationRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { method: "POST", path: "/v1/organizations", body }, + opts, + ); + } +} diff --git a/packages/sdk/src/projects.ts b/packages/sdk/src/projects.ts new file mode 100644 index 0000000..c6e521e --- /dev/null +++ b/packages/sdk/src/projects.ts @@ -0,0 +1,85 @@ +import type { + ArchiveProjectResponse, + CreateProjectRequest, + CreateProjectResponse, + GetProjectResponse, + ListProjectsResponse, +} from "@saas/contracts/projects"; + +import type { Transport, RequestOptions } from "./transport.js"; + +/** + * Projects resource client. + * + * Org-scoped: every method takes `orgId` as the first argument. + * Maps to `apps/projects-worker` via the api-edge `project-facade` route. + */ +export class ProjectsClient { + constructor(private readonly transport: Transport) {} + + /** GET /v1/organizations/:orgId/projects */ + list(orgId: string, opts: RequestOptions = {}): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/projects/:projectId */ + get( + orgId: string, + projectId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/projects + * + * Pass `idempotencyKey` in `opts` for safe retry semantics. + */ + create( + orgId: string, + body: CreateProjectRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects`, + body, + }, + opts, + ); + } + + /** + * DELETE /v1/organizations/:orgId/projects/:projectId + * + * api-edge maps this to a soft-archive on the projects-worker; the response + * envelope returns the archived `PublicProject` shape. + */ + archive( + orgId: string, + projectId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}`, + }, + opts, + ); + } +} diff --git a/packages/sdk/src/securityEvents.ts b/packages/sdk/src/securityEvents.ts new file mode 100644 index 0000000..22b2b9d --- /dev/null +++ b/packages/sdk/src/securityEvents.ts @@ -0,0 +1,109 @@ +import type { + PublicSecurityEvent, + SecurityEventListResponse, +} from "@saas/contracts/security-events"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Cursor-pagination query for the security-events list. Both fields are + * optional and map 1:1 to the only two query params the identity-worker reads + * for this surface (`limit` and an opaque `cursor`). + * + * `cursor` is the server-issued continuation token surfaced on the previous + * page's `meta.cursor` (an opaque base64 string — callers MUST NOT construct + * or parse it). Pass it back verbatim to fetch the next page. + */ +export interface ListSecurityEventsQuery { + /** Page size. The server clamps to its own bounds when omitted. */ + limit?: number; + /** Opaque continuation cursor from the previous page's `meta.cursor`. */ + cursor?: string; +} + +/** + * Single page of security events plus the server-issued continuation cursor. + * `nextCursor` is `null` when there are no further pages, mirroring the + * api-edge `meta.cursor` field exactly (same shape as + * `WebhooksClient.listDeliveryAttemptsPage` / + * `EventsClient.listAuditEntriesPage`). + */ +export interface SecurityEventsPage { + securityEvents: ReadonlyArray; + nextCursor: string | null; +} + +/** + * Security Events resource client. + * + * The api-edge exposes this surface at `GET /v1/auth/security-events` + * (note: actor-scoped, not org-scoped — backed by `apps/identity-worker` + * via the `auth-facade`). Returns the public security-event projection + * with secrets, codes, and credential material already stripped by the + * worker. + */ +export class SecurityEventsClient { + constructor(private readonly transport: Transport) {} + + /** + * GET /v1/auth/security-events + * + * Threads optional `limit`/`cursor` query params through to the worker. + * Returns the contract `data` payload only — the continuation cursor lives + * on `meta.cursor`, NOT in this body, so use {@link listPage} when you need + * to paginate. + */ + list( + query: ListSecurityEventsQuery = {}, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + buildSecurityEventsRequest(query), + opts, + ); + } + + /** + * Single-page security-events fetch that also exposes the server-issued + * continuation cursor (`meta.cursor`). Use this to drive a paginated UI: + * the returned `nextCursor` is `null` when there are no further pages, and + * otherwise an opaque token to pass back as `query.cursor` for the next + * call. Mirrors `WebhooksClient.listDeliveryAttemptsPage` / + * `EventsClient.listAuditEntriesPage`. + */ + async listPage( + query: ListSecurityEventsQuery = {}, + opts: RequestOptions = {}, + ): Promise { + const { data, meta } = + await this.transport.requestWithEnvelope( + buildSecurityEventsRequest(query), + opts, + ); + return { + securityEvents: data.securityEvents, + nextCursor: meta.cursor ?? null, + }; + } +} + +/** + * Build the GET request for the security-events list, threading the optional + * `limit`/`cursor` query params (omitting `undefined` so the URL builder never + * emits an empty `key=`). Shared by `list` and `listPage` so the wire shape + * stays in lock-step. + */ +function buildSecurityEventsRequest(query: ListSecurityEventsQuery): { + method: "GET"; + path: string; + query: Record; +} { + const params: Record = {}; + if (query.limit !== undefined) params.limit = query.limit; + if (query.cursor !== undefined) params.cursor = query.cursor; + return { + method: "GET", + path: "/v1/auth/security-events", + query: params, + }; +} diff --git a/packages/sdk/src/transport.ts b/packages/sdk/src/transport.ts new file mode 100644 index 0000000..26aa9a5 --- /dev/null +++ b/packages/sdk/src/transport.ts @@ -0,0 +1,228 @@ +// Base HTTP transport for the newtest SDK. +// +// Goals: +// - Runtime-agnostic: native `fetch`, native `crypto.randomUUID`, no `node:*`. +// - Stripe-style ergonomics: `Idempotency-Key` is a per-request option, +// request-id auto-generated when caller omits it, abort signal passthrough. +// - Typed errors: every non-2xx response is decoded into a `newtestError` +// subclass via `decodeError`. +// - Forward-compatible envelope: success responses are `{ data: T, meta: {...} }` +// today; the transport only requires the `data` field to exist. + +import { decodeError } from "./errors.js"; + +export type AuthOption = + | { kind: "bearer"; token: string } + | { kind: "session"; cookie: string }; + +export interface ClientOptions { + /** + * Base URL of the newtest api-edge worker, e.g. + * `https://api.new-test.dev`. Trailing slash is stripped. + */ + baseUrl: string; + /** Optional auth credential; sent on every request when present. */ + auth?: AuthOption; + /** Default headers merged into every request (per-request wins on conflict). */ + defaultHeaders?: Record; + /** + * Custom `fetch` implementation. Defaults to the platform global. Useful + * for tests, retries-on-the-outside, or polyfilled environments. + */ + fetch?: typeof fetch; +} + +export interface RequestOptions { + /** + * Per-request idempotency key. Caller-owned (Stripe parity) — the SDK does + * NOT auto-generate one for unsafe methods. When omitted, no + * `Idempotency-Key` header is sent. + */ + idempotencyKey?: string; + /** Abort signal forwarded to fetch. */ + signal?: AbortSignal; + /** + * Request id for distributed tracing. When omitted, the SDK generates a + * `req_` value and sends it as `x-request-id`. + */ + requestId?: string; + /** Per-request header overrides (merged after defaults). */ + headers?: Record; +} + +export interface SuccessEnvelope { + data: T; + meta: { requestId: string; cursor?: string | null }; +} + +interface PerformInput { + method: string; + path: string; + query?: Record | undefined; + body?: unknown; +} + +/** + * Internal HTTP gateway. Resource clients receive an instance of this and call + * `request()`; they never see `fetch` directly. + * + * The transport is intentionally exported so power users can drive it without + * the high-level resource namespaces, but the public stable surface is + * `newtest` (the client class wired up in `index.ts`). + */ +export class Transport { + readonly baseUrl: string; + readonly auth: AuthOption | undefined; + readonly defaultHeaders: Record; + readonly fetchImpl: typeof fetch; + + constructor(options: ClientOptions) { + this.baseUrl = options.baseUrl.replace(/\/+$/, ""); + this.auth = options.auth; + this.defaultHeaders = { ...(options.defaultHeaders ?? {}) }; + const fetchImpl = options.fetch ?? globalThis.fetch; + if (typeof fetchImpl !== "function") { + throw new TypeError( + "newtest SDK requires a fetch implementation. Pass `fetch` in options on platforms without a global.", + ); + } + this.fetchImpl = fetchImpl.bind(globalThis); + } + + async request(input: PerformInput, opts: RequestOptions = {}): Promise { + const { data } = await this.performRequest(input, opts); + return data; + } + + /** + * Envelope-aware sibling of `request`. Returns BOTH the unwrapped `data` + * payload AND the `meta` block (request id + optional cursor) so paginated + * resource clients can drive cursor-based loops without reaching into raw + * `fetchImpl`. Same auth / idempotency / abort-signal semantics as + * `request`. + * + * Added for Task 0102 (SDK-side close of audit pagination gap surfaced by + * Task 0101). `EventsClient.iterAuditEntries` consumes this; future + * paginated reads (security events, future feeds) can adopt the same + * pattern. + */ + async requestWithEnvelope( + input: PerformInput, + opts: RequestOptions = {}, + ): Promise<{ data: T; meta: { requestId: string; cursor?: string | null } }> { + return this.performRequest(input, opts); + } + + private async performRequest( + input: PerformInput, + opts: RequestOptions, + ): Promise<{ data: T; meta: { requestId: string; cursor?: string | null } }> { + const url = this.buildUrl(input.path, input.query); + const requestId = opts.requestId ?? generateRequestId(); + + const headers = new Headers(); + for (const [k, v] of Object.entries(this.defaultHeaders)) headers.set(k, v); + if (this.auth) applyAuth(headers, this.auth); + + let body: BodyInit | undefined; + if (input.body !== undefined) { + headers.set("content-type", "application/json"); + body = JSON.stringify(input.body); + } + + headers.set("accept", "application/json"); + headers.set("x-request-id", requestId); + if (opts.idempotencyKey !== undefined) { + headers.set("idempotency-key", opts.idempotencyKey); + } + if (opts.headers) { + for (const [k, v] of Object.entries(opts.headers)) headers.set(k, v); + } + + const init: RequestInit = { + method: input.method, + headers, + }; + if (body !== undefined) init.body = body; + if (opts.signal !== undefined) init.signal = opts.signal; + + const response = await this.fetchImpl(url, init); + + if (!response.ok) { + throw await decodeError(response, requestId); + } + + if (response.status === 204) { + // No content: caller-supplied T is implicitly `void`/`null`-shaped. + return { data: undefined as T, meta: { requestId } }; + } + + const parsed: unknown = await response.json(); + if (isSuccessEnvelope(parsed)) { + const meta = parsed.meta ?? { requestId }; + return { data: parsed.data as T, meta }; + } + // Defensive: server returned a 2xx with a non-conformant body. Surface the + // raw payload to the caller rather than crashing. + return { data: parsed as T, meta: { requestId } }; + } + + private buildUrl( + path: string, + query: Record | undefined, + ): string { + const normalized = path.startsWith("/") ? path : `/${path}`; + const url = new URL(this.baseUrl + normalized); + if (query) { + for (const [k, v] of Object.entries(query)) { + if (v === undefined) continue; + url.searchParams.set(k, String(v)); + } + } + return url.toString(); + } +} + +function applyAuth(headers: Headers, auth: AuthOption): void { + switch (auth.kind) { + case "bearer": + headers.set("authorization", `Bearer ${auth.token}`); + return; + case "session": + headers.set("cookie", auth.cookie); + return; + } +} + +/** + * Generate a `req_`-shaped request id using the platform `crypto.randomUUID`. + * Falls back to a `getRandomValues`-derived hex string on the (rare) platforms + * that expose `crypto` but not `randomUUID`. + */ +export function generateRequestId(): string { + const cryptoRef = globalThis.crypto; + if (cryptoRef && typeof cryptoRef.randomUUID === "function") { + return `req_${cryptoRef.randomUUID().replace(/-/g, "")}`; + } + if (cryptoRef && typeof cryptoRef.getRandomValues === "function") { + const buf = new Uint8Array(16); + cryptoRef.getRandomValues(buf); + let hex = ""; + for (let i = 0; i < buf.length; i++) { + hex += (buf[i] ?? 0).toString(16).padStart(2, "0"); + } + return `req_${hex}`; + } + throw new Error( + "newtest SDK requires the Web Crypto API (globalThis.crypto). No source of randomness was found.", + ); +} + +function isSuccessEnvelope(value: unknown): value is SuccessEnvelope { + return ( + typeof value === "object" && + value !== null && + "data" in value && + !Array.isArray(value) + ); +} diff --git a/packages/sdk/src/webhooks.ts b/packages/sdk/src/webhooks.ts new file mode 100644 index 0000000..a4fc28b --- /dev/null +++ b/packages/sdk/src/webhooks.ts @@ -0,0 +1,446 @@ +import type { + CreateWebhookEndpointRequest, + CreateWebhookEndpointResponse, + CreateWebhookSubscriptionRequest, + CreateWebhookSubscriptionResponse, + DeleteWebhookEndpointResponse, + DeleteWebhookSubscriptionResponse, + DisableWebhookEndpointRequest, + DisableWebhookEndpointResponse, + EnableWebhookEndpointRequest, + EnableWebhookEndpointResponse, + GetWebhookDeliveryAttemptResponse, + GetWebhookEndpointResponse, + GetWebhookSubscriptionResponse, + ListWebhookDeliveryAttemptsResponse, + ListWebhookEndpointsResponse, + ListWebhookSubscriptionsResponse, + PublicWebhookDeliveryAttempt, + ReplayWebhookDeliveryResponse, + RotateWebhookSecretResponse, + UpdateWebhookEndpointRequest, + UpdateWebhookEndpointResponse, + UpdateWebhookSubscriptionRequest, + UpdateWebhookSubscriptionResponse, +} from "@saas/contracts/webhooks"; + +import type { RequestOptions, Transport } from "./transport.js"; + +/** + * Cursor-pagination query for the delivery-attempts list. Both fields are + * optional and map 1:1 to the only two query params the webhooks-worker + * `parsePageParams` reads (`limit` 1–100 default 50, opaque `cursor`). + * + * `cursor` is the server-issued continuation token surfaced on the previous + * page's `meta.cursor` (an opaque base64 string — callers MUST NOT construct + * or parse it). Pass it back verbatim to fetch the next page. + */ +export interface ListDeliveryAttemptsQuery { + /** Page size, 1–100. Server defaults to 50 when omitted. */ + limit?: number; + /** Opaque continuation cursor from the previous page's `meta.cursor`. */ + cursor?: string; +} + +/** + * Single page of delivery attempts plus the server-issued continuation + * cursor. `nextCursor` is `null` when there are no further pages, mirroring + * the api-edge `meta.cursor` field exactly (same shape as + * `EventsClient.listAuditEntriesPage`). + */ +export interface DeliveryAttemptsPage { + deliveryAttempts: ReadonlyArray; + nextCursor: string | null; +} + +/** + * Webhooks resource client. + * + * Backed by `apps/webhooks-worker` via the api-edge `webhooks-facade`. The + * facade exposes both an org-scoped surface and a project-scoped surface for + * endpoint listing/creation; subscriptions and delivery attempts are + * org-scoped only. + */ +export class WebhooksClient { + constructor(private readonly transport: Transport) {} + + // ------------------------------------------------------------------------- + // Endpoints — org scope + // ------------------------------------------------------------------------- + + /** GET /v1/organizations/:orgId/webhooks/endpoints */ + listEndpoints( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/projects/:projectId/webhooks/endpoints */ + listProjectEndpoints( + orgId: string, + projectId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/webhooks/endpoints`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/webhooks/endpoints/:endpointId */ + getEndpoint( + orgId: string, + endpointId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/webhooks/endpoints + * + * Pass `idempotencyKey` in `opts` for safe retry semantics. + */ + createEndpoint( + orgId: string, + body: CreateWebhookEndpointRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints`, + body, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/projects/:projectId/webhooks/endpoints + * + * Project-scoped endpoint creation. Pass `idempotencyKey` for retry safety. + */ + createProjectEndpoint( + orgId: string, + projectId: string, + body: CreateWebhookEndpointRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/projects/${encodeURIComponent(projectId)}/webhooks/endpoints`, + body, + }, + opts, + ); + } + + /** PATCH /v1/organizations/:orgId/webhooks/endpoints/:endpointId */ + updateEndpoint( + orgId: string, + endpointId: string, + body: UpdateWebhookEndpointRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}`, + body, + }, + opts, + ); + } + + /** POST /v1/organizations/:orgId/webhooks/endpoints/:endpointId/disable */ + disableEndpoint( + orgId: string, + endpointId: string, + body: DisableWebhookEndpointRequest = {}, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}/disable`, + body, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/webhooks/endpoints/:endpointId/enable + * + * Re-enable a disabled webhook endpoint. Body is empty (the contract + * carries no fields). Pass `idempotencyKey` in `opts` for retry safety. + * The worker returns the public endpoint envelope on success and a + * standard `not_found` envelope when the endpoint is already active or + * missing. + */ + enableEndpoint( + orgId: string, + endpointId: string, + body: EnableWebhookEndpointRequest = {}, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}/enable`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/webhooks/endpoints/:endpointId */ + deleteEndpoint( + orgId: string, + endpointId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/webhooks/endpoints/:endpointId/rotate-secret + * + * Bumps the endpoint's `secretVersion`. The new secret material is delivered + * out-of-band via the worker — the response carries only metadata. + */ + rotateSecret( + orgId: string, + endpointId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}/rotate-secret`, + }, + opts, + ); + } + + // ------------------------------------------------------------------------- + // Subscriptions — org scope + // ------------------------------------------------------------------------- + + /** GET /v1/organizations/:orgId/webhooks/subscriptions */ + listSubscriptions( + orgId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/subscriptions`, + }, + opts, + ); + } + + /** GET /v1/organizations/:orgId/webhooks/subscriptions/:subscriptionId */ + getSubscription( + orgId: string, + subscriptionId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/webhooks/subscriptions + * + * Pass `idempotencyKey` in `opts` for safe retry semantics. + */ + createSubscription( + orgId: string, + body: CreateWebhookSubscriptionRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/subscriptions`, + body, + }, + opts, + ); + } + + /** PATCH /v1/organizations/:orgId/webhooks/subscriptions/:subscriptionId */ + updateSubscription( + orgId: string, + subscriptionId: string, + body: UpdateWebhookSubscriptionRequest, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "PATCH", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, + body, + }, + opts, + ); + } + + /** DELETE /v1/organizations/:orgId/webhooks/subscriptions/:subscriptionId */ + deleteSubscription( + orgId: string, + subscriptionId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "DELETE", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, + }, + opts, + ); + } + + // ------------------------------------------------------------------------- + // Delivery attempts + // ------------------------------------------------------------------------- + + /** + * GET /v1/organizations/:orgId/webhooks/endpoints/:endpointId/delivery-attempts + * + * Threads optional `limit`/`cursor` query params through to the worker + * (`parsePageParams` reads ONLY these two). Returns the contract `data` + * payload. The continuation cursor lives on `meta.cursor`, NOT in this + * body — use {@link listDeliveryAttemptsPage} when you need to paginate. + */ + listDeliveryAttempts( + orgId: string, + endpointId: string, + query: ListDeliveryAttemptsQuery = {}, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + buildDeliveryAttemptsRequest(orgId, endpointId, query), + opts, + ); + } + + /** + * Single-page delivery-attempts fetch that also exposes the server-issued + * continuation cursor (`meta.cursor`). Use this to drive a paginated UI: + * the returned `nextCursor` is `null` when there are no further pages, and + * otherwise an opaque token to pass back as `query.cursor` for the next + * call. Mirrors `EventsClient.listAuditEntriesPage`. + */ + async listDeliveryAttemptsPage( + orgId: string, + endpointId: string, + query: ListDeliveryAttemptsQuery = {}, + opts: RequestOptions = {}, + ): Promise { + const { data, meta } = + await this.transport.requestWithEnvelope( + buildDeliveryAttemptsRequest(orgId, endpointId, query), + opts, + ); + return { + deliveryAttempts: data.deliveryAttempts, + nextCursor: meta.cursor ?? null, + }; + } + + /** GET /v1/organizations/:orgId/webhooks/delivery-attempts/:attemptId */ + getDeliveryAttempt( + orgId: string, + attemptId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/delivery-attempts/${encodeURIComponent(attemptId)}`, + }, + opts, + ); + } + + /** + * POST /v1/organizations/:orgId/webhooks/delivery-attempts/:attemptId/replay + * + * Manually replay a past delivery attempt — re-send the same event to the + * same endpoint through the existing signing/delivery seam. Creates and + * returns a NEW delivery attempt (fresh id, `attemptNumber` 1) carrying its + * post-delivery status; the original attempt is unchanged. Empty body. 404 + * if the attempt is missing or belongs to another org. + */ + replayDelivery( + orgId: string, + attemptId: string, + opts: RequestOptions = {}, + ): Promise { + return this.transport.request( + { + method: "POST", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/delivery-attempts/${encodeURIComponent(attemptId)}/replay`, + body: {}, + }, + opts, + ); + } +} + +/** + * Build the GET request for the delivery-attempts list, threading the + * optional `limit`/`cursor` query params (omitting `undefined` so the URL + * builder never emits an empty `key=`). Shared by `listDeliveryAttempts` + * and `listDeliveryAttemptsPage` so the wire shape stays in lock-step. + */ +function buildDeliveryAttemptsRequest( + orgId: string, + endpointId: string, + query: ListDeliveryAttemptsQuery, +): { + method: "GET"; + path: string; + query: Record; +} { + const params: Record = {}; + if (query.limit !== undefined) params.limit = query.limit; + if (query.cursor !== undefined) params.cursor = query.cursor; + return { + method: "GET", + path: `/v1/organizations/${encodeURIComponent(orgId)}/webhooks/endpoints/${encodeURIComponent(endpointId)}/delivery-attempts`, + query: params, + }; +} diff --git a/packages/sdk/tsconfig.build.json b/packages/sdk/tsconfig.build.json new file mode 100644 index 0000000..90bc1c5 --- /dev/null +++ b/packages/sdk/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "lib": ["ES2022", "DOM"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist", "src/**/*.test.ts", "src/__tests__/**"] +} diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json new file mode 100644 index 0000000..1829ad2 --- /dev/null +++ b/packages/sdk/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/shared/component.yaml b/packages/shared/component.yaml new file mode 100644 index 0000000..8aa4779 --- /dev/null +++ b/packages/shared/component.yaml @@ -0,0 +1,28 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: shared +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-shared + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: shared +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) +# ci: trigger full-component verification (orun v2.20.0 upgrade — workspace tenancy ws_) diff --git a/packages/shared/docs/architecture.md b/packages/shared/docs/architecture.md new file mode 100644 index 0000000..e10786b --- /dev/null +++ b/packages/shared/docs/architecture.md @@ -0,0 +1,9 @@ +# shared — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/shared`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/shared/docs/overview.md b/packages/shared/docs/overview.md new file mode 100644 index 0000000..e7678cf --- /dev/null +++ b/packages/shared/docs/overview.md @@ -0,0 +1,13 @@ +# shared + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/shared/docs/runbook.md b/packages/shared/docs/runbook.md new file mode 100644 index 0000000..1e5bde6 --- /dev/null +++ b/packages/shared/docs/runbook.md @@ -0,0 +1,26 @@ +# shared — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/shared/eslint.config.js b/packages/shared/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/shared/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/shared/package.json b/packages/shared/package.json new file mode 100644 index 0000000..acd1015 --- /dev/null +++ b/packages/shared/package.json @@ -0,0 +1,21 @@ +{ + "name": "@saas/shared", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./ids": "./src/ids.ts", + "./errors": "./src/errors.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3" + } +} diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts new file mode 100644 index 0000000..90bda69 --- /dev/null +++ b/packages/shared/src/errors.ts @@ -0,0 +1,16 @@ +// Generic error utilities — no domain knowledge + +export class ApplicationError extends Error { + constructor( + message: string, + public readonly code: string, + public readonly statusCode: number = 500 + ) { + super(message); + this.name = "ApplicationError"; + } +} + +export function isApplicationError(err: unknown): err is ApplicationError { + return err instanceof ApplicationError; +} diff --git a/packages/shared/src/ids.ts b/packages/shared/src/ids.ts new file mode 100644 index 0000000..6e84e5d --- /dev/null +++ b/packages/shared/src/ids.ts @@ -0,0 +1,14 @@ +// Generic ID utilities — no domain knowledge + +/** + * Generates a simple random ID string. In production, use a CUID2 or ULID library. + * This is a placeholder implementation for local development only. + */ +export function generateId(prefix?: string): string { + const rand = Math.random().toString(36).slice(2, 11); + return prefix ? `${prefix}_${rand}` : rand; +} + +export function isValidId(id: unknown): id is string { + return typeof id === "string" && id.length > 0; +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts new file mode 100644 index 0000000..e9c893f --- /dev/null +++ b/packages/shared/src/index.ts @@ -0,0 +1,2 @@ +export * from "./ids.js"; +export * from "./errors.js"; diff --git a/packages/shared/tsconfig.build.json b/packages/shared/tsconfig.build.json new file mode 100644 index 0000000..4d78c7b --- /dev/null +++ b/packages/shared/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/shared/tsconfig.json b/packages/shared/tsconfig.json new file mode 100644 index 0000000..d84a568 --- /dev/null +++ b/packages/shared/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/testing/component.yaml b/packages/testing/component.yaml new file mode 100644 index 0000000..6512040 --- /dev/null +++ b/packages/testing/component.yaml @@ -0,0 +1,22 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: testing +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-shared + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: test-utilities +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/testing/docs/architecture.md b/packages/testing/docs/architecture.md new file mode 100644 index 0000000..fdedf83 --- /dev/null +++ b/packages/testing/docs/architecture.md @@ -0,0 +1,9 @@ +# testing — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/testing`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/testing/docs/overview.md b/packages/testing/docs/overview.md new file mode 100644 index 0000000..3cbd7ab --- /dev/null +++ b/packages/testing/docs/overview.md @@ -0,0 +1,13 @@ +# testing + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/testing/docs/runbook.md b/packages/testing/docs/runbook.md new file mode 100644 index 0000000..7d9e0ec --- /dev/null +++ b/packages/testing/docs/runbook.md @@ -0,0 +1,26 @@ +# testing — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/testing/eslint.config.js b/packages/testing/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/testing/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/testing/package.json b/packages/testing/package.json new file mode 100644 index 0000000..833ab52 --- /dev/null +++ b/packages/testing/package.json @@ -0,0 +1,25 @@ +{ + "name": "@saas/testing", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts", + "./fixtures": "./src/fixtures.ts", + "./ids": "./src/ids.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*", + "@saas/db": "workspace:*" + } +} diff --git a/packages/testing/src/fixtures.ts b/packages/testing/src/fixtures.ts new file mode 100644 index 0000000..a00b84a --- /dev/null +++ b/packages/testing/src/fixtures.ts @@ -0,0 +1,24 @@ +import type { TenantContext, HealthResponse } from "@saas/contracts"; + +export function makeTenantContext( + overrides?: Partial +): TenantContext { + return { + orgId: "org_test", + actorId: "user_test", + actorKind: "user", + ...overrides, + }; +} + +export function makeHealthResponse( + overrides?: Partial +): HealthResponse { + return { + status: "ok", + service: "test-service", + environment: "test", + timestamp: new Date().toISOString(), + ...overrides, + }; +} diff --git a/packages/testing/src/ids.ts b/packages/testing/src/ids.ts new file mode 100644 index 0000000..8b1ebce --- /dev/null +++ b/packages/testing/src/ids.ts @@ -0,0 +1,46 @@ +import { asUuid, type Uuid } from "@saas/db/ids"; + +// Deterministic id fixtures. +// +// Tests historically used human-readable fake ids (`org-001`, `usr_aabbccdd`) +// that are NOT valid UUIDs / `_<32 hex>` public ids. That both masked +// the public-id↔UUID-column bug class and blocks the `Uuid` brand (a fake id +// can't satisfy a `Uuid`-typed repo input). These helpers mint *valid*, +// *deterministic* ids from a seed label so fixtures are stable across runs and +// the public form always decodes to the matching UUID. + +/** Deterministic 32-char hex derived from a seed (dependency-free mixer). */ +function hex32(seed: string): string { + let h1 = (0x9e3779b9 ^ seed.length) >>> 0; + let h2 = 0x85ebca6b; + let h3 = 0xc2b2ae35; + let h4 = 0x27d4eb2f; + for (let i = 0; i < seed.length; i++) { + const c = seed.charCodeAt(i); + h1 = Math.imul(h1 ^ c, 2654435761); + h2 = Math.imul(h2 ^ c, 1597334677); + h3 = Math.imul(h3 ^ c, 374761393); + h4 = Math.imul(h4 ^ c, 3266489917); + } + const part = (n: number) => (n >>> 0).toString(16).padStart(8, "0"); + return part(h1) + part(h2) + part(h3) + part(h4); +} + +function format(hex: string): string { + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +/** A stable, valid (branded) UUID derived from a seed label. */ +export function testUuid(seed: string): Uuid { + return asUuid(format(hex32(seed))); +} + +/** The matching public id `_<32 hex>` whose decoded form === testUuid(seed). */ +export function testPublicId(prefix: string, seed: string): string { + return `${prefix}_${hex32(seed)}`; +} + +/** Both representations for one seed — `{ uuid, publicId }`. */ +export function testId(prefix: string, seed: string): { uuid: Uuid; publicId: string } { + return { uuid: testUuid(seed), publicId: testPublicId(prefix, seed) }; +} diff --git a/packages/testing/src/index.ts b/packages/testing/src/index.ts new file mode 100644 index 0000000..6ad7d56 --- /dev/null +++ b/packages/testing/src/index.ts @@ -0,0 +1,2 @@ +export * from "./fixtures.js"; +export * from "./ids.js"; diff --git a/packages/testing/tsconfig.build.json b/packages/testing/tsconfig.build.json new file mode 100644 index 0000000..4d78c7b --- /dev/null +++ b/packages/testing/tsconfig.build.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/testing/tsconfig.json b/packages/testing/tsconfig.json new file mode 100644 index 0000000..d84a568 --- /dev/null +++ b/packages/testing/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/webhook-verifier/README.md b/packages/webhook-verifier/README.md new file mode 100644 index 0000000..1402b93 --- /dev/null +++ b/packages/webhook-verifier/README.md @@ -0,0 +1,34 @@ +# @saas/webhook-verifier + +Zero-dependency, WebCrypto-only HMAC-SHA256 signature verifier for +new-test outbound webhook deliveries. Runs verbatim on Cloudflare +Workers, Bun, modern Node, and browsers. + +```ts +import { + verifyWebhookSignature, + DEFAULT_TOLERANCE_SECONDS, +} from "@saas/webhook-verifier"; + +export async function handler(request: Request): Promise { + const body = await request.text(); + const result = await verifyWebhookSignature({ + secret: process.env.NEW_TEST_WEBHOOK_SECRET!, + body, + headers: request.headers, + // toleranceSeconds: DEFAULT_TOLERANCE_SECONDS, // 5 minutes; tighten if you have strict NTP + }); + if (!result.ok) { + return new Response(`rejected: ${result.reason}`, { status: 401 }); + } + // body is now trusted — JSON.parse and dispatch on event.type + return new Response("ok"); +} +``` + +`toleranceSeconds` controls the replay window (default 300s); lower it if +your clocks are tightly synchronized, raise it if they aren't. + +The companion `signWebhookPayload({ secret, body, timestamp })` helper +produces the exact `sha256=` header value new-test emits — useful +for fixtures and symmetric debugging. diff --git a/packages/webhook-verifier/component.yaml b/packages/webhook-verifier/component.yaml new file mode 100644 index 0000000..738ecce --- /dev/null +++ b/packages/webhook-verifier/component.yaml @@ -0,0 +1,27 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: webhook-verifier +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-shared + subscribe: + environments: + - name: dev + profile: quick-check + - name: stage + profile: quick-check + - name: prod + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + labels: + team: platform + layer: shared + surface: shared +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/packages/webhook-verifier/docs/architecture.md b/packages/webhook-verifier/docs/architecture.md new file mode 100644 index 0000000..93c243b --- /dev/null +++ b/packages/webhook-verifier/docs/architecture.md @@ -0,0 +1,9 @@ +# webhook-verifier — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `packages/webhook-verifier`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/packages/webhook-verifier/docs/overview.md b/packages/webhook-verifier/docs/overview.md new file mode 100644 index 0000000..d4b1e35 --- /dev/null +++ b/packages/webhook-verifier/docs/overview.md @@ -0,0 +1,13 @@ +# webhook-verifier + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/packages/webhook-verifier/docs/runbook.md b/packages/webhook-verifier/docs/runbook.md new file mode 100644 index 0000000..d6e6edc --- /dev/null +++ b/packages/webhook-verifier/docs/runbook.md @@ -0,0 +1,26 @@ +# webhook-verifier — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/packages/webhook-verifier/eslint.config.js b/packages/webhook-verifier/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/packages/webhook-verifier/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/packages/webhook-verifier/package.json b/packages/webhook-verifier/package.json new file mode 100644 index 0000000..405838d --- /dev/null +++ b/packages/webhook-verifier/package.json @@ -0,0 +1,21 @@ +{ + "name": "@saas/webhook-verifier", + "version": "0.0.0", + "private": true, + "type": "module", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "build": "tsc --project tsconfig.build.json", + "typecheck": "tsc --noEmit", + "lint": "eslint src", + "test": "vitest run" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "typescript": "^5.8.3", + "vitest": "^2.1.9" + } +} diff --git a/packages/webhook-verifier/src/__tests__/verify.test.ts b/packages/webhook-verifier/src/__tests__/verify.test.ts new file mode 100644 index 0000000..eba6c02 --- /dev/null +++ b/packages/webhook-verifier/src/__tests__/verify.test.ts @@ -0,0 +1,370 @@ +// Vitest suite for @saas/webhook-verifier. +// +// Covers: +// - Happy-path verification +// - Header-case-insensitivity (Record + Headers shapes) +// - Each VerifyFailureReason branch (one dedicated test per reason) +// - signWebhookPayload round-trip through verifyWebhookSignature +// - Byte-identity match against the canonical signing scheme as +// implemented in apps/webhooks-worker/src/delivery.ts:45-61. +// The scheme is duplicated below as `canonicalComputeSignature` +// (NOT imported from the worker) so any future drift in either +// side fails this test. + +import { describe, expect, it } from "vitest"; + +import { + DEFAULT_TOLERANCE_SECONDS, + SIGNATURE_HEADER, + SIGNATURE_PREFIX, + TIMESTAMP_HEADER, + signWebhookPayload, + verifyWebhookSignature, +} from "../index.js"; + +// Verbatim duplicate of apps/webhooks-worker/src/delivery.ts:45-61's +// `computeSignature` — kept as a fixture so we exercise byte-identity +// without importing from the worker tree. +async function canonicalComputeSignature( + secret: string, + timestamp: string, + body: string, +): Promise { + const encoder = new TextEncoder(); + const keyData = encoder.encode(secret); + const key = await crypto.subtle.importKey( + "raw", + keyData, + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const message = encoder.encode(`${timestamp}.${body}`); + const sig = await crypto.subtle.sign("HMAC", key, message); + const hex = Array.from(new Uint8Array(sig)) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); + return `sha256=${hex}`; +} + +const SECRET = "whsec_test_super_secret"; +const BODY = JSON.stringify({ id: "evt_123", type: "test.event", data: { hello: "world" } }); +const TS = "1717000000"; // 2024-05-29T18:26:40Z, fixed epoch +const FIXED_NOW = () => new Date(Number(TS) * 1000); + +describe("verifyWebhookSignature", () => { + it("accepts a valid signature (happy path)", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: true }); + }); + + it("is case-insensitive on Record header keys", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + "x-webhook-signature": sig, + "x-webhook-timestamp": TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: true }); + }); + + it("accepts a Headers instance input", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const headers = new Headers(); + headers.set(SIGNATURE_HEADER, sig); + headers.set(TIMESTAMP_HEADER, TS); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: true }); + }); + + it("accepts Record with array value", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: [sig, "stale=ignored"], + [TIMESTAMP_HEADER]: TS, + "x-extra": undefined, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: true }); + }); + + it("returns missing_signature when no signature header is present", async () => { + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { [TIMESTAMP_HEADER]: TS }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "missing_signature" }); + }); + + it("returns missing_timestamp when no timestamp header is present", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { [SIGNATURE_HEADER]: sig }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "missing_timestamp" }); + }); + + it("returns malformed_timestamp on non-numeric timestamp", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: "not-a-number", + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "malformed_timestamp" }); + }); + + it("returns malformed_timestamp on oversized timestamp", async () => { + const huge = "9".repeat(40); + const sig = await canonicalComputeSignature(SECRET, huge, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: huge, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "malformed_timestamp" }); + }); + + it("returns timestamp_out_of_tolerance when stale beyond default 300s", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: () => new Date((Number(TS) + DEFAULT_TOLERANCE_SECONDS + 1) * 1000), + }); + expect(result).toEqual({ ok: false, reason: "timestamp_out_of_tolerance" }); + }); + + it("respects custom toleranceSeconds: 0 (any drift fails)", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: () => new Date((Number(TS) + 1) * 1000), + toleranceSeconds: 0, + }); + expect(result).toEqual({ ok: false, reason: "timestamp_out_of_tolerance" }); + }); + + it("returns malformed_signature when the sha256= prefix is missing", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const stripped = sig.slice(SIGNATURE_PREFIX.length); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: stripped, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "malformed_signature" }); + }); + + it("returns malformed_signature when hex is non-hex / odd-length", async () => { + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: "sha256=zz", // not hex + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "malformed_signature" }); + }); + + it("returns signature_mismatch on wrong secret", async () => { + const sig = await canonicalComputeSignature("whsec_other_secret", TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("returns signature_mismatch when body bytes are tampered", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY + " ", // single byte added after signing + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("returns signature_mismatch when timestamp is tampered (re-signed elsewhere wouldn't match)", async () => { + // Sign with TS, then advertise TS+1 in the header — message templates + // diverge so HMACs diverge. + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const tampered = String(Number(TS) + 1); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: tampered, + }, + now: () => new Date(Number(tampered) * 1000), + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("returns signature_mismatch on first-byte tamper of provided signature", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const hex = sig.slice(SIGNATURE_PREFIX.length); + const flipped = (hex[0] === "0" ? "1" : "0") + hex.slice(1); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: SIGNATURE_PREFIX + flipped, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("returns signature_mismatch on last-byte tamper of provided signature", async () => { + // Symmetric structural assertion that the per-byte loop runs to + // completion regardless of where the difference occurs (constant-time + // intent — the test is intentionally not a wall-clock timing assertion; + // structural equivalence with the first-byte case is sufficient and + // stable in CI). + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + const hex = sig.slice(SIGNATURE_PREFIX.length); + const last = hex[hex.length - 1] as string; + const flipped = hex.slice(0, -1) + (last === "0" ? "1" : "0"); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: SIGNATURE_PREFIX + flipped, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("returns signature_mismatch on hex-length mismatch (truncated signature)", async () => { + const sig = await canonicalComputeSignature(SECRET, TS, BODY); + // Drop the last 4 hex chars — still even-length, still valid hex, + // but byte length differs from a SHA-256 digest. + const truncated = sig.slice(0, -4); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: truncated, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: false, reason: "signature_mismatch" }); + }); + + it("uses default now() = new Date() when not supplied (within tolerance)", async () => { + const nowSec = Math.floor(Date.now() / 1000).toString(); + const sig = await canonicalComputeSignature(SECRET, nowSec, BODY); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: nowSec, + }, + }); + expect(result).toEqual({ ok: true }); + }); +}); + +describe("signWebhookPayload", () => { + it("produces sha256= prefix + 64 lowercase hex chars", async () => { + const sig = await signWebhookPayload({ secret: SECRET, body: BODY, timestamp: TS }); + expect(sig.startsWith(SIGNATURE_PREFIX)).toBe(true); + const hex = sig.slice(SIGNATURE_PREFIX.length); + expect(hex).toHaveLength(64); + expect(/^[0-9a-f]{64}$/.test(hex)).toBe(true); + }); + + it("signWebhookPayload output round-trips through verifyWebhookSignature", async () => { + const sig = await signWebhookPayload({ secret: SECRET, body: BODY, timestamp: TS }); + const result = await verifyWebhookSignature({ + secret: SECRET, + body: BODY, + headers: { + [SIGNATURE_HEADER]: sig, + [TIMESTAMP_HEADER]: TS, + }, + now: FIXED_NOW, + }); + expect(result).toEqual({ ok: true }); + }); + + it("byte-identity: matches apps/webhooks-worker delivery.ts canonical scheme", async () => { + // Both implementations use the same `${timestamp}.${body}` template, + // same HMAC-SHA256 over the secret, same `sha256=` + lowercase-hex + // serialization. Any drift on either side fails this assertion. + const fromHelper = await signWebhookPayload({ + secret: SECRET, + body: BODY, + timestamp: TS, + }); + const fromCanonical = await canonicalComputeSignature(SECRET, TS, BODY); + expect(fromHelper).toBe(fromCanonical); + }); +}); diff --git a/packages/webhook-verifier/src/index.ts b/packages/webhook-verifier/src/index.ts new file mode 100644 index 0000000..3a982de --- /dev/null +++ b/packages/webhook-verifier/src/index.ts @@ -0,0 +1,204 @@ +/** + * @saas/webhook-verifier — zero-dependency, WebCrypto-only HMAC-SHA256 + * signature verifier for newtest outbound webhook deliveries. + * + * Codifies the canonical signing scheme implemented in + * `apps/webhooks-worker/src/delivery.ts` so external integrators + * (and console-side replay tooling) don't reinvent it. + * + * Scheme: + * message = `${timestamp}.${body}` + * signature = `sha256=` + lowercase-hex( HMAC-SHA256(secret, message) ) + * + * X-Webhook-Signature: sha256= + * X-Webhook-Timestamp: + * X-Webhook-ID: + * + * Runs verbatim on Cloudflare Workers, Bun, modern Node, and browsers — + * uses only `crypto.subtle.importKey` + `crypto.subtle.sign`. + */ + +export const SIGNATURE_HEADER = "X-Webhook-Signature"; +export const TIMESTAMP_HEADER = "X-Webhook-Timestamp"; +export const WEBHOOK_ID_HEADER = "X-Webhook-ID"; +export const SIGNATURE_PREFIX = "sha256="; +export const DEFAULT_TOLERANCE_SECONDS = 300; + +export type VerifyFailureReason = + | "missing_signature" + | "missing_timestamp" + | "malformed_timestamp" + | "timestamp_out_of_tolerance" + | "malformed_signature" + | "signature_mismatch"; + +export type VerifyResult = + | { ok: true } + | { ok: false; reason: VerifyFailureReason }; + +export type HeadersInput = + | Headers + | Record; + +export interface VerifyWebhookSignatureInput { + secret: string; + body: string; + headers: HeadersInput; + now?: () => Date; + toleranceSeconds?: number; +} + +export interface SignWebhookPayloadInput { + secret: string; + body: string; + timestamp: string; +} + +// ── Header lookup (case-insensitive for both shapes) ────────────────── + +function lookupHeader(headers: HeadersInput, name: string): string | undefined { + const lower = name.toLowerCase(); + if (typeof Headers !== "undefined" && headers instanceof Headers) { + const value = headers.get(name); + return value === null ? undefined : value; + } + const record = headers as Record; + for (const key of Object.keys(record)) { + if (key.toLowerCase() === lower) { + const value = record[key]; + if (value === undefined) return undefined; + return Array.isArray(value) ? value[0] : value; + } + } + return undefined; +} + +// ── Hex helpers ─────────────────────────────────────────────────────── + +const HEX_RE = /^[0-9a-f]+$/i; + +function bytesToHex(bytes: Uint8Array): string { + let out = ""; + for (let i = 0; i < bytes.length; i++) { + const b = bytes[i] as number; + out += b.toString(16).padStart(2, "0"); + } + return out; +} + +function hexToBytes(hex: string): Uint8Array | null { + if (hex.length === 0 || hex.length % 2 !== 0) return null; + if (!HEX_RE.test(hex)) return null; + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) { + out[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16); + } + return out; +} + +// ── HMAC-SHA256 via WebCrypto ──────────────────────────────────────── + +async function hmacSha256Hex(secret: string, message: string): Promise { + const encoder = new TextEncoder(); + const key = await crypto.subtle.importKey( + "raw", + encoder.encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const sig = await crypto.subtle.sign("HMAC", key, encoder.encode(message)); + return bytesToHex(new Uint8Array(sig)); +} + +/** + * Constant-time equality over two equal-length byte arrays. + * Loops the full length; never short-circuits on first mismatch. + */ +function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) { + diff |= (a[i] as number) ^ (b[i] as number); + } + return diff === 0; +} + +// ── Public API ──────────────────────────────────────────────────────── + +/** + * Compute the canonical newtest webhook signature for a payload. + * Returns the full `sha256=` header value. + */ +export async function signWebhookPayload( + input: SignWebhookPayloadInput, +): Promise { + const hex = await hmacSha256Hex(input.secret, `${input.timestamp}.${input.body}`); + return `${SIGNATURE_PREFIX}${hex}`; +} + +/** + * Verify the HMAC-SHA256 signature of a newtest webhook delivery. + * + * Returns a tagged result. On `ok: false`, `reason` enumerates the + * exact failure mode for caller observability. Comparison is + * constant-time (full-length XOR accumulator). + */ +export async function verifyWebhookSignature( + input: VerifyWebhookSignatureInput, +): Promise { + const sigHeader = lookupHeader(input.headers, SIGNATURE_HEADER); + if (sigHeader === undefined || sigHeader === "") { + return { ok: false, reason: "missing_signature" }; + } + + const tsHeader = lookupHeader(input.headers, TIMESTAMP_HEADER); + if (tsHeader === undefined || tsHeader === "") { + return { ok: false, reason: "missing_timestamp" }; + } + + // Timestamp must be a positive integer (unix seconds), bounded so wildly + // large values can't bypass the tolerance check via overflow. + if (!/^[0-9]+$/.test(tsHeader)) { + return { ok: false, reason: "malformed_timestamp" }; + } + const tsSeconds = Number(tsHeader); + if (!Number.isFinite(tsSeconds) || tsSeconds > Number.MAX_SAFE_INTEGER / 1000) { + return { ok: false, reason: "malformed_timestamp" }; + } + + const tolerance = input.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS; + const now = (input.now ?? (() => new Date()))(); + const nowSeconds = Math.floor(now.getTime() / 1000); + if (Math.abs(nowSeconds - tsSeconds) > tolerance) { + return { ok: false, reason: "timestamp_out_of_tolerance" }; + } + + if (!sigHeader.startsWith(SIGNATURE_PREFIX)) { + return { ok: false, reason: "malformed_signature" }; + } + const providedHex = sigHeader.slice(SIGNATURE_PREFIX.length); + const providedBytes = hexToBytes(providedHex); + if (providedBytes === null) { + return { ok: false, reason: "malformed_signature" }; + } + + const expectedHex = await hmacSha256Hex(input.secret, `${tsHeader}.${input.body}`); + const expectedBytes = hexToBytes(expectedHex); + // expectedBytes is always non-null (hmacSha256Hex emits 64 valid hex chars), + // but the explicit guard keeps the compiler honest under + // `noUncheckedIndexedAccess` and documents the invariant. + if (expectedBytes === null) { + return { ok: false, reason: "malformed_signature" }; + } + + if (providedBytes.length !== expectedBytes.length) { + return { ok: false, reason: "signature_mismatch" }; + } + + if (!constantTimeEqual(providedBytes, expectedBytes)) { + return { ok: false, reason: "signature_mismatch" }; + } + + return { ok: true }; +} diff --git a/packages/webhook-verifier/tsconfig.build.json b/packages/webhook-verifier/tsconfig.build.json new file mode 100644 index 0000000..c0963cc --- /dev/null +++ b/packages/webhook-verifier/tsconfig.build.json @@ -0,0 +1,10 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM"], + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src/index.ts"], + "exclude": ["node_modules", "dist", "src/__tests__"] +} diff --git a/packages/webhook-verifier/tsconfig.json b/packages/webhook-verifier/tsconfig.json new file mode 100644 index 0000000..1829ad2 --- /dev/null +++ b/packages/webhook-verifier/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "lib": ["ES2022", "DOM"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 941f00f..87013e3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -24,6 +24,283 @@ importers: specifier: ^5.8.3 version: 5.9.3 + packages/cli: + dependencies: + '@saas/sdk': + specifier: workspace:* + version: link:../sdk + '@saas/webhook-verifier': + specifier: workspace:* + version: link:../webhook-verifier + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: ^20.14.0 + version: 20.19.43 + esbuild: + specifier: ^0.25.4 + version: 0.25.12 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^2.1.9 + version: 2.1.9(@types/node@20.19.43) + optionalDependencies: + keytar: + specifier: ^7.9.0 + version: 7.9.0 + + packages/contracts: + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/db: + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/node': + specifier: ^20.17.0 + version: 20.19.43 + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/notifications-client: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../contracts + devDependencies: + '@cloudflare/workers-types': + specifier: ^4.20250508.0 + version: 4.20260702.1 + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/policy-engine: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../contracts + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/sdk: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../contracts + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^2.1.9 + version: 2.1.9(@types/node@22.20.4) + + packages/shared: + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/testing: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../contracts + '@saas/db': + specifier: workspace:* + version: link:../db + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + packages/webhook-verifier: + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^2.1.9 + version: 2.1.9(@types/node@22.20.4) + + tests/contracts: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@saas/testing': + specifier: workspace:* + version: link:../../packages/testing + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@20.19.43) + ts-jest: + specifier: ^29.3.4 + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.43))(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/db: + dependencies: + '@saas/db': + specifier: workspace:* + version: link:../../packages/db + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + '@types/node': + specifier: ^22.10.0 + version: 22.20.4 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@22.20.4) + ts-jest: + specifier: ^29.3.4 + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.20.4))(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/notifications-client: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@saas/notifications-client': + specifier: workspace:* + version: link:../../packages/notifications-client + devDependencies: + '@cloudflare/workers-types': + specifier: ^4.20250508.0 + version: 4.20260702.1 + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + '@types/node': + specifier: ^20.17.0 + version: 20.19.43 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@20.19.43) + ts-jest: + specifier: ^29.3.4 + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.43))(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + + tests/policy-engine: + dependencies: + '@saas/contracts': + specifier: workspace:* + version: link:../../packages/contracts + '@saas/policy-engine': + specifier: workspace:* + version: link:../../packages/policy-engine + devDependencies: + '@saas/eslint-config': + specifier: workspace:* + version: link:../../tooling/eslint + '@saas/tsconfig': + specifier: workspace:* + version: link:../../tooling/tsconfig + '@types/jest': + specifier: ^29.5.14 + version: 29.5.14 + jest: + specifier: ^29.7.0 + version: 29.7.0(@types/node@22.20.4) + ts-jest: + specifier: ^29.3.2 + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.20.4))(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + tooling/eslint: devDependencies: '@typescript-eslint/eslint-plugin': @@ -40,495 +317,2613 @@ importers: packages: - '@eslint-community/eslint-utils@4.9.1': - resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - peerDependencies: - eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 - - '@eslint-community/regexpp@4.12.2': - resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - - '@eslint/config-array@0.21.2': - resolution: {integrity: sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/config-helpers@0.4.2': - resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} - '@eslint/core@0.17.0': - resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} - '@eslint/eslintrc@3.3.5': - resolution: {integrity: sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} + engines: {node: '>=6.9.0'} - '@eslint/js@9.39.4': - resolution: {integrity: sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/generator@7.29.8': + resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==} + engines: {node: '>=6.9.0'} - '@eslint/object-schema@2.1.7': - resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} + engines: {node: '>=6.9.0'} - '@eslint/plugin-kit@0.4.1': - resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} + engines: {node: '>=6.9.0'} - '@humanfs/core@0.19.2': - resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} - engines: {node: '>=18.18.0'} + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} - '@humanfs/node@0.16.8': - resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} - engines: {node: '>=18.18.0'} + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0 - '@humanfs/types@0.15.0': - resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} - engines: {node: '>=18.18.0'} + '@babel/helper-plugin-utils@7.29.7': + resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==} + engines: {node: '>=6.9.0'} - '@humanwhocodes/module-importer@1.0.1': - resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} - engines: {node: '>=12.22'} + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} - '@humanwhocodes/retry@0.4.3': - resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} - engines: {node: '>=18.18'} + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} - '@turbo/darwin-64@2.9.12': - resolution: {integrity: sha512-eu3eFRmE9NjgZ0wPdRJ44l+LGSeIky+tz5ZQd8zQkw/Yqi+BM7wq+8nbabeoiVUcICi/IZweMOKl/MCmkrd1+g==} - cpu: [x64] - os: [darwin] + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} - '@turbo/darwin-arm64@2.9.12': - resolution: {integrity: sha512-RUkAE404z/J8NsyrUosMcBaXT6M4bRFxTQrmkDQBLQVXaC8Jl0e9bMvYDSX0GW7Ffm2m3j9y7RXgR1foeUAM9w==} - cpu: [arm64] - os: [darwin] + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} + engines: {node: '>=6.9.0'} - '@turbo/linux-64@2.9.12': - resolution: {integrity: sha512-InIUtH7cw/vqXNX1Gr7QgWfmw3ct08pV5CpfdEOR48z2u2rzdmpIuk00B/Q2xCb0PMWtKgiMQynfuphmEuUyTQ==} - cpu: [x64] - os: [linux] + '@babel/parser@7.29.9': + resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==} + engines: {node: '>=6.0.0'} + hasBin: true - '@turbo/linux-arm64@2.9.12': - resolution: {integrity: sha512-lC6nD//Xh67fmJM0LKaLsg74Wry0aYrgMklpiNgCbUaMdPIOqj0A00iri3NU7Lb7pZHx8ViisgpeDKlpSgFUCA==} - cpu: [arm64] - os: [linux] + '@babel/plugin-syntax-async-generators@7.8.4': + resolution: {integrity: sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@turbo/windows-64@2.9.12': - resolution: {integrity: sha512-conYri8VUl72JOdYnLDPYwzqbPcY5ECoHmo9FWoKznemhaAIilj4maHqs9Uar0aKfNoZIULniy+6iWaLtLO34A==} - cpu: [x64] - os: [win32] + '@babel/plugin-syntax-bigint@7.8.3': + resolution: {integrity: sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@turbo/windows-arm64@2.9.12': - resolution: {integrity: sha512-XoR4bsg62/L/esRVcmoMESEiNZ36+YmyjYGLpoqk8nwMgXzzVjNOgX0lRSz5w/U/ajLGv3nhMsS0Q2QOdvp2AQ==} - cpu: [arm64] - os: [win32] + '@babel/plugin-syntax-class-properties@7.12.13': + resolution: {integrity: sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@types/estree@1.0.9': - resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + '@babel/plugin-syntax-class-static-block@7.14.5': + resolution: {integrity: sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@types/json-schema@7.0.15': - resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@babel/plugin-syntax-import-attributes@7.29.7': + resolution: {integrity: sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@typescript-eslint/eslint-plugin@8.59.2': - resolution: {integrity: sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-import-meta@7.10.4': + resolution: {integrity: sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==} peerDependencies: - '@typescript-eslint/parser': ^8.59.2 - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/parser@8.59.2': - resolution: {integrity: sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-json-strings@7.8.3': + resolution: {integrity: sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==} peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/project-service@8.59.2': - resolution: {integrity: sha512-+2hqvEkeyf/0FBor67duF0Ll7Ot8jyKzDQOSrxazF/danillRq2DwR9dLptsXpoZQqxE1UisSmoZewrlPas9Vw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-jsx@7.29.7': + resolution: {integrity: sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==} + engines: {node: '>=6.9.0'} peerDependencies: - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/scope-manager@8.59.2': - resolution: {integrity: sha512-JzfyEpEtOU89CcFSwyNS3mu4MLvLSXqnmX05+aKBDM+TdR5jzcGOEBwxwGNxrEQ7p/z6kK2WyioCGBf2zZBnvg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-logical-assignment-operators@7.10.4': + resolution: {integrity: sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@typescript-eslint/tsconfig-utils@8.59.2': - resolution: {integrity: sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3': + resolution: {integrity: sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==} peerDependencies: - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/type-utils@8.59.2': - resolution: {integrity: sha512-nhqaj1nmTdVVl/BP5omXNRGO38jn5iosis2vbdmupF2txCf8ylWT8lx+JlvMYYVqzGVKtjojUFoQ3JRWK+mfzQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-numeric-separator@7.10.4': + resolution: {integrity: sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==} peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/types@8.59.2': - resolution: {integrity: sha512-e82GVOE8Ps3E++Egvb6Y3Dw0S10u8NkQ9KXmtRhCWJJ8kDhOJTvtMAWnFL16kB1583goCWXsr0NieKCZMs2/0Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-object-rest-spread@7.8.3': + resolution: {integrity: sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==} + peerDependencies: + '@babel/core': ^7.0.0-0 - '@typescript-eslint/typescript-estree@8.59.2': - resolution: {integrity: sha512-o0XPGNwcWw+FIwStOWn+BwBuEmL6QXP0rsvAFg7ET1dey1Nr6Wb1ac8p5HEsK0ygO/6mUxlk+YWQD9xcb/nnXg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-optional-catch-binding@7.8.3': + resolution: {integrity: sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==} peerDependencies: - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/utils@8.59.2': - resolution: {integrity: sha512-Juw3EinkXqjaffxz6roowvV7GZT/kET5vSKKZT6upl5TXdWkLkYmNPXwDDL2Vkt2DPn0nODIS4egC/0AGxKo/Q==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-optional-chaining@7.8.3': + resolution: {integrity: sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==} peerDependencies: - eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 - typescript: '>=4.8.4 <6.1.0' + '@babel/core': ^7.0.0-0 - '@typescript-eslint/visitor-keys@8.59.2': - resolution: {integrity: sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + '@babel/plugin-syntax-private-property-in-object@7.14.5': + resolution: {integrity: sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 - acorn-jsx@5.3.2: - resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + '@babel/plugin-syntax-top-level-await@7.14.5': + resolution: {integrity: sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==} + engines: {node: '>=6.9.0'} peerDependencies: - acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + '@babel/core': ^7.0.0-0 - acorn@8.16.0: - resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} - engines: {node: '>=0.4.0'} - hasBin: true + '@babel/plugin-syntax-typescript@7.29.7': + resolution: {integrity: sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==} + engines: {node: '>=6.9.0'} + peerDependencies: + '@babel/core': ^7.0.0-0 - ajv@6.15.0: - resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} - ansi-styles@4.3.0: - resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} - engines: {node: '>=8'} + '@babel/traverse@7.29.8': + resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==} + engines: {node: '>=6.9.0'} - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + '@bcoe/v8-coverage@0.2.3': + resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} - balanced-match@4.0.4: - resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} - engines: {node: 18 || 20 || >=22} + '@cloudflare/workers-types@4.20260702.1': + resolution: {integrity: sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA==} - brace-expansion@1.1.14: - resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} + '@esbuild/aix-ppc64@0.21.5': + resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [aix] - brace-expansion@5.0.6: - resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} - engines: {node: 18 || 20 || >=22} + '@esbuild/aix-ppc64@0.25.12': + resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] - callsites@3.1.0: - resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} - engines: {node: '>=6'} + '@esbuild/android-arm64@0.21.5': + resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [android] - chalk@4.1.2: - resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} - engines: {node: '>=10'} + '@esbuild/android-arm64@0.25.12': + resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] - color-convert@2.0.1: - resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} - engines: {node: '>=7.0.0'} + '@esbuild/android-arm@0.21.5': + resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} + engines: {node: '>=12'} + cpu: [arm] + os: [android] - color-name@1.1.4: - resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + '@esbuild/android-arm@0.25.12': + resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] - concat-map@0.0.1: - resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + '@esbuild/android-x64@0.21.5': + resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} + engines: {node: '>=12'} + cpu: [x64] + os: [android] - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} - engines: {node: '>= 8'} + '@esbuild/android-x64@0.25.12': + resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] - debug@4.4.3: + '@esbuild/darwin-arm64@0.21.5': + resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} + engines: {node: '>=12'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.25.12': + resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.21.5': + resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} + engines: {node: '>=12'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.25.12': + resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.21.5': + resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} + engines: {node: '>=12'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.25.12': + resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.21.5': + resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.25.12': + resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.21.5': + resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} + engines: {node: '>=12'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.25.12': + resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.21.5': + resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} + engines: {node: '>=12'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.25.12': + resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.21.5': + resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} + engines: {node: '>=12'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.25.12': + resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.21.5': + resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} + engines: {node: '>=12'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.25.12': + resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.21.5': + resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} + engines: {node: '>=12'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.25.12': + resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.21.5': + resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} + engines: {node: '>=12'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.25.12': + resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.21.5': + resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} + engines: {node: '>=12'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.25.12': + resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.21.5': + resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} + engines: {node: '>=12'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.25.12': + resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.21.5': + resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} + engines: {node: '>=12'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.25.12': + resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.25.12': + resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.21.5': + resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} + engines: {node: '>=12'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.25.12': + resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.25.12': + resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.21.5': + resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} + engines: {node: '>=12'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.25.12': + resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.25.12': + resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.21.5': + resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} + engines: {node: '>=12'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.25.12': + resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.21.5': + resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} + engines: {node: '>=12'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.25.12': + resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.21.5': + resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} + engines: {node: '>=12'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.25.12': + resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.21.5': + resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} + engines: {node: '>=12'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.25.12': + resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@eslint-community/eslint-utils@4.9.1': + resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + peerDependencies: + eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 + + '@eslint-community/regexpp@4.12.2': + resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} + engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} + + '@eslint/config-array@0.21.2': + resolution: {integrity: sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/config-helpers@0.4.2': + resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/core@0.17.0': + resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/eslintrc@3.3.5': + resolution: {integrity: sha512-4IlJx0X0qftVsN5E+/vGujTRIFtwuLbNsVUe7TO6zYPDR1O6nFwvwhIKEKSrl6dZchmYBITazxKoUYOjdtjlRg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/js@9.39.4': + resolution: {integrity: sha512-nE7DEIchvtiFTwBw4Lfbu59PG+kCofhjsKaCWzxTpt4lfRjRMqG6uMBzKXuEcyXhOHoUp9riAm7/aWYGhXZ9cw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/object-schema@2.1.7': + resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@eslint/plugin-kit@0.4.1': + resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@humanfs/core@0.19.2': + resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==} + engines: {node: '>=18.18.0'} + + '@humanfs/node@0.16.8': + resolution: {integrity: sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==} + engines: {node: '>=18.18.0'} + + '@humanfs/types@0.15.0': + resolution: {integrity: sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==} + engines: {node: '>=18.18.0'} + + '@humanwhocodes/module-importer@1.0.1': + resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} + engines: {node: '>=12.22'} + + '@humanwhocodes/retry@0.4.3': + resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} + engines: {node: '>=18.18'} + + '@istanbuljs/load-nyc-config@1.1.0': + resolution: {integrity: sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==} + engines: {node: '>=8'} + + '@istanbuljs/schema@0.1.6': + resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==} + engines: {node: '>=8'} + + '@jest/console@29.7.0': + resolution: {integrity: sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/core@29.7.0': + resolution: {integrity: sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + + '@jest/environment@29.7.0': + resolution: {integrity: sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/expect-utils@29.7.0': + resolution: {integrity: sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/expect@29.7.0': + resolution: {integrity: sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/fake-timers@29.7.0': + resolution: {integrity: sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/globals@29.7.0': + resolution: {integrity: sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/reporters@29.7.0': + resolution: {integrity: sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + + '@jest/schemas@29.6.3': + resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/source-map@29.6.3': + resolution: {integrity: sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/test-result@29.7.0': + resolution: {integrity: sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/test-sequencer@29.7.0': + resolution: {integrity: sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/transform@29.7.0': + resolution: {integrity: sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/types@29.6.3': + resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/remapping@2.3.5': + resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + + '@rollup/rollup-android-arm-eabi@4.63.4': + resolution: {integrity: sha512-I+BSHzTAhKN2n7ZwGZsegGcZjDpLqFOMAtJz/u6uFGe0pUFbq56dEHjqJV/ZUdRJtNXNxA+hREUatZBvMR3Oiw==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.63.4': + resolution: {integrity: sha512-pu3BdjS2LtEzRu2elmGzS3fIeWSZy4BMDIaLNwjorO76+k2d0LMluijhsDx3KQyQBQ/lLUZCQA9/s6csvUfuhw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.63.4': + resolution: {integrity: sha512-xfSrj9MHnWK9GaSqT9U0ImHtH/N8WZlHLx4cZHiuLcqs640hvZ3hLPd5UR2AZS57FaE8HrRUSpltbZdWRxHiDA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.63.4': + resolution: {integrity: sha512-bqU99PLJb/dqb3S0GIMdeuyAEETSUgZBoqXYd3Sd+WCsV+MmPhnN6JrotWyir31+QgH7EvvE5/mwGJlEoci8Fw==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.63.4': + resolution: {integrity: sha512-JinsFZ5G40oXQb+sUuiA5x689vhr6dDYK0H0NL+rwKdL6CqnmYN8PE4ZwfRSoIjrCxqTQG/SLfTtSvHeGxoVlw==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.63.4': + resolution: {integrity: sha512-GAdA4UxpiNm27cLHr2GqXBpAD0x9FqwYBY7/YSP0Ss0/PNi4k8gbviqpIpYbVSRBaS2ZcegXEzgTQMbRNCwxCw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.63.4': + resolution: {integrity: sha512-qDd6NoA1znaLjp4jR5U/KWCdLAKDJNB8W9ChbbDaKbo0xA+Atln5HK6LFCZ4oJQpemtRZA288DCirFRjrspptw==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.63.4': + resolution: {integrity: sha512-WtB5Tz5KTNINb8ZA+8sQ7bmjuS1JrRT7YverYIhUGdWWDlpzVWmIwuZE+jidkEXUn1l0zrEkaIMa8dHF3NGcsA==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.63.4': + resolution: {integrity: sha512-VcQ3L1tjnkKzWjryAVaFhHEWcqOfICX9uxVVoDzm2t0DpgKRHd2zOpVrJc0xsWeBZcBFyYROCIBdyR/fS174pg==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.63.4': + resolution: {integrity: sha512-6+ZQX6P5s0cMDN2Ypb8Lbm2+/sZYmZjdaYny992ujUU9UKi/4CWoJWsl1pNvjWJHNHGK51m+jKGLlh1ylb2ifQ==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.63.4': + resolution: {integrity: sha512-D72ZnvkFkBXOfzMMQLcwfPLyGkKb7HZ9/mf97B7v6/P5Lbv4oFOtSY/uHbS8lH6uKUOxoKiuokdb50XZSzzbJw==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.63.4': + resolution: {integrity: sha512-piU6BxeqA3O9KSu3kRCIQQtNqFFaTu21SEV4FwaRZowpnj3bLaWPZHw+xFqCs0XlJ+aOH3PTRWGoglH+mKA/OA==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.63.4': + resolution: {integrity: sha512-/5PGpHwqt2EEEOUs1XwzubE/ucr0dWDQ+to3zqi4Ds7EWpwtQ79wXc4JBoxqj/OwpawTsKWzJxHfSuBOq3DrWA==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.63.4': + resolution: {integrity: sha512-cX3beZDLWt7G2oJF+nhChiT+qtaihs+S2xi7ziGmVB+2pwPng6D0Ed0HmElQOgv2UsUmSJJLGwpBao/3TDx3VA==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.63.4': + resolution: {integrity: sha512-1uz2mGWHyptR7DgHHrlbdRAjXK7v7elGZ9lMja910/RP+ZYbX6xAmCiU9UZSX4hqmgtHMv6lr5l3kq1HIOpcag==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.63.4': + resolution: {integrity: sha512-nLS8topojxyz7SRpKR2IODRpQ0XPZ+xaOXvT3+hqK/Uy8Lo5HFgkkIBiIrCu5tL5YqzTvgovGw55PwpahTAGig==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.63.4': + resolution: {integrity: sha512-gs7DRKotr3l3q+jGPQBjH0ng1FjlEDm5ueQrkw5JtQvtLyEIcLASqAEaor56BhkKRzk+IcQzrcanBdb/bBQn8g==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.63.4': + resolution: {integrity: sha512-791ET7W17NnScOZM7h4dX5hYspxE28htPFsb1awY/NRR8+PRNkS53e475rDdxXXDrP+kwnCcNWg9CX5ztn/Aqw==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.63.4': + resolution: {integrity: sha512-iwZQRcmj7g88g3tzefIrQY7qvmuA/cfYwhrDtTBhsmukO4U2huVO5W+86XacUMRvdSFVAc6kZUZy21JaRwiB9w==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.63.4': + resolution: {integrity: sha512-dVHFp9gRWrdTpnqQuGfCwd7hOQDatK1VCP2iWhLY/cGrOQs/ucFzJ6A5SRqbXX12ZDI8EUuejSM5kwg+ja7Png==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.63.4': + resolution: {integrity: sha512-t3NlauOW6gxZVVFcBEnO62Cb4wbyDFL416gTg1uFI/2tgqYQlf69FbSE115Ajre9I+c26Lk4mcmdFUsS/DGifQ==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.63.4': + resolution: {integrity: sha512-xWuIaSye5FWZF8+UYtVEcHtRJDN5kN9Kfgxx3Kq8XIov9KSKbc1fiqQCm90SKrgQbUXZelbnUhnlUJmfSE7P9A==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.63.4': + resolution: {integrity: sha512-9ALJJUOg/ZflMJepVo2PlgsGxSaxN7SQ4Z8GoZfVlarWr6r3rkHUNsd/zAio7p4YMtChSMXPionxej4Hkf6CXQ==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.63.4': + resolution: {integrity: sha512-blj9z5qx/Pv4WU0W1NMFDB97e0JH5ed+aZGywW8WCvp/NhWX/4PFAq5uu6Q0AebNn+Vo6KzUYDT++JzTT5ojlQ==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.63.4': + resolution: {integrity: sha512-Erx822VRBwLa124shbj+wNXe//BOgMEctDV0m1aqTQdNO1S69DgNUCFKC1RCeZfixs1J31l6igk1ziyXErbigQ==} + cpu: [x64] + os: [win32] + + '@sinclair/typebox@0.27.12': + resolution: {integrity: sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==} + + '@sinonjs/commons@3.0.1': + resolution: {integrity: sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==} + + '@sinonjs/fake-timers@10.3.0': + resolution: {integrity: sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==} + + '@turbo/darwin-64@2.9.12': + resolution: {integrity: sha512-eu3eFRmE9NjgZ0wPdRJ44l+LGSeIky+tz5ZQd8zQkw/Yqi+BM7wq+8nbabeoiVUcICi/IZweMOKl/MCmkrd1+g==} + cpu: [x64] + os: [darwin] + + '@turbo/darwin-arm64@2.9.12': + resolution: {integrity: sha512-RUkAE404z/J8NsyrUosMcBaXT6M4bRFxTQrmkDQBLQVXaC8Jl0e9bMvYDSX0GW7Ffm2m3j9y7RXgR1foeUAM9w==} + cpu: [arm64] + os: [darwin] + + '@turbo/linux-64@2.9.12': + resolution: {integrity: sha512-InIUtH7cw/vqXNX1Gr7QgWfmw3ct08pV5CpfdEOR48z2u2rzdmpIuk00B/Q2xCb0PMWtKgiMQynfuphmEuUyTQ==} + cpu: [x64] + os: [linux] + + '@turbo/linux-arm64@2.9.12': + resolution: {integrity: sha512-lC6nD//Xh67fmJM0LKaLsg74Wry0aYrgMklpiNgCbUaMdPIOqj0A00iri3NU7Lb7pZHx8ViisgpeDKlpSgFUCA==} + cpu: [arm64] + os: [linux] + + '@turbo/windows-64@2.9.12': + resolution: {integrity: sha512-conYri8VUl72JOdYnLDPYwzqbPcY5ECoHmo9FWoKznemhaAIilj4maHqs9Uar0aKfNoZIULniy+6iWaLtLO34A==} + cpu: [x64] + os: [win32] + + '@turbo/windows-arm64@2.9.12': + resolution: {integrity: sha512-XoR4bsg62/L/esRVcmoMESEiNZ36+YmyjYGLpoqk8nwMgXzzVjNOgX0lRSz5w/U/ajLGv3nhMsS0Q2QOdvp2AQ==} + cpu: [arm64] + os: [win32] + + '@types/babel__core@7.20.5': + resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==} + + '@types/babel__generator@7.27.0': + resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==} + + '@types/babel__template@7.4.4': + resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==} + + '@types/babel__traverse@7.28.0': + resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/graceful-fs@4.1.9': + resolution: {integrity: sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==} + + '@types/istanbul-lib-coverage@2.0.6': + resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==} + + '@types/istanbul-lib-report@3.0.3': + resolution: {integrity: sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==} + + '@types/istanbul-reports@3.0.4': + resolution: {integrity: sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==} + + '@types/jest@29.5.14': + resolution: {integrity: sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==} + + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + + '@types/node@20.19.43': + resolution: {integrity: sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA==} + + '@types/node@22.20.4': + resolution: {integrity: sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==} + + '@types/stack-utils@2.0.3': + resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==} + + '@types/yargs-parser@21.0.3': + resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} + + '@types/yargs@17.0.35': + resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==} + + '@typescript-eslint/eslint-plugin@8.59.2': + resolution: {integrity: sha512-j/bwmkBvHUtPNxzuWe5z6BEk3q54YRyGlBXkSsmfoih7zNrBvl5A9A98anlp/7JbyZcWIJ8KXo/3Tq/DjFLtuQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + '@typescript-eslint/parser': ^8.59.2 + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/parser@8.59.2': + resolution: {integrity: sha512-plR3pp6D+SSUn1HM7xvSkx12/DhoHInI2YF35KAcVFNZvlC0gtrWqx7Qq1oH2Ssgi0vlFRCTbP+DZc7B9+TtsQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/project-service@8.59.2': + resolution: {integrity: sha512-+2hqvEkeyf/0FBor67duF0Ll7Ot8jyKzDQOSrxazF/danillRq2DwR9dLptsXpoZQqxE1UisSmoZewrlPas9Vw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/scope-manager@8.59.2': + resolution: {integrity: sha512-JzfyEpEtOU89CcFSwyNS3mu4MLvLSXqnmX05+aKBDM+TdR5jzcGOEBwxwGNxrEQ7p/z6kK2WyioCGBf2zZBnvg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/tsconfig-utils@8.59.2': + resolution: {integrity: sha512-BKK4alN7oi4C/zv4VqHQ+uRU+lTa6JGIZ7s1juw7b3RHo9OfKB+bKX3u0iVZetdsUCBBkSbdWbarJbmN0fTeSw==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/type-utils@8.59.2': + resolution: {integrity: sha512-nhqaj1nmTdVVl/BP5omXNRGO38jn5iosis2vbdmupF2txCf8ylWT8lx+JlvMYYVqzGVKtjojUFoQ3JRWK+mfzQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/types@8.59.2': + resolution: {integrity: sha512-e82GVOE8Ps3E++Egvb6Y3Dw0S10u8NkQ9KXmtRhCWJJ8kDhOJTvtMAWnFL16kB1583goCWXsr0NieKCZMs2/0Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@typescript-eslint/typescript-estree@8.59.2': + resolution: {integrity: sha512-o0XPGNwcWw+FIwStOWn+BwBuEmL6QXP0rsvAFg7ET1dey1Nr6Wb1ac8p5HEsK0ygO/6mUxlk+YWQD9xcb/nnXg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/utils@8.59.2': + resolution: {integrity: sha512-Juw3EinkXqjaffxz6roowvV7GZT/kET5vSKKZT6upl5TXdWkLkYmNPXwDDL2Vkt2DPn0nODIS4egC/0AGxKo/Q==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + peerDependencies: + eslint: ^8.57.0 || ^9.0.0 || ^10.0.0 + typescript: '>=4.8.4 <6.1.0' + + '@typescript-eslint/visitor-keys@8.59.2': + resolution: {integrity: sha512-NwjLUnGy8/Zfx23fl50tRC8rYaYnM52xNRYFAXvmiil9yh1+K6aRVQMnzW6gQB/1DLgWt977lYQn7C+wtgXZiA==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + '@vitest/expect@2.1.9': + resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==} + + '@vitest/mocker@2.1.9': + resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@2.1.9': + resolution: {integrity: sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==} + + '@vitest/runner@2.1.9': + resolution: {integrity: sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==} + + '@vitest/snapshot@2.1.9': + resolution: {integrity: sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==} + + '@vitest/spy@2.1.9': + resolution: {integrity: sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==} + + '@vitest/utils@2.1.9': + resolution: {integrity: sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==} + + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + + acorn@8.16.0: + resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} + engines: {node: '>=0.4.0'} + hasBin: true + + ajv@6.15.0: + resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} + + ansi-escapes@4.3.2: + resolution: {integrity: sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==} + engines: {node: '>=8'} + + ansi-regex@5.0.1: + resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} + engines: {node: '>=8'} + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + anymatch@3.1.3: + resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} + engines: {node: '>= 8'} + + argparse@1.0.10: + resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==} + + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + babel-jest@29.7.0: + resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + peerDependencies: + '@babel/core': ^7.8.0 + + babel-plugin-istanbul@6.1.1: + resolution: {integrity: sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==} + engines: {node: '>=8'} + + babel-plugin-jest-hoist@29.6.3: + resolution: {integrity: sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + babel-preset-current-node-syntax@1.2.0: + resolution: {integrity: sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==} + peerDependencies: + '@babel/core': ^7.0.0 || ^8.0.0-0 + + babel-preset-jest@29.6.3: + resolution: {integrity: sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + peerDependencies: + '@babel/core': ^7.0.0 + + balanced-match@1.0.2: + resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} + + balanced-match@4.0.4: + resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} + engines: {node: 18 || 20 || >=22} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + baseline-browser-mapping@2.11.25: + resolution: {integrity: sha512-gMmEShwwq7FJqMwvfRwvCl00v4kN+KOfJqXn+f4nrufak5gNHJOksd/60Dvjuz7sI8Y5WiSFBa8FEYr+zoyqCw==} + engines: {node: '>=6.0.0'} + hasBin: true + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + brace-expansion@1.1.14: + resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} + + brace-expansion@5.0.6: + resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} + engines: {node: 18 || 20 || >=22} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + browserslist@4.29.0: + resolution: {integrity: sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + + bs-logger@0.2.6: + resolution: {integrity: sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==} + engines: {node: '>= 6'} + + bser@2.1.1: + resolution: {integrity: sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==} + + buffer-from@1.1.2: + resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + callsites@3.1.0: + resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} + engines: {node: '>=6'} + + camelcase@5.3.1: + resolution: {integrity: sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==} + engines: {node: '>=6'} + + camelcase@6.3.0: + resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} + engines: {node: '>=10'} + + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + char-regex@1.0.2: + resolution: {integrity: sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==} + engines: {node: '>=10'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + + ci-info@3.9.0: + resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} + engines: {node: '>=8'} + + cjs-module-lexer@1.4.3: + resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==} + + cliui@8.0.1: + resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} + engines: {node: '>=12'} + + co@4.6.0: + resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==} + engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'} + + collect-v8-coverage@1.0.3: + resolution: {integrity: sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + concat-map@0.0.1: + resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + create-jest@29.7.0: + resolution: {integrity: sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + hasBin: true + + cross-spawn@7.0.6: + resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} + engines: {node: '>= 8'} + + debug@4.4.3: resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} engines: {node: '>=6.0'} peerDependencies: - supports-color: '*' + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + dedent@1.7.2: + resolution: {integrity: sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==} + peerDependencies: + babel-plugin-macros: ^3.1.0 + peerDependenciesMeta: + babel-plugin-macros: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + + deep-is@0.1.4: + resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + + deepmerge@4.3.1: + resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==} + engines: {node: '>=0.10.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + detect-newline@3.1.0: + resolution: {integrity: sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==} + engines: {node: '>=8'} + + diff-sequences@29.6.3: + resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + electron-to-chromium@1.5.433: + resolution: {integrity: sha512-5lCAbyZBjtmUt/RAGHRqrL2q0oEFRThDAsZHHDn9XHa89Qw7gMYOeSicBTy+AHfvo0r6vwsZvqNJTQIQy1BLzA==} + + emittery@0.13.1: + resolution: {integrity: sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==} + engines: {node: '>=12'} + + emoji-regex@8.0.0: + resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + error-ex@1.3.4: + resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.21.5: + resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} + engines: {node: '>=12'} + hasBin: true + + esbuild@0.25.12: + resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} + engines: {node: '>=18'} + hasBin: true + + escalade@3.2.0: + resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} + engines: {node: '>=6'} + + escape-string-regexp@2.0.0: + resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} + engines: {node: '>=8'} + + escape-string-regexp@4.0.0: + resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + engines: {node: '>=10'} + + eslint-scope@8.4.0: + resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint-visitor-keys@3.4.3: + resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} + engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + + eslint-visitor-keys@4.2.1: + resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + eslint-visitor-keys@5.0.1: + resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} + engines: {node: ^20.19.0 || ^22.13.0 || >=24} + + eslint@9.39.4: + resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. + hasBin: true + peerDependencies: + jiti: '*' + peerDependenciesMeta: + jiti: + optional: true + + espree@10.4.0: + resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==} + engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + + esprima@4.0.1: + resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} + engines: {node: '>=4'} + hasBin: true + + esquery@1.7.0: + resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} + engines: {node: '>=0.10'} + + esrecurse@4.3.0: + resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} + engines: {node: '>=4.0'} + + estraverse@5.3.0: + resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} + engines: {node: '>=4.0'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + esutils@2.0.3: + resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} + engines: {node: '>=0.10.0'} + + execa@5.1.1: + resolution: {integrity: sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==} + engines: {node: '>=10'} + + exit@0.1.2: + resolution: {integrity: sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==} + engines: {node: '>= 0.8.0'} + + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + expect@29.7.0: + resolution: {integrity: sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-json-stable-stringify@2.1.0: + resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + + fast-levenshtein@2.0.6: + resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + + fb-watchman@2.0.2: + resolution: {integrity: sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-entry-cache@8.0.0: + resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} + engines: {node: '>=16.0.0'} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + find-up@4.1.0: + resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} + engines: {node: '>=8'} + + find-up@5.0.0: + resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} + engines: {node: '>=10'} + + flat-cache@4.0.1: + resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} + engines: {node: '>=16'} + + flatted@3.4.2: + resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + + fs.realpath@1.0.0: + resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + gensync@1.0.0-beta.2: + resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} + engines: {node: '>=6.9.0'} + + get-caller-file@2.0.5: + resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} + engines: {node: 6.* || 8.* || >= 10.*} + + get-package-type@0.1.0: + resolution: {integrity: sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==} + engines: {node: '>=8.0.0'} + + get-stream@6.0.1: + resolution: {integrity: sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==} + engines: {node: '>=10'} + + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + + glob-parent@6.0.2: + resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} + engines: {node: '>=10.13.0'} + + glob@7.2.3: + resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + + globals@14.0.0: + resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} + engines: {node: '>=18'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + handlebars@4.7.9: + resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + engines: {node: '>=0.4.7'} + hasBin: true + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + html-escaper@2.0.2: + resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} + + human-signals@2.1.0: + resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} + engines: {node: '>=10.17.0'} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + ignore@5.3.2: + resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} + engines: {node: '>= 4'} + + ignore@7.0.5: + resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} + engines: {node: '>= 4'} + + import-fresh@3.3.1: + resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} + engines: {node: '>=6'} + + import-local@3.2.0: + resolution: {integrity: sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==} + engines: {node: '>=8'} + hasBin: true + + imurmurhash@0.1.4: + resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} + engines: {node: '>=0.8.19'} + + inflight@1.0.6: + resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==} + deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful. + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + is-arrayish@0.2.1: + resolution: {integrity: sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==} + + is-core-module@2.17.0: + resolution: {integrity: sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==} + engines: {node: '>= 0.4'} + + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + + is-fullwidth-code-point@3.0.0: + resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} + engines: {node: '>=8'} + + is-generator-fn@2.1.0: + resolution: {integrity: sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==} + engines: {node: '>=6'} + + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + is-stream@2.0.1: + resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==} + engines: {node: '>=8'} + + isexe@2.0.0: + resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + + istanbul-lib-coverage@3.2.2: + resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} + engines: {node: '>=8'} + + istanbul-lib-instrument@5.2.1: + resolution: {integrity: sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==} + engines: {node: '>=8'} + + istanbul-lib-instrument@6.0.3: + resolution: {integrity: sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==} + engines: {node: '>=10'} + + istanbul-lib-report@3.0.1: + resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} + engines: {node: '>=10'} + + istanbul-lib-source-maps@4.0.1: + resolution: {integrity: sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==} + engines: {node: '>=10'} + + istanbul-reports@3.2.0: + resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} + engines: {node: '>=8'} + + jest-changed-files@29.7.0: + resolution: {integrity: sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-circus@29.7.0: + resolution: {integrity: sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-cli@29.7.0: + resolution: {integrity: sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + hasBin: true + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + + jest-config@29.7.0: + resolution: {integrity: sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + peerDependencies: + '@types/node': '*' + ts-node: '>=9.0.0' + peerDependenciesMeta: + '@types/node': + optional: true + ts-node: + optional: true + + jest-diff@29.7.0: + resolution: {integrity: sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-docblock@29.7.0: + resolution: {integrity: sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-each@29.7.0: + resolution: {integrity: sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-environment-node@29.7.0: + resolution: {integrity: sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-get-type@29.6.3: + resolution: {integrity: sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-haste-map@29.7.0: + resolution: {integrity: sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-leak-detector@29.7.0: + resolution: {integrity: sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-matcher-utils@29.7.0: + resolution: {integrity: sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-message-util@29.7.0: + resolution: {integrity: sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-mock@29.7.0: + resolution: {integrity: sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-pnp-resolver@1.2.3: + resolution: {integrity: sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==} + engines: {node: '>=6'} + peerDependencies: + jest-resolve: '*' + peerDependenciesMeta: + jest-resolve: + optional: true + + jest-regex-util@29.6.3: + resolution: {integrity: sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-resolve-dependencies@29.7.0: + resolution: {integrity: sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-resolve@29.7.0: + resolution: {integrity: sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-runner@29.7.0: + resolution: {integrity: sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-runtime@29.7.0: + resolution: {integrity: sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-snapshot@29.7.0: + resolution: {integrity: sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-util@29.7.0: + resolution: {integrity: sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-validate@29.7.0: + resolution: {integrity: sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-watcher@29.7.0: + resolution: {integrity: sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-worker@29.7.0: + resolution: {integrity: sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest@29.7.0: + resolution: {integrity: sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + hasBin: true + peerDependencies: + node-notifier: ^8.0.1 || ^9.0.0 || ^10.0.0 + peerDependenciesMeta: + node-notifier: + optional: true + + jiti@1.21.7: + resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==} + hasBin: true + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + js-yaml@3.15.2: + resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} + hasBin: true + + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + + jsesc@3.1.0: + resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} + engines: {node: '>=6'} + hasBin: true + + json-buffer@3.0.1: + resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + + json-parse-even-better-errors@2.3.1: + resolution: {integrity: sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==} + + json-schema-traverse@0.4.1: + resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + + json-stable-stringify-without-jsonify@1.0.1: + resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + + json5@2.2.3: + resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} + engines: {node: '>=6'} + hasBin: true + + keytar@7.9.0: + resolution: {integrity: sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==} + + keyv@4.5.4: + resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + + kleur@3.0.3: + resolution: {integrity: sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==} + engines: {node: '>=6'} + + leven@3.1.0: + resolution: {integrity: sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==} + engines: {node: '>=6'} + + levn@0.4.1: + resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} + engines: {node: '>= 0.8.0'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + locate-path@5.0.0: + resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} + engines: {node: '>=8'} + + locate-path@6.0.0: + resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} + engines: {node: '>=10'} + + lodash.memoize@4.1.2: + resolution: {integrity: sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==} + + lodash.merge@4.6.2: + resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + lru-cache@5.1.1: + resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + make-dir@4.0.0: + resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} + engines: {node: '>=10'} + + make-error@1.3.6: + resolution: {integrity: sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==} + + makeerror@1.0.12: + resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} + + merge-stream@2.0.0: + resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mimic-fn@2.1.0: + resolution: {integrity: sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==} + engines: {node: '>=6'} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimatch@10.2.5: + resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} + engines: {node: 18 || 20 || >=22} + + minimatch@3.1.5: + resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.19: + resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + + natural-compare@1.4.0: + resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + + neo-async@2.6.2: + resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} + + node-abi@3.96.0: + resolution: {integrity: sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==} + engines: {node: '>=10'} + + node-addon-api@4.3.0: + resolution: {integrity: sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==} + + node-int64@0.4.0: + resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==} + + node-releases@2.0.56: + resolution: {integrity: sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A==} + engines: {node: '>=18'} + + normalize-path@3.0.0: + resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} + engines: {node: '>=0.10.0'} + + npm-run-path@4.0.1: + resolution: {integrity: sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==} + engines: {node: '>=8'} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + onetime@5.1.2: + resolution: {integrity: sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==} + engines: {node: '>=6'} + + optionator@0.9.4: + resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} + engines: {node: '>= 0.8.0'} + + p-limit@2.3.0: + resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} + engines: {node: '>=6'} + + p-limit@3.1.0: + resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} + engines: {node: '>=10'} + + p-locate@4.1.0: + resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} + engines: {node: '>=8'} + + p-locate@5.0.0: + resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} + engines: {node: '>=10'} + + p-try@2.2.0: + resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} + engines: {node: '>=6'} + + parent-module@1.0.1: + resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} + engines: {node: '>=6'} + + parse-json@5.2.0: + resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==} + engines: {node: '>=8'} + + path-exists@4.0.0: + resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} + engines: {node: '>=8'} + + path-is-absolute@1.0.1: + resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==} + engines: {node: '>=0.10.0'} + + path-key@3.1.1: + resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} + engines: {node: '>=8'} + + path-parse@1.0.7: + resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} + + pathe@1.1.2: + resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + + pkg-dir@4.2.0: + resolution: {integrity: sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==} + engines: {node: '>=8'} + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + + prelude-ls@1.2.1: + resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} + engines: {node: '>= 0.8.0'} + + pretty-format@29.7.0: + resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + prompts@2.4.2: + resolution: {integrity: sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==} + engines: {node: '>= 6'} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + pure-rand@6.1.0: + resolution: {integrity: sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==} + + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + + react-is@18.3.1: + resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==} + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + require-directory@2.1.1: + resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==} + engines: {node: '>=0.10.0'} + + resolve-cwd@3.0.0: + resolution: {integrity: sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==} + engines: {node: '>=8'} + + resolve-from@4.0.0: + resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} + engines: {node: '>=4'} + + resolve-from@5.0.0: + resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} + engines: {node: '>=8'} + + resolve.exports@2.0.3: + resolution: {integrity: sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==} + engines: {node: '>=10'} + + resolve@1.22.12: + resolution: {integrity: sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==} + engines: {node: '>= 0.4'} + hasBin: true + + rollup@4.63.4: + resolution: {integrity: sha512-4U0liVayNIoLp3GFl1FcI8561WepLnZ1rqfraGh7S9B3Ur5F9S283y8Futii7RUU2C/97tOBmBy7nYvhoiOpbQ==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + semver@6.3.1: + resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} + hasBin: true + + semver@7.8.0: + resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} + engines: {node: '>=10'} + hasBin: true + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} + + shebang-regex@3.0.0: + resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} + engines: {node: '>=8'} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + signal-exit@3.0.7: + resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + sisteransi@1.0.5: + resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} + + slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + source-map-support@0.5.13: + resolution: {integrity: sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==} + + source-map@0.6.1: + resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} + engines: {node: '>=0.10.0'} + + sprintf-js@1.0.3: + resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} + + stack-utils@2.0.6: + resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} + engines: {node: '>=10'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + string-length@4.0.2: + resolution: {integrity: sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==} + engines: {node: '>=10'} + + string-width@4.2.3: + resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==} + engines: {node: '>=8'} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-ansi@6.0.1: + resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} + engines: {node: '>=8'} + + strip-bom@4.0.0: + resolution: {integrity: sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==} + engines: {node: '>=8'} + + strip-final-newline@2.0.0: + resolution: {integrity: sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==} + engines: {node: '>=6'} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + + strip-json-comments@3.1.1: + resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} + engines: {node: '>=8'} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + supports-color@8.1.1: + resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==} + engines: {node: '>=10'} + + supports-preserve-symlinks-flag@1.0.0: + resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} + engines: {node: '>= 0.4'} + + tar-fs@2.1.5: + resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + + test-exclude@6.0.0: + resolution: {integrity: sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==} + engines: {node: '>=8'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.16: + resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@1.2.0: + resolution: {integrity: sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==} + engines: {node: '>=14.0.0'} + + tinyspy@3.0.2: + resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==} + engines: {node: '>=14.0.0'} + + tmpl@1.0.5: + resolution: {integrity: sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + ts-api-utils@2.5.0: + resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} + engines: {node: '>=18.12'} + peerDependencies: + typescript: '>=4.8.4' + + ts-jest@29.4.12: + resolution: {integrity: sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==} + engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@babel/core': '>=7.0.0-beta.0 <8' + '@jest/transform': ^29.0.0 || ^30.0.0 + '@jest/types': ^29.0.0 || ^30.0.0 + babel-jest: ^29.0.0 || ^30.0.0 + esbuild: '*' + jest: ^29.0.0 || ^30.0.0 + jest-util: ^29.0.0 || ^30.0.0 + typescript: '>=4.3 <7' peerDependenciesMeta: - supports-color: + '@babel/core': + optional: true + '@jest/transform': optional: true + '@jest/types': + optional: true + babel-jest: + optional: true + esbuild: + optional: true + jest-util: + optional: true + + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + + turbo@2.9.12: + resolution: {integrity: sha512-lCPgus1NuTiBdaITWqzSH/Ff6HVL8HHGBtOXHg1dHRfcshN79XkygSdh0M6g8b0td91ILLG5MTkLOkp5UvyPJw==} + hasBin: true + + type-check@0.4.0: + resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} + engines: {node: '>= 0.8.0'} + + type-detect@4.0.8: + resolution: {integrity: sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==} + engines: {node: '>=4'} + + type-fest@0.21.3: + resolution: {integrity: sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==} + engines: {node: '>=10'} + + type-fest@4.41.0: + resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==} + engines: {node: '>=16'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + uglify-js@3.19.3: + resolution: {integrity: sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==} + engines: {node: '>=0.8.0'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + + update-browserslist-db@1.3.3: + resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + + uri-js@4.4.1: + resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + v8-to-istanbul@9.3.0: + resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==} + engines: {node: '>=10.12.0'} + + vite-node@2.1.9: + resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + + vite@5.4.21: + resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@types/node': ^18.0.0 || >=20.0.0 + less: '*' + lightningcss: ^1.21.0 + sass: '*' + sass-embedded: '*' + stylus: '*' + sugarss: '*' + terser: ^5.4.0 + peerDependenciesMeta: + '@types/node': + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + + vitest@2.1.9: + resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==} + engines: {node: ^18.0.0 || >=20.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/node': ^18.0.0 || >=20.0.0 + '@vitest/browser': 2.1.9 + '@vitest/ui': 2.1.9 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + walker@1.0.8: + resolution: {integrity: sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==} + + which@2.0.2: + resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} + engines: {node: '>= 8'} + hasBin: true - deep-is@0.1.4: - resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true - escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} + word-wrap@1.2.5: + resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} + engines: {node: '>=0.10.0'} + + wordwrap@1.0.0: + resolution: {integrity: sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==} + + wrap-ansi@7.0.0: + resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==} engines: {node: '>=10'} - eslint-scope@8.4.0: - resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - eslint-visitor-keys@3.4.3: - resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} + write-file-atomic@4.0.2: + resolution: {integrity: sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==} + engines: {node: ^12.13.0 || ^14.15.0 || >=16.0.0} - eslint-visitor-keys@4.2.1: - resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + y18n@5.0.8: + resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} + engines: {node: '>=10'} - eslint-visitor-keys@5.0.1: - resolution: {integrity: sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==} - engines: {node: ^20.19.0 || ^22.13.0 || >=24} + yallist@3.1.1: + resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} - eslint@9.39.4: - resolution: {integrity: sha512-XoMjdBOwe/esVgEvLmNsD3IRHkm7fbKIUGvrleloJXUZgDHig2IPWNniv+GwjyJXzuNqVjlr5+4yVUZjycJwfQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. - hasBin: true - peerDependencies: - jiti: '*' - peerDependenciesMeta: - jiti: - optional: true + yargs-parser@21.1.1: + resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} + engines: {node: '>=12'} - espree@10.4.0: - resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + yargs@17.7.3: + resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} + engines: {node: '>=12'} - esquery@1.7.0: - resolution: {integrity: sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==} - engines: {node: '>=0.10'} + yocto-queue@0.1.0: + resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} + engines: {node: '>=10'} - esrecurse@4.3.0: - resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} - engines: {node: '>=4.0'} +snapshots: - estraverse@5.3.0: - resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} - engines: {node: '>=4.0'} + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 - esutils@2.0.3: - resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} - engines: {node: '>=0.10.0'} + '@babel/compat-data@7.29.7': {} - fast-deep-equal@3.1.3: - resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + '@babel/core@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/remapping': 2.3.5 + convert-source-map: 2.0.0 + debug: 4.4.3 + gensync: 1.0.0-beta.2 + json5: 2.2.3 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color - fast-json-stable-stringify@2.1.0: - resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} + '@babel/generator@7.29.8': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 - fast-levenshtein@2.0.6: - resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.29.0 + lru-cache: 5.1.1 + semver: 6.3.1 - fdir@6.5.0: - resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} - engines: {node: '>=12.0.0'} - peerDependencies: - picomatch: ^3 || ^4 - peerDependenciesMeta: - picomatch: - optional: true + '@babel/helper-globals@7.29.7': {} - file-entry-cache@8.0.0: - resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} - engines: {node: '>=16.0.0'} + '@babel/helper-module-imports@7.29.7': + dependencies: + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 + transitivePeerDependencies: + - supports-color - find-up@5.0.0: - resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} - engines: {node: '>=10'} + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.8 + transitivePeerDependencies: + - supports-color - flat-cache@4.0.1: - resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} - engines: {node: '>=16'} + '@babel/helper-plugin-utils@7.29.7': {} - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + '@babel/helper-string-parser@7.29.7': {} - glob-parent@6.0.2: - resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} - engines: {node: '>=10.13.0'} + '@babel/helper-validator-identifier@7.29.7': {} - globals@14.0.0: - resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} - engines: {node: '>=18'} + '@babel/helper-validator-option@7.29.7': {} - has-flag@4.0.0: - resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} - engines: {node: '>=8'} + '@babel/helpers@7.29.7': + dependencies: + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 - ignore@5.3.2: - resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} - engines: {node: '>= 4'} + '@babel/parser@7.29.9': + dependencies: + '@babel/types': 7.29.8 - ignore@7.0.5: - resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} - engines: {node: '>= 4'} + '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - import-fresh@3.3.1: - resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} - engines: {node: '>=6'} + '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - imurmurhash@0.1.4: - resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} - engines: {node: '>=0.8.19'} + '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} + '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} + '@babel/plugin-syntax-import-attributes@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - isexe@2.0.0: - resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} + '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - jiti@1.21.7: - resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==} - hasBin: true + '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - js-yaml@4.1.1: - resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} - hasBin: true + '@babel/plugin-syntax-jsx@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - json-buffer@3.0.1: - resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - json-schema-traverse@0.4.1: - resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} + '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - json-stable-stringify-without-jsonify@1.0.1: - resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - keyv@4.5.4: - resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} + '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - levn@0.4.1: - resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} - engines: {node: '>= 0.8.0'} + '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - locate-path@6.0.0: - resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} - engines: {node: '>=10'} + '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - lodash.merge@4.6.2: - resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} + '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - minimatch@10.2.5: - resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} - engines: {node: 18 || 20 || >=22} + '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - minimatch@3.1.5: - resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} + '@babel/plugin-syntax-typescript@7.29.7(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 + '@babel/helper-plugin-utils': 7.29.7 - ms@2.1.3: - resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + '@babel/template@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 - natural-compare@1.4.0: - resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} + '@babel/traverse@7.29.8': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.9 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color - optionator@0.9.4: - resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} - engines: {node: '>= 0.8.0'} + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 - p-limit@3.1.0: - resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} - engines: {node: '>=10'} + '@bcoe/v8-coverage@0.2.3': {} - p-locate@5.0.0: - resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} - engines: {node: '>=10'} + '@cloudflare/workers-types@4.20260702.1': {} - parent-module@1.0.1: - resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} - engines: {node: '>=6'} + '@esbuild/aix-ppc64@0.21.5': + optional: true - path-exists@4.0.0: - resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} - engines: {node: '>=8'} + '@esbuild/aix-ppc64@0.25.12': + optional: true - path-key@3.1.1: - resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} - engines: {node: '>=8'} + '@esbuild/android-arm64@0.21.5': + optional: true - picomatch@4.0.4: - resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} - engines: {node: '>=12'} + '@esbuild/android-arm64@0.25.12': + optional: true + + '@esbuild/android-arm@0.21.5': + optional: true + + '@esbuild/android-arm@0.25.12': + optional: true + + '@esbuild/android-x64@0.21.5': + optional: true + + '@esbuild/android-x64@0.25.12': + optional: true + + '@esbuild/darwin-arm64@0.21.5': + optional: true + + '@esbuild/darwin-arm64@0.25.12': + optional: true + + '@esbuild/darwin-x64@0.21.5': + optional: true + + '@esbuild/darwin-x64@0.25.12': + optional: true + + '@esbuild/freebsd-arm64@0.21.5': + optional: true + + '@esbuild/freebsd-arm64@0.25.12': + optional: true + + '@esbuild/freebsd-x64@0.21.5': + optional: true + + '@esbuild/freebsd-x64@0.25.12': + optional: true + + '@esbuild/linux-arm64@0.21.5': + optional: true + + '@esbuild/linux-arm64@0.25.12': + optional: true + + '@esbuild/linux-arm@0.21.5': + optional: true + + '@esbuild/linux-arm@0.25.12': + optional: true + + '@esbuild/linux-ia32@0.21.5': + optional: true + + '@esbuild/linux-ia32@0.25.12': + optional: true + + '@esbuild/linux-loong64@0.21.5': + optional: true + + '@esbuild/linux-loong64@0.25.12': + optional: true + + '@esbuild/linux-mips64el@0.21.5': + optional: true + + '@esbuild/linux-mips64el@0.25.12': + optional: true + + '@esbuild/linux-ppc64@0.21.5': + optional: true + + '@esbuild/linux-ppc64@0.25.12': + optional: true + + '@esbuild/linux-riscv64@0.21.5': + optional: true + + '@esbuild/linux-riscv64@0.25.12': + optional: true - prelude-ls@1.2.1: - resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} - engines: {node: '>= 0.8.0'} + '@esbuild/linux-s390x@0.21.5': + optional: true - punycode@2.3.1: - resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} - engines: {node: '>=6'} + '@esbuild/linux-s390x@0.25.12': + optional: true - resolve-from@4.0.0: - resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} - engines: {node: '>=4'} + '@esbuild/linux-x64@0.21.5': + optional: true - semver@7.8.0: - resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} - engines: {node: '>=10'} - hasBin: true + '@esbuild/linux-x64@0.25.12': + optional: true - shebang-command@2.0.0: - resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} - engines: {node: '>=8'} + '@esbuild/netbsd-arm64@0.25.12': + optional: true - shebang-regex@3.0.0: - resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} - engines: {node: '>=8'} + '@esbuild/netbsd-x64@0.21.5': + optional: true - strip-json-comments@3.1.1: - resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} - engines: {node: '>=8'} + '@esbuild/netbsd-x64@0.25.12': + optional: true - supports-color@7.2.0: - resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} - engines: {node: '>=8'} + '@esbuild/openbsd-arm64@0.25.12': + optional: true - tinyglobby@0.2.16: - resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} - engines: {node: '>=12.0.0'} + '@esbuild/openbsd-x64@0.21.5': + optional: true - ts-api-utils@2.5.0: - resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} - engines: {node: '>=18.12'} - peerDependencies: - typescript: '>=4.8.4' + '@esbuild/openbsd-x64@0.25.12': + optional: true - turbo@2.9.12: - resolution: {integrity: sha512-lCPgus1NuTiBdaITWqzSH/Ff6HVL8HHGBtOXHg1dHRfcshN79XkygSdh0M6g8b0td91ILLG5MTkLOkp5UvyPJw==} - hasBin: true + '@esbuild/openharmony-arm64@0.25.12': + optional: true - type-check@0.4.0: - resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} - engines: {node: '>= 0.8.0'} + '@esbuild/sunos-x64@0.21.5': + optional: true - typescript@5.9.3: - resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} - engines: {node: '>=14.17'} - hasBin: true + '@esbuild/sunos-x64@0.25.12': + optional: true - uri-js@4.4.1: - resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} + '@esbuild/win32-arm64@0.21.5': + optional: true - which@2.0.2: - resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} - engines: {node: '>= 8'} - hasBin: true + '@esbuild/win32-arm64@0.25.12': + optional: true - word-wrap@1.2.5: - resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} - engines: {node: '>=0.10.0'} + '@esbuild/win32-ia32@0.21.5': + optional: true - yocto-queue@0.1.0: - resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} - engines: {node: '>=10'} + '@esbuild/win32-ia32@0.25.12': + optional: true -snapshots: + '@esbuild/win32-x64@0.21.5': + optional: true + + '@esbuild/win32-x64@0.25.12': + optional: true '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4(jiti@1.21.7))': dependencies: @@ -592,6 +2987,285 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} + '@istanbuljs/load-nyc-config@1.1.0': + dependencies: + camelcase: 5.3.1 + find-up: 4.1.0 + get-package-type: 0.1.0 + js-yaml: 3.15.2 + resolve-from: 5.0.0 + + '@istanbuljs/schema@0.1.6': {} + + '@jest/console@29.7.0': + dependencies: + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + chalk: 4.1.2 + jest-message-util: 29.7.0 + jest-util: 29.7.0 + slash: 3.0.0 + + '@jest/core@29.7.0': + dependencies: + '@jest/console': 29.7.0 + '@jest/reporters': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + ansi-escapes: 4.3.2 + chalk: 4.1.2 + ci-info: 3.9.0 + exit: 0.1.2 + graceful-fs: 4.2.11 + jest-changed-files: 29.7.0 + jest-config: 29.7.0(@types/node@20.19.43) + jest-haste-map: 29.7.0 + jest-message-util: 29.7.0 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-resolve-dependencies: 29.7.0 + jest-runner: 29.7.0 + jest-runtime: 29.7.0 + jest-snapshot: 29.7.0 + jest-util: 29.7.0 + jest-validate: 29.7.0 + jest-watcher: 29.7.0 + micromatch: 4.0.8 + pretty-format: 29.7.0 + slash: 3.0.0 + strip-ansi: 6.0.1 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + - ts-node + + '@jest/environment@29.7.0': + dependencies: + '@jest/fake-timers': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + jest-mock: 29.7.0 + + '@jest/expect-utils@29.7.0': + dependencies: + jest-get-type: 29.6.3 + + '@jest/expect@29.7.0': + dependencies: + expect: 29.7.0 + jest-snapshot: 29.7.0 + transitivePeerDependencies: + - supports-color + + '@jest/fake-timers@29.7.0': + dependencies: + '@jest/types': 29.6.3 + '@sinonjs/fake-timers': 10.3.0 + '@types/node': 20.19.43 + jest-message-util: 29.7.0 + jest-mock: 29.7.0 + jest-util: 29.7.0 + + '@jest/globals@29.7.0': + dependencies: + '@jest/environment': 29.7.0 + '@jest/expect': 29.7.0 + '@jest/types': 29.6.3 + jest-mock: 29.7.0 + transitivePeerDependencies: + - supports-color + + '@jest/reporters@29.7.0': + dependencies: + '@bcoe/v8-coverage': 0.2.3 + '@jest/console': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + '@jridgewell/trace-mapping': 0.3.31 + '@types/node': 20.19.43 + chalk: 4.1.2 + collect-v8-coverage: 1.0.3 + exit: 0.1.2 + glob: 7.2.3 + graceful-fs: 4.2.11 + istanbul-lib-coverage: 3.2.2 + istanbul-lib-instrument: 6.0.3 + istanbul-lib-report: 3.0.1 + istanbul-lib-source-maps: 4.0.1 + istanbul-reports: 3.2.0 + jest-message-util: 29.7.0 + jest-util: 29.7.0 + jest-worker: 29.7.0 + slash: 3.0.0 + string-length: 4.0.2 + strip-ansi: 6.0.1 + v8-to-istanbul: 9.3.0 + transitivePeerDependencies: + - supports-color + + '@jest/schemas@29.6.3': + dependencies: + '@sinclair/typebox': 0.27.12 + + '@jest/source-map@29.6.3': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + callsites: 3.1.0 + graceful-fs: 4.2.11 + + '@jest/test-result@29.7.0': + dependencies: + '@jest/console': 29.7.0 + '@jest/types': 29.6.3 + '@types/istanbul-lib-coverage': 2.0.6 + collect-v8-coverage: 1.0.3 + + '@jest/test-sequencer@29.7.0': + dependencies: + '@jest/test-result': 29.7.0 + graceful-fs: 4.2.11 + jest-haste-map: 29.7.0 + slash: 3.0.0 + + '@jest/transform@29.7.0': + dependencies: + '@babel/core': 7.29.7 + '@jest/types': 29.6.3 + '@jridgewell/trace-mapping': 0.3.31 + babel-plugin-istanbul: 6.1.1 + chalk: 4.1.2 + convert-source-map: 2.0.0 + fast-json-stable-stringify: 2.1.0 + graceful-fs: 4.2.11 + jest-haste-map: 29.7.0 + jest-regex-util: 29.6.3 + jest-util: 29.7.0 + micromatch: 4.0.8 + pirates: 4.0.7 + slash: 3.0.0 + write-file-atomic: 4.0.2 + transitivePeerDependencies: + - supports-color + + '@jest/types@29.6.3': + dependencies: + '@jest/schemas': 29.6.3 + '@types/istanbul-lib-coverage': 2.0.6 + '@types/istanbul-reports': 3.0.4 + '@types/node': 20.19.43 + '@types/yargs': 17.0.35 + chalk: 4.1.2 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/remapping@2.3.5': + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@rollup/rollup-android-arm-eabi@4.63.4': + optional: true + + '@rollup/rollup-android-arm64@4.63.4': + optional: true + + '@rollup/rollup-darwin-arm64@4.63.4': + optional: true + + '@rollup/rollup-darwin-x64@4.63.4': + optional: true + + '@rollup/rollup-freebsd-arm64@4.63.4': + optional: true + + '@rollup/rollup-freebsd-x64@4.63.4': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.63.4': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.63.4': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.63.4': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.63.4': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.63.4': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.63.4': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.63.4': + optional: true + + '@rollup/rollup-linux-x64-musl@4.63.4': + optional: true + + '@rollup/rollup-openbsd-x64@4.63.4': + optional: true + + '@rollup/rollup-openharmony-arm64@4.63.4': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.63.4': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.63.4': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.63.4': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.63.4': + optional: true + + '@sinclair/typebox@0.27.12': {} + + '@sinonjs/commons@3.0.1': + dependencies: + type-detect: 4.0.8 + + '@sinonjs/fake-timers@10.3.0': + dependencies: + '@sinonjs/commons': 3.0.1 + '@turbo/darwin-64@2.9.12': optional: true @@ -610,10 +3284,66 @@ snapshots: '@turbo/windows-arm64@2.9.12': optional: true + '@types/babel__core@7.20.5': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + '@types/babel__generator': 7.27.0 + '@types/babel__template': 7.4.4 + '@types/babel__traverse': 7.28.0 + + '@types/babel__generator@7.27.0': + dependencies: + '@babel/types': 7.29.8 + + '@types/babel__template@7.4.4': + dependencies: + '@babel/parser': 7.29.9 + '@babel/types': 7.29.8 + + '@types/babel__traverse@7.28.0': + dependencies: + '@babel/types': 7.29.8 + '@types/estree@1.0.9': {} + '@types/graceful-fs@4.1.9': + dependencies: + '@types/node': 20.19.43 + + '@types/istanbul-lib-coverage@2.0.6': {} + + '@types/istanbul-lib-report@3.0.3': + dependencies: + '@types/istanbul-lib-coverage': 2.0.6 + + '@types/istanbul-reports@3.0.4': + dependencies: + '@types/istanbul-lib-report': 3.0.3 + + '@types/jest@29.5.14': + dependencies: + expect: 29.7.0 + pretty-format: 29.7.0 + '@types/json-schema@7.0.15': {} + '@types/node@20.19.43': + dependencies: + undici-types: 6.21.0 + + '@types/node@22.20.4': + dependencies: + undici-types: 6.21.0 + + '@types/stack-utils@2.0.3': {} + + '@types/yargs-parser@21.0.3': {} + + '@types/yargs@17.0.35': + dependencies: + '@types/yargs-parser': 21.0.3 + '@typescript-eslint/eslint-plugin@8.59.2(@typescript-eslint/parser@8.59.2(eslint@9.39.4(jiti@1.21.7))(typescript@5.9.3))(eslint@9.39.4(jiti@1.21.7))(typescript@5.9.3)': dependencies: '@eslint-community/regexpp': 4.12.2 @@ -705,29 +3435,163 @@ snapshots: '@typescript-eslint/types': 8.59.2 eslint-visitor-keys: 5.0.1 + '@vitest/expect@2.1.9': + dependencies: + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + tinyrainbow: 1.2.0 + + '@vitest/mocker@2.1.9(vite@5.4.21(@types/node@20.19.43))': + dependencies: + '@vitest/spy': 2.1.9 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21(@types/node@20.19.43) + + '@vitest/mocker@2.1.9(vite@5.4.21(@types/node@22.20.4))': + dependencies: + '@vitest/spy': 2.1.9 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 5.4.21(@types/node@22.20.4) + + '@vitest/pretty-format@2.1.9': + dependencies: + tinyrainbow: 1.2.0 + + '@vitest/runner@2.1.9': + dependencies: + '@vitest/utils': 2.1.9 + pathe: 1.1.2 + + '@vitest/snapshot@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + magic-string: 0.30.21 + pathe: 1.1.2 + + '@vitest/spy@2.1.9': + dependencies: + tinyspy: 3.0.2 + + '@vitest/utils@2.1.9': + dependencies: + '@vitest/pretty-format': 2.1.9 + loupe: 3.2.1 + tinyrainbow: 1.2.0 + acorn-jsx@5.3.2(acorn@8.16.0): dependencies: acorn: 8.16.0 acorn@8.16.0: {} - ajv@6.15.0: + ajv@6.15.0: + dependencies: + fast-deep-equal: 3.1.3 + fast-json-stable-stringify: 2.1.0 + json-schema-traverse: 0.4.1 + uri-js: 4.4.1 + + ansi-escapes@4.3.2: + dependencies: + type-fest: 0.21.3 + + ansi-regex@5.0.1: {} + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.2.0: {} + + anymatch@3.1.3: + dependencies: + normalize-path: 3.0.0 + picomatch: 2.3.2 + + argparse@1.0.10: + dependencies: + sprintf-js: 1.0.3 + + argparse@2.0.1: {} + + assertion-error@2.0.1: {} + + babel-jest@29.7.0(@babel/core@7.29.7): + dependencies: + '@babel/core': 7.29.7 + '@jest/transform': 29.7.0 + '@types/babel__core': 7.20.5 + babel-plugin-istanbul: 6.1.1 + babel-preset-jest: 29.6.3(@babel/core@7.29.7) + chalk: 4.1.2 + graceful-fs: 4.2.11 + slash: 3.0.0 + transitivePeerDependencies: + - supports-color + + babel-plugin-istanbul@6.1.1: dependencies: - fast-deep-equal: 3.1.3 - fast-json-stable-stringify: 2.1.0 - json-schema-traverse: 0.4.1 - uri-js: 4.4.1 + '@babel/helper-plugin-utils': 7.29.7 + '@istanbuljs/load-nyc-config': 1.1.0 + '@istanbuljs/schema': 0.1.6 + istanbul-lib-instrument: 5.2.1 + test-exclude: 6.0.0 + transitivePeerDependencies: + - supports-color - ansi-styles@4.3.0: + babel-plugin-jest-hoist@29.6.3: dependencies: - color-convert: 2.0.1 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 + '@types/babel__core': 7.20.5 + '@types/babel__traverse': 7.28.0 - argparse@2.0.1: {} + babel-preset-current-node-syntax@1.2.0(@babel/core@7.29.7): + dependencies: + '@babel/core': 7.29.7 + '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.29.7) + '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.29.7) + '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.29.7) + '@babel/plugin-syntax-import-attributes': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.7) + '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.7) + + babel-preset-jest@29.6.3(@babel/core@7.29.7): + dependencies: + '@babel/core': 7.29.7 + babel-plugin-jest-hoist: 29.6.3 + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) balanced-match@1.0.2: {} balanced-match@4.0.4: {} + base64-js@1.5.1: + optional: true + + baseline-browser-mapping@2.11.25: {} + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + optional: true + brace-expansion@1.1.14: dependencies: balanced-match: 1.0.2 @@ -737,13 +3601,78 @@ snapshots: dependencies: balanced-match: 4.0.4 + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + browserslist@4.29.0: + dependencies: + baseline-browser-mapping: 2.11.25 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.433 + node-releases: 2.0.56 + update-browserslist-db: 1.3.3(browserslist@4.29.0) + + bs-logger@0.2.6: + dependencies: + fast-json-stable-stringify: 2.1.0 + + bser@2.1.1: + dependencies: + node-int64: 0.4.0 + + buffer-from@1.1.2: {} + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + optional: true + + cac@6.7.14: {} + callsites@3.1.0: {} + camelcase@5.3.1: {} + + camelcase@6.3.0: {} + + caniuse-lite@1.0.30001810: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + chalk@4.1.2: dependencies: ansi-styles: 4.3.0 supports-color: 7.2.0 + char-regex@1.0.2: {} + + check-error@2.1.3: {} + + chownr@1.1.4: + optional: true + + ci-info@3.9.0: {} + + cjs-module-lexer@1.4.3: {} + + cliui@8.0.1: + dependencies: + string-width: 4.2.3 + strip-ansi: 6.0.1 + wrap-ansi: 7.0.0 + + co@4.6.0: {} + + collect-v8-coverage@1.0.3: {} + color-convert@2.0.1: dependencies: color-name: 1.1.4 @@ -752,6 +3681,38 @@ snapshots: concat-map@0.0.1: {} + convert-source-map@2.0.0: {} + + create-jest@29.7.0(@types/node@20.19.43): + dependencies: + '@jest/types': 29.6.3 + chalk: 4.1.2 + exit: 0.1.2 + graceful-fs: 4.2.11 + jest-config: 29.7.0(@types/node@20.19.43) + jest-util: 29.7.0 + prompts: 2.4.2 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + + create-jest@29.7.0(@types/node@22.20.4): + dependencies: + '@jest/types': 29.6.3 + chalk: 4.1.2 + exit: 0.1.2 + graceful-fs: 4.2.11 + jest-config: 29.7.0(@types/node@22.20.4) + jest-util: 29.7.0 + prompts: 2.4.2 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -762,8 +3723,107 @@ snapshots: dependencies: ms: 2.1.3 + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + optional: true + + dedent@1.7.2: {} + + deep-eql@5.0.2: {} + + deep-extend@0.6.0: + optional: true + deep-is@0.1.4: {} + deepmerge@4.3.1: {} + + detect-libc@2.1.2: + optional: true + + detect-newline@3.1.0: {} + + diff-sequences@29.6.3: {} + + electron-to-chromium@1.5.433: {} + + emittery@0.13.1: {} + + emoji-regex@8.0.0: {} + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + optional: true + + error-ex@1.3.4: + dependencies: + is-arrayish: 0.2.1 + + es-errors@1.3.0: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.21.5: + optionalDependencies: + '@esbuild/aix-ppc64': 0.21.5 + '@esbuild/android-arm': 0.21.5 + '@esbuild/android-arm64': 0.21.5 + '@esbuild/android-x64': 0.21.5 + '@esbuild/darwin-arm64': 0.21.5 + '@esbuild/darwin-x64': 0.21.5 + '@esbuild/freebsd-arm64': 0.21.5 + '@esbuild/freebsd-x64': 0.21.5 + '@esbuild/linux-arm': 0.21.5 + '@esbuild/linux-arm64': 0.21.5 + '@esbuild/linux-ia32': 0.21.5 + '@esbuild/linux-loong64': 0.21.5 + '@esbuild/linux-mips64el': 0.21.5 + '@esbuild/linux-ppc64': 0.21.5 + '@esbuild/linux-riscv64': 0.21.5 + '@esbuild/linux-s390x': 0.21.5 + '@esbuild/linux-x64': 0.21.5 + '@esbuild/netbsd-x64': 0.21.5 + '@esbuild/openbsd-x64': 0.21.5 + '@esbuild/sunos-x64': 0.21.5 + '@esbuild/win32-arm64': 0.21.5 + '@esbuild/win32-ia32': 0.21.5 + '@esbuild/win32-x64': 0.21.5 + + esbuild@0.25.12: + optionalDependencies: + '@esbuild/aix-ppc64': 0.25.12 + '@esbuild/android-arm': 0.25.12 + '@esbuild/android-arm64': 0.25.12 + '@esbuild/android-x64': 0.25.12 + '@esbuild/darwin-arm64': 0.25.12 + '@esbuild/darwin-x64': 0.25.12 + '@esbuild/freebsd-arm64': 0.25.12 + '@esbuild/freebsd-x64': 0.25.12 + '@esbuild/linux-arm': 0.25.12 + '@esbuild/linux-arm64': 0.25.12 + '@esbuild/linux-ia32': 0.25.12 + '@esbuild/linux-loong64': 0.25.12 + '@esbuild/linux-mips64el': 0.25.12 + '@esbuild/linux-ppc64': 0.25.12 + '@esbuild/linux-riscv64': 0.25.12 + '@esbuild/linux-s390x': 0.25.12 + '@esbuild/linux-x64': 0.25.12 + '@esbuild/netbsd-arm64': 0.25.12 + '@esbuild/netbsd-x64': 0.25.12 + '@esbuild/openbsd-arm64': 0.25.12 + '@esbuild/openbsd-x64': 0.25.12 + '@esbuild/openharmony-arm64': 0.25.12 + '@esbuild/sunos-x64': 0.25.12 + '@esbuild/win32-arm64': 0.25.12 + '@esbuild/win32-ia32': 0.25.12 + '@esbuild/win32-x64': 0.25.12 + + escalade@3.2.0: {} + + escape-string-regexp@2.0.0: {} + escape-string-regexp@4.0.0: {} eslint-scope@8.4.0: @@ -824,6 +3884,8 @@ snapshots: acorn-jsx: 5.3.2(acorn@8.16.0) eslint-visitor-keys: 4.2.1 + esprima@4.0.1: {} + esquery@1.7.0: dependencies: estraverse: 5.3.0 @@ -834,14 +3896,49 @@ snapshots: estraverse@5.3.0: {} + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + esutils@2.0.3: {} + execa@5.1.1: + dependencies: + cross-spawn: 7.0.6 + get-stream: 6.0.1 + human-signals: 2.1.0 + is-stream: 2.0.1 + merge-stream: 2.0.0 + npm-run-path: 4.0.1 + onetime: 5.1.2 + signal-exit: 3.0.7 + strip-final-newline: 2.0.0 + + exit@0.1.2: {} + + expand-template@2.0.3: + optional: true + + expect-type@1.4.0: {} + + expect@29.7.0: + dependencies: + '@jest/expect-utils': 29.7.0 + jest-get-type: 29.6.3 + jest-matcher-utils: 29.7.0 + jest-message-util: 29.7.0 + jest-util: 29.7.0 + fast-deep-equal@3.1.3: {} fast-json-stable-stringify@2.1.0: {} fast-levenshtein@2.0.6: {} + fb-watchman@2.0.2: + dependencies: + bser: 2.1.1 + fdir@6.5.0(picomatch@4.0.4): optionalDependencies: picomatch: 4.0.4 @@ -850,6 +3947,15 @@ snapshots: dependencies: flat-cache: 4.0.1 + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + find-up@4.1.0: + dependencies: + locate-path: 5.0.0 + path-exists: 4.0.0 + find-up@5.0.0: dependencies: locate-path: 6.0.0 @@ -862,61 +3968,615 @@ snapshots: flatted@3.4.2: {} + fs-constants@1.0.0: + optional: true + + fs.realpath@1.0.0: {} + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + gensync@1.0.0-beta.2: {} + + get-caller-file@2.0.5: {} + + get-package-type@0.1.0: {} + + get-stream@6.0.1: {} + + github-from-package@0.0.0: + optional: true + glob-parent@6.0.2: dependencies: is-glob: 4.0.3 + glob@7.2.3: + dependencies: + fs.realpath: 1.0.0 + inflight: 1.0.6 + inherits: 2.0.4 + minimatch: 3.1.5 + once: 1.4.0 + path-is-absolute: 1.0.1 + globals@14.0.0: {} + graceful-fs@4.2.11: {} + + handlebars@4.7.9: + dependencies: + minimist: 1.2.8 + neo-async: 2.6.2 + source-map: 0.6.1 + wordwrap: 1.0.0 + optionalDependencies: + uglify-js: 3.19.3 + has-flag@4.0.0: {} - ignore@5.3.2: {} + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + html-escaper@2.0.2: {} + + human-signals@2.1.0: {} + + ieee754@1.2.1: + optional: true + + ignore@5.3.2: {} + + ignore@7.0.5: {} + + import-fresh@3.3.1: + dependencies: + parent-module: 1.0.1 + resolve-from: 4.0.0 + + import-local@3.2.0: + dependencies: + pkg-dir: 4.2.0 + resolve-cwd: 3.0.0 + + imurmurhash@0.1.4: {} + + inflight@1.0.6: + dependencies: + once: 1.4.0 + wrappy: 1.0.2 + + inherits@2.0.4: {} + + ini@1.3.8: + optional: true + + is-arrayish@0.2.1: {} + + is-core-module@2.17.0: + dependencies: + hasown: 2.0.4 + + is-extglob@2.1.1: {} + + is-fullwidth-code-point@3.0.0: {} + + is-generator-fn@2.1.0: {} + + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + + is-number@7.0.0: {} + + is-stream@2.0.1: {} + + isexe@2.0.0: {} + + istanbul-lib-coverage@3.2.2: {} + + istanbul-lib-instrument@5.2.1: + dependencies: + '@babel/core': 7.29.7 + '@babel/parser': 7.29.9 + '@istanbuljs/schema': 0.1.6 + istanbul-lib-coverage: 3.2.2 + semver: 6.3.1 + transitivePeerDependencies: + - supports-color + + istanbul-lib-instrument@6.0.3: + dependencies: + '@babel/core': 7.29.7 + '@babel/parser': 7.29.9 + '@istanbuljs/schema': 0.1.6 + istanbul-lib-coverage: 3.2.2 + semver: 7.8.0 + transitivePeerDependencies: + - supports-color + + istanbul-lib-report@3.0.1: + dependencies: + istanbul-lib-coverage: 3.2.2 + make-dir: 4.0.0 + supports-color: 7.2.0 + + istanbul-lib-source-maps@4.0.1: + dependencies: + debug: 4.4.3 + istanbul-lib-coverage: 3.2.2 + source-map: 0.6.1 + transitivePeerDependencies: + - supports-color + + istanbul-reports@3.2.0: + dependencies: + html-escaper: 2.0.2 + istanbul-lib-report: 3.0.1 + + jest-changed-files@29.7.0: + dependencies: + execa: 5.1.1 + jest-util: 29.7.0 + p-limit: 3.1.0 + + jest-circus@29.7.0: + dependencies: + '@jest/environment': 29.7.0 + '@jest/expect': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + chalk: 4.1.2 + co: 4.6.0 + dedent: 1.7.2 + is-generator-fn: 2.1.0 + jest-each: 29.7.0 + jest-matcher-utils: 29.7.0 + jest-message-util: 29.7.0 + jest-runtime: 29.7.0 + jest-snapshot: 29.7.0 + jest-util: 29.7.0 + p-limit: 3.1.0 + pretty-format: 29.7.0 + pure-rand: 6.1.0 + slash: 3.0.0 + stack-utils: 2.0.6 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + + jest-cli@29.7.0(@types/node@20.19.43): + dependencies: + '@jest/core': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/types': 29.6.3 + chalk: 4.1.2 + create-jest: 29.7.0(@types/node@20.19.43) + exit: 0.1.2 + import-local: 3.2.0 + jest-config: 29.7.0(@types/node@20.19.43) + jest-util: 29.7.0 + jest-validate: 29.7.0 + yargs: 17.7.3 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + + jest-cli@29.7.0(@types/node@22.20.4): + dependencies: + '@jest/core': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/types': 29.6.3 + chalk: 4.1.2 + create-jest: 29.7.0(@types/node@22.20.4) + exit: 0.1.2 + import-local: 3.2.0 + jest-config: 29.7.0(@types/node@22.20.4) + jest-util: 29.7.0 + jest-validate: 29.7.0 + yargs: 17.7.3 + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node + + jest-config@29.7.0(@types/node@20.19.43): + dependencies: + '@babel/core': 7.29.7 + '@jest/test-sequencer': 29.7.0 + '@jest/types': 29.6.3 + babel-jest: 29.7.0(@babel/core@7.29.7) + chalk: 4.1.2 + ci-info: 3.9.0 + deepmerge: 4.3.1 + glob: 7.2.3 + graceful-fs: 4.2.11 + jest-circus: 29.7.0 + jest-environment-node: 29.7.0 + jest-get-type: 29.6.3 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-runner: 29.7.0 + jest-util: 29.7.0 + jest-validate: 29.7.0 + micromatch: 4.0.8 + parse-json: 5.2.0 + pretty-format: 29.7.0 + slash: 3.0.0 + strip-json-comments: 3.1.1 + optionalDependencies: + '@types/node': 20.19.43 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + + jest-config@29.7.0(@types/node@22.20.4): + dependencies: + '@babel/core': 7.29.7 + '@jest/test-sequencer': 29.7.0 + '@jest/types': 29.6.3 + babel-jest: 29.7.0(@babel/core@7.29.7) + chalk: 4.1.2 + ci-info: 3.9.0 + deepmerge: 4.3.1 + glob: 7.2.3 + graceful-fs: 4.2.11 + jest-circus: 29.7.0 + jest-environment-node: 29.7.0 + jest-get-type: 29.6.3 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-runner: 29.7.0 + jest-util: 29.7.0 + jest-validate: 29.7.0 + micromatch: 4.0.8 + parse-json: 5.2.0 + pretty-format: 29.7.0 + slash: 3.0.0 + strip-json-comments: 3.1.1 + optionalDependencies: + '@types/node': 22.20.4 + transitivePeerDependencies: + - babel-plugin-macros + - supports-color + + jest-diff@29.7.0: + dependencies: + chalk: 4.1.2 + diff-sequences: 29.6.3 + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-docblock@29.7.0: + dependencies: + detect-newline: 3.1.0 + + jest-each@29.7.0: + dependencies: + '@jest/types': 29.6.3 + chalk: 4.1.2 + jest-get-type: 29.6.3 + jest-util: 29.7.0 + pretty-format: 29.7.0 + + jest-environment-node@29.7.0: + dependencies: + '@jest/environment': 29.7.0 + '@jest/fake-timers': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + jest-mock: 29.7.0 + jest-util: 29.7.0 + + jest-get-type@29.6.3: {} + + jest-haste-map@29.7.0: + dependencies: + '@jest/types': 29.6.3 + '@types/graceful-fs': 4.1.9 + '@types/node': 20.19.43 + anymatch: 3.1.3 + fb-watchman: 2.0.2 + graceful-fs: 4.2.11 + jest-regex-util: 29.6.3 + jest-util: 29.7.0 + jest-worker: 29.7.0 + micromatch: 4.0.8 + walker: 1.0.8 + optionalDependencies: + fsevents: 2.3.3 + + jest-leak-detector@29.7.0: + dependencies: + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-matcher-utils@29.7.0: + dependencies: + chalk: 4.1.2 + jest-diff: 29.7.0 + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-message-util@29.7.0: + dependencies: + '@babel/code-frame': 7.29.7 + '@jest/types': 29.6.3 + '@types/stack-utils': 2.0.3 + chalk: 4.1.2 + graceful-fs: 4.2.11 + micromatch: 4.0.8 + pretty-format: 29.7.0 + slash: 3.0.0 + stack-utils: 2.0.6 + + jest-mock@29.7.0: + dependencies: + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + jest-util: 29.7.0 + + jest-pnp-resolver@1.2.3(jest-resolve@29.7.0): + optionalDependencies: + jest-resolve: 29.7.0 + + jest-regex-util@29.6.3: {} + + jest-resolve-dependencies@29.7.0: + dependencies: + jest-regex-util: 29.6.3 + jest-snapshot: 29.7.0 + transitivePeerDependencies: + - supports-color + + jest-resolve@29.7.0: + dependencies: + chalk: 4.1.2 + graceful-fs: 4.2.11 + jest-haste-map: 29.7.0 + jest-pnp-resolver: 1.2.3(jest-resolve@29.7.0) + jest-util: 29.7.0 + jest-validate: 29.7.0 + resolve: 1.22.12 + resolve.exports: 2.0.3 + slash: 3.0.0 + + jest-runner@29.7.0: + dependencies: + '@jest/console': 29.7.0 + '@jest/environment': 29.7.0 + '@jest/test-result': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + chalk: 4.1.2 + emittery: 0.13.1 + graceful-fs: 4.2.11 + jest-docblock: 29.7.0 + jest-environment-node: 29.7.0 + jest-haste-map: 29.7.0 + jest-leak-detector: 29.7.0 + jest-message-util: 29.7.0 + jest-resolve: 29.7.0 + jest-runtime: 29.7.0 + jest-util: 29.7.0 + jest-watcher: 29.7.0 + jest-worker: 29.7.0 + p-limit: 3.1.0 + source-map-support: 0.5.13 + transitivePeerDependencies: + - supports-color + + jest-runtime@29.7.0: + dependencies: + '@jest/environment': 29.7.0 + '@jest/fake-timers': 29.7.0 + '@jest/globals': 29.7.0 + '@jest/source-map': 29.6.3 + '@jest/test-result': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + chalk: 4.1.2 + cjs-module-lexer: 1.4.3 + collect-v8-coverage: 1.0.3 + glob: 7.2.3 + graceful-fs: 4.2.11 + jest-haste-map: 29.7.0 + jest-message-util: 29.7.0 + jest-mock: 29.7.0 + jest-regex-util: 29.6.3 + jest-resolve: 29.7.0 + jest-snapshot: 29.7.0 + jest-util: 29.7.0 + slash: 3.0.0 + strip-bom: 4.0.0 + transitivePeerDependencies: + - supports-color + + jest-snapshot@29.7.0: + dependencies: + '@babel/core': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/plugin-syntax-jsx': 7.29.7(@babel/core@7.29.7) + '@babel/plugin-syntax-typescript': 7.29.7(@babel/core@7.29.7) + '@babel/types': 7.29.8 + '@jest/expect-utils': 29.7.0 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) + chalk: 4.1.2 + expect: 29.7.0 + graceful-fs: 4.2.11 + jest-diff: 29.7.0 + jest-get-type: 29.6.3 + jest-matcher-utils: 29.7.0 + jest-message-util: 29.7.0 + jest-util: 29.7.0 + natural-compare: 1.4.0 + pretty-format: 29.7.0 + semver: 7.8.0 + transitivePeerDependencies: + - supports-color - ignore@7.0.5: {} + jest-util@29.7.0: + dependencies: + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + chalk: 4.1.2 + ci-info: 3.9.0 + graceful-fs: 4.2.11 + picomatch: 2.3.2 - import-fresh@3.3.1: + jest-validate@29.7.0: dependencies: - parent-module: 1.0.1 - resolve-from: 4.0.0 + '@jest/types': 29.6.3 + camelcase: 6.3.0 + chalk: 4.1.2 + jest-get-type: 29.6.3 + leven: 3.1.0 + pretty-format: 29.7.0 - imurmurhash@0.1.4: {} + jest-watcher@29.7.0: + dependencies: + '@jest/test-result': 29.7.0 + '@jest/types': 29.6.3 + '@types/node': 20.19.43 + ansi-escapes: 4.3.2 + chalk: 4.1.2 + emittery: 0.13.1 + jest-util: 29.7.0 + string-length: 4.0.2 - is-extglob@2.1.1: {} + jest-worker@29.7.0: + dependencies: + '@types/node': 20.19.43 + jest-util: 29.7.0 + merge-stream: 2.0.0 + supports-color: 8.1.1 - is-glob@4.0.3: + jest@29.7.0(@types/node@20.19.43): dependencies: - is-extglob: 2.1.1 + '@jest/core': 29.7.0 + '@jest/types': 29.6.3 + import-local: 3.2.0 + jest-cli: 29.7.0(@types/node@20.19.43) + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node - isexe@2.0.0: {} + jest@29.7.0(@types/node@22.20.4): + dependencies: + '@jest/core': 29.7.0 + '@jest/types': 29.6.3 + import-local: 3.2.0 + jest-cli: 29.7.0(@types/node@22.20.4) + transitivePeerDependencies: + - '@types/node' + - babel-plugin-macros + - supports-color + - ts-node jiti@1.21.7: optional: true + js-tokens@4.0.0: {} + + js-yaml@3.15.2: + dependencies: + argparse: 1.0.10 + esprima: 4.0.1 + js-yaml@4.1.1: dependencies: argparse: 2.0.1 + jsesc@3.1.0: {} + json-buffer@3.0.1: {} + json-parse-even-better-errors@2.3.1: {} + json-schema-traverse@0.4.1: {} json-stable-stringify-without-jsonify@1.0.1: {} + json5@2.2.3: {} + + keytar@7.9.0: + dependencies: + node-addon-api: 4.3.0 + prebuild-install: 7.1.3 + optional: true + keyv@4.5.4: dependencies: json-buffer: 3.0.1 + kleur@3.0.3: {} + + leven@3.1.0: {} + levn@0.4.1: dependencies: prelude-ls: 1.2.1 type-check: 0.4.0 + lines-and-columns@1.2.4: {} + + locate-path@5.0.0: + dependencies: + p-locate: 4.1.0 + locate-path@6.0.0: dependencies: p-locate: 5.0.0 + lodash.memoize@4.1.2: {} + lodash.merge@4.6.2: {} + loupe@3.2.1: {} + + lru-cache@5.1.1: + dependencies: + yallist: 3.1.1 + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + make-dir@4.0.0: + dependencies: + semver: 7.8.0 + + make-error@1.3.6: {} + + makeerror@1.0.12: + dependencies: + tmpl: 1.0.5 + + merge-stream@2.0.0: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mimic-fn@2.1.0: {} + + mimic-response@3.1.0: + optional: true + minimatch@10.2.5: dependencies: brace-expansion: 5.0.6 @@ -925,10 +4585,48 @@ snapshots: dependencies: brace-expansion: 1.1.14 + minimist@1.2.8: {} + + mkdirp-classic@0.5.3: + optional: true + ms@2.1.3: {} + nanoid@3.3.19: {} + + napi-build-utils@2.0.0: + optional: true + natural-compare@1.4.0: {} + neo-async@2.6.2: {} + + node-abi@3.96.0: + dependencies: + semver: 7.8.0 + optional: true + + node-addon-api@4.3.0: + optional: true + + node-int64@0.4.0: {} + + node-releases@2.0.56: {} + + normalize-path@3.0.0: {} + + npm-run-path@4.0.1: + dependencies: + path-key: 3.1.1 + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + onetime@5.1.2: + dependencies: + mimic-fn: 2.1.0 + optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -938,53 +4636,356 @@ snapshots: type-check: 0.4.0 word-wrap: 1.2.5 + p-limit@2.3.0: + dependencies: + p-try: 2.2.0 + p-limit@3.1.0: dependencies: yocto-queue: 0.1.0 + p-locate@4.1.0: + dependencies: + p-limit: 2.3.0 + p-locate@5.0.0: dependencies: p-limit: 3.1.0 + p-try@2.2.0: {} + parent-module@1.0.1: dependencies: callsites: 3.1.0 + parse-json@5.2.0: + dependencies: + '@babel/code-frame': 7.29.7 + error-ex: 1.3.4 + json-parse-even-better-errors: 2.3.1 + lines-and-columns: 1.2.4 + path-exists@4.0.0: {} + path-is-absolute@1.0.1: {} + path-key@3.1.1: {} + path-parse@1.0.7: {} + + pathe@1.1.2: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + picomatch@4.0.4: {} + pirates@4.0.7: {} + + pkg-dir@4.2.0: + dependencies: + find-up: 4.1.0 + + postcss@8.5.28: + dependencies: + nanoid: 3.3.19 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.96.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.5 + tunnel-agent: 0.6.0 + optional: true + prelude-ls@1.2.1: {} + pretty-format@29.7.0: + dependencies: + '@jest/schemas': 29.6.3 + ansi-styles: 5.2.0 + react-is: 18.3.1 + + prompts@2.4.2: + dependencies: + kleur: 3.0.3 + sisteransi: 1.0.5 + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + optional: true + punycode@2.3.1: {} + pure-rand@6.1.0: {} + + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + optional: true + + react-is@18.3.1: {} + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + optional: true + + require-directory@2.1.1: {} + + resolve-cwd@3.0.0: + dependencies: + resolve-from: 5.0.0 + resolve-from@4.0.0: {} + resolve-from@5.0.0: {} + + resolve.exports@2.0.3: {} + + resolve@1.22.12: + dependencies: + es-errors: 1.3.0 + is-core-module: 2.17.0 + path-parse: 1.0.7 + supports-preserve-symlinks-flag: 1.0.0 + + rollup@4.63.4: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.63.4 + '@rollup/rollup-android-arm64': 4.63.4 + '@rollup/rollup-darwin-arm64': 4.63.4 + '@rollup/rollup-darwin-x64': 4.63.4 + '@rollup/rollup-freebsd-arm64': 4.63.4 + '@rollup/rollup-freebsd-x64': 4.63.4 + '@rollup/rollup-linux-arm-gnueabihf': 4.63.4 + '@rollup/rollup-linux-arm-musleabihf': 4.63.4 + '@rollup/rollup-linux-arm64-gnu': 4.63.4 + '@rollup/rollup-linux-arm64-musl': 4.63.4 + '@rollup/rollup-linux-loong64-gnu': 4.63.4 + '@rollup/rollup-linux-loong64-musl': 4.63.4 + '@rollup/rollup-linux-ppc64-gnu': 4.63.4 + '@rollup/rollup-linux-ppc64-musl': 4.63.4 + '@rollup/rollup-linux-riscv64-gnu': 4.63.4 + '@rollup/rollup-linux-riscv64-musl': 4.63.4 + '@rollup/rollup-linux-s390x-gnu': 4.63.4 + '@rollup/rollup-linux-x64-gnu': 4.63.4 + '@rollup/rollup-linux-x64-musl': 4.63.4 + '@rollup/rollup-openbsd-x64': 4.63.4 + '@rollup/rollup-openharmony-arm64': 4.63.4 + '@rollup/rollup-win32-arm64-msvc': 4.63.4 + '@rollup/rollup-win32-ia32-msvc': 4.63.4 + '@rollup/rollup-win32-x64-gnu': 4.63.4 + '@rollup/rollup-win32-x64-msvc': 4.63.4 + fsevents: 2.3.3 + + safe-buffer@5.2.1: + optional: true + + semver@6.3.1: {} + semver@7.8.0: {} + semver@7.8.5: {} + shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 shebang-regex@3.0.0: {} + siginfo@2.0.0: {} + + signal-exit@3.0.7: {} + + simple-concat@1.0.1: + optional: true + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + optional: true + + sisteransi@1.0.5: {} + + slash@3.0.0: {} + + source-map-js@1.2.1: {} + + source-map-support@0.5.13: + dependencies: + buffer-from: 1.1.2 + source-map: 0.6.1 + + source-map@0.6.1: {} + + sprintf-js@1.0.3: {} + + stack-utils@2.0.6: + dependencies: + escape-string-regexp: 2.0.0 + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + string-length@4.0.2: + dependencies: + char-regex: 1.0.2 + strip-ansi: 6.0.1 + + string-width@4.2.3: + dependencies: + emoji-regex: 8.0.0 + is-fullwidth-code-point: 3.0.0 + strip-ansi: 6.0.1 + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + optional: true + + strip-ansi@6.0.1: + dependencies: + ansi-regex: 5.0.1 + + strip-bom@4.0.0: {} + + strip-final-newline@2.0.0: {} + + strip-json-comments@2.0.1: + optional: true + strip-json-comments@3.1.1: {} supports-color@7.2.0: dependencies: has-flag: 4.0.0 + supports-color@8.1.1: + dependencies: + has-flag: 4.0.0 + + supports-preserve-symlinks-flag@1.0.0: {} + + tar-fs@2.1.5: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + optional: true + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + optional: true + + test-exclude@6.0.0: + dependencies: + '@istanbuljs/schema': 0.1.6 + glob: 7.2.3 + minimatch: 3.1.5 + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + tinyglobby@0.2.16: dependencies: fdir: 6.5.0(picomatch@4.0.4) picomatch: 4.0.4 + tinypool@1.1.1: {} + + tinyrainbow@1.2.0: {} + + tinyspy@3.0.2: {} + + tmpl@1.0.5: {} + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + ts-api-utils@2.5.0(typescript@5.9.3): dependencies: typescript: 5.9.3 + ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@20.19.43))(typescript@5.9.3): + dependencies: + bs-logger: 0.2.6 + fast-json-stable-stringify: 2.1.0 + handlebars: 4.7.9 + jest: 29.7.0(@types/node@20.19.43) + json5: 2.2.3 + lodash.memoize: 4.1.2 + make-error: 1.3.6 + semver: 7.8.5 + type-fest: 4.41.0 + typescript: 5.9.3 + yargs-parser: 21.1.1 + optionalDependencies: + '@babel/core': 7.29.7 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + babel-jest: 29.7.0(@babel/core@7.29.7) + jest-util: 29.7.0 + + ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.20.4))(typescript@5.9.3): + dependencies: + bs-logger: 0.2.6 + fast-json-stable-stringify: 2.1.0 + handlebars: 4.7.9 + jest: 29.7.0(@types/node@22.20.4) + json5: 2.2.3 + lodash.memoize: 4.1.2 + make-error: 1.3.6 + semver: 7.8.5 + type-fest: 4.41.0 + typescript: 5.9.3 + yargs-parser: 21.1.1 + optionalDependencies: + '@babel/core': 7.29.7 + '@jest/transform': 29.7.0 + '@jest/types': 29.6.3 + babel-jest: 29.7.0(@babel/core@7.29.7) + jest-util: 29.7.0 + + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + optional: true + turbo@2.9.12: optionalDependencies: '@turbo/darwin-64': 2.9.12 @@ -998,16 +4999,206 @@ snapshots: dependencies: prelude-ls: 1.2.1 + type-detect@4.0.8: {} + + type-fest@0.21.3: {} + + type-fest@4.41.0: {} + typescript@5.9.3: {} + uglify-js@3.19.3: + optional: true + + undici-types@6.21.0: {} + + update-browserslist-db@1.3.3(browserslist@4.29.0): + dependencies: + browserslist: 4.29.0 + escalade: 3.2.0 + picocolors: 1.1.1 + uri-js@4.4.1: dependencies: punycode: 2.3.1 + util-deprecate@1.0.2: + optional: true + + v8-to-istanbul@9.3.0: + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@types/istanbul-lib-coverage': 2.0.6 + convert-source-map: 2.0.0 + + vite-node@2.1.9(@types/node@20.19.43): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 1.1.2 + vite: 5.4.21(@types/node@20.19.43) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite-node@2.1.9(@types/node@22.20.4): + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 1.1.2 + vite: 5.4.21(@types/node@22.20.4) + transitivePeerDependencies: + - '@types/node' + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vite@5.4.21(@types/node@20.19.43): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.28 + rollup: 4.63.4 + optionalDependencies: + '@types/node': 20.19.43 + fsevents: 2.3.3 + + vite@5.4.21(@types/node@22.20.4): + dependencies: + esbuild: 0.21.5 + postcss: 8.5.28 + rollup: 4.63.4 + optionalDependencies: + '@types/node': 22.20.4 + fsevents: 2.3.3 + + vitest@2.1.9(@types/node@20.19.43): + dependencies: + '@vitest/expect': 2.1.9 + '@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@20.19.43)) + '@vitest/pretty-format': 2.1.9 + '@vitest/runner': 2.1.9 + '@vitest/snapshot': 2.1.9 + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 1.1.2 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinypool: 1.1.1 + tinyrainbow: 1.2.0 + vite: 5.4.21(@types/node@20.19.43) + vite-node: 2.1.9(@types/node@20.19.43) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 20.19.43 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + vitest@2.1.9(@types/node@22.20.4): + dependencies: + '@vitest/expect': 2.1.9 + '@vitest/mocker': 2.1.9(vite@5.4.21(@types/node@22.20.4)) + '@vitest/pretty-format': 2.1.9 + '@vitest/runner': 2.1.9 + '@vitest/snapshot': 2.1.9 + '@vitest/spy': 2.1.9 + '@vitest/utils': 2.1.9 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.4.0 + magic-string: 0.30.21 + pathe: 1.1.2 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinypool: 1.1.1 + tinyrainbow: 1.2.0 + vite: 5.4.21(@types/node@22.20.4) + vite-node: 2.1.9(@types/node@22.20.4) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 22.20.4 + transitivePeerDependencies: + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + + walker@1.0.8: + dependencies: + makeerror: 1.0.12 + which@2.0.2: dependencies: isexe: 2.0.0 + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + word-wrap@1.2.5: {} + wordwrap@1.0.0: {} + + wrap-ansi@7.0.0: + dependencies: + ansi-styles: 4.3.0 + string-width: 4.2.3 + strip-ansi: 6.0.1 + + wrappy@1.0.2: {} + + write-file-atomic@4.0.2: + dependencies: + imurmurhash: 0.1.4 + signal-exit: 3.0.7 + + y18n@5.0.8: {} + + yallist@3.1.1: {} + + yargs-parser@21.1.1: {} + + yargs@17.7.3: + dependencies: + cliui: 8.0.1 + escalade: 3.2.0 + get-caller-file: 2.0.5 + require-directory: 2.1.1 + string-width: 4.2.3 + y18n: 5.0.8 + yargs-parser: 21.1.1 + yocto-queue@0.1.0: {} diff --git a/tests/contracts/component.yaml b/tests/contracts/component.yaml new file mode 100644 index 0000000..e8c81ea --- /dev/null +++ b/tests/contracts/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: contracts-tests +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/tests/contracts/docs/architecture.md b/tests/contracts/docs/architecture.md new file mode 100644 index 0000000..93c241e --- /dev/null +++ b/tests/contracts/docs/architecture.md @@ -0,0 +1,9 @@ +# contracts-tests — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `tests/contracts`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/tests/contracts/docs/overview.md b/tests/contracts/docs/overview.md new file mode 100644 index 0000000..8e5f861 --- /dev/null +++ b/tests/contracts/docs/overview.md @@ -0,0 +1,13 @@ +# contracts-tests + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/contracts/docs/runbook.md b/tests/contracts/docs/runbook.md new file mode 100644 index 0000000..b04374f --- /dev/null +++ b/tests/contracts/docs/runbook.md @@ -0,0 +1,26 @@ +# contracts-tests — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/tests/contracts/eslint.config.js b/tests/contracts/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/contracts/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/contracts/package.json b/tests/contracts/package.json new file mode 100644 index 0000000..6e50923 --- /dev/null +++ b/tests/contracts/package.json @@ -0,0 +1,39 @@ +{ + "name": "@saas/contracts-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/jest": "^29.5.14", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*", + "@saas/testing": "workspace:*" + }, + "jest": { + "preset": "ts-jest/presets/default-esm", + "extensionsToTreatAsEsm": [".ts"], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1", + "^@saas/contracts$": "/../../packages/contracts/src/index.ts", + "^@saas/contracts/(.*)$": "/../../packages/contracts/src/$1.ts", + "^@saas/testing$": "/../../packages/testing/src/index.ts", + "^@saas/testing/(.*)$": "/../../packages/testing/src/$1.ts" + }, + "transform": { + "^.+\\.ts$": ["ts-jest", { "useESM": true }] + }, + "testMatch": ["/src/**/*.test.ts"] + } +} diff --git a/tests/contracts/src/billing.test.ts b/tests/contracts/src/billing.test.ts new file mode 100644 index 0000000..cc41113 --- /dev/null +++ b/tests/contracts/src/billing.test.ts @@ -0,0 +1,351 @@ +import type { + PublicPlan, + PublicBillingCustomer, + PublicSubscription, + PublicInvoice, + PublicEntitlement, + ListPlansRequest, + ListPlansResponse, + GetBillingCustomerResponse, + ListInvoicesRequest, + ListInvoicesResponse, + GetEntitlementsRequest, + GetEntitlementsResponse, + GetBillingSummaryResponse, + CheckBillingEntitlementRequest, + CheckBillingEntitlementResponse, + BillingEntitlementAllowedDecision, + BillingEntitlementDeniedDecision, + BillingEntitlementDeniedReason, +} from "@saas/contracts/billing"; + +describe("contracts: billing — Plan shape", () => { + it("PublicPlan has the expected fields and types", () => { + const p: PublicPlan = { + id: "plan_1", + code: "starter", + name: "Starter", + description: null, + status: "active", + billingInterval: "month", + priceAmountCents: 0, + priceCurrency: "usd", + metadata: null, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }; + expect(p.code).toBe("starter"); + expect(p.status).toBe("active"); + }); + + it("supports archived status and yearly/none intervals", () => { + const yearly: PublicPlan = { + id: "p", + code: "annual", + name: "Annual", + description: null, + status: "archived", + billingInterval: "year", + priceAmountCents: 99900, + priceCurrency: "eur", + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(yearly.billingInterval).toBe("year"); + }); + + it("ListPlansRequest accepts optional status; response wraps a list", () => { + const req: ListPlansRequest = { status: "active" }; + const res: ListPlansResponse = { plans: [] }; + expect(req.status).toBe("active"); + expect(res.plans).toEqual([]); + }); +}); + +describe("contracts: billing — Customer shape", () => { + it("PublicBillingCustomer has org_id-keyed identity and no secret fields", () => { + const c: PublicBillingCustomer = { + id: "bc_1", + orgId: "org_1", + displayName: "Acme", + email: "billing@acme.example", + status: "active", + provider: "stripe", + providerCustomerId: "cus_abc", + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(c.orgId).toBe("org_1"); + // Forbidden secret-bearing keys must not exist on the type + const forbidden = ["apiKey", "secret", "token", "providerApiKey"]; + for (const k of forbidden) { + expect(Object.prototype.hasOwnProperty.call(c, k)).toBe(false); + } + }); + + it("GetBillingCustomerResponse wraps a customer", () => { + const r: GetBillingCustomerResponse = { + customer: { + id: "bc_1", + orgId: "org_1", + displayName: null, + email: null, + status: "active", + provider: null, + providerCustomerId: null, + metadata: null, + createdAt: "x", + updatedAt: "x", + }, + }; + expect(r.customer.orgId).toBe("org_1"); + }); +}); + +describe("contracts: billing — Subscription shape", () => { + it("PublicSubscription includes all status values", () => { + const statuses: PublicSubscription["status"][] = [ + "trialing", + "active", + "past_due", + "canceled", + "expired", + ]; + expect(statuses).toContain("active"); + }); + + it("PublicSubscription has provider-neutral opaque ids", () => { + const s: PublicSubscription = { + id: "sub_1", + orgId: "org_1", + billingCustomerId: "bc_1", + planId: "plan_1", + status: "active", + currentPeriodStart: "2026-01-01T00:00:00.000Z", + currentPeriodEnd: "2026-02-01T00:00:00.000Z", + trialEnd: null, + cancelAt: null, + canceledAt: null, + provider: null, + providerSubscriptionId: null, + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(s.orgId).toBe("org_1"); + expect(s.status).toBe("active"); + }); +}); + +describe("contracts: billing — Invoice shape", () => { + it("PublicInvoice exposes safe display URL and never secret fields", () => { + const i: PublicInvoice = { + id: "inv_1", + orgId: "org_1", + billingCustomerId: "bc_1", + subscriptionId: "sub_1", + number: "INV-0001", + status: "open", + amountDueCents: 1000, + amountPaidCents: 0, + currency: "usd", + issuedAt: "2026-01-15T00:00:00.000Z", + dueAt: "2026-02-01T00:00:00.000Z", + paidAt: null, + periodStart: "2026-01-01T00:00:00.000Z", + periodEnd: "2026-02-01T00:00:00.000Z", + provider: "stripe", + providerInvoiceId: "in_abc", + hostedUrl: "https://invoice.stripe.com/i/abc/safe", + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(i.hostedUrl).toContain("https://"); + const forbidden = [ + "providerPayload", + "rawPayload", + "secret", + "apiKey", + "checkoutSessionSecret", + "cardNumber", + "cvc", + ]; + for (const k of forbidden) { + expect(Object.prototype.hasOwnProperty.call(i, k)).toBe(false); + } + }); + + it("ListInvoicesRequest/Response support cursor pagination", () => { + const req: ListInvoicesRequest = { + subscriptionId: "sub_1", + status: "open", + limit: 25, + cursor: { createdAt: "x", id: "y" }, + }; + const res: ListInvoicesResponse = { + invoices: [], + nextCursor: null, + }; + expect(req.limit).toBe(25); + expect(res.invoices).toEqual([]); + }); +}); + +describe("contracts: billing — Entitlement shape", () => { + it("PublicEntitlement supports boolean/quantity/feature value types", () => { + const e: PublicEntitlement = { + id: "ent_1", + orgId: "org_1", + subscriptionId: null, + entitlementKey: "feature.custom_domains", + valueType: "boolean", + enabled: true, + limitValue: null, + source: "plan", + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(e.entitlementKey).toBe("feature.custom_domains"); + expect(e.source).toBe("plan"); + }); + + it("PublicEntitlement allows numeric limit for quantity types", () => { + const e: PublicEntitlement = { + id: "ent_2", + orgId: "org_1", + subscriptionId: "sub_1", + entitlementKey: "limit.projects", + valueType: "quantity", + enabled: true, + limitValue: 10, + source: "override", + metadata: null, + createdAt: "x", + updatedAt: "x", + }; + expect(e.valueType).toBe("quantity"); + expect(e.limitValue).toBe(10); + }); + + it("GetEntitlementsRequest accepts optional filters; response wraps a list", () => { + const req: GetEntitlementsRequest = { source: "plan" }; + const res: GetEntitlementsResponse = { entitlements: [] }; + expect(req.source).toBe("plan"); + expect(res.entitlements).toEqual([]); + }); +}); + +describe("contracts: billing — Summary shape", () => { + it("GetBillingSummaryResponse composes customer/sub/plan/entitlements", () => { + const r: GetBillingSummaryResponse = { + customer: null, + activeSubscription: null, + plan: null, + entitlements: [], + }; + expect(r.entitlements).toEqual([]); + }); +}); + +describe("contracts: billing — secret-safe surface (type-level)", () => { + it("PublicBillingCustomer compiles without secret-bearing fields", () => { + // This file fails to compile if any of the Public* types include + // apiKey / secret / token / providerPayload / cardNumber / cvc / + // bearerToken / checkoutSessionSecret. The assertions in the suites + // above already exercise the runtime shape; this test just documents + // the invariant. + expect(true).toBe(true); + }); +}); + +describe("contracts: billing — Entitlement decision (internal seam)", () => { + it("CheckBillingEntitlementRequest only carries orgId + entitlementKey", () => { + const req: CheckBillingEntitlementRequest = { + orgId: "org_11111111111111111111111111111111", + entitlementKey: "feature.custom_domains", + }; + expect(req.orgId).toMatch(/^org_/); + expect(req.entitlementKey).toBe("feature.custom_domains"); + const forbidden = [ + "apiKey", + "secret", + "token", + "providerCustomerId", + "providerSubscriptionId", + "providerPayload", + "sql", + "metadata", + ]; + for (const k of forbidden) { + expect(Object.prototype.hasOwnProperty.call(req, k)).toBe(false); + } + }); + + it("BillingEntitlementAllowedDecision shape carries safe entitlement details only", () => { + const allowed: BillingEntitlementAllowedDecision = { + allowed: true, + orgId: "org_1", + entitlementKey: "feature.custom_domains", + valueType: "boolean", + limitValue: null, + source: "plan", + subscriptionId: null, + }; + expect(allowed.allowed).toBe(true); + expect(allowed.source).toBe("plan"); + const forbidden = [ + "apiKey", + "secret", + "token", + "providerPayload", + "rawPayload", + "sql", + "stack", + "stackTrace", + "metadata", + "providerSubscriptionId", + ]; + for (const k of forbidden) { + expect(Object.prototype.hasOwnProperty.call(allowed, k)).toBe(false); + } + }); + + it("BillingEntitlementDeniedDecision uses a narrow reason set", () => { + const reasons: BillingEntitlementDeniedReason[] = ["disabled", "not_configured"]; + expect(reasons).toEqual(["disabled", "not_configured"]); + const denied: BillingEntitlementDeniedDecision = { + allowed: false, + orgId: "org_1", + entitlementKey: "feature.custom_domains", + reason: "not_configured", + }; + expect(denied.allowed).toBe(false); + expect(denied.reason).toBe("not_configured"); + }); + + it("CheckBillingEntitlementResponse discriminates on `allowed`", () => { + const responses: CheckBillingEntitlementResponse[] = [ + { + allowed: true, + orgId: "org_1", + entitlementKey: "limit.projects", + valueType: "quantity", + limitValue: 10, + source: "override", + subscriptionId: "sub_1", + }, + { + allowed: false, + orgId: "org_1", + entitlementKey: "limit.projects", + reason: "disabled", + }, + ]; + const allowedCount = responses.filter((r) => r.allowed).length; + expect(allowedCount).toBe(1); + }); +}); diff --git a/tests/contracts/src/contracts.test.ts b/tests/contracts/src/contracts.test.ts new file mode 100644 index 0000000..bc1049a --- /dev/null +++ b/tests/contracts/src/contracts.test.ts @@ -0,0 +1,74 @@ +import { + HEALTH_STATUS, + ERROR_CODES, + type ErrorResponse, + type TenantContext, +} from "@saas/contracts"; +import { makeTenantContext, makeHealthResponse } from "@saas/testing/fixtures"; + +describe("contracts: health types", () => { + it("exports HEALTH_STATUS constants", () => { + expect(HEALTH_STATUS.OK).toBe("ok"); + expect(HEALTH_STATUS.DEGRADED).toBe("degraded"); + expect(HEALTH_STATUS.DOWN).toBe("down"); + }); + + it("makeHealthResponse returns a valid HealthResponse shape", () => { + const r = makeHealthResponse(); + expect(r.status).toBe("ok"); + expect(typeof r.service).toBe("string"); + expect(typeof r.timestamp).toBe("string"); + }); + + it("makeHealthResponse accepts overrides", () => { + const r = makeHealthResponse({ status: "degraded", service: "api-edge" }); + expect(r.status).toBe("degraded"); + expect(r.service).toBe("api-edge"); + }); +}); + +describe("contracts: error types", () => { + it("exports ERROR_CODES constants", () => { + expect(ERROR_CODES.BAD_REQUEST).toBe("bad_request"); + expect(ERROR_CODES.UNAUTHENTICATED).toBe("unauthenticated"); + expect(ERROR_CODES.FORBIDDEN).toBe("forbidden"); + expect(ERROR_CODES.NOT_FOUND).toBe("not_found"); + expect(ERROR_CODES.CONFLICT).toBe("conflict"); + expect(ERROR_CODES.RATE_LIMITED).toBe("rate_limited"); + expect(ERROR_CODES.VALIDATION_FAILED).toBe("validation_failed"); + expect(ERROR_CODES.PRECONDITION_FAILED).toBe("precondition_failed"); + expect(ERROR_CODES.UNSUPPORTED).toBe("unsupported"); + expect(ERROR_CODES.INTERNAL_ERROR).toBe("internal_error"); + }); + + it("ErrorResponse shape is structurally correct", () => { + const e: ErrorResponse = { + error: "not_found", + message: "Resource not found", + }; + expect(e.error).toBe("not_found"); + }); +}); + +describe("contracts: tenancy types", () => { + it("makeTenantContext returns a valid TenantContext", () => { + const ctx = makeTenantContext(); + expect(ctx.orgId).toBe("org_test"); + expect(ctx.actorKind).toBe("user"); + }); + + it("makeTenantContext accepts partial overrides", () => { + const ctx = makeTenantContext({ orgId: "org_acme", projectId: "proj_1" }); + expect(ctx.orgId).toBe("org_acme"); + expect(ctx.projectId).toBe("proj_1"); + }); + + it("TenantContext shape includes actorId", () => { + const ctx: TenantContext = { + orgId: "org_x", + actorId: "svc_deployer", + actorKind: "service_principal", + }; + expect(ctx.actorKind).toBe("service_principal"); + }); +}); diff --git a/tests/contracts/src/events.test.ts b/tests/contracts/src/events.test.ts new file mode 100644 index 0000000..f7b80ab --- /dev/null +++ b/tests/contracts/src/events.test.ts @@ -0,0 +1,239 @@ +import type { + EventEnvelope, + EventActor, + EventTenant, + EventSubject, + EventTrace, + EventAuditMeta, + AuditEntry, + AuditQueryByOrg, + AuditQueryByTarget, + PublicAuditEntry, + ListAuditEntriesResponse, +} from "@saas/contracts"; + +describe("contracts: event envelope types", () => { + it("EventEnvelope shape matches the schema", () => { + const envelope: EventEnvelope = { + id: "evt_01hxyz", + type: "project.created", + version: 1, + source: "projects-worker", + occurredAt: "2026-04-22T12:00:00Z", + actor: { + type: "user", + id: "usr_123", + sessionId: "ses_123", + ip: "203.0.113.10", + }, + tenant: { + orgId: "org_123", + projectId: "prj_123", + environmentId: null, + }, + subject: { + kind: "project", + id: "prj_123", + name: "Acme API", + }, + trace: { + requestId: "req_123", + correlationId: "cor_123", + causationId: null, + idempotencyKey: "idem_123", + }, + payload: { projectId: "prj_123", name: "Acme API" }, + }; + + expect(envelope.id).toBe("evt_01hxyz"); + expect(envelope.type).toBe("project.created"); + expect(envelope.version).toBe(1); + expect(envelope.actor.type).toBe("user"); + expect(envelope.tenant.orgId).toBe("org_123"); + expect(envelope.subject.kind).toBe("project"); + expect(envelope.trace.requestId).toBe("req_123"); + expect(envelope.payload).toBeDefined(); + }); + + it("EventEnvelope supports optional audit redaction metadata", () => { + const envelope: EventEnvelope = { + id: "evt_02", + type: "member.invited", + version: 1, + source: "membership-worker", + occurredAt: "2026-04-22T12:00:00Z", + actor: { type: "system", id: "sys" }, + tenant: { orgId: "org_1" }, + subject: { kind: "invitation", id: "inv_1" }, + trace: { requestId: "req_2" }, + payload: { email: "test@example.com" }, + audit: { redact: ["$.payload.email"] }, + }; + + expect(envelope.audit?.redact).toEqual(["$.payload.email"]); + }); + + it("EventActor supports all actor types", () => { + const actors: EventActor[] = [ + { type: "user", id: "u1" }, + { type: "service_principal", id: "sp1" }, + { type: "workflow", id: "wf1" }, + { type: "system", id: "sys" }, + ]; + expect(actors).toHaveLength(4); + }); + + it("EventTenant requires orgId, optional projectId/environmentId", () => { + const tenant: EventTenant = { orgId: "org_1" }; + expect(tenant.orgId).toBe("org_1"); + expect(tenant.projectId).toBeUndefined(); + + const full: EventTenant = { orgId: "org_2", projectId: "prj_1", environmentId: "env_1" }; + expect(full.projectId).toBe("prj_1"); + }); + + it("EventSubject requires kind and id, optional name", () => { + const s: EventSubject = { kind: "project", id: "prj_1" }; + expect(s.name).toBeUndefined(); + }); + + it("EventTrace requires requestId, optional correlation/causation/idempotency", () => { + const t: EventTrace = { requestId: "req_1" }; + expect(t.correlationId).toBeUndefined(); + }); + + it("EventAuditMeta redact is optional array of strings", () => { + const meta: EventAuditMeta = { redact: ["$.a", "$.b"] }; + expect(meta.redact).toHaveLength(2); + }); +}); + +describe("contracts: audit entry types", () => { + it("AuditEntry shape is structurally correct", () => { + const entry: AuditEntry = { + id: "aud_1", + eventId: "evt_1", + orgId: "org_1", + projectId: null, + environmentId: null, + actorType: "user", + actorId: "usr_1", + eventType: "organization.created", + eventVersion: 1, + source: "membership-worker", + subjectKind: "organization", + subjectId: "org_1", + subjectName: "Acme", + category: "general", + description: "Organization created", + occurredAt: "2026-01-15T10:00:00Z", + requestId: "req_1", + correlationId: null, + payload: {}, + redactPaths: [], + }; + + expect(entry.orgId).toBe("org_1"); + expect(entry.eventId).toBe("evt_1"); + expect(entry.redactPaths).toEqual([]); + }); +}); + +describe("contracts: audit query filter types", () => { + it("AuditQueryByOrg is structurally valid", () => { + const q: AuditQueryByOrg = { orgId: "org_1", limit: 20 }; + expect(q.orgId).toBe("org_1"); + expect(q.cursor).toBeUndefined(); + }); + + it("AuditQueryByTarget includes subject kind/id", () => { + const q: AuditQueryByTarget = { + orgId: "org_1", + subjectKind: "project", + subjectId: "prj_1", + limit: 10, + cursor: "cur_abc", + }; + expect(q.subjectKind).toBe("project"); + expect(q.cursor).toBe("cur_abc"); + }); +}); + +describe("contracts: public audit response types", () => { + it("PublicAuditEntry shape is structurally correct", () => { + const entry: PublicAuditEntry = { + id: "aud_1", + eventId: "evt_1", + orgId: "org_abc123", + projectId: "prj_def456", + environmentId: null, + actorType: "user", + actorId: "usr_1", + eventType: "project.created", + source: "projects-worker", + category: "projects", + description: "Project created", + subject: { + kind: "project", + id: "prj_def456", + name: "Acme API", + }, + occurredAt: "2026-05-26T10:00:00.000Z", + requestId: "req_1", + correlationId: null, + payload: { name: "Acme API" }, + }; + + expect(entry.orgId).toBe("org_abc123"); + expect(entry.subject.kind).toBe("project"); + expect(entry.subject.id).toBe("prj_def456"); + expect(entry.payload).toEqual({ name: "Acme API" }); + }); + + it("ListAuditEntriesResponse envelope shape", () => { + const response: ListAuditEntriesResponse = { + data: { + auditEntries: [], + }, + meta: { + requestId: "req_1", + cursor: null, + }, + }; + + expect(response.data.auditEntries).toEqual([]); + expect(response.meta.cursor).toBeNull(); + }); + + it("ListAuditEntriesResponse with cursor", () => { + const response: ListAuditEntriesResponse = { + data: { + auditEntries: [{ + id: "aud_1", + eventId: "evt_1", + orgId: "org_abc", + projectId: null, + environmentId: null, + actorType: "user", + actorId: "usr_1", + eventType: "organization.created", + source: "membership-worker", + category: "general", + description: "Org created", + subject: { kind: "organization", id: "org_abc", name: "Acme" }, + occurredAt: "2026-05-26T10:00:00.000Z", + requestId: "req_1", + correlationId: null, + payload: {}, + }], + }, + meta: { + requestId: "req_1", + cursor: "eyJ2IjoxLCJ0IjoiMjAyNi0wNS0yNiJ9", + }, + }; + + expect(response.data.auditEntries).toHaveLength(1); + expect(response.meta.cursor).not.toBeNull(); + }); +}); diff --git a/tests/contracts/src/idempotency.test.ts b/tests/contracts/src/idempotency.test.ts new file mode 100644 index 0000000..ad695ca --- /dev/null +++ b/tests/contracts/src/idempotency.test.ts @@ -0,0 +1,110 @@ +import { + IDEMPOTENCY_KEY_HEADER, + IDEMPOTENCY_KEY_MAX_LENGTH, + describeIdempotencyKeyParseError, + parseIdempotencyKey, +} from "@saas/contracts/idempotency"; + +describe("packages/contracts idempotency", () => { + describe("IDEMPOTENCY_KEY_HEADER", () => { + it("uses canonical Stripe-style spelling", () => { + expect(IDEMPOTENCY_KEY_HEADER).toBe("Idempotency-Key"); + }); + }); + + describe("parseIdempotencyKey", () => { + it("returns ok with key=null when value is null", () => { + expect(parseIdempotencyKey(null)).toEqual({ ok: true, key: null }); + }); + + it("returns ok with key=null when value is undefined", () => { + expect(parseIdempotencyKey(undefined)).toEqual({ ok: true, key: null }); + }); + + it("accepts a typical UUID-shaped key", () => { + const k = "550e8400-e29b-41d4-a716-446655440000"; + expect(parseIdempotencyKey(k)).toEqual({ ok: true, key: k }); + }); + + it("accepts ASCII printable special chars", () => { + const k = "client_retry:order#42/abc.xyz+~!@$%^&*()-_="; + expect(parseIdempotencyKey(k)).toEqual({ ok: true, key: k }); + }); + + it("trims surrounding whitespace and returns the trimmed key", () => { + expect(parseIdempotencyKey(" abc ")).toEqual({ ok: true, key: "abc" }); + }); + + it("accepts a 255-character key (boundary)", () => { + const k = "a".repeat(IDEMPOTENCY_KEY_MAX_LENGTH); + expect(parseIdempotencyKey(k)).toEqual({ ok: true, key: k }); + }); + + it("rejects empty string", () => { + expect(parseIdempotencyKey("")).toEqual({ ok: false, reason: "empty" }); + }); + + it("rejects whitespace-only string as empty", () => { + expect(parseIdempotencyKey(" \t ")).toEqual({ ok: false, reason: "empty" }); + }); + + it("rejects 256-character key as too_long", () => { + const k = "a".repeat(IDEMPOTENCY_KEY_MAX_LENGTH + 1); + expect(parseIdempotencyKey(k)).toEqual({ ok: false, reason: "too_long" }); + }); + + it("rejects newline (header injection vector)", () => { + expect(parseIdempotencyKey("abc\ndef")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + }); + + it("rejects carriage return", () => { + expect(parseIdempotencyKey("abc\rdef")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + }); + + it("rejects null byte", () => { + expect(parseIdempotencyKey("abc\u0000def")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + }); + + it("rejects non-ASCII characters", () => { + expect(parseIdempotencyKey("café")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + expect(parseIdempotencyKey("🔑")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + }); + + it("rejects DEL (0x7F) as illegal", () => { + expect(parseIdempotencyKey("abc\u007fdef")).toEqual({ + ok: false, + reason: "illegal_characters", + }); + }); + }); + + describe("describeIdempotencyKeyParseError", () => { + it("references the canonical header in every message", () => { + for (const reason of ["empty", "too_long", "illegal_characters", "wat"]) { + expect(describeIdempotencyKeyParseError(reason)).toContain( + IDEMPOTENCY_KEY_HEADER, + ); + } + }); + + it("mentions the length cap for too_long", () => { + const msg = describeIdempotencyKeyParseError("too_long"); + expect(msg).toContain(String(IDEMPOTENCY_KEY_MAX_LENGTH)); + }); + }); +}); diff --git a/tests/contracts/src/policy.test.ts b/tests/contracts/src/policy.test.ts new file mode 100644 index 0000000..0020557 --- /dev/null +++ b/tests/contracts/src/policy.test.ts @@ -0,0 +1,90 @@ +import type { + AuthorizationContextRequest, + AuthorizationContextResponse, + MembershipFact, + PolicySubject, +} from "@saas/contracts/policy"; +import { ORGANIZATION_ACTIONS } from "@saas/contracts/policy"; + +describe("contracts: authorization-context types", () => { + it("AuthorizationContextRequest accepts subject and orgId", () => { + const req: AuthorizationContextRequest = { + subject: { type: "user", id: "usr_abc123" }, + orgId: "org_001", + }; + expect(req.subject.type).toBe("user"); + expect(req.subject.id).toBe("usr_abc123"); + expect(req.orgId).toBe("org_001"); + }); + + it("AuthorizationContextRequest accepts service_principal subject type", () => { + const req: AuthorizationContextRequest = { + subject: { type: "service_principal", id: "svc_deploy" }, + orgId: "org_002", + }; + expect(req.subject.type).toBe("service_principal"); + }); + + it("AuthorizationContextResponse contains membership facts array", () => { + const res: AuthorizationContextResponse = { + memberships: [ + { + kind: "role_assignment", + role: "admin", + scope: { kind: "organization", orgId: "org_001" }, + }, + ], + }; + expect(res.memberships).toHaveLength(1); + expect(res.memberships[0]!.kind).toBe("role_assignment"); + expect(res.memberships[0]!.role).toBe("admin"); + expect(res.memberships[0]!.scope.kind).toBe("organization"); + }); + + it("AuthorizationContextResponse supports project-scoped facts", () => { + const fact: MembershipFact = { + kind: "role_assignment", + role: "project_builder", + scope: { kind: "project", orgId: "org_001", projectId: "prj_123" }, + }; + const res: AuthorizationContextResponse = { memberships: [fact] }; + expect(res.memberships[0]!.scope.projectId).toBe("prj_123"); + }); + + it("AuthorizationContextResponse supports empty memberships", () => { + const res: AuthorizationContextResponse = { memberships: [] }; + expect(res.memberships).toHaveLength(0); + }); + + it("PolicySubject type is structurally compatible with request subject", () => { + const subject: PolicySubject = { type: "workflow", id: "wf_run_1" }; + const req: AuthorizationContextRequest = { subject, orgId: "org_003" }; + expect(req.subject.type).toBe("workflow"); + }); +}); + +describe("contracts: ORGANIZATION_ACTIONS", () => { + it("includes project.list as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("project.list"); + }); + + it("includes project.read as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("project.read"); + }); + + it("includes environment.create as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("environment.create"); + }); + + it("includes environment.read as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("environment.read"); + }); + + it("includes environment.delete as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("environment.delete"); + }); + + it("includes audit.read as a known action", () => { + expect(ORGANIZATION_ACTIONS).toContain("audit.read"); + }); +}); diff --git a/tests/contracts/src/projects.test.ts b/tests/contracts/src/projects.test.ts new file mode 100644 index 0000000..ad697c8 --- /dev/null +++ b/tests/contracts/src/projects.test.ts @@ -0,0 +1,176 @@ +import type { + PublicProject, + CreateProjectRequest, + CreateProjectResponse, + GetProjectResponse, + ListProjectsResponse, + ArchiveProjectResponse, + PublicEnvironment, + CreateEnvironmentRequest, + CreateEnvironmentResponse, + GetEnvironmentResponse, + ListEnvironmentsResponse, + ArchiveEnvironmentResponse, +} from "@saas/contracts/projects"; + +describe("contracts: project types", () => { + it("PublicProject shape includes orgId and status fields", () => { + const project: PublicProject = { + id: "prj_001", + orgId: "org_001", + name: "My Project", + slug: "my-project", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }; + expect(project.orgId).toBe("org_001"); + expect(project.status).toBe("active"); + expect(project.archivedAt).toBeNull(); + }); + + it("CreateProjectRequest accepts name and optional slug", () => { + const req: CreateProjectRequest = { name: "New Project" }; + expect(req.name).toBe("New Project"); + expect(req.slug).toBeUndefined(); + + const reqWithSlug: CreateProjectRequest = { name: "Proj", slug: "proj" }; + expect(reqWithSlug.slug).toBe("proj"); + }); + + it("CreateProjectResponse wraps a PublicProject", () => { + const res: CreateProjectResponse = { + project: { + id: "prj_001", + orgId: "org_001", + name: "Test", + slug: "test", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }, + }; + expect(res.project.id).toBe("prj_001"); + }); + + it("GetProjectResponse wraps a PublicProject", () => { + const res: GetProjectResponse = { + project: { + id: "prj_001", + orgId: "org_001", + name: "Test", + slug: "test", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }, + }; + expect(res.project.orgId).toBe("org_001"); + }); + + it("ListProjectsResponse contains an array of PublicProject", () => { + const res: ListProjectsResponse = { projects: [] }; + expect(res.projects).toEqual([]); + }); + + it("ArchiveProjectResponse includes archivedAt timestamp", () => { + const res: ArchiveProjectResponse = { + project: { + id: "prj_001", + orgId: "org_001", + name: "Archived", + slug: "archived", + status: "archived", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-02-01T00:00:00Z", + archivedAt: "2026-02-01T00:00:00Z", + }, + }; + expect(res.project.status).toBe("archived"); + expect(res.project.archivedAt).toBe("2026-02-01T00:00:00Z"); + }); +}); + +describe("contracts: environment types", () => { + it("PublicEnvironment shape includes orgId and projectId", () => { + const env: PublicEnvironment = { + id: "env_001", + orgId: "org_001", + projectId: "prj_001", + name: "Production", + slug: "production", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }; + expect(env.orgId).toBe("org_001"); + expect(env.projectId).toBe("prj_001"); + }); + + it("CreateEnvironmentRequest accepts name and optional slug", () => { + const req: CreateEnvironmentRequest = { name: "Staging" }; + expect(req.name).toBe("Staging"); + expect(req.slug).toBeUndefined(); + }); + + it("CreateEnvironmentResponse wraps a PublicEnvironment", () => { + const res: CreateEnvironmentResponse = { + environment: { + id: "env_001", + orgId: "org_001", + projectId: "prj_001", + name: "Staging", + slug: "staging", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }, + }; + expect(res.environment.projectId).toBe("prj_001"); + }); + + it("GetEnvironmentResponse wraps a PublicEnvironment", () => { + const res: GetEnvironmentResponse = { + environment: { + id: "env_001", + orgId: "org_001", + projectId: "prj_001", + name: "Test", + slug: "test", + status: "active", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-01-01T00:00:00Z", + archivedAt: null, + }, + }; + expect(res.environment.orgId).toBe("org_001"); + }); + + it("ListEnvironmentsResponse contains an array of PublicEnvironment", () => { + const res: ListEnvironmentsResponse = { environments: [] }; + expect(res.environments).toEqual([]); + }); + + it("ArchiveEnvironmentResponse includes archivedAt timestamp", () => { + const res: ArchiveEnvironmentResponse = { + environment: { + id: "env_001", + orgId: "org_001", + projectId: "prj_001", + name: "Archived", + slug: "archived", + status: "archived", + createdAt: "2026-01-01T00:00:00Z", + updatedAt: "2026-02-01T00:00:00Z", + archivedAt: "2026-02-01T00:00:00Z", + }, + }; + expect(res.environment.status).toBe("archived"); + expect(res.environment.archivedAt).toBe("2026-02-01T00:00:00Z"); + }); +}); diff --git a/tests/contracts/src/timing.test.ts b/tests/contracts/src/timing.test.ts new file mode 100644 index 0000000..94d7617 --- /dev/null +++ b/tests/contracts/src/timing.test.ts @@ -0,0 +1,111 @@ +import { + createTimings, + parseServerTimingDuration, + appendServerTiming, + shouldEmitTimingLog, +} from "@saas/contracts/timing"; + +describe("contracts: timing (Server-Timing helper)", () => { + // Deterministic clock: each call advances by the queued deltas. + function fakeClock(values: number[]): () => number { + let i = 0; + return () => values[Math.min(i++, values.length - 1)]!; + } + + it("records a phase via start()/end and renders a Server-Timing header", () => { + const t = createTimings(fakeClock([100, 145])); + const end = t.start("db"); + end(); + expect(t.header()).toBe("db;dur=45"); + expect(t.toJSON()).toEqual({ db: 45 }); + }); + + it("times an async function via measure()", async () => { + const t = createTimings(fakeClock([1000, 1120])); + const value = await t.measure("authz", async () => "ok"); + expect(value).toBe("ok"); + expect(t.toJSON()).toEqual({ authz: 120 }); + }); + + it("still records duration when the measured function throws", async () => { + const t = createTimings(fakeClock([0, 30])); + await expect( + t.measure("db", async () => { + throw new Error("boom"); + }), + ).rejects.toThrow("boom"); + expect(t.toJSON()).toEqual({ db: 30 }); + }); + + it("preserves insertion order and supports add() for precomputed durations", () => { + const t = createTimings(fakeClock([0, 10])); + t.start("auth")(); + t.add("downstream", 200, "membership"); + expect(t.phases().map((p) => p.name)).toEqual(["auth", "downstream"]); + expect(t.header()).toBe('auth;dur=10, downstream;dur=200;desc="membership"'); + }); + + it("end() is idempotent (records once)", () => { + const t = createTimings(fakeClock([0, 5, 99])); + const end = t.start("x"); + end(); + end(); + expect(t.phases()).toHaveLength(1); + expect(t.toJSON()).toEqual({ x: 5 }); + }); + + it("sanitizes phase names and strips quotes from descriptions (header-safe)", () => { + const t = createTimings(fakeClock([0, 1])); + t.add("bad name!", 1, 'has "quotes" and \\slashes'); + expect(t.header()).toBe('bad_name_;dur=1;desc="has quotes and slashes"'); + }); + + it("clamps negative/non-finite durations to 0", () => { + const t = createTimings(); + t.add("neg", -5); + t.add("nan", Number.NaN); + expect(t.toJSON()).toEqual({ neg: 0, nan: 0 }); + }); + + it("returns an empty header when no phases recorded", () => { + expect(createTimings().header()).toBe(""); + }); + + describe("parseServerTimingDuration", () => { + it("extracts dur for a named metric", () => { + expect(parseServerTimingDuration("authz;dur=120, db;dur=45", "db")).toBe(45); + expect(parseServerTimingDuration("authz;dur=120.5, db;dur=45", "authz")).toBe(120.5); + }); + it("returns null for missing metric or header", () => { + expect(parseServerTimingDuration("authz;dur=10", "db")).toBeNull(); + expect(parseServerTimingDuration(null, "db")).toBeNull(); + expect(parseServerTimingDuration("db", "db")).toBeNull(); + }); + }); + + describe("appendServerTiming", () => { + it("joins existing and new metrics", () => { + expect(appendServerTiming("a;dur=1", "b;dur=2")).toBe("a;dur=1, b;dur=2"); + }); + it("handles empty sides", () => { + expect(appendServerTiming(null, "b;dur=2")).toBe("b;dur=2"); + expect(appendServerTiming("a;dur=1", "")).toBe("a;dur=1"); + expect(appendServerTiming(null, "")).toBe(""); + }); + }); + + describe("shouldEmitTimingLog (PERF14 sampling)", () => { + it("always emits when a phase is slow, regardless of the sample roll", () => { + // random=0.99 (would normally be sampled out at rate 0.1), but a slow phase forces emit. + expect(shouldEmitTimingLog({ total: 1200 }, { rate: 0.1, slowMs: 1000, random: () => 0.99 })).toBe(true); + }); + it("emits a fast request only when the sample roll is under the rate", () => { + expect(shouldEmitTimingLog({ total: 50 }, { rate: 0.1, random: () => 0.05 })).toBe(true); + expect(shouldEmitTimingLog({ total: 50 }, { rate: 0.1, random: () => 0.5 })).toBe(false); + }); + it("respects a custom slow threshold", () => { + expect(shouldEmitTimingLog({ edge_ratelimit: 300 }, { rate: 0, slowMs: 200, random: () => 0.99 })).toBe(true); + expect(shouldEmitTimingLog({ edge_ratelimit: 100 }, { rate: 0, slowMs: 200, random: () => 0.99 })).toBe(false); + }); + }); +}); diff --git a/tests/contracts/src/webhooks.test.ts b/tests/contracts/src/webhooks.test.ts new file mode 100644 index 0000000..345ef9b --- /dev/null +++ b/tests/contracts/src/webhooks.test.ts @@ -0,0 +1,253 @@ +import type { + PublicWebhookEndpoint, + PublicWebhookSubscription, + PublicWebhookDeliveryAttempt, + ListWebhookEndpointsResponse, + CreateWebhookEndpointRequest, + UpdateWebhookEndpointRequest, + CreateWebhookSubscriptionRequest, + ListWebhookSubscriptionsResponse, + ListWebhookDeliveryAttemptsResponse, + RotateWebhookSecretResponse, + DisableWebhookEndpointRequest, + ReplayWebhookDeliveryRequest, + ReplayWebhookDeliveryResponse, + DeleteWebhookEndpointResponse, +} from "@saas/contracts/webhooks"; + +// ── Webhook endpoint contract tests ─────────────────────── + +describe("contracts: webhook endpoint types", () => { + it("PublicWebhookEndpoint shape has required fields and no secret material", () => { + const endpoint: PublicWebhookEndpoint = { + id: "ep-001", + orgId: "org-001", + projectId: null, + url: "https://example.com/webhook", + name: "Test", + description: null, + status: "active", + disabledReason: null, + disabledAt: null, + secretVersion: 1, + secretLastRotatedAt: null, + createdAt: "2026-01-15T10:00:00Z", + updatedAt: "2026-01-15T10:00:00Z", + }; + expect(endpoint.id).toBe("ep-001"); + expect(endpoint.orgId).toBe("org-001"); + expect(endpoint.secretVersion).toBe(1); + // Must not include secret material + expect("signingSecret" in endpoint).toBe(false); + expect("secretCiphertext" in endpoint).toBe(false); + expect("secret_ciphertext" in endpoint).toBe(false); + expect("secretHash" in endpoint).toBe(false); + expect("plaintext" in endpoint).toBe(false); + }); + + it("ListWebhookEndpointsResponse has endpoints array and cursor", () => { + const response: ListWebhookEndpointsResponse = { + endpoints: [], + nextCursor: null, + }; + expect(response.endpoints).toHaveLength(0); + expect(response.nextCursor).toBeNull(); + }); + + it("CreateWebhookEndpointRequest has url and optional fields", () => { + const req: CreateWebhookEndpointRequest = { + url: "https://example.com/webhook", + name: "My Hook", + projectId: "prj-001", + }; + expect(req.url).toBe("https://example.com/webhook"); + // Must not accept secret values + expect("signingSecret" in req).toBe(false); + expect("secret" in req).toBe(false); + }); + + it("UpdateWebhookEndpointRequest allows partial updates", () => { + const req: UpdateWebhookEndpointRequest = { url: "https://new.example.com" }; + expect(req.url).toBe("https://new.example.com"); + expect(req.name).toBeUndefined(); + }); + + it("DisableWebhookEndpointRequest has optional reason", () => { + const req: DisableWebhookEndpointRequest = { reason: "Too many failures" }; + expect(req.reason).toBe("Too many failures"); + }); + + it("DeleteWebhookEndpointResponse has deleted: true", () => { + const res: DeleteWebhookEndpointResponse = { deleted: true }; + expect(res.deleted).toBe(true); + }); + + it("RotateWebhookSecretResponse returns endpoint without secret material", () => { + const res: RotateWebhookSecretResponse = { + endpoint: { + id: "ep-001", + orgId: "org-001", + projectId: null, + url: "https://example.com/webhook", + name: null, + description: null, + status: "active", + disabledReason: null, + disabledAt: null, + secretVersion: 2, + secretLastRotatedAt: "2026-01-15T10:00:00Z", + createdAt: "2026-01-15T10:00:00Z", + updatedAt: "2026-01-15T10:00:00Z", + }, + previousSecretExpiresAt: "2026-01-16T10:00:00Z", + gracePeriodSeconds: 86400, + }; + expect(res.endpoint.secretVersion).toBe(2); + expect("signingSecret" in res.endpoint).toBe(false); + // Grace window expiry is operator-visible but contains no secret material + expect(typeof res.previousSecretExpiresAt === "string" || res.previousSecretExpiresAt === null).toBe(true); + expect(typeof res.gracePeriodSeconds).toBe("number"); + }); + + it("RotateWebhookSecretResponse can carry reveal-once plaintext `whsec_<32 hex>`", () => { + const res: RotateWebhookSecretResponse = { + endpoint: { + id: "ep-001", + orgId: "org-001", + projectId: null, + url: "https://example.com/webhook", + name: null, + description: null, + status: "active", + disabledReason: null, + disabledAt: null, + secretVersion: 3, + secretLastRotatedAt: "2026-01-15T10:00:00Z", + createdAt: "2026-01-15T10:00:00Z", + updatedAt: "2026-01-15T10:00:00Z", + }, + secret: "whsec_0123456789abcdef0123456789abcdef", + previousSecretExpiresAt: null, + gracePeriodSeconds: 86400, + }; + // Reveal-once contract: optional plaintext follows the whsec_ + 32 hex shape + expect(res.secret).toMatch(/^whsec_[0-9a-f]{32}$/); + }); + + it("PublicWebhookEndpoint supports all status values", () => { + const statuses: PublicWebhookEndpoint["status"][] = ["active", "disabled", "pending"]; + statuses.forEach((s) => expect(typeof s).toBe("string")); + }); +}); + +// ── Webhook subscription contract tests ─────────────────── + +describe("contracts: webhook subscription types", () => { + it("PublicWebhookSubscription shape has required fields", () => { + const sub: PublicWebhookSubscription = { + id: "sub-001", + orgId: "org-001", + endpointId: "ep-001", + projectId: null, + eventType: "project.created", + enabled: true, + createdAt: "2026-01-15T10:00:00Z", + updatedAt: "2026-01-15T10:00:00Z", + }; + expect(sub.eventType).toBe("project.created"); + expect(sub.enabled).toBe(true); + }); + + it("ListWebhookSubscriptionsResponse has subscriptions array", () => { + const response: ListWebhookSubscriptionsResponse = { + subscriptions: [], + nextCursor: null, + }; + expect(response.subscriptions).toHaveLength(0); + }); + + it("CreateWebhookSubscriptionRequest has endpointId and eventType", () => { + const req: CreateWebhookSubscriptionRequest = { + endpointId: "ep-001", + eventType: "member.added", + projectId: "prj-001", + }; + expect(req.endpointId).toBe("ep-001"); + expect(req.projectId).toBe("prj-001"); + }); +}); + +// ── Webhook delivery attempt contract tests ─────────────── + +describe("contracts: webhook delivery attempt types", () => { + it("PublicWebhookDeliveryAttempt shape has required fields and no raw payload", () => { + const attempt: PublicWebhookDeliveryAttempt = { + id: "del-001", + orgId: "org-001", + endpointId: "ep-001", + subscriptionId: "sub-001", + eventId: "evt-001", + eventType: "project.created", + status: "success", + attemptNumber: 1, + httpStatusCode: 200, + failureReason: null, + idempotencyKey: null, + nextRetryAt: null, + completedAt: "2026-01-15T10:00:00Z", + createdAt: "2026-01-15T10:00:00Z", + updatedAt: "2026-01-15T10:00:00Z", + }; + expect(attempt.status).toBe("success"); + expect(attempt.httpStatusCode).toBe(200); + // Must not include raw event payload or response body + expect("eventPayload" in attempt).toBe(false); + expect("event_payload" in attempt).toBe(false); + expect("responseBody" in attempt).toBe(false); + expect("response_body" in attempt).toBe(false); + }); + + it("ListWebhookDeliveryAttemptsResponse has deliveryAttempts array", () => { + const response: ListWebhookDeliveryAttemptsResponse = { + deliveryAttempts: [], + nextCursor: null, + }; + expect(response.deliveryAttempts).toHaveLength(0); + }); + + it("PublicWebhookDeliveryAttempt supports all status values", () => { + const statuses: PublicWebhookDeliveryAttempt["status"][] = ["pending", "success", "failed", "retrying"]; + statuses.forEach((s) => expect(typeof s).toBe("string")); + }); + + it("ReplayWebhookDeliveryResponse wraps a single public delivery attempt", () => { + const response: ReplayWebhookDeliveryResponse = { + deliveryAttempt: { + id: "del-replay-001", + orgId: "org-001", + endpointId: "whe-001", + subscriptionId: "whs-001", + eventId: "evt-001", + eventType: "user.created", + status: "success", + attemptNumber: 1, + httpStatusCode: 200, + failureReason: null, + idempotencyKey: "whs-001:evt-001:replay:new-uuid", + nextRetryAt: null, + completedAt: "2026-02-01T10:00:00.000Z", + createdAt: "2026-02-01T09:59:59.000Z", + updatedAt: "2026-02-01T10:00:00.000Z", + }, + }; + expect(response.deliveryAttempt.status).toBe("success"); + // No secret material or raw payload field on the response. + expect(JSON.stringify(response)).not.toContain("payload"); + expect(JSON.stringify(response)).not.toContain("secret"); + }); + + it("ReplayWebhookDeliveryRequest is an empty (fieldless) body", () => { + const request: ReplayWebhookDeliveryRequest = {}; + expect(Object.keys(request)).toHaveLength(0); + }); +}); diff --git a/tests/contracts/tsconfig.json b/tests/contracts/tsconfig.json new file mode 100644 index 0000000..1dfb183 --- /dev/null +++ b/tests/contracts/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "paths": { + "@saas/contracts": ["../../packages/contracts/src/index.ts"], + "@saas/contracts/*": ["../../packages/contracts/src/*.ts"], + "@saas/testing": ["../../packages/testing/src/index.ts"], + "@saas/testing/*": ["../../packages/testing/src/*.ts"] + } + }, + "include": ["src/**/*.ts", "../../packages/testing/src/**/*.ts", "../../packages/contracts/src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/tests/db/component.yaml b/tests/db/component.yaml new file mode 100644 index 0000000..bd516a3 --- /dev/null +++ b/tests/db/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: db-tests +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "20" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/tests/db/docs/architecture.md b/tests/db/docs/architecture.md new file mode 100644 index 0000000..d6e0555 --- /dev/null +++ b/tests/db/docs/architecture.md @@ -0,0 +1,9 @@ +# db-tests — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `tests/db`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/tests/db/docs/overview.md b/tests/db/docs/overview.md new file mode 100644 index 0000000..dfd5364 --- /dev/null +++ b/tests/db/docs/overview.md @@ -0,0 +1,13 @@ +# db-tests + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/db/docs/runbook.md b/tests/db/docs/runbook.md new file mode 100644 index 0000000..26e6d52 --- /dev/null +++ b/tests/db/docs/runbook.md @@ -0,0 +1,26 @@ +# db-tests — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/db/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/db/package.json b/tests/db/package.json new file mode 100644 index 0000000..95595f7 --- /dev/null +++ b/tests/db/package.json @@ -0,0 +1,48 @@ +{ + "name": "@saas/db-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "lint": "eslint src" + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/jest": "^29.5.14", + "@types/node": "^22.10.0", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/db": "workspace:*" + }, + "jest": { + "preset": "ts-jest/presets/default-esm", + "extensionsToTreatAsEsm": [ + ".ts" + ], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1", + "^@saas/db$": "/../../packages/db/src/index.ts", + "^@saas/db/manifest$": "/../../packages/db/src/manifest.ts", + "^@saas/db/types$": "/../../packages/db/src/types.ts", + "^@saas/db/(.*)$": "/../../packages/db/src/$1/index.ts" + }, + "transform": { + "^.+\\.ts$": [ + "ts-jest", + { + "useESM": true + } + ] + }, + "testMatch": [ + "/src/**/*.test.ts" + ] + } +} diff --git a/tests/db/src/billing-scope.test.ts b/tests/db/src/billing-scope.test.ts new file mode 100644 index 0000000..2fee0b6 --- /dev/null +++ b/tests/db/src/billing-scope.test.ts @@ -0,0 +1,23 @@ +import { effectiveBillingOrgId } from "@saas/db/membership"; + +describe("effectiveBillingOrgId", () => { + it("returns the org's own id when standalone (parentOrgId null)", () => { + expect(effectiveBillingOrgId({ id: "org_standalone", parentOrgId: null })).toBe( + "org_standalone", + ); + }); + + it("returns the parent's id when the org is a child", () => { + expect( + effectiveBillingOrgId({ id: "org_child", parentOrgId: "org_parent" }), + ).toBe("org_parent"); + }); + + it("treats every standalone org as its own billing entity (back-compat)", () => { + // The MO1 invariant: with no parent set (every existing org), resolution + // collapses to the org id, so all current billing behavior is preserved. + for (const id of ["org_a", "org_b", "org_c"]) { + expect(effectiveBillingOrgId({ id, parentOrgId: null })).toBe(id); + } + }); +}); diff --git a/tests/db/src/billing.test.ts b/tests/db/src/billing.test.ts new file mode 100644 index 0000000..c663bca --- /dev/null +++ b/tests/db/src/billing.test.ts @@ -0,0 +1,589 @@ +import { createBillingRepository } from "@saas/db/billing"; +import type { + CreatePlanInput, + UpsertBillingCustomerInput, + CreateSubscriptionInput, + UpsertInvoiceInput, + UpsertEntitlementInput, +} from "@saas/db/billing"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +// ── Mock executor ────────────────────────────────────────── + +interface MockCall { + sql: string; + params: unknown[]; +} + +function createMockExecutor( + handler?: (sql: string, params: unknown[]) => SqlExecutorResult>, +): SqlExecutor & { calls: MockCall[] } { + const calls: MockCall[] = []; + return { + calls, + async execute( + text: string, + params: unknown[] = [], + ): Promise> { + calls.push({ sql: text, params }); + if (handler) { + return handler(text, params) as unknown as SqlExecutorResult; + } + return { rows: [] as T[], rowCount: 0 }; + }, + }; +} + +// ── Constants ────────────────────────────────────────────── + +const ORG_ID = "org-test-001"; +const OTHER_ORG_ID = "org-test-other"; +const PLAN_ID = "plan-001"; +const CUSTOMER_ID = "bcust-001"; +const SUB_ID = "sub-001"; +const INVOICE_ID = "inv-001"; +const ENT_ID = "ent-001"; + +// ── Row factories ────────────────────────────────────────── + +function planRow(o: Record = {}): Record { + return { + id: PLAN_ID, + code: "starter", + name: "Starter", + description: null, + status: "active", + billing_interval: "month", + price_amount_cents: "0", + price_currency: "usd", + metadata: null, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + ...o, + }; +} + +function customerRow(o: Record = {}): Record { + return { + id: CUSTOMER_ID, + org_id: ORG_ID, + display_name: null, + email: null, + status: "active", + provider: null, + provider_customer_id: null, + metadata: null, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + ...o, + }; +} + +function subRow(o: Record = {}): Record { + return { + id: SUB_ID, + org_id: ORG_ID, + billing_customer_id: CUSTOMER_ID, + plan_id: PLAN_ID, + status: "active", + current_period_start: "2026-01-01T00:00:00.000Z", + current_period_end: "2026-02-01T00:00:00.000Z", + trial_end: null, + cancel_at: null, + canceled_at: null, + provider: null, + provider_subscription_id: null, + metadata: null, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + ...o, + }; +} + +function invoiceRow(o: Record = {}): Record { + return { + id: INVOICE_ID, + org_id: ORG_ID, + billing_customer_id: CUSTOMER_ID, + subscription_id: SUB_ID, + number: "INV-0001", + status: "open", + amount_due_cents: "1000", + amount_paid_cents: "0", + currency: "usd", + issued_at: "2026-01-15T00:00:00.000Z", + due_at: "2026-02-01T00:00:00.000Z", + paid_at: null, + period_start: "2026-01-01T00:00:00.000Z", + period_end: "2026-02-01T00:00:00.000Z", + provider: null, + provider_invoice_id: null, + hosted_url: null, + metadata: null, + created_at: "2026-01-15T00:00:00.000Z", + updated_at: "2026-01-15T00:00:00.000Z", + ...o, + }; +} + +function entRow(o: Record = {}): Record { + return { + id: ENT_ID, + org_id: ORG_ID, + subscription_id: SUB_ID, + entitlement_key: "feature.custom_domains", + value_type: "boolean", + enabled: true, + limit_value: null, + source: "plan", + metadata: null, + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + ...o, + }; +} + +// ── Input helpers ────────────────────────────────────────── + +function planInput(o: Partial = {}): CreatePlanInput { + return { id: PLAN_ID, code: "starter", name: "Starter", ...o }; +} + +function customerInput( + o: Partial = {}, +): UpsertBillingCustomerInput { + return { id: CUSTOMER_ID, orgId: ORG_ID, ...o }; +} + +function subInput(o: Partial = {}): CreateSubscriptionInput { + return { + id: SUB_ID, + orgId: ORG_ID, + billingCustomerId: CUSTOMER_ID, + planId: PLAN_ID, + ...o, + }; +} + +function invoiceInput(o: Partial = {}): UpsertInvoiceInput { + return { + id: INVOICE_ID, + orgId: ORG_ID, + billingCustomerId: CUSTOMER_ID, + ...o, + }; +} + +function entInput(o: Partial = {}): UpsertEntitlementInput { + return { + id: ENT_ID, + orgId: ORG_ID, + entitlementKey: "feature.custom_domains", + valueType: "boolean", + ...o, + }; +} + +// ── Tests ────────────────────────────────────────────────── + +describe("Billing Repository — Plans", () => { + it("createPlan inserts and returns the plan", async () => { + const executor = createMockExecutor(() => ({ rows: [planRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.createPlan(planInput()); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.code).toBe("starter"); + expect(result.value.status).toBe("active"); + expect(result.value.billingInterval).toBe("month"); + } + }); + + it("createPlan returns conflict on duplicate code", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createBillingRepository(executor); + const result = await repo.createPlan(planInput()); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("createPlan parameterizes all values — no SQL interpolation", async () => { + const executor = createMockExecutor(() => ({ rows: [planRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.createPlan(planInput({ code: "pro'; DROP TABLE" })); + const call = executor.calls[0]!; + expect(call.sql).toContain("$1"); + expect(call.sql).not.toContain("DROP TABLE"); + expect(call.params).toContain("pro'; DROP TABLE"); + }); + + it("getPlanByCode returns the plan", async () => { + const executor = createMockExecutor(() => ({ rows: [planRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.getPlanByCode("starter"); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.code).toBe("starter"); + }); + + it("listPlans applies optional status filter", async () => { + const executor = createMockExecutor(() => ({ rows: [planRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.listPlans({ status: "active" }); + const call = executor.calls[0]!; + expect(call.sql).toContain("status = $1"); + expect(call.params).toContain("active"); + }); +}); + +describe("Billing Repository — Billing Customers", () => { + it("upsertBillingCustomer creates a new row", async () => { + const executor = createMockExecutor(() => ({ rows: [customerRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.upsertBillingCustomer(customerInput()); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.status).toBe("active"); + } + }); + + it("upsertBillingCustomer uses ON CONFLICT on org_id (V1 invariant)", async () => { + const executor = createMockExecutor(() => ({ rows: [customerRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.upsertBillingCustomer(customerInput()); + const call = executor.calls[0]!; + expect(call.sql).toContain("ON CONFLICT (org_id)"); + }); + + it("getBillingCustomer scopes by orgId", async () => { + const executor = createMockExecutor(() => ({ rows: [customerRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.getBillingCustomer(ORG_ID); + const call = executor.calls[0]!; + expect(call.sql).toContain("WHERE org_id = $1"); + expect(call.params[0]).toBe(ORG_ID); + }); + + it("getBillingCustomer returns not_found when no row", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createBillingRepository(executor); + const result = await repo.getBillingCustomer(ORG_ID); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("BillingCustomer type omits any plaintext provider credentials", () => { + const row = customerRow({ provider: "stripe", provider_customer_id: "cus_abc" }); + const executor = createMockExecutor(() => ({ rows: [row], rowCount: 1 })); + return createBillingRepository(executor) + .getBillingCustomer(ORG_ID) + .then((r) => { + if (!r.ok) throw new Error("expected ok"); + // No api_key / secret / token fields should ever be present + expect(Object.keys(r.value)).not.toEqual( + expect.arrayContaining(["apiKey", "secret", "token", "providerSecret"]), + ); + // Provider id is opaque only + expect(r.value.providerCustomerId).toBe("cus_abc"); + }); + }); +}); + +describe("Billing Repository — Subscriptions", () => { + it("createSubscription inserts row and returns it", async () => { + const executor = createMockExecutor(() => ({ rows: [subRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.createSubscription(subInput()); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.status).toBe("active"); + expect(result.value.currentPeriodEnd).toBeInstanceOf(Date); + } + }); + + it("getSubscription scopes by both org_id AND id (tenant isolation)", async () => { + const executor = createMockExecutor(() => ({ rows: [subRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.getSubscription(ORG_ID, SUB_ID); + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("id = $2"); + expect(call.params).toEqual([ORG_ID, SUB_ID]); + }); + + it("getSubscription cross-org lookup returns not_found", async () => { + const executor = createMockExecutor((_sql, params) => { + // Mimic DB: row only returned when org_id matches + if (params[0] === OTHER_ORG_ID) return { rows: [], rowCount: 0 }; + return { rows: [subRow()], rowCount: 1 }; + }); + const repo = createBillingRepository(executor); + const result = await repo.getSubscription(OTHER_ORG_ID, SUB_ID); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("getActiveSubscription only returns trialing/active/past_due", async () => { + const executor = createMockExecutor(() => ({ rows: [subRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.getActiveSubscription(ORG_ID); + const call = executor.calls[0]!; + expect(call.sql).toContain("trialing"); + expect(call.sql).toContain("active"); + expect(call.sql).toContain("past_due"); + expect(call.sql).not.toContain("canceled"); + }); + + it("listSubscriptions scopes by org and paginates", async () => { + const executor = createMockExecutor(() => ({ + rows: [subRow(), subRow({ id: "sub-002" })], + rowCount: 2, + })); + const repo = createBillingRepository(executor); + const result = await repo.listSubscriptions(ORG_ID, { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.items.length).toBe(2); + expect(executor.calls[0]!.sql).toContain("org_id = $1"); + }); + + it("updateSubscription applies dynamic SET and requires org_id+id", async () => { + const executor = createMockExecutor(() => ({ + rows: [subRow({ status: "canceled" })], + rowCount: 1, + })); + const repo = createBillingRepository(executor); + const result = await repo.updateSubscription(ORG_ID, SUB_ID, { + status: "canceled", + canceledAt: new Date("2026-01-20T00:00:00.000Z"), + }); + expect(result.ok).toBe(true); + const call = executor.calls[0]!; + expect(call.sql).toContain("UPDATE billing_subscriptions"); + expect(call.sql).toContain("WHERE org_id = $1 AND id = $2"); + expect(call.params[0]).toBe(ORG_ID); + expect(call.params[1]).toBe(SUB_ID); + }); +}); + +describe("Billing Repository — Invoices", () => { + it("upsertInvoice creates and maps amounts and timestamps", async () => { + const executor = createMockExecutor(() => ({ rows: [invoiceRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.upsertInvoice(invoiceInput({ status: "open" })); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.amountDueCents).toBe(1000); + expect(result.value.amountPaidCents).toBe(0); + expect(result.value.status).toBe("open"); + expect(result.value.issuedAt).toBeInstanceOf(Date); + } + }); + + it("upsertInvoice ON CONFLICT only updates when org_id matches (no cross-org overwrite)", async () => { + const executor = createMockExecutor(() => ({ rows: [invoiceRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.upsertInvoice(invoiceInput()); + const call = executor.calls[0]!; + expect(call.sql).toContain("ON CONFLICT (id) DO UPDATE"); + expect(call.sql).toContain("WHERE billing_invoices.org_id = EXCLUDED.org_id"); + }); + + it("listInvoices requires orgId and applies optional filters", async () => { + const executor = createMockExecutor(() => ({ + rows: [invoiceRow()], + rowCount: 1, + })); + const repo = createBillingRepository(executor); + await repo.listInvoices( + { orgId: ORG_ID, subscriptionId: SUB_ID, status: "open" }, + { limit: 25, cursor: null }, + ); + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("subscription_id = $2"); + expect(call.sql).toContain("status = $3"); + expect(call.params[0]).toBe(ORG_ID); + }); + + it("getInvoice scopes by org_id AND id", async () => { + const executor = createMockExecutor(() => ({ rows: [invoiceRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.getInvoice(ORG_ID, INVOICE_ID); + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("id = $2"); + }); + + it("Invoice type exposes safe hostedUrl only — never raw provider payloads", () => { + const row = invoiceRow({ + hosted_url: "https://invoice.stripe.com/i/abc/safe-display", + provider: "stripe", + provider_invoice_id: "in_abc", + }); + const executor = createMockExecutor(() => ({ rows: [row], rowCount: 1 })); + return createBillingRepository(executor) + .getInvoice(ORG_ID, INVOICE_ID) + .then((r) => { + if (!r.ok) throw new Error("expected ok"); + // Sanity check: type has no provider_payload, no secret field + expect(Object.keys(r.value)).not.toEqual( + expect.arrayContaining(["providerPayload", "rawPayload", "secret", "apiKey"]), + ); + expect(r.value.hostedUrl).toBe("https://invoice.stripe.com/i/abc/safe-display"); + }); + }); +}); + +describe("Billing Repository — Entitlements", () => { + it("upsertEntitlement creates and returns row", async () => { + const executor = createMockExecutor(() => ({ rows: [entRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.upsertEntitlement(entInput()); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.entitlementKey).toBe("feature.custom_domains"); + expect(result.value.enabled).toBe(true); + expect(result.value.limitValue).toBeNull(); + } + }); + + it("upsertEntitlement upserts on (org_id, entitlement_key)", async () => { + const executor = createMockExecutor(() => ({ rows: [entRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.upsertEntitlement(entInput()); + expect(executor.calls[0]!.sql).toContain("ON CONFLICT (org_id, entitlement_key)"); + }); + + it("upsertEntitlement supports quantity with limit_value", async () => { + const row = entRow({ + entitlement_key: "limit.projects", + value_type: "quantity", + limit_value: "10", + }); + const executor = createMockExecutor(() => ({ rows: [row], rowCount: 1 })); + const repo = createBillingRepository(executor); + const result = await repo.upsertEntitlement( + entInput({ + entitlementKey: "limit.projects", + valueType: "quantity", + limitValue: 10, + }), + ); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.valueType).toBe("quantity"); + expect(result.value.limitValue).toBe(10); + } + }); + + it("getEntitlement scopes by org_id and entitlement_key", async () => { + const executor = createMockExecutor(() => ({ rows: [entRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.getEntitlement(ORG_ID, "feature.custom_domains"); + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("entitlement_key = $2"); + expect(call.params).toEqual([ORG_ID, "feature.custom_domains"]); + }); + + it("listEntitlements requires orgId; applies subscription/source filters", async () => { + const executor = createMockExecutor(() => ({ rows: [entRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + await repo.listEntitlements({ + orgId: ORG_ID, + subscriptionId: SUB_ID, + source: "override", + }); + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("subscription_id = $2"); + expect(call.sql).toContain("source = $3"); + expect(call.params[0]).toBe(ORG_ID); + }); + + it("cross-org getEntitlement returns not_found", async () => { + const executor = createMockExecutor((_sql, params) => { + if (params[0] === OTHER_ORG_ID) return { rows: [], rowCount: 0 }; + return { rows: [entRow()], rowCount: 1 }; + }); + const repo = createBillingRepository(executor); + const result = await repo.getEntitlement(OTHER_ORG_ID, "feature.custom_domains"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); +}); + +describe("Billing Repository — getBillingSummary", () => { + it("composes customer + active subscription + plan + entitlements scoped to org", async () => { + let n = 0; + const executor = createMockExecutor(() => { + n++; + // 1: getBillingCustomer + // 2: getActiveSubscription + // 3: getPlan + // 4: listEntitlements + if (n === 1) return { rows: [customerRow()], rowCount: 1 }; + if (n === 2) return { rows: [subRow()], rowCount: 1 }; + if (n === 3) return { rows: [planRow()], rowCount: 1 }; + return { rows: [entRow()], rowCount: 1 }; + }); + const repo = createBillingRepository(executor); + const result = await repo.getBillingSummary(ORG_ID); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.customer?.orgId).toBe(ORG_ID); + expect(result.value.activeSubscription?.id).toBe(SUB_ID); + expect(result.value.plan?.code).toBe("starter"); + expect(result.value.entitlements.length).toBe(1); + } + // Every org-scoped call must pass ORG_ID; plan lookup is by plan_id. + for (const call of executor.calls) { + if (call.sql.includes("billing_plans WHERE id")) continue; + expect(call.params[0]).toBe(ORG_ID); + } + }); + + it("returns nulls when no customer / subscription / plan but still includes entitlements list", async () => { + let n = 0; + const executor = createMockExecutor(() => { + n++; + if (n === 1) return { rows: [], rowCount: 0 }; // no customer + if (n === 2) return { rows: [], rowCount: 0 }; // no sub + // listEntitlements + return { rows: [], rowCount: 0 }; + }); + const repo = createBillingRepository(executor); + const result = await repo.getBillingSummary(ORG_ID); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.customer).toBeNull(); + expect(result.value.activeSubscription).toBeNull(); + expect(result.value.plan).toBeNull(); + expect(result.value.entitlements).toEqual([]); + } + }); +}); + +describe("Billing Repository — metering/billing boundary", () => { + it("never reads from or writes to metering-owned tables", async () => { + const executor = createMockExecutor(() => ({ rows: [planRow()], rowCount: 1 })); + const repo = createBillingRepository(executor); + + await repo.createPlan(planInput()); + await repo.upsertBillingCustomer(customerInput()); + await repo.createSubscription(subInput()); + await repo.upsertInvoice(invoiceInput()); + await repo.upsertEntitlement(entInput()); + await repo.listEntitlements({ orgId: ORG_ID }); + await repo.getEntitlement(ORG_ID, "feature.custom_domains"); + await repo.listSubscriptions(ORG_ID, { limit: 10, cursor: null }); + await repo.listInvoices({ orgId: ORG_ID }, { limit: 10, cursor: null }); + + for (const call of executor.calls) { + expect(call.sql).not.toMatch(/metering\./); + } + }); +}); diff --git a/tests/db/src/config.test.ts b/tests/db/src/config.test.ts new file mode 100644 index 0000000..d91f9af --- /dev/null +++ b/tests/db/src/config.test.ts @@ -0,0 +1,566 @@ +import { + createConfigRepository, +} from "@saas/db/config"; +import { asUuid } from "@saas/db"; +import type { + Scope, + SecretMetadata, +} from "@saas/db/config"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + if (options?.error) { + throw options.error; + } + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); + +const SAMPLE_SETTING_ROW = { + id: "set-001", + org_id: "org-001", + project_id: null, + environment_id: null, + scope_kind: "organization", + key: "theme", + value: { dark: true }, + description: "UI theme", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_FLAG_ROW = { + id: "flg-001", + org_id: "org-001", + project_id: null, + environment_id: null, + scope_kind: "organization", + flag_key: "beta_feature", + enabled: true, + value: null, + description: "Beta feature toggle", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_SECRET_ROW = { + id: "sec-001", + org_id: "org-001", + project_id: null, + environment_id: null, + scope_kind: "organization", + secret_key: "DB_PASSWORD", + display_name: "Database Password", + status: "active", + version: 1, + rotation_policy: null, + last_rotated_at: null, + expires_at: null, + created_by: "user-001", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const ORG_SCOPE: Scope = { kind: "organization", orgId: "org-001" }; +const PROJECT_SCOPE: Scope = { kind: "project", orgId: "org-001", projectId: "prj-001" }; +const ENV_SCOPE: Scope = { kind: "environment", orgId: "org-001", projectId: "prj-001", environmentId: "env-001" }; + +// ── Settings tests ───────────────────────────────────────── + +describe("ConfigRepository — Settings", () => { + it("creates an org-scoped setting with parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SETTING_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-001", + scope: ORG_SCOPE, + key: "theme", + value: { dark: true }, + description: "UI theme", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("set-001"); + expect(result.value.scopeKind).toBe("organization"); + expect(result.value.projectId).toBeNull(); + expect(result.value.environmentId).toBeNull(); + } + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("config_settings"); + expect(queries[0]!.params[2]).toBeNull(); // project_id null + expect(queries[0]!.params[3]).toBeNull(); // environment_id null + }); + + it("creates a project-scoped setting with both orgId and projectId", async () => { + const row = { ...SAMPLE_SETTING_ROW, project_id: "prj-001", scope_kind: "project" }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-002", + scope: PROJECT_SCOPE, + key: "timeout", + value: 30, + }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[1]).toBe("org-001"); // org_id + expect(queries[0]!.params[2]).toBe("prj-001"); // project_id + expect(queries[0]!.params[3]).toBeNull(); // environment_id + }); + + it("creates an environment-scoped setting with all three IDs", async () => { + const row = { ...SAMPLE_SETTING_ROW, project_id: "prj-001", environment_id: "env-001", scope_kind: "environment" }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-003", + scope: ENV_SCOPE, + key: "log_level", + value: "debug", + }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[1]).toBe("org-001"); + expect(queries[0]!.params[2]).toBe("prj-001"); + expect(queries[0]!.params[3]).toBe("env-001"); + }); + + it("returns conflict on unique violation", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-001", + scope: ORG_SCOPE, + key: "theme", + value: {}, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns conflict when insert returns 0 rows", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-001", + scope: ORG_SCOPE, + key: "theme", + value: {}, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns internal error on check violation", async () => { + const { executor } = createFakeExecutor({ error: { code: "23514" } }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-001", + scope: ORG_SCOPE, + key: "theme", + value: {}, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + } + }); + + it("updates a setting by orgId + settingId", async () => { + const updatedRow = { ...SAMPLE_SETTING_ROW, value: { dark: false } }; + const { executor, queries } = createFakeExecutor({ rows: [updatedRow] }); + const repo = createConfigRepository(executor); + const result = await repo.updateSetting("org-001", "set-001", { value: { dark: false } }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("set-001"); + }); + + it("returns not_found when updating a non-existent setting", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.updateSetting("org-001", "set-999", { value: {} }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("gets a setting by orgId + settingId", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SETTING_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.getSetting("org-001", "set-001"); + expect(result.ok).toBe(true); + }); + + it("returns not_found for missing setting", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.getSetting("org-001", "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("lists settings with org scope filter", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SETTING_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.listSettings(ORG_SCOPE, { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.items).toHaveLength(1); + expect(queries[0]!.text).toContain("scope_kind = 'organization'"); + }); + + it("lists settings with project scope filter requiring orgId + projectId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createConfigRepository(executor); + await repo.listSettings(PROJECT_SCOPE, { limit: 10, cursor: null }); + expect(queries[0]!.text).toContain("org_id = $1 AND project_id = $2"); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("prj-001"); + }); + + it("lists settings with environment scope filter requiring all three IDs", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createConfigRepository(executor); + await repo.listSettings(ENV_SCOPE, { limit: 10, cursor: null }); + expect(queries[0]!.text).toContain("org_id = $1 AND project_id = $2 AND environment_id = $3"); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("prj-001"); + expect(queries[0]!.params[2]).toBe("env-001"); + }); + + it("supports cursor pagination in list", async () => { + const rows = [ + { ...SAMPLE_SETTING_ROW, id: "set-a" }, + { ...SAMPLE_SETTING_ROW, id: "set-b" }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createConfigRepository(executor); + const result = await repo.listSettings(ORG_SCOPE, { limit: 1, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).not.toBeNull(); + } + }); +}); + +// ── Feature flags tests ──────────────────────────────────── + +describe("ConfigRepository — Feature Flags", () => { + it("creates an org-scoped flag", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_FLAG_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.createFeatureFlag({ + id: "flg-001", + scope: ORG_SCOPE, + flagKey: "beta_feature", + enabled: true, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.flagKey).toBe("beta_feature"); + expect(result.value.enabled).toBe(true); + } + expect(queries[0]!.text).toContain("config_feature_flags"); + }); + + it("creates a project-scoped flag with orgId + projectId", async () => { + const row = { ...SAMPLE_FLAG_ROW, project_id: "prj-001", scope_kind: "project" }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createConfigRepository(executor); + await repo.createFeatureFlag({ + id: "flg-002", + scope: PROJECT_SCOPE, + flagKey: "dark_mode", + }); + expect(queries[0]!.params[2]).toBe("prj-001"); + }); + + it("returns conflict on duplicate flag key", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createConfigRepository(executor); + const result = await repo.createFeatureFlag({ + id: "flg-001", + scope: ORG_SCOPE, + flagKey: "beta_feature", + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("updates a flag by orgId + flagId", async () => { + const updatedRow = { ...SAMPLE_FLAG_ROW, enabled: false }; + const { executor, queries } = createFakeExecutor({ rows: [updatedRow] }); + const repo = createConfigRepository(executor); + const result = await repo.updateFeatureFlag("org-001", "flg-001", { enabled: false }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("flg-001"); + }); + + it("returns not_found when updating a missing flag", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.updateFeatureFlag("org-001", "nope", { enabled: true }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("gets a flag by orgId + flagId", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_FLAG_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.getFeatureFlag("org-001", "flg-001"); + expect(result.ok).toBe(true); + }); + + it("lists flags with scope filter", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_FLAG_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.listFeatureFlags(ORG_SCOPE, { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("config_feature_flags"); + }); +}); + +// ── Secret metadata tests ────────────────────────────────── + +describe("ConfigRepository — Secret Metadata", () => { + it("creates secret metadata without exposing plaintext", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECRET_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.createSecretMetadata({ + id: "sec-001", + scope: ORG_SCOPE, + secretKey: "DB_PASSWORD", + displayName: "Database Password", + createdBy: asUuid("00000000-0000-0000-0000-000000000001"), + }); + expect(result.ok).toBe(true); + if (result.ok) { + const val = result.value; + // Must not have ciphertext_envelope or any plaintext secret field + expect("ciphertext_envelope" in val).toBe(false); + expect("ciphertextEnvelope" in val).toBe(false); + expect("plaintext" in val).toBe(false); + expect("secret_value" in val).toBe(false); + expect("secretValue" in val).toBe(false); + expect(val.secretKey).toBe("DB_PASSWORD"); + expect(val.status).toBe("active"); + expect(val.version).toBe(1); + } + // RETURNING clause must not include ciphertext_envelope + expect(queries[0]!.text).not.toContain("ciphertext_envelope"); + }); + + it("lists secret metadata without exposing ciphertext_envelope", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECRET_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.listSecretMetadata(ORG_SCOPE, { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + const item = result.value.items[0]!; + expect("ciphertext_envelope" in item).toBe(false); + expect("ciphertextEnvelope" in item).toBe(false); + } + // SELECT must use safe columns, not * + expect(queries[0]!.text).not.toContain("SELECT *"); + expect(queries[0]!.text).not.toContain("ciphertext_envelope"); + }); + + it("gets secret metadata without exposing ciphertext_envelope", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECRET_ROW] }); + const repo = createConfigRepository(executor); + const result = await repo.getSecretMetadata("org-001", "sec-001"); + expect(result.ok).toBe(true); + expect(queries[0]!.text).not.toContain("ciphertext_envelope"); + expect(queries[0]!.text).not.toContain("SELECT *"); + }); + + it("rotates secret metadata (increments version)", async () => { + const rotatedRow = { ...SAMPLE_SECRET_ROW, version: 2, last_rotated_at: NOW.toISOString() }; + const { executor, queries } = createFakeExecutor({ rows: [rotatedRow] }); + const repo = createConfigRepository(executor); + const result = await repo.rotateSecretMetadata("org-001", "sec-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.version).toBe(2); + } + expect(queries[0]!.text).toContain("version = version + 1"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.text).not.toContain("ciphertext_envelope"); + }); + + it("revokes secret metadata", async () => { + const revokedRow = { ...SAMPLE_SECRET_ROW, status: "revoked" }; + const { executor, queries } = createFakeExecutor({ rows: [revokedRow] }); + const repo = createConfigRepository(executor); + const result = await repo.revokeSecretMetadata("org-001", "sec-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("revoked"); + } + expect(queries[0]!.text).toContain("status = 'revoked'"); + expect(queries[0]!.text).not.toContain("ciphertext_envelope"); + }); + + it("returns not_found when rotating non-existent secret", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.rotateSecretMetadata("org-001", "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns not_found when revoking non-existent secret", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createConfigRepository(executor); + const result = await repo.revokeSecretMetadata("org-001", "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("lists secret metadata with project scope requiring orgId + projectId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createConfigRepository(executor); + await repo.listSecretMetadata(PROJECT_SCOPE, { limit: 10, cursor: null }); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("prj-001"); + }); + + it("creates project-scoped secret with orgId + projectId", async () => { + const row = { ...SAMPLE_SECRET_ROW, project_id: "prj-001", scope_kind: "project" }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createConfigRepository(executor); + await repo.createSecretMetadata({ + id: "sec-002", + scope: PROJECT_SCOPE, + secretKey: "API_TOKEN", + createdBy: asUuid("00000000-0000-0000-0000-000000000001"), + }); + expect(queries[0]!.params[1]).toBe("org-001"); + expect(queries[0]!.params[2]).toBe("prj-001"); + expect(queries[0]!.params[3]).toBeNull(); // environment_id + }); + + it("returns conflict on duplicate secret key", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createConfigRepository(executor); + const result = await repo.createSecretMetadata({ + id: "sec-001", + scope: ORG_SCOPE, + secretKey: "DB_PASSWORD", + createdBy: asUuid("00000000-0000-0000-0000-000000000001"), + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); +}); + +// ── Scope validation tests ───────────────────────────────── + +describe("ConfigRepository — Scope Validation", () => { + it("rejects setting creation when check constraint violated", async () => { + const { executor } = createFakeExecutor({ error: { code: "23514" } }); + const repo = createConfigRepository(executor); + const result = await repo.createSetting({ + id: "set-bad", + scope: ORG_SCOPE, + key: "x", + value: {}, + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); + + it("rejects flag creation when check constraint violated", async () => { + const { executor } = createFakeExecutor({ error: { code: "23514" } }); + const repo = createConfigRepository(executor); + const result = await repo.createFeatureFlag({ + id: "flg-bad", + scope: ORG_SCOPE, + flagKey: "x", + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); + + it("rejects secret creation when check constraint violated", async () => { + const { executor } = createFakeExecutor({ error: { code: "23514" } }); + const repo = createConfigRepository(executor); + const result = await repo.createSecretMetadata({ + id: "sec-bad", + scope: ORG_SCOPE, + secretKey: "x", + createdBy: asUuid("00000000-0000-0000-0000-000000000001"), + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); +}); + +// ── Secret safety invariants ─────────────────────────────── + +describe("Secret Safety Invariants", () => { + it("SecretMetadata type does not include plaintext or ciphertext fields", () => { + // This is a compile-time + runtime assertion + const sample: SecretMetadata = { + id: "x", + orgId: "o", + projectId: null, + environmentId: null, + scopeKind: "organization", + secretKey: "k", + displayName: null, + status: "active", + version: 1, + rotationPolicy: null, + lastRotatedAt: null, + expiresAt: null, + createdBy: asUuid("00000000-0000-0000-0000-000000000002"), + createdAt: NOW, + updatedAt: NOW, + }; + const keys = Object.keys(sample); + expect(keys).not.toContain("ciphertextEnvelope"); + expect(keys).not.toContain("ciphertext_envelope"); + expect(keys).not.toContain("plaintext"); + expect(keys).not.toContain("secretValue"); + expect(keys).not.toContain("secret_value"); + expect(keys).not.toContain("value"); + }); + + it("repository read queries never SELECT * for secret_metadata", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECRET_ROW] }); + const repo = createConfigRepository(executor); + + await repo.getSecretMetadata("org-001", "sec-001"); + await repo.listSecretMetadata(ORG_SCOPE, { limit: 10, cursor: null }); + await repo.rotateSecretMetadata("org-001", "sec-001"); + await repo.revokeSecretMetadata("org-001", "sec-001"); + + for (const q of queries) { + expect(q.text).not.toContain("SELECT *"); + expect(q.text).not.toContain("ciphertext_envelope"); + } + }); +}); diff --git a/tests/db/src/d1-adapter.test.ts b/tests/db/src/d1-adapter.test.ts new file mode 100644 index 0000000..e2f691c --- /dev/null +++ b/tests/db/src/d1-adapter.test.ts @@ -0,0 +1,83 @@ +import { createD1Adapter, type D1Binding, type DbHealthResult } from "@saas/db/d1"; +import { isUniqueViolation } from "@saas/db/d1"; + +function bindingThat(outcome: () => Promise): D1Binding { + return { + prepare() { + const statement = { + bind() { + return statement; + }, + all: outcome as () => Promise<{ results?: Record[] }>, + }; + return statement; + }, + } as unknown as D1Binding; +} + +describe("createD1Adapter", () => { + it("reports not-configured when the binding is absent", async () => { + // A worker deployed to an environment whose wrangler config has no + // d1_databases entry: an operator/wiring problem, distinct from a + // database that is present but unreachable. + const result: DbHealthResult = await createD1Adapter(undefined).ping(); + expect(result).toEqual({ configured: false, reachable: false }); + }); + + it("reports configured and reachable when the probe returns", async () => { + let asked = false; + const binding = bindingThat(() => { + asked = true; + return Promise.resolve({ results: [{ ok: 1 }] }); + }); + + expect(await createD1Adapter(binding).ping()).toEqual({ + configured: true, + reachable: true, + }); + expect(asked).toBe(true); + }); + + it("reports configured but unreachable when the probe throws", async () => { + const binding = bindingThat(() => Promise.reject(new Error("D1_ERROR: network"))); + expect(await createD1Adapter(binding).ping()).toEqual({ + configured: true, + reachable: false, + }); + }); + + it("never leaks the underlying error out of ping", async () => { + const binding = bindingThat(() => + Promise.reject(new Error("D1_ERROR: authentication failure token=secret")), + ); + await expect(createD1Adapter(binding).ping()).resolves.toBeDefined(); + }); + + it("dispose resolves", async () => { + await expect(createD1Adapter(undefined).dispose()).resolves.toBeUndefined(); + }); +}); + +describe("isUniqueViolation", () => { + it("recognizes SQLite's unique constraint message", () => { + expect( + isUniqueViolation(new Error("D1_ERROR: UNIQUE constraint failed: identity_users.email_lower")), + ).toBe(true); + }); + + it("recognizes a primary key collision", () => { + expect(isUniqueViolation(new Error("PRIMARY KEY constraint failed: membership_organizations.id"))).toBe( + true, + ); + }); + + it("reads the message off a plain error-shaped object", () => { + expect(isUniqueViolation({ message: "UNIQUE constraint failed: t.c" })).toBe(true); + }); + + it("does not claim unrelated failures", () => { + expect(isUniqueViolation(new Error("no such table: identity_users"))).toBe(false); + expect(isUniqueViolation(new Error("FOREIGN KEY constraint failed"))).toBe(false); + expect(isUniqueViolation(undefined)).toBe(false); + }); +}); diff --git a/tests/db/src/d1-executor.test.ts b/tests/db/src/d1-executor.test.ts new file mode 100644 index 0000000..a060cf3 --- /dev/null +++ b/tests/db/src/d1-executor.test.ts @@ -0,0 +1,161 @@ +import { createSqlExecutor, type D1Binding } from "@saas/db/d1"; + +interface Call { + sql: string; + values: unknown[]; +} + +/** A D1 binding double that records what it was asked to run. */ +function fakeBinding( + rowsFor: (sql: string, values: unknown[]) => Array> | Error = () => [], +): D1Binding & { calls: Call[] } { + const calls: Call[] = []; + return { + calls, + prepare(sql: string) { + let bound: unknown[] = []; + const statement = { + bind(...values: unknown[]) { + bound = values; + return statement; + }, + all() { + calls.push({ sql, values: bound }); + const outcome = rowsFor(sql, bound); + if (outcome instanceof Error) return Promise.reject(outcome); + return Promise.resolve({ results: outcome, success: true }); + }, + }; + return statement; + }, + } as D1Binding & { calls: Call[] }; +} + +describe("createSqlExecutor (D1)", () => { + it("binds numbered placeholders positionally and returns the rows", async () => { + const binding = fakeBinding(() => [{ id: "u-001", name: "test" }]); + const executor = createSqlExecutor(binding); + + const result = await executor.execute( + "SELECT * FROM identity_users WHERE id = $1 AND status = $2", + ["u-001", "active"], + ); + + expect(binding.calls[0]!.sql).toBe( + "SELECT * FROM identity_users WHERE id = ? AND status = ?", + ); + expect(binding.calls[0]!.values).toEqual(["u-001", "active"]); + expect(result.rows).toEqual([{ id: "u-001", name: "test" }]); + expect(result.rowCount).toBe(1); + + await executor.dispose(); + }); + + it("runs a statement with no parameters without calling bind", async () => { + const binding = fakeBinding(() => [{ ok: 1 }]); + const executor = createSqlExecutor(binding); + + const result = await executor.execute("SELECT 1 AS ok"); + + expect(binding.calls[0]!.values).toEqual([]); + expect(result.rowCount).toBe(1); + }); + + it("normalizes bind values that SQLite cannot store natively", async () => { + const binding = fakeBinding(() => []); + const executor = createSqlExecutor(binding); + + await executor.execute("INSERT INTO t (a, b, c, d) VALUES ($1, $2, $3, $4)", [ + new Date("2026-01-01T00:00:00.000Z"), + true, + { nested: 1 }, + undefined, + ]); + + expect(binding.calls[0]!.values).toEqual([ + "2026-01-01T00:00:00.000Z", + 1, + '{"nested":1}', + null, + ]); + }); + + it("reports an empty result as zero rows rather than throwing", async () => { + const executor = createSqlExecutor(fakeBinding(() => [])); + const result = await executor.execute("SELECT * FROM identity_users WHERE id = $1", ["nope"]); + expect(result.rows).toEqual([]); + expect(result.rowCount).toBe(0); + }); + + it("propagates a query failure to the caller", async () => { + const executor = createSqlExecutor( + fakeBinding(() => new Error("D1_ERROR: no such table: identity_users")), + ); + await expect(executor.execute("SELECT 1")).rejects.toThrow(/no such table/); + }); + + describe("transaction", () => { + it("runs the callback's statements against the same database", async () => { + const binding = fakeBinding(() => [{ id: "row-1" }]); + const executor = createSqlExecutor(binding); + + const rows = await executor.transaction(async (tx) => { + const r = await tx.execute("INSERT INTO foo VALUES ($1) RETURNING *", ["bar"]); + return r.rows; + }); + + expect(rows).toEqual([{ id: "row-1" }]); + expect(binding.calls[0]!.sql).toBe("INSERT INTO foo VALUES (?) RETURNING *"); + }); + + it("returns the callback's value", async () => { + const executor = createSqlExecutor(fakeBinding()); + await expect(executor.transaction(async () => "committed")).resolves.toBe("committed"); + }); + + it("propagates a thrown callback", async () => { + const executor = createSqlExecutor(fakeBinding()); + await expect( + executor.transaction(async () => { + throw new Error("business logic failed"); + }), + ).rejects.toThrow("business logic failed"); + }); + + it("does NOT roll back — D1 has no interactive transaction", async () => { + // This is the documented constraint of the Cloudflare-only baseline, + // asserted so a future change to the executor cannot quietly weaken + // (or silently claim to strengthen) it. The first write stays applied. + const binding = fakeBinding(() => []); + const executor = createSqlExecutor(binding); + + await expect( + executor.transaction(async (tx) => { + await tx.execute("INSERT INTO foo VALUES ($1)", ["first"]); + throw new Error("second step failed"); + }), + ).rejects.toThrow("second step failed"); + + expect(binding.calls).toHaveLength(1); + expect(binding.calls[0]!.values).toEqual(["first"]); + }); + }); + + describe("Worker-safe export surface", () => { + it("exports the executor and adapter without dragging in the migration runner", async () => { + const mod = await import("@saas/db/d1"); + const keys = Object.keys(mod); + + expect(keys).toContain("createSqlExecutor"); + expect(keys).toContain("createD1Adapter"); + expect(keys).not.toContain("runMigrations"); + expect(keys).not.toContain("D1ApiAdapter"); + expect(keys).not.toContain("loadD1CredentialsFromEnv"); + }); + + it("dispose resolves — a D1 binding holds nothing to release", async () => { + const executor = createSqlExecutor(fakeBinding()); + await expect(executor.dispose()).resolves.toBeUndefined(); + }); + }); +}); diff --git a/tests/db/src/d1-sql.test.ts b/tests/db/src/d1-sql.test.ts new file mode 100644 index 0000000..be47177 --- /dev/null +++ b/tests/db/src/d1-sql.test.ts @@ -0,0 +1,103 @@ +import { translatePlaceholders, toBindValue } from "@saas/db/d1"; + +describe("translatePlaceholders", () => { + it("rewrites numbered placeholders to positional ones in order", () => { + const { text, values } = translatePlaceholders( + "SELECT * FROM identity_users WHERE id = $1 AND status = $2", + ["u-001", "active"], + ); + expect(text).toBe("SELECT * FROM identity_users WHERE id = ? AND status = ?"); + expect(values).toEqual(["u-001", "active"]); + }); + + it("duplicates the bound value when a placeholder is referenced twice", () => { + // `created_at, updated_at) VALUES ($5, $5)` is the shape that makes + // numbered placeholders worth keeping — positional `?` cannot express it + // without the caller passing the same value twice. + const { text, values } = translatePlaceholders( + "INSERT INTO t (a, created_at, updated_at) VALUES ($1, $2, $2)", + ["a", "2026-01-01T00:00:00.000Z"], + ); + expect(text).toBe("INSERT INTO t (a, created_at, updated_at) VALUES (?, ?, ?)"); + expect(values).toEqual(["a", "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z"]); + }); + + it("reorders bound values to match out-of-order placeholders", () => { + const { text, values } = translatePlaceholders( + "UPDATE identity_sessions SET revoked_at = $2 WHERE id = $1", + ["sess-1", "2026-01-01T00:00:00.000Z"], + ); + expect(text).toBe("UPDATE identity_sessions SET revoked_at = ? WHERE id = ?"); + expect(values).toEqual(["2026-01-01T00:00:00.000Z", "sess-1"]); + }); + + it("leaves a $n inside a string literal alone", () => { + const { text, values } = translatePlaceholders( + "SELECT '$1 is data' AS note WHERE id = $1", + ["u-001"], + ); + expect(text).toBe("SELECT '$1 is data' AS note WHERE id = ?"); + expect(values).toEqual(["u-001"]); + }); + + it("leaves a $n inside a line comment alone", () => { + const { text, values } = translatePlaceholders( + "SELECT 1 -- $9 in a comment\nWHERE id = $1", + ["u-001"], + ); + expect(text).toBe("SELECT 1 -- $9 in a comment\nWHERE id = ?"); + expect(values).toEqual(["u-001"]); + }); + + it("leaves a $n inside a block comment alone", () => { + const { text } = translatePlaceholders("SELECT 1 /* $9 */ WHERE a = $1", ["x"]); + expect(text).toBe("SELECT 1 /* $9 */ WHERE a = ?"); + }); + + it("handles an escaped quote inside a literal without losing the string state", () => { + const { text, values } = translatePlaceholders( + "SELECT 'it''s $2 fine' AS note WHERE id = $1", + ["u-001"], + ); + expect(text).toBe("SELECT 'it''s $2 fine' AS note WHERE id = ?"); + expect(values).toEqual(["u-001"]); + }); + + it("passes through a statement with no placeholders", () => { + const { text, values } = translatePlaceholders("SELECT 1 AS ok", []); + expect(text).toBe("SELECT 1 AS ok"); + expect(values).toEqual([]); + }); + + it("refuses a placeholder with no matching parameter", () => { + expect(() => translatePlaceholders("SELECT * FROM t WHERE id = $2", ["only-one"])).toThrow( + /references \$2 but 1 parameter/, + ); + }); +}); + +describe("toBindValue", () => { + it("passes primitives through untouched", () => { + expect(toBindValue("text")).toBe("text"); + expect(toBindValue(42)).toBe(42); + }); + + it("maps undefined to null so an omitted field is stored as NULL", () => { + expect(toBindValue(undefined)).toBeNull(); + expect(toBindValue(null)).toBeNull(); + }); + + it("serializes a Date to ISO-8601, matching how timestamps are stored", () => { + expect(toBindValue(new Date("2026-01-01T12:00:00.000Z"))).toBe("2026-01-01T12:00:00.000Z"); + }); + + it("maps booleans to 0/1 because SQLite has no boolean type", () => { + expect(toBindValue(true)).toBe(1); + expect(toBindValue(false)).toBe(0); + }); + + it("serializes objects and arrays as JSON text", () => { + expect(toBindValue({ a: 1 })).toBe('{"a":1}'); + expect(toBindValue(["x", "y"])).toBe('["x","y"]'); + }); +}); diff --git a/tests/db/src/events-migration.test.ts b/tests/db/src/events-migration.test.ts new file mode 100644 index 0000000..8ebccef --- /dev/null +++ b/tests/db/src/events-migration.test.ts @@ -0,0 +1,103 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "@saas/db"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve(__dirname, "../../..", "packages/db/src/migrations"); + +describe("030_events_audit_core migration", () => { + const entry = manifest.migrations.find((m) => m.id === "030_events_audit_core"); + const sql = entry + ? readFileSync(resolve(MIGRATIONS_ROOT, entry.path), "utf-8") + : ""; + + it("migration entry exists in manifest", () => { + expect(entry).toBeDefined(); + }); + + it("context is events", () => { + expect(entry!.context).toBe("events"); + }); + + it("manifest ordering includes the new migration after 020", () => { + const ids = manifest.migrations.map((m) => m.id); + const idx020 = ids.indexOf("020_membership_core"); + const idx030 = ids.indexOf("030_events_audit_core"); + expect(idx030).toBeGreaterThan(idx020); + }); + + it("namespaces its tables to the events context", () => { + // SQLite has no schemas, so the bounded-context boundary lives in the + // table name prefix instead of a CREATE SCHEMA. + expect(sql).toContain("CREATE TABLE IF NOT EXISTS events_"); + }); + + it("creates event_log table", () => { + expect(sql).toContain("CREATE TABLE IF NOT EXISTS events_event_log"); + }); + + it("creates audit_entries table", () => { + expect(sql).toContain("CREATE TABLE IF NOT EXISTS events_audit_entries"); + }); + + it("event_log includes org_id column", () => { + expect(sql).toMatch(/org_id\s+TEXT\s+NOT NULL/); + }); + + it("event_log includes project_id and environment_id columns", () => { + expect(sql).toContain("project_id"); + expect(sql).toContain("environment_id"); + }); + + it("audit_entries includes org_id column", () => { + // audit_entries org_id is NOT NULL + expect(sql).toContain("audit_entries"); + expect(sql).toMatch(/org_id\s+TEXT\s+NOT NULL/); + }); + + it("audit_entries references event_log (same-context FK allowed)", () => { + expect(sql).toContain("REFERENCES events_event_log(id)"); + }); + + it("does not contain cross-context foreign keys", () => { + // No FKs to identity, membership, control, projects, billing schemas + expect(sql).not.toContain("REFERENCES identity."); + expect(sql).not.toContain("REFERENCES membership."); + expect(sql).not.toContain("REFERENCES control."); + expect(sql).not.toContain("REFERENCES projects."); + expect(sql).not.toContain("REFERENCES billing."); + }); + + it("DDL is idempotent (IF NOT EXISTS throughout)", () => { + const createStatements = sql.match(/CREATE\s+(TABLE|INDEX)/g) ?? []; + const ifNotExists = sql.match(/IF NOT EXISTS/g) ?? []; + expect(ifNotExists.length).toBeGreaterThanOrEqual(createStatements.length); + }); + + it("includes JSON payload storage", () => { + // JSON documents are TEXT on SQLite; @saas/db/json owns the encode/decode. + expect(sql).toMatch(/payload\s+TEXT/); + }); + + it("includes redaction path storage", () => { + expect(sql).toContain("redact_paths"); + }); + + it("includes organization+time index for event_log", () => { + expect(sql).toContain("event_log_org_occurred_idx"); + }); + + it("includes organization+time index for audit_entries", () => { + expect(sql).toContain("audit_entries_org_occurred_idx"); + }); + + it("includes target lookup index for audit_entries", () => { + expect(sql).toContain("audit_entries_target_idx"); + }); + + it("includes trace fields (request_id)", () => { + expect(sql).toContain("request_id"); + expect(sql).toContain("correlation_id"); + }); +}); diff --git a/tests/db/src/events.test.ts b/tests/db/src/events.test.ts new file mode 100644 index 0000000..c08c594 --- /dev/null +++ b/tests/db/src/events.test.ts @@ -0,0 +1,633 @@ +import { + createEventsRepository, +} from "@saas/db/events"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; + callResponses?: Array<{ rows?: Record[]; rowCount?: number; error?: unknown }>; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + let callIndex = 0; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + + if (options?.callResponses && callIndex < options.callResponses.length) { + const response = options.callResponses[callIndex]!; + callIndex++; + if (response.error) throw response.error; + const rows = (response.rows ?? []) as unknown as T[]; + return { rows, rowCount: response.rowCount ?? rows.length }; + } + + if (options?.error) throw options.error; + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); + +const SAMPLE_EVENT_ROW = { + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurred_at: NOW.toISOString(), + actor_type: "user", + actor_id: "usr-001", + actor_session_id: "ses-001", + actor_ip: "203.0.113.10", + org_id: "org-001", + project_id: null, + environment_id: null, + subject_kind: "organization", + subject_id: "org-001", + subject_name: "Acme Corp", + request_id: "req-001", + correlation_id: "cor-001", + causation_id: null, + idempotency_key: "idem-001", + payload: JSON.stringify({ name: "Acme Corp" }), + redact_paths: JSON.stringify([]), + created_at: NOW.toISOString(), +}; + +const SAMPLE_AUDIT_ROW_DATA = { + id: "aud-001", + event_id: "evt-001", + org_id: "org-001", + project_id: null, + environment_id: null, + actor_type: "user", + actor_id: "usr-001", + event_type: "organization.created", + event_version: 1, + source: "membership-worker", + subject_kind: "organization", + subject_id: "org-001", + subject_name: "Acme Corp", + category: "general", + description: "Organization created", + occurred_at: NOW.toISOString(), + request_id: "req-001", + correlation_id: "cor-001", + payload: JSON.stringify({ name: "Acme Corp" }), + redact_paths: JSON.stringify(["$.payload.secret"]), + created_at: NOW.toISOString(), +}; + +const SAMPLE_AUDIT_ROW = { ...SAMPLE_AUDIT_ROW_DATA }; + +const SAMPLE_EVENT_WITH_AUDIT_ROW = { + _event: SAMPLE_EVENT_ROW, + _audit: SAMPLE_AUDIT_ROW_DATA, +}; + +describe("events repository: appendEvent", () => { + it("inserts an event and returns the mapped entity", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_EVENT_ROW] }); + const repo = createEventsRepository(executor); + + const result = await repo.appendEvent({ + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + actorSessionId: "ses-001", + actorIp: "203.0.113.10", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + subjectName: "Acme Corp", + requestId: "req-001", + correlationId: "cor-001", + idempotencyKey: "idem-001", + payload: { name: "Acme Corp" }, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("evt-001"); + expect(result.value.type).toBe("organization.created"); + expect(result.value.orgId).toBe("org-001"); + expect(result.value.actorType).toBe("user"); + expect(result.value.payload).toEqual({ name: "Acme Corp" }); + } + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("INSERT INTO events_event_log"); + expect(queries[0]!.text).toContain("ON CONFLICT (id) DO NOTHING"); + }); + + it("uses parameterized SQL", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_EVENT_ROW] }); + const repo = createEventsRepository(executor); + + await repo.appendEvent({ + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + requestId: "req-001", + payload: { name: "Acme Corp" }, + }); + + // Params array should contain the values, not interpolated into SQL + expect(queries[0]!.params.length).toBeGreaterThan(0); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).not.toContain("evt-001"); + }); + + it("returns conflict on duplicate event ID (no rows returned)", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + const result = await repo.appendEvent({ + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + requestId: "req-001", + payload: {}, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns conflict on a SQLite unique-constraint failure", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createEventsRepository(executor); + + const result = await repo.appendEvent({ + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + requestId: "req-001", + payload: {}, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("serializes JSON payload and redact paths", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_EVENT_ROW] }); + const repo = createEventsRepository(executor); + + await repo.appendEvent({ + id: "evt-001", + type: "test.event", + version: 1, + source: "test", + occurredAt: NOW, + actorType: "system", + actorId: "sys", + orgId: "org-001", + subjectKind: "test", + subjectId: "t-1", + requestId: "req-001", + payload: { key: "value" }, + redactPaths: ["$.payload.key"], + }); + + const params = queries[0]!.params; + // payload should be JSON string + expect(params[19]).toBe(JSON.stringify({ key: "value" })); + // redactPaths should be JSON string + expect(params[20]).toBe(JSON.stringify(["$.payload.key"])); + }); +}); + +describe("events repository: appendEventWithAudit", () => { + it("inserts event and audit in one SQL statement", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [SAMPLE_EVENT_WITH_AUDIT_ROW], + }); + const repo = createEventsRepository(executor); + + const result = await repo.appendEventWithAudit({ + event: { + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + actorSessionId: "ses-001", + actorIp: "203.0.113.10", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + subjectName: "Acme Corp", + requestId: "req-001", + correlationId: "cor-001", + payload: { name: "Acme Corp" }, + }, + audit: { + id: "aud-001", + category: "general", + description: "Organization created", + }, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.event.id).toBe("evt-001"); + expect(result.value.audit.id).toBe("aud-001"); + expect(result.value.audit.eventId).toBe("evt-001"); + } + // Only one SQL call (CTE) + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("WITH inserted_event AS"); + expect(queries[0]!.text).toContain("inserted_audit AS"); + }); + + it("returns conflict when event already exists (no event row returned)", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + const result = await repo.appendEventWithAudit({ + event: { + id: "evt-001", + type: "organization.created", + version: 1, + source: "membership-worker", + occurredAt: NOW, + actorType: "user", + actorId: "usr-001", + orgId: "org-001", + subjectKind: "organization", + subjectId: "org-001", + requestId: "req-001", + payload: {}, + }, + audit: { id: "aud-001" }, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); +}); + +describe("events repository: queryAuditByOrg", () => { + it("queries audit entries by organization with cursor pagination", async () => { + const rows = [ + { ...SAMPLE_AUDIT_ROW, id: "aud-001" }, + { ...SAMPLE_AUDIT_ROW, id: "aud-002" }, + ]; + const { executor, queries } = createFakeExecutor({ rows }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).toBeNull(); + } + expect(queries[0]!.text).toContain("WHERE org_id IN ($1, $2)"); + expect(queries[0]!.text).toContain("ORDER BY occurred_at DESC, id DESC"); + expect(queries[0]!.params[0]).toBe("org-001"); + // Legacy org_ format for backward compatibility + expect(queries[0]!.params[1]).toBe("org_org001"); + // limit + 1 to detect next page + expect(queries[0]!.params[2]).toBe(11); + }); + + it("returns nextCursor when more items exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_AUDIT_ROW, + id: `aud-${String(i).padStart(3, "0")}`, + occurred_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("aud-001"); + } + }); + + it("applies cursor condition when provided", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { + limit: 10, + cursor: { occurredAt: "2026-01-15T09:00:00Z", id: "aud-005" }, + }); + + expect(queries[0]!.text).toContain("(occurred_at, id) < ($4, $5)"); + expect(queries[0]!.params[3]).toBe("2026-01-15T09:00:00Z"); + expect(queries[0]!.params[4]).toBe("aud-005"); + }); + + it("filters by category when provided", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, "membership"); + + expect(queries[0]!.text).toContain("category = $3"); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("org_org001"); + expect(queries[0]!.params[2]).toBe("membership"); + expect(queries[0]!.params[3]).toBe(11); + }); + + it("applies both category and cursor conditions", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { + limit: 5, + cursor: { occurredAt: "2026-01-15T09:00:00Z", id: "aud-010" }, + }, "projects"); + + expect(queries[0]!.text).toContain("category = $3"); + expect(queries[0]!.text).toContain("(occurred_at, id) < ($5, $6)"); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[1]).toBe("org_org001"); + expect(queries[0]!.params[2]).toBe("projects"); + expect(queries[0]!.params[3]).toBe(6); + expect(queries[0]!.params[4]).toBe("2026-01-15T09:00:00Z"); + expect(queries[0]!.params[5]).toBe("aud-010"); + }); + + it("does not add category clause when category is undefined", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, undefined); + + expect(queries[0]!.text).not.toContain("category"); + }); + + it("returns safe internal error on query failure", async () => { + const { executor } = createFakeExecutor({ rows: [], error: new Error("db crash") }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, "membership"); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + } + }); + + it("filters by actor, subject, and event type with parameterized equality", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, undefined, { + actorId: "usr-123", + actorType: "user", + subjectKind: "project", + subjectId: "prj-9", + eventType: "member.role_changed", + }); + + const text = queries[0]!.text; + expect(text).toContain("actor_id = $3"); + expect(text).toContain("actor_type = $4"); + expect(text).toContain("subject_kind = $5"); + expect(text).toContain("subject_id = $6"); + expect(text).toContain("event_type = $7"); + expect(text).not.toContain("usr-123"); + expect(text).not.toContain("member.role_changed"); + expect(queries[0]!.params.slice(2, 7)).toEqual([ + "usr-123", + "user", + "project", + "prj-9", + "member.role_changed", + ]); + expect(queries[0]!.params[7]).toBe(11); + }); + + it("applies an inclusive occurred_at time window for from/to", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, undefined, { + from: "2026-01-01T00:00:00.000Z", + to: "2026-02-01T00:00:00.000Z", + }); + + const text = queries[0]!.text; + expect(text).toContain("occurred_at >= $3"); + expect(text).toContain("occurred_at <= $4"); + expect(queries[0]!.params[2]).toBe("2026-01-01T00:00:00.000Z"); + expect(queries[0]!.params[3]).toBe("2026-02-01T00:00:00.000Z"); + }); + + it("composes category + filters + cursor without altering ORDER BY", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg( + "org-001", + { limit: 5, cursor: { occurredAt: "2026-01-15T09:00:00Z", id: "aud-010" } }, + "membership", + { actorType: "service_principal", from: "2026-01-01T00:00:00.000Z" }, + ); + + const text = queries[0]!.text; + expect(text).toContain("WHERE org_id IN ($1, $2)"); + expect(text).toContain("category = $3"); + expect(text).toContain("actor_type = $4"); + expect(text).toContain("occurred_at >= $5"); + expect(text).toContain("ORDER BY occurred_at DESC, id DESC"); + expect(queries[0]!.params[0]).toBe("org-001"); + expect(queries[0]!.params[2]).toBe("membership"); + expect(queries[0]!.params[3]).toBe("service_principal"); + expect(queries[0]!.params[4]).toBe("2026-01-01T00:00:00.000Z"); + expect(queries[0]!.params[5]).toBe(6); + expect(queries[0]!.params[6]).toBe("2026-01-15T09:00:00Z"); + expect(queries[0]!.params[7]).toBe("aud-010"); + }); + + it("adds no filter clauses when filters is empty", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }, undefined, {}); + + const text = queries[0]!.text; + expect(text).not.toContain("actor_id"); + expect(text).not.toContain("occurred_at >="); + expect(queries[0]!.params[2]).toBe(11); + }); +}); + +describe("events repository: queryAuditByTarget", () => { + it("queries by org + subject kind/id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_AUDIT_ROW] }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByTarget("org-001", "organization", "org-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.items[0]!.subjectKind).toBe("organization"); + } + expect(queries[0]!.text).toContain("subject_kind = $2"); + expect(queries[0]!.text).toContain("subject_id = $3"); + expect(queries[0]!.params[1]).toBe("organization"); + expect(queries[0]!.params[2]).toBe("org-001"); + }); + + it("applies cursor for target queries", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByTarget("org-001", "member", "mem-001", { + limit: 5, + cursor: { occurredAt: "2026-01-15T09:00:00Z", id: "aud-010" }, + }); + + expect(queries[0]!.text).toContain("(occurred_at, id) < ($5, $6)"); + expect(queries[0]!.params[4]).toBe("2026-01-15T09:00:00Z"); + expect(queries[0]!.params[5]).toBe("aud-010"); + }); +}); + +describe("events repository: JSON handling", () => { + it("deserializes JSON string payload from database", async () => { + const row = { ...SAMPLE_AUDIT_ROW, payload: '{"complex":{"nested":true}}' }; + const { executor } = createFakeExecutor({ rows: [row] }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items[0]!.payload).toEqual({ complex: { nested: true } }); + } + }); + + it("deserializes object payload from database (pre-parsed by driver)", async () => { + const row = { ...SAMPLE_AUDIT_ROW, payload: { already: "parsed" } }; + const { executor } = createFakeExecutor({ rows: [row] }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items[0]!.payload).toEqual({ already: "parsed" }); + } + }); + + it("preserves redaction paths", async () => { + const row = { ...SAMPLE_AUDIT_ROW, redact_paths: JSON.stringify(["$.payload.secret", "$.payload.token"]) }; + const { executor } = createFakeExecutor({ rows: [row] }); + const repo = createEventsRepository(executor); + + const result = await repo.queryAuditByOrg("org-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items[0]!.redactPaths).toEqual(["$.payload.secret", "$.payload.token"]); + } + }); + + it("queries both raw UUID and legacy org_ format for backward compatibility", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + await repo.queryAuditByOrg("a1b2c3d4-e5f6-7890-abcd-ef1234567890", { limit: 10, cursor: null }); + + // Must use IN clause with both formats + expect(queries[0]!.text).toContain("WHERE org_id IN ($1, $2)"); + expect(queries[0]!.params[0]).toBe("a1b2c3d4-e5f6-7890-abcd-ef1234567890"); + expect(queries[0]!.params[1]).toBe("org_a1b2c3d4e5f67890abcdef1234567890"); + }); +}); + +describe("events repository: getEventById", () => { + it("returns the mapped event when the row exists", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_EVENT_ROW] }); + const repo = createEventsRepository(executor); + + const result = await repo.getEventById("org-001", "evt-001"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).not.toBeNull(); + expect(result.value!.id).toBe("evt-001"); + expect(result.value!.type).toBe("organization.created"); + // Full payload is rehydrated — this is what makes manual replay + // resend the original body rather than data:{}. + expect(result.value!.payload).toEqual({ name: "Acme Corp" }); + } + // Parameterized, org-scoped lookup by id. + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("FROM events_event_log"); + expect(queries[0]!.params).toEqual(["org-001", "evt-001"]); + }); + + it("returns null when no row matches (absent, not an error)", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createEventsRepository(executor); + + const result = await repo.getEventById("org-001", "evt-missing"); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBeNull(); + }); + + it("surfaces a safe error when the query throws", async () => { + const { executor } = createFakeExecutor({ error: new Error("connection lost") }); + const repo = createEventsRepository(executor); + + const result = await repo.getEventById("org-001", "evt-001"); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).toBe("Failed to get event by id"); + } + }); +}); diff --git a/tests/db/src/identity-migration.test.ts b/tests/db/src/identity-migration.test.ts new file mode 100644 index 0000000..09f3730 --- /dev/null +++ b/tests/db/src/identity-migration.test.ts @@ -0,0 +1,306 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "@saas/db"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve( + __dirname, + "../../..", + "packages/db/src/migrations", +); + +describe("Identity Migration Verification", () => { + const identityMigrations = manifest.migrations.filter( + (m) => m.context === "identity", + ); + + it("has at least one identity migration", () => { + expect(identityMigrations.length).toBeGreaterThan(0); + }); + + it("identity migration has context 'identity'", () => { + for (const m of identityMigrations) { + expect(m.context).toBe("identity"); + } + }); + + it("identity migration is ordered after control migrations", () => { + const ids = manifest.migrations.map((m) => m.id); + const controlIdx = ids.indexOf("000_control_baseline"); + const identityIdx = ids.indexOf("010_identity_core"); + + expect(identityIdx).toBeGreaterThan(controlIdx); + }); + + describe("identity SQL schema validation", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "010_identity_core/up.sql"), + "utf-8", + ); + + it("namespaces its tables to the identity context", () => { + // SQLite has no schemas — the context boundary is the name prefix. + expect(sql).toContain("CREATE TABLE IF NOT EXISTS identity_"); + }); + + it("creates identity_users table", () => { + expect(sql).toContain("identity_users"); + }); + + it("creates identity_auth_identities table", () => { + expect(sql).toContain("identity_auth_identities"); + }); + + it("creates identity_login_challenges table", () => { + expect(sql).toContain("identity_login_challenges"); + }); + + it("creates identity_sessions table", () => { + expect(sql).toContain("identity_sessions"); + }); + + it("stores only hashed codes, never raw values", () => { + expect(sql).toContain("code_hash"); + expect(sql).not.toMatch(/\bcode\b\s+TEXT/); + }); + + it("stores only hashed tokens, never raw values", () => { + expect(sql).toContain("token_hash"); + expect(sql).not.toMatch(/\btoken\b\s+TEXT/); + }); + + it("uses normalized email column for lookup", () => { + expect(sql).toContain("email_lower"); + expect(sql).toContain("users_email_lower_idx"); + }); + + it("uses IF NOT EXISTS for idempotency", () => { + const createStatements = sql.match(/CREATE\s+(TABLE|SCHEMA|INDEX)/g) ?? []; + const ifNotExists = sql.match(/IF NOT EXISTS/g) ?? []; + expect(ifNotExists.length).toBeGreaterThanOrEqual(createStatements.length); + }); + + it("does not reference cross-context tables", () => { + expect(sql).not.toContain("membership."); + expect(sql).not.toContain("projects."); + expect(sql).not.toContain("billing."); + expect(sql).not.toContain("events."); + }); + + it("does not require extensions like citext", () => { + expect(sql).not.toContain("CREATE EXTENSION"); + expect(sql).not.toContain("citext"); + }); + + it("foreign keys stay within identity context", () => { + const fkMatches = sql.match(/REFERENCES\s+(\w+\.\w+)/g) ?? []; + for (const fk of fkMatches) { + expect(fk).toContain("identity."); + } + }); + }); + + describe("project-scoped invariant still applies only to projects context", () => { + it("identity migrations are not subject to project-scoped org_id/project_id check", () => { + expect(identityMigrations.every((m) => m.context === "identity")).toBe(true); + expect(identityMigrations.some((m) => m.context === "projects")).toBe(false); + }); + }); + + describe("050_identity_security_events SQL schema validation", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "050_identity_security_events/up.sql"), + "utf-8", + ); + + it("creates identity_security_events table", () => { + expect(sql).toContain("identity_security_events"); + }); + + it("has all expected columns", () => { + const expectedColumns = [ + "id", "event_type", "outcome", "user_id", "session_id", + "challenge_id", "request_id", "correlation_id", "ip", + "user_agent", "occurred_at", "created_at", "metadata", "redact_paths", + ]; + for (const col of expectedColumns) { + expect(sql).toContain(col); + } + }); + + it("stores JSON metadata for flexible payloads", () => { + expect(sql).toMatch(/metadata\s+TEXT/); + }); + + it("stores JSON redact_paths for compliance", () => { + expect(sql).toMatch(/redact_paths\s+TEXT/); + }); + + it("does not store raw secret columns", () => { + const secretPatterns = [ + /\bcode\b\s+TEXT/, + /\btoken\b\s+TEXT/, + /\bbearer_token\b/, + /\btoken_hash\b/, + /\bcode_hash\b/, + /\bapi_key\b/, + /\bsecret\b\s+TEXT/, + ]; + for (const pattern of secretPatterns) { + expect(sql).not.toMatch(pattern); + } + }); + + it("does not require org_id", () => { + expect(sql).not.toMatch(/org_id\s+\w+\s+NOT NULL/); + }); + + it("uses IF NOT EXISTS for idempotency", () => { + const createStatements = sql.match(/CREATE\s+(TABLE|INDEX)/g) ?? []; + const ifNotExists = sql.match(/IF NOT EXISTS/g) ?? []; + expect(ifNotExists.length).toBeGreaterThanOrEqual(createStatements.length); + }); + + it("does not reference cross-context tables", () => { + expect(sql).not.toContain("membership."); + expect(sql).not.toContain("projects."); + expect(sql).not.toContain("billing."); + expect(sql).not.toContain("events."); + }); + + it("creates user+time index for cursor pagination", () => { + expect(sql).toContain("security_events_user_occurred_idx"); + expect(sql).toMatch(/user_id.*occurred_at\s+DESC.*id\s+DESC/); + }); + + it("creates event type index", () => { + expect(sql).toContain("security_events_event_type_idx"); + }); + + it("creates request_id index for trace lookups", () => { + expect(sql).toContain("security_events_request_id_idx"); + }); + + it("uses a text primary key holding a UUID", () => { + expect(sql).toMatch(/id\s+TEXT\s+PRIMARY KEY/); + }); + + it("foreign keys stay within identity context if any exist", () => { + const fkMatches = sql.match(/REFERENCES\s+(\w+\.\w+)/g) ?? []; + for (const fk of fkMatches) { + expect(fk).toContain("identity."); + } + }); + }); + + describe("060_identity_api_keys SQL schema validation", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "060_identity_api_keys/up.sql"), + "utf-8", + ); + + it("creates identity_service_principals table", () => { + expect(sql).toContain("identity_service_principals"); + }); + + it("creates identity_api_keys table", () => { + expect(sql).toContain("identity_api_keys"); + }); + + it("service principals have org_id NOT NULL for organization binding", () => { + expect(sql).toMatch(/org_id\s+TEXT\s+NOT NULL/); + }); + + it("service principals have optional project_id scope", () => { + expect(sql).toMatch(/project_id\s+TEXT/); + // project_id should NOT be NOT NULL + expect(sql).not.toMatch(/project_id\s+TEXT\s+NOT NULL/); + }); + + it("enforces project scope requires org scope via CHECK constraint", () => { + expect(sql).toContain("service_principals_project_scope_check"); + }); + + it("API keys store only hash and prefix, never raw key material", () => { + expect(sql).toContain("key_hash"); + expect(sql).toContain("key_prefix"); + // No raw key/secret/token columns + expect(sql).not.toMatch(/\bkey_value\b/); + expect(sql).not.toMatch(/\braw_key\b/); + expect(sql).not.toMatch(/\bsecret\b\s+TEXT/); + expect(sql).not.toMatch(/\bbearer_token\b/); + }); + + it("API keys have key_prefix length constraint (4-12 chars)", () => { + expect(sql).toContain("api_keys_prefix_length"); + }); + + it("API keys have unique hash index for auth-time lookup", () => { + expect(sql).toContain("api_keys_key_hash_idx"); + }); + + it("API keys belong to a service principal via FK", () => { + expect(sql).toMatch(/REFERENCES\s+identity_service_principals/); + }); + + it("has org-scoped index for API key listing", () => { + expect(sql).toContain("api_keys_org_id_idx"); + }); + + it("has service principal index for key listing", () => { + expect(sql).toContain("api_keys_service_principal_idx"); + }); + + it("has prefix index for key identification", () => { + expect(sql).toContain("api_keys_prefix_idx"); + }); + + it("uses IF NOT EXISTS for idempotency", () => { + const createStatements = sql.match(/CREATE\s+(TABLE|INDEX)/g) ?? []; + const ifNotExists = sql.match(/IF NOT EXISTS/g) ?? []; + expect(ifNotExists.length).toBeGreaterThanOrEqual(createStatements.length); + }); + + it("does not reference cross-context tables", () => { + expect(sql).not.toContain("membership."); + expect(sql).not.toContain("projects."); + expect(sql).not.toContain("billing."); + expect(sql).not.toContain("events."); + }); + + it("foreign keys stay within identity context", () => { + const fkMatches = sql.match(/REFERENCES\s+(\w+)/g) ?? []; + expect(fkMatches.length).toBeGreaterThan(0); + for (const fk of fkMatches) { + expect(fk).toMatch(/REFERENCES\s+identity_/); + } + }); + + it("uses text primary keys holding UUIDs", () => { + const pkMatches = sql.match(/id\s+TEXT\s+PRIMARY KEY/g) ?? []; + expect(pkMatches.length).toBe(2); // service_principals + api_keys + }); + + it("API keys have status constraint (active/revoked/expired)", () => { + expect(sql).toContain("api_keys_status_check"); + }); + + it("service principals have status constraint (active/suspended/deleted)", () => { + expect(sql).toContain("service_principals_status_check"); + }); + + it("API keys support revocation tracking", () => { + expect(sql).toContain("revoked_at"); + expect(sql).toContain("revoked_by"); + }); + + it("API keys support expiry tracking", () => { + expect(sql).toContain("expires_at"); + }); + + it("API keys support usage tracking", () => { + expect(sql).toContain("last_used_at"); + }); + }); +}); diff --git a/tests/db/src/identity.test.ts b/tests/db/src/identity.test.ts new file mode 100644 index 0000000..3f644f8 --- /dev/null +++ b/tests/db/src/identity.test.ts @@ -0,0 +1,1418 @@ +import { + createIdentityRepository, +} from "@saas/db/identity"; +import { asUuid } from "@saas/db"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +const ORG_UUID = asUuid("00000000-0000-4000-8000-000000000001"); +const USER_UUID = asUuid("00000000-0000-4000-8000-000000000002"); +const PROJECT_UUID = asUuid("00000000-0000-4000-8000-000000000003"); +const REVOKER_UUID = asUuid("00000000-0000-4000-8000-000000000004"); + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + if (options?.error) { + throw options.error; + } + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); +const FUTURE = new Date("2099-01-15T11:00:00Z"); +const PAST = new Date("2020-01-15T09:00:00Z"); + +const SAMPLE_USER_ROW = { + id: "u-001", + email: "Test@Example.com", + email_lower: "test@example.com", + display_name: "Test User", + status: "active", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_AUTH_IDENTITY_ROW = { + id: "ai-001", + user_id: "u-001", + provider: "email", + subject: "test@example.com", + metadata: {}, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_CHALLENGE_ROW = { + id: "ch-001", + user_id: "u-001", + method: "email_code", + expires_at: FUTURE.toISOString(), + consumed_at: null, + created_at: NOW.toISOString(), +}; + +const SAMPLE_SESSION_ROW = { + id: "sess-001", + user_id: "u-001", + expires_at: FUTURE.toISOString(), + revoked_at: null, + created_at: NOW.toISOString(), + last_seen_at: NOW.toISOString(), +}; + +const SAMPLE_SECURITY_EVENT_ROW = { + id: "se-001", + event_type: "login.completed", + outcome: "success", + user_id: "u-001", + session_id: "sess-001", + challenge_id: "ch-001", + request_id: "req-001", + correlation_id: "cor-001", + ip: "192.168.1.1", + user_agent: "Mozilla/5.0", + occurred_at: NOW.toISOString(), + created_at: NOW.toISOString(), + metadata: JSON.stringify({ provider: "email" }), + redact_paths: JSON.stringify(["/metadata/provider"]), +}; + +describe("IdentityRepository", () => { + describe("createUser", () => { + it("uses parameterized query for user creation", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_USER_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.createUser({ + id: "u-001", + email: "Test@Example.com", + emailLower: "test@example.com", + displayName: "Test User", + createdAt: NOW, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.params).toEqual([ + "u-001", + "Test@Example.com", + "test@example.com", + "Test User", + NOW.toISOString(), + ]); + }); + + it("maps returned row to User type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_USER_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createUser({ + id: "u-001", + email: "Test@Example.com", + emailLower: "test@example.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("u-001"); + expect(result.value.email).toBe("Test@Example.com"); + expect(result.value.emailLower).toBe("test@example.com"); + expect(result.value.status).toBe("active"); + expect(result.value.createdAt).toEqual(NOW); + } + }); + + it("returns conflict on duplicate user", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.createUser({ + id: "u-001", + email: "Test@Example.com", + emailLower: "test@example.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns conflict on unique violation error code", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createUser({ + id: "u-001", + email: "Test@Example.com", + emailLower: "test@example.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ + error: new Error("connection to host 10.0.0.1:5432 refused"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createUser({ + id: "u-001", + email: "a@b.com", + emailLower: "a@b.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("10.0.0.1"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("5432"); + } + }); + }); + + describe("getUserById", () => { + it("uses parameterized query for lookup", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_USER_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.getUserById("u-001"); + + expect(queries[0]!.params).toEqual(["u-001"]); + expect(queries[0]!.text).toContain("$1"); + }); + + it("returns not_found when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getUserById("u-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("getUserByEmail", () => { + it("uses normalized email in parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_USER_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.getUserByEmail("test@example.com"); + + expect(queries[0]!.params).toEqual(["test@example.com"]); + expect(queries[0]!.text).toContain("email_lower"); + }); + + it("returns not_found for unknown email", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getUserByEmail("unknown@example.com"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("createAuthIdentity", () => { + it("uses parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_AUTH_IDENTITY_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.createAuthIdentity({ + id: "ai-001", + userId: "u-001", + provider: "email", + subject: "test@example.com", + createdAt: NOW, + }); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.params[2]).toBe("email"); + expect(queries[0]!.params[3]).toBe("test@example.com"); + }); + + it("returns conflict on duplicate provider+subject", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createAuthIdentity({ + id: "ai-002", + userId: "u-001", + provider: "email", + subject: "test@example.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("getAuthIdentityByProviderSubject", () => { + it("uses parameterized query with provider and subject", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_AUTH_IDENTITY_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.getAuthIdentityByProviderSubject("email", "test@example.com"); + + expect(queries[0]!.params).toEqual(["email", "test@example.com"]); + }); + + it("returns not_found for unknown provider+subject", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getAuthIdentityByProviderSubject("oauth", "unknown"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("createLoginChallenge", () => { + it("stores hashed code via parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_CHALLENGE_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.createLoginChallenge({ + id: "ch-001", + userId: "u-001", + method: "email_code", + codeHash: "sha256-hashed-code", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(queries[0]!.params[3]).toBe("sha256-hashed-code"); + expect(queries[0]!.text).toContain("$4"); + }); + }); + + describe("getLoginChallengeById", () => { + it("returns challenge for valid unconsumed challenge", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_CHALLENGE_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getLoginChallengeById("ch-001"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("ch-001"); + expect(result.value).not.toHaveProperty("codeHash"); + } + }); + + it("returns already_consumed for consumed challenge", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_CHALLENGE_ROW, consumed_at: NOW.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.getLoginChallengeById("ch-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("already_consumed"); + }); + + it("returns expired for expired challenge", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_CHALLENGE_ROW, expires_at: PAST.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.getLoginChallengeById("ch-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + }); + + it("returns not_found for missing challenge", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getLoginChallengeById("ch-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("consumeLoginChallenge", () => { + it("uses parameterized update with code_hash and consumed_at IS NULL guard", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_CHALLENGE_ROW, consumed_at: NOW.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + await repo.consumeLoginChallenge("ch-001", "sha256-hashed-code", NOW); + + expect(queries[0]!.text).toContain("code_hash = $2"); + expect(queries[0]!.text).toContain("consumed_at IS NULL"); + expect(queries[0]!.params).toEqual(["ch-001", "sha256-hashed-code", NOW.toISOString()]); + }); + + it("returns already_consumed when no rows affected", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.consumeLoginChallenge("ch-001", "sha256-hashed-code", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("already_consumed"); + }); + + it("does not expose codeHash in returned challenge", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_CHALLENGE_ROW, consumed_at: NOW.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.consumeLoginChallenge("ch-001", "sha256-hashed-code", NOW); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).not.toHaveProperty("codeHash"); + } + }); + }); + + describe("createSession", () => { + it("stores hashed token via parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SESSION_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.createSession({ + id: "sess-001", + userId: "u-001", + tokenHash: "sha256-hashed-token", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(queries[0]!.params[2]).toBe("sha256-hashed-token"); + expect(queries[0]!.text).toContain("$3"); + }); + + it("returns conflict on duplicate token hash", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createSession({ + id: "sess-002", + userId: "u-001", + tokenHash: "sha256-hashed-token", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("getSessionByTokenHash", () => { + it("uses parameterized query with token hash", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SESSION_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.getSessionByTokenHash("sha256-hashed-token"); + + expect(queries[0]!.params).toEqual(["sha256-hashed-token"]); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + }); + + it("returns not_found for unknown token hash", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionByTokenHash("unknown-hash"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns expired for expired session", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_SESSION_ROW, expires_at: PAST.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + }); + + it("does not expose tokenHash in returned session", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SESSION_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).not.toHaveProperty("tokenHash"); + } + }); + }); + + describe("getSessionWithUserByTokenHash (PERF12d JOIN)", () => { + const SAMPLE_JOINED_ROW = { + // session columns, aliased as the JOIN selects them + session_id: "sess-001", + session_user_id: "u-001", + session_expires_at: FUTURE.toISOString(), + session_revoked_at: null, + session_created_at: NOW.toISOString(), + session_last_seen_at: NOW.toISOString(), + // the joined `u.*` user columns (id: "u-001", email, created_at, …) + ...SAMPLE_USER_ROW, + }; + + it("JOINs sessions to users in one parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_JOINED_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.getSessionWithUserByTokenHash("sha256-hashed-token"); + + expect(queries[0]!.params).toEqual(["sha256-hashed-token"]); + expect(queries[0]!.text).toContain("JOIN identity_users"); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + }); + + it("splits the joined row into session + user with no column collision", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_JOINED_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionWithUserByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(true); + if (result.ok) { + // session.id must come from session_id, NOT the user's id ("u-001"). + expect(result.value.session.id).toBe("sess-001"); + expect(result.value.session.userId).toBe("u-001"); + expect(result.value.user.id).toBe("u-001"); + expect(result.value.user.email).toBe("Test@Example.com"); + expect(result.value.session).not.toHaveProperty("tokenHash"); + } + }); + + it("returns not_found for unknown token hash", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionWithUserByTokenHash("unknown-hash"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns expired for an expired session", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_JOINED_ROW, session_expires_at: PAST.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.getSessionWithUserByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + }); + }); + + describe("revokeSession", () => { + it("uses parameterized update with revoked_at IS NULL guard", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_SESSION_ROW, revoked_at: NOW.toISOString() }], + }); + const repo = createIdentityRepository(executor); + + await repo.revokeSession("sess-001", NOW); + + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + expect(queries[0]!.params).toEqual(["sess-001", NOW.toISOString()]); + }); + + it("returns not_found when session already revoked", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.revokeSession("sess-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("safe error handling", () => { + it("never exposes raw SQL errors in repository outputs", async () => { + const pgError = new Error( + 'relation "identity_users" does not exist at character 15', + ); + const { executor } = createFakeExecutor({ error: pgError }); + const repo = createIdentityRepository(executor); + + const result = await repo.getUserById("u-001"); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("relation"); + expect(result.error.message).not.toContain("character 15"); + } + }); + + it("never exposes connection strings in errors", async () => { + const connError = new Error( + "could not connect to postgres://admin:secret@db.internal:5432/prod", + ); + const { executor } = createFakeExecutor({ error: connError }); + const repo = createIdentityRepository(executor); + + const result = await repo.createUser({ + id: "u-001", + email: "a@b.com", + emailLower: "a@b.com", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("admin"); + expect(result.error.message).not.toContain("secret"); + expect(result.error.message).not.toContain("db.internal"); + } + }); + + it("never exposes token hashes in error outputs", async () => { + const { executor } = createFakeExecutor({ + error: new Error("duplicate key value (token_hash)=(abc123secret)"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createSession({ + id: "sess-001", + userId: "u-001", + tokenHash: "abc123secret", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + const serialized = JSON.stringify(result.error); + expect(serialized).not.toContain("abc123secret"); + } + }); + }); + + describe("Worker-safe import isolation", () => { + it("does not import runner-only modules", async () => { + const mod = await import("@saas/db/identity"); + const exportKeys = Object.keys(mod); + + expect(exportKeys).toContain("createIdentityRepository"); + expect(exportKeys).not.toContain("runMigrations"); + expect(exportKeys).not.toContain("D1ApiAdapter"); + expect(exportKeys).not.toContain("loadD1CredentialsFromEnv"); + }); + }); + + describe("recordSecurityEvent", () => { + it("uses parameterized query for insert", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + userId: "u-001", + sessionId: "sess-001", + challengeId: "ch-001", + requestId: "req-001", + correlationId: "cor-001", + ip: "192.168.1.1", + userAgent: "Mozilla/5.0", + occurredAt: NOW, + metadata: { provider: "email" }, + redactPaths: ["/metadata/provider"], + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$13"); + expect(queries[0]!.text).toContain("identity_security_events"); + expect(queries[0]!.params[0]).toBe("se-001"); + expect(queries[0]!.params[1]).toBe("login.completed"); + expect(queries[0]!.params[2]).toBe("success"); + expect(queries[0]!.params[3]).toBe("u-001"); + }); + + it("maps returned row to SecurityEvent type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + occurredAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("se-001"); + expect(result.value.eventType).toBe("login.completed"); + expect(result.value.outcome).toBe("success"); + expect(result.value.userId).toBe("u-001"); + expect(result.value.sessionId).toBe("sess-001"); + expect(result.value.challengeId).toBe("ch-001"); + expect(result.value.ip).toBe("192.168.1.1"); + expect(result.value.occurredAt).toEqual(NOW); + expect(result.value.createdAt).toEqual(NOW); + } + }); + + it("serializes metadata as JSON", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + metadata: { provider: "email", extra: 42 }, + }); + + const metadataParam = queries[0]!.params[11]; + expect(typeof metadataParam).toBe("string"); + expect(JSON.parse(metadataParam as string)).toEqual({ provider: "email", extra: 42 }); + }); + + it("parses JSONB metadata from returned row", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_SECURITY_EVENT_ROW, metadata: JSON.stringify({ deep: { nested: true } }) }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.metadata).toEqual({ deep: { nested: true } }); + } + }); + + it("parses redact_paths from returned row", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.redactPaths).toEqual(["/metadata/provider"]); + } + }); + + it("defaults nullable fields to null", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ + ...SAMPLE_SECURITY_EVENT_ROW, + user_id: null, + session_id: null, + challenge_id: null, + ip: null, + user_agent: null, + correlation_id: null, + }], + }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-002", + eventType: "login.started", + outcome: "pending", + }); + + expect(queries[0]!.params[3]).toBeNull(); + expect(queries[0]!.params[4]).toBeNull(); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.userId).toBeNull(); + expect(result.value.sessionId).toBeNull(); + expect(result.value.challengeId).toBeNull(); + expect(result.value.ip).toBeNull(); + expect(result.value.userAgent).toBeNull(); + } + }); + + it("returns conflict on unique violation", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ + error: new Error("connection to host 10.0.0.1:5432 refused"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("10.0.0.1"); + expect(result.error.message).not.toContain("5432"); + expect(result.error.message).toBe("Failed to record security event"); + } + }); + + it("does not store raw secret values in params", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + metadata: { safe_field: "visible" }, + }); + + const allParams = JSON.stringify(queries[0]!.params); + expect(allParams).not.toContain("token_hash"); + expect(allParams).not.toContain("code_hash"); + expect(allParams).not.toContain("bearer_token"); + }); + }); + + describe("querySecurityEventsByUser", () => { + it("uses parameterized query with user_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: null, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("user_id = $1"); + expect(queries[0]!.params[0]).toBe("u-001"); + expect(queries[0]!.params[1]).toBe(11); + }); + + it("returns items with correct mapping", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: null, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.items[0]!.id).toBe("se-001"); + expect(result.value.items[0]!.eventType).toBe("login.completed"); + } + }); + + it("orders by occurred_at DESC, id DESC", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: null, + }); + + expect(queries[0]!.text).toContain("ORDER BY occurred_at DESC, id DESC"); + }); + + it("returns null nextCursor when items fit within limit", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: null, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns nextCursor when more items exist (limit+1 pattern)", async () => { + const rows = [ + { ...SAMPLE_SECURITY_EVENT_ROW, id: "se-001", occurred_at: "2026-01-15T10:03:00Z" }, + { ...SAMPLE_SECURITY_EVENT_ROW, id: "se-002", occurred_at: "2026-01-15T10:02:00Z" }, + { ...SAMPLE_SECURITY_EVENT_ROW, id: "se-003", occurred_at: "2026-01-15T10:01:00Z" }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createIdentityRepository(executor); + + const result = await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 2, + cursor: null, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("se-002"); + expect(result.value.nextCursor!.occurredAt).toBe(new Date("2026-01-15T10:02:00Z").toISOString()); + } + }); + + it("applies cursor filter with tuple comparison", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createIdentityRepository(executor); + + await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: { occurredAt: "2026-01-15T10:00:00Z", id: "se-005" }, + }); + + expect(queries[0]!.text).toContain("(occurred_at, id) < ($3, $4)"); + expect(queries[0]!.params[2]).toBe("2026-01-15T10:00:00Z"); + expect(queries[0]!.params[3]).toBe("se-005"); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ + error: new Error("relation does not exist"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.querySecurityEventsByUser({ + userId: "u-001", + limit: 10, + cursor: null, + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).toBe("Failed to query security events"); + expect(result.error.message).not.toContain("relation"); + } + }); + }); + + describe("security event secret safety", () => { + it("never includes secret columns in security event type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SECURITY_EVENT_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(true); + if (result.ok) { + const serialized = JSON.stringify(result.value); + expect(serialized).not.toContain("tokenHash"); + expect(serialized).not.toContain("codeHash"); + expect(serialized).not.toContain("bearerToken"); + expect(serialized).not.toContain("apiKey"); + expect(result.value).not.toHaveProperty("tokenHash"); + expect(result.value).not.toHaveProperty("codeHash"); + expect(result.value).not.toHaveProperty("bearerToken"); + expect(result.value).not.toHaveProperty("secret"); + } + }); + + it("never exposes secrets in error output for security events", async () => { + const { executor } = createFakeExecutor({ + error: new Error("duplicate key value (token_hash)=(abc123secret)"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.recordSecurityEvent({ + id: "se-001", + eventType: "login.completed", + outcome: "success", + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + const serialized = JSON.stringify(result.error); + expect(serialized).not.toContain("abc123secret"); + expect(serialized).not.toContain("token_hash"); + } + }); + }); + + // --- Service Principal Tests --- + + const SAMPLE_SERVICE_PRINCIPAL_ROW = { + id: "sp-001", + org_id: ORG_UUID, + project_id: null, + display_name: "CI Pipeline", + description: "Continuous integration automation", + status: "active", + created_by: USER_UUID, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), + }; + + describe("createServicePrincipal", () => { + it("inserts into identity_service_principals with correct params", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SERVICE_PRINCIPAL_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createServicePrincipal({ + id: "sp-001", + orgId: ORG_UUID, + displayName: "CI Pipeline", + description: "Continuous integration automation", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("sp-001"); + expect(result.value.orgId).toBe(ORG_UUID); + expect(result.value.projectId).toBeNull(); + expect(result.value.displayName).toBe("CI Pipeline"); + } + expect(queries.length).toBe(1); + expect(queries[0]!.text).toContain("identity_service_principals"); + expect(queries[0]!.text).toContain("INSERT INTO"); + }); + + it("supports project-scoped service principals", async () => { + const projectRow = { ...SAMPLE_SERVICE_PRINCIPAL_ROW, project_id: PROJECT_UUID }; + const { executor } = createFakeExecutor({ rows: [projectRow] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createServicePrincipal({ + id: "sp-001", + orgId: ORG_UUID, + projectId: PROJECT_UUID, + displayName: "CI Pipeline", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.projectId).toBe(PROJECT_UUID); + } + }); + + it("returns conflict on duplicate id", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.createServicePrincipal({ + id: "sp-001", + orgId: ORG_UUID, + displayName: "CI Pipeline", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("handles unique violation", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createIdentityRepository(executor); + + const result = await repo.createServicePrincipal({ + id: "sp-001", + orgId: ORG_UUID, + displayName: "CI Pipeline", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + }); + + describe("getServicePrincipalById", () => { + it("returns service principal by id", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_SERVICE_PRINCIPAL_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getServicePrincipalById("sp-001"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("sp-001"); + expect(result.value.orgId).toBe(ORG_UUID); + } + }); + + it("filters out deleted service principals", async () => { + const { executor, queries } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.getServicePrincipalById("sp-001"); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("not_found"); + } + expect(queries[0]!.text).toContain("status != 'deleted'"); + }); + }); + + describe("listServicePrincipalsByOrg", () => { + it("lists service principals for org, excluding deleted", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SERVICE_PRINCIPAL_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.listServicePrincipalsByOrg("org-001"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.length).toBe(1); + expect(result.value[0]!.orgId).toBe(ORG_UUID); + } + expect(queries[0]!.text).toContain("status != 'deleted'"); + expect(queries[0]!.text).toContain("ORDER BY created_at DESC"); + }); + }); + + // --- API Key Tests --- + + const SAMPLE_API_KEY_ROW = { + id: "ak-001", + service_principal_id: "sp-001", + org_id: ORG_UUID, + key_prefix: "spk_abc1", + label: "Production CI key", + status: "active", + expires_at: FUTURE.toISOString(), + last_used_at: null, + revoked_at: null, + revoked_by: null, + created_by: USER_UUID, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), + }; + + describe("createApiKey", () => { + it("inserts into identity_api_keys with correct params", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createApiKey({ + id: "ak-001", + servicePrincipalId: "sp-001", + orgId: ORG_UUID, + keyPrefix: "spk_abc1", + keyHash: "sha256hashvalue", + label: "Production CI key", + expiresAt: FUTURE, + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("ak-001"); + expect(result.value.servicePrincipalId).toBe("sp-001"); + expect(result.value.orgId).toBe(ORG_UUID); + expect(result.value.keyPrefix).toBe("spk_abc1"); + expect(result.value.label).toBe("Production CI key"); + expect(result.value.status).toBe("active"); + } + expect(queries.length).toBe(1); + expect(queries[0]!.text).toContain("identity_api_keys"); + expect(queries[0]!.text).toContain("key_hash"); + // CRITICAL: key_hash must NOT appear in RETURNING clause + expect(queries[0]!.text.split("RETURNING")[1]).not.toContain("key_hash"); + }); + + it("never returns key_hash in the created API key", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createApiKey({ + id: "ak-001", + servicePrincipalId: "sp-001", + orgId: ORG_UUID, + keyPrefix: "spk_abc1", + keyHash: "sha256hashvalue", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + const serialized = JSON.stringify(result.value); + expect(serialized).not.toContain("keyHash"); + expect(serialized).not.toContain("key_hash"); + expect(serialized).not.toContain("sha256hashvalue"); + expect(result.value).not.toHaveProperty("keyHash"); + expect(result.value).not.toHaveProperty("key_hash"); + } + }); + + it("returns conflict on duplicate id", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.createApiKey({ + id: "ak-001", + servicePrincipalId: "sp-001", + orgId: ORG_UUID, + keyPrefix: "spk_abc1", + keyHash: "sha256hashvalue", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + }); + + describe("getApiKeyByKeyHash", () => { + it("returns active API key by hash", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.getApiKeyByKeyHash("sha256hashvalue"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("ak-001"); + } + // Must filter by active status + expect(queries[0]!.text).toContain("status = 'active'"); + // Must NOT return key_hash in SELECT + expect(queries[0]!.text.split("FROM")[0]).not.toContain("key_hash"); + }); + + it("returns not_found for missing/revoked key", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.getApiKeyByKeyHash("nonexistent"); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("not_found"); + } + }); + }); + + describe("listApiKeysByOrg", () => { + it("lists API keys for org with cursor pagination", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.listApiKeysByOrg({ orgId: "org-001", limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items.length).toBe(1); + expect(result.value.nextCursor).toBeNull(); + } + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("ORDER BY created_at DESC"); + // Must NOT return key_hash in SELECT + expect(queries[0]!.text.split("FROM")[0]).not.toContain("key_hash"); + }); + + it("uses cursor for pagination", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.listApiKeysByOrg({ + orgId: "org-001", + limit: 50, + cursor: { createdAt: NOW.toISOString(), id: "ak-000" }, + }); + + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("(created_at, id) <"); + }); + + it("returns nextCursor when more results exist", async () => { + const rows = [ + { ...SAMPLE_API_KEY_ROW, id: "ak-001" }, + { ...SAMPLE_API_KEY_ROW, id: "ak-002" }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createIdentityRepository(executor); + + const result = await repo.listApiKeysByOrg({ orgId: "org-001", limit: 1, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items.length).toBe(1); + expect(result.value.nextCursor).not.toBeNull(); + } + }); + }); + + describe("revokeApiKey", () => { + it("revokes an active API key", async () => { + const revokedRow = { ...SAMPLE_API_KEY_ROW, status: "revoked", revoked_at: NOW.toISOString(), revoked_by: REVOKER_UUID }; + const { executor, queries } = createFakeExecutor({ rows: [revokedRow] }); + const repo = createIdentityRepository(executor); + + const result = await repo.revokeApiKey("ak-001", REVOKER_UUID, NOW); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("revoked"); + expect(result.value.revokedBy).toBe(REVOKER_UUID); + expect(result.value.revokedAt).not.toBeNull(); + } + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.text).toContain("status = 'revoked'"); + // Must NOT return key_hash in RETURNING + expect(queries[0]!.text.split("RETURNING")[1]).not.toContain("key_hash"); + }); + + it("returns not_found for already-revoked key", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIdentityRepository(executor); + + const result = await repo.revokeApiKey("ak-001", REVOKER_UUID, NOW); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("not_found"); + } + }); + }); + + describe("API key secret safety", () => { + it("API key type never includes keyHash property", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_API_KEY_ROW] }); + const repo = createIdentityRepository(executor); + + const result = await repo.createApiKey({ + id: "ak-001", + servicePrincipalId: "sp-001", + orgId: ORG_UUID, + keyPrefix: "spk_abc1", + keyHash: "sha256hashvalue", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + const serialized = JSON.stringify(result.value); + expect(serialized).not.toContain("keyHash"); + expect(serialized).not.toContain("key_hash"); + expect(serialized).not.toContain("secret"); + expect(serialized).not.toContain("bearerToken"); + expect(result.value).not.toHaveProperty("keyHash"); + expect(result.value).not.toHaveProperty("secret"); + } + }); + + it("never exposes secrets in error output for API keys", async () => { + const { executor } = createFakeExecutor({ + error: new Error("duplicate key value (key_hash)=(sha256secrethash)"), + }); + const repo = createIdentityRepository(executor); + + const result = await repo.createApiKey({ + id: "ak-001", + servicePrincipalId: "sp-001", + orgId: ORG_UUID, + keyPrefix: "spk_abc1", + keyHash: "sha256secrethash", + createdBy: USER_UUID, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + const serialized = JSON.stringify(result.error); + expect(serialized).not.toContain("sha256secrethash"); + expect(serialized).not.toContain("key_hash"); + } + }); + }); +}); diff --git a/tests/db/src/integrations-migration.test.ts b/tests/db/src/integrations-migration.test.ts new file mode 100644 index 0000000..bc97d9a --- /dev/null +++ b/tests/db/src/integrations-migration.test.ts @@ -0,0 +1,114 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest, BOUNDED_CONTEXTS } from "@saas/db"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve( + __dirname, + "../../..", + "packages/db/src/migrations", +); + +describe("Integrations Migration Verification", () => { + const integrationsMigrations = manifest.migrations.filter( + (m) => m.context === "integrations", + ); + + it("registers 'integrations' as a bounded context", () => { + expect(BOUNDED_CONTEXTS).toContain("integrations"); + }); + + it("has the 180_integrations_foundation migration", () => { + expect(integrationsMigrations.map((m) => m.id)).toContain( + "180_integrations_foundation", + ); + }); + + it("orders the integrations migrations at the manifest tail", () => { + const ids = manifest.migrations.map((m) => m.id); + expect(ids.indexOf("180_integrations_foundation")).toBe(ids.length - 2); + expect(ids.indexOf("190_integrations_delivery_attribution")).toBe(ids.length - 1); + }); + + it("manifest checksums match the on-disk up.sql files", () => { + for (const id of ["180_integrations_foundation", "190_integrations_delivery_attribution"]) { + const entry = manifest.migrations.find((m) => m.id === id)!; + const content = readFileSync(resolve(MIGRATIONS_ROOT, entry.path)); + const checksum = createHash("sha256").update(content).digest("hex"); + expect(entry.checksum).toBe(checksum); + } + }); + + it("190 adds the connection pointer additively and idempotently", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "190_integrations_delivery_attribution/up.sql"), + "utf-8", + ); + // SQLite has no `ADD COLUMN IF NOT EXISTS`; re-run safety is the + // runner's applied-ledger, and the column is a UUID held as TEXT. + expect(sql).toContain("ADD COLUMN connection_id TEXT"); + expect(sql).toContain("idx_integrations_inbound_deliveries_connection"); + expect(sql).toContain("WHERE connection_id IS NOT NULL"); + }); + + describe("integrations SQL schema validation", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "180_integrations_foundation/up.sql"), + "utf-8", + ); + + it("namespaces its tables to the integrations context", () => { + expect(sql).toContain("CREATE TABLE IF NOT EXISTS integrations_"); + }); + + it("creates the five foundation tables", () => { + expect(sql).toContain("integrations_connections"); + expect(sql).toContain("integrations_github_installations"); + expect(sql).toContain("integrations_repo_links"); + expect(sql).toContain("integrations_inbound_deliveries"); + expect(sql).toContain("integrations_installation_tokens"); + }); + + it("is idempotent (IF NOT EXISTS on every CREATE)", () => { + const creates = sql.match(/^CREATE (TABLE|SCHEMA|INDEX|UNIQUE INDEX)/gm) ?? []; + const guarded = sql.match(/^CREATE (?:TABLE|SCHEMA|INDEX|UNIQUE INDEX) IF NOT EXISTS/gm) ?? []; + expect(creates.length).toBeGreaterThan(0); + expect(guarded.length).toBe(creates.length); + }); + + it("enforces the delivery idempotency ledger (unique provider + delivery_key)", () => { + expect(sql).toContain("uq_integrations_inbound_delivery_key"); + expect(sql).toMatch(/ON integrations_inbound_deliveries \(provider, delivery_key\)/); + }); + + it("enforces one active connection per (org, provider, account)", () => { + expect(sql).toContain("uq_integrations_connection_active_account"); + expect(sql).toMatch(/WHERE status = 'active' AND external_account_id IS NOT NULL/); + }); + + it("enforces one active repo link per (project, repo)", () => { + expect(sql).toContain("uq_integrations_repo_link_project_repo"); + }); + + it("keeps the installation binding unique (tenancy keystone)", () => { + expect(sql).toContain("uq_integrations_github_installation"); + }); + + it("has keyset pagination indexes on org-scoped tables", () => { + expect(sql).toMatch(/ON integrations_connections \(org_id, created_at DESC, id DESC\)/); + expect(sql).toMatch(/ON integrations_repo_links \(org_id, created_at DESC, id DESC\)/); + expect(sql).toMatch(/ON integrations_inbound_deliveries \(org_id, received_at DESC, id DESC\)/); + }); + + it("never stores platform GitHub credentials as rows", () => { + // Cached installation tokens are ciphertext envelopes; the App private + // key / webhook secret / client secret must not have columns. + expect(sql).not.toMatch(/private_key/i); + expect(sql).not.toMatch(/webhook_secret/i); + expect(sql).not.toMatch(/client_secret/i); + expect(sql).toContain("token_ciphertext"); + }); + }); +}); diff --git a/tests/db/src/integrations.test.ts b/tests/db/src/integrations.test.ts new file mode 100644 index 0000000..695f3e6 --- /dev/null +++ b/tests/db/src/integrations.test.ts @@ -0,0 +1,486 @@ +import { createIntegrationsRepository } from "@saas/db/integrations"; +import { asUuid } from "@saas/db"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +const ORG_ID = asUuid("00000000-0000-4000-8000-000000000001"); +const OTHER_ID = asUuid("00000000-0000-4000-8000-000000000099"); +const CONNECTION_ID = asUuid("00000000-0000-4000-8000-000000000002"); +const PROJECT_ID = asUuid("00000000-0000-4000-8000-000000000003"); +const LINK_ID = asUuid("00000000-0000-4000-8000-000000000004"); +const DELIVERY_ID = asUuid("00000000-0000-4000-8000-000000000005"); + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + rowsBySequence?: Record[][]; + error?: unknown; + rowCount?: number; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + let call = 0; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + if (options?.error) { + throw options.error; + } + const sequence = options?.rowsBySequence; + const rows = (sequence ? (sequence[call++] ?? []) : (options?.rows ?? [])) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-06-11T10:00:00Z"); + +const SAMPLE_CONNECTION_ROW = { + id: CONNECTION_ID, + org_id: ORG_ID, + provider: "github", + status: "pending", + display_name: null, + external_account_login: null, + external_account_id: null, + external_account_type: null, + created_by: "usr_abc", + state_expires_at: NOW.toISOString(), + connected_at: null, + suspended_at: null, + revoked_at: null, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_INSTALLATION_ROW = { + id: "00000000-0000-4000-8000-000000000010", + connection_id: CONNECTION_ID, + installation_id: "9912345", + account_login: "acme", + account_id: "42", + account_type: "Organization", + repository_selection: "selected", + permissions: { contents: "read" }, + events: ["push"], + suspended_at: null, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_REPO_LINK_ROW = { + id: LINK_ID, + org_id: ORG_ID, + project_id: PROJECT_ID, + connection_id: CONNECTION_ID, + repo_external_id: "777", + repo_full_name: "acme/storefront", + default_branch: "main", + branch_env_map: { main: "prod" }, + status: "active", + created_by: "usr_abc", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_DELIVERY_ROW = { + id: DELIVERY_ID, + org_id: null, + provider: "github", + delivery_key: "gh-delivery-uuid-1", + event_type: "push", + action: null, + payload: { ref: "refs/heads/main" }, + signature_ok: true, + status: "received", + attempts: 0, + next_attempt_at: null, + failure_reason: null, + emitted_event_id: null, + received_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +describe("IntegrationsRepository — connections", () => { + it("creates a pending connection with parameterized values", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_CONNECTION_ROW] }); + const repo = createIntegrationsRepository(executor); + + const result = await repo.createConnection({ + id: CONNECTION_ID, + orgId: ORG_ID, + provider: "github", + createdBy: "usr_abc", + stateNonceHash: "abc123hash", + stateExpiresAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("pending"); + expect(result.value.orgId).toBe(ORG_ID); + } + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("integrations_connections"); + expect(queries[0]!.text).toContain("'pending'"); + expect(queries[0]!.params).toContain("abc123hash"); + }); + + it("maps a unique violation to a conflict error", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createIntegrationsRepository(executor); + const result = await repo.createConnection({ + id: CONNECTION_ID, + orgId: ORG_ID, + provider: "github", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toEqual({ kind: "conflict", entity: "connection" }); + } + }); + + it("scopes reads by org_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_CONNECTION_ROW] }); + const repo = createIntegrationsRepository(executor); + await repo.getConnection(ORG_ID, CONNECTION_ID); + expect(queries[0]!.text).toContain("WHERE org_id = $1 AND id = $2"); + expect(queries[0]!.params).toEqual([ORG_ID, CONNECTION_ID]); + }); + + it("never returns the state nonce hash through the read model", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_CONNECTION_ROW, state_nonce_hash: "should-not-leak" }], + }); + const repo = createIntegrationsRepository(executor); + const result = await repo.getConnection(ORG_ID, CONNECTION_ID); + expect(result.ok).toBe(true); + if (result.ok) { + expect(JSON.stringify(result.value)).not.toContain("should-not-leak"); + } + }); + + it("consumes connect state single-use, unexpired, pending-only", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_CONNECTION_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.consumeConnectionState("noncehash"); + expect(result.ok).toBe(true); + const sql = queries[0]!.text; + expect(sql).toContain("SET state_nonce_hash = NULL"); + expect(sql).toContain("status = 'pending'"); + expect(sql).toContain("state_expires_at > strftime('%Y-%m-%dT%H:%M:%fZ','now')"); + }); + + it("fails closed when the state nonce does not resolve", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIntegrationsRepository(executor); + const result = await repo.consumeConnectionState("expired-or-replayed"); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("not_found"); + } + }); + + it("activates only pending connections and clears the connect state", async () => { + const activated = { + ...SAMPLE_CONNECTION_ROW, + status: "active", + external_account_login: "acme", + connected_at: NOW.toISOString(), + }; + const { executor, queries } = createFakeExecutor({ rows: [activated] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.activateConnection(ORG_ID, CONNECTION_ID, { + externalAccountLogin: "acme", + externalAccountId: "42", + externalAccountType: "Organization", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("active"); + } + const sql = queries[0]!.text; + expect(sql).toContain("AND status = 'pending'"); + expect(sql).toContain("state_expires_at = NULL"); + }); + + it("stamps revoked_at when revoking", async () => { + const revoked = { ...SAMPLE_CONNECTION_ROW, status: "revoked", revoked_at: NOW.toISOString() }; + const { executor, queries } = createFakeExecutor({ rows: [revoked] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.updateConnectionStatus(ORG_ID, CONNECTION_ID, "revoked"); + expect(result.ok).toBe(true); + expect(queries[0]!.params).toEqual([ORG_ID, CONNECTION_ID, "revoked"]); + }); + + it("paginates connection lists with keyset cursors", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_CONNECTION_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.listConnections(ORG_ID, { + limit: 20, + cursor: { createdAt: NOW.toISOString(), id: CONNECTION_ID }, + }); + expect(result.ok).toBe(true); + const sql = queries[0]!.text; + expect(sql).toContain("ORDER BY created_at DESC, id DESC"); + expect(sql).toContain("(created_at, id) <"); + }); +}); + +describe("IntegrationsRepository — GitHub installations", () => { + it("upserts keyed by installation_id and preserves an existing binding", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INSTALLATION_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.upsertGithubInstallation({ + id: SAMPLE_INSTALLATION_ROW.id, + connectionId: CONNECTION_ID, + installationId: 9912345, + accountLogin: "acme", + accountType: "Organization", + repositorySelection: "selected", + permissions: { contents: "read" }, + events: ["push"], + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.installationId).toBe(9912345); + expect(result.value.connectionId).toBe(CONNECTION_ID); + } + const sql = queries[0]!.text; + expect(sql).toContain("ON CONFLICT (installation_id)"); + // An orphan re-delivery (connection_id NULL) must never clear a binding. + expect(sql).toContain("COALESCE(EXCLUDED.connection_id, integrations_github_installations.connection_id)"); + }); + + it("supports orphaned installations (no connection binding)", async () => { + const orphanRow = { ...SAMPLE_INSTALLATION_ROW, connection_id: null }; + const { executor } = createFakeExecutor({ rows: [orphanRow] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.upsertGithubInstallation({ + id: SAMPLE_INSTALLATION_ROW.id, + installationId: 9912345, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.connectionId).toBeNull(); + } + }); + + it("looks up by installation id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INSTALLATION_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.getGithubInstallationByInstallationId(9912345); + expect(result.ok).toBe(true); + expect(queries[0]!.params).toEqual([9912345]); + }); +}); + +describe("IntegrationsRepository — repo links", () => { + it("creates an org+project scoped link with a branch map", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_REPO_LINK_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.createRepoLink({ + id: LINK_ID, + orgId: ORG_ID, + projectId: PROJECT_ID, + connectionId: CONNECTION_ID, + repoExternalId: "777", + repoFullName: "acme/storefront", + defaultBranch: "main", + branchEnvMap: { main: "prod" }, + createdBy: "usr_abc", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.branchEnvMap).toEqual({ main: "prod" }); + } + expect(queries[0]!.text).toContain("integrations_repo_links"); + expect(queries[0]!.params[1]).toBe(ORG_ID); + expect(queries[0]!.params[2]).toBe(PROJECT_ID); + }); + + it("maps duplicate active links to conflict", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createIntegrationsRepository(executor); + const result = await repo.createRepoLink({ + id: LINK_ID, + orgId: ORG_ID, + projectId: PROJECT_ID, + connectionId: CONNECTION_ID, + repoExternalId: "777", + repoFullName: "acme/storefront", + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error).toEqual({ kind: "conflict", entity: "repo_link" }); + } + }); + + it("filters list by project when given", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_REPO_LINK_ROW] }); + const repo = createIntegrationsRepository(executor); + await repo.listRepoLinks(ORG_ID, { limit: 10, cursor: null }, { projectId: PROJECT_ID, status: "active" }); + const sql = queries[0]!.text; + expect(sql).toContain("AND project_id = $2"); + expect(sql).toContain("AND status = $3"); + }); + + it("soft-unlinks only active rows, org-scoped", async () => { + const unlinked = { ...SAMPLE_REPO_LINK_ROW, status: "unlinked" }; + const { executor, queries } = createFakeExecutor({ rows: [unlinked] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.unlinkRepoLink(ORG_ID, LINK_ID); + expect(result.ok).toBe(true); + const sql = queries[0]!.text; + expect(sql).toContain("SET status = 'unlinked'"); + expect(sql).toContain("WHERE org_id = $1 AND id = $2 AND status = 'active'"); + }); + + it("returns not_found when unlinking another org's link", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createIntegrationsRepository(executor); + const result = await repo.unlinkRepoLink(OTHER_ID, LINK_ID); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("not_found"); + } + }); +}); + +describe("IntegrationsRepository — inbound deliveries (durable inbox)", () => { + it("inserts a new delivery with created=true", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_DELIVERY_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.insertInboundDelivery({ + id: DELIVERY_ID, + provider: "github", + deliveryKey: "gh-delivery-uuid-1", + eventType: "push", + payload: { ref: "refs/heads/main" }, + signatureOk: true, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.created).toBe(true); + expect(result.value.delivery.status).toBe("received"); + } + expect(queries[0]!.text).toContain("ON CONFLICT (provider, delivery_key) DO NOTHING"); + }); + + it("treats a redelivery as a no-op returning the existing row", async () => { + const { executor, queries } = createFakeExecutor({ + rowsBySequence: [[], [SAMPLE_DELIVERY_ROW]], + }); + const repo = createIntegrationsRepository(executor); + const result = await repo.insertInboundDelivery({ + id: asUuid("00000000-0000-4000-8000-000000000006"), + provider: "github", + deliveryKey: "gh-delivery-uuid-1", + eventType: "push", + payload: { ref: "refs/heads/main" }, + signatureOk: true, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.created).toBe(false); + expect(result.value.delivery.id).toBe(DELIVERY_ID); + } + expect(queries).toHaveLength(2); + expect(queries[1]!.text).toContain("WHERE provider = $1 AND delivery_key = $2"); + }); + + it("scans due work oldest-first for the cron drain", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_DELIVERY_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.listDueInboundDeliveries(50); + expect(result.ok).toBe(true); + const sql = queries[0]!.text; + expect(sql).toContain("status IN ('received', 'attributed')"); + expect(sql).toContain("next_attempt_at IS NULL OR next_attempt_at <= strftime('%Y-%m-%dT%H:%M:%fZ','now')"); + expect(sql).toContain("ORDER BY received_at ASC, id ASC"); + }); + + it("marks attribution and emission transitions", async () => { + const attributed = { ...SAMPLE_DELIVERY_ROW, org_id: ORG_ID, status: "attributed" }; + const { executor, queries } = createFakeExecutor({ rows: [attributed] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.markInboundDelivery(DELIVERY_ID, { + orgId: ORG_ID, + status: "attributed", + attempts: 1, + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.status).toBe("attributed"); + } + expect(queries[0]!.params[0]).toBe(DELIVERY_ID); + }); + + it("lists the org-scoped delivery log keyed by received_at", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_DELIVERY_ROW, org_id: ORG_ID }], + }); + const repo = createIntegrationsRepository(executor); + await repo.listInboundDeliveries(ORG_ID, { limit: 10, cursor: null }); + const sql = queries[0]!.text; + expect(sql).toContain("WHERE org_id = $1"); + expect(sql).toContain("ORDER BY received_at DESC, id DESC"); + }); +}); + +describe("IntegrationsRepository — installation token cache", () => { + const SAMPLE_TOKEN_ROW = { + id: "00000000-0000-4000-8000-000000000020", + connection_id: CONNECTION_ID, + token_ciphertext: "v1:abc:ciphertext", + permissions: { contents: "read" }, + repository_ids: [777], + expires_at: NOW.toISOString(), + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), + }; + + it("upserts one cache entry per connection", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_TOKEN_ROW] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.upsertInstallationToken({ + id: SAMPLE_TOKEN_ROW.id, + connectionId: CONNECTION_ID, + tokenCiphertext: "v1:abc:ciphertext", + permissions: { contents: "read" }, + repositoryIds: [777], + expiresAt: NOW, + }); + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("ON CONFLICT (connection_id) DO UPDATE"); + }); + + it("only returns unexpired tokens", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_TOKEN_ROW] }); + const repo = createIntegrationsRepository(executor); + await repo.getInstallationToken(CONNECTION_ID); + expect(queries[0]!.text).toContain("expires_at > strftime('%Y-%m-%dT%H:%M:%fZ','now')"); + }); + + it("deletes the cache entry on revoke", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createIntegrationsRepository(executor); + const result = await repo.deleteInstallationToken(CONNECTION_ID); + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("DELETE FROM integrations_installation_tokens"); + }); + + it("returns a safe internal error without leaking driver details", async () => { + const { executor } = createFakeExecutor({ error: new Error("connection refused at 10.0.0.5") }); + const repo = createIntegrationsRepository(executor); + const result = await repo.getInstallationToken(CONNECTION_ID); + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("10.0.0.5"); + } + }); +}); diff --git a/tests/db/src/membership-migration.test.ts b/tests/db/src/membership-migration.test.ts new file mode 100644 index 0000000..ab6d4a7 --- /dev/null +++ b/tests/db/src/membership-migration.test.ts @@ -0,0 +1,147 @@ +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "@saas/db"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve( + __dirname, + "../../..", + "packages/db/src/migrations", +); + +describe("Membership Migration Verification", () => { + const membershipMigrations = manifest.migrations.filter( + (m) => m.context === "membership", + ); + + it("has at least one membership migration", () => { + expect(membershipMigrations.length).toBeGreaterThan(0); + }); + + it("membership migration has context 'membership'", () => { + for (const m of membershipMigrations) { + expect(m.context).toBe("membership"); + } + }); + + it("membership migration is ordered after identity migrations", () => { + const ids = manifest.migrations.map((m) => m.id); + const identityIdx = ids.indexOf("010_identity_core"); + const membershipIdx = ids.indexOf("020_membership_core"); + + expect(membershipIdx).toBeGreaterThan(identityIdx); + }); + + describe("membership SQL schema validation", () => { + const sql = readFileSync( + resolve(MIGRATIONS_ROOT, "020_membership_core/up.sql"), + "utf-8", + ); + + it("namespaces its tables to the membership context", () => { + expect(sql).toContain("CREATE TABLE IF NOT EXISTS membership_"); + }); + + it("creates membership_organizations table", () => { + expect(sql).toContain("membership_organizations"); + }); + + it("creates membership_organization_members table", () => { + expect(sql).toContain("membership_organization_members"); + }); + + it("creates membership_organization_invitations table", () => { + expect(sql).toContain("membership_organization_invitations"); + }); + + it("creates membership_role_assignments table", () => { + expect(sql).toContain("membership_role_assignments"); + }); + + it("stores only hashed invitation tokens, never raw values", () => { + expect(sql).toContain("token_hash"); + expect(sql).not.toMatch(/\btoken\b\s+TEXT/); + }); + + it("uses normalized slug column for lookup", () => { + expect(sql).toContain("slug_lower"); + expect(sql).toContain("organizations_slug_lower_idx"); + }); + + it("uses normalized email for invitation lookup", () => { + expect(sql).toContain("email_lower"); + expect(sql).toContain("org_invitations_email_lower_idx"); + }); + + it("uses IF NOT EXISTS for idempotency", () => { + const createStatements = sql.match(/CREATE\s+(TABLE|SCHEMA|INDEX)/g) ?? []; + const ifNotExists = sql.match(/IF NOT EXISTS/g) ?? []; + expect(ifNotExists.length).toBeGreaterThanOrEqual(createStatements.length); + }); + + it("does not reference cross-context tables", () => { + expect(sql).not.toContain("identity."); + expect(sql).not.toContain("projects."); + expect(sql).not.toContain("billing."); + expect(sql).not.toContain("events."); + }); + + it("does not require extensions like citext", () => { + expect(sql).not.toContain("CREATE EXTENSION"); + expect(sql).not.toContain("citext"); + }); + + it("has no foreign keys to cross-context tables", () => { + const fkMatches = sql.match(/REFERENCES\s+(\w+\.\w+)/g) ?? []; + for (const fk of fkMatches) { + expect(fk).toContain("membership."); + } + }); + + it("all organization-scoped tables include org_id column", () => { + const tableBlocks = sql.split(/CREATE TABLE IF NOT EXISTS/); + const orgScopedTables = tableBlocks.filter( + (block) => + block.includes("membership_organization_members") || + block.includes("membership_organization_invitations") || + block.includes("membership_role_assignments"), + ); + for (const block of orgScopedTables) { + expect(block).toContain("org_id"); + } + }); + + it("invitation secrets are hash-only", () => { + expect(sql).toContain("token_hash"); + expect(sql).not.toMatch(/\braw_token\b/); + expect(sql).not.toMatch(/\btoken\b\s+TEXT\s+NOT NULL(?!.*hash)/); + }); + + it("supports all organization roles from spec", () => { + expect(sql).toContain("owner"); + expect(sql).toContain("admin"); + expect(sql).toContain("builder"); + expect(sql).toContain("viewer"); + expect(sql).toContain("billing_admin"); + }); + + it("supports project roles without coupling to projects schema", () => { + expect(sql).toContain("project_admin"); + expect(sql).toContain("project_builder"); + expect(sql).toContain("project_viewer"); + }); + + it("role_assignments has scope_kind and scope_ref for project scoping", () => { + expect(sql).toContain("scope_kind"); + expect(sql).toContain("scope_ref"); + }); + }); + + describe("project-scoped invariant still applies only to projects context", () => { + it("membership migrations are not subject to project-scoped org_id/project_id check", () => { + expect(membershipMigrations.every((m) => m.context === "membership")).toBe(true); + expect(membershipMigrations.some((m) => m.context === "projects")).toBe(false); + }); + }); +}); diff --git a/tests/db/src/membership.test.ts b/tests/db/src/membership.test.ts new file mode 100644 index 0000000..0564a1b --- /dev/null +++ b/tests/db/src/membership.test.ts @@ -0,0 +1,1688 @@ +import { + createMembershipRepository, +} from "@saas/db/membership"; +import { asUuid } from "@saas/db"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +const ORG1 = asUuid("00000000-0000-0000-0000-000000000001"); +const ORG2 = asUuid("00000000-0000-0000-0000-000000000002"); +const ORG999 = asUuid("00000000-0000-0000-0000-000000000099"); +const ORG_EMPTY = asUuid("00000000-0000-0000-0000-0000000000ee"); + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; + callResponses?: Array<{ rows?: Record[]; rowCount?: number; error?: unknown }>; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + let callIndex = 0; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + + if (options?.callResponses && callIndex < options.callResponses.length) { + const response = options.callResponses[callIndex]!; + callIndex++; + if (response.error) { + throw response.error; + } + const rows = (response.rows ?? []) as unknown as T[]; + return { rows, rowCount: response.rowCount ?? rows.length }; + } + + if (options?.error) { + throw options.error; + } + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); +const FUTURE = new Date("2099-01-15T11:00:00Z"); +const PAST = new Date("2020-01-15T09:00:00Z"); + +const SAMPLE_ORG_ROW = { + id: ORG1, + name: "Acme Corp", + slug: "acme-corp", + slug_lower: "acme-corp", + status: "active", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_MEMBER_ROW = { + id: "mem-001", + org_id: ORG1, + subject_id: "usr-001", + subject_type: "user", + status: "active", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_INVITATION_ROW = { + id: "inv-001", + org_id: ORG1, + email: "Invite@Example.com", + email_lower: "invite@example.com", + role: "builder", + status: "pending", + invited_by: "usr-001", + expires_at: FUTURE.toISOString(), + accepted_at: null, + revoked_at: null, + created_at: NOW.toISOString(), +}; + +const SAMPLE_ROLE_ASSIGNMENT_ROW = { + id: "ra-001", + org_id: ORG1, + subject_id: "usr-001", + subject_type: "user", + role: "owner", + scope_kind: "organization", + scope_ref: null, + created_at: NOW.toISOString(), + revoked_at: null, +}; + +describe("MembershipRepository", () => { + describe("createOrganization", () => { + it("uses parameterized query for organization creation", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.createOrganization({ + id: ORG1, + name: "Acme Corp", + slug: "acme-corp", + slugLower: "acme-corp", + createdAt: NOW, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.params).toEqual([ + ORG1, + "Acme Corp", + "acme-corp", + "acme-corp", + NOW.toISOString(), + ]); + }); + + it("maps returned row to Organization type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + const result = await repo.createOrganization({ + id: ORG1, + name: "Acme Corp", + slug: "acme-corp", + slugLower: "acme-corp", + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe(ORG1); + expect(result.value.name).toBe("Acme Corp"); + expect(result.value.slugLower).toBe("acme-corp"); + expect(result.value.status).toBe("active"); + expect(result.value.createdAt).toEqual(NOW); + } + }); + + it("returns conflict on duplicate organization", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createMembershipRepository(executor); + + const result = await repo.createOrganization({ + id: ORG1, + name: "Acme Corp", + slug: "acme-corp", + slugLower: "acme-corp", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns conflict on unique violation error code", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createOrganization({ + id: ORG2, + name: "Acme Corp", + slug: "acme-corp", + slugLower: "acme-corp", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("maps generic errors to safe internal error (and logs the cause for diagnosis)", async () => { + const { executor } = createFakeExecutor({ + error: Object.assign(new Error("connection to host 10.0.0.1:5432 refused"), { code: "ECONNREFUSED" }), + }); + const repo = createMembershipRepository(executor); + const originalError = console.error; + const logged: unknown[][] = []; + console.error = (...args: unknown[]) => { logged.push(args); }; + + let result; + try { + result = await repo.createOrganization({ + id: ORG1, + name: "Test", + slug: "test", + slugLower: "test", + createdAt: NOW, + }); + } finally { + console.error = originalError; + } + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + // The user-facing error message must stay opaque (no host/port leak). + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("10.0.0.1"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("5432"); + } + // ...but the underlying cause is logged for ops diagnosis (name/message/code only). + const hit = logged.find( + (a) => typeof a[0] === "string" && a[0].includes("[membership-repo]") && (a[1] as { code?: string })?.code === "ECONNREFUSED", + ); + expect(hit).toBeDefined(); + }); + }); + + describe("getOrganizationById", () => { + it("uses parameterized query for lookup", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.getOrganizationById(ORG1); + + expect(queries[0]!.params).toEqual([ORG1]); + expect(queries[0]!.text).toContain("$1"); + }); + + it("returns not_found when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getOrganizationById("org-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("getOrganizationBySlug", () => { + it("uses normalized slug in parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.getOrganizationBySlug("acme-corp"); + + expect(queries[0]!.params).toEqual(["acme-corp"]); + expect(queries[0]!.text).toContain("slug_lower"); + }); + + it("returns not_found for unknown slug", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getOrganizationBySlug("unknown-slug"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("listOrganizationsForSubject", () => { + it("uses parameterized query with subject_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listOrganizationsForSubject("usr-001"); + + expect(queries[0]!.params).toEqual(["usr-001"]); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("subject_id"); + }); + + it("returns empty array when no organizations found", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listOrganizationsForSubject("usr-missing"); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toEqual([]); + }); + }); + + describe("bootstrapOrganization", () => { + it("creates org, member, and role assignment atomically in a single CTE statement", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ + org: SAMPLE_ORG_ROW, + member: SAMPLE_MEMBER_ROW, + role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW, + }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.bootstrapOrganization({ + org: { id: ORG1, name: "Acme Corp", slug: "acme-corp", slugLower: "acme-corp", createdAt: NOW }, + member: { id: "mem-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", createdAt: NOW }, + roleAssignment: { id: "ra-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", role: "owner", scopeKind: "organization", createdAt: NOW }, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("WITH new_org AS"); + expect(queries[0]!.text).toContain("new_member AS"); + expect(queries[0]!.text).toContain("new_role AS"); + expect(queries[0]!.text).toContain("CROSS JOIN"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.org.id).toBe(ORG1); + expect(result.value.member.subjectId).toBe("usr-001"); + expect(result.value.roleAssignment.role).toBe("owner"); + } + }); + + it("uses parameterized query with all 18 parameters", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ + org: SAMPLE_ORG_ROW, + member: SAMPLE_MEMBER_ROW, + role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW, + }], + }); + const repo = createMembershipRepository(executor); + + await repo.bootstrapOrganization({ + org: { id: ORG1, name: "Acme Corp", slug: "acme-corp", slugLower: "acme-corp", createdAt: NOW }, + member: { id: "mem-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", createdAt: NOW }, + roleAssignment: { id: "ra-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", role: "owner", scopeKind: "organization", createdAt: NOW }, + }); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$18"); + // $19 = parent_org_id (MO3); standalone bootstrap passes null. + expect(queries[0]!.text).toContain("parent_org_id"); + expect(queries[0]!.params.length).toBe(19); + expect(queries[0]!.params[18]).toBeNull(); + }); + + it("returns conflict if organization already exists", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createMembershipRepository(executor); + + const result = await repo.bootstrapOrganization({ + org: { id: ORG1, name: "Acme Corp", slug: "acme-corp", slugLower: "acme-corp", createdAt: NOW }, + member: { id: "mem-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", createdAt: NOW }, + roleAssignment: { id: "ra-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", role: "owner", scopeKind: "organization", createdAt: NOW }, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("all-or-nothing: member and role depend on org via CTE chain", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ + org: SAMPLE_ORG_ROW, + member: SAMPLE_MEMBER_ROW, + role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW, + }], + }); + const repo = createMembershipRepository(executor); + + await repo.bootstrapOrganization({ + org: { id: ORG1, name: "Acme Corp", slug: "acme-corp", slugLower: "acme-corp", createdAt: NOW }, + member: { id: "mem-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", createdAt: NOW }, + roleAssignment: { id: "ra-001", orgId: ORG1, subjectId: "usr-001", subjectType: "user", role: "owner", scopeKind: "organization", createdAt: NOW }, + }); + + expect(queries[0]!.text).toContain("FROM new_org"); + expect(queries[0]!.text).toContain("FROM new_member"); + }); + }); + + describe("createMember", () => { + it("uses parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_MEMBER_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.createMember({ + id: "mem-001", + orgId: ORG1, + subjectId: "usr-001", + subjectType: "user", + createdAt: NOW, + }); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.params).toEqual([ + "mem-001", + ORG1, + "usr-001", + "user", + NOW.toISOString(), + ]); + }); + + it("returns conflict on duplicate member", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createMember({ + id: "mem-002", + orgId: ORG1, + subjectId: "usr-001", + subjectType: "user", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("getMemberById", () => { + it("uses parameterized query with org_id and member_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_MEMBER_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.getMemberById(ORG1, "mem-001"); + + expect(queries[0]!.params).toEqual([ORG1, "mem-001"]); + }); + + it("returns not_found when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getMemberById(ORG1, "mem-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns removed for removed member", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_MEMBER_ROW, status: "removed" }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getMemberById(ORG1, "mem-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("removed"); + }); + }); + + describe("listMembers", () => { + it("uses parameterized query for org_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_MEMBER_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listMembers(ORG1); + + expect(queries[0]!.params).toEqual([ORG1]); + expect(queries[0]!.text).toContain("status = 'active'"); + }); + + it("returns empty array when no members", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listMembers(ORG_EMPTY); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toEqual([]); + }); + }); + + describe("removeMember", () => { + it("uses parameterized update with status = 'active' guard", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_MEMBER_ROW, status: "removed", updated_at: NOW.toISOString() }], + }); + const repo = createMembershipRepository(executor); + + await repo.removeMember(ORG1, "mem-001", NOW); + + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG1, "mem-001", NOW.toISOString()]); + }); + + it("returns not_found when member already removed", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createMembershipRepository(executor); + + const result = await repo.removeMember(ORG1, "mem-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("createInvitation", () => { + it("stores hashed token via parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.createInvitation({ + id: "inv-001", + orgId: ORG1, + email: "Invite@Example.com", + emailLower: "invite@example.com", + role: "builder", + tokenHash: "sha256-hashed-invite-token", + invitedBy: "usr-001", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(queries[0]!.params[5]).toBe("sha256-hashed-invite-token"); + expect(queries[0]!.text).toContain("$6"); + }); + + it("does not expose token_hash in returned invitation", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + const result = await repo.createInvitation({ + id: "inv-001", + orgId: ORG1, + email: "Invite@Example.com", + emailLower: "invite@example.com", + role: "builder", + tokenHash: "sha256-hashed-invite-token", + invitedBy: "usr-001", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).not.toHaveProperty("tokenHash"); + expect(result.value).not.toHaveProperty("token_hash"); + } + }); + + it("returns conflict on duplicate invitation", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createInvitation({ + id: "inv-002", + orgId: ORG1, + email: "test@example.com", + emailLower: "test@example.com", + role: "viewer", + tokenHash: "sha256-another-hash", + invitedBy: "usr-001", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("getInvitationById", () => { + it("uses parameterized query with org_id and invitation_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.getInvitationById(ORG1, "inv-001"); + + expect(queries[0]!.params).toEqual([ORG1, "inv-001"]); + }); + + it("returns not_found for missing invitation", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationById(ORG1, "inv-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns revoked for revoked invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, revoked_at: NOW.toISOString(), status: "revoked" }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationById(ORG1, "inv-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("revoked"); + }); + + it("returns already_accepted for accepted invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationById(ORG1, "inv-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("already_accepted"); + }); + + it("returns expired for expired invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, expires_at: PAST.toISOString() }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationById(ORG1, "inv-001"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + }); + + it("does not expose token_hash in returned invitation", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationById(ORG1, "inv-001"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).not.toHaveProperty("tokenHash"); + expect(result.value).not.toHaveProperty("token_hash"); + } + }); + }); + + describe("getInvitationByTokenHash", () => { + it("uses parameterized query with token hash", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.getInvitationByTokenHash("sha256-hashed-token"); + + expect(queries[0]!.params).toEqual(["sha256-hashed-token"]); + expect(queries[0]!.text).toContain("token_hash = $1"); + }); + + it("returns not_found for unknown token hash", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationByTokenHash("unknown-hash"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns revoked for revoked invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, revoked_at: NOW.toISOString(), status: "revoked" }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("revoked"); + }); + + it("returns already_accepted for accepted invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("already_accepted"); + }); + + it("returns expired for expired invitation", async () => { + const { executor } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, expires_at: PAST.toISOString() }], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.getInvitationByTokenHash("sha256-hashed-token"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + }); + }); + + describe("listInvitations", () => { + it("uses parameterized query for org_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listInvitations(ORG1); + + expect(queries[0]!.params).toEqual([ORG1]); + }); + + it("returns empty array when no invitations", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listInvitations(ORG_EMPTY); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toEqual([]); + }); + }); + + describe("revokeInvitation", () => { + it("uses parameterized update with pending/null guards", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_INVITATION_ROW, revoked_at: NOW.toISOString(), status: "revoked" }], + }); + const repo = createMembershipRepository(executor); + + await repo.revokeInvitation(ORG1, "inv-001", NOW); + + expect(queries[0]!.text).toContain("status = 'pending'"); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + expect(queries[0]!.params).toEqual([ORG1, "inv-001", NOW.toISOString()]); + }); + + it("returns not_found when invitation already revoked or accepted", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createMembershipRepository(executor); + + const result = await repo.revokeInvitation(ORG1, "inv-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("acceptInvitation", () => { + it("validates invitation state and creates member + role assignment atomically", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + { rows: [{ invitation: { ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }, member: SAMPLE_MEMBER_ROW, role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(queries).toHaveLength(2); + expect(queries[0]!.text).toContain("token_hash = $1"); + expect(queries[1]!.text).toContain("WITH accepted_inv AS"); + expect(queries[1]!.text).toContain("org_id = $3"); + expect(queries[1]!.text).toContain("email_lower = $4"); + expect(queries[1]!.text).toContain("expires_at > $2"); + expect(queries[1]!.text).toContain("new_role AS"); + expect(queries[1]!.text).toContain("scope_kind"); + expect(queries[1]!.text).toContain("CROSS JOIN"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.invitation.status).toBe("accepted"); + expect(result.value.member.subjectId).toBe("usr-001"); + expect(result.value.roleAssignment.role).toBe("owner"); + expect(result.value.roleAssignment.scopeKind).toBe("organization"); + } + }); + + it("returns not_found when invitation not found by token hash", async () => { + const { executor } = createFakeExecutor({ + callResponses: [ + { rows: [], rowCount: 0 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-unknown-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("returns not_found when invitation belongs to a different organization", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG999, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + expect(queries).toHaveLength(1); + }); + + it("returns not_found when email does not match", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "wrong@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + expect(queries).toHaveLength(1); + }); + + it("returns expired when invitation past expiry without marking it accepted", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [{ ...SAMPLE_INVITATION_ROW, expires_at: PAST.toISOString() }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("expired"); + expect(queries).toHaveLength(1); + }); + + it("returns revoked when invitation is revoked", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [{ ...SAMPLE_INVITATION_ROW, revoked_at: NOW.toISOString(), status: "revoked" }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("revoked"); + expect(queries).toHaveLength(1); + }); + + it("returns already_accepted when invitation was already accepted", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [{ ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("already_accepted"); + expect(queries).toHaveLength(1); + }); + + it("returns conflict when member uniqueness constraint fails", async () => { + const { executor } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + { error: new Error("D1_ERROR: UNIQUE constraint failed") }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("does not expose token hash in invitation output", async () => { + const { executor } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + { rows: [{ invitation: { ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }, member: SAMPLE_MEMBER_ROW, role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.invitation).not.toHaveProperty("tokenHash"); + expect(result.value.invitation).not.toHaveProperty("token_hash"); + } + }); + + it("raw token is never part of repository input parameters", async () => { + const { executor, queries } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + { rows: [{ invitation: { ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }, member: SAMPLE_MEMBER_ROW, role_assignment: SAMPLE_ROLE_ASSIGNMENT_ROW }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + const allParams = queries.flatMap((q) => q.params); + expect(allParams).not.toContain("raw_token_value"); + expect(allParams[0]).toBe("sha256-hashed-token"); + }); + + it("returned role assignment is organization-scoped", async () => { + const { executor } = createFakeExecutor({ + callResponses: [ + { rows: [SAMPLE_INVITATION_ROW], rowCount: 1 }, + { rows: [{ invitation: { ...SAMPLE_INVITATION_ROW, accepted_at: NOW.toISOString(), status: "accepted" }, member: SAMPLE_MEMBER_ROW, role_assignment: { ...SAMPLE_ROLE_ASSIGNMENT_ROW, scope_kind: "organization", scope_ref: null } }], rowCount: 1 }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.acceptInvitation({ + tokenHash: "sha256-hashed-token", + orgId: ORG1, + emailLower: "invite@example.com", + memberId: "mem-002", + roleAssignmentId: "ra-002", + subjectId: "usr-002", + subjectType: "user", + acceptedAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.roleAssignment.scopeKind).toBe("organization"); + expect(result.value.roleAssignment.scopeRef).toBeNull(); + } + }); + }); + + describe("createRoleAssignment", () => { + it("uses parameterized query for role assignment creation", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ROLE_ASSIGNMENT_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.createRoleAssignment({ + id: "ra-001", + orgId: ORG1, + subjectId: "usr-001", + subjectType: "user", + role: "owner", + scopeKind: "organization", + createdAt: NOW, + }); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.params).toEqual([ + "ra-001", + ORG1, + "usr-001", + "user", + "owner", + "organization", + null, + NOW.toISOString(), + ]); + }); + + it("supports project-scoped role assignments", async () => { + const projectRole = { ...SAMPLE_ROLE_ASSIGNMENT_ROW, role: "project_builder", scope_kind: "project", scope_ref: "prj-001" }; + const { executor, queries } = createFakeExecutor({ rows: [projectRole] }); + const repo = createMembershipRepository(executor); + + await repo.createRoleAssignment({ + id: "ra-002", + orgId: ORG1, + subjectId: "usr-001", + subjectType: "user", + role: "project_builder", + scopeKind: "project", + scopeRef: "prj-001", + createdAt: NOW, + }); + + expect(queries[0]!.params[6]).toBe("prj-001"); + }); + + it("returns conflict on duplicate active role assignment", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createRoleAssignment({ + id: "ra-003", + orgId: ORG1, + subjectId: "usr-001", + subjectType: "user", + role: "owner", + scopeKind: "organization", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("listRoleAssignments", () => { + it("uses parameterized query with org_id and subject_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ROLE_ASSIGNMENT_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listRoleAssignments(ORG1, "usr-001"); + + expect(queries[0]!.params).toEqual([ORG1, "usr-001"]); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + }); + + it("returns empty array when no assignments", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listRoleAssignments(ORG1, "usr-missing"); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toEqual([]); + }); + }); + + describe("listRoleAssignmentsForSubjects", () => { + it("batches with a scalar IN list (no array param) and groups by subject", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [ + SAMPLE_ROLE_ASSIGNMENT_ROW, + { ...SAMPLE_ROLE_ASSIGNMENT_ROW, id: "ra-002", subject_id: "usr-002", role: "member" }, + ], + }); + const repo = createMembershipRepository(executor); + + const result = await repo.listRoleAssignmentsForSubjects!(ORG1, ["usr-001", "usr-002"]); + + // One query, not N. Regression guard: must use scalar IN-list params, + // never `= ANY($array)` (array params throw under fetch_types:false). + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("subject_id IN ($2, $3)"); + expect(queries[0]!.text).not.toContain("ANY("); + expect(queries[0]!.params).toEqual([ORG1, "usr-001", "usr-002"]); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.get("usr-001")?.map((ra) => ra.role)).toEqual(["owner"]); + expect(result.value.get("usr-002")?.map((ra) => ra.role)).toEqual(["member"]); + } + }); + + it("short-circuits without a query for an empty subject list", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listRoleAssignmentsForSubjects!(ORG1, []); + + expect(queries).toHaveLength(0); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.size).toBe(0); + }); + }); + + describe("revokeRoleAssignment", () => { + it("uses parameterized update with revoked_at IS NULL guard", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_ROLE_ASSIGNMENT_ROW, revoked_at: NOW.toISOString() }], + }); + const repo = createMembershipRepository(executor); + + await repo.revokeRoleAssignment(ORG1, "ra-001", NOW); + + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + expect(queries[0]!.params).toEqual([ORG1, "ra-001", NOW.toISOString()]); + }); + + it("returns not_found when assignment already revoked", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createMembershipRepository(executor); + + const result = await repo.revokeRoleAssignment(ORG1, "ra-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("safe error handling", () => { + it("never exposes raw SQL errors in repository outputs", async () => { + const pgError = new Error( + 'relation "membership_organizations" does not exist at character 15', + ); + const { executor } = createFakeExecutor({ error: pgError }); + const repo = createMembershipRepository(executor); + + const result = await repo.getOrganizationById(ORG1); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("relation"); + expect(result.error.message).not.toContain("character 15"); + } + }); + + it("never exposes connection strings in errors", async () => { + const connError = new Error( + "could not connect to postgres://admin:secret@db.internal:5432/prod", + ); + const { executor } = createFakeExecutor({ error: connError }); + const repo = createMembershipRepository(executor); + + const result = await repo.createOrganization({ + id: ORG1, + name: "Test", + slug: "test", + slugLower: "test", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("admin"); + expect(result.error.message).not.toContain("secret"); + expect(result.error.message).not.toContain("db.internal"); + } + }); + + it("never exposes invitation token hashes in error outputs", async () => { + const { executor } = createFakeExecutor({ + error: new Error("duplicate key value (token_hash)=(secret-token-hash-value)"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createInvitation({ + id: "inv-001", + orgId: ORG1, + email: "test@example.com", + emailLower: "test@example.com", + role: "viewer", + tokenHash: "secret-token-hash-value", + invitedBy: "usr-001", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + const serialized = JSON.stringify(result.error); + expect(serialized).not.toContain("secret-token-hash-value"); + } + }); + + it("never exposes emails in internal error messages", async () => { + const { executor } = createFakeExecutor({ + error: new Error("constraint violation for email user@secret-domain.com"), + }); + const repo = createMembershipRepository(executor); + + const result = await repo.createInvitation({ + id: "inv-001", + orgId: ORG1, + email: "user@secret-domain.com", + emailLower: "user@secret-domain.com", + role: "viewer", + tokenHash: "hash", + invitedBy: "usr-001", + expiresAt: FUTURE, + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("user@secret-domain.com"); + } + }); + }); + + describe("listOrganizationsForSubjectPaged", () => { + it("uses parameterized query with deterministic ordering and limit+1", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ORG_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listOrganizationsForSubjectPaged("usr-001", { limit: 10, cursor: null }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("ORDER BY"); + expect(queries[0]!.text).toContain("LIMIT"); + expect(queries[0]!.params).toEqual(["usr-001", 11]); + }); + + it("applies cursor filtering with timestamp and id tie-breaker", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + await repo.listOrganizationsForSubjectPaged("usr-001", { + limit: 5, + cursor: { createdAt: "2026-01-15T10:00:00.000Z", id: ORG1 }, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.params).toEqual(["usr-001", 6, "2026-01-15T10:00:00.000Z", ORG1]); + }); + + it("returns nextCursor when more rows exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_ORG_ROW, + id: `org-${String(i).padStart(3, "0")}`, + created_at: new Date(NOW.getTime() - i * 1000).toISOString(), + updated_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listOrganizationsForSubjectPaged("usr-001", { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("org-001"); + } + }); + + it("returns null nextCursor when no more rows", async () => { + const rows = [SAMPLE_ORG_ROW]; + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listOrganizationsForSubjectPaged("usr-001", { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns empty result safely", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listOrganizationsForSubjectPaged("usr-001", { limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(0); + expect(result.value.nextCursor).toBeNull(); + } + }); + }); + + describe("listMembersPaged", () => { + it("uses parameterized query with deterministic ordering and limit+1", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_MEMBER_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listMembersPaged(ORG1, { limit: 10, cursor: null }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("ORDER BY"); + expect(queries[0]!.text).toContain("LIMIT"); + expect(queries[0]!.params).toEqual([ORG1, 11]); + }); + + it("applies cursor filtering with timestamp and id tie-breaker", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + await repo.listMembersPaged(ORG1, { + limit: 5, + cursor: { createdAt: "2026-01-15T10:00:00.000Z", id: "mem-001" }, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.params).toEqual([ORG1, 6, "2026-01-15T10:00:00.000Z", "mem-001"]); + }); + + it("returns nextCursor when more rows exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_MEMBER_ROW, + id: `mem-${String(i).padStart(3, "0")}`, + created_at: new Date(NOW.getTime() - i * 1000).toISOString(), + updated_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listMembersPaged(ORG1, { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("mem-001"); + } + }); + + it("returns null nextCursor when no more rows", async () => { + const rows = [SAMPLE_MEMBER_ROW]; + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listMembersPaged(ORG1, { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns empty result safely", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listMembersPaged(ORG1, { limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(0); + expect(result.value.nextCursor).toBeNull(); + } + }); + }); + + describe("Worker-safe import isolation", () => { + it("does not import runner-only modules", async () => { + const mod = await import("@saas/db/membership"); + const exportKeys = Object.keys(mod); + + expect(exportKeys).toContain("createMembershipRepository"); + expect(exportKeys).not.toContain("runMigrations"); + expect(exportKeys).not.toContain("D1ApiAdapter"); + expect(exportKeys).not.toContain("loadD1CredentialsFromEnv"); + }); + }); + + describe("listInvitationsPaged", () => { + it("uses parameterized query with deterministic ordering and limit+1", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + await repo.listInvitationsPaged(ORG1, { limit: 10, cursor: null }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("ORDER BY"); + expect(queries[0]!.text).toContain("LIMIT"); + expect(queries[0]!.params).toEqual([ORG1, 11]); + }); + + it("applies cursor filtering with timestamp and id tie-breaker", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + await repo.listInvitationsPaged(ORG1, { + limit: 5, + cursor: { createdAt: "2026-01-15T10:00:00.000Z", id: "inv-001" }, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.params).toEqual([ORG1, 6, "2026-01-15T10:00:00.000Z", "inv-001"]); + }); + + it("returns nextCursor when more rows exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_INVITATION_ROW, + id: `inv-${String(i).padStart(3, "0")}`, + created_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listInvitationsPaged(ORG1, { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("inv-001"); + } + }); + + it("returns null nextCursor when no more rows", async () => { + const rows = [SAMPLE_INVITATION_ROW]; + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.listInvitationsPaged(ORG1, { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns empty result safely", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listInvitationsPaged(ORG1, { limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(0); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("does not expose token_hash in paginated results", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_INVITATION_ROW] }); + const repo = createMembershipRepository(executor); + + const result = await repo.listInvitationsPaged(ORG1, { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items[0]).not.toHaveProperty("tokenHash"); + expect(result.value.items[0]).not.toHaveProperty("token_hash"); + } + }); + }); + + describe("revokeAllRoleAssignments", () => { + it("uses parameterized SQL with org_id and subject_id", async () => { + const { executor, queries } = createFakeExecutor({ + rows: [{ ...SAMPLE_ROLE_ASSIGNMENT_ROW, revoked_at: NOW.toISOString() }], + }); + const repo = createMembershipRepository(executor); + + await repo.revokeAllRoleAssignments(ORG1, "usr-001", NOW); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + expect(queries[0]!.params).toEqual([ORG1, "usr-001", NOW.toISOString()]); + }); + + it("returns all revoked role assignments", async () => { + const rows = [ + { ...SAMPLE_ROLE_ASSIGNMENT_ROW, id: "ra-001", revoked_at: NOW.toISOString() }, + { ...SAMPLE_ROLE_ASSIGNMENT_ROW, id: "ra-002", role: "admin", revoked_at: NOW.toISOString() }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createMembershipRepository(executor); + + const result = await repo.revokeAllRoleAssignments(ORG1, "usr-001", NOW); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).toHaveLength(2); + expect(result.value[0]!.id).toBe("ra-001"); + expect(result.value[1]!.id).toBe("ra-002"); + } + }); + + it("returns empty array when no active assignments exist", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createMembershipRepository(executor); + + const result = await repo.revokeAllRoleAssignments(ORG1, "usr-001", NOW); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toEqual([]); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ error: new Error("connection refused") }); + const repo = createMembershipRepository(executor); + + const result = await repo.revokeAllRoleAssignments(ORG1, "usr-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("connection refused"); + } + }); + }); + + describe("countActiveOwners", () => { + it("uses parameterized SQL joining members and role_assignments", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{ cnt: "2" }] }); + const repo = createMembershipRepository(executor); + + await repo.countActiveOwners(ORG1); + + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("role = 'owner'"); + expect(queries[0]!.text).toContain("scope_kind = 'organization'"); + expect(queries[0]!.text).toContain("revoked_at IS NULL"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG1]); + }); + + it("returns count of active owners", async () => { + const { executor } = createFakeExecutor({ rows: [{ cnt: "3" }] }); + const repo = createMembershipRepository(executor); + + const result = await repo.countActiveOwners(ORG1); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(3); + }); + + it("returns 0 when no active owners", async () => { + const { executor } = createFakeExecutor({ rows: [{ cnt: "0" }] }); + const repo = createMembershipRepository(executor); + + const result = await repo.countActiveOwners(ORG1); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(0); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ error: new Error("timeout") }); + const repo = createMembershipRepository(executor); + + const result = await repo.countActiveOwners(ORG1); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + } + }); + }); + + describe("countBillableMembers", () => { + it("uses parameterized SQL summing active members and pending non-expired invitations", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{ cnt: "5" }] }); + const repo = createMembershipRepository(executor); + const now = new Date("2026-01-15T10:00:00Z"); + + await repo.countBillableMembers(ORG1, now); + + const sql = queries[0]!.text; + expect(sql).toContain("$1"); + expect(sql).toContain("$2"); + expect(sql).toContain("membership_organization_members"); + expect(sql).toContain("status = 'active'"); + expect(sql).toContain("membership_organization_invitations"); + expect(sql).toContain("status = 'pending'"); + expect(sql).toContain("revoked_at IS NULL"); + expect(sql).toContain("accepted_at IS NULL"); + expect(sql).toContain("expires_at > $2"); + expect(queries[0]!.params).toEqual([ORG1, now.toISOString()]); + }); + + it("returns the combined billable count", async () => { + const { executor } = createFakeExecutor({ rows: [{ cnt: "7" }] }); + const repo = createMembershipRepository(executor); + + const result = await repo.countBillableMembers(ORG1, new Date()); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(7); + }); + + it("returns 0 when org has no members or pending invitations", async () => { + const { executor } = createFakeExecutor({ rows: [{ cnt: "0" }] }); + const repo = createMembershipRepository(executor); + + const result = await repo.countBillableMembers(ORG_EMPTY, new Date()); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(0); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ error: new Error("connection refused") }); + const repo = createMembershipRepository(executor); + + const result = await repo.countBillableMembers(ORG1, new Date()); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("connection refused"); + } + }); + }); +}); diff --git a/tests/db/src/metering.test.ts b/tests/db/src/metering.test.ts new file mode 100644 index 0000000..ce97600 --- /dev/null +++ b/tests/db/src/metering.test.ts @@ -0,0 +1,737 @@ +import { createMeteringRepository } from "@saas/db/metering"; +import type { + RecordUsageInput, +} from "@saas/db/metering"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +// ── Mock executor ────────────────────────────────────────── + +interface MockCall { + sql: string; + params: unknown[]; +} + +function createMockExecutor( + handler?: (sql: string, params: unknown[]) => SqlExecutorResult>, +): SqlExecutor & { calls: MockCall[] } { + const calls: MockCall[] = []; + return { + calls, + async execute( + text: string, + params: unknown[] = [], + ): Promise> { + calls.push({ sql: text, params }); + if (handler) { + return handler(text, params) as unknown as SqlExecutorResult; + } + return { rows: [] as T[], rowCount: 0 }; + }, + }; +} + +// ── Test data factories ──────────────────────────────────── + +const ORG_ID = "org-test-001"; +const PROJECT_ID = "proj-test-001"; +const ENV_ID = "env-test-001"; + +function makeUsageInput(overrides: Partial = {}): RecordUsageInput { + return { + id: "usage-001", + orgId: ORG_ID, + metric: "api_requests", + quantity: 1, + idempotencyKey: "idem-001", + ...overrides, + }; +} + +function makeUsageRow(overrides: Record = {}): Record { + return { + id: "usage-001", + org_id: ORG_ID, + project_id: null, + environment_id: null, + resource_id: null, + metric: "api_requests", + quantity: "1", + idempotency_key: "idem-001", + recorded_at: "2026-01-01T00:00:00.000Z", + metadata: null, + created_at: "2026-01-01T00:00:00.000Z", + ...overrides, + }; +} + +function makeRollupRow(overrides: Record = {}): Record { + return { + id: "rollup-001", + org_id: ORG_ID, + project_id: null, + environment_id: null, + metric: "api_requests", + bucket_type: "hour", + bucket_start: "2026-01-01T00:00:00.000Z", + quantity: "100", + record_count: "10", + created_at: "2026-01-01T00:00:00.000Z", + updated_at: "2026-01-01T00:00:00.000Z", + ...overrides, + }; +} + +function makeViolationRow(overrides: Record = {}): Record { + return { + id: "violation-001", + org_id: ORG_ID, + project_id: null, + environment_id: null, + resource_id: null, + quota_id: "quota-001", + metric: "api_requests", + limit_value: "1000", + actual_value: "1050", + period: "month", + enforcement: "soft", + violated_at: "2026-01-01T12:00:00.000Z", + resolved_at: null, + metadata: null, + created_at: "2026-01-01T12:00:00.000Z", + ...overrides, + }; +} + +// ── Tests ────────────────────────────────────────────────── + +describe("Metering Repository", () => { + describe("recordUsage", () => { + it("inserts a usage record and returns it", async () => { + const row = makeUsageRow(); + const executor = createMockExecutor(() => ({ + rows: [row], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + const result = await repo.recordUsage(makeUsageInput()); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("usage-001"); + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.metric).toBe("api_requests"); + expect(result.value.quantity).toBe(1); + expect(result.value.idempotencyKey).toBe("idem-001"); + } + }); + + it("returns conflict for duplicate idempotency key", async () => { + const executor = createMockExecutor(() => ({ + rows: [], + rowCount: 0, + })); + const repo = createMeteringRepository(executor); + const result = await repo.recordUsage(makeUsageInput()); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + expect(result.error).toHaveProperty("entity", "usage_record"); + } + }); + + it("handles unique violation errors", async () => { + const executor = createMockExecutor(() => { + throw new Error( + "D1_ERROR: UNIQUE constraint failed: metering_usage_records.idempotency_key", + ); + }); + const repo = createMeteringRepository(executor); + const result = await repo.recordUsage(makeUsageInput()); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("passes orgId as parameter — never interpolated into SQL", async () => { + const executor = createMockExecutor(() => ({ + rows: [makeUsageRow()], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + await repo.recordUsage(makeUsageInput()); + + expect(executor.calls.length).toBe(1); + const call = executor.calls[0]!; + // orgId must be in params, not spliced into the SQL string + expect(call.params).toContain(ORG_ID); + // SQL should use $N placeholders, not raw values + expect(call.sql).toContain("$1"); + expect(call.sql).not.toContain(`'${ORG_ID}'`); + }); + + it("stores optional project/environment/resource scope", async () => { + const row = makeUsageRow({ + project_id: PROJECT_ID, + environment_id: ENV_ID, + resource_id: "res-001", + }); + const executor = createMockExecutor(() => ({ + rows: [row], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + const result = await repo.recordUsage( + makeUsageInput({ + projectId: PROJECT_ID, + environmentId: ENV_ID, + resourceId: "res-001", + }), + ); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.projectId).toBe(PROJECT_ID); + expect(result.value.environmentId).toBe(ENV_ID); + expect(result.value.resourceId).toBe("res-001"); + } + }); + + it("stores and returns safe metadata", async () => { + const meta = { source: "api", region: "us-east-1" }; + const row = makeUsageRow({ metadata: meta }); + const executor = createMockExecutor(() => ({ + rows: [row], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + const result = await repo.recordUsage( + makeUsageInput({ metadata: meta }), + ); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.metadata).toEqual(meta); + } + }); + }); + + describe("ingestUsageBatch", () => { + it("processes each record individually and returns per-record results", async () => { + let callCount = 0; + const executor = createMockExecutor(() => { + callCount++; + if (callCount === 2) { + // Second record conflicts + return { rows: [], rowCount: 0 }; + } + return { + rows: [makeUsageRow({ id: `usage-${callCount}`, idempotency_key: `idem-${callCount}` })], + rowCount: 1, + }; + }); + const repo = createMeteringRepository(executor); + + const result = await repo.ingestUsageBatch([ + makeUsageInput({ id: "usage-1", idempotencyKey: "idem-1" }), + makeUsageInput({ id: "usage-2", idempotencyKey: "idem-2" }), + makeUsageInput({ id: "usage-3", idempotencyKey: "idem-3" }), + ]); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.results).toHaveLength(3); + expect(result.value.results[0]!.ok).toBe(true); + expect(result.value.results[1]!.ok).toBe(false); + expect(result.value.results[2]!.ok).toBe(true); + } + }); + }); + + describe("getUsageSummary", () => { + it("returns aggregated rollup data", async () => { + const executor = createMockExecutor(() => ({ + rows: [ + makeRollupRow({ quantity: "50", record_count: "5" }), + makeRollupRow({ id: "rollup-002", quantity: "30", record_count: "3" }), + ], + rowCount: 2, + })); + const repo = createMeteringRepository(executor); + const result = await repo.getUsageSummary({ + orgId: ORG_ID, + metric: "api_requests", + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.metric).toBe("api_requests"); + expect(result.value.totalQuantity).toBe(80); + expect(result.value.totalRecords).toBe(8); + expect(result.value.rollups).toHaveLength(2); + } + }); + + it("requires orgId in query — always includes org_id = $1", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.getUsageSummary({ orgId: ORG_ID, metric: "api_requests" }); + + expect(executor.calls[0]!.sql).toContain("org_id = $1"); + expect(executor.calls[0]!.params[0]).toBe(ORG_ID); + }); + + it("applies optional project/environment filters", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.getUsageSummary({ + orgId: ORG_ID, + metric: "api_requests", + projectId: PROJECT_ID, + environmentId: ENV_ID, + }); + + const call = executor.calls[0]!; + expect(call.sql).toContain("project_id = $3"); + expect(call.sql).toContain("environment_id = $4"); + expect(call.params).toContain(PROJECT_ID); + expect(call.params).toContain(ENV_ID); + }); + }); + + describe("materializeUsageRollups", () => { + const WIN_START = new Date("2026-03-15T11:00:00.000Z"); + const WIN_END = new Date("2026-03-15T13:00:00.000Z"); + + it("aggregates raw usage into rollups grouped by org/project/env/metric/bucket", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 4 })); + const repo = createMeteringRepository(executor); + + const result = await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.bucketType).toBe("hour"); + expect(result.value.rollupsWritten).toBe(4); + expect(result.value.windowStart).toEqual(WIN_START); + expect(result.value.windowEnd).toEqual(WIN_END); + } + + const call = executor.calls[0]!; + // Grouping must include org_id + project_id + environment_id + metric + bucket + expect(call.sql).toMatch( + /GROUP BY\s+org_id,\s*project_id,\s*environment_id,\s*metric,\s*strftime/i, + ); + // Window is parameter-bound, not interpolated + expect(call.sql).toContain("recorded_at >= $2"); + expect(call.sql).toContain("recorded_at < $3"); + expect(call.params[0]).toBe("hour"); + expect(call.params[1]).toBe(WIN_START.toISOString()); + expect(call.params[2]).toBe(WIN_END.toISOString()); + }); + + it("supports both hour and day bucket types via the same seam", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + + await repo.materializeUsageRollups({ + bucketType: "day", + start: new Date("2026-03-14T00:00:00.000Z"), + end: new Date("2026-03-16T00:00:00.000Z"), + }); + + expect(executor.calls[0]!.params[0]).toBe("day"); + }); + + it("is idempotent — issues an INSERT ... ON CONFLICT ... DO UPDATE upsert", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + + await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + + const sql = executor.calls[0]!.sql; + expect(sql).toMatch(/INSERT INTO metering_usage_rollups/i); + expect(sql).toMatch(/ON CONFLICT[\s\S]*DO UPDATE SET/i); + // The conflict key must mirror the unique index on the table: + // (org_id, COALESCE(project_id,''), COALESCE(environment_id,''), metric, bucket_type, bucket_start) + expect(sql).toMatch(/ON CONFLICT[\s\S]*org_id[\s\S]*COALESCE\(project_id/i); + expect(sql).toMatch(/ON CONFLICT[\s\S]*COALESCE\(environment_id/i); + expect(sql).toMatch(/ON CONFLICT[\s\S]*metric[\s\S]*bucket_type[\s\S]*bucket_start/i); + // Updated columns are the aggregate values + updated_at, not the id. + expect(sql).toMatch(/quantity\s*=\s*EXCLUDED\.quantity/i); + expect(sql).toMatch(/record_count\s*=\s*EXCLUDED\.record_count/i); + expect(sql).toMatch(/updated_at\s*=\s*strftime\('%Y-%m-%dT%H:%M:%fZ','now'\)/i); + }); + + it("emits a deterministic id derived from the full aggregation key (org + project + env + metric + bucket_type + bucket_start)", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + + await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + + const sql = executor.calls[0]!.sql; + // The id IS the aggregation key — same inputs produce the same id on + // re-run. (SQLite has no md5, and the key was already unique; hashing + // only shortened it.) + expect(sql).toMatch(/org_id\s*\|\|/i); + expect(sql).toMatch(/COALESCE\(project_id,\s*''\)\s*\|\|/i); + expect(sql).toMatch(/COALESCE\(environment_id,\s*''\)\s*\|\|/i); + expect(sql).toMatch(/metric\s*\|\|/i); + expect(sql).toMatch(/bucket_start AS id/i); + }); + + it("never aggregates across organizations — org_id is always in GROUP BY", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + + await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + + const sql = executor.calls[0]!.sql; + const groupBy = sql.match(/GROUP BY[^)]*\)?/i)?.[0] ?? ""; + expect(groupBy.toLowerCase()).toContain("org_id"); + }); + + it("uses parameterized SQL only — window bounds are not interpolated", async () => { + const executor = createMockExecutor((sql) => { + expect(sql).not.toContain(WIN_START.toISOString()); + expect(sql).not.toContain(WIN_END.toISOString()); + return { rows: [], rowCount: 0 }; + }); + const repo = createMeteringRepository(executor); + await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + }); + + it("rejects an invalid bucket_type without issuing SQL", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + const result = await repo.materializeUsageRollups({ + bucketType: "minute" as unknown as "hour", + start: WIN_START, + end: WIN_END, + }); + expect(result.ok).toBe(false); + expect(executor.calls).toHaveLength(0); + }); + + it("rejects an inverted/empty window without issuing SQL", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + const result = await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_END, + end: WIN_START, + }); + expect(result.ok).toBe(false); + expect(executor.calls).toHaveLength(0); + }); + + it("returns a safe internal error on executor failure — no raw error leaked", async () => { + const executor = createMockExecutor(() => { + throw new Error("connection refused to host db.internal:5432"); + }); + const repo = createMeteringRepository(executor); + const result = await repo.materializeUsageRollups({ + bucketType: "hour", + start: WIN_START, + end: WIN_END, + }); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + if (result.error.kind === "internal") { + expect(result.error.message).not.toContain("db.internal"); + expect(result.error.message).not.toContain("connection refused"); + } + } + }); + }); + + describe("listUsageRollups", () => { + it("paginates rollups by org", async () => { + const executor = createMockExecutor(() => ({ + rows: [makeRollupRow()], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + const result = await repo.listUsageRollups(ORG_ID, { + limit: 10, + cursor: null, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("always requires orgId — first param is org_id", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.listUsageRollups(ORG_ID, { limit: 10, cursor: null }); + + expect(executor.calls[0]!.sql).toContain("org_id = $1"); + expect(executor.calls[0]!.params[0]).toBe(ORG_ID); + }); + }); + + describe("checkQuota", () => { + it("returns allowed=true with no_quota_defined when no quota exists", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + const result = await repo.checkQuota(ORG_ID, "api_requests"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.allowed).toBe(true); + expect(result.value.limit).toBe(-1); + expect(result.value.remaining).toBe(-1); + expect(result.value.reason).toBe("no_quota_defined"); + } + }); + + it("returns allowed=true when usage is under limit", async () => { + let callCount = 0; + const executor = createMockExecutor(() => { + callCount++; + if (callCount === 1) { + // Quota definition + return { + rows: [{ + id: "quota-001", + org_id: ORG_ID, + project_id: null, + environment_id: null, + resource_id: null, + metric: "api_requests", + limit_value: "1000", + period: "month", + enforcement: "soft", + status: "active", + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }], + rowCount: 1, + }; + } + // Usage sum + return { rows: [{ total: "500" }], rowCount: 1 }; + }); + const repo = createMeteringRepository(executor); + const result = await repo.checkQuota(ORG_ID, "api_requests"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.allowed).toBe(true); + expect(result.value.limit).toBe(1000); + expect(result.value.used).toBe(500); + expect(result.value.remaining).toBe(500); + expect(result.value.reason).toBeNull(); + } + }); + + it("returns allowed=false when usage exceeds limit", async () => { + let callCount = 0; + const executor = createMockExecutor(() => { + callCount++; + if (callCount === 1) { + return { + rows: [{ + id: "quota-001", + org_id: ORG_ID, + project_id: null, + environment_id: null, + resource_id: null, + metric: "api_requests", + limit_value: "1000", + period: "month", + enforcement: "hard", + status: "active", + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }], + rowCount: 1, + }; + } + return { rows: [{ total: "1500" }], rowCount: 1 }; + }); + const repo = createMeteringRepository(executor); + const result = await repo.checkQuota(ORG_ID, "api_requests"); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.allowed).toBe(false); + expect(result.value.limit).toBe(1000); + expect(result.value.used).toBe(1500); + expect(result.value.remaining).toBe(0); + expect(result.value.enforcement).toBe("hard"); + expect(result.value.reason).toBe("quota_exceeded"); + } + }); + + it("always requires orgId — SQL includes org_id = $1", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.checkQuota(ORG_ID, "api_requests"); + + expect(executor.calls[0]!.sql).toContain("org_id = $1"); + expect(executor.calls[0]!.params[0]).toBe(ORG_ID); + }); + + it("returns structured facts — does not throw on exceeded quota", async () => { + let callCount = 0; + const executor = createMockExecutor(() => { + callCount++; + if (callCount === 1) { + return { + rows: [{ + id: "quota-001", org_id: ORG_ID, project_id: null, environment_id: null, + resource_id: null, metric: "api_requests", limit_value: "100", + period: "day", enforcement: "hard", status: "active", + created_at: "2026-01-01T00:00:00Z", updated_at: "2026-01-01T00:00:00Z", + }], + rowCount: 1, + }; + } + return { rows: [{ total: "200" }], rowCount: 1 }; + }); + const repo = createMeteringRepository(executor); + + // Should not throw + const result = await repo.checkQuota(ORG_ID, "api_requests"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value).toHaveProperty("allowed"); + expect(result.value).toHaveProperty("limit"); + expect(result.value).toHaveProperty("used"); + expect(result.value).toHaveProperty("remaining"); + expect(result.value).toHaveProperty("period"); + expect(result.value).toHaveProperty("enforcement"); + expect(result.value).toHaveProperty("reason"); + } + }); + }); + + describe("listQuotaViolations", () => { + it("lists violations by org", async () => { + const executor = createMockExecutor(() => ({ + rows: [makeViolationRow()], + rowCount: 1, + })); + const repo = createMeteringRepository(executor); + const result = await repo.listQuotaViolations( + { orgId: ORG_ID }, + { limit: 10, cursor: null }, + ); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + const v = result.value.items[0]!; + expect(v.orgId).toBe(ORG_ID); + expect(v.metric).toBe("api_requests"); + expect(v.limitValue).toBe(1000); + expect(v.actualValue).toBe(1050); + } + }); + + it("applies optional project/environment/resource/metric filters", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.listQuotaViolations( + { + orgId: ORG_ID, + projectId: PROJECT_ID, + environmentId: ENV_ID, + resourceId: "res-001", + metric: "api_requests", + }, + { limit: 10, cursor: null }, + ); + + const call = executor.calls[0]!; + expect(call.sql).toContain("org_id = $1"); + expect(call.sql).toContain("project_id = $2"); + expect(call.sql).toContain("environment_id = $3"); + expect(call.sql).toContain("resource_id = $4"); + expect(call.sql).toContain("metric = $5"); + expect(call.params).toContain(ORG_ID); + expect(call.params).toContain(PROJECT_ID); + expect(call.params).toContain(ENV_ID); + expect(call.params).toContain("res-001"); + expect(call.params).toContain("api_requests"); + }); + + it("always requires orgId — cannot query without it", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + await repo.listQuotaViolations( + { orgId: ORG_ID }, + { limit: 10, cursor: null }, + ); + + expect(executor.calls[0]!.sql).toContain("org_id = $1"); + expect(executor.calls[0]!.params[0]).toBe(ORG_ID); + }); + }); + + describe("SQL parameterization invariant", () => { + it("no repository method interpolates user values into SQL text", async () => { + const executor = createMockExecutor((sql) => { + // Verify no raw org/project/env IDs appear in SQL text + expect(sql).not.toContain(`'${ORG_ID}'`); + expect(sql).not.toContain(`'${PROJECT_ID}'`); + expect(sql).not.toContain(`'${ENV_ID}'`); + return { rows: [makeUsageRow()], rowCount: 1 }; + }); + const repo = createMeteringRepository(executor); + + // Exercise all methods + await repo.recordUsage(makeUsageInput({ projectId: PROJECT_ID, environmentId: ENV_ID })); + await repo.getUsageSummary({ orgId: ORG_ID, metric: "api_requests", projectId: PROJECT_ID }); + await repo.listUsageRollups(ORG_ID, { limit: 10, cursor: null }); + await repo.listQuotaViolations({ orgId: ORG_ID, projectId: PROJECT_ID }, { limit: 10, cursor: null }); + }); + }); + + describe("org scoping enforcement", () => { + it("every query method includes orgId as a required SQL condition", async () => { + const executor = createMockExecutor(() => ({ rows: [], rowCount: 0 })); + const repo = createMeteringRepository(executor); + + // All these methods require orgId + await repo.recordUsage(makeUsageInput()); + await repo.getUsageSummary({ orgId: ORG_ID, metric: "m" }); + await repo.listUsageRollups(ORG_ID, { limit: 10, cursor: null }); + await repo.checkQuota(ORG_ID, "m"); + await repo.listQuotaViolations({ orgId: ORG_ID }, { limit: 10, cursor: null }); + + // Every single SQL call must reference org_id + for (const call of executor.calls) { + expect(call.sql.toLowerCase()).toContain("org_id"); + } + }); + }); +}); diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts new file mode 100644 index 0000000..8cb8292 --- /dev/null +++ b/tests/db/src/migrations.test.ts @@ -0,0 +1,124 @@ +import { createHash } from "node:crypto"; +import { readFileSync, existsSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest, BOUNDED_CONTEXTS } from "@saas/db"; +import type { BoundedContext, MigrationEntry } from "@saas/db"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve( + __dirname, + "../../..", + "packages/db/src/migrations" +); + +function computeChecksum(filePath: string): string { + const content = readFileSync(filePath); + return createHash("sha256").update(content).digest("hex"); +} + +describe("Migration Manifest Verifier", () => { + const { migrations } = manifest; + + it("manifest has version 1", () => { + expect(manifest.version).toBe(1); + }); + + it("has at least one migration", () => { + expect(migrations.length).toBeGreaterThan(0); + }); + + describe("ID uniqueness and ordering", () => { + it("all migration IDs are unique", () => { + const ids = migrations.map((m) => m.id); + expect(new Set(ids).size).toBe(ids.length); + }); + + it("migration IDs are sorted in ascending lexicographic order", () => { + const ids = migrations.map((m) => m.id); + const sorted = [...ids].sort(); + expect(ids).toEqual(sorted); + }); + + it("migration IDs follow the naming convention", () => { + const pattern = /^\d{3}_[a-z]+_[a-z][a-z0-9_]*$/; + for (const m of migrations) { + expect(m.id).toMatch(pattern); + } + }); + }); + + describe("bounded context ownership", () => { + const VALID_CONTEXTS = BOUNDED_CONTEXTS; + + it("each migration declares a valid bounded context", () => { + for (const m of migrations) { + expect(VALID_CONTEXTS).toContain(m.context); + } + }); + }); + + describe("file existence and manifest completeness", () => { + it("each migration file exists on disk", () => { + for (const m of migrations) { + const fullPath = resolve(MIGRATIONS_ROOT, m.path); + expect(existsSync(fullPath)).toBe(true); + } + }); + }); + + describe("checksum integrity (drift detection)", () => { + it.each(migrations.map((m) => [m.id, m] as [string, MigrationEntry]))( + "checksum matches for %s", + (_id, m) => { + const fullPath = resolve(MIGRATIONS_ROOT, m.path); + const actual = computeChecksum(fullPath); + expect(actual).toBe(m.checksum); + } + ); + }); + + describe("tenant isolation invariant", () => { + it("project-scoped migrations reference org_id + project_id pattern", () => { + const PROJECT_SCOPED_CONTEXTS: BoundedContext[] = ["projects"]; + + const projectMigrations = migrations.filter((m) => + PROJECT_SCOPED_CONTEXTS.includes(m.context) + ); + + for (const m of projectMigrations) { + const fullPath = resolve(MIGRATIONS_ROOT, m.path); + const sql = readFileSync(fullPath, "utf-8"); + expect(sql).toContain("org_id"); + expect(sql).toContain("project_id"); + } + + expect(true).toBe(true); + }); + + it("project-scoped migrations do not reference other bounded-context schemas", () => { + const PROJECT_SCOPED_CONTEXTS: BoundedContext[] = ["projects"]; + const FORBIDDEN_REFS = ["membership.", "identity.", "billing.", "events."]; + + const projectMigrations = migrations.filter((m) => + PROJECT_SCOPED_CONTEXTS.includes(m.context) + ); + + for (const m of projectMigrations) { + const fullPath = resolve(MIGRATIONS_ROOT, m.path); + const sql = readFileSync(fullPath, "utf-8"); + for (const ref of FORBIDDEN_REFS) { + expect(sql).not.toContain(ref); + } + } + }); + }); + + describe("migration description", () => { + it("each migration has a non-empty description", () => { + for (const m of migrations) { + expect(m.description.length).toBeGreaterThan(0); + } + }); + }); +}); diff --git a/tests/db/src/projects.test.ts b/tests/db/src/projects.test.ts new file mode 100644 index 0000000..4b72308 --- /dev/null +++ b/tests/db/src/projects.test.ts @@ -0,0 +1,796 @@ +import { + createProjectsRepository, +} from "@saas/db/projects"; +import { asUuid } from "@saas/db"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +const ORG_ID = asUuid("aaaaaaaa-0001-0001-0001-000000000001"); +const PRJ_ID = asUuid("bbbbbbbb-0001-0001-0001-000000000001"); + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + if (options?.error) { + throw options.error; + } + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); + +const SAMPLE_PROJECT_ROW = { + id: "prj-001", + org_id: ORG_ID, + name: "My Project", + slug: "my-project", + slug_lower: "my-project", + status: "active", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), + archived_at: null, +}; + +const SAMPLE_ENVIRONMENT_ROW = { + id: "env-001", + org_id: ORG_ID, + project_id: "prj-001", + name: "Production", + slug: "production", + slug_lower: "production", + status: "active", + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), + archived_at: null, +}; + +describe("ProjectsRepository", () => { + describe("createProject", () => { + it("uses parameterized query for project creation", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.createProject({ + id: "prj-001", + orgId: ORG_ID, + name: "My Project", + slug: "my-project", + slugLower: "my-project", + createdAt: NOW, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$2"); + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.text).toContain("$5"); + expect(queries[0]!.text).toContain("$6"); + expect(queries[0]!.params).toEqual([ + "prj-001", + ORG_ID, + "My Project", + "my-project", + "my-project", + NOW.toISOString(), + ]); + }); + + it("maps returned row to Project type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + const result = await repo.createProject({ + id: "prj-001", + orgId: ORG_ID, + name: "My Project", + slug: "my-project", + slugLower: "my-project", + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("prj-001"); + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.name).toBe("My Project"); + expect(result.value.slugLower).toBe("my-project"); + expect(result.value.status).toBe("active"); + expect(result.value.createdAt).toEqual(NOW); + expect(result.value.archivedAt).toBeNull(); + } + }); + + it("returns conflict on duplicate project", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createProjectsRepository(executor); + + const result = await repo.createProject({ + id: "prj-001", + orgId: ORG_ID, + name: "My Project", + slug: "my-project", + slugLower: "my-project", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("returns conflict on unique violation error code", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createProjectsRepository(executor); + + const result = await repo.createProject({ + id: "prj-002", + orgId: ORG_ID, + name: "My Project", + slug: "my-project", + slugLower: "my-project", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("conflict"); + } + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ + error: new Error("connection to host 10.0.0.1:5432 refused"), + }); + const repo = createProjectsRepository(executor); + + const result = await repo.createProject({ + id: "prj-001", + orgId: ORG_ID, + name: "Test", + slug: "test", + slugLower: "test", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("10.0.0.1"); + } + }); + }); + + describe("countActiveProjects", () => { + it("uses parameterized COUNT scoped by org_id and active status", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{ count: 3 }] }); + const repo = createProjectsRepository(executor); + + await repo.countActiveProjects(ORG_ID); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("COUNT(*)"); + expect(queries[0]!.text).toContain("projects_projects"); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG_ID]); + }); + + it("returns numeric count when pg returns a number", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: 7 }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(7); + }); + + it("coerces bigint count returned by pg", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: BigInt(42) }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(42); + }); + + it("coerces string count returned by pg (bigint-as-string)", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: "12" }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(12); + }); + + it("returns 0 when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(0); + }); + + it("returns safe internal error on executor failure", async () => { + const { executor } = createFakeExecutor({ + error: new Error("connection to 10.0.0.1:5432 refused"), + }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect( + (result.error as { kind: "internal"; message: string }).message, + ).not.toContain("10.0.0.1"); + } + }); + + it("returns safe internal error when count parses to NaN", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: "not-a-number" }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveProjects(ORG_ID); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); + }); + + describe("countActiveEnvironments", () => { + it("uses parameterized COUNT scoped by org_id, project_id, and active status", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{ count: 3 }] }); + const repo = createProjectsRepository(executor); + + await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("COUNT(*)"); + expect(queries[0]!.text).toContain("projects_environments"); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("project_id = $2"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID]); + }); + + it("returns numeric count when pg returns a number", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: 7 }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(7); + }); + + it("coerces bigint count returned by pg", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: BigInt(42) }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(42); + }); + + it("coerces string count returned by pg (bigint-as-string)", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: "12" }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(12); + }); + + it("returns 0 when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(true); + if (result.ok) expect(result.value).toBe(0); + }); + + it("returns safe internal error on executor failure", async () => { + const { executor } = createFakeExecutor({ + error: new Error("connection to 10.0.0.1:5432 refused"), + }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect( + (result.error as { kind: "internal"; message: string }).message, + ).not.toContain("10.0.0.1"); + } + }); + + it("returns safe internal error when count parses to NaN", async () => { + const { executor } = createFakeExecutor({ rows: [{ count: "not-a-number" }] }); + const repo = createProjectsRepository(executor); + + const result = await repo.countActiveEnvironments(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); + }); + + describe("getProjectById", () => { + it("includes org_id and project_id in query params", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.getProjectById(ORG_ID, PRJ_ID); + + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID]); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("id = $2"); + }); + + it("returns not_found when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.getProjectById(ORG_ID, asUuid("bbbbbbbb-0001-0001-0001-000000000099")); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("getProjectBySlug", () => { + it("scopes slug lookup by org_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.getProjectBySlug(ORG_ID, "my-project"); + + expect(queries[0]!.params).toEqual([ORG_ID, "my-project"]); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("slug_lower = $2"); + }); + + it("returns not_found for unknown slug", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.getProjectBySlug(ORG_ID, "unknown-slug"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("listProjectsPaged", () => { + it("uses deterministic ordering with limit+1 and org_id scope", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.listProjectsPaged(ORG_ID, { limit: 10, cursor: null }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("ORDER BY"); + expect(queries[0]!.text).toContain("LIMIT"); + expect(queries[0]!.params).toEqual([ORG_ID, 11]); + }); + + it("applies cursor filtering with timestamp and id tie-breaker", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + await repo.listProjectsPaged(ORG_ID, { + limit: 5, + cursor: { createdAt: "2026-01-15T10:00:00.000Z", id: "prj-001" }, + }); + + expect(queries[0]!.text).toContain("$3"); + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.params).toEqual([ORG_ID, 6, "2026-01-15T10:00:00.000Z", "prj-001"]); + }); + + it("returns nextCursor when more rows exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_PROJECT_ROW, + id: `prj-${String(i).padStart(3, "0")}`, + created_at: new Date(NOW.getTime() - i * 1000).toISOString(), + updated_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createProjectsRepository(executor); + + const result = await repo.listProjectsPaged(ORG_ID, { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("prj-001"); + } + }); + + it("returns null nextCursor when no more rows", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_PROJECT_ROW] }); + const repo = createProjectsRepository(executor); + + const result = await repo.listProjectsPaged(ORG_ID, { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns empty result safely", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.listProjectsPaged(ORG_ID, { limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(0); + expect(result.value.nextCursor).toBeNull(); + } + }); + }); + + describe("archiveProject", () => { + it("uses parameterized update with status = 'active' guard and org_id scope", async () => { + const archivedRow = { ...SAMPLE_PROJECT_ROW, status: "archived", archived_at: NOW.toISOString() }; + const { executor, queries } = createFakeExecutor({ rows: [archivedRow] }); + const repo = createProjectsRepository(executor); + + await repo.archiveProject(ORG_ID, PRJ_ID, NOW); + + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("id = $2"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, NOW.toISOString()]); + }); + + it("returns not_found when project already archived or does not exist", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createProjectsRepository(executor); + + const result = await repo.archiveProject(ORG_ID, PRJ_ID, NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ error: new Error("timeout") }); + const repo = createProjectsRepository(executor); + + const result = await repo.archiveProject(ORG_ID, PRJ_ID, NOW); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + } + }); + }); + + describe("createEnvironment", () => { + it("carries org_id and project_id in parameterized insert", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.createEnvironment({ + id: "env-001", + orgId: ORG_ID, + projectId: PRJ_ID, + name: "Production", + slug: "production", + slugLower: "production", + createdAt: NOW, + }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("$1"); + expect(queries[0]!.text).toContain("$7"); + expect(queries[0]!.params).toEqual([ + "env-001", + ORG_ID, + PRJ_ID, + "Production", + "production", + "production", + NOW.toISOString(), + ]); + }); + + it("maps returned row to Environment type", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + const result = await repo.createEnvironment({ + id: "env-001", + orgId: ORG_ID, + projectId: PRJ_ID, + name: "Production", + slug: "production", + slugLower: "production", + createdAt: NOW, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("env-001"); + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.projectId).toBe("prj-001"); + expect(result.value.name).toBe("Production"); + expect(result.value.archivedAt).toBeNull(); + } + }); + + it("returns conflict on unique violation", async () => { + const { executor } = createFakeExecutor({ + error: new Error("D1_ERROR: UNIQUE constraint failed"), + }); + const repo = createProjectsRepository(executor); + + const result = await repo.createEnvironment({ + id: "env-002", + orgId: ORG_ID, + projectId: PRJ_ID, + name: "Production", + slug: "production", + slugLower: "production", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + }); + + describe("getEnvironmentById", () => { + it("includes org_id + project_id + environment_id in query params", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.getEnvironmentById(ORG_ID, PRJ_ID, "env-001"); + + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, "env-001"]); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("project_id = $2"); + expect(queries[0]!.text).toContain("id = $3"); + }); + + it("returns not_found when no rows", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.getEnvironmentById(ORG_ID, PRJ_ID, "env-missing"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("getEnvironmentBySlug", () => { + it("scopes slug lookup by org_id + project_id", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.getEnvironmentBySlug(ORG_ID, PRJ_ID, "production"); + + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, "production"]); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("project_id = $2"); + expect(queries[0]!.text).toContain("slug_lower = $3"); + }); + + it("returns not_found for unknown slug", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.getEnvironmentBySlug(ORG_ID, PRJ_ID, "unknown"); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + }); + + describe("listEnvironmentsPaged", () => { + it("includes org_id + project_id and uses deterministic ordering", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + await repo.listEnvironmentsPaged(ORG_ID, PRJ_ID, { limit: 10, cursor: null }); + + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("project_id = $2"); + expect(queries[0]!.text).toContain("ORDER BY"); + expect(queries[0]!.text).toContain("LIMIT"); + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, 11]); + }); + + it("applies cursor filtering with timestamp and id tie-breaker", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + await repo.listEnvironmentsPaged(ORG_ID, PRJ_ID, { + limit: 5, + cursor: { createdAt: "2026-01-15T10:00:00.000Z", id: "env-001" }, + }); + + expect(queries[0]!.text).toContain("$4"); + expect(queries[0]!.text).toContain("$5"); + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, 6, "2026-01-15T10:00:00.000Z", "env-001"]); + }); + + it("returns nextCursor when more rows exist", async () => { + const rows = Array.from({ length: 3 }, (_, i) => ({ + ...SAMPLE_ENVIRONMENT_ROW, + id: `env-${String(i).padStart(3, "0")}`, + created_at: new Date(NOW.getTime() - i * 1000).toISOString(), + updated_at: new Date(NOW.getTime() - i * 1000).toISOString(), + })); + const { executor } = createFakeExecutor({ rows }); + const repo = createProjectsRepository(executor); + + const result = await repo.listEnvironmentsPaged(ORG_ID, PRJ_ID, { limit: 2, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(2); + expect(result.value.nextCursor).not.toBeNull(); + expect(result.value.nextCursor!.id).toBe("env-001"); + } + }); + + it("returns null nextCursor when no more rows", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_ENVIRONMENT_ROW] }); + const repo = createProjectsRepository(executor); + + const result = await repo.listEnvironmentsPaged(ORG_ID, PRJ_ID, { limit: 10, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).toBeNull(); + } + }); + + it("returns empty result safely", async () => { + const { executor } = createFakeExecutor({ rows: [] }); + const repo = createProjectsRepository(executor); + + const result = await repo.listEnvironmentsPaged(ORG_ID, PRJ_ID, { limit: 50, cursor: null }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(0); + expect(result.value.nextCursor).toBeNull(); + } + }); + }); + + describe("archiveEnvironment", () => { + it("uses parameterized update with org_id + project_id + id and active guard", async () => { + const archivedRow = { ...SAMPLE_ENVIRONMENT_ROW, status: "archived", archived_at: NOW.toISOString() }; + const { executor, queries } = createFakeExecutor({ rows: [archivedRow] }); + const repo = createProjectsRepository(executor); + + await repo.archiveEnvironment(ORG_ID, PRJ_ID, "env-001", NOW); + + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.text).toContain("project_id = $2"); + expect(queries[0]!.text).toContain("id = $3"); + expect(queries[0]!.text).toContain("status = 'active'"); + expect(queries[0]!.params).toEqual([ORG_ID, PRJ_ID, "env-001", NOW.toISOString()]); + }); + + it("returns not_found when environment already archived", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createProjectsRepository(executor); + + const result = await repo.archiveEnvironment(ORG_ID, PRJ_ID, "env-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("maps generic errors to safe internal error", async () => { + const { executor } = createFakeExecutor({ error: new Error("connection refused") }); + const repo = createProjectsRepository(executor); + + const result = await repo.archiveEnvironment(ORG_ID, PRJ_ID, "env-001", NOW); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.kind).toBe("internal"); + expect((result.error as { kind: "internal"; message: string }).message).not.toContain("connection refused"); + } + }); + }); + + describe("safe error handling", () => { + it("never exposes raw SQL errors in repository outputs", async () => { + const pgError = new Error( + 'relation "projects_projects" does not exist at character 15', + ); + const { executor } = createFakeExecutor({ error: pgError }); + const repo = createProjectsRepository(executor); + + const result = await repo.getProjectById(ORG_ID, PRJ_ID); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("relation"); + expect(result.error.message).not.toContain("character 15"); + } + }); + + it("never exposes connection strings in errors", async () => { + const connError = new Error( + "could not connect to postgres://admin:secret@db.internal:5432/prod", + ); + const { executor } = createFakeExecutor({ error: connError }); + const repo = createProjectsRepository(executor); + + const result = await repo.createProject({ + id: "prj-001", + orgId: ORG_ID, + name: "Test", + slug: "test", + slugLower: "test", + createdAt: NOW, + }); + + expect(result.ok).toBe(false); + if (!result.ok && result.error.kind === "internal") { + expect(result.error.message).not.toContain("admin"); + expect(result.error.message).not.toContain("secret"); + expect(result.error.message).not.toContain("db.internal"); + } + }); + }); + + describe("Worker-safe import isolation", () => { + it("does not import runner-only modules", async () => { + const mod = await import("@saas/db/projects"); + const exportKeys = Object.keys(mod); + + expect(exportKeys).toContain("createProjectsRepository"); + expect(exportKeys).not.toContain("runMigrations"); + expect(exportKeys).not.toContain("D1ApiAdapter"); + expect(exportKeys).not.toContain("loadD1CredentialsFromEnv"); + }); + }); +}); diff --git a/tests/db/src/runner.test.ts b/tests/db/src/runner.test.ts new file mode 100644 index 0000000..fb88e17 --- /dev/null +++ b/tests/db/src/runner.test.ts @@ -0,0 +1,285 @@ +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { manifest } from "@saas/db"; +import type { MigrationEntry } from "@saas/db"; +import { buildPlan, runMigrations } from "@saas/db/runner"; +import type { + AppliedMigration, + MigrationAdapter, + MigrationPlan, +} from "@saas/db/runner"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_DIR = resolve(__dirname, "../../..", "packages/db/src/migrations"); + +class FakeAdapter implements MigrationAdapter { + connected = false; + locked = false; + appliedMigrations: AppliedMigration[] = []; + executedSql: string[] = []; + recorded: MigrationEntry[] = []; + inTransaction = false; + shouldFailOnSql: string | null = null; + lockAcquirable = true; + + async connect(): Promise { + this.connected = true; + } + + async disconnect(): Promise { + this.connected = false; + } + + async acquireAdvisoryLock(_lockId: number): Promise { + if (!this.lockAcquirable) return false; + this.locked = true; + return true; + } + + async releaseAdvisoryLock(_lockId: number): Promise { + this.locked = false; + } + + async getAppliedMigrations(): Promise { + return this.appliedMigrations; + } + + async beginTransaction(): Promise { + this.inTransaction = true; + } + + async commitTransaction(): Promise { + this.inTransaction = false; + } + + async rollbackTransaction(): Promise { + this.inTransaction = false; + } + + async executeSql(sql: string): Promise { + if (this.shouldFailOnSql && sql.includes(this.shouldFailOnSql)) { + throw new Error(`Simulated SQL failure on: ${this.shouldFailOnSql}`); + } + this.executedSql.push(sql); + } + + async recordMigration(entry: MigrationEntry): Promise { + this.recorded.push(entry); + this.appliedMigrations.push({ + id: entry.id, + context: entry.context, + checksum: entry.checksum, + applied_at: new Date().toISOString(), + }); + } +} + +describe("Migration Runner", () => { + let adapter: FakeAdapter; + + const firstMigration = manifest.migrations[0]!; + + beforeEach(() => { + adapter = new FakeAdapter(); + }); + + describe("no pending migrations", () => { + it("reports all migrations as skipped when fully applied", async () => { + adapter.appliedMigrations = manifest.migrations.map((m) => ({ + id: m.id, + context: m.context, + checksum: m.checksum, + applied_at: "2026-01-01T00:00:00Z", + })); + + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result.applied).toHaveLength(0); + expect(result.skipped).toEqual(manifest.migrations.map((m) => m.id)); + expect(result.failed).toBeNull(); + }); + + it("is idempotent when re-run with no pending migrations", async () => { + adapter.appliedMigrations = manifest.migrations.map((m) => ({ + id: m.id, + context: m.context, + checksum: m.checksum, + applied_at: "2026-01-01T00:00:00Z", + })); + + const result1 = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + const result2 = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result1).toEqual(result2); + }); + }); + + describe("pending migrations", () => { + it("applies all pending migrations in manifest order", async () => { + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + expect(result.skipped).toHaveLength(0); + expect(result.failed).toBeNull(); + expect(adapter.recorded).toHaveLength(manifest.migrations.length); + }); + + it("applies only missing migrations when some are already applied", async () => { + adapter.appliedMigrations = [ + { + id: firstMigration.id, + context: firstMigration.context, + checksum: firstMigration.checksum, + applied_at: "2026-01-01T00:00:00Z", + }, + ]; + + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result.skipped).toContain(firstMigration.id); + expect(result.applied).toEqual( + manifest.migrations.slice(1).map((m) => m.id), + ); + expect(result.failed).toBeNull(); + }); + }); + + describe("plan mode", () => { + it("reports pending migrations without executing SQL", async () => { + const result = await runMigrations(manifest, { + mode: "plan", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result.applied).toEqual(manifest.migrations.map((m) => m.id)); + expect(adapter.executedSql).toHaveLength(0); + expect(adapter.recorded).toHaveLength(0); + }); + }); + + describe("checksum mismatch", () => { + it("fails when an applied migration has a different checksum", async () => { + adapter.appliedMigrations = [ + { + id: firstMigration.id, + context: firstMigration.context, + checksum: "0000000000000000000000000000000000000000000000000000000000000000", + applied_at: "2026-01-01T00:00:00Z", + }, + ]; + + await expect( + runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }), + ).rejects.toThrow("Checksum mismatch for already-applied migrations"); + }); + }); + + describe("migration failure rollback", () => { + it("rolls back the failed migration and reports the error", async () => { + adapter.shouldFailOnSql = "CREATE TABLE"; + + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(result.failed).not.toBeNull(); + expect(result.failed!.id).toBe(firstMigration.id); + expect(result.failed!.error).toContain("Simulated SQL failure"); + expect(adapter.inTransaction).toBe(false); + }); + }); + + describe("deterministic apply order", () => { + it("applies migrations in manifest array order", async () => { + const result = await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + for (let i = 0; i < result.applied.length; i++) { + expect(result.applied[i]).toBe(manifest.migrations[i]!.id); + } + }); + }); + + describe("advisory lock", () => { + it("fails when advisory lock cannot be acquired", async () => { + adapter.lockAcquirable = false; + + await expect( + runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }), + ).rejects.toThrow("Could not acquire migration advisory lock"); + }); + + it("releases lock even when migration fails", async () => { + adapter.shouldFailOnSql = "CREATE TABLE"; + + await runMigrations(manifest, { + mode: "apply", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(adapter.locked).toBe(false); + }); + }); + + describe("connection lifecycle", () => { + it("connects before running and disconnects after", async () => { + await runMigrations(manifest, { + mode: "plan", + migrationsDir: MIGRATIONS_DIR, + adapter, + }); + + expect(adapter.connected).toBe(false); + }); + }); +}); + +describe("buildPlan", () => { + it("identifies pending, applied, and mismatched migrations", () => { + const first = manifest.migrations[0]!; + const appliedMap = new Map([ + [first.id, first.checksum], + ]); + + const plan: MigrationPlan = buildPlan(manifest, appliedMap, MIGRATIONS_DIR); + + expect(plan.alreadyApplied).toContain(first.id); + expect(plan.checksumMismatches).toHaveLength(0); + expect(plan.pending).toEqual(manifest.migrations.slice(1)); + }); +}); diff --git a/tests/db/src/sqlite-schema.test.ts b/tests/db/src/sqlite-schema.test.ts new file mode 100644 index 0000000..112bc44 --- /dev/null +++ b/tests/db/src/sqlite-schema.test.ts @@ -0,0 +1,335 @@ +import { DatabaseSync } from "node:sqlite"; +import { readFileSync, readdirSync, existsSync } from "node:fs"; +import { resolve, dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { createSqlExecutor, type D1Binding } from "@saas/db/d1"; +import { createIdentityRepository } from "@saas/db/identity"; +import { createMembershipRepository } from "@saas/db/membership"; +import { createProjectsRepository } from "@saas/db/projects"; +import { createMeteringRepository } from "@saas/db/metering"; +import { createWebhookRepository } from "@saas/db/webhooks"; +import { asUuid } from "@saas/db"; +import { D1ApiAdapter } from "@saas/db/runner"; + +// The runner's own statement splitter — the same one that will feed D1 over +// the REST API — so this suite exercises the production path, not a copy. +const splitStatements = D1ApiAdapter.splitStatements; + +// The migrations and the repositories are checked against a REAL SQLite engine +// here, not a mock. Every other repository suite in this package stubs the +// executor and asserts the SQL text — necessary, but blind to whether SQLite +// would accept that text. This suite closes that gap: D1 is SQLite, so a +// statement `node:sqlite` parses and runs is a statement D1 runs. + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const MIGRATIONS_ROOT = resolve(__dirname, "../../..", "packages/db/src/migrations"); + +function migrationDirs(): string[] { + return readdirSync(MIGRATIONS_ROOT) + .filter((d) => existsSync(join(MIGRATIONS_ROOT, d, "up.sql"))) + .sort(); +} + +/** A D1 binding backed by an in-memory SQLite database. */ +function d1Over(db: DatabaseSync): D1Binding { + return { + prepare(query: string) { + let bound: unknown[] = []; + const statement = { + bind(...values: unknown[]) { + bound = values; + return statement; + }, + all() { + const prepared = db.prepare(query); + const rows = prepared.all(...(bound as never[])) as T[]; + return Promise.resolve({ results: rows, success: true }); + }, + }; + return statement; + }, + } as unknown as D1Binding; +} + +function migratedDatabase(): DatabaseSync { + const db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON"); + for (const dir of migrationDirs()) { + const sql = readFileSync(join(MIGRATIONS_ROOT, dir, "up.sql"), "utf8"); + for (const statement of splitStatements(sql)) db.exec(statement); + } + return db; +} + +describe("migrations against a real SQLite engine", () => { + it("apply cleanly in manifest order", () => { + expect(() => migratedDatabase()).not.toThrow(); + }); + + it("are idempotent — a second application changes nothing", () => { + const db = migratedDatabase(); + for (const dir of migrationDirs()) { + const sql = readFileSync(join(MIGRATIONS_ROOT, dir, "up.sql"), "utf8"); + for (const statement of splitStatements(sql)) { + try { + db.exec(statement); + } catch (err) { + // SQLite has no `ADD COLUMN IF NOT EXISTS`; the runner's applied + // ledger is what stops a column add from running twice. Every other + // statement must be re-runnable on its own. + expect(String(err)).toMatch(/duplicate column name/i); + } + } + } + db.close(); + }); + + it("create every table the repositories address, with no schema prefixes left", () => { + const db = migratedDatabase(); + const tables = ( + db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as { + name: string; + }[] + ).map((r) => r.name); + + expect(tables).toContain("identity_users"); + expect(tables).toContain("membership_organizations"); + expect(tables).toContain("_migrations_applied"); + // A dot in a table name would mean a Postgres schema survived the port. + for (const name of tables) expect(name).not.toContain("."); + db.close(); + }); + + it("default timestamps to a parseable ISO-8601 instant", () => { + // Postgres `now()` became a strftime format string; if that format were + // wrong, `new Date(row.created_at)` in every row mapper would yield + // Invalid Date — silently, and only at runtime. + const db = migratedDatabase(); + db.exec( + `INSERT INTO identity_users (id, email, email_lower) VALUES ('u1', 'a@b.c', 'a@b.c')`, + ); + const row = db.prepare("SELECT created_at FROM identity_users").get() as { + created_at: string; + }; + expect(row.created_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/); + expect(Number.isNaN(new Date(row.created_at).getTime())).toBe(false); + db.close(); + }); +}); + +describe("repositories against a real SQLite engine", () => { + let db: DatabaseSync; + let executor: ReturnType; + + beforeEach(() => { + db = migratedDatabase(); + executor = createSqlExecutor(d1Over(db)); + }); + + afterEach(() => { + db.close(); + }); + + it("round-trips a user through create and read", async () => { + const repo = createIdentityRepository(executor); + const created = await repo.createUser({ + id: "11111111-1111-4111-8111-111111111111", + email: "Ada@Example.com", + emailLower: "ada@example.com", + displayName: "Ada", + createdAt: new Date("2026-01-01T00:00:00.000Z"), + }); + + expect(created.ok).toBe(true); + if (!created.ok) return; + expect(created.value.email).toBe("Ada@Example.com"); + expect(created.value.createdAt.toISOString()).toBe("2026-01-01T00:00:00.000Z"); + + const found = await repo.getUserByEmail("ada@example.com"); + expect(found.ok).toBe(true); + if (found.ok) expect(found.value.id).toBe("11111111-1111-4111-8111-111111111111"); + }); + + it("maps a real unique-constraint failure to a conflict result", async () => { + // The dialect's own error, raised by the engine — not a hand-written + // fixture. This is what makes isUniqueViolation's pattern trustworthy. + const repo = createIdentityRepository(executor); + const input = { + id: "22222222-2222-4222-8222-222222222222", + email: "dup@example.com", + emailLower: "dup@example.com", + displayName: null, + createdAt: new Date("2026-01-01T00:00:00.000Z"), + }; + expect((await repo.createUser(input)).ok).toBe(true); + + const again = await repo.createUser({ + ...input, + id: "33333333-3333-4333-8333-333333333333", + }); + expect(again.ok).toBe(false); + if (!again.ok) expect(again.error.kind).toBe("conflict"); + }); + + it("round-trips an organization and its slug lookup", async () => { + const repo = createMembershipRepository(executor); + const created = await repo.createOrganization({ + id: "44444444-4444-4444-8444-444444444444", + name: "Acme", + slug: "acme", + slugLower: "acme", + createdAt: new Date("2026-01-01T00:00:00.000Z"), + }); + expect(created.ok).toBe(true); + + const bySlug = await repo.getOrganizationBySlug("acme"); + expect(bySlug.ok).toBe(true); + if (bySlug.ok) expect(bySlug.value.name).toBe("Acme"); + }); + + it("counts through the un-cast COUNT(*) the port left behind", async () => { + // `COUNT(*)::bigint` was a Postgres cast; SQLite rejects it. This asserts + // the replacement still returns a usable number through the mapper — the + // value quota enforcement reads before allowing another project. + const orgId = asUuid("55555555-5555-4555-8555-555555555555"); + const projects = createProjectsRepository(executor); + + const empty = await projects.countActiveProjects(orgId); + expect(empty.ok).toBe(true); + if (empty.ok) expect(empty.value).toBe(0); + + const created = await projects.createProject({ + id: asUuid("66666666-6666-4666-8666-666666666666"), + orgId, + name: "First", + slug: "first", + slugLower: "first", + createdAt: new Date("2026-01-01T00:00:00.000Z"), + }); + expect(created.ok).toBe(true); + + const counted = await projects.countActiveProjects(orgId); + expect(counted.ok).toBe(true); + if (counted.ok) expect(counted.value).toBe(1); + }); +}); + +// The three queries the port rewrote most, run for real. Each replaced a +// Postgres construct SQLite does not have (date_trunc, md5, INTERVAL, a +// timestamptz cast), and each is a place where a mock executor would happily +// assert the text of SQL that the engine rejects. +describe("the rewritten queries, against a real SQLite engine", () => { + let db: DatabaseSync; + let executor: ReturnType; + + beforeEach(() => { + db = migratedDatabase(); + executor = createSqlExecutor(d1Over(db)); + }); + + afterEach(() => { + db.close(); + }); + + it("materializes usage rollups: strftime buckets, a key-derived id, and an upsert", async () => { + const repo = createMeteringRepository(executor); + const orgId = "org-roll"; + + // Two records in the same hour, one in the next: the aggregation must fold + // the first two together and keep the third separate. + const at = async (iso: string, key: string, quantity: number) => { + const r = await repo.recordUsage({ + id: `usage-${key}`, + orgId, + metric: "api_requests", + quantity, + idempotencyKey: key, + recordedAt: new Date(iso), + }); + expect(r.ok).toBe(true); + }; + await at("2026-03-15T11:10:00.000Z", "a", 3); + await at("2026-03-15T11:50:00.000Z", "b", 4); + await at("2026-03-15T12:05:00.000Z", "c", 5); + + const first = await repo.materializeUsageRollups({ + bucketType: "hour", + start: new Date("2026-03-15T11:00:00.000Z"), + end: new Date("2026-03-15T13:00:00.000Z"), + }); + expect(first.ok).toBe(true); + + const rows = db + .prepare( + "SELECT bucket_start, quantity, record_count FROM metering_usage_rollups ORDER BY bucket_start", + ) + .all() as { bucket_start: string; quantity: number; record_count: number }[]; + expect(rows).toEqual([ + { bucket_start: "2026-03-15T11:00:00.000Z", quantity: 7, record_count: 2 }, + { bucket_start: "2026-03-15T12:00:00.000Z", quantity: 5, record_count: 1 }, + ]); + + // Re-materializing the same window must UPDATE, never duplicate — the + // ON CONFLICT target has to match the unique index expression for expression. + const again = await repo.materializeUsageRollups({ + bucketType: "hour", + start: new Date("2026-03-15T11:00:00.000Z"), + end: new Date("2026-03-15T13:00:00.000Z"), + }); + expect(again.ok).toBe(true); + const count = db.prepare("SELECT COUNT(*) AS n FROM metering_usage_rollups").get() as { + n: number; + }; + expect(count.n).toBe(2); + }); + + it("rotates a webhook secret with a grace window computed by strftime", async () => { + const repo = createWebhookRepository(executor); + const orgId = asUuid("77777777-7777-4777-8777-777777777777"); + const endpointId = "wep_rotate"; + + const created = await repo.createEndpoint({ + id: endpointId, + orgId, + url: "https://example.test/hook", + secretCiphertext: "envelope-v1", + }); + expect(created.ok).toBe(true); + + const rotated = await repo.rotateEndpointSecret(orgId, endpointId, { + secretCiphertext: "envelope-v2", + gracePeriodSeconds: 3600, + }); + expect(rotated.ok).toBe(true); + + const row = db + .prepare( + `SELECT previous_secret_ciphertext, previous_secret_version, previous_secret_expires_at + FROM webhooks_webhook_endpoints WHERE id = ?`, + ) + .get(endpointId) as { + previous_secret_ciphertext: string; + previous_secret_version: number; + previous_secret_expires_at: string; + }; + expect(row.previous_secret_ciphertext).toBe("envelope-v1"); + expect(row.previous_secret_version).toBe(1); + // The INTERVAL literal became a strftime modifier; if the modifier were + // malformed SQLite returns NULL rather than failing, so assert the shape. + expect(row.previous_secret_expires_at).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/, + ); + expect(new Date(row.previous_secret_expires_at).getTime()).toBeGreaterThan(Date.now()); + }); + + it("counts a delivery failure streak past the epoch fallback", async () => { + // The fallback used a `'1970-01-01'::timestamptz` cast; with no prior + // success the whole count depends on it comparing sanely against the + // ISO-8601 text the rest of the schema stores. + const repo = createWebhookRepository(executor); + const orgId = asUuid("88888888-8888-4888-8888-888888888888"); + const streak = await repo.countConsecutiveEndpointFailures(orgId, "wep_none"); + expect(streak.ok).toBe(true); + if (streak.ok) expect(streak.value).toBe(0); + }); +}); diff --git a/tests/db/src/webhooks.test.ts b/tests/db/src/webhooks.test.ts new file mode 100644 index 0000000..8f0f42b --- /dev/null +++ b/tests/db/src/webhooks.test.ts @@ -0,0 +1,653 @@ +import { + createWebhookRepository, +} from "@saas/db/webhooks"; +import { asUuid } from "@saas/db"; +import type { SqlExecutor, SqlExecutorResult, SqlRow } from "@saas/db/d1"; + +// Valid canonical UUIDs. webhook_endpoints/subscriptions org_id & project_id are +// UUID columns, so the branded create inputs require real UUIDs (not slugs). +const ORG_ID = asUuid("00000000-0000-4000-8000-000000000001"); +const PROJECT_ID = asUuid("00000000-0000-4000-8000-000000000002"); + +type QueryRecord = { text: string; params: unknown[] }; + +function createFakeExecutor(options?: { + rows?: Record[]; + error?: unknown; + rowCount?: number; +}): { executor: SqlExecutor; queries: QueryRecord[] } { + const queries: QueryRecord[] = []; + const executor: SqlExecutor = { + async execute( + text: string, + params?: unknown[], + ): Promise> { + queries.push({ text, params: params ?? [] }); + if (options?.error) { + throw options.error; + } + const rows = (options?.rows ?? []) as unknown as T[]; + return { rows, rowCount: options?.rowCount ?? rows.length }; + }, + }; + return { executor, queries }; +} + +const NOW = new Date("2026-01-15T10:00:00Z"); + +const SAMPLE_ENDPOINT_ROW = { + id: "ep-001", + org_id: ORG_ID, + project_id: null, + url: "https://example.com/webhook", + name: "My Webhook", + description: "Test endpoint", + status: "active", + disabled_reason: null, + disabled_at: null, + secret_version: 1, + secret_last_rotated_at: null, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_SUBSCRIPTION_ROW = { + id: "sub-001", + org_id: ORG_ID, + endpoint_id: "ep-001", + project_id: null, + event_type: "project.created", + enabled: true, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +const SAMPLE_DELIVERY_ROW = { + id: "del-001", + org_id: ORG_ID, + endpoint_id: "ep-001", + subscription_id: "sub-001", + event_id: "evt-001", + event_type: "project.created", + status: "pending", + attempt_number: 1, + http_status_code: null, + failure_reason: null, + idempotency_key: null, + next_retry_at: null, + completed_at: null, + created_at: NOW.toISOString(), + updated_at: NOW.toISOString(), +}; + +// ── Endpoint tests ──────────────────────────────────────── + +describe("WebhookRepository — Endpoints", () => { + it("creates an org-scoped endpoint with parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.createEndpoint({ + id: "ep-001", + orgId: ORG_ID, + url: "https://example.com/webhook", + name: "My Webhook", + description: "Test endpoint", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.id).toBe("ep-001"); + expect(result.value.orgId).toBe(ORG_ID); + expect(result.value.projectId).toBeNull(); + expect(result.value.status).toBe("active"); + expect(result.value.secretVersion).toBe(1); + } + expect(queries).toHaveLength(1); + expect(queries[0]!.text).toContain("webhooks_webhook_endpoints"); + expect(queries[0]!.params[2]).toBeNull(); // project_id null + }); + + it("creates a project-scoped endpoint with orgId + projectId", async () => { + const row = { ...SAMPLE_ENDPOINT_ROW, project_id: PROJECT_ID }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createWebhookRepository(executor); + await repo.createEndpoint({ + id: "ep-002", + orgId: ORG_ID, + projectId: PROJECT_ID, + url: "https://example.com/webhook", + }); + expect(queries[0]!.params[1]).toBe(ORG_ID); // org_id + expect(queries[0]!.params[2]).toBe(PROJECT_ID); // project_id + }); + + it("does not expose secret_ciphertext in RETURNING clause", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + await repo.createEndpoint({ + id: "ep-001", + orgId: ORG_ID, + url: "https://example.com/webhook", + }); + expect(queries[0]!.text).not.toContain("secret_ciphertext"); + }); + + it("does not expose secret_ciphertext on get", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.getEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect("secretCiphertext" in result.value).toBe(false); + expect("secret_ciphertext" in result.value).toBe(false); + } + expect(queries[0]!.text).not.toContain("secret_ciphertext"); + expect(queries[0]!.text).not.toContain("SELECT *"); + }); + + it("does not expose secret_ciphertext on list", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + await repo.listEndpoints(ORG_ID, { limit: 10, cursor: null }); + expect(queries[0]!.text).not.toContain("secret_ciphertext"); + expect(queries[0]!.text).not.toContain("SELECT *"); + }); + + it("returns conflict on unique violation", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createWebhookRepository(executor); + const result = await repo.createEndpoint({ + id: "ep-001", + orgId: ORG_ID, + url: "https://example.com/webhook", + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("gets an endpoint scoped by orgId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.getEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + expect(queries[0]!.params[1]).toBe("ep-001"); + }); + + it("returns not_found for missing endpoint", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.getEndpoint(ORG_ID, "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("lists endpoints with org scope filter", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.listEndpoints(ORG_ID, { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.items).toHaveLength(1); + expect(queries[0]!.text).toContain("org_id = $1"); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); + + it("lists endpoints with project scope filter requiring orgId + projectId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createWebhookRepository(executor); + await repo.listEndpoints(ORG_ID, { limit: 10, cursor: null }, PROJECT_ID); + expect(queries[0]!.text).toContain("org_id = $1 AND project_id = $2"); + expect(queries[0]!.params[0]).toBe(ORG_ID); + expect(queries[0]!.params[1]).toBe(PROJECT_ID); + }); + + it("supports cursor pagination in endpoint list", async () => { + const rows = [ + { ...SAMPLE_ENDPOINT_ROW, id: "ep-a" }, + { ...SAMPLE_ENDPOINT_ROW, id: "ep-b" }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createWebhookRepository(executor); + const result = await repo.listEndpoints(ORG_ID, { limit: 1, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).not.toBeNull(); + } + }); + + it("updates an endpoint by orgId + endpointId", async () => { + const updatedRow = { ...SAMPLE_ENDPOINT_ROW, url: "https://new.example.com" }; + const { executor, queries } = createFakeExecutor({ rows: [updatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.updateEndpoint(ORG_ID, "ep-001", { url: "https://new.example.com" }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + expect(queries[0]!.params[1]).toBe("ep-001"); + }); + + it("returns not_found when updating a non-existent endpoint", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.updateEndpoint(ORG_ID, "ep-999", { url: "https://x.com" }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("disables an endpoint with reason", async () => { + const disabledRow = { ...SAMPLE_ENDPOINT_ROW, status: "disabled", disabled_reason: "Too many failures" }; + const { executor, queries } = createFakeExecutor({ rows: [disabledRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.disableEndpoint(ORG_ID, "ep-001", { reason: "Too many failures" }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("disabled"); + expect(result.value.disabledReason).toBe("Too many failures"); + } + expect(queries[0]!.text).toContain("status = 'disabled'"); + expect(queries[0]!.text).toContain("status = 'active'"); // WHERE guard + }); + + it("enables a disabled endpoint and clears disabled_reason / disabled_at", async () => { + const activeRow = { + ...SAMPLE_ENDPOINT_ROW, + status: "active", + disabled_reason: null, + disabled_at: null, + }; + const { executor, queries } = createFakeExecutor({ rows: [activeRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.enableEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("active"); + expect(result.value.disabledReason).toBeNull(); + expect(result.value.disabledAt).toBeNull(); + } + const sql = queries[0]!.text; + expect(sql).toContain("status = 'active'"); + expect(sql).toContain("disabled_reason = NULL"); + expect(sql).toContain("disabled_at = NULL"); + // WHERE guard must scope to disabled rows only (idempotent semantics + // and explicit pending-exclusion). + expect(sql).toContain("AND status = 'disabled'"); + // Must not expose secret_ciphertext on the public-read surface. + expect(sql).not.toMatch(/RETURNING[\s\S]*?\bsecret_ciphertext\b/); + // Params: only orgId + endpointId (no body fields). + expect(queries[0]!.params).toEqual([ORG_ID, "ep-001"]); + }); + + it("returns not_found when enabling a missing or already-active endpoint", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.enableEndpoint(ORG_ID, "ep-missing"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("enableEndpoint surfaces internal errors as a safe envelope", async () => { + const { executor } = createFakeExecutor({ error: new Error("PG down") }); + const repo = createWebhookRepository(executor); + const result = await repo.enableEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("internal"); + }); + + it("deletes an endpoint scoped by orgId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{}], rowCount: 1 }); + const repo = createWebhookRepository(executor); + const result = await repo.deleteEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.deleted).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); + + it("returns not_found when deleting a missing endpoint", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.deleteEndpoint(ORG_ID, "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("rotates endpoint secret (increments version)", async () => { + const rotatedRow = { ...SAMPLE_ENDPOINT_ROW, secret_version: 2, secret_last_rotated_at: NOW.toISOString() }; + const { executor, queries } = createFakeExecutor({ rows: [rotatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.rotateEndpointSecret(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.endpoint.secretVersion).toBe(2); + expect(result.value.previousSecretVersion).toBeNull(); + expect(result.value.previousSecretExpiresAt).toBeNull(); + } + expect(queries[0]!.text).toContain("secret_version = secret_version + 1"); + expect(queries[0]!.text).toContain("status = 'active'"); + // Must not return secret_ciphertext (current or previous) — public read surface + expect(queries[0]!.text).not.toMatch(/RETURNING[\s\S]*?\bsecret_ciphertext\b/); + expect(queries[0]!.text).not.toMatch(/RETURNING[\s\S]*?previous_secret_ciphertext/); + }); + + it("returns not_found when rotating secret on non-existent endpoint", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.rotateEndpointSecret(ORG_ID, "nope"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("rotate with grace window snapshots previous ciphertext, version, and sets expires_at", async () => { + const futureExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(); + const rotatedRow = { + ...SAMPLE_ENDPOINT_ROW, + secret_version: 5, + secret_last_rotated_at: NOW.toISOString(), + previous_secret_version: 4, + previous_secret_expires_at: futureExpiry, + }; + const { executor, queries } = createFakeExecutor({ rows: [rotatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.rotateEndpointSecret(ORG_ID, "ep-001", { + secretCiphertext: "new-encrypted-envelope", + gracePeriodSeconds: 86400, + }); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.endpoint.secretVersion).toBe(5); + // Previous-secret snapshot must propagate to the result + expect(result.value.previousSecretVersion).toBe(4); + expect(result.value.previousSecretExpiresAt).toBe(new Date(futureExpiry).toISOString()); + } + + const sql = queries[0]!.text; + // SQL must snapshot current secret_ciphertext + secret_version into previous_* + expect(sql).toMatch(/previous_secret_ciphertext\s*=\s*secret_ciphertext/); + expect(sql).toMatch(/previous_secret_version\s*=\s*secret_version/); + // SQL must compute expires_at as now + the grace window in seconds. On + // SQLite that is a strftime modifier, not an INTERVAL literal. + expect(sql).toContain("previous_secret_expires_at"); + expect(sql).toContain("' || $4 || ' seconds'"); + // grace seconds and ciphertext both passed as parameters + expect(queries[0]!.params).toContain(86400); + expect(queries[0]!.params).toContain("new-encrypted-envelope"); + // Public read surface must NOT expose previous secret material + expect(sql).not.toMatch(/RETURNING[\s\S]*?previous_secret_ciphertext/); + }); + + it("rotate without grace window clears any stale previous-secret snapshot", async () => { + const rotatedRow = { + ...SAMPLE_ENDPOINT_ROW, + secret_version: 6, + secret_last_rotated_at: NOW.toISOString(), + previous_secret_version: null, + previous_secret_expires_at: null, + }; + const { executor, queries } = createFakeExecutor({ rows: [rotatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.rotateEndpointSecret(ORG_ID, "ep-001", { + secretCiphertext: "new-envelope", + // gracePeriodSeconds intentionally omitted + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.previousSecretVersion).toBeNull(); + expect(result.value.previousSecretExpiresAt).toBeNull(); + } + const sql = queries[0]!.text; + expect(sql).toMatch(/previous_secret_ciphertext\s*=\s*NULL/); + expect(sql).toMatch(/previous_secret_version\s*=\s*NULL/); + expect(sql).toMatch(/previous_secret_expires_at\s*=\s*NULL/); + }); +}); + +// ── Subscription tests ──────────────────────────────────── + +describe("WebhookRepository — Subscriptions", () => { + it("creates a subscription with parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SUBSCRIPTION_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.createSubscription({ + id: "sub-001", + orgId: ORG_ID, + endpointId: "ep-001", + eventType: "project.created", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.eventType).toBe("project.created"); + expect(result.value.enabled).toBe(true); + expect(result.value.projectId).toBeNull(); + } + expect(queries[0]!.text).toContain("webhooks_webhook_subscriptions"); + }); + + it("creates a project-scoped subscription with orgId + projectId", async () => { + const row = { ...SAMPLE_SUBSCRIPTION_ROW, project_id: PROJECT_ID }; + const { executor, queries } = createFakeExecutor({ rows: [row] }); + const repo = createWebhookRepository(executor); + await repo.createSubscription({ + id: "sub-002", + orgId: ORG_ID, + endpointId: "ep-001", + projectId: PROJECT_ID, + eventType: "member.added", + }); + expect(queries[0]!.params[1]).toBe(ORG_ID); + expect(queries[0]!.params[3]).toBe(PROJECT_ID); + }); + + it("returns conflict on duplicate subscription", async () => { + const { executor } = createFakeExecutor({ error: new Error("D1_ERROR: UNIQUE constraint failed") }); + const repo = createWebhookRepository(executor); + const result = await repo.createSubscription({ + id: "sub-001", + orgId: ORG_ID, + endpointId: "ep-001", + eventType: "project.created", + }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("conflict"); + }); + + it("gets a subscription scoped by orgId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SUBSCRIPTION_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.getSubscription(ORG_ID, "sub-001"); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); + + it("lists subscriptions scoped by orgId + endpointId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_SUBSCRIPTION_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.listSubscriptions(ORG_ID, "ep-001", { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("org_id = $1 AND endpoint_id = $2"); + }); + + it("updates a subscription by orgId", async () => { + const updatedRow = { ...SAMPLE_SUBSCRIPTION_ROW, enabled: false }; + const { executor, queries } = createFakeExecutor({ rows: [updatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.updateSubscription(ORG_ID, "sub-001", { enabled: false }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); + + it("returns not_found when updating non-existent subscription", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.updateSubscription(ORG_ID, "nope", { enabled: true }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("deletes a subscription scoped by orgId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [{}], rowCount: 1 }); + const repo = createWebhookRepository(executor); + const result = await repo.deleteSubscription(ORG_ID, "sub-001"); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); +}); + +// ── Delivery attempt tests ──────────────────────────────── + +describe("WebhookRepository — Delivery Attempts", () => { + it("creates a delivery attempt with parameterized query", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_DELIVERY_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.createDeliveryAttempt({ + id: "del-001", + orgId: ORG_ID, + endpointId: "ep-001", + subscriptionId: "sub-001", + eventId: "evt-001", + eventType: "project.created", + }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.status).toBe("pending"); + expect(result.value.attemptNumber).toBe(1); + } + expect(queries[0]!.text).toContain("webhooks_webhook_delivery_attempts"); + }); + + it("updates a delivery attempt by orgId + attemptId", async () => { + const updatedRow = { ...SAMPLE_DELIVERY_ROW, status: "success", http_status_code: 200 }; + const { executor, queries } = createFakeExecutor({ rows: [updatedRow] }); + const repo = createWebhookRepository(executor); + const result = await repo.updateDeliveryAttempt(ORG_ID, "del-001", { + status: "success", + httpStatusCode: 200, + completedAt: NOW, + }); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + expect(queries[0]!.params[1]).toBe("del-001"); + }); + + it("returns not_found when updating non-existent delivery attempt", async () => { + const { executor } = createFakeExecutor({ rows: [], rowCount: 0 }); + const repo = createWebhookRepository(executor); + const result = await repo.updateDeliveryAttempt(ORG_ID, "nope", { status: "failed" }); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error.kind).toBe("not_found"); + }); + + it("gets a delivery attempt scoped by orgId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_DELIVERY_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.getDeliveryAttempt(ORG_ID, "del-001"); + expect(result.ok).toBe(true); + expect(queries[0]!.params[0]).toBe(ORG_ID); + }); + + it("lists delivery attempts scoped by orgId + endpointId", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_DELIVERY_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.listDeliveryAttempts(ORG_ID, "ep-001", { limit: 10, cursor: null }); + expect(result.ok).toBe(true); + expect(queries[0]!.text).toContain("org_id = $1 AND endpoint_id = $2"); + }); + + it("supports cursor pagination in delivery attempt list", async () => { + const rows = [ + { ...SAMPLE_DELIVERY_ROW, id: "del-a" }, + { ...SAMPLE_DELIVERY_ROW, id: "del-b" }, + ]; + const { executor } = createFakeExecutor({ rows }); + const repo = createWebhookRepository(executor); + const result = await repo.listDeliveryAttempts(ORG_ID, "ep-001", { limit: 1, cursor: null }); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.items).toHaveLength(1); + expect(result.value.nextCursor).not.toBeNull(); + } + }); +}); + +// ── Secret safety invariants ────────────────────────────── + +describe("WebhookRepository — Secret Safety", () => { + it("endpoint read type does not contain plaintext secret fields", async () => { + const { executor } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + const result = await repo.getEndpoint(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) { + const val = result.value; + expect("secret_ciphertext" in val).toBe(false); + expect("secretCiphertext" in val).toBe(false); + expect("signingSecret" in val).toBe(false); + expect("signing_secret" in val).toBe(false); + expect("plaintext" in val).toBe(false); + expect("secret_hash" in val).toBe(false); + expect("secretHash" in val).toBe(false); + } + }); + + it("endpoint SELECT never uses SELECT *", async () => { + const { executor, queries } = createFakeExecutor({ rows: [SAMPLE_ENDPOINT_ROW] }); + const repo = createWebhookRepository(executor); + await repo.getEndpoint(ORG_ID, "ep-001"); + expect(queries[0]!.text).not.toContain("SELECT *"); + }); + + it("endpoint list never uses SELECT *", async () => { + const { executor, queries } = createFakeExecutor({ rows: [] }); + const repo = createWebhookRepository(executor); + await repo.listEndpoints(ORG_ID, { limit: 10, cursor: null }); + expect(queries[0]!.text).not.toContain("SELECT *"); + }); + + it("rotate secret never returns secret_ciphertext", async () => { + const rotatedRow = { ...SAMPLE_ENDPOINT_ROW, secret_version: 2 }; + const { executor, queries } = createFakeExecutor({ rows: [rotatedRow] }); + const repo = createWebhookRepository(executor); + await repo.rotateEndpointSecret(ORG_ID, "ep-001", { secretCiphertext: "encrypted-data" }); + // Neither current nor previous ciphertext is exposed via RETURNING + expect(queries[0]!.text).not.toMatch(/RETURNING[\s\S]*?\bsecret_ciphertext\b/); + expect(queries[0]!.text).not.toMatch(/RETURNING[\s\S]*?previous_secret_ciphertext/); + }); + + it("getEndpointForDelivery surfaces previous-secret grace fields to the worker", async () => { + const expiry = new Date(Date.now() + 60 * 60 * 1000).toISOString(); + const row = { + id: "ep-001", + org_id: ORG_ID, + url: "https://example.com/webhook", + status: "active", + secret_ciphertext: "current-envelope", + secret_version: 7, + previous_secret_ciphertext: "previous-envelope", + previous_secret_version: 6, + previous_secret_expires_at: expiry, + }; + const { executor } = createFakeExecutor({ rows: [row] }); + const repo = createWebhookRepository(executor); + const result = await repo.getEndpointForDelivery(ORG_ID, "ep-001"); + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.value.secretCiphertext).toBe("current-envelope"); + expect(result.value.secretVersion).toBe(7); + expect(result.value.previousSecretCiphertext).toBe("previous-envelope"); + expect(result.value.previousSecretVersion).toBe(6); + expect(result.value.previousSecretExpiresAt).toBe(new Date(expiry).toISOString()); + } + }); +}); + +// ── Migration shape tests ───────────────────────────────── + +describe("WebhookRepository — Migration Manifest", () => { + it("manifest includes 080_webhooks_core with correct checksum format", async () => { + // This test validates the manifest entry exists and checksum looks like SHA-256 + const { manifest } = await import("@saas/db/manifest"); + const entry = manifest.migrations.find((m: { id: string }) => m.id === "080_webhooks_core"); + expect(entry).toBeDefined(); + expect(entry!.context).toBe("webhooks"); + expect(entry!.path).toBe("080_webhooks_core/up.sql"); + expect(entry!.checksum).toMatch(/^[a-f0-9]{64}$/); + }); +}); diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json new file mode 100644 index 0000000..f4e8f7f --- /dev/null +++ b/tests/db/tsconfig.json @@ -0,0 +1,29 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "types": ["jest", "node"], + "allowSyntheticDefaultImports": true, + "composite": false, + "incremental": false, + "declaration": false, + "declarationMap": false, + "baseUrl": ".", + "paths": { + "@saas/db": ["../../packages/db/src/index.ts"], + "@saas/db/d1": ["../../packages/db/src/d1/index.ts"], + "@saas/db/identity": ["../../packages/db/src/identity/index.ts"], + "@saas/db/runner": ["../../packages/db/src/runner/index.ts"], + "@saas/db/manifest": ["../../packages/db/src/manifest.ts"], + "@saas/db/types": ["../../packages/db/src/types.ts"], + "@saas/db/membership": ["../../packages/db/src/membership/index.ts"], + "@saas/db/events": ["../../packages/db/src/events/index.ts"], + "@saas/db/projects": ["../../packages/db/src/projects/index.ts"], + "@saas/db/config": ["../../packages/db/src/config/index.ts"], + "@saas/db/webhooks": ["../../packages/db/src/webhooks/index.ts"], + "@saas/db/metering": ["../../packages/db/src/metering/index.ts"], + "@saas/db/billing": ["../../packages/db/src/billing/index.ts"] + } + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/tests/notifications-client/component.yaml b/tests/notifications-client/component.yaml new file mode 100644 index 0000000..ecf1579 --- /dev/null +++ b/tests/notifications-client/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: notifications-client-tests +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/tests/notifications-client/docs/architecture.md b/tests/notifications-client/docs/architecture.md new file mode 100644 index 0000000..13ee5d9 --- /dev/null +++ b/tests/notifications-client/docs/architecture.md @@ -0,0 +1,9 @@ +# notifications-client-tests — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `tests/notifications-client`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/tests/notifications-client/docs/overview.md b/tests/notifications-client/docs/overview.md new file mode 100644 index 0000000..04aed35 --- /dev/null +++ b/tests/notifications-client/docs/overview.md @@ -0,0 +1,13 @@ +# notifications-client-tests + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/notifications-client/docs/runbook.md b/tests/notifications-client/docs/runbook.md new file mode 100644 index 0000000..be070cc --- /dev/null +++ b/tests/notifications-client/docs/runbook.md @@ -0,0 +1,26 @@ +# notifications-client-tests — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/tests/notifications-client/eslint.config.js b/tests/notifications-client/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/notifications-client/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/notifications-client/package.json b/tests/notifications-client/package.json new file mode 100644 index 0000000..a722a96 --- /dev/null +++ b/tests/notifications-client/package.json @@ -0,0 +1,40 @@ +{ + "name": "@saas/notifications-client-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "build": "tsc --noEmit", + "typecheck": "tsc --noEmit", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "lint": "eslint src" + }, + "devDependencies": { + "@cloudflare/workers-types": "^4.20250508.0", + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/jest": "^29.5.14", + "@types/node": "^20.17.0", + "jest": "^29.7.0", + "ts-jest": "^29.3.4", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*", + "@saas/notifications-client": "workspace:*" + }, + "jest": { + "preset": "ts-jest/presets/default-esm", + "extensionsToTreatAsEsm": [".ts"], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1", + "^@saas/contracts$": "/../../packages/contracts/src/index.ts", + "^@saas/contracts/(.*)$": "/../../packages/contracts/src/$1.ts", + "^@saas/notifications-client$": "/../../packages/notifications-client/src/index.ts" + }, + "transform": { + "^.+\\.ts$": ["ts-jest", { "useESM": true }] + }, + "testMatch": ["/src/**/*.test.ts"] + } +} diff --git a/tests/notifications-client/src/notifications-client.test.ts b/tests/notifications-client/src/notifications-client.test.ts new file mode 100644 index 0000000..bb90a01 --- /dev/null +++ b/tests/notifications-client/src/notifications-client.test.ts @@ -0,0 +1,228 @@ +/// +/** + * Canonical test suite for `@saas/notifications-client`. This used to live + * twice — once under `tests/identity-worker/` and once under + * `tests/membership-worker/` — when each worker carried its own copy of + * the client. With the Task 0089 extraction it's a single package, so the + * suite lives once, here, and is executed under `@saas/notifications-client-tests`. + */ +import { + enqueueNotification, + buildIdempotencyKey, + type NotificationsEnvBinding, +} from "@saas/notifications-client"; + +type FetchHandler = (url: string, init?: RequestInit) => Promise; + +function makeEnv(handler?: FetchHandler): NotificationsEnvBinding { + if (!handler) return {}; + return { + NOTIFICATIONS_WORKER: { + fetch: handler, + } as unknown as NonNullable, + }; +} + +const baseCtx = { + internalActor: "identity-worker", + actorSubjectType: "system", + actorSubjectId: "identity-worker", + requestId: "req_test_123", +}; + +const baseRequest = { + orgId: "00000000-0000-0000-0000-000000000000", + category: "security" as const, + templateKey: "auth.magic_link", + templateData: { + code: "123456", + emailHint: "t***@example.com", + expiresAt: "2026-05-30T10:00:00.000Z", + requestId: "req_test_123", + }, + recipient: { + channel: "email" as const, + address: "test@example.com", + }, +}; + +describe("@saas/notifications-client enqueueNotification", () => { + it("returns no_binding when NOTIFICATIONS_WORKER is missing", async () => { + const result = await enqueueNotification(makeEnv(), baseCtx, baseRequest); + expect(result).toEqual({ ok: false, reason: "no_binding" }); + }); + + it("posts to the internal enqueue URL with the required headers", async () => { + let capturedUrl: string | undefined; + let capturedInit: RequestInit | undefined; + const handler: FetchHandler = async (url, init) => { + capturedUrl = url; + capturedInit = init; + return new Response( + JSON.stringify({ + data: { + notification: { + id: "ntf_abc123", + orgId: baseRequest.orgId, + category: "security", + templateKey: "auth.magic_link", + status: "sent", + recipient: { channel: "email", address: baseRequest.recipient.address }, + providerMessageId: "local-debug-xyz", + queuedAt: "2026-05-30T10:00:00.000Z", + sentAt: "2026-05-30T10:00:00.000Z", + failedAt: null, + lastError: null, + attempts: [], + }, + }, + meta: { requestId: baseCtx.requestId, cursor: null }, + }), + { status: 201, headers: { "content-type": "application/json" } }, + ); + }; + + const result = await enqueueNotification(makeEnv(handler), baseCtx, baseRequest); + + expect(result).toEqual({ ok: true, notificationId: "ntf_abc123" }); + expect(capturedUrl).toBe("https://notifications.internal/v1/notifications"); + expect(capturedInit?.method).toBe("POST"); + const headers = capturedInit?.headers as Record; + expect(headers["x-internal-actor"]).toBe("identity-worker"); + expect(headers["x-actor-subject-type"]).toBe("system"); + expect(headers["x-actor-subject-id"]).toBe("identity-worker"); + expect(headers["x-request-id"]).toBe(baseCtx.requestId); + expect(headers["content-type"]).toBe("application/json"); + const body = JSON.parse(capturedInit?.body as string); + expect(body.category).toBe("security"); + expect(body.templateKey).toBe("auth.magic_link"); + expect(body.recipient.channel).toBe("email"); + expect(body.recipient.address).toBe(baseRequest.recipient.address); + }); + + it("forwards membership-worker caller identity headers correctly", async () => { + let capturedInit: RequestInit | undefined; + const handler: FetchHandler = async (_url, init) => { + capturedInit = init; + return new Response( + JSON.stringify({ data: { notification: { id: "ntf_xyz" } } }), + { status: 201, headers: { "content-type": "application/json" } }, + ); + }; + + const ctx = { + internalActor: "membership-worker", + actorSubjectType: "user", + actorSubjectId: "usr_admin", + requestId: "req_mem_1", + }; + const req = { + orgId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", + category: "invitation" as const, + templateKey: "invitation.created", + templateData: { role: "builder" }, + recipient: { channel: "email" as const, address: "i@example.com" }, + }; + + const result = await enqueueNotification(makeEnv(handler), ctx, req); + expect(result).toEqual({ ok: true, notificationId: "ntf_xyz" }); + const headers = capturedInit?.headers as Record; + expect(headers["x-internal-actor"]).toBe("membership-worker"); + expect(headers["x-actor-subject-type"]).toBe("user"); + expect(headers["x-actor-subject-id"]).toBe("usr_admin"); + }); + + it("returns non_2xx when the worker responds with a 4xx/5xx", async () => { + const handler: FetchHandler = async () => + new Response(JSON.stringify({ error: { code: "validation_failed" } }), { + status: 422, + headers: { "content-type": "application/json" }, + }); + + const result = await enqueueNotification(makeEnv(handler), baseCtx, baseRequest); + expect(result).toEqual({ ok: false, reason: "non_2xx" }); + }); + + it("returns network_error when the binding fetch throws", async () => { + const handler: FetchHandler = async () => { + throw new TypeError("network down"); + }; + + const result = await enqueueNotification(makeEnv(handler), baseCtx, baseRequest); + expect(result).toEqual({ ok: false, reason: "network_error" }); + }); + + it("returns bad_response when the body is not the expected envelope", async () => { + const handler: FetchHandler = async () => + new Response(JSON.stringify({ unexpected: true }), { + status: 201, + headers: { "content-type": "application/json" }, + }); + + const result = await enqueueNotification(makeEnv(handler), baseCtx, baseRequest); + expect(result).toEqual({ ok: false, reason: "bad_response" }); + }); + + it("returns bad_response when the body is malformed JSON", async () => { + const handler: FetchHandler = async () => + new Response("not json at all", { + status: 201, + headers: { "content-type": "application/json" }, + }); + + const result = await enqueueNotification(makeEnv(handler), baseCtx, baseRequest); + expect(result).toEqual({ ok: false, reason: "bad_response" }); + }); + + it("never throws — all failure modes return a result", async () => { + const handler: FetchHandler = async () => { + throw new Error("boom"); + }; + + await expect( + enqueueNotification(makeEnv(handler), baseCtx, baseRequest), + ).resolves.toBeDefined(); + }); +}); + +describe("buildIdempotencyKey", () => { + it("returns a deterministic, scope-prefixed string", () => { + expect(buildIdempotencyKey("auth.magic_link", "chl_abc")).toBe( + "auth.magic_link:chl_abc", + ); + expect( + buildIdempotencyKey("invitation.accepted", "inv_xyz", "mem_qux"), + ).toBe("invitation.accepted:inv_xyz:mem_qux"); + }); + + it("is pure — same inputs produce the same output across calls", () => { + const a = buildIdempotencyKey("invitation.created", "inv_1"); + const b = buildIdempotencyKey("invitation.created", "inv_1"); + expect(a).toBe(b); + }); + + it("template-scopes — different scopes with the same id never collide", () => { + const created = buildIdempotencyKey("invitation.created", "inv_1"); + const accepted = buildIdempotencyKey("invitation.accepted", "inv_1"); + expect(created).not.toBe(accepted); + }); + + it("rejects empty scope", () => { + expect(() => buildIdempotencyKey("", "inv_1")).toThrow(TypeError); + }); + + it("rejects calls with no parts", () => { + expect(() => (buildIdempotencyKey as (s: string) => string)("auth.magic_link")).toThrow(TypeError); + }); + + it("rejects empty parts", () => { + expect(() => buildIdempotencyKey("invitation.created", "")).toThrow(TypeError); + }); + + it("rejects parts containing whitespace, ':' or control characters", () => { + expect(() => buildIdempotencyKey("auth.magic_link", "has space")).toThrow(TypeError); + expect(() => buildIdempotencyKey("auth.magic_link", "has:colon")).toThrow(TypeError); + expect(() => buildIdempotencyKey("auth.magic_link", "has\nnewline")).toThrow(TypeError); + expect(() => buildIdempotencyKey("auth.magic_link", "has\u0007bell")).toThrow(TypeError); + }); +}); diff --git a/tests/notifications-client/tsconfig.json b/tests/notifications-client/tsconfig.json new file mode 100644 index 0000000..2631fc3 --- /dev/null +++ b/tests/notifications-client/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "types": ["jest", "node", "@cloudflare/workers-types"], + "allowSyntheticDefaultImports": true, + "composite": false, + "incremental": false, + "declaration": false, + "declarationMap": false, + "baseUrl": ".", + "paths": { + "@saas/contracts": ["../../packages/contracts/src/index.ts"], + "@saas/contracts/*": ["../../packages/contracts/src/*.ts"], + "@saas/notifications-client": ["../../packages/notifications-client/src/index.ts"] + } + }, + "include": ["src/**/*.ts", "../../packages/notifications-client/src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/tests/policy-engine/component.yaml b/tests/policy-engine/component.yaml new file mode 100644 index 0000000..38e747a --- /dev/null +++ b/tests/policy-engine/component.yaml @@ -0,0 +1,23 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: policy-engine-tests +spec: + type: turbo-package + lifecycle: production + owner: platform + domain: starter-tests + subscribe: + environments: + - name: dev + profile: quick-check + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + buildCommand: pnpm exec turbo run build --filter=./ + typecheckCommand: pnpm exec turbo run typecheck --filter=./ + preBuildCommand: pnpm exec turbo run test --filter=./ + labels: + team: platform + layer: test +# ci: trigger full-component verification (orun v2.12.0 upgrade — PR #183) diff --git a/tests/policy-engine/docs/architecture.md b/tests/policy-engine/docs/architecture.md new file mode 100644 index 0000000..b9fe9b4 --- /dev/null +++ b/tests/policy-engine/docs/architecture.md @@ -0,0 +1,9 @@ +# policy-engine-tests — architecture + +A `turbo-package` component: TypeScript built by the turbo pipeline +from `tests/policy-engine`. + +## Boundaries + +A library, not a runtime: it holds no credentials, opens no connections, +and is consumed at build time by the components that depend on it. diff --git a/tests/policy-engine/docs/overview.md b/tests/policy-engine/docs/overview.md new file mode 100644 index 0000000..a90e433 --- /dev/null +++ b/tests/policy-engine/docs/overview.md @@ -0,0 +1,13 @@ +# policy-engine-tests + + + +A workspace package built by the turbo pipeline. It deploys nothing on its own — its lane type-checks, lints, tests, and builds it for the components that depend on it. + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/policy-engine/docs/runbook.md b/tests/policy-engine/docs/runbook.md new file mode 100644 index 0000000..95a7b2a --- /dev/null +++ b/tests/policy-engine/docs/runbook.md @@ -0,0 +1,26 @@ +# policy-engine-tests — runbook + +## How it deploys + +Merges to `main` converge automatically: CI plans changed components +(`orun plan --changed`) and runs this component's lane via +`orun run --remote-state` with credential-free OIDC auth. The convergence +run is the deployment; the DAG orders this component after everything it +depends on. Failed lanes resume with `gh run rerun --failed`. + +## Rollback + +Revert the offending commit on `main`; the next convergence applies the +previous desired state. There is no out-of-band mutation to undo — the +repo is the source of truth. + +## Verify + +The lane itself is the gate: typecheck, lint, test, build. This package +has no deployed surface. + +## Common failures + +- **A dependent's lane fails to build after a change here**: the change + was source-compatible but not type-compatible — run + `pnpm typecheck` across the workspace before landing. diff --git a/tests/policy-engine/eslint.config.js b/tests/policy-engine/eslint.config.js new file mode 100644 index 0000000..2e905dc --- /dev/null +++ b/tests/policy-engine/eslint.config.js @@ -0,0 +1,2 @@ +import config from "../../tooling/eslint/index.js"; +export default config; diff --git a/tests/policy-engine/package.json b/tests/policy-engine/package.json new file mode 100644 index 0000000..4fa5226 --- /dev/null +++ b/tests/policy-engine/package.json @@ -0,0 +1,37 @@ +{ + "name": "@saas/policy-engine-tests", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", + "typecheck": "tsc --noEmit", + "lint": "eslint src" + }, + "jest": { + "preset": "ts-jest/presets/default-esm", + "extensionsToTreatAsEsm": [".ts"], + "moduleNameMapper": { + "^(\\.{1,2}/.*)\\.js$": "$1", + "^@saas/contracts$": "/../../packages/contracts/src/index.ts", + "^@saas/contracts/(.*)$": "/../../packages/contracts/src/$1.ts", + "^@saas/policy-engine$": "/../../packages/policy-engine/src/index.ts" + }, + "transform": { + "^.+\\.ts$": ["ts-jest", { "useESM": true }] + }, + "testMatch": ["/src/**/*.test.ts"] + }, + "devDependencies": { + "@saas/eslint-config": "workspace:*", + "@saas/tsconfig": "workspace:*", + "@types/jest": "^29.5.14", + "jest": "^29.7.0", + "ts-jest": "^29.3.2", + "typescript": "^5.8.3" + }, + "dependencies": { + "@saas/contracts": "workspace:*", + "@saas/policy-engine": "workspace:*" + } +} diff --git a/tests/policy-engine/src/api-key-policy.test.ts b/tests/policy-engine/src/api-key-policy.test.ts new file mode 100644 index 0000000..c41aabe --- /dev/null +++ b/tests/policy-engine/src/api-key-policy.test.ts @@ -0,0 +1,151 @@ +import { authorize } from "@saas/policy-engine"; +import type { + AuthorizationRequest, + MembershipFact, + PolicyMembershipFact, + PolicySubject, + PolicyResource, +} from "@saas/contracts/policy"; +import type { TenancyRole } from "@saas/contracts/tenancy"; + +const subject: PolicySubject = { type: "user", id: "usr_abc123" }; + +function orgFact(role: string, orgId: string): MembershipFact { + return { kind: "role_assignment", role: role as TenancyRole, scope: { kind: "organization", orgId } }; +} + +function projectFact(role: string, orgId: string, projectId: string): MembershipFact { + return { + kind: "role_assignment", + role: role as TenancyRole, + scope: { kind: "project", orgId, projectId }, + }; +} + +function authReq( + action: string, + orgId: string, + memberships: PolicyMembershipFact[], + projectId?: string, +): AuthorizationRequest { + const resource: PolicyResource = { kind: "organization", orgId }; + if (projectId) resource.projectId = projectId; + return { + subject, + action, + resource, + context: { memberships }, + }; +} + +const API_KEY_ACTIONS = [ + "organization.api_key.create", + "organization.api_key.list", + "organization.api_key.revoke", +] as const; + +describe("authorize – api_key actions", () => { + describe("owner role", () => { + const facts = [orgFact("owner", "org_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`allows ${action}`, () => { + const result = authorize(authReq(action, "org_1", facts)); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + } + }); + + describe("admin role", () => { + const facts = [orgFact("admin", "org_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`allows ${action}`, () => { + const result = authorize(authReq(action, "org_1", facts)); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + } + }); + + describe("project_admin with matching projectId", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`allows ${action} when resource projectId matches`, () => { + const result = authorize(authReq(action, "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("project_admin"); + }); + } + }); + + describe("project_admin denied for org-wide", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} when resource has no projectId`, () => { + const result = authorize(authReq(action, "org_1", facts)); + expect(result.allow).toBe(false); + }); + } + }); + + describe("project_admin denied for mismatched projectId", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} when resource projectId differs`, () => { + const result = authorize(authReq(action, "org_1", facts, "prj_2")); + expect(result.allow).toBe(false); + }); + } + }); + + describe("builder/viewer/billing_admin are denied", () => { + for (const role of ["builder", "viewer", "billing_admin"]) { + const facts = [orgFact(role, "org_1")]; + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} for ${role}`, () => { + const result = authorize(authReq(action, "org_1", facts)); + expect(result.allow).toBe(false); + }); + } + } + }); + + describe("project_builder/project_viewer are denied", () => { + for (const role of ["project_builder", "project_viewer"]) { + const facts = [projectFact(role, "org_1", "prj_1")]; + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} for ${role} even with matching projectId`, () => { + const result = authorize(authReq(action, "org_1", facts, "prj_1")); + expect(result.allow).toBe(false); + }); + } + } + }); + + describe("cross-org membership is denied", () => { + const facts = [orgFact("owner", "org_1")]; + + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} when membership org differs from resource org`, () => { + const result = authorize(authReq(action, "org_2", facts)); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + } + }); + + describe("no memberships", () => { + for (const action of API_KEY_ACTIONS) { + it(`denies ${action} when memberships are empty`, () => { + const result = authorize(authReq(action, "org_1", [])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + } + }); +}); diff --git a/tests/policy-engine/src/policy-engine.test.ts b/tests/policy-engine/src/policy-engine.test.ts new file mode 100644 index 0000000..923631b --- /dev/null +++ b/tests/policy-engine/src/policy-engine.test.ts @@ -0,0 +1,1018 @@ +import { authorize, listEffectivePermissions, validateRoleAssignment } from "@saas/policy-engine"; +import type { + AuthorizationRequest, + EffectivePermissionsRequest, + MembershipFact, + PolicyMembershipFact, + PolicySubject, + PolicyResource, +} from "@saas/contracts/policy"; +import type { TenancyRole, RoleScopeKind } from "@saas/contracts/tenancy"; + +const subject: PolicySubject = { type: "user", id: "usr_abc123" }; + +function orgFact(role: string, orgId: string): MembershipFact { + return { kind: "role_assignment", role: role as TenancyRole, scope: { kind: "organization", orgId } }; +} + +function projectFact(role: string, orgId: string, projectId: string): MembershipFact { + return { + kind: "role_assignment", + role: role as TenancyRole, + scope: { kind: "project", orgId, projectId }, + }; +} + +function authReq( + action: string, + orgId: string, + memberships: PolicyMembershipFact[], + projectId?: string, +): AuthorizationRequest { + const resource: PolicyResource = { kind: "organization", orgId }; + if (projectId) resource.projectId = projectId; + return { + subject, + action, + resource, + context: { memberships }, + }; +} + +describe("authorize", () => { + describe("deny-by-default", () => { + it("denies when no memberships are present", () => { + const result = authorize(authReq("organization.read", "org_1", [])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + expect(result.policyVersion).toBe(1); + }); + + it("denies unknown actions", () => { + const result = authorize(authReq("organization.destroy", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("unknown_action"); + }); + + it("denies when orgId is missing", () => { + const result = authorize({ + subject, + action: "organization.read", + resource: { kind: "organization", orgId: "" }, + context: { memberships: [orgFact("owner", "org_1")] }, + }); + expect(result.allow).toBe(false); + expect(result.reason).toBe("invalid_scope"); + }); + + it("denies project-scoped actions when projectId is missing", () => { + for (const action of [ + "project.read", + "project.update", + "project.delete", + "environment.read", + "environment.update", + "environment.delete", + ]) { + const result = authorize(authReq(action, "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("invalid_scope"); + } + }); + }); + + describe("cross-organization denial", () => { + it("denies access when role is for a different organization", () => { + const result = authorize(authReq("organization.read", "org_2", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies project access when role org does not match resource org", () => { + const result = authorize( + authReq("project.read", "org_2", [projectFact("project_admin", "org_1", "prj_1")], "prj_1"), + ); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + }); + + describe("owner role", () => { + const facts = [orgFact("owner", "org_1")]; + + it("allows organization.read", () => { + const result = authorize(authReq("organization.read", "org_1", facts)); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows organization.settings.update", () => { + const result = authorize(authReq("organization.settings.update", "org_1", facts)); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows organization.invitation.create", () => { + const result = authorize(authReq("organization.invitation.create", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows organization.member.list", () => { + const result = authorize(authReq("organization.member.list", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows organization.member.remove", () => { + const result = authorize(authReq("organization.member.remove", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows organization.member.update_role", () => { + const result = authorize(authReq("organization.member.update_role", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows project.create", () => { + const result = authorize(authReq("project.create", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows project.read with projectId", () => { + const result = authorize(authReq("project.read", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows project.update", () => { + const result = authorize(authReq("project.update", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows project.delete", () => { + const result = authorize(authReq("project.delete", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows environment.read", () => { + const result = authorize(authReq("environment.read", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows environment.create", () => { + const result = authorize(authReq("environment.create", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows environment.update", () => { + const result = authorize(authReq("environment.update", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows environment.delete", () => { + const result = authorize(authReq("environment.delete", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + }); + + it("allows billing.read", () => { + const result = authorize(authReq("billing.read", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows billing.manage", () => { + const result = authorize(authReq("billing.manage", "org_1", facts)); + expect(result.allow).toBe(true); + }); + }); + + describe("admin role", () => { + const facts = [orgFact("admin", "org_1")]; + + it("allows organization.read", () => { + const result = authorize(authReq("organization.read", "org_1", facts)); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + + it("allows organization.settings.update", () => { + const result = authorize(authReq("organization.settings.update", "org_1", facts)); + expect(result.allow).toBe(true); + }); + + it("allows invitation management", () => { + expect(authorize(authReq("organization.invitation.create", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.invitation.list", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.invitation.revoke", "org_1", facts)).allow).toBe(true); + }); + + it("allows member management", () => { + expect(authorize(authReq("organization.member.list", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.member.remove", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.member.update_role", "org_1", facts)).allow).toBe(true); + }); + + it("allows project CRUD", () => { + expect(authorize(authReq("project.create", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows environment access", () => { + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies billing.read", () => { + expect(authorize(authReq("billing.read", "org_1", facts)).allow).toBe(false); + }); + + it("denies billing.manage", () => { + expect(authorize(authReq("billing.manage", "org_1", facts)).allow).toBe(false); + }); + }); + + describe("builder role", () => { + const facts = [orgFact("builder", "org_1")]; + + it("allows organization.read", () => { + expect(authorize(authReq("organization.read", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.read", "org_1", facts)).reason).toBe("org_builder"); + }); + + it("allows project.create", () => { + expect(authorize(authReq("project.create", "org_1", facts)).allow).toBe(true); + }); + + it("allows project.read and project.update", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows environment access", () => { + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies environment.delete", () => { + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(false); + }); + + it("denies organization.settings.update", () => { + expect(authorize(authReq("organization.settings.update", "org_1", facts)).allow).toBe(false); + }); + + it("denies member management", () => { + expect(authorize(authReq("organization.member.list", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("organization.member.remove", "org_1", facts)).allow).toBe(false); + }); + + it("denies invitation management", () => { + expect(authorize(authReq("organization.invitation.create", "org_1", facts)).allow).toBe(false); + }); + + it("denies billing", () => { + expect(authorize(authReq("billing.read", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("billing.manage", "org_1", facts)).allow).toBe(false); + }); + + it("denies project.delete", () => { + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(false); + }); + }); + + describe("viewer role", () => { + const facts = [orgFact("viewer", "org_1")]; + + it("allows organization.read", () => { + expect(authorize(authReq("organization.read", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.read", "org_1", facts)).reason).toBe("org_viewer"); + }); + + it("allows project.read", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows environment.read", () => { + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies all write actions", () => { + expect(authorize(authReq("organization.settings.update", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("project.create", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("billing.read", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("billing.manage", "org_1", facts)).allow).toBe(false); + }); + }); + + describe("billing_admin role", () => { + const facts = [orgFact("billing_admin", "org_1")]; + + it("allows organization.read", () => { + expect(authorize(authReq("organization.read", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("organization.read", "org_1", facts)).reason).toBe("org_billing_admin"); + }); + + it("allows billing.read and billing.manage", () => { + expect(authorize(authReq("billing.read", "org_1", facts)).allow).toBe(true); + expect(authorize(authReq("billing.manage", "org_1", facts)).allow).toBe(true); + }); + + it("denies member management", () => { + expect(authorize(authReq("organization.member.list", "org_1", facts)).allow).toBe(false); + }); + + it("denies project management", () => { + expect(authorize(authReq("project.create", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(false); + }); + + it("denies project.list", () => { + expect(authorize(authReq("project.list", "org_1", facts)).allow).toBe(false); + }); + + it("denies settings", () => { + expect(authorize(authReq("organization.settings.update", "org_1", facts)).allow).toBe(false); + }); + }); + + describe("project.list action", () => { + it("allows owner to list projects", () => { + const result = authorize(authReq("project.list", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows admin to list projects", () => { + const result = authorize(authReq("project.list", "org_1", [orgFact("admin", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + + it("allows builder to list projects", () => { + const result = authorize(authReq("project.list", "org_1", [orgFact("builder", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_builder"); + }); + + it("allows viewer to list projects", () => { + const result = authorize(authReq("project.list", "org_1", [orgFact("viewer", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_viewer"); + }); + + it("denies billing_admin from listing projects", () => { + const result = authorize(authReq("project.list", "org_1", [orgFact("billing_admin", "org_1")])); + expect(result.allow).toBe(false); + }); + + it("denies when no memberships", () => { + const result = authorize(authReq("project.list", "org_1", [])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies cross-org facts", () => { + const result = authorize(authReq("project.list", "org_2", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + }); + + it("project-scoped roles alone do not grant org-wide list", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("project.list", "org_1", facts)); + expect(result.allow).toBe(false); + }); + + it("project.read still requires explicit projectId", () => { + const result = authorize(authReq("project.read", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("invalid_scope"); + }); + }); + + describe("project roles", () => { + describe("project_admin", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + + it("allows project.read for matching project", () => { + const result = authorize(authReq("project.read", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("project_admin"); + }); + + it("allows project.update for matching project", () => { + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows project.delete for matching project", () => { + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows environment access for matching project", () => { + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies access to a different project", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_2")).allow).toBe(false); + }); + + it("denies organization-level actions", () => { + expect(authorize(authReq("organization.read", "org_1", facts)).allow).toBe(false); + expect(authorize(authReq("organization.settings.update", "org_1", facts)).allow).toBe(false); + }); + }); + + describe("project_builder", () => { + const facts = [projectFact("project_builder", "org_1", "prj_1")]; + + it("allows project.read and project.update", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("allows environment access", () => { + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies project.delete", () => { + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(false); + }); + + it("denies environment.delete", () => { + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(false); + }); + + it("denies access to different project", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_2")).allow).toBe(false); + }); + }); + + describe("project_viewer", () => { + const facts = [projectFact("project_viewer", "org_1", "prj_1")]; + + it("allows project.read", () => { + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).allow).toBe(true); + expect(authorize(authReq("project.read", "org_1", facts, "prj_1")).reason).toBe("project_viewer"); + }); + + it("allows environment.read", () => { + expect(authorize(authReq("environment.read", "org_1", facts, "prj_1")).allow).toBe(true); + }); + + it("denies writes", () => { + expect(authorize(authReq("project.update", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("project.delete", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.create", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.update", "org_1", facts, "prj_1")).allow).toBe(false); + expect(authorize(authReq("environment.delete", "org_1", facts, "prj_1")).allow).toBe(false); + }); + }); + + it("denies project role when orgId does not match", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("project.read", "org_2", facts, "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies project role when projectId is missing from resource", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("project.read", "org_1", facts)); + expect(result.allow).toBe(false); + }); + }); + + describe("environment.create action", () => { + it("allows owner to create environments", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("owner", "org_1")], "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows admin to create environments", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("admin", "org_1")], "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + + it("allows builder to create environments", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("builder", "org_1")], "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_builder"); + }); + + it("denies viewer from creating environments", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("viewer", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies billing_admin from creating environments", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("billing_admin", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("allows project_admin to create environments for matching project", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("environment.create", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("project_admin"); + }); + + it("allows project_builder to create environments for matching project", () => { + const facts = [projectFact("project_builder", "org_1", "prj_1")]; + const result = authorize(authReq("environment.create", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("project_builder"); + }); + + it("denies project_viewer from creating environments", () => { + const facts = [projectFact("project_viewer", "org_1", "prj_1")]; + const result = authorize(authReq("environment.create", "org_1", facts, "prj_1")); + expect(result.allow).toBe(false); + }); + + it("requires projectId scope", () => { + const result = authorize(authReq("environment.create", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("invalid_scope"); + }); + + it("denies cross-org facts", () => { + const result = authorize(authReq("environment.create", "org_2", [orgFact("owner", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies wrong-project project role", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("environment.create", "org_1", facts, "prj_2")); + expect(result.allow).toBe(false); + }); + }); + + describe("environment.delete action", () => { + it("allows owner to delete environments", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("owner", "org_1")], "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows admin to delete environments", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("admin", "org_1")], "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + + it("denies builder from deleting environments", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("builder", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies viewer from deleting environments", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("viewer", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies billing_admin from deleting environments", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("billing_admin", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("allows project_admin to delete environments for matching project", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("environment.delete", "org_1", facts, "prj_1")); + expect(result.allow).toBe(true); + expect(result.reason).toBe("project_admin"); + }); + + it("denies project_builder from deleting environments", () => { + const facts = [projectFact("project_builder", "org_1", "prj_1")]; + const result = authorize(authReq("environment.delete", "org_1", facts, "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies project_viewer from deleting environments", () => { + const facts = [projectFact("project_viewer", "org_1", "prj_1")]; + const result = authorize(authReq("environment.delete", "org_1", facts, "prj_1")); + expect(result.allow).toBe(false); + }); + + it("requires projectId scope", () => { + const result = authorize(authReq("environment.delete", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("invalid_scope"); + }); + + it("denies cross-org facts", () => { + const result = authorize(authReq("environment.delete", "org_2", [orgFact("owner", "org_1")], "prj_1")); + expect(result.allow).toBe(false); + }); + + it("denies wrong-project project role", () => { + const facts = [projectFact("project_admin", "org_1", "prj_1")]; + const result = authorize(authReq("environment.delete", "org_1", facts, "prj_2")); + expect(result.allow).toBe(false); + }); + }); + + describe("unknown future facts", () => { + it("ignores facts with unknown kind values", () => { + const facts: PolicyMembershipFact[] = [ + { kind: "entitlement", tier: "premium", scope: { kind: "organization", orgId: "org_1" } }, + ]; + const result = authorize(authReq("organization.read", "org_1", facts)); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("ignores facts with unknown roles but does not widen access", () => { + const facts: MembershipFact[] = [ + { kind: "role_assignment", role: "super_admin" as TenancyRole, scope: { kind: "organization", orgId: "org_1" } }, + ]; + const result = authorize(authReq("organization.read", "org_1", facts)); + expect(result.allow).toBe(false); + }); + + it("ignores malformed future fact objects without authorizing or throwing", () => { + const malformedNull: unknown = null; + const facts: PolicyMembershipFact[] = [ + { kind: "quota", limit: 100 }, + { kind: "role_assignment", role: "owner", scope: "org_1" }, + malformedNull as PolicyMembershipFact, + ]; + const result = authorize(authReq("organization.read", "org_1", facts)); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + }); + + describe("policyVersion and derivedScope", () => { + it("always returns policyVersion 1", () => { + const result = authorize(authReq("organization.read", "org_1", [orgFact("owner", "org_1")])); + expect(result.policyVersion).toBe(1); + }); + + it("returns derivedScope with orgId", () => { + const result = authorize(authReq("organization.read", "org_1", [orgFact("owner", "org_1")])); + expect(result.derivedScope.orgId).toBe("org_1"); + }); + + it("returns derivedScope with projectId when present", () => { + const result = authorize(authReq("project.read", "org_1", [orgFact("owner", "org_1")], "prj_1")); + expect(result.derivedScope.projectId).toBe("prj_1"); + }); + }); +}); + +describe("listEffectivePermissions", () => { + it("returns all permissions for owner", () => { + const input: EffectivePermissionsRequest = { + subject, + resource: { kind: "organization", orgId: "org_1" }, + context: { memberships: [orgFact("owner", "org_1")] }, + }; + const result = listEffectivePermissions(input); + expect(result.policyVersion).toBe(1); + expect(result.derivedScope.orgId).toBe("org_1"); + + const allowed = result.permissions.filter((p) => p.allow); + expect(allowed.length).toBe(31); + }); + + it("returns limited permissions for viewer", () => { + const input: EffectivePermissionsRequest = { + subject, + resource: { kind: "organization", orgId: "org_1" }, + context: { memberships: [orgFact("viewer", "org_1")] }, + }; + const result = listEffectivePermissions(input); + const allowed = result.permissions.filter((p) => p.allow); + expect(allowed.map((p) => p.action).sort()).toEqual([ + "organization.config.read", + "organization.integration.read", + "organization.metering.read", + "organization.read", + "organization.webhook.read", + "project.list", + "project.webhook.read", + ]); + }); + + it("returns billing permissions for billing_admin", () => { + const input: EffectivePermissionsRequest = { + subject, + resource: { kind: "organization", orgId: "org_1" }, + context: { memberships: [orgFact("billing_admin", "org_1")] }, + }; + const result = listEffectivePermissions(input); + const allowed = result.permissions.filter((p) => p.allow); + expect(allowed.map((p) => p.action).sort()).toEqual([ + "billing.manage", + "billing.read", + "organization.read", + ]); + }); + + it("returns no permissions when no facts match", () => { + const input: EffectivePermissionsRequest = { + subject, + resource: { kind: "organization", orgId: "org_1" }, + context: { memberships: [] }, + }; + const result = listEffectivePermissions(input); + const allowed = result.permissions.filter((p) => p.allow); + expect(allowed.length).toBe(0); + }); + + it("combines org and project role permissions", () => { + const input: EffectivePermissionsRequest = { + subject, + resource: { kind: "project", orgId: "org_1", projectId: "prj_1" }, + context: { + memberships: [ + orgFact("viewer", "org_1"), + projectFact("project_builder", "org_1", "prj_1"), + ], + }, + }; + const result = listEffectivePermissions(input); + const allowed = result.permissions.filter((p) => p.allow); + const actions = allowed.map((p) => p.action).sort(); + expect(actions).toContain("organization.read"); + expect(actions).toContain("project.read"); + expect(actions).toContain("project.update"); + expect(actions).toContain("environment.read"); + expect(actions).toContain("environment.update"); + }); +}); + +describe("validateRoleAssignment", () => { + describe("organization scope", () => { + it("accepts valid org roles", () => { + for (const role of ["owner", "admin", "builder", "viewer", "billing_admin"]) { + const result = validateRoleAssignment({ + role, + scope: { kind: "organization", orgId: "org_1" }, + }); + expect(result.valid).toBe(true); + expect(result.reason).toBe("valid_org_role"); + expect(result.policyVersion).toBe(1); + } + }); + + it("rejects project roles at org scope", () => { + const result = validateRoleAssignment({ + role: "project_admin", + scope: { kind: "organization", orgId: "org_1" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("invalid_role_for_scope"); + }); + + it("rejects unknown roles", () => { + const result = validateRoleAssignment({ + role: "super_admin", + scope: { kind: "organization", orgId: "org_1" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("invalid_role_for_scope"); + }); + }); + + describe("project scope", () => { + it("accepts valid project roles with projectId", () => { + for (const role of ["project_admin", "project_builder", "project_viewer"]) { + const result = validateRoleAssignment({ + role, + scope: { kind: "project", orgId: "org_1", projectId: "prj_1" }, + }); + expect(result.valid).toBe(true); + expect(result.reason).toBe("valid_project_role"); + } + }); + + it("rejects project roles without projectId", () => { + const result = validateRoleAssignment({ + role: "project_admin", + scope: { kind: "project", orgId: "org_1" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("missing_project_id"); + }); + + it("rejects org roles at project scope", () => { + const result = validateRoleAssignment({ + role: "admin", + scope: { kind: "project", orgId: "org_1", projectId: "prj_1" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("invalid_role_for_scope"); + }); + }); + + describe("edge cases", () => { + it("rejects missing orgId", () => { + const result = validateRoleAssignment({ + role: "owner", + scope: { kind: "organization", orgId: "" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("missing_org_id"); + }); + + it("rejects unknown scope kind", () => { + const result = validateRoleAssignment({ + role: "owner", + scope: { kind: "environment" as RoleScopeKind, orgId: "org_1" }, + }); + expect(result.valid).toBe(false); + expect(result.reason).toBe("unknown_scope_kind"); + }); + }); +}); + +describe("audit.read authorization", () => { + it("allows organization owner to read audit", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_owner"); + }); + + it("allows organization admin to read audit", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("admin", "org_1")])); + expect(result.allow).toBe(true); + expect(result.reason).toBe("org_admin"); + }); + + it("denies organization builder from reading audit", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("builder", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies organization viewer from reading audit", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("viewer", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies billing_admin from reading audit", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("billing_admin", "org_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies project-scoped roles from reading organization audit", () => { + const result = authorize(authReq("audit.read", "org_1", [projectFact("project_admin", "org_1", "prj_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies project_builder from reading organization audit", () => { + const result = authorize(authReq("audit.read", "org_1", [projectFact("project_builder", "org_1", "prj_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies project_viewer from reading organization audit", () => { + const result = authorize(authReq("audit.read", "org_1", [projectFact("project_viewer", "org_1", "prj_1")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies when memberships are for a different org", () => { + const result = authorize(authReq("audit.read", "org_1", [orgFact("owner", "org_other")])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); + + it("denies malformed membership facts", () => { + const malformed = { kind: "something_else", role: "owner" } as unknown as MembershipFact; + const result = authorize(authReq("audit.read", "org_1", [malformed])); + expect(result.allow).toBe(false); + expect(result.reason).toBe("no_matching_role"); + }); +}); + +describe("service-principal binding actions", () => { + const spActions = [ + "organization.service_principal.binding.create", + "organization.service_principal.binding.list", + "organization.service_principal.binding.revoke", + ]; + + for (const action of spActions) { + it(`owner can ${action}`, () => { + const result = authorize(authReq(action, "org_1", [orgFact("owner", "org_1")])); + expect(result.allow).toBe(true); + }); + + it(`admin can ${action}`, () => { + const result = authorize(authReq(action, "org_1", [orgFact("admin", "org_1")])); + expect(result.allow).toBe(true); + }); + + it(`builder cannot ${action}`, () => { + const result = authorize(authReq(action, "org_1", [orgFact("builder", "org_1")])); + expect(result.allow).toBe(false); + }); + + it(`viewer cannot ${action}`, () => { + const result = authorize(authReq(action, "org_1", [orgFact("viewer", "org_1")])); + expect(result.allow).toBe(false); + }); + + it(`billing_admin cannot ${action}`, () => { + const result = authorize(authReq(action, "org_1", [orgFact("billing_admin", "org_1")])); + expect(result.allow).toBe(false); + }); + } +}); + +describe("integration actions (saas-integrations IG1)", () => { + const ORG = "org-1"; + + it("owner and admin can read, connect, and manage integrations", () => { + for (const role of ["owner", "admin"]) { + for (const action of [ + "organization.integration.read", + "organization.integration.connect", + "organization.integration.manage", + ]) { + expect(authorize(authReq(action, ORG, [orgFact(role, ORG)])).allow).toBe(true); + } + } + }); + + it("builder and viewer can only read integrations", () => { + for (const role of ["builder", "viewer"]) { + expect( + authorize(authReq("organization.integration.read", ORG, [orgFact(role, ORG)])).allow, + ).toBe(true); + expect( + authorize(authReq("organization.integration.connect", ORG, [orgFact(role, ORG)])).allow, + ).toBe(false); + expect( + authorize(authReq("organization.integration.manage", ORG, [orgFact(role, ORG)])).allow, + ).toBe(false); + } + }); + + it("denies integration actions across org boundaries and for project roles", () => { + expect( + authorize(authReq("organization.integration.connect", ORG, [orgFact("owner", "org-2")])).allow, + ).toBe(false); + expect( + authorize( + authReq("organization.integration.connect", ORG, [projectFact("project_admin", ORG, "p1")]), + ).allow, + ).toBe(false); + }); +}); + +describe("project.repo_link.write (saas-integrations IG3)", () => { + const ORG = "org-1"; + + it("requires a projectId (project-scoped action)", () => { + expect( + authorize(authReq("project.repo_link.write", ORG, [orgFact("owner", ORG)])).allow, + ).toBe(false); + expect( + authorize(authReq("project.repo_link.write", ORG, [orgFact("owner", ORG)], "p1")).allow, + ).toBe(true); + }); + + it("grants org owner/admin and the project's own admin, denies the rest", () => { + expect( + authorize(authReq("project.repo_link.write", ORG, [orgFact("admin", ORG)], "p1")).allow, + ).toBe(true); + expect( + authorize( + authReq("project.repo_link.write", ORG, [projectFact("project_admin", ORG, "p1")], "p1"), + ).allow, + ).toBe(true); + expect( + authorize( + authReq("project.repo_link.write", ORG, [projectFact("project_admin", ORG, "p2")], "p1"), + ).allow, + ).toBe(false); + expect( + authorize(authReq("project.repo_link.write", ORG, [orgFact("builder", ORG)], "p1")).allow, + ).toBe(false); + expect( + authorize( + authReq("project.repo_link.write", ORG, [projectFact("project_builder", ORG, "p1")], "p1"), + ).allow, + ).toBe(false); + }); +}); diff --git a/tests/policy-engine/tsconfig.json b/tests/policy-engine/tsconfig.json new file mode 100644 index 0000000..caba175 --- /dev/null +++ b/tests/policy-engine/tsconfig.json @@ -0,0 +1,19 @@ +{ + "extends": "../../tooling/tsconfig/base.json", + "compilerOptions": { + "types": ["jest"], + "allowSyntheticDefaultImports": true, + "composite": false, + "incremental": false, + "declaration": false, + "declarationMap": false, + "baseUrl": ".", + "paths": { + "@saas/contracts": ["../../packages/contracts/src/index.ts"], + "@saas/contracts/*": ["../../packages/contracts/src/*.ts"], + "@saas/policy-engine": ["../../packages/policy-engine/src/index.ts"] + } + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +}