Skip to content

Self-improving AI Employees for everyone

fix(cloudflare): CLI-owned login, API-token dual-path, GraphQL analytics

trohitg55d727a1de27
diff --git a/CLAUDE.md b/CLAUDE.md
index 69e59aa8..44690d97 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -30,6 +30,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). 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). npm install into the shared packages tree (pinned version). 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 the npm `.cmd` wrapper orphans the node child 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 npm install into the shared packages tree, system cf never consulted (preview argv surface drifts across versions). Palette group `deployment`. |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, 21.5 s cold post-`company clean` — was 71 s before the 2026-07-14 boot-delay fixes; first WS connect 8.29 s) + warm and cold per-phase timelines + optimisation history (lazy LangChain imports, lazy LLM-SDK exception refs, esbuild sidecar bundle, bytecode-at-build, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`, Vite dep-cache preservation, off-loop Temporal build-id hash) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce (incl. eager SDK import at LLM provider registration, unconditional `.vite` wipe, synchronous `Worker()` on the event loop). Pairs with the build-time pipeline doc below. |
| **[Release Build Pipeline](./docs-internal/release_build_pipeline.md)** | npm-distribution build pipeline: `tsgo` for type-check (5× faster than tsc), Vite `manualChunks` + `target: 'es2022'`, esbuild Node.js sidecar bundle (drops `tsx` interpreter cost), bytecode pre-compile in two halves — `[tool.uv] compile-bytecode = true` (uv sync compiles `.venv/` site-packages) + `python -m compileall` for project source (plain `.pyc`, **no `-O`** — per PEP 488 the non-`-O` runtimes never load `.opt-1.pyc`; excludes `.venv/`, `tests/`). Single source of truth for the bytecode-compile path list: `cli.commands.build.COMPILEALL_SOURCE_DIRS`. |
@@ -495,7 +496,7 @@ class CacheEntry(SQLModel, table=True):
## Codebase Summary
- **Hybrid architecture**: Python (FastAPI + Pydantic plugins) + React/TypeScript frontend + Node.js subprocess for JS/TS code execution.
-- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe / vercel / github.
+- **Backend NodeSpec is the single source of truth.** Plugins live in [`server/nodes/<group>/<name>.py`](./server/nodes/) and auto-register via `BaseNode.__init_subclass__`. Authoritative node count is whatever globs out of `server/nodes/**/*.py` (excluding `_*.py` helpers and `__init__.py`); folders cover agent / model / android / google / whatsapp / twitter / telegram / social / email / search / scraper / document / code / filesystem / proxy / location / chat / text / scheduler / trigger / tool / utility / workflow / skill / browser / stripe / vercel / github / cloudflare.
- **WebSocket-first frontend-backend communication.** Authoritative handler count is the size of the `MESSAGE_HANDLERS` dict in [`server/routers/websocket.py`](./server/routers/websocket.py) plus plugin-registered handlers via `services.ws_handler_registry`. Don't hand-maintain the count in this doc — it drifts on every plugin add.
- **Plugin-first architecture (Wave 11).** One file = one node. `services/handlers/` shrank from 12.8K → 1.1K LOC across 16 → 4 files. Live invariant total via `pytest --collect-only`.
@@ -618,7 +619,7 @@ The project uses WebSocket as the primary communication method between frontend
> The authoritative, per-node reference is the backend plugin registry plus the per-node "logic-flow" cards under [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) (one card per node, grouped by category, with handles / params / outputs / side-effects / edge-cases). Live node list = the plugin registry (one folder per node under `server/nodes/<group>/`, ~118 node types today; a bare `__init__.py` glob also counts the 26 group packages); live total via `pytest --collect-only`. Do NOT maintain a per-node catalogue here — it drifts on every plugin add.
-Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe, vercel, github (palette group `vcs`). See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
+Node groups (palette categories): agent, model, skill, tool, trigger, workflow, search, google, android, whatsapp, telegram, twitter, social, email, proxy, chat, scheduler, text, code, document, location, utility, browser, scraper, filesystem, stripe, vercel, github (palette group `vcs`), cloudflare (palette group `deployment`). See [docs-internal/node-logic-flows/](./docs-internal/node-logic-flows/) for the card index.
## Backend Services
diff --git a/docs-internal/cloudflare_service.md b/docs-internal/cloudflare_service.md
new file mode 100644
index 00000000..8bddc1ab
--- /dev/null
+++ b/docs-internal/cloudflare_service.md
@@ -0,0 +1,194 @@
+# 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.
+
+| | |
+|---|---|
+| 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`), npm-installed into the shared `packages_dir()` tree, Node >= 22 |
+| Auth | Dual-path: cf-owned OAuth login OR optional `cloudflare_api_token` field -> `CLOUDFLARE_API_TOKEN` env |
+| 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) (35 contract tests) |
+| Paired skill | [`server/skills/cloudflare/cloudflare-skill/SKILL.md`](../server/skills/cloudflare/cloudflare-skill/SKILL.md) |
+
+## Folder map
+
+```
+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 npm install, system cf NEVER consulted
+├── _service.py # cf_env(token) / login_env() / whoami_snapshot() / stored_token()
+└── 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).
+
+## Install — pinned, never the system PATH
+
+`_install.py` uses vercel's npm **mechanism** (install into the shared
+`packages_dir()` tree, `.bin` shim, `asyncio.to_thread`, double-checked
+lock) 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 an npm `.cmd`
+ shim; killing it terminates only the cmd.exe wrapper and orphans the
+ node child, 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 path is an **API token** with the matching
+permission groups, and cf documents the env token as its
+**first-priority credential source** ("1. `CLOUDFLARE_API_TOKEN`
+environment variable, 2. cf OAuth token"). Hence the dual-path:
+
+- Optional `cloudflare_api_token` field in the credentials modal
+ (`required: false` — Login gates on required fields only, the
+ OAuthConnect invariant). Injected by `cf_env(token)` as
+ `CLOUDFLARE_API_TOKEN` on **every op**; the stored token beats an
+ ambient server-env token (explicit user config wins).
+- `CloudflareCredential.resolve()` returns the token row so other
+ surfaces can consume it.
+- Permissions for analytics: **Account > Account Analytics > Read**
+ (covers RUM datasets + `rum/site_info` reads) plus
+ **Zone > Analytics > Read** for zone-scoped queries. Account-owned
+ tokens are Cloudflare's recommendation for automation.
+
+## `graphql_query` — the GraphQL Analytics API
+
+The legacy Zone Analytics REST API was deprecated (2021-03-01 in the
+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; without one the op raises `NodeUserError`
+ with the permission-group guidance. 401/403 map to the same fix
+ message. 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`
+ / `rumPerformanceEventsAdaptiveGroups` /
+ `rumWebVitalsEventsAdaptiveGroups` (under `viewer.accounts`), DNS
+ `dnsAnalyticsAdaptive(Groups)` (both scopes).
+- 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 the token
+
+| Surface | OAuth login | API token |
+|---|---|---|
+| zones / DNS records / accounts / registrar | yes | yes |
+| `cf dns analytics` (REST, dies 2026-12-01) | yes (`dns_analytics:read`) | yes |
+| `graphql_query` (zone traffic, RUM, DNS analytics) | **no — no scope exists** | yes (`Account Analytics: Read` / `Zone Analytics: Read`) |
+| `rum/site_info` config endpoints (no cf command yet; `custom`/httpRequest) | **no** | yes |
+
+## 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; GraphQL endpoint constant + official body
+shape + 403 permission guidance; folder assets (no `icon.svg`,
+`#F38020`, both visuals entries, paired skill).
diff --git a/docs-internal/node_creation.md b/docs-internal/node_creation.md
index 77799fb9..3d0d4047 100644
--- a/docs-internal/node_creation.md
+++ b/docs-internal/node_creation.md
@@ -186,6 +186,24 @@ platforms. The installer is `npm install <pkg> --prefix
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 the npm `.cmd` shim orphans the node child 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:
+[`server/nodes/cloudflare/`](../server/nodes/cloudflare/) +
+[cloudflare_service.md](./cloudflare_service.md).
+
## What auto-wires (don't write it yourself)
When a plugin file is imported (which the `nodes/__init__.py`
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.json
index a0663c79..e18b3ec6 100644
--- a/server/config/credential_providers.json
+++ b/server/config/credential_providers.json
@@ -560,7 +560,18 @@
"logout": "cloudflare_logout",
"status": "cloudflare_status"
},
- "instructions": "Click 'Login with Cloudflare' — the cf CLI (auto-installed via npm) opens the Cloudflare dashboard OAuth page and completes via a localhost callback, so the browser must run on this machine. The token is stored by cf in its own user-level config; OpenCompany never keeps it. Alternatives: run 'cf auth login' in a terminal, or set CLOUDFLARE_API_TOKEN in the server environment for headless use (dash.cloudflare.com/profile/api-tokens)."
+ "fields": [
+ {
+ "key": "cloudflare_api_token",
+ "label": "API Token (optional)",
+ "type": "password",
+ "secret": true,
+ "placeholder": "Create at dash.cloudflare.com/profile/api-tokens",
+ "required": false,
+ "help": "Used as CLOUDFLARE_API_TOKEN on every CLI call and takes precedence over CLI login. 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, create a token with 'Account > Account Analytics > Read' (plus 'Zone > Analytics > Read' for zone-scoped queries). The Login button works without it."
+ }
+ ],
+ "instructions": "Two independent auth paths: click 'Login with Cloudflare' — the cf CLI (auto-installed via npm) 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."
}
}
}
diff --git a/server/nodes/README.md b/server/nodes/README.md
index e759bda1..00511448 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -128,6 +128,7 @@ browser/ — browser (agent-browser CLI)
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")
```
---
diff --git a/server/nodes/cloudflare/_credentials.py b/server/nodes/cloudflare/_credentials.py
index d22ab7e4..ccc77a5d 100644
--- a/server/nodes/cloudflare/_credentials.py
+++ b/server/nodes/cloudflare/_credentials.py
@@ -1,12 +1,20 @@
-"""Cloudflare credential — thin marker (Stripe idiom, github shape).
-
-The cf CLI manages its own auth state: ``cf auth login`` (driven by the
-modal's Login button or run by the user in a terminal) stores the OAuth
-token in cf's user-level config (``auth.jsonc``, or the OS keyring when
-``CLOUDFLARE_AUTH_USE_KEYRING`` is set) and ``cf auth logout`` revokes
-it. OpenCompany stores no token — the credentials modal's connected
-badge is driven by the synthetic ``cli-managed`` marker OAuth row
-written by ``_handlers.py`` after a successful login.
+"""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).
+* **API token** — the optional ``cloudflare_api_token`` api-key row,
+ 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).
"""
from __future__ import annotations
@@ -25,7 +33,9 @@ class CloudflareCredential(Credential):
@classmethod
async def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:
- """Nothing to resolve — auth lives in the cf CLI's own config
- (or an ambient ``CLOUDFLARE_API_TOKEN`` env var, per cf's own
- documented precedence)."""
- return {}
+ """Return the optional API token. There is no api_key for the
+ CLI-login path — that state lives in cf's own config."""
+ from services.plugin.deps import get_auth_service
+
+ token = await get_auth_service().get_api_key("cloudflare_api_token")
+ return {"cloudflare_api_token": token} if token else {}
diff --git a/server/nodes/cloudflare/_handlers.py b/server/nodes/cloudflare/_handlers.py
index 85d4dea0..7013f094 100644
--- a/server/nodes/cloudflare/_handlers.py
+++ b/server/nodes/cloudflare/_handlers.py
@@ -1,35 +1,41 @@
"""Cloudflare WebSocket handlers — the cf CLI owns its own auth (gh /
-Stripe CLI pattern).
-
-``cloudflare_login`` spawns cf's official browser login::
-
- cf auth login
-
-Source-verified behavior (cf 0.2.0 ``dist/auth-*.mjs`` + live headless
-capture): the flow runs a PKCE OAuth against
-``dash.cloudflare.com/oauth2/auth`` with a loopback callback server on
-``localhost:8877``, self-opens the browser, and prints to **stderr**
-(status stream; stdout is reserved for JSON)::
-
- Attempting to login via OAuth...
- Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?...
-
-(or ``Visit this link to authenticate: <url>`` when it can't open a
-browser). There is NO device code — the loopback callback completes the
-flow, so the handler returns ``{success, url}`` only and the modal just
-opens the url. Success gate: ``cf auth whoami`` reporting
-``authenticated: true`` (cf exits 0 in both states, so exit codes are
-never trusted). On success we write the synthetic ``cli-managed``
-marker OAuth row (flips the catalogue's ``stored`` badge, with the
-whoami email as the account label) and broadcast the generic
-catalogue-invalidation event. Marker + broadcast plumbing is the shared
-:mod:`services.cli_agent._cli_auth` module (claude/codex/github all use
-it).
-
-cf delta vs gh: when a session already exists, ``cf auth login``
-(without ``--force``) exits without printing an authorize URL — the
-handler detects the early exit, confirms via whoami, and reports
-success immediately.
+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.
+
+Success gate: ``cf auth whoami`` reporting ``authenticated: true`` (cf
+exits 0 in both auth states, so exit codes are never trusted). On
+success we write the synthetic ``cli-managed`` marker OAuth row (flips
+the catalogue's ``stored`` badge, with the whoami email as the account
+label) and broadcast the generic catalogue-invalidation event. Marker +
+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).
@@ -47,25 +53,32 @@ from services.cli_agent._cli_auth import broadcast_credential_event, mark_logged
from services.events import run_cli_command
from ._install import ensure_cf_cli
-from ._service import extract_login_url, login_env, whoami_snapshot
+from ._service import login_env, whoami_snapshot
logger = get_logger(__name__)
-_LOGIN_ARGS = ["auth", "login"]
+# --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"]
_LOGIN_TIMEOUT_SECONDS = 600
-# How long to wait for the authorize URL on the CLI's output before
-# giving up on this attempt.
-_BANNER_DEADLINE_SECONDS = 20
# The frontend drops WS requests after 30s. A first-ever login pays a
# cold npm install inside this handler — answer within this budget no
# matter what and let the flow continue in the background.
_RESPONSE_BUDGET_SECONDS = 22
+# Retained head of the CLI's output, used only for the failure log line.
+_OUTPUT_CAP_BYTES = 8192
# 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)
@@ -74,60 +87,25 @@ def _spawn_background(coro) -> asyncio.Task:
return task
-async def _read_login_banner(proc: asyncio.subprocess.Process) -> tuple[Optional[str], List[str]]:
- """Read the login process's early output until the authorize URL
- shows up (or deadline / EOF). Chunk-based, not ``readline()`` —
- spinner frames repaint via ``\\r`` with no newline. The pumps
- deliberately OUTLIVE this function: they keep draining both pipes
- for the process lifetime so cf never blocks on a full pipe buffer
- while its callback server waits (~10 min); only the first 32 KiB is
- retained for parsing."""
- buf: List[str] = []
- buf_len = 0
- new_data = asyncio.Event()
-
- async def pump(stream: Optional[asyncio.StreamReader]) -> None:
- nonlocal buf_len
- if stream is None:
- new_data.set()
- return
- while True:
- chunk = await stream.read(4096)
- if not chunk:
- break
- if buf_len < 32768:
- text = chunk.decode(errors="replace")
- buf.append(text)
- buf_len += len(text)
- new_data.set()
- new_data.set()
-
- pumps = [_spawn_background(pump(proc.stdout)), _spawn_background(pump(proc.stderr))]
-
- url: Optional[str] = None
- loop = asyncio.get_running_loop()
- deadline = loop.time() + _BANNER_DEADLINE_SECONDS
- while True:
- url = extract_login_url("".join(buf))
- if url is not None or all(t.done() for t in pumps):
- break
- remaining = deadline - loop.time()
- if remaining <= 0:
- break
- new_data.clear()
- try:
- await asyncio.wait_for(new_data.wait(), timeout=remaining)
- except asyncio.TimeoutError:
- break
+def _login_in_progress() -> bool:
+ task = _active_login["task"]
+ if task is not None and not task.done():
+ return True
+ proc = _active_login["proc"]
+ return proc is not None and proc.returncode is None
- tail = [ln.strip() for ln in "".join(buf).splitlines() if ln.strip()]
- return url, tail
+
+async def _mark_connected(email: Optional[str]) -> None:
+ await mark_logged_in("cloudflare", email=email)
+ logger.info("[Cloudflare] connected as %s — catalogue marker persisted", email or "<unknown>")
+ await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")
async def _start_login_flow() -> Dict[str, Any]:
- """Install (if needed) + spawn cf's browser login + parse the
- banner + schedule completion. Never raises — returns the WS
- response dict."""
+ """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."""
try:
try:
binary = str(await ensure_cf_cli())
@@ -138,6 +116,14 @@ async def _start_login_flow() -> Dict[str, Any]:
"error": f"cf CLI install failed ({e}). Manual install: npm i -g cf",
}
+ # Fast path: a live session already exists (user logged in via a
+ # terminal, or a previous flow completed after the modal closed).
+ info = await whoami_snapshot()
+ if info:
+ email = info.get("email")
+ 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.
@@ -149,47 +135,61 @@ async def _start_login_flow() -> Dict[str, Any]:
stderr=asyncio.subprocess.PIPE,
env=login_env(),
)
-
- url, lines = await _read_login_banner(proc)
- if url is None:
- # cf delta: with a live session, `cf auth login` exits
- # without printing an authorize URL — confirm via whoami
- # and mark immediately instead of treating it as a failure.
- if proc.returncode is not None:
- info = await whoami_snapshot()
- if info:
- email = info.get("email")
- await mark_logged_in("cloudflare", email=email)
- await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")
- logger.info("[Cloudflare] already logged in as %s — marker refreshed", email or "<unknown>")
- return {"success": True, "message": f"Already logged in{f' as {email}' if email else ''}."}
- proc.kill()
- banner = " | ".join(lines[-5:]) or "(no output)"
- logger.warning("[Cloudflare] login banner had no authorize URL within %ss: %s", _BANNER_DEADLINE_SECONDS, banner)
- return {
- "success": False,
- "error": (
- f"Could not start cf's browser login. CLI said: {banner} — "
- "you can also run 'cf auth login' in a terminal on this machine."
- ),
- }
+ _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.
+ 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))
+ _spawn_background(_complete_login(proc, output))
logger.info(
- "[Cloudflare] OAuth authorize URL issued — opening on frontend; awaiting loopback callback in background (timeout=%ss)",
+ "[Cloudflare] cf auth login spawned (pid=%s) — cf opens the browser itself; awaiting completion in background (timeout=%ss)",
+ proc.pid,
_LOGIN_TIMEOUT_SECONDS,
)
- _spawn_background(_complete_login(proc))
- return {"success": True, "url": url}
+ return {
+ "success": True,
+ "message": "cf is opening your default browser — complete the Cloudflare login there.",
+ }
except Exception as e:
logger.exception("[Cloudflare] login flow raised unexpectedly: %s", e)
return {"success": False, "error": f"Cloudflare login failed: {e}"}
async def handle_cloudflare_login(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
- """Answer within the frontend's request window no matter what
- (vercel's cold-install pending pattern)."""
+ """Single-flight + answer within the frontend's request window no
+ matter what (vercel's cold-install pending pattern)."""
+ 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)")
flow = _spawn_background(_start_login_flow())
+ _active_login["task"] = flow
try:
return await asyncio.wait_for(asyncio.shield(flow), timeout=_RESPONSE_BUDGET_SECONDS)
except asyncio.TimeoutError:
@@ -200,37 +200,47 @@ async def handle_cloudflare_login(data: Dict[str, Any], websocket: WebSocket) ->
return {
"success": True,
"pending": True,
- "message": "cf CLI is being installed — click Login again in a few seconds.",
+ "message": "cf CLI is being installed — the browser will open automatically when it is ready.",
}
-async def _complete_login(proc: asyncio.subprocess.Process) -> None:
+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."""
+ 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.
+ """
try:
try:
returncode = await asyncio.wait_for(proc.wait(), timeout=_LOGIN_TIMEOUT_SECONDS)
except asyncio.TimeoutError:
- proc.kill()
- logger.warning("[Cloudflare] login timed out after %ss — user never completed the browser flow", _LOGIN_TIMEOUT_SECONDS)
+ logger.warning(
+ "[Cloudflare] login still running after %ss — leaving it to cf's own timeout (killing the shim would orphan the callback server)",
+ _LOGIN_TIMEOUT_SECONDS,
+ )
return
- except Exception as e:
- logger.exception("[Cloudflare] login wait raised unexpectedly: %s", e)
- return
- info = await whoami_snapshot()
- if not info:
- logger.warning(
- "[Cloudflare] login exited (code=%s) but 'cf auth whoami' reports no session — user likely closed the browser before authorising",
- returncode,
- )
- 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",
+ returncode,
+ banner,
+ )
+ return
- email = info.get("email")
- await mark_logged_in("cloudflare", email=email)
- logger.info("[Cloudflare] connected as %s — catalogue marker persisted", email or "<unknown>")
- await broadcast_credential_event("credential.oauth.connected", provider="cloudflare")
+ await _mark_connected(info.get("email"))
+ except Exception as e:
+ logger.exception("[Cloudflare] login completion raised unexpectedly: %s", e)
+ finally:
+ if _active_login["proc"] is proc:
+ _active_login["proc"] = None
async def handle_cloudflare_logout(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
diff --git a/server/nodes/cloudflare/_service.py b/server/nodes/cloudflare/_service.py
index 55882f2b..f1de2413 100644
--- a/server/nodes/cloudflare/_service.py
+++ b/server/nodes/cloudflare/_service.py
@@ -1,14 +1,15 @@
-"""Shared Cloudflare plugin helpers — subprocess env builders, cf
-session probe, login-output parsing.
+"""Shared Cloudflare plugin helpers — subprocess env builders and the
+cf session probe.
-Auth model — **the cf CLI owns its own auth** (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
+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``; 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
+``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
@@ -20,9 +21,17 @@ be stripped for ``cf auth login`` / ``whoami`` / ``logout`` (see
from __future__ import annotations
import os
-import re
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.
+TOKEN_KEY = "cloudflare_api_token"
+
# 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.
@@ -36,16 +45,28 @@ _AMBIENT_CREDENTIAL_VARS = (
)
-def cf_env() -> Dict[str, str]:
- """Child env for cf op invocations. No token handling: cf reads its
- own config (or an ambient env token, per its own documented
- precedence). ``NO_COLOR`` keeps the chalk-based status output free
- of ANSI codes."""
+def cf_env(token: Optional[str] = None) -> Dict[str, str]:
+ """Child env for cf op invocations. ``token`` (the stored optional
+ API token) is injected as ``CLOUDFLARE_API_TOKEN`` and takes
+ precedence over both the OAuth session (cf's own documented
+ resolution order) and any ambient server env token (explicit user
+ config beats environment). Without a token, cf reads its own config
+ or an ambient env token. ``NO_COLOR`` keeps the chalk-based status
+ output free of ANSI codes."""
env = os.environ.copy()
env["NO_COLOR"] = "1"
+ if token:
+ env["CLOUDFLARE_API_TOKEN"] = token
return env
+async def stored_token() -> Optional[str]:
+ """The user's optional API token from the credentials DB."""
+ from services.plugin.deps import get_auth_service
+
+ return await get_auth_service().get_api_key(TOKEN_KEY)
+
+
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
@@ -93,24 +114,3 @@ async def whoami_snapshot() -> Optional[Dict[str, Any]]:
if info.get("tokenValid") is False:
return None
return info
-
-
-# --- Login-output parsing ----------------------------------------------------
-
-_ANSI_RE = re.compile(r"\x1b\[[0-9;?]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
-# cf 0.2.0 prints the authorize URL on stderr (source-verified, both
-# variants carry the same URL):
-# Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?...
-# Visit this link to authenticate: https://dash.cloudflare.com/oauth2/auth?...
-_URL_RE = re.compile(r"https://dash\.(?:staging\.)?cloudflare\.com/oauth2/auth\S+")
-
-
-def strip_ansi(text: str) -> str:
- return _ANSI_RE.sub("", text)
-
-
-def extract_login_url(text: str) -> Optional[str]:
- """The OAuth authorize URL from cf's login banner, or ``None``
- while still waiting for it."""
- m = _URL_RE.search(strip_ansi(text))
- return m.group(0).rstrip(".,;)'\"") if m else None
diff --git a/server/nodes/cloudflare/cloudflare_action.py b/server/nodes/cloudflare/cloudflare_action.py
index 459c6af2..5057c2f0 100644
--- a/server/nodes/cloudflare/cloudflare_action.py
+++ b/server/nodes/cloudflare/cloudflare_action.py
@@ -20,9 +20,11 @@ positional.
from __future__ import annotations
import json
+import os
import shlex
from typing import Any, Dict, List, Literal, Optional
+import httpx
from pydantic import BaseModel, ConfigDict, Field, field_validator
from services.events import run_cli_command
@@ -34,16 +36,27 @@ _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"]}}}
+_GRAPHQL = {"displayOptions": {"show": {"operation": ["graphql_query"]}}}
_CUSTOM = {"displayOptions": {"show": {"operation": ["custom"]}}}
_ONESHOT_TIMEOUT = 120.0
_CUSTOM_TIMEOUT = 300.0
+_GRAPHQL_TIMEOUT = 60.0
_STDERR_TAIL_CHARS = 2000
+# 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).
+# https://developers.cloudflare.com/analytics/graphql-api/
+_GRAPHQL_ENDPOINT = "https://api.cloudflare.com/client/v4/graphql"
+
class CloudflareActionParams(BaseModel):
operation: Literal[
- "whoami", "zones_list", "dns_records_list", "dns_record_create", "dns_record_delete", "custom"
+ "whoami", "zones_list", "dns_records_list", "dns_record_create", "dns_record_delete", "graphql_query", "custom"
] = "whoami"
# Shared zone target for the DNS operations (global -z/--zone flag).
@@ -83,6 +96,26 @@ class CloudflareActionParams(BaseModel):
json_schema_extra={"placeholder": "023e105f4ecef8ad9ca31a8372d0c353", **_DELETE},
)
+ # graphql_query
+ graphql_query: str = Field(
+ default="",
+ description="GraphQL Analytics API query (the replacement for the sunsetted Zone Analytics REST API)",
+ json_schema_extra={
+ "rows": 6,
+ "placeholder": 'query { viewer { zones(filter: {zoneTag: "..."}) { httpRequestsAdaptiveGroups(limit: 10, filter: {...}) { count } } } }',
+ **_GRAPHQL,
+ },
+ )
+ graphql_variables: str = Field(
+ default="",
+ description="Optional JSON object of GraphQL variables",
+ json_schema_extra={
+ "rows": 3,
+ "placeholder": '{"zoneTag": "023e105f4ecef8ad9ca31a8372d0c353"}',
+ **_GRAPHQL,
+ },
+ )
+
# custom
command: str = Field(
default="",
@@ -95,11 +128,11 @@ class CloudflareActionParams(BaseModel):
model_config = ConfigDict(extra="ignore")
- @field_validator("record_body", mode="before")
+ @field_validator("record_body", "graphql_variables", mode="before")
@classmethod
- def _coerce_record_body(cls, v: Any) -> Any:
- """LLM tool calls may pass the record as a real JSON object —
- coerce to the string the CLI flag expects (canonical
+ def _coerce_json_field(cls, v: Any) -> Any:
+ """LLM tool calls may pass these as real JSON objects — coerce
+ to the string the CLI flag / HTTP body expects (canonical
field_validator(mode="before") rule)."""
if isinstance(v, (dict, list)):
return json.dumps(v)
@@ -122,7 +155,7 @@ class CloudflareActionNode(ActionNode):
display_name = "Cloudflare"
subtitle = "cf CLI"
group = ("deployment", "tool")
- description = "Cloudflare via the official cf CLI — check auth, list zones, manage DNS records, or run any cf command"
+ description = "Cloudflare via the official cf CLI — auth, zones, DNS records, GraphQL analytics, or any cf command"
component_kind = "square"
tool_name = "cloudflare"
tool_description = (
@@ -130,12 +163,16 @@ class CloudflareActionNode(ActionNode):
"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), 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, 'schema <cmd>' for request shapes). "
- "DNS operations take 'zone' as a zone ID or domain name. Output is JSON. "
- "Auth is managed by the cf CLI itself — connect via Credentials -> Cloudflare (Login "
- "button) or run 'cf auth login' in a terminal; a CLOUDFLARE_API_TOKEN env var also works. "
+ "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"
)
handles = (
@@ -162,11 +199,12 @@ class CloudflareActionNode(ActionNode):
timeout: float = _ONESHOT_TIMEOUT,
) -> Dict[str, Any]:
"""No auth pre-flight (Stripe pattern) — cf authenticates from
- its own config (or an ambient env token), and its error
- (including "Not logged in") surfaces via the NodeUserError wrap
- below."""
+ the stored API token (injected as CLOUDFLARE_API_TOKEN, cf's
+ first-priority credential source), its own OAuth config, or an
+ ambient env token; its error (including "Not logged in")
+ surfaces via the NodeUserError wrap below."""
from ._install import ensure_cf_cli
- from ._service import cf_env
+ from ._service import cf_env, stored_token
try:
binary = str(await ensure_cf_cli())
@@ -177,7 +215,7 @@ class CloudflareActionNode(ActionNode):
binary=binary,
argv=argv,
timeout=timeout,
- env=cf_env(),
+ env=cf_env(await stored_token()),
)
if not result.get("success"):
stderr = (result.get("stderr") or "").strip()
@@ -277,6 +315,67 @@ class CloudflareActionNode(ActionNode):
result = await self._run(argv)
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)."""
+ query = params.graphql_query.strip()
+ if not query:
+ raise NodeUserError(
+ "graphql_query is required (e.g. query { viewer { zones(filter: {zoneTag: $zoneTag}) "
+ "{ httpRequestsAdaptiveGroups(limit: 10) { count } } } })"
+ )
+ variables: Dict[str, Any] = {}
+ if params.graphql_variables.strip():
+ try:
+ variables = json.loads(params.graphql_variables)
+ except ValueError as e:
+ raise NodeUserError(f"graphql_variables is not valid JSON: {e}") from e
+
+ from ._service import stored_token
+
+ token = await stored_token() or os.environ.get("CLOUDFLARE_API_TOKEN")
+ if not token:
+ raise NodeUserError(
+ "The GraphQL Analytics API needs an API token — the cf OAuth login carries no "
+ "analytics scopes. Create one at dash.cloudflare.com/profile/api-tokens with "
+ "'Account > Account Analytics > Read' and paste it in Credentials -> Cloudflare."
+ )
+
+ body = await self._graphql_post(token, {"query": query, "variables": variables})
+ return self._shape("graphql_query", {"result": body, "stdout": "", "stderr": ""})
+
+ @staticmethod
+ async def _graphql_post(token: str, payload: Dict[str, Any]) -> Dict[str, Any]:
+ """One POST to the official endpoint, exactly as documented
+ (Bearer token + {query, variables} body). 401/403 map to the
+ permission-group fix; hard GraphQL errors (no data) surface as
+ NodeUserError; partial data rides back in the body."""
+ async with httpx.AsyncClient(timeout=_GRAPHQL_TIMEOUT) as client:
+ resp = await client.post(
+ _GRAPHQL_ENDPOINT,
+ json=payload,
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ if resp.status_code in (401, 403):
+ raise NodeUserError(
+ f"GraphQL Analytics API rejected the token (HTTP {resp.status_code}). "
+ "The API token needs 'Account > Account Analytics > Read' (and 'Zone > Analytics > Read' "
+ "for zone-scoped queries) — edit it at dash.cloudflare.com/profile/api-tokens."
+ )
+ try:
+ body = resp.json()
+ except ValueError as e:
+ raise NodeUserError(f"GraphQL Analytics API returned non-JSON (HTTP {resp.status_code}): {resp.text[:300]}") from e
+ if resp.status_code >= 400 or (body.get("data") is None and body.get("errors")):
+ errors = body.get("errors") or [{"message": f"HTTP {resp.status_code}"}]
+ first = errors[0]
+ message = first.get("message") if isinstance(first, dict) else str(first)
+ raise NodeUserError(f"GraphQL query failed: {message}")
+ return body
+
@Operation("custom", cost={"service": "cloudflare", "action": "custom", "count": 1})
async def custom(self, ctx: NodeContext, params: CloudflareActionParams) -> Any:
cmd = params.command.strip()
diff --git a/server/skills/cloudflare/cloudflare-skill/SKILL.md b/server/skills/cloudflare/cloudflare-skill/SKILL.md
index 08df352b..15128adc 100644
--- a/server/skills/cloudflare/cloudflare-skill/SKILL.md
+++ b/server/skills/cloudflare/cloudflare-skill/SKILL.md
@@ -1,6 +1,6 @@
---
name: cloudflare-skill
-description: Work with Cloudflare via the official cf CLI — check auth identity, list zones, list/create/delete DNS records, and run any other cf command (accounts, registrar, per-product schemas). Output is parsed JSON.
+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.
allowed-tools: "cloudflare"
metadata:
author: opencompany
@@ -28,6 +28,7 @@ come back parsed in `result`.
| `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 ` |
### Response
@@ -72,6 +73,50 @@ To update a record, use `custom` with `--body`:
{ "operation": "custom", "command": "dns records update <record-id> --zone example.com --body '{\"content\":\"192.0.2.2\"}'" }
```
+## 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
+endpoint `api.cloudflare.com/client/v4/graphql`.
+
+**Requires the API token** from Credentials -> Cloudflare (the OAuth
+login has no analytics scopes): permission `Account > Account
+Analytics > Read`, plus `Zone > Analytics > Read` for zone-scoped
+queries.
+
+Zone HTTP traffic (official migration-guide query, current dataset):
+
+```json
+{
+ "operation": "graphql_query",
+ "graphql_query": "query Sample($zoneTag: string, $start: Time, $end: Time) { viewer { zones(filter: {zoneTag: $zoneTag}) { series: httpRequestsAdaptiveGroups(limit: 5, orderBy: [count_DESC], filter: {datetime_geq: $start, datetime_lt: $end, requestSource: \"eyeball\"}) { count avg { sampleInterval } sum { visits edgeResponseBytes } dimensions { coloCode } } } } }",
+ "graphql_variables": "{\"zoneTag\": \"<zone id>\", \"start\": \"2026-07-01T00:00:00Z\", \"end\": \"2026-07-15T00:00:00Z\"}"
+}
+```
+
+Web Analytics / RUM (account-scoped datasets:
+`rumPageloadEventsAdaptiveGroups`, `rumPerformanceEventsAdaptiveGroups`,
+`rumWebVitalsEventsAdaptiveGroups`):
+
+```json
+{
+ "operation": "graphql_query",
+ "graphql_query": "query Rum($accountTag: string, $start: Time, $end: Time) { viewer { accounts(filter: {accountTag: $accountTag}) { rumPageloadEventsAdaptiveGroups(limit: 100, orderBy: [count_DESC], filter: {datetime_geq: $start, datetime_lt: $end}) { count sum { visits } dimensions { requestPath } } } } }",
+ "graphql_variables": "{\"accountTag\": \"<account id>\", \"start\": \"2026-07-01T00:00:00Z\", \"end\": \"2026-07-15T00:00:00Z\"}"
+}
+```
+
+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
@@ -99,20 +144,24 @@ quotes: `custom: "dns records create --zone example.com --body '{\"type\":\"A\",
## Authentication
-The cf CLI owns its auth — OpenCompany never stores a token. Three
-equivalent ways to connect (any one is enough):
-
-1. **Credentials Modal → Cloudflare → Login with Cloudflare** — cf
- (auto-installed) opens the Cloudflare dashboard OAuth page and
- completes via a localhost callback (browser must be on the same
- machine as the server).
-2. **`cf auth login`** in a terminal on this machine.
-3. **`CLOUDFLARE_API_TOKEN`** set in the server environment
- (create at dash.cloudflare.com/profile/api-tokens) — cf's
- documented first-priority credential source; works headless.
-
-If a command fails with an authentication error, tell the user to
-connect via one of these; don't ask them for a token.
+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** — pasted in the credentials panel (or
+ `CLOUDFLARE_API_TOKEN` in the server env; the panel token takes
+ precedence). Create at dash.cloudflare.com/profile/api-tokens with
+ the permission groups the task needs — required for `graphql_query`
+ and anything else outside the OAuth scopes.
+
+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.
## Best practices
diff --git a/server/tests/test_cloudflare_plugin.py b/server/tests/test_cloudflare_plugin.py
index 5fa03639..6873ea6d 100644
--- a/server/tests/test_cloudflare_plugin.py
+++ b/server/tests/test_cloudflare_plugin.py
@@ -47,6 +47,14 @@ def test_cf_env_keeps_ambient_token_for_ops(monkeypatch):
assert env["CLOUDFLARE_API_TOKEN"] == "cf_ambient"
+def test_cf_env_stored_token_overrides_ambient(monkeypatch):
+ # Explicit user config (the credentials-modal token) beats the
+ # server environment.
+ monkeypatch.setenv("CLOUDFLARE_API_TOKEN", "cf_ambient")
+ env = cf_service.cf_env("cf_stored")
+ assert env["CLOUDFLARE_API_TOKEN"] == "cf_stored"
+
+
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
@@ -59,40 +67,6 @@ def test_login_env_strips_ambient_credential_vars(monkeypatch):
assert env["NO_COLOR"] == "1"
-# --- login banner parsing (source-verified cf 0.2.0 output) ---------------------
-
-
-def test_extract_login_url_from_browser_banner():
- # Live-captured cf 0.2.0 stderr shape.
- banner = (
- "Attempting to login via OAuth...\n"
- "Opening a link in your default browser: "
- "https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc&redirect_uri=http%3A%2F%2Flocalhost%3A8877%2Foauth%2Fcallback&scope=openid\n"
- )
- url = cf_service.extract_login_url(banner)
- assert url is not None
- assert url.startswith("https://dash.cloudflare.com/oauth2/auth?response_type=code")
- assert "8877" in url
-
-
-def test_extract_login_url_from_headless_banner():
- # The no-browser variant carries the same URL.
- banner = "Visit this link to authenticate: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc\n"
- assert cf_service.extract_login_url(banner) == (
- "https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=abc"
- )
-
-
-def test_extract_login_url_waits_until_url_present():
- assert cf_service.extract_login_url("Attempting to login via OAuth...\n") is None
- assert cf_service.extract_login_url("") is None
-
-
-def test_extract_login_url_strips_ansi():
- banner = "\x1b[36mOpening a link in your default browser:\x1b[0m https://dash.cloudflare.com/oauth2/auth?x=1\x1b[0m\n"
- assert cf_service.extract_login_url(banner) == "https://dash.cloudflare.com/oauth2/auth?x=1"
-
-
# --- _install resolution --------------------------------------------------------
@@ -147,8 +121,14 @@ def _wire(monkeypatch, tmp_path, run_impl):
async def fake_ensure():
return tmp_path / "cf"
+ async def no_stored_token():
+ return None
+
monkeypatch.setattr(cf_install, "ensure_cf_cli", fake_ensure)
monkeypatch.setattr(cf_action_mod, "run_cli_command", run_impl)
+ # ops resolve the optional modal token from the credentials DB —
+ # absent in unit tests, so stub the lookup to "no token stored".
+ monkeypatch.setattr(cf_service, "stored_token", no_stored_token)
def _ctx(tmp_path) -> NodeContext:
@@ -163,15 +143,38 @@ async def test_whoami_argv_and_env(monkeypatch, tmp_path):
return {"success": True, "result": {"authenticated": True, "email": "[email protected]"}, "stdout": "{}", "stderr": "", "error": None}
_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"))
assert captured["argv"] == ["auth", "whoami"]
- # env comes from cf_env() — no token was resolved or injected anywhere
+ # 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]"}
+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}
+
+ _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_zones_list_builds_filter_argv(monkeypatch, tmp_path):
captured = {}
@@ -310,6 +313,95 @@ async def test_custom_requires_command_and_shlex_splits(monkeypatch, tmp_path):
assert captured["timeout"] == cf_action_mod._CUSTOM_TIMEOUT
+async def test_graphql_requires_api_token(monkeypatch, tmp_path):
+ """The cf OAuth grant has no analytics scopes — graphql_query must
+ fail with the permission-group guidance, not a bare 403."""
+ _wire(monkeypatch, tmp_path, None)
+ monkeypatch.delenv("CLOUDFLARE_API_TOKEN", raising=False)
+ node = CloudflareActionNode()
+ with pytest.raises(NodeUserError, match="Account Analytics"):
+ await node.graphql_query(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="graphql_query", graphql_query="query { viewer { zones { __typename } } }"),
+ )
+
+
+async def test_graphql_posts_official_body_shape(monkeypatch, tmp_path):
+ _wire(monkeypatch, tmp_path, None)
+
+ async def fake_token():
+ return "cf_tok"
+
+ captured = {}
+
+ async def fake_post(token, payload):
+ captured["token"] = token
+ captured["payload"] = payload
+ return {"data": {"viewer": {"zones": []}}}
+
+ monkeypatch.setattr(cf_service, "stored_token", fake_token)
+ monkeypatch.setattr(CloudflareActionNode, "_graphql_post", staticmethod(fake_post))
+ node = CloudflareActionNode()
+
+ with pytest.raises(NodeUserError, match="graphql_query is required"):
+ await node.graphql_query(_ctx(tmp_path), CloudflareActionParams(operation="graphql_query"))
+
+ with pytest.raises(NodeUserError, match="not valid JSON"):
+ await node.graphql_query(
+ _ctx(tmp_path),
+ CloudflareActionParams(operation="graphql_query", graphql_query="query { viewer }", graphql_variables="{oops"),
+ )
+
+ out = await node.graphql_query(
+ _ctx(tmp_path),
+ CloudflareActionParams(
+ operation="graphql_query",
+ graphql_query="query Q($zoneTag: string) { viewer }",
+ graphql_variables='{"zoneTag": "z1"}',
+ ),
+ )
+ # The official request body shape: {query, variables}, Bearer token.
+ assert captured["token"] == "cf_tok"
+ assert captured["payload"] == {
+ "query": "query Q($zoneTag: string) { viewer }",
+ "variables": {"zoneTag": "z1"},
+ }
+ assert out["result"] == {"data": {"viewer": {"zones": []}}}
+
+
+async def test_graphql_post_maps_403_to_permission_guidance(monkeypatch):
+ class _Resp:
+ status_code = 403
+ text = "forbidden"
+
+ @staticmethod
+ def json():
+ return {"data": None, "errors": [{"message": "not authorized for that account"}]}
+
+ class _Client:
+ def __init__(self, **kwargs):
+ pass
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ return False
+
+ async def post(self, url, **kwargs):
+ assert url == cf_action_mod._GRAPHQL_ENDPOINT
+ assert kwargs["headers"]["Authorization"] == "Bearer tok"
+ return _Resp()
+
+ monkeypatch.setattr(cf_action_mod.httpx, "AsyncClient", _Client)
+ with pytest.raises(NodeUserError, match="Account Analytics"):
+ await CloudflareActionNode._graphql_post("tok", {"query": "q", "variables": {}})
+
+
+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}]
@@ -343,10 +435,16 @@ def test_node_has_no_auth_preflight():
# --- login handler --------------------------------------------------------------
+def _reset_login_state(monkeypatch):
+ monkeypatch.setattr(cf_handlers, "_active_login", {"task": None, "proc": None})
+
+
async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
+ _reset_login_state(monkeypatch)
+
async def stalled_flow():
await asyncio.sleep(30)
- return {"success": True, "url": "https://dash.cloudflare.com/oauth2/auth?x=1"}
+ return {"success": True, "message": "done"}
monkeypatch.setattr(cf_handlers, "_start_login_flow", stalled_flow)
monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
@@ -355,25 +453,75 @@ async def test_login_answers_within_budget_when_flow_stalls(monkeypatch):
assert res.get("pending") is True
-async def test_login_fast_path_returns_authorize_url(monkeypatch):
+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).
+ _reset_login_state(monkeypatch)
+
async def instant_flow():
- return {"success": True, "url": "https://dash.cloudflare.com/oauth2/auth?x=1"}
+ return {"success": True, "message": "cf is opening your default browser."}
monkeypatch.setattr(cf_handlers, "_start_login_flow", instant_flow)
res = await cf_handlers.handle_cloudflare_login({}, websocket=None)
assert res["success"] is True
- assert res["url"] == "https://dash.cloudflare.com/oauth2/auth?x=1"
- # cf's loopback flow has no device code — nothing to render in the modal.
+ assert "url" not in res
assert "verification_code" not in res
+ src = inspect.getsource(cf_handlers._start_login_flow)
+ assert '"url"' not in src
+
+
+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.
+ _reset_login_state(monkeypatch)
+
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def slow_flow():
+ started.set()
+ await release.wait()
+ return {"success": True, "message": "done"}
+
+ monkeypatch.setattr(cf_handlers, "_start_login_flow", slow_flow)
+ monkeypatch.setattr(cf_handlers, "_RESPONSE_BUDGET_SECONDS", 0.05)
+
+ first = await cf_handlers.handle_cloudflare_login({}, websocket=None)
+ assert first.get("pending") is True
+ await started.wait()
+
+ def boom():
+ raise AssertionError("second click must not spawn a second flow")
+ monkeypatch.setattr(cf_handlers, "_start_login_flow", boom)
+ 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()
-def test_login_flow_handles_already_logged_in_exit():
- # cf delta vs gh: with a live session, `cf auth login` exits without
- # printing an authorize URL — the flow must confirm via whoami and
- # succeed instead of reporting a failure.
+ 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():
+ # The installed binary is an npm .cmd shim on Windows: killing it
+ # orphans the node 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
# --- marker-token + broadcast contract (source introspection) -------------------
@@ -386,8 +534,10 @@ def test_login_success_gates_on_whoami_then_marks_and_broadcasts():
# exit code alone is never trusted — cf exits 0 logged-in AND logged-out;
# `cf auth whoami` JSON is the gate (and the account-label email source).
assert "whoami_snapshot" in complete
- assert 'mark_logged_in("cloudflare"' in complete
- assert "credential.oauth.connected" in complete
+ assert "_mark_connected" in complete
+ marked = inspect.getsource(cf_handlers._mark_connected)
+ assert 'mark_logged_in("cloudflare"' in marked
+ assert "credential.oauth.connected" in marked
snapshot = inspect.getsource(cf_service.whoami_snapshot)
assert '"auth", "whoami"' in snapshot
assert "authenticated" in snapshot
@@ -401,9 +551,12 @@ 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.
+ # 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):
- assert "login_env" in inspect.getsource(fn)
+ src = inspect.getsource(fn)
+ assert "login_env" in src
+ assert "stored_token" not in src
assert "login_env" in inspect.getsource(cf_service.whoami_snapshot)
@@ -414,7 +567,7 @@ def test_ws_handlers_registered():
# --- catalogue + assets ----------------------------------------------------------
-def test_catalogue_entry_is_fieldless_stripe_shape():
+def test_catalogue_entry_is_vercel_dual_path_shape():
config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
assert "deployment" in config["categories"]
cloudflare = config["providers"]["cloudflare"]
@@ -426,8 +579,16 @@ def test_catalogue_entry_is_fieldless_stripe_shape():
"logout": "cloudflare_logout",
"status": "cloudflare_status",
}
- # cf owns the token — the modal stores nothing (Stripe shape).
- assert "fields" not in cloudflare
+ # Dual-path (vercel shape): one OPTIONAL token field — required
+ # would gate the Login button (OAuthConnect counts required fields
+ # only), and the OAuth login must keep working without a token.
+ fields = cloudflare["fields"]
+ assert len(fields) == 1
+ token_field = fields[0]
+ assert token_field["key"] == "cloudflare_api_token"
+ assert token_field["required"] is False
+ assert token_field["secret"] is True
+ assert token_field["type"] == "password"
def test_credential_class_shape():
@@ -435,6 +596,24 @@ def test_credential_class_shape():
assert CloudflareCredential.auth == "custom"
+async def test_credential_resolve_returns_optional_token_row(monkeypatch):
+ from services.plugin import deps as plugin_deps
+
+ class _Auth:
+ def __init__(self, token):
+ self._token = token
+
+ async def get_api_key(self, key):
+ assert key == "cloudflare_api_token"
+ return self._token
+
+ monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth("tok"))
+ assert await CloudflareCredential.resolve() == {"cloudflare_api_token": "tok"}
+
+ monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth(None))
+ assert await CloudflareCredential.resolve() == {}
+
+
def test_plugin_folder_assets():
# Icon is the official lobehub brand glyph via visuals.json — a
# co-located icon.svg would silently override it.