diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..1697f79 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,51 @@ +# Exclude anything that would slow a build, break it, or leak into an image. + +# Host-installed dependencies — NEVER ship these. npm resolves platform-specific +# native binaries here (@cloudflare/workerd-*, @esbuild/*, @tailwindcss/oxide-*) +# and a win32 build cannot execute in a Linux container. Every image runs its +# own `npm ci` instead. +node_modules/ +**/node_modules/ + +# Build output — rebuilt inside the image. NOTE: this is exactly why every +# Dockerfile runs `npm run build -w @toggleflow/engine`, and why the dev profile +# has an engine watcher service: @toggleflow/engine resolves through its +# package.json "exports" to dist/, which never arrives with the source. +dist/ +**/dist/ +.turbo/ +**/.turbo/ +coverage/ +**/coverage/ +*.tsbuildinfo + +# Local workerd/miniflare KV state. Containers get the `wrangler-state` named +# volume; a Windows copy of a SQLite store must never seed it. +.wrangler/ +**/.wrangler/ + +# Stale pnpm artefacts — this repo is npm workspaces (packageManager npm@11.16.0) +# and package-lock.json is the only lockfile the Dockerfiles copy. +pnpm-lock.yaml +pnpm-workspace.yaml + +.git/ +.github/ +.gitignore +.gitattributes +*.md + +# Env values arrive via compose `environment:` (runtime) and build args (build +# time) — never baked into a layer. +.env +.env.* +!.env.example + +# Not needed in any image. docker/ IS needed: the nginx confs are COPYd. +docker-compose.yml + +.vscode/ +.idea/ +.DS_Store +Thumbs.db +*.log diff --git a/.env.example b/.env.example index 6c58fa2..945804d 100644 --- a/.env.example +++ b/.env.example @@ -1,20 +1,44 @@ # Copy to .env and adjust. .env is gitignored. +# +# THIS FILE IS FOR BARE-METAL DEV (`npm run dev` on the host). +# +# Two things worth knowing: +# +# 1. Nothing loads this file into the app. There is no dotenv and no +# --env-file anywhere in the repo, and Node does not auto-load .env. Bare-metal +# dev works because every value below equals the zod default in +# apps/api/src/env.ts. Change one here and the app will NOT see it — export it +# in your shell instead. +# +# 2. Docker Compose DOES read this file, for ${VAR} interpolation. That means +# anything defined here overrides the `:-default` build args in +# docker-compose.yml. The VITE_* values below deliberately match those +# defaults so the shadowing is a no-op. Verify with: +# docker compose --profile prod config | grep VITE_ +# Container runtime values are set inline in docker-compose.yml, not here — +# they differ (postgres:5432, not localhost:5434). # --- Control-plane API (apps/api) --- PORT=4000 HOST=0.0.0.0 -# ToggleFlow's own dev Postgres (docker compose up -d). Host port 5434 — -# 5433 belongs to the fixmytext stack's velobits-dev-db. +# ToggleFlow's own dev Postgres (`docker compose --profile dev up -d postgres`). +# Host port 5434 — 5433 belongs to the fixmytext stack's velobits-dev-db. DATABASE_URL=postgres://toggleflow:toggleflow@localhost:5434/toggleflow -# --- Auth (shared keycloak-dev + shared Velobits-Dev realm, velobits-infra stack) --- +# --- Auth (shared keycloak-dev + shared Velobits realm, velobits-infra stack) --- # Start that stack first (`docker compose up -d` in ../velobits-infra). -# ToggleFlow uses the shared Velobits-Dev realm with its own clients +# ToggleFlow uses the shared Velobits realm with its own clients # (toggleflow-dashboard SPA/PKCE + toggleflow-api bearer audience) — # decided 2026-07-27, superseding the earlier dedicated-realm plan. -# Host address below; containerized services use http://keycloak-dev:8080. +# KEYCLOAK_URL is the ISSUER: it must match the `iss` claim byte-for-byte. +# velobits-infra pins KC_HOSTNAME=localhost, so every token says +# http://localhost:8080/realms/Velobits regardless of the request's Host header. KEYCLOAK_URL=http://localhost:8080 -KEYCLOAK_REALM=Velobits-Dev +# Containers only: the base used for the JWKS *network fetch*, because the issuer +# address above is unreachable from inside one. docker-compose.yml sets this to +# http://keycloak-dev:8080; leave it unset on bare metal. +# KEYCLOAK_INTERNAL_URL=http://keycloak-dev:8080 +KEYCLOAK_REALM=Velobits # Access-token audience the API requires (set by the dashboard client's audience mapper). KEYCLOAK_AUDIENCE=toggleflow-api @@ -36,3 +60,13 @@ PUBLISH_DEBOUNCE_MS=500 # Production only (KV_MODE=cloudflare); also used by wrangler for deploys. # CLOUDFLARE_API_TOKEN= # CLOUDFLARE_ACCOUNT_ID= + +# --- Dashboard (apps/dashboard) --- +# Vite BAKES these into the bundle at build time (apps/dashboard/src/auth/oidc.ts), +# so they are browser-facing HOST addresses even for containerized builds. These +# also feed the ${} build args in docker-compose.yml — see the header note about +# shadowing, and keep VITE_KEYCLOAK_URL in sync with the CSP connect-src in +# docker/nginx.router.prod.conf. +VITE_KEYCLOAK_URL=http://localhost:8080 +VITE_KEYCLOAK_REALM=Velobits +VITE_KEYCLOAK_CLIENT_ID=toggleflow-dashboard diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..28d58b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,14 @@ +# Normalise line endings to LF in the repository. CRLF reaching a Linux +# container produces errors that look nothing like a line-ending problem: +# Dockerfile with CRLF → exec /bin/sh: no such file or directory +# *.sh with CRLF → $'\r': command not found +# env file with CRLF → a trailing \r INSIDE the value, so a DATABASE_URL +# becomes "…/toggleflow\r" and Postgres rejects it +* text=auto eol=lf + +Dockerfile* text eol=lf +*.sh text eol=lf +*.conf text eol=lf +.env* text eol=lf +*.yml text eol=lf +*.yaml text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 374e286..b5aabea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,35 +3,165 @@ name: CI on: push: branches: [main, develop] + # `branches` filters on the PR's BASE, not its head. Without it every pull + # request runs — including feature -> sandbox, where sandbox is the shared + # integration branch and CI is not wanted. The trade-off is deliberate: + # nothing gates a merge into sandbox, and breakage surfaces one step later at + # the sandbox -> develop PR. pull_request: + branches: [main, develop] + workflow_dispatch: + +# One run per ref. A force-push to a PR cancels the superseded run instead of +# leaving two full pipelines (including the 25-minute docker smoke) racing. +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +# Read-only by default; no job here writes to the repo. +permissions: + contents: read jobs: ci: runs-on: ubuntu-latest + # The postgres service health-check can hang; fail fast rather than sitting + # until GitHub's 6h default. + timeout-minutes: 20 + + services: + # apps/api's integration tests hit a real Postgres and TRUNCATE all 13 + # tables between suites (apps/api/test/helpers.ts). Port 5434 matches the + # DATABASE_URL default in apps/api/src/env.ts and docker-compose.yml, so + # nothing needs a special-case URL. + postgres: + image: postgres:17-alpine + env: + POSTGRES_USER: toggleflow + POSTGRES_PASSWORD: toggleflow + POSTGRES_DB: toggleflow + ports: + - 5434:5432 + options: >- + --health-cmd "pg_isready -U toggleflow -d toggleflow" + --health-interval 5s + --health-timeout 3s + --health-retries 10 + steps: - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 with: node-version: 24 - cache: pnpm + cache: npm - name: Install dependencies - run: pnpm install --frozen-lockfile + run: npm ci + + # Turbo's cache is local-only, so without this every run rebuilds and + # re-tests from cold. Keyed on the lockfile plus the SHA so a run restores + # the nearest previous cache and then writes its own. + - name: Restore turbo cache + uses: actions/cache@v4 + with: + path: .turbo + key: turbo-${{ runner.os }}-${{ hashFiles('package-lock.json') }}-${{ github.sha }} + restore-keys: | + turbo-${{ runner.os }}-${{ hashFiles('package-lock.json') }}- + turbo-${{ runner.os }}- - name: Lint - run: pnpm lint + run: npm run lint - name: Format check - run: pnpm format:check + run: npm run format:check - name: Typecheck - run: pnpm typecheck + run: npm run typecheck - name: Build - run: pnpm build + run: npm run build + + # One merged coverage run across every workspace instead of `npm test`. + # It runs the same 179 tests, so nothing is lost by replacing the plain + # test step — and it must come after Build because apps/edge-worker's + # suite boots dist/index.js in workerd. Thresholds live in + # vitest.config.ts and fail the step on their own. + - name: Test + coverage + run: npm run test:coverage + env: + # Set explicitly rather than relying on the zod default: every var in + # apps/api/src/env.ts has one, so a mis-wired database never throws at + # boot — it fails at the first query, much further from the cause. + DATABASE_URL: postgres://toggleflow:toggleflow@localhost:5434/toggleflow + + - name: Upload coverage report + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage + path: coverage/ + retention-days: 7 + if-no-files-found: warn + + docker-smoke: + name: Docker prod smoke + runs-on: ubuntu-latest + # Fail fast rather than sitting until GitHub's 6h default if something hangs. + timeout-minutes: 25 + + steps: + - uses: actions/checkout@v4 + + # ../velobits-infra owns velobits-net and does not exist in CI. api-prod + # joins it as external, so it must exist or `up` errors out. No Keycloak is + # needed here: /health sits outside the /v1/ auth hook and jose's + # createRemoteJWKSet fetches lazily — only an authenticated request would + # try to reach it. + - name: Create the external network the compose file expects + run: docker network create velobits-net || true + + - name: Start the prod stack + run: docker compose --profile prod up --build -d + + - name: Wait for the router + run: | + for i in $(seq 1 60); do + if curl -sf -o /dev/null http://localhost:3200/healthz; then + echo "router up after ${i} attempts"; exit 0 + fi + sleep 5 + done + echo "router did not become ready" >&2 + exit 1 + + - name: Smoke — the stack through one origin + run: | + set -euo pipefail + # Dashboard: nginx serves the built SPA at the webroot. + curl -sf http://localhost:3200/ | grep -q '
-w @toggleflow/`. -Database (from `apps/api`): `pnpm db:generate` (emit SQL migrations from the Drizzle schema), `pnpm db:migrate`, `pnpm db:studio`. Migrations in `apps/api/drizzle/` are committed. +Database (from `apps/api`): `npm run db:generate` (emit SQL migrations from the Drizzle schema), `npm run db:migrate`, `npm run db:studio`. Migrations in `apps/api/drizzle/` are committed. ## Architecture in one paragraph diff --git a/apps/api/package.json b/apps/api/package.json index f43a880..819d0a5 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -18,7 +18,7 @@ }, "dependencies": { "@fastify/cors": "^11.3.0", - "@toggleflow/engine": "workspace:*", + "@toggleflow/engine": "*", "drizzle-orm": "^0.45.2", "fastify": "^5.10.0", "jose": "^6.1.3", diff --git a/apps/api/src/auth/verifier.ts b/apps/api/src/auth/verifier.ts index 9c4ffcd..8bde1c8 100644 --- a/apps/api/src/auth/verifier.ts +++ b/apps/api/src/auth/verifier.ts @@ -45,7 +45,22 @@ export function createTokenVerifier(config: VerifierConfig): TokenVerifier { }; } -export function createKeycloakVerifier(opts: { issuer: string; audience: string }): TokenVerifier { - const jwksUrl = new URL(`${opts.issuer}/protocol/openid-connect/certs`); - return createTokenVerifier({ ...opts, getKey: createRemoteJWKSet(jwksUrl) }); +export function createKeycloakVerifier(opts: { + issuer: string; + audience: string; + /** + * Base for the JWKS network fetch; defaults to `issuer`. These differ inside a + * container: Keycloak pins the `iss` claim to its configured frontend URL + * (http://localhost:8080/...), which a container cannot reach — so the fetch + * goes to http://keycloak-dev:8080/... over the shared network while `iss` + * validation still compares against `issuer`. + */ + jwksIssuer?: string; +}): TokenVerifier { + const jwksUrl = new URL(`${opts.jwksIssuer ?? opts.issuer}/protocol/openid-connect/certs`); + return createTokenVerifier({ + issuer: opts.issuer, + audience: opts.audience, + getKey: createRemoteJWKSet(jwksUrl), + }); } diff --git a/apps/api/src/db/schema.ts b/apps/api/src/db/schema.ts index 9501df3..e4a142b 100644 --- a/apps/api/src/db/schema.ts +++ b/apps/api/src/db/schema.ts @@ -3,7 +3,7 @@ * * Tenancy: org → project → environment. Tools + segments are project-scoped; * flag state, config, ruleset snapshots, and API keys are per-environment. - * `pnpm db:generate` emits SQL migrations into ./drizzle (committed). + * `npm run db:generate` emits SQL migrations into ./drizzle (committed). */ import { relations, sql } from 'drizzle-orm'; import { diff --git a/apps/api/src/db/seed.ts b/apps/api/src/db/seed.ts index 11b6bb1..983da1f 100644 --- a/apps/api/src/db/seed.ts +++ b/apps/api/src/db/seed.ts @@ -2,7 +2,7 @@ * Dev seed: demo org → project → dev/staging/prod → a handful of tools with * flag state, a segment, and versioned config on two tools. * - * Run with `pnpm db:seed` (after `pnpm db:migrate`). Safe to re-run: exits + * Run with `npm run db:seed` (after `npm run db:migrate`). Safe to re-run: exits * early if the demo org already exists. */ import { eq } from 'drizzle-orm'; diff --git a/apps/api/src/env.ts b/apps/api/src/env.ts index 47eb0af..7b5979d 100644 --- a/apps/api/src/env.ts +++ b/apps/api/src/env.ts @@ -9,7 +9,14 @@ const envSchema = z.object({ HOST: z.string().default('0.0.0.0'), DATABASE_URL: z.string().default('postgres://toggleflow:toggleflow@localhost:5434/toggleflow'), KEYCLOAK_URL: z.string().default('http://localhost:8080'), - KEYCLOAK_REALM: z.string().default('Velobits-Dev'), + // Container-only override for the JWKS *network fetch*. The `iss` claim + // Keycloak mints is pinned by KC_HOSTNAME=localhost in the velobits-infra + // stack, so KEYCLOAK_URL (and therefore keycloakIssuer) must stay + // http://localhost:8080 to match it — but that address is unreachable from + // inside a container. Set this to http://keycloak-dev:8080 there, and leave it + // unset on bare metal. + KEYCLOAK_INTERNAL_URL: z.string().optional(), + KEYCLOAK_REALM: z.string().default('Velobits'), KEYCLOAK_AUDIENCE: z.string().default('toggleflow-api'), // Delivery-plane publish target. `miniflare` = workerd's local KV persisted // into the edge worker's .wrangler state so `wrangler dev` reads it. @@ -31,6 +38,8 @@ export const env = { keycloakRealm: parsed.KEYCLOAK_REALM, keycloakAudience: parsed.KEYCLOAK_AUDIENCE, keycloakIssuer: `${parsed.KEYCLOAK_URL}/realms/${parsed.KEYCLOAK_REALM}`, + /** Same shape as keycloakIssuer, but used only to build the JWKS fetch URL. */ + keycloakJwksIssuer: `${parsed.KEYCLOAK_INTERNAL_URL ?? parsed.KEYCLOAK_URL}/realms/${parsed.KEYCLOAK_REALM}`, kvMode: parsed.KV_MODE, kvNamespaceId: parsed.KV_NAMESPACE_ID, kvPersistPath: parsed.KV_PERSIST_PATH, diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index e5b0c19..4ac04e8 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -3,6 +3,20 @@ import { buildServer } from './server'; const app = await buildServer(); +// Containers stop with SIGTERM. Without a handler, `docker stop` SIGKILLs after +// its grace period and the onClose hook in server.ts never runs — leaving the +// publisher undrained, miniflare's workerd child orphaned (and its KV store +// possibly locked), and the Postgres pool abandoned. +for (const signal of ['SIGTERM', 'SIGINT'] as const) { + process.once(signal, () => { + app.log.info({ signal }, 'shutting down'); + void app.close().then( + () => process.exit(0), + () => process.exit(1), + ); + }); +} + try { await app.listen({ port: env.port, host: env.host }); } catch (err) { diff --git a/apps/api/src/scripts/migrate.ts b/apps/api/src/scripts/migrate.ts new file mode 100644 index 0000000..de3d523 --- /dev/null +++ b/apps/api/src/scripts/migrate.ts @@ -0,0 +1,29 @@ +/** + * Standalone migrator for containers and CI. + * + * Deliberately dependency-light: it uses drizzle-orm's programmatic migrator over + * the committed SQL in apps/api/drizzle — the same path apps/api/test/helpers.ts + * takes — so it needs neither drizzle-kit (a devDependency, pruned out of the + * production image) nor drizzle.config.ts. `npm run db:migrate` stays the + * bare-metal developer command; this is the one a prod-only-deps image can run. + */ +import { fileURLToPath } from 'node:url'; + +import { drizzle } from 'drizzle-orm/postgres-js'; +import { migrate } from 'drizzle-orm/postgres-js/migrator'; +import postgres from 'postgres'; + +import { env } from '../env'; + +// Resolved from this module's own URL, not process.cwd(). '../../drizzle' lands on +// apps/api/drizzle from BOTH src/scripts/migrate.ts (tsx, dev image, cwd /app) and +// dist/scripts/migrate.js (production image, cwd /app/apps/api). +const migrationsFolder = fileURLToPath(new URL('../../drizzle', import.meta.url)); + +const client = postgres(env.databaseUrl, { max: 1 }); +try { + await migrate(drizzle(client), { migrationsFolder }); + console.log(`migrations applied from ${migrationsFolder}`); +} finally { + await client.end(); +} diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index cee85d9..faf6be1 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -92,7 +92,11 @@ export async function buildServer(opts: BuildServerOptions = {}): Promise diff --git a/apps/api/test/kv-cloudflare.test.ts b/apps/api/test/kv-cloudflare.test.ts new file mode 100644 index 0000000..77aa442 --- /dev/null +++ b/apps/api/test/kv-cloudflare.test.ts @@ -0,0 +1,121 @@ +/** + * The production KV client, driven against a stubbed `fetch`. This is the one + * path that cannot be exercised for real in CI — it talks to api.cloudflare.com + * — so the contract is pinned here instead: URL shape, auth header, the + * multipart body, and which HTTP statuses are errors versus expected misses. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { createCloudflareKvClient } from '../src/lib/kv'; + +const ACCOUNT = 'acct-123'; +const NAMESPACE = 'ns-456'; +const TOKEN = 'cf-token'; +const BASE = `https://api.cloudflare.com/client/v4/accounts/${ACCOUNT}/storage/kv/namespaces/${NAMESPACE}`; + +const client = () => + createCloudflareKvClient({ accountId: ACCOUNT, namespaceId: NAMESPACE, apiToken: TOKEN }); + +/** Queue one response per expected fetch, in order. */ +function stubFetch(...responses: Response[]) { + const spy = vi.fn(); + for (const res of responses) spy.mockResolvedValueOnce(res); + vi.stubGlobal('fetch', spy); + return spy; +} + +const ok = (body = '', status = 200) => new Response(body, { status }); + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('put', () => { + it('PUTs a multipart body with value and metadata to the values endpoint', async () => { + const spy = stubFetch(ok()); + await client().put('ruleset:env-1', '{"flags":[]}', { contentHash: 'abc', version: 7 }); + + expect(spy).toHaveBeenCalledOnce(); + const [url, init] = spy.mock.calls[0]!; + expect(url).toBe(`${BASE}/values/ruleset%3Aenv-1`); + expect(init?.method).toBe('PUT'); + expect((init?.headers as Record).authorization).toBe(`Bearer ${TOKEN}`); + + const form = init?.body as FormData; + expect(form.get('value')).toBe('{"flags":[]}'); + expect(JSON.parse(form.get('metadata') as string)).toEqual({ + contentHash: 'abc', + version: 7, + }); + }); + + it('sends an empty metadata object when none is supplied', async () => { + const spy = stubFetch(ok()); + await client().put('keys:env-1', 'payload'); + const form = spy.mock.calls[0]![1]!.body as FormData; + expect(form.get('metadata')).toBe('{}'); + }); + + it('throws with the status when Cloudflare rejects the write', async () => { + stubFetch(ok('denied', 403)); + await expect(client().put('ruleset:env-1', 'x')).rejects.toThrow( + 'KV put ruleset:env-1 failed: HTTP 403', + ); + }); +}); + +describe('getWithMetadata', () => { + it('returns the value and the metadata result', async () => { + const spy = stubFetch( + ok('{"flags":[]}'), + ok(JSON.stringify({ result: { contentHash: 'abc', version: 7 } })), + ); + + const entry = await client().getWithMetadata('ruleset:env-1'); + expect(entry).toEqual({ value: '{"flags":[]}', metadata: { contentHash: 'abc', version: 7 } }); + expect(spy.mock.calls[0]![0]).toBe(`${BASE}/values/ruleset%3Aenv-1`); + expect(spy.mock.calls[1]![0]).toBe(`${BASE}/metadata/ruleset%3Aenv-1`); + }); + + it('treats a 404 as an empty entry and never asks for metadata', async () => { + const spy = stubFetch(ok('', 404)); + expect(await client().getWithMetadata('missing')).toEqual({ value: null, metadata: null }); + // A miss is normal — the second round trip would be wasted. + expect(spy).toHaveBeenCalledOnce(); + }); + + it('keeps the value when the metadata request fails', async () => { + stubFetch(ok('body'), ok('', 500)); + expect(await client().getWithMetadata('k')).toEqual({ value: 'body', metadata: null }); + }); + + it('nulls the metadata when the response carries no result', async () => { + stubFetch(ok('body'), ok(JSON.stringify({}))); + expect(await client().getWithMetadata('k')).toEqual({ value: 'body', metadata: null }); + }); + + it('throws on a non-404 read failure', async () => { + stubFetch(ok('', 500)); + await expect(client().getWithMetadata('k')).rejects.toThrow('KV get k failed: HTTP 500'); + }); +}); + +describe('delete', () => { + it('DELETEs the value endpoint', async () => { + const spy = stubFetch(ok()); + await client().delete('ruleset:env-1'); + const [url, init] = spy.mock.calls[0]!; + expect(url).toBe(`${BASE}/values/ruleset%3Aenv-1`); + expect(init?.method).toBe('DELETE'); + }); + + it('tolerates a 404 — deleting an absent key is a no-op', async () => { + stubFetch(ok('', 404)); + await expect(client().delete('missing')).resolves.toBeUndefined(); + }); + + it('throws on any other failure', async () => { + stubFetch(ok('', 500)); + await expect(client().delete('k')).rejects.toThrow('KV delete k failed: HTTP 500'); + }); +}); diff --git a/apps/api/test/seed.test.ts b/apps/api/test/seed.test.ts new file mode 100644 index 0000000..944deaf --- /dev/null +++ b/apps/api/test/seed.test.ts @@ -0,0 +1,176 @@ +/** + * The dev seed script. It is a documented setup step (`npm run db:seed`), so a + * silent break costs every new developer an afternoon — and it is the one place + * the interesting prod flag states (a kill switch, a 25% rollout) are asserted + * end to end. + * + * seed.ts runs on import via a top-level `seed().catch(...)`, so each case here + * resets the module registry and re-imports to trigger a run. + */ +import { eq } from 'drizzle-orm'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Db } from '../src/db'; +import { + configVersions, + environments, + flagStates, + orgMemberships, + orgs, + projects, + segments, + toolConfigs, + tools, +} from '../src/db/schema'; +import { resetDb, setupTestApp, type TestHarness } from './helpers'; + +let h: TestHarness; +let db: Db; +let logs: string[]; + +beforeAll(async () => { + h = await setupTestApp(); + db = h.db; +}); +afterAll(async () => { + await h.app.close(); +}); + +beforeEach(async () => { + await resetDb(db); + logs = []; + vi.spyOn(console, 'log').mockImplementation((msg: unknown) => void logs.push(String(msg))); + vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.resetModules(); +}); +afterEach(() => { + vi.restoreAllMocks(); +}); + +/** + * Imports seed.ts (which starts the run) and waits for it to settle. The module + * does not export a promise, so completion is observed through its log line. + */ +async function runSeed(): Promise { + await import('../src/db/seed'); + for (let i = 0; i < 100; i++) { + if (logs.some((l) => l.startsWith('Seeded:') || l.startsWith('Seed skipped:'))) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error(`seed did not finish; logs: ${JSON.stringify(logs)}`); +} + +describe('dev seed', () => { + it('creates the demo org, admin, and membership', async () => { + await runSeed(); + + const [org] = await db.select().from(orgs).where(eq(orgs.name, 'Demo Org')); + expect(org).toBeDefined(); + const memberships = await db + .select() + .from(orgMemberships) + .where(eq(orgMemberships.orgId, org!.id)); + expect(memberships).toHaveLength(1); + expect(memberships[0]!.role).toBe('admin'); + }); + + it('creates one project with dev, staging, and prod', async () => { + await runSeed(); + + const [project] = await db.select().from(projects); + expect(project!.name).toBe('Demo Project'); + const envRows = await db + .select() + .from(environments) + .where(eq(environments.projectId, project!.id)); + expect(envRows.map((e) => e.key).sort()).toEqual(['dev', 'prod', 'staging']); + }); + + it('registers five tools with tags', async () => { + await runSeed(); + + const toolRows = await db.select().from(tools); + expect(toolRows).toHaveLength(5); + expect(toolRows.map((t) => t.key).sort()).toEqual([ + 'tool.grammar-check', + 'tool.summarize', + 'tool.title-case', + 'tool.tone-rewrite', + 'tool.translate', + ]); + expect(toolRows.find((t) => t.key === 'tool.tone-rewrite')!.tags).toContain('experimental'); + }); + + it('leaves dev and staging fully on', async () => { + await runSeed(); + + const nonProd = await db.select().from(environments); + const devIds = nonProd.filter((e) => e.key !== 'prod').map((e) => e.id); + const states = await db.select().from(flagStates); + + const nonProdStates = states.filter((s) => devIds.includes(s.environmentId)); + expect(nonProdStates).toHaveLength(10); // 5 tools x 2 environments + expect(nonProdStates.every((s) => s.enabled)).toBe(true); + expect(nonProdStates.every((s) => s.rolloutPercent === null)).toBe(true); + }); + + it('kill-switches translate and puts tone-rewrite on a 25% rollout in prod only', async () => { + await runSeed(); + + const [prod] = await db.select().from(environments).where(eq(environments.key, 'prod')); + const toolRows = await db.select().from(tools); + const prodStates = await db + .select() + .from(flagStates) + .where(eq(flagStates.environmentId, prod!.id)); + const byKey = (key: string) => { + const tool = toolRows.find((t) => t.key === key)!; + return prodStates.find((s) => s.toolId === tool.id)!; + }; + + expect(byKey('tool.translate').enabled).toBe(false); + expect(byKey('tool.tone-rewrite').rolloutPercent).toBe(25); + // Everything else is plain on. + expect(byKey('tool.summarize').enabled).toBe(true); + expect(byKey('tool.summarize').rolloutPercent).toBeNull(); + }); + + it('creates the beta-users segment', async () => { + await runSeed(); + + const [segment] = await db.select().from(segments); + expect(segment!.key).toBe('beta-users'); + expect(segment!.rules).toEqual([ + { attribute: 'plan', operator: 'in', values: ['pro', 'team'] }, + ]); + }); + + it('creates versioned prod config on exactly the two configured tools', async () => { + await runSeed(); + + const configs = await db.select().from(toolConfigs); + expect(configs).toHaveLength(2); + expect(configs.every((c) => c.version === 1)).toBe(true); + + const versions = await db.select().from(configVersions); + expect(versions).toHaveLength(2); + // The fallback payload rides inside the config value. + const value = configs[0]!.value as { fallback: { mode: string; message: string } }; + expect(value.fallback.mode).toBe('message'); + expect(value.fallback.message).toMatch(/temporarily unavailable/); + }); + + it('is safe to re-run — the second pass skips instead of duplicating', async () => { + await runSeed(); + expect(logs.some((l) => l.startsWith('Seeded:'))).toBe(true); + + logs = []; + vi.resetModules(); + await runSeed(); + + expect(logs.some((l) => l.startsWith('Seed skipped:'))).toBe(true); + expect(await db.select().from(orgs)).toHaveLength(1); + expect(await db.select().from(tools)).toHaveLength(5); + expect(process.exitCode).toBeFalsy(); + }); +}); diff --git a/apps/api/test/segments.test.ts b/apps/api/test/segments.test.ts new file mode 100644 index 0000000..2d1a81a --- /dev/null +++ b/apps/api/test/segments.test.ts @@ -0,0 +1,268 @@ +/** + * Reusable segments: CRUD, key/rule validation, RBAC, audit trail, and the + * fan-out that republishes every environment in the project on each mutation + * (a segment is referenced by rulesets, so editing one changes what the + * delivery plane must serve). + */ +import { eq } from 'drizzle-orm'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +import { segments } from '../src/db/schema'; +import { + addMember, + createWorkspace, + setupTestApp, + type TestHarness, + type Workspace, +} from './helpers'; + +let h: TestHarness; +let ws: Workspace; +let viewerToken: string; +let outsiderToken: string; + +beforeAll(async () => { + h = await setupTestApp(); + ws = await createWorkspace(h); + await addMember(h.db, ws.orgId, 'seg-viewer', 'viewer'); + viewerToken = await h.signToken('seg-viewer'); + // First login bootstraps its OWN org, so this caller is a legitimate user + // who simply has no membership in ws.orgId. + const outsider = await h.signToken('seg-outsider'); + await h.app.inject({ method: 'GET', url: '/v1/me', headers: h.authed(outsider) }); + outsiderToken = outsider; +}); +afterAll(async () => { + await h.app.close(); +}); + +// `unknown` here would push inject() onto its chainable overload, losing +// statusCode/json on the result. +const create = (payload: Record, token = ws.adminToken) => + h.app.inject({ + method: 'POST', + url: `/v1/projects/${ws.projectId}/segments`, + headers: h.authed(token), + payload, + }); + +describe('segments CRUD', () => { + let segmentId: string; + + it('creates a segment with rules and returns it', async () => { + const res = await create({ + key: 'beta-testers', + name: 'Beta testers', + description: 'Opted into the beta', + rules: [ + { attribute: 'plan', operator: 'in', values: ['pro', 'team'] }, + { attribute: 'seats', operator: 'gte', value: 5 }, + ], + }); + expect(res.statusCode).toBe(201); + const body = res.json(); + segmentId = body.id; + expect(body.key).toBe('beta-testers'); + expect(body.description).toBe('Opted into the beta'); + expect(body.rules).toHaveLength(2); + }); + + it('defaults rules to an empty array and description to null', async () => { + const res = await create({ key: 'everyone', name: 'Everyone' }); + expect(res.statusCode).toBe(201); + expect(res.json().rules).toEqual([]); + expect(res.json().description).toBeNull(); + }); + + it("lists a project's segments ordered by key", async () => { + const res = await h.app.inject({ + method: 'GET', + url: `/v1/projects/${ws.projectId}/segments`, + headers: h.authed(viewerToken), + }); + expect(res.statusCode).toBe(200); + expect(res.json().map((s: { key: string }) => s.key)).toEqual(['beta-testers', 'everyone']); + }); + + it('patches a subset of fields, leaving the rest intact', async () => { + const res = await h.app.inject({ + method: 'PATCH', + url: `/v1/segments/${segmentId}`, + headers: h.authed(ws.adminToken), + payload: { name: 'Beta cohort' }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().name).toBe('Beta cohort'); + // Untouched by a name-only patch. + expect(res.json().rules).toHaveLength(2); + expect(res.json().description).toBe('Opted into the beta'); + }); + + it('replaces rules and clears description via an explicit null', async () => { + const res = await h.app.inject({ + method: 'PATCH', + url: `/v1/segments/${segmentId}`, + headers: h.authed(ws.adminToken), + payload: { + description: null, + rules: [{ attribute: 'country', operator: 'eq', value: 'NL' }], + }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().description).toBeNull(); + expect(res.json().rules).toEqual([{ attribute: 'country', operator: 'eq', value: 'NL' }]); + }); + + it('deletes a segment and stops listing it', async () => { + const res = await h.app.inject({ + method: 'DELETE', + url: `/v1/segments/${segmentId}`, + headers: h.authed(ws.adminToken), + }); + expect(res.statusCode).toBe(204); + + const [row] = await h.db.select().from(segments).where(eq(segments.id, segmentId)); + expect(row).toBeUndefined(); + }); + + it('records create, update, and delete in the audit log', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `/v1/orgs/${ws.orgId}/audit`, + headers: h.authed(ws.adminToken), + }); + const actions = res.json().entries.map((e: { action: string }) => e.action); + expect(actions).toContain('segment.create'); + expect(actions).toContain('segment.update'); + expect(actions).toContain('segment.delete'); + }); +}); + +describe('segments validation', () => { + it.each([ + ['uppercase', 'Beta'], + ['leading dash', '-beta'], + ['spaces', 'beta testers'], + ['empty', ''], + ])('rejects a %s key', async (_label, key) => { + expect((await create({ key, name: 'x' })).statusCode).toBe(400); + }); + + it('accepts dots, dashes, underscores, and digits', async () => { + const res = await create({ key: 'eu.beta_2-x', name: 'Mixed' }); + expect(res.statusCode).toBe(201); + }); + + it('rejects an unknown operator', async () => { + const res = await create({ + key: 'bad-op', + name: 'Bad op', + rules: [{ attribute: 'plan', operator: 'startsWith', value: 'p' }], + }); + expect(res.statusCode).toBe(400); + }); + + it('rejects a numeric comparison against a non-number', async () => { + const res = await create({ + key: 'bad-gt', + name: 'Bad gt', + rules: [{ attribute: 'seats', operator: 'gt', value: 'five' }], + }); + expect(res.statusCode).toBe(400); + }); + + it('rejects an empty patch body', async () => { + const made = await create({ key: 'patchable', name: 'Patchable' }); + const res = await h.app.inject({ + method: 'PATCH', + url: `/v1/segments/${made.json().id}`, + headers: h.authed(ws.adminToken), + payload: {}, + }); + expect(res.statusCode).toBe(400); + }); + + it('rejects a non-uuid segment id', async () => { + const res = await h.app.inject({ + method: 'DELETE', + url: '/v1/segments/not-a-uuid', + headers: h.authed(ws.adminToken), + }); + expect(res.statusCode).toBe(400); + }); + + it('rejects a duplicate key within one project', async () => { + await create({ key: 'dupe', name: 'First' }); + const res = await create({ key: 'dupe', name: 'Second' }); + expect(res.statusCode).toBeGreaterThanOrEqual(400); + }); +}); + +describe('segments RBAC', () => { + it('lets a viewer read but not write', async () => { + const list = await h.app.inject({ + method: 'GET', + url: `/v1/projects/${ws.projectId}/segments`, + headers: h.authed(viewerToken), + }); + expect(list.statusCode).toBe(200); + expect((await create({ key: 'viewer-made', name: 'Nope' }, viewerToken)).statusCode).toBe(403); + }); + + it("hides another org's project behind a 404, not a 403", async () => { + expect((await create({ key: 'x', name: 'x' }, outsiderToken)).statusCode).toBe(404); + }); + + it('404s an unknown segment id', async () => { + const res = await h.app.inject({ + method: 'PATCH', + url: '/v1/segments/00000000-0000-4000-8000-000000000000', + headers: h.authed(ws.adminToken), + payload: { name: 'ghost' }, + }); + expect(res.statusCode).toBe(404); + }); + + it('rejects an unauthenticated request', async () => { + const res = await h.app.inject({ + method: 'GET', + url: `/v1/projects/${ws.projectId}/segments`, + }); + expect(res.statusCode).toBe(401); + }); +}); + +describe('segment mutations republish every environment in the project', () => { + it('schedules a ruleset publish per environment on create, patch, and delete', async () => { + const spy = vi.spyOn(h.app.publisher, 'scheduleRuleset'); + // createWorkspace seeds the default environment set; every one of them must + // be republished, not just the one being looked at. + const envIds = ws.environments.map((e) => e.id).sort(); + const scheduled = () => spy.mock.calls.map(([envId]) => envId).sort(); + + try { + const made = await create({ key: 'fanout', name: 'Fan out' }); + expect(made.statusCode).toBe(201); + expect(scheduled()).toEqual(envIds); + + spy.mockClear(); + await h.app.inject({ + method: 'PATCH', + url: `/v1/segments/${made.json().id}`, + headers: h.authed(ws.adminToken), + payload: { name: 'Fan out again' }, + }); + expect(scheduled()).toEqual(envIds); + + spy.mockClear(); + await h.app.inject({ + method: 'DELETE', + url: `/v1/segments/${made.json().id}`, + headers: h.authed(ws.adminToken), + }); + expect(scheduled()).toEqual(envIds); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/apps/api/tsup.config.ts b/apps/api/tsup.config.ts index 69639c3..ff76c16 100644 --- a/apps/api/tsup.config.ts +++ b/apps/api/tsup.config.ts @@ -1,7 +1,11 @@ import { defineConfig } from 'tsup'; export default defineConfig({ - entry: ['src/index.ts'], + // migrate.ts and seed.ts ship alongside the server so the one-shot compose + // services can reuse the production image — drizzle-kit and tsx are + // devDependencies and are pruned out of it. tsup preserves the src/ tree shape, + // so the outputs are dist/index.js, dist/scripts/migrate.js, dist/db/seed.js. + entry: ['src/index.ts', 'src/scripts/migrate.ts', 'src/db/seed.ts'], format: ['esm'], target: 'node22', sourcemap: true, diff --git a/apps/dashboard/package.json b/apps/dashboard/package.json index 33f6285..63cd8c9 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -17,7 +17,7 @@ "@radix-ui/react-toast": "^1.2.23", "@radix-ui/react-toggle-group": "^1.1.19", "@tanstack/react-query": "^5.101.4", - "@toggleflow/engine": "workspace:*", + "@toggleflow/engine": "*", "clsx": "^2.1.1", "oidc-client-ts": "^3.5.0", "react": "^19.2.8", diff --git a/apps/dashboard/src/App.tsx b/apps/dashboard/src/App.tsx index 0b0521d..f0a0c2f 100644 --- a/apps/dashboard/src/App.tsx +++ b/apps/dashboard/src/App.tsx @@ -5,7 +5,7 @@ import { CallbackPage } from './auth/CallbackPage'; import { Layout } from './components/Layout'; import { ApiKeysPage } from './pages/ApiKeysPage'; import { AuditPage } from './pages/AuditPage'; -import { LoginPage } from './pages/LoginPage'; +import { GuestHomePage } from './pages/GuestHomePage'; import { MembersPage } from './pages/MembersPage'; import { SegmentsPage } from './pages/SegmentsPage'; import { ToolDetailPage } from './pages/ToolDetailPage'; @@ -24,7 +24,9 @@ export function App() { loading ? (
Loading…
) : !user ? ( - + // Guests land on the public home page whatever path they asked for; + // its sign-in carries that path so the deep link survives login. + ) : ( diff --git a/apps/dashboard/src/auth/AuthContext.tsx b/apps/dashboard/src/auth/AuthContext.tsx index b87ec1d..3b5137b 100644 --- a/apps/dashboard/src/auth/AuthContext.tsx +++ b/apps/dashboard/src/auth/AuthContext.tsx @@ -2,12 +2,14 @@ import type { User } from 'oidc-client-ts'; import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { signupRedirect, userManager } from './oidc'; +import { safeReturnTo } from './return-to'; interface AuthState { user: User | null; loading: boolean; - login: () => Promise; - signup: () => Promise; + /** `returnTo` is the in-app path to land on after the Keycloak round trip. */ + login: (returnTo?: string) => Promise; + signup: (returnTo?: string) => Promise; logout: () => Promise; } @@ -40,8 +42,9 @@ export function AuthProvider({ children }: { children: ReactNode }) { value={{ user, loading, - login: () => userManager.signinRedirect(), - signup: signupRedirect, + login: (returnTo) => + userManager.signinRedirect({ state: { returnTo: safeReturnTo(returnTo) } }), + signup: (returnTo) => signupRedirect(safeReturnTo(returnTo)), logout: () => userManager.signoutRedirect(), }} > diff --git a/apps/dashboard/src/auth/CallbackPage.tsx b/apps/dashboard/src/auth/CallbackPage.tsx index 6396e7f..d9898c0 100644 --- a/apps/dashboard/src/auth/CallbackPage.tsx +++ b/apps/dashboard/src/auth/CallbackPage.tsx @@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { userManager } from './oidc'; +import { returnToFromState } from './return-to'; export function CallbackPage() { const navigate = useNavigate(); @@ -14,7 +15,7 @@ export function CallbackPage() { ran.current = true; userManager .signinRedirectCallback() - .then(() => navigate('/', { replace: true })) + .then((loaded) => navigate(returnToFromState(loaded.state), { replace: true })) .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err))); }, [navigate]); diff --git a/apps/dashboard/src/auth/oidc.ts b/apps/dashboard/src/auth/oidc.ts index e27eafe..797f3e9 100644 --- a/apps/dashboard/src/auth/oidc.ts +++ b/apps/dashboard/src/auth/oidc.ts @@ -1,6 +1,6 @@ /** * Keycloak OIDC wiring: `toggleflow-dashboard` public client (PKCE) on the - * shared Velobits-Dev realm. + * shared Velobits realm. * * Signup: Keycloak ignores prompt=create, so a second UserManager overrides * the authorization endpoint with /registrations (the fixmytext-proven @@ -10,7 +10,7 @@ import { UserManager, WebStorageStateStore, type UserManagerSettings } from 'oidc-client-ts'; const KEYCLOAK_URL = import.meta.env.VITE_KEYCLOAK_URL ?? 'http://localhost:8080'; -const REALM = import.meta.env.VITE_KEYCLOAK_REALM ?? 'Velobits-Dev'; +const REALM = import.meta.env.VITE_KEYCLOAK_REALM ?? 'Velobits'; const CLIENT_ID = import.meta.env.VITE_KEYCLOAK_CLIENT_ID ?? 'toggleflow-dashboard'; const authority = `${KEYCLOAK_URL}/realms/${REALM}`; @@ -42,4 +42,5 @@ const signupUserManager = new UserManager({ }); /** Keycloak registration page with a full code-flow round trip back to the app. */ -export const signupRedirect = (): Promise => signupUserManager.signinRedirect(); +export const signupRedirect = (returnTo?: string): Promise => + signupUserManager.signinRedirect({ state: { returnTo } }); diff --git a/apps/dashboard/src/auth/return-to.ts b/apps/dashboard/src/auth/return-to.ts new file mode 100644 index 0000000..fbbe06b --- /dev/null +++ b/apps/dashboard/src/auth/return-to.ts @@ -0,0 +1,22 @@ +/** + * Where to land after a Keycloak round trip. The guest home sends the path the + * visitor was trying to reach through the OIDC `state`, so a deep link survives + * signing in. Anything that isn't an in-app path falls back to `/`. + */ +export function safeReturnTo(value: unknown): string { + if (typeof value !== 'string' || !value.startsWith('/')) return '/'; + // `//host` and `/\host` are protocol-relative — they leave the app. + if (/^\/[/\\]/.test(value)) return '/'; + // Returning to the callback would re-run a spent auth code. + if (value.startsWith('/auth/')) return '/'; + return value; +} + +/** Read the return path out of the `state` oidc-client-ts hands back on callback. */ +export function returnToFromState(state: unknown): string { + const raw = + typeof state === 'object' && state !== null + ? (state as { returnTo?: unknown }).returnTo + : state; + return safeReturnTo(raw); +} diff --git a/apps/dashboard/src/components/GuestNav.tsx b/apps/dashboard/src/components/GuestNav.tsx new file mode 100644 index 0000000..8d99e05 --- /dev/null +++ b/apps/dashboard/src/components/GuestNav.tsx @@ -0,0 +1,245 @@ +import { useEffect, useRef, useState } from 'react'; + +import { useAuth } from '../auth/AuthContext'; +import { cn } from '../ui/cn'; +import { MenuIcon, XIcon } from '../ui/icons'; +import { ThemeToggle } from '../ui/theme-toggle'; + +/** + * Floating "island" nav for the public landing page — a fixed, centred bar that + * gains weight past 40px of scroll but never changes size, so nothing under it + * shifts. Below `sm` the section links collapse into a disclosure panel, while + * Sign in stays in the island at every width: there is no /login screen, so this + * is the app's only entry point (see GuestHomePage). + * + * Geometry mirrors velobits-website's Navbar so the VeloBits properties share a + * visual language; the palette is ToggleFlow's own tokens (that site is + * dark-only lime, this must work in light and dark on the product accent). + */ + +const NAV_LINKS: { href: string; label: string }[] = [ + { href: '#features', label: 'Features' }, + { href: '#how', label: 'How it works' }, + { href: '#why', label: 'Why ToggleFlow' }, +]; + +/** + * At rest. In light mode --panel (#fff) ≈ --bg (#f8f8f8), so the fill reads as + * almost nothing on purpose: the hairline border and an ambient shadow do the + * separating. Dark mode's --panel is lighter than its --bg, so translucency is + * genuinely visible there and the border can step back. + */ +const SURFACE_TOP = + 'border-border/80 bg-panel/80 shadow-[0_1px_2px_rgba(0,0,0,0.03),0_6px_20px_rgba(0,0,0,0.05)] dark:border-border/60 dark:bg-panel/55 dark:shadow-[0_1px_2px_rgba(0,0,0,0.25),0_6px_20px_rgba(0,0,0,0.28)]'; + +/** Scrolled: content is passing underneath, so the pill goes near-opaque and lifts. */ +const SURFACE_SCROLLED = + 'border-border bg-panel/95 shadow-[0_1px_2px_rgba(0,0,0,0.05),0_10px_30px_rgba(0,0,0,0.10)] dark:border-border-strong dark:bg-panel/85 dark:shadow-[0_1px_2px_rgba(0,0,0,0.40),0_12px_34px_rgba(0,0,0,0.45)]'; + +const FOCUS = 'focus-visible:ring-accent focus-visible:ring-2 focus-visible:outline-none'; + +/** Section anchor as a pill hover-chip. Muted, so the accent stays with the CTA. */ +const LINK = `text-muted hover:bg-highlight hover:text-text rounded-pill px-[0.85rem] py-[0.42rem] text-[13px] font-medium whitespace-nowrap transition-colors duration-150 motion-reduce:transition-none ${FOCUS}`; + +/** Quiet button — chip treatment, with the legacy `button` box explicitly undone. */ +const QUIET = `text-muted hover:bg-highlight hover:text-text shrink-0 rounded-pill border-0 bg-transparent px-3 py-1.5 text-[13px] font-medium whitespace-nowrap transition-colors duration-150 motion-reduce:transition-none ${FOCUS}`; + +/** The one accent action. Ring offset keeps the focus ring visible on accent fill. */ +const CTA = `border-accent bg-accent hover:border-accent-hover hover:bg-accent-hover focus-visible:ring-offset-panel shrink-0 rounded-pill border px-4 py-1.5 text-[13px] font-semibold whitespace-nowrap text-white transition-colors duration-150 focus-visible:ring-offset-2 motion-reduce:transition-none ${FOCUS}`; + +export function GuestNav({ returnTo }: { returnTo: string }) { + const { login, signup } = useAuth(); + const [scrolled, setScrolled] = useState(false); + const [menuOpen, setMenuOpen] = useState(false); + const [activeHash, setActiveHash] = useState(() => window.location.hash); + const menuRef = useRef(null); + const toggleRef = useRef(null); + + useEffect(() => { + const onScroll = () => setScrolled(window.scrollY > 40); + onScroll(); // browsers restore scroll position on reload + window.addEventListener('scroll', onScroll, { passive: true }); + return () => window.removeEventListener('scroll', onScroll); + }, []); + + // aria-current follows the fragment so back/forward and deep links stay right; + // the click handlers below also set it, since hashchange fires asynchronously. + useEffect(() => { + const onHashChange = () => setActiveHash(window.location.hash); + window.addEventListener('hashchange', onHashChange); + return () => window.removeEventListener('hashchange', onHashChange); + }, []); + + useEffect(() => { + if (!menuOpen) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== 'Escape') return; + setMenuOpen(false); + toggleRef.current?.focus(); + }; + const onMouseDown = (event: MouseEvent) => { + const target = event.target as Node; + if (menuRef.current?.contains(target) || toggleRef.current?.contains(target)) return; + setMenuOpen(false); + }; + document.addEventListener('keydown', onKeyDown); + document.addEventListener('mousedown', onMouseDown); + return () => { + document.removeEventListener('keydown', onKeyDown); + document.removeEventListener('mousedown', onMouseDown); + }; + }, [menuOpen]); + + const linkProps = (href: string) => ({ + href, + 'aria-current': activeHash === href ? ('location' as const) : undefined, + onClick: () => setActiveHash(href), + }); + + return ( + <> +
+ + + {menuOpen && ( + // `top-full` lands the panel exactly the header's pb-4 below the island + // at any nav height — no magic offset to retune. +
+ + + + +
+ )} +
+ + {menuOpen && ( +
setMenuOpen(false)} + /> + )} + + ); +} diff --git a/apps/dashboard/src/components/Layout.tsx b/apps/dashboard/src/components/Layout.tsx index 7bdd642..7aecfde 100644 --- a/apps/dashboard/src/components/Layout.tsx +++ b/apps/dashboard/src/components/Layout.tsx @@ -3,25 +3,10 @@ import { NavLink } from 'react-router-dom'; import { useAuth } from '../auth/AuthContext'; import { useWorkspace } from '../state/WorkspaceContext'; -import { isDark, toggleTheme } from '../ui/theme'; +import { ThemeToggle } from '../ui/theme-toggle'; import { useToast } from '../ui/toast'; import { ErrorNote, Modal } from './ui'; -function ThemeToggle() { - const [dark, setDark] = useState(isDark); - return ( - - ); -} - function Switchers() { const ws = useWorkspace(); const toast = useToast(); diff --git a/apps/dashboard/src/main.tsx b/apps/dashboard/src/main.tsx index df6f805..435ab94 100644 --- a/apps/dashboard/src/main.tsx +++ b/apps/dashboard/src/main.tsx @@ -6,7 +6,6 @@ import { BrowserRouter } from 'react-router-dom'; import { App } from './App'; import { AuthProvider } from './auth/AuthContext'; import './theme.css'; -import './styles.css'; import { ToastProvider } from './ui/toast'; import { initTheme } from './ui/theme'; diff --git a/apps/dashboard/src/pages/GuestHomePage.tsx b/apps/dashboard/src/pages/GuestHomePage.tsx new file mode 100644 index 0000000..276de9d --- /dev/null +++ b/apps/dashboard/src/pages/GuestHomePage.tsx @@ -0,0 +1,303 @@ +import type { ReactNode } from 'react'; +import { useLocation } from 'react-router-dom'; + +import { useAuth } from '../auth/AuthContext'; +import { GuestNav } from '../components/GuestNav'; + +/** + * Public landing page — the default screen for anyone who isn't signed in. + * Sign-in lives in the topbar (right side) rather than on a dedicated login + * screen; both auth entry points carry the path the visitor asked for so a deep + * link survives the Keycloak round trip. + */ + +const FEATURES: { title: string; body: string; glyph: string }[] = [ + { + glyph: '⏻', + title: 'Kill switch', + body: 'Turn any tool off in production instantly — no redeploy. Define the fallback users see: hide it, show a notice, or run an alternate path.', + }, + { + glyph: '◐', + title: 'Gradual rollouts', + body: 'Ship to 5%, then 25%, then everyone. Bucketing is deterministic per user, so nobody flickers between versions.', + }, + { + glyph: '◱', + title: 'Targeting & segments', + body: 'Reusable segments by plan, region, or any trait you send. The same rule model everywhere — no invented jargon.', + }, + { + glyph: '⚙', + title: 'Remote config & prompts', + body: 'Limits, endpoints, model params, and prompts edited live. Every change is versioned with a diff and one-click rollback.', + }, + { + glyph: '⚡', + title: 'Edge delivery', + body: 'Reads are served from the edge and keep serving the last published ruleset even if the control plane is down.', + }, + { + glyph: '≡', + title: 'Audit trail', + body: 'Who flipped what, when, and why — per flag and org-wide, with scoped per-environment API keys and roles.', + }, +]; + +const STEPS: { step: string; title: string; body: string }[] = [ + { + step: '1', + title: 'Register your tools', + body: 'Create a project and get dev, staging, and production environments with their own keys.', + }, + { + step: '2', + title: 'Guard them in code', + body: 'The backend SDK evaluates locally from an in-memory ruleset, so a flag check costs ~0ms and survives outages.', + }, + { + step: '3', + title: 'Control from the dashboard', + body: 'Flip a switch or edit config; connected SDKs pick the change up within seconds.', + }, +]; + +// Real `@toggleflow/sdk` API (server client) — keep in step with packages/sdk-js. +const SNIPPET = `import { createServerClient } from '@toggleflow/sdk'; + +const flags = createServerClient({ + edgeUrl: 'https://edge.toggleflow.dev', + environmentId: process.env.TF_ENV_ID, + serverKey: process.env.TF_SERVER_KEY, +}); + +app.post('/summarize', (req, res) => { + const flag = 'tool.summarize'; + if (!flags.isEnabled(flag, req.user)) { + return res.status(503).json(flags.getFallback(flag)); + } + const { model } = flags.getConfig(flag) ?? {}; + // …run the tool +});`; + +function MockRow({ + flagKey, + name, + state, +}: { + flagKey: string; + name: string; + state: 'on' | 'off' | 'rollout'; +}) { + const chip = + state === 'on' ? ( + ON + ) : state === 'off' ? ( + OFF + ) : ( + 25% + ); + const glyph = state === 'on' ? '●' : state === 'off' ? '○' : '◐'; + const tone = state === 'on' ? 'text-on' : state === 'off' ? 'text-off' : 'text-rollout'; + return ( +
+ + {glyph} + + + {flagKey} + {name} + + {chip} +
+ ); +} + +function Section({ + id, + eyebrow, + title, + children, +}: { + id: string; + eyebrow: string; + title: string; + children: ReactNode; +}) { + return ( +
+
+

+ {eyebrow} +

+

{title}

+ {children} +
+
+ ); +} + +export function GuestHomePage() { + const { login, signup } = useAuth(); + const location = useLocation(); + // A visitor who landed on /tools/abc gets sent back there after signing in. + const returnTo = `${location.pathname}${location.search}`; + + return ( +
+ + Skip to content + + + + {/* The nav is fixed, so the hero owns the clearance under it. */} +
+
+
+
+

+ VeloBits Control Plane +

+

+ A remote control plane for every tool in your app +

+

+ Kill switches, gradual rollouts, targeting, and live configuration — changed from a + dashboard and delivered in seconds. No redeploy, no waiting on a release. +

+
+ + +
+

+ Free tier · Set up in about 15 minutes · Flat, predictable pricing +

+
+ +
+
+ + ● + + fixmytext · production + + ruleset v418 +
+ + + + +
+ 254 flags · 246 on · 5 off · 3 rolling out +
+
+
+
+ +
+
    + {FEATURES.map((feature) => ( +
  • + + {feature.glyph} + +

    {feature.title}

    +

    {feature.body}

    +
  • + ))} +
+
+ +
+
+
    + {STEPS.map((item) => ( +
  1. + + {item.step} + + +

    {item.title}

    +

    {item.body}

    +
    +
  2. + ))} +
+
+              {SNIPPET}
+            
+
+
+ +
+
+
+

Flags that know what they control

+

+ A flag can carry its tool's route, owner, and model parameters — not just a + bare boolean. +

+
+
+

Config and prompts, versioned

+

+ Prompts and model params are configuration: edit, diff, and roll back without a + deploy. +

+
+
+

The read path is the promise

+

+ Evaluation runs at the edge or in your process, so your app keeps working even when + ours doesn't. +

+
+
+
+ +
+

Take back control of production

+

+ Create an organization, add your first application, and flip a real flag in minutes. +

+
+ + +
+
+
+ +
+
+ ToggleFlow — a VeloBits product + + +
+
+
+ ); +} diff --git a/apps/dashboard/src/pages/LoginPage.tsx b/apps/dashboard/src/pages/LoginPage.tsx deleted file mode 100644 index 4e33df3..0000000 --- a/apps/dashboard/src/pages/LoginPage.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { useAuth } from '../auth/AuthContext'; - -export function LoginPage() { - const { login, signup } = useAuth(); - return ( -
-
-

ToggleFlow

-

- Kill switches, gradual rollouts, and live configuration for every tool in your app. -

-
- - -
-
-
- ); -} diff --git a/apps/dashboard/src/styles.css b/apps/dashboard/src/styles.css index 3857b66..6592261 100644 --- a/apps/dashboard/src/styles.css +++ b/apps/dashboard/src/styles.css @@ -363,20 +363,3 @@ tr.clickable { height: 100vh; gap: 12px; } -.login-card { - background: var(--panel); - border: 1px solid var(--border); - border-radius: 12px; - padding: 40px; - text-align: center; - width: 360px; -} -.login-card h1 { - color: var(--accent); -} -.login-card .actions { - display: flex; - flex-direction: column; - gap: 8px; - margin-top: 20px; -} diff --git a/apps/dashboard/src/theme.css b/apps/dashboard/src/theme.css index af2323a..a0b77dd 100644 --- a/apps/dashboard/src/theme.css +++ b/apps/dashboard/src/theme.css @@ -1,5 +1,14 @@ @import 'tailwindcss'; +/* + * The hand-written component CSS goes into Tailwind's `components` layer, so + * utilities (a later layer) override it without `!important` while it still + * beats Preflight. Unlayered, `button { border-radius; padding }` and + * `a { color }` would win over every utility. Imported here rather than in + * main.tsx — a second unlayered import would defeat this. + */ +@import './styles.css' layer(components); + /* * VeloBits theme bridge — VSCode Dark+/Light inspired, same palette as * fixmytext's design system (frontend/packages/design-system/theme.css + diff --git a/apps/dashboard/src/ui/icons.tsx b/apps/dashboard/src/ui/icons.tsx new file mode 100644 index 0000000..8f01a0f --- /dev/null +++ b/apps/dashboard/src/ui/icons.tsx @@ -0,0 +1,71 @@ +import type { ReactNode, SVGProps } from 'react'; + +export interface IconProps extends SVGProps { + /** Width and height in px — icons are square. */ + size?: number | string; +} + +/** + * Stroke-based icon set (Feather/Lucide-style, 24×24 grid, currentColor) — the + * same convention as fixmytext's `@velobits/design-system` icons, copied rather + * than imported because that package is private and in a different workspace. + * Icons are decorative by default (aria-hidden); pass `aria-hidden={undefined}` + * plus an `aria-label` for semantic use. + */ +function createIcon(displayName: string, children: ReactNode) { + function Icon({ size = 16, ...props }: IconProps) { + return ( + + ); + } + Icon.displayName = displayName; + return Icon; +} + +export const MenuIcon = createIcon( + 'MenuIcon', + <> + + + + , +); + +export const MoonIcon = createIcon('MoonIcon', ); + +export const SunIcon = createIcon( + 'SunIcon', + <> + + + + + + + + + + , +); + +export const XIcon = createIcon( + 'XIcon', + <> + + + , +); diff --git a/apps/dashboard/src/ui/theme-toggle.tsx b/apps/dashboard/src/ui/theme-toggle.tsx new file mode 100644 index 0000000..a1818a2 --- /dev/null +++ b/apps/dashboard/src/ui/theme-toggle.tsx @@ -0,0 +1,21 @@ +import { useState } from 'react'; + +import { cn } from './cn'; +import { MoonIcon, SunIcon } from './icons'; +import { isDark, toggleTheme } from './theme'; + +/** Light/dark switch — shared by the app shell topbar and the public guest home. */ +export function ThemeToggle({ className }: { className?: string }) { + const [dark, setDark] = useState(isDark); + return ( + + ); +} diff --git a/apps/dashboard/test/api-client.test.ts b/apps/dashboard/test/api-client.test.ts new file mode 100644 index 0000000..73e23af --- /dev/null +++ b/apps/dashboard/test/api-client.test.ts @@ -0,0 +1,112 @@ +// @vitest-environment happy-dom +/** + * The fetch wrapper every page goes through: auth header, /api prefix, JSON + * body handling, and the ApiError mapping that ErrorNote renders. + */ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { ApiError, api } from '../src/api/client'; +import { stubAuth, stubFetch } from './harness'; + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +const fetchMock = () => vi.mocked(globalThis.fetch); + +describe('request wiring', () => { + it('prefixes /api and attaches the bearer token', async () => { + stubAuth(); + stubFetch({ 'GET /v1/me': { user: { id: 'u1' } } }); + + await api.get('/v1/me'); + + const [url, init] = fetchMock().mock.calls[0]!; + expect(url).toBe('/api/v1/me'); + expect((init!.headers as Record).authorization).toBe('Bearer test-token'); + }); + + it('sends an empty bearer token when logged out', async () => { + stubAuth({ user: null }); + stubFetch({ 'GET /v1/me': {} }); + + await api.get('/v1/me'); + + const [, init] = fetchMock().mock.calls[0]!; + expect((init!.headers as Record).authorization).toBe('Bearer '); + }); + + it('serialises a body and sets content-type only when one is present', async () => { + stubAuth(); + stubFetch({ 'POST /v1/things': { id: 'x' }, 'DELETE /v1/things/x': { status: 204 } }); + + await api.post('/v1/things', { name: 'thing' }); + const [, postInit] = fetchMock().mock.calls[0]!; + expect(postInit!.body).toBe('{"name":"thing"}'); + expect((postInit!.headers as Record)['content-type']).toBe('application/json'); + + await api.delete('/v1/things/x'); + const [, delInit] = fetchMock().mock.calls[1]!; + expect(delInit!.body).toBeUndefined(); + expect((delInit!.headers as Record)['content-type']).toBeUndefined(); + }); + + it('exposes every verb the pages use', async () => { + stubAuth(); + stubFetch({ + 'GET /v1/x': { v: 'get' }, + 'POST /v1/x': { v: 'post' }, + 'PUT /v1/x': { v: 'put' }, + 'PATCH /v1/x': { v: 'patch' }, + 'DELETE /v1/x': { v: 'delete' }, + }); + + expect(await api.get('/v1/x')).toEqual({ v: 'get' }); + expect(await api.post('/v1/x', {})).toEqual({ v: 'post' }); + expect(await api.put('/v1/x', {})).toEqual({ v: 'put' }); + expect(await api.patch('/v1/x', {})).toEqual({ v: 'patch' }); + expect(await api.delete('/v1/x')).toEqual({ v: 'delete' }); + }); +}); + +describe('response handling', () => { + it('returns undefined for 204 without parsing a body', async () => { + stubAuth(); + stubFetch({ 'DELETE /v1/segments/s1': { status: 204 } }); + expect(await api.delete('/v1/segments/s1')).toBeUndefined(); + }); + + it('maps an error payload onto ApiError status/code/message', async () => { + stubAuth(); + stubFetch({ + 'POST /v1/things': { status: 403, body: { error: 'forbidden', message: 'role too low' } }, + }); + + const err = await api.post('/v1/things', {}).catch((e: unknown) => e); + expect(err).toBeInstanceOf(ApiError); + expect(err).toMatchObject({ status: 403, code: 'forbidden', message: 'role too low' }); + }); + + it('falls back to request_failed and the status when the body has no detail', async () => { + stubAuth(); + stubFetch({ 'GET /v1/x': { status: 500, body: {} } }); + + const err = (await api.get('/v1/x').catch((e: unknown) => e)) as ApiError; + expect(err.code).toBe('request_failed'); + expect(err.message).toBe('HTTP 500'); + }); + + it('survives an error response that is not JSON at all', async () => { + stubAuth(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('gateway timeout', { status: 504 })), + ); + + const err = (await api.get('/v1/x').catch((e: unknown) => e)) as ApiError; + expect(err).toBeInstanceOf(ApiError); + expect(err.status).toBe(504); + expect(err.message).toBe('HTTP 504'); + }); +}); diff --git a/apps/dashboard/test/api-keys-page.test.tsx b/apps/dashboard/test/api-keys-page.test.tsx new file mode 100644 index 0000000..e474846 --- /dev/null +++ b/apps/dashboard/test/api-keys-page.test.tsx @@ -0,0 +1,236 @@ +// @vitest-environment happy-dom +/** + * API keys: admin-only gate, issue-and-reveal-once flow, revocation, and the + * fact that a revoked key stays listed but loses its Revoke control. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ApiKey } from '../src/api/client'; +import { ApiKeysPage } from '../src/pages/ApiKeysPage'; +import { + ENV_ID, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const KEYS_URL = `/v1/environments/${ENV_ID}/keys`; + +const key = (over: Partial = {}): ApiKey => ({ + id: 'k1', + environmentId: ENV_ID, + kind: 'server', + name: 'production backend', + prefix: 'tf_srv_abc', + createdAt: '2026-07-20T10:00:00.000Z', + revokedAt: null, + ...over, +}); + +const pageHandlers = ( + role: 'admin' | 'developer' | 'viewer' = 'admin', + over: Handlers = {}, +): Handlers => ({ + ...workspaceHandlers(role), + [`GET ${KEYS_URL}`]: [key()], + ...over, +}); + +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders(); + return { stub }; +} + +const loaded = () => waitFor(() => expect(screen.getByText('production backend')).toBeTruthy()); + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('access', () => { + it.each(['developer', 'viewer'] as const)('refuses the page to a %s', async (role) => { + const { stub } = renderPage(pageHandlers(role)); + await waitFor(() => + expect(screen.getByText('API keys are managed by org admins.')).toBeTruthy(), + ); + // The query is disabled for non-admins, so no key ever reaches the browser. + expect(stub.calls.some((c) => c.key.includes('/keys'))).toBe(false); + }); + + it('shows the environment scope to an admin', async () => { + renderPage(); + await loaded(); + expect(screen.getByText('scoped to Development')).toBeTruthy(); + }); +}); + +describe('listing', () => { + it('renders kind, truncated prefix, and active status', async () => { + renderPage(); + await loaded(); + expect(screen.getByText('server')).toBeTruthy(); + expect(screen.getByText('tf_srv_abc…')).toBeTruthy(); + expect(screen.getByText('active')).toBeTruthy(); + }); + + it('marks a revoked key and drops its Revoke button', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${KEYS_URL}`]: [key({ revokedAt: '2026-07-21T10:00:00.000Z' })], + }), + ); + await loaded(); + expect(screen.getByText('revoked')).toBeTruthy(); + expect(screen.queryByText('Revoke')).toBeNull(); + }); + + it('shows an empty state', async () => { + renderPage(pageHandlers('admin', { [`GET ${KEYS_URL}`]: [] })); + await waitFor(() => expect(screen.getByText('No keys for this environment yet.')).toBeTruthy()); + }); + + it('surfaces a load failure', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${KEYS_URL}`]: { status: 500, body: { error: 'server_error', message: 'kaput' } }, + }), + ); + await waitFor(() => expect(screen.getByText('kaput')).toBeTruthy()); + }); +}); + +describe('creation', () => { + it('issues a key and reveals the token exactly once', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`POST ${KEYS_URL}`]: key({ id: 'k2', token: 'tf_srv_full-secret-value' }), + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ Create key')); + const submit = screen.getByText('Create'); + expect(submit).toHaveProperty('disabled', true); + + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'ci runner' } }); + fireEvent.change(screen.getByLabelText('Kind'), { target: { value: 'client' } }); + expect(submit).toHaveProperty('disabled', false); + fireEvent.click(submit); + + await waitFor(() => expect(screen.getByText('Copy your key now')).toBeTruthy()); + expect(screen.getByText('tf_srv_full-secret-value')).toBeTruthy(); + expect(stub.calls.find((c) => c.key === `POST ${KEYS_URL}`)?.body).toEqual({ + name: 'ci runner', + kind: 'client', + }); + // The creation modal gives way to the reveal modal. + expect(screen.queryByText('Create API key')).toBeNull(); + }); + + it('copies the revealed token to the clipboard', async () => { + const writeText = vi.fn(async () => {}); + vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText } }); + + renderPage( + pageHandlers('admin', { [`POST ${KEYS_URL}`]: key({ id: 'k2', token: 'tf_cli_secret' }) }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ Create key')); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'browser' } }); + fireEvent.click(screen.getByText('Create')); + + await waitFor(() => expect(screen.getByText('Copy your key now')).toBeTruthy()); + fireEvent.click(screen.getByText('Copy')); + expect(writeText).toHaveBeenCalledWith('tf_cli_secret'); + }); + + it('dismisses the reveal modal for good', async () => { + renderPage( + pageHandlers('admin', { [`POST ${KEYS_URL}`]: key({ id: 'k2', token: 'tf_srv_x' }) }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ Create key')); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'temp' } }); + fireEvent.click(screen.getByText('Create')); + + await waitFor(() => expect(screen.getByText('Copy your key now')).toBeTruthy()); + fireEvent.click(screen.getByText('Done')); + expect(screen.queryByText('Copy your key now')).toBeNull(); + expect(screen.queryByText('tf_srv_x')).toBeNull(); + }); + + it('surfaces a rejected creation and keeps the form open', async () => { + renderPage( + pageHandlers('admin', { + [`POST ${KEYS_URL}`]: { + status: 402, + body: { error: 'quota', message: 'key limit reached' }, + }, + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ Create key')); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'one too many' } }); + fireEvent.click(screen.getByText('Create')); + + await waitFor(() => expect(screen.getByText('key limit reached')).toBeTruthy()); + expect(screen.getByText('Create API key')).toBeTruthy(); + }); + + it('closes on cancel without issuing anything', async () => { + const { stub } = renderPage(); + await loaded(); + + fireEvent.click(screen.getByText('+ Create key')); + fireEvent.click(screen.getByText('Cancel')); + expect(screen.queryByText('Create API key')).toBeNull(); + expect(stub.calls.some((c) => c.key.startsWith('POST'))).toBe(false); + }); +}); + +describe('revocation', () => { + it('revokes after a confirm', async () => { + const { stub } = renderPage( + pageHandlers('admin', { 'DELETE /v1/api-keys/k1': { ...key(), revokedAt: 'now' } }), + ); + await loaded(); + + fireEvent.click(screen.getByText('Revoke')); + expect(stub.calls.some((c) => c.key.startsWith('DELETE'))).toBe(false); + + fireEvent.click(screen.getByText('Revoke permanently?')); + await waitFor(() => + expect(stub.calls.some((c) => c.key === 'DELETE /v1/api-keys/k1')).toBe(true), + ); + }); + + it('surfaces a failed revocation', async () => { + renderPage( + pageHandlers('admin', { + 'DELETE /v1/api-keys/k1': { + status: 500, + body: { error: 'server_error', message: 'could not revoke' }, + }, + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('Revoke')); + fireEvent.click(screen.getByText('Revoke permanently?')); + await waitFor(() => expect(screen.getByText('could not revoke')).toBeTruthy()); + }); +}); diff --git a/apps/dashboard/test/audit-page.test.tsx b/apps/dashboard/test/audit-page.test.tsx new file mode 100644 index 0000000..ad1274d --- /dev/null +++ b/apps/dashboard/test/audit-page.test.tsx @@ -0,0 +1,180 @@ +// @vitest-environment happy-dom +/** + * Audit log: actor resolution against the member list, the before/after detail + * cell, and cursor pagination — which only offers "Load older" on a full page. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { AuditEntry, Member } from '../src/api/client'; +import { AuditPage } from '../src/pages/AuditPage'; +import { + ORG_ID, + dynamic, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const AUDIT_URL = `/v1/orgs/${ORG_ID}/audit`; +const MEMBERS_URL = `/v1/orgs/${ORG_ID}/members`; + +const entry = (over: Partial = {}): AuditEntry => ({ + id: 'a1', + actorId: 'u1', + action: 'flag.update', + entityType: 'flag_state', + entityId: 'f1', + before: { enabled: true }, + after: { enabled: false }, + createdAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const members: Member[] = [ + { + userId: 'u1', + email: 'dev@velobits.test', + displayName: 'Dev User', + role: 'admin', + createdAt: '2026-07-01T00:00:00.000Z', + }, + { + userId: 'u2', + email: 'ops@velobits.test', + displayName: null, + role: 'developer', + createdAt: '2026-07-01T00:00:00.000Z', + }, +]; + +/** A full page is exactly the request limit, which is what unlocks pagination. */ +const fullPage = (prefix: string) => + Array.from({ length: 50 }, (_, i) => + entry({ + id: `${prefix}-${i}`, + action: `action.${prefix}.${i}`, + createdAt: `2026-07-${String(20 - (i % 19)).padStart(2, '0')}T10:00:00.000Z`, + }), + ); + +const pageHandlers = (over: Handlers = {}): Handlers => ({ + ...workspaceHandlers(), + [`GET ${AUDIT_URL}`]: { entries: [entry()] }, + [`GET ${MEMBERS_URL}`]: members, + ...over, +}); + +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders(); + return { stub }; +} + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('listing', () => { + it('renders the action and the before/after detail', async () => { + renderPage(); + await waitFor(() => expect(screen.getByText('flag.update')).toBeTruthy()); + expect( + screen.getByText(JSON.stringify({ before: { enabled: true }, after: { enabled: false } })), + ).toBeTruthy(); + }); + + it('falls back to the entity type when there is no before or after', async () => { + renderPage( + pageHandlers({ + [`GET ${AUDIT_URL}`]: { entries: [entry({ before: null, after: null })] }, + }), + ); + await waitFor(() => expect(screen.getByText('flag_state')).toBeTruthy()); + }); + + it('shows an empty state', async () => { + renderPage(pageHandlers({ [`GET ${AUDIT_URL}`]: { entries: [] } })); + await waitFor(() => expect(screen.getByText('Nothing yet.')).toBeTruthy()); + }); + + it('surfaces a load failure', async () => { + renderPage( + pageHandlers({ + [`GET ${AUDIT_URL}`]: { status: 403, body: { error: 'forbidden', message: 'no audit' } }, + }), + ); + await waitFor(() => expect(screen.getByText('no audit')).toBeTruthy()); + }); +}); + +describe('actor resolution', () => { + it('prefers the display name', async () => { + renderPage(); + await waitFor(() => expect(screen.getByText('Dev User')).toBeTruthy()); + }); + + it('falls back to the email when there is no display name', async () => { + renderPage(pageHandlers({ [`GET ${AUDIT_URL}`]: { entries: [entry({ actorId: 'u2' })] } })); + await waitFor(() => expect(screen.getByText('ops@velobits.test')).toBeTruthy()); + }); + + it('shows a truncated id for an actor who is no longer a member', async () => { + renderPage( + pageHandlers({ + [`GET ${AUDIT_URL}`]: { entries: [entry({ actorId: 'deadbeef-gone-forever' })] }, + }), + ); + await waitFor(() => expect(screen.getByText('deadbeef')).toBeTruthy()); + }); + + it('attributes a null actor to the system', async () => { + renderPage(pageHandlers({ [`GET ${AUDIT_URL}`]: { entries: [entry({ actorId: null })] } })); + await waitFor(() => expect(screen.getByText('system')).toBeTruthy()); + }); +}); + +describe('pagination', () => { + it('offers no Load older on a partial page', async () => { + renderPage(); + await waitFor(() => expect(screen.getByText('flag.update')).toBeTruthy()); + expect(screen.queryByText('Load older')).toBeNull(); + }); + + it('pages with a before cursor and keeps earlier pages on screen', async () => { + const first = fullPage('first'); + const oldest = first.at(-1)!; + const { stub } = renderPage( + pageHandlers({ + [`GET ${AUDIT_URL}`]: dynamic(({ url }) => + url.includes('before=') + ? { entries: [entry({ id: 'older-1', action: 'older.action' })] } + : { entries: first }, + ), + [`GET ${MEMBERS_URL}`]: members, + }), + ); + + await waitFor(() => expect(screen.getByText('Load older')).toBeTruthy()); + fireEvent.click(screen.getByText('Load older')); + + await waitFor(() => expect(screen.getByText('older.action')).toBeTruthy()); + // The first page is retained above the newly fetched one. + expect(screen.getByText('action.first.0')).toBeTruthy(); + // The cursor is the createdAt of the last row of the previous page. + expect( + stub.calls.some((c) => c.key.includes(`before=${encodeURIComponent(oldest.createdAt)}`)), + ).toBe(true); + // A short second page ends pagination. + expect(screen.queryByText('Load older')).toBeNull(); + }); +}); diff --git a/apps/dashboard/test/auth.test.tsx b/apps/dashboard/test/auth.test.tsx new file mode 100644 index 0000000..a658f72 --- /dev/null +++ b/apps/dashboard/test/auth.test.tsx @@ -0,0 +1,185 @@ +// @vitest-environment happy-dom +/** + * AuthProvider's lifecycle (initial load, expiry, UserManager events), the + * token helper the API client depends on, and the two auth-facing screens. + */ +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import type { User } from 'oidc-client-ts'; +import { MemoryRouter } from 'react-router-dom'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { AuthProvider, getAccessToken, useAuth } from '../src/auth/AuthContext'; +import { CallbackPage } from '../src/auth/CallbackPage'; +import { userManager } from '../src/auth/oidc'; +import { stubAuth, testUser } from './harness'; + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function Probe() { + const { user, loading, login, signup, logout } = useAuth(); + return ( + <> + {loading ? 'loading' : (user?.profile.email ?? 'anonymous')} + + + + + ); +} + +const renderProbe = () => + render( + + + , + ); + +describe('AuthProvider', () => { + it('resolves a stored user and leaves loading', async () => { + stubAuth(); + renderProbe(); + expect(screen.getByTestId('state').textContent).toBe('loading'); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test')); + }); + + it('treats an expired user as logged out', async () => { + stubAuth({ user: { ...testUser, expired: true } as unknown as User }); + renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('anonymous')); + }); + + it('treats no stored user as logged out', async () => { + stubAuth({ user: null }); + renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('anonymous')); + }); + + it('adopts a user pushed by the userLoaded event (silent renew)', async () => { + stubAuth({ user: null }); + let onLoaded: ((u: User) => void) | undefined; + vi.spyOn(userManager.events, 'addUserLoaded').mockImplementation((cb) => { + onLoaded = cb as (u: User) => void; + // oidc-client-ts hands back an unsubscribe function. + return () => {}; + }); + + renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('anonymous')); + + act(() => onLoaded!(testUser)); + expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test'); + }); + + it('clears the user on the userUnloaded event (logout in another tab)', async () => { + stubAuth(); + let onUnloaded: (() => void) | undefined; + vi.spyOn(userManager.events, 'addUserUnloaded').mockImplementation((cb) => { + onUnloaded = cb as () => void; + return () => {}; + }); + + renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test')); + + act(() => onUnloaded!()); + expect(screen.getByTestId('state').textContent).toBe('anonymous'); + }); + + it('detaches both event listeners on unmount', async () => { + stubAuth(); + const removeLoaded = vi.spyOn(userManager.events, 'removeUserLoaded'); + const removeUnloaded = vi.spyOn(userManager.events, 'removeUserUnloaded'); + + const { unmount } = renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test')); + unmount(); + + expect(removeLoaded).toHaveBeenCalled(); + expect(removeUnloaded).toHaveBeenCalled(); + }); + + it('wires login, signup, and logout to the UserManager', async () => { + const auth = stubAuth(); + renderProbe(); + await waitFor(() => expect(screen.getByTestId('state').textContent).toBe('dev@velobits.test')); + + // No argument means "land back on /" once Keycloak returns. + fireEvent.click(screen.getByText('login')); + expect(auth.signinRedirect).toHaveBeenCalledWith({ state: { returnTo: '/' } }); + + // signupRedirect drives a second UserManager (Keycloak's /registrations) + // that this module never exports, so it is only observable as "did not + // throw" here. + expect(() => fireEvent.click(screen.getByText('signup'))).not.toThrow(); + + fireEvent.click(screen.getByText('logout')); + expect(auth.signoutRedirect).toHaveBeenCalled(); + }); + + it('useAuth outside a provider fails loudly', () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + expect(() => render()).toThrow('useAuth outside AuthProvider'); + }); +}); + +describe('getAccessToken', () => { + it('returns the access token when signed in', async () => { + stubAuth(); + expect(await getAccessToken()).toBe('test-token'); + }); + + it('returns an empty string when signed out, so requests still form', async () => { + stubAuth({ user: null }); + expect(await getAccessToken()).toBe(''); + }); +}); + +// The sign-in/sign-up entry points moved to GuestHomePage when the dedicated +// login screen was dropped; units.test.tsx covers them, including the returnTo +// deep link that the old LoginPage had no notion of. + +describe('CallbackPage', () => { + const renderCallback = () => + render( + + + , + ); + + it('completes the code exchange exactly once despite StrictMode double-mount', async () => { + const auth = stubAuth(); + renderCallback(); + await waitFor(() => expect(auth.signinRedirectCallback).toHaveBeenCalled()); + expect(auth.signinRedirectCallback).toHaveBeenCalledOnce(); + }); + + it('shows a progress message while exchanging', () => { + stubAuth(); + renderCallback(); + expect(screen.getByText('Signing you in…')).toBeTruthy(); + }); + + it('surfaces the failure reason when the exchange rejects', async () => { + stubAuth(); + vi.spyOn(userManager, 'signinRedirectCallback').mockRejectedValue(new Error('state not found')); + renderCallback(); + await waitFor(() => expect(screen.getByText(/state not found/)).toBeTruthy()); + expect(screen.getByText('Back')).toBeTruthy(); + }); + + it('stringifies a non-Error rejection', async () => { + stubAuth(); + vi.spyOn(userManager, 'signinRedirectCallback').mockRejectedValue('access_denied'); + renderCallback(); + await waitFor(() => expect(screen.getByText(/access_denied/)).toBeTruthy()); + }); +}); diff --git a/apps/dashboard/test/harness.tsx b/apps/dashboard/test/harness.tsx new file mode 100644 index 0000000..d105399 --- /dev/null +++ b/apps/dashboard/test/harness.tsx @@ -0,0 +1,188 @@ +/** + * Shared harness for dashboard component tests. + * + * Deliberately stubs at the `fetch` boundary rather than mocking `../src/api`, + * so src/api/client.ts (auth header, 204 handling, ApiError mapping) is + * exercised by every page test instead of being replaced by a mock. + * + * oidc.ts is imported for real rather than vi.mock'd: constructing a + * UserManager does no I/O, so spying on its methods (`stubAuth`) keeps that + * module covered AND sidesteps vi.mock's hoisting rules, which would not apply + * to a factory called from this file. + */ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, type RenderResult } from '@testing-library/react'; +import type { User } from 'oidc-client-ts'; +import type { ReactNode } from 'react'; +import { MemoryRouter } from 'react-router-dom'; +import { expect, vi, type MockInstance } from 'vitest'; + +import type { Environment, Me, Project } from '../src/api/client'; +import { userManager } from '../src/auth/oidc'; +import { WorkspaceProvider } from '../src/state/WorkspaceContext'; +import { ToastProvider } from '../src/ui/toast'; + +// ── fetch stubbing ──────────────────────────────────────────────────────────── + +export interface HandlerRequest { + body: unknown; + url: string; +} + +/** + * `"GET /v1/me"` -> a 200 body, a `{ status, body }` pair, or a function of the + * request. The value stays `unknown`: a union with a bare `unknown` member + * collapses to `unknown`, which would strip the parameter types off the + * function form. `dynamic()` supplies those instead. + */ +export type Handlers = Record; + +/** + * Wraps a request-dependent handler so its parameter is typed at the call site + * (`dynamic(({ url }) => …)`). + */ +export const dynamic = (fn: (req: HandlerRequest) => unknown) => fn; + +export interface FetchStub { + /** Every request seen, in order, as `"METHOD /path"`. */ + calls: { key: string; body: unknown }[]; + /** Replace or add handlers mid-test (e.g. after a mutation changes the list). */ + set: (handlers: Handlers) => void; +} + +const isStatusShape = (v: unknown): v is { status: number; body?: unknown } => + typeof v === 'object' && v !== null && 'status' in v; + +/** + * Installs a `fetch` that resolves the handler table. An unhandled route is a + * test bug, not a 404 — it fails loudly so a renamed endpoint cannot silently + * turn into an empty page. + */ +export function stubFetch(handlers: Handlers): FetchStub { + let table = { ...handlers }; + const calls: { key: string; body: unknown }[] = []; + + vi.stubGlobal( + 'fetch', + vi.fn(async (input: string, init?: RequestInit) => { + const path = String(input).replace(/^\/api/, ''); + const method = init?.method ?? 'GET'; + const body = init?.body ? JSON.parse(String(init.body)) : undefined; + const key = `${method} ${path}`; + calls.push({ key, body }); + + const handler = table[key] ?? table[`${method} ${path.split('?')[0]}`]; + if (handler === undefined) { + throw new Error( + `unhandled request: ${key}\nhandlers: ${Object.keys(table).join(', ') || '(none)'}`, + ); + } + + const resolved = typeof handler === 'function' ? handler({ body, url: path }) : handler; + if (isStatusShape(resolved)) { + return new Response(resolved.body === undefined ? '' : JSON.stringify(resolved.body), { + status: resolved.status, + }); + } + return new Response(JSON.stringify(resolved), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }), + ); + + return { + calls, + set: (next) => { + table = { ...table, ...next }; + }, + }; +} + +/** Assert a request was made, and return its parsed body. */ +export function requestBody(stub: FetchStub, key: string): unknown { + const call = stub.calls.find((c) => c.key === key); + expect( + call, + `no request matched ${key}; saw ${stub.calls.map((c) => c.key).join(', ')}`, + ).toBeDefined(); + return call!.body; +} + +// ── auth ────────────────────────────────────────────────────────────────────── + +/** A signed-in user, minus every field the dashboard never reads. */ +export const testUser = { + access_token: 'test-token', + expired: false, + profile: { email: 'dev@velobits.test' }, +} as unknown as User; + +export interface AuthStub { + getUser: MockInstance; + signinRedirect: MockInstance; + signoutRedirect: MockInstance; + signinRedirectCallback: MockInstance; +} + +/** + * Spies over the real UserManager. `user: null` models logged-out, which is how + * getAccessToken's empty-string branch gets reached. + */ +export function stubAuth({ user = testUser }: { user?: User | null } = {}): AuthStub { + return { + getUser: vi.spyOn(userManager, 'getUser').mockResolvedValue(user), + signinRedirect: vi.spyOn(userManager, 'signinRedirect').mockResolvedValue(undefined), + signoutRedirect: vi.spyOn(userManager, 'signoutRedirect').mockResolvedValue(undefined), + signinRedirectCallback: vi + .spyOn(userManager, 'signinRedirectCallback') + .mockResolvedValue(testUser), + }; +} + +// ── fixtures ────────────────────────────────────────────────────────────────── + +export const ORG_ID = '11111111-1111-4111-8111-111111111111'; +export const PROJECT_ID = '22222222-2222-4222-8222-222222222222'; +export const ENV_ID = '33333333-3333-4333-8333-333333333333'; + +export const me = (role: Me['orgs'][number]['role'] = 'admin'): Me => ({ + user: { id: 'u1', email: 'dev@velobits.test', displayName: 'Dev User' }, + orgs: [{ id: ORG_ID, name: 'VeloBits', role }], +}); + +export const project = (): Project => ({ id: PROJECT_ID, name: 'Control Plane' }); + +export const environments = (): Environment[] => [ + { id: ENV_ID, key: 'dev', name: 'Development' }, + { id: '44444444-4444-4444-8444-444444444444', key: 'prod', name: 'Production' }, +]; + +/** The three requests WorkspaceProvider always makes, so page tests only declare their own. */ +export const workspaceHandlers = (role: Me['orgs'][number]['role'] = 'admin'): Handlers => ({ + 'GET /v1/me': me(role), + [`GET /v1/orgs/${ORG_ID}/projects`]: [project()], + [`GET /v1/projects/${PROJECT_ID}/environments`]: environments(), +}); + +// ── rendering ───────────────────────────────────────────────────────────────── + +/** Fresh QueryClient per render; retries off so an expected error surfaces at once. */ +export function renderWithProviders( + ui: ReactNode, + { route = '/', withWorkspace = true }: { route?: string; withWorkspace?: boolean } = {}, +): RenderResult { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } }, + }); + + const inner = withWorkspace ? {ui} : ui; + + return render( + + + {inner} + + , + ); +} diff --git a/apps/dashboard/test/layout.test.tsx b/apps/dashboard/test/layout.test.tsx new file mode 100644 index 0000000..40abd1a --- /dev/null +++ b/apps/dashboard/test/layout.test.tsx @@ -0,0 +1,230 @@ +// @vitest-environment happy-dom +/** + * The app shell: org/project/environment switchers, the admin-only project + * creation path, identity display, theme toggle, and nav. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { AuthProvider } from '../src/auth/AuthContext'; +import { Layout } from '../src/components/Layout'; +import { + ORG_ID, + PROJECT_ID, + environments, + me, + project, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type Handlers, + type FetchStub, +} from './harness'; + +const SECOND_PROJECT = '88888888-8888-4888-8888-888888888888'; +const PROD_ENV = '44444444-4444-4444-8444-444444444444'; + +beforeEach(() => { + localStorage.clear(); + document.body.className = ''; +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +function renderLayout(handlers: Handlers = workspaceHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders( + + +

