@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.55 → 5.0.0-alpha.551

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, PluginToken, RelaySourceState, ResolveTokenInput, 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,112 @@ 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
+ };
110
180
  capabilities: {
111
181
  deployment?: (() => Deployment) | undefined;
112
182
  workers?: (() => Workers) | undefined;
183
+ tunnels?: (() => Tunnels) | undefined;
113
184
  dns: () => Dns;
114
185
  };
115
186
  };
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 };
187
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
188
+ export declare const AUTH_HINT: string;
189
+ 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 } 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 } : {}
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
186
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];
187
436
  }
188
- //#endregion
189
- //#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. */
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,224 @@ function generateProxyScript(config) {
251
589
  `};`
252
590
  ].join("\n");
253
591
  }
254
- //#endregion
255
- //#region src/verify-token.ts
592
+ // src/probes/token/parse-token-args.ts
593
+ /** Reads the words after the probe name: `--layer <word>`, `--token-name <VAR>` and any number of zone names. */
594
+ function parseTokenArgs(args) {
595
+ const zones = [];
596
+ let layer;
597
+ let tokenName;
598
+ for (let i = 0; i < args.length; i++) {
599
+ const arg = args[i];
600
+ if (arg === "--layer") layer = args[++i];
601
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
602
+ else if (arg === "--token-name") tokenName = args[++i];
603
+ else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
604
+ else if (!arg.startsWith("--")) zones.push(arg);
605
+ }
606
+ return {
607
+ ...layer ? { layer } : {},
608
+ ...tokenName ? { tokenName } : {},
609
+ zones
610
+ };
611
+ }
612
+ // src/probes/token/token.ts
613
+ /** The most zones whose DNS and Workers routes are read, so a token that sees many does not make many requests. */
614
+ const MAX_ZONES = 5;
615
+ /** How many names to show before "(+N more)". */
616
+ const SHOWN = 5;
617
+ /** `a, b, c (+2 more)`. */
618
+ function summarise(names) {
619
+ return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
620
+ }
621
+ /**
622
+ * Reads one list and says what came back. Cloudflare answers a token without the permission in one of two ways (a 401 or
623
+ * 403, or an empty list), so an empty list is `none`: the token cannot see any, or there are none. A request that fails
624
+ * for another reason (the network, a 5xx) is an `error`.
625
+ */
626
+ async function reach(read, noun) {
627
+ try {
628
+ const items = await read();
629
+ if (items.length === 0) return {
630
+ kind: "none",
631
+ detail: `no ${noun} visible (none exist, or the token cannot see them)`
632
+ };
633
+ const names = items.map((i) => i.name).filter((n) => typeof n === "string");
634
+ return {
635
+ kind: "has",
636
+ detail: names.length > 0 ? `${items.length} ${noun}: ${summarise(names)}` : `${items.length} ${noun}`
637
+ };
638
+ } catch (err) {
639
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
640
+ kind: "none",
641
+ detail: `no access (${err.status})`
642
+ };
643
+ return {
644
+ kind: "error",
645
+ detail: errorMessage(err)
646
+ };
647
+ }
648
+ }
649
+ /**
650
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
651
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
652
+ * permission that is rightly absent is a bare `ok`.
653
+ */
654
+ function rowFor({ label, outcome }, rule) {
655
+ if (outcome.kind === "error") return {
656
+ status: "fail",
657
+ label,
658
+ detail: outcome.detail
659
+ };
660
+ const has = outcome.kind === "has";
661
+ if (rule === "required") return has ? {
662
+ status: "ok",
663
+ label,
664
+ detail: outcome.detail
665
+ } : {
666
+ status: "fail",
667
+ label,
668
+ detail: outcome.detail
669
+ };
670
+ if (rule === "absent") return has ? {
671
+ status: "fail",
672
+ label,
673
+ detail: outcome.detail
674
+ } : {
675
+ status: "ok",
676
+ label
677
+ };
678
+ return {
679
+ status: has ? "ok" : "info",
680
+ label,
681
+ detail: outcome.detail
682
+ };
683
+ }
684
+ /**
685
+ * The `token` probe: tries each permission Holocron uses with the Cloudflare API token and reports which ones the token
686
+ * has. It only reads (a list per permission), so it changes nothing. The token is the one the plugin resolves, so
687
+ * `--token cloudflare=<token>` or `--environment <layer>` checks another one; the account id is the plugin's own.
688
+ *
689
+ * A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
690
+ * `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
691
+ * two groups, what it should have and what it should not, where a missing or extra permission fails. The other words
692
+ * limit the zone checks to those zones; otherwise up to five are read. How the token is chosen is in `holocron probe --help`.
693
+ */
694
+ function tokenProbe(ctx) {
695
+ return {
696
+ 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.",
697
+ writes: false,
698
+ acceptsToken: true,
699
+ async run(probe) {
700
+ const token = ctx.token();
701
+ probe.secret(token);
702
+ const client = ctx.client();
703
+ const { layer, tokenName, zones: wanted } = parseTokenArgs(probe.args ?? []);
704
+ const expectation = layer ? tokenExpectations(tokens, {
705
+ layer,
706
+ ...tokenName ? { envName: tokenName } : {}
707
+ })[0] : void 0;
708
+ const rules = expectation?.rules;
709
+ if (layer && !rules) probe.say({
710
+ status: "info",
711
+ label: layer,
712
+ detail: "no expectations are declared for it, so the token is only described"
713
+ });
714
+ const now = (ctx.now ?? (() => /* @__PURE__ */ new Date()))();
715
+ const rotation = expectation?.rotation ?? DEFAULT_TOKEN_ROTATION;
716
+ let lifetime;
717
+ try {
718
+ const verified = await client.tokens.verify();
719
+ probe.say({
720
+ status: "ok",
721
+ label: "token",
722
+ detail: `${verified.id} (${verified.status})`
723
+ });
724
+ lifetime = {
725
+ ...verified.not_before ? { createdAt: verified.not_before } : {},
726
+ ...verified.expires_on ? { expiresAt: verified.expires_on } : {}
727
+ };
728
+ } catch {}
729
+ const rotationRows = tokenRotationRows(lifetime, rotation, now);
730
+ const sayRotation = () => {
731
+ probe.say({
732
+ status: "heading",
733
+ label: "Rotation"
734
+ });
735
+ for (const row of rotationRows) probe.say(row);
736
+ };
737
+ const named = wanted.length > 0 ? wanted : ctx.options.zone ? [ctx.options.zone] : [];
738
+ const tried = [];
739
+ let zones = [];
740
+ const zoneOutcome = await reach(async () => {
741
+ zones = named.length > 0 ? (await Promise.all(named.map((name) => client.zones.list({ name })))).flat() : await client.zones.list({ per_page: MAX_ZONES });
742
+ return zones.map((z) => ({ name: z.name }));
743
+ }, "zones");
744
+ tried.push({
745
+ label: "Zone: Read",
746
+ permission: "zone",
747
+ outcome: zoneOutcome
748
+ });
749
+ if (zoneOutcome.kind !== "error") {
750
+ for (const zone of zones.slice(0, MAX_ZONES)) {
751
+ tried.push({
752
+ label: `DNS: Edit (${zone.name})`,
753
+ permission: "dns",
754
+ outcome: await reach(() => client.dns.list(zone.id), "records")
755
+ });
756
+ tried.push({
757
+ label: `Workers Routes: Edit (${zone.name})`,
758
+ permission: "routes",
759
+ outcome: await reach(async () => (await client.workers.listRoutes(zone.id)).map((r) => ({ name: r.pattern })), "routes")
760
+ });
761
+ }
762
+ const account = ctx.options.accountId;
763
+ if (account) {
764
+ tried.push({
765
+ label: "Workers Scripts: Edit",
766
+ permission: "scripts",
767
+ outcome: await reach(async () => (await client.workers.listScripts(account)).map((s) => ({ name: s.id })), "scripts")
768
+ });
769
+ tried.push({
770
+ label: "Pages: Edit",
771
+ permission: "pages",
772
+ outcome: await reach(() => client.pages.listProjects(account), "projects")
773
+ });
774
+ tried.push({
775
+ label: "Cloudflare Tunnel: Edit",
776
+ permission: "tunnels",
777
+ outcome: await reach(() => client.tunnels.list(account), "tunnels")
778
+ });
779
+ tried.push({
780
+ label: "Notifications: Edit",
781
+ permission: "notifications",
782
+ outcome: await reach(async () => (await client.alerting.webhooks.list(account)).map((w) => ({ name: w.name })), "notification webhooks")
783
+ });
784
+ } else probe.say({
785
+ status: rules ? "fail" : "info",
786
+ label: "account permissions",
787
+ detail: "no account id: set HOLOCRON_CLOUDFLARE_ACCOUNT_ID or the plugin's accountId option to check them"
788
+ });
789
+ }
790
+ if (!rules) {
791
+ for (const t of tried) probe.say(rowFor(t, void 0));
792
+ sayRotation();
793
+ return;
794
+ }
795
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
796
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
797
+ if (inGroup.length === 0) continue;
798
+ probe.say({
799
+ status: "heading",
800
+ label: heading
801
+ });
802
+ for (const t of inGroup) probe.say(rowFor(t, rule));
803
+ }
804
+ sayRotation();
805
+ }
806
+ };
807
+ }
808
+ // src/verify-token.ts
809
+ /** 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
810
  async function verifyToken(token, opts = {}) {
257
811
  const client = createCloudflareClient({
258
812
  token,
@@ -267,21 +821,26 @@ async function verifyToken(token, opts = {}) {
267
821
  };
268
822
  } catch {}
269
823
  try {
824
+ const names = (await client.zones.list()).map((z) => z.name);
825
+ if (names.length === 0) return {
826
+ ok: true,
827
+ subject: "no zones visible"
828
+ };
270
829
  return {
271
830
  ok: true,
272
- subject: `zone: ${(await client.zones.list({ per_page: 1 }))[0]?.name ?? "unknown"}`
831
+ subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
273
832
  };
274
833
  } catch (err) {
275
834
  return {
276
835
  ok: false,
277
- message: err instanceof Error ? err.message : String(err)
836
+ message: errorMessage(err)
278
837
  };
279
838
  }
280
839
  }
281
- //#endregion
282
- //#region src/index.ts
840
+ // src/index.ts
841
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
283
842
  function createContext(options = {}) {
284
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
843
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
285
844
  const opts = {
286
845
  ...options,
287
846
  accountId
@@ -299,30 +858,53 @@ function createContext(options = {}) {
299
858
  })
300
859
  };
301
860
  }
861
+ /** Builds the `dns` capability for a context. */
302
862
  function dns(ctx) {
303
- return new CloudflareDns(ctx.client);
863
+ return new CloudflareDns(ctx.client, ctx.options.accountId);
304
864
  }
