From 4e175b174c9604e7bb9d5946c14e50f2b6468fee Mon Sep 17 00:00:00 2001 From: Madraka <8898640+Madraka@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:41:23 +0300 Subject: [PATCH] feat(selfhost): render_page through an optional Chrome sidecar (#292) CLOUDHAL_BROWSER_URL (Chrome's DevTools port, http://chrome:9222) makes the generated workerd config bind an ExternalServer to the admin Worker as BROWSER_CDP. @cloudhal/cloudflare's new devtoolsRenderer drives it with the shared cdpSession: /json/version and the browser socket over Host: localhost, one browser context per render, disposed after it; the shared browser is never closed. adminRender picks Browser Rendering first, else the sidecar, and CLOUDHAL_RENDER=off still turns both off. render_page opens only the page's own signed preview link. RenderDeps.origin (CLOUDHAL_RENDER_ORIGIN, default http://cloudhal:, the same on every instance) opens that link at the private origin the browser reaches the site at, so a self-host site without a domain renders too (core-ts previewUrlAt). The admin Worker gets increase_websocket_message_size while a sidecar is configured, for DevTools messages above 1 MiB. Recipes: compose's chrome profile (chromedp/headless-shell pinned, no port, its own network shared with Cloudhal only, so it cannot reach the store), chrome.* Helm values (Deployment, Service, NetworkPolicy admitting the release's instances only), Swarm docs. CI: scripts/render-smoke.ts calls render_page over /mcp with an agent key and checks a JPEG comes back and no render page is left; the compose and chart checks cover the new parts. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Madraka <8898640+Madraka@users.noreply.github.com> --- .changeset/selfhost-chrome.md | 12 + .github/workflows/docker.yml | 12 +- AGENTS.md | 2 +- deploy/docker/.env.example | 5 + deploy/docker/README.md | 3 +- deploy/docker/compose.yml | 25 ++ deploy/helm/cloudhal/README.md | 8 + deploy/helm/cloudhal/templates/chrome.yaml | 95 ++++++ .../helm/cloudhal/templates/statefulset.yaml | 6 + deploy/helm/cloudhal/values.yaml | 18 + deploy/swarm/README.md | 10 + docs/guides/self-host.md | 21 +- docs/rfcs/0047-self-host-on-workerd.md | 2 +- packages/cli/src/selfhost/browser-sidecar.ts | 75 +++++ packages/cli/src/selfhost/settings.ts | 8 +- packages/cli/src/selfhost/workerd-config.ts | 12 +- packages/cli/test/selfhost-browser.test.ts | 68 ++++ packages/cloudflare/src/admin-worker.ts | 13 +- packages/cloudflare/src/browser-cdp.ts | 98 ++++++ packages/cloudflare/test/browser-cdp.test.ts | 97 ++++++ packages/core-ts/src/preview-token.ts | 6 +- packages/mcp-server/src/common.ts | 6 + packages/mcp-server/src/render-tools.ts | 22 +- packages/mcp-server/test/render-tools.test.ts | 24 ++ scripts/render-smoke.ts | 311 ++++++++++++++++++ 25 files changed, 944 insertions(+), 15 deletions(-) create mode 100644 .changeset/selfhost-chrome.md create mode 100644 deploy/helm/cloudhal/templates/chrome.yaml create mode 100644 packages/cli/src/selfhost/browser-sidecar.ts create mode 100644 packages/cli/test/selfhost-browser.test.ts create mode 100644 packages/cloudflare/src/browser-cdp.ts create mode 100644 packages/cloudflare/test/browser-cdp.test.ts create mode 100644 scripts/render-smoke.ts diff --git a/.changeset/selfhost-chrome.md b/.changeset/selfhost-chrome.md new file mode 100644 index 00000000..e15ba171 --- /dev/null +++ b/.changeset/selfhost-chrome.md @@ -0,0 +1,12 @@ +--- +"@cloudhal/cli": minor +"@cloudhal/cloudflare": minor +"@cloudhal/mcp-server": minor +"@cloudhal/core-ts": patch +--- + +`render_page` on self-host through an optional Chrome sidecar (#292). +- **The setting.** `CLOUDHAL_BROWSER_URL` (Chrome's DevTools port) gives the admin Worker a `BROWSER_CDP` binding. +- **The driver.** `@cloudhal/cloudflare`'s new `devtoolsRenderer` drives it with the shared `cdpSession`: one browser context per render, and the shared browser is never closed. +- **What it opens.** `render_page` opens only the page's signed preview link. With `RenderDeps.origin` (`CLOUDHAL_RENDER_ORIGIN`, default `http://cloudhal:8788`) it opens the link at that private origin, so a site without a domain renders too. `@cloudhal/core-ts` gains `previewUrlAt`. +- **The recipes.** The compose file gains a `chrome` profile: no port, and a network shared with Cloudhal only. The Helm chart gains `chrome.*` values: a Deployment, a Service and a NetworkPolicy. diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 0aefe2da..37e904f9 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -12,7 +12,8 @@ name: Docker image # on the next request, a restart, the Node-volume guard, a second instance taking over while the # first stops), scripts/failover-smoke.ts (three instances, one killed with SIGKILL while a release # is due, then graceful handoffs under load; #290), scripts/mail-smoke.ts (an invite and a reset -# through Mailpit with STARTTLS and AUTH; #291) and Trivy, which fails the job on a CRITICAL +# through Mailpit with STARTTLS and AUTH; #291), scripts/render-smoke.ts (render_page through +# the Chrome sidecar; #292) and Trivy, which fails the job on a CRITICAL # vulnerability with a fix; # - `smoke-arm64` runs the same smoke test on the arm64 image, on GitHub's native arm64 runner; # - `tag` adds the release tags to the very digest that passed, with `imagetools create`, writes @@ -54,6 +55,7 @@ on: - "scripts/docker-smoke.ts" - "scripts/failover-smoke.ts" - "scripts/mail-smoke.ts" + - "scripts/render-smoke.ts" - "scripts/pack-packages.ts" - "scripts/selfhost-edge-bundle.ts" - "packages/cli/src/selfhost/**" @@ -114,6 +116,7 @@ jobs: docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" config --quiet docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile caddy config --quiet docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile mail config --quiet + docker compose -f deploy/docker/compose.yml --env-file "$RUNNER_TEMP/compose.env" --profile chrome config --quiet - name: Lint the Helm chart run: | helm lint deploy/helm/cloudhal @@ -121,6 +124,8 @@ jobs: helm template t deploy/helm/cloudhal --set httpRoute.enabled=true --set baseUrl=https://studio.example.com --set 'httpRoute.parentRefs[0].name=gw' > /dev/null helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp --set mail.from=cloudhal@example.com --set mail.caConfigMap.name=ca \ | grep -q 'CLOUDHAL_SMTP_CA_FILE' || { echo "::error::the chart's mail values render no CLOUDHAL_SMTP_CA_FILE"; exit 1; } + helm template t deploy/helm/cloudhal --set chrome.enabled=true \ + | grep -q 'value: "http://t-cloudhal-chrome:9222"' || { echo "::error::chrome.enabled renders no CLOUDHAL_BROWSER_URL"; exit 1; } if helm template t deploy/helm/cloudhal --set mail.smtpUrlSecret.name=smtp > /dev/null 2>&1; then echo "::error::mail.smtpUrlSecret without mail.from must fail"; exit 1 fi @@ -264,6 +269,11 @@ jobs: - name: Mail smoke test (Mailpit) timeout-minutes: 10 run: node scripts/mail-smoke.ts --image cloudhal:ci + # render_page (#292): the chrome profile's browser on a network of its own; an agent key calls + # render_page over /mcp and gets a JPEG back. CI only. + - name: render_page smoke test (Chrome sidecar) + timeout-minutes: 10 + run: node scripts/render-smoke.ts --image cloudhal:ci - name: Trivy scan timeout-minutes: 15 uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 diff --git a/AGENTS.md b/AGENTS.md index c3b6c63f..4e63e61b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ node scripts/release-bundle.ts build|verify … # RFC-0046 release bundle: det - `packages/core-ts` — `SiteGraphStore` (CAS on `rev`, snapshots, diff, publish, rollback). Behavioural suite in `src/testing.ts` runs on sqlite and Miniflare D1. `./local` opens the offline store; `seedStarterSite` seeds a demo. `./surfaces` is RFC-0020's generative UI: the catalog (primitives + block types), eval-free surface checks, bindings, repairs, JSON Patch (`patchPage`), `catalogPrompt`; `./interop` converts A2UI v0.9 and json-render to and from surfaces; `./design` is RFC-0021's DESIGN.md lint and guidance. `./fields` is RFC-0041's typed custom fields (definition and value checks, `resolveFields`, `formatFieldValue`, the agents' JSON Schema, the conversion table); `src/fields-operations/` runs rename/retype/localize/remove. `search.ts` is RFC-0019's FTS5 site search (index written with the publish batch; articles, pages, terms and authors, RFC-0029); `search-provider.ts` is RFC-0029's `SearchProvider` (`fts5`, `memory`, `withFallback`), set with `SiteGraphStoreOptions.search`; `search-ai.ts` is the experimental Cloudflare AI Search provider (`hybridProvider`, `searchProviderFromEnv`, `cloudhal.json` `search`, docs/guides/search.md). - `packages/schedules` — RFC-0008: time model (only `temporal-polyfill/implementation`, `now` injected, never `Temporal.Now`), RRULE subset, release model (`rl1:`), automation/run state, taint and budgets, `runDue`; `./sql` is `SqlScheduleStore`, `./engine` the Temporal-free part core-ts and the site Worker use. Worker-safe; conformance suites in `src/testing.ts` on sqlite and Miniflare D1. - `packages/astro-renderer` — `GraphSource` (live/snapshot), `cloudhal()` integration (virtual config + dev route-cache watcher), `.astro` section components (`Surface.astro` for RFC-0020 surfaces; `./surfaces` renders them, `./kit` has the table of contents and reading time; `./fields` and `EntryFields.astro` render typed field values, RFC-0041). `./status-page` is RFC-0043's status pages (`statusPage(state, input) → Response`, served by the Site Worker entry before Astro and by `cloudhal dev` at `/__cloudhal/status/`; the optional `statusPage` theme hook; the catalog in `src/status-strings/` where only `en.ts` is hand-edited and the other languages come from `pnpm i18n:import`). Routes live in starters, not here. -- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard, the first site and the SMTP sender behind `EMAIL` (`smtp-*.ts`, #291: STARTTLS or TLS only; `smtp-client.ts` has no imports because the config embeds it as a Worker module); `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. +- `packages/cli` — the `cloudhal` CLI (`init`, `dev`, `studio`, `mcp`, `deploy`, `push`, `pull`, `export`, `import`, …; every command is in `src/cli/help.ts`, which `cloudhal --help` prints and the docs site's CLI reference is generated from); TS bin run by Node 24 type stripping. `src/cli.ts` parses flags and dispatches through `COMMANDS`, built from `src/cli/commands-{local,remote,content,ops,site}.ts` (a new command is one handler plus one line in `src/cli/help.ts`). `src/archive/` is RFC-0039's `.cloudhal` container (tar, gzip, manifest, limits), read and written by `src/commands/export.ts` and `import*.ts` (`archive-bundle.ts`, `archive-reassemble.ts`); the starter demo archive `test/fixtures/site-archives/starter-blog.cloudhal` is written by `pnpm demo:archive`, and `pnpm check` fails when it is stale. E2E test spawns the bin (Astro disables dev middleware under `VITEST`). Cloudflare tests run both Workers on workerd via wrangler's `createTestHarness`; test files run serially (shared starter caches). `src/commands/deploy/release/` is RFC-0046 §11b's `deploy --release`: the signed key and yank lists (`trust.ts`, the yank memory in `~/.cloudhal/release-trust.json`), the release lookup and download, the theme check against the CLI's starter (`theme-check.ts`; recheck its build-input list on every Astro or Vite major), the build keys of `src/config-build-keys.ts`, extraction and the `no_bundle` wrangler configs; tests use `@cloudhal/release-verify`'s synthetic bundle (`test/fixtures/release-deploy.ts`), never the network. `src/selfhost/` is RFC-0047's self-host image on workerd (`cloudhal selfhost fetch|check|config|secrets|start`): the settings (`_FILE` secrets), the generated Cap'n Proto config (Durable Object `uniqueKey`s are constants, never change them), the bundle check, the Node-volume guard, the first site and the SMTP sender behind `EMAIL` (`smtp-*.ts`, #291: STARTTLS or TLS only; `smtp-client.ts` has no imports because the config embeds it as a Worker module); `browser-sidecar.ts` binds the optional Chrome for `render_page` as `BROWSER_CDP` (#292, `@cloudhal/cloudflare`'s `browser-cdp.ts`); `deploy/docker/workerd/` pins workerd (an npm lockfile Dependabot bumps weekly, ADR-0047; never the Miniflare pin), `scripts/docker-smoke.ts` runs it on SeaweedFS. - `packages/cloudflare` — the admin Worker (`createAdminWorker`); `./playground` is RFC-0036's playground Worker (`createPlaygroundWorker`, the `PlaygroundSite` Durable Object, signed session cookies). Generated entries must import `@cloudhal/cloudflare/workerd-prelude` first (ADR-0012). - `packages/agent-runtime` / `packages/mcp-server` — policy, skills, audit; MCP tools and transports (ADR-0011). `@cloudhal/mcp-server/render` is RFC-0021's `render_page` core: a small DevTools client, the in-page checks and limits; the CLI drives local Chrome with it (`render-chrome.ts`), the admin Worker Browser Rendering (`browser-render.ts`). - `starters/blog` — the theme boundary: `src/pages/[...path].astro`, `src/layouts`, `src/theme.ts`. diff --git a/deploy/docker/.env.example b/deploy/docker/.env.example index d37ea3c8..daaacea1 100644 --- a/deploy/docker/.env.example +++ b/deploy/docker/.env.example @@ -48,5 +48,10 @@ #CLOUDHAL_SMTP_URL=smtp://cloudhal:mailpit@mailpit:1025 #CLOUDHAL_SMTP_CA_FILE=/run/cloudhal-mail/cert.pem +# render_page (the agents' screenshot tool): Chrome's DevTools port. The chrome profile runs one +# (`docker compose --profile chrome up -d`); it opens the site at CLOUDHAL_RENDER_ORIGIN. +#CLOUDHAL_BROWSER_URL=http://chrome:9222 +#CLOUDHAL_RENDER_ORIGIN=http://cloudhal:8788 + # Traces of every Worker invocation to an OTLP/HTTP collector. #OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 diff --git a/deploy/docker/README.md b/deploy/docker/README.md index 069e2228..68bb6d45 100644 --- a/deploy/docker/README.md +++ b/deploy/docker/README.md @@ -17,6 +17,7 @@ The official self-host image, `ghcr.io/cloudhal-dev/cloudhal`, built from each r - **`compose.yml`, `.env.example`, `Caddyfile`:** Cloudhal with SeaweedFS and a one-shot that creates the bucket. - With the `caddy` profile, Caddy proxies both hosts with TLS and sets `CF-Connecting-IP`. - With the `mail` profile, Mailpit catches every message at http://127.0.0.1:8025. It requires STARTTLS, with a certificate the `mail-tls` one-shot makes once. + - With the `chrome` profile, a headless Chrome serves `render_page` (`CLOUDHAL_BROWSER_URL=http://chrome:9222`). It publishes no port and shares a network with Cloudhal only. Build a release: @@ -32,4 +33,4 @@ node scripts/pack-packages.ts deploy/docker/tarballs && pnpm --filter @cloudhal/ `node scripts/docker-smoke.ts --image cloudhal:local` runs what CI runs after every build (`.github/workflows/docker.yml`); `--platform linux/arm64` runs the other architecture where Docker can. -`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. So does `scripts/mail-smoke.ts` (#291), which sends an invite and a password reset through Mailpit with STARTTLS and AUTH required. +`scripts/failover-smoke.ts` is the cluster failover test (#290): three instances, one killed with SIGKILL while a release is due, then graceful handoffs under load. It runs in CI only and refuses to start anywhere else. So does `scripts/mail-smoke.ts` (#291), which sends an invite and a password reset through Mailpit with STARTTLS and AUTH required, and `scripts/render-smoke.ts` (#292), which calls `render_page` through the Chrome sidecar. diff --git a/deploy/docker/compose.yml b/deploy/docker/compose.yml index 6fac14fd..e8717e93 100644 --- a/deploy/docker/compose.yml +++ b/deploy/docker/compose.yml @@ -7,6 +7,8 @@ # (Studio) and CLOUDHAL_SITE_URL (the site) # docker compose --profile mail up -d + Mailpit, which catches every mail Cloudhal sends # (http://127.0.0.1:8025; see the mailpit service) +# docker compose --profile chrome up -d + a headless Chrome for render_page (see the chrome +# service) # Every instance of an installation needs the same .env; this file runs one instance (the cluster # of one). More instances: deploy/swarm or deploy/helm. x-store: &store @@ -59,6 +61,11 @@ services: CLOUDHAL_SMTP_CA_FILE: ${CLOUDHAL_SMTP_CA_FILE:-} CLOUDHAL_MAIL_FROM: ${CLOUDHAL_MAIL_FROM:-} CLOUDHAL_MAIL_FROM_NAME: ${CLOUDHAL_MAIL_FROM_NAME:-} + # render_page: Chrome's DevTools port (the chrome profile: http://chrome:9222), off when empty. + # The browser opens the site at CLOUDHAL_RENDER_ORIGIN (default http://cloudhal:8788). + CLOUDHAL_BROWSER_URL: ${CLOUDHAL_BROWSER_URL:-} + CLOUDHAL_RENDER_ORIGIN: ${CLOUDHAL_RENDER_ORIGIN:-} + networks: [default, render] volumes: - cloudhal-data:/data # The mail profile's certificate (empty without the profile). @@ -156,6 +163,24 @@ services: volumes: - mail-tls:/tls:ro + # The chrome profile: a headless Chrome for render_page (RFC-0047 §6). It publishes no port and + # sits on its own network with Cloudhal only, so it cannot reach the store; Cloudhal opens in it + # only a page's own signed preview link, one browser context per render. Set in .env: + # CLOUDHAL_BROWSER_URL=http://chrome:9222 + chrome: + profiles: [chrome] + image: chromedp/headless-shell:159.0.8154.34@sha256:5bb2432d550896f4cb4266c367c48d82e6e2ed61f71ced68687bb175d62ce312 + restart: unless-stopped + shm_size: 512m + cap_drop: [ALL] + security_opt: ["no-new-privileges:true"] + networks: [render] + +networks: + default: + # Cloudhal and the chrome profile's browser, nothing else. + render: + volumes: # Each instance's Durable Object files (they replicate through the store) and the v2 marker. cloudhal-data: diff --git a/deploy/helm/cloudhal/README.md b/deploy/helm/cloudhal/README.md index 58299dd9..3223f044 100644 --- a/deploy/helm/cloudhal/README.md +++ b/deploy/helm/cloudhal/README.md @@ -71,6 +71,14 @@ helm upgrade cloudhal deploy/helm/cloudhal --reuse-values \ - For a relay whose certificate no browser trusts, put its CA in a ConfigMap and set `mail.caConfigMap.name` (key `ca.pem` by default). - The pods connect to the server themselves. Under an egress NetworkPolicy of your own, allow its port. +## Screenshots for agents + +`render_page` needs a browser. `--set chrome.enabled=true` runs a headless Chrome in the release: +- a Deployment and a Service, with no Ingress; +- a NetworkPolicy that admits only the release's instances to its DevTools port. + +The instances open in it only a page's signed preview link, at `http://:8788` (`chrome.renderOrigin`). `chrome.url` names a browser of your own instead. + ## Upgrades ```bash diff --git a/deploy/helm/cloudhal/templates/chrome.yaml b/deploy/helm/cloudhal/templates/chrome.yaml new file mode 100644 index 00000000..c7ba9162 --- /dev/null +++ b/deploy/helm/cloudhal/templates/chrome.yaml @@ -0,0 +1,95 @@ +{{- if .Values.chrome.enabled }} +{{- $fullname := include "cloudhal.fullname" . }} +# A headless Chrome for render_page (RFC-0047 §6, #292). It has no Ingress or route, and only this +# release's instances may reach its DevTools port. They open in it only a page's own signed +# preview link, at http://:, one browser context per render. +apiVersion: apps/v1 +kind: Deployment +metadata: + name: {{ $fullname }}-chrome + labels: + {{- include "cloudhal.labels" . | nindent 4 }} + app.kubernetes.io/component: chrome +spec: + replicas: 1 + selector: + matchLabels: + app.kubernetes.io/name: {{ .Chart.Name }} + app.kubernetes.io/instance: {{ .Release.Name }} + app.kubernetes.io/component: chrome + template: + metadata: + labels: + {{- include "cloudhal.labels" . | nindent 8 }} + app.kubernetes.io/component: chrome + spec: + enableServiceLinks: false + automountServiceAccountToken: false + securityContext: + seccompProfile: + type: RuntimeDefault + containers: + - name: chrome + image: "{{ .Values.chrome.image.repository }}:{{ .Values.chrome.image.tag }}" + ports: + - name: devtools + containerPort: 9222 + readinessProbe: + tcpSocket: { port: devtools } + periodSeconds: 5 + resources: + {{- toYaml .Values.chrome.resources | nindent 12 }} + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: [ALL] + volumeMounts: + - name: shm + mountPath: /dev/shm + volumes: + - name: shm + emptyDir: + medium: Memory + sizeLimit: 512Mi +--- +apiVersion: v1 +kind: Service +metadata: + name: {{ $fullname }}-chrome + labels: + {{- include "cloudhal.labels" . | nindent 4 }} + app.kubernetes.io/component: chrome +spec: + selector: + app.kubernetes.io/name: {{ .Chart.Name }} + app.kubernetes.io/instance: {{ .Release.Name }} + app.kubernetes.io/component: chrome + ports: + - name: devtools + port: 9222 + targetPort: devtools +{{- if .Values.networkPolicy.enabled }} +--- +# Whoever reaches the DevTools port drives the browser: only this release's instances may. +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ $fullname }}-chrome + labels: + {{- include "cloudhal.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + app.kubernetes.io/name: {{ .Chart.Name }} + app.kubernetes.io/instance: {{ .Release.Name }} + app.kubernetes.io/component: chrome + policyTypes: [Ingress] + ingress: + - from: + - podSelector: + matchLabels: + {{- include "cloudhal.selector" . | nindent 14 }} + ports: + - port: 9222 +{{- end }} +{{- end }} diff --git a/deploy/helm/cloudhal/templates/statefulset.yaml b/deploy/helm/cloudhal/templates/statefulset.yaml index 2bc56724..2f050dd8 100644 --- a/deploy/helm/cloudhal/templates/statefulset.yaml +++ b/deploy/helm/cloudhal/templates/statefulset.yaml @@ -89,6 +89,12 @@ spec: value: "/etc/cloudhal/smtp-ca/{{ $.Values.mail.caConfigMap.key }}" {{- end }} {{- end }} + {{- if or .Values.chrome.enabled .Values.chrome.url }} + - name: CLOUDHAL_BROWSER_URL + value: {{ .Values.chrome.url | default (printf "http://%s-chrome:9222" $fullname) | quote }} + - name: CLOUDHAL_RENDER_ORIGIN + value: {{ .Values.chrome.renderOrigin | default (printf "http://%s:%v" $fullname .Values.service.sitePort) | quote }} + {{- end }} {{- with .Values.extraEnv }} {{- toYaml . | nindent 12 }} {{- end }} diff --git a/deploy/helm/cloudhal/values.yaml b/deploy/helm/cloudhal/values.yaml index 500d7ebe..621fc3cf 100644 --- a/deploy/helm/cloudhal/values.yaml +++ b/deploy/helm/cloudhal/values.yaml @@ -103,6 +103,24 @@ mail: name: "" key: ca.pem +# render_page (the agents' screenshot tool) through a headless Chrome. `enabled` runs one in this +# release, reachable only from its instances; `url` names one of your own instead +# (http://chrome.tools:9222, Chrome's DevTools port). The instances open in it only a page's own +# signed preview link, at `renderOrigin` (default: this release's Service, http://:8788). +chrome: + enabled: false + url: "" + renderOrigin: "" + image: + repository: chromedp/headless-shell + tag: "159.0.8154.34@sha256:5bb2432d550896f4cb4266c367c48d82e6e2ed61f71ced68687bb175d62ce312" + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + memory: 1Gi + # Extra environment for the Cloudhal container (CLOUDHAL_AUTOMATIONS, …). extraEnv: [] diff --git a/deploy/swarm/README.md b/deploy/swarm/README.md index f6b03497..875fcf15 100644 --- a/deploy/swarm/README.md +++ b/deploy/swarm/README.md @@ -43,4 +43,14 @@ ``` Then add `cloudhal_smtp_url` to the `cloudhal` service's `secrets` and to the file's `secrets:` list (`external: true`), and set `CLOUDHAL_SMTP_URL_FILE: /run/secrets/cloudhal_smtp_url` and `CLOUDHAL_MAIL_FROM` in its `environment`. `smtp://` is STARTTLS and `smtps://` TLS from the start; a server without STARTTLS is refused. Without the secret, mail stays off. +- **Screenshots (`render_page`):** add a headless Chrome to the stack, on the stack's network and with no published port, and point the instances at it: + + ```yaml + chrome: + image: chromedp/headless-shell:159.0.8154.34 + networks: [cloudhal] + deploy: { replicas: 1 } + ``` + + Add `CLOUDHAL_BROWSER_URL: http://chrome:9222` to the `cloudhal` service's `environment`. The browser opens only the page's signed preview link, at `http://cloudhal:8788` (`CLOUDHAL_RENDER_ORIGIN`). Pin the image by digest as `deploy/docker/compose.yml` does. - **External store:** to use an external S3 store, set `CLOUDHAL_S3_ENDPOINT` and the bucket, put its keys in the two `cloudhal_aws_*` secrets, and remove the `seaweedfs` service. diff --git a/docs/guides/self-host.md b/docs/guides/self-host.md index 1a53bc84..d2e9fb20 100644 --- a/docs/guides/self-host.md +++ b/docs/guides/self-host.md @@ -111,6 +111,8 @@ location / { | `CLOUDHAL_SMTP_URL` | The SMTP server for invites and password resets ([mail](#mail)): `smtp://user:password@host:587` (STARTTLS) or `smtps://…:465`. `_FILE` works too. Unset, mail is off. | | `CLOUDHAL_MAIL_FROM`, `CLOUDHAL_MAIL_FROM_NAME` | The one sender address mail goes out from, and its display name. The address is required with `CLOUDHAL_SMTP_URL`. | | `CLOUDHAL_SMTP_CA_FILE` | PEM certificates to trust besides the browser CAs, for a relay with a private CA. | +| `CLOUDHAL_BROWSER_URL` | Chrome's DevTools port for `render_page` ([screenshots](#screenshots-for-agents)), such as `http://chrome:9222`. Unset, the tool reports itself unavailable. | +| `CLOUDHAL_RENDER_ORIGIN` | Where that Chrome reaches the site, the same on every instance. Default: `http://cloudhal:`. | | `OTEL_EXPORTER_OTLP_ENDPOINT` | Traces of every Worker invocation to an OTLP/HTTP collector. | | `CLOUDHAL_BIND`, `CLOUDHAL_PORT`, `CLOUDHAL_SITE_PORT` | Compose only: the host address and ports for Studio (8787) and the site (8788). | @@ -197,6 +199,24 @@ docker compose --profile mail up -d CI sends an invite and a password reset through Mailpit with every image, with STARTTLS and SMTP AUTH required ([`scripts/mail-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/mail-smoke.ts)). +## Screenshots for agents + +`render_page` lets an agent look at the page it built: screenshots at several widths and automatic checks. It needs a browser, and the image carries none. Point `CLOUDHAL_BROWSER_URL` at a headless Chrome's DevTools port, and the admin Worker drives it, as Cloudflare's Browser Rendering does on Cloudflare. + +- **Reachable from the instances only.** The DevTools port lets anyone who reaches it drive the browser, so never publish it. The compose file's `chrome` profile publishes no port and puts the browser on a network of its own, shared with Cloudhal and nothing else, so it cannot reach the store. The Helm chart adds a NetworkPolicy that admits only the release's instances. +- **One browser context per render**, closed after it. The browser itself is shared and stays up. +- **Only the page's own preview.** The browser opens nothing but the page's signed preview link, at `CLOUDHAL_RENDER_ORIGIN` (default `http://cloudhal:8788`, the compose and Swarm service name). That works for a site without a domain too. + +```bash +CLOUDHAL_BROWSER_URL=http://chrome:9222 +``` + +```bash +docker compose --profile chrome up -d +``` + +On Kubernetes, set `chrome.enabled=true` (or `chrome.url` for a browser of your own). Swarm's README shows the service to add. CI calls `render_page` through the sidecar with every image ([`scripts/render-smoke.ts`](https://github.com/cloudhal-dev/cloudhal/blob/main/scripts/render-smoke.ts)). + ## Upgrades The image carries the same version as the npm packages and the release bundle. Tags are `X.Y.Z`, `X.Y` and `latest`; in production, pin `X.Y` (`CLOUDHAL_TAG=0.11`). @@ -245,7 +265,6 @@ For one site rather than the installation, `cloudhal export` writes a portable ` ## Limits -- **`render_page`** (the agents' screenshot tool) needs a browser, which the image does not carry, so the tool reports itself unavailable. A Chrome sidecar is planned. - **One site** per installation for now (RFC-0047 decision 2). - **No edge cache.** Every page renders on request. Put a CDN in front if you need one. A shared cache with purge on publish is a later step. - **Analytics** (Cloudflare Analytics Engine) is not available when self-hosting. diff --git a/docs/rfcs/0047-self-host-on-workerd.md b/docs/rfcs/0047-self-host-on-workerd.md index d4bc35fb..5f544456 100644 --- a/docs/rfcs/0047-self-host-on-workerd.md +++ b/docs/rfcs/0047-self-host-on-workerd.md @@ -144,7 +144,7 @@ The site Worker needs the site's id in its config (`CLOUDHAL_SITE_ID`). Open que | `ANALYTICS` analytics engine, `ANALYTICS_SQL` | absent (optional bindings) | analytics off on self-host for now | | `ANALYTICS_RL`, `COMMENTS_RL` ratelimit | `/workerd/ratelimit.js` | counts are per process, not per cluster; acceptable for these soft limits | | `EMAIL` send_email | **new:** an SMTP sender Worker (`CLOUDHAL_SMTP_URL`) behind the same binding | *Done (#291):* the `smtp` Worker's default entrypoint has the binding's `send` (JS RPC), over STARTTLS or implicit TLS only, through its own `smtp-network` | -| `BROWSER` | **new:** optional Chrome sidecar over CDP | follow-up PR, removes the "no `render_page`" limit | +| `BROWSER` | **new:** optional Chrome sidecar over CDP | *Done (#292):* `CLOUDHAL_BROWSER_URL` becomes an `ExternalServer` bound to the admin Worker as `BROWSER_CDP`. `devtoolsRenderer` drives it with the shared `cdpSession`, one browser context per render. The browser opens only the page's signed preview link, at `CLOUDHAL_RENDER_ORIGIN` | | `AI` | REST with `CLOUDHAL_AI_TOKEN`, as today | unchanged | ### 7. Health, readiness and shutdown diff --git a/packages/cli/src/selfhost/browser-sidecar.ts b/packages/cli/src/selfhost/browser-sidecar.ts new file mode 100644 index 00000000..46974d5b --- /dev/null +++ b/packages/cli/src/selfhost/browser-sidecar.ts @@ -0,0 +1,75 @@ +/** + * #292: `render_page` through an optional Chrome sidecar (RFC-0047 §6). With + * `CLOUDHAL_BROWSER_URL` (its DevTools HTTP port, `http://chrome:9222`), the generated config gets + * an `ExternalServer` to it and the admin Worker a `BROWSER_CDP` binding; `@cloudhal/cloudflare`'s + * `devtoolsRenderer` drives it with the shared `cdpSession`, one browser context per render. + * + * The sidecar reaches the site on the private network at `CLOUDHAL_RENDER_ORIGIN` (default + * `http://cloudhal:`, the compose and Swarm service name). It is the same on every + * instance, as the config must be (RFC-0047 §2, invariant 2), and `render_page` opens there only + * the page's own signed preview link. + */ + +export interface BrowserSettings { + /** `host:port` of the sidecar's DevTools HTTP endpoint. */ + readonly address: string; + /** The origin the sidecar opens the site at. */ + readonly renderOrigin: string; +} + +type Env = Readonly>; + +function plainUrl(value: string, name: string, problems: string[]): URL | undefined { + let url: URL; + try { + url = new URL(value.trim()); + } catch { + problems.push(`${name} is not a URL`); + return undefined; + } + if ((url.pathname !== "" && url.pathname !== "/") || url.search || url.hash || url.username) { + problems.push(`${name} takes a scheme, a host and a port only`); + return undefined; + } + return url; +} + +/** The sidecar settings, or `undefined` when `CLOUDHAL_BROWSER_URL` is unset. */ +export function readBrowserSettings( + env: Env, + sitePort: number, + problems: string[], +): BrowserSettings | undefined { + const raw = env.CLOUDHAL_BROWSER_URL?.trim(); + if (!raw) return undefined; + const url = plainUrl(raw, "CLOUDHAL_BROWSER_URL", problems); + if (url && url.protocol !== "http:") + problems.push( + "CLOUDHAL_BROWSER_URL is Chrome's DevTools port over http:// (http://chrome:9222)", + ); + const originRaw = env.CLOUDHAL_RENDER_ORIGIN?.trim() || `http://cloudhal:${sitePort}`; + const origin = plainUrl(originRaw, "CLOUDHAL_RENDER_ORIGIN", problems); + if (origin && origin.protocol !== "http:" && origin.protocol !== "https:") + problems.push("CLOUDHAL_RENDER_ORIGIN is an http:// or https:// origin"); + if (!url || !origin) return undefined; + return { address: `${url.hostname}:${url.port || "9222"}`, renderOrigin: origin.origin }; +} + +const q = (s: string) => JSON.stringify(s); + +/** Lets the admin Worker take DevTools messages above 1 MiB (a tall page's screenshot). */ +export const BROWSER_FLAGS = ["increase_websocket_message_size"] as const; + +/** The admin Worker's bindings for the sidecar. */ +export function browserAdminBindings(b: BrowserSettings | undefined): string[] { + if (!b) return []; + return [ + `(name = "BROWSER_CDP", service = "browser")`, + `(name = "CLOUDHAL_RENDER_ORIGIN", text = ${q(b.renderOrigin)})`, + ]; +} + +/** The sidecar as an `ExternalServer`: only the admin Worker is bound to it. */ +export function browserServices(b: BrowserSettings | undefined): string[] { + return b ? [`(name = "browser", external = (address = ${q(b.address)}, http = ()))`] : []; +} diff --git a/packages/cli/src/selfhost/settings.ts b/packages/cli/src/selfhost/settings.ts index 38628fdd..9713004b 100644 --- a/packages/cli/src/selfhost/settings.ts +++ b/packages/cli/src/selfhost/settings.ts @@ -7,6 +7,7 @@ */ import { readFileSync } from "node:fs"; import { resolveAdvertise } from "./advertise.ts"; +import { type BrowserSettings, readBrowserSettings } from "./browser-sidecar.ts"; import { type MailSettings, readMailSettings } from "./smtp-settings.ts"; /** The manifest's secrets (RFC-0046 `bindingTemplates.*.secrets`) the image requires. */ @@ -52,6 +53,8 @@ export interface SelfhostSettings { readonly adminVars: Readonly>; /** The SMTP sender behind `EMAIL` (#291), when `CLOUDHAL_SMTP_URL` is set. */ readonly mail: MailSettings | undefined; + /** The Chrome sidecar for `render_page` (#292), when `CLOUDHAL_BROWSER_URL` is set. */ + readonly browser: BrowserSettings | undefined; } export type Env = Readonly>; @@ -134,6 +137,8 @@ export function readSettings( ): SelfhostSettings { const found = problems(env); const mail = readMailSettings(env, found, read); + const sitePort = port(env, "CLOUDHAL_SITE_PORT", 8788); + const browser = readBrowserSettings(env, sitePort, found); if (found.length > 0) throw new Error(`the self-host settings are incomplete:\n - ${found.join("\n - ")}`); const prefix = (env.CLOUDHAL_S3_PREFIX ?? "").replace(/^\/+/, ""); @@ -159,10 +164,11 @@ export function readSettings( dataDir: env.CLOUDHAL_DATA_DIR || "/data", ports: { studio: port(env, "CLOUDHAL_PORT", 8787), - site: port(env, "CLOUDHAL_SITE_PORT", 8788), + site: sitePort, }, otlp: env.OTEL_EXPORTER_OTLP_ENDPOINT ? hostPort(env.OTEL_EXPORTER_OTLP_ENDPOINT) : undefined, adminVars, mail, + browser, }; } diff --git a/packages/cli/src/selfhost/workerd-config.ts b/packages/cli/src/selfhost/workerd-config.ts index 4ac3cf14..269bc55f 100644 --- a/packages/cli/src/selfhost/workerd-config.ts +++ b/packages/cli/src/selfhost/workerd-config.ts @@ -9,6 +9,7 @@ */ import path from "node:path"; import type { ReleaseManifest } from "@cloudhal/release-verify"; +import { BROWSER_FLAGS, browserAdminBindings, browserServices } from "./browser-sidecar.ts"; import { FRONT_WORKER_SOURCE } from "./front-worker.ts"; import type { SelfhostSettings } from "./settings.ts"; import { smtpAdminBindings, smtpServices } from "./smtp-service.ts"; @@ -82,9 +83,13 @@ function builtins(cron: string): string[] { function worker( input: ConfigInput, role: "site" | "admin", - extra: { bindings: string[]; objects?: string[] }, + extra: { bindings: string[]; objects?: string[]; flags?: readonly string[] }, ): string { - const { compatibilityDate, compatibilityFlags } = input.manifest.runtime; + const { compatibilityDate } = input.manifest.runtime; + const compatibilityFlags = [ + ...input.manifest.runtime.compatibilityFlags, + ...(extra.flags ?? []).filter((f) => !input.manifest.runtime.compatibilityFlags.includes(f)), + ]; const secrets = input.manifest.bindingTemplates[role].secrets.map(env); const parts = [ `compatibilityDate = ${q(compatibilityDate)}`, @@ -144,7 +149,9 @@ export function workerdConfig(input: ConfigInput): string { siteId, ...Object.entries(s.adminVars).map(([k, v]) => text(k, v)), ...smtpAdminBindings(s), + ...browserAdminBindings(s.browser), ], + ...(s.browser ? { flags: BROWSER_FLAGS } : {}), }); const site = worker(input, "site", { bindings: [ @@ -164,6 +171,7 @@ export function workerdConfig(input: ConfigInput): string { front("site", s), front("admin", s), ...smtpServices(s), + ...browserServices(s.browser), ...(s.otlp ? [`(name = "otlp", external = (address = ${q(s.otlp)}, http = ()))`] : []), ].map((x) => x.replaceAll("{DATA}", s.dataDir)); const bucket = `s3://${s.s3.bucket}/${s.s3.prefix}cluster`; diff --git a/packages/cli/test/selfhost-browser.test.ts b/packages/cli/test/selfhost-browser.test.ts new file mode 100644 index 00000000..66afef02 --- /dev/null +++ b/packages/cli/test/selfhost-browser.test.ts @@ -0,0 +1,68 @@ +/** #292: the self-host settings and config of the Chrome sidecar for `render_page`. */ +import { describe, expect, it } from "vitest"; +import { + BROWSER_FLAGS, + browserAdminBindings, + browserServices, +} from "../src/selfhost/browser-sidecar.ts"; +import { secretsEnv } from "../src/selfhost/secrets.ts"; +import { readSettings } from "../src/selfhost/settings.ts"; + +const ENV: Record = { + ...Object.fromEntries( + secretsEnv() + .split("\n") + .filter((l) => l && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ), + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", +}; + +describe("the Chrome sidecar settings", () => { + it("is off without CLOUDHAL_BROWSER_URL", () => { + const s = readSettings(ENV); + expect(s.browser).toBeUndefined(); + expect(browserAdminBindings(s.browser)).toEqual([]); + expect(browserServices(s.browser)).toEqual([]); + }); + + it("binds the admin Worker to the sidecar and opens the site at one origin for every instance", () => { + const s = readSettings({ ...ENV, CLOUDHAL_BROWSER_URL: "http://chrome:9222" }); + expect(s.browser).toEqual({ address: "chrome:9222", renderOrigin: "http://cloudhal:8788" }); + expect(browserServices(s.browser)).toEqual([ + '(name = "browser", external = (address = "chrome:9222", http = ()))', + ]); + expect(browserAdminBindings(s.browser)).toEqual([ + '(name = "BROWSER_CDP", service = "browser")', + '(name = "CLOUDHAL_RENDER_ORIGIN", text = "http://cloudhal:8788")', + ]); + expect(BROWSER_FLAGS).toEqual(["increase_websocket_message_size"]); + const k8s = readSettings({ + ...ENV, + CLOUDHAL_BROWSER_URL: "http://ch-cloudhal-chrome", + CLOUDHAL_RENDER_ORIGIN: "http://ch-cloudhal:8788/", + CLOUDHAL_SITE_PORT: "9000", + }); + expect(k8s.browser).toEqual({ + address: "ch-cloudhal-chrome:9222", + renderOrigin: "http://ch-cloudhal:8788", + }); + }); + + it("refuses anything but a DevTools http:// address and an http(s) origin", () => { + expect(() => readSettings({ ...ENV, CLOUDHAL_BROWSER_URL: "ws://chrome:9222" })).toThrow( + /DevTools port over http/, + ); + expect(() => + readSettings({ ...ENV, CLOUDHAL_BROWSER_URL: "http://chrome:9222/json/version" }), + ).toThrow(/a scheme, a host and a port only/); + expect(() => + readSettings({ + ...ENV, + CLOUDHAL_BROWSER_URL: "http://chrome:9222", + CLOUDHAL_RENDER_ORIGIN: "file://x", + }), + ).toThrow(/CLOUDHAL_RENDER_ORIGIN/); + }); +}); diff --git a/packages/cloudflare/src/admin-worker.ts b/packages/cloudflare/src/admin-worker.ts index b50eb060..bd7a9ce4 100644 --- a/packages/cloudflare/src/admin-worker.ts +++ b/packages/cloudflare/src/admin-worker.ts @@ -63,7 +63,8 @@ import { SqlScheduleStore } from "@cloudhal/schedules/sql"; import { migrate, migrations, type SqlDriver } from "@cloudhal/storage"; import { D1Driver } from "@cloudhal/storage/d1"; import { R2BlobStore } from "@cloudhal/storage/r2"; -import { type BrowserBinding, browserRenderingRenderer } from "./browser-render.ts"; +import { adminRender, type DevtoolsBinding } from "./browser-cdp.ts"; +import type { BrowserBinding } from "./browser-render.ts"; import { type BuildRoomsEnv, buildRoomClass, createDurableBuildHub } from "./build-rooms.ts"; import { adminComments, type CommentsEnv, commentsOn, flushCommentPurges } from "./comments.ts"; import { featureRoute, type SiteConfirmations, siteSupport } from "./features.ts"; @@ -110,6 +111,10 @@ export interface AdminEnv extends CommentsEnv, SchedulerEnv, MailEnv, BuildRooms CLOUDHAL_ANALYTICS_DEFAULTS?: string; /** Cloudflare Browser Rendering for `render_page` (RFC-0021 §4); absent: `render_unavailable`. */ BROWSER?: BrowserBinding; + /** A Chrome over its DevTools port (the self-host sidecar, RFC-0047 §6), when there is no `BROWSER`. */ + BROWSER_CDP?: DevtoolsBinding; + /** Where that Chrome reaches the site: `render_page` opens the signed preview link there. */ + CLOUDHAL_RENDER_ORIGIN?: string; /** `off` keeps `render_page` unavailable even with a `BROWSER` binding. */ CLOUDHAL_RENDER?: string; /** `off` turns the OAuth authorization server for remote MCP clients off (RFC-0044 §10). */ @@ -504,10 +509,8 @@ export function createAdminWorker(options: AdminWorkerOptions = {}) { // fetch_asset_url never reaches this Worker's own host (Studio, API, purge); each site's // domains are refused too. Workers cannot pin DNS: see `workersTransport` (RFC-0004 §5.7). media: { blockedHosts: [url.hostname] }, - // RFC-0021 §4: render_page opens the preview link in Browser Rendering. - ...(env.BROWSER && env.CLOUDHAL_RENDER !== "off" - ? { render: { renderer: browserRenderingRenderer(env.BROWSER) } } - : {}), + // RFC-0021 §4: render_page opens the preview link in Browser Rendering or a sidecar. + ...adminRender(env), }, ...(env.CLOUDHAL_PREVIEW_SECRET ? { preview: { secret: env.CLOUDHAL_PREVIEW_SECRET } } diff --git a/packages/cloudflare/src/browser-cdp.ts b/packages/cloudflare/src/browser-cdp.ts new file mode 100644 index 00000000..24f61dc7 --- /dev/null +++ b/packages/cloudflare/src/browser-cdp.ts @@ -0,0 +1,98 @@ +/** + * `render_page` with a Chrome of one's own (RFC-0047 §6, #292): the self-host image's Chrome + * sidecar, reached through the admin Worker's `BROWSER_CDP` service binding (an `ExternalServer` + * to its DevTools port). Each session opens one DevTools socket to the running browser and one + * browser context in it (`cdpSession`), and closes both; the browser itself is shared and never + * closed. Chrome answers its DevTools HTTP only for `Host: localhost` or an address, so every + * request names `localhost`; the binding delivers it to the sidecar whatever the URL says. + */ +import { + type CdpSocket, + cdpSession, + type PageRenderer, + RenderError, +} from "@cloudhal/mcp-server/render"; +import type { RenderDeps } from "@cloudhal/mcp-server/tools"; +import { type BrowserBinding, browserRenderingRenderer } from "./browser-render.ts"; + +/** A service binding to the browser's DevTools HTTP port. */ +export interface DevtoolsBinding { + fetch(input: string, init?: RequestInit): Promise; +} + +const HOST = "http://localhost"; + +/** The path of the browser's own DevTools socket, from `/json/version`. */ +export function browserSocketPath(version: unknown): string { + const url = (version as { webSocketDebuggerUrl?: unknown } | null)?.webSocketDebuggerUrl; + if (typeof url !== "string") throw new RenderError("the browser named no DevTools socket"); + const path = new URL(url).pathname; + if (!path.startsWith("/devtools/browser/")) + throw new RenderError("the browser's DevTools socket is not a browser target"); + return path; +} + +/** A Workers WebSocket as a `CdpSocket` (DevTools sends text frames). */ +export function devtoolsSocket(ws: WebSocket): CdpSocket { + return { + send: (m) => ws.send(m), + onMessage: (l) => + ws.addEventListener("message", (e) => { + if (typeof e.data === "string") l(e.data); + }), + onClose: (l) => ws.addEventListener("close", () => l()), + close: () => { + try { + ws.close(); + } catch { + // already closed + } + }, + }; +} + +export function devtoolsRenderer(binding: DevtoolsBinding): PageRenderer { + return { + async session() { + const version = await binding + .fetch(`${HOST}/json/version`, { signal: AbortSignal.timeout(10_000) }) + .catch((e: Error) => { + throw new RenderError(`could not reach the browser: ${e.message}`); + }); + if (version.status !== 200) + throw new RenderError(`the browser answered ${version.status} for /json/version`); + const path = browserSocketPath(await version.json()); + const upgraded = await binding.fetch(`${HOST}${path}`, { headers: { Upgrade: "websocket" } }); + const ws = (upgraded as Response & { webSocket?: WebSocket | null }).webSocket; + if (!ws) throw new RenderError(`the browser did not open a socket (${upgraded.status})`); + (ws as WebSocket & { accept(): void }).accept(); + return cdpSession(devtoolsSocket(ws)); + }, + }; +} + +/** The bindings `render_page` can use (RFC-0021 §4; RFC-0047 §6). */ +export interface RenderEnv { + /** Cloudflare Browser Rendering. */ + BROWSER?: BrowserBinding; + /** A Chrome of one's own over its DevTools port (the self-host sidecar). */ + BROWSER_CDP?: DevtoolsBinding; + /** Where that Chrome reaches the site (`http://cloudhal:8788`). */ + CLOUDHAL_RENDER_ORIGIN?: string; + /** `off` keeps `render_page` unavailable whatever the bindings. */ + CLOUDHAL_RENDER?: string; +} + +/** `render_page`'s deps for the admin Worker: Browser Rendering first, else the sidecar. */ +export function adminRender(env: RenderEnv): { render?: RenderDeps } { + if (env.CLOUDHAL_RENDER === "off") return {}; + if (env.BROWSER) return { render: { renderer: browserRenderingRenderer(env.BROWSER) } }; + if (env.BROWSER_CDP) + return { + render: { + renderer: devtoolsRenderer(env.BROWSER_CDP), + ...(env.CLOUDHAL_RENDER_ORIGIN ? { origin: env.CLOUDHAL_RENDER_ORIGIN } : {}), + }, + }; + return {}; +} diff --git a/packages/cloudflare/test/browser-cdp.test.ts b/packages/cloudflare/test/browser-cdp.test.ts new file mode 100644 index 00000000..258ffc53 --- /dev/null +++ b/packages/cloudflare/test/browser-cdp.test.ts @@ -0,0 +1,97 @@ +/** RFC-0047 §6, #292: render_page through a Chrome of one's own (the self-host sidecar). */ +import { describe, expect, it } from "vitest"; +import { + adminRender, + browserSocketPath, + type DevtoolsBinding, + devtoolsRenderer, +} from "../src/browser-cdp.ts"; + +/** A DevTools browser socket that answers every command; records what it was sent. */ +function fakeBrowser() { + const sent: { method: string; params?: Record }[] = []; + const requests: { url: string; upgrade: string | null }[] = []; + const listeners: Record void)[]> = {}; + const ws = { + accepted: false, + accept() { + this.accepted = true; + }, + send(m: string) { + const msg = JSON.parse(m) as { id: number; method: string; params?: Record }; + sent.push({ method: msg.method, ...(msg.params ? { params: msg.params } : {}) }); + const result = + msg.method === "Target.createBrowserContext" ? { browserContextId: "ctx1" } : {}; + queueMicrotask(() => { + for (const l of listeners.message ?? []) + l({ data: JSON.stringify({ id: msg.id, result }) }); + }); + }, + close() { + for (const l of listeners.close ?? []) l({}); + }, + addEventListener(type: string, l: (e: { data?: unknown }) => void) { + listeners[type] = [...(listeners[type] ?? []), l]; + }, + }; + const binding: DevtoolsBinding = { + async fetch(url, init) { + const upgrade = new Headers(init?.headers).get("upgrade"); + requests.push({ url, upgrade }); + if (url.endsWith("/json/version")) + return Response.json({ + Browser: "HeadlessChrome/140", + webSocketDebuggerUrl: "ws://localhost/devtools/browser/abc-123", + }); + const res = new Response(null); + Object.defineProperty(res, "webSocket", { value: ws }); + return res; + }, + }; + return { binding, ws, sent, requests }; +} + +describe("the sidecar renderer", () => { + it("opens one browser context per session over Host: localhost, and never closes the browser", async () => { + const b = fakeBrowser(); + const session = await devtoolsRenderer(b.binding).session(); + expect(b.requests).toEqual([ + { url: "http://localhost/json/version", upgrade: null }, + { url: "http://localhost/devtools/browser/abc-123", upgrade: "websocket" }, + ]); + expect(b.ws.accepted).toBe(true); + expect(b.sent[0]).toEqual({ + method: "Target.createBrowserContext", + params: { disposeOnDetach: true }, + }); + await session.close(); + expect(b.sent.map((s) => s.method)).toEqual([ + "Target.createBrowserContext", + "Target.disposeBrowserContext", + ]); + }); + + it("accepts only a browser target's socket path", () => { + expect( + browserSocketPath({ webSocketDebuggerUrl: "ws://0.0.0.0:9222/devtools/browser/x" }), + ).toBe("/devtools/browser/x"); + expect(() => browserSocketPath({ webSocketDebuggerUrl: "ws://h/devtools/page/x" })).toThrow( + /not a browser target/, + ); + expect(() => browserSocketPath({})).toThrow(/no DevTools socket/); + }); + + it("is chosen when there is no Browser Rendering, with the render origin", () => { + const b = fakeBrowser(); + const rendering = { fetch: b.binding.fetch }; + expect(adminRender({})).toEqual({}); + expect(adminRender({ BROWSER_CDP: b.binding, CLOUDHAL_RENDER: "off" })).toEqual({}); + expect( + adminRender({ BROWSER_CDP: b.binding, CLOUDHAL_RENDER_ORIGIN: "http://cloudhal:8788" }).render + ?.origin, + ).toBe("http://cloudhal:8788"); + const both = adminRender({ BROWSER: rendering, BROWSER_CDP: b.binding }); + expect(both.render?.origin).toBeUndefined(); + expect(both.render?.renderer).toBeDefined(); + }); +}); diff --git a/packages/core-ts/src/preview-token.ts b/packages/core-ts/src/preview-token.ts index d05d787d..2a800dba 100644 --- a/packages/core-ts/src/preview-token.ts +++ b/packages/core-ts/src/preview-token.ts @@ -114,7 +114,11 @@ export function previewUrl( token: string, ): string | undefined { const origin = primaryOrigin(site); - if (!origin) return undefined; + return origin ? previewUrlAt(origin, path, token) : undefined; +} + +/** The same link at another origin: `/?cloudhal-preview=`. */ +export function previewUrlAt(origin: string, path: string, token: string): string { const url = new URL(path.startsWith("/") ? path : `/${path}`, origin); url.searchParams.set("cloudhal-preview", token); return url.toString(); diff --git a/packages/mcp-server/src/common.ts b/packages/mcp-server/src/common.ts index dae48416..67648044 100644 --- a/packages/mcp-server/src/common.ts +++ b/packages/mcp-server/src/common.ts @@ -145,6 +145,12 @@ export interface RenderDeps { readonly limiter?: RenderLimiter | undefined; /** Per call (default 20 s). */ readonly timeoutMs?: number | undefined; + /** + * Where this browser reaches the site, when that is not the site's public origin (RFC-0047, + * #292: a self-host Chrome sidecar on a private network, `http://cloudhal:8788`). The browser + * then opens the same signed preview link at this origin, also for a site with no domain yet. + */ + readonly origin?: string | undefined; } /** diff --git a/packages/mcp-server/src/render-tools.ts b/packages/mcp-server/src/render-tools.ts index e910d1b6..35faca52 100644 --- a/packages/mcp-server/src/render-tools.ts +++ b/packages/mcp-server/src/render-tools.ts @@ -5,6 +5,7 @@ * component behind each problem. Read-only: nothing is stored, and the preview link expires. */ +import { mintPreviewToken, previewUrlAt } from "@cloudhal/core-ts"; import { id, obj, @@ -126,6 +127,25 @@ function mergeContrast( ); } +/** + * The link the browser opens: the preview link, or the same signed link at `render.origin` for a + * browser that reaches the site only on a private network (RFC-0047, #292). Still the site's own + * preview of this page: no other URL is ever opened. + */ +async function renderTarget( + a: Record, + ctx: ToolContext, + doc: { title: string; path: string; url: string | null }, +): Promise<{ title: string; path: string; url: string | null }> { + const origin = ctx.render?.origin; + if (!origin || !ctx.previewSecret) return doc; + const token = await mintPreviewToken(ctx.previewSecret, { + site: a.siteId as string, + target: "live", + }); + return { ...doc, url: previewUrlAt(origin, doc.path, token) }; +} + export function renderTools(previewDoc: PreviewDoc): ToolDefinition[] { return [ { @@ -229,7 +249,7 @@ export function renderTools(previewDoc: PreviewDoc): ToolDefinition[] { }, handler: async (a, ctx) => { if (!a.pageId && !a.entryId) throw new ToolError("invalid", "pass pageId or entryId"); - const doc = await previewDoc(a, ctx); + const doc = await renderTarget(a, ctx, await previewDoc(a, ctx)); if (!ctx.render) throw new ToolError( "render_unavailable", diff --git a/packages/mcp-server/test/render-tools.test.ts b/packages/mcp-server/test/render-tools.test.ts index f92c7ae7..9aff76de 100644 --- a/packages/mcp-server/test/render-tools.test.ts +++ b/packages/mcp-server/test/render-tools.test.ts @@ -289,4 +289,28 @@ describe("render_page (RFC-0021 §4)", () => { }); expect(res.structuredContent).not.toHaveProperty("images"); }); + + it("opens the same signed link at render.origin for a private browser, with or without a domain (#292)", async () => { + const at = async () => { + const log: string[] = []; + const render = { + renderer: fakeRenderer(log), + limiter: new RenderLimiter(), + origin: "http://cloudhal:8788", + }; + const out = await runTool(def, { siteId, pageId, widths: [768] }, ctx({ render }), { + policy, + }); + return { log, url: (out.result as { url: string }).url }; + }; + const withDomain = await at(); + expect(withDomain.log[1]).toMatch( + /^open 768x\d+ light http:\/\/cloudhal:8788\/about\?cloudhal-preview=/, + ); + expect(withDomain.url).toMatch(/^http:\/\/cloudhal:8788\/about\?cloudhal-preview=/); + const site = await store.getSite(siteId); + await store.updateSite({ ...(site as NonNullable), domains: [] }); + const fresh = await at(); + expect(fresh.log[1]).toMatch(/http:\/\/cloudhal:8788\/about\?cloudhal-preview=/); + }); }); diff --git a/scripts/render-smoke.ts b/scripts/render-smoke.ts new file mode 100644 index 00000000..ea80dbfb --- /dev/null +++ b/scripts/render-smoke.ts @@ -0,0 +1,311 @@ +/** + * `render_page` through the self-host image's Chrome sidecar, end to end (#292). CI only: + * .github/workflows/docker.yml runs it on the candidate image, and it refuses to start outside + * GitHub Actions. + * + * 1. Starts SeaweedFS and one instance on one network, and the compose file's Chrome on a network + * of its own that it shares with the instance only (as the compose file's chrome profile does). + * The browser publishes no port. + * 2. The first owner publishes and makes an agent key. The agent calls `render_page` over `/mcp` + * for the starter post, and a JPEG screenshot and the checks come back. + * 3. Afterwards the browser keeps no context: every render's browser context is gone. + * + * node scripts/render-smoke.ts --image [--port ] + */ +import { execFile } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; + +if (process.env.GITHUB_ACTIONS !== "true") { + console.error("render-smoke runs in CI only (.github/workflows/docker.yml), never locally"); + process.exit(2); +} + +const arg = (name: string): string | undefined => { + const i = process.argv.indexOf(`--${name}`); + return i === -1 ? undefined : process.argv[i + 1]; +}; +const image = arg("image") ?? "cloudhal:ci"; +const port = Number(arg("port") ?? 48787); +const id = `cloudhal-render-${process.pid}`; +const nets = { main: `${id}-main`, render: `${id}-render` }; +const names = { store: `${id}-store`, chrome: `${id}-chrome`, cloudhal: `${id}-cloudhal` }; +// 127.0.0.1, never localhost (#306) +const studio = `http://127.0.0.1:${port}`; +const compose = readFileSync( + path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../deploy/docker/compose.yml"), + "utf8", +); +const pinned = (repo: string) => { + const at = compose.indexOf(`image: ${repo}:`); + if (at === -1) throw new Error(`compose.yml names no ${repo} image`); + return compose.slice(at + 7, compose.indexOf("\n", at)).trim(); +}; +const STORE_IMAGE = pinned("chrislusf/seaweedfs"); +const CHROME_IMAGE = pinned("chromedp/headless-shell"); + +const run = promisify(execFile); +async function docker(args: string[], timeout = 120_000): Promise { + const { stdout } = await run("docker", args, { encoding: "utf8", timeout, maxBuffer: 64 << 20 }); + return stdout.trim(); +} +async function dockerLogs(name: string): Promise { + const { stdout, stderr } = await run("docker", ["logs", "--tail", "200", "--timestamps", name], { + encoding: "utf8", + timeout: 30_000, + maxBuffer: 64 << 20, + }); + return `${stdout}${stderr}`; +} +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const step = (text: string) => console.log(`✓ ${text}`); +function expect(ok: boolean, what: string, detail?: unknown): void { + if (!ok) throw new Error(`${what}${detail === undefined ? "" : `: ${JSON.stringify(detail)}`}`); +} + +const work = mkdtempSync(path.join(os.tmpdir(), "cloudhal-render-")); +function envFile(name: string, env: Record): string { + const file = path.join(work, `${name}.env`); + writeFileSync( + file, + Object.entries(env) + .map(([k, v]) => `${k}=${v}\n`) + .join(""), + { mode: 0o600 }, + ); + return file; +} + +interface Res { + status: number; + text: string; + body: unknown; + headers: Headers; +} +async function req(url: string, init: RequestInit = {}, ms = 30_000): Promise { + try { + const res = await fetch(url, { ...init, signal: AbortSignal.timeout(ms) }); + const text = await res.text(); + let body: unknown = text; + try { + body = JSON.parse(text); + } catch { + // not JSON + } + return { status: res.status, text, body, headers: res.headers }; + } catch (e) { + const err = e as { name?: string; cause?: { code?: string } }; + const text = err.cause?.code ?? err.name ?? String(e); + return { status: 0, text, body: text, headers: new Headers() }; + } +} +async function until(what: string, seconds: number, check: () => Promise) { + const deadline = Date.now() + seconds * 1000; + while (Date.now() < deadline) { + const v = await check().catch(() => undefined); + if (v !== undefined) return v; + await sleep(1000); + } + throw new Error(`${what} within ${seconds} s`); +} + +async function start(env: Record): Promise { + await docker(["network", "create", nets.main]); + await docker(["network", "create", nets.render]); + const s3 = JSON.stringify({ + identities: [ + { + name: "cloudhal", + credentials: [{ accessKey: env.AWS_ACCESS_KEY_ID, secretKey: env.AWS_SECRET_ACCESS_KEY }], + actions: ["Admin", "Read", "Write", "List", "Tagging"], + }, + ], + }); + await docker([ + ...["run", "-d", "--name", names.store, "--network", nets.main, "--network-alias", "seaweedfs"], + ...["--env-file", envFile("store", { S3_CONFIG: s3 }), "--entrypoint", "/bin/sh"], + STORE_IMAGE, + "-c", + 'printf "%s" "$S3_CONFIG" > /tmp/s3.json && exec weed server -dir=/data -s3 -s3.config=/tmp/s3.json -master.volumeSizeLimitMB=256', + ]); + // as the chrome profile runs it: no port, its own network, no capabilities + await docker([ + ...["run", "-d", "--name", names.chrome, "--network", nets.render, "--network-alias", "chrome"], + ...["--shm-size", "512m", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], + CHROME_IMAGE, + ]); + const cloudhal = envFile("cloudhal", { + ...env, + CLOUDHAL_S3_ENDPOINT: "http://seaweedfs:8333", + CLOUDHAL_S3_BUCKET: "cloudhal", + CLOUDHAL_CLUSTER_ADVERTISE: `${names.cloudhal}:7000`, + CLOUDHAL_SITE_NAME: "Render Site", + CLOUDHAL_BASE_URL: studio, + CLOUDHAL_BROWSER_URL: "http://chrome:9222", + }); + await docker([ + ...["run", "-d", "--name", names.cloudhal, "--network", nets.main, "--read-only"], + ...["--tmpfs", "/tmp", "--cap-drop", "ALL", "--security-opt", "no-new-privileges:true"], + ...["--env-file", cloudhal, "-p", `127.0.0.1:${port}:8787`, "-p", `127.0.0.1:${port + 1}:8788`], + image, + ]); + // the browser reaches the instance as `cloudhal`, the default CLOUDHAL_RENDER_ORIGIN's host + await docker(["network", "connect", "--alias", "cloudhal", nets.render, names.cloudhal]); +} + +/** One JSON-RPC answer from `/mcp`, as JSON or as the first matching server-sent event. */ +async function rpc( + key: string, + session: string | undefined, + message: Record, +): Promise<{ answer: Record | undefined; session: string | undefined }> { + const res = await fetch(`${studio}/mcp`, { + method: "POST", + headers: { + authorization: `Bearer ${key}`, + "content-type": "application/json", + accept: "application/json, text/event-stream", + ...(session ? { "mcp-session-id": session } : {}), + }, + body: JSON.stringify({ jsonrpc: "2.0", ...message }), + signal: AbortSignal.timeout(120_000), + }); + const text = await res.text(); + const next = res.headers.get("mcp-session-id") ?? session; + if (!("id" in message)) return { answer: undefined, session: next }; + expect(res.status === 200, `/mcp ${String(message.method)}`, { status: res.status, text }); + const json = (res.headers.get("content-type") ?? "").includes("text/event-stream") + ? text + .split("\n") + .filter((l) => l.startsWith("data:")) + .map((l) => JSON.parse(l.slice(5)) as Record) + .find((m) => m.id === message.id) + : (JSON.parse(text) as Record); + return { answer: json, session: next }; +} + +async function ownerAndKey(env: Record): Promise<{ cookie: string; key: string }> { + const json = { origin: studio, "content-type": "application/json" }; + const signUp = await req(`${studio}/api/auth/sign-up/email`, { + method: "POST", + headers: { ...json, "x-cloudhal-setup-token": env.CLOUDHAL_SETUP_TOKEN as string }, + body: JSON.stringify({ + name: "Render Owner", + email: "owner@example.com", + password: "render-smoke-password", + }), + }); + expect(signUp.status === 200, "sign-up of the first owner", signUp.body); + const cookie = + signUp.headers + .getSetCookie() + .map((c) => c.split(";")[0] as string) + .find((c) => c.includes("better-auth.session_token=")) ?? ""; + const published = await req(`${studio}/api/sites/${env.CLOUDHAL_SITE_ID}/snapshots`, { + method: "POST", + headers: { ...json, cookie }, + body: JSON.stringify({ publish: true }), + }); + expect(published.status === 201, "publish", published.body); + const created = await req(`${studio}/api/agent-keys`, { + method: "POST", + headers: { ...json, cookie }, + body: JSON.stringify({ name: "render smoke" }), + }); + const key = (created.body as { key?: string }).key; + expect(created.status === 201 && typeof key === "string", "the agent key", created.status); + return { cookie, key: key as string }; +} + +async function main(env: Record): Promise { + await start(env); + const admin = { authorization: `Bearer ${env.CLOUDHAL_DEPLOY_TOKEN}` }; + await until("the instance did not create its site", 180, async () => { + const r = await req(`${studio}/api/admin/sites`, { headers: admin }); + const sites = (r.body as { sites?: { id: string }[] }).sites ?? []; + return sites.some((s) => s.id === env.CLOUDHAL_SITE_ID) ? true : undefined; + }); + step("an instance with CLOUDHAL_BROWSER_URL and the Chrome sidecar are up"); + + const { cookie, key } = await ownerAndKey(env); + const list = await req(`${studio}/api/sites/${env.CLOUDHAL_SITE_ID}/entries?collection=posts`, { + headers: { cookie }, + }); + const entry = (list.body as { id: string; slug: string }[]).find?.( + (e) => e.slug === "hello-world", + ); + expect(entry !== undefined, "the starter post", list.status); + step("the owner published and made an agent key"); + + const init = await rpc(key, undefined, { + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "render-smoke", version: "1.0.0" }, + }, + }); + await rpc(key, init.session, { method: "notifications/initialized" }); + const { answer } = await rpc(key, init.session, { + id: 2, + method: "tools/call", + params: { + name: "render_page", + arguments: { siteId: env.CLOUDHAL_SITE_ID, entryId: entry?.id, widths: [1440] }, + }, + }); + const result = answer?.result as + | { + isError?: boolean; + content?: { type: string; mimeType?: string; data?: string; text?: string }[]; + } + | undefined; + const content = result?.content ?? []; + expect(result !== undefined && !result.isError, "render_page answered", answer); + const jpeg = content.find((c) => c.type === "image" && c.mimeType === "image/jpeg"); + const bytes = Buffer.from(jpeg?.data ?? "", "base64"); + expect(bytes.length > 2000 && bytes[0] === 0xff && bytes[1] === 0xd8, "a JPEG screenshot", { + bytes: bytes.length, + text: content.filter((c) => c.type === "text").map((c) => c.text?.slice(0, 300)), + }); + step(`render_page returned a ${bytes.length}-byte JPEG through the sidecar`); + + // the render's context is disposed: only the browser's own first page is left + const contexts = await docker([ + ...["run", "--rm", "--network", nets.render, "curlimages/curl:8.11.1"], + ...["-s", "-m", "10", "-H", "Host: localhost", "http://chrome:9222/json/list"], + ]); + const pages = (JSON.parse(contexts) as { type: string; url: string }[]).filter( + (p) => p.type === "page" && p.url !== "about:blank", + ); + expect(pages.length === 0, "the render's tabs and context are gone", pages); + step("no page of the render is left in the browser"); + console.log("\nrender_page smoke test passed."); +} + +const env = Object.fromEntries( + (await docker(["run", "--rm", image, "secrets"])) + .split("\n") + .filter((l) => l.includes("=") && !l.startsWith("#")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), +) as Record; +try { + await main(env); +} catch (e) { + console.error(`\n✗ ${e instanceof Error ? e.message : String(e)}`); + for (const name of Object.values(names)) { + const text = await dockerLogs(name).catch((d: Error) => `error: ${d.message}`); + console.error(`--- ${name} logs\n${text.slice(-12_000)}`); + } + process.exitCode = 1; +} finally { + for (const name of Object.values(names)) + await docker(["rm", "-f", "-v", name], 60_000).catch(() => undefined); + for (const n of Object.values(nets)) + await docker(["network", "rm", n], 30_000).catch(() => undefined); + rmSync(work, { recursive: true, force: true }); +}