@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.5 → 5.0.0-alpha.500
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 +42 -5
- package/dist/index.d.mts +107 -58
- package/dist/index.mjs +458 -94
- package/package.json +32 -25
package/README.md
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
# `@theholocron/holocron-plugin-cloudflare`
|
|
4
4
|
|
|
5
|
-
Cloudflare plugin for [Holocron](../cli). Implements the `dns
|
|
6
|
-
capabilities against the
|
|
5
|
+
Cloudflare plugin for [Holocron](../cli). Implements the `dns`, `deployment`,
|
|
6
|
+
`workers` and `tunnels` capabilities against the
|
|
7
|
+
[Cloudflare v4 API](https://developers.cloudflare.com/api/).
|
|
7
8
|
|
|
8
9
|
## Install
|
|
9
10
|
|
|
@@ -21,7 +22,7 @@ Token resolution order:
|
|
|
21
22
|
2. `HOLOCRON_CLOUDFLARE_TOKEN` env var
|
|
22
23
|
3. `CLOUDFLARE_API_TOKEN` env var (the standard Cloudflare variable name)
|
|
23
24
|
4. Keyring `cloudflare.<org>` — tried first when an org is active via `--org`, `HOLOCRON_ORG`, or `org` in `holocron.config.ts`
|
|
24
|
-
5. Keyring `cloudflare` — unnamespaced fallback; set via `holocron
|
|
25
|
+
5. Keyring `cloudflare` — unnamespaced fallback; set via `holocron new token cloudflare <token>`
|
|
25
26
|
|
|
26
27
|
Generate a scoped API token at **dash.cloudflare.com/profile/api-tokens**.
|
|
27
28
|
|
|
@@ -40,12 +41,15 @@ Generate a scoped API token at **dash.cloudflare.com/profile/api-tokens**.
|
|
|
40
41
|
// Cloudflare Pages deployments (requires accountId)
|
|
41
42
|
// accountId falls back to CLOUDFLARE_ACCOUNT_ID env var when omitted
|
|
42
43
|
"deployment": "cloudflare",
|
|
44
|
+
|
|
45
|
+
// Workers deployment (also requires accountId)
|
|
46
|
+
"workers": "cloudflare",
|
|
43
47
|
},
|
|
44
48
|
}
|
|
45
49
|
|
|
46
50
|
```
|
|
47
51
|
|
|
48
|
-
|
|
52
|
+
Any combination of capabilities can be enabled together:
|
|
49
53
|
|
|
50
54
|
<!-- prettier-ignore -->
|
|
51
55
|
```jsonc
|
|
@@ -53,12 +57,16 @@ Both capabilities can be enabled together:
|
|
|
53
57
|
"providers": {
|
|
54
58
|
"dns": "cloudflare",
|
|
55
59
|
"deployment": "cloudflare",
|
|
60
|
+
"workers": "cloudflare",
|
|
56
61
|
},
|
|
57
62
|
}
|
|
58
63
|
|
|
59
64
|
```
|
|
60
65
|
|
|
61
|
-
The `deployment`
|
|
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).
|
|
62
70
|
|
|
63
71
|
## `dns` capability
|
|
64
72
|
|
|
@@ -83,6 +91,35 @@ Manages [Cloudflare Pages](https://developers.cloudflare.com/pages/) projects. U
|
|
|
83
91
|
| `triggerDeployment` | Triggers a new Pages deployment from the latest production branch commit. |
|
|
84
92
|
| `updateProjectSettings` | Updates project-level settings (currently a no-op; CF Pages REST API has no direct settings endpoint for these fields). |
|
|
85
93
|
|
|
94
|
+
## `workers` capability
|
|
95
|
+
|
|
96
|
+
Deploys and manages [Workers](https://developers.cloudflare.com/workers/) scripts.
|
|
97
|
+
|
|
98
|
+
| Method | What it does |
|
|
99
|
+
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
100
|
+
| `upsertProxy` | Deploys a generated reverse-proxy Worker forwarding `hostname/*` to `config.target`, injecting `config.headers`. Used by `setup` to wire wiki custom-domain proxies when the wiki provider requires one in addition to the CNAME. |
|
|
101
|
+
| `deployScript` | Deploys (or updates) an arbitrary Worker script — the caller's own code, not a generated proxy — with optional secret bindings and route patterns. For a consumer that isn't a reverse-proxy, e.g. a webhook receiver. |
|
|
102
|
+
|
|
103
|
+
Both methods are idempotent: re-running with the same inputs makes no
|
|
104
|
+
route-write call when nothing changed. Zone ids are cached per plugin
|
|
105
|
+
instance for the lifetime of the process — the `workers` capability's own
|
|
106
|
+
cache, separate from `dns`'s.
|
|
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
|
+
|
|
86
123
|
### Preview deployment setup
|
|
87
124
|
|
|
88
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, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, ResolveTokenInput, WikiProxyConfig, Workers } from "@theholocron/cli";
|
|
2
|
-
import { CloudflareClient,
|
|
3
|
-
|
|
4
|
-
declare const resolveToken: (
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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, WorkerDeploymentState, WorkerScriptState, Workers } from "@theholocron/cli";
|
|
2
|
+
import { CloudflareClient, CloudflareClient as CloudflareClient$1, CloudflareClientOptions, createCloudflareClient } from "@theholocron/cloudflare-client";
|
|
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,48 @@ 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
|
-
ensureCustomDomain(projectId: string, hostname: string): Promise<
|
|
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
|
-
|
|
35
|
-
|
|
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
|
+
/** The capability this class provides, always `"dns"`. */
|
|
38
50
|
readonly key: "dns";
|
|
51
|
+
/** The provider name, `"cloudflare"`. */
|
|
39
52
|
readonly providerName = "cloudflare";
|
|
40
53
|
private readonly zoneCache;
|
|
41
54
|
constructor(client: () => CloudflareClient);
|
|
55
|
+
/** Lists the DNS records in the zone that holds the domain. */
|
|
42
56
|
listRecords(domain: string): Promise<DnsRecord[]>;
|
|
57
|
+
/** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
|
|
43
58
|
upsertRecord(domain: string, record: DnsRecord): Promise<DnsRecord>;
|
|
59
|
+
/** Deletes the DNS record with this id from the zone that holds the domain. */
|
|
44
60
|
deleteRecord(domain: string, id: string): Promise<void>;
|
|
61
|
+
/** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
|
|
62
|
+
whoami(): Promise<{
|
|
63
|
+
ok: boolean;
|
|
64
|
+
zones: number;
|
|
65
|
+
}>;
|
|
45
66
|
/**
|
|
46
67
|
* Walk from full domain up to apex to find the Cloudflare zone.
|
|
47
68
|
* E.g. "api.staging.example.com" tries:
|
|
@@ -51,84 +72,112 @@ declare class CloudflareDns implements Dns {
|
|
|
51
72
|
*/
|
|
52
73
|
private resolveZone;
|
|
53
74
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
75
|
+
/** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
|
|
76
|
+
export declare class CloudflareTunnels implements Tunnels {
|
|
77
|
+
private readonly client;
|
|
78
|
+
private readonly accountId;
|
|
79
|
+
/** The capability this class provides, always `"tunnels"`. */
|
|
80
|
+
readonly key: "tunnels";
|
|
81
|
+
/** The provider name, `"cloudflare"`. */
|
|
82
|
+
readonly providerName = "cloudflare";
|
|
83
|
+
constructor(client: () => Pick<CloudflareClient$1, "tunnels">, accountId: string);
|
|
84
|
+
/** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
|
|
85
|
+
ensureTunnel(route: TunnelRoute): Promise<EnsuredTunnel>;
|
|
86
|
+
/** The token `cloudflared` runs the tunnel with. */
|
|
87
|
+
tunnelToken(tunnelId: string): Promise<string>;
|
|
88
|
+
/** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
|
|
89
|
+
whoami(): Promise<{
|
|
90
|
+
ok: boolean;
|
|
91
|
+
tunnels: number;
|
|
92
|
+
}>;
|
|
63
93
|
}
|
|
64
|
-
|
|
65
|
-
|
|
94
|
+
/** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
|
|
95
|
+
export declare class CloudflareWorkers implements Workers {
|
|
96
|
+
private readonly client;
|
|
66
97
|
private readonly accountId;
|
|
98
|
+
/** The capability this class provides, always `"workers"`. */
|
|
67
99
|
readonly key: "workers";
|
|
100
|
+
/** The provider name, `"cloudflare"`. */
|
|
68
101
|
readonly providerName = "cloudflare";
|
|
69
102
|
private readonly zoneCache;
|
|
70
|
-
|
|
71
|
-
private readonly fetchImpl;
|
|
72
|
-
/** Memoized token thunk — resolved on the first authenticated request. */
|
|
73
|
-
private readonly token;
|
|
74
|
-
constructor(zones: () => ZonesClient, accountId: string, opts: {
|
|
75
|
-
token: () => string;
|
|
76
|
-
} & Pick<CloudflareClientOptions$1, "baseUrl" | "fetch">);
|
|
103
|
+
constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
|
|
77
104
|
upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
105
|
+
/** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
|
|
106
|
+
whoami(): Promise<{
|
|
107
|
+
ok: boolean;
|
|
108
|
+
scripts: number;
|
|
109
|
+
}>;
|
|
110
|
+
deployScript(name: string, config: DeployScriptConfig): Promise<DeployScriptResult>;
|
|
111
|
+
setSecret(script: string, name: string, value: string): Promise<void>;
|
|
112
|
+
secretNames(script: string): Promise<string[]>;
|
|
113
|
+
/**
|
|
114
|
+
* Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
|
|
115
|
+
* only, and asks Cloudflare for names, so no value is ever fetched.
|
|
116
|
+
*/
|
|
117
|
+
inspectScript(name: string, host: string): Promise<WorkerScriptState>;
|
|
118
|
+
/** The newest deployment of the script, and whether it serves all traffic. Reads only. */
|
|
119
|
+
latestDeployment(script: string): Promise<WorkerDeploymentState | null>;
|
|
120
|
+
proxyScriptName(hostname: string): string;
|
|
121
|
+
/** Idempotent create-or-update for one route pattern — shared by both public methods. */
|
|
122
|
+
private upsertRoute;
|
|
83
123
|
private resolveZone;
|
|
84
124
|
}
|
|
85
|
-
//#endregion
|
|
86
|
-
//#region src/verify-token.d.ts
|
|
87
|
-
interface VerifyTokenSuccess {
|
|
88
|
-
ok: true;
|
|
89
|
-
subject: string;
|
|
90
|
-
}
|
|
91
|
-
interface VerifyTokenFailure {
|
|
92
|
-
ok: false;
|
|
93
|
-
message: string;
|
|
94
|
-
}
|
|
95
|
-
type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
|
|
96
125
|
interface VerifyTokenOptions {
|
|
97
126
|
baseUrl?: string;
|
|
98
127
|
fetch?: typeof fetch;
|
|
99
128
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
interface CloudflarePluginOptions extends ResolveTokenInput {
|
|
129
|
+
/** 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. */
|
|
130
|
+
export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
|
|
131
|
+
/** Options for the Cloudflare plugin: how the API token is resolved, the account, and test overrides. */
|
|
132
|
+
export interface CloudflarePluginOptions extends ResolveTokenInput {
|
|
104
133
|
/**
|
|
105
134
|
* Cloudflare account ID. Required for Pages (deployment) operations;
|
|
106
135
|
* optional for DNS-only use.
|
|
107
136
|
*/
|
|
108
137
|
accountId?: string;
|
|
138
|
+
/**
|
|
139
|
+
* The zone the organization's own DNS lives in. The `token` probe reads this one zone when no zone is named on the
|
|
140
|
+
* command line; without it the probe reads the first few zones of the account.
|
|
141
|
+
*/
|
|
142
|
+
zone?: string;
|
|
109
143
|
/** Override base URL for tests. */
|
|
110
144
|
baseUrl?: string;
|
|
145
|
+
/** The `fetch` to use instead of the global one, for tests. */
|
|
111
146
|
fetch?: typeof fetch;
|
|
112
147
|
}
|
|
113
|
-
|
|
148
|
+
/** The shared state the Cloudflare plugin's capabilities and probes are built from. */
|
|
149
|
+
export interface PluginContext {
|
|
150
|
+
/** The options the plugin was created with, with `accountId` falling back to `CLOUDFLARE_ACCOUNT_ID` in the environment, then in the `credentials` providers' variables. */
|
|
114
151
|
options: CloudflarePluginOptions;
|
|
115
152
|
/** Memoized client — the token is resolved on first use, not at plugin load. */
|
|
116
153
|
client: () => CloudflareClient;
|
|
117
154
|
/** Memoized token resolver — shared by the client and the Workers capability. */
|
|
118
155
|
token: () => string;
|
|
119
156
|
}
|
|
120
|
-
|
|
121
|
-
declare function
|
|
122
|
-
|
|
123
|
-
declare function
|
|
124
|
-
|
|
157
|
+
/** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
|
|
158
|
+
export declare function createContext(options?: CloudflarePluginOptions): PluginContext;
|
|
159
|
+
/** Builds the `dns` capability for a context. */
|
|
160
|
+
export declare function dns(ctx: PluginContext): Dns;
|
|
161
|
+
/** Builds the `deployment` capability for a context; throws when no account id is set. */
|
|
162
|
+
export declare function deployment(ctx: PluginContext): Deployment;
|
|
163
|
+
/** Builds the `workers` capability for a context; throws when no account id is set. */
|
|
164
|
+
export declare function workersCapability(ctx: PluginContext): Workers;
|
|
165
|
+
/** Builds the `tunnels` capability for a context; throws when no account id is set. */
|
|
166
|
+
export declare function tunnelsCapability(ctx: PluginContext): Tunnels;
|
|
167
|
+
/** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
|
|
168
|
+
export declare function createPlugin(options?: CloudflarePluginOptions): {
|
|
125
169
|
name: string;
|
|
170
|
+
probes: {
|
|
171
|
+
token: import("@theholocron/cli").Probe;
|
|
172
|
+
connection: import("@theholocron/cli").Probe;
|
|
173
|
+
};
|
|
126
174
|
capabilities: {
|
|
127
175
|
deployment?: (() => Deployment) | undefined;
|
|
128
176
|
workers?: (() => Workers) | undefined;
|
|
177
|
+
tunnels?: (() => Tunnels) | undefined;
|
|
129
178
|
dns: () => Dns;
|
|
130
179
|
};
|
|
131
180
|
};
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
export {
|
|
181
|
+
/** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
|
|
182
|
+
export declare const AUTH_HINT: string;
|
|
183
|
+
export { AuthError, type CloudflareClient, type CloudflareClientOptions, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient };
|
package/dist/index.mjs
CHANGED
|
@@ -1,23 +1,68 @@
|
|
|
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
|
-
|
|
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 = {
|
|
22
|
+
rotation: {
|
|
23
|
+
maxAgeDays: 90,
|
|
24
|
+
warnDays: 14
|
|
25
|
+
},
|
|
26
|
+
permissions: {
|
|
27
|
+
local: EVERYTHING,
|
|
28
|
+
dev: EVERYTHING,
|
|
29
|
+
ci: {
|
|
30
|
+
zone: "absent",
|
|
31
|
+
dns: "absent",
|
|
32
|
+
routes: "absent",
|
|
33
|
+
scripts: "absent",
|
|
34
|
+
pages: "required",
|
|
35
|
+
tunnels: "absent"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
// src/auth.ts
|
|
40
|
+
/** 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
41
|
const resolveToken = createResolveToken({
|
|
5
42
|
envName: "HOLOCRON_CLOUDFLARE_TOKEN",
|
|
6
43
|
vendorEnvName: "CLOUDFLARE_API_TOKEN",
|
|
7
44
|
keyringService: "cloudflare",
|
|
8
|
-
errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron
|
|
45
|
+
errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron new token cloudflare <TOKEN>"
|
|
9
46
|
});
|
|
10
|
-
|
|
11
|
-
|
|
47
|
+
/** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
|
|
48
|
+
const tokens = [{
|
|
49
|
+
...resolveToken.token,
|
|
50
|
+
expect: EXPECTED
|
|
51
|
+
}];
|
|
52
|
+
// src/capabilities/deployment.ts
|
|
53
|
+
/** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
|
|
12
54
|
var CloudflareDeployment = class {
|
|
13
55
|
client;
|
|
14
56
|
accountId;
|
|
57
|
+
/** The capability this class provides, always `"deployment"`. */
|
|
15
58
|
key = "deployment";
|
|
59
|
+
/** The provider name, `"cloudflare"`. */
|
|
16
60
|
providerName = "cloudflare";
|
|
17
61
|
constructor(client, accountId) {
|
|
18
62
|
this.client = client;
|
|
19
63
|
this.accountId = accountId;
|
|
20
64
|
}
|
|
65
|
+
/** Lists the account's Pages projects. */
|
|
21
66
|
async listProjects() {
|
|
22
67
|
return (await this.client().pages.listProjects(this.accountId)).map(mapProject);
|
|
23
68
|
}
|
|
@@ -29,14 +74,17 @@ var CloudflareDeployment = class {
|
|
|
29
74
|
production_branch: "main"
|
|
30
75
|
}));
|
|
31
76
|
}
|
|
77
|
+
/** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
|
|
32
78
|
async updateProjectSettings(projectId, settings) {
|
|
33
79
|
return mapProject(await this.client().pages.getProject(this.accountId, projectId));
|
|
34
80
|
}
|
|
81
|
+
/** Lists the names of the environment variables set for the production or preview target. */
|
|
35
82
|
async listEnvVars(projectId, target) {
|
|
36
83
|
const project = await this.client().pages.getProject(this.accountId, projectId);
|
|
37
84
|
const envConfig = target === "production" ? project.deployment_configs.production : project.deployment_configs.preview;
|
|
38
85
|
return Object.keys(envConfig.env_vars);
|
|
39
86
|
}
|
|
87
|
+
/** Sets a plain-text environment variable on the production or preview target, keeping the others. */
|
|
40
88
|
async setEnvVar(projectId, target, name, value) {
|
|
41
89
|
const cfg = (await this.client().pages.getProject(this.accountId, projectId)).deployment_configs;
|
|
42
90
|
const scope = target === "production" ? "production" : "preview";
|
|
@@ -55,6 +103,7 @@ var CloudflareDeployment = class {
|
|
|
55
103
|
async triggerDeployment(input) {
|
|
56
104
|
return mapDeployment(await this.client().pages.createDeployment(this.accountId, input.projectId, input.branch), input.projectId, input.branch, input.target);
|
|
57
105
|
}
|
|
106
|
+
/** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
|
|
58
107
|
async getDeployment(deploymentId) {
|
|
59
108
|
const sep = deploymentId.indexOf(":");
|
|
60
109
|
if (sep === -1) throw new ProviderApiError(`Invalid Cloudflare Pages deployment id "${deploymentId}" — expected "projectName:deploymentId"`, 400, void 0);
|
|
@@ -74,8 +123,22 @@ var CloudflareDeployment = class {
|
|
|
74
123
|
return deploymentIds.length;
|
|
75
124
|
}
|
|
76
125
|
async ensureCustomDomain(projectId, hostname) {
|
|
77
|
-
if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return;
|
|
126
|
+
if ((await this.client().pages.listDomains(this.accountId, projectId)).some((d) => d.name === hostname)) return null;
|
|
78
127
|
await this.client().pages.addDomain(this.accountId, projectId, hostname);
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
/** The hostnames attached to the Pages project. Reads only. */
|
|
131
|
+
async listDomains(projectId) {
|
|
132
|
+
return (await this.client().pages.listDomains(this.accountId, projectId)).map((d) => d.name);
|
|
133
|
+
}
|
|
134
|
+
/** The newest production deployment of the project, or null. Reads only. */
|
|
135
|
+
async latestDeployment(projectId) {
|
|
136
|
+
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));
|
|
137
|
+
if (!newest) return null;
|
|
138
|
+
return {
|
|
139
|
+
...mapDeployment(newest, projectId, newest.deployment_trigger.metadata.branch, "production"),
|
|
140
|
+
createdAt: newest.created_on
|
|
141
|
+
};
|
|
79
142
|
}
|
|
80
143
|
async getProjectByName(name) {
|
|
81
144
|
try {
|
|
@@ -113,20 +176,24 @@ function normalizeStatus(status) {
|
|
|
113
176
|
default: return "error";
|
|
114
177
|
}
|
|
115
178
|
}
|
|
116
|
-
|
|
117
|
-
|
|
179
|
+
// src/capabilities/dns.ts
|
|
180
|
+
/** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
|
|
118
181
|
var CloudflareDns = class {
|
|
119
182
|
client;
|
|
183
|
+
/** The capability this class provides, always `"dns"`. */
|
|
120
184
|
key = "dns";
|
|
185
|
+
/** The provider name, `"cloudflare"`. */
|
|
121
186
|
providerName = "cloudflare";
|
|
122
187
|
zoneCache = /* @__PURE__ */ new Map();
|
|
123
188
|
constructor(client) {
|
|
124
189
|
this.client = client;
|
|
125
190
|
}
|
|
191
|
+
/** Lists the DNS records in the zone that holds the domain. */
|
|
126
192
|
async listRecords(domain) {
|
|
127
193
|
const zoneId = await this.resolveZone(domain);
|
|
128
194
|
return (await this.client().dns.list(zoneId)).map(mapRecord);
|
|
129
195
|
}
|
|
196
|
+
/** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
|
|
130
197
|
async upsertRecord(domain, record) {
|
|
131
198
|
const client = this.client();
|
|
132
199
|
const zoneId = await this.resolveZone(domain);
|
|
@@ -149,10 +216,18 @@ var CloudflareDns = class {
|
|
|
149
216
|
...record.proxied !== void 0 ? { proxied: record.proxied } : {}
|
|
150
217
|
}));
|
|
151
218
|
}
|
|
219
|
+
/** Deletes the DNS record with this id from the zone that holds the domain. */
|
|
152
220
|
async deleteRecord(domain, id) {
|
|
153
221
|
const zoneId = await this.resolveZone(domain);
|
|
154
222
|
await this.client().dns.delete(zoneId, id);
|
|
155
223
|
}
|
|
224
|
+
/** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
|
|
225
|
+
async whoami() {
|
|
226
|
+
return {
|
|
227
|
+
ok: true,
|
|
228
|
+
zones: (await this.client().zones.list()).length
|
|
229
|
+
};
|
|
230
|
+
}
|
|
156
231
|
/**
|
|
157
232
|
* Walk from full domain up to apex to find the Cloudflare zone.
|
|
158
233
|
* E.g. "api.staging.example.com" tries:
|
|
@@ -181,93 +256,147 @@ function mapRecord(raw) {
|
|
|
181
256
|
type: raw.type,
|
|
182
257
|
name: raw.name,
|
|
183
258
|
content: raw.content,
|
|
184
|
-
ttl: raw.ttl
|
|
259
|
+
ttl: raw.ttl,
|
|
260
|
+
...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
|
|
185
261
|
};
|
|
186
262
|
}
|
|
187
|
-
|
|
188
|
-
|
|
263
|
+
// src/capabilities/tunnels.ts
|
|
264
|
+
/** The rule a tunnel needs last: anything no other rule matches is answered with a 404 by the connector itself. */
|
|
265
|
+
const CATCH_ALL = { service: "http_status:404" };
|
|
266
|
+
/**
|
|
267
|
+
* The ingress rules with `hostname` served at `service`: the rule for the hostname is replaced where it is or added
|
|
268
|
+
* after the others, every other hostname's rule is kept, and the rule without a hostname closes the list.
|
|
269
|
+
*/
|
|
270
|
+
function withRoute(current, hostname, service) {
|
|
271
|
+
const rule = {
|
|
272
|
+
hostname,
|
|
273
|
+
service
|
|
274
|
+
};
|
|
275
|
+
const named = current.filter((r) => r.hostname !== void 0);
|
|
276
|
+
const at = named.findIndex((r) => r.hostname === hostname);
|
|
277
|
+
return [...at === -1 ? [...named, rule] : named.map((r, i) => i === at ? rule : r), current.find((r) => r.hostname === void 0) ?? CATCH_ALL];
|
|
278
|
+
}
|
|
279
|
+
/** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
|
|
280
|
+
var CloudflareTunnels = class {
|
|
281
|
+
client;
|
|
282
|
+
accountId;
|
|
283
|
+
/** The capability this class provides, always `"tunnels"`. */
|
|
284
|
+
key = "tunnels";
|
|
285
|
+
/** The provider name, `"cloudflare"`. */
|
|
286
|
+
providerName = "cloudflare";
|
|
287
|
+
constructor(client, accountId) {
|
|
288
|
+
this.client = client;
|
|
289
|
+
this.accountId = accountId;
|
|
290
|
+
}
|
|
291
|
+
/** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
|
|
292
|
+
async ensureTunnel(route) {
|
|
293
|
+
const { tunnels } = this.client();
|
|
294
|
+
const found = (await tunnels.list(this.accountId)).find((t) => t.name === route.name);
|
|
295
|
+
const tunnel = found ?? await tunnels.create(this.accountId, { name: route.name });
|
|
296
|
+
const current = (await tunnels.getConfig(this.accountId, tunnel.id)).config?.ingress ?? [];
|
|
297
|
+
const wanted = withRoute(current, route.hostname, route.service);
|
|
298
|
+
const configured = JSON.stringify(wanted) !== JSON.stringify(current);
|
|
299
|
+
if (configured) await tunnels.putConfig(this.accountId, tunnel.id, { ingress: wanted });
|
|
300
|
+
return {
|
|
301
|
+
id: tunnel.id,
|
|
302
|
+
name: tunnel.name,
|
|
303
|
+
created: found === void 0,
|
|
304
|
+
configured,
|
|
305
|
+
target: `${tunnel.id}.cfargotunnel.com`
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/** The token `cloudflared` runs the tunnel with. */
|
|
309
|
+
tunnelToken(tunnelId) {
|
|
310
|
+
return this.client().tunnels.token(this.accountId, tunnelId);
|
|
311
|
+
}
|
|
312
|
+
/** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
|
|
313
|
+
async whoami() {
|
|
314
|
+
return {
|
|
315
|
+
ok: true,
|
|
316
|
+
tunnels: (await this.client().tunnels.list(this.accountId)).length
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
// src/capabilities/workers.ts
|
|
321
|
+
/** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
|
|
189
322
|
var CloudflareWorkers = class {
|
|
190
|
-
|
|
323
|
+
client;
|
|
191
324
|
accountId;
|
|
325
|
+
/** The capability this class provides, always `"workers"`. */
|
|
192
326
|
key = "workers";
|
|
327
|
+
/** The provider name, `"cloudflare"`. */
|
|
193
328
|
providerName = "cloudflare";
|
|
194
329
|
zoneCache = /* @__PURE__ */ new Map();
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
/** Memoized token thunk — resolved on the first authenticated request. */
|
|
198
|
-
token;
|
|
199
|
-
constructor(zones, accountId, opts) {
|
|
200
|
-
this.zones = zones;
|
|
330
|
+
constructor(client, accountId) {
|
|
331
|
+
this.client = client;
|
|
201
332
|
this.accountId = accountId;
|
|
202
|
-
this.token = opts.token;
|
|
203
|
-
this.baseUrl = opts.baseUrl ?? "https://api.cloudflare.com/client/v4";
|
|
204
|
-
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
205
333
|
}
|
|
206
334
|
async upsertProxy(hostname, config) {
|
|
207
335
|
const scriptName = hostnameToScriptName(hostname);
|
|
208
336
|
const script = generateProxyScript(config);
|
|
209
|
-
await this.putScript(scriptName, script);
|
|
210
|
-
|
|
211
|
-
const pattern = `${hostname}/*`;
|
|
212
|
-
const existing = (await this.listRoutes(zoneId)).find((r) => r.pattern === pattern);
|
|
213
|
-
if (existing) {
|
|
214
|
-
if (existing.script !== scriptName) await this.updateRoute(zoneId, existing.id, pattern, scriptName);
|
|
215
|
-
} else await this.createRoute(zoneId, pattern, scriptName);
|
|
216
|
-
}
|
|
217
|
-
async putScript(scriptName, script) {
|
|
218
|
-
const form = new FormData();
|
|
219
|
-
form.append("metadata", new Blob([JSON.stringify({
|
|
220
|
-
main_module: "index.js",
|
|
221
|
-
compatibility_date: "2025-08-31"
|
|
222
|
-
})], { type: "application/json" }));
|
|
223
|
-
form.append("index.js", new Blob([script], { type: "application/javascript+module" }), "index.js");
|
|
224
|
-
const path = `/accounts/${this.accountId}/workers/scripts/${encodeURIComponent(scriptName)}`;
|
|
225
|
-
const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
226
|
-
method: "PUT",
|
|
227
|
-
headers: { authorization: `Bearer ${this.token()}` },
|
|
228
|
-
body: form
|
|
229
|
-
});
|
|
230
|
-
if (!res.ok) {
|
|
231
|
-
const body = await res.text().catch(() => "");
|
|
232
|
-
throw new ProviderApiError(`Cloudflare PUT ${path} → ${res.status}`, res.status, body);
|
|
233
|
-
}
|
|
337
|
+
await this.client().workers.putScript(this.accountId, scriptName, script);
|
|
338
|
+
await this.upsertRoute(`${hostname}/*`, scriptName);
|
|
234
339
|
}
|
|
235
|
-
|
|
236
|
-
|
|
340
|
+
/** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
|
|
341
|
+
async whoami() {
|
|
342
|
+
return {
|
|
343
|
+
ok: true,
|
|
344
|
+
scripts: (await this.client().workers.listScripts(this.accountId)).length
|
|
345
|
+
};
|
|
237
346
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
}
|
|
347
|
+
async deployScript(name, config) {
|
|
348
|
+
await this.client().workers.putScript(this.accountId, name, config.code);
|
|
349
|
+
for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
|
|
350
|
+
for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
|
|
351
|
+
return { scriptName: name };
|
|
243
352
|
}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
353
|
+
async setSecret(script, name, value) {
|
|
354
|
+
await this.client().workers.putSecret(this.accountId, script, name, value);
|
|
355
|
+
}
|
|
356
|
+
async secretNames(script) {
|
|
357
|
+
return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
|
|
249
358
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
359
|
+
/**
|
|
360
|
+
* Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
|
|
361
|
+
* only, and asks Cloudflare for names, so no value is ever fetched.
|
|
362
|
+
*/
|
|
363
|
+
async inspectScript(name, host) {
|
|
364
|
+
const client = this.client();
|
|
365
|
+
if (!(await client.workers.listScripts(this.accountId)).some((s) => s.id === name)) return {
|
|
366
|
+
exists: false,
|
|
367
|
+
routes: [],
|
|
368
|
+
bindingNames: []
|
|
254
369
|
};
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
370
|
+
const zoneId = await this.resolveZone(host);
|
|
371
|
+
const routes = await client.workers.listRoutes(zoneId);
|
|
372
|
+
const secrets = await client.workers.listSecrets(this.accountId, name);
|
|
373
|
+
return {
|
|
374
|
+
exists: true,
|
|
375
|
+
routes: routes.filter((r) => r.script === name).map((r) => r.pattern),
|
|
376
|
+
bindingNames: secrets.map((secret) => secret.name)
|
|
258
377
|
};
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
378
|
+
}
|
|
379
|
+
/** The newest deployment of the script, and whether it serves all traffic. Reads only. */
|
|
380
|
+
async latestDeployment(script) {
|
|
381
|
+
const [newest] = [...await this.client().workers.listDeployments(this.accountId, script)].sort((a, b) => b.created_on.localeCompare(a.created_on));
|
|
382
|
+
if (!newest) return null;
|
|
383
|
+
return {
|
|
384
|
+
id: newest.id,
|
|
385
|
+
createdAt: newest.created_on,
|
|
386
|
+
active: newest.versions.length > 0 && newest.versions.some((v) => v.percentage === 100)
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
proxyScriptName(hostname) {
|
|
390
|
+
return hostnameToScriptName(hostname);
|
|
391
|
+
}
|
|
392
|
+
/** Idempotent create-or-update for one route pattern — shared by both public methods. */
|
|
393
|
+
async upsertRoute(pattern, scriptName) {
|
|
394
|
+
const hostname = pattern.split("/")[0];
|
|
395
|
+
const zoneId = await this.resolveZone(hostname);
|
|
396
|
+
const existing = (await this.client().workers.listRoutes(zoneId)).find((r) => r.pattern === pattern);
|
|
397
|
+
if (existing) {
|
|
398
|
+
if (existing.script !== scriptName) await this.client().workers.updateRoute(zoneId, existing.id, pattern, scriptName);
|
|
399
|
+
} else await this.client().workers.createRoute(zoneId, pattern, scriptName);
|
|
271
400
|
}
|
|
272
401
|
async resolveZone(domain) {
|
|
273
402
|
const cached = this.zoneCache.get(domain);
|
|
@@ -275,7 +404,7 @@ var CloudflareWorkers = class {
|
|
|
275
404
|
const parts = domain.split(".");
|
|
276
405
|
for (let i = 0; i < parts.length - 1; i++) {
|
|
277
406
|
const candidate = parts.slice(i).join(".");
|
|
278
|
-
const zones = await this.
|
|
407
|
+
const zones = await this.client().zones.list({ name: candidate });
|
|
279
408
|
if (zones.length > 0) {
|
|
280
409
|
this.zoneCache.set(domain, zones[0].id);
|
|
281
410
|
return zones[0].id;
|
|
@@ -302,8 +431,219 @@ function generateProxyScript(config) {
|
|
|
302
431
|
`};`
|
|
303
432
|
].join("\n");
|
|
304
433
|
}
|
|
305
|
-
|
|
306
|
-
|
|
434
|
+
// src/probes/token/parse-token-args.ts
|
|
435
|
+
/** Reads the words after the probe name: `--layer <word>`, `--token-name <VAR>` and any number of zone names. */
|
|
436
|
+
function parseTokenArgs(args) {
|
|
437
|
+
const zones = [];
|
|
438
|
+
let layer;
|
|
439
|
+
let tokenName;
|
|
440
|
+
for (let i = 0; i < args.length; i++) {
|
|
441
|
+
const arg = args[i];
|
|
442
|
+
if (arg === "--layer") layer = args[++i];
|
|
443
|
+
else if (arg.startsWith("--layer=")) layer = arg.slice(8);
|
|
444
|
+
else if (arg === "--token-name") tokenName = args[++i];
|
|
445
|
+
else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
|
|
446
|
+
else if (!arg.startsWith("--")) zones.push(arg);
|
|
447
|
+
}
|
|
448
|
+
return {
|
|
449
|
+
...layer ? { layer } : {},
|
|
450
|
+
...tokenName ? { tokenName } : {},
|
|
451
|
+
zones
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
// src/probes/token/token.ts
|
|
455
|
+
/** The most zones whose DNS and Workers routes are read, so a token that sees many does not make many requests. */
|
|
456
|
+
const MAX_ZONES = 5;
|
|
457
|
+
/** How many names to show before "(+N more)". */
|
|
458
|
+
const SHOWN = 5;
|
|
459
|
+
/** `a, b, c (+2 more)`. */
|
|
460
|
+
function summarise(names) {
|
|
461
|
+
return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Reads one list and says what came back. Cloudflare answers a token without the permission in one of two ways (a 401 or
|
|
465
|
+
* 403, or an empty list), so an empty list is `none`: the token cannot see any, or there are none. A request that fails
|
|
466
|
+
* for another reason (the network, a 5xx) is an `error`.
|
|
467
|
+
*/
|
|
468
|
+
async function reach(read, noun) {
|
|
469
|
+
try {
|
|
470
|
+
const items = await read();
|
|
471
|
+
if (items.length === 0) return {
|
|
472
|
+
kind: "none",
|
|
473
|
+
detail: `no ${noun} visible (none exist, or the token cannot see them)`
|
|
474
|
+
};
|
|
475
|
+
const names = items.map((i) => i.name).filter((n) => typeof n === "string");
|
|
476
|
+
return {
|
|
477
|
+
kind: "has",
|
|
478
|
+
detail: names.length > 0 ? `${items.length} ${noun}: ${summarise(names)}` : `${items.length} ${noun}`
|
|
479
|
+
};
|
|
480
|
+
} catch (err) {
|
|
481
|
+
if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
|
|
482
|
+
kind: "none",
|
|
483
|
+
detail: `no access (${err.status})`
|
|
484
|
+
};
|
|
485
|
+
return {
|
|
486
|
+
kind: "error",
|
|
487
|
+
detail: errorMessage(err)
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
|
|
493
|
+
* judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
|
|
494
|
+
* permission that is rightly absent is a bare `ok`.
|
|
495
|
+
*/
|
|
496
|
+
function rowFor({ label, outcome }, rule) {
|
|
497
|
+
if (outcome.kind === "error") return {
|
|
498
|
+
status: "fail",
|
|
499
|
+
label,
|
|
500
|
+
detail: outcome.detail
|
|
501
|
+
};
|
|
502
|
+
const has = outcome.kind === "has";
|
|
503
|
+
if (rule === "required") return has ? {
|
|
504
|
+
status: "ok",
|
|
505
|
+
label,
|
|
506
|
+
detail: outcome.detail
|
|
507
|
+
} : {
|
|
508
|
+
status: "fail",
|
|
509
|
+
label,
|
|
510
|
+
detail: outcome.detail
|
|
511
|
+
};
|
|
512
|
+
if (rule === "absent") return has ? {
|
|
513
|
+
status: "fail",
|
|
514
|
+
label,
|
|
515
|
+
detail: outcome.detail
|
|
516
|
+
} : {
|
|
517
|
+
status: "ok",
|
|
518
|
+
label
|
|
519
|
+
};
|
|
520
|
+
return {
|
|
521
|
+
status: has ? "ok" : "info",
|
|
522
|
+
label,
|
|
523
|
+
detail: outcome.detail
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* The `token` probe: tries each permission Holocron uses with the Cloudflare API token and reports which ones the token
|
|
528
|
+
* has. It only reads (a list per permission), so it changes nothing. The token is the one the plugin resolves, so
|
|
529
|
+
* `--token cloudflare=<token>` or `--environment <layer>` checks another one; the account id is the plugin's own.
|
|
530
|
+
*
|
|
531
|
+
* A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
|
|
532
|
+
* `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
|
|
533
|
+
* two groups, what it should have and what it should not, where a missing or extra permission fails. The other words
|
|
534
|
+
* limit the zone checks to those zones; otherwise up to five are read. How the token is chosen is in `holocron probe --help`.
|
|
535
|
+
*/
|
|
536
|
+
function tokenProbe(ctx) {
|
|
537
|
+
return {
|
|
538
|
+
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.",
|
|
539
|
+
writes: false,
|
|
540
|
+
acceptsToken: true,
|
|
541
|
+
async run(probe) {
|
|
542
|
+
const token = ctx.token();
|
|
543
|
+
probe.secret(token);
|
|
544
|
+
const client = ctx.client();
|
|
545
|
+
const { layer, tokenName, zones: wanted } = parseTokenArgs(probe.args ?? []);
|
|
546
|
+
const expectation = layer ? tokenExpectations(tokens, {
|
|
547
|
+
layer,
|
|
548
|
+
...tokenName ? { envName: tokenName } : {}
|
|
549
|
+
})[0] : void 0;
|
|
550
|
+
const rules = expectation?.rules;
|
|
551
|
+
if (layer && !rules) probe.say({
|
|
552
|
+
status: "info",
|
|
553
|
+
label: layer,
|
|
554
|
+
detail: "no expectations are declared for it, so the token is only described"
|
|
555
|
+
});
|
|
556
|
+
const now = (ctx.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
557
|
+
const rotation = expectation?.rotation ?? DEFAULT_TOKEN_ROTATION;
|
|
558
|
+
let lifetime;
|
|
559
|
+
try {
|
|
560
|
+
const verified = await client.tokens.verify();
|
|
561
|
+
probe.say({
|
|
562
|
+
status: "ok",
|
|
563
|
+
label: "token",
|
|
564
|
+
detail: `${verified.id} (${verified.status})`
|
|
565
|
+
});
|
|
566
|
+
lifetime = {
|
|
567
|
+
...verified.not_before ? { createdAt: verified.not_before } : {},
|
|
568
|
+
...verified.expires_on ? { expiresAt: verified.expires_on } : {}
|
|
569
|
+
};
|
|
570
|
+
} catch {}
|
|
571
|
+
const rotationRows = tokenRotationRows(lifetime, rotation, now);
|
|
572
|
+
const sayRotation = () => {
|
|
573
|
+
probe.say({
|
|
574
|
+
status: "heading",
|
|
575
|
+
label: "Rotation"
|
|
576
|
+
});
|
|
577
|
+
for (const row of rotationRows) probe.say(row);
|
|
578
|
+
};
|
|
579
|
+
const named = wanted.length > 0 ? wanted : ctx.options.zone ? [ctx.options.zone] : [];
|
|
580
|
+
const tried = [];
|
|
581
|
+
let zones = [];
|
|
582
|
+
const zoneOutcome = await reach(async () => {
|
|
583
|
+
zones = named.length > 0 ? (await Promise.all(named.map((name) => client.zones.list({ name })))).flat() : await client.zones.list({ per_page: MAX_ZONES });
|
|
584
|
+
return zones.map((z) => ({ name: z.name }));
|
|
585
|
+
}, "zones");
|
|
586
|
+
tried.push({
|
|
587
|
+
label: "Zone: Read",
|
|
588
|
+
permission: "zone",
|
|
589
|
+
outcome: zoneOutcome
|
|
590
|
+
});
|
|
591
|
+
if (zoneOutcome.kind !== "error") {
|
|
592
|
+
for (const zone of zones.slice(0, MAX_ZONES)) {
|
|
593
|
+
tried.push({
|
|
594
|
+
label: `DNS: Edit (${zone.name})`,
|
|
595
|
+
permission: "dns",
|
|
596
|
+
outcome: await reach(() => client.dns.list(zone.id), "records")
|
|
597
|
+
});
|
|
598
|
+
tried.push({
|
|
599
|
+
label: `Workers Routes: Edit (${zone.name})`,
|
|
600
|
+
permission: "routes",
|
|
601
|
+
outcome: await reach(async () => (await client.workers.listRoutes(zone.id)).map((r) => ({ name: r.pattern })), "routes")
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
const account = ctx.options.accountId;
|
|
605
|
+
if (account) {
|
|
606
|
+
tried.push({
|
|
607
|
+
label: "Workers Scripts: Edit",
|
|
608
|
+
permission: "scripts",
|
|
609
|
+
outcome: await reach(async () => (await client.workers.listScripts(account)).map((s) => ({ name: s.id })), "scripts")
|
|
610
|
+
});
|
|
611
|
+
tried.push({
|
|
612
|
+
label: "Pages: Edit",
|
|
613
|
+
permission: "pages",
|
|
614
|
+
outcome: await reach(() => client.pages.listProjects(account), "projects")
|
|
615
|
+
});
|
|
616
|
+
tried.push({
|
|
617
|
+
label: "Cloudflare Tunnel: Edit",
|
|
618
|
+
permission: "tunnels",
|
|
619
|
+
outcome: await reach(() => client.tunnels.list(account), "tunnels")
|
|
620
|
+
});
|
|
621
|
+
} else probe.say({
|
|
622
|
+
status: rules ? "fail" : "info",
|
|
623
|
+
label: "account permissions",
|
|
624
|
+
detail: "no account id: set HOLOCRON_CLOUDFLARE_ACCOUNT_ID or the plugin's accountId option to check them"
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
if (!rules) {
|
|
628
|
+
for (const t of tried) probe.say(rowFor(t, void 0));
|
|
629
|
+
sayRotation();
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
|
|
633
|
+
const inGroup = tried.filter((t) => rules[t.permission] === rule);
|
|
634
|
+
if (inGroup.length === 0) continue;
|
|
635
|
+
probe.say({
|
|
636
|
+
status: "heading",
|
|
637
|
+
label: heading
|
|
638
|
+
});
|
|
639
|
+
for (const t of inGroup) probe.say(rowFor(t, rule));
|
|
640
|
+
}
|
|
641
|
+
sayRotation();
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
// src/verify-token.ts
|
|
646
|
+
/** Checks a Cloudflare API token, first by the token-verify endpoint and otherwise by listing zones; resolves to a description of what it found, or the failure message. */
|
|
307
647
|
async function verifyToken(token, opts = {}) {
|
|
308
648
|
const client = createCloudflareClient({
|
|
309
649
|
token,
|
|
@@ -318,21 +658,26 @@ async function verifyToken(token, opts = {}) {
|
|
|
318
658
|
};
|
|
319
659
|
} catch {}
|
|
320
660
|
try {
|
|
661
|
+
const names = (await client.zones.list()).map((z) => z.name);
|
|
662
|
+
if (names.length === 0) return {
|
|
663
|
+
ok: true,
|
|
664
|
+
subject: "no zones visible"
|
|
665
|
+
};
|
|
321
666
|
return {
|
|
322
667
|
ok: true,
|
|
323
|
-
subject: `
|
|
668
|
+
subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
|
|
324
669
|
};
|
|
325
670
|
} catch (err) {
|
|
326
671
|
return {
|
|
327
672
|
ok: false,
|
|
328
|
-
message:
|
|
673
|
+
message: errorMessage(err)
|
|
329
674
|
};
|
|
330
675
|
}
|
|
331
676
|
}
|
|
332
|
-
|
|
333
|
-
|
|
677
|
+
// src/index.ts
|
|
678
|
+
/** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
|
|
334
679
|
function createContext(options = {}) {
|
|
335
|
-
const accountId = options.accountId ??
|
|
680
|
+
const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
|
|
336
681
|
const opts = {
|
|
337
682
|
...options,
|
|
338
683
|
accountId
|
|
@@ -350,34 +695,53 @@ function createContext(options = {}) {
|
|
|
350
695
|
})
|
|
351
696
|
};
|
|
352
697
|
}
|
|
698
|
+
/** Builds the `dns` capability for a context. */
|
|
353
699
|
function dns(ctx) {
|
|
354
700
|
return new CloudflareDns(ctx.client);
|
|
355
701
|
}
|
|
702
|
+
/** Builds the `deployment` capability for a context; throws when no account id is set. */
|
|
356
703
|
function deployment(ctx) {
|
|
357
704
|
if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Pages deployments — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
|
|
358
705
|
return new CloudflareDeployment(ctx.client, ctx.options.accountId);
|
|
359
706
|
}
|
|
707
|
+
/** Builds the `workers` capability for a context; throws when no account id is set. */
|
|
360
708
|
function workersCapability(ctx) {
|
|
361
709
|
if (!ctx.options.accountId) throw new Error("Cloudflare accountId is required for Workers — set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID env var");
|
|
362
|
-
return new CloudflareWorkers(
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
710
|
+
return new CloudflareWorkers(ctx.client, ctx.options.accountId);
|
|
711
|
+
}
|
|
712
|
+
/** Builds the `tunnels` capability for a context; throws when no account id is set. */
|
|
713
|
+
function tunnelsCapability(ctx) {
|
|
714
|
+
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");
|
|
715
|
+
return new CloudflareTunnels(ctx.client, ctx.options.accountId);
|
|
367
716
|
}
|
|
717
|
+
/** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
|
|
368
718
|
function createPlugin(options = {}) {
|
|
369
719
|
const ctx = createContext(options);
|
|
370
720
|
return {
|
|
371
721
|
name: "@theholocron/holocron-plugin-cloudflare",
|
|
722
|
+
probes: {
|
|
723
|
+
token: tokenProbe(ctx),
|
|
724
|
+
connection: connectionProbe({
|
|
725
|
+
provider: "Cloudflare",
|
|
726
|
+
url: options.baseUrl ?? "https://api.cloudflare.com",
|
|
727
|
+
fetch: options.fetch,
|
|
728
|
+
token: () => resolveToken(options),
|
|
729
|
+
verify: (token) => verifyToken(token, {
|
|
730
|
+
baseUrl: options.baseUrl,
|
|
731
|
+
fetch: options.fetch
|
|
732
|
+
})
|
|
733
|
+
})
|
|
734
|
+
},
|
|
372
735
|
capabilities: {
|
|
373
736
|
dns: () => dns(ctx),
|
|
374
737
|
...ctx.options.accountId ? {
|
|
375
738
|
deployment: () => deployment(ctx),
|
|
376
|
-
workers: () => workersCapability(ctx)
|
|
739
|
+
workers: () => workersCapability(ctx),
|
|
740
|
+
tunnels: () => tunnelsCapability(ctx)
|
|
377
741
|
} : {}
|
|
378
742
|
}
|
|
379
743
|
};
|
|
380
744
|
}
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
|
|
745
|
+
/** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
|
|
746
|
+
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>";
|
|
747
|
+
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.
|
|
3
|
+
"version": "5.0.0-alpha.500",
|
|
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://
|
|
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": "
|
|
16
|
+
"directory": "plugins/holocron-plugin-cloudflare"
|
|
17
17
|
},
|
|
18
18
|
"license": "MIT",
|
|
19
19
|
"author": "Newton Koumantzelis",
|
|
@@ -29,28 +29,35 @@
|
|
|
29
29
|
"files": [
|
|
30
30
|
"dist"
|
|
31
31
|
],
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@theholocron/env-utils": "^1.17.0-alpha.5"
|
|
34
|
+
},
|
|
32
35
|
"devDependencies": {
|
|
33
|
-
"@theholocron/cloudflare-client": "^1.14.2",
|
|
34
|
-
"@theholocron/eslint-config": "^8.0.0",
|
|
35
|
-
"@theholocron/tsconfig": "^8.0.0",
|
|
36
|
-
"@theholocron/tsdown-config": "^8.0.0",
|
|
37
|
-
"@theholocron/vitest-config": "^8.0.0",
|
|
38
36
|
"@types/node": "^26",
|
|
39
|
-
"@vitest/coverage-v8": "^
|
|
40
|
-
"@vitest/eslint-plugin": "^1.6.
|
|
41
|
-
"chalk": "^6.0.
|
|
42
|
-
"eslint": "^10.
|
|
43
|
-
"eslint-plugin-n": "^18.
|
|
44
|
-
"globals": "^17.
|
|
45
|
-
"tsdown": "^0.
|
|
46
|
-
"tsx": "4.23.
|
|
37
|
+
"@vitest/coverage-v8": "^5.1.0",
|
|
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",
|
|
47
45
|
"typescript": "^5.9.3",
|
|
48
|
-
"vitest": "^
|
|
49
|
-
"@theholocron/
|
|
46
|
+
"vitest": "^5.1.0",
|
|
47
|
+
"@theholocron/eslint-config": "^8.9.0-alpha.21",
|
|
48
|
+
"@theholocron/cloudflare-client": "^1.58.0-alpha.45",
|
|
49
|
+
"@theholocron/cli": "5.0.0-alpha.500",
|
|
50
|
+
"@theholocron/misc-utils": "^1.17.0-alpha.5",
|
|
51
|
+
"@theholocron/http-client": "^1.58.0-alpha.45",
|
|
52
|
+
"@theholocron/tsconfig": "^8.9.0-alpha.21",
|
|
53
|
+
"@theholocron/vitest-config": "^8.9.0-alpha.21",
|
|
54
|
+
"@theholocron/tsdown-config": "^8.9.0-alpha.21",
|
|
55
|
+
"@theholocron/kyber": "5.0.0-alpha.500"
|
|
50
56
|
},
|
|
51
57
|
"peerDependencies": {
|
|
52
|
-
"@theholocron/cloudflare-client": "^1.
|
|
53
|
-
"@theholocron/
|
|
58
|
+
"@theholocron/cloudflare-client": "^1.53.1",
|
|
59
|
+
"@theholocron/misc-utils": "^1.16.0",
|
|
60
|
+
"@theholocron/cli": "5.0.0-alpha.500"
|
|
54
61
|
},
|
|
55
62
|
"peerDependenciesMeta": {
|
|
56
63
|
"@theholocron/cloudflare-client": {}
|
|
@@ -62,11 +69,11 @@
|
|
|
62
69
|
"access": "public"
|
|
63
70
|
},
|
|
64
71
|
"scripts": {
|
|
65
|
-
"
|
|
66
|
-
"
|
|
72
|
+
"build": "tsdown",
|
|
73
|
+
"lint:code": "eslint .",
|
|
74
|
+
"test:unit": "vitest run --coverage",
|
|
67
75
|
"test:watch": "vitest",
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"verification.unitTests": "holocron run verification.unitTests --"
|
|
76
|
+
"typecheck": "tsc --noEmit",
|
|
77
|
+
"validate:plugin": "tsx scripts/validate.mjs"
|
|
71
78
|
}
|
|
72
79
|
}
|