@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.57 → 5.0.0-alpha.571

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/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  # `@theholocron/holocron-plugin-cloudflare`
4
4
 
5
5
  Cloudflare plugin for [Holocron](../cli). Implements the `dns`, `deployment`,
6
- and `workers` capabilities against the
6
+ `workers` and `tunnels` capabilities against the
7
7
  [Cloudflare v4 API](https://developers.cloudflare.com/api/).
8
8
 
9
9
  ## Install
@@ -22,7 +22,7 @@ Token resolution order:
22
22
  2. `HOLOCRON_CLOUDFLARE_TOKEN` env var
23
23
  3. `CLOUDFLARE_API_TOKEN` env var (the standard Cloudflare variable name)
24
24
  4. Keyring `cloudflare.<org>` — tried first when an org is active via `--org`, `HOLOCRON_ORG`, or `org` in `holocron.config.ts`
25
- 5. Keyring `cloudflare` — unnamespaced fallback; set via `holocron auth set cloudflare <token>`
25
+ 5. Keyring `cloudflare` — unnamespaced fallback; set via `holocron new token cloudflare <token>`
26
26
 
27
27
  Generate a scoped API token at **dash.cloudflare.com/profile/api-tokens**.
28
28
 
@@ -63,9 +63,10 @@ Any combination of capabilities can be enabled together:
63
63
 
64
64
  ```
65
65
 
66
- The `deployment` and `workers` capabilities are only exposed when `accountId`
67
- is resolvable — either passed explicitly in options or set via the
68
- `CLOUDFLARE_ACCOUNT_ID` env var.
66
+ The `deployment`, `workers` and `tunnels` capabilities are only exposed when `accountId`
67
+ is resolvable — either passed explicitly in options or set as the
68
+ `HOLOCRON_CLOUDFLARE_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`) env var or in a `credentials` provider's Environment (the option wins, then the
69
+ environment, then the provider).
69
70
 
70
71
  ## `dns` capability
71
72
 
@@ -104,6 +105,21 @@ route-write call when nothing changed. Zone ids are cached per plugin
104
105
  instance for the lifetime of the process — the `workers` capability's own
105
106
  cache, separate from `dns`'s.
106
107
 
108
+ ## `tunnels` capability
109
+
110
+ Named [Cloudflare Tunnels](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/): a stable
111
+ public hostname that reaches a port on this machine, for a webhook that has to find a development instance. It needs a
112
+ token with **Cloudflare Tunnel: Edit** (account).
113
+
114
+ | Method | What it does |
115
+ | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
116
+ | `ensureTunnel` | Finds the tunnel by name or makes it, and makes its configuration serve `hostname` at `service`. Other hostnames' rules are kept and the catch-all (`http_status:404`) stays last. Returns the tunnel id and the `CNAME` target (`<id>.cfargotunnel.com`). |
117
+ | `tunnelToken` | The token `cloudflared` runs the tunnel with. A credential: never printed or stored. |
118
+ | `whoami` | How many tunnels the token can see, for `holocron doctor`. |
119
+
120
+ `ensureTunnel` is idempotent: a tunnel that already serves the hostname is not rewritten. The DNS record for the
121
+ hostname is the `dns` provider's job.
122
+
107
123
  ### Preview deployment setup
108
124
 
109
125
  When `preview: true` (or `preview: { project, domain }`) is set in a repo's deploy config, `holocron setup` calls:
package/dist/index.d.mts CHANGED
@@ -1,15 +1,19 @@
1
- import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, ResolveTokenInput, WikiProxyConfig, Workers } from "@theholocron/cli";
1
+ import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, EnsureRelaySourceInput, EnsureRelaySourceResult, EnsuredTunnel, InspectRelaySourceInput, MintTokenInput, PluginToken, RelaySourceState, ResolveTokenInput, RevokeTokenInput, TunnelRoute, Tunnels, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, WikiProxyConfig, WorkerDeploymentState, WorkerScriptState, Workers } from "@theholocron/cli";
2
2
  import { CloudflareClient, CloudflareClient as CloudflareClient$1, CloudflareClientOptions, createCloudflareClient } from "@theholocron/cloudflare-client";
3
- //#region src/auth.d.ts
4
- declare const resolveToken: (input?: ResolveTokenInput) => string;
5
- //#endregion
6
- //#region src/capabilities/deployment.d.ts
7
- declare class CloudflareDeployment implements Deployment {
3
+ /** 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
+ export declare const resolveToken: import("@theholocron/cli").TokenResolver;
5
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
6
+ export declare const tokens: PluginToken[];
7
+ /** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
8
+ export declare class CloudflareDeployment implements Deployment {
8
9
  private readonly client;
9
10
  private readonly accountId;
11
+ /** The capability this class provides, always `"deployment"`. */
10
12
  readonly key: "deployment";
13
+ /** The provider name, `"cloudflare"`. */
11
14
  readonly providerName = "cloudflare";
12
15
  constructor(client: () => CloudflareClient, accountId: string);
16
+ /** Lists the account's Pages projects. */
13
17
  listProjects(): Promise<DeploymentProject[]>;
14
18
  ensureProject(input: {
15
19
  name: string;
@@ -17,31 +21,54 @@ declare class CloudflareDeployment implements Deployment {
17
21
  repo?: string;
18
22
  rootDirectory?: string;
19
23
  }): Promise<DeploymentProject>;
24
+ /** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
20
25
  updateProjectSettings(projectId: string, settings: DeploymentProjectSettings): Promise<DeploymentProject>;
26
+ /** Lists the names of the environment variables set for the production or preview target. */
21
27
  listEnvVars(projectId: string, target: DeploymentTarget): Promise<string[]>;
28
+ /** Sets a plain-text environment variable on the production or preview target, keeping the others. */
22
29
  setEnvVar(projectId: string, target: DeploymentTarget, name: string, value: string): Promise<void>;
23
30
  triggerDeployment(input: {
24
31
  projectId: string;
25
32
  branch: string;
26
33
  target?: DeploymentTrigger;
27
34
  }): Promise<DeploymentRecord>;
35
+ /** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
28
36
  getDeployment(deploymentId: string): Promise<DeploymentRecord>;
29
37
  listPreviewDeployments(projectId: string, branch: string): Promise<DeploymentRecord[]>;
30
38
  deletePreviewDeployments(projectId: string, deploymentIds: string[]): Promise<number>;
31
39
  ensureCustomDomain(projectId: string, hostname: string): Promise<DnsRecordRequest | null>;
40
+ /** The hostnames attached to the Pages project. Reads only. */
41
+ listDomains(projectId: string): Promise<string[]>;
42
+ /** The newest production deployment of the project, or null. Reads only. */
43
+ latestDeployment(projectId: string): Promise<DeploymentRecord | null>;
32
44
  private getProjectByName;
33
45
  }
34
- //#endregion
35
- //#region src/capabilities/dns.d.ts
36
- declare class CloudflareDns implements Dns {
46
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
47
+ export declare class CloudflareDns implements Dns {
37
48
  private readonly client;
49
+ private readonly accountId?;
50
+ /** The capability this class provides, always `"dns"`. */
38
51
  readonly key: "dns";
52
+ /** The provider name, `"cloudflare"`. */
39
53
  readonly providerName = "cloudflare";
40
54
  private readonly zoneCache;
41
- constructor(client: () => CloudflareClient);
55
+ constructor(client: () => CloudflareClient, accountId?: string | undefined);
56
+ /** Makes the Cloudflare notification webhook and the policies that send to it for a relay source; needs the account id. */
57
+ ensureRelaySource(input: EnsureRelaySourceInput): Promise<EnsureRelaySourceResult>;
58
+ /** Reads the relay source's notification webhook and its policies back, changing nothing. */
59
+ inspectRelaySource(input: InspectRelaySourceInput): Promise<RelaySourceState>;
60
+ private account;
61
+ /** Lists the DNS records in the zone that holds the domain. */
42
62
  listRecords(domain: string): Promise<DnsRecord[]>;
63
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
43
64
  upsertRecord(domain: string, record: DnsRecord): Promise<DnsRecord>;
65
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
44
66
  deleteRecord(domain: string, id: string): Promise<void>;
67
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
68
+ whoami(): Promise<{
69
+ ok: boolean;
70
+ zones: number;
71
+ }>;
45
72
  /**
46
73
  * Walk from full domain up to apex to find the Cloudflare zone.
47
74
  * E.g. "api.staging.example.com" tries:
@@ -51,68 +78,116 @@ declare class CloudflareDns implements Dns {
51
78
  */
52
79
  private resolveZone;
53
80
  }
54
- //#endregion
55
- //#region src/capabilities/workers.d.ts
56
- declare class CloudflareWorkers implements Workers {
81
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
82
+ export declare class CloudflareTunnels implements Tunnels {
57
83
  private readonly client;
58
84
  private readonly accountId;
85
+ /** The capability this class provides, always `"tunnels"`. */
86
+ readonly key: "tunnels";
87
+ /** The provider name, `"cloudflare"`. */
88
+ readonly providerName = "cloudflare";
89
+ constructor(client: () => Pick<CloudflareClient$1, "tunnels">, accountId: string);
90
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
91
+ ensureTunnel(route: TunnelRoute): Promise<EnsuredTunnel>;
92
+ /** The token `cloudflared` runs the tunnel with. */
93
+ tunnelToken(tunnelId: string): Promise<string>;
94
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
95
+ whoami(): Promise<{
96
+ ok: boolean;
97
+ tunnels: number;
98
+ }>;
99
+ }
100
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
101
+ export declare class CloudflareWorkers implements Workers {
102
+ private readonly client;
103
+ private readonly accountId;
104
+ /** The capability this class provides, always `"workers"`. */
59
105
  readonly key: "workers";
106
+ /** The provider name, `"cloudflare"`. */
60
107
  readonly providerName = "cloudflare";
61
108
  private readonly zoneCache;
62
109
  constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
63
110
  upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
111
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
112
+ whoami(): Promise<{
113
+ ok: boolean;
114
+ scripts: number;
115
+ }>;
64
116
  deployScript(name: string, config: DeployScriptConfig): Promise<DeployScriptResult>;
117
+ setSecret(script: string, name: string, value: string): Promise<void>;
118
+ secretNames(script: string): Promise<string[]>;
119
+ /**
120
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
121
+ * only, and asks Cloudflare for names, so no value is ever fetched.
122
+ */
123
+ inspectScript(name: string, host: string): Promise<WorkerScriptState>;
124
+ /** The newest deployment of the script, and whether it serves all traffic. Reads only. */
125
+ latestDeployment(script: string): Promise<WorkerDeploymentState | null>;
126
+ proxyScriptName(hostname: string): string;
65
127
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
66
128
  private upsertRoute;
67
129
  private resolveZone;
68
130
  }
69
- //#endregion
70
- //#region src/verify-token.d.ts
71
- interface VerifyTokenSuccess {
72
- ok: true;
73
- subject: string;
74
- }
75
- interface VerifyTokenFailure {
76
- ok: false;
77
- message: string;
78
- }
79
- type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
80
131
  interface VerifyTokenOptions {
81
132
  baseUrl?: string;
82
133
  fetch?: typeof fetch;
83
134
  }
84
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
85
- //#endregion
86
- //#region src/index.d.ts
87
- interface CloudflarePluginOptions extends ResolveTokenInput {
135
+ /** 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. */
136
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
137
+ /** Options for the Cloudflare plugin: how the API token is resolved, the account, and test overrides. */
138
+ export interface CloudflarePluginOptions extends ResolveTokenInput {
88
139
  /**
89
140
  * Cloudflare account ID. Required for Pages (deployment) operations;
90
141
  * optional for DNS-only use.
91
142
  */
92
143
  accountId?: string;
144
+ /**
145
+ * The zone the organization's own DNS lives in. The `token` probe reads this one zone when no zone is named on the
146
+ * command line; without it the probe reads the first few zones of the account.
147
+ */
148
+ zone?: string;
93
149
  /** Override base URL for tests. */
94
150
  baseUrl?: string;
151
+ /** The `fetch` to use instead of the global one, for tests. */
95
152
  fetch?: typeof fetch;
96
153
  }
97
- interface PluginContext {
154
+ /** The shared state the Cloudflare plugin's capabilities and probes are built from. */
155
+ export interface PluginContext {
156
+ /** The options the plugin was created with, with `accountId` falling back to `CLOUDFLARE_ACCOUNT_ID` in the environment, then in the `credentials` providers' variables. */
98
157
  options: CloudflarePluginOptions;
99
158
  /** Memoized client — the token is resolved on first use, not at plugin load. */
100
159
  client: () => CloudflareClient;
101
160
  /** Memoized token resolver — shared by the client and the Workers capability. */
102
161
  token: () => string;
103
162
  }
104
- declare function createContext(options?: CloudflarePluginOptions): PluginContext;
105
- declare function dns(ctx: PluginContext): Dns;
106
- declare function deployment(ctx: PluginContext): Deployment;
107
- declare function workersCapability(ctx: PluginContext): Workers;
108
- declare function createPlugin(options?: CloudflarePluginOptions): {
163
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
164
+ export declare function createContext(options?: CloudflarePluginOptions): PluginContext;
165
+ /** Builds the `dns` capability for a context. */
166
+ export declare function dns(ctx: PluginContext): Dns;
167
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
168
+ export declare function deployment(ctx: PluginContext): Deployment;
169
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
170
+ export declare function workersCapability(ctx: PluginContext): Workers;
171
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
172
+ export declare function tunnelsCapability(ctx: PluginContext): Tunnels;
173
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
174
+ export declare function createPlugin(options?: CloudflarePluginOptions): {
109
175
  name: string;
176
+ probes: {
177
+ token: import("@theholocron/cli").Probe;
178
+ connection: import("@theholocron/cli").Probe;
179
+ };
180
+ whoami: import("@theholocron/cli").ProviderAction;
181
+ mintToken: (input: MintTokenInput) => Promise<import("@theholocron/cli").MintTokenResult>;
182
+ revokeToken: (input: RevokeTokenInput) => Promise<import("@theholocron/cli").RevokeTokenResult>;
183
+ readTokenId: () => Promise<string | undefined>;
110
184
  capabilities: {
111
185
  deployment?: (() => Deployment) | undefined;
112
186
  workers?: (() => Workers) | undefined;
187
+ tunnels?: (() => Tunnels) | undefined;
113
188
  dns: () => Dns;
114
189
  };
115
190
  };
116
- declare const AUTH_HINT: string;
117
- //#endregion
118
- export { AUTH_HINT, AuthError, type CloudflareClient, type CloudflareClientOptions, CloudflareDeployment, CloudflareDns, CloudflarePluginOptions, CloudflareWorkers, PluginContext, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
191
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
192
+ export declare const AUTH_HINT: string;
193
+ export { AuthError, type CloudflareClient, type CloudflareClientOptions, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient };
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);
@@ -78,6 +129,19 @@ var CloudflareDeployment = class {
78
129
  await this.client().pages.addDomain(this.accountId, projectId, hostname);
79
130
  return null;
80
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
+ };
144
+ }
81
145
  async getProjectByName(name) {
82
146
  try {
83
147
  return mapProject(await this.client().pages.getProject(this.accountId, name));
@@ -114,20 +178,180 @@ function normalizeStatus(status) {
114
178
  default: return "error";
115
179
  }
116
180
  }
117
- //#endregion
118
- //#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. */
119
325
  var CloudflareDns = class {
120
326
  client;
327
+ accountId;
328
+ /** The capability this class provides, always `"dns"`. */
121
329
  key = "dns";
330
+ /** The provider name, `"cloudflare"`. */
122
331
  providerName = "cloudflare";
123
332
  zoneCache = /* @__PURE__ */ new Map();
124
- constructor(client) {
333
+ constructor(client, accountId) {
125
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);
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;
126
348
  }
349
+ /** Lists the DNS records in the zone that holds the domain. */
127
350
  async listRecords(domain) {
128
351
  const zoneId = await this.resolveZone(domain);
129
352
  return (await this.client().dns.list(zoneId)).map(mapRecord);
130
353
  }
354
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
131
355
  async upsertRecord(domain, record) {
132
356
  const client = this.client();
133
357
  const zoneId = await this.resolveZone(domain);
@@ -150,10 +374,18 @@ var CloudflareDns = class {
150
374
  ...record.proxied !== void 0 ? { proxied: record.proxied } : {}
151
375
  }));
152
376
  }
377
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
153
378
  async deleteRecord(domain, id) {
154
379
  const zoneId = await this.resolveZone(domain);
155
380
  await this.client().dns.delete(zoneId, id);
156
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
+ }
157
389
  /**
158
390
  * Walk from full domain up to apex to find the Cloudflare zone.
159
391
  * E.g. "api.staging.example.com" tries:
@@ -182,15 +414,75 @@ function mapRecord(raw) {
182
414
  type: raw.type,
183
415
  name: raw.name,
184
416
  content: raw.content,
185
- ttl: raw.ttl
417
+ ttl: raw.ttl,
418
+ ...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
186
419
  };
187
420
  }
188
- //#endregion
189
- //#region src/capabilities/workers.ts
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
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];
436
+ }
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. */
190
480
  var CloudflareWorkers = class {
191
481
  client;
192
482
  accountId;
483
+ /** The capability this class provides, always `"workers"`. */
193
484
  key = "workers";
485
+ /** The provider name, `"cloudflare"`. */
194
486
  providerName = "cloudflare";
195
487
  zoneCache = /* @__PURE__ */ new Map();
196
488
  constructor(client, accountId) {
@@ -203,12 +495,58 @@ var CloudflareWorkers = class {
203
495
  await this.client().workers.putScript(this.accountId, scriptName, script);
204
496
  await this.upsertRoute(`${hostname}/*`, scriptName);
205
497
  }
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
+ };
504
+ }
206
505
  async deployScript(name, config) {
207
506
  await this.client().workers.putScript(this.accountId, name, config.code);
208
507
  for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
209
508
  for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
210
509
  return { scriptName: name };
211
510
  }
511
+ async setSecret(script, name, value) {
512
+ await this.client().workers.putSecret(this.accountId, script, name, value);
513
+ }
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: []
527
+ };
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)
535
+ };
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
+ }
212
550
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
213
551
  async upsertRoute(pattern, scriptName) {
214
552
  const hostname = pattern.split("/")[0];
@@ -251,8 +589,359 @@ function generateProxyScript(config) {
251
589
  `};`
252
590
  ].join("\n");
253
591
  }
254
- //#endregion
255
- //#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. */
256
945
  async function verifyToken(token, opts = {}) {
257
946
  const client = createCloudflareClient({
258
947
  token,
@@ -267,21 +956,26 @@ async function verifyToken(token, opts = {}) {
267
956
  };
268
957
  } catch {}
269
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
+ };
270
964
  return {
271
965
  ok: true,
272
- 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)`}`
273
967
  };
274
968
  } catch (err) {
275
969
  return {
276
970
  ok: false,
277
- message: err instanceof Error ? err.message : String(err)
971
+ message: errorMessage(err)
278
972
  };
279
973
  }
