@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.6 → 5.0.0-alpha.600

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.
package/dist/index.mjs CHANGED
@@ -1,23 +1,70 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, DEFAULT_TOKEN_ROTATION, ProviderApiError, connectionProbe, createResolveToken, resolveValue, tokenExpectations, tokenRotationRows, whoamiAction } from "@theholocron/cli";
2
+ import { PREFIX } from "@theholocron/env-utils/lookup";
3
+ import { errorMessage } from "@theholocron/misc-utils";
2
4
  import { createCloudflareClient } from "@theholocron/cloudflare-client";
3
- //#region src/auth.ts
5
+ // src/probes/token/expectations.ts
6
+ const EVERYTHING = {
7
+ zone: "required",
8
+ dns: "required",
9
+ routes: "required",
10
+ scripts: "required",
11
+ pages: "required",
12
+ tunnels: "required",
13
+ notifications: "required"
14
+ };
15
+ /**
16
+ * What each layer's Cloudflare token is meant to carry, the same as "What each Cloudflare token needs" in
17
+ * `docs/src/content/docs/tokens.mdx`: a laptop (`local` inherits `dev`) runs everything, CI only deploys Pages, so a
18
+ * leak from CI cannot change DNS, Workers or a tunnel. A layer not listed (`prod`) has no declared expectations and its
19
+ * token is only reported. This is the plugin's `tokens` declaration, read through `tokenExpectations()`; change it and
20
+ * that table together.
21
+ */
22
+ const EXPECTED = {
23
+ rotation: {
24
+ maxAgeDays: 90,
25
+ warnDays: 14
26
+ },
27
+ permissions: {
28
+ local: EVERYTHING,
29
+ dev: EVERYTHING,
30
+ ci: {
31
+ zone: "absent",
32
+ dns: "absent",
33
+ routes: "absent",
34
+ scripts: "absent",
35
+ pages: "required",
36
+ tunnels: "absent",
37
+ notifications: "absent"
38
+ }
39
+ }
40
+ };
41
+ // src/auth.ts
42
+ /** Resolves the Cloudflare API token from `--token`, `HOLOCRON_CLOUDFLARE_TOKEN`, `CLOUDFLARE_API_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
4
43
  const resolveToken = createResolveToken({
5
44
  envName: "HOLOCRON_CLOUDFLARE_TOKEN",
6
45
  vendorEnvName: "CLOUDFLARE_API_TOKEN",
7
46
  keyringService: "cloudflare",
8
- errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron auth set cloudflare <TOKEN>"
47
+ errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron new token cloudflare <TOKEN>"
9
48
  });
10
- //#endregion
11
- //#region src/capabilities/deployment.ts
49
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
50
+ const tokens = [{
51
+ ...resolveToken.token,
52
+ expect: EXPECTED
53
+ }];
54
+ // src/capabilities/deployment.ts
55
+ /** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
12
56
  var CloudflareDeployment = class {
13
57
  client;
14
58
  accountId;
59
+ /** The capability this class provides, always `"deployment"`. */
15
60
  key = "deployment";
61
+ /** The provider name, `"cloudflare"`. */
16
62
  providerName = "cloudflare";
17
63
  constructor(client, accountId) {
18
64
  this.client = client;
19
65
  this.accountId = accountId;
20
66
  }
67
+ /** Lists the account's Pages projects. */
21
68
  async listProjects() {
22
69
  return (await this.client().pages.listProjects(this.accountId)).map(mapProject);
23
70
  }
@@ -29,14 +76,17 @@ var CloudflareDeployment = class {
29
76
  production_branch: "main"
30
77
  }));
31
78
  }
79
+ /** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
32
80
  async updateProjectSettings(projectId, settings) {
33
81
  return mapProject(await this.client().pages.getProject(this.accountId, projectId));
34
82
  }
83
+ /** Lists the names of the environment variables set for the production or preview target. */
35
84
  async listEnvVars(projectId, target) {
36
85
  const project = await this.client().pages.getProject(this.accountId, projectId);
37
86
  const envConfig = target === "production" ? project.deployment_configs.production : project.deployment_configs.preview;
38
87
  return Object.keys(envConfig.env_vars);
39
88
  }