865
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
305
866
  function deployment(ctx) {
306
867
  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
868
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
308
869
  }
870
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
309
871
  function workersCapability(ctx) {
310
872
  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
873
  return new CloudflareWorkers(ctx.client, ctx.options.accountId);
312
874
  }
875
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
876
+ function tunnelsCapability(ctx) {
877
+ 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");
878
+ return new CloudflareTunnels(ctx.client, ctx.options.accountId);
879
+ }
880
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
313
881
  function createPlugin(options = {}) {
314
882
  const ctx = createContext(options);
315
883
  return {
316
884
  name: "@theholocron/holocron-plugin-cloudflare",
885
+ probes: {
886
+ token: tokenProbe(ctx),
887
+ connection: connectionProbe({
888
+ provider: "Cloudflare",
889
+ url: options.baseUrl ?? "https://api.cloudflare.com",
890
+ fetch: options.fetch,
891
+ token: () => resolveToken(options),
892
+ verify: (token) => verifyToken(token, {
893
+ baseUrl: options.baseUrl,
894
+ fetch: options.fetch
895
+ })
896
+ })
897
+ },
317
898
  capabilities: {
318
899
  dns: () => dns(ctx),
319
900
  ...ctx.options.accountId ? {
320
901
  deployment: () => deployment(ctx),
321
- workers: () => workersCapability(ctx)
902
+ workers: () => workersCapability(ctx),
903
+ tunnels: () => tunnelsCapability(ctx)
322
904
  } : {}
323
905
  }
324
906
  };
325
907
  }
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 };
908
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
909
+ 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>";
910
+ 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.55",
3
+ "version": "5.0.0-alpha.551",
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.8"
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.55"
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.551",
48
+ "@theholocron/cloudflare-client": "^1.58.0-alpha.59",
49
+ "@theholocron/eslint-config": "^8.9.0-alpha.24",
50
+ "@theholocron/http-client": "^1.58.0-alpha.59",
51
+ "@theholocron/kyber": "5.0.0-alpha.551",
52
+ "@theholocron/misc-utils": "^1.17.0-alpha.8",
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.55"
58
+ "@theholocron/cloudflare-client": "^1.53.1",
59
+ "@theholocron/misc-utils": "^1.16.0",
60
+ "@theholocron/cli": "5.0.0-alpha.551"
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
  }