page body

+
+
, + ); + return { stub }; +} + +/** + * Waits for all three switchers to be populated. Gating on the Project select + * alone is not enough — the environments query resolves one tick later, and + * asserting before that reads an empty select. + */ +const ready = () => + waitFor(() => { + expect(screen.getByLabelText('Project')).toBeTruthy(); + expect((screen.getByLabelText('Environment') as HTMLSelectElement).value).not.toBe(''); + }); + +describe('shell', () => { + it('renders the brand, nav, and page children', async () => { + renderLayout(); + await ready(); + + expect(screen.getByText('ToggleFlow')).toBeTruthy(); + expect(screen.getByText('page body')).toBeTruthy(); + for (const label of ['Tools', 'Segments', 'API keys', 'Audit log', 'Members']) { + expect(screen.getByText(label)).toBeTruthy(); + } + }); + + it('shows the display name and role', async () => { + renderLayout(); + await ready(); + expect(screen.getByText(/Dev User · admin/)).toBeTruthy(); + }); + + it('falls back to the email when there is no display name', async () => { + renderLayout({ + ...workspaceHandlers(), + 'GET /v1/me': { user: { ...me().user, displayName: null }, orgs: me().orgs }, + }); + await ready(); + expect(screen.getByText(/dev@velobits\.test · admin/)).toBeTruthy(); + }); + + it('signs out through the UserManager', async () => { + stubAuth(); + const auth = stubAuth(); + stubFetch(workspaceHandlers()); + renderWithProviders( + + +

body

+
+
, + ); + await ready(); + + fireEvent.click(screen.getByText('Sign out')); + expect(auth.signoutRedirect).toHaveBeenCalled(); + }); +}); + +describe('switchers', () => { + it('lists orgs, projects, and environments', async () => { + renderLayout(); + await ready(); + + expect(screen.getByLabelText('Organization')).toHaveProperty('value', ORG_ID); + expect(screen.getByLabelText('Project')).toHaveProperty('value', PROJECT_ID); + // Environments render as "Name (key)". + expect(screen.getByText('Production (prod)')).toBeTruthy(); + }); + + it('switching environment persists the choice', async () => { + renderLayout(); + await ready(); + + fireEvent.change(screen.getByLabelText('Environment'), { target: { value: PROD_ENV } }); + expect(localStorage.getItem('tf.environment')).toBe(PROD_ENV); + }); + + it('switching project persists it and resets the environment', async () => { + localStorage.setItem('tf.environment', PROD_ENV); + renderLayout({ + ...workspaceHandlers(), + [`GET /v1/orgs/${ORG_ID}/projects`]: [project(), { id: SECOND_PROJECT, name: 'Second' }], + [`GET /v1/projects/${SECOND_PROJECT}/environments`]: environments(), + }); + await ready(); + + fireEvent.change(screen.getByLabelText('Project'), { target: { value: SECOND_PROJECT } }); + expect(localStorage.getItem('tf.project')).toBe(SECOND_PROJECT); + expect(localStorage.getItem('tf.environment')).toBeNull(); + }); +}); + +describe('project creation', () => { + it('offers a create option to admins and creates from the modal', async () => { + const created = { id: SECOND_PROJECT, name: 'Fresh' }; + const { stub } = renderLayout({ + ...workspaceHandlers(), + [`POST /v1/orgs/${ORG_ID}/projects`]: created, + [`GET /v1/projects/${SECOND_PROJECT}/environments`]: environments(), + }); + await ready(); + + fireEvent.change(screen.getByLabelText('Project'), { target: { value: '__new__' } }); + expect(screen.getByText('New project')).toBeTruthy(); + + const submit = screen.getByText('Create (with dev/staging/prod)'); + // Guarded until a name is typed. + expect(submit).toHaveProperty('disabled', true); + + fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Fresh ' } }); + expect(submit).toHaveProperty('disabled', false); + + stub.set({ [`GET /v1/orgs/${ORG_ID}/projects`]: [project(), created] }); + fireEvent.click(submit); + + await waitFor(() => expect(screen.getByText(/Project created/)).toBeTruthy()); + // Name is trimmed before it reaches the API. + const call = stub.calls.find((c) => c.key === `POST /v1/orgs/${ORG_ID}/projects`); + expect(call?.body).toEqual({ name: 'Fresh' }); + }); + + it('surfaces a creation failure in the modal and keeps it open', async () => { + renderLayout({ + ...workspaceHandlers(), + [`POST /v1/orgs/${ORG_ID}/projects`]: { + status: 403, + body: { error: 'forbidden', message: 'role too low' }, + }, + }); + await ready(); + + fireEvent.change(screen.getByLabelText('Project'), { target: { value: '__new__' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Nope' } }); + fireEvent.click(screen.getByText('Create (with dev/staging/prod)')); + + await waitFor(() => expect(screen.getByText('role too low')).toBeTruthy()); + expect(screen.getByText('New project')).toBeTruthy(); + }); + + it('closes the modal on cancel', async () => { + renderLayout(); + await ready(); + + fireEvent.change(screen.getByLabelText('Project'), { target: { value: '__new__' } }); + fireEvent.click(screen.getByText('Cancel')); + expect(screen.queryByText('New project')).toBeNull(); + }); + + it('offers a bare create button when the org has no projects', async () => { + renderLayout({ ...workspaceHandlers(), [`GET /v1/orgs/${ORG_ID}/projects`]: [] }); + await waitFor(() => expect(screen.getByText('+ New project')).toBeTruthy()); + // No project select exists to hang the "__new__" option off. + expect(screen.queryByLabelText('Project')).toBeNull(); + }); + + it('hides project creation from non-admins', async () => { + renderLayout({ ...workspaceHandlers('developer'), [`GET /v1/orgs/${ORG_ID}/projects`]: [] }); + await waitFor(() => expect(screen.getByText(/developer/)).toBeTruthy()); + expect(screen.queryByText('+ New project')).toBeNull(); + }); + + it('offers no __new__ option to a viewer who does have projects', async () => { + renderLayout(workspaceHandlers('viewer')); + await ready(); + expect(screen.queryByText('+ New project…')).toBeNull(); + }); +}); + +describe('theme toggle', () => { + it('flips the theme and relabels itself', async () => { + renderLayout(); + await ready(); + + const toggle = screen.getByLabelText('Switch to dark theme'); + fireEvent.click(toggle); + expect(document.body.classList.contains('dark')).toBe(true); + + // The control now offers the inverse action. + fireEvent.click(screen.getByLabelText('Switch to light theme')); + expect(document.body.classList.contains('dark')).toBe(false); + }); +}); diff --git a/apps/dashboard/test/members-page.test.tsx b/apps/dashboard/test/members-page.test.tsx new file mode 100644 index 0000000..d5b3eee --- /dev/null +++ b/apps/dashboard/test/members-page.test.tsx @@ -0,0 +1,224 @@ +// @vitest-environment happy-dom +/** + * Members: role changes, removal, and the read-only view a non-admin gets + * (the list is still visible — only the controls are admin-gated). + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Member } from '../src/api/client'; +import { MembersPage } from '../src/pages/MembersPage'; +import { + ORG_ID, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const MEMBERS_URL = `/v1/orgs/${ORG_ID}/members`; + +const member = (over: Partial = {}): Member => ({ + userId: 'u1', + email: 'dev@velobits.test', + displayName: 'Dev User', + role: 'admin', + createdAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const MEMBERS: Member[] = [ + member(), + member({ userId: 'u2', email: 'ops@velobits.test', displayName: null, role: 'viewer' }), +]; + +const pageHandlers = ( + role: 'admin' | 'developer' | 'viewer' = 'admin', + over: Handlers = {}, +): Handlers => ({ + ...workspaceHandlers(role), + [`GET ${MEMBERS_URL}`]: MEMBERS, + ...over, +}); + +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders(); + return { stub }; +} + +const loaded = () => waitFor(() => expect(screen.getByText('ops@velobits.test')).toBeTruthy()); + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('listing', () => { + it('renders names, emails, and an em dash for a missing display name', async () => { + renderPage(); + await loaded(); + expect(screen.getByText('Dev User')).toBeTruthy(); + expect(screen.getByText('—')).toBeTruthy(); + }); + + it('surfaces a load failure', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${MEMBERS_URL}`]: { status: 403, body: { error: 'forbidden', message: 'not yours' } }, + }), + ); + await waitFor(() => expect(screen.getByText('not yours')).toBeTruthy()); + }); +}); + +describe('admin controls', () => { + it('changes a role', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`PATCH ${MEMBERS_URL}/u2`]: { ok: true } }), + ); + await loaded(); + + fireEvent.change(screen.getByLabelText('Role for ops@velobits.test'), { + target: { value: 'developer' }, + }); + await waitFor(() => + expect(stub.calls.find((c) => c.key === `PATCH ${MEMBERS_URL}/u2`)?.body).toEqual({ + role: 'developer', + }), + ); + }); + + it('surfaces a rejected role change', async () => { + renderPage( + pageHandlers('admin', { + [`PATCH ${MEMBERS_URL}/u2`]: { + status: 409, + body: { error: 'last_admin', message: 'org needs one admin' }, + }, + }), + ); + await loaded(); + + fireEvent.change(screen.getByLabelText('Role for ops@velobits.test'), { + target: { value: 'admin' }, + }); + await waitFor(() => expect(screen.getByText('org needs one admin')).toBeTruthy()); + }); + + it('removes a member after confirming', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`DELETE ${MEMBERS_URL}/u2`]: { status: 204 } }), + ); + await loaded(); + + const [firstRemove] = screen.getAllByText('Remove'); + fireEvent.click(firstRemove!); + expect(stub.calls.some((c) => c.key.startsWith('DELETE'))).toBe(false); + + fireEvent.click(screen.getByText('Remove from org?')); + await waitFor(() => expect(stub.calls.some((c) => c.key.startsWith('DELETE'))).toBe(true)); + }); + + it('surfaces a failed removal', async () => { + renderPage( + pageHandlers('admin', { + [`DELETE ${MEMBERS_URL}/u1`]: { + status: 409, + body: { error: 'last_admin', message: 'cannot remove the last admin' }, + }, + }), + ); + await loaded(); + + const [firstRemove] = screen.getAllByText('Remove'); + fireEvent.click(firstRemove!); + fireEvent.click(screen.getByText('Remove from org?')); + await waitFor(() => expect(screen.getByText('cannot remove the last admin')).toBeTruthy()); + }); +}); + +describe('adding a member', () => { + it('posts email and role, defaulting to developer', async () => { + const { stub } = renderPage(pageHandlers('admin', { [`POST ${MEMBERS_URL}`]: { ok: true } })); + await loaded(); + + fireEvent.click(screen.getByText('+ Add member')); + const submit = screen.getByText('Add'); + expect(submit).toHaveProperty('disabled', true); + expect(screen.getByLabelText('Role')).toHaveProperty('value', 'developer'); + + fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'new@velobits.test' } }); + expect(submit).toHaveProperty('disabled', false); + fireEvent.click(submit); + + await waitFor(() => expect(screen.queryByText('Add member')).toBeNull()); + expect(stub.calls.find((c) => c.key === `POST ${MEMBERS_URL}`)?.body).toEqual({ + email: 'new@velobits.test', + role: 'developer', + }); + }); + + it('honours a chosen role', async () => { + const { stub } = renderPage(pageHandlers('admin', { [`POST ${MEMBERS_URL}`]: { ok: true } })); + await loaded(); + + fireEvent.click(screen.getByText('+ Add member')); + fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'boss@velobits.test' } }); + fireEvent.change(screen.getByLabelText('Role'), { target: { value: 'admin' } }); + fireEvent.click(screen.getByText('Add')); + + await waitFor(() => + expect( + (stub.calls.find((c) => c.key === `POST ${MEMBERS_URL}`)?.body as { role: string }).role, + ).toBe('admin'), + ); + }); + + it('surfaces an unknown-user failure and keeps the modal open', async () => { + renderPage( + pageHandlers('admin', { + [`POST ${MEMBERS_URL}`]: { + status: 404, + body: { error: 'not_found', message: 'no such user — they must sign in once' }, + }, + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ Add member')); + fireEvent.change(screen.getByLabelText('Email'), { target: { value: 'ghost@velobits.test' } }); + fireEvent.click(screen.getByText('Add')); + + await waitFor(() => expect(screen.getByText(/no such user/)).toBeTruthy()); + expect(screen.getByText('Add member')).toBeTruthy(); + }); + + it('closes on cancel', async () => { + renderPage(); + await loaded(); + fireEvent.click(screen.getByText('+ Add member')); + fireEvent.click(screen.getByText('Cancel')); + expect(screen.queryByText('Add member')).toBeNull(); + }); +}); + +describe('non-admin view', () => { + it('lists members read-only, with roles as chips', async () => { + renderPage(pageHandlers('developer')); + await loaded(); + + expect(screen.queryByText('+ Add member')).toBeNull(); + expect(screen.queryByText('Remove')).toBeNull(); + expect(screen.queryByLabelText('Role for ops@velobits.test')).toBeNull(); + // Roles still readable, just not editable. + expect(screen.getByText('viewer')).toBeTruthy(); + }); +}); diff --git a/apps/dashboard/test/segments-page.test.tsx b/apps/dashboard/test/segments-page.test.tsx new file mode 100644 index 0000000..7c99453 --- /dev/null +++ b/apps/dashboard/test/segments-page.test.tsx @@ -0,0 +1,308 @@ +// @vitest-environment happy-dom +/** + * Segments admin: list, create vs edit (the key is immutable once set), + * condition-JSON validation against the engine schema, and delete. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { Segment } from '../src/api/client'; +import { SegmentsPage } from '../src/pages/SegmentsPage'; +import { + PROJECT_ID, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const SEGMENTS_URL = `/v1/projects/${PROJECT_ID}/segments`; + +const segment = (over: Partial = {}): Segment => ({ + id: 's1', + key: 'beta-users', + name: 'Beta users', + description: 'Opted in', + rules: [{ attribute: 'plan', operator: 'in', values: ['pro'] }], + ...over, +}); + +const pageHandlers = ( + role: 'admin' | 'developer' | 'viewer' = 'admin', + over: Handlers = {}, +): Handlers => ({ + ...workspaceHandlers(role), + [`GET ${SEGMENTS_URL}`]: [segment()], + ...over, +}); + +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders(); + return { stub }; +} + +const loaded = () => waitFor(() => expect(screen.getByText('beta-users')).toBeTruthy()); + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('listing', () => { + it('renders key, name, description, and the raw conditions', async () => { + renderPage(); + await loaded(); + expect(screen.getByText(/Opted in/)).toBeTruthy(); + expect( + screen.getByText(JSON.stringify([{ attribute: 'plan', operator: 'in', values: ['pro'] }])), + ).toBeTruthy(); + }); + + it('omits the description separator when there is none', async () => { + renderPage( + pageHandlers('admin', { [`GET ${SEGMENTS_URL}`]: [segment({ description: null })] }), + ); + await loaded(); + expect(screen.queryByText(/—/)).toBeNull(); + }); + + it('shows an empty state', async () => { + renderPage(pageHandlers('admin', { [`GET ${SEGMENTS_URL}`]: [] })); + await waitFor(() => expect(screen.getByText('No segments yet.')).toBeTruthy()); + }); + + it('surfaces a load failure', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${SEGMENTS_URL}`]: { + status: 403, + body: { error: 'forbidden', message: 'no access' }, + }, + }), + ); + await waitFor(() => expect(screen.getByText('no access')).toBeTruthy()); + }); + + it('hides all mutation controls from a viewer', async () => { + renderPage(pageHandlers('viewer')); + await loaded(); + expect(screen.queryByText('+ New segment')).toBeNull(); + expect(screen.queryByText('edit')).toBeNull(); + expect(screen.queryByText('delete')).toBeNull(); + }); +}); + +describe('create', () => { + it('posts a new segment with a trimmed key, name, and parsed conditions', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`POST ${SEGMENTS_URL}`]: segment({ id: 's2' }) }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ New segment')); + expect(screen.getByText('New segment')).toBeTruthy(); + + const save = screen.getByText('Save'); + // Both key and name are required for a create. + expect(save).toHaveProperty('disabled', true); + fireEvent.change(screen.getByLabelText('Key'), { target: { value: ' power-users ' } }); + expect(save).toHaveProperty('disabled', true); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Power users ' } }); + expect(save).toHaveProperty('disabled', false); + + fireEvent.change(screen.getByLabelText('Conditions (ALL must match)'), { + target: { value: '[{"attribute":"seats","operator":"gte","value":5}]' }, + }); + fireEvent.click(save); + + await waitFor(() => expect(screen.queryByText('New segment')).toBeNull()); + expect(stub.calls.find((c) => c.key === `POST ${SEGMENTS_URL}`)?.body).toEqual({ + key: 'power-users', + name: 'Power users', + description: null, + rules: [{ attribute: 'seats', operator: 'gte', value: 5 }], + }); + }); + + it('pre-fills a sensible starter condition', async () => { + renderPage(); + await loaded(); + fireEvent.click(screen.getByText('+ New segment')); + expect(screen.getByLabelText('Conditions (ALL must match)')).toHaveProperty( + 'value', + JSON.stringify([{ attribute: 'plan', operator: 'in', values: ['pro'] }], null, 2), + ); + }); + + it('sends a description when one is typed', async () => { + const { stub } = renderPage(pageHandlers('admin', { [`POST ${SEGMENTS_URL}`]: segment() })); + await loaded(); + + fireEvent.click(screen.getByText('+ New segment')); + fireEvent.change(screen.getByLabelText('Key'), { target: { value: 'k' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'N' } }); + fireEvent.change(screen.getByLabelText('Description'), { target: { value: ' notes ' } }); + fireEvent.click(screen.getByText('Save')); + + await waitFor(() => + expect( + (stub.calls.find((c) => c.key === `POST ${SEGMENTS_URL}`)?.body as { description: string }) + .description, + ).toBe('notes'), + ); + }); + + it('rejects malformed JSON without calling the API', async () => { + const { stub } = renderPage(); + await loaded(); + + fireEvent.click(screen.getByText('+ New segment')); + fireEvent.change(screen.getByLabelText('Key'), { target: { value: 'k' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'N' } }); + fireEvent.change(screen.getByLabelText('Conditions (ALL must match)'), { + target: { value: 'not json' }, + }); + fireEvent.click(screen.getByText('Save')); + + expect(screen.getByText('Not valid JSON.')).toBeTruthy(); + expect(stub.calls.some((c) => c.key.startsWith('POST'))).toBe(false); + }); + + it('reports an unknown operator with its path', async () => { + const { stub } = renderPage(); + await loaded(); + + fireEvent.click(screen.getByText('+ New segment')); + fireEvent.change(screen.getByLabelText('Key'), { target: { value: 'k' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'N' } }); + fireEvent.change(screen.getByLabelText('Conditions (ALL must match)'), { + target: { value: '[{"attribute":"plan","operator":"startsWith","value":"p"}]' }, + }); + fireEvent.click(screen.getByText('Save')); + + await waitFor(() => expect(document.querySelector('.error-note')).toBeTruthy()); + expect(stub.calls.some((c) => c.key.startsWith('POST'))).toBe(false); + }); + + it('surfaces a rejected create and keeps the modal open', async () => { + renderPage( + pageHandlers('admin', { + [`POST ${SEGMENTS_URL}`]: { + status: 409, + body: { error: 'conflict', message: 'key already used' }, + }, + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('+ New segment')); + fireEvent.change(screen.getByLabelText('Key'), { target: { value: 'beta-users' } }); + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Dupe' } }); + fireEvent.click(screen.getByText('Save')); + + await waitFor(() => expect(screen.getByText('key already used')).toBeTruthy()); + expect(screen.getByText('New segment')).toBeTruthy(); + }); + + it('closes on cancel', async () => { + renderPage(); + await loaded(); + fireEvent.click(screen.getByText('+ New segment')); + fireEvent.click(screen.getByText('Cancel')); + expect(screen.queryByText('New segment')).toBeNull(); + }); +}); + +describe('edit', () => { + it('pre-fills from the segment and PATCHes without the key', async () => { + const { stub } = renderPage(pageHandlers('admin', { 'PATCH /v1/segments/s1': segment() })); + await loaded(); + + fireEvent.click(screen.getByText('edit')); + expect(screen.getByText('Edit beta-users')).toBeTruthy(); + // The key is immutable once assigned, so the field is not offered. + expect(screen.queryByLabelText('Key')).toBeNull(); + expect(screen.getByLabelText('Name')).toHaveProperty('value', 'Beta users'); + expect(screen.getByLabelText('Description')).toHaveProperty('value', 'Opted in'); + + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Beta cohort' } }); + fireEvent.click(screen.getByText('Save')); + + await waitFor(() => expect(screen.queryByText('Edit beta-users')).toBeNull()); + expect(stub.calls.find((c) => c.key === 'PATCH /v1/segments/s1')?.body).toEqual({ + name: 'Beta cohort', + description: 'Opted in', + rules: [{ attribute: 'plan', operator: 'in', values: ['pro'] }], + }); + }); + + it('clears the description to null when emptied', async () => { + const { stub } = renderPage(pageHandlers('admin', { 'PATCH /v1/segments/s1': segment() })); + await loaded(); + + fireEvent.click(screen.getByText('edit')); + fireEvent.change(screen.getByLabelText('Description'), { target: { value: ' ' } }); + fireEvent.click(screen.getByText('Save')); + + await waitFor(() => + expect( + ( + stub.calls.find((c) => c.key === 'PATCH /v1/segments/s1')?.body as { + description: unknown; + } + ).description, + ).toBeNull(), + ); + }); + + it('handles a segment that arrives with an empty description', async () => { + renderPage( + pageHandlers('admin', { [`GET ${SEGMENTS_URL}`]: [segment({ description: null })] }), + ); + await loaded(); + fireEvent.click(screen.getByText('edit')); + expect(screen.getByLabelText('Description')).toHaveProperty('value', ''); + }); +}); + +describe('delete', () => { + it('deletes after confirming', async () => { + const { stub } = renderPage( + pageHandlers('admin', { 'DELETE /v1/segments/s1': { status: 204 } }), + ); + await loaded(); + + fireEvent.click(screen.getByText('delete')); + // Two-step: the first click only arms. + expect(stub.calls.some((c) => c.key.startsWith('DELETE'))).toBe(false); + + fireEvent.click(screen.getByText('Delete segment?')); + await waitFor(() => + expect(stub.calls.some((c) => c.key === 'DELETE /v1/segments/s1')).toBe(true), + ); + }); + + it('surfaces a delete failure', async () => { + renderPage( + pageHandlers('admin', { + 'DELETE /v1/segments/s1': { + status: 409, + body: { error: 'in_use', message: 'segment referenced by a rule' }, + }, + }), + ); + await loaded(); + + fireEvent.click(screen.getByText('delete')); + fireEvent.click(screen.getByText('Delete segment?')); + await waitFor(() => expect(screen.getByText('segment referenced by a rule')).toBeTruthy()); + }); +}); diff --git a/apps/dashboard/test/tool-detail-page.test.tsx b/apps/dashboard/test/tool-detail-page.test.tsx new file mode 100644 index 0000000..042d259 --- /dev/null +++ b/apps/dashboard/test/tool-detail-page.test.tsx @@ -0,0 +1,526 @@ +// @vitest-environment happy-dom +/** + * The tool detail screen: kill switch (with the prod confirm gate), rollout, + * targeting-rule validation, config save, and version history / diff / + * rollback. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { Route, Routes } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { ConfigVersion, FlagRow, Tool, ToolConfig } from '../src/api/client'; +import { ToolDetailPage } from '../src/pages/ToolDetailPage'; +import { + ENV_ID, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const TOOL_ID = 't1'; +const PROD_ENV = '44444444-4444-4444-8444-444444444444'; +const CONFIG_BASE = (envId = ENV_ID) => `/v1/environments/${envId}/tools/${TOOL_ID}/config`; + +const toolDetail = (over: Partial = {}) => ({ + id: TOOL_ID, + key: 'tool.summarize', + name: 'Summarize', + description: 'Shortens text', + tags: ['text'], + metadata: {}, + archived: false, + updatedAt: '2026-07-20T10:00:00.000Z', + flagStates: [], + ...over, +}); + +const flagRow = (over: Partial = {}): FlagRow => ({ + toolId: TOOL_ID, + toolKey: 'tool.summarize', + toolName: 'Summarize', + archived: false, + enabled: true, + rolloutPercent: null, + targetingRules: [], + updatedAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const config = (over: Partial = {}): ToolConfig => ({ + value: { limit: 5, mode: 'fast' }, + version: 3, + ...over, +}); + +const version = (v: number, over: Partial = {}): ConfigVersion => ({ + id: `cv-${v}`, + version: v, + value: { limit: v, mode: 'fast' }, + authorId: 'u1', + restoredFromVersion: null, + createdAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const pageHandlers = ( + role: 'admin' | 'developer' | 'viewer' = 'admin', + over: Handlers = {}, + envId = ENV_ID, +): Handlers => ({ + ...workspaceHandlers(role), + [`GET /v1/tools/${TOOL_ID}`]: toolDetail(), + [`GET /v1/environments/${envId}/flags`]: [flagRow()], + [`GET ${CONFIG_BASE(envId)}`]: config(), + [`GET ${CONFIG_BASE(envId)}/versions`]: [version(3), version(2)], + ...over, +}); + +/** + * Mounted under a real route: the page reads :toolId from useParams and + * early-returns null without one, so rendering it bare shows nothing at all. + */ +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders( + + } /> + } /> + , + { route: `/tools/${TOOL_ID}` }, + ); + return { stub }; +} + +const loaded = () => waitFor(() => expect(screen.getByText('tool.summarize')).toBeTruthy()); +/** + * Positive gate on both panels. Waiting for "Loading flag state…" to DISAPPEAR + * would pass instantly on the first render, before the tool query has even + * resolved — that text is absent before the panel exists, not only after. + */ +const flagReady = () => + waitFor(() => { + expect(screen.getByText(/Flag state in/)).toBeTruthy(); + expect(screen.getByLabelText('Config value')).toBeTruthy(); + }); + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('header', () => { + it('renders key, name, description, and tags', async () => { + renderPage(); + await loaded(); + expect(screen.getByText(/Summarize — Shortens text/)).toBeTruthy(); + expect(screen.getByText('text')).toBeTruthy(); + }); + + it('omits the em dash when there is no description', async () => { + renderPage( + pageHandlers('admin', { [`GET /v1/tools/${TOOL_ID}`]: toolDetail({ description: null }) }), + ); + await loaded(); + expect(screen.queryByText(/—/)).toBeNull(); + }); + + it('shows a loading state, then the tool', async () => { + renderPage(); + expect(screen.getByText('Loading…')).toBeTruthy(); + await loaded(); + }); + + it('renders the error instead of the page when the tool fails to load', async () => { + renderPage( + pageHandlers('admin', { + [`GET /v1/tools/${TOOL_ID}`]: { + status: 404, + body: { error: 'not_found', message: 'tool not found' }, + }, + }), + ); + await waitFor(() => expect(screen.getByText('tool not found')).toBeTruthy()); + expect(screen.queryByText('Config')).toBeNull(); + }); +}); + +describe('archive', () => { + it('archives after a confirm and refetches', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`PATCH /v1/tools/${TOOL_ID}`]: { ok: true } }), + ); + await loaded(); + + fireEvent.click(screen.getByText('Archive')); + fireEvent.click(screen.getByText('Archive (drops from snapshots)?')); + + await waitFor(() => + expect(stub.calls.find((c) => c.key === `PATCH /v1/tools/${TOOL_ID}`)?.body).toEqual({ + archived: true, + }), + ); + }); + + it('offers unarchive for an archived tool and marks it', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`GET /v1/tools/${TOOL_ID}`]: toolDetail({ archived: true }), + [`PATCH /v1/tools/${TOOL_ID}`]: { ok: true }, + }), + ); + await loaded(); + expect(screen.getByText('archived')).toBeTruthy(); + + fireEvent.click(screen.getByText('Unarchive')); + fireEvent.click(screen.getByText('Unarchive?')); + await waitFor(() => + expect(stub.calls.find((c) => c.key === `PATCH /v1/tools/${TOOL_ID}`)?.body).toEqual({ + archived: false, + }), + ); + }); + + it('hides archive from a viewer', async () => { + renderPage(pageHandlers('viewer')); + await loaded(); + expect(screen.queryByText('Archive')).toBeNull(); + }); +}); + +describe('flag panel', () => { + it('shows the current state and flips the kill switch without confirming in dev', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`]: { ok: true }, + }), + ); + await flagReady(); + expect(screen.getByText('Flag state in Development')).toBeTruthy(); + + // requireConfirm is false outside prod, so one click is enough. + fireEvent.click(screen.getByText('Turn OFF (kill switch)')); + await waitFor(() => + expect( + stub.calls.find((c) => c.key === `PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`) + ?.body, + ).toEqual({ enabled: false }), + ); + }); + + it('requires a second click in prod', async () => { + localStorage.setItem('tf.environment', PROD_ENV); + const { stub } = renderPage( + pageHandlers( + 'admin', + { [`PATCH /v1/environments/${PROD_ENV}/tools/${TOOL_ID}/flag`]: { ok: true } }, + PROD_ENV, + ), + ); + await flagReady(); + expect(screen.getByText('production changes ask for confirmation')).toBeTruthy(); + + fireEvent.click(screen.getByText('Turn OFF (kill switch)')); + expect(stub.calls.some((c) => c.key.startsWith('PATCH'))).toBe(false); + + fireEvent.click(screen.getByText('Confirm OFF in prod?')); + await waitFor(() => expect(stub.calls.some((c) => c.key.startsWith('PATCH'))).toBe(true)); + }); + + it('offers Turn ON for a disabled tool', async () => { + renderPage( + pageHandlers('admin', { + [`GET /v1/environments/${ENV_ID}/flags`]: [flagRow({ enabled: false })], + }), + ); + await flagReady(); + expect(screen.getByText('Turn ON')).toBeTruthy(); + }); + + it('pre-fills the rollout and saves it as a number', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`GET /v1/environments/${ENV_ID}/flags`]: [flagRow({ rolloutPercent: 25 })], + [`PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`]: { ok: true }, + }), + ); + await flagReady(); + expect(screen.getByLabelText(/Rollout %/)).toHaveProperty('value', '25'); + + fireEvent.change(screen.getByLabelText(/Rollout %/), { target: { value: '60' } }); + fireEvent.click(screen.getByText('Save')); + await waitFor(() => + expect(stub.calls.find((c) => c.key.endsWith('/flag'))?.body).toEqual({ rolloutPercent: 60 }), + ); + }); + + it('sends null when the rollout is cleared — empty means everyone', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`GET /v1/environments/${ENV_ID}/flags`]: [flagRow({ rolloutPercent: 25 })], + [`PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`]: { ok: true }, + }), + ); + await flagReady(); + + fireEvent.change(screen.getByLabelText(/Rollout %/), { target: { value: '' } }); + fireEvent.click(screen.getByText('Save')); + await waitFor(() => + expect( + (stub.calls.find((c) => c.key.endsWith('/flag'))?.body as { rolloutPercent: unknown }) + .rolloutPercent, + ).toBeNull(), + ); + }); + + it('rejects malformed JSON in the targeting field without calling the API', async () => { + const { stub } = renderPage(); + await flagReady(); + + fireEvent.change(screen.getByLabelText(/Targeting rules/), { target: { value: '{oops' } }); + fireEvent.click(screen.getByText('Save targeting + rollout')); + + expect(screen.getByText('Not valid JSON.')).toBeTruthy(); + expect(stub.calls.some((c) => c.key.startsWith('PATCH'))).toBe(false); + }); + + it('reports schema violations with a field path', async () => { + const { stub } = renderPage(); + await flagReady(); + + // Valid JSON, but `enabled` is required on a targeting rule. + fireEvent.change(screen.getByLabelText(/Targeting rules/), { + target: { value: '[{"segments":["beta"]}]' }, + }); + fireEvent.click(screen.getByText('Save targeting + rollout')); + + await waitFor(() => expect(screen.getByText(/0\.enabled/)).toBeTruthy()); + expect(stub.calls.some((c) => c.key.startsWith('PATCH'))).toBe(false); + }); + + it('saves valid targeting rules together with the rollout', async () => { + const { stub } = renderPage( + pageHandlers('admin', { + [`PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`]: { ok: true }, + }), + ); + await flagReady(); + + fireEvent.change(screen.getByLabelText(/Targeting rules/), { + target: { value: '[{"segments":["beta"],"enabled":true}]' }, + }); + fireEvent.click(screen.getByText('Save targeting + rollout')); + + await waitFor(() => expect(stub.calls.some((c) => c.key.endsWith('/flag'))).toBe(true)); + expect(stub.calls.find((c) => c.key.endsWith('/flag'))?.body).toEqual({ + targetingRules: [{ segments: ['beta'], conditions: [], enabled: true }], + rolloutPercent: null, + }); + }); + + it('surfaces a rejected flag patch', async () => { + renderPage( + pageHandlers('admin', { + [`PATCH /v1/environments/${ENV_ID}/tools/${TOOL_ID}/flag`]: { + status: 403, + body: { error: 'forbidden', message: 'role too low' }, + }, + }), + ); + await flagReady(); + + fireEvent.click(screen.getByText('Turn OFF (kill switch)')); + await waitFor(() => expect(screen.getByText('role too low')).toBeTruthy()); + }); + + it('is read-only for a viewer', async () => { + renderPage(pageHandlers('viewer')); + await flagReady(); + expect(screen.getByLabelText(/Rollout %/)).toHaveProperty('disabled', true); + expect(screen.queryByText('Save targeting + rollout')).toBeNull(); + expect(screen.queryByText('Turn OFF (kill switch)')).toBeNull(); + }); + + it('is read-only for an archived tool even as admin', async () => { + renderPage( + pageHandlers('admin', { [`GET /v1/tools/${TOOL_ID}`]: toolDetail({ archived: true }) }), + ); + await flagReady(); + // canEdit is `canEdit && !tool.archived` for the flag panel only. + expect(screen.queryByText('Turn OFF (kill switch)')).toBeNull(); + expect(screen.getByText(/Save as version/)).toBeTruthy(); + }); + + it('keeps showing the loading panel when the tool has no flag row', async () => { + renderPage(pageHandlers('admin', { [`GET /v1/environments/${ENV_ID}/flags`]: [] })); + await loaded(); + expect(screen.getByText('Loading flag state…')).toBeTruthy(); + }); +}); + +describe('config panel', () => { + it('shows the current version and pre-fills the draft', async () => { + renderPage(); + await flagReady(); + expect(screen.getByText('(version 3)')).toBeTruthy(); + expect(screen.getByLabelText('Config value')).toHaveProperty( + 'value', + JSON.stringify({ limit: 5, mode: 'fast' }, null, 2), + ); + }); + + it('offers a fallback skeleton when no config exists yet', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${CONFIG_BASE()}`]: config({ value: null, version: 0 }), + [`GET ${CONFIG_BASE()}/versions`]: [], + }), + ); + await flagReady(); + expect(screen.getByLabelText('Config value')).toHaveProperty( + 'value', + JSON.stringify({ fallback: { mode: 'message', message: '' } }, null, 2), + ); + // No history table when there are no versions. + expect(screen.queryByText('History')).toBeNull(); + }); + + it('saves the draft as the next version', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`PUT ${CONFIG_BASE()}`]: { version: 4 } }), + ); + await flagReady(); + + expect(screen.getByText('Save as version 4')).toBeTruthy(); + fireEvent.change(screen.getByLabelText('Config value'), { + target: { value: '{"limit":9}' }, + }); + fireEvent.click(screen.getByText('Save as version 4')); + + await waitFor(() => + expect(stub.calls.find((c) => c.key === `PUT ${CONFIG_BASE()}`)?.body).toEqual({ + value: { limit: 9 }, + }), + ); + }); + + it('rejects invalid JSON in the config draft', async () => { + const { stub } = renderPage(); + await flagReady(); + + fireEvent.change(screen.getByLabelText('Config value'), { target: { value: '{' } }); + fireEvent.click(screen.getByText('Save as version 4')); + expect(screen.getByText('Not valid JSON.')).toBeTruthy(); + expect(stub.calls.some((c) => c.key.startsWith('PUT'))).toBe(false); + }); + + it('rejects a non-object config', async () => { + const { stub } = renderPage(); + await flagReady(); + + fireEvent.change(screen.getByLabelText('Config value'), { target: { value: '[1,2,3]' } }); + fireEvent.click(screen.getByText('Save as version 4')); + expect(screen.getByText('Config must be a JSON object.')).toBeTruthy(); + expect(stub.calls.some((c) => c.key.startsWith('PUT'))).toBe(false); + }); + + it('surfaces a rejected save', async () => { + renderPage( + pageHandlers('admin', { + [`PUT ${CONFIG_BASE()}`]: { status: 403, body: { error: 'forbidden', message: 'nope' } }, + }), + ); + await flagReady(); + + fireEvent.click(screen.getByText('Save as version 4')); + await waitFor(() => expect(screen.getByText('nope')).toBeTruthy()); + }); + + it('hides the save button from a viewer', async () => { + renderPage(pageHandlers('viewer')); + await flagReady(); + expect(screen.queryByText(/Save as version/)).toBeNull(); + }); +}); + +describe('config history', () => { + it('lists versions and notes a restore', async () => { + renderPage( + pageHandlers('admin', { + [`GET ${CONFIG_BASE()}/versions`]: [version(3, { restoredFromVersion: 1 }), version(2)], + }), + ); + await flagReady(); + + expect(screen.getByText('History')).toBeTruthy(); + expect(screen.getByText('v3')).toBeTruthy(); + expect(screen.getByText('restored from v1')).toBeTruthy(); + }); + + it('toggles a diff open and closed', async () => { + renderPage(); + await flagReady(); + + const [diffButton] = screen.getAllByText('diff'); + fireEvent.click(diffButton!); + expect(screen.getByText(/removed lines are v3/)).toBeTruthy(); + // The added/removed lines come from the LCS diff of the two payloads. + expect(document.querySelector('.diff .removed')).toBeTruthy(); + + fireEvent.click(screen.getByText('hide diff')); + expect(screen.queryByText(/removed lines are v/)).toBeNull(); + }); + + it('offers restore only for versions that are not current', async () => { + renderPage(); + await flagReady(); + // v3 is current, v2 is not — so exactly one restore button. + expect(screen.getAllByText('restore')).toHaveLength(1); + }); + + it('rolls back to a chosen version after confirming', async () => { + const { stub } = renderPage( + pageHandlers('admin', { [`POST ${CONFIG_BASE()}/rollback`]: { version: 4 } }), + ); + await flagReady(); + + fireEvent.click(screen.getByText('restore')); + fireEvent.click(screen.getByText('Restore this version?')); + + await waitFor(() => + expect(stub.calls.find((c) => c.key === `POST ${CONFIG_BASE()}/rollback`)?.body).toEqual({ + toVersion: 2, + }), + ); + }); + + it('surfaces a failed rollback', async () => { + renderPage( + pageHandlers('admin', { + [`POST ${CONFIG_BASE()}/rollback`]: { + status: 409, + body: { error: 'conflict', message: 'version moved on' }, + }, + }), + ); + await flagReady(); + + fireEvent.click(screen.getByText('restore')); + fireEvent.click(screen.getByText('Restore this version?')); + await waitFor(() => expect(screen.getByText('version moved on')).toBeTruthy()); + }); + + it('hides restore from a viewer but keeps the diff', async () => { + renderPage(pageHandlers('viewer')); + await flagReady(); + expect(screen.queryByText('restore')).toBeNull(); + expect(screen.getAllByText('diff').length).toBeGreaterThan(0); + }); +}); diff --git a/apps/dashboard/test/tools-page.test.tsx b/apps/dashboard/test/tools-page.test.tsx new file mode 100644 index 0000000..7d80e44 --- /dev/null +++ b/apps/dashboard/test/tools-page.test.tsx @@ -0,0 +1,316 @@ +// @vitest-environment happy-dom +/** + * The tools list: flag/tag join, the four filters, role-gated registration, + * and the two distinct empty states. + */ +import { cleanup, fireEvent, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { FlagRow, Tool } from '../src/api/client'; +import { ToolsPage } from '../src/pages/ToolsPage'; +import { + ENV_ID, + PROJECT_ID, + renderWithProviders, + stubAuth, + stubFetch, + workspaceHandlers, + type FetchStub, + type Handlers, +} from './harness'; + +const flag = (over: Partial = {}): FlagRow => ({ + toolId: 't1', + toolKey: 'tool.summarize', + toolName: 'Summarize', + archived: false, + enabled: true, + rolloutPercent: null, + targetingRules: [], + updatedAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const tool = (over: Partial = {}): Tool => ({ + id: 't1', + key: 'tool.summarize', + name: 'Summarize', + description: null, + tags: ['text'], + metadata: {}, + archived: false, + updatedAt: '2026-07-20T10:00:00.000Z', + ...over, +}); + +const ROWS: FlagRow[] = [ + flag(), + flag({ toolId: 't2', toolKey: 'tool.translate', toolName: 'Translate', enabled: false }), + flag({ toolId: 't3', toolKey: 'tool.rewrite', toolName: 'Rewrite', rolloutPercent: 25 }), + flag({ toolId: 't4', toolKey: 'tool.legacy', toolName: 'Legacy', archived: true }), +]; + +const TOOLS: Tool[] = [ + tool(), + tool({ id: 't2', key: 'tool.translate', name: 'Translate', tags: ['text', 'i18n'] }), + tool({ id: 't3', key: 'tool.rewrite', name: 'Rewrite', tags: [] }), + tool({ id: 't4', key: 'tool.legacy', name: 'Legacy', tags: [], archived: true }), +]; + +const pageHandlers = ( + role: 'admin' | 'developer' | 'viewer' = 'admin', + over: Handlers = {}, +): Handlers => ({ + ...workspaceHandlers(role), + [`GET /v1/environments/${ENV_ID}/flags`]: ROWS, + [`GET /v1/projects/${PROJECT_ID}/tools`]: TOOLS, + ...over, +}); + +function renderPage(handlers: Handlers = pageHandlers()): { stub: FetchStub } { + stubAuth(); + const stub = stubFetch(handlers); + renderWithProviders(); + return { stub }; +} + +const visibleKeys = () => [...document.querySelectorAll('td.mono')].map((td) => td.textContent); + +beforeEach(() => { + localStorage.clear(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('listing', () => { + it('hides archived rows by default and reports the visible count', async () => { + renderPage(); + await waitFor(() => expect(visibleKeys()).toHaveLength(3)); + expect(visibleKeys()).not.toContain('tool.legacy'); + // The denominator is every row fetched, so the hidden archived one counts. + expect(screen.getByText('3 of 4 in Development')).toBeTruthy(); + }); + + it('renders each status as its own chip', async () => { + renderPage(); + await waitFor(() => expect(visibleKeys()).toHaveLength(3)); + expect(screen.getByText('ON')).toBeTruthy(); + expect(screen.getByText('OFF')).toBeTruthy(); + expect(screen.getByText('25%')).toBeTruthy(); + }); + + it('joins tags from the tools query onto the flag rows', async () => { + renderPage(); + await waitFor(() => expect(visibleKeys()).toHaveLength(3)); + // Scoped to the table: 'i18n' is also an