@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.43 → 5.0.0-alpha.430

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, EnsuredTunnel, PluginToken, ResolveTokenInput, TunnelRoute, Tunnels, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, WikiProxyConfig, 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,44 @@ 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>;
32
40
  private getProjectByName;
33
41
  }
34
- //#endregion
35
- //#region src/capabilities/dns.d.ts
36
- declare class CloudflareDns implements Dns {
42
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
43
+ export declare class CloudflareDns implements Dns {
37
44
  private readonly client;
45
+ /** The capability this class provides, always `"dns"`. */
38
46
  readonly key: "dns";
47
+ /** The provider name, `"cloudflare"`. */
39
48
  readonly providerName = "cloudflare";
40
49
  private readonly zoneCache;
41
50
  constructor(client: () => CloudflareClient);
51
+ /** Lists the DNS records in the zone that holds the domain. */
42
52
  listRecords(domain: string): Promise<DnsRecord[]>;
53
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
43
54
  upsertRecord(domain: string, record: DnsRecord): Promise<DnsRecord>;
55
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
44
56
  deleteRecord(domain: string, id: string): Promise<void>;
57
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
58
+ whoami(): Promise<{
59
+ ok: boolean;
60
+ zones: number;
61
+ }>;
45
62
  /**
46
63
  * Walk from full domain up to apex to find the Cloudflare zone.
47
64
  * E.g. "api.staging.example.com" tries:
@@ -51,40 +68,61 @@ declare class CloudflareDns implements Dns {
51
68
  */
52
69
  private resolveZone;
53
70
  }
54
- //#endregion
55
- //#region src/capabilities/workers.d.ts
56
- declare class CloudflareWorkers implements Workers {
71
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
72
+ export declare class CloudflareTunnels implements Tunnels {
57
73
  private readonly client;
58
74
  private readonly accountId;
75
+ /** The capability this class provides, always `"tunnels"`. */
76
+ readonly key: "tunnels";
77
+ /** The provider name, `"cloudflare"`. */
78
+ readonly providerName = "cloudflare";
79
+ constructor(client: () => Pick<CloudflareClient$1, "tunnels">, accountId: string);
80
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
81
+ ensureTunnel(route: TunnelRoute): Promise<EnsuredTunnel>;
82
+ /** The token `cloudflared` runs the tunnel with. */
83
+ tunnelToken(tunnelId: string): Promise<string>;
84
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
85
+ whoami(): Promise<{
86
+ ok: boolean;
87
+ tunnels: number;
88
+ }>;
89
+ }
90
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
91
+ export declare class CloudflareWorkers implements Workers {
92
+ private readonly client;
93
+ private readonly accountId;
94
+ /** The capability this class provides, always `"workers"`. */
59
95
  readonly key: "workers";
96
+ /** The provider name, `"cloudflare"`. */
60
97
  readonly providerName = "cloudflare";
61
98
  private readonly zoneCache;
62
99
  constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
63
100
  upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
101
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
102
+ whoami(): Promise<{
103
+ ok: boolean;
104
+ scripts: number;
105
+ }>;
64
106
  deployScript(name: string, config: DeployScriptConfig): Promise<DeployScriptResult>;
107
+ setSecret(script: string, name: string, value: string): Promise<void>;
108
+ secretNames(script: string): Promise<string[]>;
109
+ /**
110
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
111
+ * only, and asks Cloudflare for names, so no value is ever fetched.
112
+ */
113
+ inspectScript(name: string, host: string): Promise<WorkerScriptState>;
65
114
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
66
115
  private upsertRoute;
67
116
  private resolveZone;
68
117
  }
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
118
  interface VerifyTokenOptions {
81
119
  baseUrl?: string;
82
120
  fetch?: typeof fetch;
83
121
  }
84
- declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult>;
85
- //#endregion
86
- //#region src/index.d.ts
87
- interface CloudflarePluginOptions extends ResolveTokenInput {
122
+ /** 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. */
123
+ export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
124
+ /** Options for the Cloudflare plugin: how the API token is resolved, the account, and test overrides. */
125
+ export interface CloudflarePluginOptions extends ResolveTokenInput {
88
126
  /**
89
127
  * Cloudflare account ID. Required for Pages (deployment) operations;
90
128
  * optional for DNS-only use.
@@ -92,27 +130,42 @@ interface CloudflarePluginOptions extends ResolveTokenInput {
92
130
  accountId?: string;
93
131
  /** Override base URL for tests. */
94
132
  baseUrl?: string;
133
+ /** The `fetch` to use instead of the global one, for tests. */
95
134
  fetch?: typeof fetch;
96
135
  }
97
- interface PluginContext {
136
+ /** The shared state the Cloudflare plugin's capabilities and probes are built from. */
137
+ export interface PluginContext {
138
+ /** 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
139
  options: CloudflarePluginOptions;
99
140
  /** Memoized client — the token is resolved on first use, not at plugin load. */
100
141
  client: () => CloudflareClient;
101
142
  /** Memoized token resolver — shared by the client and the Workers capability. */
102
143
  token: () => string;
103
144
  }
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): {
145
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
146
+ export declare function createContext(options?: CloudflarePluginOptions): PluginContext;
147
+ /** Builds the `dns` capability for a context. */
148
+ export declare function dns(ctx: PluginContext): Dns;
149
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
150
+ export declare function deployment(ctx: PluginContext): Deployment;
151
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
152
+ export declare function workersCapability(ctx: PluginContext): Workers;
153
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
154
+ export declare function tunnelsCapability(ctx: PluginContext): Tunnels;
155
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
156
+ export declare function createPlugin(options?: CloudflarePluginOptions): {
109
157
  name: string;
158
+ probes: {
159
+ token: import("@theholocron/cli").Probe;
160
+ connection: import("@theholocron/cli").Probe;
161
+ };
110
162
  capabilities: {
111
163
  deployment?: (() => Deployment) | undefined;
112
164
  workers?: (() => Workers) | undefined;
165
+ tunnels?: (() => Tunnels) | undefined;
113
166
  dns: () => Dns;
114
167
  };
115
168
  };
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 };
169
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
170
+ export declare const AUTH_HINT: string;
171
+ export { AuthError, type CloudflareClient, type CloudflareClientOptions, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient };
package/dist/index.mjs CHANGED
@@ -1,23 +1,62 @@
1
- import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
1
+ import { AuthError, ProviderApiError, connectionProbe, createResolveToken, resolveValue, tokenExpectations } 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
+ };
14
+ /**
15
+ * What each layer's Cloudflare token is meant to carry, the same as "What each Cloudflare token needs" in
16
+ * `docs/src/content/docs/tokens.mdx`: a laptop (`local` inherits `dev`) runs everything, CI only deploys Pages, so a
17
+ * leak from CI cannot change DNS, Workers or a tunnel. A layer not listed (`prod`) has no declared expectations and its
18
+ * token is only reported. This is the plugin's `tokens` declaration, read through `tokenExpectations()`; change it and
19
+ * that table together.
20
+ */
21
+ const EXPECTED = { permissions: {
22
+ local: EVERYTHING,
23
+ dev: EVERYTHING,
24
+ ci: {
25
+ zone: "absent",
26
+ dns: "absent",
27
+ routes: "absent",
28
+ scripts: "absent",
29
+ pages: "required",
30
+ tunnels: "absent"
31
+ }
32
+ } };
33
+ // src/auth.ts
34
+ /** 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
35
  const resolveToken = createResolveToken({
5
36
  envName: "HOLOCRON_CLOUDFLARE_TOKEN",
6
37
  vendorEnvName: "CLOUDFLARE_API_TOKEN",
7
38
  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>"
39
+ errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron new token cloudflare <TOKEN>"
9
40
  });
10
- //#endregion
11
- //#region src/capabilities/deployment.ts
41
+ /** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
42
+ const tokens = [{
43
+ ...resolveToken.token,
44
+ expect: EXPECTED
45
+ }];
46
+ // src/capabilities/deployment.ts
47
+ /** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
12
48
  var CloudflareDeployment = class {
13
49
  client;
14
50
  accountId;
51
+ /** The capability this class provides, always `"deployment"`. */
15
52
  key = "deployment";
53
+ /** The provider name, `"cloudflare"`. */
16
54
  providerName = "cloudflare";
17
55
  constructor(client, accountId) {
18
56
  this.client = client;
19
57
  this.accountId = accountId;
20
58
  }
59
+ /** Lists the account's Pages projects. */
21
60
  async listProjects() {
22
61
  return (await this.client().pages.listProjects(this.accountId)).map(mapProject);
23
62
  }
@@ -29,14 +68,17 @@ var CloudflareDeployment = class {
29
68
  production_branch: "main"
30
69
  }));
