@geekmidas/edge 10.0.0-alpha.189 → 10.0.0-alpha.190

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47,10 +47,12 @@ var CloudflareCredentialsInvalid = class extends require_errors.EdgeError {
47
47
  var CloudflarePermissionMissing = class extends require_errors.EdgeError {
48
48
  domain;
49
49
  detail;
50
- constructor(domain, detail) {
51
- super(`The Cloudflare token may not change ${domain}'s DNS${detail ? ` (${detail})` : ""}. Give it Zone:Read and DNS:Edit on ${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`);
50
+ permission;
51
+ constructor(domain, detail, permission = DNS_PERMISSIONS) {
52
+ super(`The Cloudflare token was refused on ${domain}${detail ? ` (${detail})` : ""}. Give it ${permission} on ${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`);
52
53
  this.domain = domain;
53
54
  this.detail = detail;
55
+ this.permission = permission;
54
56
  this.name = "CloudflarePermissionMissing";
55
57
  }
56
58
  };
@@ -101,6 +103,10 @@ var CloudflareRecordNotAllowed = class extends require_errors.EdgeError {
101
103
  this.name = "CloudflareRecordNotAllowed";
102
104
  }
103
105
  };
106
+ /** What reading and writing a zone's records needs. */
107
+ const DNS_PERMISSIONS = "Zone:Read and DNS:Edit";
108
+ /** What an origin certificate needs, beside finding the zone. */
109
+ const ORIGIN_CA_PERMISSIONS = "Zone:Read and SSL and Certificates:Edit";
104
110
  /** Cloudflare's authentication error codes: a bad or unusable token. */
105
111
  const AUTH_CODES = /* @__PURE__ */ new Set([
106
112
  6003,
@@ -121,7 +127,7 @@ var CloudflareApi = class {
121
127
  this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
122
128
  this.maxAttempts = options.maxAttempts ?? 4;
123
129
  }
124
- async request(domain, method, path, body) {
130
+ async request(domain, method, path, body, permission = DNS_PERMISSIONS) {
125
131
  for (let attempt = 1;; attempt++) {
126
132
  const response = await fetch(`${this.baseUrl}${path}`, {
127
133
  method,
@@ -147,7 +153,7 @@ var CloudflareApi = class {
147
153
  const errors = envelope?.errors ?? [];
148
154
  const detail = errors.map((e) => e.message).join("; ") || void 0;
149
155
  if (response.status === 401 || errors.some((e) => AUTH_CODES.has(e.code))) throw new CloudflareCredentialsInvalid(detail);
150
- if (response.status === 403) throw new CloudflarePermissionMissing(domain, detail);
156
+ if (response.status === 403) throw new CloudflarePermissionMissing(domain, detail, permission);
151
157
  throw new CloudflareRequestFailed(method, path, response.status, errors);
152
158
  }
153
159
  }
@@ -189,6 +195,23 @@ var CloudflareApi = class {
189
195
  const { result } = await this.request(domain, "PATCH", `/zones/${zone}/dns_records/${id}`, record);
190
196
  return result;
191
197
  }
198
+ /**
199
+ * An origin certificate from Cloudflare's Origin CA, for a CSR made where
200
+ * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid
201
+ * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs
202
+ * `Zone → SSL and Certificates → Edit` on the zone.
203
+ *
204
+ * @param domain - the zone, for what an error says
205
+ */
206
+ async createOriginCertificate(domain, request) {
207
+ const { result } = await this.request(domain, "POST", "/certificates", {
208
+ csr: request.csr,
209
+ hostnames: [...request.hostnames],
210
+ requested_validity: request.days,
211
+ request_type: request.type
212
+ }, ORIGIN_CA_PERMISSIONS);
213
+ return result;
214
+ }
192
215
  async deleteRecord(domain, id) {
193
216
  const zone = await this.zoneId(domain);
194
217
  await this.request(domain, "DELETE", `/zones/${zone}/dns_records/${id}`);
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["EdgeError","mxValue","parseMxValue"],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"sourcesContent":["/**\n * Cloudflare's v4 DNS API, as gkm uses it: the records of one name and type\n * at a time, inside a zone found by its name.\n *\n * - zone: `GET /zones?name={domain}` — the one call that is not a record's\n * - read: `GET /zones/{zone}/dns_records?type={type}&name.exact={fqdn}`\n * - create: `POST /zones/{zone}/dns_records`\n * - update: `PATCH /zones/{zone}/dns_records/{id}`\n * - delete: `DELETE /zones/{zone}/dns_records/{id}`\n *\n * Never the zone itself, its settings or the account. An API token with\n * `Zone:Read` and `DNS:Edit` on the zone is all it needs, sent as\n * `Authorization: Bearer <token>`.\n *\n * Every answer is the v4 envelope — `{ success, errors, result }` — and a\n * failure is read from its `errors`, not from the status alone. A 429 is\n * waited out a few times (its `Retry-After`, else a second) before the run\n * gives up with {@link CloudflareRateLimited}.\n */\n\nimport { EdgeError } from '../../errors';\n\n/** A Cloudflare API token, sent as `Authorization: Bearer <token>`. */\nexport interface CloudflareCredential {\n\ttoken: string;\n}\n\nexport const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4';\n\n/**\n * Cloudflare's \"automatic\" TTL — 300 seconds, and the only TTL a proxied\n * record takes.\n */\nexport const CLOUDFLARE_AUTO_TTL = 1;\n\n/** The record types gkm writes. Never TXT, NS, SOA, SRV or CAA. */\nexport const CLOUDFLARE_MANAGED_TYPES = ['A', 'AAAA', 'CNAME', 'MX'] as const;\n\nexport type CloudflareRecordType = (typeof CLOUDFLARE_MANAGED_TYPES)[number];\n\n/** One record as Cloudflare returns it. */\nexport interface CloudflareRecord {\n\tid: string;\n\ttype: string;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\t/** Whether Cloudflare's proxy answers for it — its CDN, the orange cloud. */\n\tproxied?: boolean;\n\t/** An MX record's: Cloudflare keeps it apart from `content`. */\n\tpriority?: number;\n}\n\n/** What a write sends. */\nexport interface CloudflareRecordInput {\n\ttype: CloudflareRecordType;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\tproxied?: boolean;\n\tpriority?: number;\n}\n\n/** The v4 envelope. */\ninterface Envelope<T> {\n\tsuccess: boolean;\n\terrors?: { code: number; message: string }[];\n\tresult: T;\n\tresult_info?: { page: number; total_pages: number };\n}\n\n/** The token is missing, malformed, expired or revoked. */\nexport class CloudflareCredentialsInvalid extends EdgeError {\n\tconstructor(readonly detail?: string) {\n\t\tsuper(\n\t\t\t`Cloudflare refused the API token${detail ? ` (${detail})` : ''}. ` +\n\t\t\t\t'Create one at dash.cloudflare.com/profile/api-tokens with Zone:Read ' +\n\t\t\t\t'and DNS:Edit on the zone, then set CLOUDFLARE_API_TOKEN or run ' +\n\t\t\t\t'`gkm login --provider cloudflare`.',\n\t\t);\n\t\tthis.name = 'CloudflareCredentialsInvalid';\n\t}\n}\n\n/** The token is good, and may not do this to this zone. */\nexport class CloudflarePermissionMissing extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly detail?: string,\n\t) {\n\t\tsuper(\n\t\t\t`The Cloudflare token may not change ${domain}'s DNS` +\n\t\t\t\t`${detail ? ` (${detail})` : ''}. Give it Zone:Read and DNS:Edit on ` +\n\t\t\t\t`${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`,\n\t\t);\n\t\tthis.name = 'CloudflarePermissionMissing';\n\t}\n}\n\n/** No zone of that name is in the token's reach. */\nexport class CloudflareZoneNotFound extends EdgeError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`Cloudflare has no zone ${domain} the token can read. Add ${domain} to ` +\n\t\t\t\t'the Cloudflare account and point its nameservers at Cloudflare, and ' +\n\t\t\t\t\"make sure the token's zone resources include it.\",\n\t\t);\n\t\tthis.name = 'CloudflareZoneNotFound';\n\t}\n}\n\n/** Still rate limited after waiting it out. */\nexport class CloudflareRateLimited extends EdgeError {\n\tconstructor(readonly attempts: number) {\n\t\tsuper(\n\t\t\t`Cloudflare kept answering 429 Too Many Requests after ${attempts} ` +\n\t\t\t\t'attempts. Wait a few minutes and deploy again: every record written ' +\n\t\t\t\t'so far is kept.',\n\t\t);\n\t\tthis.name = 'CloudflareRateLimited';\n\t}\n}\n\n/** Any other answer that is not a success. */\nexport class CloudflareRequestFailed extends EdgeError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly path: string,\n\t\treadonly status: number,\n\t\t/** Cloudflare's `errors`, as it answered them. */\n\t\treadonly failures: readonly { code: number; message: string }[],\n\t) {\n\t\tconst detail =\n\t\t\tfailures.length > 0\n\t\t\t\t? failures.map((e) => `${e.code}: ${e.message}`).join('; ')\n\t\t\t\t: `HTTP ${status}`;\n\t\tsuper(`Cloudflare refused ${method} ${path}: ${detail}.`);\n\t\tthis.name = 'CloudflareRequestFailed';\n\t}\n}\n\n/** A record type gkm does not write. */\nexport class CloudflareRecordNotAllowed extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly type: string,\n\t\t/** The record's name, as it was asked for: `api`, `@`. */\n\t\treadonly record: string,\n\t) {\n\t\tsuper(\n\t\t\t`gkm does not manage ${type} records, so it will not touch '${record}' ` +\n\t\t\t\t`${type} in ${domain}: only ${CLOUDFLARE_MANAGED_TYPES.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CloudflareRecordNotAllowed';\n\t}\n}\n\n/** Cloudflare's authentication error codes: a bad or unusable token. */\nconst AUTH_CODES = new Set([6003, 6111, 9106, 9109, 10000]);\n\nexport interface CloudflareApiOptions {\n\tcredential: CloudflareCredential;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: (ms: number) => Promise<void>;\n\tmaxAttempts?: number;\n}\n\nexport class CloudflareApi {\n\tprivate readonly baseUrl: string;\n\tprivate readonly sleep: (ms: number) => Promise<void>;\n\tprivate readonly maxAttempts: number;\n\tprivate readonly zones = new Map<string, string>();\n\n\tconstructor(private readonly options: CloudflareApiOptions) {\n\t\tthis.baseUrl = (options.baseUrl ?? CLOUDFLARE_API_BASE).replace(/\\/$/, '');\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis.maxAttempts = options.maxAttempts ?? 4;\n\t}\n\n\tprivate async request<T>(\n\t\tdomain: string,\n\t\tmethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<Envelope<T>> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.options.credential.token}`,\n\t\t\t\t\t...(body ? { 'Content-Type': 'application/json' } : {}),\n\t\t\t\t},\n\t\t\t\t...(body ? { body: JSON.stringify(body) } : {}),\n\t\t\t});\n\t\t\tif (response.status === 429) {\n\t\t\t\tif (attempt >= this.maxAttempts) {\n\t\t\t\t\tthrow new CloudflareRateLimited(attempt);\n\t\t\t\t}\n\t\t\t\tconst after = Number(response.headers.get('retry-after'));\n\t\t\t\tawait this.sleep(\n\t\t\t\t\tNumber.isFinite(after) && after > 0 ? after * 1000 : 1000,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet envelope: Envelope<T> | undefined;\n\t\t\ttry {\n\t\t\t\tenvelope = (await response.json()) as Envelope<T>;\n\t\t\t} catch {\n\t\t\t\tenvelope = undefined;\n\t\t\t}\n\t\t\tif (response.ok && envelope?.success) return envelope;\n\t\t\tconst errors = envelope?.errors ?? [];\n\t\t\tconst detail = errors.map((e) => e.message).join('; ') || undefined;\n\t\t\tif (\n\t\t\t\tresponse.status === 401 ||\n\t\t\t\terrors.some((e) => AUTH_CODES.has(e.code))\n\t\t\t) {\n\t\t\t\tthrow new CloudflareCredentialsInvalid(detail);\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\tthrow new CloudflarePermissionMissing(domain, detail);\n\t\t\t}\n\t\t\tthrow new CloudflareRequestFailed(method, path, response.status, errors);\n\t\t}\n\t}\n\n\t/** The zone's id, found once by its name. */\n\tasync zoneId(domain: string): Promise<string> {\n\t\tconst key = domain.toLowerCase();\n\t\tconst known = this.zones.get(key);\n\t\tif (known) return known;\n\t\tconst { result } = await this.request<{ id: string; name: string }[]>(\n\t\t\tkey,\n\t\t\t'GET',\n\t\t\t`/zones?name=${encodeURIComponent(key)}`,\n\t\t);\n\t\tconst zone = result.find((z) => z.name.toLowerCase() === key);\n\t\tif (!zone) throw new CloudflareZoneNotFound(key);\n\t\tthis.zones.set(key, zone.id);\n\t\treturn zone.id;\n\t}\n\n\t/** Every record of exactly this name and type — of the type, without a name. */\n\tasync getRecords(\n\t\tdomain: string,\n\t\ttype: CloudflareRecordType,\n\t\tfqdn?: string,\n\t): Promise<CloudflareRecord[]> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst found: CloudflareRecord[] = [];\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst query = new URLSearchParams({\n\t\t\t\ttype,\n\t\t\t\t...(fqdn ? { 'name.exact': fqdn } : {}),\n\t\t\t\tper_page: '100',\n\t\t\t\tpage: String(page),\n\t\t\t});\n\t\t\tconst envelope = await this.request<CloudflareRecord[]>(\n\t\t\t\tdomain,\n\t\t\t\t'GET',\n\t\t\t\t`/zones/${zone}/dns_records?${query}`,\n\t\t\t);\n\t\t\tfound.push(...envelope.result);\n\t\t\tconst info = envelope.result_info;\n\t\t\tif (!info || info.page >= info.total_pages) return found;\n\t\t}\n\t}\n\n\tasync createRecord(\n\t\tdomain: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t`/zones/${zone}/dns_records`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync updateRecord(\n\t\tdomain: string,\n\t\tid: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'PATCH',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync deleteRecord(domain: string, id: string): Promise<void> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tawait this.request<unknown>(\n\t\t\tdomain,\n\t\t\t'DELETE',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t);\n\t}\n}\n","/**\n * Cloudflare DNS Provider\n *\n * Implements DnsProvider against Cloudflare's v4 API, one name and type at a\n * time: it reads and writes only the A, AAAA, CNAME and MX records of the\n * names it is handed, inside the zone found by the domain's name, and never\n * the zone's settings or the account. An API token with `Zone:Read` and\n * `DNS:Edit` on the zone is all it needs.\n *\n * Cloudflare is also a CDN: a record it proxies (`proxied: true`, the orange\n * cloud) is answered by Cloudflare's edge, which forwards to the record's\n * value. A write that says `proxied` sets it; one that does not leaves an\n * existing record's as it was and creates a new one unproxied — so a\n * certificate's validation CNAME, which Cloudflare must not answer, is\n * never proxied by accident. A proxied record's TTL is always Cloudflare's\n * automatic one.\n *\n * Cloudflare can hold several records of one name and type; an upsert leaves\n * exactly one, with its value. An MX value is `<priority> <host>` on the\n * DnsProvider side, as everywhere in gkm; Cloudflare keeps the priority\n * apart, so it is split on a write and joined on a read.\n *\n * Credentials: `CLOUDFLARE_API_TOKEN`, else what `gkm login --provider\n * cloudflare` stored. Never logged.\n */\n\nimport {\n\ttype DeleteDnsRecord,\n\ttype DeleteResult,\n\ttype DnsProvider,\n\ttype DnsRecord,\n\tmxValue,\n\tparseMxValue,\n\ttype UpsertDnsRecord,\n\ttype UpsertResult,\n} from '../index';\nimport {\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n} from './api';\n\n/** Cloudflare refuses a TTL under this, but for its automatic one. */\nconst CLOUDFLARE_MIN_TTL = 60;\n\nexport interface CloudflareProviderOptions {\n\t/**\n\t * Where the token comes from, asked the first time the API is called. It\n\t * throws when there is none: what to do about a missing token is the\n\t * caller's to say.\n\t */\n\tcredential: () => Promise<CloudflareCredential>;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: CloudflareApiOptions['sleep'];\n\tmaxAttempts?: number;\n}\n\n/** A value compared the way DNS does: case-insensitive, no trailing dot. */\nfunction normalize(value: string): string {\n\treturn value.trim().replace(/\\.$/, '').replace(/\\s+/g, ' ').toLowerCase();\n}\n\n/** `api` under `example.com` → `api.example.com`; `@` → `example.com`. */\nexport function fullName(name: string, domain: string): string {\n\tconst zone = domain.toLowerCase().replace(/\\.$/, '');\n\tconst label = name.trim().toLowerCase().replace(/\\.$/, '');\n\tif (label === '@' || label === '' || label === zone) return zone;\n\treturn label.endsWith(`.${zone}`) ? label : `${label}.${zone}`;\n}\n\n/** A Cloudflare record's value in gkm's form: an MX's is `<priority> <host>`. */\nfunction valueOf(record: CloudflareRecord): string {\n\treturn record.type === 'MX'\n\t\t? mxValue(record.priority ?? 0, record.content)\n\t\t: record.content;\n}\n\nfunction managed(type: string): type is CloudflareRecordType {\n\treturn (CLOUDFLARE_MANAGED_TYPES as readonly string[]).includes(type);\n}\n\n/** Only an address or an alias can be proxied. */\nfunction proxiable(type: string): boolean {\n\treturn type === 'A' || type === 'AAAA' || type === 'CNAME';\n}\n\nexport class CloudflareProvider implements DnsProvider {\n\treadonly name = 'cloudflare';\n\tprivate api: CloudflareApi | null = null;\n\n\tconstructor(private readonly options: CloudflareProviderOptions) {}\n\n\tprivate async getApi(): Promise<CloudflareApi> {\n\t\tif (this.api) return this.api;\n\t\tconst credential = await this.options.credential();\n\t\tthis.api = new CloudflareApi({\n\t\t\tcredential,\n\t\t\t...(this.options.baseUrl ? { baseUrl: this.options.baseUrl } : {}),\n\t\t\t...(this.options.sleep ? { sleep: this.options.sleep } : {}),\n\t\t\t...(this.options.maxAttempts\n\t\t\t\t? { maxAttempts: this.options.maxAttempts }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn this.api;\n\t}\n\n\tprivate assertManaged(domain: string, type: string, name: string): void {\n\t\tif (!managed(type))\n\t\t\tthrow new CloudflareRecordNotAllowed(domain, type, name);\n\t}\n\n\t/**\n\t * The managed records of the whole zone: A, AAAA, CNAME and MX. Prefer\n\t * {@link readRecords}, which asks for exactly the names it needs.\n\t */\n\tasync getRecords(domain: string): Promise<DnsRecord[]> {\n\t\tconst api = await this.getApi();\n\t\tconst zone = domain.toLowerCase();\n\t\tconst out: DnsRecord[] = [];\n\t\tfor (const type of CLOUDFLARE_MANAGED_TYPES) {\n\t\t\tconst records = await api.getRecords(zone, type);\n\t\t\tout.push(...group(zone, type, records));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** The records of exactly these names and types, one request each. */\n\tasync readRecords(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]> {\n\t\tfor (const { name, type } of wanted) this.assertManaged(domain, type, name);\n\t\tconst api = await this.getApi();\n\t\tconst found: DnsRecord[] = [];\n\t\tfor (const { name, type } of wanted) {\n\t\t\tconst records = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\ttype as CloudflareRecordType,\n\t\t\t\tfullName(name, domain),\n\t\t\t);\n\t\t\tfound.push(...group(domain, type as CloudflareRecordType, records, name));\n\t\t}\n\t\treturn found;\n\t}\n\n\t/**\n\t * Each name and type set to exactly its one value: read it, and write it\n\t * only when its value or its proxy differ. The first record of the name\n\t * is updated in place and any other of that type deleted, so the set\n\t * ends up with one.\n\t */\n\tasync upsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]> {\n\t\t// Every record is checked before any is written, so a refused one\n\t\t// leaves the zone as it was.\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\n\t\tconst results: UpsertResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as CloudflareRecordType;\n\t\t\tconst name = fullName(record.name, domain);\n\t\t\tconst existing = await api.getRecords(domain, type, name);\n\t\t\tconst [first, ...rest] = existing;\n\t\t\tconst proxied = proxiable(type)\n\t\t\t\t? (record.proxied ?? first?.proxied ?? false)\n\t\t\t\t: undefined;\n\n\t\t\tif (\n\t\t\t\tfirst &&\n\t\t\t\trest.length === 0 &&\n\t\t\t\tnormalize(valueOf(first)) === normalize(record.value) &&\n\t\t\t\t(proxied === undefined || (first.proxied ?? false) === proxied)\n\t\t\t) {\n\t\t\t\tresults.push({ record, created: false, unchanged: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst input = recordInput(type, name, record, proxied);\n\t\t\tif (first) await api.updateRecord(domain, first.id, input);\n\t\t\telse await api.createRecord(domain, input);\n\t\t\tfor (const extra of rest) await api.deleteRecord(domain, extra.id);\n\t\t\tresults.push({ record, created: !first, unchanged: false });\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]> {\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\t\tconst results: DeleteResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst existing = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\trecord.type as CloudflareRecordType,\n\t\t\t\tfullName(record.name, domain),\n\t\t\t);\n\t\t\tif (existing.length === 0) {\n\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const found of existing) await api.deleteRecord(domain, found.id);\n\t\t\tresults.push({ record, deleted: true, notFound: false });\n\t\t}\n\t\treturn results;\n\t}\n}\n\n/** What a write sends for one record. */\nfunction recordInput(\n\ttype: CloudflareRecordType,\n\tname: string,\n\trecord: UpsertDnsRecord,\n\tproxied: boolean | undefined,\n): CloudflareRecordInput {\n\tconst ttl = proxied\n\t\t? CLOUDFLARE_AUTO_TTL\n\t\t: Math.max(record.ttl, CLOUDFLARE_MIN_TTL);\n\tif (type === 'MX') {\n\t\tconst { priority, host } = parseMxValue(record.value);\n\t\treturn { type, name, content: host, priority, ttl };\n\t}\n\treturn {\n\t\ttype,\n\t\tname,\n\t\tcontent: record.value.trim().replace(/\\.$/, ''),\n\t\tttl,\n\t\t...(proxied !== undefined ? { proxied } : {}),\n\t};\n}\n\n/**\n * Cloudflare's records as DnsRecords: one per name, its values together,\n * named relative to the domain (`@` for the apex) — or as `asked`, when the\n * caller named it.\n */\nfunction group(\n\tdomain: string,\n\ttype: CloudflareRecordType,\n\trecords: readonly CloudflareRecord[],\n\tasked?: string,\n): DnsRecord[] {\n\tconst zone = domain.toLowerCase();\n\tconst byName = new Map<string, CloudflareRecord[]>();\n\tfor (const record of records) {\n\t\tconst fqdn = record.name.toLowerCase();\n\t\tbyName.set(fqdn, [...(byName.get(fqdn) ?? []), record]);\n\t}\n\treturn [...byName.entries()].map(([fqdn, set]) => ({\n\t\tname:\n\t\t\tasked ??\n\t\t\t(fqdn === zone ? '@' : fqdn.slice(0, fqdn.length - zone.length - 1)),\n\t\ttype,\n\t\tttl: set[0]!.ttl === CLOUDFLARE_AUTO_TTL ? 300 : set[0]!.ttl,\n\t\tvalues: set.map(valueOf),\n\t\t...(proxiable(type) ? { proxied: set[0]!.proxied ?? false } : {}),\n\t}));\n}\n\nexport {\n\tCLOUDFLARE_API_BASE,\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\tCloudflareCredentialsInvalid,\n\tCloudflarePermissionMissing,\n\tCloudflareRateLimited,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n\tCloudflareRequestFailed,\n\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AAI,EAAE,CAAE,QAAA,IAA8B,MAAM,IAAI,EAAE,CAAE;EACzD,QAAQ,IAAI,IAAI,OAAO;EACvB,GAAI,UAAU,IAAI,IAAI,EAAE,SAAS,IAAI,EAAE,CAAE,WAAW,MAAM,IAAI,CAAC;CAChE,EAAE;AACH"}
1
+ {"version":3,"file":"index.cjs","names":["EdgeError","mxValue","parseMxValue"],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"sourcesContent":["/**\n * Cloudflare's v4 DNS API, as gkm uses it: the records of one name and type\n * at a time, inside a zone found by its name.\n *\n * - zone: `GET /zones?name={domain}` — the one call that is not a record's\n * - read: `GET /zones/{zone}/dns_records?type={type}&name.exact={fqdn}`\n * - create: `POST /zones/{zone}/dns_records`\n * - update: `PATCH /zones/{zone}/dns_records/{id}`\n * - delete: `DELETE /zones/{zone}/dns_records/{id}`\n *\n * Never the zone itself, its settings or the account. An API token with\n * `Zone:Read` and `DNS:Edit` on the zone is all it needs, sent as\n * `Authorization: Bearer <token>`.\n *\n * Every answer is the v4 envelope — `{ success, errors, result }` — and a\n * failure is read from its `errors`, not from the status alone. A 429 is\n * waited out a few times (its `Retry-After`, else a second) before the run\n * gives up with {@link CloudflareRateLimited}.\n */\n\nimport { EdgeError } from '../../errors';\n\n/** A Cloudflare API token, sent as `Authorization: Bearer <token>`. */\nexport interface CloudflareCredential {\n\ttoken: string;\n}\n\nexport const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4';\n\n/**\n * Cloudflare's \"automatic\" TTL — 300 seconds, and the only TTL a proxied\n * record takes.\n */\nexport const CLOUDFLARE_AUTO_TTL = 1;\n\n/** The record types gkm writes. Never TXT, NS, SOA, SRV or CAA. */\nexport const CLOUDFLARE_MANAGED_TYPES = ['A', 'AAAA', 'CNAME', 'MX'] as const;\n\nexport type CloudflareRecordType = (typeof CLOUDFLARE_MANAGED_TYPES)[number];\n\n/** One record as Cloudflare returns it. */\nexport interface CloudflareRecord {\n\tid: string;\n\ttype: string;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\t/** Whether Cloudflare's proxy answers for it — its CDN, the orange cloud. */\n\tproxied?: boolean;\n\t/** An MX record's: Cloudflare keeps it apart from `content`. */\n\tpriority?: number;\n}\n\n/** What a write sends. */\nexport interface CloudflareRecordInput {\n\ttype: CloudflareRecordType;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\tproxied?: boolean;\n\tpriority?: number;\n}\n\n/** An origin certificate as the Origin CA returns it. */\nexport interface CloudflareOriginCertificate {\n\t/** Its serial number. */\n\tid: string;\n\t/** PEM. */\n\tcertificate: string;\n\thostnames: string[];\n\t/** `2041-11-22 10:00:00 +0000 UTC` */\n\texpires_on: string;\n}\n\n/** The v4 envelope. */\ninterface Envelope<T> {\n\tsuccess: boolean;\n\terrors?: { code: number; message: string }[];\n\tresult: T;\n\tresult_info?: { page: number; total_pages: number };\n}\n\n/** The token is missing, malformed, expired or revoked. */\nexport class CloudflareCredentialsInvalid extends EdgeError {\n\tconstructor(readonly detail?: string) {\n\t\tsuper(\n\t\t\t`Cloudflare refused the API token${detail ? ` (${detail})` : ''}. ` +\n\t\t\t\t'Create one at dash.cloudflare.com/profile/api-tokens with Zone:Read ' +\n\t\t\t\t'and DNS:Edit on the zone, then set CLOUDFLARE_API_TOKEN or run ' +\n\t\t\t\t'`gkm login --provider cloudflare`.',\n\t\t);\n\t\tthis.name = 'CloudflareCredentialsInvalid';\n\t}\n}\n\n/** The token is good, and may not do this to this zone. */\nexport class CloudflarePermissionMissing extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly detail?: string,\n\t\t/** What the token needs for it: `Zone:Read and DNS:Edit`. */\n\t\treadonly permission: string = DNS_PERMISSIONS,\n\t) {\n\t\tsuper(\n\t\t\t`The Cloudflare token was refused on ${domain}` +\n\t\t\t\t`${detail ? ` (${detail})` : ''}. Give it ${permission} on ` +\n\t\t\t\t`${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`,\n\t\t);\n\t\tthis.name = 'CloudflarePermissionMissing';\n\t}\n}\n\n/** No zone of that name is in the token's reach. */\nexport class CloudflareZoneNotFound extends EdgeError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`Cloudflare has no zone ${domain} the token can read. Add ${domain} to ` +\n\t\t\t\t'the Cloudflare account and point its nameservers at Cloudflare, and ' +\n\t\t\t\t\"make sure the token's zone resources include it.\",\n\t\t);\n\t\tthis.name = 'CloudflareZoneNotFound';\n\t}\n}\n\n/** Still rate limited after waiting it out. */\nexport class CloudflareRateLimited extends EdgeError {\n\tconstructor(readonly attempts: number) {\n\t\tsuper(\n\t\t\t`Cloudflare kept answering 429 Too Many Requests after ${attempts} ` +\n\t\t\t\t'attempts. Wait a few minutes and deploy again: every record written ' +\n\t\t\t\t'so far is kept.',\n\t\t);\n\t\tthis.name = 'CloudflareRateLimited';\n\t}\n}\n\n/** Any other answer that is not a success. */\nexport class CloudflareRequestFailed extends EdgeError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly path: string,\n\t\treadonly status: number,\n\t\t/** Cloudflare's `errors`, as it answered them. */\n\t\treadonly failures: readonly { code: number; message: string }[],\n\t) {\n\t\tconst detail =\n\t\t\tfailures.length > 0\n\t\t\t\t? failures.map((e) => `${e.code}: ${e.message}`).join('; ')\n\t\t\t\t: `HTTP ${status}`;\n\t\tsuper(`Cloudflare refused ${method} ${path}: ${detail}.`);\n\t\tthis.name = 'CloudflareRequestFailed';\n\t}\n}\n\n/** A record type gkm does not write. */\nexport class CloudflareRecordNotAllowed extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly type: string,\n\t\t/** The record's name, as it was asked for: `api`, `@`. */\n\t\treadonly record: string,\n\t) {\n\t\tsuper(\n\t\t\t`gkm does not manage ${type} records, so it will not touch '${record}' ` +\n\t\t\t\t`${type} in ${domain}: only ${CLOUDFLARE_MANAGED_TYPES.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CloudflareRecordNotAllowed';\n\t}\n}\n\n/** What reading and writing a zone's records needs. */\nconst DNS_PERMISSIONS = 'Zone:Read and DNS:Edit';\n\n/** What an origin certificate needs, beside finding the zone. */\nconst ORIGIN_CA_PERMISSIONS = 'Zone:Read and SSL and Certificates:Edit';\n\n/** Cloudflare's authentication error codes: a bad or unusable token. */\nconst AUTH_CODES = new Set([6003, 6111, 9106, 9109, 10000]);\n\nexport interface CloudflareApiOptions {\n\tcredential: CloudflareCredential;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: (ms: number) => Promise<void>;\n\tmaxAttempts?: number;\n}\n\nexport class CloudflareApi {\n\tprivate readonly baseUrl: string;\n\tprivate readonly sleep: (ms: number) => Promise<void>;\n\tprivate readonly maxAttempts: number;\n\tprivate readonly zones = new Map<string, string>();\n\n\tconstructor(private readonly options: CloudflareApiOptions) {\n\t\tthis.baseUrl = (options.baseUrl ?? CLOUDFLARE_API_BASE).replace(/\\/$/, '');\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis.maxAttempts = options.maxAttempts ?? 4;\n\t}\n\n\tprivate async request<T>(\n\t\tdomain: string,\n\t\tmethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tpermission: string = DNS_PERMISSIONS,\n\t): Promise<Envelope<T>> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.options.credential.token}`,\n\t\t\t\t\t...(body ? { 'Content-Type': 'application/json' } : {}),\n\t\t\t\t},\n\t\t\t\t...(body ? { body: JSON.stringify(body) } : {}),\n\t\t\t});\n\t\t\tif (response.status === 429) {\n\t\t\t\tif (attempt >= this.maxAttempts) {\n\t\t\t\t\tthrow new CloudflareRateLimited(attempt);\n\t\t\t\t}\n\t\t\t\tconst after = Number(response.headers.get('retry-after'));\n\t\t\t\tawait this.sleep(\n\t\t\t\t\tNumber.isFinite(after) && after > 0 ? after * 1000 : 1000,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet envelope: Envelope<T> | undefined;\n\t\t\ttry {\n\t\t\t\tenvelope = (await response.json()) as Envelope<T>;\n\t\t\t} catch {\n\t\t\t\tenvelope = undefined;\n\t\t\t}\n\t\t\tif (response.ok && envelope?.success) return envelope;\n\t\t\tconst errors = envelope?.errors ?? [];\n\t\t\tconst detail = errors.map((e) => e.message).join('; ') || undefined;\n\t\t\tif (\n\t\t\t\tresponse.status === 401 ||\n\t\t\t\terrors.some((e) => AUTH_CODES.has(e.code))\n\t\t\t) {\n\t\t\t\tthrow new CloudflareCredentialsInvalid(detail);\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\tthrow new CloudflarePermissionMissing(domain, detail, permission);\n\t\t\t}\n\t\t\tthrow new CloudflareRequestFailed(method, path, response.status, errors);\n\t\t}\n\t}\n\n\t/** The zone's id, found once by its name. */\n\tasync zoneId(domain: string): Promise<string> {\n\t\tconst key = domain.toLowerCase();\n\t\tconst known = this.zones.get(key);\n\t\tif (known) return known;\n\t\tconst { result } = await this.request<{ id: string; name: string }[]>(\n\t\t\tkey,\n\t\t\t'GET',\n\t\t\t`/zones?name=${encodeURIComponent(key)}`,\n\t\t);\n\t\tconst zone = result.find((z) => z.name.toLowerCase() === key);\n\t\tif (!zone) throw new CloudflareZoneNotFound(key);\n\t\tthis.zones.set(key, zone.id);\n\t\treturn zone.id;\n\t}\n\n\t/** Every record of exactly this name and type — of the type, without a name. */\n\tasync getRecords(\n\t\tdomain: string,\n\t\ttype: CloudflareRecordType,\n\t\tfqdn?: string,\n\t): Promise<CloudflareRecord[]> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst found: CloudflareRecord[] = [];\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst query = new URLSearchParams({\n\t\t\t\ttype,\n\t\t\t\t...(fqdn ? { 'name.exact': fqdn } : {}),\n\t\t\t\tper_page: '100',\n\t\t\t\tpage: String(page),\n\t\t\t});\n\t\t\tconst envelope = await this.request<CloudflareRecord[]>(\n\t\t\t\tdomain,\n\t\t\t\t'GET',\n\t\t\t\t`/zones/${zone}/dns_records?${query}`,\n\t\t\t);\n\t\t\tfound.push(...envelope.result);\n\t\t\tconst info = envelope.result_info;\n\t\t\tif (!info || info.page >= info.total_pages) return found;\n\t\t}\n\t}\n\n\tasync createRecord(\n\t\tdomain: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t`/zones/${zone}/dns_records`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync updateRecord(\n\t\tdomain: string,\n\t\tid: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'PATCH',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\t/**\n\t * An origin certificate from Cloudflare's Origin CA, for a CSR made where\n\t * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid\n\t * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs\n\t * `Zone → SSL and Certificates → Edit` on the zone.\n\t *\n\t * @param domain - the zone, for what an error says\n\t */\n\tasync createOriginCertificate(\n\t\tdomain: string,\n\t\trequest: {\n\t\t\tcsr: string;\n\t\t\thostnames: readonly string[];\n\t\t\tdays: number;\n\t\t\ttype: 'origin-rsa' | 'origin-ecc';\n\t\t},\n\t): Promise<CloudflareOriginCertificate> {\n\t\tconst { result } = await this.request<CloudflareOriginCertificate>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t'/certificates',\n\t\t\t{\n\t\t\t\tcsr: request.csr,\n\t\t\t\thostnames: [...request.hostnames],\n\t\t\t\trequested_validity: request.days,\n\t\t\t\trequest_type: request.type,\n\t\t\t},\n\t\t\tORIGIN_CA_PERMISSIONS,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync deleteRecord(domain: string, id: string): Promise<void> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tawait this.request<unknown>(\n\t\t\tdomain,\n\t\t\t'DELETE',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t);\n\t}\n}\n","/**\n * Cloudflare DNS Provider\n *\n * Implements DnsProvider against Cloudflare's v4 API, one name and type at a\n * time: it reads and writes only the A, AAAA, CNAME and MX records of the\n * names it is handed, inside the zone found by the domain's name, and never\n * the zone's settings or the account. An API token with `Zone:Read` and\n * `DNS:Edit` on the zone is all it needs.\n *\n * Cloudflare is also a CDN: a record it proxies (`proxied: true`, the orange\n * cloud) is answered by Cloudflare's edge, which forwards to the record's\n * value. A write that says `proxied` sets it; one that does not leaves an\n * existing record's as it was and creates a new one unproxied — so a\n * certificate's validation CNAME, which Cloudflare must not answer, is\n * never proxied by accident. A proxied record's TTL is always Cloudflare's\n * automatic one.\n *\n * Cloudflare can hold several records of one name and type; an upsert leaves\n * exactly one, with its value. An MX value is `<priority> <host>` on the\n * DnsProvider side, as everywhere in gkm; Cloudflare keeps the priority\n * apart, so it is split on a write and joined on a read.\n *\n * Credentials: `CLOUDFLARE_API_TOKEN`, else what `gkm login --provider\n * cloudflare` stored. Never logged.\n */\n\nimport {\n\ttype DeleteDnsRecord,\n\ttype DeleteResult,\n\ttype DnsProvider,\n\ttype DnsRecord,\n\tmxValue,\n\tparseMxValue,\n\ttype UpsertDnsRecord,\n\ttype UpsertResult,\n} from '../index';\nimport {\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n} from './api';\n\n/** Cloudflare refuses a TTL under this, but for its automatic one. */\nconst CLOUDFLARE_MIN_TTL = 60;\n\nexport interface CloudflareProviderOptions {\n\t/**\n\t * Where the token comes from, asked the first time the API is called. It\n\t * throws when there is none: what to do about a missing token is the\n\t * caller's to say.\n\t */\n\tcredential: () => Promise<CloudflareCredential>;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: CloudflareApiOptions['sleep'];\n\tmaxAttempts?: number;\n}\n\n/** A value compared the way DNS does: case-insensitive, no trailing dot. */\nfunction normalize(value: string): string {\n\treturn value.trim().replace(/\\.$/, '').replace(/\\s+/g, ' ').toLowerCase();\n}\n\n/** `api` under `example.com` → `api.example.com`; `@` → `example.com`. */\nexport function fullName(name: string, domain: string): string {\n\tconst zone = domain.toLowerCase().replace(/\\.$/, '');\n\tconst label = name.trim().toLowerCase().replace(/\\.$/, '');\n\tif (label === '@' || label === '' || label === zone) return zone;\n\treturn label.endsWith(`.${zone}`) ? label : `${label}.${zone}`;\n}\n\n/** A Cloudflare record's value in gkm's form: an MX's is `<priority> <host>`. */\nfunction valueOf(record: CloudflareRecord): string {\n\treturn record.type === 'MX'\n\t\t? mxValue(record.priority ?? 0, record.content)\n\t\t: record.content;\n}\n\nfunction managed(type: string): type is CloudflareRecordType {\n\treturn (CLOUDFLARE_MANAGED_TYPES as readonly string[]).includes(type);\n}\n\n/** Only an address or an alias can be proxied. */\nfunction proxiable(type: string): boolean {\n\treturn type === 'A' || type === 'AAAA' || type === 'CNAME';\n}\n\nexport class CloudflareProvider implements DnsProvider {\n\treadonly name = 'cloudflare';\n\tprivate api: CloudflareApi | null = null;\n\n\tconstructor(private readonly options: CloudflareProviderOptions) {}\n\n\tprivate async getApi(): Promise<CloudflareApi> {\n\t\tif (this.api) return this.api;\n\t\tconst credential = await this.options.credential();\n\t\tthis.api = new CloudflareApi({\n\t\t\tcredential,\n\t\t\t...(this.options.baseUrl ? { baseUrl: this.options.baseUrl } : {}),\n\t\t\t...(this.options.sleep ? { sleep: this.options.sleep } : {}),\n\t\t\t...(this.options.maxAttempts\n\t\t\t\t? { maxAttempts: this.options.maxAttempts }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn this.api;\n\t}\n\n\tprivate assertManaged(domain: string, type: string, name: string): void {\n\t\tif (!managed(type))\n\t\t\tthrow new CloudflareRecordNotAllowed(domain, type, name);\n\t}\n\n\t/**\n\t * The managed records of the whole zone: A, AAAA, CNAME and MX. Prefer\n\t * {@link readRecords}, which asks for exactly the names it needs.\n\t */\n\tasync getRecords(domain: string): Promise<DnsRecord[]> {\n\t\tconst api = await this.getApi();\n\t\tconst zone = domain.toLowerCase();\n\t\tconst out: DnsRecord[] = [];\n\t\tfor (const type of CLOUDFLARE_MANAGED_TYPES) {\n\t\t\tconst records = await api.getRecords(zone, type);\n\t\t\tout.push(...group(zone, type, records));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** The records of exactly these names and types, one request each. */\n\tasync readRecords(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]> {\n\t\tfor (const { name, type } of wanted) this.assertManaged(domain, type, name);\n\t\tconst api = await this.getApi();\n\t\tconst found: DnsRecord[] = [];\n\t\tfor (const { name, type } of wanted) {\n\t\t\tconst records = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\ttype as CloudflareRecordType,\n\t\t\t\tfullName(name, domain),\n\t\t\t);\n\t\t\tfound.push(...group(domain, type as CloudflareRecordType, records, name));\n\t\t}\n\t\treturn found;\n\t}\n\n\t/**\n\t * Each name and type set to exactly its one value: read it, and write it\n\t * only when its value or its proxy differ. The first record of the name\n\t * is updated in place and any other of that type deleted, so the set\n\t * ends up with one.\n\t */\n\tasync upsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]> {\n\t\t// Every record is checked before any is written, so a refused one\n\t\t// leaves the zone as it was.\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\n\t\tconst results: UpsertResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as CloudflareRecordType;\n\t\t\tconst name = fullName(record.name, domain);\n\t\t\tconst existing = await api.getRecords(domain, type, name);\n\t\t\tconst [first, ...rest] = existing;\n\t\t\tconst proxied = proxiable(type)\n\t\t\t\t? (record.proxied ?? first?.proxied ?? false)\n\t\t\t\t: undefined;\n\n\t\t\tif (\n\t\t\t\tfirst &&\n\t\t\t\trest.length === 0 &&\n\t\t\t\tnormalize(valueOf(first)) === normalize(record.value) &&\n\t\t\t\t(proxied === undefined || (first.proxied ?? false) === proxied)\n\t\t\t) {\n\t\t\t\tresults.push({ record, created: false, unchanged: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst input = recordInput(type, name, record, proxied);\n\t\t\tif (first) await api.updateRecord(domain, first.id, input);\n\t\t\telse await api.createRecord(domain, input);\n\t\t\tfor (const extra of rest) await api.deleteRecord(domain, extra.id);\n\t\t\tresults.push({ record, created: !first, unchanged: false });\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]> {\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\t\tconst results: DeleteResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst existing = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\trecord.type as CloudflareRecordType,\n\t\t\t\tfullName(record.name, domain),\n\t\t\t);\n\t\t\tif (existing.length === 0) {\n\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const found of existing) await api.deleteRecord(domain, found.id);\n\t\t\tresults.push({ record, deleted: true, notFound: false });\n\t\t}\n\t\treturn results;\n\t}\n}\n\n/** What a write sends for one record. */\nfunction recordInput(\n\ttype: CloudflareRecordType,\n\tname: string,\n\trecord: UpsertDnsRecord,\n\tproxied: boolean | undefined,\n): CloudflareRecordInput {\n\tconst ttl = proxied\n\t\t? CLOUDFLARE_AUTO_TTL\n\t\t: Math.max(record.ttl, CLOUDFLARE_MIN_TTL);\n\tif (type === 'MX') {\n\t\tconst { priority, host } = parseMxValue(record.value);\n\t\treturn { type, name, content: host, priority, ttl };\n\t}\n\treturn {\n\t\ttype,\n\t\tname,\n\t\tcontent: record.value.trim().replace(/\\.$/, ''),\n\t\tttl,\n\t\t...(proxied !== undefined ? { proxied } : {}),\n\t};\n}\n\n/**\n * Cloudflare's records as DnsRecords: one per name, its values together,\n * named relative to the domain (`@` for the apex) — or as `asked`, when the\n * caller named it.\n */\nfunction group(\n\tdomain: string,\n\ttype: CloudflareRecordType,\n\trecords: readonly CloudflareRecord[],\n\tasked?: string,\n): DnsRecord[] {\n\tconst zone = domain.toLowerCase();\n\tconst byName = new Map<string, CloudflareRecord[]>();\n\tfor (const record of records) {\n\t\tconst fqdn = record.name.toLowerCase();\n\t\tbyName.set(fqdn, [...(byName.get(fqdn) ?? []), record]);\n\t}\n\treturn [...byName.entries()].map(([fqdn, set]) => ({\n\t\tname:\n\t\t\tasked ??\n\t\t\t(fqdn === zone ? '@' : fqdn.slice(0, fqdn.length - zone.length - 1)),\n\t\ttype,\n\t\tttl: set[0]!.ttl === CLOUDFLARE_AUTO_TTL ? 300 : set[0]!.ttl,\n\t\tvalues: set.map(valueOf),\n\t\t...(proxiable(type) ? { proxied: set[0]!.proxied ?? false } : {}),\n\t}));\n}\n\nexport {\n\tCLOUDFLARE_API_BASE,\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\tCloudflareCredentialsInvalid,\n\ttype CloudflareOriginCertificate,\n\tCloudflarePermissionMissing,\n\tCloudflareRateLimited,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n\tCloudflareRequestFailed,\n\tCloudflareZoneNotFound,\n} from './api';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,sBAAsB;;;;;AAMnC,MAAa,sBAAsB;;AAGnC,MAAa,2BAA2B;CAAC;CAAK;CAAQ;CAAS;AAAI;;AAiDnE,IAAa,+BAAb,cAAkDA,eAAAA,UAAU;CACtC;CAArB,YAAY,QAA0B;EACrC,MACC,mCAAmC,SAAS,KAAK,OAAO,KAAK,GAAG,0KAIjE;EANoB,KAAA,SAAA;EAOpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,8BAAb,cAAiDA,eAAAA,UAAU;CAEhD;CACA;CAEA;CAJV,YACC,QACA,QAEA,aAA8B,iBAC7B;EACD,MACC,uCAAuC,SACnC,SAAS,KAAK,OAAO,KAAK,GAAG,YAAY,WAAW,MACpD,OAAO,8DACZ;EATS,KAAA,SAAA;EACA,KAAA,SAAA;EAEA,KAAA,aAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,yBAAb,cAA4CA,eAAAA,UAAU;CAChC;CAArB,YAAY,QAAyB;EACpC,MACC,0BAA0B,OAAO,2BAA2B,OAAO,yHAGpE;EALoB,KAAA,SAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wBAAb,cAA2CA,eAAAA,UAAU;CAC/B;CAArB,YAAY,UAA2B;EACtC,MACC,yDAAyD,SAAS,qFAGnE;EALoB,KAAA,WAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAG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,OAAO;GAAE;GAAM;GAAM,SAAS;GAAM;GAAU;EAAI;CACnD;CACA,OAAO;EACN;EACA;EACA,SAAS,OAAO,MAAM,KAAK,CAAC,CAAC,QAAQ,OAAO,EAAE;EAC9C;EACA,GAAI,YAAY,KAAA,IAAY,EAAE,QAAQ,IAAI,CAAC;CAC5C;AACD;;;;;;AAOA,SAAS,MACR,QACA,MACA,SACA,OACc;CACd,MAAM,OAAO,OAAO,YAAY;CAChC,MAAM,yBAAS,IAAI,IAAgC;CACnD,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,OAAO,OAAO,KAAK,YAAY;EACrC,OAAO,IAAI,MAAM,CAAC,GAAI,OAAO,IAAI,IAAI,KAAK,CAAC,GAAI,MAAM,CAAC;CACvD;CACA,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,UAAU;EAClD,MACC,UACC,SAAS,OAAO,MAAM,KAAK,MAAM,GAAG,KAAK,SAAS,KAAK,SAAS,CAAC;EACnE;EACA,KAAK,IAAI,EAAE,CAAE,QAAA,IAA8B,MAAM,IAAI,EAAE,CAAE;EACzD,QAAQ,IAAI,IAAI,OAAO;EACvB,GAAI,UAAU,IAAI,IAAI,EAAE,SAAS,IAAI,EAAE,CAAE,WAAW,MAAM,IAAI,CAAC;CAChE,EAAE;AACH"}
@@ -37,6 +37,16 @@ interface CloudflareRecordInput {
37
37
  proxied?: boolean;
38
38
  priority?: number;
39
39
  }
40
+ /** An origin certificate as the Origin CA returns it. */
41
+ interface CloudflareOriginCertificate {
42
+ /** Its serial number. */
43
+ id: string;
44
+ /** PEM. */
45
+ certificate: string;
46
+ hostnames: string[];
47
+ /** `2041-11-22 10:00:00 +0000 UTC` */
48
+ expires_on: string;
49
+ }
40
50
  /** The token is missing, malformed, expired or revoked. */
41
51
  export declare class CloudflareCredentialsInvalid extends EdgeError {
42
52
  readonly detail?: string | undefined;
@@ -46,7 +56,11 @@ export declare class CloudflareCredentialsInvalid extends EdgeError {
46
56
  export declare class CloudflarePermissionMissing extends EdgeError {
47
57
  readonly domain: string;
48
58
  readonly detail?: string | undefined;
49
- constructor(domain: string, detail?: string | undefined);
59
+ /** What the token needs for it: `Zone:Read and DNS:Edit`. */
60
+ readonly permission: string;
61
+ constructor(domain: string, detail?: string | undefined,
62
+ /** What the token needs for it: `Zone:Read and DNS:Edit`. */
63
+ permission?: string);
50
64
  }
51
65
  /** No zone of that name is in the token's reach. */
52
66
  export declare class CloudflareZoneNotFound extends EdgeError {
@@ -107,6 +121,20 @@ export declare class CloudflareApi {
107
121
  getRecords(domain: string, type: CloudflareRecordType, fqdn?: string): Promise<CloudflareRecord[]>;
108
122
  createRecord(domain: string, record: CloudflareRecordInput): Promise<CloudflareRecord>;
109
123
  updateRecord(domain: string, id: string, record: CloudflareRecordInput): Promise<CloudflareRecord>;
124
+ /**
125
+ * An origin certificate from Cloudflare's Origin CA, for a CSR made where
126
+ * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid
127
+ * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs
128
+ * `Zone → SSL and Certificates → Edit` on the zone.
129
+ *
130
+ * @param domain - the zone, for what an error says
131
+ */
132
+ createOriginCertificate(domain: string, request: {
133
+ csr: string;
134
+ hostnames: readonly string[];
135
+ days: number;
136
+ type: 'origin-rsa' | 'origin-ecc';
137
+ }): Promise<CloudflareOriginCertificate>;
110
138
  deleteRecord(domain: string, id: string): Promise<void>;
111
139
  }
112
140
  //#endregion
@@ -150,5 +178,5 @@ export declare class CloudflareProvider implements DnsProvider {
150
178
  deleteRecords(domain: string, records: DeleteDnsRecord[]): Promise<DeleteResult[]>;
151
179
  }
152
180
  //#endregion
153
- export type { CloudflareApiOptions, CloudflareCredential, CloudflareRecord, CloudflareRecordInput, CloudflareRecordType };
181
+ export type { CloudflareApiOptions, CloudflareCredential, CloudflareOriginCertificate, CloudflareRecord, CloudflareRecordInput, CloudflareRecordType };
154
182
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"mappings":";;;;UAuBiB;EAChB;;qBAGY;;;;;qBAMA;;qBAGA;KAED,+BAA+B;;UAG1B;EAChB;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;;;UAIgB;EAChB,MAAM;;EAEN;EACA;EACA;EACA;EACA;;;qBAYY,qCAAqC;WAC5B;EAArB,YAAqB;;;qBAYT,oCAAoC;WAEtC;WACA;EAFV,YACU,gBACA;;;qBAYE,+BAA+B;WACtB;EAArB,YAAqB;;;qBAWT,8BAA8B;WACrB;EAArB,YAAqB;;;qBAWT,gCAAgC;WAElC;WACA;WACA;;WAEA;IAAqB;IAAc;;EAL7C,YACU,gBACA,cACA,gBAEA;;EAAA;IAAqB;IAAc;;;;qBAYjC,mCAAmC;WAErC;WACA;;WAEA;EAJV,YACU,gBACA,cAEA;;EAAA;;UAaM;EAChB,YAAY;;EAEZ;;EAEA,SAAS,eAAe;EACxB;;qBAGY;mBAMiB;mBALZ;mBACA;mBACA;mBACA;EAEjB,YAA6B,SAAS;UAQxB;;EAgDR,OAAO,iBAAiB;;EAgBxB,WACL,gBACA,MAAM,sBACN,gBACE,QAAQ;EAqBL,aACL,gBACA,QAAQ,wBACN,QAAQ;EAWL,aACL,gBACA,YACA,QAAQ,wBACN,QAAQ;EAWL,aAAa,gBAAgB,aAAa;;;;iBC5PhC;;;;;;EAMhB,kBAAkB,QAAQ;;EAE1B;;EAEA,QAAQ;EACR;;;wBASe,SAAS,cAAc;qBAuB1B,8BAA8B;mBAIb;WAHpB;UACD;EAER,YAA6B,SAAS;UAExB;UAcN;;;;;EASF,WAAW,iBAAiB,QAAQ;;EAYpC,YACL,gBACA,iBAAiB,oBACf,QAAQ;;;;;;;EAqBL,cACL,gBACA,SAAS,oBACP,QAAQ;EAqCL,cACL,gBACA,SAAS,oBACP,QAAQ"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"mappings":";;;;UAuBiB;EAChB;;qBAGY;;;;;qBAMA;;qBAGA;KAED,+BAA+B;;UAG1B;EAChB;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;;;UAIgB;EAChB,MAAM;;EAEN;EACA;EACA;EACA;EACA;;;UAIgB;;EAEhB;;EAEA;EACA;;EAEA;;;qBAYY,qCAAqC;WAC5B;EAArB,YAAqB;;;qBAYT,oCAAoC;WAEtC;WACA;;WAEA;EAJV,YACU,gBACA,6BAEA;;EAAA;;;qBAYE,+BAA+B;WACtB;EAArB,YAAqB;;;qBAWT,8BAA8B;WACrB;EAArB,YAAqB;;;qBAWT,gCAAgC;WAElC;WACA;WACA;;WAEA;IAAqB;IAAc;;EAL7C,YACU,gBACA,cACA,gBAEA;;EAAA;IAAqB;IAAc;;;;qBAYjC,mCAAmC;WAErC;WACA;;WAEA;EAJV,YACU,gBACA,cAEA;;EAAA;;UAmBM;EAChB,YAAY;;EAEZ;;EAEA,SAAS,eAAe;EACxB;;qBAGY;mBAMiB;mBALZ;mBACA;mBACA;mBACA;EAEjB,YAA6B,SAAS;UAQxB;;EAiDR,OAAO,iBAAiB;;EAgBxB,WACL,gBACA,MAAM,sBACN,gBACE,QAAQ;EAqBL,aACL,gBACA,QAAQ,wBACN,QAAQ;EAWL,aACL,gBACA,YACA,QAAQ,wBACN,QAAQ;;;;;;;;;EAmBL,wBACL,gBACA;IACC;IACA;IACA;IACA;MAEC,QAAQ;EAgBL,aAAa,gBAAgB,aAAa;;;;iBChThC;;;;;;EAMhB,kBAAkB,QAAQ;;EAE1B;;EAEA,QAAQ;EACR;;;wBASe,SAAS,cAAc;qBAuB1B,8BAA8B;mBAIb;WAHpB;UACD;EAER,YAA6B,SAAS;UAExB;UAcN;;;;;EASF,WAAW,iBAAiB,QAAQ;;EAYpC,YACL,gBACA,iBAAiB,oBACf,QAAQ;;;;;;;EAqBL,cACL,gBACA,SAAS,oBACP,QAAQ;EAqCL,cACL,gBACA,SAAS,oBACP,QAAQ"}
@@ -37,6 +37,16 @@ interface CloudflareRecordInput {
37
37
  proxied?: boolean;
38
38
  priority?: number;
39
39
  }
40
+ /** An origin certificate as the Origin CA returns it. */
41
+ interface CloudflareOriginCertificate {
42
+ /** Its serial number. */
43
+ id: string;
44
+ /** PEM. */
45
+ certificate: string;
46
+ hostnames: string[];
47
+ /** `2041-11-22 10:00:00 +0000 UTC` */
48
+ expires_on: string;
49
+ }
40
50
  /** The token is missing, malformed, expired or revoked. */
41
51
  export declare class CloudflareCredentialsInvalid extends EdgeError {
42
52
  readonly detail?: string | undefined;
@@ -46,7 +56,11 @@ export declare class CloudflareCredentialsInvalid extends EdgeError {
46
56
  export declare class CloudflarePermissionMissing extends EdgeError {
47
57
  readonly domain: string;
48
58
  readonly detail?: string | undefined;
49
- constructor(domain: string, detail?: string | undefined);
59
+ /** What the token needs for it: `Zone:Read and DNS:Edit`. */
60
+ readonly permission: string;
61
+ constructor(domain: string, detail?: string | undefined,
62
+ /** What the token needs for it: `Zone:Read and DNS:Edit`. */
63
+ permission?: string);
50
64
  }
51
65
  /** No zone of that name is in the token's reach. */
52
66
  export declare class CloudflareZoneNotFound extends EdgeError {
@@ -107,6 +121,20 @@ export declare class CloudflareApi {
107
121
  getRecords(domain: string, type: CloudflareRecordType, fqdn?: string): Promise<CloudflareRecord[]>;
108
122
  createRecord(domain: string, record: CloudflareRecordInput): Promise<CloudflareRecord>;
109
123
  updateRecord(domain: string, id: string, record: CloudflareRecordInput): Promise<CloudflareRecord>;
124
+ /**
125
+ * An origin certificate from Cloudflare's Origin CA, for a CSR made where
126
+ * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid
127
+ * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs
128
+ * `Zone → SSL and Certificates → Edit` on the zone.
129
+ *
130
+ * @param domain - the zone, for what an error says
131
+ */
132
+ createOriginCertificate(domain: string, request: {
133
+ csr: string;
134
+ hostnames: readonly string[];
135
+ days: number;
136
+ type: 'origin-rsa' | 'origin-ecc';
137
+ }): Promise<CloudflareOriginCertificate>;
110
138
  deleteRecord(domain: string, id: string): Promise<void>;
111
139
  }
112
140
  //#endregion
@@ -150,5 +178,5 @@ export declare class CloudflareProvider implements DnsProvider {
150
178
  deleteRecords(domain: string, records: DeleteDnsRecord[]): Promise<DeleteResult[]>;
151
179
  }
152
180
  //#endregion
153
- export type { CloudflareApiOptions, CloudflareCredential, CloudflareRecord, CloudflareRecordInput, CloudflareRecordType };
181
+ export type { CloudflareApiOptions, CloudflareCredential, CloudflareOriginCertificate, CloudflareRecord, CloudflareRecordInput, CloudflareRecordType };
154
182
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"mappings":";;;;UAuBiB;EAChB;;qBAGY;;;;;qBAMA;;qBAGA;KAED,+BAA+B;;UAG1B;EAChB;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;;;UAIgB;EAChB,MAAM;;EAEN;EACA;EACA;EACA;EACA;;;qBAYY,qCAAqC;WAC5B;EAArB,YAAqB;;;qBAYT,oCAAoC;WAEtC;WACA;EAFV,YACU,gBACA;;;qBAYE,+BAA+B;WACtB;EAArB,YAAqB;;;qBAWT,8BAA8B;WACrB;EAArB,YAAqB;;;qBAWT,gCAAgC;WAElC;WACA;WACA;;WAEA;IAAqB;IAAc;;EAL7C,YACU,gBACA,cACA,gBAEA;;EAAA;IAAqB;IAAc;;;;qBAYjC,mCAAmC;WAErC;WACA;;WAEA;EAJV,YACU,gBACA,cAEA;;EAAA;;UAaM;EAChB,YAAY;;EAEZ;;EAEA,SAAS,eAAe;EACxB;;qBAGY;mBAMiB;mBALZ;mBACA;mBACA;mBACA;EAEjB,YAA6B,SAAS;UAQxB;;EAgDR,OAAO,iBAAiB;;EAgBxB,WACL,gBACA,MAAM,sBACN,gBACE,QAAQ;EAqBL,aACL,gBACA,QAAQ,wBACN,QAAQ;EAWL,aACL,gBACA,YACA,QAAQ,wBACN,QAAQ;EAWL,aAAa,gBAAgB,aAAa;;;;iBC5PhC;;;;;;EAMhB,kBAAkB,QAAQ;;EAE1B;;EAEA,QAAQ;EACR;;;wBASe,SAAS,cAAc;qBAuB1B,8BAA8B;mBAIb;WAHpB;UACD;EAER,YAA6B,SAAS;UAExB;UAcN;;;;;EASF,WAAW,iBAAiB,QAAQ;;EAYpC,YACL,gBACA,iBAAiB,oBACf,QAAQ;;;;;;;EAqBL,cACL,gBACA,SAAS,oBACP,QAAQ;EAqCL,cACL,gBACA,SAAS,oBACP,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"mappings":";;;;UAuBiB;EAChB;;qBAGY;;;;;qBAMA;;qBAGA;KAED,+BAA+B;;UAG1B;EAChB;EACA;;EAEA;EACA;EACA;;EAEA;;EAEA;;;UAIgB;EAChB,MAAM;;EAEN;EACA;EACA;EACA;EACA;;;UAIgB;;EAEhB;;EAEA;EACA;;EAEA;;;qBAYY,qCAAqC;WAC5B;EAArB,YAAqB;;;qBAYT,oCAAoC;WAEtC;WACA;;WAEA;EAJV,YACU,gBACA,6BAEA;;EAAA;;;qBAYE,+BAA+B;WACtB;EAArB,YAAqB;;;qBAWT,8BAA8B;WACrB;EAArB,YAAqB;;;qBAWT,gCAAgC;WAElC;WACA;WACA;;WAEA;IAAqB;IAAc;;EAL7C,YACU,gBACA,cACA,gBAEA;;EAAA;IAAqB;IAAc;;;;qBAYjC,mCAAmC;WAErC;WACA;;WAEA;EAJV,YACU,gBACA,cAEA;;EAAA;;UAmBM;EAChB,YAAY;;EAEZ;;EAEA,SAAS,eAAe;EACxB;;qBAGY;mBAMiB;mBALZ;mBACA;mBACA;mBACA;EAEjB,YAA6B,SAAS;UAQxB;;EAiDR,OAAO,iBAAiB;;EAgBxB,WACL,gBACA,MAAM,sBACN,gBACE,QAAQ;EAqBL,aACL,gBACA,QAAQ,wBACN,QAAQ;EAWL,aACL,gBACA,YACA,QAAQ,wBACN,QAAQ;;;;;;;;;EAmBL,wBACL,gBACA;IACC;IACA;IACA;IACA;MAEC,QAAQ;EAgBL,aAAa,gBAAgB,aAAa;;;;iBChThC;;;;;;EAMhB,kBAAkB,QAAQ;;EAE1B;;EAEA,QAAQ;EACR;;;wBASe,SAAS,cAAc;qBAuB1B,8BAA8B;mBAIb;WAHpB;UACD;EAER,YAA6B,SAAS;UAExB;UAcN;;;;;EASF,WAAW,iBAAiB,QAAQ;;EAYpC,YACL,gBACA,iBAAiB,oBACf,QAAQ;;;;;;;EAqBL,cACL,gBACA,SAAS,oBACP,QAAQ;EAqCL,cACL,gBACA,SAAS,oBACP,QAAQ"}
@@ -46,10 +46,12 @@ var CloudflareCredentialsInvalid = class extends EdgeError {
46
46
  var CloudflarePermissionMissing = class extends EdgeError {
47
47
  domain;
48
48
  detail;
49
- constructor(domain, detail) {
50
- super(`The Cloudflare token may not change ${domain}'s DNS${detail ? ` (${detail})` : ""}. Give it Zone:Read and DNS:Edit on ${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`);
49
+ permission;
50
+ constructor(domain, detail, permission = DNS_PERMISSIONS) {
51
+ super(`The Cloudflare token was refused on ${domain}${detail ? ` (${detail})` : ""}. Give it ${permission} on ${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`);
51
52
  this.domain = domain;
52
53
  this.detail = detail;
54
+ this.permission = permission;
53
55
  this.name = "CloudflarePermissionMissing";
54
56
  }
55
57
  };
@@ -100,6 +102,10 @@ var CloudflareRecordNotAllowed = class extends EdgeError {
100
102
  this.name = "CloudflareRecordNotAllowed";
101
103
  }
102
104
  };
105
+ /** What reading and writing a zone's records needs. */
106
+ const DNS_PERMISSIONS = "Zone:Read and DNS:Edit";
107
+ /** What an origin certificate needs, beside finding the zone. */
108
+ const ORIGIN_CA_PERMISSIONS = "Zone:Read and SSL and Certificates:Edit";
103
109
  /** Cloudflare's authentication error codes: a bad or unusable token. */
104
110
  const AUTH_CODES = /* @__PURE__ */ new Set([
105
111
  6003,
@@ -120,7 +126,7 @@ var CloudflareApi = class {
120
126
  this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
121
127
  this.maxAttempts = options.maxAttempts ?? 4;
122
128
  }
123
- async request(domain, method, path, body) {
129
+ async request(domain, method, path, body, permission = DNS_PERMISSIONS) {
124
130
  for (let attempt = 1;; attempt++) {
125
131
  const response = await fetch(`${this.baseUrl}${path}`, {
126
132
  method,
@@ -146,7 +152,7 @@ var CloudflareApi = class {
146
152
  const errors = envelope?.errors ?? [];
147
153
  const detail = errors.map((e) => e.message).join("; ") || void 0;
148
154
  if (response.status === 401 || errors.some((e) => AUTH_CODES.has(e.code))) throw new CloudflareCredentialsInvalid(detail);
149
- if (response.status === 403) throw new CloudflarePermissionMissing(domain, detail);
155
+ if (response.status === 403) throw new CloudflarePermissionMissing(domain, detail, permission);
150
156
  throw new CloudflareRequestFailed(method, path, response.status, errors);
151
157
  }
152
158
  }
@@ -188,6 +194,23 @@ var CloudflareApi = class {
188
194
  const { result } = await this.request(domain, "PATCH", `/zones/${zone}/dns_records/${id}`, record);
189
195
  return result;
190
196
  }
197
+ /**
198
+ * An origin certificate from Cloudflare's Origin CA, for a CSR made where
199
+ * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid
200
+ * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs
201
+ * `Zone → SSL and Certificates → Edit` on the zone.
202
+ *
203
+ * @param domain - the zone, for what an error says
204
+ */
205
+ async createOriginCertificate(domain, request) {
206
+ const { result } = await this.request(domain, "POST", "/certificates", {
207
+ csr: request.csr,
208
+ hostnames: [...request.hostnames],
209
+ requested_validity: request.days,
210
+ request_type: request.type
211
+ }, ORIGIN_CA_PERMISSIONS);
212
+ return result;
213
+ }
191
214
  async deleteRecord(domain, id) {
192
215
  const zone = await this.zoneId(domain);
193
216
  await this.request(domain, "DELETE", `/zones/${zone}/dns_records/${id}`);
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"sourcesContent":["/**\n * Cloudflare's v4 DNS API, as gkm uses it: the records of one name and type\n * at a time, inside a zone found by its name.\n *\n * - zone: `GET /zones?name={domain}` — the one call that is not a record's\n * - read: `GET /zones/{zone}/dns_records?type={type}&name.exact={fqdn}`\n * - create: `POST /zones/{zone}/dns_records`\n * - update: `PATCH /zones/{zone}/dns_records/{id}`\n * - delete: `DELETE /zones/{zone}/dns_records/{id}`\n *\n * Never the zone itself, its settings or the account. An API token with\n * `Zone:Read` and `DNS:Edit` on the zone is all it needs, sent as\n * `Authorization: Bearer <token>`.\n *\n * Every answer is the v4 envelope — `{ success, errors, result }` — and a\n * failure is read from its `errors`, not from the status alone. A 429 is\n * waited out a few times (its `Retry-After`, else a second) before the run\n * gives up with {@link CloudflareRateLimited}.\n */\n\nimport { EdgeError } from '../../errors';\n\n/** A Cloudflare API token, sent as `Authorization: Bearer <token>`. */\nexport interface CloudflareCredential {\n\ttoken: string;\n}\n\nexport const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4';\n\n/**\n * Cloudflare's \"automatic\" TTL — 300 seconds, and the only TTL a proxied\n * record takes.\n */\nexport const CLOUDFLARE_AUTO_TTL = 1;\n\n/** The record types gkm writes. Never TXT, NS, SOA, SRV or CAA. */\nexport const CLOUDFLARE_MANAGED_TYPES = ['A', 'AAAA', 'CNAME', 'MX'] as const;\n\nexport type CloudflareRecordType = (typeof CLOUDFLARE_MANAGED_TYPES)[number];\n\n/** One record as Cloudflare returns it. */\nexport interface CloudflareRecord {\n\tid: string;\n\ttype: string;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\t/** Whether Cloudflare's proxy answers for it — its CDN, the orange cloud. */\n\tproxied?: boolean;\n\t/** An MX record's: Cloudflare keeps it apart from `content`. */\n\tpriority?: number;\n}\n\n/** What a write sends. */\nexport interface CloudflareRecordInput {\n\ttype: CloudflareRecordType;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\tproxied?: boolean;\n\tpriority?: number;\n}\n\n/** The v4 envelope. */\ninterface Envelope<T> {\n\tsuccess: boolean;\n\terrors?: { code: number; message: string }[];\n\tresult: T;\n\tresult_info?: { page: number; total_pages: number };\n}\n\n/** The token is missing, malformed, expired or revoked. */\nexport class CloudflareCredentialsInvalid extends EdgeError {\n\tconstructor(readonly detail?: string) {\n\t\tsuper(\n\t\t\t`Cloudflare refused the API token${detail ? ` (${detail})` : ''}. ` +\n\t\t\t\t'Create one at dash.cloudflare.com/profile/api-tokens with Zone:Read ' +\n\t\t\t\t'and DNS:Edit on the zone, then set CLOUDFLARE_API_TOKEN or run ' +\n\t\t\t\t'`gkm login --provider cloudflare`.',\n\t\t);\n\t\tthis.name = 'CloudflareCredentialsInvalid';\n\t}\n}\n\n/** The token is good, and may not do this to this zone. */\nexport class CloudflarePermissionMissing extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly detail?: string,\n\t) {\n\t\tsuper(\n\t\t\t`The Cloudflare token may not change ${domain}'s DNS` +\n\t\t\t\t`${detail ? ` (${detail})` : ''}. Give it Zone:Read and DNS:Edit on ` +\n\t\t\t\t`${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`,\n\t\t);\n\t\tthis.name = 'CloudflarePermissionMissing';\n\t}\n}\n\n/** No zone of that name is in the token's reach. */\nexport class CloudflareZoneNotFound extends EdgeError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`Cloudflare has no zone ${domain} the token can read. Add ${domain} to ` +\n\t\t\t\t'the Cloudflare account and point its nameservers at Cloudflare, and ' +\n\t\t\t\t\"make sure the token's zone resources include it.\",\n\t\t);\n\t\tthis.name = 'CloudflareZoneNotFound';\n\t}\n}\n\n/** Still rate limited after waiting it out. */\nexport class CloudflareRateLimited extends EdgeError {\n\tconstructor(readonly attempts: number) {\n\t\tsuper(\n\t\t\t`Cloudflare kept answering 429 Too Many Requests after ${attempts} ` +\n\t\t\t\t'attempts. Wait a few minutes and deploy again: every record written ' +\n\t\t\t\t'so far is kept.',\n\t\t);\n\t\tthis.name = 'CloudflareRateLimited';\n\t}\n}\n\n/** Any other answer that is not a success. */\nexport class CloudflareRequestFailed extends EdgeError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly path: string,\n\t\treadonly status: number,\n\t\t/** Cloudflare's `errors`, as it answered them. */\n\t\treadonly failures: readonly { code: number; message: string }[],\n\t) {\n\t\tconst detail =\n\t\t\tfailures.length > 0\n\t\t\t\t? failures.map((e) => `${e.code}: ${e.message}`).join('; ')\n\t\t\t\t: `HTTP ${status}`;\n\t\tsuper(`Cloudflare refused ${method} ${path}: ${detail}.`);\n\t\tthis.name = 'CloudflareRequestFailed';\n\t}\n}\n\n/** A record type gkm does not write. */\nexport class CloudflareRecordNotAllowed extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly type: string,\n\t\t/** The record's name, as it was asked for: `api`, `@`. */\n\t\treadonly record: string,\n\t) {\n\t\tsuper(\n\t\t\t`gkm does not manage ${type} records, so it will not touch '${record}' ` +\n\t\t\t\t`${type} in ${domain}: only ${CLOUDFLARE_MANAGED_TYPES.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CloudflareRecordNotAllowed';\n\t}\n}\n\n/** Cloudflare's authentication error codes: a bad or unusable token. */\nconst AUTH_CODES = new Set([6003, 6111, 9106, 9109, 10000]);\n\nexport interface CloudflareApiOptions {\n\tcredential: CloudflareCredential;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: (ms: number) => Promise<void>;\n\tmaxAttempts?: number;\n}\n\nexport class CloudflareApi {\n\tprivate readonly baseUrl: string;\n\tprivate readonly sleep: (ms: number) => Promise<void>;\n\tprivate readonly maxAttempts: number;\n\tprivate readonly zones = new Map<string, string>();\n\n\tconstructor(private readonly options: CloudflareApiOptions) {\n\t\tthis.baseUrl = (options.baseUrl ?? CLOUDFLARE_API_BASE).replace(/\\/$/, '');\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis.maxAttempts = options.maxAttempts ?? 4;\n\t}\n\n\tprivate async request<T>(\n\t\tdomain: string,\n\t\tmethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n\t\tpath: string,\n\t\tbody?: unknown,\n\t): Promise<Envelope<T>> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.options.credential.token}`,\n\t\t\t\t\t...(body ? { 'Content-Type': 'application/json' } : {}),\n\t\t\t\t},\n\t\t\t\t...(body ? { body: JSON.stringify(body) } : {}),\n\t\t\t});\n\t\t\tif (response.status === 429) {\n\t\t\t\tif (attempt >= this.maxAttempts) {\n\t\t\t\t\tthrow new CloudflareRateLimited(attempt);\n\t\t\t\t}\n\t\t\t\tconst after = Number(response.headers.get('retry-after'));\n\t\t\t\tawait this.sleep(\n\t\t\t\t\tNumber.isFinite(after) && after > 0 ? after * 1000 : 1000,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet envelope: Envelope<T> | undefined;\n\t\t\ttry {\n\t\t\t\tenvelope = (await response.json()) as Envelope<T>;\n\t\t\t} catch {\n\t\t\t\tenvelope = undefined;\n\t\t\t}\n\t\t\tif (response.ok && envelope?.success) return envelope;\n\t\t\tconst errors = envelope?.errors ?? [];\n\t\t\tconst detail = errors.map((e) => e.message).join('; ') || undefined;\n\t\t\tif (\n\t\t\t\tresponse.status === 401 ||\n\t\t\t\terrors.some((e) => AUTH_CODES.has(e.code))\n\t\t\t) {\n\t\t\t\tthrow new CloudflareCredentialsInvalid(detail);\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\tthrow new CloudflarePermissionMissing(domain, detail);\n\t\t\t}\n\t\t\tthrow new CloudflareRequestFailed(method, path, response.status, errors);\n\t\t}\n\t}\n\n\t/** The zone's id, found once by its name. */\n\tasync zoneId(domain: string): Promise<string> {\n\t\tconst key = domain.toLowerCase();\n\t\tconst known = this.zones.get(key);\n\t\tif (known) return known;\n\t\tconst { result } = await this.request<{ id: string; name: string }[]>(\n\t\t\tkey,\n\t\t\t'GET',\n\t\t\t`/zones?name=${encodeURIComponent(key)}`,\n\t\t);\n\t\tconst zone = result.find((z) => z.name.toLowerCase() === key);\n\t\tif (!zone) throw new CloudflareZoneNotFound(key);\n\t\tthis.zones.set(key, zone.id);\n\t\treturn zone.id;\n\t}\n\n\t/** Every record of exactly this name and type — of the type, without a name. */\n\tasync getRecords(\n\t\tdomain: string,\n\t\ttype: CloudflareRecordType,\n\t\tfqdn?: string,\n\t): Promise<CloudflareRecord[]> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst found: CloudflareRecord[] = [];\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst query = new URLSearchParams({\n\t\t\t\ttype,\n\t\t\t\t...(fqdn ? { 'name.exact': fqdn } : {}),\n\t\t\t\tper_page: '100',\n\t\t\t\tpage: String(page),\n\t\t\t});\n\t\t\tconst envelope = await this.request<CloudflareRecord[]>(\n\t\t\t\tdomain,\n\t\t\t\t'GET',\n\t\t\t\t`/zones/${zone}/dns_records?${query}`,\n\t\t\t);\n\t\t\tfound.push(...envelope.result);\n\t\t\tconst info = envelope.result_info;\n\t\t\tif (!info || info.page >= info.total_pages) return found;\n\t\t}\n\t}\n\n\tasync createRecord(\n\t\tdomain: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t`/zones/${zone}/dns_records`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync updateRecord(\n\t\tdomain: string,\n\t\tid: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'PATCH',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync deleteRecord(domain: string, id: string): Promise<void> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tawait this.request<unknown>(\n\t\t\tdomain,\n\t\t\t'DELETE',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t);\n\t}\n}\n","/**\n * Cloudflare DNS Provider\n *\n * Implements DnsProvider against Cloudflare's v4 API, one name and type at a\n * time: it reads and writes only the A, AAAA, CNAME and MX records of the\n * names it is handed, inside the zone found by the domain's name, and never\n * the zone's settings or the account. An API token with `Zone:Read` and\n * `DNS:Edit` on the zone is all it needs.\n *\n * Cloudflare is also a CDN: a record it proxies (`proxied: true`, the orange\n * cloud) is answered by Cloudflare's edge, which forwards to the record's\n * value. A write that says `proxied` sets it; one that does not leaves an\n * existing record's as it was and creates a new one unproxied — so a\n * certificate's validation CNAME, which Cloudflare must not answer, is\n * never proxied by accident. A proxied record's TTL is always Cloudflare's\n * automatic one.\n *\n * Cloudflare can hold several records of one name and type; an upsert leaves\n * exactly one, with its value. An MX value is `<priority> <host>` on the\n * DnsProvider side, as everywhere in gkm; Cloudflare keeps the priority\n * apart, so it is split on a write and joined on a read.\n *\n * Credentials: `CLOUDFLARE_API_TOKEN`, else what `gkm login --provider\n * cloudflare` stored. Never logged.\n */\n\nimport {\n\ttype DeleteDnsRecord,\n\ttype DeleteResult,\n\ttype DnsProvider,\n\ttype DnsRecord,\n\tmxValue,\n\tparseMxValue,\n\ttype UpsertDnsRecord,\n\ttype UpsertResult,\n} from '../index';\nimport {\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n} from './api';\n\n/** Cloudflare refuses a TTL under this, but for its automatic one. */\nconst CLOUDFLARE_MIN_TTL = 60;\n\nexport interface CloudflareProviderOptions {\n\t/**\n\t * Where the token comes from, asked the first time the API is called. It\n\t * throws when there is none: what to do about a missing token is the\n\t * caller's to say.\n\t */\n\tcredential: () => Promise<CloudflareCredential>;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: CloudflareApiOptions['sleep'];\n\tmaxAttempts?: number;\n}\n\n/** A value compared the way DNS does: case-insensitive, no trailing dot. */\nfunction normalize(value: string): string {\n\treturn value.trim().replace(/\\.$/, '').replace(/\\s+/g, ' ').toLowerCase();\n}\n\n/** `api` under `example.com` → `api.example.com`; `@` → `example.com`. */\nexport function fullName(name: string, domain: string): string {\n\tconst zone = domain.toLowerCase().replace(/\\.$/, '');\n\tconst label = name.trim().toLowerCase().replace(/\\.$/, '');\n\tif (label === '@' || label === '' || label === zone) return zone;\n\treturn label.endsWith(`.${zone}`) ? label : `${label}.${zone}`;\n}\n\n/** A Cloudflare record's value in gkm's form: an MX's is `<priority> <host>`. */\nfunction valueOf(record: CloudflareRecord): string {\n\treturn record.type === 'MX'\n\t\t? mxValue(record.priority ?? 0, record.content)\n\t\t: record.content;\n}\n\nfunction managed(type: string): type is CloudflareRecordType {\n\treturn (CLOUDFLARE_MANAGED_TYPES as readonly string[]).includes(type);\n}\n\n/** Only an address or an alias can be proxied. */\nfunction proxiable(type: string): boolean {\n\treturn type === 'A' || type === 'AAAA' || type === 'CNAME';\n}\n\nexport class CloudflareProvider implements DnsProvider {\n\treadonly name = 'cloudflare';\n\tprivate api: CloudflareApi | null = null;\n\n\tconstructor(private readonly options: CloudflareProviderOptions) {}\n\n\tprivate async getApi(): Promise<CloudflareApi> {\n\t\tif (this.api) return this.api;\n\t\tconst credential = await this.options.credential();\n\t\tthis.api = new CloudflareApi({\n\t\t\tcredential,\n\t\t\t...(this.options.baseUrl ? { baseUrl: this.options.baseUrl } : {}),\n\t\t\t...(this.options.sleep ? { sleep: this.options.sleep } : {}),\n\t\t\t...(this.options.maxAttempts\n\t\t\t\t? { maxAttempts: this.options.maxAttempts }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn this.api;\n\t}\n\n\tprivate assertManaged(domain: string, type: string, name: string): void {\n\t\tif (!managed(type))\n\t\t\tthrow new CloudflareRecordNotAllowed(domain, type, name);\n\t}\n\n\t/**\n\t * The managed records of the whole zone: A, AAAA, CNAME and MX. Prefer\n\t * {@link readRecords}, which asks for exactly the names it needs.\n\t */\n\tasync getRecords(domain: string): Promise<DnsRecord[]> {\n\t\tconst api = await this.getApi();\n\t\tconst zone = domain.toLowerCase();\n\t\tconst out: DnsRecord[] = [];\n\t\tfor (const type of CLOUDFLARE_MANAGED_TYPES) {\n\t\t\tconst records = await api.getRecords(zone, type);\n\t\t\tout.push(...group(zone, type, records));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** The records of exactly these names and types, one request each. */\n\tasync readRecords(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]> {\n\t\tfor (const { name, type } of wanted) this.assertManaged(domain, type, name);\n\t\tconst api = await this.getApi();\n\t\tconst found: DnsRecord[] = [];\n\t\tfor (const { name, type } of wanted) {\n\t\t\tconst records = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\ttype as CloudflareRecordType,\n\t\t\t\tfullName(name, domain),\n\t\t\t);\n\t\t\tfound.push(...group(domain, type as CloudflareRecordType, records, name));\n\t\t}\n\t\treturn found;\n\t}\n\n\t/**\n\t * Each name and type set to exactly its one value: read it, and write it\n\t * only when its value or its proxy differ. The first record of the name\n\t * is updated in place and any other of that type deleted, so the set\n\t * ends up with one.\n\t */\n\tasync upsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]> {\n\t\t// Every record is checked before any is written, so a refused one\n\t\t// leaves the zone as it was.\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\n\t\tconst results: UpsertResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as CloudflareRecordType;\n\t\t\tconst name = fullName(record.name, domain);\n\t\t\tconst existing = await api.getRecords(domain, type, name);\n\t\t\tconst [first, ...rest] = existing;\n\t\t\tconst proxied = proxiable(type)\n\t\t\t\t? (record.proxied ?? first?.proxied ?? false)\n\t\t\t\t: undefined;\n\n\t\t\tif (\n\t\t\t\tfirst &&\n\t\t\t\trest.length === 0 &&\n\t\t\t\tnormalize(valueOf(first)) === normalize(record.value) &&\n\t\t\t\t(proxied === undefined || (first.proxied ?? false) === proxied)\n\t\t\t) {\n\t\t\t\tresults.push({ record, created: false, unchanged: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst input = recordInput(type, name, record, proxied);\n\t\t\tif (first) await api.updateRecord(domain, first.id, input);\n\t\t\telse await api.createRecord(domain, input);\n\t\t\tfor (const extra of rest) await api.deleteRecord(domain, extra.id);\n\t\t\tresults.push({ record, created: !first, unchanged: false });\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]> {\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\t\tconst results: DeleteResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst existing = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\trecord.type as CloudflareRecordType,\n\t\t\t\tfullName(record.name, domain),\n\t\t\t);\n\t\t\tif (existing.length === 0) {\n\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const found of existing) await api.deleteRecord(domain, found.id);\n\t\t\tresults.push({ record, deleted: true, notFound: false });\n\t\t}\n\t\treturn results;\n\t}\n}\n\n/** What a write sends for one record. */\nfunction recordInput(\n\ttype: CloudflareRecordType,\n\tname: string,\n\trecord: UpsertDnsRecord,\n\tproxied: boolean | undefined,\n): CloudflareRecordInput {\n\tconst ttl = proxied\n\t\t? CLOUDFLARE_AUTO_TTL\n\t\t: Math.max(record.ttl, CLOUDFLARE_MIN_TTL);\n\tif (type === 'MX') {\n\t\tconst { priority, host } = parseMxValue(record.value);\n\t\treturn { type, name, content: host, priority, ttl };\n\t}\n\treturn {\n\t\ttype,\n\t\tname,\n\t\tcontent: record.value.trim().replace(/\\.$/, ''),\n\t\tttl,\n\t\t...(proxied !== undefined ? { proxied } : {}),\n\t};\n}\n\n/**\n * Cloudflare's records as DnsRecords: one per name, its values together,\n * named relative to the domain (`@` for the apex) — or as `asked`, when the\n * caller named it.\n */\nfunction group(\n\tdomain: string,\n\ttype: CloudflareRecordType,\n\trecords: readonly CloudflareRecord[],\n\tasked?: string,\n): DnsRecord[] {\n\tconst zone = domain.toLowerCase();\n\tconst byName = new Map<string, CloudflareRecord[]>();\n\tfor (const record of records) {\n\t\tconst fqdn = record.name.toLowerCase();\n\t\tbyName.set(fqdn, [...(byName.get(fqdn) ?? []), record]);\n\t}\n\treturn [...byName.entries()].map(([fqdn, set]) => ({\n\t\tname:\n\t\t\tasked ??\n\t\t\t(fqdn === zone ? '@' : fqdn.slice(0, fqdn.length - zone.length - 1)),\n\t\ttype,\n\t\tttl: set[0]!.ttl === CLOUDFLARE_AUTO_TTL ? 300 : set[0]!.ttl,\n\t\tvalues: set.map(valueOf),\n\t\t...(proxiable(type) ? { proxied: set[0]!.proxied ?? false } : {}),\n\t}));\n}\n\nexport {\n\tCLOUDFLARE_API_BASE,\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\tCloudflareCredentialsInvalid,\n\tCloudflarePermissionMissing,\n\tCloudflareRateLimited,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n\tCloudflareRequestFailed,\n\tCloudflareZoneNotFound,\n} from './api';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,sBAAsB;;;;;AAMnC,MAAa,sBAAsB;;AAGnC,MAAa,2BAA2B;CAAC;CAAK;CAAQ;CAAS;AAAI;;AAsCnE,IAAa,+BAAb,cAAkD,UAAU;CACtC;CAArB,YAAY,QAA0B;EACrC,MACC,mCAAmC,SAAS,KAAK,OAAO,KAAK,GAAG,0KAIjE;EANoB,KAAA,SAAA;EAOpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,8BAAb,cAAiD,UAAU;CAEhD;CACA;CAFV,YACC,QACA,QACC;EACD,MACC,uCAAuC,OAAO,QAC1C,SAAS,KAAK,OAAO,KAAK,GAAG,sCAC7B,OAAO,8DACZ;EAPS,KAAA,SAAA;EACA,KAAA,SAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,yBAAb,cAA4C,UAAU;CAChC;CAArB,YAAY,QAAyB;EACpC,MACC,0BAA0B,OAAO,2BAA2B,OAAO,yHAGpE;EALoB,KAAA,SAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wBAAb,cAA2C,UAAU;CAC/B;CAArB,YAAY,UAA2B;EACtC,MACC,yDAAyD,SAAS,qFAGnE;EALoB,KAAA,WAAA;EAMpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,0BAAb,cAA6C,UAAU;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AAO,OAAO,KAAK,YAAY;EACrC,OAAO,IAAI,MAAM,CAAC,GAAI,OAAO,IAAI,IAAI,KAAK,CAAC,GAAI,MAAM,CAAC;CACvD;CACA,OAAO,CAAC,GAAG,OAAO,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,UAAU;EAClD,MACC,UACC,SAAS,OAAO,MAAM,KAAK,MAAM,GAAG,KAAK,SAAS,KAAK,SAAS,CAAC;EACnE;EACA,KAAK,IAAI,EAAE,CAAE,QAAA,IAA8B,MAAM,IAAI,EAAE,CAAE;EACzD,QAAQ,IAAI,IAAI,OAAO;EACvB,GAAI,UAAU,IAAI,IAAI,EAAE,SAAS,IAAI,EAAE,CAAE,WAAW,MAAM,IAAI,CAAC;CAChE,EAAE;AACH"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../../src/dns/cloudflare/api.ts","../../../src/dns/cloudflare/index.ts"],"sourcesContent":["/**\n * Cloudflare's v4 DNS API, as gkm uses it: the records of one name and type\n * at a time, inside a zone found by its name.\n *\n * - zone: `GET /zones?name={domain}` — the one call that is not a record's\n * - read: `GET /zones/{zone}/dns_records?type={type}&name.exact={fqdn}`\n * - create: `POST /zones/{zone}/dns_records`\n * - update: `PATCH /zones/{zone}/dns_records/{id}`\n * - delete: `DELETE /zones/{zone}/dns_records/{id}`\n *\n * Never the zone itself, its settings or the account. An API token with\n * `Zone:Read` and `DNS:Edit` on the zone is all it needs, sent as\n * `Authorization: Bearer <token>`.\n *\n * Every answer is the v4 envelope — `{ success, errors, result }` — and a\n * failure is read from its `errors`, not from the status alone. A 429 is\n * waited out a few times (its `Retry-After`, else a second) before the run\n * gives up with {@link CloudflareRateLimited}.\n */\n\nimport { EdgeError } from '../../errors';\n\n/** A Cloudflare API token, sent as `Authorization: Bearer <token>`. */\nexport interface CloudflareCredential {\n\ttoken: string;\n}\n\nexport const CLOUDFLARE_API_BASE = 'https://api.cloudflare.com/client/v4';\n\n/**\n * Cloudflare's \"automatic\" TTL — 300 seconds, and the only TTL a proxied\n * record takes.\n */\nexport const CLOUDFLARE_AUTO_TTL = 1;\n\n/** The record types gkm writes. Never TXT, NS, SOA, SRV or CAA. */\nexport const CLOUDFLARE_MANAGED_TYPES = ['A', 'AAAA', 'CNAME', 'MX'] as const;\n\nexport type CloudflareRecordType = (typeof CLOUDFLARE_MANAGED_TYPES)[number];\n\n/** One record as Cloudflare returns it. */\nexport interface CloudflareRecord {\n\tid: string;\n\ttype: string;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\t/** Whether Cloudflare's proxy answers for it — its CDN, the orange cloud. */\n\tproxied?: boolean;\n\t/** An MX record's: Cloudflare keeps it apart from `content`. */\n\tpriority?: number;\n}\n\n/** What a write sends. */\nexport interface CloudflareRecordInput {\n\ttype: CloudflareRecordType;\n\t/** The full name: `api.example.com`. */\n\tname: string;\n\tcontent: string;\n\tttl: number;\n\tproxied?: boolean;\n\tpriority?: number;\n}\n\n/** An origin certificate as the Origin CA returns it. */\nexport interface CloudflareOriginCertificate {\n\t/** Its serial number. */\n\tid: string;\n\t/** PEM. */\n\tcertificate: string;\n\thostnames: string[];\n\t/** `2041-11-22 10:00:00 +0000 UTC` */\n\texpires_on: string;\n}\n\n/** The v4 envelope. */\ninterface Envelope<T> {\n\tsuccess: boolean;\n\terrors?: { code: number; message: string }[];\n\tresult: T;\n\tresult_info?: { page: number; total_pages: number };\n}\n\n/** The token is missing, malformed, expired or revoked. */\nexport class CloudflareCredentialsInvalid extends EdgeError {\n\tconstructor(readonly detail?: string) {\n\t\tsuper(\n\t\t\t`Cloudflare refused the API token${detail ? ` (${detail})` : ''}. ` +\n\t\t\t\t'Create one at dash.cloudflare.com/profile/api-tokens with Zone:Read ' +\n\t\t\t\t'and DNS:Edit on the zone, then set CLOUDFLARE_API_TOKEN or run ' +\n\t\t\t\t'`gkm login --provider cloudflare`.',\n\t\t);\n\t\tthis.name = 'CloudflareCredentialsInvalid';\n\t}\n}\n\n/** The token is good, and may not do this to this zone. */\nexport class CloudflarePermissionMissing extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly detail?: string,\n\t\t/** What the token needs for it: `Zone:Read and DNS:Edit`. */\n\t\treadonly permission: string = DNS_PERMISSIONS,\n\t) {\n\t\tsuper(\n\t\t\t`The Cloudflare token was refused on ${domain}` +\n\t\t\t\t`${detail ? ` (${detail})` : ''}. Give it ${permission} on ` +\n\t\t\t\t`${domain} (dash.cloudflare.com/profile/api-tokens → the token → Edit).`,\n\t\t);\n\t\tthis.name = 'CloudflarePermissionMissing';\n\t}\n}\n\n/** No zone of that name is in the token's reach. */\nexport class CloudflareZoneNotFound extends EdgeError {\n\tconstructor(readonly domain: string) {\n\t\tsuper(\n\t\t\t`Cloudflare has no zone ${domain} the token can read. Add ${domain} to ` +\n\t\t\t\t'the Cloudflare account and point its nameservers at Cloudflare, and ' +\n\t\t\t\t\"make sure the token's zone resources include it.\",\n\t\t);\n\t\tthis.name = 'CloudflareZoneNotFound';\n\t}\n}\n\n/** Still rate limited after waiting it out. */\nexport class CloudflareRateLimited extends EdgeError {\n\tconstructor(readonly attempts: number) {\n\t\tsuper(\n\t\t\t`Cloudflare kept answering 429 Too Many Requests after ${attempts} ` +\n\t\t\t\t'attempts. Wait a few minutes and deploy again: every record written ' +\n\t\t\t\t'so far is kept.',\n\t\t);\n\t\tthis.name = 'CloudflareRateLimited';\n\t}\n}\n\n/** Any other answer that is not a success. */\nexport class CloudflareRequestFailed extends EdgeError {\n\tconstructor(\n\t\treadonly method: string,\n\t\treadonly path: string,\n\t\treadonly status: number,\n\t\t/** Cloudflare's `errors`, as it answered them. */\n\t\treadonly failures: readonly { code: number; message: string }[],\n\t) {\n\t\tconst detail =\n\t\t\tfailures.length > 0\n\t\t\t\t? failures.map((e) => `${e.code}: ${e.message}`).join('; ')\n\t\t\t\t: `HTTP ${status}`;\n\t\tsuper(`Cloudflare refused ${method} ${path}: ${detail}.`);\n\t\tthis.name = 'CloudflareRequestFailed';\n\t}\n}\n\n/** A record type gkm does not write. */\nexport class CloudflareRecordNotAllowed extends EdgeError {\n\tconstructor(\n\t\treadonly domain: string,\n\t\treadonly type: string,\n\t\t/** The record's name, as it was asked for: `api`, `@`. */\n\t\treadonly record: string,\n\t) {\n\t\tsuper(\n\t\t\t`gkm does not manage ${type} records, so it will not touch '${record}' ` +\n\t\t\t\t`${type} in ${domain}: only ${CLOUDFLARE_MANAGED_TYPES.join(', ')}.`,\n\t\t);\n\t\tthis.name = 'CloudflareRecordNotAllowed';\n\t}\n}\n\n/** What reading and writing a zone's records needs. */\nconst DNS_PERMISSIONS = 'Zone:Read and DNS:Edit';\n\n/** What an origin certificate needs, beside finding the zone. */\nconst ORIGIN_CA_PERMISSIONS = 'Zone:Read and SSL and Certificates:Edit';\n\n/** Cloudflare's authentication error codes: a bad or unusable token. */\nconst AUTH_CODES = new Set([6003, 6111, 9106, 9109, 10000]);\n\nexport interface CloudflareApiOptions {\n\tcredential: CloudflareCredential;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: (ms: number) => Promise<void>;\n\tmaxAttempts?: number;\n}\n\nexport class CloudflareApi {\n\tprivate readonly baseUrl: string;\n\tprivate readonly sleep: (ms: number) => Promise<void>;\n\tprivate readonly maxAttempts: number;\n\tprivate readonly zones = new Map<string, string>();\n\n\tconstructor(private readonly options: CloudflareApiOptions) {\n\t\tthis.baseUrl = (options.baseUrl ?? CLOUDFLARE_API_BASE).replace(/\\/$/, '');\n\t\tthis.sleep =\n\t\t\toptions.sleep ??\n\t\t\t((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis.maxAttempts = options.maxAttempts ?? 4;\n\t}\n\n\tprivate async request<T>(\n\t\tdomain: string,\n\t\tmethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n\t\tpath: string,\n\t\tbody?: unknown,\n\t\tpermission: string = DNS_PERMISSIONS,\n\t): Promise<Envelope<T>> {\n\t\tfor (let attempt = 1; ; attempt++) {\n\t\t\tconst response = await fetch(`${this.baseUrl}${path}`, {\n\t\t\t\tmethod,\n\t\t\t\theaders: {\n\t\t\t\t\tAuthorization: `Bearer ${this.options.credential.token}`,\n\t\t\t\t\t...(body ? { 'Content-Type': 'application/json' } : {}),\n\t\t\t\t},\n\t\t\t\t...(body ? { body: JSON.stringify(body) } : {}),\n\t\t\t});\n\t\t\tif (response.status === 429) {\n\t\t\t\tif (attempt >= this.maxAttempts) {\n\t\t\t\t\tthrow new CloudflareRateLimited(attempt);\n\t\t\t\t}\n\t\t\t\tconst after = Number(response.headers.get('retry-after'));\n\t\t\t\tawait this.sleep(\n\t\t\t\t\tNumber.isFinite(after) && after > 0 ? after * 1000 : 1000,\n\t\t\t\t);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlet envelope: Envelope<T> | undefined;\n\t\t\ttry {\n\t\t\t\tenvelope = (await response.json()) as Envelope<T>;\n\t\t\t} catch {\n\t\t\t\tenvelope = undefined;\n\t\t\t}\n\t\t\tif (response.ok && envelope?.success) return envelope;\n\t\t\tconst errors = envelope?.errors ?? [];\n\t\t\tconst detail = errors.map((e) => e.message).join('; ') || undefined;\n\t\t\tif (\n\t\t\t\tresponse.status === 401 ||\n\t\t\t\terrors.some((e) => AUTH_CODES.has(e.code))\n\t\t\t) {\n\t\t\t\tthrow new CloudflareCredentialsInvalid(detail);\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\tthrow new CloudflarePermissionMissing(domain, detail, permission);\n\t\t\t}\n\t\t\tthrow new CloudflareRequestFailed(method, path, response.status, errors);\n\t\t}\n\t}\n\n\t/** The zone's id, found once by its name. */\n\tasync zoneId(domain: string): Promise<string> {\n\t\tconst key = domain.toLowerCase();\n\t\tconst known = this.zones.get(key);\n\t\tif (known) return known;\n\t\tconst { result } = await this.request<{ id: string; name: string }[]>(\n\t\t\tkey,\n\t\t\t'GET',\n\t\t\t`/zones?name=${encodeURIComponent(key)}`,\n\t\t);\n\t\tconst zone = result.find((z) => z.name.toLowerCase() === key);\n\t\tif (!zone) throw new CloudflareZoneNotFound(key);\n\t\tthis.zones.set(key, zone.id);\n\t\treturn zone.id;\n\t}\n\n\t/** Every record of exactly this name and type — of the type, without a name. */\n\tasync getRecords(\n\t\tdomain: string,\n\t\ttype: CloudflareRecordType,\n\t\tfqdn?: string,\n\t): Promise<CloudflareRecord[]> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst found: CloudflareRecord[] = [];\n\t\tfor (let page = 1; ; page++) {\n\t\t\tconst query = new URLSearchParams({\n\t\t\t\ttype,\n\t\t\t\t...(fqdn ? { 'name.exact': fqdn } : {}),\n\t\t\t\tper_page: '100',\n\t\t\t\tpage: String(page),\n\t\t\t});\n\t\t\tconst envelope = await this.request<CloudflareRecord[]>(\n\t\t\t\tdomain,\n\t\t\t\t'GET',\n\t\t\t\t`/zones/${zone}/dns_records?${query}`,\n\t\t\t);\n\t\t\tfound.push(...envelope.result);\n\t\t\tconst info = envelope.result_info;\n\t\t\tif (!info || info.page >= info.total_pages) return found;\n\t\t}\n\t}\n\n\tasync createRecord(\n\t\tdomain: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t`/zones/${zone}/dns_records`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync updateRecord(\n\t\tdomain: string,\n\t\tid: string,\n\t\trecord: CloudflareRecordInput,\n\t): Promise<CloudflareRecord> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tconst { result } = await this.request<CloudflareRecord>(\n\t\t\tdomain,\n\t\t\t'PATCH',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t\trecord,\n\t\t);\n\t\treturn result;\n\t}\n\n\t/**\n\t * An origin certificate from Cloudflare's Origin CA, for a CSR made where\n\t * the key is: trusted by Cloudflare's proxy alone, for `hostnames`, valid\n\t * `days` (one of 7, 30, 90, 365, 730, 1095, 5475). The token needs\n\t * `Zone → SSL and Certificates → Edit` on the zone.\n\t *\n\t * @param domain - the zone, for what an error says\n\t */\n\tasync createOriginCertificate(\n\t\tdomain: string,\n\t\trequest: {\n\t\t\tcsr: string;\n\t\t\thostnames: readonly string[];\n\t\t\tdays: number;\n\t\t\ttype: 'origin-rsa' | 'origin-ecc';\n\t\t},\n\t): Promise<CloudflareOriginCertificate> {\n\t\tconst { result } = await this.request<CloudflareOriginCertificate>(\n\t\t\tdomain,\n\t\t\t'POST',\n\t\t\t'/certificates',\n\t\t\t{\n\t\t\t\tcsr: request.csr,\n\t\t\t\thostnames: [...request.hostnames],\n\t\t\t\trequested_validity: request.days,\n\t\t\t\trequest_type: request.type,\n\t\t\t},\n\t\t\tORIGIN_CA_PERMISSIONS,\n\t\t);\n\t\treturn result;\n\t}\n\n\tasync deleteRecord(domain: string, id: string): Promise<void> {\n\t\tconst zone = await this.zoneId(domain);\n\t\tawait this.request<unknown>(\n\t\t\tdomain,\n\t\t\t'DELETE',\n\t\t\t`/zones/${zone}/dns_records/${id}`,\n\t\t);\n\t}\n}\n","/**\n * Cloudflare DNS Provider\n *\n * Implements DnsProvider against Cloudflare's v4 API, one name and type at a\n * time: it reads and writes only the A, AAAA, CNAME and MX records of the\n * names it is handed, inside the zone found by the domain's name, and never\n * the zone's settings or the account. An API token with `Zone:Read` and\n * `DNS:Edit` on the zone is all it needs.\n *\n * Cloudflare is also a CDN: a record it proxies (`proxied: true`, the orange\n * cloud) is answered by Cloudflare's edge, which forwards to the record's\n * value. A write that says `proxied` sets it; one that does not leaves an\n * existing record's as it was and creates a new one unproxied — so a\n * certificate's validation CNAME, which Cloudflare must not answer, is\n * never proxied by accident. A proxied record's TTL is always Cloudflare's\n * automatic one.\n *\n * Cloudflare can hold several records of one name and type; an upsert leaves\n * exactly one, with its value. An MX value is `<priority> <host>` on the\n * DnsProvider side, as everywhere in gkm; Cloudflare keeps the priority\n * apart, so it is split on a write and joined on a read.\n *\n * Credentials: `CLOUDFLARE_API_TOKEN`, else what `gkm login --provider\n * cloudflare` stored. Never logged.\n */\n\nimport {\n\ttype DeleteDnsRecord,\n\ttype DeleteResult,\n\ttype DnsProvider,\n\ttype DnsRecord,\n\tmxValue,\n\tparseMxValue,\n\ttype UpsertDnsRecord,\n\ttype UpsertResult,\n} from '../index';\nimport {\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n} from './api';\n\n/** Cloudflare refuses a TTL under this, but for its automatic one. */\nconst CLOUDFLARE_MIN_TTL = 60;\n\nexport interface CloudflareProviderOptions {\n\t/**\n\t * Where the token comes from, asked the first time the API is called. It\n\t * throws when there is none: what to do about a missing token is the\n\t * caller's to say.\n\t */\n\tcredential: () => Promise<CloudflareCredential>;\n\t/** The API's base URL, for tests. */\n\tbaseUrl?: string;\n\t/** How a 429 is waited out, for tests. */\n\tsleep?: CloudflareApiOptions['sleep'];\n\tmaxAttempts?: number;\n}\n\n/** A value compared the way DNS does: case-insensitive, no trailing dot. */\nfunction normalize(value: string): string {\n\treturn value.trim().replace(/\\.$/, '').replace(/\\s+/g, ' ').toLowerCase();\n}\n\n/** `api` under `example.com` → `api.example.com`; `@` → `example.com`. */\nexport function fullName(name: string, domain: string): string {\n\tconst zone = domain.toLowerCase().replace(/\\.$/, '');\n\tconst label = name.trim().toLowerCase().replace(/\\.$/, '');\n\tif (label === '@' || label === '' || label === zone) return zone;\n\treturn label.endsWith(`.${zone}`) ? label : `${label}.${zone}`;\n}\n\n/** A Cloudflare record's value in gkm's form: an MX's is `<priority> <host>`. */\nfunction valueOf(record: CloudflareRecord): string {\n\treturn record.type === 'MX'\n\t\t? mxValue(record.priority ?? 0, record.content)\n\t\t: record.content;\n}\n\nfunction managed(type: string): type is CloudflareRecordType {\n\treturn (CLOUDFLARE_MANAGED_TYPES as readonly string[]).includes(type);\n}\n\n/** Only an address or an alias can be proxied. */\nfunction proxiable(type: string): boolean {\n\treturn type === 'A' || type === 'AAAA' || type === 'CNAME';\n}\n\nexport class CloudflareProvider implements DnsProvider {\n\treadonly name = 'cloudflare';\n\tprivate api: CloudflareApi | null = null;\n\n\tconstructor(private readonly options: CloudflareProviderOptions) {}\n\n\tprivate async getApi(): Promise<CloudflareApi> {\n\t\tif (this.api) return this.api;\n\t\tconst credential = await this.options.credential();\n\t\tthis.api = new CloudflareApi({\n\t\t\tcredential,\n\t\t\t...(this.options.baseUrl ? { baseUrl: this.options.baseUrl } : {}),\n\t\t\t...(this.options.sleep ? { sleep: this.options.sleep } : {}),\n\t\t\t...(this.options.maxAttempts\n\t\t\t\t? { maxAttempts: this.options.maxAttempts }\n\t\t\t\t: {}),\n\t\t});\n\t\treturn this.api;\n\t}\n\n\tprivate assertManaged(domain: string, type: string, name: string): void {\n\t\tif (!managed(type))\n\t\t\tthrow new CloudflareRecordNotAllowed(domain, type, name);\n\t}\n\n\t/**\n\t * The managed records of the whole zone: A, AAAA, CNAME and MX. Prefer\n\t * {@link readRecords}, which asks for exactly the names it needs.\n\t */\n\tasync getRecords(domain: string): Promise<DnsRecord[]> {\n\t\tconst api = await this.getApi();\n\t\tconst zone = domain.toLowerCase();\n\t\tconst out: DnsRecord[] = [];\n\t\tfor (const type of CLOUDFLARE_MANAGED_TYPES) {\n\t\t\tconst records = await api.getRecords(zone, type);\n\t\t\tout.push(...group(zone, type, records));\n\t\t}\n\t\treturn out;\n\t}\n\n\t/** The records of exactly these names and types, one request each. */\n\tasync readRecords(\n\t\tdomain: string,\n\t\twanted: readonly DeleteDnsRecord[],\n\t): Promise<DnsRecord[]> {\n\t\tfor (const { name, type } of wanted) this.assertManaged(domain, type, name);\n\t\tconst api = await this.getApi();\n\t\tconst found: DnsRecord[] = [];\n\t\tfor (const { name, type } of wanted) {\n\t\t\tconst records = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\ttype as CloudflareRecordType,\n\t\t\t\tfullName(name, domain),\n\t\t\t);\n\t\t\tfound.push(...group(domain, type as CloudflareRecordType, records, name));\n\t\t}\n\t\treturn found;\n\t}\n\n\t/**\n\t * Each name and type set to exactly its one value: read it, and write it\n\t * only when its value or its proxy differ. The first record of the name\n\t * is updated in place and any other of that type deleted, so the set\n\t * ends up with one.\n\t */\n\tasync upsertRecords(\n\t\tdomain: string,\n\t\trecords: UpsertDnsRecord[],\n\t): Promise<UpsertResult[]> {\n\t\t// Every record is checked before any is written, so a refused one\n\t\t// leaves the zone as it was.\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\n\t\tconst results: UpsertResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst type = record.type as CloudflareRecordType;\n\t\t\tconst name = fullName(record.name, domain);\n\t\t\tconst existing = await api.getRecords(domain, type, name);\n\t\t\tconst [first, ...rest] = existing;\n\t\t\tconst proxied = proxiable(type)\n\t\t\t\t? (record.proxied ?? first?.proxied ?? false)\n\t\t\t\t: undefined;\n\n\t\t\tif (\n\t\t\t\tfirst &&\n\t\t\t\trest.length === 0 &&\n\t\t\t\tnormalize(valueOf(first)) === normalize(record.value) &&\n\t\t\t\t(proxied === undefined || (first.proxied ?? false) === proxied)\n\t\t\t) {\n\t\t\t\tresults.push({ record, created: false, unchanged: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst input = recordInput(type, name, record, proxied);\n\t\t\tif (first) await api.updateRecord(domain, first.id, input);\n\t\t\telse await api.createRecord(domain, input);\n\t\t\tfor (const extra of rest) await api.deleteRecord(domain, extra.id);\n\t\t\tresults.push({ record, created: !first, unchanged: false });\n\t\t}\n\t\treturn results;\n\t}\n\n\tasync deleteRecords(\n\t\tdomain: string,\n\t\trecords: DeleteDnsRecord[],\n\t): Promise<DeleteResult[]> {\n\t\tfor (const record of records) {\n\t\t\tthis.assertManaged(domain, record.type, record.name);\n\t\t}\n\t\tconst api = await this.getApi();\n\t\tconst results: DeleteResult[] = [];\n\t\tfor (const record of records) {\n\t\t\tconst existing = await api.getRecords(\n\t\t\t\tdomain,\n\t\t\t\trecord.type as CloudflareRecordType,\n\t\t\t\tfullName(record.name, domain),\n\t\t\t);\n\t\t\tif (existing.length === 0) {\n\t\t\t\tresults.push({ record, deleted: false, notFound: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (const found of existing) await api.deleteRecord(domain, found.id);\n\t\t\tresults.push({ record, deleted: true, notFound: false });\n\t\t}\n\t\treturn results;\n\t}\n}\n\n/** What a write sends for one record. */\nfunction recordInput(\n\ttype: CloudflareRecordType,\n\tname: string,\n\trecord: UpsertDnsRecord,\n\tproxied: boolean | undefined,\n): CloudflareRecordInput {\n\tconst ttl = proxied\n\t\t? CLOUDFLARE_AUTO_TTL\n\t\t: Math.max(record.ttl, CLOUDFLARE_MIN_TTL);\n\tif (type === 'MX') {\n\t\tconst { priority, host } = parseMxValue(record.value);\n\t\treturn { type, name, content: host, priority, ttl };\n\t}\n\treturn {\n\t\ttype,\n\t\tname,\n\t\tcontent: record.value.trim().replace(/\\.$/, ''),\n\t\tttl,\n\t\t...(proxied !== undefined ? { proxied } : {}),\n\t};\n}\n\n/**\n * Cloudflare's records as DnsRecords: one per name, its values together,\n * named relative to the domain (`@` for the apex) — or as `asked`, when the\n * caller named it.\n */\nfunction group(\n\tdomain: string,\n\ttype: CloudflareRecordType,\n\trecords: readonly CloudflareRecord[],\n\tasked?: string,\n): DnsRecord[] {\n\tconst zone = domain.toLowerCase();\n\tconst byName = new Map<string, CloudflareRecord[]>();\n\tfor (const record of records) {\n\t\tconst fqdn = record.name.toLowerCase();\n\t\tbyName.set(fqdn, [...(byName.get(fqdn) ?? []), record]);\n\t}\n\treturn [...byName.entries()].map(([fqdn, set]) => ({\n\t\tname:\n\t\t\tasked ??\n\t\t\t(fqdn === zone ? '@' : fqdn.slice(0, fqdn.length - zone.length - 1)),\n\t\ttype,\n\t\tttl: set[0]!.ttl === CLOUDFLARE_AUTO_TTL ? 300 : set[0]!.ttl,\n\t\tvalues: set.map(valueOf),\n\t\t...(proxiable(type) ? { proxied: set[0]!.proxied ?? false } : {}),\n\t}));\n}\n\nexport {\n\tCLOUDFLARE_API_BASE,\n\tCLOUDFLARE_AUTO_TTL,\n\tCLOUDFLARE_MANAGED_TYPES,\n\tCloudflareApi,\n\ttype CloudflareApiOptions,\n\ttype CloudflareCredential,\n\tCloudflareCredentialsInvalid,\n\ttype CloudflareOriginCertificate,\n\tCloudflarePermissionMissing,\n\tCloudflareRateLimited,\n\ttype CloudflareRecord,\n\ttype CloudflareRecordInput,\n\tCloudflareRecordNotAllowed,\n\ttype CloudflareRecordType,\n\tCloudflareRequestFailed,\n\tCloudflareZoneNotFound,\n} from './api';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,sBAAsB;;;;;AAMnC,MAAa,sBAAsB;;AAGnC,MAAa,2BAA2B;CAAC;CAAK;CAAQ;CAAS;AAAI;;AAiDnE,IAAa,+BAAb,cAAkD,UAAU;CACtC;CAArB,YAAY,QAA0B;EACrC,MACC,mCAAmC,SAAS,KAAK,OAAO,KAAK,GAAG,0KAIjE;EANoB,KAAA,SAAA;EAOpB,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,8BAAb,cAAiD,UAAU;CAEhD;CACA;CAEA;CAJV,YACC,QACA,QAEA,aAA8B,iBAC7B;EACD,MACC,uCAAuC,SACnC,SAAS,KAAK,OAAO,KAAK,GAAG,YAAY,WAAW,MACpD,OAAO,8DACZ;EATS,KAAA,SAAA;EACA,KAAA,SAAA;EAEA,KAAA,aAAA;EAOT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,yBAAb,cAA4C,UAAU;CAChC;CAArB,YAAY,QAAyB;EACpC,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