Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(cloudflare): credential Validate button + Global API Key support
trohitg56c0b0214a24
diff --git a/client/src/components/credentials/panels/OAuthPanel.tsx b/client/src/components/credentials/panels/OAuthPanel.tsxindex 7ba2a38b..d53fb977 100644--- a/client/src/components/credentials/panels/OAuthPanel.tsx+++ b/client/src/components/credentials/panels/OAuthPanel.tsx@@ -38,6 +38,9 @@ const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ coconst snapshot = panel.form.getFieldsValue();panel.execute('save', async () => {for (const f of config.fields!) {+ // The canonical `apiKey` field is validate-managed (its+ // own ApiKeyInput; backend stores under the provider id).+ if (f.key === 'apiKey') continue;const v = snapshot[f.key]?.trim();if (v) await panel.actions.save(f.key, v);}@@ -45,6 +48,8 @@ const OAuthPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ coreturn { success: true };});}}+ onValidateApiKey={() => panel.actions.validate(config.id, (panel.form.getFieldValue('apiKey') ?? '').trim())}+ onDeleteApiKey={() => panel.actions.remove(config.id)}onLogin={() => panel.actions.oauthLogin()}onLogout={() => panel.actions.oauthLogout()}onRefresh={() => panel.actions.oauthRefresh()}diff --git a/client/src/components/credentials/primitives/OAuthConnect.tsx b/client/src/components/credentials/primitives/OAuthConnect.tsxindex b5d2fc9c..3e200dc0 100644--- a/client/src/components/credentials/primitives/OAuthConnect.tsx+++ b/client/src/components/credentials/primitives/OAuthConnect.tsx@@ -8,6 +8,7 @@ import React from 'react';import { Loader2, RotateCcw } from 'lucide-react';import { Alert, AlertDescription } from '@/components/ui/alert';import { ActionButton } from '@/components/ui/action-button';+import ApiKeyInput from '../../ui/ApiKeyInput';import FieldRenderer from './FieldRenderer';import ActionBar, { type ActionDef } from './ActionBar';import StatusCard from './StatusCard';@@ -30,6 +31,15 @@ interface Props {verificationCode?: string | null;icon: React.ReactNode;onSaveCredentials: () => void;+ /** Validate-and-store for the canonical `apiKey` field (dual-path+ * providers like Cloudflare: OAuth login OR a validated API token).+ * Same wiring as ApiKeyPanel's primary field — the backend+ * Credential's `_probe` owns all validation logic; the panel just+ * calls `panel.actions.validate(config.id, value)`. Rendered via the+ * shared ApiKeyInput component when the catalogue declares an+ * `apiKey` field. */+ onValidateApiKey?: () => void;+ onDeleteApiKey?: () => void;onLogin: () => void;onLogout: () => void;onRefresh: () => void;@@ -39,7 +49,7 @@ interface Props {const OAuthConnect: React.FC<Props> = ({config, form, connected, stored, loading, error, verificationCode, icon,- onSaveCredentials, onLogin, onLogout, onRefresh, extraSection,+ onSaveCredentials, onValidateApiKey, onDeleteApiKey, onLogin, onLogout, onRefresh, extraSection,}) => {// Some providers (e.g. Stripe) delegate auth entirely to an external// CLI tool — they have no OpenCompany-side credentials to paste, so@@ -64,17 +74,49 @@ const OAuthConnect: React.FC<Props> = ({const isSaving = loading === 'save';+ // The canonical `apiKey` field renders via the shared ApiKeyInput+ // (Validate button + Valid state + delete — same component every+ // api_key provider uses); remaining fields keep the generic+ // FieldRenderer + Save Credentials path.+ const apiKeyField = config.fields?.find((f) => f.key === 'apiKey');+ const otherFields = (config.fields ?? []).filter((f) => f.key !== 'apiKey');++ // Dual-path providers keep the token field reachable while+ // OAuth-connected (e.g. adding a Cloudflare analytics token after+ // logging in) — plain OAuth providers hide fields once connected.+ const showFields = !!config.fields && (!connected || !!apiKeyField);+return (<div className="flex min-h-0 flex-1 flex-col gap-4"><StatusCard icon={icon} title={config.name} rows={statusRows} status={null} />- {!connected && config.fields && (+ {showFields && config.fields && (<div className="flex w-full flex-col gap-3">- <FieldRenderer fields={config.fields} form={form} />- <ActionButton intent="secret" onClick={onSaveCredentials} disabled={isSaving}>- {isSaving && <Loader2 className="h-4 w-4 animate-spin" />}- Save Credentials- </ActionButton>+ {apiKeyField && onValidateApiKey && (+ <div className="flex flex-col gap-2">+ <ApiKeyInput+ value={form.getFieldValue('apiKey') ?? ''}+ onChange={(v) => form.setFieldValue('apiKey', v)}+ onSave={onValidateApiKey}+ onDelete={stored ? onDeleteApiKey : undefined}+ placeholder={apiKeyField.placeholder}+ loading={loading === 'validate'}+ isStored={stored}+ />+ {apiKeyField.help && (+ <p className="text-xs text-muted-foreground">{apiKeyField.help}</p>+ )}+ </div>+ )}+ {otherFields.length > 0 && (+ <>+ <FieldRenderer fields={otherFields} form={form} />+ <ActionButton intent="secret" onClick={onSaveCredentials} disabled={isSaving}>+ {isSaving && <Loader2 className="h-4 w-4 animate-spin" />}+ Save Credentials+ </ActionButton>+ </>+ )}{config.instructions && (<div className="text-xs leading-relaxed text-muted-foreground">{config.instructions}diff --git a/docs-internal/cloudflare_service.md b/docs-internal/cloudflare_service.mdindex 8bddc1ab..9a35556d 100644--- a/docs-internal/cloudflare_service.md+++ b/docs-internal/cloudflare_service.md@@ -109,22 +109,44 @@ documented `--scopes` list has none either), so `/accounts/{id}/rum/*`and the analytics datasets return **403 under any OAuth login** — thisis 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+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). 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.+ 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).+ - `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.## `graphql_query` — the GraphQL Analytics API@@ -139,10 +161,11 @@ directly: one POST with `{query, variables}` + `Bearer` token(`_graphql_post`, ~30 lines of repo-standard httpx; there is no moreofficial 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`.+- 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+ `NodeUserError`; partial data rides back in `result`.- Key datasets: zone traffic `httpRequestsAdaptiveGroups` (under`viewer.zones`), Web Analytics/RUM `rumPageloadEventsAdaptiveGroups`/ `rumPerformanceEventsAdaptiveGroups` /@@ -172,14 +195,15 @@ multi-object stdout that defeats `run_cli_command`'s single`json.loads`. No auth pre-flight (Stripe-strict): cf's own "Not loggedin" error surfaces via the `NodeUserError` wrap.-## What the OAuth login CAN do vs what needs the token+## What the OAuth login CAN do vs what needs a stored credential-| 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 |+| 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 |## Invariants locked by `test_cloudflare_plugin.py`@@ -189,6 +213,11 @@ 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-gatedcompletion 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).+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).diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex e18b3ec6..0176a0d3 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -562,13 +562,21 @@},"fields": [{- "key": "cloudflare_api_token",- "label": "API Token (optional)",+ "key": "apiKey",+ "label": "API Token or Global Key (optional)","type": "password","secret": true,- "placeholder": "Create at dash.cloudflare.com/profile/api-tokens",+ "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."+ },+ {+ "key": "cloudflare_email",+ "label": "Account Email (for Global Key)",+ "type": "text","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."+ "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."}],"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/cloudflare/_credentials.py b/server/nodes/cloudflare/_credentials.pyindex ccc77a5d..b3914224 100644--- a/server/nodes/cloudflare/_credentials.py+++ b/server/nodes/cloudflare/_credentials.py@@ -21,7 +21,19 @@ from __future__ import annotationsfrom typing import Any, Dict-from services.plugin.credential import Credential+import httpx++from services.plugin.credential import Credential, ProbeResult++from ._service import ACCOUNT_TOKEN_PREFIX, GLOBAL_KEY_PREFIX, stored_email++# Cloudflare's official token-validation endpoint ("Verify Token"):+# returns {"success": true, "result": {"id": ..., "status": "active"}}+# for a live user token.+# https://developers.cloudflare.com/fundamentals/api/how-to/verify-token/+_VERIFY_URL = "https://api.cloudflare.com/client/v4/user/tokens/verify"+_ACCOUNTS_URL = "https://api.cloudflare.com/client/v4/accounts"+_USER_URL = "https://api.cloudflare.com/client/v4/user"class CloudflareCredential(Credential):@@ -33,9 +45,70 @@ class CloudflareCredential(Credential):@classmethodasync def resolve(cls, *, user_id: str = "owner") -> Dict[str, Any]:- """Return the optional API token. There is no api_key for the- CLI-login path — that state lives in cf's own config."""+ """Return the optional credential rows: the ``apiKey`` field+ (an API token OR a cfk_ Global API Key, stored under the+ provider id) plus the companion account email. 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 {}+ auth = get_auth_service()+ secrets: Dict[str, Any] = {}+ token = await auth.get_api_key(cls.id)+ if token:+ secrets["cloudflare_api_token"] = token+ email = await stored_email()+ if email:+ secrets["cloudflare_email"] = email+ return secrets++ @classmethod+ async def _probe(cls, api_key: str) -> ProbeResult:+ """Validate the credential, routing by Cloudflare's documented+ prefix (Global API Key vs account token vs user token). The+ base ``Credential.validate`` scaffold does the rest (store+ under ``cls.id`` on success, broadcast, envelope); httpx errors+ propagate for its typed classification. Reads the stored+ companion email for cfk_ keys — a read, not a side effect."""+ if api_key.startswith(GLOBAL_KEY_PREFIX):+ email = await stored_email()+ if not email:+ return ProbeResult(+ valid=False,+ message=(+ "Global API Keys (cfk_...) authenticate with your account email — "+ "fill the Account Email field below, Save Credentials, then validate "+ "again. (Scoped API tokens from dash.cloudflare.com/profile/api-tokens "+ "work without it.)"+ ),+ )+ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.get(_USER_URL, headers={"X-Auth-Email": email, "X-Auth-Key": api_key})+ resp.raise_for_status()+ if resp.json().get("success"):+ return ProbeResult(valid=True, message=f"Global API Key is valid for {email}")+ return ProbeResult(valid=False, message="Cloudflare rejected the Global API Key + email pair")++ if api_key.startswith(ACCOUNT_TOKEN_PREFIX):+ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.get(+ _ACCOUNTS_URL,+ params={"per_page": 1},+ headers={"Authorization": f"Bearer {api_key}"},+ )+ resp.raise_for_status()+ if resp.json().get("success"):+ return ProbeResult(valid=True, message="Cloudflare account API token is valid")+ return ProbeResult(valid=False, message="Cloudflare rejected the account API token")++ async with httpx.AsyncClient(timeout=10.0) as client:+ resp = await client.get(_VERIFY_URL, headers={"Authorization": f"Bearer {api_key}"})+ resp.raise_for_status()+ body = resp.json()+ status = str((body.get("result") or {}).get("status") or "").lower()+ if body.get("success") and status == "active":+ return ProbeResult(valid=True, message="Cloudflare API token is valid and active")+ return ProbeResult(+ valid=False,+ message=f"Cloudflare reports the token as '{status or 'unknown'}' — check it at dash.cloudflare.com/profile/api-tokens",+ )diff --git a/server/nodes/cloudflare/_service.py b/server/nodes/cloudflare/_service.pyindex f1de2413..82429156 100644--- a/server/nodes/cloudflare/_service.py+++ b/server/nodes/cloudflare/_service.py@@ -30,7 +30,25 @@ from typing import Any, Dict, Optional# 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"+#+# Storage key is the PROVIDER ID, not a bespoke name: the catalogue+# field key is the canonical ``apiKey``, which the credentials panel+# maps to the provider id ("cloudflare") for storage, and the base+# ``Credential.validate`` scaffold stores under ``cls.id`` — one+# convention, zero storage-key overrides.+TOKEN_KEY = "cloudflare"+# Companion field for Global API Key auth (X-Auth-Email). Only needed+# when the stored credential is a cfk_ key; scoped tokens ignore it.+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,+# 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@@ -45,28 +63,65 @@ _AMBIENT_CREDENTIAL_VARS = ()-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."""+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."""env = os.environ.copy()env["NO_COLOR"] = "1"- if token:+ 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["CLOUDFLARE_API_TOKEN"] = tokenreturn env+def api_auth_headers(key: Optional[str], email: Optional[str]) -> Optional[Dict[str, str]]:+ """Auth headers for direct api.cloudflare.com calls (GraphQL,+ verify probes) — the two officially documented schemes: ``Bearer``+ for API tokens, the legacy ``X-Auth-Email``/``X-Auth-Key`` pair for+ Global API Keys. ``None`` when no usable credential (cfk_ without+ an email included)."""+ if key and key.startswith(GLOBAL_KEY_PREFIX):+ return {"X-Auth-Email": email, "X-Auth-Key": key} if email else None+ if key:+ return {"Authorization": f"Bearer {key}"}+ return None++async def stored_token() -> Optional[str]:- """The user's optional API token from the credentials DB."""+ """The user's optional API token or Global API Key from the+ credentials DB (the panel's ``apiKey`` field accepts either)."""from services.plugin.deps import get_auth_servicereturn await get_auth_service().get_api_key(TOKEN_KEY)+async def stored_email() -> Optional[str]:+ """The optional account email companion for Global API Key auth."""+ from services.plugin.deps import get_auth_service++ return await get_auth_service().get_api_key(EMAIL_KEY)++def login_env() -> Dict[str, str]:"""Env for ``cf auth login`` / ``cf auth whoami`` / ``cf authlogout`` — the CLI must consult its OWN stored session, so ambientdiff --git a/server/nodes/cloudflare/cloudflare_action.py b/server/nodes/cloudflare/cloudflare_action.pyindex 5057c2f0..36f54309 100644--- a/server/nodes/cloudflare/cloudflare_action.py+++ b/server/nodes/cloudflare/cloudflare_action.py@@ -199,12 +199,13 @@ class CloudflareActionNode(ActionNode):timeout: float = _ONESHOT_TIMEOUT,) -> Dict[str, Any]:"""No auth pre-flight (Stripe pattern) — cf authenticates from- 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."""+ 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."""from ._install import ensure_cf_cli- from ._service import cf_env, stored_token+ from ._service import cf_env, stored_email, stored_tokentry:binary = str(await ensure_cf_cli())@@ -215,7 +216,7 @@ class CloudflareActionNode(ActionNode):binary=binary,argv=argv,timeout=timeout,- env=cf_env(await stored_token()),+ env=cf_env(await stored_token(), await stored_email()),)if not result.get("success"):stderr = (result.get("stderr") or "").strip()@@ -334,36 +335,42 @@ class CloudflareActionNode(ActionNode):except ValueError as e:raise NodeUserError(f"graphql_variables is not valid JSON: {e}") from e- from ._service import stored_token+ from ._service import api_auth_headers, stored_email, stored_token- token = await stored_token() or os.environ.get("CLOUDFLARE_API_TOKEN")- if not token:+ key = await stored_token() or os.environ.get("CLOUDFLARE_API_TOKEN") or os.environ.get("CLOUDFLARE_API_KEY")+ email = await stored_email() or os.environ.get("CLOUDFLARE_EMAIL")+ headers = api_auth_headers(key, email)+ if headers is None: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."+ "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.")- body = await self._graphql_post(token, {"query": query, "variables": variables})+ body = await self._graphql_post(headers, {"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]:+ async def _graphql_post(headers: Dict[str, 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."""+ ({query, variables} body; auth headers from api_auth_headers —+ Bearer for tokens, X-Auth-Email/X-Auth-Key for Global API+ Keys). 401/403 map to the credential 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}"},+ headers=headers,)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."+ f"GraphQL Analytics API rejected the credential (HTTP {resp.status_code}). "+ "API tokens need 'Account > Account Analytics > Read' (and 'Zone > Analytics > Read' "+ "for zone-scoped queries) — edit at dash.cloudflare.com/profile/api-tokens. "+ "Global API Keys need the matching Account Email.")try:body = resp.json()diff --git a/server/skills/cloudflare/cloudflare-skill/SKILL.md b/server/skills/cloudflare/cloudflare-skill/SKILL.mdindex 15128adc..5080bf08 100644--- a/server/skills/cloudflare/cloudflare-skill/SKILL.md+++ b/server/skills/cloudflare/cloudflare-skill/SKILL.md@@ -153,11 +153,13 @@ resolution order):grant is a FIXED scope set: zones, DNS (incl. `dns_analytics:read`),accounts, registrar, Workers — but NO Web Analytics/RUM or zoneanalytics 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.+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 userwhich permission group the token needs; don't ask them to paste adiff --git a/server/tests/test_cloudflare_plugin.py b/server/tests/test_cloudflare_plugin.pyindex 6873ea6d..34a7a187 100644--- a/server/tests/test_cloudflare_plugin.py+++ b/server/tests/test_cloudflare_plugin.py@@ -55,6 +55,36 @@ 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]"+ 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+++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("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 envtoken (authSource: env) instead of the stored OAuth session — the@@ -121,14 +151,15 @@ def _wire(monkeypatch, tmp_path, run_impl):async def fake_ensure():return tmp_path / "cf"- async def no_stored_token():+ async def nothing_stored():return Nonemonkeypatch.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)+ # ops resolve the optional modal credential from the credentials DB+ # — 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)def _ctx(tmp_path) -> NodeContext:@@ -175,6 +206,33 @@ async def test_ops_inject_stored_api_token(monkeypatch, tmp_path):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 = {}++ async def fake_run(**kwargs):+ captured.update(kwargs)+ return {"success": True, "result": [], "stdout": "[]", "stderr": "", "error": None}++ _wire(monkeypatch, tmp_path, fake_run)+ key = "cfk_" + "y" * 48++ async def fake_token():+ return key++ async def fake_email():+ return "[email protected]"++ monkeypatch.setattr(cf_service, "stored_token", fake_token)+ monkeypatch.setattr(cf_service, "stored_email", fake_email)+ 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"]++async def test_zones_list_builds_filter_argv(monkeypatch, tmp_path):captured = {}@@ -313,11 +371,13 @@ 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):+async def test_graphql_requires_a_credential(monkeypatch, tmp_path):"""The cf OAuth grant has no analytics scopes — graphql_query must- fail with the permission-group guidance, not a bare 403."""+ fail with the credential guidance (token OR global key + email),+ not a bare 403."""_wire(monkeypatch, tmp_path, None)- monkeypatch.delenv("CLOUDFLARE_API_TOKEN", raising=False)+ 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(@@ -334,8 +394,8 @@ async def test_graphql_posts_official_body_shape(monkeypatch, tmp_path):captured = {}- async def fake_post(token, payload):- captured["token"] = token+ async def fake_post(headers, payload):+ captured["headers"] = headerscaptured["payload"] = payloadreturn {"data": {"viewer": {"zones": []}}}@@ -361,7 +421,7 @@ async def test_graphql_posts_official_body_shape(monkeypatch, tmp_path):),)# The official request body shape: {query, variables}, Bearer token.- assert captured["token"] == "cf_tok"+ assert captured["headers"] == {"Authorization": "Bearer cf_tok"}assert captured["payload"] == {"query": "query Q($zoneTag: string) { viewer }","variables": {"zoneTag": "z1"},@@ -395,7 +455,7 @@ async def test_graphql_post_maps_403_to_permission_guidance(monkeypatch):monkeypatch.setattr(cf_action_mod.httpx, "AsyncClient", _Client)with pytest.raises(NodeUserError, match="Account Analytics"):- await CloudflareActionNode._graphql_post("tok", {"query": "q", "variables": {}})+ await CloudflareActionNode._graphql_post({"Authorization": "Bearer tok"}, {"query": "q", "variables": {}})def test_graphql_endpoint_is_the_official_one():@@ -579,16 +639,23 @@ def test_catalogue_entry_is_vercel_dual_path_shape():"logout": "cloudflare_logout","status": "cloudflare_status",}- # 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.+ # Dual-path (vercel shape): OPTIONAL fields only — required would+ # gate the Login button (OAuthConnect counts required fields only),+ # and the OAuth login must keep working without a credential.+ # The primary key is the canonical `apiKey` (accepts an API token+ # OR a cfk_ Global API Key): the panel maps it to the provider id+ # for storage, so the base Credential.validate scaffold (which+ # stores under cls.id) needs no override, and the shared+ # ApiKeyInput validate flow lights up automatically. The secondary+ # field carries the account email Global API Keys authenticate with.fields = cloudflare["fields"]- assert len(fields) == 1+ assert [f["key"] for f in fields] == ["apiKey", "cloudflare_email"]token_field = fields[0]- assert token_field["key"] == "cloudflare_api_token"assert token_field["required"] is Falseassert token_field["secret"] is Trueassert token_field["type"] == "password"+ email_field = fields[1]+ assert email_field["required"] is Falsedef test_credential_class_shape():@@ -596,24 +663,195 @@ def test_credential_class_shape():assert CloudflareCredential.auth == "custom"-async def test_credential_resolve_returns_optional_token_row(monkeypatch):+async def test_credential_resolve_returns_optional_credential_rows(monkeypatch):from services.plugin import deps as plugin_depsclass _Auth:- def __init__(self, token):- self._token = token+ def __init__(self, rows):+ self._rows = rowsasync def get_api_key(self, key):- assert key == "cloudflare_api_token"- return self._token+ # Token stored under the provider id (canonical `apiKey`+ # field, mapped to config.id by the panel); the email+ # companion under its own field key.+ assert key in ("cloudflare", "cloudflare_email")+ return self._rows.get(key)- monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth("tok"))+ monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth({"cloudflare": "tok"}))assert await CloudflareCredential.resolve() == {"cloudflare_api_token": "tok"}- monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth(None))+ monkeypatch.setattr(+ plugin_deps,+ "get_auth_service",+ lambda: _Auth({"cloudflare": "cfk_" + "y" * 48, "cloudflare_email": "[email protected]"}),+ )+ assert await CloudflareCredential.resolve() == {+ "cloudflare_api_token": "cfk_" + "y" * 48,+ "cloudflare_email": "[email protected]",+ }++ monkeypatch.setattr(plugin_deps, "get_auth_service", lambda: _Auth({}))assert await CloudflareCredential.resolve() == {}+async def test_probe_hits_official_verify_endpoint(monkeypatch):+ """The Validate button flows through the base Credential.validate+ scaffold to this probe — one GET to Cloudflare's documented+ token-verify endpoint, nothing else."""+ import nodes.cloudflare._credentials as cf_credentials++ captured = {}++ class _Resp:+ status_code = 200++ @staticmethod+ def raise_for_status():+ return None++ @staticmethod+ def json():+ return {"success": True, "result": {"id": "t1", "status": captured["status"]}}++ class _Client:+ def __init__(self, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def get(self, url, **kwargs):+ captured["url"] = url+ captured["auth"] = kwargs["headers"]["Authorization"]+ return _Resp()++ monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Client)++ captured["status"] = "active"+ result = await CloudflareCredential._probe("tok123")+ assert result.valid is True+ assert captured["url"] == "https://api.cloudflare.com/client/v4/user/tokens/verify"+ assert captured["auth"] == "Bearer tok123"++ captured["status"] = "disabled"+ result = await CloudflareCredential._probe("tok123")+ assert result.valid is False+ assert "disabled" in result.message+++async def test_probe_global_key_without_email_gives_guidance(monkeypatch):+ """cfk_ is Cloudflare's documented Global API Key prefix — legacy+ X-Auth-Email/X-Auth-Key auth that is NEVER valid as a Bearer token.+ Without the stored email companion the probe must explain the fix+ up front (no network call) instead of relaying the API's generic+ 1000/9109 rejection."""+ import nodes.cloudflare._credentials as cf_credentials++ async def no_email():+ return None++ class _Boom:+ def __init__(self, **kwargs):+ raise AssertionError("cfk_ without email must not hit the network")++ monkeypatch.setattr(cf_credentials, "stored_email", no_email)+ monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Boom)+ result = await CloudflareCredential._probe("cfk_" + "y" * 48)+ assert result.valid is False+ assert "Account Email" in result.message+++async def test_probe_validates_global_key_with_email(monkeypatch):+ """cfk_ + stored email validate via the documented legacy header+ pair against GET /user."""+ import nodes.cloudflare._credentials as cf_credentials++ async def has_email():+ return "[email protected]"++ captured = {}++ class _Resp:+ status_code = 200++ @staticmethod+ def raise_for_status():+ return None++ @staticmethod+ def json():+ return {"success": True, "result": {"id": "u1", "email": "[email protected]"}}++ class _Client:+ def __init__(self, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def get(self, url, **kwargs):+ captured["url"] = url+ captured["headers"] = kwargs["headers"]+ return _Resp()++ monkeypatch.setattr(cf_credentials, "stored_email", has_email)+ monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Client)+ key = "cfk_" + "y" * 48+ result = await CloudflareCredential._probe(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}+++async def test_probe_verifies_account_tokens_via_accounts_read(monkeypatch):+ """cfat_ account-owned tokens cannot verify at /user/tokens/verify+ (that endpoint is user-token-only) — validity is proven with a+ lightweight authenticated read instead."""+ import nodes.cloudflare._credentials as cf_credentials++ captured = {}++ class _Resp:+ status_code = 200++ @staticmethod+ def raise_for_status():+ return None++ @staticmethod+ def json():+ return {"success": True, "result": [{"id": "acct1"}]}++ class _Client:+ def __init__(self, **kwargs):+ pass++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def get(self, url, **kwargs):+ captured["url"] = url+ captured["auth"] = kwargs["headers"]["Authorization"]+ return _Resp()++ monkeypatch.setattr(cf_credentials.httpx, "AsyncClient", _Client)+ token = "cfat_" + "y" * 48+ result = await CloudflareCredential._probe(token)+ assert result.valid is True+ assert captured["url"] == "https://api.cloudflare.com/client/v4/accounts"+ assert captured["auth"] == f"Bearer {token}"++def test_plugin_folder_assets():# Icon is the official lobehub brand glyph via visuals.json — a# co-located icon.svg would silently override it.