31
70
  }
71
+ /** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
32
72
  async updateProjectSettings(projectId, settings) {
33
73
  return mapProject(await this.client().pages.getProject(this.accountId, projectId));
34
74
  }
75
+ /** Lists the names of the environment variables set for the production or preview target. */
35
76
  async listEnvVars(projectId, target) {
36
77
  const project = await this.client().pages.getProject(this.accountId, projectId);
37
78
  const envConfig = target === "production" ? project.deployment_configs.production : project.deployment_configs.preview;
38
79
  return Object.keys(envConfig.env_vars);
39
80
  }
81
+ /** Sets a plain-text environment variable on the production or preview target, keeping the others. */
40
82
  async setEnvVar(projectId, target, name, value) {
41
83
  const cfg = (await this.client().pages.getProject(this.accountId, projectId)).deployment_configs;
42
84
  const scope = target === "production" ? "production" : "preview";
@@ -55,6 +97,7 @@ var CloudflareDeployment = class {
55
97
  async triggerDeployment(input) {
56
98
  return mapDeployment(await this.client().pages.createDeployment(this.accountId, input.projectId, input.branch), input.projectId, input.branch, input.target);
57
99
  }
100
+ /** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
58
101
  async getDeployment(deploymentId) {
59
102
  const sep = deploymentId.indexOf(":");
60
103
  if (sep === -1) throw new ProviderApiError(`Invalid Cloudflare Pages deployment id "${deploymentId}" — expected "projectName:deploymentId"`, 400, void 0);
@@ -114,20 +157,24 @@ function normalizeStatus(status) {
114
157
  default: return "error";
115
158
  }
116
159
  }
117
- //#endregion
118
- //#region src/capabilities/dns.ts
160
+ // src/capabilities/dns.ts
161
+ /** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
119
162
  var CloudflareDns = class {
120
163
  client;
164
+ /** The capability this class provides, always `"dns"`. */
121
165
  key = "dns";
166
+ /** The provider name, `"cloudflare"`. */
122
167
  providerName = "cloudflare";
123
168
  zoneCache = /* @__PURE__ */ new Map();
124
169
  constructor(client) {
125
170
  this.client = client;
126
171
  }
172
+ /** Lists the DNS records in the zone that holds the domain. */
127
173
  async listRecords(domain) {
128
174
  const zoneId = await this.resolveZone(domain);
129
175
  return (await this.client().dns.list(zoneId)).map(mapRecord);
130
176
  }
177
+ /** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
131
178
  async upsertRecord(domain, record) {
132
179
  const client = this.client();
133
180
  const zoneId = await this.resolveZone(domain);
@@ -150,10 +197,18 @@ var CloudflareDns = class {
150
197
  ...record.proxied !== void 0 ? { proxied: record.proxied } : {}
151
198
  }));
152
199
  }
200
+ /** Deletes the DNS record with this id from the zone that holds the domain. */
153
201
  async deleteRecord(domain, id) {
154
202
  const zoneId = await this.resolveZone(domain);
155
203
  await this.client().dns.delete(zoneId, id);
156
204
  }
205
+ /** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
206
+ async whoami() {
207
+ return {
208
+ ok: true,
209
+ zones: (await this.client().zones.list()).length
210
+ };
211
+ }
157
212
  /**
158
213
  * Walk from full domain up to apex to find the Cloudflare zone.
159
214
  * E.g. "api.staging.example.com" tries:
@@ -182,15 +237,75 @@ function mapRecord(raw) {
182
237
  type: raw.type,
183
238
  name: raw.name,
184
239
  content: raw.content,
185
- ttl: raw.ttl
240
+ ttl: raw.ttl,
241
+ ...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
242
+ };
243
+ }
244
+ // src/capabilities/tunnels.ts
245
+ /** The rule a tunnel needs last: anything no other rule matches is answered with a 404 by the connector itself. */
246
+ const CATCH_ALL = { service: "http_status:404" };
247
+ /**
248
+ * The ingress rules with `hostname` served at `service`: the rule for the hostname is replaced where it is or added
249
+ * after the others, every other hostname's rule is kept, and the rule without a hostname closes the list.
250
+ */
251
+ function withRoute(current, hostname, service) {
252
+ const rule = {
253
+ hostname,
254
+ service
186
255
  };
256
+ const named = current.filter((r) => r.hostname !== void 0);
257
+ const at = named.findIndex((r) => r.hostname === hostname);
258
+ return [...at === -1 ? [...named, rule] : named.map((r, i) => i === at ? rule : r), current.find((r) => r.hostname === void 0) ?? CATCH_ALL];
187
259
  }
188
- //#endregion
189
- //#region src/capabilities/workers.ts
260
+ /** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
261
+ var CloudflareTunnels = class {
262
+ client;
263
+ accountId;
264
+ /** The capability this class provides, always `"tunnels"`. */
265
+ key = "tunnels";
266
+ /** The provider name, `"cloudflare"`. */
267
+ providerName = "cloudflare";
268
+ constructor(client, accountId) {
269
+ this.client = client;
270
+ this.accountId = accountId;
271
+ }
272
+ /** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
273
+ async ensureTunnel(route) {
274
+ const { tunnels } = this.client();
275
+ const found = (await tunnels.list(this.accountId)).find((t) => t.name === route.name);
276
+ const tunnel = found ?? await tunnels.create(this.accountId, { name: route.name });
277
+ const current = (await tunnels.getConfig(this.accountId, tunnel.id)).config?.ingress ?? [];
278
+ const wanted = withRoute(current, route.hostname, route.service);
279
+ const configured = JSON.stringify(wanted) !== JSON.stringify(current);
280
+ if (configured) await tunnels.putConfig(this.accountId, tunnel.id, { ingress: wanted });
281
+ return {
282
+ id: tunnel.id,
283
+ name: tunnel.name,
284
+ created: found === void 0,
285
+ configured,
286
+ target: `${tunnel.id}.cfargotunnel.com`
287
+ };
288
+ }
289
+ /** The token `cloudflared` runs the tunnel with. */
290
+ tunnelToken(tunnelId) {
291
+ return this.client().tunnels.token(this.accountId, tunnelId);
292
+ }
293
+ /** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
294
+ async whoami() {
295
+ return {
296
+ ok: true,
297
+ tunnels: (await this.client().tunnels.list(this.accountId)).length
298
+ };
299
+ }
300
+ };
301
+ // src/capabilities/workers.ts
302
+ /** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
190
303
  var CloudflareWorkers = class {
191
304
  client;
192
305
  accountId;
306
+ /** The capability this class provides, always `"workers"`. */
193
307
  key = "workers";
308
+ /** The provider name, `"cloudflare"`. */
194
309
  providerName = "cloudflare";
195
310
  zoneCache = /* @__PURE__ */ new Map();
196
311
  constructor(client, accountId) {
@@ -203,12 +318,45 @@ var CloudflareWorkers = class {
203
318
  await this.client().workers.putScript(this.accountId, scriptName, script);
204
319
  await this.upsertRoute(`${hostname}/*`, scriptName);
205
320
  }
321
+ /** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
322
+ async whoami() {
323
+ return {
324
+ ok: true,
325
+ scripts: (await this.client().workers.listScripts(this.accountId)).length
326
+ };
327
+ }
206
328
  async deployScript(name, config) {
207
329
  await this.client().workers.putScript(this.accountId, name, config.code);
208
330
  for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
209
331
  for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
210
332
  return { scriptName: name };
211
333
  }
334
+ async setSecret(script, name, value) {
335
+ await this.client().workers.putSecret(this.accountId, script, name, value);
336
+ }
337
+ async secretNames(script) {
338
+ return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
339
+ }
340
+ /**
341
+ * Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
342
+ * only, and asks Cloudflare for names, so no value is ever fetched.
343
+ */
344
+ async inspectScript(name, host) {
345
+ const client = this.client();
346
+ if (!(await client.workers.listScripts(this.accountId)).some((s) => s.id === name)) return {
347
+ exists: false,
348
+ routes: [],
349
+ bindingNames: []
350
+ };
351
+ const zoneId = await this.resolveZone(host);
352
+ const routes = await client.workers.listRoutes(zoneId);
353
+ const secrets = await client.workers.listSecrets(this.accountId, name);
354
+ return {
355
+ exists: true,
356
+ routes: routes.filter((r) => r.script === name).map((r) => r.pattern),
357
+ bindingNames: secrets.map((secret) => secret.name)
358
+ };
359
+ }
212
360
  /** Idempotent create-or-update for one route pattern — shared by both public methods. */
213
361
  async upsertRoute(pattern, scriptName) {
214
362
  const hostname = pattern.split("/")[0];
@@ -251,8 +399,193 @@ function generateProxyScript(config) {
251
399
  `};`
252
400
  ].join("\n");
253
401
  }
254
- //#endregion
255
- //#region src/verify-token.ts
402
+ // src/probes/token/parse-token-args.ts
403
+ /** Reads the words after the probe name: `--layer <word>` and any number of zone names. */
404
+ function parseTokenArgs(args) {
405
+ const zones = [];
406
+ let layer;
407
+ for (let i = 0; i < args.length; i++) {
408
+ const arg = args[i];
409
+ if (arg === "--layer") layer = args[++i];
410
+ else if (arg.startsWith("--layer=")) layer = arg.slice(8);
411
+ else if (!arg.startsWith("--")) zones.push(arg);
412
+ }
413
+ return {
414
+ ...layer ? { layer } : {},
415
+ zones
416
+ };
417
+ }
418
+ // src/probes/token/token.ts
419
+ /** The most zones whose DNS and Workers routes are read, so a token that sees many does not make many requests. */
420
+ const MAX_ZONES = 5;
421
+ /** How many names to show before "(+N more)". */
422
+ const SHOWN = 5;
423
+ /** `a, b, c (+2 more)`. */
424
+ function summarise(names) {
425
+ return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
426
+ }
427
+ /**
428
+ * Reads one list and says what came back. Cloudflare answers a token without the permission in one of two ways (a 401 or
429
+ * 403, or an empty list), so an empty list is `none`: the token cannot see any, or there are none. A request that fails
430
+ * for another reason (the network, a 5xx) is an `error`.
431
+ */
432
+ async function reach(read, noun) {
433
+ try {
434
+ const items = await read();
435
+ if (items.length === 0) return {
436
+ kind: "none",
437
+ detail: `no ${noun} visible (none exist, or the token cannot see them)`
438
+ };
439
+ const names = items.map((i) => i.name).filter((n) => typeof n === "string");
440
+ return {
441
+ kind: "has",
442
+ detail: names.length > 0 ? `${items.length} ${noun}: ${summarise(names)}` : `${items.length} ${noun}`
443
+ };
444
+ } catch (err) {
445
+ if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
446
+ kind: "none",
447
+ detail: `no access (${err.status})`
448
+ };
449
+ return {
450
+ kind: "error",
451
+ detail: errorMessage(err)
452
+ };
453
+ }
454
+ }
455
+ /**
456
+ * One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
457
+ * judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
458
+ * permission that is rightly absent is a bare `ok`.
459
+ */
460
+ function rowFor({ label, outcome }, rule) {
461
+ if (outcome.kind === "error") return {
462
+ status: "fail",
463
+ label,
464
+ detail: outcome.detail
465
+ };
466
+ const has = outcome.kind === "has";
467
+ if (rule === "required") return has ? {
468
+ status: "ok",
469
+ label,
470
+ detail: outcome.detail
471
+ } : {
472
+ status: "fail",
473
+ label,
474
+ detail: outcome.detail
475
+ };
476
+ if (rule === "absent") return has ? {
477
+ status: "fail",
478
+ label,
479
+ detail: outcome.detail
480
+ } : {
481
+ status: "ok",
482
+ label
483
+ };
484
+ return {
485
+ status: has ? "ok" : "info",
486
+ label,
487
+ detail: outcome.detail
488
+ };
489
+ }
490
+ /**
491
+ * The `token` probe: tries each permission Holocron uses with the Cloudflare API token and reports which ones the token
492
+ * has. It only reads (a list per permission), so it changes nothing. The token is the one the plugin resolves, so
493
+ * `--token cloudflare=<token>` or `--environment <layer>` checks another one; the account id is the plugin's own.
494
+ *
495
+ * A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
496
+ * `local`), 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
497
+ * two groups, what it should have and what it should not, where a missing or extra permission fails. The other words
498
+ * limit the zone checks to those zones; otherwise up to five are read. How the token is chosen is in `holocron probe --help`.
499
+ */
500
+ function tokenProbe(ctx) {
501
+ return {
502
+ 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.",
503
+ writes: false,
504
+ acceptsToken: true,
505
+ async run(probe) {
506
+ const token = ctx.token();
507
+ probe.secret(token);
508
+ const client = ctx.client();
509
+ const { layer, zones: wanted } = parseTokenArgs(probe.args ?? []);
510
+ const rules = layer ? tokenExpectations(tokens, { layer })[0]?.rules : void 0;
511
+ if (layer && !rules) probe.say({
512
+ status: "info",
513
+ label: layer,
514
+ detail: "no expectations are declared for it, so the token is only described"
515
+ });
516
+ try {
517
+ const verified = await client.tokens.verify();
518
+ probe.say({
519
+ status: "ok",
520
+ label: "token",
521
+ detail: `${verified.id} (${verified.status})`
522
+ });
523
+ } catch {}
524
+ const tried = [];
525
+ let zones = [];
526
+ const zoneOutcome = await reach(async () => {
527
+ zones = wanted.length > 0 ? (await Promise.all(wanted.map((name) => client.zones.list({ name })))).flat() : await client.zones.list({ per_page: MAX_ZONES });
528
+ return zones.map((z) => ({ name: z.name }));
529
+ }, "zones");
530
+ tried.push({
531
+ label: "Zone: Read",
532
+ permission: "zone",
533
+ outcome: zoneOutcome
534
+ });
535
+ if (zoneOutcome.kind !== "error") {
536
+ for (const zone of zones.slice(0, MAX_ZONES)) {
537
+ tried.push({
538
+ label: `DNS: Edit (${zone.name})`,
539
+ permission: "dns",
540
+ outcome: await reach(() => client.dns.list(zone.id), "records")
541
+ });
542
+ tried.push({
543
+ label: `Workers Routes: Edit (${zone.name})`,
544
+ permission: "routes",
545
+ outcome: await reach(async () => (await client.workers.listRoutes(zone.id)).map((r) => ({ name: r.pattern })), "routes")
546
+ });
547
+ }
548
+ const account = ctx.options.accountId;
549
+ if (account) {
550
+ tried.push({
551
+ label: "Workers Scripts: Edit",
552
+ permission: "scripts",
553
+ outcome: await reach(async () => (await client.workers.listScripts(account)).map((s) => ({ name: s.id })), "scripts")
554
+ });
555
+ tried.push({
556
+ label: "Pages: Edit",
557
+ permission: "pages",
558
+ outcome: await reach(() => client.pages.listProjects(account), "projects")
559
+ });
560
+ tried.push({
561
+ label: "Cloudflare Tunnel: Edit",
562
+ permission: "tunnels",
563
+ outcome: await reach(() => client.tunnels.list(account), "tunnels")
564
+ });
565
+ } else probe.say({
566
+ status: rules ? "fail" : "info",
567
+ label: "account permissions",
568
+ detail: "no account id: set HOLOCRON_CLOUDFLARE_ACCOUNT_ID or the plugin's accountId option to check them"
569
+ });
570
+ }
571
+ if (!rules) {
572
+ for (const t of tried) probe.say(rowFor(t, void 0));
573
+ return;
574
+ }
575
+ for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
576
+ const inGroup = tried.filter((t) => rules[t.permission] === rule);
577
+ if (inGroup.length === 0) continue;
578
+ probe.say({
579
+ status: "heading",
580
+ label: heading
581
+ });
582
+ for (const t of inGroup) probe.say(rowFor(t, rule));
583
+ }
584
+ }
585
+ };
586
+ }
587
+ // src/verify-token.ts
588
+ /** 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
589
  async function verifyToken(token, opts = {}) {
257
590
  const client = createCloudflareClient({
258
591
  token,
@@ -267,21 +600,26 @@ async function verifyToken(token, opts = {}) {
267
600
  };
268
601
  } catch {}
269
602
  try {
603
+ const names = (await client.zones.list()).map((z) => z.name);
604
+ if (names.length === 0) return {
605
+ ok: true,
606
+ subject: "no zones visible"
607
+ };
270
608
  return {
271
609
  ok: true,
272
- subject: `zone: ${(await client.zones.list({ per_page: 1 }))[0]?.name ?? "unknown"}`
610
+ subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
273
611
  };
274
612
  } catch (err) {
275
613
  return {
276
614
  ok: false,
277
- message: err instanceof Error ? err.message : String(err)
615
+ message: errorMessage(err)
278
616
  };
279
617
  }
280
618
  }
281
- //#endregion
282
- //#region src/index.ts
619
+ // src/index.ts
620
+ /** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
283
621
  function createContext(options = {}) {
284
- const accountId = options.accountId ?? process.env.CLOUDFLARE_ACCOUNT_ID;
622
+ const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
285
623
  const opts = {
286
624
  ...options,
287
625
  accountId
@@ -299,30 +637,53 @@ function createContext(options = {}) {
299
637
  })
300
638
  };
301
639
  }
640
+ /** Builds the `dns` capability for a context. */
302
641
  function dns(ctx) {
303
642
  return new CloudflareDns(ctx.client);
304
643
  }
644
+ /** Builds the `deployment` capability for a context; throws when no account id is set. */
305
645
  function deployment(ctx) {
306
646
  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
647
  return new CloudflareDeployment(ctx.client, ctx.options.accountId);
308
648
  }
649
+ /** Builds the `workers` capability for a context; throws when no account id is set. */
309
650
  function workersCapability(ctx) {
310
651
  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
652
  return new CloudflareWorkers(ctx.client, ctx.options.accountId);
312
653
  }
654
+ /** Builds the `tunnels` capability for a context; throws when no account id is set. */
655
+ function tunnelsCapability(ctx) {
656
+ 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");
657
+ return new CloudflareTunnels(ctx.client, ctx.options.accountId);
658
+ }
659
+ /** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
313
660
  function createPlugin(options = {}) {
314
661
  const ctx = createContext(options);
315
662
  return {
316
663
  name: "@theholocron/holocron-plugin-cloudflare",
664
+ probes: {
665
+ token: tokenProbe(ctx),
666
+ connection: connectionProbe({
667
+ provider: "Cloudflare",
668
+ url: options.baseUrl ?? "https://api.cloudflare.com",
669
+ fetch: options.fetch,
670
+ token: () => resolveToken(options),
671
+ verify: (token) => verifyToken(token, {
672
+ baseUrl: options.baseUrl,
673
+ fetch: options.fetch
674
+ })
675
+ })
676
+ },
317
677
  capabilities: {
318
678
  dns: () => dns(ctx),
319
679
  ...ctx.options.accountId ? {
320
680
  deployment: () => deployment(ctx),
321
- workers: () => workersCapability(ctx)
681
+ workers: () => workersCapability(ctx),
682
+ tunnels: () => tunnelsCapability(ctx)
322
683
  } : {}
323
684
  }
324
685
  };
325
686
  }
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 };
687
+ /** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
688
+ 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 (account-level) permissions, then run: holocron new token cloudflare <TOKEN>";
689
+ 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.43",
3
+ "version": "5.0.0-alpha.430",
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.4"
34
+ },
32
35
  "devDependencies": {
33
- "@theholocron/cloudflare-client": "^1.24.0",
34
- "@theholocron/eslint-config": "^8.4.5",
35
- "@theholocron/http-client": "^1.24.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",
37
+ "@vitest/coverage-v8": "^5.1.0",
38
+ "@vitest/eslint-plugin": "^1.6.28",
39
+ "chalk": "^6.0.1",
40
+ "eslint": "^10.14.0",
41
+ "eslint-plugin-n": "^18.5.0",
42
+ "globals": "^17.14.0",
43
+ "tsdown": "^0.23.5",
44
+ "tsx": "4.23.15",
48
45
  "typescript": "^5.9.3",
49
- "vitest": "^4.1.11",
50
- "@theholocron/cli": "5.0.0-alpha.43"
46
+ "vitest": "^5.1.0",
47
+ "@theholocron/cloudflare-client": "^1.58.0-alpha.29",
48
+ "@theholocron/http-client": "^1.58.0-alpha.29",
49
+ "@theholocron/cli": "5.0.0-alpha.430",
50
+ "@theholocron/misc-utils": "^1.17.0-alpha.4",
51
+ "@theholocron/kyber": "5.0.0-alpha.430",
52
+ "@theholocron/tsconfig": "^8.9.0-alpha.17",
53
+ "@theholocron/tsdown-config": "^8.9.0-alpha.17",
54
+ "@theholocron/vitest-config": "^8.9.0-alpha.17",
55
+ "@theholocron/eslint-config": "^8.9.0-alpha.17"
51
56
  },
52
57
  "peerDependencies": {
53
- "@theholocron/cloudflare-client": "^1.24.0",
54
- "@theholocron/cli": "5.0.0-alpha.43"
58
+ "@theholocron/cloudflare-client": "^1.53.1",
59
+ "@theholocron/misc-utils": "^1.16.0",
60
+ "@theholocron/cli": "5.0.0-alpha.430"
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
  }