280
974
  }
281
- //#endregion
282
- //#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. */
283
977
  function createContext(options = {}) {
284
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
978
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
285
979
  const opts = {
286
980
  ...options,
287
981
  accountId
@@ -299,30 +993,81 @@ function createContext(options = {}) {
299
993
  })
300
994
  };
301
995
  }
996
+ /** Builds the `dns` capability for a context. */
302
997
  function dns(ctx) {
303
- return new CloudflareDns(ctx.client);
998
+ return new CloudflareDns(ctx.client, ctx.options.accountId);
304
999
  }
1000
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
305
1001
  function deployment(ctx) {
306
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");
307
1003
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
308
1004
  }
1005
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
309
1006
  function workersCapability(ctx) {
310
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");
311
1008
  return new CloudflareWorkers(ctx.client, ctx.options.accountId);
312
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. */
313
1016
  function createPlugin(options = {}) {
314
1017
  const ctx = createContext(options);
315
1018
  return {
316
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),
317
1061
  capabilities: {
318
1062
  dns: () => dns(ctx),
319
1063
  ...ctx.options.accountId ? {
320
1064
  deployment: () => deployment(ctx),
321
- workers: () => workersCapability(ctx)
1065
+ workers: () => workersCapability(ctx),
1066
+ tunnels: () => tunnelsCapability(ctx)
322
1067
  } : {}
323
1068
  }
324
1069
  };
325
1070
  }
