diff --git a/dashboard/e2e/staging-cms.spec.ts b/dashboard/e2e/staging-cms.spec.ts new file mode 100644 index 00000000..439f88e8 --- /dev/null +++ b/dashboard/e2e/staging-cms.spec.ts @@ -0,0 +1,88 @@ +import { expect, test, type Page, type Route } from "@playwright/test"; + +// A repository's staging CMS write connection, from Settings > Repositories. +// Every API call is answered here; nothing reaches a real backend. + +interface Backend { + role: string; + saved: Record | null; + calls: { method: string; path: string; body: Record | null }[]; +} + +async function mockApi(page: Page, init: Partial = {}): Promise { + const db: Backend = { role: "admin", saved: null, calls: [], ...init }; + const json = (route: Route, body: unknown, status = 200) => + route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); + await page.route((url) => url.hostname !== "localhost", (route) => route.abort()); + await page.route( + (url) => url.hostname === "localhost" && /^\/(api|auth)\//.test(url.pathname), + async (route) => { + const req = route.request(); + const p = new URL(req.url()).pathname; + const method = req.method(); + const body = req.postData() ? (JSON.parse(req.postData() as string) as Record) : null; + db.calls.push({ method, path: p, body }); + if (p === "/api/me") + return json(route, { user_id: "u_1", team_id: "t_1", github_login: null, email: "person@example.com", avatar_url: "", role: db.role, auth_provider: "email", mfa_enabled: false }); + if (p === "/api/banners") return json(route, { banners: [] }); + if (p === "/api/teams") return json(route, { teams: [{ team_id: "t_1", org: "your-team", status: "active", current: true }] }); + if (p === "/api/repos") + return json(route, { repos: [{ name: "your-team/web", enabled: true, ticket_source: "github", onboard_status: "ready" }, { name: "your-team/api", enabled: false, ticket_source: "github" }] }); + if (p === "/api/github/installation-status") return json(route, { status: "connected", github_org: "your-team", installation_id: 7 }); + if (p === "/api/repos/your-team/web/staging-cms") { + if (method === "GET") return json(route, db.saved ?? { configured: false, repo: "your-team/web", providers: ["sanity"] }); + if (method === "PUT") { + db.saved = { configured: true, repo: "your-team/web", provider: "sanity", project_id: body?.project_id, dataset: body?.dataset, production_dataset: body?.production_dataset, token_set: true }; + return json(route, db.saved); + } + if (method === "DELETE") { + db.saved = null; + return json(route, { configured: false, repo: "your-team/web" }); + } + } + return json(route, { error: `not mocked: ${method} ${p}` }, 404); + }, + ); + return db; +} + +test("an admin saves a staging-only connection; production names are refused", async ({ page }) => { + const db = await mockApi(page); + await page.goto("/settings/repos/"); + await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click(); + const dialog = page.getByTestId("staging-cms-dialog"); + await expect(dialog).toBeVisible(); + await dialog.getByLabel("Project id").fill("abc123"); + await dialog.getByLabel("Staging dataset", { exact: true }).fill("production"); + await expect(dialog.getByText("This looks like production.")).toBeVisible(); + await expect(dialog.getByRole("button", { name: "Save" })).toBeDisabled(); + await dialog.getByLabel("Staging dataset", { exact: true }).fill("staging"); + await dialog.getByLabel("Token with write access to the staging dataset").fill("sk-test"); + await dialog.getByRole("button", { name: "Save" }).click(); + await expect(dialog).toBeHidden(); + const put = db.calls.find((c) => c.method === "PUT"); + expect(put?.body).toMatchObject({ provider: "sanity", project_id: "abc123", dataset: "staging", token: "sk-test" }); + // The token is never shown again; a saved one keeps its place. + await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click(); + await expect(dialog.getByLabel("Token with write access to the staging dataset")).toHaveValue(""); + await expect(dialog.getByRole("button", { name: "Remove connection" })).toBeVisible(); +}); + +test("a turned-off repository and a member see no staging content button", async ({ page }) => { + await mockApi(page, { role: "member" }); + await page.goto("/settings/repos/"); + await expect(page.getByRole("list", { name: "Repositories" }).getByRole("listitem")).toHaveCount(2); + await expect(page.getByRole("button", { name: /Staging content connection/ })).toHaveCount(0); +}); + +for (const width of [375, 1440]) { + test(`the dialog has no horizontal scroll at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await mockApi(page); + await page.goto("/settings/repos/"); + await page.getByRole("button", { name: "Staging content connection for your-team/web" }).click(); + await expect(page.getByTestId("staging-cms-dialog")).toBeVisible(); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + expect(overflow).toBeLessThanOrEqual(0); + }); +} diff --git a/dashboard/src/app/settings/repos/page.tsx b/dashboard/src/app/settings/repos/page.tsx index 243172af..c12340ce 100644 --- a/dashboard/src/app/settings/repos/page.tsx +++ b/dashboard/src/app/settings/repos/page.tsx @@ -9,6 +9,7 @@ import { Suspense, useCallback, useEffect, useState } from "react"; import { api, type Repo } from "@/lib/api"; import { githubAppUrl } from "@/lib/runtime-config"; import { RoleGuard } from "@/components/role-guard"; +import { StagingCmsDialog } from "@/components/staging-cms-dialog"; import { useToast } from "@/components/toast"; import { Page, PageHeader } from "@/components/page"; import { buttonClass, secondaryButton } from "@/components/ui"; @@ -75,6 +76,8 @@ function ReposPage() { const [toggling, setToggling] = useState(null); const [syncing, setSyncing] = useState(false); const [savingRole, setSavingRole] = useState(null); + // The repository whose staging CMS connection is open, if any. + const [stagingRepo, setStagingRepo] = useState(null); // Turning repos on or off, syncing and routing roles need `repos`. const { ready, can } = useCan(); const canManage = can("repos"); @@ -295,6 +298,17 @@ function ReposPage() { ))} ) : undefined} + {repo.enabled && canManage && ( + + )} } /> @@ -304,6 +318,13 @@ function ReposPage() { )} shownCount} loading={false} onClick={() => setShownCount((n) => n + PAGE_SIZE)} /> + {stagingRepo && ( + !v && setStagingRepo(null)} + /> + )} ); } diff --git a/dashboard/src/components/staging-cms-dialog.tsx b/dashboard/src/components/staging-cms-dialog.tsx new file mode 100644 index 00000000..c0912d1d --- /dev/null +++ b/dashboard/src/components/staging-cms-dialog.tsx @@ -0,0 +1,190 @@ +"use client"; + +import { useEffect, useId, useState } from "react"; +import { api, type StagingCms } from "@/lib/api"; +import { SecretInput } from "./field"; +import { Modal, ModalFooter } from "./modal"; +import { inputClass, primaryButton, secondaryButton } from "./ui"; + +// A repository's staging CMS write connection. When a feature changes the CMS +// schema and the end-to-end tests read pages from the CMS, Coderhelm updates +// the staging content those tests read through this connection, never +// production. Without one, the run stops and lists the content to change. + +/** Dataset names Coderhelm refuses: they look like production. */ +const PRODUCTION_WORDS = ["production", "prod", "prd", "live", "master", "main"]; + +export function looksLikeProduction(dataset: string): boolean { + return dataset + .toLowerCase() + .split(/[^a-z0-9]+/) + .some((w) => PRODUCTION_WORDS.includes(w)); +} + +export function StagingCmsDialog({ + repo, + open, + onOpenChange, +}: { + repo: string; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const [conn, setConn] = useState(null); + const [projectId, setProjectId] = useState(""); + const [dataset, setDataset] = useState(""); + const [prodDataset, setProdDataset] = useState(""); + const [token, setToken] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(""); + const ids = { project: useId(), dataset: useId(), prod: useId(), token: useId() }; + + // Each opening reads the saved connection; the token is never sent back. + useEffect(() => { + if (!open) return; + setError(""); + setToken(""); + setConn(null); + api + .getStagingCms(repo) + .then((c) => { + setConn(c); + setProjectId(c.project_id ?? ""); + setDataset(c.dataset ?? ""); + setProdDataset(c.production_dataset ?? ""); + }) + .catch(() => setError("Couldn't load the connection. Try again.")); + }, [open, repo]); + + const production = looksLikeProduction(dataset) || (!!prodDataset && prodDataset === dataset); + + const save = async () => { + setBusy(true); + setError(""); + try { + const c = await api.saveStagingCms(repo, { + provider: "sanity", + project_id: projectId.trim(), + dataset: dataset.trim(), + production_dataset: prodDataset.trim(), + token: token.trim() || undefined, + }); + setConn(c); + onOpenChange(false); + } catch (e) { + setError(e instanceof Error && e.message ? e.message : "Couldn't save. Try again."); + } + setBusy(false); + }; + + const remove = async () => { + setBusy(true); + setError(""); + try { + await api.deleteStagingCms(repo); + onOpenChange(false); + } catch { + setError("Couldn't remove the connection. Try again."); + } + setBusy(false); + }; + + return ( + !busy && onOpenChange(v)} + testId="staging-cms-dialog" + title={`Staging content for ${repo}`} + description="When a new feature changes the CMS schema and the end-to-end tests read pages from the CMS, Coderhelm updates the staging content those tests read. It never writes to production. Without a connection, the run stops and lists the content to change." + > +
{ + e.preventDefault(); + if (!production) void save(); + }} + > +

