import { CredentialStore } from '@agentproto/auth'; /** * Minimal Cloudflare v4 API client for the `cloudflare-managed` tunnel * provider — only the endpoints the managed engine needs (tunnels, tunnel * token, remote ingress config, zones, DNS records). * * Every request goes through an INJECTED `fetch`: production passes the * global one, tests pass a simulated Cloudflare API. Nothing here ever logs * or echoes the API token — it only rides in the `Authorization` header — * and the tunnel token returned by `getTunnelToken` is a secret the caller * must keep in memory only. */ type FetchLike = (input: string, init?: { method?: string; headers?: Record; body?: string; redirect?: "follow" | "manual" | "error"; signal?: AbortSignal; }) => Promise<{ status: number; ok: boolean; headers: { get(name: string): string | null; }; json(): Promise; text(): Promise; }>; interface CfTunnel { id: string; name: string; deleted_at?: string | null; } interface CfDnsRecord { id: string; type: string; name: string; content: string; proxied?: boolean; comment?: string | null; } interface CfIngressRule { hostname?: string; service: string; } /** A Cloudflare API failure. `status` is the HTTP status; `codes` the CF error codes. */ declare class CloudflareApiError extends Error { readonly status: number; readonly codes: number[]; constructor(message: string, status: number, codes: number[]); } /** True for "the thing is already gone" — delete paths tolerate it. */ declare function isNotFound(err: unknown): boolean; interface CloudflareApiOptions { /** API token (Bearer). Never logged, never part of an error message. */ token: string; fetch: FetchLike; baseUrl?: string; } declare class CloudflareApi { private readonly token; private readonly fetchImpl; private readonly baseUrl; constructor(opts: CloudflareApiOptions); /** Live (not deleted) tunnels with exactly this name. */ listTunnelsByName(accountId: string, name: string): Promise; /** A tunnel by id, or null when it doesn't exist / was deleted. */ getTunnel(accountId: string, tunnelId: string): Promise; /** Create a remotely-configured tunnel (`config_src: "cloudflare"`). */ createTunnel(accountId: string, name: string): Promise; /** The connector token for `cloudflared tunnel run`. SECRET. */ getTunnelToken(accountId: string, tunnelId: string): Promise; getTunnelIngress(accountId: string, tunnelId: string): Promise; putTunnelIngress(accountId: string, tunnelId: string, ingress: CfIngressRule[]): Promise; /** Drop stale connector connections (required before a tunnel delete). */ deleteTunnelConnections(accountId: string, tunnelId: string): Promise; deleteTunnel(accountId: string, tunnelId: string): Promise; findZoneId(zoneName: string, accountId: string): Promise; /** Every record (any type) with exactly this name. */ listDnsRecords(zoneId: string, name: string): Promise; createDnsRecord(zoneId: string, record: Omit): Promise; patchDnsRecord(zoneId: string, recordId: string, patch: Partial>): Promise; deleteDnsRecord(zoneId: string, recordId: string): Promise; private call; } /** * Provider config for `cloudflare-managed`: the zone list, hostname → zone * resolution, and API-token references. * * Stored through `setup_tunnel_provider` in the tunnel creds store * (`~/.agentproto/tunnel-creds/cloudflare-managed.json`, 0600) as two * string fields: * * zones JSON array, one entry per zone the engine may write to: * [{ "zone": "example.com", "accountId": "…", "tokenRef": "env:CF_TOKEN_AGENTIK", * "zoneId"?: "…", "maxLabels"?: 1 }, …] * zoneTokens OPTIONAL JSON object of raw tokens, `{ "": "" }`, * referenced from a zone as `tokenRef: "stored:"`. Lives * only in the 0600 creds file; never echoed, never logged. * * A `tokenRef` is a reference, never the token itself: * env: read from the daemon's environment * file: read from a file that must be owner-only (no group/other bits) * keychain: read from the OS keychain (`@agentproto/auth` KeychainStore) * stored: read from `zoneTokens` in the 0600 creds file */ interface ManagedZoneConfig { /** Zone apex, e.g. "example.com". */ zone: string; /** Cloudflare account id the zone (and its tunnels) live in. */ accountId: string; /** Token reference — see the module header. Never the raw token. */ tokenRef: string; /** Zone id; looked up by name via the API when omitted. */ zoneId?: string; /** * How many labels under the zone a hostname may have. Default 1: a zone * without Advanced Certificate Manager only has an edge certificate for * `*.zone`, so `a.b.zone` would fail TLS at the edge. */ maxLabels?: number; } /** Parse + validate the `zones` setup field. Throws with a precise message. */ declare function parseManagedZones(raw: string | undefined | null): ManagedZoneConfig[]; declare function normalizeHost(h: string): string; /** * Pick the zone that serves `hostname` (longest suffix wins, so a delegated * `eu.example.com` zone beats `example.com`) and check the hostname depth * against that zone's `maxLabels`. Throws a message naming the configured * zones when nothing matches. */ declare function resolveZoneForHostname(zones: readonly ManagedZoneConfig[], hostnameRaw: string): ManagedZoneConfig; type TokenResolver = (ref: string) => Promise; interface TokenResolverOptions { storedTokens?: Record; env?: NodeJS.ProcessEnv; /** Keychain backend; defaults to the OS keychain. Injectable for tests. */ keychain?: Pick; /** Platform override for the file-permission check (tests). */ platform?: NodeJS.Platform; } /** * Build the resolver that turns a `tokenRef` into the token. Errors name the * reference, never a value. */ declare function makeTokenResolver(opts?: TokenResolverOptions): TokenResolver; /** * Desired-state engine behind the `cloudflare-managed` tunnel provider. * * You declare `{ key, hostnames, service }`; `reconcile` makes Cloudflare * match it and is safe to replay on every start: * * 1. find the tunnel `agentproto-managed-` (list FIRST, never * duplicate) or create it with `config_src: "cloudflare"`; * 2. fetch its connector token (secret — returned, never stored/logged); * 3. PUT the remote ingress: one `{hostname, service}` rule per hostname, * then the final `http_status:404` catch-all; * 4. upsert a proxied CNAME `hostname → .cfargotunnel.com` per * hostname — only when no record exists, or the existing one carries * the engine's ownership comment. Anything else is an error. * * `destroy` undoes it in order: CNAMEs (only the engine's own, pointing at * THIS tunnel), then stale connections, then the tunnel — every step * tolerating "already gone". `removeHostname` is the second half of a swap. * * Ownership: the engine only ever looks up tunnels by its prefixed name * and only edits/deletes DNS records carrying {@link MANAGED_DNS_COMMENT}. * A tunnel or record it didn't create is never touched. */ declare const MANAGED_TUNNEL_PREFIX = "agentproto-managed-"; declare const MANAGED_DNS_COMMENT = "managed by agentproto tunnel engine"; /** Cloudflare's CNAME target domain for tunnels: `.cfargotunnel.com`. */ declare const TUNNEL_CNAME_DOMAIN = "cfargotunnel.com"; interface ManagedTunnelSpec { /** Stable identity — becomes the tunnel name suffix. */ key: string; /** Hostnames routed to the tunnel, primary first. */ hostnames: readonly string[]; } interface ReconcileResult { accountId: string; tunnelId: string; tunnelName: string; /** Connector token. SECRET — keep in memory, hand to cloudflared via env. */ token: string; created: boolean; } interface ManagedEngineOptions { zones: readonly ManagedZoneConfig[]; resolveToken: TokenResolver; fetch: FetchLike; apiBaseUrl?: string; onLog?: (line: string) => void; } /** `agentproto-managed-` with the key squeezed to Cloudflare-safe chars. */ declare function managedTunnelName(key: string): string; declare function tunnelCnameTarget(tunnelId: string): string; declare class ManagedTunnelEngine { private readonly zones; private readonly resolveToken; private readonly fetchImpl; private readonly apiBaseUrl; private readonly onLog; private readonly zoneIds; constructor(opts: ManagedEngineOptions); /** * Validate a hostname set without touching the API: every hostname must * resolve to a configured zone within its `maxLabels`, and all of them * must live in the same account as the primary (a tunnel is per-account). */ validateHostnames(hostnames: readonly string[]): ManagedZoneConfig[]; /** * Bring Cloudflare to the desired state. Idempotent. `service` is the * origin every hostname routes to; `null` (tunnel not running here) * keeps the origin already in the remote ingress, and skips the ingress * write when there is none yet — the next start replays it. */ reconcile(spec: ManagedTunnelSpec, service: string | null): Promise; /** * Second half of a swap: drop `hostname` from the tunnel's ingress and * delete its CNAME (only if it's ours and points at this tunnel). The * remaining hostnames keep serving throughout. */ removeHostname(spec: ManagedTunnelSpec, hostnameRaw: string): Promise; /** * Tear everything down: CNAMEs → connections → tunnel. Tolerates every * piece already being gone. Callers stop cloudflared FIRST. */ destroy(spec: ManagedTunnelSpec): Promise; private findTunnel; private zoneHandle; private ensureCname; private deleteOwnCname; } declare function buildIngress(hostnames: readonly string[], service: string): CfIngressRule[]; export { type CfDnsRecord, type CfIngressRule, type CfTunnel, CloudflareApi, CloudflareApiError, type FetchLike, MANAGED_DNS_COMMENT, MANAGED_TUNNEL_PREFIX, type ManagedEngineOptions, ManagedTunnelEngine, type ManagedTunnelSpec, type ManagedZoneConfig, type ReconcileResult, TUNNEL_CNAME_DOMAIN, type TokenResolver, buildIngress, isNotFound, makeTokenResolver, managedTunnelName, normalizeHost, parseManagedZones, resolveZoneForHostname, tunnelCnameTarget };