89
+ /** Sets a plain-text environment variable on the production or preview target, keeping the others. */
40
90
  async setEnvVar(projectId, target, name, value) {
41
91
  const cfg = (await this.client().pages.getProject(this.accountId, projectId)).deployment_configs;
42
92
  const scope = target === "production" ? "production" : "preview";
@@ -55,6 +105,7 @@ var CloudflareDeployment = class {
55
105
  async triggerDeployment(input) {
56
106
  return mapDeployment(await this.client().pages.createDeployment(this.accountId, input.projectId, input.branch), input.projectId, input.branch, input.target);
57
107
  }
108
+ /** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
58
109
  async getDeployment(deploymentId) {
59
110
  const sep = deploymentId.indexOf(":");
60
111
  if (sep === -1) throw new ProviderApiError(`Invalid Cloudflare Pages deployment id "${deploymentId}" — expected "projectName:deploymentId"`, 400, void 0);
@@ -74,8 +125,22 @@ var CloudflareDeployment = class {
74
125
  return deploymentIds.length;
75
126
  }
76
127
  async ensureCustomDomain(projectId, hostname) {
77
- if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return;
128
+ if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return null;
78
129
  await this.client().pages.addDomain(this.accountId, projectId, hostname);
130
+ return null;
131
+ }
132
+ /** The hostnames attached to the Pages project. Reads only. */
133
+ async listDomains(projectId) {
134
+ return (await this.client().pages.listDomains(this.accountId, projectId)).map((d) => d.name);
135
+ }
136
+ /** The newest production deployment of the project, or null. Reads only. */
137
+ async latestDeployment(projectId) {
138
+ const [newest] = (await this.client().pages.listDeployments(this.accountId, projectId)).filter((d) => d.environment === "production").sort((a, b) => b.created_on.localeCompare(a.created_on));
139
+ if (!newest) return null;
140
+ return {
141
+ ...mapDeployment(newest, projectId, newest.deployment_trigger.metadata.branch, "production"),
142
+ createdAt: newest.created_on
143
+ };
79
144
  }
80
145
  async getProjectByName(name) {
81
146
  try {
@@ -113,20 +178,180 @@ function normalizeStatus(status) {
113
178
  default: return "error";
114
179
  }
115
180
  }
116
- //#endregion
117
- //#region src/capabilities/dns.ts
181
+ // src/capabilities/destination-matches.ts
182
+ /** The origin of a URL, or `undefined` when it is not one. */
183
+ function originOf(url) {
184
+ try {
185
+ return new URL(url).origin;
186
+ } catch {
187
+ return;
188
+ }
189
+ }
190
+ /**
191
+ * Whether a Cloudflare notification destination belongs to a relay source. The URL equal to the wanted one always
192
+ * matches. Cloudflare otherwise returns a destination's URL masked, the whole path replaced (`https://host/...`), so
193
+ * the path cannot be compared: a masked URL matches when it is exactly that shape on the wanted URL's origin and the
194
+ * name is equal (ignoring case). A real URL that merely ends in `...` is not a masked one.
195
+ */
196
+ function destinationMatches(destination, wanted) {
197
+ if (destination.url === wanted.url) return true;
198
+ if (destination.name.toLowerCase() !== wanted.name.toLowerCase()) return false;
199
+ const origin = originOf(wanted.url);
200
+ return origin !== void 0 && destination.url === `${origin}/...`;
201
+ }
202
+ // src/capabilities/newest-destination.ts
203
+ /** The instant of an RFC 3339 time, so `+02:00` and `Z` spellings of times compare as the moments they are; `-Infinity` when absent or unreadable. */
204
+ function instant(createdAt) {
205
+ const time = createdAt === void 0 ? NaN : Date.parse(createdAt);
206
+ return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;
207
+ }
208
+ /**
209
+ * The destination to use among several that match: the one created last (by the instant of `created_at`, not the
210
+ * text), else the last in list order (a destination with no usable date never beats one with a date; ties go to the
211
+ * later one in the list).
212
+ */
213
+ function newestDestination(destinations) {
214
+ let best;
215
+ for (const d of destinations) if (!best || instant(d.created_at) >= instant(best.created_at)) best = d;
216
+ return best;
217
+ }
218
+ // src/capabilities/relay-source.ts
219
+ /** The name of the policy that sends one alert type to the relay: the source's name, then the alert type. */
220
+ function policyName(name, alertType) {
221
+ return `${name}: ${alertType}`;
222
+ }
223
+ /**
224
+ * The webhook targets of a policy with the destination in them, once, and without the other destinations that match
225
+ * the same source (`duplicates`): a policy that still names an older duplicate would send every alert twice.
226
+ */
227
+ function withDestination(webhooks = [], id, duplicates) {
228
+ const kept = webhooks.filter((w) => w.id === id || !duplicates.has(w.id));
229
+ return kept.some((w) => w.id === id) ? kept : [...kept, { id }];
230
+ }
231
+ /** The policies that belong to a source, found by name (ignoring case, as the destination is), one per alert type of its layout. */
232
+ function ownPolicies(policies, name) {
233
+ const prefix = `${name}: `.toLowerCase();
234
+ return policies.filter((p) => p.name.toLowerCase().startsWith(prefix));
235
+ }
236
+ /**
237
+ * Makes the Cloudflare notification webhook for a relay source (spec `tech-relay-sources`). A destination alone sends
238
+ * nothing, so each alert type of `events` gets a policy of its own that names the destination. The destination is
239
+ * found by name and (masked) URL and each policy by name; nothing is deleted. The secret the caller offers is set only when the
240
+ * destination is made (Cloudflare never returns it), so it is returned only then.
241
+ */
242
+ async function ensureRelaySource(client, accountId, input) {
243
+ const updated = [];
244
+ const matches = (await client.alerting.webhooks.list(accountId)).filter((d) => destinationMatches(d, input));
245
+ let found = newestDestination(matches);
246
+ let created = false;
247
+ let secret;
248
+ if (!found) {
249
+ found = {
250
+ id: (await client.alerting.webhooks.create(accountId, {
251
+ name: input.name,
252
+ url: input.url,
253
+ ...input.secret ? { secret: input.secret } : {}
254
+ })).id,
255
+ name: input.name,
256
+ url: input.url
257
+ };
258
+ created = true;
259
+ if (input.secret) secret = input.secret;
260
+ }
261
+ const destination = found;
262
+ const duplicates = new Set(matches.map((d) => d.id));
263
+ const todo = [];
264
+ if (matches.length > 1) {
265
+ const others = matches.filter((d) => d.id !== destination.id).map((d) => d.id);
266
+ todo.push(`Cloudflare has ${matches.length} destinations named ${input.name} for ${input.url} (${matches.map((d) => d.id).join(", ")}). Setup attaches the policies to the newest (${destination.id}) and takes the others off them. Cloudflare does not show a destination's secret, so which one the Worker's secret belongs to is not checked. Send a test alert to confirm it is accepted, then delete the unused ones (${others.join(", ")}) in the Cloudflare dashboard (Notifications, Destinations).`);
267
+ }
268
+ const events = input.events ?? [];
269
+ if (events.length === 0) {
270
+ todo.push(`List the Cloudflare alert types to send in the source's \`events\` (GET /accounts/<id>/alerting/v3/available_alerts names them); a webhook with no policy sends nothing.`);
271
+ return {
272
+ created,
273
+ updated,
274
+ ...secret ? { secret } : {},
275
+ todo
276
+ };
277
+ }
278
+ const policies = ownPolicies(await client.alerting.policies.list(accountId), input.name);
279
+ for (const alertType of events) {
280
+ const name = policyName(input.name, alertType);
281
+ const body = (base) => ({
282
+ name,
283
+ alert_type: alertType,
284
+ enabled: true,
285
+ mechanisms: {
286
+ ...base?.mechanisms,
287
+ webhooks: withDestination(base?.mechanisms.webhooks, destination.id, duplicates)
288
+ },
289
+ ...base?.description !== void 0 ? { description: base.description } : {},
290
+ ...base?.filters !== void 0 ? { filters: base.filters } : {},
291
+ ...base?.alert_interval !== void 0 ? { alert_interval: base.alert_interval } : {}
292
+ });
293
+ const existing = policies.find((p) => p.name.toLowerCase() === name.toLowerCase());
294
+ if (!existing) {
295
+ await client.alerting.policies.create(accountId, body());
296
+ updated.push(`policy ${alertType}`);
297
+ continue;
298
+ }
299
+ const targets = existing.mechanisms.webhooks ?? [];
300
+ const attached = targets.some((w) => w.id === destination.id) && targets.every((w) => w.id === destination.id || !duplicates.has(w.id));
301
+ if (existing.enabled && attached) continue;
302
+ await client.alerting.policies.update(accountId, existing.id, body(existing));
303
+ updated.push(`policy ${alertType}`);
304
+ }
305
+ return {
306
+ created,
307
+ updated: created ? [] : updated,
308
+ ...secret ? { secret } : {},
309
+ ...todo.length > 0 ? { todo } : {}
310
+ };
311
+ }
312
+ /** Reads the webhook back without changing anything: whether the destination exists and which alert types it is sent for. */
313
+ async function inspectRelaySource(client, accountId, input) {
314
+ const ids = new Set((await client.alerting.webhooks.list(accountId)).filter((d) => destinationMatches(d, input)).map((d) => d.id));
315
+ if (ids.size === 0) return { exists: false };
316
+ const policies = ownPolicies(await client.alerting.policies.list(accountId), input.name).filter((p) => p.mechanisms.webhooks?.some((w) => ids.has(w.id)));
317
+ return {
318
+ exists: true,
319
+ enabled: policies.length > 0 && policies.every((p) => p.enabled),
320
+ events: policies.map((p) => p.alert_type)
321
+ };
322
+ }
323
+ // src/capabilities/dns.ts
324
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
118
325
  var CloudflareDns = class {
119
326
  client;
327
+ accountId;
328
+ /** The capability this class provides, always `"dns"`. */
120
329
  key = "dns";
330
+ /** The provider name, `"cloudflare"`. */
121
331
  providerName = "cloudflare";
122
332
  zoneCache = /* @__PURE__ */ new Map();
123
- constructor(client) {
333
+ constructor(client, accountId) {
124
334
  this.client = client;
335
+ this.accountId = accountId;
336
+ }
337
+ /** Makes the Cloudflare notification webhook and the policies that send to it for a relay source; needs the account id. */
338
+ async ensureRelaySource(input) {
339
+ return ensureRelaySource(this.client(), this.account(), input);
125
340
  }
341
+ /** Reads the relay source's notification webhook and its policies back, changing nothing. */
342
+ async inspectRelaySource(input) {
343
+ return inspectRelaySource(this.client(), this.account(), input);
344
+ }
345
+ account() {
346
+ if (!this.accountId) throw new ProviderApiError("Cloudflare accountId is required for notification webhooks: set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID", 0, void 0);
347
+ return this.accountId;
348
+ }
349
+ /** Lists the DNS records in the zone that holds the domain. */
126
350
  async listRecords(domain) {
127
351
  const zoneId = await this.resolveZone(domain);
128
352
  return (await this.client().dns.list(zoneId)).map(mapRecord);
129
353
  }
354
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
130
355
  async upsertRecord(domain, record) {
131
356
  const client = this.client();
132
357
  const zoneId = await this.resolveZone(domain);
@@ -149,10 +374,18 @@ var CloudflareDns = class {
149
374
  ...record.proxied !== void 0 ? { proxied: record.proxied } : {}
150
375
  }));
151
376
  }
377
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
152
378
  async deleteRecord(domain, id) {
153
379
  const zoneId = await this.resolveZone(domain);
154
380
  await this.client().dns.delete(zoneId, id);
155
381
  }
382
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
383
+ async whoami() {
384
+ return {
385
+ ok: true,
386
+ zones: (await this.client().zones.list()).length
387
+ };
388
+ }
156
389
  /**
157
390
  * Walk from full domain up to apex to find the Cloudflare zone.
158
391
  * E.g. "api.staging.example.com" tries:
@@ -181,93 +414,147 @@ function mapRecord(raw) {
181
414
  type: raw.type,
182
415
  name: raw.name,
183
416
  content: raw.content,
184
- ttl: raw.ttl
417
+ ttl: raw.ttl,
418
+ ...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
419
+ };
420
+ }
421
+ // src/capabilities/tunnels.ts
422
+ /** The rule a tunnel needs last: anything no other rule matches is answered with a 404 by the connector itself. */
423
+ const CATCH_ALL = { service: "http_status:404" };
424
+ /**
425
+ * The ingress rules with `hostname` served at `service`: the rule for the hostname is replaced where it is or added
426
+ * after the others, every other hostname's rule is kept, and the rule without a hostname closes the list.
427
+ */
428
+ function withRoute(current, hostname, service) {
429
+ const rule = {
430
+ hostname,
431
+ service
185
432
  };
433
+ const named = current.filter((r) => r.hostname !== void 0);
434
+ const at = named.findIndex((r) => r.hostname === hostname);
435
+ return [...at === -1 ? [...named, rule] : named.map((r, i) => i === at ? rule : r), current.find((r) => r.hostname === void 0) ?? CATCH_ALL];
186
436
  }
187
- //#endregion
188
- //#region src/capabilities/workers.ts
437
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
438
+ var CloudflareTunnels = class {
439
+ client;
440
+ accountId;
441
+ /** The capability this class provides, always `"tunnels"`. */
442
+ key = "tunnels";
443
+ /** The provider name, `"cloudflare"`. */
444
+ providerName = "cloudflare";
445
+ constructor(client, accountId) {
446
+ this.client = client;
447
+ this.accountId = accountId;
448
+ }
449
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
450
+ async ensureTunnel(route) {
451
+ const { tunnels } = this.client();
452
+ const found = (await tunnels.list(this.accountId)).find((t) => t.name === route.name);
453
+ const tunnel = found ?? await tunnels.create(this.accountId, { name: route.name });
454
+ const current = (await tunnels.getConfig(this.accountId, tunnel.id)).config?.ingress ?? [];
455
+ const wanted = withRoute(current, route.hostname, route.service);
456
+ const configured = JSON.stringify(wanted) !== JSON.stringify(current);
457
+ if (configured) await tunnels.putConfig(this.accountId, tunnel.id, { ingress: wanted });
458
+ return {
459
+ id: tunnel.id,
460
+ name: tunnel.name,
461
+ created: found === void 0,
462
+ configured,
463
+ target: `${tunnel.id}.cfargotunnel.com`
464
+ };
465
+ }
466
+ /** The token `cloudflared` runs the tunnel with. */
467
+ tunnelToken(tunnelId) {
468
+ return this.client().tunnels.token(this.accountId, tunnelId);
469
+ }
470
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
471
+ async whoami() {
472
+ return {
473
+ ok: true,
474
+ tunnels: (await this.client().tunnels.list(this.accountId)).length
475
+ };
476
+ }
477
+ };
478
+ // src/capabilities/workers.ts
479
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
189
480
  var CloudflareWorkers = class {
190
- zones;
481
+ client;
191
482
  accountId;
483
+ /** The capability this class provides, always `"workers"`. */
192
484
  key = "workers";
485
+ /** The provider name, `"cloudflare"`. */
193
486
  providerName = "cloudflare";
194
487
  zoneCache = /* @__PURE__ */ new Map();
195
- baseUrl;
196
- fetchImpl;
197
- /** Memoized token thunk — resolved on the first authenticated request. */
198
- token;
199
- constructor(zones, accountId, opts) {
200
- this.zones = zones;
488
+ constructor(client, accountId) {
489
+ this.client = client;
201
490
  this.accountId = accountId;
202
- this.token = opts.token;
203
- this.baseUrl = opts.baseUrl ?? "https://api.cloudflare.com/client/v4";
204
- this.fetchImpl = opts.fetch ?? globalThis.fetch;
205
491
  }
206
492
  async upsertProxy(hostname, config) {
207
493
  const scriptName = hostnameToScriptName(hostname);
208
494
  const script = generateProxyScript(config);
209
- await this.putScript(scriptName, script);
210
- const zoneId = await this.resolveZone(hostname);
211
- const pattern = `${hostname}/*`;
212
- const existing = (await this.listRoutes(zoneId)).find((r) => r.pattern === pattern);
213
- if (existing) {
214
- if (existing.script !== scriptName) await this.updateRoute(zoneId, existing.id, pattern, scriptName);
215
- } else await this.createRoute(zoneId, pattern, scriptName);
216
- }
217
- async putScript(scriptName, script) {
218
- const form = new FormData();
219
- form.append("metadata", new Blob([JSON.stringify({
220
- main_module: "index.js",
221
- compatibility_date: "2025-08-31"
222
- })], { type: "application/json" }));
223
- form.append("index.js", new Blob([script], { type: "application/javascript+module" }), "index.js");
224
- const path = `/accounts/${this.accountId}/workers/scripts/${encodeURIComponent(scriptName)}`;
225
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
226
- method: "PUT",
227
- headers: { authorization: `Bearer ${this.token()}` },
228
- body: form
229
- });
230
- if (!res.ok) {
231
- const body = await res.text().catch(() => "");
232
- throw new ProviderApiError(`Cloudflare PUT ${path} → ${res.status}`, res.status, body);
233
- }
495
+ await this.client().workers.putScript(this.accountId, scriptName, script);
496
+ await this.upsertRoute(`${hostname}/*`, scriptName);
234
497
  }
235
- listRoutes(zoneId) {
236
- return this.cfRequest("GET", `/zones/${zoneId}/workers/routes`);
498
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
499
+ async whoami() {
500
+ return {
501
+ ok: true,
502
+ scripts: (await this.client().workers.listScripts(this.accountId)).length
503
+ };
237
504
  }
238
- createRoute(zoneId, pattern, script) {
239
- return this.cfRequest("POST", `/zones/${zoneId}/workers/routes`, {
240
- pattern,
241
- script
242
- });
505
+ async deployScript(name, config) {
506
+ await this.client().workers.putScript(this.accountId, name, config.code);
507
+ for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
508
+ for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
509
+ return { scriptName: name };
243
510
  }
244
- updateRoute(zoneId, routeId, pattern, script) {
245
- return this.cfRequest("PUT", `/zones/${zoneId}/workers/routes/${routeId}`, {
246
- pattern,
247
- script
248
- });
511
+ async setSecret(script, name, value) {
512
+ await this.client().workers.putSecret(this.accountId, script, name, value);
249
513
  }
250
- async cfRequest(method, path, body) {
251
- const headers = {
252
- authorization: `Bearer ${this.token()}`,
253
- accept: "application/json"
514
+ async secretNames(script) {
515
+ return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
516
+ }
517
+ /**
518
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
519
+ * only, and asks Cloudflare for names, so no value is ever fetched.
520
+ */
521
+ async inspectScript(name, host) {
522
+ const client = this.client();
523
+ if (!(await client.workers.listScripts(this.accountId)).some((s) => s.id === name)) return {
524
+ exists: false,
525
+ routes: [],
526
+ bindingNames: []
254
527
  };
255
- const init = {
256
- method,
257
- headers
528
+ const zoneId = await this.resolveZone(host);
529
+ const routes = await client.workers.listRoutes(zoneId);
530
+ const secrets = await client.workers.listSecrets(this.accountId, name);
531
+ return {
532
+ exists: true,
533
+ routes: routes.filter((r) => r.script === name).map((r) => r.pattern),
534
+ bindingNames: secrets.map((secret) => secret.name)
258
535
  };
259
- if (body !== void 0) {
260
- headers["content-type"] = "application/json";
261
- init.body = JSON.stringify(body);
262
- }
263
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, init);
264
- if (!res.ok) {
265
- const text = await res.text().catch(() => "");
266
- throw new ProviderApiError(`Cloudflare ${method} ${path} → ${res.status}`, res.status, text);
267
- }
268
- const envelope = await res.json();
269
- if (!envelope.success) throw new ProviderApiError(`Cloudflare ${method} ${path} returned success:false`, 0, JSON.stringify(envelope.errors));
270
- return envelope.result;
536
+ }
537
+ /** The newest deployment of the script, and whether it serves all traffic. Reads only. */
538
+ async latestDeployment(script) {
539
+ const [newest] = [...await this.client().workers.listDeployments(this.accountId, script)].sort((a, b) => b.created_on.localeCompare(a.created_on));
540
+ if (!newest) return null;
541
+ return {
542
+ id: newest.id,
543
+ createdAt: newest.created_on,
544
+ active: newest.versions.length > 0 && newest.versions.some((v) => v.percentage === 100)
545
+ };
546
+ }
547
+ proxyScriptName(hostname) {
548
+ return hostnameToScriptName(hostname);
549
+ }
550
+ /** Idempotent create-or-update for one route pattern — shared by both public methods. */
551
+ async upsertRoute(pattern, scriptName) {
552
+ const hostname = pattern.split("/")[0];
553
+ const zoneId = await this.resolveZone(hostname);
554
+ const existing = (await this.client().workers.listRoutes(zoneId)).find((r) => r.pattern === pattern);
555
+ if (existing) {
556
+ if (existing.script !== scriptName) await this.client().workers.updateRoute(zoneId, existing.id, pattern, scriptName);
557
+ } else await this.client().workers.createRoute(zoneId, pattern, scriptName);
271
558
  }
272
559
  async resolveZone(domain) {
273
560
  const cached = this.zoneCache.get(domain);
@@ -275,7 +562,7 @@ var CloudflareWorkers = class {
275
562
  const parts = domain.split(".");
276
563
  for (let i = 0; i < parts.length - 1; i++) {
277
564
  const candidate = parts.slice(i).join(".");
278
- const zones = await this.zones().list({ name: candidate });
565
+ const zones = await this.client().zones.list({ name: candidate });
279
566
  if (zones.length > 0) {
280
567
  this.zoneCache.set(domain, zones[0].id);
281
568
  return zones[0].id;
@@ -302,8 +589,359 @@ function generateProxyScript(config) {
302
589
  `};`
303
590
  ].join("\n");
304
591
  }
305
- //#endregion
306
- //#region src/verify-token.ts
592
+ // src/mint-token/mint-token.ts
593
+ /**
594
+ * The Cloudflare permission group each declared permission needs, by the names Cloudflare has used for it, first match
595
+ * wins (the dashboard says `Cloudflare Pages: Edit`, the API's group is named differently, and neither is certain, so a
596
+ * name that matches none is an error that lists the near ones, never a guess).
597
+ */
598
+ const GROUPS = {
599
+ zone: {
600
+ resource: "zone",
601
+ names: ["Zone Read"]
602
+ },
603
+ dns: {
604
+ resource: "zone",
605
+ names: ["DNS Write"]
606
+ },
607
+ routes: {
608
+ resource: "zone",
609
+ names: ["Workers Routes Write"]
610
+ },
611
+ scripts: {
612
+ resource: "account",
613
+ names: ["Workers Scripts Write"]
614
+ },
615
+ pages: {
616
+ resource: "account",
617
+ names: ["Pages Write", "Cloudflare Pages Write"]
618
+ },
619
+ tunnels: {
620
+ resource: "account",
621
+ names: ["Cloudflare Tunnel Write", "Tunnel Write"]
622
+ },
623
+ notifications: {
624
+ resource: "account",
625
+ names: ["Notifications Write", "Account Notifications Write"]
626
+ }
627
+ };
628
+ const DAY_MS = 864e5;
629
+ /**
630
+ * Makes a Cloudflare API token for a layer, scoped to exactly the permissions the plugin declares it `required` there
631
+ * (`PluginToken.expect`), through `POST /user/tokens`. The calling token needs `API Tokens: Edit`. It refuses (nothing is
632
+ * made) a layer with no declared permissions, a missing account id, and a permission whose group Cloudflare does not
633
+ * list, so a token is never broader than the declaration. The value is returned, never printed.
634
+ */
635
+ async function mintCloudflareToken(ctx, input) {
636
+ const declared = tokenExpectations(tokens, { layer: input.layer })[0];
637
+ if (!declared || declared.required.length === 0) throw new Error(`the Cloudflare token declares no permissions for \`${input.layer}\`, so none can be made for it; a token with no declared scope is never made`);
638
+ const { accountId } = ctx.options;
639
+ if (!accountId) throw new Error("a Cloudflare accountId is required to make a token: set it in the plugin options or CLOUDFLARE_ACCOUNT_ID");
640
+ const client = ctx.client();
641
+ const available = await client.tokens.permissionGroups();
642
+ const wanted = declared.required.map((permission) => {
643
+ const group = GROUPS[permission];
644
+ const found = available.find((g) => group.names.includes(g.name));
645
+ if (!found) {
646
+ const near = available.filter((g) => g.name.toLowerCase().includes(permission.toLowerCase().slice(0, 4))).map((g) => g.name);
647
+ throw new Error(`Cloudflare has no permission group for \`${permission}\` (looked for ${group.names.join(" or ")})` + (near.length > 0 ? `; near names: ${near.slice(0, 5).join(", ")}` : ""));
648
+ }
649
+ return {
650
+ permission,
651
+ resource: group.resource,
652
+ id: found.id
653
+ };
654
+ });
655
+ const policies = ["account", "zone"].flatMap((resource) => {
656
+ const ids = wanted.filter((w) => w.resource === resource).map((w) => ({ id: w.id }));
657
+ if (ids.length === 0) return [];
658
+ return [{
659
+ effect: "allow",
660
+ resources: { [resource === "account" ? `com.cloudflare.api.account.${accountId}` : `com.cloudflare.api.account.zone.*`]: "*" },
661
+ permission_groups: ids
662
+ }];
663
+ });
664
+ const now = (input.now ?? (() => /* @__PURE__ */ new Date()))();
665
+ const days = input.expiresInDays ?? declared.rotation.maxAgeDays;
666
+ const created = await client.tokens.create({
667
+ name: input.name,
668
+ policies,
669
+ expires_on: new Date(now.getTime() + days * DAY_MS).toISOString()
670
+ });
671
+ if (!created.value) throw new Error("Cloudflare made the token but returned no value");
672
+ return {
673
+ value: created.value,
674
+ envName: resolveToken.token.envName,
675
+ id: created.id,
676
+ ...created.expires_on ? { expiresAt: created.expires_on } : {},
677
+ notes: [`scoped to ${wanted.map((w) => `${w.permission} (${w.resource})`).join(", ")}, the permissions declared for \`${input.layer}\``, ...wanted.some((w) => w.resource === "zone") ? ["zone permissions cover every zone in the account"] : []]
678
+ };
679
+ }
680
+ // src/probes/token/parse-token-args.ts
681
+ /** Reads the words after the probe name: `--layer <word>`, `--token-name <VAR>` and any number of zone names. */
682
+ function parseTokenArgs(args) {
683
+ const zones = [];
684
+ let layer;
685
+ let tokenName;
686
+ for (let i = 0; i < args.length; i++) {
687
+ const arg = args[i];
688
+ if (arg === "--layer") layer = args[++i];
689
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
690
+ else if (arg === "--token-name") tokenName = args[++i];
691
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
692
+ else if (!arg.startsWith("--")) zones.push(arg);
693
+ }
694
+ return {
695
+ ...layer ? { layer } : {},
696
+ ...tokenName ? { tokenName } : {},
697
+ zones
698
+ };
699
+ }
700
+ // src/probes/token/token.ts
701
+ /** The most zones whose DNS and Workers routes are read, so a token that sees many does not make many requests. */
702
+ const MAX_ZONES = 5;
703
+ /** How many names to show before "(+N more)". */
704
+ const SHOWN = 5;
705
+ /** `a, b, c (+2 more)`. */
706
+ function summarise(names) {
707
+ return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
708
+ }
709
+ /**
710
+ * Reads one list and says what came back. Cloudflare answers a token without the permission in one of two ways (a 401 or
711
+ * 403, or an empty list), so an empty list is `none`: the token cannot see any, or there are none. A request that fails
712
+ * for another reason (the network, a 5xx) is an `error`.
713
+ */
714
+ async function reach(read, noun) {
715
+ try {
716
+ const items = await read();
717
+ if (items.length === 0) return {
718
+ kind: "none",
719
+ detail: `no ${noun} visible (none exist, or the token cannot see them)`
720
+ };
721
+ const names = items.map((i) => i.name).filter((n) => typeof n === "string");
722
+ return {
723
+ kind: "has",
724
+ detail: names.length > 0 ? `${items.length} ${noun}: ${summarise(names)}` : `${items.length} ${noun}`
725
+ };
726
+ } catch (err) {
727
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
728
+ kind: "none",
729
+ detail: `no access (${err.status})`
730
+ };
731
+ return {
732
+ kind: "error",
733
+ detail: errorMessage(err)
734
+ };
735
+ }
736
+ }
737
+ /**
738
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
739
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
740
+ * permission that is rightly absent is a bare `ok`.
741
+ */
742
+ function rowFor({ label, outcome }, rule) {
743
+ if (outcome.kind === "error") return {
744
+ status: "fail",
745
+ label,
746
+ detail: outcome.detail
747
+ };
748
+ const has = outcome.kind === "has";
749
+ if (rule === "required") return has ? {
750
+ status: "ok",
751
+ label,
752
+ detail: outcome.detail
753
+ } : {
754
+ status: "fail",
755
+ label,
756
+ detail: outcome.detail
757
+ };
758
+ if (rule === "absent") return has ? {
759
+ status: "fail",
760
+ label,
761
+ detail: outcome.detail
762
+ } : {
763
+ status: "ok",
764
+ label
765
+ };
766
+ return {
767
+ status: has ? "ok" : "info",
768
+ label,
769
+ detail: outcome.detail
770
+ };
771
+ }
772
+ /**
773
+ * The `token` probe: tries each permission Holocron uses with the Cloudflare API token and reports which ones the token
774
+ * has. It only reads (a list per permission), so it changes nothing. The token is the one the plugin resolves, so
775
+ * `--token cloudflare=<token>` or `--environment <layer>` checks another one; the account id is the plugin's own.
776
+ *
777
+ * A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
778
+ * `local`) with `--token-name` (the declared token the Environment held, so the expectations are that token's own), the results are judged against what that layer's token is meant to carry (the plugin's `tokens` declaration, read with `tokenExpectations()`) and shown in
779
+ * two groups, what it should have and what it should not, where a missing or extra permission fails. The other words
780
+ * limit the zone checks to those zones; otherwise up to five are read. How the token is chosen is in `holocron probe --help`.
781
+ */
782
+ function tokenProbe(ctx) {
783
+ return {
784
+ summary: "Try each Cloudflare permission Holocron uses (zones, DNS, Workers routes and scripts, Pages, tunnels) with a token and report which it has; for a ci or dev Environment, check it against what that layer should carry. Read-only.",
785
+ writes: false,
786
+ acceptsToken: true,
787
+ async run(probe) {
788
+ const token = ctx.token();
789
+ probe.secret(token);
790
+ const client = ctx.client();
791
+ const { layer, tokenName, zones: wanted } = parseTokenArgs(probe.args ?? []);
792
+ const expectation = layer ? tokenExpectations(tokens, {
793
+ layer,
794
+ ...tokenName ? { envName: tokenName } : {}
795
+ })[0] : void 0;
796
+ const rules = expectation?.rules;
797
+ if (layer && !rules) probe.say({
798
+ status: "info",
799
+ label: layer,
800
+ detail: "no expectations are declared for it, so the token is only described"
801
+ });
802
+ const now = (ctx.now ?? (() => /* @__PURE__ */ new Date()))();
803
+ const rotation = expectation?.rotation ?? DEFAULT_TOKEN_ROTATION;
804
+ let lifetime;
805
+ try {
806
+ const verified = await client.tokens.verify();
807
+ probe.say({
808
+ status: "ok",
809
+ label: "token",
810
+ detail: `${verified.id} (${verified.status})`
811
+ });
812
+ lifetime = {
813
+ ...verified.not_before ? { createdAt: verified.not_before } : {},
814
+ ...verified.expires_on ? { expiresAt: verified.expires_on } : {}
815
+ };
816
+ } catch {}
817
+ const rotationRows = tokenRotationRows(lifetime, rotation, now);
818
+ const sayRotation = () => {
819
+ probe.say({
820
+ status: "heading",
821
+ label: "Rotation"
822
+ });
823
+ for (const row of rotationRows) probe.say(row);
824
+ };
825
+ const named = wanted.length > 0 ? wanted : ctx.options.zone ? [ctx.options.zone] : [];
826
+ const tried = [];
827
+ let zones = [];
828
+ const zoneOutcome = await reach(async () => {
829
+ zones = named.length > 0 ? (await Promise.all(named.map((name) => client.zones.list({ name })))).flat() : await client.zones.list({ per_page: MAX_ZONES });
830
+ return zones.map((z) => ({ name: z.name }));
831
+ }, "zones");
832
+ tried.push({
833
+ label: "Zone: Read",
834
+ permission: "zone",
835
+ outcome: zoneOutcome
836
+ });
837
+ if (zoneOutcome.kind !== "error") {
838
+ for (const zone of zones.slice(0, MAX_ZONES)) {
839
+ tried.push({
840
+ label: `DNS: Edit (${zone.name})`,
841
+ permission: "dns",
842
+ outcome: await reach(() => client.dns.list(zone.id), "records")
843
+ });
844
+ tried.push({
845
+ label: `Workers Routes: Edit (${zone.name})`,
846
+ permission: "routes",
847
+ outcome: await reach(async () => (await client.workers.listRoutes(zone.id)).map((r) => ({ name: r.pattern })), "routes")
848
+ });
849
+ }
850
+ const account = ctx.options.accountId;
851
+ if (account) {
852
+ tried.push({
853
+ label: "Workers Scripts: Edit",
854
+ permission: "scripts",
855
+ outcome: await reach(async () => (await client.workers.listScripts(account)).map((s) => ({ name: s.id })), "scripts")
856
+ });
857
+ tried.push({
858
+ label: "Pages: Edit",
859
+ permission: "pages",
860
+ outcome: await reach(() => client.pages.listProjects(account), "projects")
861
+ });
862
+ tried.push({
863
+ label: "Cloudflare Tunnel: Edit",
864
+ permission: "tunnels",
865
+ outcome: await reach(() => client.tunnels.list(account), "tunnels")
866
+ });
867
+ tried.push({
868
+ label: "Notifications: Edit",
869
+ permission: "notifications",
870
+ outcome: await reach(async () => (await client.alerting.webhooks.list(account)).map((w) => ({ name: w.name })), "notification webhooks")
871
+ });
872
+ } else probe.say({
873
+ status: rules ? "fail" : "info",
874
+ label: "account permissions",
875
+ detail: "no account id: set HOLOCRON_CLOUDFLARE_ACCOUNT_ID or the plugin's accountId option to check them"
876
+ });
877
+ }
878
+ if (!rules) {
879
+ for (const t of tried) probe.say(rowFor(t, void 0));
880
+ sayRotation();
881
+ return;
882
+ }
883
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
884
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
885
+ if (inGroup.length === 0) continue;
886
+ probe.say({
887
+ status: "heading",
888
+ label: heading
889
+ });
890
+ for (const t of inGroup) probe.say(rowFor(t, rule));
891
+ }
892
+ sayRotation();
893
+ }
894
+ };
895
+ }
896
+ // src/read-token-id/read-token-id.ts
897
+ /**
898
+ * The id of the Cloudflare token this plugin was built with, from `GET /user/tokens/verify` (`result.id`), the id
899
+ * `provider cloudflare revoke` takes. A token with `User: API Tokens Read` can ask; an account or zone token is refused
900
+ * with a 401 or 403, which is `undefined` ("Cloudflare cannot say"), not a failure. Any other failure is thrown. No
901
+ * token value is read or returned.
902
+ */
903
+ async function readCloudflareTokenId(ctx) {
904
+ try {
905
+ return (await ctx.client().tokens.verify()).id || void 0;
906
+ } catch (err) {
907
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return void 0;
908
+ throw err;
909
+ }
910
+ }
911
+ // src/revoke-token/revoke-token.ts
912
+ const AFTER = "anything still using the token stops working; make sure its replacement is in place (`holocron sync secrets --env <layer>`)";
913
+ /**
914
+ * Deletes a Cloudflare API token by its id through `DELETE /user/tokens/{token_id}` (needs `API Tokens: Write`). It
915
+ * first asks `GET /user/tokens/verify` which token the call is made with and refuses that id, because deleting it would
916
+ * lock the run out; an account or zone token is refused by that endpoint, so there the plugin cannot tell and relies on
917
+ * Cloudflare. A 404 means the token is already gone (`revoked: false`); any other failure is thrown. No value is read or
918
+ * returned.
919
+ */
920
+ async function revokeCloudflareToken(ctx, input) {
921
+ const client = ctx.client();
922
+ let ownId;
923
+ try {
924
+ ownId = (await client.tokens.verify()).id;
925
+ } catch {
926
+ ownId = void 0;
927
+ }
928
+ if (ownId === input.id) throw new Error(`\`${input.id}\` is the token this call is made with; deleting it would lock the run out. Run it with another token (--token cloudflare=<value>)`);
929
+ try {
930
+ await client.tokens.delete(input.id);
931
+ } catch (err) {
932
+ if (err.status === 404) return {
933
+ revoked: false,
934
+ notes: ["Cloudflare has no token with that id, so there is nothing to delete"]
935
+ };
936
+ throw err;
937
+ }
938
+ return {
939
+ revoked: true,
940
+ notes: [`deleted token ${input.id}; ${AFTER}`, ...ownId === void 0 ? ["could not tell whether this was the token in use (an account or zone token cannot ask Cloudflare)"] : []]
941
+ };
942
+ }
943
+ // src/verify-token.ts
944
+ /** Checks a Cloudflare API token, first by the token-verify endpoint and otherwise by listing zones; resolves to a description of what it found, or the failure message. */
307
945
  async function verifyToken(token, opts = {}) {
308
946
  const client = createCloudflareClient({
309
947
  token,
@@ -318,21 +956,26 @@ async function verifyToken(token, opts = {}) {
318
956
  };
319
957
  } catch {}
320
958
  try {
959
+ const names = (await client.zones.list()).map((z) => z.name);
960
+ if (names.length === 0) return {
961
+ ok: true,
962
+ subject: "no zones visible"
963
+ };
321
964
  return {
322
965
  ok: true,
323
- subject: `zone: ${(await client.zones.list({ per_page: 1 }))[0]?.name ?? "unknown"}`
966
+ subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
324
967
  };
325
968
  } catch (err) {
326
969
  return {
327
970
  ok: false,
328
- message: err instanceof Error ? err.message : String(err)
971
+ message: errorMessage(err)
329
972
  };
330
973
  }
331
974
  }
332
- //#endregion
333
- //#region src/index.ts
975
+ // src/index.ts
976
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
334
977
  function createContext(options = {}) {
335
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
978
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
336
979
  const opts = {
337
980
  ...options,
338
981
  accountId
@@ -350,34 +993,81 @@ function createContext(options = {}) {
350
993
  })
351
994
  };
352
995
  }
996
+ /** Builds the `dns` capability for a context. */
353
997
  function dns(ctx) {
354
- return new CloudflareDns(ctx.client);
998
+ return new CloudflareDns(ctx.client, ctx.options.accountId);
355
999
  }
1000
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
356
1001
  function deployment(ctx) {
357
1002
  if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Pages deployments — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
358
1003
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
359
1004
  }
1005
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
360
1006
  function workersCapability(ctx) {
361
1007
  if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Workers — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
362
- return new CloudflareWorkers(() => ctx.client().zones, ctx.options.accountId, {
363
- token: ctx.token,
364
- baseUrl: ctx.options.baseUrl,
365
- fetch: ctx.options.fetch
366
- });
1008
+ return new CloudflareWorkers(ctx.client, ctx.options.accountId);
367
1009
  }
1010
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
1011
+ function tunnelsCapability(ctx) {
1012
+ if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Tunnels — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
1013
+ return new CloudflareTunnels(ctx.client, ctx.options.accountId);
1014
+ }
1015
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
368
1016
  function createPlugin(options = {}) {
369
1017
  const ctx = createContext(options);
370
1018
  return {
371
1019
  name: "@theholocron/holocron-plugin-cloudflare",
1020
+ probes: {
1021
+ token: tokenProbe(ctx),
1022
+ connection: connectionProbe({
1023
+ provider: "Cloudflare",
1024
+ url: options.baseUrl ?? "https://api.cloudflare.com",
1025
+ fetch: options.fetch,
1026
+ token: () => resolveToken(options),
1027
+ verify: (token) => verifyToken(token, {
1028
+ baseUrl: options.baseUrl,
1029
+ fetch: options.fetch
1030
+ })
1031
+ })
1032
+ },
1033
+ whoami: whoamiAction({
1034
+ provider: "cloudflare",
1035
+ token: () => resolveToken(options),
1036
+ verify: (token) => verifyToken(token, {
1037
+ baseUrl: options.baseUrl,
1038
+ fetch: options.fetch
1039
+ }),
1040
+ tokens,
1041
+ lifetime: async (token) => {
1042
+ try {
1043
+ const verified = await createCloudflareClient({
1044
+ token,
1045
+ baseUrl: options.baseUrl,
1046
+ fetch: options.fetch
1047
+ }).tokens.verify();
1048
+ return {
1049
+ ...verified.not_before ? { createdAt: verified.not_before } : {},
1050
+ ...verified.expires_on ? { expiresAt: verified.expires_on } : {}
1051
+ };
1052
+ } catch (err) {
1053
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return void 0;
1054
+ throw err;
1055
+ }
1056
+ }
1057
+ }),
1058
+ mintToken: (input) => mintCloudflareToken(ctx, input),
1059
+ revokeToken: (input) => revokeCloudflareToken(ctx, input),
1060
+ readTokenId: () => readCloudflareTokenId(ctx),
372
1061
  capabilities: {
373
1062
  dns: () => dns(ctx),
374
1063
  ...ctx.options.accountId ? {
375
1064
  deployment: () => deployment(ctx),
376
- workers: () => workersCapability(ctx)
1065
+ workers: () => workersCapability(ctx),
1066
+ tunnels: () => tunnelsCapability(ctx)
377
1067
  } : {}
378
1068
  }
379
1069
  };
380
1070
  }
381
- const AUTH_HINT = "create an API token at https://dash.cloudflare.com/profile/api-tokens with Zone:Read, DNS:Edit, Cloudflare Pages:Edit, Workers Scripts:Edit (account-level), and Workers Routes:Edit (zone-level) permissions, then run: holocron auth set cloudflare <TOKEN>";
382
- //#endregion
383
- export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
1071
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
1072
+ const AUTH_HINT = "create an API token at https://dash.cloudflare.com/profile/api-tokens with Zone:Read, DNS:Edit, Cloudflare Pages:Edit, Workers Scripts:Edit (account-level), Workers Routes:Edit (zone-level) and, for tunnels, Cloudflare Tunnel:Edit and, for relay sources, Notifications:Edit (account-level) permissions, then run: holocron new token cloudflare <TOKEN>";
1073
+ export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareTunnels, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, tokens, tunnelsCapability, verifyToken, workersCapability };