Cloudflare
Cloudflare
Connect Cloudflare so your agents can look after your sites: list your accounts and zones, read every DNS record, follow your Workers and Pages projects with their deployments, versions and build logs, list your R2 buckets, and report a zone's traffic by day or hour, with requests, bandwidth, cache hits, threats and breakdowns by status code or country.
With write access, agents can also create, change and delete DNS records, purge cached content, roll a Worker back to an earlier version and roll a Pages project back to an earlier production deployment. These changes reach live traffic at once, so agents confirm them with you first.
Agents see only the accounts, zones and products your API token covers, and your token stays on Houston's server.
Setup instructions
Setup instructions
Connect Cloudflare
- Open API Tokens and choose
Create Token → Create Custom Token. Name the token
Houston. - Grant the permissions below for the products agents may use; restrict Account Resources and Zone Resources to the intended account and zones.
- Create and copy the token. In Houston, choose the matching access level, paste API token and save.
| Permission | Read | Write |
|---|---|---|
| Account · Account Settings | Read | Read |
| Account · Workers Scripts | Read | Edit |
| Account · Cloudflare Pages | Read | Edit |
| Account · Workers R2 Storage | Read | Read |
| Zone · Zone | Read | Read |
| Zone · DNS | Read | Edit |
| Zone · Analytics | Read | Read |
| Zone · Cache Purge | — | Purge |
Edit permissions allow more than Houston's supported changes. Houston still blocks changes on connections with Read access. An IP filter must allow Houston's server addresses, not your device's.
Advanced
An account-owned token keeps working when its creator leaves. A Super Administrator or someone allowed to create tokens can make one under Manage Account → Account API Tokens, using the same permissions above.
For missing data or authorization errors, check the token's permissions, account and zones. Analytics history depends on your plan. Rollbacks may fail if resources used by the previous deployment no longer exist.
Files
Files
connector.luau
-- Cloudflare API v4 and its GraphQL Analytics API. Arguments and results keep Cloudflare's native snake_case field names. type Options = {[string]: any} type Endpoint = {method: string, path: string, query: {string}?, extra: {string}?, required: {string}?, access: string?, body: (boolean | string)?, fields: {string}?, perPage: number?, doc: string, about: string} local PROVIDER = "Cloudflare" local DOCS = "https://developers.cloudflare.com/" local PAGE = {"page", "per_page"} local DNS_FIELDS = {"type", "name", "content", "ttl", "proxied", "comment", "tags", "priority", "data", "settings", "private_routing"} local function with(...: {string}): {string} local fields: {string} = {} for _, group in {...} do table.move(group, 1, #group, #fields + 1, fields) end return fields end -- Operations in Cloudflare's public OpenAPI (github.com/cloudflare/api-schemas), checked on -- 2026-10-30, plus the GraphQL Analytics API. Path {fields} are required; listed query fields -- are taken from the options and the other fields form the JSON body. local endpoints: {[string]: Endpoint} = { listAccounts = {method = "GET", path = "/accounts", query = with({"name", "direction"}, PAGE), doc = "api/resources/accounts/methods/list/", about = "Accounts the token can reach: {id, name, type, settings, created_on}. An account token sees only its own account. per_page is 5 to 50."}, getAccount = {method = "GET", path = "/accounts/{account_id}", doc = "api/resources/accounts/methods/get/", about = "One account."}, listZones = {method = "GET", path = "/zones", query = with({"name", "status", "type", "account.id", "account.name", "match", "order", "direction"}, PAGE), doc = "api/resources/zones/methods/list/", about = "Zones (domains): {id, name, status, paused, type, name_servers, account={id, name}, plan, meta, created_on, modified_on}. name matches exactly, or with a prefix such as 'contains:shop' (also starts_with:, ends_with:). status: initializing, pending, active or moved. type: full, partial or secondary, or an array. order: name, status, account.id, account.name or plan.id; direction asc or desc. per_page is 5 to 50."}, getZone = {method = "GET", path = "/zones/{zone_id}", doc = "api/resources/zones/methods/get/", about = "One zone, with its plan, name servers and status."}, listDnsRecords = {method = "GET", path = "/zones/{zone_id}/dns_records", query = with({"type", "name", "name.contains", "name.startswith", "name.endswith", "content", "content.contains", "proxied", "comment.contains", "tag", "search", "match", "order", "direction"}, PAGE), perPage = 1000, doc = "api/resources/dns/subresources/records/methods/list/", about = "DNS records: {id, type, name, content, proxied, proxiable, ttl (1 is automatic), priority?, data?, comment, tags, settings, created_on, modified_on}. name is the full hostname, such as www.example.com. type: A, AAAA, CNAME, MX, TXT, NS, SRV, CAA and others. search matches any field; match='any' ORs the other filters. order: type (default), name, content, ttl or proxied. per_page is at most 1000 here (default 100)."}, getDnsRecord = {method = "GET", path = "/zones/{zone_id}/dns_records/{dns_record_id}", doc = "api/resources/dns/subresources/records/methods/get/", about = "One DNS record."}, getZoneAnalytics = {method = "POST", path = "/graphql", body = false, extra = {"zone_id", "since", "until", "granularity", "breakdowns"}, required = {"zone_id", "since", "until"}, doc = "analytics/graphql-api/", about = "A zone's HTTP traffic over time, from Cloudflare's GraphQL Analytics API, as {data={viewer={zones=[{groups=[{dimensions={date or datetime}, sum={requests, cachedRequests, bytes, cachedBytes, encryptedRequests, encryptedBytes, threats, pageViews, ...breakdowns}, uniq={uniques}}]}]}}, errors}, oldest first. granularity 'day' (default) takes since and until as inclusive dates such as '2026-10-01'; 'hour' takes whole UTC hours such as '2026-10-29T00:00:00Z', with until excluded. breakdowns adds per-group lists, an array of: responseStatusMap {edgeResponseStatus, requests}, countryMap {clientCountryName, requests, bytes, threats}, contentTypeMap {edgeResponseContentTypeName, requests, bytes}, browserMap {uaBrowserFamily, pageViews}, clientSSLMap {clientSSLProtocol, requests}, clientHTTPVersionMap {clientHTTPProtocol, requests}, ipClassMap {ipType, requests}, threatPathingMap {threatPathingName, requests}. One request covers at most 1000 days or hours, or 100 with breakdowns; the zone's plan may allow less, and limits how far back data goes."}, listWorkerScripts = {method = "GET", path = "/accounts/{account_id}/workers/scripts", query = {"tags"}, doc = "api/resources/workers/subresources/scripts/methods/list/", about = "The account's Workers, all at once: {id (the script name), created_on, modified_on, usage_model, handlers, compatibility_date, placement, tags, ...}."}, listWorkerDeployments = {method = "GET", path = "/accounts/{account_id}/workers/scripts/{script_name}/deployments", query = with({"since", "until"}, PAGE), doc = "api/resources/workers/subresources/scripts/subresources/deployments/methods/list/", about = "A Worker's deployments, newest first, in result.deployments: {id, created_on, source, strategy='percentage', versions=[{version_id, percentage}], author_email, annotations={'workers/message', 'workers/triggered_by'}}. The first is the one serving traffic. since and until filter creation times (ISO 8601); per_page is at most 100 (default 10)."}, listWorkerVersions = {method = "GET", path = "/accounts/{account_id}/workers/scripts/{script_name}/versions", query = with({"deployable"}, PAGE), doc = "api/resources/workers/subresources/scripts/subresources/versions/methods/list/", about = "A Worker's uploaded versions, newest first, in result.items: {id, number, metadata={created_on, author_email, source, hasPreview}, annotations}. deployable=true keeps those that can still be deployed."}, getWorkerVersion = {method = "GET", path = "/accounts/{account_id}/workers/scripts/{script_name}/versions/{version_id}", doc = "api/resources/workers/subresources/scripts/subresources/versions/methods/get/", about = "One version with its bindings (names, types and non-secret values such as plain_text text and json; secret values are never returned), compatibility settings and metadata, but not its code."}, listPagesProjects = {method = "GET", path = "/accounts/{account_id}/pages/projects", query = PAGE, doc = "api/resources/pages/subresources/projects/methods/list/", about = "Pages projects: {id, name, subdomain, domains, production_branch, source, build_config, latest_deployment, canonical_deployment, created_on}."}, getPagesProject = {method = "GET", path = "/accounts/{account_id}/pages/projects/{project_name}", doc = "api/resources/pages/subresources/projects/methods/get/", about = "One project, with its deployment settings per environment (deployment_configs.production and .preview)."}, listPagesDeployments = {method = "GET", path = "/accounts/{account_id}/pages/projects/{project_name}/deployments", query = with({"env"}, PAGE), doc = "api/resources/pages/subresources/projects/subresources/deployments/methods/list/", about = "A project's deployments, newest first: {id, short_id, url, environment, created_on, latest_stage={name, status}, deployment_trigger={type, metadata={branch, commit_hash, commit_message}}, aliases, is_skipped_build}. env: production or preview."}, getPagesDeployment = {method = "GET", path = "/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}", doc = "api/resources/pages/subresources/projects/subresources/deployments/methods/get/", about = "One deployment, with its build stages."}, getPagesDeploymentLogs = {method = "GET", path = "/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/history/logs", doc = "api/resources/pages/subresources/projects/subresources/deployments/subresources/history/subresources/logs/methods/get/", about = "A deployment's build log: {total, includes_container_logs, data=[{ts, line}]}."}, listR2Buckets = {method = "GET", path = "/accounts/{account_id}/r2/buckets", query = {"name_contains", "start_after", "per_page", "order", "direction", "cursor"}, extra = {"jurisdiction"}, doc = "api/resources/r2/subresources/buckets/methods/list/", about = "R2 buckets in result.buckets: {name, creation_date, location, jurisdiction, storage_class}. Pages with cursor=result_info.cursor; per_page is at most 1000. jurisdiction 'eu', 'us', 'fedramp' or 'fedramp-high' lists the buckets kept there instead."}, getR2Bucket = {method = "GET", path = "/accounts/{account_id}/r2/buckets/{bucket_name}", extra = {"jurisdiction"}, doc = "api/resources/r2/subresources/buckets/methods/get/", about = "One bucket; pass jurisdiction for a bucket in one."}, createDnsRecord = {method = "POST", path = "/zones/{zone_id}/dns_records", access = "data:write", required = {"type", "name"}, fields = DNS_FIELDS, doc = "api/resources/dns/subresources/records/methods/create/", about = "Creates a record and returns it. Body {type, name, content, ttl? (1 automatic, else 60 to 86400 seconds, 30 on Enterprise), proxied? (A, AAAA and CNAME only), comment?, tags? ('name:value' strings), priority? (MX), data? (SRV, CAA and other structured types), settings?, private_routing?}. Cloudflare refuses an identical record and a CNAME next to other records of the same name."}, updateDnsRecord = {method = "PATCH", path = "/zones/{zone_id}/dns_records/{dns_record_id}", access = "data:write", fields = DNS_FIELDS, doc = "api/resources/dns/subresources/records/methods/edit/", about = "Changes only the given fields of a record and returns it."}, deleteDnsRecord = {method = "DELETE", path = "/zones/{zone_id}/dns_records/{dns_record_id}", access = "data:write", doc = "api/resources/dns/subresources/records/methods/delete/", about = "Deletes a record and returns {result={id}}."}, purgeCache = {method = "POST", path = "/zones/{zone_id}/purge_cache", access = "data:write", fields = {"purge_everything", "files", "tags", "hosts", "prefixes"}, doc = "api/resources/cache/methods/purge/", about = "Removes cached content from every Cloudflare data center, so the next requests go to the origin. Body: exactly one of purge_everything=true, files (full URLs, or {url, headers} for cache keys with headers), tags (Cache-Tag values), hosts or prefixes (such as 'www.example.com/blog/'), at most 100 items (500 URLs on Enterprise). Free plans allow 5 purges of everything, hosts, tags or prefixes per minute."}, createWorkerDeployment = {method = "POST", path = "/accounts/{account_id}/workers/scripts/{script_name}/deployments", access = "data:write", required = {"strategy", "versions"}, fields = {"strategy", "versions", "annotations"}, doc = "api/resources/workers/subresources/scripts/subresources/deployments/methods/create/", about = "Deploys existing versions, which serve traffic at once, and returns the deployment. Body {strategy='percentage', versions=[{version_id, percentage}] totalling 100, annotations?={['workers/message']=text}}. Roll back with one earlier version at 100 (one of the 100 most recent); Cloudflare refuses when a KV namespace, R2 bucket or queue it binds no longer exists, or Durable Object classes changed since. Bindings, routes and secrets stay as they are."}, rollbackPagesDeployment = {method = "POST", path = "/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/rollback", access = "data:write", body = false, doc = "api/resources/pages/subresources/projects/subresources/deployments/methods/rollback/", about = "Serves production from an earlier successful production deployment at once, without rebuilding, and returns it. Preview deployments are not valid targets."}, } -- Request layer shared verbatim by the endpoint-table connectors -- (tools/validate checks they match). It uses each connector's PROVIDER, DOCS and Endpoint type. local NULL = json.decode("null") local NONE: {string} = table.freeze({}) local function options(input: Options?): Options if input == nil then return {} end assert(type(input) == "table", "opts must be an object") for key in input do assert(type(key) == "string", "opts must have named fields") end return table.clone(input) end local function scalar(value: any, field: string): string local kind = type(value) assert(kind == "string" or kind == "boolean" or kind == "number", field .. " must be a string, boolean, number or array of those") return url.encode(value) end -- A query value's encoded parts: one for a scalar, one per item of a nonempty array. Each -- connector joins them as its provider expects, comma-separated or with the key repeated. local function queryParts(value: any, field: string): {string} if type(value) ~= "table" then return {scalar(value, field)} end local parts: {string} = {} for index, item in value do assert(type(index) == "number" and index == #parts + 1, field .. " must be an array, not an object") table.insert(parts, scalar(item, field)) end assert(#parts > 0, field .. " must not be an empty array") return parts end -- POST, PATCH and PUT send the remaining options as the JSON body unless body is false -- (no body) or names the one option to send. local function hasBody(endpoint: Endpoint): boolean return endpoint.body ~= false and (endpoint.method == "POST" or endpoint.method == "PATCH" or endpoint.method == "PUT") end local function fail(name: string, response: HttpResponse, message: string): never return houston.fail({operation = name, layer = "upstream", upstream_status = response.statusCode, retryable = response.statusCode == 429 or response.statusCode >= 500, message = message}) end -- A successful response's JSON object, or nil when a write answers without a body. With arrays, -- a top-level JSON array is accepted too, and the second result tells which one came back. local function object(name: string, endpoint: Endpoint, response: HttpResponse, arrays: boolean?): (any, boolean) local raw = await(response.body:readAll()) if endpoint.method ~= "GET" and endpoint.access and string.match(raw, "^%s*$") then return nil, false end local ok, value = pcall(json.decode, raw) local list = arrays == true and string.match(raw, "^%s*%[") ~= nil if not ok or type(value) ~= "table" or not (list or string.match(raw, "^%s*{")) then fail(name, response, PROVIDER .. " returned an invalid JSON object") end return value, list end -- name({path fields, query fields?, extra fields?, required body fields, ...body}) built from the -- endpoint itself. -- Extra fields are options the connector's own request consumes, such as a request header. local function signature(endpoint: Endpoint): string local fields: {string} = {} for field in string.gmatch(endpoint.path, "{([%w_]+)}") do table.insert(fields, field) end for _, group in {endpoint.query or NONE, endpoint.extra or NONE} do for _, field in group do table.insert(fields, if table.find(endpoint.required or NONE, field) then field else field .. "?") end end if type(endpoint.body) == "string" then table.insert(fields, endpoint.body) elseif hasBody(endpoint) then for _, field in endpoint.required or NONE do if not table.find(fields, field) then table.insert(fields, field) end end table.insert(fields, "...body") end return "({" .. table.concat(fields, ", ") .. "})" end -- A function for each endpoint the connection's access allows, and help listing them after intro. local function operations(endpoints: {[string]: Endpoint}, request: (string, Endpoint, Options?) -> any, intro: {string}): {[string]: any} local exports: {[string]: any} = {} for name, endpoint in endpoints do if not endpoint.access or houston.allows(endpoint.access) then exports[name] = function(args: Options?): any return request(name, endpoint, args) end end end exports.help = function(): string local names: {string} = {} for name in exports do if name ~= "help" then table.insert(names, name) end end table.sort(names) local lines = table.clone(intro) table.insert(lines, "Each function below names its route and reference page, " .. DOCS .. "<page>.") for _, name in names do local endpoint = endpoints[name] table.insert(lines, name .. signature(endpoint) .. ": " .. endpoint.about .. " " .. endpoint.method .. " " .. endpoint.path .. " (" .. endpoint.doc .. ")") end return table.concat(lines, "\n") end return exports end -- End of the shared request layer. local API = "https://api.cloudflare.com/client/v4" -- The GraphQL datasets behind getZoneAnalytics: daily or hourly HTTP request groups, which -- every plan has. Each granularity takes one fixed format: a date, or a whole UTC hour. local GRANULARITIES = { day = {node = "httpRequests1dGroups", dimension = "date", type = "Date", upto = "date_leq", format = "^%d%d%d%d%-%d%d%-%d%d$", example = "date such as 2026-10-01"}, hour = {node = "httpRequests1hGroups", dimension = "datetime", type = "Time", upto = "datetime_lt", format = "^%d%d%d%d%-%d%d%-%d%dT%d%d:00:00Z$", example = "whole UTC hour such as 2026-10-01T00:00:00Z"}, } local BREAKDOWNS = { responseStatusMap = "edgeResponseStatus requests", countryMap = "clientCountryName requests bytes threats", contentTypeMap = "edgeResponseContentTypeName requests bytes", browserMap = "uaBrowserFamily pageViews", clientSSLMap = "clientSSLProtocol requests", clientHTTPVersionMap = "clientHTTPProtocol requests", ipClassMap = "ipType requests", threatPathingMap = "threatPathingName requests", } -- At most this many groups per request, fewer with breakdowns, so each answer stays well -- under the 8 MiB response bound. local MAX_GROUPS, MAX_BREAKDOWN_GROUPS = 1000, 100 local DAYS_IN_MONTH = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} -- Hours since 1970-01-01 of a real date or whole UTC hour in the granularity's format, or nil. -- Days use Howard Hinnant's days_from_civil. local function hours(value: any, format: string): number? if type(value) ~= "string" or not string.match(value, format) then return nil end local y, m, d = tonumber(string.sub(value, 1, 4)) :: number, tonumber(string.sub(value, 6, 7)) :: number, tonumber(string.sub(value, 9, 10)) :: number local h = tonumber(string.sub(value, 12, 13)) or 0 local leap = y % 4 == 0 and (y % 100 ~= 0 or y % 400 == 0) if m < 1 or m > 12 or d < 1 or d > DAYS_IN_MONTH[m] + (if m == 2 and leap then 1 else 0) or h > 23 then return nil end if m <= 2 then y -= 1 end local era = y // 400 local yoe = y - era * 400 local doy = (153 * (if m > 2 then m - 3 else m + 9) + 2) // 5 + d - 1 return ((era * 146097 + yoe * 365 + yoe // 4 - yoe // 100 + doy) - 719468) * 24 + h end -- The analytics request body. The query text depends only on the granularity and breakdowns; -- caller values travel as GraphQL variables. local function analytics(endpoint: Endpoint, args: Options): string local zone, since, upto, granularity, breakdowns = args.zone_id, args.since, args["until"], args.granularity or "day", args.breakdowns for _, field in endpoint.extra or NONE do args[field] = nil end local set = if type(granularity) == "string" then GRANULARITIES[granularity] else nil assert(set, "granularity must be day or hour") assert(type(zone) == "string" and string.match(zone, "^%x+$"), "zone_id must be a zone id from listZones") local from, to = hours(since, set.format), hours(upto, set.format) assert(from, "since must be a real " .. set.example) assert(to, "until must be a real " .. set.example) local maps: {string} = {} if breakdowns ~= nil then assert(type(breakdowns) == "table", "breakdowns must be an array") for index, name in breakdowns do assert(type(index) == "number" and type(name) == "string" and BREAKDOWNS[name], "breakdowns has no item " .. tostring(name)) table.insert(maps, name .. " { " .. BREAKDOWNS[name] .. " } ") end end local limit = if #maps > 0 then MAX_BREAKDOWN_GROUPS else MAX_GROUPS local groups = if granularity == "day" then (to - from) // 24 + 1 else to - from assert(groups > 0, "since must come before until") assert(groups <= limit, "since to until spans " .. groups .. " " .. granularity .. "s; ask for at most " .. limit) local query = string.format("query ZoneAnalytics($zoneTag: string, $since: %s, $until: %s) { viewer { zones(filter: {zoneTag: $zoneTag}) { " .. "groups: %s(limit: %d, orderBy: [%s_ASC], filter: {%s_geq: $since, %s: $until}) { dimensions { %s } " .. "sum { requests cachedRequests bytes cachedBytes encryptedRequests encryptedBytes threats pageViews %s} uniq { uniques } } } } }", set.type, set.type, set.node, limit, set.dimension, set.dimension, set.upto, set.dimension, table.concat(maps)) return json.encode({query = query, variables = {zoneTag = string.lower(zone), since = since, ["until"] = upto}}) end -- Cloudflare answers {success, errors=[{code, message, error_chain?}], messages, result, -- result_info?}, and GraphQL {data, errors=[{message, path, extensions}]}, with errors null -- on success. Either errors list becomes the failure message. local function errorText(value: any): string? if type(value) ~= "table" or type(value.errors) ~= "table" or #value.errors == 0 then return nil end local parts: {string} = {} for _, item in value.errors do if type(item) == "table" then local text = if type(item.message) == "string" then item.message else json.encode(item) if type(item.code) == "number" then text = item.code .. " " .. text end if type(item.error_chain) == "table" then for _, cause in item.error_chain do if type(cause) == "table" and type(cause.message) == "string" then text ..= " (" .. cause.message .. ")" end end end table.insert(parts, text) end end return string.sub(table.concat(parts, "; "), 1, 600) end local function failStatus(name: string, response: HttpResponse): never local message = "Cloudflare HTTP " .. tostring(response.statusCode) local raw = await(response.body:readPrefix(16 * 1024)) local ok, value = pcall(json.decode, raw) local text = if ok then errorText(value) else nil if text then message ..= ": " .. text end local retry = response.headers["retry-after"] if response.statusCode == 429 and retry and retry[1] then -- Retry-After is either delay seconds or an HTTP date. local value = string.sub(retry[1], 1, 32) message ..= "; retry after " .. value .. (if string.match(value, "^%d+$") then "s" else "") end return fail(name, response, message) end local function request(name: string, endpoint: Endpoint, input: Options?): any local args = options(input) local path = string.gsub(endpoint.path, "{([%w_]+)}", function(field: string) local value = args[field] args[field] = nil assert(type(value) == "string", field .. " is required and must be a string") local ok, segment = pcall(url.segment, value, field) assert(ok, field .. " must be a Cloudflare id or name") return segment end) for _, field in endpoint.required or NONE do assert(args[field] ~= nil and args[field] ~= NULL, field .. " is required") end if endpoint.perPage and args.per_page ~= nil then assert(type(args.per_page) == "number" and args.per_page >= 1 and args.per_page <= endpoint.perPage, "per_page must be 1 to " .. endpoint.perPage) end -- Cloudflare takes an array as comma-separated values, as type=full,partial. local query: {string} = {} for _, field in endpoint.query or NONE do if args[field] ~= nil then table.insert(query, field .. "=" .. table.concat(queryParts(args[field], field), ",")) end args[field] = nil end if #query > 0 then path ..= "?" .. table.concat(query, "&") end local headers: HttpHeaders = {Accept = {"application/json"}} if table.find(endpoint.extra or NONE, "jurisdiction") and args.jurisdiction ~= nil then assert(type(args.jurisdiction) == "string" and string.match(args.jurisdiction, "^[%a%-]+$"), "jurisdiction must be a name such as eu") headers["cf-r2-jurisdiction"] = {args.jurisdiction} args.jurisdiction = nil end if endpoint.fields then for field in args do assert(table.find(endpoint.fields :: {string}, field), name .. " has no option " .. field) end end local body: string? = nil if endpoint == endpoints.getZoneAnalytics then body = analytics(endpoint, args) elseif hasBody(endpoint) then assert(next(args) ~= nil, name .. " needs a body field") body = json.encode(args) args = {} end if body then headers["Content-Type"] = {"application/json"} end local unknown = next(args) assert(unknown == nil, name .. " has no option " .. tostring(unknown)) local response = await(http.request({url = API .. path, method = endpoint.method, headers = headers, body = body})) if response.statusCode < 200 or response.statusCode >= 300 then failStatus(name, response) end local value = object(name, endpoint, response) local text = errorText(value) if text or (type(value) == "table" and value.success == false) then fail(name, response, "Cloudflare reported an error: " .. (text or "no details")) end return value end local intro = { "Cloudflare API v4 on " .. API .. ". Every function takes one named options object with Cloudflare's native names; ? marks optional fields and ...body the JSON body fields. Connector calls return completed values: use them directly, without await.", "Results are Cloudflare's JSON unchanged: {success, errors, messages, result, result_info?}; read result. Lists return one page with result_info={page, per_page, count, total_count, total_pages}: pass page=result_info.page + 1 while it is below total_pages. R2 buckets page with a cursor instead. getZoneAnalytics returns GraphQL's {data, errors}.", "Account, zone and DNS record ids are 32-character hex strings: start with listAccounts and listZones (zone.account.id is its account). Workers are named by script_name, Pages projects by project_name and R2 buckets by bucket_name; Workers version and deployment ids and Pages deployment ids are UUIDs. Times are ISO 8601 UTC. Write until as ['until'] in Luau, since until is a keyword.", "Examples: local zone = cloudflare.listZones({name='example.com'}).result[1]; cloudflare.listDnsRecords({zone_id=zone.id, type='CNAME', per_page=100}); cloudflare.getZoneAnalytics({zone_id=zone.id, since='2026-10-01', ['until']='2026-10-07', breakdowns={'responseStatusMap'}}).", "The token's permissions and resources still apply: HTTP 403 (usually code 10000 'Authentication error') means the token lacks a permission for that account or zone, or doesn't cover it. Cloudflare allows 1200 requests per 5 minutes per token (GraphQL about 300) and then refuses requests for up to 5 minutes; Houston retries an HTTP 429 at most twice, when Retry-After is absent or at most 5 seconds, and the error reports Retry-After when Cloudflare sends one. A GraphQL 429 about query cost or too many nodes needs a shorter period or fewer breakdowns, not a retry. Errors report the HTTP status and Cloudflare's codes and messages. 5xx and 429 are retryable.", } if houston.allows("data:write") then table.insert(intro, "Writes change production at once: DNS changes reach Cloudflare's network within seconds, while resolvers may keep old answers for the record's TTL (deleting or editing a record can take a site or its mail offline), purgeCache sends the next requests to the origin, which can overload it, and Worker deployments and Pages rollbacks switch live traffic. Confirm the exact change with the user first, and read the current state (getDnsRecord, listWorkerDeployments, listPagesDeployments) before changing it so it can be restored. Writes are retried only after an HTTP 429, which Cloudflare refused before acting: after a timeout or 5xx, read the state again before repeating one.") else table.insert(intro, "This read-only connection omits writes.") end return operations(endpoints, request, intro)houston.json
{ "schema_version": 2, "name": "Cloudflare", "files": [ "connector.luau" ], "icon": "icon.svg", "access": [ { "name": "data", "label": "Access", "levels": [ { "value": "read", "label": "Read" }, { "value": "write", "label": "Write" } ], "default": "read" } ], "auth": { "token": { "type": "manual", "label": "API token", "config": { "token": { "type": "secret", "label": "API token", "description": "A Cloudflare user or account API token with the permissions for your access level.", "required": true } } } }, "proxy": [ { "match": { "protocol": "http", "host": [ "api.cloudflare.com" ], "method": [ "GET" ], "path": [ "/client/v4/accounts", "/client/v4/accounts/{account_id}", "/client/v4/accounts/{account_id}/pages/projects", "/client/v4/accounts/{account_id}/pages/projects/{project_name}", "/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments", "/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}", "/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/history/logs", "/client/v4/accounts/{account_id}/r2/buckets", "/client/v4/accounts/{account_id}/r2/buckets/{bucket_name}", "/client/v4/accounts/{account_id}/workers/scripts", "/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments", "/client/v4/accounts/{account_id}/workers/scripts/{script_name}/versions", "/client/v4/accounts/{account_id}/workers/scripts/{script_name}/versions/{version_id}", "/client/v4/zones", "/client/v4/zones/{zone_id}", "/client/v4/zones/{zone_id}/dns_records", "/client/v4/zones/{zone_id}/dns_records/{dns_record_id}" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } } }, { "match": { "protocol": "http", "host": [ "api.cloudflare.com" ], "method": [ "POST" ], "path": [ "/client/v4/graphql" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } } }, { "if": "{{ allows access.data \"write\" }}", "match": { "protocol": "http", "host": [ "api.cloudflare.com" ], "method": [ "POST" ], "path": [ "/client/v4/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/rollback", "/client/v4/accounts/{account_id}/workers/scripts/{script_name}/deployments", "/client/v4/zones/{zone_id}/dns_records", "/client/v4/zones/{zone_id}/purge_cache" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } } }, { "if": "{{ allows access.data \"write\" }}", "match": { "protocol": "http", "host": [ "api.cloudflare.com" ], "method": [ "PATCH", "DELETE" ], "path": [ "/client/v4/zones/{zone_id}/dns_records/{dns_record_id}" ] }, "action": { "headers": { "set": { "Authorization": "Bearer {{auth.token.token}}" } } } } ] }icon.svg
README.md
--- description: Review Cloudflare zones, DNS records, Workers, Pages deployments, R2 buckets and traffic analytics, and manage DNS, purge the cache or roll back deployments. --- # Cloudflare Connect Cloudflare so your agents can look after your sites: list your accounts and zones, read every DNS record, follow your Workers and Pages projects with their deployments, versions and build logs, list your R2 buckets, and report a zone's traffic by day or hour, with requests, bandwidth, cache hits, threats and breakdowns by status code or country. With write access, agents can also create, change and delete DNS records, purge cached content, roll a Worker back to an earlier version and roll a Pages project back to an earlier production deployment. These changes reach live traffic at once, so agents confirm them with you first. Agents see only the accounts, zones and products your API token covers, and your token stays on Houston's server. [Connect Cloudflare](SETUP.md).SETUP.md
# Connect Cloudflare 1. Open [API Tokens](https://dash.cloudflare.com/profile/api-tokens) and choose **Create Token → Create Custom Token**. Name the token `Houston`. 2. Grant the permissions below for the products agents may use; restrict **Account Resources** and **Zone Resources** to the intended account and zones. 3. Create and copy the token. In Houston, choose the matching access level, paste **API token** and save. | Permission | Read | Write | | --- | --- | --- | | Account · Account Settings | Read | Read | | Account · Workers Scripts | Read | Edit | | Account · Cloudflare Pages | Read | Edit | | Account · Workers R2 Storage | Read | Read | | Zone · Zone | Read | Read | | Zone · DNS | Read | Edit | | Zone · Analytics | Read | Read | | Zone · Cache Purge | — | Purge | > Edit permissions allow more than Houston's supported changes. Houston still > blocks changes on connections with **Read** access. An IP filter must allow Houston's > server addresses, not your device's. [Official token guide](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/). ## Advanced An account-owned token keeps working when its creator leaves. A Super Administrator or someone allowed to create tokens can make one under **Manage Account → Account API Tokens**, using the same permissions above. For missing data or authorization errors, check the token's permissions, account and zones. Analytics history depends on your plan. Rollbacks may fail if resources used by the previous deployment no longer exist.tests
authentication.luau
return { contract = function(m) m.authentication({ { auth = { token = "synthetic-method-secret" }, config = {}, endpoint = { "GET", "https://api.cloudflare.com/client/v4/accounts" }, expected = "Bearer synthetic-method-secret", header = "Authorization", method = "token", publisher = {}, }, }) end, }endpoints.luau
return { contract = function(m) m.endpointRules() end, }errors.luau
return { scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "fixture-token"}}, configure = function() calls = 0 status = 200 payload = "{}" responseHeaders = {} http = {request = function(req) calls += 1 return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)}) end} end, run = function(cloudflare) local ZONE = "023e105f4ecef8ad9ca31a8372d0c353" local function failure(call, code, body, headers, expected) status, payload, responseHeaders = code, body, headers local before = calls local ok, err = pcall(call) for _, text in expected do assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err)) end assert(calls == before + 1, "failed request was retried") end local function zone() cloudflare.getZone({zone_id = ZONE}) end local function create() cloudflare.createDnsRecord({zone_id = ZONE, type = "A", name = "www.example.com", content = "198.51.100.4"}) end local function traffic() cloudflare.getZoneAnalytics({zone_id = ZONE, since = "2025-01-01", ["until"] = "2025-01-02"}) end failure(zone, 400, '{"success":false,"errors":[{"code":6003,"message":"Invalid request headers","error_chain":[{"code":6111,"message":"Invalid format for Authorization header"}]}],"messages":[],"result":null}', {}, {"Cloudflare HTTP 400: 6003 Invalid request headers (Invalid format for Authorization header)", '"upstream_status":400', '"retryable":false'}) failure(zone, 401, '{"success":false,"errors":[{"code":10001,"message":"Unable to authenticate request"}],"messages":[],"result":null}', {}, {"Cloudflare HTTP 401: 10001 Unable to authenticate request", '"retryable":false'}) failure(zone, 403, '{"success":false,"errors":[{"code":10000,"message":"Authentication error"}],"messages":[],"result":null}', {}, {"Cloudflare HTTP 403: 10000 Authentication error", '"retryable":false'}) failure(zone, 404, '{"result":null,"success":false,"errors":[{"code":7003,"message":"Could not route to /client/v4/zones/x, perhaps your object identifier is invalid?"}],"messages":[]}', {}, {"HTTP 404: 7003 Could not route", '"retryable":false'}) failure(create, 400, '{"success":false,"errors":[{"code":81058,"message":"An identical record already exists."},{"code":1004,"message":"DNS Validation Error"}],"messages":[],"result":null}', {}, {"HTTP 400: 81058 An identical record already exists.; 1004 DNS Validation Error"}) failure(create, 400, json.encode({errors = {{code = 1, message = string.rep("x", 5000)}}}), {}, {"HTTP 400: 1 xxx"}) failure(zone, 429, '{"success":false,"errors":[{"code":10429,"message":"Too many requests"}],"messages":[],"result":null}', {["retry-after"] = {"300"}}, {"HTTP 429: 10429 Too many requests; retry after 300s", '"retryable":true'}) failure(zone, 429, '{"success":false,"errors":[{"code":10429,"message":"Too many requests"}],"messages":[],"result":null}', {["retry-after"] = {"Fri, 30 Oct 2026 18:40:00 GMT"}}, {"Too many requests; retry after Fri, 30 Oct 2026 18:40:00 GMT\"", '"retryable":true'}) failure(zone, 502, "<html>Bad gateway</html>", {}, {'"message":"Cloudflare HTTP 502"', '"retryable":true'}) failure(zone, 200, "<html>Maintenance</html>", {}, {"Cloudflare returned an invalid JSON object"}) failure(zone, 200, '{"success":false,"errors":[],"messages":[],"result":null}', {}, {"Cloudflare reported an error: no details", '"upstream_status":200'}) -- GraphQL reports some errors with HTTP 200, and others with a status. failure(traffic, 200, '{"data":null,"errors":[{"message":"cannot request data older than 31536000s","path":["viewer","zones","0","groups"],"extensions":{"timestamp":"2026-10-30T10:00:00Z"}}]}', {}, {"Cloudflare reported an error: cannot request data older than 31536000s", '"upstream_status":200', '"retryable":false'}) failure(traffic, 403, '{"data":null,"errors":[{"message":"zones [' .. ZONE .. '] are not authorized","path":["viewer","zones"]}]}', {}, {"Cloudflare HTTP 403: zones [" .. ZONE .. "] are not authorized"}) failure(traffic, 429, '{"data":null,"errors":[{"message":"rate limiter budget depleted, try again after 5 minutes"}]}', {}, {"HTTP 429: rate limiter budget depleted", '"retryable":true'}) failure(traffic, 503, '{"data":null,"errors":[{"message":"too many queries in progress, please try again later"}]}', {}, {"HTTP 503: too many queries in progress", '"retryable":true'}) failure(traffic, 200, "[]", {}, {"Cloudflare returned an invalid JSON object"}) end, }manifest.luau
return { contract = function(m) -- TestCloudflareAccessRoutes do local api = "https://api.cloudflare.com/client/v4" local account = api .. "/accounts/0123456789abcdef0123456789abcdef" local zone = api .. "/zones/023e105f4ecef8ad9ca31a8372d0c353" local record = zone .. "/dns_records/372e67954025e0ba6aaa6d586b9e0b59" local script = account .. "/workers/scripts/api" local pages = account .. "/pages/projects/site" for _, access in { "read", "write" } do local r, err = m.resolve(nil, {}, { token = "cfut_fixture" }, "token", { data = access }) assert(not err, tostring(err)) m.routes(r, "Bearer cfut_fixture", true, { "GET " .. api .. "/accounts?page=2&per_page=50", "GET " .. account, "GET " .. api .. "/zones?name=example.com&type=full,partial", "GET " .. zone, "GET " .. zone .. "/dns_records?type=CNAME&per_page=1000", "GET " .. record, "POST " .. api .. "/graphql", "GET " .. account .. "/workers/scripts?tags=prod%3Ayes", "GET " .. script .. "/deployments?per_page=5", "GET " .. script .. "/versions?deployable=true", "GET " .. script .. "/versions/bcf48806-b317-4351-9ee7-36e7d557d4de", "GET " .. account .. "/pages/projects", "GET " .. pages, "GET " .. pages .. "/deployments?env=production", "GET " .. pages .. "/deployments/4f0b3a52", "GET " .. pages .. "/deployments/4f0b3a52/history/logs", "GET " .. account .. "/r2/buckets?cursor=YXNzZXRz", "GET " .. account .. "/r2/buckets/assets", }) m.routes(r, "Bearer cfut_fixture", (access == "write"), { "POST " .. zone .. "/dns_records", "PATCH " .. record, "DELETE " .. record, "POST " .. zone .. "/purge_cache", "POST " .. script .. "/deployments", "POST " .. pages .. "/deployments/4f0b3a52/rollback", }) m.routes(r, "Bearer cfut_fixture", false, { "GET " .. api .. "/user", "GET " .. api .. "/user/tokens", "GET " .. api .. "/user/tokens/verify", "GET " .. account .. "/tokens", "GET " .. account .. "/tokens/abc/value", "PUT " .. account .. "/tokens/abc/value", "POST " .. account .. "/tokens", "GET " .. account .. "/members", "GET " .. script, "PUT " .. script, "DELETE " .. script, "GET " .. script .. "/content", "GET " .. script .. "/secrets", "PUT " .. script .. "/secrets", "POST " .. script .. "/versions", "DELETE " .. script .. "/deployments/6d4b3a52", "GET " .. script .. "/settings", "PUT " .. record, "POST " .. zone .. "/dns_records/batch", "POST " .. zone .. "/dns_records/import", "PATCH " .. zone, "DELETE " .. zone, "POST " .. api .. "/zones", "PATCH " .. zone .. "/settings/ssl", "GET " .. zone .. "/settings", "POST " .. pages .. "/deployments", "DELETE " .. pages .. "/deployments/4f0b3a52", "POST " .. pages .. "/deployments/4f0b3a52/retry", "PATCH " .. pages, "DELETE " .. pages, "POST " .. account .. "/r2/buckets", "DELETE " .. account .. "/r2/buckets/assets", "GET " .. account .. "/r2/buckets/assets/objects", "GET " .. zone .. "/dns_records/%2e%2e", "GET " .. api .. "/zones/..", "PUT " .. api .. "/graphql", "GET https://api.cloudflare.com/client/v3/zones", "GET https://dash.cloudflare.com/api/v4/zones", "GET https://api.cloudflare.com.example.com/client/v4/zones", "GET http://api.cloudflare.com/client/v4/zones", "GET https://api.cloudflare.com:8443/client/v4/zones", "GET https://cloudflare.com/client/v4/zones", }) end end end, }read_only.luau
return { scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "fixture-token"}}, configure = function() requests = {} payload = '{"success":true,"errors":[],"messages":[],"result":[]}' http = {request = function(req) table.insert(requests, req) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)}) end} end, run = function(cloudflare) local API = "https://api.cloudflare.com/client/v4" local ACCOUNT = "0123456789abcdef0123456789abcdef" local ZONE = "023e105f4ecef8ad9ca31a8372d0c353" local NULL = json.decode("null") local function last() return requests[#requests] end local function got(target) local req = last() assert(req.method == "GET" and req.url == target and req.body == nil, req.method .. " " .. req.url) assert(req.headers.Accept[1] == "application/json" and req.headers.Authorization == nil and req.headers["Content-Type"] == nil) end local function rejected(fn, expected) local before = #requests local ok, err = pcall(fn) assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err)) assert(#requests == before, "invalid input reached Cloudflare") end local names = {} for name in cloudflare do table.insert(names, name) end table.sort(names) assert(table.concat(names, ",") == "getAccount,getDnsRecord,getPagesDeployment,getPagesDeploymentLogs,getPagesProject,getR2Bucket,getWorkerVersion,getZone,getZoneAnalytics,listAccounts,listDnsRecords,listPagesDeployments,listPagesProjects,listR2Buckets,listWorkerDeployments,listWorkerScripts,listWorkerVersions,listZones", "wrong read-only surface: " .. table.concat(names, ",")) assert(#requests == 0, "initialization reached Cloudflare") -- An empty list comes back unchanged. local accounts = cloudflare.listAccounts() got(API .. "/accounts") assert(accounts.success == true and json.encode(accounts.result) == "[]", json.encode(accounts)) cloudflare.listAccounts({name = "Acme Inc", page = 2, per_page = 50}) got(API .. "/accounts?name=Acme%20Inc&page=2&per_page=50") cloudflare.getAccount({account_id = ACCOUNT}) got(API .. "/accounts/" .. ACCOUNT) -- Populated results keep Cloudflare's nulls and paging fields. payload = '{"success":true,"errors":[],"messages":[],"result":[{"id":"' .. ZONE .. '","name":"example.com","status":"active","paused":false,' .. '"account":{"id":"' .. ACCOUNT .. '","name":"Acme"},"owner":{"id":null,"type":"user","email":null},"vanity_name_servers":null}],' .. '"result_info":{"page":1,"per_page":20,"count":1,"total_count":21,"total_pages":2}}' local zones = cloudflare.listZones({name = "contains:example", type = {"full", "partial"}, ["account.id"] = ACCOUNT, status = "active", page = 1}) got(API .. "/zones?name=contains%3Aexample&status=active&type=full,partial&account.id=" .. ACCOUNT .. "&page=1") local zone = zones.result[1] assert(zone.name == "example.com" and zone.owner.id == NULL and zone.vanity_name_servers == NULL and zones.result_info.total_pages == 2, json.encode(zones)) cloudflare.getZone({zone_id = ZONE}) got(API .. "/zones/" .. ZONE) payload = '{"success":true,"errors":[],"messages":[],"result":[{"id":"372e67954025e0ba6aaa6d586b9e0b59","type":"CNAME","name":"www.example.com",' .. '"content":"example.com","proxied":true,"ttl":1,"comment":null,"tags":[],"settings":{"flatten_cname":false}}],"result_info":{"page":1,"per_page":1000,"count":1,"total_count":1,"total_pages":1}}' local records = cloudflare.listDnsRecords({zone_id = ZONE, type = "CNAME", ["name.endswith"] = ".example.com", proxied = true, search = "www", per_page = 1000}) got(API .. "/zones/" .. ZONE .. "/dns_records?type=CNAME&name.endswith=.example.com&proxied=true&search=www&per_page=1000") assert(records.result[1].comment == NULL and records.result[1].proxied == true) cloudflare.getDnsRecord({zone_id = ZONE, dns_record_id = "372e67954025e0ba6aaa6d586b9e0b59"}) got(API .. "/zones/" .. ZONE .. "/dns_records/372e67954025e0ba6aaa6d586b9e0b59") payload = '{"success":true,"errors":[],"messages":[],"result":[{"id":"api","created_on":"2026-10-01T00:00:00Z","tags":null}]}' assert(cloudflare.listWorkerScripts({account_id = ACCOUNT, tags = "prod:yes"}).result[1].id == "api") got(API .. "/accounts/" .. ACCOUNT .. "/workers/scripts?tags=prod%3Ayes") local SCRIPT = API .. "/accounts/" .. ACCOUNT .. "/workers/scripts/api" cloudflare.listWorkerDeployments({account_id = ACCOUNT, script_name = "api", per_page = 5}) got(SCRIPT .. "/deployments?per_page=5") cloudflare.listWorkerVersions({account_id = ACCOUNT, script_name = "api", deployable = true, page = 2}) got(SCRIPT .. "/versions?deployable=true&page=2") cloudflare.getWorkerVersion({account_id = ACCOUNT, script_name = "api", version_id = "bcf48806-b317-4351-9ee7-36e7d557d4de"}) got(SCRIPT .. "/versions/bcf48806-b317-4351-9ee7-36e7d557d4de") local PAGES = API .. "/accounts/" .. ACCOUNT .. "/pages/projects" cloudflare.listPagesProjects({account_id = ACCOUNT}) got(PAGES) cloudflare.getPagesProject({account_id = ACCOUNT, project_name = "site"}) got(PAGES .. "/site") cloudflare.listPagesDeployments({account_id = ACCOUNT, project_name = "site", env = "production", per_page = 10}) got(PAGES .. "/site/deployments?env=production&per_page=10") cloudflare.getPagesDeployment({account_id = ACCOUNT, project_name = "site", deployment_id = "4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c"}) got(PAGES .. "/site/deployments/4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c") payload = '{"success":true,"errors":[],"messages":[],"result":{"total":2,"includes_container_logs":true,"data":[{"ts":"2026-10-30T10:00:00Z","line":"Cloning repository..."},{"ts":"2026-10-30T10:00:05Z","line":"Success: Build complete!"}]}}' local logs = cloudflare.getPagesDeploymentLogs({account_id = ACCOUNT, project_name = "site", deployment_id = "4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c"}) got(PAGES .. "/site/deployments/4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c/history/logs") assert(logs.result.total == 2 and logs.result.data[2].line == "Success: Build complete!") -- R2 pages with a cursor, and a jurisdiction travels as Cloudflare's header. payload = '{"success":true,"errors":[],"messages":[],"result":{"buckets":[{"name":"assets","creation_date":"2026-01-01T00:00:00Z","location":"WEUR","jurisdiction":"eu"}]},"result_info":{"cursor":"YXNzZXRz","per_page":1}}' local buckets = cloudflare.listR2Buckets({account_id = ACCOUNT, per_page = 1, cursor = "YXNzZXRz", jurisdiction = "eu"}) assert(last().url == API .. "/accounts/" .. ACCOUNT .. "/r2/buckets?per_page=1&cursor=YXNzZXRz" and last().headers["cf-r2-jurisdiction"][1] == "eu", last().url) assert(buckets.result.buckets[1].name == "assets" and buckets.result_info.cursor == "YXNzZXRz") cloudflare.getR2Bucket({account_id = ACCOUNT, bucket_name = "assets"}) got(API .. "/accounts/" .. ACCOUNT .. "/r2/buckets/assets") assert(last().headers["cf-r2-jurisdiction"] == nil) cloudflare.getR2Bucket({account_id = ACCOUNT, bucket_name = "records", jurisdiction = "fedramp-high"}) assert(last().url == API .. "/accounts/" .. ACCOUNT .. "/r2/buckets/records" and last().headers["cf-r2-jurisdiction"][1] == "fedramp-high") -- Analytics send a fixed GraphQL query, with caller values only as variables. payload = '{"data":{"viewer":{"zones":[{"groups":[{"dimensions":{"date":"2026-10-01"},"sum":{"requests":1200,"cachedRequests":800,"bytes":5000000,' .. '"responseStatusMap":[{"edgeResponseStatus":200,"requests":1100},{"edgeResponseStatus":404,"requests":100}]},"uniq":{"uniques":90}}]}]}},"errors":null}' local traffic = cloudflare.getZoneAnalytics({zone_id = string.upper(ZONE), since = "2026-10-01", ["until"] = "2026-10-07", breakdowns = {"responseStatusMap", "countryMap"}}) local req = last() assert(req.method == "POST" and req.url == API .. "/graphql" and req.headers["Content-Type"][1] == "application/json" and req.headers.Authorization == nil) local sent = json.decode(req.body) assert(json.encode(sent.variables) == json.encode({zoneTag = ZONE, since = "2026-10-01", ["until"] = "2026-10-07"}), req.body) assert(sent.query == "query ZoneAnalytics($zoneTag: string, $since: Date, $until: Date) { viewer { zones(filter: {zoneTag: $zoneTag}) { " .. "groups: httpRequests1dGroups(limit: 100, orderBy: [date_ASC], filter: {date_geq: $since, date_leq: $until}) { dimensions { date } " .. "sum { requests cachedRequests bytes cachedBytes encryptedRequests encryptedBytes threats pageViews responseStatusMap { edgeResponseStatus requests } " .. "countryMap { clientCountryName requests bytes threats } } uniq { uniques } } } } }", sent.query) local group = traffic.data.viewer.zones[1].groups[1] assert(traffic.errors == NULL and group.sum.requests == 1200 and group.sum.responseStatusMap[2].edgeResponseStatus == 404 and group.uniq.uniques == 90) payload = '{"data":{"viewer":{"zones":[{"groups":[]}]}},"errors":null}' local hourly = cloudflare.getZoneAnalytics({zone_id = ZONE, granularity = "hour", since = "2026-10-29T00:00:00Z", ["until"] = "2026-10-30T00:00:00Z"}) sent = json.decode(last().body) assert(sent.query == "query ZoneAnalytics($zoneTag: string, $since: Time, $until: Time) { viewer { zones(filter: {zoneTag: $zoneTag}) { " .. "groups: httpRequests1hGroups(limit: 1000, orderBy: [datetime_ASC], filter: {datetime_geq: $since, datetime_lt: $until}) { dimensions { datetime } " .. "sum { requests cachedRequests bytes cachedBytes encryptedRequests encryptedBytes threats pageViews } uniq { uniques } } } } }", sent.query) assert(json.encode(hourly.data.viewer.zones[1].groups) == "[]") local analytics = {zone_id = ZONE, since = "2026-10-01", ["until"] = "2026-10-07"} local function variant(changes) local args = table.clone(analytics) for key, value in changes do args[key] = value end return function() cloudflare.getZoneAnalytics(args) end end rejected(variant({granularity = "minute"}), "granularity must be day or hour") rejected(variant({zone_id = 'x") { secret }'}), "zone_id must be a zone id") rejected(variant({since = "2026-10-01T00:00:00Z"}), "since must be a real date such as 2026-10-01") rejected(variant({granularity = "hour"}), "since must be a real whole UTC hour such as 2026-10-01T00:00:00Z") rejected(variant({since = "2026-13-01"}), "since must be a real date") rejected(variant({["until"] = "2026-02-29"}), "until must be a real date") rejected(variant({granularity = "hour", since = "2026-10-01T24:00:00Z", ["until"] = "2026-10-02T01:00:00Z"}), "since must be a real whole UTC hour") rejected(variant({granularity = "hour", since = "2026-10-01T00:00:00Z", ["until"] = "2026-10-01T10:30:00Z"}), "until must be a real whole UTC hour") rejected(variant({["until"] = "2026-09-30"}), "since must come before until") rejected(variant({granularity = "hour", since = "2026-10-01T00:00:00Z", ["until"] = "2026-10-01T00:00:00Z"}), "since must come before until") rejected(variant({breakdowns = {"countryMap { secret }"}}), "breakdowns has no item") rejected(variant({breakdowns = "countryMap"}), "breakdowns must be an array") rejected(variant({["until"] = NULL}), "until is required") rejected(variant({limit = 5}), "getZoneAnalytics has no option limit") -- A request spans at most 1000 days or hours, or 100 with breakdowns, counted across leap days. payload = '{"data":{"viewer":{"zones":[{"groups":[]}]}},"errors":null}' cloudflare.getZoneAnalytics({zone_id = ZONE, since = "2024-02-29", ["until"] = "2024-02-29", breakdowns = {"countryMap"}}) cloudflare.getZoneAnalytics({zone_id = ZONE, since = "2024-01-01", ["until"] = "2024-04-09", breakdowns = {"countryMap"}}) assert(string.find(json.decode(last().body).query, "(limit: 100,", 1, true)) cloudflare.getZoneAnalytics({zone_id = ZONE, since = "2023-12-31", ["until"] = "2026-09-25"}) cloudflare.getZoneAnalytics({zone_id = ZONE, granularity = "hour", since = "2024-02-28T00:00:00Z", ["until"] = "2024-04-09T16:00:00Z"}) rejected(variant({since = "2024-01-01", ["until"] = "2024-04-10", breakdowns = {"countryMap"}}), "since to until spans 101 days; ask for at most 100") rejected(variant({since = "2023-12-31", ["until"] = "2026-09-26"}), "since to until spans 1001 days; ask for at most 1000") rejected(variant({granularity = "hour", since = "2024-02-28T00:00:00Z", ["until"] = "2024-04-09T17:00:00Z"}), "spans 1001 hours; ask for at most 1000") rejected(function() cloudflare.getZone() end, "zone_id is required") rejected(function() cloudflare.getZone({zone_id = "../accounts"}) end, "zone_id must be a Cloudflare id or name") rejected(function() cloudflare.getDnsRecord({zone_id = ZONE, dns_record_id = ".."}) end, "dns_record_id must be a Cloudflare id or name") rejected(function() cloudflare.listDnsRecords({zone_id = ZONE, per_page = 1001}) end, "per_page must be 1 to 1000") rejected(function() cloudflare.listZones({type = {}}) end, "type must not be an empty array") rejected(function() cloudflare.listZones({account = {id = ACCOUNT}}) end, "listZones has no option account") rejected(function() cloudflare.listR2Buckets({account_id = ACCOUNT, jurisdiction = "eu\r\nX-Evil: 1"}) end, "jurisdiction must be a name such as eu") rejected(function() cloudflare.listAccounts("acme") end, "opts must be an object") end, }writes.luau
return { scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "fixture-token"}}, configure = function() requests = {} payload = '{"success":true,"errors":[],"messages":[],"result":{}}' http = {request = function(req) table.insert(requests, req) return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)}) end} end, run = function(cloudflare) local API = "https://api.cloudflare.com/client/v4" local ACCOUNT = "0123456789abcdef0123456789abcdef" local ZONE = API .. "/zones/023e105f4ecef8ad9ca31a8372d0c353" local RECORD = "372e67954025e0ba6aaa6d586b9e0b59" local function last() return requests[#requests] end local function sent(method, target, body) local req = last() assert(req.method == method and req.url == target, req.method .. " " .. req.url) assert(req.headers.Authorization == nil and req.headers.Accept[1] == "application/json") if body == nil then assert(req.body == nil and req.headers["Content-Type"] == nil, tostring(req.body)) else assert(req.headers["Content-Type"][1] == "application/json" and json.encode(json.decode(req.body)) == json.encode(body), req.body) end end local function rejected(fn, expected) local before = #requests local ok, err = pcall(fn) assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err)) assert(#requests == before, "invalid input reached Cloudflare") end local names = {} for name in cloudflare do table.insert(names, name) end table.sort(names) assert(table.concat(names, ",") == "createDnsRecord,createWorkerDeployment,deleteDnsRecord,getAccount,getDnsRecord,getPagesDeployment,getPagesDeploymentLogs,getPagesProject,getR2Bucket,getWorkerVersion,getZone,getZoneAnalytics,listAccounts,listDnsRecords,listPagesDeployments,listPagesProjects,listR2Buckets,listWorkerDeployments,listWorkerScripts,listWorkerVersions,listZones,purgeCache,rollbackPagesDeployment,updateDnsRecord", "wrong read-write surface: " .. table.concat(names, ",")) payload = '{"success":true,"errors":[],"messages":[],"result":{"id":"' .. RECORD .. '","type":"A","name":"api.example.com","content":"198.51.100.4","proxied":true,"ttl":1,"comment":null}}' local record = cloudflare.createDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", type = "A", name = "api.example.com", content = "198.51.100.4", proxied = true, ttl = 1}) sent("POST", ZONE .. "/dns_records", {type = "A", name = "api.example.com", content = "198.51.100.4", proxied = true, ttl = 1}) assert(record.result.id == RECORD) cloudflare.createDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", type = "MX", name = "example.com", content = "mx.example.net", priority = 10, tags = {"owner:mail"}}) sent("POST", ZONE .. "/dns_records", {type = "MX", name = "example.com", content = "mx.example.net", priority = 10, tags = {"owner:mail"}}) cloudflare.updateDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", dns_record_id = RECORD, content = "198.51.100.5", comment = "moved"}) sent("PATCH", ZONE .. "/dns_records/" .. RECORD, {content = "198.51.100.5", comment = "moved"}) -- An explicit JSON null clears a field. local NULL = json.decode("null") cloudflare.updateDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", dns_record_id = RECORD, comment = NULL}) assert(last().body == '{"comment":null}', last().body) payload = '{"success":true,"errors":[],"messages":[],"result":{"id":"' .. RECORD .. '"}}' assert(cloudflare.deleteDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", dns_record_id = RECORD}).result.id == RECORD) sent("DELETE", ZONE .. "/dns_records/" .. RECORD) payload = '{"success":true,"errors":[],"messages":[],"result":{"id":"023e105f4ecef8ad9ca31a8372d0c353"}}' cloudflare.purgeCache({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", files = {"https://www.example.com/app.css"}}) sent("POST", ZONE .. "/purge_cache", {files = {"https://www.example.com/app.css"}}) cloudflare.purgeCache({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", purge_everything = true}) sent("POST", ZONE .. "/purge_cache", {purge_everything = true}) local versions = {{version_id = "bcf48806-b317-4351-9ee7-36e7d557d4de", percentage = 100}} payload = '{"success":true,"errors":[],"messages":[],"result":{"id":"6d4b3a52-0000-4b6c-9c1a-1d2e3f4a5b6c","strategy":"percentage","versions":[{"version_id":"bcf48806-b317-4351-9ee7-36e7d557d4de","percentage":100}]}}' local deployment = cloudflare.createWorkerDeployment({account_id = ACCOUNT, script_name = "api", strategy = "percentage", versions = versions, annotations = {["workers/message"] = "Roll back to 41"}}) sent("POST", API .. "/accounts/" .. ACCOUNT .. "/workers/scripts/api/deployments", {strategy = "percentage", versions = versions, annotations = {["workers/message"] = "Roll back to 41"}}) assert(deployment.result.versions[1].percentage == 100) cloudflare.rollbackPagesDeployment({account_id = ACCOUNT, project_name = "site", deployment_id = "4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c"}) sent("POST", API .. "/accounts/" .. ACCOUNT .. "/pages/projects/site/deployments/4f0b3a52-3c5d-4b6c-9c1a-1d2e3f4a5b6c/rollback") -- A write answering without a body returns nil. payload = "" assert(cloudflare.deleteDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", dns_record_id = RECORD}) == nil) assert(#requests == 10) rejected(function() cloudflare.createDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", type = "A", content = "198.51.100.4"}) end, "name is required") rejected(function() cloudflare.createDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", type = "A", name = "x", id = RECORD}) end, "createDnsRecord has no option id") rejected(function() cloudflare.updateDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", dns_record_id = RECORD}) end, "updateDnsRecord needs a body field") rejected(function() cloudflare.updateDnsRecord({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", content = "x"}) end, "dns_record_id is required") rejected(function() cloudflare.purgeCache({zone_id = "023e105f4ecef8ad9ca31a8372d0c353"}) end, "purgeCache needs a body field") rejected(function() cloudflare.purgeCache({zone_id = "023e105f4ecef8ad9ca31a8372d0c353", everything = true}) end, "purgeCache has no option everything") rejected(function() cloudflare.createWorkerDeployment({account_id = ACCOUNT, script_name = "api", versions = versions}) end, "strategy is required") rejected(function() cloudflare.createWorkerDeployment({account_id = ACCOUNT, script_name = "api", strategy = "percentage", versions = versions, force = true}) end, "createWorkerDeployment has no option force") rejected(function() cloudflare.rollbackPagesDeployment({account_id = ACCOUNT, project_name = "site", deployment_id = "x", force = true}) end, "rollbackPagesDeployment has no option force") end, }