Skip to content

Self-improving AI Employees for everyone

feat(cloudflare): move the cf node to cf 1.0 and fix deletes that never ran

trohitg9a5cd688950b
diff --git a/CLAUDE.md b/CLAUDE.md
index 70bf8a01..b22f2309 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -34,7 +34,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Stripe Service](./docs-internal/stripe_service.md)** | Stripe CLI integration — `stripeAction` (CLI pass-through) + `stripeReceive` (signed-webhook trigger, on a canvas Run and deployed: every Stripe event travels under one CloudEvents type, `com.opencompany.stripe.event.received`, with the Stripe type in `subject` and `data.event_type`, where the node's own `build_filter` reads it; the source shapes the payload once, wakes the in-process waiter through `WebhookSource.handle` and reaches deployed listeners through `dispatch.emit`; deploying starts `stripe listen` through the generic `TriggerNode.prepare_deployment` hook, at Start and at the boot re-arm). Reference plugin for the Wave 12 event framework AND the **CLI-managed-auth pattern**: browser OAuth via `stripe login --non-interactive` + `--complete <url>` (URL extracted from `next_step` shell command via `shlex.split`) + auto-installed binary (`ensure_stripe_cli` from GitHub releases) + marker-token reuse of `auth_service.store_oauth_tokens` + CloudEvents-shaped `broadcast_credential_event("credential.oauth.connected" \| ".disconnected", provider=...)` — zero per-provider hardcoding in the frontend. Daemon stdout/stderr ingested via `ProcessService`'s `line_handler` callback (no log-file tailing); credential gate routed through `await self.has_credential()` so non-api-key auth (`is_logged_in()`) plugs in via subclass override. |
| **[Vercel Service](./docs-internal/vercel_service.md)** | Vercel CLI integration — `vercelAction` (deploy / inspect / list + `custom` CLI passthrough; AI tool `vercel`). Second reference for the CLI-managed-auth pattern: the **device-flow variant** (`vercel login` is one blocking process — no two-step `--complete`; direct `create_subprocess_exec` + chunk-based banner read for the code-embedding URL, pumps drain pipes for the process lifetime, success gate = auth.json mtime advance + sniff). Dual auth: optional `vercel_token` field (injected as `VERCEL_TOKEN` env, never argv) OR CLI login with marker tokens. All invocations pin `--global-config <DATA_DIR>/vercel/` (the `CLAUDE_CONFIG_DIR` isolation idiom). `bun add` into the shared packages tree (pinned version, via `core/js_runtime.add_package`; the CLI runs on bun). First-deploy project guard raises `NodeUserError` instead of letting Vercel derive an invalid name from the workspace dir. Shipped with the generic OAuthConnect change: Login gates on **required** fields only, so optional fields never block CLI login. |
| **[GitHub Service](./docs-internal/github_service.md)** | GitHub CLI integration — `githubAction` (repo_clone / pr_create / pr_list / pr_merge / issue_create / issue_list + `custom` passthrough; AI tool `github`). **Strict Stripe pattern: the gh CLI owns its own auth** — no token stored/injected by OpenCompany, no auth pre-flight (gh's own error surfaces), marker OAuth row for the modal badge, fieldless catalogue entry. Login = spawned `gh auth login --hostname github.com --git-protocol https --web` — source-verified: headless takes the `isInteractive=false` branch (no Press-Enter), prints one-time code + `github.com/login/device` URL on stderr; the modal shows the code via the generic `verificationCode` plumbing (`useCredentialPanel` → `OAuthConnect`). `login_env()` strips `GH_TOKEN`/`GITHUB_TOKEN` (login aborts otherwise). Success gate = `gh auth status` exit 0, then best-effort **`gh auth setup-git`** (official bridge — the future git node needs zero auth code). gh binary: **project-local, pooch-driven** (temporal `_install.py` idiom) — pinned release under `package_dir("gh")`, system gh never consulted (auth state still shared: gh config paths are user-level). Palette group `vcs`. |
-| **[Cloudflare Service](./docs-internal/cloudflare_service.md)** | Cloudflare CLI integration — `cloudflareAction` (whoami / zones_list / dns_records CRUD / `graphql_query` / `custom` passthrough; AI tool `cloudflare`) wrapping the official `cf` CLI (npm `[email protected]`, technical preview — "the next version of Wrangler"). **Two cf-specific variants of the CLI-managed-auth pattern**: (1) the CLI opens the browser ITSELF (loopback PKCE callback on fixed port 8877) so the login handler proxies nothing — single-flight guard (concurrent logins collide on the fixed port) + never-kill-the-shim invariant (killing bun's `cf.exe` launcher shim orphans the child bun process holding 8877); success gate = `cf auth whoami` JSON (`authenticated: true` — cf exits 0 in BOTH auth states). (2) **Fixed 86-scope OAuth grant with no `--scopes` flag** — only `dns_analytics:read` for analytics; no RUM/zone-analytics OAuth scope exists anywhere, so the optional `cloudflare_api_token` field (injected as `CLOUDFLARE_API_TOKEN`, cf's documented first-priority credential) is the only path to Web Analytics/RUM + the GraphQL Analytics API. `graphql_query` op POSTs the official `client/v4/graphql` endpoint directly (outside the OpenAPI schema cf/SDKs are generated from) — the replacement for the sunsetted Zone Analytics REST API; needs `Account > Account Analytics > Read`. Pinned `bun add` into the shared packages tree (the CLI declares `engines.node >= 22`, which bun ignores — verified running on bun with no Node on PATH), system cf never consulted (preview argv surface drifts across versions). Palette group `deployment`. |
+| **[Cloudflare Service](./docs-internal/cloudflare_service.md)** | Cloudflare CLI integration — `cloudflareAction` (whoami / `search_commands` (`cf cli search`) / zones_list / DNS records list-create-edit-delete / `graphql_query` / `custom` passthrough; AI tool `cloudflare`) wrapping the official `cf` CLI (npm `[email protected]`, open beta — "the next version of Wrangler"). **Pin enforced, not just installed once**: `ensure_cf_cli` compares `core.js_runtime.installed_version("cf")` with the pin and re-runs `bun add` on a mismatch (clearing the login marker, since a new version may not see the old login). **Login = gh's device-flow shape**: `cf auth login --force --device --no-browser` prints a URL + one-time code on stderr that the handler relays to the modal (works from any machine; the old fixed-port-8877 loopback flow is `--no-device` only) — single flight (a repeat click returns the same code), install before any login (no invisible codes), never-kill-the-shim (killing bun's `cf.exe` launcher orphans the child), success gate = `cf auth whoami` JSON (`authenticated: true` — cf exits 0 in BOTH auth states). **cf contract traps**: destructive commands without `--force` print "Aborted." and **exit 0** (delete always passes it; `custom` turns it into an error); no `--account-id` flag on most commands (account = `CLOUDFLARE_ACCOUNT_ID`, from the `account_id` param — several accounts fail non-interactively without it); cf resolves a domain `--zone` only in the first page of the selected account, so the node resolves domains itself via `zones list --name`; no output-format flag (unknown flags rejected); cf reads `.env` files from its working directory and fails under bun on a `cloudflare.config.ts` found above it, so typed ops run from a neutral `<DATA_DIR>/cloudflare` (`custom` from the workspace) with `CF_DELEGATION=1` (otherwise bun lets cf hand off to another cached cf copy) and telemetry off. The optional `apiKey` field (an API token) rides `CLOUDFLARE_API_TOKEN` and beats the login; cf does NOT accept a Global API Key, so a `cfk_` key (with `cloudflare_email`) serves only `graphql_query`, which POSTs the official `client/v4/graphql` endpoint directly (no cf GraphQL command; the cf login's token never leaves the CLI) — needs `Account > Account Analytics > Read`. System cf never consulted. Palette group `deployment`. |
| **[Google Cloud Service](./docs-internal/gcloud_service.md)** | Google Cloud CLI integration — `gcloudAction` (auth/config/projects + set_project / Compute Engine instances list-start-stop-describe / Cloud Run deploy-list-describe / Cloud Storage ls-cp-rm / `custom` passthrough; AI tool `gcloud`) wrapping the official gcloud CLI (pinned versioned archive via pooch into `package_dir("gcloud")` — NOT npm; the Windows bundled-python zip keeps the legacy `google-cloud-sdk-` filename prefix, the `-cli-` spelling 404s, locked by test). Cloudflare login variant (CLI opens the browser itself, random loopback port — no fixed-port hazard) + the gh marker-token pattern; success gate = `gcloud auth list --filter=status:ACTIVE --format=json` non-empty (exit codes never trusted). **Config isolation divergence from gh**: every invocation pins `CLOUDSDK_CONFIG=<DATA_DIR>/gcloud/`, so terminal logins against the operator's global gcloud are deliberately NOT visible to the node. ADC note: node login mints gcloud USER creds only (CLI commands never read ADC); client-library code gets ADC via the `custom` op `auth application-default login` (lands isolated in the pinned dir). Cold install ~100 MB → login answers `pending: True` within the 22 s WS budget. Provider id `gcloud` is orthogonal to the Workspace `google` OAuth2 provider. Palette group `deployment`. |
| **[TikHub Service](./docs-internal/tikhub_service.md)** | TikHub social-scraping integration — `tikhubAction` (`call` / `list_endpoints` / `fetch_url` / `account`; AI tool `tikhub_action`; palette group `scraper`, visible in normal mode) over the **official `tikhub` SDK** (`tikhub>=2.1.2,<3`, auto-generated from TikHub's `openapi.json`; ~1,100 methods across TikTok / Douyin / Instagram / YouTube / Twitter / Xiaohongshu / Bilibili / Kuaishou / Weibo / Reddit / Threads / LinkedIn / Zhihu). **The node is the "flattened CLI"**: one `call` op addressed by the SDK's own `resource.method` id (`douyin_web.fetch_one_video`, also `resource/method` or the `/api/v1/...` path) with **reflective `getattr` dispatch** and `inspect.signature(...).bind` pre-flight so unknown kwargs fail before any paid request; **nothing is vendored** — `endpoint_index()` introspects the installed SDK at runtime (resources = `AsyncResource` instance attrs, params = keyword-only signature, route from the docstring's ``GET /api/v1/...`` literal), cached per process, and feeds both `list_endpoints` and the `platform`-dependent dynamic `endpoint` dropdown (`tikhubEndpoints` loader; `all` returns no options, the LLM path stays free text). `tikhub` is imported lazily inside `_sdk.py` only (plugin imports with `sys.modules["tikhub"] = None`). `TikHubCredential` = bearer `ApiKeyCredential` with a declarative httpx probe against `/api/v1/tikhub/user/get_user_info` (never the unauthenticated health route); runtime key via `TikHubCredential.resolve` so a missing key yields the structured `PermissionDeniedError` envelope. SDK `TikHubError` subclasses map to `NodeUserError` (401 key rejected -> Credentials; 403 scope-or-balance -> `account`; 429 + `retry_after`; 400/422 with TikHub `detail`; 404; 5xx upstream after the SDK's own retries) and HTTP-200-with-in-body-`code >= 400` is raised too. **Flat `$0.001`/request tracking** (`pricing.json: api.tikhub` + `operation_map.tikhub`, `track_tikhub_usage` -> `api_usage_metrics`, only after a 2xx, never for `list_endpoints`). SDK drift is guarded by two contract tests (every `PLATFORMS` value matches a live resource; every backticked id in the skill resolves). |
| **[Discord Service](./docs-internal/discord_service.md)** | Discord bot integration — `discordSend` / `discordAction` (AI tools) + `discordReceive` / `discordInteraction` triggers. **discord.py owns the gateway, REST is plugin-owned** (nodes must work with no gateway, `discordAction` needs arbitrary routes, and the invalid-request guard is process-wide across accounts). **Multi-account rides the existing `session_id` credential column** — `_accounts.py` is the only file that knows `account_id -> "discord:<app_id>"`, `"default"` is the row the modal already writes, and `credential_customer_id` is deliberately NOT used (it is per-execution-context tenancy, so two nodes in one workflow could never target different bots). **`AccountScopedNode` exists because `server_controlled_fields` is enforced only in `execute_as_tool`'s ToolNode branch** — a dual-purpose ActionNode takes an earlier `{**node_params, **tool_args}` merge with model args winning, so locked fields are stripped before it. Attachments are metadata on the trigger and downloaded by `discordAction` (deployed triggers never run their node body). Interaction tokens never leave the server — the trigger emits an opaque ref. The interactions endpoint is a plugin router, not a `WebhookSource`: Discord's validation probe requires **401** (the generic intake raises 400) and the 3-second ACK deadline precludes awaiting `emit`. Rate limiting is reactive; the invalid-request guard is **process-global** because Cloudflare bans the source IP, not the token. |
diff --git a/docs-internal/cloudflare_service.md b/docs-internal/cloudflare_service.md
index 708034c8..80433b03 100644
--- a/docs-internal/cloudflare_service.md
+++ b/docs-internal/cloudflare_service.md
@@ -1,23 +1,23 @@
# Cloudflare Service (`cf` CLI)
The `cloudflareAction` node wraps the **official Cloudflare CLI `cf`**
-(npm package `cf`, a Technical Preview announced 2026-04-13 as "the
-next version of Wrangler"). One self-contained plugin folder at
-[`server/nodes/cloudflare/`](../server/nodes/cloudflare/), following
-the CLI-managed-auth pattern (stripe -> vercel -> github lineage) with
-two cf-specific variants documented below: **the CLI opens the browser
-itself** (no URL proxying to the modal) and **a fixed-scope OAuth
-grant** that makes the optional API token the only path to analytics.
+(npm package `cf`, in open beta since 2026-09-28 as "the next version of
+Wrangler"; docs at [developers.cloudflare.com/cf](https://developers.cloudflare.com/cf/)).
+One self-contained plugin folder at
+[`server/nodes/cloudflare/`](../server/nodes/cloudflare/), following the
+CLI-managed-auth pattern (stripe -> vercel -> github lineage). Its login
+is gh's device-flow shape: cf prints a URL and a one-time code, and the
+credentials modal shows them.
| | |
|---|---|
| Node type | `cloudflareAction` (palette group `deployment`, dual-purpose AI tool `cloudflare`) |
-| Operations | `whoami` / `zones_list` / `dns_records_list` / `dns_record_create` / `dns_record_delete` / `graphql_query` / `custom` |
-| CLI pin | `[email protected]` (`_NPM_SPEC` in `_install.py`), `bun add`ed into the shared `packages_dir()` tree via `core/js_runtime.add_package` and run on bun; cf declares `engines.node >= 22`, which bun ignores — verified on bun 1.4 with no Node on PATH, including `cf auth whoami` |
-| Auth | Dual-path: cf-owned OAuth login OR optional canonical `apiKey` field (stored under the provider id `cloudflare`) -> `CLOUDFLARE_API_TOKEN` env |
+| Operations | `whoami` / `search_commands` / `zones_list` / `dns_records_list` / `dns_record_create` / `dns_record_edit` / `dns_record_delete` / `graphql_query` / `custom` |
+| CLI pin | `[email protected]` (`_NPM_VERSION` in `_install.py`), `bun add`ed into the shared `packages_dir()` tree via `core/js_runtime.add_package` and run on bun; the pin is enforced against the installed `node_modules/cf/package.json` version |
+| Auth | Dual-path: cf-owned OAuth device login OR optional canonical `apiKey` field (stored under the provider id `cloudflare`) -> `CLOUDFLARE_API_TOKEN` env. A `cfk_` Global API Key in that field (plus `cloudflare_email`) serves only `graphql_query` |
| Task queue | `TaskQueue.REST_API` |
-| Output | `ui_hints = {"outputMode": "terminal"}`; `_shape` contract (parsed JSON -> `result`, text -> `stdout`, never both) + NDJSON recovery |
-| Tests | [`server/tests/test_cloudflare_plugin.py`](../server/tests/test_cloudflare_plugin.py) (42 contract tests at time of writing; `pytest --collect-only -q`) |
+| Output | `ui_hints = {"outputMode": "terminal"}`; `_shape` contract (parsed JSON -> `result`, text -> `stdout`, never both) |
+| Tests | [`server/tests/test_cloudflare_plugin.py`](../server/tests/test_cloudflare_plugin.py) (`pytest --collect-only -q` for the count) |
| Paired skill | [`server/skills/cloudflare/cloudflare-skill/SKILL.md`](../server/skills/cloudflare/cloudflare-skill/SKILL.md) |
## Folder map
@@ -25,131 +25,255 @@ grant** that makes the optional API token the only path to analytics.
```
server/nodes/cloudflare/
├── __init__.py # register_ws_handlers(WS_HANDLERS) + register_output_schema
-├── cloudflare_action.py # CloudflareActionNode + Params/Output + _run/_shape + _graphql_post
-├── _credentials.py # CloudflareCredential — resolve() returns the optional token row
-├── _handlers.py # cloudflare_login / cloudflare_logout / cloudflare_status
-├── _install.py # ensure_cf_cli() — pinned `bun add` (core/js_runtime), system cf NEVER consulted
-├── _service.py # cf_env(token, email) / api_auth_headers() / login_env() / whoami_snapshot() / stored_token() / stored_email() / resolve_cf_light()
+├── cloudflare_action.py # CloudflareActionNode + Params/Output + _run/_failure/_zone_id/_shape + _graphql_post
+├── _credentials.py # CloudflareCredential — resolve() returns the optional token + email rows; prefix-routed _probe
+├── _handlers.py # cloudflare_login (device flow) / cloudflare_logout / cloudflare_status
+├── _install.py # ensure_cf_cli() — pinned, version-enforcing `bun add` (core/js_runtime); system cf NEVER consulted
+├── _service.py # cf_env(token, account_id) / cf_workdir() / login_env() / api_auth_headers() / whoami_snapshot() / stored_token() / stored_email() / resolve_cf_light()
└── meta.json # {"color": "#F38020"}
```
Icon: `lobehub:Cloudflare` via `visuals.json` (`cloudflareAction` entry
+ lowercase `cloudflare` alias for the tool name — no folder
`icon.svg`). Catalogue entry in `credential_providers.json` (vercel
-dual-path shape: one optional field, never gating the Login button).
+dual-path shape: optional fields only, never gating the Login button).
-## Install — pinned, never the system PATH
+## Install — pinned, enforced, never the system PATH
`_install.py` uses vercel's install **mechanism** (`core.js_runtime.add_package`
— `bun add --cwd <packages_dir> <spec>` into the shared tree, the
`node_modules/.bin` shim via `shared_tree_bin("cf")`, `asyncio.to_thread`,
-double-checked lock; the CLI runs on bun, no Node or npm involved) but
-github's **resolution philosophy**: `shutil.which("cf")` is
-never consulted. The preview CLI's command tree is schema-generated and
-drifts between versions — between 0.0.5 and 0.2.0, `--ndjson`/`--fields`
-were removed (JSON became the default output), `dns records create`
-kept only the `--body` escape hatch, and the auth config moved from
-`~/.cf/config.toml` to `auth.jsonc` under the config dir. The argv
-builders are verified against the pinned version only. **Version-bump
-recipe**: change `_NPM_SPEC`, re-run `cf <cmd> --help-full` for every
-wrapped command, adjust argv builders + tests. (0.3.0 is already out.)
-
-Auth state is user-level and shared with any system cf install — which
-binary runs does not affect who is logged in.
-
-## Auth — CLI-owned OAuth login (the cf variant)
-
-`cf auth login` is a PKCE OAuth flow against
-`dash.cloudflare.com/oauth2/*` with a loopback callback server on the
-**fixed port `localhost:8877`**, and cf **opens the default browser
-itself** (`start` / `open` / `xdg-open`). The handler therefore does
-NOT parse or proxy the authorize URL to the frontend (no custom login
-UI, no `verification_code`) — `cloudflare_login` returns
-`{success, message}` and the modal badge flips when the background
-completion broadcasts `credential.oauth.connected`.
-
-Two hazards drove the handler's shape (both observed live):
-
-1. **Fixed callback port** — two concurrent `cf auth login` processes
- collide on 8877; the second exits instantly with "Port already in
- use". A module-level **single-flight guard** (`_active_login` task +
- proc) makes repeat Login clicks return "already in progress".
-2. **Windows shim orphaning** — the installed binary is bun's `cf.exe`
- launcher shim (plus a `cf.bunx` file, never `.cmd`); killing it
- terminates only the launcher and orphans the child bun process running
- the CLI, which keeps holding 8877 and breaks every later login.
- The completion watcher **never kills the process** (test-locked) —
- cf enforces its own login timeout and exits by itself.
-
-Flow: single-flight check -> `ensure_cf_cli()` (22s response budget,
-`pending: true` past it) -> **whoami short-circuit** (live session ->
-mark + broadcast immediately, no spawn) -> spawn
-`cf auth login --force` (`--force` pushes past a stale/invalid stored
-token; only reached when whoami says no session) with pipes drained for
-the process lifetime -> background `_complete_login` waits (<= 600s) ->
-gate on `whoami_snapshot()` -> marker row + broadcast.
-
-**Success gate**: `cf auth whoami` prints JSON
-`{authenticated, tokenValid, email, scopes[]}` and **exits 0 in BOTH
-auth states** (verified) — exit codes are never consulted; the
-`authenticated` field is the only signal. The whoami email feeds
-`mark_logged_in("cloudflare", email=...)` (shared
-`services/cli_agent/_cli_auth.py` module, same as claude/codex/github).
-
-`login_env()` strips all six ambient credential vars
-(`CLOUDFLARE_API_TOKEN`/`CF_API_TOKEN`, `CLOUDFLARE_API_KEY`/`CF_API_KEY`,
-`CLOUDFLARE_EMAIL`/`CF_EMAIL`) so login/whoami/logout reflect the OAuth
-session, never an env token; the stored modal token is never injected
-there either (test-locked).
-
-## The OAuth scope ceiling — why the API token exists
-
-cf's PKCE client hard-codes **86 scopes with no `--scopes` flag**
-(source-verified in the bundle). The only analytics scope is
-`dns_analytics:read`. **No Web Analytics/RUM or zone-analytics OAuth
-scope exists anywhere in Cloudflare's OAuth catalog** (wrangler's
-documented `--scopes` list has none either), so `/accounts/{id}/rum/*`
-and the analytics datasets return **403 under any OAuth login** — this
-is structural, not a configuration error.
-
-Cloudflare's sanctioned paths are an **API token** with the matching
-permission groups (cf documents the env token as its first-priority
-credential source: "1. `CLOUDFLARE_API_TOKEN` environment variable,
-2. cf OAuth token") or the legacy **Global API Key** + account email
-pair (full access — also covers endpoints the account-token
-compatibility matrix excludes). Hence the dual-path fields:
-
-- Optional canonical `apiKey` field in the credentials modal
- (`required: false` — Login gates on required fields only, the
- OAuthConnect invariant; stored under the provider id so the base
- `Credential.validate` scaffold needs no storage override). Accepts
- EITHER a scoped API token (`cfut_`/`cfat_`) OR a Global API Key
- (`cfk_`); the optional `cloudflare_email` companion field carries
- the account email Global keys authenticate with.
-- Credential prefixes are Cloudflare's documented scannable formats
- (`cfk_` = Global API Key, `cfut_` = user token, `cfat_` = account
- token) — `_service.py` routes on them everywhere:
- - `cf_env(token, email)`: tokens ride `CLOUDFLARE_API_TOKEN`; a
- cfk_ key + email ride the documented `CLOUDFLARE_API_KEY` +
- `CLOUDFLARE_EMAIL` pair (ambient token vars dropped — cf ranks
- tokens above the key pair and would silently override).
+double-checked lock; no `--trust`, since no lifecycle script is needed)
+but github's **resolution philosophy**: `shutil.which("cf")` is never
+consulted. The command tree is generated from Cloudflare's OpenAPI schema
+and drifts between releases, and the argv builders are verified against
+the pinned version only.
+
+**The pin is enforced, not just installed once.** An existing shim says
+nothing about which version it runs, so `ensure_cf_cli()` compares
+`core.js_runtime.installed_version("cf")` with `_NPM_VERSION` and re-runs
+`bun add` when they differ; `cf_cli_path()` (the no-install probe the
+status/logout handlers use) returns `None` for an older version. A
+version change clears the catalogue's login marker (`_forget_cli_login`),
+because the new version may not see the old login (1.0 does not migrate
+0.2.0's `auth.jsonc`); the login handler's whoami short-circuit re-marks
+it at once when the session did survive. `company clean` keeps
+`packages/`, so this check is the only thing that moves an existing
+install to a new pin.
+
+cf 1.0 depends on miniflare + workerd (for `cf dev` / `--local`): the
+first install downloads about 300 MB (0.2.0 was 18 MB).
+
+**Version-bump recipe**: change `_NPM_VERSION`, re-check every wrapped
+command with `cf <cmd> --help` and `--dry-run`, adjust argv builders +
+tests, update this page and the skill.
+
+### What changed from the old 0.2.0 pin
+
+- Login: device authorization became the default (0.11.0); the PKCE
+ loopback flow on `localhost:8877` is `--no-device` only. `--scopes`
+ exists (0.4.0); the default grant requests 475 scopes, analytics
+ included.
+- Auth store moved to `<xdg-config>/cloudflare/config/default.json`
+ (`%APPDATA%\xdg.config\cloudflare\...` on Windows); named profiles
+ (`cf auth create|activate|list`) exist.
+- `cf context` and `cf agent-context` are gone; `cf cli search` and
+ `cf schema` replace them.
+- `whoami` gained an `accounts` array.
+- Telemetry was added (on by default).
+
+## Runtime — bun, delegation, and the working directory
+
+cf declares `engines.node >= 22`; bun 1.4 reports a Node version that
+passes the bin's guard, and every API command works on it (verified with
+no Node on PATH). Two documented limits follow from running on bun:
+
+- **`cloudflare.config.ts` cannot load under bun** ("Bun is not
+ supported" — commands that load it fail with *"cloudflare.config.ts
+ loading is not supported on Bun"*). API commands walk up from the
+ working directory looking for that file, so ops run from a **neutral
+ directory**, `cf_workdir()` = `<DATA_DIR>/cloudflare`. Project
+ commands (`init`, `build`, `dev`, `deploy`) need Node 22.18+; the
+ bun shim uses `node` when one is on PATH.
+- **cf reads its working directory**: API commands load
+ `CLOUDFLARE_API_TOKEN` / `CLOUDFLARE_ACCOUNT_ID` / `CLOUDFLARE_ZONE_ID`
+ (and a few more) from `.env`, `.env.local`, `.env.<mode>` there (real
+ process env wins), and cache the auto-selected account under
+ `.cloudflare/cache/`. Running from the server's own cwd would pick up
+ whatever `.env` sits there. `custom` runs from the workflow workspace
+ instead, so relative paths (`--body @file.json`, `--file`, `--dir`)
+ resolve against the workflow's files.
+
+`cf_env()` also sets **`CF_DELEGATION=1`**: `bin/cf` otherwise hands the
+command to any other cf copy it can resolve from the working directory —
+under bun that includes bun's install cache, even from an empty
+directory — so the pinned, verified version might not be the one that
+runs. And `CF_SEND_TELEMETRY=false` opts out of cf's usage telemetry
+(sibling precedent: vercel's `telemetry disable`, gcloud's
+`CLOUDSDK_CORE_DISABLE_USAGE_REPORTING`).
+
+## Auth — CLI-owned OAuth device login
+
+`cf auth login --force --device --no-browser` runs the OAuth 2.0 Device
+Authorization Grant (RFC 8628) against `dash.cloudflare.com/oauth2/device/auth`.
+cf prints (stderr, source-verified in the 1.0.0-beta.12 bundle):
+
+```
+To authorize cf, please visit:
+
+ <verification_uri>
+
+and enter the code:
+
+ <user_code>
+
+You have 5 minutes to approve this request.
+```
+
+then polls until the user approves, at most 5 minutes, and exits. The
+handler parses the URL + code (`parse_login_banner`) and answers
+`{success, url, verification_code}`; `useCredentialPanel` opens the URL
+and `OAuthConnect` renders the code (the gh device-flow contract). No
+callback server is involved, so the login works from any browser on any
+machine. `--no-browser` stops cf from also opening a tab on the server
+machine (a duplicate tab on desktop installs, a failure on remote
+servers); `--device` pins the flow against a future default change;
+`--force` pushes past a stale stored token (the spawn only happens when
+whoami says there is no live login).
+
+Handler shape (`_handlers.py`):
+
+1. **Single flight** (`_active_login`: `task`, `proc`, `url`, `code`,
+ `install`). While a device flow waits for approval, a repeat click
+ returns the same URL + code; while one is starting, it returns
+ `pending`.
+2. **Install before login.** When `cf_cli_path()` is `None` (missing or
+ older version) the install runs as a background task and the login
+ waits for it only while enough of the 30 s request window remains for
+ cf to print its code (`_RESPONSE_BUDGET_SECONDS` 22 minus
+ `_BANNER_DEADLINE_SECONDS` 15); otherwise the click answers `pending`
+ and the next click logs in. A login is never spawned after its
+ request was answered, so cf never issues a code nobody sees.
+3. **whoami short-circuit** — a live login (from a terminal, or a flow
+ that completed after the modal closed) marks + broadcasts without a
+ spawn.
+4. Spawn (`_spawn_login`, `login_env()` + `cf_workdir()`), pumps drain
+ both pipes for the process lifetime and store the banner as soon as
+ it appears (a click answered "still preparing" picks it up next time).
+5. Background `_complete_login` waits for cf to exit (600 s backstop;
+ cf gives up after 5 minutes), gates on `whoami_snapshot()`, then the
+ marker row + `credential.oauth.connected` broadcast via the shared
+ `services/cli_agent/_cli_auth.py`.
+
+**Never kill the login process** (test-locked): the installed binary is
+bun's `cf.exe` launcher shim (plus a `cf.bunx` file, never `.cmd`), and
+killing it orphans the child bun process running the CLI. The old fixed
+port 8877 hazard is gone with the device flow.
+
+**Success gate**: `cf auth whoami` prints
+`{authenticated, authSource, tokenValid, email, accounts[], scopes[], expiresAt}`
+and **exits 0 in BOTH auth states** (`{"authenticated": false, "error":
+"Not logged in"}` when logged out) — exit codes are never consulted.
+
+`login_env()` strips `CLOUDFLARE_API_TOKEN` / `CF_API_TOKEN`: with a
+token set, whoami reports the token and `cf auth login` refuses to start
+("CLOUDFLARE_API_TOKEN is set and takes precedence"). The stored modal
+token is never injected there either (test-locked).
+
+## Credentials — token, Global API Key, and what each reaches
+
+cf's credential order: `CLOUDFLARE_API_TOKEN` (deprecated alias
+`CF_API_TOKEN`) -> the OAuth profile. **cf does not accept a Global API
+Key** (`allowGlobalAuthKey: false`; the `CLOUDFLARE_API_KEY` +
+`CLOUDFLARE_EMAIL` pair is ignored — 0.2.0 behaved the same).
+
+- Optional canonical `apiKey` field (`required: false` — Login gates on
+ required fields only, the OAuthConnect invariant; stored under the
+ provider id so the base `Credential.validate` scaffold needs no
+ storage override). An API token (`cfut_` / `cfat_`) rides every CLI
+ call as `CLOUDFLARE_API_TOKEN` and takes precedence over the login. A
+ `cfk_` Global API Key is NOT injected into cf (nothing cf reads would
+ carry it); with the `cloudflare_email` companion it authenticates the
+ direct API calls only.
+- `_service.py` routes on Cloudflare's documented prefixes (`cfk_` =
+ Global API Key, `cfut_` = user token, `cfat_` = account token):
+ - `cf_env(token, account_id)`: tokens -> `CLOUDFLARE_API_TOKEN`;
+ `cfk_` -> nothing; `account_id` -> `CLOUDFLARE_ACCOUNT_ID`.
- `api_auth_headers(key, email)`: `Bearer` for tokens,
- `X-Auth-Email`/`X-Auth-Key` for Global keys (direct API calls:
- GraphQL, probes).
- - The Validate probe: cfk_ → `GET /user` with the X-Auth pair (or
- an "add the Account Email" guidance when the companion is
- missing); cfat_ → authenticated `GET /accounts` read (the
- `/user/tokens/verify` endpoint is user-token-only and falsely
- rejects account tokens); cfut_/legacy → the official
- `/user/tokens/verify` endpoint.
-- `CloudflareCredential.resolve()` returns the credential rows so
- other surfaces can consume them.
-- Token permissions for analytics: **Account > Account Analytics >
- Read** (covers RUM datasets + `rum/site_info` reads) plus
- **Zone > Analytics > Read** for zone-scoped queries. The Global API
- Key needs no permission setup (it has everything) but is
- Cloudflare-discouraged legacy — prefer scoped tokens when they
- suffice.
+ `X-Auth-Email`/`X-Auth-Key` for Global keys (GraphQL, probes).
+ - The Validate probe: cfk_ -> `GET /user` with the X-Auth pair (or an
+ "add the Account Email" guidance when the companion is missing);
+ cfat_ -> authenticated `GET /accounts` read (`/user/tokens/verify`
+ is user-token-only); cfut_/legacy -> `/user/tokens/verify`.
+- The OAuth login's token never leaves cf (OpenCompany does not read
+ cf's profile store), so `graphql_query` needs the panel credential
+ even though cf's default grant now includes analytics scopes.
+
+| Surface | OAuth login | API token | Global API Key + email |
+|---|---|---|---|
+| CLI operations (zones, DNS, Workers, R2, KV, D1, ...) | yes | yes (per token permissions) | **no — cf refuses it** |
+| `graphql_query` (zone traffic, RUM, DNS analytics) | **no — token stays in the CLI** | yes (`Account Analytics: Read` / `Zone Analytics: Read`) | yes |
+
+## Accounts and zones
+
+- cf has **no `--account-id` flag** on most commands; the account comes
+ from `CLOUDFLARE_ACCOUNT_ID`, then `cloudflare.config.ts`, then a
+ cached choice, then the only account. With several accounts a
+ non-interactive run fails (*"More than one account available but
+ unable to select one in non-interactive mode"*), so the node exposes
+ `account_id` (-> `CLOUDFLARE_ACCOUNT_ID`; `zones_list` also passes it
+ as its `--account-id` filter) and `_failure` points at it.
+- The zone is the global `-z/--zone`. cf passes a 32-hex ID (or UUID)
+ through, but resolves a **domain** only after selecting an account and
+ only within the first page (20) of that account's zones. The node
+ therefore resolves domains itself (`_zone_id`: `zones list --name
+ <domain> [--account-id]`, an exact match across every account the
+ credential sees) and passes the ID; several matches in different
+ accounts ask for `account_id`.
+
+## Operations -> argv (verified against [email protected] `--help` / `--dry-run`)
+
+| Operation | argv / call |
+|---|---|
+| `whoami` | `auth whoami` |
+| `search_commands` | `cli search <search_query>` (local index, no credentials or network) |
+| `zones_list` | `zones list [--name <f>] [--account-id <id>] [--page N] [--per-page N]` |
+| `dns_records_list` | `dns records list --zone <zone id> [--name <fqdn>] [--type <TYPE>] [--page N] [--per-page N]` |
+| `dns_record_create` | `dns records create --zone <zone id> --body <json>` (create/update/edit take the record only as `--body`) |
+| `dns_record_edit` | `dns records edit <record_id> --zone <zone id> --body <json>` (PATCH; `update` would overwrite) |
+| `dns_record_delete` | `dns records delete <record_id> --zone <zone id> --force` |
+| `graphql_query` | POST `client/v4/graphql` (not the CLI) |
+| `custom` | `shlex.split(command)`, a leading `cf`/`cloudflare` dropped; runs from the workflow workspace with the custom timeout |
+
+Contract notes:
+
+- **Output**: one pretty-printed JSON document on stdout — the API
+ `result`, unwrapped (no `{success, errors, result_info}` envelope);
+ a change that returns no data prints nothing; text and binary
+ responses (`dns records export`, `r2 objects get`) print raw. Status
+ lines and errors go to stderr. There is **no output-format flag**
+ (`--json` etc. are rejected — yargs strict mode).
+- **No auto-pagination**: list commands return one page and drop
+ `result_info`; the node exposes `page` / `per_page`.
+- **Destructive commands need `--force`**: without it a non-interactive
+ run prints *"(non-interactive; pass --force to confirm)"* and
+ *"Aborted."* and **exits 0** having changed nothing. `dns_record_delete`
+ always passes `--force` (choosing the operation is the confirmation),
+ and `_run` turns that output into a `NodeUserError` for `custom`.
+- **Errors** are a box on stderr (`┌ Error │ ... └`; API errors add
+ `[<code>] <message>` and `<status> · HTTP <path>`) with exit 1.
+ `_run` raises `NodeUserError("cf <command> failed: <stderr tail>")`
+ plus a `hint` for known failures: no login / 401 (also
+ `requires_user_action=True`, and a note when only a `cfk_` key is
+ stored), several accounts, 403 permissions, the bun config-file limit,
+ "Zone not found". Timeouts read `cf <command> timed out after Ns`; an
+ install failure is a `NodeUserError` too.
+- **`custom` guards**: unbalanced quotes are a `NodeUserError`; sign-in
+ state changes (`auth login|logout|create|delete|activate|deactivate`,
+ `login`) are refused — they belong to the Credentials modal, and a
+ logout behind its back would leave the badge stale; `dev` (a
+ long-running local server) is refused.
+- No auth pre-flight (Stripe-strict): cf's own error surfaces.
## `graphql_query` — the GraphQL Analytics API
@@ -158,16 +282,15 @@ current deprecations table) and the DNS analytics REST API is
**removed 2026-12-01**; the official replacement for both is the
GraphQL Analytics API at `api.cloudflare.com/client/v4/graphql`. That
endpoint is **outside the REST OpenAPI schema** cf (and the official
-SDKs) are generated from — cf has no `graphql`/`api` passthrough — so
-the node's `graphql_query` operation calls the documented endpoint
-directly: one POST with `{query, variables}` + `Bearer` token
-(`_graphql_post`, ~30 lines of repo-standard httpx; there is no more
-official channel to rely on).
-
-- Requires the API token OR the Global API Key + email (both
- documented GraphQL auth schemes); without either the op raises
- `NodeUserError` with the credential guidance. 401/403 map to the
- same fix message. Hard GraphQL errors (no `data`) surface as
+SDKs) are generated from — cf has no `graphql` or raw-request command —
+so the node calls it directly: one POST with `{query, variables}`
+(`_graphql_post`).
+
+- Requires the stored API token or Global API Key + email (else the
+ `CLOUDFLARE_API_TOKEN` / `CLOUDFLARE_API_KEY` + `CLOUDFLARE_EMAIL`
+ server env); without one the op raises `NodeUserError` with the
+ credential guidance and `requires_user_action=True`. 401/403 map to
+ the permission fix. Hard GraphQL errors (no `data`) surface as
`NodeUserError`; partial data rides back in `result`.
- Key datasets: zone traffic `httpRequestsAdaptiveGroups` (under
`viewer.zones`), Web Analytics/RUM `rumPageloadEventsAdaptiveGroups`
@@ -177,50 +300,27 @@ official channel to rely on).
- Limits: 300 queries per 5-minute window; one query spans <= 10 zones
or 1 account; Adaptive Bit Rate sampling on wide ranges (multiply by
`sampleInterval`).
-- The skill carries Cloudflare's own migration-guide queries verbatim.
-
-## Operations -> argv (verified against [email protected] `--help-full`)
-
-| Operation | argv / call |
-|---|---|
-| `whoami` | `auth whoami` |
-| `zones_list` | `zones list [--name <f>] [--account-id <id>]` |
-| `dns_records_list` | `dns records list --zone <zone>` |
-| `dns_record_create` | `dns records create --zone <zone> --body <json>` (`--body` is the schema-stable escape hatch; per-field flags churn) |
-| `dns_record_delete` | `dns records delete <record_id> --zone <zone>` (positional id) |
-| `graphql_query` | POST `client/v4/graphql` (not the CLI) |
-| `custom` | `shlex.split(command)` — anything after `cf ` (incl. `agent-context <product>` and `schema <cmd>` for discovery) |
-
-`zone` accepts a zone ID or domain name (global `-z/--zone`). cf 0.2.0
-prints JSON to stdout by default (status noise on stderr) so parsed
-results flow into `result`; `_parse_ndjson` in `_shape` recovers
-multi-object stdout that defeats `run_cli_command`'s single
-`json.loads`. No auth pre-flight (Stripe-strict): cf's own "Not logged
-in" error surfaces via the `NodeUserError` wrap.
-
-## What the OAuth login CAN do vs what needs a stored credential
-
-| Surface | OAuth login | API token | Global API Key + email |
-|---|---|---|---|
-| zones / DNS records / accounts / registrar | yes | yes | yes |
-| `cf dns analytics` (REST, dies 2026-12-01) | yes (`dns_analytics:read`) | yes | yes |
-| `graphql_query` (zone traffic, RUM, DNS analytics) | **no — no scope exists** | yes (`Account Analytics: Read` / `Zone Analytics: Read`) | yes (full access) |
-| `rum/site_info` config endpoints (no cf command yet; `custom`/httpRequest) | **no** | yes | yes |
-| Endpoints the account-token compatibility matrix excludes | no | varies | yes |
+- Web Analytics site configuration is a (hidden) cf command group:
+ `rum site-info list|get|create|update|delete`, reachable via `custom`.
## Invariants locked by `test_cloudflare_plugin.py`
-Pinned `_NPM_SPEC` (never `@latest`); no `shutil.which("cf")`; per-op
-argv shapes incl. `--body`/positional-delete; `login_env` strips all
-six ambient vars; stored token injected on ops, never on login;
-single-flight login; **no `.kill(`/`.terminate(` in `_complete_login`**;
-no URL/`verification_code` in the login response; whoami-gated
-completion via the shared `_cli_auth` marker + broadcasts; catalogue =
-vercel dual-path shape (`apiKey` + `cloudflare_email`, both optional);
-prefix-routed probe (cfk_ no-email guidance without a network call,
-cfk_+email via X-Auth `GET /user`, cfat_ via `GET /accounts`,
-cfut_/legacy via the verify endpoint); `cf_env` global-key pair
-injection with ambient-token drop; `api_auth_headers` Bearer-vs-X-Auth
-routing; GraphQL endpoint constant + official body shape + 403
-credential guidance; folder assets (no `icon.svg`, `#F38020`, both
-visuals entries, paired skill).
+Pinned `_NPM_SPEC` (never `@latest`); version-enforcing install (older
+version -> reinstall + marker cleared; matching -> reused;
+`cf_cli_path()` ignores older versions); no `shutil.which("cf")`;
+`cf_env` hygiene (`CF_DELEGATION`, telemetry off, `NO_COLOR`), stored
+token injected, Global API Key never, `account_id` ->
+`CLOUDFLARE_ACCOUNT_ID`; `login_env` strips the token vars; typed ops
+run from `cf_workdir()`, `custom` from the workspace; per-op argv shapes
+incl. `--force` on delete, PATCH edit, domain -> zone ID lookup,
+filters + paging; failure hints (`requires_user_action` for no login);
+"Aborted." is an error; `custom` guards; operation enum == implemented
+operations, every operation named in `tool_description`; device-flow
+login (URL + code relayed, repeat click returns the same code, install
+before any login, whoami short-circuit, **no `.kill(`/`.terminate(` in
+the login code**, whoami-gated completion via the shared `_cli_auth`
+marker + broadcasts); catalogue = vercel dual-path shape (`apiKey` +
+`cloudflare_email`, both optional); prefix-routed probe; GraphQL
+endpoint constant + official body shape + 403 credential guidance;
+folder assets (no `icon.svg`, `#F38020`, both visuals entries, paired
+skill).
diff --git a/docs-internal/gcloud_service.md b/docs-internal/gcloud_service.md
index 81f09dbf..258d096b 100644
--- a/docs-internal/gcloud_service.md
+++ b/docs-internal/gcloud_service.md
@@ -9,13 +9,15 @@ Storage) plus a `custom` passthrough covering the entire gcloud surface
(IAM, Cloud SQL, Functions, GKE, logging, `services enable`, ...).
**Auth model: the gcloud CLI owns its own auth** — the Stripe/gh
-pattern, with the cloudflare login variant (the CLI opens the browser
-itself). OpenCompany never stores, reads, or injects a credential:
+pattern, with the CLI-opens-the-browser login variant (the one the
+Cloudflare plugin used before cf 1.0 moved to device authorization).
+OpenCompany never stores, reads, or injects a credential:
- `gcloud auth login --quiet` runs Google's OAuth flow with a loopback
callback on a **random port** and opens the default browser itself —
the handler never parses or proxies the authorize URL (no custom
- login UI; cf precedent, minus cf's fixed-port collision hazard).
+ login UI; the pre-1.0 cf precedent, minus its fixed-port collision
+ hazard).
- Credentials land in **gcloud's own store under the pinned config
dir** (see isolation below), not the operator's global gcloud state.
- The credentials modal's connected badge is a synthetic `cli-managed`
@@ -91,7 +93,7 @@ calls.
and returns `{success, message}` — no url/verification_code (the CLI
opens the browser itself). Fast path: if `active_account()` is already
truthy the handler marks + returns without spawning. Hazards handled
-(cf precedent): single-flight guard (repeat clicks return "already in
+(inherited from the pre-1.0 cf plugin): single-flight guard (repeat clicks return "already in
progress" instead of a second browser tab), pipes drained for the
process lifetime, and the completion watcher **never kills the
process** — on Windows `gcloud.cmd` is a cmd.exe shim around the
diff --git a/docs-internal/gcp_vm_deploy_runbook.md b/docs-internal/gcp_vm_deploy_runbook.md
index 24a3a046..04f2ed3e 100644
--- a/docs-internal/gcp_vm_deploy_runbook.md
+++ b/docs-internal/gcp_vm_deploy_runbook.md
@@ -329,18 +329,20 @@ Skipping this step is fine: the app is fully reachable at `http://<STATIC_IP>` (
`https://<STATIC_IP>` with a browser cert warning). If you skip it, set
`JWT_COOKIE_SECURE=false` in step 2 (pitfall 11) or browser login will bounce.
-The `cf` CLI needs an account + zone context once, and `records create` takes a raw
-JSON `--body` (individual flags like `--type/--name` are NOT supported):
+The `cf` CLI (1.0 and later) takes the account and zone from the environment — the
+old `cf context set` commands are gone — and `records create` takes a raw JSON
+`--body` (individual flags like `--type/--name` are NOT supported):
```bash
-cf zones list # find the zone; grab account id from the output
-cf context set account-id <ACCOUNT_ID>
-cf context set zone <ZONE_DOMAIN> # e.g. opencompany.sh
-cf dns records list # check the name is free
+cf zones list --name <ZONE_DOMAIN> # e.g. opencompany.sh; note the zone "id" and "account" id
+export CLOUDFLARE_ACCOUNT_ID=<ACCOUNT_ID> # needed when the login can see more than one account
+export CLOUDFLARE_ZONE_ID=<ZONE_ID>
+cf dns records list --name <SUBDOMAIN>.<ZONE_DOMAIN> # check the name is free
cf dns records create --body '{"type":"A","name":"<SUBDOMAIN>","content":"<STATIC_IP>","proxied":true,"ttl":1,"comment":"OpenCompany VM <ZONE> (gcloud, opencompany@latest)"}'
```
-Delete a record by id: `cf dns records delete <RECORD_ID>`.
+Delete a record by id: `cf dns records delete <RECORD_ID>` (cf asks to confirm; in a
+script add `--force`, or cf prints "Aborted." and exits 0 without deleting).
`proxied: true` matches the zone's other app records; Cloudflare terminates public TLS
and (in Full SSL mode) connects to the origin's self-signed :443.
@@ -425,8 +427,8 @@ Origin CA cert.
gcloud compute instances delete <VM_NAME> --zone=<ZONE> --project=<PROJECT> --quiet
gcloud compute addresses delete <IP_NAME> --region=<REGION> --project=<PROJECT> --quiet
gcloud compute firewall-rules delete opencompany-allow-http --project=<PROJECT> --quiet
-cf dns records list # find the record id
-cf dns records delete <RECORD_ID>
+cf dns records list --zone <ZONE_ID> # find the record id
+cf dns records delete <RECORD_ID> --zone <ZONE_ID>
```
## Operations cheat sheet
diff --git a/docs-internal/node-logic-flows/cli_integrations/cloudflareAction.md b/docs-internal/node-logic-flows/cli_integrations/cloudflareAction.md
index 855ed137..5609006a 100644
--- a/docs-internal/node-logic-flows/cli_integrations/cloudflareAction.md
+++ b/docs-internal/node-logic-flows/cli_integrations/cloudflareAction.md
@@ -3,50 +3,56 @@
| Field | Value |
|------|-------|
| **Category** | deployment (palette group `deployment`; class `group = ("deployment", "tool")`) |
-| **Backend handler** | [`server/nodes/cloudflare/cloudflare_action.py`](../../../server/nodes/cloudflare/cloudflare_action.py) (`CloudflareActionNode`, on `ActionNode`); env / credential routing in [`_service.py`](../../../server/nodes/cloudflare/_service.py); installer [`_install.py`](../../../server/nodes/cloudflare/_install.py); login WS handlers [`_handlers.py`](../../../server/nodes/cloudflare/_handlers.py) |
+| **Backend handler** | [`server/nodes/cloudflare/cloudflare_action.py`](../../../server/nodes/cloudflare/cloudflare_action.py) (`CloudflareActionNode`, on `ActionNode`); env / credential routing and the neutral working directory in [`_service.py`](../../../server/nodes/cloudflare/_service.py); installer [`_install.py`](../../../server/nodes/cloudflare/_install.py); login WS handlers [`_handlers.py`](../../../server/nodes/cloudflare/_handlers.py) |
| **Tests** | [`server/tests/test_cloudflare_plugin.py`](../../../server/tests/test_cloudflare_plugin.py) |
| **Skill (if any)** | [`server/skills/cloudflare/cloudflare-skill/SKILL.md`](../../../server/skills/cloudflare/cloudflare-skill/SKILL.md) (`allowed-tools: "cloudflare"`) |
| **Dual-purpose tool** | yes - tool name `cloudflare` |
## Purpose
-Drive Cloudflare through the official `cf` CLI (npm `[email protected]`, a technical
-preview) from a workflow or from an agent. Six typed operations cover auth
-identity, zone listing and DNS record CRUD, one operation posts directly to
-the GraphQL Analytics API (the only channel to zone traffic / RUM analytics,
-which the cf OAuth grant cannot reach), and `custom` passes any `cf ...`
-command through verbatim. The CLI owns its own auth: the node performs no
-credential pre-flight and never injects a token into argv.
+Drive Cloudflare through the official `cf` CLI (npm `[email protected]`, in
+open beta) from a workflow or from an agent. Typed operations cover the
+CLI identity, a command search, zone listing and DNS record list / create /
+edit / delete; one operation posts directly to the GraphQL Analytics API
+(cf has no GraphQL command); `custom` passes any other `cf ...` command
+through. The CLI owns its own auth: the node performs no credential
+pre-flight and never puts a token in argv.
## Inputs (handles)
| Handle | Connection type | Required | Purpose |
|--------|-----------------|----------|---------|
-| `input-main` | main | no | Declared, but `hideInputHandle` is auto-set (`usable_as_tool = True` and the class does not declare `hide_input_handle`) - the node is normally reached through `output-tool` |
+| `input-main` | main | no | Declared, so it renders on the canvas although `hideInputHandle` is auto-set (`usable_as_tool = True`); the node is usually reached through `output-tool` |
## Parameters
-`extra="ignore"` on the model. `record_body` and `graphql_variables` have a
-`mode="before"` validator that `json.dumps` a dict / list (LLM tool calls pass
-real objects; the CLI flag and HTTP body want a string).
+`extra="ignore"` on the model. A `mode="before"` model validator
+(`coerce_blank_params`) drops panel blanks for the integer fields, and
+`record_body` / `graphql_variables` have a `mode="before"` validator that
+`json.dumps` a dict / list (LLM tool calls pass real objects; the CLI flag
+and HTTP body want a string).
| Name | Type | Default | Required | displayOptions.show | Description |
|------|------|---------|----------|---------------------|-------------|
-| `operation` | `whoami \| zones_list \| dns_records_list \| dns_record_create \| dns_record_delete \| graphql_query \| custom` | `whoami` | no | - | Operation dispatch key |
-| `zone` | string | `""` | yes* | `operation` in `dns_records_list`, `dns_record_create`, `dns_record_delete` | Zone ID or domain name; becomes the global `--zone` flag. Empty raises `NodeUserError` on any DNS op |
-| `name_filter` | string | `""` | no | `operation=zones_list` | `--name <f>` when non-blank |
-| `account_id` | string | `""` | no | `operation=zones_list` | `--account-id <id>` when non-blank |
-| `record_body` | string (JSON) | `""` | yes* | `operation=dns_record_create` | Raw JSON request body passed as `--body`; validated with `json.loads` first |
-| `record_id` | string | `""` | yes* | `operation=dns_record_delete` | Positional record id for `dns records delete` |
+| `operation` | `whoami \| search_commands \| zones_list \| dns_records_list \| dns_record_create \| dns_record_edit \| dns_record_delete \| graphql_query \| custom` | `whoami` | no | - | Operation dispatch key |
+| `account_id` | string | `""` | no | `zones_list`, the four `dns_*` ops, `custom` | Sent as `CLOUDFLARE_ACCOUNT_ID` (cf has no `--account-id` flag on most commands); `zones_list` also passes it as `--account-id` |
+| `zone` | string | `""` | yes* | the four `dns_*` ops | Zone ID or domain; a domain is resolved to its ID first (see Decision Logic). Empty raises `NodeUserError` |
+| `name_filter` | string | `""` | no | `zones_list`, `dns_records_list` | `--name <f>` (a domain for zones, a full record name for DNS) |
+| `record_type` | string | `""` | no | `dns_records_list` | `--type`, upper-cased |
+| `page` | int \| null | `null` | no | `zones_list`, `dns_records_list` | `--page N` (>= 1) |
+| `per_page` | int \| null | `null` | no | `zones_list`, `dns_records_list` | `--per-page N` (>= 1) |
+| `record_body` | string (JSON object) | `""` | yes* | `dns_record_create`, `dns_record_edit` | Passed as `--body`; must parse as a JSON object |
+| `record_id` | string | `""` | yes* | `dns_record_edit`, `dns_record_delete` | Positional record id |
| `graphql_query` | string | `""` | yes* | `operation=graphql_query` | GraphQL Analytics API query text |
| `graphql_variables` | string (JSON object) | `""` | no | `operation=graphql_query` | Parsed with `json.loads`; invalid JSON raises `NodeUserError` |
+| `search_query` | string | `""` | yes* | `operation=search_commands` | The task to find a command for (`cf cli search`) |
| `command` | string | `""` | yes* | `operation=custom` | Everything after `cf `, split with `shlex.split` |
## Outputs (handles)
| Handle | Shape | Description |
|--------|-------|-------------|
-| `output-main` | object | `CloudflareActionOutput`; `hideOutputHandle` auto-set like the input |
+| `output-main` | object | `CloudflareActionOutput`; declared, so it renders although `hideOutputHandle` is auto-set |
| `output-tool` | - | Auto-appended for `usable_as_tool` |
### Output payload (TypeScript shape)
@@ -59,9 +65,9 @@ preserves that). `extra="allow"`.
operation: string;
success: true; // failures raise instead of returning
url?: string; // custom only: stdout that is one line starting with "http"
- result?: unknown; // parsed JSON stdout (or NDJSON recovered as an array), or the GraphQL body
- stdout?: string; // raw stdout ONLY when nothing parsed as JSON
- stderr_tail?: string; // last 2000 chars of stderr, present even on success (cf status noise)
+ result?: unknown; // parsed JSON stdout (cf prints the unwrapped API result), or the GraphQL body
+ stdout?: string; // raw stdout ONLY when it did not parse as JSON (e.g. a BIND export)
+ stderr_tail?: string; // last 2000 chars of stderr when cf printed status lines
}
```
@@ -70,41 +76,59 @@ preserves that). `extra="allow"`.
```mermaid
flowchart TD
A[Validate params] --> B{operation}
- B -- whoami --> R[_run: ensure_cf_cli -> run_cli_command argv, env=cf_env token,email]
- B -- zones_list --> Z[argv zones list + optional --name / --account-id] --> R
- B -- dns_records_list --> D1[require zone] --> R
- B -- dns_record_create --> D2[require zone + record_body, json.loads check] --> R
- B -- dns_record_delete --> D3[require zone + record_id] --> R
- B -- custom --> C[require command, shlex.split, timeout 300s] --> R
+ B -- whoami --> R[_run: ensure_cf_cli -> run_cli_command argv, env=cf_env token,account_id, cwd=cf_workdir]
+ B -- search_commands --> Q[require search_query, argv cli search query] --> R
+ B -- zones_list --> Z[argv zones list + optional --name / --account-id / --page / --per-page] --> R
+ B -- dns_records_list / create / edit / delete --> D[require record_id / record_body where needed]
+ D --> ZI{zone is a 32-hex ID or UUID?}
+ ZI -- no --> ZL[_run zones list --name domain] --> ZR{exactly one zone id?}
+ ZR -- none or several --> ERR3[NodeUserError: zone not found / set account_id]
+ ZR -- one --> ZID[zone id]
+ ZI -- yes --> ZID
+ ZID --> R
+ B -- custom --> C[shlex.split, drop leading cf, refuse sign-in / dev, cwd = workspace, timeout 300s] --> R
B -- graphql_query --> G[require graphql_query, parse graphql_variables]
G --> K{stored token or CLOUDFLARE_API_TOKEN / CLOUDFLARE_API_KEY env}
- K -- none, or cfk_ without email --> ERR[NodeUserError: credential guidance]
+ K -- none, or cfk_ without email --> ERR[NodeUserError: credential guidance, requires_user_action]
K -- ok --> P[POST client/v4/graphql, 60s httpx]
P -- 401/403 --> ERR
P -- non-JSON, >=400, or data null with errors --> ERR
P -- ok --> S[_shape: result = body]
- R -- install raised --> RT[RuntimeError cf CLI install failed]
- R -- exit != 0 or timeout --> ERR2[NodeUserError cf argv0 failed: stderr tail]
- R -- ok --> S2[_shape: parsed JSON -> result, else NDJSON, else stdout; stderr_tail]
+ R -- install raised --> RT[NodeUserError cf CLI install failed]
+ R -- exit != 0 or timeout --> ERR2[NodeUserError cf command failed: stderr tail + hint]
+ R -- exit 0 but Aborted --> ERR4[NodeUserError: add --force]
+ R -- ok --> S2[_shape: parsed JSON -> result, else stdout; stderr_tail]
S --> OUT[Return envelope]
S2 --> OUT
```
## Decision Logic
-- **Validation** (all `NodeUserError`): blank `zone` on any DNS op; blank
- `record_body` or `record_body` that is not JSON; blank `record_id`; blank
- `graphql_query`; `graphql_variables` that is not JSON; blank `command`.
+- **Validation** (all `NodeUserError`, raised before any CLI call): blank
+ `zone` on a DNS op; blank or non-object `record_body`; blank `record_id`;
+ blank `search_query`; blank `graphql_query`; `graphql_variables` that is
+ not JSON; blank or unparseable `command`.
- **No auth pre-flight**: `_run` never checks whether cf is logged in. cf's
- own "Not logged in" text arrives on stderr and is surfaced by the failure
- wrap.
-- **Credential routing for CLI ops** (`cf_env`): a stored key starting with
- `cfk_` plus a stored email becomes the `CLOUDFLARE_API_KEY` +
- `CLOUDFLARE_EMAIL` pair and the ambient `CLOUDFLARE_API_TOKEN` /
- `CF_API_TOKEN` are popped (cf ranks tokens above the key pair); any other
- stored key becomes `CLOUDFLARE_API_TOKEN`; a `cfk_` key without an email
- injects nothing and cf falls back to its own OAuth session. Ambient env
- vars are otherwise left in place for ops.
+ own "No authentication token found" text arrives on stderr and is
+ surfaced by the failure wrap.
+- **Zone resolution** (`_zone_id`): a 32-hex ID or UUID is used as-is.
+ Anything else is a domain: lower-cased, trailing dot dropped, looked up
+ with `zones list --name <domain> [--account-id <id>]` (exact match across
+ every account the credential sees). No match -> "Zone not found";
+ matches with different ids -> "set account_id". cf's own domain lookup is
+ avoided because it needs an account selected and searches only the
+ first page of that account's zones.
+- **Credential routing for CLI ops** (`cf_env`): a stored key that does not
+ start with `cfk_` becomes `CLOUDFLARE_API_TOKEN` (beats the OAuth login
+ and an ambient token); a `cfk_` Global API Key is not injected (cf does
+ not accept Global API Keys). `account_id` becomes `CLOUDFLARE_ACCOUNT_ID`.
+ `CF_DELEGATION=1`, `CF_SEND_TELEMETRY=false` and `NO_COLOR=1` are always
+ set. Ambient env vars are otherwise left in place.
+- **Working directory**: typed ops run from `cf_workdir()`
+ (`<DATA_DIR>/cloudflare`), so no stray `.env` or `cloudflare.config.ts`
+ is read; `custom` runs from the workflow workspace when it exists (else
+ `cf_workdir()`), so relative `--body @file` / `--file` / `--dir` paths
+ resolve there.
- **Credential routing for `graphql_query`** (`api_auth_headers`): key from
the stored `cloudflare` row, else `CLOUDFLARE_API_TOKEN`, else
`CLOUDFLARE_API_KEY` env; email from the stored `cloudflare_email` row,
@@ -116,45 +140,61 @@ flowchart TD
(`data` is null and `errors` present) -> `NodeUserError` with the first
error's `message`; otherwise the whole body (including partial `errors`)
is returned as `result`.
-- **Output shaping** (`_shape`): `run_cli_command` already ran a single
- `json.loads` on stdout; when that is `None` and stdout has two or more
- non-blank lines, every line is parsed as JSON (`_parse_ndjson`) - one
- failure abandons the attempt and stdout ships as text. `url` is set only by
- `custom`, and only when stdout is a single line starting with `http`.
-- **Timeouts**: 120 s for the typed CLI ops, 300 s for `custom`, 60 s for the
- GraphQL POST. `run_cli_command` kills the process tree on timeout and
- returns `success: False` with `error: "<binary> timed out (Ns)"`, which the
- failure wrap turns into a `NodeUserError`.
+- **Failure hints** (`_failure`, on the `NodeUserError`): no login / 401 ->
+ connect in Credentials -> Cloudflare, `requires_user_action=True` (plus a
+ note when only a `cfk_` key is stored); "More than one account" -> set
+ `account_id`; 403 -> missing token permission; "not supported on Bun" ->
+ the command needs Node.js 22.18+; "Zone not found" -> pass the zone ID.
+- **Unconfirmed destructive commands**: cf exits 0 with "Aborted." when a
+ destructive command lacks `--force`; `_run` raises a `NodeUserError`
+ asking for `--force`. `dns_record_delete` always passes `--force`.
+- **`custom` guards**: `auth login|logout|create|delete|activate|deactivate`
+ and `login` are refused (sign-in belongs to the Credentials modal), as is
+ `dev` (a long-running local server). A leading `cf` / `cloudflare` word
+ is dropped.
+- **Output shaping** (`_shape`): `run_cli_command` already ran `json.loads`
+ on stdout (cf prints one pretty-printed document); when that is `None`,
+ non-empty stdout ships as text. `url` is set only by `custom`, and only
+ when stdout is a single line starting with `http`.
+- **Timeouts**: 120 s for the typed CLI ops (and the zone lookup), 300 s for
+ `custom`, 60 s for the GraphQL POST. `run_cli_command` kills the process
+ tree on timeout; the wrap reports `cf <command> timed out after Ns`.
- **Error paths**: `ensure_cf_cli()` raising (bun missing, `bun add`
- failing) -> `RuntimeError("cf CLI install failed: ...")`, which is NOT a
- `NodeUserError` and therefore takes `BaseNode.execute`'s generic exception
- branch (full traceback). Non-zero exit -> `NodeUserError("cf <argv0>
- failed: <last 2000 chars of stderr>")`, falling back to the envelope
- `error` when stderr is empty.
+ failing) -> `NodeUserError("cf CLI install failed: ...")` with a hint.
+ Non-zero exit -> `NodeUserError("cf <command> failed: <last 2000 chars of
+ stderr>")`, falling back to the envelope `error` when stderr is empty.
## Side Effects
-- **Subprocess**: one `cf` process per operation from the project-local
- shim `<DATA_DIR>/packages/node_modules/.bin/cf` (`cf.exe` plus a `cf.bunx`
- file on Windows — bun's shims, never `.cmd`), which runs the CLI on bun.
- The system-global `cf` is never consulted. Child env is a copy of the
- server env plus `NO_COLOR=1` and the credential vars above; no `cwd` is
- passed (the process inherits the server's cwd - the workflow workspace is
- not used).
-- **Install**: on first use `core.js_runtime.add_package("[email protected]")` — `bun add
- --cwd <DATA_DIR>/packages --no-progress [email protected]` — runs in a worker thread
- under an install lock.
-- **External API calls**: `POST https://api.cloudflare.com/client/v4/graphql`
- with `{query, variables}` (`graphql_query` only).
-- **Credential reads**: `auth_service.get_api_key("cloudflare")` and
- `get_api_key("cloudflare_email")` on every `_run` and every GraphQL call.
+- **Subprocess**: one `cf` process per operation (two for a DNS op given a
+ domain) from the project-local shim `<DATA_DIR>/packages/node_modules/.bin/cf`
+ (`cf.exe` plus a `cf.bunx` file on Windows — bun's shims, never `.cmd`),
+ which runs the CLI on bun (or Node when one is on PATH). The system-global
+ `cf` is never consulted. Child env is a copy of the server env plus the
+ vars above.
+- **Install**: on first use, or when another cf version is installed,
+ `core.js_runtime.add_package("[email protected]")` — `bun add --cwd
+ <DATA_DIR>/packages --no-progress [email protected]` (about 300 MB with
+ miniflare + workerd) — runs in a worker thread under an install lock. A
+ version change also clears the Cloudflare login marker and broadcasts
+ `credential.oauth.disconnected`.
+- **Files**: cf may cache the auto-selected account under
+ `<DATA_DIR>/cloudflare/.cloudflare/cache/` (or the workspace, for
+ `custom`).
+- **External API calls**: cf's own calls to `api.cloudflare.com` (30 s per
+ request, no retries); `POST https://api.cloudflare.com/client/v4/graphql`
+ with `{query, variables}` (`graphql_query` only). `search_commands` is
+ local.
+- **Credential reads**: `auth_service.get_api_key("cloudflare")` on every
+ CLI call, plus `get_api_key("cloudflare_email")` for GraphQL.
- **Cost metadata**: every operation declares
`cost={"service": "cloudflare", "action": "<operation>", "count": 1}`.
- **Broadcasts**: standard node status via `BaseNode.execute`; nothing
- plugin-specific. (Login / logout / status broadcasts belong to the WS
- handlers `cloudflare_login` / `cloudflare_logout` / `cloudflare_status`,
- not to this node.)
-- **Database writes**: none by the node.
+ plugin-specific beyond the upgrade marker clear. (Login / logout / status
+ belong to the WS handlers `cloudflare_login` / `cloudflare_logout` /
+ `cloudflare_status`, not to this node.)
+- **Database writes**: none by the node, apart from the upgrade marker
+ clear.
## External Dependencies
@@ -162,39 +202,41 @@ flowchart TD
`auth = "custom"`). `resolve()` returns the optional
`cloudflare_api_token` (stored under the provider id `cloudflare`; an API
token or a `cfk_` Global API Key) and `cloudflare_email`. The cf OAuth
- session created by `cf auth login` lives in cf's own user-level config and
- is never read by OpenCompany; the modal badge is a synthetic `cli-managed`
- marker OAuth row written by `_handlers.py`.
-- **Services**: the `cf` CLI (declares `engines.node >= 22`, which bun ignores —
- it runs on bun with no Node on PATH; `bun` on PATH or `OPENCOMPANY_BUN_BIN`
- for the install);
- Cloudflare's dashboard OAuth for login (cf opens the browser itself and
- listens on a fixed loopback port it owns - see `_handlers.py` for the
- single-flight guard and the never-kill rule).
+ login lives in cf's own profile store
+ (`<xdg-config>/cloudflare/config/default.json`) and is never read by
+ OpenCompany; the modal badge is a synthetic `cli-managed` marker OAuth
+ row written by `_handlers.py`.
+- **Services**: the `cf` CLI (declares `engines.node >= 22`; runs on bun for
+ every API command, `bun` on PATH or `OPENCOMPANY_BUN_BIN` for the
+ install); Cloudflare's OAuth device authorization for login (URL + code
+ shown in the modal; see `_handlers.py`).
- **Python packages**: `httpx`, `pydantic`; `services.events.run_cli_command`.
-- **Environment variables**: `CLOUDFLARE_API_TOKEN`, `CF_API_TOKEN`,
- `CLOUDFLARE_API_KEY`, `CF_API_KEY`, `CLOUDFLARE_EMAIL`, `CF_EMAIL`
+- **Environment variables**: `CLOUDFLARE_API_TOKEN`, `CF_API_TOKEN`
(ambient values honoured for ops, stripped for login / whoami / logout),
- `NO_COLOR`.
+ `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_ZONE_ID` (read by cf), and
+ `CLOUDFLARE_API_KEY` / `CLOUDFLARE_EMAIL` (GraphQL fallback only). Set
+ for the child: `NO_COLOR`, `CF_DELEGATION`, `CF_SEND_TELEMETRY`.
## Edge cases & known limits
-- `annotations` declare `destructive: False` although `dns_record_delete`
- deletes records (gcloud, by contrast, declares `destructive: True`).
+- `annotations` declare `destructive: True` (`dns_record_delete`, and
+ `custom` can run any destructive command with `--force`).
- `ui_hints = {"outputMode": "terminal"}`: text output renders
preformatted; JSON `result` renders as a tree.
-- `stderr_tail` is populated on success too, because cf prints status noise
- on stderr.
-- `custom` can run any cf subcommand including `auth login` / `auth logout`;
- those run with `cf_env`, not `login_env`, so ambient credential vars are
- NOT stripped there (only the WS login handlers strip them).
-- The GraphQL op ignores the cf OAuth session entirely: the fixed 86-scope
- grant has no analytics scope, so only a stored / ambient token or Global
- API Key can satisfy it.
-- `whoami` under an ambient `CLOUDFLARE_API_TOKEN` reports the env token,
- not the OAuth session (that is why the WS status handler uses `login_env`).
-- Argv shapes are verified only against the pinned `[email protected]`; the preview
- CLI's surface drifts between versions.
+- Lists return one page; `result_info` (totals, cursors) is dropped by cf,
+ so cursor-paginated lists (`kv keys list`, `r2 objects list`) cannot be
+ followed past the first page from CLI output.
+- Project commands (`init`, `build`, `dev`, `deploy`) need Node.js 22.18+;
+ under bun, any command that finds a `cloudflare.config.ts` above its
+ working directory fails. `custom` runs from the workspace, so a
+ `cloudflare.config.ts` written there affects later `custom` calls.
+- The GraphQL op ignores the cf OAuth login entirely: the token never
+ leaves the CLI, so only a stored / ambient token or Global API Key can
+ satisfy it.
+- `whoami` under a stored or ambient API token reports that token, not the
+ OAuth login (that is why the WS status handler uses `login_env`).
+- Argv shapes are verified only against the pinned `[email protected]`; the
+ beta CLI's surface can change between releases.
## Related
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index f71129cf..f7467d47 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -202,29 +202,30 @@ packages tree, the bin shim then running on bun — instead of a
GitHub-release download. Reference: [`server/nodes/vercel/`](../server/nodes/vercel/)
+ [vercel_service.md](./vercel_service.md).
-**CLI-opens-the-browser variant (Cloudflare).** Some CLIs run the
-whole browser interaction themselves: `cf auth login` starts a loopback
-PKCE callback server on a **fixed port** (8877) and opens the default
-browser directly. The login handler then proxies NOTHING to the modal
-(no URL, no verification code — just `{success, message}`); the badge
-flips when the background completion broadcasts. Two hazards force the
-handler's shape: concurrent logins collide on the fixed port
-(single-flight guard: repeat clicks return "already in progress"), and
-on Windows killing bun's `.exe` launcher shim orphans the child bun
-process still holding the port (the completion watcher never kills — the CLI's own
-login timeout ends it). Success gate = a CLI status probe that parses
-JSON, never exit codes (`cf auth whoami` exits 0 in both auth states).
-When the CLI's OAuth grant is a fixed scope set (cf: 86 scopes, no
-`--scopes`), pair it with an optional API-token field (vercel dual-path)
-as the documented full-scope escape. Reference:
+**CLI-opens-the-browser variant (gcloud).** Some CLIs run the whole
+browser interaction themselves: `gcloud auth login --quiet` starts a
+loopback callback server and opens the default browser directly. The
+login handler then proxies NOTHING to the modal (no URL, no
+verification code — just `{success, message}`); the badge flips when the
+background completion broadcasts. A single-flight guard (repeat clicks
+return "already in progress") prevents duplicate browser tabs — and,
+for a CLI whose callback port is fixed, port collisions — and the
+completion watcher never kills the process: on Windows killing a
+launcher shim orphans the child still serving the callback, and the
+CLI's own login timeout ends it. Success gate = a CLI status probe that
+parses JSON, never exit codes. gcloud also pins `CLOUDSDK_CONFIG` so
+node auth state never touches the operator's own gcloud config.
+Reference: [`server/nodes/gcloud/`](../server/nodes/gcloud/) +
+[gcloud_service.md](./gcloud_service.md). Cloudflare used this variant
+until cf 1.0 made device authorization its default login; it now
+follows the gh device-flow shape (URL + code relayed to the modal,
+`--no-browser` so the server never opens a second tab), keeps the
+single-flight guard (a repeat click returns the same code) and the
+never-kill rule, installs the CLI before spawning any login so no code
+is issued after its request was answered, and pairs the login with an
+optional API-token field (vercel dual-path) for unattended use:
[`server/nodes/cloudflare/`](../server/nodes/cloudflare/) +
-[cloudflare_service.md](./cloudflare_service.md). gcloud is the second
-reference for this variant (`gcloud auth login --quiet`; random
-loopback port, so no fixed-port collision — the single-flight guard is
-kept anyway to prevent duplicate browser tabs, and it adds a pinned
-`CLOUDSDK_CONFIG` dir so node auth state never touches the operator's
-own gcloud config): [`server/nodes/gcloud/`](../server/nodes/gcloud/) +
-[gcloud_service.md](./gcloud_service.md).
+[cloudflare_service.md](./cloudflare_service.md).
## What auto-wires (don't write it yourself)
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index ad973e93..55d556dd 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -1084,7 +1084,7 @@
"secret": true,
"placeholder": "API token (cfut_/cfat_) or Global API Key (cfk_)",
"required": false,
- "help": "Takes precedence over CLI login on every call. The OAuth login carries a fixed scope set with no analytics access beyond DNS — for Web Analytics (RUM), zone analytics, or the GraphQL Analytics API use either: an API token from dash.cloudflare.com/profile/api-tokens with 'Account > Account Analytics > Read' (plus 'Zone > Analytics > Read' for zone-scoped queries), or your Global API Key (cfk_..., full access — also covers endpoints the account-token matrix excludes) together with the Account Email below. The Login button works without it."
+ "help": "An API token from dash.cloudflare.com/profile/api-tokens takes precedence over the CLI login on every call and suits unattended use. The GraphQL Analytics operation (zone traffic, Web Analytics/RUM) always needs a credential here, because the CLI login stays inside the cf CLI: an API token with 'Account > Account Analytics > Read' (plus 'Zone > Analytics > Read' for zone-scoped queries), or your Global API Key (cfk_...) together with the Account Email below. The cf CLI itself does not accept Global API Keys. The Login button works without this field."
},
{
"key": "cloudflare_email",
@@ -1092,10 +1092,10 @@
"type": "text",
"required": false,
"placeholder": "[email protected]",
- "help": "Only needed with a Global API Key (cfk_) — sent as X-Auth-Email / CLOUDFLARE_EMAIL alongside it. Scoped API tokens don't use it."
+ "help": "Only needed with a Global API Key (cfk_) — sent as X-Auth-Email alongside it on the GraphQL Analytics calls. Scoped API tokens don't use it."
}
],
- "instructions": "Two independent auth paths: click 'Login with Cloudflare' — the cf CLI (auto-installed on first use) opens your default browser itself and completes via a localhost callback (browser must run on this machine; the badge flips when the CLI finishes; token stored by cf, never by OpenCompany) — or paste an API token above for full-scope and headless use."
+ "instructions": "Two independent auth paths: click 'Login with Cloudflare' — the cf CLI (installed on first use; the first install downloads about 300 MB, click Login again when it finishes) opens Cloudflare's device page in your browser and shows a one-time code here; approve the request from any browser and the badge flips when the CLI finishes (token stored by cf, never by OpenCompany) — or paste an API token above for unattended use. Alternative: run 'cf auth login' in a terminal on this machine."
},
"gcloud": {
"name": "Google Cloud",
diff --git a/server/core/js_runtime.py b/server/core/js_runtime.py
index 405f93cb..c5826357 100644
--- a/server/core/js_runtime.py
+++ b/server/core/js_runtime.py
@@ -78,6 +78,25 @@ def ensure_shared_tree(root: Path | None = None) -> Path:
return tree
+def installed_version(name: str, root: Path | None = None) -> str | None:
+ """Version of ``name`` in the shared tree, from its
+ ``node_modules/<name>/package.json``; ``None`` when the package is not
+ installed or its manifest is unreadable.
+
+ An existing bin shim says nothing about which version it runs, so a
+ plugin that pins a version compares against this to notice that its
+ pin moved on (``bun add`` of the new pin replaces the old copy).
+ """
+ tree = root or packages_dir()
+ manifest = tree / "node_modules" / name / "package.json"
+ try:
+ data = json.loads(manifest.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ version = data.get("version") if isinstance(data, dict) else None
+ return version if isinstance(version, str) and version else None
+
+
def add_package(spec: str, *, trust: bool = False, root: Path | None = None) -> subprocess.CompletedProcess[str]:
"""Blocking ``bun add`` of ``spec`` into the shared tree.
@@ -102,6 +121,7 @@ __all__ = [
"bin_shim_name",
"bun_binary",
"ensure_shared_tree",
+ "installed_version",
"require_bun",
"shared_tree_bin",
]
diff --git a/server/nodes/README.md b/server/nodes/README.md
index ac848651..b6cf1933 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -160,7 +160,7 @@ browser/ — browser (installed Chrome/Edge/Chromium + browser-use CLI; Chro
stripe/ — Stripe (CLI passthrough action + signed-webhook trigger)
vercel/ — Vercel (CLI deploy / inspect / list / custom passthrough)
github/ — GitHub (gh CLI: clone / PRs / issues / custom; palette group "vcs")
-cloudflare/ — Cloudflare (cf CLI: zones / DNS / GraphQL analytics / custom; palette group "deployment")
+cloudflare/ — Cloudflare (cf CLI: command search / zones / DNS / GraphQL analytics / custom; palette group "deployment")
gcloud/ — Google Cloud (gcloud CLI: projects / Compute Engine / Cloud Run / Cloud Storage / custom; palette group "deployment")
speech/ — Provider-abstracted text_to_speech / speech_to_text (palette group "language").
One node per direction with a `provider` dropdown, not one node per vendor. Owns
diff --git a/server/nodes/cloudflare/__init__.py b/server/nodes/cloudflare/__init__.py
index 5cac49dd..c6f4aa85 100644
--- a/server/nodes/cloudflare/__init__.py
+++ b/server/nodes/cloudflare/__init__.py
@@ -2,13 +2,14 @@
official cf CLI.
Self-contained CLI-managed-auth plugin (Stripe/gh pattern): the cf CLI
-owns its auth end-to-end — ``cf auth login`` (PKCE OAuth with a
-loopback callback on localhost:8877) driven from the credentials modal
-(or the user's own terminal), token in cf's user-level config, a
+owns its auth end-to-end — ``cf auth login`` (OAuth device
+authorization; the URL + one-time code are shown in the credentials
+modal) or the user's own terminal, token in cf's own profile store, a
synthetic ``cli-managed`` marker OAuth row for the catalogue badge.
-OpenCompany never stores or injects a token. Headless alternative: an
-ambient ``CLOUDFLARE_API_TOKEN`` env var (cf's documented first-priority
-credential source) works for ops without any login.
+OpenCompany never reads that token. Headless alternative: an API token
+pasted in the modal, or an ambient ``CLOUDFLARE_API_TOKEN`` env var
+(cf's documented first-priority credential source), works for ops
+without any login.
"""
from __future__ import annotations
diff --git a/server/nodes/cloudflare/_credentials.py b/server/nodes/cloudflare/_credentials.py
index 0c418ab4..7b56e839 100644
--- a/server/nodes/cloudflare/_credentials.py
+++ b/server/nodes/cloudflare/_credentials.py
@@ -1,21 +1,23 @@
"""Cloudflare credential — thin marker (stripe idiom, vercel shape).
-Two independent auth paths, either is sufficient:
-
-* **CLI login** — ``cf auth login`` (browser OAuth, loopback callback)
- driven by the ``cloudflare_login`` WS handler; cf stores its own auth
- state in its user-level config, and a synthetic marker OAuth token
- flips the catalogue's ``stored`` flag. The OAuth grant carries a
- FIXED 86-scope set (only ``dns_analytics:read`` for analytics — no
- Web Analytics/RUM or zone-analytics scopes, and no way to request
- more).
+Two independent auth paths, either is sufficient for the CLI:
+
+* **CLI login** — ``cf auth login`` (OAuth device authorization: a URL
+ + one-time code relayed to the modal) driven by the
+ ``cloudflare_login`` WS handler; cf stores its own auth state in its
+ profile store, and a synthetic marker OAuth token flips the
+ catalogue's ``stored`` flag. The token never leaves the CLI, so the
+ login cannot serve the node's direct API calls (GraphQL Analytics).
* **API token** — the optional canonical ``apiKey`` field (stored under
the provider id ``cloudflare``; exposed to the node as
``cloudflare_api_token``), pasted in the credentials modal and injected as the
``CLOUDFLARE_API_TOKEN`` env var on every CLI invocation (token takes
precedence over CLI login, per cf's documented resolution order).
- This is the only path to endpoints outside the OAuth scope set
- (Web Analytics/RUM, GraphQL Analytics, zone analytics).
+ It is also what ``graphql_query`` authenticates with.
+
+The field also accepts a ``cfk_`` Global API Key (with the
+``cloudflare_email`` companion), but only for the direct API calls —
+the cf CLI does not accept Global API Keys.
"""
from __future__ import annotations
diff --git a/server/nodes/cloudflare/_handlers.py b/server/nodes/cloudflare/_handlers.py
index d8eee937..69cf7132 100644
--- a/server/nodes/cloudflare/_handlers.py
+++ b/server/nodes/cloudflare/_handlers.py
@@ -1,33 +1,47 @@
"""Cloudflare WebSocket handlers — the cf CLI owns its own auth (gh /
-Stripe CLI pattern), including the browser interaction.
-
-``cloudflare_login`` spawns cf's official login and lets the CLI drive
-the whole flow itself::
-
- cf auth login --force
-
-Source-verified behavior (cf 0.2.0 ``dist/auth-*.mjs`` + live capture):
-the flow runs a PKCE OAuth against ``dash.cloudflare.com/oauth2/auth``
-with a loopback callback server on the FIXED port ``localhost:8877``,
-and cf OPENS THE DEFAULT BROWSER ITSELF (``start`` / ``open`` /
-``xdg-open``). The handler deliberately does NOT parse or proxy the
-authorize URL to the frontend — no custom login UI; the modal just gets
-``{success, message}`` and the connected badge flips when the
-background completion broadcasts. Headless/remote deployments use
-``CLOUDFLARE_API_TOKEN`` instead (cf's documented first-priority
-credential source).
-
-Two hazards this module guards against (both observed live):
-
-* **Fixed callback port** — two concurrent ``cf auth login`` processes
- collide on 8877 and the second exits instantly with "Port already in
- use". A module-level single-flight guard makes repeat Login clicks
- return "already in progress" instead of spawning again.
-* **Windows shim orphaning** — the installed binary is an npm ``.cmd``
- shim; killing it terminates only the cmd.exe wrapper and orphans the
- node child, which keeps holding port 8877 and breaks every later
- login. The completion watcher therefore NEVER kills the process — cf
- enforces its own login timeout and exits by itself.
+Stripe CLI pattern); OpenCompany relays cf's device code to the modal.
+
+``cloudflare_login`` spawns cf's official login::
+
+ cf auth login --force --device --no-browser
+
+cf 1.0 signs in with the OAuth 2.0 Device Authorization Grant (RFC
+8628): it prints a verification URL and a one-time code on stderr, polls
+``dash.cloudflare.com`` until the user approves (at most 5 minutes), and
+exits. Source-verified banner (cf 1.0.0-beta.12, bundled
+``@cloudflare/workers-auth``)::
+
+ To authorize cf, please visit:
+
+ <verification_uri>
+
+ and enter the code:
+
+ <user_code>
+
+ You have 5 minutes to approve this request.
+
+The handler parses the URL + code and answers ``{success, url,
+verification_code}``: the frontend opens the URL in the user's own
+browser and shows the code (gh's device-flow shape). ``--no-browser``
+stops cf from also opening a tab on the server machine — a duplicate
+tab on a desktop install, a failure on a remote server. There is no
+callback server (cf's old ``localhost:8877`` flow is ``--no-device``
+only), so the login works from any machine.
+
+Single flight: while a login waits for approval, repeat clicks get the
+same URL + code back instead of a second device flow. The output pumps
+store the banner the moment it appears, so a click answered "still
+preparing" picks the code up on the next click.
+
+First use installs cf (~300 MB: miniflare + workerd ship with it) BEFORE
+any login is spawned — in the background when the install cannot finish
+inside the frontend's 30 s request window. No login runs while that
+install is in flight, so cf never issues a code nobody can see.
+
+The completion watcher never kills the login process: on Windows the
+binary is bun's ``cf.exe`` launcher shim, and killing it orphans the
+child bun process running the CLI. cf ends the device flow by itself.
Success gate: ``cf auth whoami`` reporting ``authenticated: true`` (cf
exits 0 in both auth states, so exit codes are never trusted). On
@@ -38,47 +52,60 @@ broadcast plumbing is the shared :mod:`services.cli_agent._cli_auth`
module (claude/codex/github all use it).
OpenCompany never stores or reads the actual token — it stays in cf's
-user-level config (``auth.jsonc`` / OS keyring).
+own profile store.
"""
from __future__ import annotations
import asyncio
-from typing import Any, Dict, List, Optional
+import re
+from typing import Any, Dict, List, Optional, Tuple
from fastapi import WebSocket
+from core.ansi import strip_ansi
from core.logging import get_logger
from services.cli_agent._cli_auth import broadcast_credential_event, mark_logged_in, mark_logged_out
from services.events import run_cli_command
-from ._install import ensure_cf_cli
-from ._service import login_env, whoami_snapshot
+from ._install import cf_cli_path, ensure_cf_cli
+from ._service import cf_workdir, login_env, whoami_snapshot
logger = get_logger(__name__)
-# --force: we only spawn when whoami reports no live session, so this
-# never discards a healthy login — it exists to push PAST a stale or
-# invalid stored token that would otherwise short-circuit the flow.
-_LOGIN_ARGS = ["auth", "login", "--force"]
+# --force: we only spawn when whoami reports no live login, so this never
+# discards a healthy one — it pushes past a stale or invalid stored token
+# that would otherwise end the run with "You are already logged in.".
+# --device pins cf's default flow; --no-browser leaves the URL to the
+# frontend.
+_LOGIN_ARGS = ["auth", "login", "--force", "--device", "--no-browser"]
+# Backstop only — cf abandons the device code after 5 minutes and exits.
_LOGIN_TIMEOUT_SECONDS = 600
-# The frontend drops WS requests after 30s. A first-ever login pays a
-# cold `bun add` inside this handler — answer within this budget no
-# matter what and let the flow continue in the background.
+# How long one request waits for the URL + code on cf's output.
+_BANNER_DEADLINE_SECONDS = 15
+# The frontend drops WS requests after 30 s — answer within this budget.
_RESPONSE_BUDGET_SECONDS = 22
-# Retained head of the CLI's output, used only for the failure log line.
-_OUTPUT_CAP_BYTES = 8192
+# Retained head of the CLI's output (banner parsing + failure log line).
+_OUTPUT_CAP_CHARS = 32768
+
+_URL_RE = re.compile(r"please visit:\s*(https?://\S+)", re.IGNORECASE)
+_CODE_RE = re.compile(r"enter the code:\s*([A-Za-z0-9][A-Za-z0-9-]*)", re.IGNORECASE)
+def _fresh_state() -> Dict[str, Any]:
+ """Single-flight state: ``task`` = the pre-spawn window (whoami probe
+ + spawn + banner wait), ``proc`` = the device flow until cf exits,
+ ``url``/``code`` = that flow's banner, ``install`` = a first-use
+ install running in the background."""
+ return {"task": None, "proc": None, "url": None, "code": None, "install": None}
+
+
+_active_login: Dict[str, Any] = _fresh_state()
+
# Strong refs for fire-and-forget tasks — asyncio holds only weak refs
# (the documented discard-set pattern from the asyncio docs).
_background_tasks: set = set()
-# Single-flight state: at most one login flow at a time (fixed callback
-# port). `task` covers the pre-spawn window (install + whoami probe),
-# `proc` covers the browser-flow window until cf exits on its own.
-_active_login: Dict[str, Any] = {"task": None, "proc": None}
-
def _spawn_background(coro) -> asyncio.Task:
task = asyncio.create_task(coro)
@@ -87,6 +114,39 @@ def _spawn_background(coro) -> asyncio.Task:
return task
+def _pending(message: str) -> Dict[str, Any]:
+ return {"success": True, "pending": True, "message": message}
+
+
+def _tail(output: List[str]) -> str:
+ lines = [ln.strip() for ln in strip_ansi("".join(output)).splitlines() if ln.strip()]
+ return " | ".join(lines[-5:]) or "(no output)"
+
+
+def parse_login_banner(text: str) -> Optional[Tuple[str, str]]:
+ """``(verification_url, user_code)`` once both appear in cf's
+ accumulated output; ``None`` while still waiting."""
+ clean = strip_ansi(text)
+ url_m = _URL_RE.search(clean)
+ code_m = _CODE_RE.search(clean)
+ if not (url_m and code_m):
+ return None
+ return url_m.group(1).rstrip(".,;)'\""), code_m.group(1)
+
+
+def _waiting_login() -> Optional[Dict[str, Any]]:
+ """The answer for a device flow that is still waiting for approval."""
+ proc = _active_login["proc"]
+ if proc is None or proc.returncode is not None or not _active_login["url"]:
+ return None
+ return {
+ "success": True,
+ "url": _active_login["url"],
+ "verification_code": _active_login["code"],
+ "message": "A Cloudflare login is waiting for approval — enter the code on the page that opened.",
+ }
+
+
def _login_in_progress() -> bool:
task = _active_login["task"]
if task is not None and not task.done():
@@ -101,22 +161,109 @@ async def _mark_connected(email: Optional[str]) -> None:
await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")
+async def _install_cf() -> Optional[str]:
+ """Install the pinned cf; an error string instead of raising."""
+ try:
+ await ensure_cf_cli()
+ return None
+ except Exception as e:
+ logger.warning("[Cloudflare] cf CLI install failed: %s", e)
+ return str(e)
+
+
+def _install_in_background() -> asyncio.Task:
+ task = _active_login["install"]
+ if task is None or task.done():
+ task = _spawn_background(_install_cf())
+ _active_login["install"] = task
+ return task
+
+
+def _install_failed(error: str) -> Dict[str, Any]:
+ return {
+ "success": False,
+ "error": f"cf CLI install failed ({error}). OpenCompany installs it with bun on first use — check that bun is available and the machine is online, then click Login again.",
+ }
+
+
+async def _spawn_login(binary: str) -> asyncio.subprocess.Process:
+ """Spawn ``cf auth login`` against cf's OWN profile store
+ (``login_env`` strips ambient tokens) from the neutral working
+ directory. stdin=PIPE left un-written: a pipe keeps any stray stdin
+ read from seeing instant EOF; cf's prompts are off without a TTY."""
+ return await asyncio.create_subprocess_exec(
+ binary,
+ *_LOGIN_ARGS,
+ stdin=asyncio.subprocess.PIPE,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=login_env(),
+ cwd=str(cf_workdir()),
+ )
+
+
+async def _read_login_banner(proc: asyncio.subprocess.Process, output: List[str]) -> Tuple[Optional[Tuple[str, str]], bool]:
+ """Read cf's early output until the URL + code appear, cf closes its
+ output, or the deadline passes; returns ``(banner, eof)``.
+
+ The pumps deliberately OUTLIVE this call: they drain both pipes for
+ the process lifetime (cf polls for up to 5 minutes and must never
+ block on a full pipe) and store the banner in the single-flight
+ state whenever it appears, so a later click can return it."""
+ new_data = asyncio.Event()
+ kept = 0
+
+ async def pump(stream: Optional[asyncio.StreamReader]) -> None:
+ nonlocal kept
+ if stream is not None:
+ while True:
+ chunk = await stream.read(4096)
+ if not chunk:
+ break
+ if kept < _OUTPUT_CAP_CHARS:
+ text = chunk.decode(errors="replace")
+ output.append(text)
+ kept += len(text)
+ if _active_login["proc"] is proc and not _active_login["url"]:
+ parsed = parse_login_banner("".join(output))
+ if parsed:
+ _active_login["url"], _active_login["code"] = parsed
+ new_data.set()
+ new_data.set()
+
+ pumps = [_spawn_background(pump(proc.stdout)), _spawn_background(pump(proc.stderr))]
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _BANNER_DEADLINE_SECONDS
+ while True:
+ # Clear BEFORE parsing: data that lands after the parse sets the
+ # event again, so no wakeup is lost.
+ new_data.clear()
+ banner = parse_login_banner("".join(output))
+ eof = all(t.done() for t in pumps)
+ if banner or eof:
+ return banner, eof
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ return None, False
+ try:
+ await asyncio.wait_for(new_data.wait(), timeout=remaining)
+ except asyncio.TimeoutError:
+ return parse_login_banner("".join(output)), False
+
+
async def _start_login_flow() -> Dict[str, Any]:
- """Install (if needed) + spawn cf's own browser login. Never raises
- — returns the WS response dict. The CLI owns the interaction from
- here: it opens the browser, serves the loopback callback, and exits
- when done; we only watch for the exit in the background."""
+ """whoami short-circuit, then spawn cf's device-flow login and wait
+ for its URL + code. Never raises — returns the WS response dict. The
+ CLI owns the interaction from here; we only watch for its exit in the
+ background."""
try:
try:
binary = str(await ensure_cf_cli())
except Exception as e:
logger.warning("[Cloudflare] cf CLI install failed: %s", e)
- return {
- "success": False,
- "error": f"cf CLI install failed ({e}). Manual install: bun add -g cf",
- }
+ return _install_failed(str(e))
- # Fast path: a live session already exists (user logged in via a
+ # Fast path: a live login already exists (the user logged in from a
# terminal, or a previous flow completed after the modal closed).
info = await whoami_snapshot()
if info:
@@ -124,50 +271,37 @@ async def _start_login_flow() -> Dict[str, Any]:
await _mark_connected(email)
return {"success": True, "message": f"Already logged in{f' as {email}' if email else ''}."}
- # stdin=PIPE left un-written: cf's prompts auto-disable when
- # stdio is not a TTY, and a pipe keeps any stray stdin read
- # from seeing instant EOF.
- proc = await asyncio.create_subprocess_exec(
- binary,
- *_LOGIN_ARGS,
- stdin=asyncio.subprocess.PIPE,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- env=login_env(),
- )
- _active_login["proc"] = proc
-
- # Drain both pipes for the process lifetime so cf never blocks
- # on a full pipe buffer while its callback server waits. Only a
- # small head is retained — solely for the failure log line.
+ proc = await _spawn_login(binary)
+ _active_login.update(proc=proc, url=None, code=None)
output: List[str] = []
-
- async def drain(stream: Optional[asyncio.StreamReader]) -> None:
- if stream is None:
- return
- kept = 0
- while True:
- chunk = await stream.read(4096)
- if not chunk:
- break
- if kept < _OUTPUT_CAP_BYTES:
- text = chunk.decode(errors="replace")
- output.append(text)
- kept += len(text)
-
- _spawn_background(drain(proc.stdout))
- _spawn_background(drain(proc.stderr))
+ banner, eof = await _read_login_banner(proc, output)
_spawn_background(_complete_login(proc, output))
- logger.info(
- "[Cloudflare] cf auth login spawned (pid=%s) — cf opens the browser itself; awaiting completion in background (timeout=%ss)",
- proc.pid,
- _LOGIN_TIMEOUT_SECONDS,
- )
- return {
- "success": True,
- "message": "cf is opening your default browser — complete the Cloudflare login there.",
- }
+ if banner:
+ url, code = banner
+ if _active_login["proc"] is proc:
+ _active_login.update(url=url, code=code)
+ logger.info(
+ "[Cloudflare] device code issued (pid=%s) — opening on the frontend; awaiting approval in background",
+ proc.pid,
+ )
+ return {
+ "success": True,
+ "url": url,
+ "verification_code": code,
+ "message": "Enter the code on the Cloudflare page that opened, then approve the request.",
+ }
+ if eof:
+ try:
+ await asyncio.wait_for(proc.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ pass
+ if proc.returncode is None:
+ # cf is still starting (slow network); the pumps keep watching.
+ return _pending("Cloudflare is still preparing the login code — click Login again in a few seconds.")
+ tail = _tail(output)
+ logger.warning("[Cloudflare] cf auth login exited (code=%s) before issuing a code: %s", proc.returncode, tail)
+ return {"success": False, "error": f"Could not start the Cloudflare login. cf said: {tail}"}
except Exception as e:
logger.exception("[Cloudflare] login flow raised unexpectedly: %s", e)
return {"success": False, "error": f"Cloudflare login failed: {e}"}
@@ -175,63 +309,67 @@ async def _start_login_flow() -> Dict[str, Any]:
async def handle_cloudflare_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
"""Single-flight + answer within the frontend's request window no
- matter what (vercel's cold-install pending pattern)."""
+ matter what."""
+ waiting = _waiting_login()
+ if waiting:
+ logger.info("[Cloudflare] login request while a device code awaits approval — re-sending it")
+ return waiting
if _login_in_progress():
- logger.info("[Cloudflare] login request ignored — a flow is already in progress")
- return {
- "success": True,
- "pending": True,
- "message": (
- "A Cloudflare login is already in progress — complete it in the browser "
- "window cf opened (it may still be preparing)."
- ),
- }
-
- logger.info("[Cloudflare] login flow starting (cf auth login)")
+ logger.info("[Cloudflare] login request ignored — a flow is already starting")
+ return _pending("A Cloudflare login is already starting — click Login again in a few seconds to see the code.")
+
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + _RESPONSE_BUDGET_SECONDS
+
+ if cf_cli_path() is None:
+ install = _install_in_background()
+ # Continue to the login only while enough of the request window is
+ # left for cf to print its code — otherwise the code would arrive
+ # after this request has been answered.
+ window = deadline - loop.time() - _BANNER_DEADLINE_SECONDS
+ try:
+ error = await asyncio.wait_for(asyncio.shield(install), timeout=max(window, 0.0))
+ except asyncio.TimeoutError:
+ logger.info("[Cloudflare] cf CLI install still running — answering pending")
+ return _pending("Installing the Cloudflare CLI (the first install downloads about 300 MB) — click Login again when it finishes.")
+ if error:
+ return _install_failed(error)
+
+ logger.info("[Cloudflare] login flow starting (cf auth login, device authorization)")
flow = _spawn_background(_start_login_flow())
_active_login["task"] = flow
try:
- return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)
+ return await asyncio.wait_for(asyncio.shield(flow), timeout=max(deadline - loop.time(), 0.0))
except asyncio.TimeoutError:
- logger.info(
- "[Cloudflare] login still preparing after %ss (cold cf install) — continuing in background",
- _RESPONSE_BUDGET_SECONDS,
- )
- return {
- "success": True,
- "pending": True,
- "message": "cf CLI is being installed — the browser will open automatically when it is ready.",
- }
+ logger.info("[Cloudflare] login still preparing after %ss — continuing in background", _RESPONSE_BUDGET_SECONDS)
+ return _pending("Cloudflare is still preparing the login code — click Login again in a few seconds.")
async def _complete_login(proc: asyncio.subprocess.Process, output: List[str]) -> None:
- """Await cf's loopback-callback flow; gate success on ``cf auth
- whoami`` (exit codes are not trusted — cf exits 0 either way); then
- the marker + broadcast.
-
- Never kills the process: the binary is an npm ``.cmd`` shim on
- Windows, and killing the wrapper orphans the node child, which
- keeps holding callback port 8877 and breaks every later login. cf
- enforces its own login timeout and exits by itself.
+ """Await cf's device-flow poll; gate success on ``cf auth whoami``
+ (exit codes are not trusted — cf exits 0 either way); then the
+ marker + broadcast.
+
+ Never kills the process: the binary is bun's ``cf.exe`` launcher
+ shim on Windows, and killing the launcher orphans the child bun
+ process running the CLI. cf gives up on the device code itself.
"""
try:
try:
returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)
except asyncio.TimeoutError:
logger.warning(
- "[Cloudflare] login still running after %ss — leaving it to cf's own timeout (killing the shim would orphan the callback server)",
+ "[Cloudflare] login still running after %ss — leaving it to cf's own device-code expiry",
_LOGIN_TIMEOUT_SECONDS,
)
return
info = await whoami_snapshot()
if not info:
- tail = "".join(output).strip().splitlines()
- banner = " | ".join(ln.strip() for ln in tail[-5:] if ln.strip()) or "(no output)"
logger.warning(
- "[Cloudflare] login exited (code=%s) but 'cf auth whoami' reports no session. CLI said: %s",
+ "[Cloudflare] login exited (code=%s) but 'cf auth whoami' reports no login. CLI said: %s",
returncode,
- banner,
+ _tail(output),
)
return
@@ -240,12 +378,13 @@ async def _complete_login(proc: asyncio.subprocess.Process, output: List[str]) -
logger.exception("[Cloudflare] login completion raised unexpectedly: %s", e)
finally:
if _active_login["proc"] is proc:
- _active_login["proc"] = None
+ _active_login.update(proc=None, url=None, code=None)
async def handle_cloudflare_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """``cf auth logout`` (best-effort, revokes the OAuth token), drop
- the catalogue marker, broadcast so the modal flips immediately."""
+ """``cf auth logout`` (best-effort: revokes the OAuth token and
+ deletes cf's default profile), drop the catalogue marker, broadcast
+ so the modal flips immediately."""
logger.info("[Cloudflare] logout starting")
from ._service import resolve_cf_light
@@ -255,12 +394,13 @@ async def handle_cloudflare_logout(data: Dict[str, Any], websocket: WebSocket) -
result = await run_cli_command(
binary=binary,
argv=["auth", "logout"],
- timeout=15.0,
+ timeout=20.0,
env=login_env(),
+ cwd=str(cf_workdir()),
)
if not result.get("success"):
logger.warning("[Cloudflare] 'cf auth logout' failed (marker still removed): %s", result.get("error"))
- result = {"success": True, "message": "cf reported no stored session; catalogue marker removed"}
+ result = {"success": True, "message": "cf reported no stored login; catalogue marker removed"}
await mark_logged_out("cloudflare")
await broadcast_credential_event("credential.oauth.disconnected", provider="cloudflare")
logger.info("[Cloudflare] logout complete: marker removed + catalogue broadcast sent")
@@ -268,7 +408,7 @@ async def handle_cloudflare_logout(data: Dict[str, Any], websocket: WebSocket) -
async def handle_cloudflare_status(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Session snapshot straight from the CLI — no side effects."""
+ """Login snapshot straight from the CLI — no side effects."""
info = await whoami_snapshot()
connected = info is not None
status: Dict[str, Any] = {"connected": connected, "logged_in": connected}
diff --git a/server/nodes/cloudflare/_install.py b/server/nodes/cloudflare/_install.py
index b3c7af4e..19e638fd 100644
--- a/server/nodes/cloudflare/_install.py
+++ b/server/nodes/cloudflare/_install.py
@@ -1,29 +1,39 @@
"""Cloudflare CLI (`cf`) auto-installer — bun, pinned, project-local.
-The official Cloudflare CLI ships as the npm package ``cf`` (a
-technical preview, "the next version of Wrangler"). It lands in the
+The official Cloudflare CLI ships as the npm package ``cf`` (open beta
+since 2026-09-28, "the next version of Wrangler"). It lands in the
shared OpenCompany packages tree at :func:`core.paths.packages_dir`
(``<DATA_DIR>/packages/``), the same single ``package.json`` +
``node_modules/`` that holds ``@anthropic-ai/claude-code`` / ``edgymeow``
-/ ``agent-browser`` / ``vercel``. :func:`core.js_runtime.add_package`
-(``bun add --cwd <packages_dir> <spec>``) extends the shared tree
-idempotently and the bin shim executes on the bun runtime; no Node or
-npm is involved.
-
-Unlike the vercel installer, the system-global ``cf`` is deliberately
-NEVER consulted (the gh philosophy): the preview CLI's command surface
-is schema-generated and shifts between versions (0.0.5's ``--ndjson``
-is gone in 0.2.0; write ops changed shape), and this plugin's argv
-builders are verified against the pinned version only. Auth state is
-unaffected by which binary runs — cf's config paths are user-level and
-shared, so a session created by the user's own ``cf auth login`` in a
-terminal is visible to this pinned binary too.
-
-Pin ``_NPM_SPEC`` when bumping and re-verify every wrapped command via
-``cf <cmd> --help-full`` (whatsapp precedent — ``@latest`` makes cold
-installs non-reproducible). cf declares ``engines.node >= 22``; bun
-ignores ``engines`` and runs the CLI on its own runtime (verified on
-bun 1.4 with no Node on PATH, including ``cf auth whoami``).
+/ ``vercel``. :func:`core.js_runtime.add_package` (``bun add --cwd
+<packages_dir> <spec>``) extends the shared tree idempotently and the
+bin shim executes on the bun runtime; no Node or npm is involved. cf
+1.0 pulls in miniflare + workerd for its local-dev commands, so the
+first install downloads about 300 MB; no lifecycle script needs
+``--trust``.
+
+The system-global ``cf`` is deliberately NEVER consulted (the gh
+philosophy): the command surface is generated from Cloudflare's
+OpenAPI schema and drifts between releases (0.2.0 -> 1.0 removed
+``context`` / ``agent-context``, moved the auth store and made device
+authorization the default login), and this plugin's argv builders are
+verified against the pinned version only.
+
+**The pin is enforced, not just installed once.** An existing shim says
+nothing about which version it runs, so :func:`ensure_cf_cli` compares
+the installed ``node_modules/cf/package.json`` version with the pin and
+re-runs ``bun add`` when they differ. A version change can strand the
+CLI's login (1.0 does not migrate 0.2.0's ``auth.jsonc``), so the
+catalogue's "connected" marker is dropped on upgrade; the login
+handler's ``whoami`` short-circuit re-marks it at once if the session
+survived.
+
+Bump recipe: change ``_NPM_VERSION``, re-check every wrapped command
+with ``cf <cmd> --help`` (and ``--dry-run``), adjust argv builders and
+tests. cf declares ``engines.node >= 22``; bun reports a Node version
+that passes that guard. Commands that load a ``cloudflare.config.ts``
+need real Node 22.18+, which is why ops run from a neutral working
+directory (``_service.cf_workdir``).
"""
from __future__ import annotations
@@ -32,34 +42,42 @@ import asyncio
from pathlib import Path
from typing import Optional
-from core.js_runtime import add_package, shared_tree_bin
+from core.js_runtime import add_package, installed_version, shared_tree_bin
from core.logging import get_logger
logger = get_logger(__name__)
-_NPM_SPEC = "[email protected]"
+_NPM_NAME = "cf"
+_NPM_VERSION = "1.0.0-beta.12"
+_NPM_SPEC = f"{_NPM_NAME}@{_NPM_VERSION}"
_cached_path: Optional[Path] = None
_install_lock = asyncio.Lock()
+def _shared_tree_bin() -> Path:
+ return shared_tree_bin("cf")
+
+
+def _installed_version() -> Optional[str]:
+ return installed_version(_NPM_NAME)
+
+
def cf_cli_path() -> Optional[Path]:
- """Sync getter for the project-local binary — the already-installed
- shim, without installing. ``None`` when never installed."""
+ """Sync getter for the project-local binary — the installed shim at
+ the PINNED version, without installing. ``None`` when cf was never
+ installed or an older version is still in place (the next op or
+ login upgrades it)."""
global _cached_path
if _cached_path and _cached_path.exists():
return _cached_path
target = _shared_tree_bin()
- if target.exists():
+ if target.exists() and _installed_version() == _NPM_VERSION:
_cached_path = target
return target
return None
-def _shared_tree_bin() -> Path:
- return shared_tree_bin("cf")
-
-
def _install() -> Path:
"""Blocking ``bun add`` into the shared tree. Raises on failure."""
bin_path = _shared_tree_bin()
@@ -67,13 +85,28 @@ def _install() -> Path:
result = add_package(_NPM_SPEC)
if result.returncode != 0 or not bin_path.exists():
raise RuntimeError(f"bun add {_NPM_SPEC} failed: {result.stderr.strip()[:500]}")
- logger.info("[Cloudflare] cf CLI installed at %s", bin_path)
+ logger.info("[Cloudflare] cf CLI %s installed at %s", _NPM_VERSION, bin_path)
return bin_path
+async def _forget_cli_login(previous: str) -> None:
+ """A version change can strand the CLI's stored login — drop the
+ catalogue marker so the modal offers Login again instead of a stale
+ "connected". Best-effort: the upgrade itself already succeeded."""
+ try:
+ from services.cli_agent._cli_auth import broadcast_credential_event, mark_logged_out
+
+ await mark_logged_out("cloudflare")
+ await broadcast_credential_event("credential.oauth.disconnected", provider="cloudflare")
+ logger.info("[Cloudflare] cf upgraded %s -> %s; cleared the login marker (log in again if cf asks)", previous, _NPM_VERSION)
+ except Exception as e: # pragma: no cover - best-effort bookkeeping
+ logger.warning("[Cloudflare] could not clear the login marker after the cf upgrade: %s", e)
+
+
async def ensure_cf_cli() -> Path:
"""Return absolute path to the project-local cf binary, installing
- the pinned release on miss. Idempotent + concurrent-safe."""
+ the pinned release on miss or when another version is installed.
+ Idempotent + concurrent-safe."""
global _cached_path
if _cached_path and _cached_path.exists():
return _cached_path
@@ -82,12 +115,15 @@ async def ensure_cf_cli() -> Path:
if _cached_path and _cached_path.exists():
return _cached_path
target = _shared_tree_bin()
- if target.exists():
+ previous = _installed_version()
+ if target.exists() and previous == _NPM_VERSION:
_cached_path = target
return target
# The install blocks for tens of seconds — keep the event loop free.
installed = await asyncio.to_thread(_install)
_cached_path = installed
+ if previous is not None and previous != _NPM_VERSION:
+ await _forget_cli_login(previous)
return installed
diff --git a/server/nodes/cloudflare/_service.py b/server/nodes/cloudflare/_service.py
index 82429156..83260663 100644
--- a/server/nodes/cloudflare/_service.py
+++ b/server/nodes/cloudflare/_service.py
@@ -1,35 +1,38 @@
-"""Shared Cloudflare plugin helpers — subprocess env builders and the
-cf session probe.
+"""Shared Cloudflare plugin helpers — subprocess env builders, the
+neutral working directory and the cf session probe.
Auth model — **the cf CLI owns its own auth end-to-end** (gh/Stripe
-pattern): ``cf auth login`` (driven by the modal's Login button or run
-by the user in a terminal) is a PKCE OAuth flow against
-``dash.cloudflare.com/oauth2/*`` with a loopback callback server on
-``localhost:8877``, and cf opens the default browser itself — the
-handlers never parse or proxy its output. The token lands in cf's
-user-level config (``auth.jsonc``) or the OS keyring. OpenCompany never
-stores or injects a token — a synthetic ``cli-managed`` marker OAuth
-row flips the catalogue's ``stored`` badge, exactly like gh. Ambient
-``CLOUDFLARE_API_TOKEN`` in the server's own environment is left
-untouched for ops (cf documents env tokens as taking precedence over
-the stored OAuth session — this is also the headless path on remote
-deployments where the loopback callback is unreachable) — but it MUST
-be stripped for ``cf auth login`` / ``whoami`` / ``logout`` (see
-:func:`login_env`).
+pattern): ``cf auth login`` is an OAuth 2.0 Device Authorization Grant
+(RFC 8628) against ``dash.cloudflare.com/oauth2/device/auth``. It
+prints a verification URL and a one-time code on stderr and polls until
+the user approves (at most 5 minutes); there is no callback server, so
+it works from any browser on any machine. The handlers relay the URL +
+code to the credentials modal (gh's device-flow shape). The token lands
+in cf's own profile store (``<xdg-config>/cloudflare/config/default.json``;
+``%APPDATA%\\xdg.config`` on Windows). OpenCompany never stores or
+injects that token — a synthetic ``cli-managed`` marker OAuth row flips
+the catalogue's ``stored`` badge, exactly like gh.
+
+cf resolves credentials env-first (verified against cf 1.0.0-beta.12):
+``CLOUDFLARE_API_TOKEN`` (deprecated alias ``CF_API_TOKEN``), then the
+OAuth profile. It does NOT accept a Global API Key — the
+``CLOUDFLARE_API_KEY`` + ``CLOUDFLARE_EMAIL`` pair is ignored — so a
+stored ``cfk_`` key serves only the direct API calls in this plugin
+(GraphQL Analytics, the Validate probe). Ambient tokens in the server's
+own environment are left in place for ops (the documented headless
+path) but stripped for login / whoami / logout (see :func:`login_env`).
"""
from __future__ import annotations
import os
+from pathlib import Path
from typing import Any, Dict, Optional
# api-key row holding the user's optional Cloudflare API token
# (dash.cloudflare.com/profile/api-tokens). Injected as the
# CLOUDFLARE_API_TOKEN env var — never argv, so it stays out of process
-# lists. The OAuth login's scope set is FIXED (86 scopes baked into cf's
-# PKCE client, no --scopes flag) and omits Web Analytics/RUM and zone
-# analytics entirely — an API token with the right permission groups is
-# the only way past that ceiling.
+# lists — and it takes precedence over the CLI's OAuth login.
#
# Storage key is the PROVIDER ID, not a bespoke name: the catalogue
# field key is the canonical ``apiKey``, which the credentials panel
@@ -44,53 +47,61 @@ EMAIL_KEY = "cloudflare_email"
# Cloudflare's documented scannable credential prefixes
# (developers.cloudflare.com/fundamentals/api/get-started/token-formats/):
# cfk_ = Global API Key (legacy X-Auth-Email/X-Auth-Key pair — full
-# account access, works on every endpoint including those the
-# account-token compatibility matrix excludes), cfut_ = User API Token,
+# account access; the cf CLI refuses it), cfut_ = User API Token,
# cfat_ = Account API Token (both Bearer).
GLOBAL_KEY_PREFIX = "cfk_"
ACCOUNT_TOKEN_PREFIX = "cfat_"
-# cf resolves credentials env-first (source-verified against cf 0.2.0's
-# auth chunk): CLOUDFLARE_API_TOKEN/CF_API_TOKEN, then the legacy
-# global-key pair. All of them mask the OAuth session for login/whoami.
+# The credential env vars cf reads; they mask the OAuth profile for
+# login / whoami / logout.
_AMBIENT_CREDENTIAL_VARS = (
"CLOUDFLARE_API_TOKEN",
"CF_API_TOKEN",
- "CLOUDFLARE_API_KEY",
- "CF_API_KEY",
- "CLOUDFLARE_EMAIL",
- "CF_EMAIL",
)
-def cf_env(token: Optional[str] = None, email: Optional[str] = None) -> Dict[str, str]:
- """Child env for cf op invocations, routed by the stored
- credential's documented prefix:
-
- - API token (``cfut_``/``cfat_``/legacy) → ``CLOUDFLARE_API_TOKEN``
- (cf's first-priority credential source).
- - Global API Key (``cfk_``) + email → the legacy
- ``CLOUDFLARE_API_KEY`` + ``CLOUDFLARE_EMAIL`` pair cf documents;
- ambient API-token vars are dropped because cf ranks tokens above
- the key pair and would silently override the user's explicit
- choice.
-
- Explicit user config always beats ambient server env. Without a
- stored credential, cf reads its own config or ambient env vars.
- ``NO_COLOR`` keeps the chalk-based status output free of ANSI
- codes."""
+def cf_workdir() -> Path:
+ """Neutral working directory for cf invocations (``<DATA_DIR>/cloudflare``).
+
+ cf reads its working directory: API commands load
+ ``CLOUDFLARE_API_TOKEN`` / ``CLOUDFLARE_ACCOUNT_ID`` /
+ ``CLOUDFLARE_ZONE_ID`` from ``.env`` files there, walk up from it for
+ a ``cloudflare.config.ts`` (whose loader fails under bun), and cache
+ the selected account in ``.cloudflare/cache/`` beneath it. Running
+ from the server's own cwd would pick up whatever ``.env`` happens to
+ sit there; this directory holds nothing but cf's account cache."""
+ from core.paths import data_path
+
+ p = data_path("cloudflare")
+ p.mkdir(parents=True, exist_ok=True)
+ return p
+
+
+def cf_env(token: Optional[str] = None, account_id: Optional[str] = None) -> Dict[str, str]:
+ """Child env for cf invocations.
+
+ - A stored API token (``cfut_``/``cfat_``/legacy) rides
+ ``CLOUDFLARE_API_TOKEN`` — cf's first-priority credential source,
+ so explicit user config beats both the OAuth login and an ambient
+ server token. A stored ``cfk_`` Global API Key is NOT injected
+ (cf ignores the key pair); cf then falls back to ambient env or
+ its OAuth login.
+ - ``account_id`` rides ``CLOUDFLARE_ACCOUNT_ID`` — cf has no
+ ``--account-id`` flag, and with several accounts a non-interactive
+ run fails unless the account is named.
+ - ``CF_DELEGATION=1`` stops cf from handing the command to another
+ cf copy it can resolve (under bun that includes bun's install
+ cache), so the pinned, verified version is the one that runs.
+ - ``CF_SEND_TELEMETRY=false`` opts out of cf's usage telemetry (on by
+ default); ``NO_COLOR`` keeps output free of ANSI codes."""
env = os.environ.copy()
env["NO_COLOR"] = "1"
- if token and token.startswith(GLOBAL_KEY_PREFIX):
- if email:
- env.pop("CLOUDFLARE_API_TOKEN", None)
- env.pop("CF_API_TOKEN", None)
- env["CLOUDFLARE_API_KEY"] = token
- env["CLOUDFLARE_EMAIL"] = email
- # cfk_ without an email is unusable — inject nothing and let cf
- # fall back to its OAuth session.
- elif token:
+ env["CF_DELEGATION"] = "1"
+ env["CF_SEND_TELEMETRY"] = "false"
+ if token and not token.startswith(GLOBAL_KEY_PREFIX):
env["CLOUDFLARE_API_TOKEN"] = token
+ if account_id:
+ env["CLOUDFLARE_ACCOUNT_ID"] = account_id
return env
@@ -124,10 +135,11 @@ async def stored_email() -> Optional[str]:
def login_env() -> Dict[str, str]:
"""Env for ``cf auth login`` / ``cf auth whoami`` / ``cf auth
- logout`` — the CLI must consult its OWN stored session, so ambient
- credential env vars are stripped: with ``CLOUDFLARE_API_TOKEN`` set,
- ``cf auth whoami`` reports the env token (``authSource: env``)
- instead of the OAuth session, and login would short-circuit."""
+ logout`` — the CLI must consult its OWN profile store, so ambient
+ token vars are stripped: with ``CLOUDFLARE_API_TOKEN`` set, ``cf auth
+ whoami`` reports the env token instead of the OAuth login, and
+ ``cf auth login`` refuses to start ("CLOUDFLARE_API_TOKEN is set and
+ takes precedence")."""
env = cf_env()
for var in _AMBIENT_CREDENTIAL_VARS:
env.pop(var, None)
@@ -135,10 +147,11 @@ def login_env() -> Dict[str, str]:
def resolve_cf_light() -> Optional[str]:
- """The project-local cf binary WITHOUT triggering an install.
- ``None`` when it has never been installed (status then reports
- disconnected; login / ops install on demand). The system-global cf
- is deliberately never consulted."""
+ """The project-local cf binary at the pinned version WITHOUT
+ triggering an install. ``None`` when it has never been installed or
+ is still an older version (status then reports disconnected; login /
+ ops install on demand). The system-global cf is deliberately never
+ consulted."""
from ._install import cf_cli_path
cached = cf_cli_path()
@@ -146,12 +159,12 @@ def resolve_cf_light() -> Optional[str]:
async def whoami_snapshot() -> Optional[Dict[str, Any]]:
- """The parsed ``cf auth whoami`` JSON when a stored OAuth session is
- live, else ``None``. cf exits 0 in BOTH states (verified on 0.2.0:
- logged-out prints ``{"authenticated": false, "error": "Not logged
- in"}`` with exit 0) — the ``authenticated`` field is the only
- signal, so exit codes are never consulted. Best-effort: ``None``
- when cf isn't installed."""
+ """The parsed ``cf auth whoami`` JSON when the OAuth login is live,
+ else ``None``. cf exits 0 in BOTH states (logged out prints
+ ``{"authenticated": false, "error": "Not logged in"}``) — the
+ ``authenticated`` field is the only signal, so exit codes are never
+ consulted. Logged in, it reports ``email``, ``accounts`` and
+ ``scopes``. Best-effort: ``None`` when cf isn't installed."""
from services.events import run_cli_command
binary = resolve_cf_light()
@@ -160,8 +173,10 @@ async def whoami_snapshot() -> Optional[Dict[str, Any]]:
result = await run_cli_command(
binary=binary,
argv=["auth", "whoami"],
- timeout=15.0,
+ # The status handler answers a 30 s frontend request.
+ timeout=20.0,
env=login_env(),
+ cwd=str(cf_workdir()),
)
info = result.get("result")
if not isinstance(info, dict) or not info.get("authenticated"):
diff --git a/server/nodes/cloudflare/cloudflare_action.py b/server/nodes/cloudflare/cloudflare_action.py
index 36f54309..f5d121ca 100644
--- a/server/nodes/cloudflare/cloudflare_action.py
+++ b/server/nodes/cloudflare/cloudflare_action.py
@@ -1,42 +1,60 @@
-"""Cloudflare Action — typed core operations over the `cf` CLI, plus a
-raw-command passthrough.
+"""Cloudflare Action — typed core operations over the official `cf` CLI,
+a command search, the GraphQL Analytics API, and a raw-command
+passthrough.
The cf CLI owns its own auth (Stripe/gh pattern): no pre-flight check
-and no token injection here — cf reads its stored OAuth session
-(populated by ``cf auth login``) or an ambient ``CLOUDFLARE_API_TOKEN``
-env token, and its own "Not logged in" error surfaces through the
-``NodeUserError`` wrap.
-
-cf 0.2.0 prints JSON to stdout by default (status noise goes to
-stderr), so parsed results flow straight into the output panel's JSON
-tree. Argv shapes below are verified against the pinned 0.2.0 (`cf
-<cmd> --help-full`): zone selection is the global ``-z/--zone`` flag,
-``dns records create`` takes ``--body`` (raw JSON request body — the
-schema-stable escape hatch; per-field flags churn between preview
-versions), and ``dns records delete`` takes the record id as a
-positional.
+here — cf uses the stored API token (injected as CLOUDFLARE_API_TOKEN),
+an ambient token, or its own OAuth login, and its own "No authentication
+token found" error surfaces through the NodeUserError wrap.
+
+Argv shapes are verified against the pinned cf 1.0.0-beta.12 (``--help``
+and ``--dry-run`` of every wrapped command):
+
+- cf prints the API ``result`` as one pretty-printed JSON document on
+ stdout (no ``{success, errors, result}`` envelope; status text and
+ error boxes go to stderr), so parsed results flow straight into the
+ output panel's JSON tree. There is no output-format flag, and unknown
+ flags are rejected.
+- The zone is the global ``--zone`` flag. cf resolves a domain only
+ within the first page of the selected account's zones, so domains are
+ looked up here with ``zones list --name`` and passed as zone IDs.
+- There is no ``--account-id`` flag on most commands: the account comes
+ from ``CLOUDFLARE_ACCOUNT_ID``, and with several accounts a
+ non-interactive run fails until it is set.
+- ``dns records create`` / ``edit`` take the record only as ``--body``
+ JSON (``edit`` is a PATCH; ``update`` would overwrite the record).
+- Destructive commands need ``--force``: without it a non-interactive
+ run prints "Aborted." and exits 0 having changed nothing.
"""
from __future__ import annotations
import json
import os
+import re
import shlex
from typing import Any, Dict, List, Literal, Optional
import httpx
-from pydantic import BaseModel, ConfigDict, Field, field_validator
+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from services.events import run_cli_command
from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue
+from services.plugin.params import coerce_blank_params
from ._credentials import CloudflareCredential
+from ._service import GLOBAL_KEY_PREFIX
-_ZONES_LIST = {"displayOptions": {"show": {"operation": ["zones_list"]}}}
-_DNS_ANY = {"displayOptions": {"show": {"operation": ["dns_records_list", "dns_record_create", "dns_record_delete"]}}}
-_CREATE = {"displayOptions": {"show": {"operation": ["dns_record_create"]}}}
-_DELETE = {"displayOptions": {"show": {"operation": ["dns_record_delete"]}}}
+_ZONE_OPS = ["dns_records_list", "dns_record_create", "dns_record_edit", "dns_record_delete"]
+
+_ACCOUNT = {"displayOptions": {"show": {"operation": ["zones_list", *_ZONE_OPS, "custom"]}}}
+_ZONE = {"displayOptions": {"show": {"operation": list(_ZONE_OPS)}}}
+_LIST = {"displayOptions": {"show": {"operation": ["zones_list", "dns_records_list"]}}}
+_RECORD_TYPE = {"displayOptions": {"show": {"operation": ["dns_records_list"]}}}
+_BODY = {"displayOptions": {"show": {"operation": ["dns_record_create", "dns_record_edit"]}}}
+_RECORD_ID = {"displayOptions": {"show": {"operation": ["dns_record_edit", "dns_record_delete"]}}}
_GRAPHQL = {"displayOptions": {"show": {"operation": ["graphql_query"]}}}
+_SEARCH = {"displayOptions": {"show": {"operation": ["search_commands"]}}}
_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}
_ONESHOT_TIMEOUT = 120.0
@@ -44,56 +62,133 @@ _CUSTOM_TIMEOUT = 300.0
_GRAPHQL_TIMEOUT = 60.0
_STDERR_TAIL_CHARS = 2000
+# cf passes a 32-hex zone ID (or a UUID) through as-is; anything else is
+# a domain name.
+_ZONE_ID_RE = re.compile(r"[0-9a-fA-F]{32}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
+
# The GraphQL Analytics API is the official replacement for the
-# sunsetted Zone Analytics REST API. It is a standalone endpoint
-# OUTSIDE the REST/OpenAPI schema the cf CLI is generated from, so the
-# node calls it directly. Cloudflare documents API tokens as the
-# authentication method for it (the cf OAuth grant has no analytics
-# scopes beyond dns_analytics:read anyway).
+# sunsetted Zone Analytics REST API. It is a standalone endpoint OUTSIDE
+# the REST/OpenAPI schema the cf CLI is generated from (cf has no graphql
+# or raw-request command), so the node calls it directly. Cloudflare
+# documents API tokens as the authentication method for it.
# https://developers.cloudflare.com/analytics/graphql-api/
_GRAPHQL_ENDPOINT = "https://api.cloudflare.com/client/v4/graphql"
+_AUTH_MARKERS = ("no authentication token found", "not logged in", "try running: cf auth login")
+_AUTH_HINT = (
+ "Connect Cloudflare in Credentials -> Cloudflare: click Login (if it still shows an older login, "
+ "click Disconnect first), or paste an API token there."
+)
+_ACCOUNT_HINT = "Set account_id to the Cloudflare account ID to use (whoami lists the accounts)."
+_PERMISSION_HINT = (
+ "Cloudflare refused the request: the API token or login lacks a permission for this resource "
+ "(edit tokens at dash.cloudflare.com/profile/api-tokens)."
+)
+_BUN_HINT = (
+ "This command loads a cloudflare.config.ts project file, which cf supports only on Node.js 22.18+; "
+ "OpenCompany runs cf on bun."
+)
+
+# Sign-in belongs to the Credentials modal: a workflow step cannot finish
+# cf's interactive device login, and a logout behind the modal's back
+# would leave its "connected" badge stale.
+_AUTH_STATE_COMMANDS = {"login", "logout", "create", "delete", "activate", "deactivate"}
+
+
+def _label(argv: List[str]) -> str:
+ """The command words of an argv, for error messages."""
+ words: List[str] = []
+ for tok in argv[:3]:
+ if tok.startswith("-"):
+ break
+ words.append(tok)
+ return " ".join(words) or "command"
+
+
+def _blocked_reason(argv: List[str]) -> Optional[str]:
+ head = [a.lower() for a in argv[:2]]
+ if head[:1] == ["login"] or (head[:1] == ["auth"] and len(head) > 1 and head[1] in _AUTH_STATE_COMMANDS):
+ return (
+ "Cloudflare sign-in is managed in Credentials -> Cloudflare (Login / Disconnect) — a workflow "
+ "step cannot complete cf's interactive device login. For unattended use, paste an API token "
+ "there. ('auth whoami' works here.)"
+ )
+ if head[:1] == ["dev"]:
+ return "'cf dev' starts a long-running local development server, which a workflow step cannot host."
+ return None
+
class CloudflareActionParams(BaseModel):
operation: Literal[
- "whoami", "zones_list", "dns_records_list", "dns_record_create", "dns_record_delete", "graphql_query", "custom"
+ "whoami",
+ "search_commands",
+ "zones_list",
+ "dns_records_list",
+ "dns_record_create",
+ "dns_record_edit",
+ "dns_record_delete",
+ "graphql_query",
+ "custom",
] = "whoami"
- # Shared zone target for the DNS operations (global -z/--zone flag).
+ # Sent as CLOUDFLARE_ACCOUNT_ID (cf has no --account-id flag on most
+ # commands); zones_list also filters by it.
+ account_id: str = Field(
+ default="",
+ description=(
+ "Cloudflare account ID. Needed when the login can see more than one account (whoami lists them); "
+ "zones_list also filters by it"
+ ),
+ json_schema_extra={"placeholder": "Account ID (optional)", **_ACCOUNT},
+ )
+
+ # Shared zone target for the DNS operations (global --zone flag).
zone: str = Field(
default="",
- description="Zone ID or domain name",
- json_schema_extra={"placeholder": "example.com or zone ID", **_DNS_ANY},
+ description="dns_* operations: zone ID or domain name, e.g. example.com",
+ json_schema_extra={"placeholder": "example.com or zone ID", **_ZONE},
)
- # zones_list
+ # zones_list / dns_records_list filters + paging
name_filter: str = Field(
default="",
- description="Filter zones by domain name",
- json_schema_extra={"placeholder": "example.com (optional)", **_ZONES_LIST},
+ description="zones_list: domain to match; dns_records_list: full record name to match, e.g. www.example.com",
+ json_schema_extra={"placeholder": "example.com (optional)", **_LIST},
)
- account_id: str = Field(
+ record_type: str = Field(
default="",
- description="Filter zones by account ID",
- json_schema_extra={"placeholder": "Account ID (optional)", **_ZONES_LIST},
+ description="dns_records_list: only records of this type (A, AAAA, CNAME, TXT, MX, NS, SRV, CAA, ...)",
+ json_schema_extra={"placeholder": "A (optional)", **_RECORD_TYPE},
+ )
+ page: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="zones_list / dns_records_list: page number (default 1)",
+ json_schema_extra={"placeholder": "1", **_LIST},
+ )
+ per_page: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="zones_list / dns_records_list: results per page (zones: default 20, max 50; DNS records: default 100)",
+ json_schema_extra={"placeholder": "Default", **_LIST},
)
- # dns_record_create
+ # dns_record_create / dns_record_edit
record_body: str = Field(
default="",
- description="DNS record as a raw JSON request body (--body)",
+ description="dns_record_create: the record as JSON; dns_record_edit: only the fields to change, as JSON",
json_schema_extra={
"rows": 4,
- "placeholder": '{"type":"A","name":"www","content":"192.0.2.1","ttl":1,"proxied":false}',
- **_CREATE,
+ "placeholder": '{"type":"A","name":"www","content":"192.0.2.1","ttl":1,"proxied":true}',
+ **_BODY,
},
)
- # dns_record_delete
+ # dns_record_edit / dns_record_delete
record_id: str = Field(
default="",
- description="DNS record ID to delete",
- json_schema_extra={"placeholder": "023e105f4ecef8ad9ca31a8372d0c353", **_DELETE},
+ description="dns_record_edit / dns_record_delete: DNS record ID (dns_records_list shows it)",
+ json_schema_extra={"placeholder": "023e105f4ecef8ad9ca31a8372d0c353", **_RECORD_ID},
)
# graphql_query
@@ -116,18 +211,35 @@ class CloudflareActionParams(BaseModel):
},
)
+ # search_commands
+ search_query: str = Field(
+ default="",
+ description=(
+ "search_commands: the task to find a cf command for, e.g. 'purge cache for a zone'. Describe the "
+ "action and resource only — no names, domains or IDs"
+ ),
+ json_schema_extra={"placeholder": "list r2 buckets", **_SEARCH},
+ )
+
# custom
command: str = Field(
default="",
- description="cf CLI command, exactly as typed after 'cf '",
+ description="custom: a cf command, as typed after 'cf ', e.g. 'r2 buckets list'",
json_schema_extra={
- "placeholder": "accounts list | dns records get <id> --zone example.com | agent-context dns",
+ "placeholder": "workers list | r2 buckets list | dns records export --zone <zone id>",
**_CUSTOM,
},
)
model_config = ConfigDict(extra="ignore")
+ @model_validator(mode="before")
+ @classmethod
+ def _coerce_blanks(cls, values: Any) -> Any:
+ """The panel stores "" for a cleared number field — drop it so the
+ field's default applies."""
+ return coerce_blank_params(cls, values)
+
@field_validator("record_body", "graphql_variables", mode="before")
@classmethod
def _coerce_json_field(cls, v: Any) -> Any:
@@ -155,31 +267,35 @@ class CloudflareActionNode(ActionNode):
display_name = "Cloudflare"
subtitle = "cf CLI"
group = ("deployment", "tool")
- description = "Cloudflare via the official cf CLI — auth, zones, DNS records, GraphQL analytics, or any cf command"
+ description = "Cloudflare via the official cf CLI — zones, DNS records, command search, GraphQL analytics, or any cf command"
component_kind = "square"
tool_name = "cloudflare"
tool_description = (
- "Interact with Cloudflare via the official cf CLI. Operations: whoami (auth status + "
- "identity), zones_list (list/filter zones), dns_records_list (records for a zone), "
- "dns_record_create (pass 'record_body' as the raw JSON record, e.g. "
- '{"type":"A","name":"www","content":"192.0.2.1","ttl":1}), dns_record_delete (by record '
- "id), graphql_query (the GraphQL Analytics API — the replacement for the sunsetted Zone "
- "Analytics REST API; zone traffic via httpRequestsAdaptiveGroups, Web Analytics/RUM via "
- "rumPageloadEventsAdaptiveGroups under viewer.accounts), custom (any other cf command — "
- "pass 'command' exactly as typed after 'cf ', e.g. 'accounts list', 'dns records get <id> "
- "--zone example.com', 'registrar domains list', 'agent-context dns' for deep per-product "
- "docs). DNS operations take 'zone' as a zone ID or domain name. Output is JSON. "
- "Auth: the cf CLI's own OAuth login (Credentials -> Cloudflare) covers zones/DNS/accounts/"
- "registrar but its fixed scope set has NO analytics access beyond DNS — graphql_query and "
- "Web Analytics/RUM need the optional API token from the credentials panel (permission "
- "'Account > Account Analytics > Read'), which then takes precedence for every operation. "
- "Reference: https://developers.cloudflare.com"
+ "Manage Cloudflare through the official cf CLI. Operations and the fields each one uses: "
+ "whoami — the identity the CLI acts as and the accounts it can use. "
+ "search_commands (search_query) — find the cf command for a task; returns 5 matches. Describe the "
+ "action and resource only, never names, domains or IDs. "
+ "zones_list (optional name_filter, account_id, page, per_page). "
+ "dns_records_list (zone; optional name_filter = full record name, record_type, page, per_page). "
+ "dns_record_create (zone, record_body = the record as JSON, e.g. "
+ '{"type":"A","name":"www","content":"192.0.2.1","ttl":1,"proxied":true}). '
+ 'dns_record_edit (zone, record_id, record_body = only the fields to change, e.g. {"content":"192.0.2.2"}). '
+ "dns_record_delete (zone, record_id) — deletes at once; confirm with the user first. "
+ "graphql_query (graphql_query, graphql_variables) — the GraphQL Analytics API: zone traffic via "
+ "httpRequestsAdaptiveGroups, Web Analytics/RUM via rumPageloadEventsAdaptiveGroups under "
+ "viewer.accounts; it needs an API token or Global API Key stored in Credentials -> Cloudflare. "
+ "custom (command) — any other cf command, as typed after 'cf ', e.g. 'workers list', "
+ "'r2 buckets list', 'dns records export --zone <zone id>'; add --force to destructive commands "
+ "(cf refuses them otherwise) and --dry-run to preview a request without sending it. "
+ "zone takes a zone ID or a domain name. Set account_id when the login can see several accounts "
+ "(whoami lists them). Results are JSON. "
+ "Reference: https://developers.cloudflare.com/cf/"
)
handles = (
{"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
{"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},
)
- annotations = {"destructive": False, "readonly": False, "open_world": True}
+ annotations = {"destructive": True, "readonly": False, "open_world": True}
# OutputPanel renders textual output preformatted (cf status text /
# custom-command output is terminal text, not markdown).
ui_hints = {"outputMode": "terminal"}
@@ -196,72 +312,144 @@ class CloudflareActionNode(ActionNode):
self,
argv: List[str],
*,
+ account_id: str = "",
+ cwd: Optional[str] = None,
timeout: float = _ONESHOT_TIMEOUT,
) -> Dict[str, Any]:
"""No auth pre-flight (Stripe pattern) — cf authenticates from
- the stored credential (API token as CLOUDFLARE_API_TOKEN, or a
- cfk_ Global API Key as the documented CLOUDFLARE_API_KEY +
- CLOUDFLARE_EMAIL pair), its own OAuth config, or ambient env
- vars; its error (including "Not logged in") surfaces via the
- NodeUserError wrap below."""
+ the stored API token (injected as CLOUDFLARE_API_TOKEN), an
+ ambient token, or its own OAuth login; its error (including "No
+ authentication token found") surfaces via the NodeUserError wrap
+ below. Runs from the neutral ``cf_workdir()`` unless ``cwd`` is
+ given."""
from ._install import ensure_cf_cli
- from ._service import cf_env, stored_email, stored_token
+ from ._service import cf_env, cf_workdir, stored_token
try:
binary = str(await ensure_cf_cli())
except Exception as e:
- raise RuntimeError(f"cf CLI install failed: {e}") from e
+ raise NodeUserError(
+ f"cf CLI install failed: {e}",
+ hint="OpenCompany installs the Cloudflare CLI with bun on first use — check that bun is available and the machine is online.",
+ ) from e
+ token = await stored_token()
result = await run_cli_command(
binary=binary,
argv=argv,
timeout=timeout,
- env=cf_env(await stored_token(), await stored_email()),
+ env=cf_env(token, account_id.strip() or None),
+ cwd=cwd or str(cf_workdir()),
)
if not result.get("success"):
- stderr = (result.get("stderr") or "").strip()
- detail = stderr[-_STDERR_TAIL_CHARS:] if stderr else (result.get("error") or "cf invocation failed")
- raise NodeUserError(f"cf {argv[0]} failed: {detail}")
+ raise self._failure(argv, result, token=token, timeout=timeout)
+ stderr = result.get("stderr") or ""
+ if "pass --force to confirm" in stderr or any(ln.strip() == "Aborted." for ln in stderr.splitlines()):
+ raise NodeUserError(
+ f"cf {_label(argv)} did not run: cf asks for confirmation, which a workflow cannot give. "
+ "Add --force to confirm the destructive command."
+ )
return result
@staticmethod
- def _zone_flag(params: "CloudflareActionParams") -> List[str]:
+ def _failure(argv: List[str], result: Dict[str, Any], *, token: Optional[str], timeout: float) -> NodeUserError:
+ """cf's own error text (a box on stderr) plus a hint for the
+ failures with a known fix."""
+ label = _label(argv)
+ stderr = (result.get("stderr") or "").strip()
+ if not stderr:
+ error = result.get("error") or "cf invocation failed"
+ if "timed out" in error:
+ return NodeUserError(f"cf {label} timed out after {timeout:g}s")
+ return NodeUserError(f"cf {label} failed: {error}")
+ message = f"cf {label} failed: {stderr[-_STDERR_TAIL_CHARS:]}"
+ lowered = stderr.lower()
+ if "more than one account" in lowered:
+ return NodeUserError(message, hint=_ACCOUNT_HINT)
+ if any(marker in lowered for marker in _AUTH_MARKERS):
+ hint = _AUTH_HINT
+ if token and token.startswith(GLOBAL_KEY_PREFIX):
+ hint += " The stored Global API Key (cfk_) works only for graphql_query: the cf CLI accepts API tokens, not Global API Keys."
+ return NodeUserError(message, hint=hint, requires_user_action=True)
+ if "check your api token permissions" in lowered:
+ return NodeUserError(message, hint=_PERMISSION_HINT)
+ if "not supported on bun" in lowered:
+ return NodeUserError(message, hint=_BUN_HINT)
+ if "zone not found" in lowered:
+ return NodeUserError(message, hint="Pass the zone ID instead of the domain (zones_list shows it).")
+ return NodeUserError(message)
+
+ async def _zone_id(self, params: "CloudflareActionParams") -> str:
+ """The zone as an ID. A domain is looked up with ``zones list
+ --name`` (an exact match across every account the credential can
+ see) instead of letting cf resolve it: cf searches only the first
+ page of the selected account's zones and needs that account picked
+ first."""
zone = params.zone.strip()
if not zone:
raise NodeUserError("zone is required (a zone ID or domain name)")
- return ["--zone", zone]
+ if _ZONE_ID_RE.fullmatch(zone):
+ return zone
+ argv = ["zones", "list", "--name", zone.lower().rstrip(".")]
+ account_id = params.account_id.strip()
+ if account_id:
+ argv += ["--account-id", account_id]
+ result = await self._run(argv, account_id=account_id)
+ zones = result.get("result")
+ matches = [z for z in zones if isinstance(z, dict) and z.get("id")] if isinstance(zones, list) else []
+ if not matches:
+ raise NodeUserError(
+ f"Zone not found: {zone}. Check the domain (the zone apex, e.g. example.com), or pass the zone ID (zones_list shows it)."
+ )
+ ids = {str(z["id"]) for z in matches}
+ if len(ids) > 1:
+ accounts = ", ".join(sorted({str((z.get("account") or {}).get("id") or "?") for z in matches}))
+ raise NodeUserError(f"{zone} matches zones in several accounts ({accounts}) — set account_id, or pass the zone ID.")
+ return ids.pop()
@staticmethod
- def _parse_ndjson(stdout: str) -> Optional[List[Any]]:
- """Multi-object stdout (one JSON document per line) defeats
- run_cli_command's single ``json.loads`` — recover it here.
- ``None`` when the text isn't NDJSON."""
- lines = [ln for ln in (s.strip() for s in stdout.splitlines()) if ln]
- if len(lines) < 2:
- return None
- parsed: List[Any] = []
- for ln in lines:
- try:
- parsed.append(json.loads(ln))
- except ValueError:
- return None
- return parsed
+ def _page_flags(params: "CloudflareActionParams") -> List[str]:
+ flags: List[str] = []
+ if params.page:
+ flags += ["--page", str(params.page)]
+ if params.per_page:
+ flags += ["--per-page", str(params.per_page)]
+ return flags
- @classmethod
- def _shape(cls, operation: str, result: Dict[str, Any], *, url: Optional[str] = None) -> Dict[str, Any]:
- """Output-panel shaping: when cf returned JSON (its default
- stdout contract), the parsed data IS the payload — the raw
- stdout string would just duplicate it as an unreadable blob
- (and pre-stringified JSON violates the output contract). Keys
- are omitted (not None'd) when empty so the panel shows only
- meaningful fields (`exclude_unset` preserves this)."""
+ @staticmethod
+ def _record_body(params: "CloudflareActionParams", example: str) -> str:
+ body = params.record_body.strip()
+ if not body:
+ raise NodeUserError(f"record_body is required (JSON, e.g. {example})")
+ try:
+ parsed = json.loads(body)
+ except ValueError as e:
+ raise NodeUserError(f"record_body is not valid JSON: {e}") from e
+ if not isinstance(parsed, dict):
+ raise NodeUserError(f"record_body must be a JSON object, e.g. {example}")
+ return body
+
+ @staticmethod
+ def _record_id(params: "CloudflareActionParams") -> str:
+ record_id = params.record_id.strip()
+ if not record_id:
+ raise NodeUserError("record_id is required (find it via dns_records_list)")
+ return record_id
+
+ @staticmethod
+ def _shape(operation: str, result: Dict[str, Any], *, url: Optional[str] = None) -> Dict[str, Any]:
+ """Output-panel shaping: when cf returned JSON (its stdout
+ contract), the parsed data IS the payload — the raw stdout string
+ would just duplicate it as an unreadable blob (and pre-stringified
+ JSON violates the output contract). Text output (e.g. a BIND
+ export) lands in ``stdout``. Keys are omitted (not None'd) when
+ empty so the panel shows only meaningful fields (`exclude_unset`
+ preserves this)."""
shaped: Dict[str, Any] = {"operation": operation, "success": True}
if url:
shaped["url"] = url
parsed = result.get("result")
stdout = (result.get("stdout") or "").strip()
- if parsed is None and stdout:
- parsed = cls._parse_ndjson(stdout)
if parsed is not None:
shaped["result"] = parsed
elif stdout:
@@ -278,50 +466,75 @@ class CloudflareActionNode(ActionNode):
result = await self._run(["auth", "whoami"])
return self._shape("whoami", result)
+ @Operation("search_commands", cost={"service": "cloudflare", "action": "search_commands", "count": 1})
+ async def search_commands(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
+ """``cf cli search`` — a local index of every cf command, no
+ credentials or network involved."""
+ query = params.search_query.strip()
+ if not query:
+ raise NodeUserError("search_query is required (describe the task, e.g. 'purge cache for a zone')")
+ result = await self._run(["cli", "search", query])
+ return self._shape("search_commands", result)
+
@Operation("zones_list", cost={"service": "cloudflare", "action": "zones_list", "count": 1})
async def zones_list(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
argv = ["zones", "list"]
if params.name_filter.strip():
argv += ["--name", params.name_filter.strip()]
- if params.account_id.strip():
- argv += ["--account-id", params.account_id.strip()]
- result = await self._run(argv)
+ account_id = params.account_id.strip()
+ if account_id:
+ argv += ["--account-id", account_id]
+ argv += self._page_flags(params)
+ result = await self._run(argv, account_id=account_id)
return self._shape("zones_list", result)
@Operation("dns_records_list", cost={"service": "cloudflare", "action": "dns_records_list", "count": 1})
async def dns_records_list(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
- argv = ["dns", "records", "list", *self._zone_flag(params)]
- result = await self._run(argv)
+ zone_id = await self._zone_id(params)
+ argv = ["dns", "records", "list", "--zone", zone_id]
+ if params.name_filter.strip():
+ argv += ["--name", params.name_filter.strip()]
+ if params.record_type.strip():
+ argv += ["--type", params.record_type.strip().upper()]
+ argv += self._page_flags(params)
+ result = await self._run(argv, account_id=params.account_id)
return self._shape("dns_records_list", result)
@Operation("dns_record_create", cost={"service": "cloudflare", "action": "dns_record_create", "count": 1})
async def dns_record_create(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
- body = params.record_body.strip()
- if not body:
- raise NodeUserError('record_body is required (raw JSON, e.g. {"type":"A","name":"www","content":"192.0.2.1","ttl":1})')
- try:
- json.loads(body)
- except ValueError as e:
- raise NodeUserError(f"record_body is not valid JSON: {e}") from e
- argv = ["dns", "records", "create", *self._zone_flag(params), "--body", body]
- result = await self._run(argv)
+ body = self._record_body(params, '{"type":"A","name":"www","content":"192.0.2.1","ttl":1}')
+ zone_id = await self._zone_id(params)
+ argv = ["dns", "records", "create", "--zone", zone_id, "--body", body]
+ result = await self._run(argv, account_id=params.account_id)
return self._shape("dns_record_create", result)
+ @Operation("dns_record_edit", cost={"service": "cloudflare", "action": "dns_record_edit", "count": 1})
+ async def dns_record_edit(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
+ """PATCH — only the fields in record_body change (``dns records
+ update`` would overwrite the whole record)."""
+ record_id = self._record_id(params)
+ body = self._record_body(params, '{"content":"192.0.2.2"}')
+ zone_id = await self._zone_id(params)
+ argv = ["dns", "records", "edit", record_id, "--zone", zone_id, "--body", body]
+ result = await self._run(argv, account_id=params.account_id)
+ return self._shape("dns_record_edit", result)
+
@Operation("dns_record_delete", cost={"service": "cloudflare", "action": "dns_record_delete", "count": 1})
async def dns_record_delete(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
- record_id = params.record_id.strip()
- if not record_id:
- raise NodeUserError("record_id is required (find it via dns_records_list)")
- argv = ["dns", "records", "delete", record_id, *self._zone_flag(params)]
- result = await self._run(argv)
+ record_id = self._record_id(params)
+ zone_id = await self._zone_id(params)
+ # --force: choosing this operation IS the confirmation. Without it
+ # cf prints "Aborted." and exits 0 with the record still there.
+ argv = ["dns", "records", "delete", record_id, "--zone", zone_id, "--force"]
+ result = await self._run(argv, account_id=params.account_id)
return self._shape("dns_record_delete", result)
@Operation("graphql_query", cost={"service": "cloudflare", "action": "graphql_query", "count": 1})
async def graphql_query(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
"""The GraphQL Analytics API — a standalone endpoint outside the
- cf CLI's generated REST surface, called directly. Requires an
- API token (the cf OAuth grant carries no analytics scopes and
- Cloudflare documents tokens as the auth method for GraphQL)."""
+ cf CLI's generated REST surface, called directly. It needs a
+ credential OpenCompany holds (API token or Global API Key + email):
+ the cf login session stays inside the CLI."""
query = params.graphql_query.strip()
if not query:
raise NodeUserError(
@@ -342,10 +555,11 @@ class CloudflareActionNode(ActionNode):
headers = api_auth_headers(key, email)
if headers is None:
raise NodeUserError(
- "The GraphQL Analytics API needs a credential — the cf OAuth login carries no "
- "analytics scopes. In Credentials -> Cloudflare paste either an API token "
- "(dash.cloudflare.com/profile/api-tokens, permission 'Account > Account Analytics "
- "> Read') or a Global API Key (cfk_...) together with the Account Email field."
+ "The GraphQL Analytics API is called directly, not through the cf CLI, so the cf login "
+ "cannot be used for it. In Credentials -> Cloudflare paste either an API token "
+ "(dash.cloudflare.com/profile/api-tokens, permission 'Account > Account Analytics > Read') "
+ "or a Global API Key (cfk_...) together with the Account Email field.",
+ requires_user_action=True,
)
body = await self._graphql_post(headers, {"query": query, "variables": variables})
@@ -385,11 +599,25 @@ class CloudflareActionNode(ActionNode):
@Operation("custom", cost={"service": "cloudflare", "action": "custom", "count": 1})
async def custom(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
+ """Any cf command. Runs from the workflow workspace so relative
+ paths (``--body @record.json``, ``--file``, ``--dir``) resolve
+ against the files the workflow wrote."""
cmd = params.command.strip()
- if not cmd:
- raise NodeUserError("command is required (e.g. 'accounts list', 'dns records get <id> --zone example.com', 'agent-context dns')")
- argv = shlex.split(cmd)
- result = await self._run(argv, timeout=_CUSTOM_TIMEOUT)
+ try:
+ argv = shlex.split(cmd)
+ except ValueError as e:
+ raise NodeUserError(
+ f"command could not be parsed ({e}) — wrap JSON in single quotes, e.g. --body '{{\"content\":\"192.0.2.2\"}}'"
+ ) from e
+ if argv and argv[0].lower() in ("cf", "cloudflare"):
+ argv = argv[1:]
+ if not argv:
+ raise NodeUserError("command is required (e.g. 'workers list', 'r2 buckets list', 'dns records export --zone <zone id>')")
+ reason = _blocked_reason(argv)
+ if reason:
+ raise NodeUserError(reason)
+ workspace = ctx.workspace_dir if ctx.workspace_dir and os.path.isdir(ctx.workspace_dir) else None
+ result = await self._run(argv, account_id=params.account_id, cwd=workspace, timeout=_CUSTOM_TIMEOUT)
stdout = (result.get("stdout") or "").strip()
url = stdout if stdout.startswith("http") and "\n" not in stdout else None
return self._shape("custom", result, url=url)
diff --git a/server/skills/cloudflare/cloudflare-skill/SKILL.md b/server/skills/cloudflare/cloudflare-skill/SKILL.md
index 5080bf08..27bafda3 100644
--- a/server/skills/cloudflare/cloudflare-skill/SKILL.md
+++ b/server/skills/cloudflare/cloudflare-skill/SKILL.md
@@ -1,21 +1,21 @@
---
name: cloudflare-skill
-description: Work with Cloudflare via the official cf CLI — check auth identity, list zones, list/create/delete DNS records, query the GraphQL Analytics API (zone traffic, Web Analytics/RUM), and run any other cf command. Output is parsed JSON.
+description: Work with Cloudflare via the official cf CLI — find the right cf command, list zones, list/create/edit/delete DNS records, query the GraphQL Analytics API (zone traffic, Web Analytics/RUM), and run any other cf command (Workers, R2, KV, D1, Pages, cache). Output is parsed JSON.
allowed-tools: "cloudflare"
metadata:
author: opencompany
- version: "1.0"
+ version: "2.0"
category: deployment
---
# Cloudflare Skill
-Wrapper over the official [Cloudflare CLI](https://blog.cloudflare.com/cf-cli-local-explorer/)
-(`cf`, a Technical Preview — "the next version of Wrangler"). Typed
-operations for the core flows plus a `custom` passthrough that covers
-the entire cf surface. cf prints JSON to stdout by default, so results
-come back parsed in `result`.
+Wrapper over the official [Cloudflare CLI](https://developers.cloudflare.com/cf/)
+(`cf`, in open beta — "the next version of Wrangler"). Typed operations
+cover the core zone and DNS flows, `search_commands` finds any other
+command, and `custom` runs it. cf prints the API result as JSON, so
+results come back parsed in `result`.
## Tool: cloudflare
@@ -23,69 +23,127 @@ come back parsed in `result`.
| Operation | Purpose | Key fields |
|---|---|---|
-| `whoami` | Auth status + identity (email, scopes) | — |
-| `zones_list` | List/filter zones (parsed JSON) | `name_filter`, `account_id` (both optional) |
-| `dns_records_list` | DNS records for a zone (parsed JSON) | `zone` (zone ID or domain) |
-| `dns_record_create` | Create a DNS record | `zone`, `record_body` (raw JSON record) |
-| `dns_record_delete` | Delete a DNS record by id | `zone`, `record_id` |
-| `graphql_query` | GraphQL Analytics API (traffic, RUM, DNS analytics) | `graphql_query`, `graphql_variables` (JSON) |
-| `custom` | Any other cf command | `command` — exactly what you would type after `cf ` |
+| `whoami` | Who the CLI acts as, and the accounts it can use | — |
+| `search_commands` | Find the cf command for a task (5 matches) | `search_query` |
+| `zones_list` | List / filter zones | `name_filter`, `account_id`, `page`, `per_page` (all optional) |
+| `dns_records_list` | DNS records of a zone | `zone`; optional `name_filter` (full record name), `record_type`, `page`, `per_page` |
+| `dns_record_create` | Create a record | `zone`, `record_body` (the record as JSON) |
+| `dns_record_edit` | Change some fields of a record | `zone`, `record_id`, `record_body` (only the changed fields) |
+| `dns_record_delete` | Delete a record | `zone`, `record_id` |
+| `graphql_query` | GraphQL Analytics API | `graphql_query`, `graphql_variables` (JSON) |
+| `custom` | Any other cf command | `command` — what you would type after `cf ` |
+
+`zone` takes a zone ID or the domain (`example.com`). `account_id` matters
+when the login can see more than one account: commands then fail with
+"More than one account available ..." until it is set. `whoami` lists
+the accounts.
### Response
```json
{
- "operation": "zones_list",
+ "operation": "dns_records_list",
"success": true,
- "result": [{ "id": "023e105f4ecef8ad9ca31a8372d0c353", "name": "example.com", "status": "active" }],
- "stdout": null,
- "stderr_tail": null
+ "result": [{ "id": "372e67954025e0ba6aaa6d586b9e0b59", "type": "A", "name": "www.example.com", "content": "192.0.2.1", "proxied": true, "ttl": 1 }]
}
```
-Parsed JSON lands in `result`; plain text (rare) lands in `stdout`.
-On failure the tool raises an error carrying cf's own message —
-surface it verbatim; cf's errors are precise (including "Not logged
-in", which tells the user exactly how to authenticate).
+Parsed JSON lands in `result`; text output (a BIND zone export, for
+example) lands in `stdout`; `stderr_tail` carries cf's status lines when
+there are any. Lists return one page: use `page` / `per_page` and keep
+going until a page comes back shorter than `per_page`. On failure the
+tool raises an error carrying cf's own message — surface it verbatim.
+
+## Finding commands
+
+cf covers almost the whole Cloudflare API: more than 2,900 commands
+shaped `cf <product> [group] <verb>`, with the verbs `list`, `get`,
+`create`, `edit` (partial update), `update` (overwrite) and `delete`.
+Don't guess command names:
+
+1. Search, describing the task generically:
+ `{ "operation": "search_commands", "search_query": "purge cache for a zone" }`.
+ Describe the action and resource only — never names, domains, emails
+ or IDs.
+2. Check the request shape: run the match with `cf` replaced by
+ `schema`, e.g. `{ "operation": "custom", "command": "schema cache purge" }`.
+ It lists the path, query parameters and body fields.
+3. Preview with `--dry-run` (prints the HTTP request; nothing is sent),
+ then run the command.
## DNS records
-`record_body` is the raw JSON request body (the API's DNS record
-shape — stable across cf versions, unlike per-field flags):
+`record_body` is the API's DNS record JSON:
```json
-{ "operation": "dns_record_create", "zone": "example.com", "record_body": "{\"type\":\"A\",\"name\":\"www\",\"content\":\"192.0.2.1\",\"ttl\":1,\"proxied\":false}" }
+{ "operation": "dns_record_create", "zone": "example.com", "record_body": "{\"type\":\"A\",\"name\":\"www\",\"content\":\"192.0.2.1\",\"ttl\":1,\"proxied\":true}" }
```
-Common record fields: `type` (A/AAAA/CNAME/TXT/MX/NS/SRV), `name`
-(record name; `@` for the zone apex), `content`, `ttl` (`1` = auto),
-`proxied` (orange-cloud), `priority` (MX/SRV). Get record ids from
-`dns_records_list` before deleting:
+Common fields: `type` (A, AAAA, CNAME, TXT, MX, NS, SRV, CAA), `name`
+(`@` for the zone apex, or a subdomain), `content`, `ttl` (`1` =
+automatic), `proxied` (the orange cloud), `priority` (MX / SRV),
+`comment`. Find record IDs with `dns_records_list` (narrow it with
+`name_filter: "www.example.com"` and `record_type: "A"`), then:
```json
-{ "operation": "dns_records_list", "zone": "example.com" }
-{ "operation": "dns_record_delete", "zone": "example.com", "record_id": "023e105f4ecef8ad9ca31a8372d0c353" }
+{ "operation": "dns_record_edit", "zone": "example.com", "record_id": "372e67954025e0ba6aaa6d586b9e0b59", "record_body": "{\"content\":\"192.0.2.2\"}" }
+{ "operation": "dns_record_delete", "zone": "example.com", "record_id": "372e67954025e0ba6aaa6d586b9e0b59" }
```
-To update a record, use `custom` with `--body`:
+`dns_record_edit` changes only the fields you pass. To replace a record
+entirely, use `custom` with
+`dns records update <record-id> --zone <zone> --body '<the full record>'`.
+Several changes in one request:
+`dns records batch --zone <zone> --posts '[...]' --patches '[...]' --deletes '[{"id":"..."}]'`.
+Zone file: `dns records export --zone <zone>` (BIND text in `stdout`).
+
+## Other products via custom
```json
-{ "operation": "custom", "command": "dns records update <record-id> --zone example.com --body '{\"content\":\"192.0.2.2\"}'" }
+{ "operation": "custom", "command": "zones get --zone example.com" }
+{ "operation": "custom", "command": "cache purge --zone example.com --body '{\"purge_everything\":true}'" }
+{ "operation": "custom", "command": "workers list" }
+{ "operation": "custom", "command": "r2 buckets list" }
+{ "operation": "custom", "command": "r2 objects list --bucket-name my-bucket --prefix logs/" }
+{ "operation": "custom", "command": "kv namespaces list" }
+{ "operation": "custom", "command": "kv keys list --namespace-id <namespace id>" }
+{ "operation": "custom", "command": "d1 list" }
+{ "operation": "custom", "command": "d1 query <database id> --sql 'SELECT * FROM users LIMIT 10'" }
+{ "operation": "custom", "command": "pages list" }
+{ "operation": "custom", "command": "accounts list" }
```
+Rules for `custom`:
+
+- **Destructive commands need `--force`.** Without it cf asks for a
+ confirmation that a workflow cannot give, and the tool reports that
+ nothing ran. Confirm with the user before adding `--force` unless
+ they asked for the deletion.
+- Request bodies go in `--body '<json>'` (single quotes around the
+ JSON; the command is split like a shell command) or
+ `--body @file.json`. Relative paths resolve in the workflow workspace.
+- Account-scoped commands (Workers, R2, KV, D1, Pages) use `account_id`;
+ most commands have no `--account-id` flag. Zone-scoped commands take
+ `--zone <zone ID or domain>`.
+- Sign-in (`auth login`, `auth logout`) is not available here; it lives
+ in Credentials -> Cloudflare. `auth whoami` works (or use the `whoami`
+ operation).
+- Project commands (`init`, `build`, `dev`, `deploy`) need Node.js
+ 22.18+ and a project directory. OpenCompany runs cf on bun, so prefer
+ the API commands.
+
## Analytics — the GraphQL Analytics API
Cloudflare's legacy Zone Analytics REST API was deprecated (2021) and
the DNS analytics REST API is scheduled for removal (2026-12-01); the
-official replacement for both is the GraphQL Analytics API. The cf CLI
-does not expose it (its commands are generated from the REST schema),
-so use the `graphql_query` operation — it POSTs to the official
+official replacement for both is the GraphQL Analytics API. cf has no
+GraphQL command, so the `graphql_query` operation POSTs to the official
endpoint `api.cloudflare.com/client/v4/graphql`.
-**Requires the API token** from Credentials -> Cloudflare (the OAuth
-login has no analytics scopes): permission `Account > Account
+**It needs a credential stored in Credentials -> Cloudflare** (the CLI
+login stays inside the cf CLI): an API token with `Account > Account
Analytics > Read`, plus `Zone > Analytics > Read` for zone-scoped
-queries.
+queries, or the Global API Key with the Account Email.
Zone HTTP traffic (official migration-guide query, current dataset):
@@ -113,65 +171,38 @@ DNS analytics: `dnsAnalyticsAdaptive` / `dnsAnalyticsAdaptiveGroups`
(zone- and account-scoped). Notes: a query spans at most 10 zones or 1
account; the user quota is 300 queries per 5 minutes; wide time ranges
are sampled (multiply by `sampleInterval` for estimates). Web Analytics
-site CONFIG (create/list sites) lives on REST under
-`accounts/{account_id}/rum/site_info` — the cf CLI has no `rum`
-commands yet, and those endpoints also need the API token.
-
-## The full cf surface via custom
-
-```json
-{ "operation": "custom", "command": "accounts list" }
-{ "operation": "custom", "command": "dns records get <record-id> --zone example.com" }
-{ "operation": "custom", "command": "registrar domains list" }
-{ "operation": "custom", "command": "zones get --zone example.com" }
-{ "operation": "custom", "command": "dns analytics report --zone example.com" }
-```
-
-Discovery helpers when unsure of a command's shape:
-
-- `{ "operation": "custom", "command": "agent-context dns" }` — cf's
- built-in per-product agent context (also `agent-context --list` for
- the product catalogue).
-- `{ "operation": "custom", "command": "schema zones list" }` — the
- API schema behind a command.
-- Append `--dry-run` to any write command to validate without
- executing.
-
-## Quoting and escaping
-
-`command` is parsed with `shlex.split` — wrap JSON bodies in single
-quotes: `custom: "dns records create --zone example.com --body '{\"type\":\"A\",...}'"`.
+site configuration is a cf command: `rum site-info list`,
+`rum site-info get <site id>`, `rum site-info create --body '...'`
+(with `account_id`).
## Authentication
-Two independent paths; the token wins when both exist (cf's documented
-resolution order):
-
-1. **OAuth login** — Credentials Modal → Cloudflare → Login (cf opens
- the browser itself; localhost callback, so the browser must be on
- the server's machine), or `cf auth login` in a terminal. The OAuth
- grant is a FIXED scope set: zones, DNS (incl. `dns_analytics:read`),
- accounts, registrar, Workers — but NO Web Analytics/RUM or zone
- analytics scopes, and no way to request more.
-2. **API token or Global API Key** — pasted in the credentials panel
- (or `CLOUDFLARE_API_TOKEN` / `CLOUDFLARE_API_KEY`+`CLOUDFLARE_EMAIL`
- in the server env; panel values take precedence). Required for
- `graphql_query` and anything else outside the OAuth scopes. Scoped
- token: dash.cloudflare.com/profile/api-tokens with the permission
- groups the task needs. Global API Key (cfk_ prefix): full access,
- needs the Account Email field filled alongside it.
-
-If a command fails with an authentication or 403 error, tell the user
-which permission group the token needs; don't ask them to paste a
-token in chat.
+Two independent paths; the API token wins when both exist (cf's
+documented resolution order):
+
+1. **Login** — Credentials -> Cloudflare -> Login. Cloudflare's device
+ page opens and the modal shows a one-time code; approve the request
+ in any browser (this also works when OpenCompany runs on a remote
+ server). Or run `cf auth login` in a terminal on the server.
+2. **API token** — pasted in the credentials panel (or
+ `CLOUDFLARE_API_TOKEN` in the server environment; the panel value
+ wins). Needed for unattended use and for `graphql_query`. Create one
+ at dash.cloudflare.com/profile/api-tokens with the permission groups
+ the task needs. A Global API Key (cfk_) in the panel works only for
+ `graphql_query` — the cf CLI does not accept Global API Keys.
+
+If a command fails because nothing is signed in, the tool stops and asks
+the owner to connect Cloudflare. A 403 means the token or login lacks a
+permission — tell the user which permission group is missing; never ask
+them to paste a token in chat.
## Best practices
-1. **Run `whoami` first** when auth state is unknown — it returns the
- authenticated email and scopes without side effects.
-2. **Pass `zone` as the domain name** (cf resolves it to the zone ID).
-3. **Preview writes with `--dry-run`** via `custom` when the user's
- intent is ambiguous.
-4. **Destructive operations** (zone deletes, record deletes) — confirm
- with the user before running unless they explicitly asked.
+1. **Run `whoami` first** when the auth state or the account is unknown.
+2. **Pass `zone` as the domain or the zone ID**, and set `account_id`
+ when several accounts exist.
+3. **Use `search_commands`, `schema` and `--dry-run`** instead of
+ guessing commands.
+4. **Confirm destructive operations** (record deletes, any `--force`
+ command) with the user unless they explicitly asked.
5. **Surface cf error messages verbatim** — don't paraphrase.
diff --git a/server/tests/core_config/test_js_runtime.py b/server/tests/core_config/test_js_runtime.py
index ca35f391..95a9a7aa 100644
--- a/server/tests/core_config/test_js_runtime.py
+++ b/server/tests/core_config/test_js_runtime.py
@@ -61,6 +61,24 @@ def test_ensure_shared_tree_writes_a_private_manifest(tmp_path):
assert "cf" in json.loads((root / "package.json").read_text(encoding="utf-8"))["dependencies"]
+def test_installed_version_reads_the_package_manifest(tmp_path):
+ assert js_runtime.installed_version("cf", root=tmp_path) is None
+ pkg = tmp_path / "node_modules" / "cf"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text('{"name":"cf","version":"1.0.0-beta.12"}', encoding="utf-8")
+ assert js_runtime.installed_version("cf", root=tmp_path) == "1.0.0-beta.12"
+ # scoped names resolve through their scope folder
+ scoped = tmp_path / "node_modules" / "@anthropic-ai" / "claude-code"
+ scoped.mkdir(parents=True)
+ (scoped / "package.json").write_text('{"version":"2.1.0"}', encoding="utf-8")
+ assert js_runtime.installed_version("@anthropic-ai/claude-code", root=tmp_path) == "2.1.0"
+ # an unreadable or version-less manifest counts as "not installed"
+ (pkg / "package.json").write_text("{oops", encoding="utf-8")
+ assert js_runtime.installed_version("cf", root=tmp_path) is None
+ (pkg / "package.json").write_text('{"name":"cf"}', encoding="utf-8")
+ assert js_runtime.installed_version("cf", root=tmp_path) is None
+
+
def test_add_package_builds_a_bun_add_argv(monkeypatch, tmp_path):
seen: dict[str, object] = {}
diff --git a/server/tests/test_cloudflare_plugin.py b/server/tests/test_cloudflare_plugin.py
index 0a8ed8f1..409367cf 100644
--- a/server/tests/test_cloudflare_plugin.py
+++ b/server/tests/test_cloudflare_plugin.py
@@ -1,15 +1,27 @@
"""Cloudflare plugin contract tests.
Locks the plugin's load-bearing seams under the CLI-owns-auth (Stripe /
-gh) pattern: env builders (no token handling; login env strips ambient
-Cloudflare credential vars so whoami reflects the OAuth session), the
-login-banner URL parser (source-verified cf 0.2.0 output), install
-resolution (pinned npm spec into the shared packages tree; system cf
-never consulted), the marker-token + CloudEvents broadcast contract
-(``inspect.getsource`` introspection, ``test_credential_broadcasts``
-style), op argv building (verified against cf 0.2.0 ``--help-full``),
-NDJSON recovery, and the catalogue entry shape (fieldless — cf owns the
-token).
+gh) pattern, verified against the pinned cf 1.0.0-beta.12:
+
+- env builders: stored API token injected, Global API Key never (cf
+ ignores it); ``CF_DELEGATION`` + telemetry opt-out; the account via
+ ``CLOUDFLARE_ACCOUNT_ID``; the login env strips ambient tokens; ops run
+ from the neutral ``cf_workdir``.
+- install resolution: pinned npm spec into the shared packages tree,
+ reinstalled when another version is in place (clearing the stale login
+ marker); the system cf is never consulted.
+- op argv (``--help`` / ``--dry-run`` verified): ``--force`` on delete,
+ PATCH edit, domain -> zone ID lookup, filters + paging, failure hints,
+ the custom passthrough's guards.
+- the device-flow login handler (URL + code relayed to the modal, single
+ flight, install before any login, never killed, whoami-gated
+ completion) and the marker-token + CloudEvents broadcast contract
+ (``inspect.getsource`` introspection, ``test_credential_broadcasts``
+ style).
+- the catalogue entry shape and the plugin folder assets.
+
+No real cf binary is ever started: ``run_cli_command`` and the login
+spawn are faked.
"""
from __future__ import annotations
@@ -17,6 +29,7 @@ from __future__ import annotations
import asyncio
import inspect
import json
+import typing
from pathlib import Path
import pytest
@@ -34,17 +47,40 @@ from services.plugin.base import NodeUserError
PLUGIN_DIR = Path(cf_service.__file__).parent
CONFIG_PATH = Path(cf_service.__file__).parents[2] / "config" / "credential_providers.json"
+ZONE_ID = "023e105f4ecef8ad9ca31a8372d0c353"
+GLOBAL_KEY = "cfk_" + "y" * 48
+
+# Verbatim shape of cf 1.0's device-flow banner (stderr).
+BANNER = (
+ "Attempting to login via OAuth Device Authorization Grant...\n"
+ "To authorize cf, please visit:\n"
+ "\n"
+ " https://dash.cloudflare.com/oauth2/device\n"
+ "\n"
+ "and enter the code:\n"
+ "\n"
+ " ABCD-EFGH\n"
+ "\n"
+ "You have 5 minutes to approve this request.\n"
+)
+
# --- _service env builders ----------------------------------------------------
-def test_cf_env_keeps_ambient_token_for_ops(monkeypatch):
+def test_cf_env_sets_cli_hygiene_and_keeps_ambient_token(monkeypatch):
monkeypatch.setenv("CLOUDFLARE_API_TOKEN", "cf_ambient")
+ monkeypatch.delenv("CLOUDFLARE_ACCOUNT_ID", raising=False)
env = cf_service.cf_env()
assert env["NO_COLOR"] == "1"
+ # The pinned cf must not hand the command to another cf copy it can
+ # resolve (bun's install cache included), and telemetry stays off.
+ assert env["CF_DELEGATION"] == "1"
+ assert env["CF_SEND_TELEMETRY"] == "false"
# Ambient env token is left alone for ops — cf's documented precedence
# (and the headless path on remote deployments).
assert env["CLOUDFLARE_API_TOKEN"] == "cf_ambient"
+ assert "CLOUDFLARE_ACCOUNT_ID" not in env
def test_cf_env_stored_token_overrides_ambient(monkeypatch):
@@ -55,84 +91,140 @@ def test_cf_env_stored_token_overrides_ambient(monkeypatch):
assert env["CLOUDFLARE_API_TOKEN"] == "cf_stored"
-def test_cf_env_global_key_injects_documented_pair(monkeypatch):
- """A stored cfk_ Global API Key rides cf's documented legacy pair
- (CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL). Ambient token vars are
- dropped — cf ranks tokens above the key pair and would silently
- override the user's explicit choice."""
- monkeypatch.setenv("CLOUDFLARE_API_TOKEN", "cf_ambient")
- monkeypatch.setenv("CF_API_TOKEN", "cf_ambient2")
- key = "cfk_" + "y" * 48
- env = cf_service.cf_env(key, "[email protected]")
- assert env["CLOUDFLARE_API_KEY"] == key
- assert env["CLOUDFLARE_EMAIL"] == "[email protected]"
+def test_cf_env_never_injects_a_global_api_key(monkeypatch):
+ """cf refuses the Global API Key (the CLOUDFLARE_API_KEY +
+ CLOUDFLARE_EMAIL pair is ignored), so a stored cfk_ key is not
+ injected under any name — cf falls back to ambient env / its login."""
+ for var in ("CLOUDFLARE_API_TOKEN", "CF_API_TOKEN", "CLOUDFLARE_API_KEY", "CLOUDFLARE_EMAIL"):
+ monkeypatch.delenv(var, raising=False)
+ env = cf_service.cf_env(GLOBAL_KEY)
assert "CLOUDFLARE_API_TOKEN" not in env
- assert "CF_API_TOKEN" not in env
-
- # cfk_ without an email is unusable — nothing injected, cf falls
- # back to its OAuth session.
- monkeypatch.delenv("CLOUDFLARE_API_TOKEN", raising=False)
- env = cf_service.cf_env(key, None)
assert "CLOUDFLARE_API_KEY" not in env
- assert "CLOUDFLARE_API_TOKEN" not in env
+ assert "CLOUDFLARE_EMAIL" not in env
+
+ # ...and an ambient token is not dropped on its behalf.
+ monkeypatch.setenv("CLOUDFLARE_API_TOKEN", "cf_ambient")
+ assert cf_service.cf_env(GLOBAL_KEY)["CLOUDFLARE_API_TOKEN"] == "cf_ambient"
+
+
+def test_cf_env_routes_account_id(monkeypatch):
+ # cf has no --account-id flag on most commands; the account is
+ # CLOUDFLARE_ACCOUNT_ID.
+ monkeypatch.delenv("CLOUDFLARE_ACCOUNT_ID", raising=False)
+ assert cf_service.cf_env(None, "acct1")["CLOUDFLARE_ACCOUNT_ID"] == "acct1"
def test_api_auth_headers_route_by_prefix():
- key = "cfk_" + "y" * 48
- assert cf_service.api_auth_headers(key, "[email protected]") == {"X-Auth-Email": "[email protected]", "X-Auth-Key": key}
- assert cf_service.api_auth_headers(key, None) is None
+ assert cf_service.api_auth_headers(GLOBAL_KEY, "[email protected]") == {"X-Auth-Email": "[email protected]", "X-Auth-Key": GLOBAL_KEY}
+ assert cf_service.api_auth_headers(GLOBAL_KEY, None) is None
assert cf_service.api_auth_headers("cfut_tok", None) == {"Authorization": "Bearer cfut_tok"}
assert cf_service.api_auth_headers(None, "[email protected]") is None
def test_login_env_strips_ambient_credential_vars(monkeypatch):
"""With CLOUDFLARE_API_TOKEN set, `cf auth whoami` reports the env
- token (authSource: env) instead of the stored OAuth session — the
- login/status/logout paths must consult cf's OWN store."""
+ token instead of the OAuth login and `cf auth login` refuses to
+ start — the login/status/logout paths must consult cf's OWN store."""
for var in cf_service._AMBIENT_CREDENTIAL_VARS:
monkeypatch.setenv(var, "ambient")
env = cf_service.login_env()
for var in cf_service._AMBIENT_CREDENTIAL_VARS:
assert var not in env
assert env["NO_COLOR"] == "1"
+ assert env["CF_DELEGATION"] == "1"
+
+
+def test_cf_workdir_is_a_dedicated_data_dir(monkeypatch, tmp_path):
+ """cf reads .env files and looks for cloudflare.config.ts from its
+ working directory — ops run from a plugin-owned directory, never the
+ server's own cwd."""
+ import core.paths
+
+ monkeypatch.setattr(core.paths, "data_path", lambda sub="": tmp_path / str(sub))
+ workdir = cf_service.cf_workdir()
+ assert workdir == tmp_path / "cloudflare"
+ assert workdir.is_dir()
# --- _install resolution --------------------------------------------------------
def test_npm_spec_is_pinned():
- # Preview CLI: @latest would make cold installs non-reproducible and
- # silently change the argv surface this plugin was verified against.
- assert cf_install._NPM_SPEC.startswith("cf@")
+ # @latest would make cold installs non-reproducible and silently
+ # change the argv surface this plugin was verified against.
+ assert cf_install._NPM_SPEC == f"cf@{cf_install._NPM_VERSION}"
assert "latest" not in cf_install._NPM_SPEC
-async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):
- """The system-global cf is never consulted — the binary comes from
- the pinned ``bun add`` into the shared packages tree."""
+def _fake_tree(monkeypatch, tmp_path, *, installed):
+ """A shared tree whose cf shim exists iff ``installed`` is a version."""
from core import js_runtime
bin_dir = tmp_path / "node_modules" / ".bin"
- bin_dir.mkdir(parents=True)
- fake_bin = bin_dir / js_runtime.bin_shim_name("cf")
-
- calls = {"installs": 0}
+ bin_dir.mkdir(parents=True, exist_ok=True)
+ shim = bin_dir / js_runtime.bin_shim_name("cf")
+ state = {"version": installed, "installs": 0, "forgot": []}
+ if installed:
+ shim.write_text("", encoding="utf-8")
def fake_install():
- calls["installs"] += 1
- fake_bin.write_text("", encoding="utf-8")
- return fake_bin
+ state["installs"] += 1
+ shim.write_text("", encoding="utf-8")
+ state["version"] = cf_install._NPM_VERSION
+ return shim
+
+ async def fake_forget(previous):
+ state["forgot"].append(previous)
monkeypatch.setattr(cf_install, "_cached_path", None)
monkeypatch.setattr(cf_install, "shared_tree_bin", lambda name: bin_dir / js_runtime.bin_shim_name(name))
+ monkeypatch.setattr(cf_install, "_installed_version", lambda: state["version"])
monkeypatch.setattr(cf_install, "_install", fake_install)
+ monkeypatch.setattr(cf_install, "_forget_cli_login", fake_forget)
+ return shim, state
- resolved = await cf_install.ensure_cf_cli()
- assert resolved == fake_bin
- assert calls["installs"] == 1
+
+async def test_ensure_cf_cli_installs_into_shared_tree(monkeypatch, tmp_path):
+ """The system-global cf is never consulted — the binary comes from
+ the pinned ``bun add`` into the shared packages tree."""
+ shim, state = _fake_tree(monkeypatch, tmp_path, installed=None)
+ assert await cf_install.ensure_cf_cli() == shim
+ assert state["installs"] == 1
# cached for subsequent calls without re-installing
- assert await cf_install.ensure_cf_cli() == fake_bin
- assert calls["installs"] == 1
+ assert await cf_install.ensure_cf_cli() == shim
+ assert state["installs"] == 1
+ # a first install strands no login
+ assert state["forgot"] == []
+
+
+async def test_ensure_cf_cli_reinstalls_when_another_version_is_installed(monkeypatch, tmp_path):
+ """An existing shim says nothing about its version: an older cf is
+ upgraded to the pin, and the login marker is cleared because the new
+ version may not see the old login."""
+ shim, state = _fake_tree(monkeypatch, tmp_path, installed="0.2.0")
+ assert await cf_install.ensure_cf_cli() == shim
+ assert state["installs"] == 1
+ assert state["forgot"] == ["0.2.0"]
+
+
+async def test_ensure_cf_cli_reuses_a_matching_install(monkeypatch, tmp_path):
+ shim, state = _fake_tree(monkeypatch, tmp_path, installed=cf_install._NPM_VERSION)
+ assert await cf_install.ensure_cf_cli() == shim
+ assert state["installs"] == 0
+ assert state["forgot"] == []
+
+
+def test_cf_cli_path_ignores_an_older_install(monkeypatch, tmp_path):
+ shim, state = _fake_tree(monkeypatch, tmp_path, installed="0.2.0")
+ assert cf_install.cf_cli_path() is None
+ state["version"] = cf_install._NPM_VERSION
+ assert cf_install.cf_cli_path() == shim
+
+
+def test_upgrade_clears_the_login_marker_and_broadcasts():
+ src = inspect.getsource(cf_install._forget_cli_login)
+ assert 'mark_logged_out("cloudflare")' in src
+ assert "credential.oauth.disconnected" in src
def test_cf_binary_never_resolved_from_system_path():
@@ -162,150 +254,225 @@ def _wire(monkeypatch, tmp_path, run_impl):
# — absent in unit tests, so stub the lookups to "nothing stored".
monkeypatch.setattr(cf_service, "stored_token", nothing_stored)
monkeypatch.setattr(cf_service, "stored_email", nothing_stored)
+ monkeypatch.setattr(cf_service, "cf_workdir", lambda: tmp_path / "cfwork")
+
+
+def _ok(result=None, stdout=None, stderr=""):
+ if stdout is None:
+ stdout = json.dumps(result, indent=2) if result is not None else ""
+ return {"success": True, "result": result, "stdout": stdout, "stderr": stderr, "error": None}
+
+
+def _recorder(*replies):
+ """A fake ``run_cli_command`` that records every call and answers
+ with ``replies`` in order (the last one repeats)."""
+ calls = []
+
+ async def fake_run(**kwargs):
+ calls.append(kwargs)
+ return replies[min(len(calls), len(replies)) - 1]
+
+ return calls, fake_run
def _ctx(tmp_path) -> NodeContext:
return NodeContext(node_id="cf1", node_type="cloudflareAction", workspace_dir=str(tmp_path))
-async def test_whoami_argv_and_env(monkeypatch, tmp_path):
- captured = {}
+def _flag(argv, name):
+ return argv[argv.index(name) + 1]
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": {"authenticated": True, "email": "[email protected]"}, "stdout": "{}", "stderr": "", "error": None}
+async def test_whoami_argv_env_and_cwd(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"authenticated": True, "email": "[email protected]", "accounts": []}))
_wire(monkeypatch, tmp_path, fake_run)
monkeypatch.delenv("CLOUDFLARE_API_TOKEN", raising=False)
- node = CloudflareActionNode()
- out = await node.whoami(_ctx(tmp_path), CloudflareActionParams(operation="whoami"))
+ out = await CloudflareActionNode().whoami(_ctx(tmp_path), CloudflareActionParams(operation="whoami"))
- assert captured["argv"] == ["auth", "whoami"]
+ (call,) = calls
+ assert call["argv"] == ["auth", "whoami"]
# env comes from cf_env() — no stored token, so nothing injected
- assert captured["env"]["NO_COLOR"] == "1"
- assert "CLOUDFLARE_API_TOKEN" not in captured["env"]
- assert out["result"] == {"authenticated": True, "email": "[email protected]"}
+ assert call["env"]["NO_COLOR"] == "1"
+ assert call["env"]["CF_DELEGATION"] == "1"
+ assert "CLOUDFLARE_API_TOKEN" not in call["env"]
+ # typed ops run from the neutral working directory
+ assert call["cwd"] == str(tmp_path / "cfwork")
+ assert out["result"]["email"] == "[email protected]"
async def test_ops_inject_stored_api_token(monkeypatch, tmp_path):
"""The optional credentials-modal token rides every op as
- CLOUDFLARE_API_TOKEN (cf's first-priority credential source) — the
- only path past the OAuth grant's fixed scope set."""
- captured = {}
-
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": [], "stdout": "[]", "stderr": "", "error": None}
-
+ CLOUDFLARE_API_TOKEN (cf's first-priority credential source)."""
+ calls, fake_run = _recorder(_ok([]))
_wire(monkeypatch, tmp_path, fake_run)
async def fake_token():
return "cf_tok_123"
monkeypatch.setattr(cf_service, "stored_token", fake_token)
- node = CloudflareActionNode()
- await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
- assert captured["env"]["CLOUDFLARE_API_TOKEN"] == "cf_tok_123"
-
-
-async def test_ops_inject_stored_global_key_pair(monkeypatch, tmp_path):
- """A stored cfk_ Global API Key + email ride every op as cf's
- documented CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL pair."""
- captured = {}
+ await CloudflareActionNode().zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+ assert calls[0]["env"]["CLOUDFLARE_API_TOKEN"] == "cf_tok_123"
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": [], "stdout": "[]", "stderr": "", "error": None}
+async def test_ops_never_inject_a_stored_global_key(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok([]))
_wire(monkeypatch, tmp_path, fake_run)
- key = "cfk_" + "y" * 48
+ for var in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_KEY", "CLOUDFLARE_EMAIL"):
+ monkeypatch.delenv(var, raising=False)
async def fake_token():
- return key
+ return GLOBAL_KEY
async def fake_email():
monkeypatch.setattr(cf_service, "stored_token", fake_token)
monkeypatch.setattr(cf_service, "stored_email", fake_email)
+ await CloudflareActionNode().zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+ env = calls[0]["env"]
+ assert "CLOUDFLARE_API_TOKEN" not in env
+ assert "CLOUDFLARE_API_KEY" not in env
+ assert "CLOUDFLARE_EMAIL" not in env
+
+
+async def test_search_commands_runs_cli_search(monkeypatch, tmp_path):
+ matches = [{"command": "cf dns records create", "summary": "Create DNS Record"}]
+ calls, fake_run = _recorder(_ok(matches))
+ _wire(monkeypatch, tmp_path, fake_run)
node = CloudflareActionNode()
- await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
- assert captured["env"]["CLOUDFLARE_API_KEY"] == key
- assert captured["env"]["CLOUDFLARE_EMAIL"] == "[email protected]"
- assert "CLOUDFLARE_API_TOKEN" not in captured["env"]
+ with pytest.raises(NodeUserError, match="search_query"):
+ await node.search_commands(_ctx(tmp_path), CloudflareActionParams(operation="search_commands"))
-async def test_zones_list_builds_filter_argv(monkeypatch, tmp_path):
- captured = {}
+ out = await node.search_commands(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="search_commands", search_query="create a dns record"),
+ )
+ # one argv element: cf joins the words itself
+ assert calls[0]["argv"] == ["cli", "search", "create a dns record"]
+ assert out["result"] == matches
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": [{"name": "example.com"}], "stdout": "[]", "stderr": "", "error": None}
+async def test_zones_list_builds_filter_and_paging_argv(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok([{"id": ZONE_ID, "name": "example.com"}]))
_wire(monkeypatch, tmp_path, fake_run)
+ monkeypatch.delenv("CLOUDFLARE_ACCOUNT_ID", raising=False)
node = CloudflareActionNode()
await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
- assert captured["argv"] == ["zones", "list"]
+ assert calls[0]["argv"] == ["zones", "list"]
+ assert "CLOUDFLARE_ACCOUNT_ID" not in calls[0]["env"]
out = await node.zones_list(
_ctx(tmp_path),
- CloudflareActionParams(operation="zones_list", name_filter="example.com", account_id="acct1"),
+ CloudflareActionParams(operation="zones_list", name_filter="example.com", account_id="acct1", page=2, per_page=50),
)
- argv = captured["argv"]
+ argv = calls[1]["argv"]
assert argv[:2] == ["zones", "list"]
- assert argv[argv.index("--name") + 1] == "example.com"
- assert argv[argv.index("--account-id") + 1] == "acct1"
- assert out["result"] == [{"name": "example.com"}]
+ assert _flag(argv, "--name") == "example.com"
+ assert _flag(argv, "--account-id") == "acct1"
+ assert _flag(argv, "--page") == "2"
+ assert _flag(argv, "--per-page") == "50"
+ assert calls[1]["env"]["CLOUDFLARE_ACCOUNT_ID"] == "acct1"
+ assert out["result"] == [{"id": ZONE_ID, "name": "example.com"}]
-async def test_dns_records_list_requires_zone(monkeypatch, tmp_path):
- captured = {}
-
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": [{"id": "r1"}], "stdout": "[]", "stderr": "", "error": None}
-
+async def test_dns_records_list_requires_zone_and_builds_filters(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok([{"id": "r1"}]))
_wire(monkeypatch, tmp_path, fake_run)
node = CloudflareActionNode()
with pytest.raises(NodeUserError, match="zone"):
await node.dns_records_list(_ctx(tmp_path), CloudflareActionParams(operation="dns_records_list"))
+ assert calls == []
- await node.dns_records_list(_ctx(tmp_path), CloudflareActionParams(operation="dns_records_list", zone="example.com"))
- argv = captured["argv"]
+ await node.dns_records_list(
+ _ctx(tmp_path),
+ CloudflareActionParams(
+ operation="dns_records_list",
+ zone=ZONE_ID,
+ name_filter="www.example.com",
+ record_type="cname",
+ per_page=100,
+ ),
+ )
+ # A zone ID needs no lookup — one call.
+ (call,) = calls
+ argv = call["argv"]
assert argv[:3] == ["dns", "records", "list"]
- assert argv[argv.index("--zone") + 1] == "example.com"
+ assert _flag(argv, "--zone") == ZONE_ID
+ assert _flag(argv, "--name") == "www.example.com"
+ assert _flag(argv, "--type") == "CNAME"
+ assert _flag(argv, "--per-page") == "100"
+ assert "--page" not in argv
+
+
+async def test_domain_zone_is_resolved_to_its_id(monkeypatch, tmp_path):
+ """cf only searches the first page of the selected account's zones
+ for a domain — the node looks it up exactly with zones list --name
+ and passes the ID."""
+ calls, fake_run = _recorder(
+ _ok([{"id": ZONE_ID, "name": "example.com", "account": {"id": "acct1"}}]),
+ _ok([{"id": "r1"}]),
+ )
+ _wire(monkeypatch, tmp_path, fake_run)
+ await CloudflareActionNode().dns_records_list(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="dns_records_list", zone="Example.com.", account_id="acct1"),
+ )
+ lookup, listing = calls
+ assert lookup["argv"] == ["zones", "list", "--name", "example.com", "--account-id", "acct1"]
+ assert listing["argv"][:5] == ["dns", "records", "list", "--zone", ZONE_ID]
+ assert listing["env"]["CLOUDFLARE_ACCOUNT_ID"] == "acct1"
-async def test_dns_record_create_validates_body_and_builds_argv(monkeypatch, tmp_path):
- captured = {}
+async def test_domain_zone_resolution_errors(monkeypatch, tmp_path):
+ node = CloudflareActionNode()
+ params = CloudflareActionParams(operation="dns_records_list", zone="example.com")
+
+ calls, fake_run = _recorder(_ok([]))
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match="Zone not found"):
+ await node.dns_records_list(_ctx(tmp_path), params)
+ assert len(calls) == 1
+
+ twins = [
+ {"id": ZONE_ID, "name": "example.com", "account": {"id": "acctA"}},
+ {"id": "f" * 32, "name": "example.com", "account": {"id": "acctB"}},
+ ]
+ calls, fake_run = _recorder(_ok(twins))
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match="account_id"):
+ await node.dns_records_list(_ctx(tmp_path), params)
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": {"id": "new1"}, "stdout": "{}", "stderr": "", "error": None}
+async def test_dns_record_create_validates_body_and_builds_argv(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"id": "new1"}))
_wire(monkeypatch, tmp_path, fake_run)
node = CloudflareActionNode()
- body = '{"type":"A","name":"www","content":"192.0.2.1","ttl":1}'
+ body = '{"type":"A","name":"www","content":"192.0.2.1","ttl":1,"proxied":true}'
with pytest.raises(NodeUserError, match="record_body"):
- await node.dns_record_create(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_create", zone="example.com"))
-
+ await node.dns_record_create(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_create", zone=ZONE_ID))
with pytest.raises(NodeUserError, match="not valid JSON"):
await node.dns_record_create(
_ctx(tmp_path),
- CloudflareActionParams(operation="dns_record_create", zone="example.com", record_body="{oops"),
+ CloudflareActionParams(operation="dns_record_create", zone=ZONE_ID, record_body="{oops"),
+ )
+ with pytest.raises(NodeUserError, match="JSON object"):
+ await node.dns_record_create(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="dns_record_create", zone=ZONE_ID, record_body="[1, 2]"),
)
+ # Local validation runs before any CLI call (zone lookup included).
+ assert calls == []
await node.dns_record_create(
_ctx(tmp_path),
- CloudflareActionParams(operation="dns_record_create", zone="example.com", record_body=body),
+ CloudflareActionParams(operation="dns_record_create", zone=ZONE_ID, record_body=body),
)
- argv = captured["argv"]
- assert argv[:3] == ["dns", "records", "create"]
- assert argv[argv.index("--zone") + 1] == "example.com"
- assert argv[argv.index("--body") + 1] == body
+ # cf 1.0: the record is --body JSON only — no per-field flags.
+ assert calls[0]["argv"] == ["dns", "records", "create", "--zone", ZONE_ID, "--body", body]
def test_record_body_coerces_llm_dict_args():
@@ -318,74 +485,196 @@ def test_record_body_coerces_llm_dict_args():
assert json.loads(params.record_body) == {"type": "A", "name": "www"}
-async def test_dns_record_delete_uses_positional_id(monkeypatch, tmp_path):
- captured = {}
+def test_page_params_accept_panel_blanks():
+ # The panel stores "" for a cleared number field.
+ params = CloudflareActionParams(operation="zones_list", page="", per_page="")
+ assert params.page is None and params.per_page is None
+ assert CloudflareActionParams(operation="zones_list", page="2").page == 2
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": {"id": "r1"}, "stdout": "{}", "stderr": "", "error": None}
+async def test_dns_record_edit_is_a_patch_with_positional_id(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"id": "r1", "content": "192.0.2.2"}))
_wire(monkeypatch, tmp_path, fake_run)
node = CloudflareActionNode()
+ body = '{"content":"192.0.2.2"}'
with pytest.raises(NodeUserError, match="record_id"):
- await node.dns_record_delete(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_delete", zone="example.com"))
+ await node.dns_record_edit(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="dns_record_edit", zone=ZONE_ID, record_body=body),
+ )
+ with pytest.raises(NodeUserError, match="record_body"):
+ await node.dns_record_edit(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="dns_record_edit", zone=ZONE_ID, record_id="r1"),
+ )
+
+ await node.dns_record_edit(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="dns_record_edit", zone=ZONE_ID, record_id="r1", record_body=body),
+ )
+ # `edit` is the PATCH (only the given fields change); `update` would overwrite.
+ assert calls[0]["argv"] == ["dns", "records", "edit", "r1", "--zone", ZONE_ID, "--body", body]
+
+
+async def test_dns_record_delete_forces_and_uses_positional_id(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"id": "r1"}))
+ _wire(monkeypatch, tmp_path, fake_run)
+ node = CloudflareActionNode()
+
+ with pytest.raises(NodeUserError, match="record_id"):
+ await node.dns_record_delete(_ctx(tmp_path), CloudflareActionParams(operation="dns_record_delete", zone=ZONE_ID))
await node.dns_record_delete(
_ctx(tmp_path),
- CloudflareActionParams(operation="dns_record_delete", zone="example.com", record_id="r1"),
+ CloudflareActionParams(operation="dns_record_delete", zone=ZONE_ID, record_id="r1"),
)
- # cf 0.2.0: `cf dns records delete <dns-record-id>` — the id is positional.
- assert captured["argv"][:4] == ["dns", "records", "delete", "r1"]
- assert captured["argv"][captured["argv"].index("--zone") + 1] == "example.com"
+ # Without --force a non-interactive cf prints "Aborted." and exits 0
+ # with the record still there.
+ assert calls[0]["argv"] == ["dns", "records", "delete", "r1", "--zone", ZONE_ID, "--force"]
-async def test_cf_auth_error_surfaces_verbatim_as_node_user_error(monkeypatch, tmp_path):
- """No pre-flight: cf's own 'Not logged in' error IS the auth error."""
+async def test_aborted_confirmation_is_an_error(monkeypatch, tmp_path):
+ aborted = _ok(stdout="", stderr="? This permanently deletes the resource. Continue?\n (non-interactive; pass --force to confirm)\nAborted.")
+ calls, fake_run = _recorder(aborted)
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match="--force"):
+ await CloudflareActionNode().custom(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="custom", command="kv namespaces delete ns1"),
+ )
- async def fake_run(**kwargs):
- return {"success": False, "stdout": "", "stderr": "Not logged in. Run 'cf auth login' to authenticate.", "error": "exit 1"}
+async def test_cf_auth_error_surfaces_verbatim_with_login_hint(monkeypatch, tmp_path):
+ """No pre-flight: cf's own error IS the auth error, and only the
+ owner can fix it."""
+ stderr = (
+ "┌ Error\n│ No authentication token found. Either:\n│ 1. Set the CLOUDFLARE_API_TOKEN environment variable\n"
+ "│ 2. Run 'cf auth login' to authenticate via OAuth\n└"
+ )
+ calls, fake_run = _recorder({"success": False, "stdout": "", "stderr": stderr, "error": stderr})
_wire(monkeypatch, tmp_path, fake_run)
- node = CloudflareActionNode()
- with pytest.raises(NodeUserError, match="cf auth login"):
- await node.zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+ with pytest.raises(NodeUserError, match="cf auth login") as exc:
+ await CloudflareActionNode().zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+ assert exc.value.requires_user_action is True
+ assert "Credentials -> Cloudflare" in exc.value.hint
-async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):
- captured = {}
+async def test_global_key_auth_failure_explains_the_cli_limit(monkeypatch, tmp_path):
+ calls, fake_run = _recorder({"success": False, "stdout": "", "stderr": "No authentication token found.", "error": "exit 1"})
+ _wire(monkeypatch, tmp_path, fake_run)
- async def fake_run(**kwargs):
- captured.update(kwargs)
- return {"success": True, "result": {"ok": True}, "stdout": "{}", "stderr": "", "error": None}
+ async def fake_token():
+ return GLOBAL_KEY
+ monkeypatch.setattr(cf_service, "stored_token", fake_token)
+ with pytest.raises(NodeUserError) as exc:
+ await CloudflareActionNode().zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+ assert "Global API Key" in exc.value.hint
+
+
+async def test_multi_account_error_points_at_account_id(monkeypatch, tmp_path):
+ stderr = "More than one account available but unable to select one in non-interactive mode."
+ calls, fake_run = _recorder({"success": False, "stdout": "", "stderr": stderr, "error": stderr})
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match="More than one account") as exc:
+ await CloudflareActionNode().custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command="workers list"))
+ assert "account_id" in exc.value.hint
+ assert exc.value.requires_user_action is False
+
+
+async def test_timeout_names_the_command(monkeypatch, tmp_path):
+ calls, fake_run = _recorder({"success": False, "error": f"{tmp_path / 'cf'} timed out (120.0s)"})
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match=r"cf zones list timed out after 120s"):
+ await CloudflareActionNode().zones_list(_ctx(tmp_path), CloudflareActionParams(operation="zones_list"))
+
+
+async def test_install_failure_is_a_user_error(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok([]))
+ _wire(monkeypatch, tmp_path, fake_run)
+
+ async def broken_install():
+ raise RuntimeError("bun add cf@x failed: offline")
+
+ monkeypatch.setattr(cf_install, "ensure_cf_cli", broken_install)
+ with pytest.raises(NodeUserError, match="cf CLI install failed"):
+ await CloudflareActionNode().whoami(_ctx(tmp_path), CloudflareActionParams(operation="whoami"))
+ assert calls == []
+
+
+async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"ok": True}))
_wire(monkeypatch, tmp_path, fake_run)
node = CloudflareActionNode()
with pytest.raises(NodeUserError):
await node.custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command=" "))
+ with pytest.raises(NodeUserError):
+ await node.custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command="cf"))
await node.custom(
_ctx(tmp_path),
- CloudflareActionParams(operation="custom", command="dns records update r1 --zone example.com --body '{\"content\":\"192.0.2.2\"}'"),
+ CloudflareActionParams(
+ operation="custom",
+ command="cf dns records update r1 --zone example.com --body '{\"content\":\"192.0.2.2\"}'",
+ ),
)
- assert captured["argv"] == ["dns", "records", "update", "r1", "--zone", "example.com", "--body", '{"content":"192.0.2.2"}']
- assert captured["timeout"] == cf_action_mod._CUSTOM_TIMEOUT
+ # A leading "cf " is tolerated; the rest passes through verbatim.
+ assert calls[0]["argv"] == ["dns", "records", "update", "r1", "--zone", "example.com", "--body", '{"content":"192.0.2.2"}']
+ assert calls[0]["timeout"] == cf_action_mod._CUSTOM_TIMEOUT
+ # custom runs from the workflow workspace so relative file paths resolve there
+ assert calls[0]["cwd"] == str(tmp_path)
+
+
+async def test_custom_without_a_workspace_runs_from_the_neutral_dir(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok([]))
+ _wire(monkeypatch, tmp_path, fake_run)
+ ctx = NodeContext(node_id="cf1", node_type="cloudflareAction", workspace_dir=None)
+ await CloudflareActionNode().custom(ctx, CloudflareActionParams(operation="custom", command="workers list"))
+ assert calls[0]["cwd"] == str(tmp_path / "cfwork")
+
+
+async def test_custom_rejects_unbalanced_quotes(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({}))
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError, match="single quotes"):
+ await CloudflareActionNode().custom(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="custom", command="dns records create --body '{\"type\":\"A\""),
+ )
+ assert calls == []
+
+
[email protected]("command", ["auth login", "login", "auth logout", "auth create work", "AUTH LOGIN --force", "dev"])
+async def test_custom_blocks_interactive_auth_and_dev(monkeypatch, tmp_path, command):
+ calls, fake_run = _recorder(_ok({}))
+ _wire(monkeypatch, tmp_path, fake_run)
+ with pytest.raises(NodeUserError):
+ await CloudflareActionNode().custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command=command))
+ assert calls == []
+
+
+async def test_custom_allows_read_only_auth_commands(monkeypatch, tmp_path):
+ calls, fake_run = _recorder(_ok({"authenticated": False}))
+ _wire(monkeypatch, tmp_path, fake_run)
+ await CloudflareActionNode().custom(_ctx(tmp_path), CloudflareActionParams(operation="custom", command="auth whoami"))
+ assert calls[0]["argv"] == ["auth", "whoami"]
async def test_graphql_requires_a_credential(monkeypatch, tmp_path):
- """The cf OAuth grant has no analytics scopes — graphql_query must
- fail with the credential guidance (token OR global key + email),
- not a bare 403."""
+ """The cf login stays inside the CLI — graphql_query must fail with
+ the credential guidance (token OR global key + email), not a bare
+ 403."""
_wire(monkeypatch, tmp_path, None)
for var in ("CLOUDFLARE_API_TOKEN", "CLOUDFLARE_API_KEY", "CLOUDFLARE_EMAIL"):
monkeypatch.delenv(var, raising=False)
- node = CloudflareActionNode()
- with pytest.raises(NodeUserError, match="Account Analytics"):
- await node.graphql_query(
+ with pytest.raises(NodeUserError, match="Account Analytics") as exc:
+ await CloudflareActionNode().graphql_query(
_ctx(tmp_path),
CloudflareActionParams(operation="graphql_query", graphql_query="query { viewer { zones { __typename } } }"),
)
+ assert exc.value.requires_user_action is True
async def test_graphql_posts_official_body_shape(monkeypatch, tmp_path):
@@ -464,28 +753,20 @@ def test_graphql_endpoint_is_the_official_one():
assert cf_action_mod._GRAPHQL_ENDPOINT == "https://api.cloudflare.com/client/v4/graphql"
-def test_parse_ndjson_recovers_multi_object_stdout():
- ndjson = '{"id": 1}\n{"id": 2}\n'
- assert CloudflareActionNode._parse_ndjson(ndjson) == [{"id": 1}, {"id": 2}]
- # Single document and non-JSON text are not NDJSON.
- assert CloudflareActionNode._parse_ndjson('{"id": 1}') is None
- assert CloudflareActionNode._parse_ndjson("plain\ntext") is None
-
-
-def test_shape_prefers_parsed_result_then_ndjson_then_stdout():
+def test_shape_prefers_parsed_result_then_stdout():
shaped = CloudflareActionNode._shape("op", {"result": {"a": 1}, "stdout": '{"a": 1}', "stderr": ""})
assert shaped["result"] == {"a": 1}
assert "stdout" not in shaped
- shaped = CloudflareActionNode._shape("op", {"result": None, "stdout": '{"id": 1}\n{"id": 2}', "stderr": ""})
- assert shaped["result"] == [{"id": 1}, {"id": 2}]
- assert "stdout" not in shaped
-
+ # Text output (e.g. a BIND export) ships as stdout.
shaped = CloudflareActionNode._shape("op", {"result": None, "stdout": "plain text", "stderr": "warn"})
assert shaped["stdout"] == "plain text"
assert "result" not in shaped
assert shaped["stderr_tail"] == "warn"
+ # A change that returns no data prints nothing — only the status keys.
+ assert CloudflareActionNode._shape("op", {"result": None, "stdout": "", "stderr": ""}) == {"operation": "op", "success": True}
+
def test_node_has_no_auth_preflight():
# Stripe-strict: the CLI owns auth; the node must not pre-check it.
@@ -494,50 +775,217 @@ def test_node_has_no_auth_preflight():
assert "PermissionError" not in src
+def test_every_operation_has_a_method():
+ declared = set(typing.get_args(CloudflareActionParams.model_fields["operation"].annotation))
+ implemented = {spec.name for spec in CloudflareActionNode._operations.values()}
+ assert declared == implemented
+
+
+def test_tool_description_names_every_operation():
+ # The LLM sees no description on the operation enum (and Gemini drops
+ # displayOptions), so the tool description is where it learns them.
+ for op in typing.get_args(CloudflareActionParams.model_fields["operation"].annotation):
+ assert op in CloudflareActionNode.tool_description
+
+
# --- login handler --------------------------------------------------------------
def _reset_login_state(monkeypatch):
- monkeypatch.setattr(cf_handlers, "_active_login", {"task": None, "proc": None})
+ monkeypatch.setattr(cf_handlers, "_active_login", cf_handlers._fresh_state())
+
+
+class _FakeProc:
+ """Just enough of asyncio.subprocess.Process for the login flow."""
+
+ def __init__(self, stderr_text: str = ""):
+ self.pid = 4242
+ self.returncode = None
+ self.stdout = asyncio.StreamReader()
+ self.stderr = asyncio.StreamReader()
+ self._exited = asyncio.Event()
+ if stderr_text:
+ self.stderr.feed_data(stderr_text.encode())
+
+ def finish(self, code: int = 0) -> None:
+ self.stdout.feed_eof()
+ self.stderr.feed_eof()
+ self.returncode = code
+ self._exited.set()
+
+ async def wait(self) -> int:
+ await self._exited.wait()
+ return self.returncode
+
+
+async def _until(condition, timeout: float = 2.0) -> None:
+ loop = asyncio.get_running_loop()
+ end = loop.time() + timeout
+ while not condition():
+ assert loop.time() < end, "condition not reached"
+ await asyncio.sleep(0.01)
+
+
+def _installed_cli(monkeypatch, tmp_path):
+ async def fake_ensure():
+ return tmp_path / "cf"
+
+ async def no_login():
+ return None
+ monkeypatch.setattr(cf_handlers, "cf_cli_path", lambda: tmp_path / "cf")
+ monkeypatch.setattr(cf_handlers, "ensure_cf_cli", fake_ensure)
+ monkeypatch.setattr(cf_handlers, "whoami_snapshot", no_login)
-async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
+
+def test_parse_login_banner_reads_cf_device_banner():
+ assert cf_handlers.parse_login_banner(BANNER) == ("https://dash.cloudflare.com/oauth2/device", "ABCD-EFGH")
+ # still waiting for the code
+ assert cf_handlers.parse_login_banner(BANNER.split("and enter")[0]) is None
+ # colour codes never leak into the URL or code
+ coloured = BANNER.replace("https://", "\x1b[36mhttps://").replace("device\n", "device\x1b[39m\n")
+ assert cf_handlers.parse_login_banner(coloured) == ("https://dash.cloudflare.com/oauth2/device", "ABCD-EFGH")
+
+
+def test_login_args_use_the_device_flow_without_a_server_browser():
+ # Device flow: no callback server, works from any machine; the
+ # frontend opens the URL, so cf must not open a second tab.
+ assert cf_handlers._LOGIN_ARGS[:2] == ["auth", "login"]
+ assert "--device" in cf_handlers._LOGIN_ARGS
+ assert "--no-browser" in cf_handlers._LOGIN_ARGS
+ assert "--no-device" not in cf_handlers._LOGIN_ARGS
+ # pushes past a stale stored token (only spawned when whoami says no login)
+ assert "--force" in cf_handlers._LOGIN_ARGS
+
+
+async def test_login_relays_device_url_and_code_then_marks_on_approval(monkeypatch, tmp_path):
_reset_login_state(monkeypatch)
+ _installed_cli(monkeypatch, tmp_path)
+ proc = _FakeProc(BANNER)
+ spawned = []
- async def stalled_flow():
- await asyncio.sleep(30)
- return {"success": True, "message": "done"}
+ async def fake_spawn(binary):
+ spawned.append(binary)
+ return proc
- monkeypatch.setattr(cf_handlers, "_start_login_flow", stalled_flow)
- monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+ monkeypatch.setattr(cf_handlers, "_spawn_login", fake_spawn)
res = await cf_handlers.handle_cloudflare_login({}, websocket=None)
assert res["success"] is True
- assert res.get("pending") is True
+ assert res["url"] == "https://dash.cloudflare.com/oauth2/device"
+ assert res["verification_code"] == "ABCD-EFGH"
+ assert len(spawned) == 1
+
+ # A repeat click while the code awaits approval returns the same code
+ # instead of starting a second device flow.
+ again = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert again["verification_code"] == "ABCD-EFGH"
+ assert len(spawned) == 1
+
+ # Approval: cf exits, whoami reports the login -> marker + broadcast.
+ marked = []
+
+ async def fake_mark(email):
+ marked.append(email)
+ async def logged_in():
+ return {"authenticated": True, "email": "[email protected]"}
-async def test_login_response_never_proxies_a_url(monkeypatch):
- # The CLI owns the whole interaction — it opens the browser itself.
- # The handler must not return url/verification_code for the modal
- # to act on (no custom login UI).
+ monkeypatch.setattr(cf_handlers, "_mark_connected", fake_mark)
+ monkeypatch.setattr(cf_handlers, "whoami_snapshot", logged_in)
+ proc.finish(0)
+ await _until(lambda: marked == ["[email protected]"])
+ await _until(lambda: cf_handlers._active_login["proc"] is None)
+
+
+async def test_login_reports_cf_output_when_no_code_is_issued(monkeypatch, tmp_path):
+ _reset_login_state(monkeypatch)
+ _installed_cli(monkeypatch, tmp_path)
+ proc = _FakeProc("┌ Error\n│ fetch failed: dash.cloudflare.com unreachable\n└\n")
+
+ async def fake_spawn(binary):
+ proc.finish(1)
+ return proc
+
+ monkeypatch.setattr(cf_handlers, "_spawn_login", fake_spawn)
+ res = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert res["success"] is False
+ assert "unreachable" in res["error"]
+
+
+async def test_login_short_circuits_when_already_logged_in(monkeypatch, tmp_path):
_reset_login_state(monkeypatch)
+ _installed_cli(monkeypatch, tmp_path)
+ marked = []
+
+ async def live_login():
+ return {"authenticated": True, "email": "[email protected]"}
- async def instant_flow():
- return {"success": True, "message": "cf is opening your default browser."}
+ async def fake_mark(email):
+ marked.append(email)
- monkeypatch.setattr(cf_handlers, "_start_login_flow", instant_flow)
+ async def boom(binary):
+ raise AssertionError("a live login must not spawn a device flow")
+
+ monkeypatch.setattr(cf_handlers, "whoami_snapshot", live_login)
+ monkeypatch.setattr(cf_handlers, "_mark_connected", fake_mark)
+ monkeypatch.setattr(cf_handlers, "_spawn_login", boom)
res = await cf_handlers.handle_cloudflare_login({}, websocket=None)
assert res["success"] is True
- assert "url" not in res
- assert "verification_code" not in res
- src = inspect.getsource(cf_handlers._start_login_flow)
- assert '"url"' not in src
+ assert "Already logged in" in res["message"]
+ assert marked == ["[email protected]"]
-async def test_login_is_single_flight(monkeypatch):
- # cf's callback server binds the FIXED port 8877 — a second
- # concurrent `cf auth login` exits instantly with a port conflict.
- # A repeat click while a flow is live must not spawn again.
+async def test_login_installs_cf_before_any_login_is_spawned(monkeypatch, tmp_path):
+ """First use: a device code issued after the request was answered
+ would be invisible — the install runs alone, and Login is clicked
+ again once it finishes."""
_reset_login_state(monkeypatch)
+ release = asyncio.Event()
+ installs = []
+
+ async def slow_install():
+ installs.append(1)
+ await release.wait()
+ return tmp_path / "cf"
+
+ async def boom(binary):
+ raise AssertionError("no login may start while cf is installing")
+
+ monkeypatch.setattr(cf_handlers, "cf_cli_path", lambda: None)
+ monkeypatch.setattr(cf_handlers, "ensure_cf_cli", slow_install)
+ monkeypatch.setattr(cf_handlers, "_spawn_login", boom)
+ monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+
+ first = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert first["success"] is True and first.get("pending") is True
+ second = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert second.get("pending") is True
+ # one install, however often Login is clicked
+ assert installs == [1]
+ release.set()
+ await _until(lambda: cf_handlers._active_login["install"].done())
+
+
+async def test_login_answers_within_budget_when_flow_stalls(monkeypatch, tmp_path):
+ _reset_login_state(monkeypatch)
+ _installed_cli(monkeypatch, tmp_path)
+
+ async def stalled_flow():
+ await asyncio.sleep(30)
+ return {"success": True, "message": "done"}
+
+ monkeypatch.setattr(cf_handlers, "_start_login_flow", stalled_flow)
+ monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+ res = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert res["success"] is True
+ assert res.get("pending") is True
+ cf_handlers._active_login["task"].cancel()
+
+
+async def test_login_is_single_flight(monkeypatch, tmp_path):
+ # A repeat click while a flow is starting must not spawn again.
+ _reset_login_state(monkeypatch)
+ _installed_cli(monkeypatch, tmp_path)
started = asyncio.Event()
release = asyncio.Event()
@@ -561,30 +1009,19 @@ async def test_login_is_single_flight(monkeypatch):
second = await cf_handlers.handle_cloudflare_login({}, websocket=None)
assert second["success"] is True
assert second.get("pending") is True
- assert "already in progress" in second["message"].lower()
+ assert "already starting" in second["message"].lower()
release.set()
-def test_login_flow_short_circuits_when_already_logged_in():
- # A live session (terminal login, or a flow that completed after the
- # modal closed) marks + returns immediately instead of spawning.
- src = inspect.getsource(cf_handlers._start_login_flow)
- assert "whoami_snapshot" in src
- assert "Already logged in" in src
- # ...and the spawn (only reached without a session) forces past a
- # stale/invalid stored token instead of short-circuiting on it.
- assert "--force" in cf_handlers._LOGIN_ARGS
-
-
-def test_completion_never_kills_the_login_process():
+def test_login_never_kills_the_cf_process():
# The installed binary is a bun bin shim on Windows (a launcher .exe
# that runs the CLI in a child bun process): killing it orphans that
- # child, which keeps holding callback port 8877 and breaks every
- # later login. cf enforces its own login timeout.
- src = inspect.getsource(cf_handlers._complete_login)
- assert ".kill(" not in src
- assert ".terminate(" not in src
+ # child. cf ends the device flow by itself.
+ for fn in (cf_handlers._complete_login, cf_handlers._start_login_flow, cf_handlers._read_login_banner):
+ src = inspect.getsource(fn)
+ assert ".kill(" not in src
+ assert ".terminate(" not in src
# --- marker-token + broadcast contract (source introspection) -------------------
@@ -616,9 +1053,10 @@ def test_logout_removes_marker_and_broadcasts():
def test_login_uses_stripped_env():
# login/status/logout must consult cf's OWN store, never env tokens
# — and the stored API token must never be injected there either.
- for fn in (cf_handlers._start_login_flow, cf_handlers.handle_cloudflare_logout):
+ for fn in (cf_handlers._spawn_login, cf_handlers.handle_cloudflare_logout):
src = inspect.getsource(fn)
assert "login_env" in src
+ assert "cf_workdir" in src
assert "stored_token" not in src
assert "login_env" in inspect.getsource(cf_service.whoami_snapshot)
@@ -686,10 +1124,10 @@ async def test_credential_resolve_returns_optional_credential_rows(monkeypatch):
monkeypatch.setattr(
plugin_deps,
"get_auth_service",
- lambda: _Auth({"cloudflare": "cfk_" + "y" * 48, "cloudflare_email": "[email protected]"}),
+ lambda: _Auth({"cloudflare": GLOBAL_KEY, "cloudflare_email": "[email protected]"}),
)
assert await CloudflareCredential.resolve() == {
- "cloudflare_api_token": "cfk_" + "y" * 48,
+ "cloudflare_api_token": GLOBAL_KEY,
"cloudflare_email": "[email protected]",
}
@@ -762,7 +1200,7 @@ async def test_probe_global_key_without_email_gives_guidance(monkeypatch):
monkeypatch.setattr(cf_credentials, "stored_email", no_email)
monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Boom)
- result = await CloudflareCredential._probe("cfk_" + "y" * 48)
+ result = await CloudflareCredential._probe(GLOBAL_KEY)
assert result.valid is False
assert "Account Email" in result.message
@@ -805,12 +1243,11 @@ async def test_probe_validates_global_key_with_email(monkeypatch):
monkeypatch.setattr(cf_credentials, "stored_email", has_email)
monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Client)
- key = "cfk_" + "y" * 48
- result = await CloudflareCredential._probe(key)
+ result = await CloudflareCredential._probe(GLOBAL_KEY)
assert result.valid is True
assert "[email protected]" in result.message
assert captured["url"] == "https://api.cloudflare.com/client/v4/user"
- assert captured["headers"] == {"X-Auth-Email": "[email protected]", "X-Auth-Key": key}
+ assert captured["headers"] == {"X-Auth-Email": "[email protected]", "X-Auth-Key": GLOBAL_KEY}
async def test_probe_verifies_account_tokens_via_accounts_read(monkeypatch):