326
- 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>";
327
- //#endregion
328
- 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theholocron/holocron-plugin-cloudflare",
3
- "version": "5.0.0-alpha.57",
3
+ "version": "5.0.0-alpha.571",
4
4
  "description": "Holocron plugin for Cloudflare. Implements the dns capability against Cloudflare's REST API — zone resolution, DNS record management.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -8,12 +8,12 @@
8
8
  "holocron",
9
9
  "plugin"
10
10
  ],
11
- "homepage": "https://github.com/theholocron/holocron/tree/main/packages/holocron-plugin-cloudflare#readme",
11
+ "homepage": "https://docs.theholocron.dev/holocron/plugins/cloudflare/",
12
12
  "bugs": "https://github.com/theholocron/holocron/issues",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "git+https://github.com/theholocron/holocron.git",
16
- "directory": "packages/holocron-plugin-cloudflare"
16
+ "directory": "plugins/holocron-plugin-cloudflare"
17
17
  },
18
18
  "license": "MIT",
19
19
  "author": "Newton Koumantzelis",
@@ -29,29 +29,35 @@
29
29
  "files": [
30
30
  "dist"
31
31
  ],
32
+ "dependencies": {
33
+ "@theholocron/env-utils": "^1.17.0-alpha.9"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/cloudflare-client": "^1.25.0",
34
- "@theholocron/eslint-config": "^8.4.5",
35
- "@theholocron/http-client": "^1.25.0",
36
- "@theholocron/tsconfig": "^8.4.5",
37
- "@theholocron/tsdown-config": "^8.4.5",
38
- "@theholocron/vitest-config": "^8.4.5",
39
36
  "@types/node": "^26",
40
- "@vitest/coverage-v8": "^4.1.11",
41
- "@vitest/eslint-plugin": "^1.6.27",
42
- "chalk": "^6.0.0",
43
- "eslint": "^10.8.1",
44
- "eslint-plugin-n": "^18.3.0",
45
- "globals": "^17.11.0",
46
- "tsdown": "^0.22.14",
47
- "tsx": "4.23.12",
48
- "typescript": "^5.9.3",
49
- "vitest": "^4.1.11",
50
- "@theholocron/cli": "5.0.0-alpha.57"
37
+ "@vitest/coverage-v8": "^5.1.1",
38
+ "@vitest/eslint-plugin": "^1.6.28",
39
+ "chalk": "^6.0.1",
40
+ "eslint": "^10.15.0",
41
+ "eslint-plugin-n": "^18.5.0",
42
+ "globals": "^17.14.0",
43
+ "tsdown": "^0.23.7",
44
+ "tsx": "4.23.15",
45
+ "typescript": "^6.0.3",
46
+ "vitest": "^5.1.1",
47
+ "@theholocron/cli": "5.0.0-alpha.571",
48
+ "@theholocron/cloudflare-client": "^1.58.0-alpha.66",
49
+ "@theholocron/eslint-config": "^8.9.0-alpha.24",
50
+ "@theholocron/http-client": "^1.58.0-alpha.66",
51
+ "@theholocron/misc-utils": "^1.17.0-alpha.9",
52
+ "@theholocron/kyber": "5.0.0-alpha.571",
53
+ "@theholocron/tsconfig": "^8.9.0-alpha.24",
54
+ "@theholocron/tsdown-config": "^8.9.0-alpha.24",
55
+ "@theholocron/vitest-config": "^8.9.0-alpha.24"
51
56
  },