CMS: Sanity

+
+ + setProjectId(e.target.value)} + className={inputClass} + autoComplete="off" + required + /> +
+
+ + setDataset(e.target.value)} + className={inputClass} + autoComplete="off" + aria-invalid={production || undefined} + aria-describedby={`${ids.dataset}-help`} + required + /> +

+ {production + ? "This looks like production. Coderhelm writes only to staging; enter the staging dataset." + : "The dataset your end-to-end tests read on staging."} +

+
+
+ + setProdDataset(e.target.value)} + className={inputClass} + autoComplete="off" + /> +

Named so Coderhelm refuses it, whatever it is called.

+
+
+ + setToken(e.target.value)} + placeholder={conn?.token_set ? "Saved. Enter a new one to replace it." : ""} + /> +
+ {error && ( +

+ {error} +

+ )} + + {conn?.configured && ( + + )} + + + +
+
+ ); +} diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index 6cc27ef9..508fc034 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -418,6 +418,15 @@ export const api = { }), deleteRepo: (repo: string) => request(`/api/repos/${repo}`, { method: "DELETE" }), + /** The repository's staging-only CMS write connection (never its token). */ + getStagingCms: (repo: string) => request(`/api/repos/${repo}/staging-cms`), + saveStagingCms: (repo: string, body: StagingCmsInput) => + request(`/api/repos/${repo}/staging-cms`, { + method: "PUT", + body: JSON.stringify(body), + }), + deleteStagingCms: (repo: string) => + request(`/api/repos/${repo}/staging-cms`, { method: "DELETE" }), // Stats getStats: () => request<{ month: Stats; all_time: Stats }>("/api/stats"), @@ -1982,6 +1991,27 @@ export interface Repo { role?: string; } +/** A repository's staging CMS write connection, as the gateway shows it. */ +export interface StagingCms { + configured: boolean; + repo: string; + provider?: string; + project_id?: string; + dataset?: string; + production_dataset?: string; + /** Whether a token is saved; the token itself is never returned. */ + token_set?: boolean; +} + +export interface StagingCmsInput { + provider: "sanity"; + project_id: string; + dataset: string; + production_dataset?: string; + /** Left out to keep the saved token. */ + token?: string; +} + export interface Stats { total_runs: number; completed: number;