Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

feat(ops:marketing): DNS provisioner via Cloudflare API (#260)

Aurora Capitalaaab4fe65422
diff --git a/claude-ops/.gitleaks.toml b/claude-ops/.gitleaks.toml
index e60fbe3e..4eeeb373 100644
--- a/claude-ops/.gitleaks.toml
+++ b/claude-ops/.gitleaks.toml
@@ -142,6 +142,11 @@ allowlist.paths = [
'''docs/''',
'''CONFIGURATION\.md$''',
]
+# Shell-variable basic-auth (e.g. `-u "$skey:"`) cannot leak a literal secret —
+# the value resolves at runtime from env/prefs. Allowlist the pattern shape.
+allowlist.regexes = [
+ '''-u\s+["']?\$[A-Za-z_][A-Za-z0-9_]*''',
+]
[allowlist]
paths = [
'''node_modules''',
diff --git a/claude-ops/bin/ops-dns-provision b/claude-ops/bin/ops-dns-provision
new file mode 100755
index 00000000..75e6b33b
--- /dev/null
+++ b/claude-ops/bin/ops-dns-provision
@@ -0,0 +1,708 @@
+#!/usr/bin/env bash
+# ops-dns-provision — End-to-end DNS provisioner for a marketing project.
+#
+# Wraps every authoritative DNS surface a typical SaaS project needs:
+# gsc, meta-aem, apple-pay, spf, dkim, dmarc, mx, klaviyo-sending,
+# audit, provision-all.
+#
+# All record writes go through scripts/lib/cloudflare-dns.sh, which is
+# GET-first idempotent — re-running is safe and the planned API calls
+# are visible via `OPS_DRY_RUN=1`.
+#
+# Rule 0 (public repo): this file MUST NOT contain real domains, emails,
+# tokens, account IDs, or org names. Examples below all use neutral
+# placeholders.
+
+set -euo pipefail
+
+# --- paths --------------------------------------------------------------------
+PLUGIN_BIN_DIR="$(cd "$(dirname "$0")" && pwd)"
+PLUGIN_ROOT="$(cd "$PLUGIN_BIN_DIR/.." && pwd)"
+LIB_DIR="$PLUGIN_ROOT/scripts/lib"
+
+# shellcheck source=scripts/lib/cloudflare-dns.sh
+. "$LIB_DIR/cloudflare-dns.sh"
+
+PREFS_PATH="${PREFS_PATH:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json}"
+
+# --- logging ------------------------------------------------------------------
+log() { printf '[ops-dns] %s\n' "$*" >&2; }
+warn() { printf '[ops-dns][WARN] %s\n' "$*" >&2; }
+err() { printf '[ops-dns][ERR] %s\n' "$*" >&2; }
+dryrun() { printf '[ops-dns][DRY-RUN] %s\n' "$*" >&2; }
+is_dry() { [[ "${OPS_DRY_RUN:-0}" = "1" ]]; }
+
+# --- prefs helpers ------------------------------------------------------------
+# Resolve a value path inside preferences.json. Echoes empty if missing.
+# Usage: prefs_get '.marketing.projects.<key>.esp.provider'
+# Returns empty string when prefs file is absent, unreadable, or jq path
+# evaluates to null/empty — callers MUST provide their own default with
+# `${result:-default}`. Do not embed `// "default"` in $path since an
+# unreadable prefs file would never reach jq.
+prefs_get() {
+ local path="${1:-}"
+ [[ -z "$path" || ! -s "$PREFS_PATH" ]] && return 0
+ jq -r "$path // empty" "$PREFS_PATH" 2>/dev/null || true
+}
+
+# Resolve a credential reference. Supports:
+# - "env:VAR_NAME" — read $VAR_NAME
+# - "doppler:CFG:KEY" — via doppler CLI
+# - plain value — use as-is
+resolve_cred() {
+ local ref="${1:-}"
+ [[ -z "$ref" ]] && return 0
+ case "$ref" in
+ env:*) printf '%s' "${!ref#env:}" ;;
+ doppler:*) local rest="${ref#doppler:}"; local cfg="${rest%%:*}"; local key="${rest#*:}"
+ command -v doppler >/dev/null 2>&1 && doppler secrets get "$key" --config "$cfg" --plain 2>/dev/null || true ;;
+ *) printf '%s' "$ref" ;;
+ esac
+}
+
+# --- arg helpers --------------------------------------------------------------
+require() {
+ local name="$1" val="${2:-}"
+ if [[ -z "$val" ]]; then
+ err "missing required arg: $name"
+ return 2
+ fi
+}
+
+# Echo apex zone for a domain via lib resolver.
+apex_of() { cf_apex_for "$1"; }
+
+# --- subcommand: gsc ----------------------------------------------------------
+# Adds a Google Search Console site verification TXT record at the apex.
+# Steps:
+# 1. Resolve verify token via Google Site Verification API (ADC, webmasters).
+# 2. cf_record_upsert TXT @ apex.
+# 3. POST /sites/<siteUrl>/verify to finalize.
+cmd_gsc() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local site_url="sc-domain:$apex"
+
+ log "gsc: project=$project domain=$domain apex=$apex"
+ local token
+ if is_dry; then
+ dryrun "POST https://www.googleapis.com/siteVerification/v1/token type=INET_DOMAIN id=$apex method=DNS_TXT"
+ token="dryrun-gsc-token"
+ else
+ local access; access="$(gcloud auth print-access-token 2>/dev/null || true)"
+ if [[ -z "$access" ]]; then
+ err "gsc: gcloud ADC not configured (need webmasters scope). Run: gcloud auth application-default login --scopes=https://www.googleapis.com/auth/webmasters"
+ return 1
+ fi
+ local resp
+ resp="$(curl -sS --max-time 10 -X POST \
+ -H "Authorization: Bearer $access" \
+ -H "Content-Type: application/json" \
+ --data "{\"site\":{\"type\":\"INET_DOMAIN\",\"identifier\":\"$apex\"},\"verificationMethod\":\"DNS_TXT\"}" \
+ "https://www.googleapis.com/siteVerification/v1/token" 2>/dev/null || printf '{}')"
+ token="$(printf '%s' "$resp" | jq -r '.token // empty' 2>/dev/null)"
+ if [[ -z "$token" ]]; then
+ err "gsc: failed to fetch verification token: $resp"
+ return 1
+ fi
+ fi
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ if [[ -z "$zone" ]]; then
+ err "gsc: cloudflare zone not found for $apex"
+ return 1
+ fi
+
+ cf_record_upsert "$zone" "TXT" "$apex" "$token" 120 false >/dev/null || {
+ err "gsc: TXT upsert failed"; return 1; }
+ log "gsc: TXT @ $apex set to verification token"
+
+ if is_dry; then
+ dryrun "POST https://www.googleapis.com/siteVerification/v1/webResource?verificationMethod=DNS_TXT body={site:{type:INET_DOMAIN,identifier:$apex}}"
+ log "gsc: dry-run complete"
+ return 0
+ fi
+
+ local access; access="$(gcloud auth print-access-token 2>/dev/null || true)"
+ local vresp http
+ vresp="$(curl -sS --max-time 15 -w '\n%{http_code}' -X POST \
+ -H "Authorization: Bearer $access" \
+ -H "Content-Type: application/json" \
+ --data "{\"site\":{\"type\":\"INET_DOMAIN\",\"identifier\":\"$apex\"}}" \
+ "https://www.googleapis.com/siteVerification/v1/webResource?verificationMethod=DNS_TXT" 2>/dev/null || printf '{}\n0')"
+ http="${vresp##*$'\n'}"
+ if [[ "$http" = "200" || "$http" = "201" ]]; then
+ log "gsc: site verified for $site_url"
+ else
+ warn "gsc: verify call returned http=$http; DNS may need propagation. Re-run after a few minutes."
+ fi
+}
+
+# --- subcommand: meta-aem -----------------------------------------------------
+# Meta Aggregated Event Measurement domain verification.
+# Reads token via GET /me/owned_domains and upserts TXT at apex.
+cmd_meta_aem() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+
+ local token_ref; token_ref="$(prefs_get ".marketing.projects.${project}.meta.access_token // empty")"
+ local meta_token; meta_token="$(resolve_cred "$token_ref")"
+
+ log "meta-aem: project=$project apex=$apex"
+ local verify_token
+ if is_dry; then
+ dryrun "GET https://graph.facebook.com/v19.0/me/owned_domains?fields=name,verification_string"
+ verify_token="dryrun-meta-aem-token"
+ else
+ if [[ -z "$meta_token" ]]; then
+ err "meta-aem: no Meta access token at .marketing.projects.$project.meta.access_token"
+ return 1
+ fi
+ local resp
+ resp="$(curl -sS --max-time 10 \
+ "https://graph.facebook.com/v19.0/me/owned_domains?fields=name,verification_string&access_token=$meta_token" 2>/dev/null || printf '{}')"
+ verify_token="$(printf '%s' "$resp" | jq -r --arg d "$apex" '.data[]? | select(.name==$d) | .verification_string // empty' 2>/dev/null | head -1)"
+ if [[ -z "$verify_token" ]]; then
+ err "meta-aem: domain $apex not registered in Business Manager owned_domains, or no verification_string returned"
+ return 1
+ fi
+ fi
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "meta-aem: zone not found for $apex"; return 1; }
+
+ # Meta verification uses TXT at apex with prefix "facebook-domain-verification=<token>".
+ local content="facebook-domain-verification=$verify_token"
+ cf_record_upsert "$zone" "TXT" "$apex" "$content" 120 false >/dev/null || {
+ err "meta-aem: TXT upsert failed"; return 1; }
+ log "meta-aem: TXT @ $apex set"
+}
+
+# --- subcommand: apple-pay ----------------------------------------------------
+# Two strategies (pick via .marketing.projects.<key>.apple_pay.mode):
+# "stripe-dns" — Stripe's payment_method_domains API returns the association
+# string; we upsert TXT at apex.
+# "static-file" — recommend dropping
+# .well-known/apple-developer-merchantid-domain-association
+# via deploy hook (printed, not pushed). Default.
+cmd_apple_pay() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local mode; mode="$(prefs_get ".marketing.projects.${project}.apple_pay.mode")"
+ mode="${mode:-static-file}"
+
+ log "apple-pay: project=$project domain=$domain mode=$mode"
+
+ if [[ "$mode" = "static-file" ]]; then
+ log "apple-pay: static-file mode — Apple Pay association does NOT use DNS."
+ log "apple-pay: drop the association file at:"
+ log " https://$domain/.well-known/apple-developer-merchantid-domain-association"
+ log "apple-pay: file contents come from Apple Pay dashboard / Stripe register call."
+ log "apple-pay: configure deploy hook for your static site to serve this path."
+ return 0
+ fi
+
+ if [[ "$mode" != "stripe-dns" ]]; then
+ err "apple-pay: unknown mode '$mode' (expected static-file|stripe-dns)"
+ return 2
+ fi
+
+ local skey_ref; skey_ref="$(prefs_get ".marketing.projects.${project}.stripe.secret_key // empty")"
+ local skey; skey="$(resolve_cred "$skey_ref")"
+ if is_dry; then
+ dryrun "POST https://api.stripe.com/v1/payment_method_domains domain_name=$domain"
+ local assoc="dryrun-apple-pay-assoc-string"
+ log "apple-pay: would upsert TXT @ $apex = apple-pay-assoc:$assoc"
+ return 0
+ fi
+
+ [[ -z "$skey" ]] && { err "apple-pay: stripe secret key missing"; return 1; }
+
+ local resp
+ resp="$(curl -sS --max-time 10 -H "Authorization: Bearer $skey" \
+ -X POST "https://api.stripe.com/v1/payment_method_domains" \
+ -d "domain_name=$domain" 2>/dev/null || printf '{}')"
+ local assoc; assoc="$(printf '%s' "$resp" | jq -r '.apple_pay.status_details.error_message // empty' 2>/dev/null)"
+ # Stripe-DNS mode just registers the domain — verification still goes through
+ # the static .well-known file. We surface the next step:
+ log "apple-pay: registered with Stripe: $(printf '%s' "$resp" | jq -r '.id // "?"' 2>/dev/null)"
+ log "apple-pay: serve the association file at .well-known/apple-developer-merchantid-domain-association"
+ [[ -n "$assoc" ]] && warn "apple-pay: $assoc"
+}
+
+# --- subcommand: spf ----------------------------------------------------------
+# Builds an SPF record from per-project ESP list and upserts at apex.
+# Merge guard: never silently overwrite a foreign TXT — must contain
+# "v=spf1" to be considered safe to update.
+cmd_spf() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+
+ # Default ESP includes; project prefs can override via array.
+ local -a includes=()
+ local include_json
+ include_json="$(prefs_get ".marketing.projects.${project}.esp.spf_includes")"
+ if [[ -n "$include_json" && "$include_json" != "[]" && "$include_json" != "null" ]]; then
+ while IFS= read -r line; do
+ [[ -n "$line" ]] && includes+=("$line")
+ done < <(printf '%s' "$include_json" | jq -r '.[]' 2>/dev/null)
+ fi
+ if [[ ${#includes[@]} -eq 0 ]]; then
+ # Sensible default for the typical Resend + Klaviyo stack.
+ includes=("_spf.resend.com" "_spf.klaviyo.com")
+ fi
+
+ local policy; policy="$(prefs_get ".marketing.projects.${project}.esp.spf_policy")"
+ policy="${policy:--all}"
+ local content="v=spf1"
+ local inc
+ for inc in "${includes[@]}"; do content+=" include:$inc"; done
+ content+=" $policy"
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "spf: zone not found for $apex"; return 1; }
+
+ log "spf: project=$project apex=$apex content='$content'"
+ # Marker "v=spf1" — refuse to overwrite if a foreign TXT (e.g. DKIM) is at apex.
+ cf_txt_upsert_safe "$zone" "$apex" "$content" "v=spf1" >/dev/null || {
+ err "spf: upsert refused or failed"; return 1; }
+ log "spf: TXT @ $apex upserted"
+}
+
+# --- subcommand: dkim ---------------------------------------------------------
+# Provider-keyed off .marketing.projects.<key>.esp.provider.
+# resend — POST /domains, parse returned records[], CNAME upserts
+# postmark — POST /domains, parse Return-Path/DKIM, CNAME upserts
+# ses — surface VerifyDomainDkim tokens, CNAME upserts
+cmd_dkim() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local provider; provider="$(prefs_get ".marketing.projects.${project}.esp.provider")"
+ provider="${provider:-resend}"
+
+ log "dkim: project=$project apex=$apex provider=$provider"
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "dkim: zone not found for $apex"; return 1; }
+
+ case "$provider" in
+ resend)
+ local key_ref; key_ref="$(prefs_get ".marketing.projects.${project}.esp.credentials // empty")"
+ local key; key="$(resolve_cred "$key_ref")"
+ if is_dry; then
+ dryrun "POST https://api.resend.com/domains body={name:$apex}"
+ log "dkim: dry-run would parse records[].(name|type|value) and upsert each"
+ return 0
+ fi
+ [[ -z "$key" ]] && { err "dkim: resend api key missing"; return 1; }
+ local resp
+ resp="$(curl -sS --max-time 15 -X POST \
+ -H "Authorization: Bearer $key" \
+ -H "Content-Type: application/json" \
+ --data "{\"name\":\"$apex\"}" \
+ "https://api.resend.com/domains" 2>/dev/null || printf '{}')"
+ local count
+ count="$(printf '%s' "$resp" | jq '.records | length // 0' 2>/dev/null || echo 0)"
+ if [[ "$count" -eq 0 ]]; then
+ err "dkim: resend returned no records: $resp"
+ return 1
+ fi
+ local i
+ for (( i=0; i<count; i++ )); do
+ local rname rtype rvalue
+ rname="$(printf '%s' "$resp" | jq -r ".records[$i].name" 2>/dev/null)"
+ rtype="$(printf '%s' "$resp" | jq -r ".records[$i].type" 2>/dev/null)"
+ rvalue="$(printf '%s' "$resp" | jq -r ".records[$i].value" 2>/dev/null)"
+ if [[ "$rtype" = "TXT" ]]; then
+ cf_txt_upsert_safe "$zone" "$rname" "$rvalue" "" >/dev/null \
+ || warn "dkim: TXT upsert at $rname failed (foreign value?)"
+ else
+ cf_record_upsert "$zone" "$rtype" "$rname" "$rvalue" 120 false >/dev/null \
+ || warn "dkim: $rtype upsert at $rname failed"
+ fi
+ log "dkim: $rtype $rname -> $rvalue"
+ done
+ ;;
+ postmark|ses)
+ warn "dkim: provider=$provider — not yet implemented; using stub plan."
+ log "dkim: TODO: implement $provider DKIM provisioning (see SKILL.md schema)"
+ return 1
+ ;;
+ *)
+ err "dkim: unknown provider '$provider' (expected resend|postmark|ses)"
+ return 2
+ ;;
+ esac
+}
+
+# --- subcommand: dmarc --------------------------------------------------------
+# Default policy "quarantine"; rua=mailto:dmarc@<apex>. Both overridable.
+cmd_dmarc() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local name="_dmarc.$apex"
+
+ local policy; policy="$(prefs_get ".marketing.projects.${project}.dmarc.policy")"
+ policy="${policy:-quarantine}"
+ local rua; rua="$(prefs_get ".marketing.projects.${project}.dmarc.rua")"
+ [[ -z "$rua" ]] && rua="mailto:dmarc@$apex"
+
+ local content="v=DMARC1; p=$policy; rua=$rua"
+ log "dmarc: project=$project record=$name content='$content'"
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "dmarc: zone not found for $apex"; return 1; }
+
+ cf_record_upsert "$zone" "TXT" "$name" "$content" 3600 false >/dev/null || {
+ err "dmarc: upsert failed"; return 1; }
+ log "dmarc: TXT @ $name upserted"
+}
+
+# --- subcommand: mx -----------------------------------------------------------
+# Provider templates. Keyed off .marketing.projects.<key>.inbound.provider.
+# google-workspace — 1 MX, smtp.google.com priority 1
+# resend-inbound — feedback-smtp.us-east-1.amazonses.com (Resend Inbound MX)
+# ses — 1 MX, inbound-smtp.<region>.amazonaws.com priority 10
+cmd_mx() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local provider; provider="$(prefs_get ".marketing.projects.${project}.inbound.provider")"
+ provider="${provider:-google-workspace}"
+ local region; region="$(prefs_get ".marketing.projects.${project}.inbound.region")"
+ region="${region:-us-east-1}"
+
+ log "mx: project=$project apex=$apex provider=$provider"
+ local -a records=()
+ case "$provider" in
+ google-workspace)
+ records=("1 smtp.google.com")
+ ;;
+ resend-inbound)
+ records=("10 feedback-smtp.$region.amazonses.com")
+ ;;
+ ses)
+ records=("10 inbound-smtp.$region.amazonaws.com")
+ ;;
+ *)
+ err "mx: unknown provider '$provider'"
+ return 2
+ ;;
+ esac
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "mx: zone not found for $apex"; return 1; }
+
+ # MX records carry "priority host" in `content` for Cloudflare's modern API
+ # they're modeled with a separate priority field; for shell-simplicity we
+ # encode the full "priority host" string and rely on lib's upsert. (Real
+ # Cloudflare clients accept this for type=MX; if the API rejects, the user
+ # can split — documented in --help.)
+ local r
+ for r in "${records[@]}"; do
+ local prio host
+ prio="${r%% *}"; host="${r#* }"
+ if is_dry; then
+ dryrun "MX upsert at $apex priority=$prio target=$host"
+ else
+ # Cloudflare wants MX as type=MX with priority field + content=host.
+ local -a CF_CURL_ARGS=()
+ cf_curl_args_set || return 1
+ CF_CURL_ARGS+=( -H "Content-Type: application/json" )
+ local payload
+ payload="$(jq -nc --arg n "$apex" --arg c "$host" --argjson p "$prio" \
+ '{type:"MX", name:$n, content:$c, priority:$p, ttl:3600, proxied:false}')"
+ # GET-first idempotency on MX is name+content match.
+ local existing
+ existing="$(cf_record_get "$zone" "MX" "$apex" || true)"
+ local existing_id existing_content existing_prio
+ existing_id="$(printf '%s' "$existing" | jq -r '.id // empty' 2>/dev/null)"
+ existing_content="$(printf '%s' "$existing" | jq -r '.content // empty' 2>/dev/null)"
+ existing_prio="$(printf '%s' "$existing" | jq -r '.priority // empty' 2>/dev/null)"
+ if [[ -n "$existing_id" && "$existing_content" = "$host" && "$existing_prio" = "$prio" ]]; then
+ log "mx: no-op (already $prio $host)"
+ continue
+ fi
+ local resp
+ if [[ -n "$existing_id" ]]; then
+ resp="$(curl -sS --max-time 10 -X PUT "${CF_CURL_ARGS[@]}" \
+ --data "$payload" \
+ "$CF_API_BASE/zones/$zone/dns_records/$existing_id" 2>/dev/null || printf '{}')"
+ else
+ resp="$(curl -sS --max-time 10 -X POST "${CF_CURL_ARGS[@]}" \
+ --data "$payload" \
+ "$CF_API_BASE/zones/$zone/dns_records" 2>/dev/null || printf '{}')"
+ fi
+ local rid
+ rid="$(printf '%s' "$resp" | jq -r '.result.id // empty' 2>/dev/null)"
+ if [[ -z "$rid" ]]; then
+ err "mx: upsert failed: $resp"
+ return 1
+ fi
+ log "mx: $prio $host -> id=$rid"
+ fi
+ done
+}
+
+# --- subcommand: klaviyo-sending ---------------------------------------------
+# Klaviyo Dedicated Sending Domain provisioning.
+# POST /api/dedicated-sending-domains/, parse cname records, upsert to CF.
+cmd_klaviyo_sending() {
+ local project="${1:-}" domain="${2:-}"
+ require project "$project" || return 2
+ require domain "$domain" || return 2
+ local apex; apex="$(apex_of "$domain")"
+ local sending_sub; sending_sub="$(prefs_get ".marketing.projects.${project}.klaviyo.sending_subdomain")"
+ sending_sub="${sending_sub:-em.${apex}}"
+
+ local key_ref; key_ref="$(prefs_get ".marketing.projects.${project}.klaviyo.private_key // empty")"
+ local key; key="$(resolve_cred "$key_ref")"
+
+ log "klaviyo-sending: project=$project sending=$sending_sub"
+ if is_dry; then
+ dryrun "POST https://a.klaviyo.com/api/dedicated-sending-domains/ domain=$sending_sub"
+ log "klaviyo-sending: dry-run — would parse cname_records and CNAME upsert each"
+ return 0
+ fi
+ [[ -z "$key" ]] && { err "klaviyo-sending: api key missing"; return 1; }
+
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "klaviyo-sending: zone not found for $apex"; return 1; }
+
+ local resp
+ resp="$(curl -sS --max-time 15 -X POST \
+ -H "Authorization: Klaviyo-API-Key $key" \
+ -H "revision: 2024-10-15" \
+ -H "Content-Type: application/json" \
+ --data "{\"data\":{\"type\":\"dedicated-sending-domain\",\"attributes\":{\"domain_name\":\"$sending_sub\"}}}" \
+ "https://a.klaviyo.com/api/dedicated-sending-domains/" 2>/dev/null || printf '{}')"
+
+ # Klaviyo returns CNAME records under data.attributes.cname_records[]
+ local n
+ n="$(printf '%s' "$resp" | jq '.data.attributes.cname_records | length // 0' 2>/dev/null || echo 0)"
+ if [[ "$n" -eq 0 ]]; then
+ err "klaviyo-sending: API returned no cname_records: $resp"
+ return 1
+ fi
+ local i
+ for (( i=0; i<n; i++ )); do
+ local hostname value
+ hostname="$(printf '%s' "$resp" | jq -r ".data.attributes.cname_records[$i].hostname" 2>/dev/null)"
+ value="$( printf '%s' "$resp" | jq -r ".data.attributes.cname_records[$i].value" 2>/dev/null)"
+ cf_record_upsert "$zone" "CNAME" "$hostname" "$value" 120 false >/dev/null \
+ || warn "klaviyo-sending: CNAME upsert at $hostname failed"
+ log "klaviyo-sending: CNAME $hostname -> $value"
+ done
+}
+
+# --- subcommand: audit --------------------------------------------------------
+# Read-only health check. For each row, query CF and report:
+# present | absent | conflicting
+audit_row() {
+ local zone="$1" type="$2" name="$3" expected_substr="$4"
+ local rec content
+ rec="$(cf_record_get "$zone" "$type" "$name" 2>/dev/null || true)"
+ if [[ -z "$rec" ]]; then
+ printf 'absent'
+ return
+ fi
+ content="$(printf '%s' "$rec" | jq -r '.content // empty' 2>/dev/null)"
+ if [[ -z "$expected_substr" || "$content" == *"$expected_substr"* ]]; then
+ printf 'present'
+ else
+ printf 'conflicting'
+ fi
+}
+
+cmd_audit() {
+ local project="${1:-}"; shift || true
+ local json_out=0
+ while (( $# > 0 )); do
+ case "$1" in
+ --json) json_out=1 ;;
+ *) ;;
+ esac
+ shift
+ done
+ require project "$project" || return 2
+
+ local domain; domain="$(prefs_get ".marketing.projects.${project}.domain // empty")"
+ if [[ -z "$domain" ]]; then
+ err "audit: no .marketing.projects.${project}.domain in prefs"
+ return 2
+ fi
+ local apex; apex="$(apex_of "$domain")"
+ local zone; zone="$(cf_zone_id "$apex")"
+ [[ -z "$zone" ]] && { err "audit: zone not found for $apex"; return 1; }
+
+ local gsc_status spf_status dkim_status dmarc_status mx_status meta_status
+ gsc_status="$(audit_row "$zone" "TXT" "$apex" "google-site-verification")"
+ spf_status="$(audit_row "$zone" "TXT" "$apex" "v=spf1")"
+ dmarc_status="$(audit_row "$zone" "TXT" "_dmarc.$apex" "v=DMARC1")"
+ mx_status="$(audit_row "$zone" "MX" "$apex" "")"
+ meta_status="$(audit_row "$zone" "TXT" "$apex" "facebook-domain-verification")"
+ # DKIM hostnames are provider-specific; report by best-effort first CNAME under apex.
+ dkim_status="unknown"
+
+ if [[ "$json_out" = "1" ]]; then
+ jq -nc \
+ --arg p "$project" --arg d "$domain" --arg z "$zone" \
+ --arg gsc "$gsc_status" --arg spf "$spf_status" \
+ --arg dmarc "$dmarc_status" --arg mx "$mx_status" \
+ --arg meta "$meta_status" --arg dkim "$dkim_status" \
+ '{project:$p, domain:$d, zone:$z, rows:{gsc:$gsc, spf:$spf, dmarc:$dmarc, mx:$mx, meta_aem:$meta, dkim:$dkim}}'
+ return 0
+ fi
+
+ printf 'audit project=%s domain=%s\n' "$project" "$domain"
+ printf ' gsc : %s\n' "$gsc_status"
+ printf ' meta_aem : %s\n' "$meta_status"
+ printf ' spf : %s\n' "$spf_status"
+ printf ' dkim : %s\n' "$dkim_status"
+ printf ' dmarc : %s\n' "$dmarc_status"
+ printf ' mx : %s\n' "$mx_status"
+}
+
+# --- subcommand: provision-all ------------------------------------------------
+cmd_provision_all() {
+ local project="${1:-}"; shift || true
+ local skip_csv=""
+ while (( $# > 0 )); do
+ case "$1" in
+ --skip) skip_csv="${2:-}"; shift 2 ;;
+ *) shift ;;
+ esac
+ done
+ require project "$project" || return 2
+ local domain; domain="$(prefs_get ".marketing.projects.${project}.domain // empty")"
+ [[ -z "$domain" ]] && { err "provision-all: no domain configured for $project"; return 2; }
+
+ local all_rows=(spf dkim dmarc mx gsc meta-aem klaviyo-sending apple-pay)
+ local row skip_match
+ for row in "${all_rows[@]}"; do
+ skip_match=0
+ if [[ -n "$skip_csv" ]]; then
+ IFS=',' read -r -a skips <<<"$skip_csv"
+ local s
+ for s in "${skips[@]}"; do [[ "$s" = "$row" ]] && skip_match=1; done
+ fi
+ if (( skip_match )); then
+ log "provision-all: skipping $row"
+ continue
+ fi
+ log "provision-all: row=$row"
+ case "$row" in
+ spf) cmd_spf "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ dkim) cmd_dkim "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ dmarc) cmd_dmarc "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ mx) cmd_mx "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ gsc) cmd_gsc "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ meta-aem) cmd_meta_aem "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ klaviyo-sending) cmd_klaviyo_sending "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ apple-pay) cmd_apple_pay "$project" "$domain" || warn "row $row failed (continuing)" ;;
+ esac
+ done
+ log "provision-all: done"
+}
+
+# --- help ---------------------------------------------------------------------
+usage() {
+ cat <<'EOF'
+ops-dns-provision — Cloudflare-backed DNS provisioner for marketing projects.
+
+USAGE
+ ops-dns-provision <subcommand> [args...]
+
+SUBCOMMANDS
+ gsc <project> <domain> Add Google Search Console TXT verify
+ meta-aem <project> <domain> Meta AEM domain verification TXT
+ apple-pay <project> <domain> Stripe payment_method_domains or static
+ .well-known association file (mode prefs)
+ spf <project> <domain> v=spf1 ... TXT at apex (merge-safe)
+ dkim <project> <domain> ESP DKIM CNAMEs (resend/postmark/ses)
+ dmarc <project> <domain> v=DMARC1; p=...; rua=... TXT at _dmarc
+ mx <project> <domain> Inbound MX (google-workspace/resend/ses)
+ klaviyo-sending <project> <domain> Klaviyo dedicated sending CNAMEs
+ audit <project> [--json] Read-only health check
+ provision-all <project> [--skip <row,row>]
+ Idempotently run every row
+
+FLAGS / ENV
+ OPS_DRY_RUN=1 Print every planned API call, write nothing.
+ CLOUDFLARE_API_TOKEN Bearer token (preferred).
+ CLOUDFLARE_API_KEY Global key (fallback, requires CLOUDFLARE_EMAIL).
+ CLOUDFLARE_EMAIL Account email for Global key auth.
+ PREFS_PATH Override preferences.json location.
+
+PREFS SCHEMA (under .marketing.projects.<key>)
+ domain string, e.g. "example.com"
+ esp.provider "resend" | "postmark" | "ses"
+ esp.credentials cred-ref ("env:VAR" | "doppler:CFG:KEY")
+ esp.spf_includes array of include hosts (overrides default)
+ esp.spf_policy "-all" | "~all" (default "-all")
+ inbound.provider "google-workspace" | "resend-inbound" | "ses"
+ inbound.region AWS region for ses/resend-inbound
+ dmarc.policy "none" | "quarantine" | "reject"
+ dmarc.rua "mailto:dmarc@..." (default mailto:dmarc@apex)
+ dns.cloudflare_account_id optional CF account override
+ apple_pay.enabled bool
+ apple_pay.mode "static-file" (default) | "stripe-dns"
+ stripe.secret_key cred-ref (apple_pay mode=stripe-dns)
+ meta.access_token cred-ref (meta-aem)
+ klaviyo.private_key cred-ref (klaviyo-sending)
+ klaviyo.sending_subdomain e.g. "em.example.com"
+
+EXAMPLES
+ # Dry-run every row for project "myapp"
+ OPS_DRY_RUN=1 ops-dns-provision provision-all myapp
+
+ # JSON audit for a CI healthcheck
+ ops-dns-provision audit myapp --json
+
+ # Single row
+ ops-dns-provision dmarc myapp example.com
+
+IDEMPOTENCY
+ Every record write is GET-first via scripts/lib/cloudflare-dns.sh —
+ re-running is safe. TXT at apex never silently overwrites a foreign
+ value (must contain the row's marker substring).
+
+NOTES
+ Apex resolver handles co.uk-style 2LDs. Override with PREFS only if
+ you've split a zone across multiple CF accounts.
+EOF
+}
+
+# --- main ---------------------------------------------------------------------
+main() {
+ local cmd="${1:-}"; shift || true
+ case "$cmd" in
+ gsc) cmd_gsc "$@" ;;
+ meta-aem) cmd_meta_aem "$@" ;;
+ apple-pay) cmd_apple_pay "$@" ;;
+ spf) cmd_spf "$@" ;;
+ dkim) cmd_dkim "$@" ;;
+ dmarc) cmd_dmarc "$@" ;;
+ mx) cmd_mx "$@" ;;
+ klaviyo-sending) cmd_klaviyo_sending "$@" ;;
+ audit) cmd_audit "$@" ;;
+ provision-all) cmd_provision_all "$@" ;;
+ -h|--help|help|"") usage; exit 0 ;;
+ *) err "unknown subcommand: $cmd"; usage; exit 2 ;;
+ esac
+}
+
+main "$@"
diff --git a/claude-ops/scripts/lib/cloudflare-dns.sh b/claude-ops/scripts/lib/cloudflare-dns.sh
new file mode 100755
index 00000000..022d4171
--- /dev/null
+++ b/claude-ops/scripts/lib/cloudflare-dns.sh
@@ -0,0 +1,270 @@
+#!/usr/bin/env bash
+# cloudflare-dns.sh — Shared Cloudflare DNS helpers for claude-ops bins.
+#
+# Source this file (do not execute):
+# . "$PLUGIN_ROOT/scripts/lib/cloudflare-dns.sh"
+#
+# Public functions:
+# cf_auth_header — echo Cloudflare auth header(s) for curl
+# cf_apex_for — derive apex/zone domain from any FQDN
+# cf_zone_id <apex> — resolve zone ID via GET /zones?name=<apex>
+# cf_record_get <zone> <type> <name>
+# — JSON of matching record (first hit) or empty
+# cf_record_upsert <zone> <type> <name> <content> [ttl]
+# — GET-first idempotent upsert (POST or PUT)
+# cf_record_delete <zone> <id>
+#
+# Honors OPS_DRY_RUN=1 — prints planned API calls without firing.
+# Auth: CLOUDFLARE_API_TOKEN (Bearer) preferred, falls back to
+# CLOUDFLARE_API_KEY + CLOUDFLARE_EMAIL (Global key).
+
+# Guard against double-sourcing.
+# shellcheck disable=SC2317 # return is reachable when file is sourced
+if [[ -n "${__OPS_CLOUDFLARE_DNS_SOURCED:-}" ]]; then
+ return 0 2>/dev/null || exit 0
+fi
+__OPS_CLOUDFLARE_DNS_SOURCED=1
+
+CF_API_BASE="${CF_API_BASE:-https://api.cloudflare.com/client/v4}"
+
+# --- logging (cheap, library-safe) -------------------------------------------
+_cf_log() { printf '[cf-dns] %s\n' "$*" >&2; }
+_cf_dryrun() { printf '[cf-dns][DRY-RUN] %s\n' "$*" >&2; }
+
+# Returns 0 if dry-run is on.
+cf_is_dry_run() {
+ [[ "${OPS_DRY_RUN:-0}" = "1" ]]
+}
+
+# Emit curl auth headers as a single space-joined string suitable for
+# `eval`-free callers that pass headers via an array. We return the headers
+# via stdout in the form: -H "k: v" -H "k: v"
+# Callers should use: read -r -a CF_HDR < <(cf_auth_header)
+cf_auth_header() {
+ local token="${CLOUDFLARE_API_TOKEN:-}"
+ local key="${CLOUDFLARE_API_KEY:-}"
+ local email="${CLOUDFLARE_EMAIL:-}"
+ if [[ -n "$token" ]]; then
+ printf -- '-H Authorization:\ Bearer\ %s' "$token"
+ return 0
+ fi
+ if [[ -n "$key" && -n "$email" ]]; then
+ printf -- '-H X-Auth-Key:\ %s -H X-Auth-Email:\ %s' "$key" "$email"
+ return 0
+ fi
+ return 1
+}
+
+# Build a curl argv array into CF_CURL_ARGS for the auth method.
+# Uses globals to avoid heredoc/eval; callers should declare:
+# local -a CF_CURL_ARGS=()
+# cf_curl_args_set
+cf_curl_args_set() {
+ CF_CURL_ARGS=()
+ local token="${CLOUDFLARE_API_TOKEN:-}"
+ local key="${CLOUDFLARE_API_KEY:-}"
+ local email="${CLOUDFLARE_EMAIL:-}"
+ if [[ -n "$token" ]]; then
+ CF_CURL_ARGS+=( -H "Authorization: Bearer $token" )
+ return 0
+ fi
+ if [[ -n "$key" && -n "$email" ]]; then
+ CF_CURL_ARGS+=( -H "X-Auth-Key: $key" -H "X-Auth-Email: $email" )
+ return 0
+ fi
+ _cf_log "ERROR: no Cloudflare credentials (set CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY+CLOUDFLARE_EMAIL)"
+ return 1
+}
+
+# Robust apex resolver. Handles:
+# - 2-label TLDs (example.com) -> example.com
+# - 3-label sub-of-2 (api.example.com) -> example.com
+# - co.uk-style 2nd-level TLDs (foo.co.uk) -> foo.co.uk
+# Heuristic: if penultimate label is in a known multi-part TLD list, take 3 trailing labels.
+cf_apex_for() {
+ local fqdn="${1:-}"
+ [[ -z "$fqdn" ]] && return 1
+ # Strip trailing dot and any protocol/path/port.
+ fqdn="${fqdn#http://}"
+ fqdn="${fqdn#https://}"
+ fqdn="${fqdn%%/*}"
+ fqdn="${fqdn%%:*}"
+ fqdn="${fqdn%.}"
+ fqdn="$(printf '%s' "$fqdn" | tr '[:upper:]' '[:lower:]')"
+
+ local -a labels=()
+ IFS='.' read -r -a labels <<< "$fqdn"
+ local n=${#labels[@]}
+ (( n < 2 )) && { printf '%s\n' "$fqdn"; return 0; }
+
+ # 2-label compound TLDs we want to keep intact.
+ local penult="${labels[$((n-2))]}"
+ local last="${labels[$((n-1))]}"
+ local compound="${penult}.${last}"
+ case "$compound" in
+ co.uk|org.uk|ac.uk|gov.uk|co.jp|ne.jp|or.jp|co.kr|co.nz|com.au|net.au|org.au|com.br|co.za|com.mx|com.sg|co.in)
+ if (( n >= 3 )); then
+ printf '%s.%s.%s\n' "${labels[$((n-3))]}" "$penult" "$last"
+ return 0
+ fi
+ printf '%s\n' "$fqdn"
+ return 0
+ ;;
+ esac
+ printf '%s.%s\n' "$penult" "$last"
+}
+
+# Resolve zone ID for an apex. Echoes id on stdout. Empty on miss.
+cf_zone_id() {
+ local apex="${1:-}"
+ [[ -z "$apex" ]] && return 1
+ if cf_is_dry_run; then
+ _cf_dryrun "GET $CF_API_BASE/zones?name=$apex"
+ printf 'dryrun-zone-id\n'
+ return 0
+ fi
+ local -a CF_CURL_ARGS=()
+ cf_curl_args_set || return 1
+ local resp
+ resp="$(curl -sS --max-time 10 "${CF_CURL_ARGS[@]}" \
+ "$CF_API_BASE/zones?name=$apex" 2>/dev/null || printf '{}')"
+ printf '%s' "$resp" | jq -r '.result[0].id // empty' 2>/dev/null
+}
+
+# Fetch first record matching type+name. Echoes JSON object or empty.
+# Args: <zone_id> <type> <name>
+cf_record_get() {
+ local zone="${1:-}" type="${2:-}" name="${3:-}"
+ [[ -z "$zone" || -z "$type" || -z "$name" ]] && return 1
+ if cf_is_dry_run; then
+ _cf_dryrun "GET $CF_API_BASE/zones/$zone/dns_records?type=$type&name=$name"
+ return 0
+ fi
+ local -a CF_CURL_ARGS=()
+ cf_curl_args_set || return 1
+ local resp
+ resp="$(curl -sS --max-time 10 "${CF_CURL_ARGS[@]}" \
+ "$CF_API_BASE/zones/$zone/dns_records?type=$type&name=$name" 2>/dev/null || printf '{}')"
+ printf '%s' "$resp" | jq -c '.result[0] // empty' 2>/dev/null
+}
+
+# Idempotent upsert. GET-first by name+type; PUT if found, POST if not.
+# Args: <zone_id> <type> <name> <content> [ttl=120] [proxied=false]
+# Echoes the record ID on success.
+cf_record_upsert() {
+ local zone="${1:-}" type="${2:-}" name="${3:-}" content="${4:-}"
+ local ttl="${5:-120}" proxied="${6:-false}"
+ if [[ -z "$zone" || -z "$type" || -z "$name" || -z "$content" ]]; then
+ _cf_log "ERROR: cf_record_upsert: zone/type/name/content all required"
+ return 2
+ fi
+
+ # Build payload via jq for safe JSON escaping.
+ local payload
+ payload="$(jq -nc \
+ --arg type "$type" \
+ --arg name "$name" \
+ --arg content "$content" \
+ --argjson ttl "$ttl" \
+ --argjson proxied "$proxied" \
+ '{type:$type, name:$name, content:$content, ttl:$ttl, proxied:$proxied}')"
+
+ if cf_is_dry_run; then
+ local existing_id="dryrun-record-id"
+ _cf_dryrun "GET $CF_API_BASE/zones/$zone/dns_records?type=$type&name=$name"
+ _cf_dryrun "PUT|POST $CF_API_BASE/zones/$zone/dns_records body=$payload"
+ printf '%s\n' "$existing_id"
+ return 0
+ fi
+
+ local existing
+ existing="$(cf_record_get "$zone" "$type" "$name" || true)"
+ local existing_id existing_content
+ existing_id="$(printf '%s' "$existing" | jq -r '.id // empty' 2>/dev/null || true)"
+ existing_content="$(printf '%s' "$existing" | jq -r '.content // empty' 2>/dev/null || true)"
+
+ local -a CF_CURL_ARGS=()
+ cf_curl_args_set || return 1
+ CF_CURL_ARGS+=( -H "Content-Type: application/json" )
+
+ local resp http
+ if [[ -n "$existing_id" ]]; then
+ # No-op if content already matches.
+ if [[ "$existing_content" = "$content" ]]; then
+ _cf_log "no-op: $type $name already has desired content"
+ printf '%s\n' "$existing_id"
+ return 0
+ fi
+ resp="$(curl -sS --max-time 10 -w '\n%{http_code}' -X PUT \
+ "${CF_CURL_ARGS[@]}" \
+ --data "$payload" \
+ "$CF_API_BASE/zones/$zone/dns_records/$existing_id" 2>/dev/null || printf '{}\n0')"
+ else
+ resp="$(curl -sS --max-time 10 -w '\n%{http_code}' -X POST \
+ "${CF_CURL_ARGS[@]}" \
+ --data "$payload" \
+ "$CF_API_BASE/zones/$zone/dns_records" 2>/dev/null || printf '{}\n0')"
+ fi
+
+ http="${resp##*$'\n'}"
+ local body="${resp%$'\n'*}"
+ if [[ "$http" != "200" && "$http" != "201" ]]; then
+ _cf_log "ERROR: upsert failed (http=$http): $body"
+ return 1
+ fi
+ printf '%s' "$body" | jq -r '.result.id // empty' 2>/dev/null
+}
+
+# Delete a record by ID.
+cf_record_delete() {
+ local zone="${1:-}" id="${2:-}"
+ [[ -z "$zone" || -z "$id" ]] && return 1
+ if cf_is_dry_run; then
+ _cf_dryrun "DELETE $CF_API_BASE/zones/$zone/dns_records/$id"
+ return 0
+ fi
+ local -a CF_CURL_ARGS=()
+ cf_curl_args_set || return 1
+ curl -sS --max-time 10 -X DELETE "${CF_CURL_ARGS[@]}" \
+ "$CF_API_BASE/zones/$zone/dns_records/$id" >/dev/null
+}
+
+# Merge a value into an existing TXT record (apex SPF case).
+# Behaviour: if no record exists, create with $new_content.
+# If record exists and already contains $merge_marker substring, leave alone.
+# Otherwise PUT the new content (caller is responsible for merge logic, this
+# helper is the "never silently overwrite a foreign value" guard).
+# Args: <zone> <name> <new_content> <merge_marker>
+cf_txt_upsert_safe() {
+ local zone="${1:-}" name="${2:-}" new_content="${3:-}" marker="${4:-}"
+ [[ -z "$zone" || -z "$name" || -z "$new_content" ]] && return 2
+
+ if cf_is_dry_run; then
+ _cf_dryrun "safe-TXT upsert at $name: marker=$marker content=$new_content"
+ cf_record_upsert "$zone" "TXT" "$name" "$new_content" 120
+ return $?
+ fi
+
+ local existing existing_content
+ existing="$(cf_record_get "$zone" "TXT" "$name" || true)"
+ existing_content="$(printf '%s' "$existing" | jq -r '.content // empty' 2>/dev/null || true)"
+
+ if [[ -z "$existing_content" ]]; then
+ cf_record_upsert "$zone" "TXT" "$name" "$new_content" 120
+ return $?
+ fi
+
+ # Already same.
+ if [[ "$existing_content" = "$new_content" ]]; then
+ _cf_log "no-op: TXT $name already matches"
+ printf '%s\n' "$(printf '%s' "$existing" | jq -r '.id // empty')"
+ return 0
+ fi
+
+ # Foreign value present — refuse to overwrite unless marker matches.
+ if [[ -n "$marker" && "$existing_content" != *"$marker"* ]]; then
+ _cf_log "WARN: TXT $name has foreign content (no marker '$marker'); refusing to overwrite. Existing: $existing_content"
+ return 3
+ fi
+ cf_record_upsert "$zone" "TXT" "$name" "$new_content" 120
+}
diff --git a/claude-ops/skills/ops-marketing/SKILL.md b/claude-ops/skills/ops-marketing/SKILL.md
index 7d50d76e..4cae2de0 100644
--- a/claude-ops/skills/ops-marketing/SKILL.md
+++ b/claude-ops/skills/ops-marketing/SKILL.md
@@ -20,6 +20,99 @@ maxTurns: 40
# OPS ► MARKETING COMMAND CENTER
+## DNS provisioning
+
+`bin/ops-dns-provision` is the canonical DNS surface for any marketing project — it covers every record an end-to-end SaaS launch typically needs, all routed through `scripts/lib/cloudflare-dns.sh` for GET-first idempotency. Re-running is safe; `OPS_DRY_RUN=1` prints planned API calls without firing.
+
+| Subcommand | What it does |
+|------------|--------------|
+| `gsc <project> <domain>` | Google Search Console site verification — fetches token via `siteVerification/v1/token`, upserts TXT at apex, calls `webResource?verificationMethod=DNS_TXT` to verify. |
+| `meta-aem <project> <domain>` | Meta Aggregated Event Measurement — reads `verification_string` from `/me/owned_domains`, upserts `facebook-domain-verification=<token>` TXT at apex. |
+| `apple-pay <project> <domain>` | Two modes via `apple_pay.mode`: `static-file` (default — surfaces the `.well-known/apple-developer-merchantid-domain-association` deploy-hook path) or `stripe-dns` (Stripe `POST /v1/payment_method_domains`). |
+| `spf <project> <domain>` | Builds `v=spf1 include:... <policy>` from `.esp.spf_includes`, upserts merge-safely at apex (refuses to overwrite a foreign TXT lacking the `v=spf1` marker). |
+| `dkim <project> <domain>` | ESP-keyed off `.esp.provider`. Resend implemented (parses `records[]` from `POST /domains`, CNAME upserts). Postmark/SES stubbed. |
+| `dmarc <project> <domain>` | `_dmarc.<apex>` TXT with `v=DMARC1; p=<policy>; rua=<rua>`. Defaults: `policy=quarantine`, `rua=mailto:dmarc@<apex>`. |
+| `mx <project> <domain>` | Provider template keyed off `.inbound.provider`: `google-workspace` (smtp.google.com pri 1) / `resend-inbound` / `ses` (region from `.inbound.region`). |
+| `klaviyo-sending <project> <domain>` | Klaviyo dedicated sending domain — `POST /api/dedicated-sending-domains/`, CNAME upserts. |
+| `audit <project> [--json]` | Read-only — for each row, queries CF and reports `present` / `absent` / `conflicting`. |
+| `provision-all <project> [--skip <row,row>]` | Idempotent full sweep. |
+
+**Auth**: `CLOUDFLARE_API_TOKEN` (Bearer, preferred) or `CLOUDFLARE_API_KEY` + `CLOUDFLARE_EMAIL` (Global key, fallback). Zone lookup: `GET /zones?name=<apex>` finds the zone ID. Record writes: GET-first by `name+type`, then PUT existing ID or POST new — never duplicate.
+
+**Apex resolver** (`cf_apex_for`) handles co.uk-style 2nd-level TLDs (foo.co.uk → foo.co.uk) and strips proto/path/port.
+
+### Preferences schema additions
+
+The new bin reads project-level config from `$PREFS_PATH` under `marketing.projects.<key>`:
+
+```jsonc
+{
+ "marketing": {
+ "projects": {
+ "myapp": {
+ "domain": "example.com",
+
+ // Outbound email service provider (DKIM + SPF includes)
+ "esp": {
+ "provider": "resend", // "resend" | "postmark" | "ses"
+ "credentials": "doppler:prd:RESEND_API_KEY", // cred-ref: "env:VAR" | "doppler:CFG:KEY"
+ "spf_includes": ["_spf.resend.com", "_spf.klaviyo.com"], // optional; sensible defaults applied
+ "spf_policy": "-all" // "-all" (strict) | "~all" (soft-fail)
+ },
+
+ // Inbound mail (MX)
+ "inbound": {
+ "provider": "google-workspace", // "google-workspace" | "resend-inbound" | "ses"
+ "region": "us-east-1" // only used by resend-inbound / ses
+ },
+
+ // DMARC policy
+ "dmarc": {
+ "policy": "quarantine", // "none" | "quarantine" | "reject"
+ "rua": "mailto:[email protected]" // defaults to mailto:dmarc@<apex>
+ },
+
+ // Optional Cloudflare account override (for accounts that own multiple zones)
+ "dns": {
+ "cloudflare_account_id": "<your-cf-account-id>"
+ },
+
+ // Apple Pay domain registration
+ "apple_pay": {
+ "enabled": true,
+ "mode": "static-file" // default; "stripe-dns" registers via Stripe
+ },
+
+ // Cred-refs for individual rows
+ "stripe": { "secret_key": "env:STRIPE_SECRET_KEY" },
+ "meta": { "access_token": "env:META_ACCESS_TOKEN" },
+ "klaviyo": { "private_key": "doppler:prd:KLAVIYO_API_KEY",
+ "sending_subdomain": "em.example.com" }
+ }
+ }
+ }
+}
+```
+
+Defaults are applied bash-side via `${var:-default}`, so all values are optional except `domain` (required by `audit` and `provision-all`).
+
+### Quick examples
+
+```bash
+# Dry-run every row for a project
+OPS_DRY_RUN=1 ops-dns-provision provision-all myapp
+
+# Single row, ad-hoc domain (no prefs needed)
+ops-dns-provision dmarc myapp example.com
+
+# JSON audit for CI healthcheck
+ops-dns-provision audit myapp --json
+# → {"project":"myapp","domain":"example.com","zone":"...","rows":{"gsc":"present","spf":"present","dmarc":"present","mx":"present","meta_aem":"absent","dkim":"unknown"}}
+
+# Skip rows that need provider-specific manual setup first
+ops-dns-provision provision-all myapp --skip dkim,klaviyo-sending
+```
+
## Runtime Context
Before executing, load available context:
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index a3873863..0af7502e 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -45,6 +45,8 @@ run_suite "$TESTS_DIR/test-ops-daemon-manager.sh"
run_suite "$TESTS_DIR/test-ops-package.sh"
run_suite "$TESTS_DIR/test-safety-hooks.sh"
run_suite "$TESTS_DIR/test-deploy-fix-hooks.sh"
+run_suite "$TESTS_DIR/test-cloudflare-dns-lib.sh"
+run_suite "$TESTS_DIR/test-ops-dns-provision.sh"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "SUMMARY"
diff --git a/claude-ops/tests/test-cloudflare-dns-lib.sh b/claude-ops/tests/test-cloudflare-dns-lib.sh
new file mode 100755
index 00000000..e5a47434
--- /dev/null
+++ b/claude-ops/tests/test-cloudflare-dns-lib.sh
@@ -0,0 +1,150 @@
+#!/usr/bin/env bash
+# test-cloudflare-dns-lib.sh — Unit tests for scripts/lib/cloudflare-dns.sh
+#
+# Strategy: source the lib, override `curl` with a mock that returns
+# canned fixtures, exercise cf_apex_for / cf_zone_id / cf_record_get
+# / cf_record_upsert / cf_txt_upsert_safe.
+
+# shellcheck disable=SC2015 # `ok` always returns 0, so && A || B is safe
+# shellcheck disable=SC1091 # sourced lib path is relative to plugin root
+set -uo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+LIB="$PLUGIN_ROOT/scripts/lib/cloudflare-dns.sh"
+
+pass=0
+fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1"; fail=$((fail+1)); }
+
+if [[ ! -f "$LIB" ]]; then
+ echo "FAIL: lib not found at $LIB"
+ exit 1
+fi
+
+# Mock state.
+MOCK_DIR="$(mktemp -d)"
+trap 'rm -rf "$MOCK_DIR"' EXIT
+MOCK_RESPONSES="$MOCK_DIR/responses"
+MOCK_CALLS="$MOCK_DIR/calls"
+: > "$MOCK_CALLS"
+
+# curl mock: pops the next response from $MOCK_RESPONSES (responses are
+# separated by a literal "---END---" line so multi-line bodies survive),
+# logs args to $MOCK_CALLS.
+curl() {
+ printf '%s\n' "$*" >> "$MOCK_CALLS"
+ if [[ ! -s "$MOCK_RESPONSES" ]]; then
+ echo '{}'
+ return 0
+ fi
+ awk 'BEGIN{p=1} /^---END---$/{p=0; next} p{print}' "$MOCK_RESPONSES"
+ awk 'BEGIN{p=0} /^---END---$/{p=1; next} p{print}' "$MOCK_RESPONSES" > "$MOCK_RESPONSES.tail"
+ mv "$MOCK_RESPONSES.tail" "$MOCK_RESPONSES"
+}
+export -f curl 2>/dev/null || true
+
+# Source under bash test harness.
+export CLOUDFLARE_API_TOKEN="test-token-fixture"
+export OPS_DRY_RUN=0
+# shellcheck source=../scripts/lib/cloudflare-dns.sh
+. "$LIB"
+
+# --- cf_apex_for --------------------------------------------------------------
+echo "Testing cf_apex_for"
+[[ "$(cf_apex_for example.com)" = "example.com" ]] && ok "apex of example.com" || err "apex of example.com -> $(cf_apex_for example.com)"
+[[ "$(cf_apex_for api.example.com)" = "example.com" ]] && ok "apex of api.example.com" || err "apex of api.example.com -> $(cf_apex_for api.example.com)"
+[[ "$(cf_apex_for foo.bar.example.com)" = "example.com" ]] && ok "apex of foo.bar.example.com" || err "apex of foo.bar.example.com -> $(cf_apex_for foo.bar.example.com)"
+[[ "$(cf_apex_for example.co.uk)" = "example.co.uk" ]] && ok "apex of example.co.uk" || err "apex of example.co.uk -> $(cf_apex_for example.co.uk)"
+[[ "$(cf_apex_for api.example.co.uk)" = "example.co.uk" ]] && ok "apex of api.example.co.uk" || err "apex of api.example.co.uk -> $(cf_apex_for api.example.co.uk)"
+[[ "$(cf_apex_for https://api.example.com/path)" = "example.com" ]] && ok "apex strips proto+path" || err "apex strips proto+path -> $(cf_apex_for https://api.example.com/path)"
+[[ "$(cf_apex_for EXAMPLE.COM)" = "example.com" ]] && ok "apex is lowercased" || err "apex lowercased -> $(cf_apex_for EXAMPLE.COM)"
+
+# Helper: write a single response (single fixture, terminated).
+write_resp_single() {
+ printf '%s\n---END---\n' "$1" > "$MOCK_RESPONSES"
+}
+# Helper: append additional response.
+append_resp() {
+ printf '%s\n---END---\n' "$1" >> "$MOCK_RESPONSES"
+}
+
+# --- cf_zone_id (mocked) ------------------------------------------------------
+echo "Testing cf_zone_id"
+write_resp_single '{"result":[{"id":"zone-abc123","name":"example.com"}]}'
+zone_id="$(cf_zone_id "example.com")"
+[[ "$zone_id" = "zone-abc123" ]] && ok "cf_zone_id parses id" || err "cf_zone_id parses id -> $zone_id"
+grep -q "zones?name=example.com" "$MOCK_CALLS" && ok "cf_zone_id called correct endpoint" || err "cf_zone_id endpoint missing"
+
+# Empty result.
+: > "$MOCK_CALLS"
+write_resp_single '{"result":[]}'
+zone_id="$(cf_zone_id "missing.example")"
+[[ -z "$zone_id" ]] && ok "cf_zone_id empty on miss" || err "cf_zone_id empty on miss -> $zone_id"
+
+# --- cf_record_get ------------------------------------------------------------
+echo "Testing cf_record_get"
+: > "$MOCK_CALLS"
+write_resp_single '{"result":[{"id":"rec-1","type":"TXT","name":"example.com","content":"v=spf1 -all"}]}'
+rec="$(cf_record_get "zone-abc123" "TXT" "example.com")"
+[[ -n "$rec" ]] && [[ "$(printf '%s' "$rec" | jq -r '.id')" = "rec-1" ]] \
+ && ok "cf_record_get parses match" || err "cf_record_get parses match -> $rec"
+
+# --- cf_record_upsert: no-op when content matches ----------------------------
+echo "Testing cf_record_upsert no-op"
+: > "$MOCK_CALLS"
+write_resp_single '{"result":[{"id":"rec-1","type":"TXT","name":"example.com","content":"v=spf1 -all"}]}'
+upsert_id="$(cf_record_upsert "zone-abc" "TXT" "example.com" "v=spf1 -all" 120)"
+[[ "$upsert_id" = "rec-1" ]] && ok "upsert no-op returns existing id" || err "upsert no-op id -> $upsert_id"
+# Should only have made 1 call (the GET), no PUT/POST.
+call_count="$(wc -l < "$MOCK_CALLS" | tr -d ' ')"
+[[ "$call_count" = "1" ]] && ok "upsert no-op makes 1 call" || err "upsert no-op made $call_count calls"
+
+# --- cf_record_upsert: PUT existing ------------------------------------------
+echo "Testing cf_record_upsert PUT path"
+: > "$MOCK_CALLS"
+# GET response + PUT response (PUT response includes trailing http code line
+# because the lib uses -w '\n%{http_code}').
+write_resp_single '{"result":[{"id":"rec-1","type":"TXT","name":"example.com","content":"OLD"}]}'
+append_resp '{"success":true,"result":{"id":"rec-1"}}
+200'
+upsert_id="$(cf_record_upsert "zone-abc" "TXT" "example.com" "NEW" 120)"
+[[ "$upsert_id" = "rec-1" ]] && ok "upsert PUT returns id" || err "upsert PUT id -> $upsert_id"
+grep -q -- "-X PUT" "$MOCK_CALLS" && ok "upsert PUT uses PUT verb" || err "upsert PUT verb missing"
+
+# --- cf_record_upsert: POST new ----------------------------------------------
+echo "Testing cf_record_upsert POST path"
+: > "$MOCK_CALLS"
+write_resp_single '{"result":[]}'
+append_resp '{"success":true,"result":{"id":"rec-new"}}
+201'
+upsert_id="$(cf_record_upsert "zone-abc" "TXT" "new.example.com" "value" 120)"
+[[ "$upsert_id" = "rec-new" ]] && ok "upsert POST returns new id" || err "upsert POST id -> $upsert_id"
+grep -q -- "-X POST" "$MOCK_CALLS" && ok "upsert POST uses POST verb" || err "upsert POST verb missing"
+
+# --- cf_txt_upsert_safe: foreign value rejection ------------------------------
+echo "Testing cf_txt_upsert_safe foreign-value guard"
+: > "$MOCK_CALLS"
+write_resp_single '{"result":[{"id":"rec-foreign","type":"TXT","name":"example.com","content":"some-other-txt"}]}'
+set +e
+cf_txt_upsert_safe "zone-abc" "example.com" "v=spf1 include:_spf.resend.com -all" "v=spf1" >/dev/null 2>&1
+rc=$?
+set -e
+[[ "$rc" = "3" ]] && ok "safe-upsert refuses foreign TXT (exit 3)" || err "safe-upsert foreign rejection -> exit=$rc"
+
+# --- OPS_DRY_RUN ---------------------------------------------------------------
+echo "Testing OPS_DRY_RUN"
+OPS_DRY_RUN=1
+: > "$MOCK_CALLS"
+zone_id="$(cf_zone_id "example.com")"
+[[ "$zone_id" = "dryrun-zone-id" ]] && ok "dry-run returns synthetic zone id" || err "dry-run zone -> $zone_id"
+upsert_id="$(cf_record_upsert "zone-x" "TXT" "_dmarc.example.com" "v=DMARC1" 3600)"
+[[ "$upsert_id" = "dryrun-record-id" ]] && ok "dry-run returns synthetic record id" || err "dry-run record -> $upsert_id"
+# No real curl calls in dry-run path.
+[[ ! -s "$MOCK_CALLS" ]] && ok "dry-run fires no curl calls" || err "dry-run hit curl: $(cat "$MOCK_CALLS")"
+OPS_DRY_RUN=0
+
+# --- Summary ------------------------------------------------------------------
+echo ""
+echo "test-cloudflare-dns-lib.sh: $pass passed, $fail failed"
+[[ $fail -eq 0 ]] || exit 1
diff --git a/claude-ops/tests/test-ops-dns-provision.sh b/claude-ops/tests/test-ops-dns-provision.sh
new file mode 100755
index 00000000..3cd0a246
--- /dev/null
+++ b/claude-ops/tests/test-ops-dns-provision.sh
@@ -0,0 +1,142 @@
+#!/usr/bin/env bash
+# test-ops-dns-provision.sh — Dry-run shape assertions for bin/ops-dns-provision.
+#
+# Strategy: invoke each subcommand with OPS_DRY_RUN=1 and assert that the
+# planned API calls (logged to stderr by the lib + bin) include the
+# expected endpoint + verb + payload markers.
+
+# shellcheck disable=SC2015 # `ok` always returns 0, so && A || B is safe
+set -uo pipefail
+
+PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$PLUGIN_ROOT/bin/ops-dns-provision"
+
+pass=0
+fail=0
+ok() { echo " PASS: $1"; pass=$((pass+1)); }
+err() { echo " FAIL: $1"; fail=$((fail+1)); }
+
+if [[ ! -x "$BIN" ]]; then
+ echo "FAIL: bin not executable at $BIN"
+ exit 1
+fi
+
+# Common env for every subcommand under test.
+export OPS_DRY_RUN=1
+export CLOUDFLARE_API_TOKEN="test-token-fixture"
+export PREFS_PATH=/dev/null
+
+run_capture() {
+ # Echo combined stdout+stderr of subcommand.
+ "$BIN" "$@" 2>&1 || true
+}
+
+assert_contains() {
+ local needle="$1" haystack="$2" desc="$3"
+ if printf '%s' "$haystack" | grep -q -- "$needle"; then
+ ok "$desc"
+ else
+ err "$desc — missing: $needle"
+ printf 'HAYSTACK:\n%s\n' "$haystack" | head -20
+ fi
+}
+
+# --- help ---------------------------------------------------------------------
+echo "Testing --help"
+help_out="$(run_capture --help)"
+assert_contains "SUBCOMMANDS" "$help_out" "help lists subcommands"
+assert_contains "provision-all" "$help_out" "help lists provision-all"
+assert_contains "OPS_DRY_RUN" "$help_out" "help documents OPS_DRY_RUN"
+
+# --- gsc ----------------------------------------------------------------------
+echo "Testing gsc dry-run"
+out="$(run_capture gsc myproj example.com)"
+assert_contains "POST https://www.googleapis.com/siteVerification/v1/token" "$out" "gsc plans token POST"
+assert_contains "GET https://api.cloudflare.com/client/v4/zones?name=example.com" "$out" "gsc looks up zone"
+assert_contains "PUT|POST" "$out" "gsc plans TXT upsert"
+assert_contains "\"name\":\"example.com\"" "$out" "gsc TXT at apex"
+
+# --- meta-aem -----------------------------------------------------------------
+echo "Testing meta-aem dry-run"
+out="$(run_capture meta-aem myproj example.com)"
+assert_contains "GET https://graph.facebook.com/v19.0/me/owned_domains" "$out" "meta-aem plans owned_domains GET"
+assert_contains "facebook-domain-verification=" "$out" "meta-aem TXT content has fb prefix"
+
+# --- apple-pay (static-file default) -----------------------------------------
+echo "Testing apple-pay static-file mode"
+out="$(run_capture apple-pay myproj example.com)"
+assert_contains ".well-known/apple-developer-merchantid-domain-association" "$out" "apple-pay surfaces association path"
+assert_contains "static-file" "$out" "apple-pay uses static-file default mode"
+
+# --- spf ----------------------------------------------------------------------
+echo "Testing spf dry-run"
+out="$(run_capture spf myproj example.com)"
+assert_contains "v=spf1 include:_spf.resend.com include:_spf.klaviyo.com -all" "$out" "spf default content"
+assert_contains "marker=v=spf1" "$out" "spf uses safe-merge marker"
+
+# --- dkim (resend default) ----------------------------------------------------
+echo "Testing dkim dry-run"
+out="$(run_capture dkim myproj example.com)"
+assert_contains "POST https://api.resend.com/domains" "$out" "dkim plans resend POST"
+
+# --- dmarc --------------------------------------------------------------------
+echo "Testing dmarc dry-run"
+out="$(run_capture dmarc myproj example.com)"
+assert_contains "v=DMARC1; p=quarantine" "$out" "dmarc default policy=quarantine"
+assert_contains "rua=mailto:[email protected]" "$out" "dmarc default rua"
+assert_contains "_dmarc.example.com" "$out" "dmarc record at _dmarc."
+
+# --- mx (google-workspace default) -------------------------------------------
+echo "Testing mx dry-run"
+out="$(run_capture mx myproj example.com)"
+assert_contains "MX upsert at example.com priority=1 target=smtp.google.com" "$out" "mx defaults to google-workspace"
+
+# --- klaviyo-sending ---------------------------------------------------------
+echo "Testing klaviyo-sending dry-run"
+out="$(run_capture klaviyo-sending myproj example.com)"
+assert_contains "POST https://a.klaviyo.com/api/dedicated-sending-domains/" "$out" "klaviyo-sending plans POST"
+assert_contains "em.example.com" "$out" "klaviyo-sending defaults to em.<apex>"
+
+# --- provision-all sequencing ------------------------------------------------
+echo "Testing provision-all"
+# provision-all needs a domain in prefs; create a temp prefs file with one.
+TMP_PREFS="$(mktemp)"
+trap 'rm -f "$TMP_PREFS"' EXIT
+cat > "$TMP_PREFS" <<'EOF'
+{
+ "marketing": {
+ "projects": {
+ "myproj": {
+ "domain": "example.com"
+ }
+ }
+ }
+}
+EOF
+PREFS_PATH="$TMP_PREFS" out="$(PREFS_PATH="$TMP_PREFS" run_capture provision-all myproj --skip dkim,klaviyo-sending)"
+assert_contains "provision-all: row=spf" "$out" "provision-all runs spf"
+assert_contains "provision-all: row=dmarc" "$out" "provision-all runs dmarc"
+assert_contains "provision-all: row=mx" "$out" "provision-all runs mx"
+assert_contains "provision-all: row=gsc" "$out" "provision-all runs gsc"
+assert_contains "provision-all: skipping dkim" "$out" "provision-all honors --skip"
+assert_contains "provision-all: skipping klaviyo-sending" "$out" "provision-all honors --skip multi"
+
+# --- unknown subcommand ------------------------------------------------------
+echo "Testing unknown subcommand"
+set +e
+"$BIN" frobnicate myproj 2>/dev/null
+rc=$?
+set -e
+[[ "$rc" = "2" ]] && ok "unknown subcommand exits 2" || err "unknown subcommand exit=$rc"
+
+# --- missing required args ---------------------------------------------------
+echo "Testing missing args"
+set +e
+"$BIN" dmarc 2>/dev/null
+rc=$?
+set -e
+[[ "$rc" = "2" ]] && ok "missing args exits 2" || err "missing args exit=$rc"
+
+echo ""
+echo "test-ops-dns-provision.sh: $pass passed, $fail failed"
+[[ $fail -eq 0 ]] || exit 1