52
57
  "peerDependencies": {
53
- "@theholocron/cloudflare-client": "^1.25.0",
54
- "@theholocron/cli": "5.0.0-alpha.57"
58
+ "@theholocron/cloudflare-client": "^1.58.0",
59
+ "@theholocron/misc-utils": "^1.16.0",
60
+ "@theholocron/cli": "5.0.0-alpha.571"
55
61
  },
56
62
  "peerDependenciesMeta": {
57
63
  "@theholocron/cloudflare-client": {}
@@ -63,11 +69,11 @@
63
69
  "access": "public"
64
70
  },
65
71
  "scripts": {
66
- "delivery.build": "tsdown",
67
- "sourceQuality.staticAnalysis": "holocron run sourceQuality.staticAnalysis --",
72
+ "build": "tsdown",
73
+ "lint:code": "eslint .",
74
+ "test:unit": "vitest run --coverage",
68
75
  "test:watch": "vitest",
69
- "validate": "tsx scripts/validate.mjs",
70
- "verification.typeSafety": "holocron run verification.typeSafety --",
71
- "verification.unitTests": "holocron run verification.unitTests --"
76
+ "typecheck": "tsc --noEmit",
77
+ "validate:plugin": "tsx scripts/validate.mjs"
72
78
  }
73
79
  }