@theholocron/holocron-plugin-cloudflare 5.0.0-alpha.52 → 5.0.0-alpha.521
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 +21 -5
- package/dist/index.d.mts +108 -37
- package/dist/index.mjs +555 -23
- package/package.json +33 -27
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 `
|
|
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
|
|
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 `
|
|
67
|
-
is resolvable — either passed explicitly in options or set
|
|
68
|
-
`CLOUDFLARE_ACCOUNT_ID` env var
|
|
66
|
+
The `deployment`, `workers` and `tunnels` capabilities are only exposed when `accountId`
|
|
67
|
+
is resolvable — either passed explicitly in options or set as the
|
|
68
|
+
`HOLOCRON_CLOUDFLARE_ACCOUNT_ID` (or `CLOUDFLARE_ACCOUNT_ID`) env var or in a `credentials` provider's Environment (the option wins, then the
|
|
69
|
+
environment, then the provider).
|
|
69
70
|
|
|
70
71
|
## `dns` capability
|
|
71
72
|
|
|
@@ -104,6 +105,21 @@ route-write call when nothing changed. Zone ids are cached per plugin
|
|
|
104
105
|
instance for the lifetime of the process — the `workers` capability's own
|
|
105
106
|
cache, separate from `dns`'s.
|
|
106
107
|
|
|
108
|
+
## `tunnels` capability
|
|
109
|
+
|
|
110
|
+
Named [Cloudflare Tunnels](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/): a stable
|
|
111
|
+
public hostname that reaches a port on this machine, for a webhook that has to find a development instance. It needs a
|
|
112
|
+
token with **Cloudflare Tunnel: Edit** (account).
|
|
113
|
+
|
|
114
|
+
| Method | What it does |
|
|
115
|
+
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
116
|
+
| `ensureTunnel` | Finds the tunnel by name or makes it, and makes its configuration serve `hostname` at `service`. Other hostnames' rules are kept and the catch-all (`http_status:404`) stays last. Returns the tunnel id and the `CNAME` target (`<id>.cfargotunnel.com`). |
|
|
117
|
+
| `tunnelToken` | The token `cloudflared` runs the tunnel with. A credential: never printed or stored. |
|
|
118
|
+
| `whoami` | How many tunnels the token can see, for `holocron doctor`. |
|
|
119
|
+
|
|
120
|
+
`ensureTunnel` is idempotent: a tunnel that already serves the hostname is not rewritten. The DNS record for the
|
|
121
|
+
hostname is the `dns` provider's job.
|
|
122
|
+
|
|
107
123
|
### Preview deployment setup
|
|
108
124
|
|
|
109
125
|
When `preview: true` (or `preview: { project, domain }`) is set in a repo's deploy config, `holocron setup` calls:
|
package/dist/index.d.mts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, ResolveTokenInput, WikiProxyConfig, Workers } from "@theholocron/cli";
|
|
1
|
+
import { AuthError, DeployScriptConfig, DeployScriptResult, Deployment, DeploymentProject, DeploymentProjectSettings, DeploymentRecord, DeploymentTarget, DeploymentTrigger, Dns, DnsRecord, DnsRecordRequest, EnsureRelaySourceInput, EnsureRelaySourceResult, EnsuredTunnel, InspectRelaySourceInput, PluginToken, RelaySourceState, ResolveTokenInput, TunnelRoute, Tunnels, VerifyTokenFailure, VerifyTokenResult, VerifyTokenResult as VerifyTokenResult$1, VerifyTokenSuccess, WikiProxyConfig, WorkerDeploymentState, WorkerScriptState, Workers } from "@theholocron/cli";
|
|
2
2
|
import { CloudflareClient, CloudflareClient as CloudflareClient$1, CloudflareClientOptions, createCloudflareClient } from "@theholocron/cloudflare-client";
|
|
3
|
-
|
|
4
|
-
declare const resolveToken: (
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
3
|
+
/** Resolves the Cloudflare API token from `--token`, `HOLOCRON_CLOUDFLARE_TOKEN`, `CLOUDFLARE_API_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
|
|
4
|
+
export declare const resolveToken: import("@theholocron/cli").TokenResolver;
|
|
5
|
+
/** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
|
|
6
|
+
export declare const tokens: PluginToken[];
|
|
7
|
+
/** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
|
|
8
|
+
export declare class CloudflareDeployment implements Deployment {
|
|
8
9
|
private readonly client;
|
|
9
10
|
private readonly accountId;
|
|
11
|
+
/** The capability this class provides, always `"deployment"`. */
|
|
10
12
|
readonly key: "deployment";
|
|
13
|
+
/** The provider name, `"cloudflare"`. */
|
|
11
14
|
readonly providerName = "cloudflare";
|
|
12
15
|
constructor(client: () => CloudflareClient, accountId: string);
|
|
16
|
+
/** Lists the account's Pages projects. */
|
|
13
17
|
listProjects(): Promise<DeploymentProject[]>;
|
|
14
18
|
ensureProject(input: {
|
|
15
19
|
name: string;
|
|
@@ -17,31 +21,54 @@ declare class CloudflareDeployment implements Deployment {
|
|
|
17
21
|
repo?: string;
|
|
18
22
|
rootDirectory?: string;
|
|
19
23
|
}): Promise<DeploymentProject>;
|
|
24
|
+
/** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
|
|
20
25
|
updateProjectSettings(projectId: string, settings: DeploymentProjectSettings): Promise<DeploymentProject>;
|
|
26
|
+
/** Lists the names of the environment variables set for the production or preview target. */
|
|
21
27
|
listEnvVars(projectId: string, target: DeploymentTarget): Promise<string[]>;
|
|
28
|
+
/** Sets a plain-text environment variable on the production or preview target, keeping the others. */
|
|
22
29
|
setEnvVar(projectId: string, target: DeploymentTarget, name: string, value: string): Promise<void>;
|
|
23
30
|
triggerDeployment(input: {
|
|
24
31
|
projectId: string;
|
|
25
32
|
branch: string;
|
|
26
33
|
target?: DeploymentTrigger;
|
|
27
34
|
}): Promise<DeploymentRecord>;
|
|
35
|
+
/** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
|
|
28
36
|
getDeployment(deploymentId: string): Promise<DeploymentRecord>;
|
|
29
37
|
listPreviewDeployments(projectId: string, branch: string): Promise<DeploymentRecord[]>;
|
|
30
38
|
deletePreviewDeployments(projectId: string, deploymentIds: string[]): Promise<number>;
|
|
31
39
|
ensureCustomDomain(projectId: string, hostname: string): Promise<DnsRecordRequest | null>;
|
|
40
|
+
/** The hostnames attached to the Pages project. Reads only. */
|
|
41
|
+
listDomains(projectId: string): Promise<string[]>;
|
|
42
|
+
/** The newest production deployment of the project, or null. Reads only. */
|
|
43
|
+
latestDeployment(projectId: string): Promise<DeploymentRecord | null>;
|
|
32
44
|
private getProjectByName;
|
|
33
45
|
}
|
|
34
|
-
|
|
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
|
+
private readonly accountId?;
|
|
50
|
+
/** The capability this class provides, always `"dns"`. */
|
|
38
51
|
readonly key: "dns";
|
|
52
|
+
/** The provider name, `"cloudflare"`. */
|
|
39
53
|
readonly providerName = "cloudflare";
|
|
40
54
|
private readonly zoneCache;
|
|
41
|
-
constructor(client: () => CloudflareClient);
|
|
55
|
+
constructor(client: () => CloudflareClient, accountId?: string | undefined);
|
|
56
|
+
/** Makes the Cloudflare notification webhook and the policies that send to it for a relay source; needs the account id. */
|
|
57
|
+
ensureRelaySource(input: EnsureRelaySourceInput): Promise<EnsureRelaySourceResult>;
|
|
58
|
+
/** Reads the relay source's notification webhook and its policies back, changing nothing. */
|
|
59
|
+
inspectRelaySource(input: InspectRelaySourceInput): Promise<RelaySourceState>;
|
|
60
|
+
private account;
|
|
61
|
+
/** Lists the DNS records in the zone that holds the domain. */
|
|
42
62
|
listRecords(domain: string): Promise<DnsRecord[]>;
|
|
63
|
+
/** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
|
|
43
64
|
upsertRecord(domain: string, record: DnsRecord): Promise<DnsRecord>;
|
|
65
|
+
/** Deletes the DNS record with this id from the zone that holds the domain. */
|
|
44
66
|
deleteRecord(domain: string, id: string): Promise<void>;
|
|
67
|
+
/** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
|
|
68
|
+
whoami(): Promise<{
|
|
69
|
+
ok: boolean;
|
|
70
|
+
zones: number;
|
|
71
|
+
}>;
|
|
45
72
|
/**
|
|
46
73
|
* Walk from full domain up to apex to find the Cloudflare zone.
|
|
47
74
|
* E.g. "api.staging.example.com" tries:
|
|
@@ -51,68 +78,112 @@ declare class CloudflareDns implements Dns {
|
|
|
51
78
|
*/
|
|
52
79
|
private resolveZone;
|
|
53
80
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
declare class CloudflareWorkers implements Workers {
|
|
81
|
+
/** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
|
|
82
|
+
export declare class CloudflareTunnels implements Tunnels {
|
|
57
83
|
private readonly client;
|
|
58
84
|
private readonly accountId;
|
|
85
|
+
/** The capability this class provides, always `"tunnels"`. */
|
|
86
|
+
readonly key: "tunnels";
|
|
87
|
+
/** The provider name, `"cloudflare"`. */
|
|
88
|
+
readonly providerName = "cloudflare";
|
|
89
|
+
constructor(client: () => Pick<CloudflareClient$1, "tunnels">, accountId: string);
|
|
90
|
+
/** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
|
|
91
|
+
ensureTunnel(route: TunnelRoute): Promise<EnsuredTunnel>;
|
|
92
|
+
/** The token `cloudflared` runs the tunnel with. */
|
|
93
|
+
tunnelToken(tunnelId: string): Promise<string>;
|
|
94
|
+
/** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
|
|
95
|
+
whoami(): Promise<{
|
|
96
|
+
ok: boolean;
|
|
97
|
+
tunnels: number;
|
|
98
|
+
}>;
|
|
99
|
+
}
|
|
100
|
+
/** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
|
|
101
|
+
export declare class CloudflareWorkers implements Workers {
|
|
102
|
+
private readonly client;
|
|
103
|
+
private readonly accountId;
|
|
104
|
+
/** The capability this class provides, always `"workers"`. */
|
|
59
105
|
readonly key: "workers";
|
|
106
|
+
/** The provider name, `"cloudflare"`. */
|
|
60
107
|
readonly providerName = "cloudflare";
|
|
61
108
|
private readonly zoneCache;
|
|
62
109
|
constructor(client: () => Pick<CloudflareClient$1, "workers" | "zones">, accountId: string);
|
|
63
110
|
upsertProxy(hostname: string, config: WikiProxyConfig): Promise<void>;
|
|
111
|
+
/** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
|
|
112
|
+
whoami(): Promise<{
|
|
113
|
+
ok: boolean;
|
|
114
|
+
scripts: number;
|
|
115
|
+
}>;
|
|
64
116
|
deployScript(name: string, config: DeployScriptConfig): Promise<DeployScriptResult>;
|
|
117
|
+
setSecret(script: string, name: string, value: string): Promise<void>;
|
|
118
|
+
secretNames(script: string): Promise<string[]>;
|
|
119
|
+
/**
|
|
120
|
+
* Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
|
|
121
|
+
* only, and asks Cloudflare for names, so no value is ever fetched.
|
|
122
|
+
*/
|
|
123
|
+
inspectScript(name: string, host: string): Promise<WorkerScriptState>;
|
|
124
|
+
/** The newest deployment of the script, and whether it serves all traffic. Reads only. */
|
|
125
|
+
latestDeployment(script: string): Promise<WorkerDeploymentState | null>;
|
|
126
|
+
proxyScriptName(hostname: string): string;
|
|
65
127
|
/** Idempotent create-or-update for one route pattern — shared by both public methods. */
|
|
66
128
|
private upsertRoute;
|
|
67
129
|
private resolveZone;
|
|
68
130
|
}
|
|
69
|
-
//#endregion
|
|
70
|
-
//#region src/verify-token.d.ts
|
|
71
|
-
interface VerifyTokenSuccess {
|
|
72
|
-
ok: true;
|
|
73
|
-
subject: string;
|
|
74
|
-
}
|
|
75
|
-
interface VerifyTokenFailure {
|
|
76
|
-
ok: false;
|
|
77
|
-
message: string;
|
|
78
|
-
}
|
|
79
|
-
type VerifyTokenResult = VerifyTokenSuccess | VerifyTokenFailure;
|
|
80
131
|
interface VerifyTokenOptions {
|
|
81
132
|
baseUrl?: string;
|
|
82
133
|
fetch?: typeof fetch;
|
|
83
134
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
interface CloudflarePluginOptions extends ResolveTokenInput {
|
|
135
|
+
/** Checks a Cloudflare API token, first by the token-verify endpoint and otherwise by listing zones; resolves to a description of what it found, or the failure message. */
|
|
136
|
+
export declare function verifyToken(token: string, opts?: VerifyTokenOptions): Promise<VerifyTokenResult$1>;
|
|
137
|
+
/** Options for the Cloudflare plugin: how the API token is resolved, the account, and test overrides. */
|
|
138
|
+
export interface CloudflarePluginOptions extends ResolveTokenInput {
|
|
88
139
|
/**
|
|
89
140
|
* Cloudflare account ID. Required for Pages (deployment) operations;
|
|
90
141
|
* optional for DNS-only use.
|
|
91
142
|
*/
|
|
92
143
|
accountId?: string;
|
|
144
|
+
/**
|
|
145
|
+
* The zone the organization's own DNS lives in. The `token` probe reads this one zone when no zone is named on the
|
|
146
|
+
* command line; without it the probe reads the first few zones of the account.
|
|
147
|
+
*/
|
|
148
|
+
zone?: string;
|
|
93
149
|
/** Override base URL for tests. */
|
|
94
150
|
baseUrl?: string;
|
|
151
|
+
/** The `fetch` to use instead of the global one, for tests. */
|
|
95
152
|
fetch?: typeof fetch;
|
|
96
153
|
}
|
|
97
|
-
|
|
154
|
+
/** The shared state the Cloudflare plugin's capabilities and probes are built from. */
|
|
155
|
+
export interface PluginContext {
|
|
156
|
+
/** The options the plugin was created with, with `accountId` falling back to `CLOUDFLARE_ACCOUNT_ID` in the environment, then in the `credentials` providers' variables. */
|
|
98
157
|
options: CloudflarePluginOptions;
|
|
99
158
|
/** Memoized client — the token is resolved on first use, not at plugin load. */
|
|
100
159
|
client: () => CloudflareClient;
|
|
101
160
|
/** Memoized token resolver — shared by the client and the Workers capability. */
|
|
102
161
|
token: () => string;
|
|
103
162
|
}
|
|
104
|
-
|
|
105
|
-
declare function
|
|
106
|
-
|
|
107
|
-
declare function
|
|
108
|
-
|
|
163
|
+
/** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
|
|
164
|
+
export declare function createContext(options?: CloudflarePluginOptions): PluginContext;
|
|
165
|
+
/** Builds the `dns` capability for a context. */
|
|
166
|
+
export declare function dns(ctx: PluginContext): Dns;
|
|
167
|
+
/** Builds the `deployment` capability for a context; throws when no account id is set. */
|
|
168
|
+
export declare function deployment(ctx: PluginContext): Deployment;
|
|
169
|
+
/** Builds the `workers` capability for a context; throws when no account id is set. */
|
|
170
|
+
export declare function workersCapability(ctx: PluginContext): Workers;
|
|
171
|
+
/** Builds the `tunnels` capability for a context; throws when no account id is set. */
|
|
172
|
+
export declare function tunnelsCapability(ctx: PluginContext): Tunnels;
|
|
173
|
+
/** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
|
|
174
|
+
export declare function createPlugin(options?: CloudflarePluginOptions): {
|
|
109
175
|
name: string;
|
|
176
|
+
probes: {
|
|
177
|
+
token: import("@theholocron/cli").Probe;
|
|
178
|
+
connection: import("@theholocron/cli").Probe;
|
|
179
|
+
};
|
|
110
180
|
capabilities: {
|
|
111
181
|
deployment?: (() => Deployment) | undefined;
|
|
112
182
|
workers?: (() => Workers) | undefined;
|
|
183
|
+
tunnels?: (() => Tunnels) | undefined;
|
|
113
184
|
dns: () => Dns;
|
|
114
185
|
};
|
|
115
186
|
};
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
export {
|
|
187
|
+
/** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
|
|
188
|
+
export declare const AUTH_HINT: string;
|
|
189
|
+
export { AuthError, type CloudflareClient, type CloudflareClientOptions, type ResolveTokenInput, type VerifyTokenFailure, type VerifyTokenResult, type VerifyTokenSuccess, createCloudflareClient };
|
package/dist/index.mjs
CHANGED
|
@@ -1,23 +1,70 @@
|
|
|
1
|
-
import { AuthError, ProviderApiError, createResolveToken } from "@theholocron/cli";
|
|
1
|
+
import { AuthError, DEFAULT_TOKEN_ROTATION, ProviderApiError, connectionProbe, createResolveToken, resolveValue, tokenExpectations, tokenRotationRows } from "@theholocron/cli";
|
|
2
|
+
import { PREFIX } from "@theholocron/env-utils/lookup";
|
|
3
|
+
import { errorMessage } from "@theholocron/misc-utils";
|
|
2
4
|
import { createCloudflareClient } from "@theholocron/cloudflare-client";
|
|
3
|
-
|
|
5
|
+
// src/probes/token/expectations.ts
|
|
6
|
+
const EVERYTHING = {
|
|
7
|
+
zone: "required",
|
|
8
|
+
dns: "required",
|
|
9
|
+
routes: "required",
|
|
10
|
+
scripts: "required",
|
|
11
|
+
pages: "required",
|
|
12
|
+
tunnels: "required",
|
|
13
|
+
notifications: "required"
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* What each layer's Cloudflare token is meant to carry, the same as "What each Cloudflare token needs" in
|
|
17
|
+
* `docs/src/content/docs/tokens.mdx`: a laptop (`local` inherits `dev`) runs everything, CI only deploys Pages, so a
|
|
18
|
+
* leak from CI cannot change DNS, Workers or a tunnel. A layer not listed (`prod`) has no declared expectations and its
|
|
19
|
+
* token is only reported. This is the plugin's `tokens` declaration, read through `tokenExpectations()`; change it and
|
|
20
|
+
* that table together.
|
|
21
|
+
*/
|
|
22
|
+
const EXPECTED = {
|
|
23
|
+
rotation: {
|
|
24
|
+
maxAgeDays: 90,
|
|
25
|
+
warnDays: 14
|
|
26
|
+
},
|
|
27
|
+
permissions: {
|
|
28
|
+
local: EVERYTHING,
|
|
29
|
+
dev: EVERYTHING,
|
|
30
|
+
ci: {
|
|
31
|
+
zone: "absent",
|
|
32
|
+
dns: "absent",
|
|
33
|
+
routes: "absent",
|
|
34
|
+
scripts: "absent",
|
|
35
|
+
pages: "required",
|
|
36
|
+
tunnels: "absent",
|
|
37
|
+
notifications: "absent"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
// src/auth.ts
|
|
42
|
+
/** Resolves the Cloudflare API token from `--token`, `HOLOCRON_CLOUDFLARE_TOKEN`, `CLOUDFLARE_API_TOKEN` or the keyring, and throws an `AuthError` when none is set. */
|
|
4
43
|
const resolveToken = createResolveToken({
|
|
5
44
|
envName: "HOLOCRON_CLOUDFLARE_TOKEN",
|
|
6
45
|
vendorEnvName: "CLOUDFLARE_API_TOKEN",
|
|
7
46
|
keyringService: "cloudflare",
|
|
8
|
-
errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron
|
|
47
|
+
errorMessage: "no Cloudflare API token found. Pass --token <TOKEN>, set HOLOCRON_CLOUDFLARE_TOKEN / CLOUDFLARE_API_TOKEN, or run: holocron new token cloudflare <TOKEN>"
|
|
9
48
|
});
|
|
10
|
-
|
|
11
|
-
|
|
49
|
+
/** Every token this plugin takes, for `holocron doctor secrets --verify`, with what each layer's token must and must not be able to do. */
|
|
50
|
+
const tokens = [{
|
|
51
|
+
...resolveToken.token,
|
|
52
|
+
expect: EXPECTED
|
|
53
|
+
}];
|
|
54
|
+
// src/capabilities/deployment.ts
|
|
55
|
+
/** The Cloudflare implementation of the `deployment` capability, backed by Cloudflare Pages projects in one account. */
|
|
12
56
|
var CloudflareDeployment = class {
|
|
13
57
|
client;
|
|
14
58
|
accountId;
|
|
59
|
+
/** The capability this class provides, always `"deployment"`. */
|
|
15
60
|
key = "deployment";
|
|
61
|
+
/** The provider name, `"cloudflare"`. */
|
|
16
62
|
providerName = "cloudflare";
|
|
17
63
|
constructor(client, accountId) {
|
|
18
64
|
this.client = client;
|
|
19
65
|
this.accountId = accountId;
|
|
20
66
|
}
|
|
67
|
+
/** Lists the account's Pages projects. */
|
|
21
68
|
async listProjects() {
|
|
22
69
|
return (await this.client().pages.listProjects(this.accountId)).map(mapProject);
|
|
23
70
|
}
|
|
@@ -29,14 +76,17 @@ var CloudflareDeployment = class {
|
|
|
29
76
|
production_branch: "main"
|
|
30
77
|
}));
|
|
31
78
|
}
|
|
79
|
+
/** Returns the project as it is now; Pages has no REST setting for the requested options, so `settings` is ignored. */
|
|
32
80
|
async updateProjectSettings(projectId, settings) {
|
|
33
81
|
return mapProject(await this.client().pages.getProject(this.accountId, projectId));
|
|
34
82
|
}
|
|
83
|
+
/** Lists the names of the environment variables set for the production or preview target. */
|
|
35
84
|
async listEnvVars(projectId, target) {
|
|
36
85
|
const project = await this.client().pages.getProject(this.accountId, projectId);
|
|
37
86
|
const envConfig = target === "production" ? project.deployment_configs.production : project.deployment_configs.preview;
|
|
38
87
|
return Object.keys(envConfig.env_vars);
|
|
39
88
|
}
|
|
89
|
+
/** Sets a plain-text environment variable on the production or preview target, keeping the others. */
|
|
40
90
|
async setEnvVar(projectId, target, name, value) {
|
|
41
91
|
const cfg = (await this.client().pages.getProject(this.accountId, projectId)).deployment_configs;
|
|
42
92
|
const scope = target === "production" ? "production" : "preview";
|
|
@@ -55,6 +105,7 @@ var CloudflareDeployment = class {
|
|
|
55
105
|
async triggerDeployment(input) {
|
|
56
106
|
return mapDeployment(await this.client().pages.createDeployment(this.accountId, input.projectId, input.branch), input.projectId, input.branch, input.target);
|
|
57
107
|
}
|
|
108
|
+
/** Fetches a deployment by an id of the form `projectName:deploymentId`; throws a 400 `ProviderApiError` for any other form. */
|
|
58
109
|
async getDeployment(deploymentId) {
|
|
59
110
|
const sep = deploymentId.indexOf(":");
|
|
60
111
|
if (sep === -1) throw new ProviderApiError(`Invalid Cloudflare Pages deployment id "${deploymentId}" — expected "projectName:deploymentId"`, 400, void 0);
|
|
@@ -78,6 +129,19 @@ var CloudflareDeployment = class {
|
|
|
78
129
|
await this.client().pages.addDomain(this.accountId, projectId, hostname);
|
|
79
130
|
return null;
|
|
80
131
|
}
|
|
132
|
+
/** The hostnames attached to the Pages project. Reads only. */
|
|
133
|
+
async listDomains(projectId) {
|
|
134
|
+
return (await this.client().pages.listDomains(this.accountId, projectId)).map((d) => d.name);
|
|
135
|
+
}
|
|
136
|
+
/** The newest production deployment of the project, or null. Reads only. */
|
|
137
|
+
async latestDeployment(projectId) {
|
|
138
|
+
const [newest] = (await this.client().pages.listDeployments(this.accountId, projectId)).filter((d) => d.environment === "production").sort((a, b) => b.created_on.localeCompare(a.created_on));
|
|
139
|
+
if (!newest) return null;
|
|
140
|
+
return {
|
|
141
|
+
...mapDeployment(newest, projectId, newest.deployment_trigger.metadata.branch, "production"),
|
|
142
|
+
createdAt: newest.created_on
|
|
143
|
+
};
|
|
144
|
+
}
|
|
81
145
|
async getProjectByName(name) {
|
|
82
146
|
try {
|
|
83
147
|
return mapProject(await this.client().pages.getProject(this.accountId, name));
|
|
@@ -114,20 +178,130 @@ function normalizeStatus(status) {
|
|
|
114
178
|
default: return "error";
|
|
115
179
|
}
|
|
116
180
|
}
|
|
117
|
-
|
|
118
|
-
|
|
181
|
+
// src/capabilities/relay-source.ts
|
|
182
|
+
/** The name of the policy that sends one alert type to the relay: the source's name, then the alert type. */
|
|
183
|
+
function policyName(name, alertType) {
|
|
184
|
+
return `${name}: ${alertType}`;
|
|
185
|
+
}
|
|
186
|
+
/** The webhook targets of a policy with the destination in them, once. */
|
|
187
|
+
function withDestination(webhooks = [], id) {
|
|
188
|
+
return webhooks.some((w) => w.id === id) ? webhooks : [...webhooks, { id }];
|
|
189
|
+
}
|
|
190
|
+
/** The policies that belong to a source, found by name, one per alert type of its layout. */
|
|
191
|
+
function ownPolicies(policies, name) {
|
|
192
|
+
const prefix = `${name}: `;
|
|
193
|
+
return policies.filter((p) => p.name.startsWith(prefix));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Makes the Cloudflare notification webhook for a relay source (spec `tech-relay-sources`). A destination alone sends
|
|
197
|
+
* nothing, so each alert type of `events` gets a policy of its own that names the destination. The destination is
|
|
198
|
+
* found by URL and each policy by name; nothing is deleted. The secret the caller offers is set only when the
|
|
199
|
+
* destination is made (Cloudflare never returns it), so it is returned only then.
|
|
200
|
+
*/
|
|
201
|
+
async function ensureRelaySource(client, accountId, input) {
|
|
202
|
+
const updated = [];
|
|
203
|
+
let found = (await client.alerting.webhooks.list(accountId)).find((d) => d.url === input.url);
|
|
204
|
+
let created = false;
|
|
205
|
+
let secret;
|
|
206
|
+
if (!found) {
|
|
207
|
+
found = {
|
|
208
|
+
id: (await client.alerting.webhooks.create(accountId, {
|
|
209
|
+
name: input.name,
|
|
210
|
+
url: input.url,
|
|
211
|
+
...input.secret ? { secret: input.secret } : {}
|
|
212
|
+
})).id,
|
|
213
|
+
name: input.name,
|
|
214
|
+
url: input.url
|
|
215
|
+
};
|
|
216
|
+
created = true;
|
|
217
|
+
if (input.secret) secret = input.secret;
|
|
218
|
+
}
|
|
219
|
+
const destination = found;
|
|
220
|
+
const events = input.events ?? [];
|
|
221
|
+
if (events.length === 0) {
|
|
222
|
+
const todo = [`List the Cloudflare alert types to send in the source's \`events\` (GET /accounts/<id>/alerting/v3/available_alerts names them); a webhook with no policy sends nothing.`];
|
|
223
|
+
return {
|
|
224
|
+
created,
|
|
225
|
+
updated,
|
|
226
|
+
...secret ? { secret } : {},
|
|
227
|
+
todo
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
const policies = ownPolicies(await client.alerting.policies.list(accountId), input.name);
|
|
231
|
+
for (const alertType of events) {
|
|
232
|
+
const name = policyName(input.name, alertType);
|
|
233
|
+
const body = (base) => ({
|
|
234
|
+
name,
|
|
235
|
+
alert_type: alertType,
|
|
236
|
+
enabled: true,
|
|
237
|
+
mechanisms: {
|
|
238
|
+
...base?.mechanisms,
|
|
239
|
+
webhooks: withDestination(base?.mechanisms.webhooks, destination.id)
|
|
240
|
+
},
|
|
241
|
+
...base?.description !== void 0 ? { description: base.description } : {},
|
|
242
|
+
...base?.filters !== void 0 ? { filters: base.filters } : {},
|
|
243
|
+
...base?.alert_interval !== void 0 ? { alert_interval: base.alert_interval } : {}
|
|
244
|
+
});
|
|
245
|
+
const existing = policies.find((p) => p.name === name);
|
|
246
|
+
if (!existing) {
|
|
247
|
+
await client.alerting.policies.create(accountId, body());
|
|
248
|
+
updated.push(`policy ${alertType}`);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const attached = existing.mechanisms.webhooks?.some((w) => w.id === destination.id) ?? false;
|
|
252
|
+
if (existing.enabled && attached) continue;
|
|
253
|
+
await client.alerting.policies.update(accountId, existing.id, body(existing));
|
|
254
|
+
updated.push(`policy ${alertType}`);
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
created,
|
|
258
|
+
updated: created ? [] : updated,
|
|
259
|
+
...secret ? { secret } : {}
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
/** Reads the webhook back without changing anything: whether the destination exists and which alert types it is sent for. */
|
|
263
|
+
async function inspectRelaySource(client, accountId, input) {
|
|
264
|
+
const destination = (await client.alerting.webhooks.list(accountId)).find((d) => d.url === input.url);
|
|
265
|
+
if (!destination) return { exists: false };
|
|
266
|
+
const policies = ownPolicies(await client.alerting.policies.list(accountId), input.name).filter((p) => p.mechanisms.webhooks?.some((w) => w.id === destination.id));
|
|
267
|
+
return {
|
|
268
|
+
exists: true,
|
|
269
|
+
enabled: policies.length > 0 && policies.every((p) => p.enabled),
|
|
270
|
+
events: policies.map((p) => p.alert_type)
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
// src/capabilities/dns.ts
|
|
274
|
+
/** The Cloudflare implementation of the `dns` capability; finds a domain's zone by walking from the domain up to its apex. */
|
|
119
275
|
var CloudflareDns = class {
|
|
120
276
|
client;
|
|
277
|
+
accountId;
|
|
278
|
+
/** The capability this class provides, always `"dns"`. */
|
|
121
279
|
key = "dns";
|
|
280
|
+
/** The provider name, `"cloudflare"`. */
|
|
122
281
|
providerName = "cloudflare";
|
|
123
282
|
zoneCache = /* @__PURE__ */ new Map();
|
|
124
|
-
constructor(client) {
|
|
283
|
+
constructor(client, accountId) {
|
|
125
284
|
this.client = client;
|
|
285
|
+
this.accountId = accountId;
|
|
286
|
+
}
|
|
287
|
+
/** Makes the Cloudflare notification webhook and the policies that send to it for a relay source; needs the account id. */
|
|
288
|
+
async ensureRelaySource(input) {
|
|
289
|
+
return ensureRelaySource(this.client(), this.account(), input);
|
|
126
290
|
}
|
|
291
|
+
/** Reads the relay source's notification webhook and its policies back, changing nothing. */
|
|
292
|
+
async inspectRelaySource(input) {
|
|
293
|
+
return inspectRelaySource(this.client(), this.account(), input);
|
|
294
|
+
}
|
|
295
|
+
account() {
|
|
296
|
+
if (!this.accountId) throw new ProviderApiError("Cloudflare accountId is required for notification webhooks: set accountId in the plugin options or CLOUDFLARE_ACCOUNT_ID", 0, void 0);
|
|
297
|
+
return this.accountId;
|
|
298
|
+
}
|
|
299
|
+
/** Lists the DNS records in the zone that holds the domain. */
|
|
127
300
|
async listRecords(domain) {
|
|
128
301
|
const zoneId = await this.resolveZone(domain);
|
|
129
302
|
return (await this.client().dns.list(zoneId)).map(mapRecord);
|
|
130
303
|
}
|
|
304
|
+
/** Updates the first record of the same type and name, or creates the record when there is none; returns the stored record. */
|
|
131
305
|
async upsertRecord(domain, record) {
|
|
132
306
|
const client = this.client();
|
|
133
307
|
const zoneId = await this.resolveZone(domain);
|
|
@@ -150,10 +324,18 @@ var CloudflareDns = class {
|
|
|
150
324
|
...record.proxied !== void 0 ? { proxied: record.proxied } : {}
|
|
151
325
|
}));
|
|
152
326
|
}
|
|
327
|
+
/** Deletes the DNS record with this id from the zone that holds the domain. */
|
|
153
328
|
async deleteRecord(domain, id) {
|
|
154
329
|
const zoneId = await this.resolveZone(domain);
|
|
155
330
|
await this.client().dns.delete(zoneId, id);
|
|
156
331
|
}
|
|
332
|
+
/** `holocron doctor` has no specific domain to check — lists every zone the token can see instead. */
|
|
333
|
+
async whoami() {
|
|
334
|
+
return {
|
|
335
|
+
ok: true,
|
|
336
|
+
zones: (await this.client().zones.list()).length
|
|
337
|
+
};
|
|
338
|
+
}
|
|
157
339
|
/**
|
|
158
340
|
* Walk from full domain up to apex to find the Cloudflare zone.
|
|
159
341
|
* E.g. "api.staging.example.com" tries:
|
|
@@ -182,15 +364,75 @@ function mapRecord(raw) {
|
|
|
182
364
|
type: raw.type,
|
|
183
365
|
name: raw.name,
|
|
184
366
|
content: raw.content,
|
|
185
|
-
ttl: raw.ttl
|
|
367
|
+
ttl: raw.ttl,
|
|
368
|
+
...raw.proxied !== void 0 ? { proxied: raw.proxied } : {}
|
|
186
369
|
};
|
|
187
370
|
}
|
|
188
|
-
|
|
189
|
-
|
|
371
|
+
// src/capabilities/tunnels.ts
|
|
372
|
+
/** The rule a tunnel needs last: anything no other rule matches is answered with a 404 by the connector itself. */
|
|
373
|
+
const CATCH_ALL = { service: "http_status:404" };
|
|
374
|
+
/**
|
|
375
|
+
* The ingress rules with `hostname` served at `service`: the rule for the hostname is replaced where it is or added
|
|
376
|
+
* after the others, every other hostname's rule is kept, and the rule without a hostname closes the list.
|
|
377
|
+
*/
|
|
378
|
+
function withRoute(current, hostname, service) {
|
|
379
|
+
const rule = {
|
|
380
|
+
hostname,
|
|
381
|
+
service
|
|
382
|
+
};
|
|
383
|
+
const named = current.filter((r) => r.hostname !== void 0);
|
|
384
|
+
const at = named.findIndex((r) => r.hostname === hostname);
|
|
385
|
+
return [...at === -1 ? [...named, rule] : named.map((r, i) => i === at ? rule : r), current.find((r) => r.hostname === void 0) ?? CATCH_ALL];
|
|
386
|
+
}
|
|
387
|
+
/** The Cloudflare implementation of the `tunnels` capability, backed by Cloudflare Tunnel in one account. */
|
|
388
|
+
var CloudflareTunnels = class {
|
|
389
|
+
client;
|
|
390
|
+
accountId;
|
|
391
|
+
/** The capability this class provides, always `"tunnels"`. */
|
|
392
|
+
key = "tunnels";
|
|
393
|
+
/** The provider name, `"cloudflare"`. */
|
|
394
|
+
providerName = "cloudflare";
|
|
395
|
+
constructor(client, accountId) {
|
|
396
|
+
this.client = client;
|
|
397
|
+
this.accountId = accountId;
|
|
398
|
+
}
|
|
399
|
+
/** Finds the tunnel by name or makes it, then rewrites its routes only when they do not already serve the hostname. */
|
|
400
|
+
async ensureTunnel(route) {
|
|
401
|
+
const { tunnels } = this.client();
|
|
402
|
+
const found = (await tunnels.list(this.accountId)).find((t) => t.name === route.name);
|
|
403
|
+
const tunnel = found ?? await tunnels.create(this.accountId, { name: route.name });
|
|
404
|
+
const current = (await tunnels.getConfig(this.accountId, tunnel.id)).config?.ingress ?? [];
|
|
405
|
+
const wanted = withRoute(current, route.hostname, route.service);
|
|
406
|
+
const configured = JSON.stringify(wanted) !== JSON.stringify(current);
|
|
407
|
+
if (configured) await tunnels.putConfig(this.accountId, tunnel.id, { ingress: wanted });
|
|
408
|
+
return {
|
|
409
|
+
id: tunnel.id,
|
|
410
|
+
name: tunnel.name,
|
|
411
|
+
created: found === void 0,
|
|
412
|
+
configured,
|
|
413
|
+
target: `${tunnel.id}.cfargotunnel.com`
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
/** The token `cloudflared` runs the tunnel with. */
|
|
417
|
+
tunnelToken(tunnelId) {
|
|
418
|
+
return this.client().tunnels.token(this.accountId, tunnelId);
|
|
419
|
+
}
|
|
420
|
+
/** `holocron doctor` has no specific tunnel to check: lists the ones the token can see. */
|
|
421
|
+
async whoami() {
|
|
422
|
+
return {
|
|
423
|
+
ok: true,
|
|
424
|
+
tunnels: (await this.client().tunnels.list(this.accountId)).length
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
// src/capabilities/workers.ts
|
|
429
|
+
/** The Cloudflare implementation of the `workers` capability, backed by Workers scripts and routes in one account. */
|
|
190
430
|
var CloudflareWorkers = class {
|
|
191
431
|
client;
|
|
192
432
|
accountId;
|
|
433
|
+
/** The capability this class provides, always `"workers"`. */
|
|
193
434
|
key = "workers";
|
|
435
|
+
/** The provider name, `"cloudflare"`. */
|
|
194
436
|
providerName = "cloudflare";
|
|
195
437
|
zoneCache = /* @__PURE__ */ new Map();
|
|
196
438
|
constructor(client, accountId) {
|
|
@@ -203,12 +445,58 @@ var CloudflareWorkers = class {
|
|
|
203
445
|
await this.client().workers.putScript(this.accountId, scriptName, script);
|
|
204
446
|
await this.upsertRoute(`${hostname}/*`, scriptName);
|
|
205
447
|
}
|
|
448
|
+
/** `holocron doctor` has no specific script to check — lists every script the token can see instead. */
|
|
449
|
+
async whoami() {
|
|
450
|
+
return {
|
|
451
|
+
ok: true,
|
|
452
|
+
scripts: (await this.client().workers.listScripts(this.accountId)).length
|
|
453
|
+
};
|
|
454
|
+
}
|
|
206
455
|
async deployScript(name, config) {
|
|
207
456
|
await this.client().workers.putScript(this.accountId, name, config.code);
|
|
208
457
|
for (const [secretName, value] of Object.entries(config.secrets ?? {})) await this.client().workers.putSecret(this.accountId, name, secretName, value);
|
|
209
458
|
for (const pattern of config.routes ?? []) await this.upsertRoute(pattern, name);
|
|
210
459
|
return { scriptName: name };
|
|
211
460
|
}
|
|
461
|
+
async setSecret(script, name, value) {
|
|
462
|
+
await this.client().workers.putSecret(this.accountId, script, name, value);
|
|
463
|
+
}
|
|
464
|
+
async secretNames(script) {
|
|
465
|
+
return (await this.client().workers.listSecrets(this.accountId, script)).map((secret) => secret.name);
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Whether the script exists, which routes in the zone of `host` point at it, and the names of its secrets. Reads
|
|
469
|
+
* only, and asks Cloudflare for names, so no value is ever fetched.
|
|
470
|
+
*/
|
|
471
|
+
async inspectScript(name, host) {
|
|
472
|
+
const client = this.client();
|
|
473
|
+
if (!(await client.workers.listScripts(this.accountId)).some((s) => s.id === name)) return {
|
|
474
|
+
exists: false,
|
|
475
|
+
routes: [],
|
|
476
|
+
bindingNames: []
|
|
477
|
+
};
|
|
478
|
+
const zoneId = await this.resolveZone(host);
|
|
479
|
+
const routes = await client.workers.listRoutes(zoneId);
|
|
480
|
+
const secrets = await client.workers.listSecrets(this.accountId, name);
|
|
481
|
+
return {
|
|
482
|
+
exists: true,
|
|
483
|
+
routes: routes.filter((r) => r.script === name).map((r) => r.pattern),
|
|
484
|
+
bindingNames: secrets.map((secret) => secret.name)
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
/** The newest deployment of the script, and whether it serves all traffic. Reads only. */
|
|
488
|
+
async latestDeployment(script) {
|
|
489
|
+
const [newest] = [...await this.client().workers.listDeployments(this.accountId, script)].sort((a, b) => b.created_on.localeCompare(a.created_on));
|
|
490
|
+
if (!newest) return null;
|
|
491
|
+
return {
|
|
492
|
+
id: newest.id,
|
|
493
|
+
createdAt: newest.created_on,
|
|
494
|
+
active: newest.versions.length > 0 && newest.versions.some((v) => v.percentage === 100)
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
proxyScriptName(hostname) {
|
|
498
|
+
return hostnameToScriptName(hostname);
|
|
499
|
+
}
|
|
212
500
|
/** Idempotent create-or-update for one route pattern — shared by both public methods. */
|
|
213
501
|
async upsertRoute(pattern, scriptName) {
|
|
214
502
|
const hostname = pattern.split("/")[0];
|
|
@@ -251,8 +539,224 @@ function generateProxyScript(config) {
|
|
|
251
539
|
`};`
|
|
252
540
|
].join("\n");
|
|
253
541
|
}
|
|
254
|
-
|
|
255
|
-
|
|
542
|
+
// src/probes/token/parse-token-args.ts
|
|
543
|
+
/** Reads the words after the probe name: `--layer <word>`, `--token-name <VAR>` and any number of zone names. */
|
|
544
|
+
function parseTokenArgs(args) {
|
|
545
|
+
const zones = [];
|
|
546
|
+
let layer;
|
|
547
|
+
let tokenName;
|
|
548
|
+
for (let i = 0; i < args.length; i++) {
|
|
549
|
+
const arg = args[i];
|
|
550
|
+
if (arg === "--layer") layer = args[++i];
|
|
551
|
+
else if (arg.startsWith("--layer=")) layer = arg.slice(8);
|
|
552
|
+
else if (arg === "--token-name") tokenName = args[++i];
|
|
553
|
+
else if (arg.startsWith("--token-name=")) tokenName = arg.slice(13);
|
|
554
|
+
else if (!arg.startsWith("--")) zones.push(arg);
|
|
555
|
+
}
|
|
556
|
+
return {
|
|
557
|
+
...layer ? { layer } : {},
|
|
558
|
+
...tokenName ? { tokenName } : {},
|
|
559
|
+
zones
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
// src/probes/token/token.ts
|
|
563
|
+
/** The most zones whose DNS and Workers routes are read, so a token that sees many does not make many requests. */
|
|
564
|
+
const MAX_ZONES = 5;
|
|
565
|
+
/** How many names to show before "(+N more)". */
|
|
566
|
+
const SHOWN = 5;
|
|
567
|
+
/** `a, b, c (+2 more)`. */
|
|
568
|
+
function summarise(names) {
|
|
569
|
+
return names.length <= SHOWN ? names.join(", ") : `${names.slice(0, SHOWN).join(", ")} (+${names.length - SHOWN} more)`;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Reads one list and says what came back. Cloudflare answers a token without the permission in one of two ways (a 401 or
|
|
573
|
+
* 403, or an empty list), so an empty list is `none`: the token cannot see any, or there are none. A request that fails
|
|
574
|
+
* for another reason (the network, a 5xx) is an `error`.
|
|
575
|
+
*/
|
|
576
|
+
async function reach(read, noun) {
|
|
577
|
+
try {
|
|
578
|
+
const items = await read();
|
|
579
|
+
if (items.length === 0) return {
|
|
580
|
+
kind: "none",
|
|
581
|
+
detail: `no ${noun} visible (none exist, or the token cannot see them)`
|
|
582
|
+
};
|
|
583
|
+
const names = items.map((i) => i.name).filter((n) => typeof n === "string");
|
|
584
|
+
return {
|
|
585
|
+
kind: "has",
|
|
586
|
+
detail: names.length > 0 ? `${items.length} ${noun}: ${summarise(names)}` : `${items.length} ${noun}`
|
|
587
|
+
};
|
|
588
|
+
} catch (err) {
|
|
589
|
+
if (err instanceof ProviderApiError && (err.status === 401 || err.status === 403)) return {
|
|
590
|
+
kind: "none",
|
|
591
|
+
detail: `no access (${err.status})`
|
|
592
|
+
};
|
|
593
|
+
return {
|
|
594
|
+
kind: "error",
|
|
595
|
+
detail: errorMessage(err)
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
/**
|
|
600
|
+
* One row for what was tried. With no rule it only describes (`ok` for access, `info` for none). Under a layer's rule it
|
|
601
|
+
* judges: a required permission the token lacks fails, and one the layer must not have fails when the token has it; a
|
|
602
|
+
* permission that is rightly absent is a bare `ok`.
|
|
603
|
+
*/
|
|
604
|
+
function rowFor({ label, outcome }, rule) {
|
|
605
|
+
if (outcome.kind === "error") return {
|
|
606
|
+
status: "fail",
|
|
607
|
+
label,
|
|
608
|
+
detail: outcome.detail
|
|
609
|
+
};
|
|
610
|
+
const has = outcome.kind === "has";
|
|
611
|
+
if (rule === "required") return has ? {
|
|
612
|
+
status: "ok",
|
|
613
|
+
label,
|
|
614
|
+
detail: outcome.detail
|
|
615
|
+
} : {
|
|
616
|
+
status: "fail",
|
|
617
|
+
label,
|
|
618
|
+
detail: outcome.detail
|
|
619
|
+
};
|
|
620
|
+
if (rule === "absent") return has ? {
|
|
621
|
+
status: "fail",
|
|
622
|
+
label,
|
|
623
|
+
detail: outcome.detail
|
|
624
|
+
} : {
|
|
625
|
+
status: "ok",
|
|
626
|
+
label
|
|
627
|
+
};
|
|
628
|
+
return {
|
|
629
|
+
status: has ? "ok" : "info",
|
|
630
|
+
label,
|
|
631
|
+
detail: outcome.detail
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* The `token` probe: tries each permission Holocron uses with the Cloudflare API token and reports which ones the token
|
|
636
|
+
* has. It only reads (a list per permission), so it changes nothing. The token is the one the plugin resolves, so
|
|
637
|
+
* `--token cloudflare=<token>` or `--environment <layer>` checks another one; the account id is the plugin's own.
|
|
638
|
+
*
|
|
639
|
+
* A token with no layer is only described. When the CLI passes `--layer` (because `--environment` named `ci`, `dev` or
|
|
640
|
+
* `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
|
|
641
|
+
* two groups, what it should have and what it should not, where a missing or extra permission fails. The other words
|
|
642
|
+
* limit the zone checks to those zones; otherwise up to five are read. How the token is chosen is in `holocron probe --help`.
|
|
643
|
+
*/
|
|
644
|
+
function tokenProbe(ctx) {
|
|
645
|
+
return {
|
|
646
|
+
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.",
|
|
647
|
+
writes: false,
|
|
648
|
+
acceptsToken: true,
|
|
649
|
+
async run(probe) {
|
|
650
|
+
const token = ctx.token();
|
|
651
|
+
probe.secret(token);
|
|
652
|
+
const client = ctx.client();
|
|
653
|
+
const { layer, tokenName, zones: wanted } = parseTokenArgs(probe.args ?? []);
|
|
654
|
+
const expectation = layer ? tokenExpectations(tokens, {
|
|
655
|
+
layer,
|
|
656
|
+
...tokenName ? { envName: tokenName } : {}
|
|
657
|
+
})[0] : void 0;
|
|
658
|
+
const rules = expectation?.rules;
|
|
659
|
+
if (layer && !rules) probe.say({
|
|
660
|
+
status: "info",
|
|
661
|
+
label: layer,
|
|
662
|
+
detail: "no expectations are declared for it, so the token is only described"
|
|
663
|
+
});
|
|
664
|
+
const now = (ctx.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
665
|
+
const rotation = expectation?.rotation ?? DEFAULT_TOKEN_ROTATION;
|
|
666
|
+
let lifetime;
|
|
667
|
+
try {
|
|
668
|
+
const verified = await client.tokens.verify();
|
|
669
|
+
probe.say({
|
|
670
|
+
status: "ok",
|
|
671
|
+
label: "token",
|
|
672
|
+
detail: `${verified.id} (${verified.status})`
|
|
673
|
+
});
|
|
674
|
+
lifetime = {
|
|
675
|
+
...verified.not_before ? { createdAt: verified.not_before } : {},
|
|
676
|
+
...verified.expires_on ? { expiresAt: verified.expires_on } : {}
|
|
677
|
+
};
|
|
678
|
+
} catch {}
|
|
679
|
+
const rotationRows = tokenRotationRows(lifetime, rotation, now);
|
|
680
|
+
const sayRotation = () => {
|
|
681
|
+
probe.say({
|
|
682
|
+
status: "heading",
|
|
683
|
+
label: "Rotation"
|
|
684
|
+
});
|
|
685
|
+
for (const row of rotationRows) probe.say(row);
|
|
686
|
+
};
|
|
687
|
+
const named = wanted.length > 0 ? wanted : ctx.options.zone ? [ctx.options.zone] : [];
|
|
688
|
+
const tried = [];
|
|
689
|
+
let zones = [];
|
|
690
|
+
const zoneOutcome = await reach(async () => {
|
|
691
|
+
zones = named.length > 0 ? (await Promise.all(named.map((name) => client.zones.list({ name })))).flat() : await client.zones.list({ per_page: MAX_ZONES });
|
|
692
|
+
return zones.map((z) => ({ name: z.name }));
|
|
693
|
+
}, "zones");
|
|
694
|
+
tried.push({
|
|
695
|
+
label: "Zone: Read",
|
|
696
|
+
permission: "zone",
|
|
697
|
+
outcome: zoneOutcome
|
|
698
|
+
});
|
|
699
|
+
if (zoneOutcome.kind !== "error") {
|
|
700
|
+
for (const zone of zones.slice(0, MAX_ZONES)) {
|
|
701
|
+
tried.push({
|
|
702
|
+
label: `DNS: Edit (${zone.name})`,
|
|
703
|
+
permission: "dns",
|
|
704
|
+
outcome: await reach(() => client.dns.list(zone.id), "records")
|
|
705
|
+
});
|
|
706
|
+
tried.push({
|
|
707
|
+
label: `Workers Routes: Edit (${zone.name})`,
|
|
708
|
+
permission: "routes",
|
|
709
|
+
outcome: await reach(async () => (await client.workers.listRoutes(zone.id)).map((r) => ({ name: r.pattern })), "routes")
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
const account = ctx.options.accountId;
|
|
713
|
+
if (account) {
|
|
714
|
+
tried.push({
|
|
715
|
+
label: "Workers Scripts: Edit",
|
|
716
|
+
permission: "scripts",
|
|
717
|
+
outcome: await reach(async () => (await client.workers.listScripts(account)).map((s) => ({ name: s.id })), "scripts")
|
|
718
|
+
});
|
|
719
|
+
tried.push({
|
|
720
|
+
label: "Pages: Edit",
|
|
721
|
+
permission: "pages",
|
|
722
|
+
outcome: await reach(() => client.pages.listProjects(account), "projects")
|
|
723
|
+
});
|
|
724
|
+
tried.push({
|
|
725
|
+
label: "Cloudflare Tunnel: Edit",
|
|
726
|
+
permission: "tunnels",
|
|
727
|
+
outcome: await reach(() => client.tunnels.list(account), "tunnels")
|
|
728
|
+
});
|
|
729
|
+
tried.push({
|
|
730
|
+
label: "Notifications: Edit",
|
|
731
|
+
permission: "notifications",
|
|
732
|
+
outcome: await reach(async () => (await client.alerting.webhooks.list(account)).map((w) => ({ name: w.name })), "notification webhooks")
|
|
733
|
+
});
|
|
734
|
+
} else probe.say({
|
|
735
|
+
status: rules ? "fail" : "info",
|
|
736
|
+
label: "account permissions",
|
|
737
|
+
detail: "no account id: set HOLOCRON_CLOUDFLARE_ACCOUNT_ID or the plugin's accountId option to check them"
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
if (!rules) {
|
|
741
|
+
for (const t of tried) probe.say(rowFor(t, void 0));
|
|
742
|
+
sayRotation();
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
for (const [heading, rule] of [["Should have", "required"], ["Should not have", "absent"]]) {
|
|
746
|
+
const inGroup = tried.filter((t) => rules[t.permission] === rule);
|
|
747
|
+
if (inGroup.length === 0) continue;
|
|
748
|
+
probe.say({
|
|
749
|
+
status: "heading",
|
|
750
|
+
label: heading
|
|
751
|
+
});
|
|
752
|
+
for (const t of inGroup) probe.say(rowFor(t, rule));
|
|
753
|
+
}
|
|
754
|
+
sayRotation();
|
|
755
|
+
}
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
// src/verify-token.ts
|
|
759
|
+
/** 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
760
|
async function verifyToken(token, opts = {}) {
|
|
257
761
|
const client = createCloudflareClient({
|
|
258
762
|
token,
|
|
@@ -267,21 +771,26 @@ async function verifyToken(token, opts = {}) {
|
|
|
267
771
|
};
|
|
268
772
|
} catch {}
|
|
269
773
|
try {
|
|
774
|
+
const names = (await client.zones.list()).map((z) => z.name);
|
|
775
|
+
if (names.length === 0) return {
|
|
776
|
+
ok: true,
|
|
777
|
+
subject: "no zones visible"
|
|
778
|
+
};
|
|
270
779
|
return {
|
|
271
780
|
ok: true,
|
|
272
|
-
subject: `
|
|
781
|
+
subject: `zones: ${names.length <= 5 ? names.join(", ") : `${names.slice(0, 5).join(", ")} (+${names.length - 5} more)`}`
|
|
273
782
|
};
|
|
274
783
|
} catch (err) {
|
|
275
784
|
return {
|
|
276
785
|
ok: false,
|
|
277
|
-
message:
|
|
786
|
+
message: errorMessage(err)
|
|
278
787
|
};
|
|
279
788
|
}
|
|
280
789
|
}
|
|
281
|
-
|
|
282
|
-
|
|
790
|
+
// src/index.ts
|
|
791
|
+
/** Builds the plugin context from its options; the API token is resolved lazily on the first client use. */
|
|
283
792
|
function createContext(options = {}) {
|
|
284
|
-
const accountId = options.accountId ??
|
|
793
|
+
const accountId = options.accountId ?? resolveValue(["CLOUDFLARE_ACCOUNT_ID"], options.env, { prefix: PREFIX });
|
|
285
794
|
const opts = {
|
|
286
795
|
...options,
|
|
287
796
|
accountId
|
|
@@ -299,30 +808,53 @@ function createContext(options = {}) {
|
|
|
299
808
|
})
|
|
300
809
|
};
|
|
301
810
|
}
|
|
811
|
+
/** Builds the `dns` capability for a context. */
|
|
302
812
|
function dns(ctx) {
|
|
303
|
-
return new CloudflareDns(ctx.client);
|
|
813
|
+
return new CloudflareDns(ctx.client, ctx.options.accountId);
|
|
304
814
|
}
|
|
815
|
+
/** Builds the `deployment` capability for a context; throws when no account id is set. */
|
|
305
816
|
function deployment(ctx) {
|
|
306
817
|
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
818
|
return new CloudflareDeployment(ctx.client, ctx.options.accountId);
|
|
308
819
|
}
|
|
820
|
+
/** Builds the `workers` capability for a context; throws when no account id is set. */
|
|
309
821
|
function workersCapability(ctx) {
|
|
310
822
|
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
823
|
return new CloudflareWorkers(ctx.client, ctx.options.accountId);
|
|
312
824
|
}
|
|
825
|
+
/** Builds the `tunnels` capability for a context; throws when no account id is set. */
|
|
826
|
+
function tunnelsCapability(ctx) {
|
|
827
|
+
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");
|
|
828
|
+
return new CloudflareTunnels(ctx.client, ctx.options.accountId);
|
|
829
|
+
}
|
|
830
|
+
/** Creates the Cloudflare plugin: `dns` always, plus `deployment`, `workers` and `tunnels` when an account id is set, and the `connection` and `token` probes. */
|
|
313
831
|
function createPlugin(options = {}) {
|
|
314
832
|
const ctx = createContext(options);
|
|
315
833
|
return {
|
|
316
834
|
name: "@theholocron/holocron-plugin-cloudflare",
|
|
835
|
+
probes: {
|
|
836
|
+
token: tokenProbe(ctx),
|
|
837
|
+
connection: connectionProbe({
|
|
838
|
+
provider: "Cloudflare",
|
|
839
|
+
url: options.baseUrl ?? "https://api.cloudflare.com",
|
|
840
|
+
fetch: options.fetch,
|
|
841
|
+
token: () => resolveToken(options),
|
|
842
|
+
verify: (token) => verifyToken(token, {
|
|
843
|
+
baseUrl: options.baseUrl,
|
|
844
|
+
fetch: options.fetch
|
|
845
|
+
})
|
|
846
|
+
})
|
|
847
|
+
},
|
|
317
848
|
capabilities: {
|
|
318
849
|
dns: () => dns(ctx),
|
|
319
850
|
...ctx.options.accountId ? {
|
|
320
851
|
deployment: () => deployment(ctx),
|
|
321
|
-
workers: () => workersCapability(ctx)
|
|
852
|
+
workers: () => workersCapability(ctx),
|
|
853
|
+
tunnels: () => tunnelsCapability(ctx)
|
|
322
854
|
} : {}
|
|
323
855
|
}
|
|
324
856
|
};
|
|
325
857
|
}
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
export { AUTH_HINT, AuthError, CloudflareDeployment, CloudflareDns, CloudflareWorkers, createCloudflareClient, createContext, createPlugin, deployment, dns, resolveToken, verifyToken, workersCapability };
|
|
858
|
+
/** One-line hint printed by `holocron new token cloudflare` when no token is supplied or the supplied one is rejected. */
|
|
859
|
+
const AUTH_HINT = "create an API token at https://dash.cloudflare.com/profile/api-tokens with Zone:Read, DNS:Edit, Cloudflare Pages:Edit, Workers Scripts:Edit (account-level), Workers Routes:Edit (zone-level) and, for tunnels, Cloudflare Tunnel:Edit and, for relay sources, Notifications:Edit (account-level) permissions, then run: holocron new token cloudflare <TOKEN>";
|
|
860
|
+
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.521",
|
|
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,29 +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.25.0",
|
|
34
|
-
"@theholocron/eslint-config": "^8.4.5",
|
|
35
|
-
"@theholocron/http-client": "^1.25.0",
|
|
36
|
-
"@theholocron/tsconfig": "^8.4.5",
|
|
37
|
-
"@theholocron/tsdown-config": "^8.4.5",
|
|
38
|
-
"@theholocron/vitest-config": "^8.4.5",
|
|
39
36
|
"@types/node": "^26",
|
|
40
|
-
"@vitest/coverage-v8": "^
|
|
41
|
-
"@vitest/eslint-plugin": "^1.6.
|
|
42
|
-
"chalk": "^6.0.
|
|
43
|
-
"eslint": "^10.
|
|
44
|
-
"eslint-plugin-n": "^18.
|
|
45
|
-
"globals": "^17.
|
|
46
|
-
"tsdown": "^0.
|
|
47
|
-
"tsx": "4.23.
|
|
48
|
-
"typescript": "^
|
|
49
|
-
"vitest": "^
|
|
50
|
-
"@theholocron/
|
|
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",
|
|
45
|
+
"typescript": "^6.0.3",
|
|
46
|
+
"vitest": "^5.1.0",
|
|
47
|
+
"@theholocron/cloudflare-client": "^1.58.0-alpha.53",
|
|
48
|
+
"@theholocron/eslint-config": "^8.9.0-alpha.22",
|
|
49
|
+
"@theholocron/cli": "5.0.0-alpha.521",
|
|
50
|
+
"@theholocron/http-client": "^1.58.0-alpha.53",
|
|
51
|
+
"@theholocron/misc-utils": "^1.17.0-alpha.5",
|
|
52
|
+
"@theholocron/tsconfig": "^8.9.0-alpha.22",
|
|
53
|
+
"@theholocron/kyber": "5.0.0-alpha.521",
|
|
54
|
+
"@theholocron/tsdown-config": "^8.9.0-alpha.22",
|
|
55
|
+
"@theholocron/vitest-config": "^8.9.0-alpha.22"
|
|
51
56
|
},
|
|
52
57
|
"peerDependencies": {
|
|
53
|
-
"@theholocron/cloudflare-client": "^1.
|
|
54
|
-
"@theholocron/
|
|
58
|
+
"@theholocron/cloudflare-client": "^1.53.1",
|
|
59
|
+
"@theholocron/misc-utils": "^1.16.0",
|
|
60
|
+
"@theholocron/cli": "5.0.0-alpha.521"
|
|
55
61
|
},
|
|
56
62
|
"peerDependenciesMeta": {
|
|
57
63
|
"@theholocron/cloudflare-client": {}
|
|
@@ -63,11 +69,11 @@
|
|
|
63
69
|
"access": "public"
|
|
64
70
|
},
|
|
65
71
|
"scripts": {
|
|
66
|
-
"
|
|
67
|
-
"
|
|
72
|
+
"build": "tsdown",
|
|
73
|
+
"lint:code": "eslint .",
|
|
74
|
+
"test:unit": "vitest run --coverage",
|
|
68
75
|
"test:watch": "vitest",
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"verification.unitTests": "holocron run verification.unitTests --"
|
|
76
|
+
"typecheck": "tsc --noEmit",
|
|
77
|
+
"validate:plugin": "tsx scripts/validate.mjs"
|
|
72
78
|
}
|
|
73
79
|
}
|