@zabaca/zbc 0.25.0 → 0.27.0
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/CHANGELOG.md +114 -0
- package/package.json +1 -1
- package/src/commands/init.ts +105 -10
- package/src/commands/secret.ts +1 -66
- package/src/commands/update.ts +77 -7
- package/src/engine/actions.ts +35 -3
- package/src/engine/on-demand.ts +9 -1
- package/src/engine/secret-outputs.ts +15 -0
- package/src/engine/secrets.ts +81 -1
- package/src/utils/copy-refresh.ts +124 -19
- package/src/utils/detect-mode.ts +1 -1
- package/src/utils/host-workspaces.ts +57 -0
- package/src/utils/subtree.ts +54 -15
- package/src/utils/template-history.ts +66 -0
- package/src/utils/vendor-audit.ts +12 -8
- package/src/utils/vendor-stamp.ts +10 -0
- package/src/utils/vendored-app.ts +3 -0
- package/templates/apps/walgit/CONTEXT.md +45 -4
- package/templates/apps/walgit/README.md +394 -11
- package/templates/apps/walgit/shared/browse.ts +61 -0
- package/templates/apps/walgit/shared/capabilities.ts +26 -0
- package/templates/apps/walgit/shared/container-env.ts +12 -0
- package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
- package/templates/apps/walgit/shared/credentials.ts +4 -0
- package/templates/apps/walgit/shared/events.ts +35 -1
- package/templates/apps/walgit/shared/instructions.ts +4 -1
- package/templates/apps/walgit/shared/landing.ts +2 -1
- package/templates/apps/walgit/shared/llms.ts +73 -5
- package/templates/apps/walgit/shared/mcp.ts +19 -3
- package/templates/apps/walgit/shared/protocol.ts +40 -3
- package/templates/apps/walgit/shared/repo-list.ts +46 -6
- package/templates/apps/walgit/shared/scoped-token.ts +500 -0
- package/templates/apps/walgit/shared/token-revocation.ts +134 -0
- package/templates/apps/walgit/shared/wal-index.ts +19 -0
- package/templates/apps/walgit/shared/webhook.ts +281 -0
- package/templates/apps/walgit/src/admin.ts +510 -0
- package/templates/apps/walgit/src/announce-main.ts +17 -9
- package/templates/apps/walgit/src/announce.ts +86 -0
- package/templates/apps/walgit/src/browse.ts +255 -2
- package/templates/apps/walgit/src/cli.ts +140 -0
- package/templates/apps/walgit/src/expire.ts +5 -0
- package/templates/apps/walgit/src/git.ts +103 -0
- package/templates/apps/walgit/src/hook-main.ts +6 -3
- package/templates/apps/walgit/src/http.ts +563 -3
- package/templates/apps/walgit/src/limits.ts +3 -0
- package/templates/apps/walgit/src/merge.ts +525 -0
- package/templates/apps/walgit/src/rate-limit.ts +51 -14
- package/templates/apps/walgit/src/server.ts +65 -1
- package/templates/apps/walgit/worker/events-do.ts +218 -3
- package/templates/apps/walgit/worker/index.ts +134 -9
- package/templates/apps/walgit/worker/mcp.ts +17 -2
- package/templates/history.json +1 -0
- package/templates/infra/modules/cloudflare/index.ts +140 -1
- package/templates/infra/modules/cloudflare-access/index.ts +176 -65
- package/templates/infra/modules/cloudflare-access/registry.json +1 -1
- package/templates/infra/modules/cloudflare-api/index.ts +56 -0
- package/templates/infra/modules/cloudflare-email/index.ts +44 -17
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
- package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
- package/templates/infra/modules/cloudflare-token/index.ts +46 -17
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
- package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
- package/templates/infra/modules/d1/index.ts +37 -35
- package/templates/infra/modules/d1/registry.json +1 -1
- package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
- package/templates/infra/modules/queue/index.ts +28 -18
- package/templates/infra/modules/queue/registry.json +1 -1
- package/templates/infra/modules/r2/index.ts +20 -11
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/src/context.ts +41 -0
- package/templates/infra/src/testing.ts +19 -1
- package/templates/infra/src/types.ts +23 -0
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
3
|
import type { ApplyContext } from '../../src/types'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type ApiTokenSource,
|
|
6
|
+
apiTokenFor,
|
|
7
|
+
apiTokenSchema,
|
|
8
|
+
CfError,
|
|
9
|
+
cf,
|
|
10
|
+
type CfOptions,
|
|
11
|
+
tokenScopeHint,
|
|
12
|
+
} from '../cloudflare-api'
|
|
5
13
|
|
|
6
14
|
/**
|
|
7
15
|
* cloudflare-email — provisions Cloudflare Email Service (public beta) for a
|
|
@@ -34,20 +42,20 @@ import { CfError, cf, type CfOptions } from '../cloudflare-api'
|
|
|
34
42
|
* exists. Everything else about the envelope (the base URL, the error shapes,
|
|
35
43
|
* the non-JSON guard, the typed throw) is `../cloudflare-api`'s.
|
|
36
44
|
*/
|
|
37
|
-
const
|
|
45
|
+
const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
|
|
38
46
|
hints: {
|
|
39
|
-
10000:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
10000: tokenScopeHint(
|
|
48
|
+
source,
|
|
49
|
+
'a scope — it needs: ' +
|
|
50
|
+
'Zone → Email Routing Rules: Edit, Zone → Zone Settings: Edit (the routing ' +
|
|
51
|
+
'enable/settings/DNS endpoints live under generic Zone Settings), Zone → DNS: Edit, ' +
|
|
52
|
+
'Account → Email Sending: Edit, Account → Email Routing Addresses: Edit',
|
|
53
|
+
),
|
|
46
54
|
10105:
|
|
47
55
|
`failed: the account is not entitled to Email Sending (10105). ` +
|
|
48
56
|
`Email Sending requires a Workers Paid plan — upgrade the account, then re-run zbc apply.`,
|
|
49
57
|
},
|
|
50
|
-
}
|
|
58
|
+
})
|
|
51
59
|
|
|
52
60
|
/**
|
|
53
61
|
* A worker name: either a literal script name, or a `{ from, output }`
|
|
@@ -135,6 +143,7 @@ async function ensureDestinationVerified(
|
|
|
135
143
|
token: string,
|
|
136
144
|
accountId: string,
|
|
137
145
|
email: string,
|
|
146
|
+
OPTS: CfOptions,
|
|
138
147
|
): Promise<void> {
|
|
139
148
|
const addresses = await cf<Array<{ email: string; verified?: string | null }>>(
|
|
140
149
|
token,
|
|
@@ -211,13 +220,27 @@ export function classifySendingDns(readings: SendingDnsReading[]): SendingDnsVer
|
|
|
211
220
|
}
|
|
212
221
|
}
|
|
213
222
|
|
|
223
|
+
/** The zone id: the literal, or the imported instance's output a reference names. */
|
|
224
|
+
function zoneIdFor(
|
|
225
|
+
zoneId: string | { from: string; output: string },
|
|
226
|
+
ctx: Pick<ApplyContext, 'output'>,
|
|
227
|
+
): string {
|
|
228
|
+
return typeof zoneId === 'string' ? zoneId : ctx.output(zoneId, 'zoneId')
|
|
229
|
+
}
|
|
230
|
+
|
|
214
231
|
export const cloudflareEmailModule = defineModule({
|
|
215
232
|
name: 'cloudflare-email',
|
|
216
233
|
configSchema: z.object({
|
|
217
234
|
/** Cloudflare account id (dashboard URL — not a secret). */
|
|
218
235
|
accountId: z.string(),
|
|
219
|
-
/**
|
|
220
|
-
|
|
236
|
+
/** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
|
|
237
|
+
apiToken: apiTokenSchema.optional(),
|
|
238
|
+
/**
|
|
239
|
+
* Zone id of the apex zone (e.g. cedarpad.com's zone): the id itself, or
|
|
240
|
+
* `{ from, output }` into an imported `cloudflare-zone` instance's `zoneId`,
|
|
241
|
+
* so a zone this environment creates is not pasted back in by hand.
|
|
242
|
+
*/
|
|
243
|
+
zoneId: z.union([z.string(), z.object({ from: z.string(), output: z.string() })]),
|
|
221
244
|
/** Email domain — the zone apex or a subdomain of it (e.g. mail.cedarpad.com). */
|
|
222
245
|
domain: z.string(),
|
|
223
246
|
/** Onboard the domain for outbound sending (SPF/DKIM/DMARC/bounce-MX). */
|
|
@@ -240,9 +263,11 @@ export const cloudflareEmailModule = defineModule({
|
|
|
240
263
|
domain: z.string(),
|
|
241
264
|
}),
|
|
242
265
|
async apply(config, ctx) {
|
|
243
|
-
const token = ctx
|
|
266
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
267
|
+
const OPTS = optsFor(config.apiToken)
|
|
244
268
|
|
|
245
|
-
const { accountId,
|
|
269
|
+
const { accountId, domain } = config
|
|
270
|
+
const zoneId = zoneIdFor(config.zoneId, ctx)
|
|
246
271
|
const dnsStatus: Record<string, string> = {}
|
|
247
272
|
let sendingEnabled = false
|
|
248
273
|
let routingEnabled = false
|
|
@@ -378,7 +403,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
378
403
|
forwardTargets.add(config.catchAll.destination)
|
|
379
404
|
}
|
|
380
405
|
for (const dest of forwardTargets) {
|
|
381
|
-
await ensureDestinationVerified(token, accountId, dest)
|
|
406
|
+
await ensureDestinationVerified(token, accountId, dest, OPTS)
|
|
382
407
|
}
|
|
383
408
|
|
|
384
409
|
// Upsert literal rules for each address.
|
|
@@ -450,8 +475,10 @@ export const cloudflareEmailModule = defineModule({
|
|
|
450
475
|
}
|
|
451
476
|
},
|
|
452
477
|
async destroy(config, ctx) {
|
|
453
|
-
const token = ctx
|
|
454
|
-
const
|
|
478
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
479
|
+
const OPTS = optsFor(config.apiToken)
|
|
480
|
+
const { domain } = config
|
|
481
|
+
const zoneId = zoneIdFor(config.zoneId, ctx)
|
|
455
482
|
|
|
456
483
|
console.log(` ⚠ DESTROYING email config for ${domain} — mail for this domain WILL STOP.`)
|
|
457
484
|
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
10
10
|
"signupUrl": "https://dash.cloudflare.com",
|
|
11
11
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
12
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run."
|
|
12
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Set `apiToken` to take the token from elsewhere: `{ from, output }` for an imported instance's output (a `cloudflare-token`'s `tokenValue`), or `{ secret }` for another key of secrets.yaml. `zoneId` is the id itself or `{ from, output }` into an imported `cloudflare-zone` instance's `zoneId`. Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run."
|
|
13
13
|
}
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { defineModule } from '../../src/define-module'
|
|
3
|
+
import type { ApplyContext } from '../../src/types'
|
|
4
|
+
import { cf } from '../cloudflare-api'
|
|
5
|
+
import {
|
|
6
|
+
buildPolicies as buildScopedPolicies,
|
|
7
|
+
deriveS3Credentials,
|
|
8
|
+
type PermissionGroup,
|
|
9
|
+
} from '../cloudflare-token'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* cloudflare-stored-token — a Cloudflare API token minted ONCE and kept in
|
|
13
|
+
* secrets.yaml, for a holder that is not an apply.
|
|
14
|
+
*
|
|
15
|
+
* `cloudflare-token` rolls its value on every apply and keeps none of them,
|
|
16
|
+
* which is right when the apply itself is the only user: a value that lives in
|
|
17
|
+
* memory cannot go stale in a file. It is wrong for a token something else
|
|
18
|
+
* holds: a laptop, a job in another repository, a reader that must keep
|
|
19
|
+
* working between applies. Rolling it there is an outage. Two projects each
|
|
20
|
+
* wrote this module for that case, both shelling out to `sops` because a
|
|
21
|
+
* module had no way to store a secret.
|
|
22
|
+
*
|
|
23
|
+
* So the two halves are split (ADR-0023):
|
|
24
|
+
*
|
|
25
|
+
* - `zbc run <env> <instance> mint` creates the token and stores it.
|
|
26
|
+
* - `zbc run <env> <instance> rotate --yes` re-applies the policies and rolls
|
|
27
|
+
* the value; what was stored stops working at once.
|
|
28
|
+
* - `apply` creates and rolls nothing. It reads the stored keys and proves
|
|
29
|
+
* they still work, so a token revoked in the dashboard is found on an apply
|
|
30
|
+
* and not by its holder.
|
|
31
|
+
*
|
|
32
|
+
* It emits no credential. A holder reads the keys `store` names.
|
|
33
|
+
*
|
|
34
|
+
* Minting needs a root token (an account-owned token with "Account API Tokens
|
|
35
|
+
* Write"), read from `rootTokenSecret` in secrets.yaml or, failing that, from
|
|
36
|
+
* an environment variable of the same name. The second exists so the root can
|
|
37
|
+
* stay out of an environment whose other readers should not hold it: `apply`
|
|
38
|
+
* never needs it.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
interface Policy {
|
|
42
|
+
effect: 'allow'
|
|
43
|
+
permission_groups: Array<{ id: string }>
|
|
44
|
+
resources: Record<string, unknown>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const BUCKET_RESOURCE = (accountId: string, bucket: string) =>
|
|
48
|
+
`com.cloudflare.edge.r2.bucket.${accountId}_default_${bucket}`
|
|
49
|
+
|
|
50
|
+
const configSchema = z
|
|
51
|
+
.object({
|
|
52
|
+
/** Cloudflare account id (not a secret). */
|
|
53
|
+
accountId: z.string(),
|
|
54
|
+
/** The token's name in the account: the converge identity. */
|
|
55
|
+
tokenName: z.string().min(1),
|
|
56
|
+
/**
|
|
57
|
+
* Permission-group NAMES granted on the account (or, for zone-scoped
|
|
58
|
+
* groups, on `zoneIds`, else every zone), as `cloudflare-token` takes them.
|
|
59
|
+
*/
|
|
60
|
+
permissions: z.array(z.string()).default([]),
|
|
61
|
+
/** Zone ids that zone-scoped `permissions` are restricted to. */
|
|
62
|
+
zoneIds: z.array(z.string()).default([]),
|
|
63
|
+
/**
|
|
64
|
+
* Permission groups granted on named R2 buckets and nothing else: a reader
|
|
65
|
+
* of one bucket should not be able to list the account's others.
|
|
66
|
+
*/
|
|
67
|
+
buckets: z
|
|
68
|
+
.object({
|
|
69
|
+
names: z.array(z.string()).nonempty(),
|
|
70
|
+
permissions: z.array(z.string()).nonempty(),
|
|
71
|
+
})
|
|
72
|
+
.optional(),
|
|
73
|
+
/**
|
|
74
|
+
* The secrets.yaml keys the token is kept under. Store the value, or the
|
|
75
|
+
* pair of S3 keys R2 derives from it (access key = token id, secret =
|
|
76
|
+
* sha256 of the value), or all three.
|
|
77
|
+
*/
|
|
78
|
+
store: z
|
|
79
|
+
.object({
|
|
80
|
+
tokenValue: z.string().min(1).optional(),
|
|
81
|
+
s3AccessKeyId: z.string().min(1).optional(),
|
|
82
|
+
s3SecretAccessKey: z.string().min(1).optional(),
|
|
83
|
+
})
|
|
84
|
+
.refine(
|
|
85
|
+
(s) => Boolean(s.tokenValue) || Boolean(s.s3AccessKeyId && s.s3SecretAccessKey),
|
|
86
|
+
'store the token value, or both S3 keys',
|
|
87
|
+
),
|
|
88
|
+
/** The key holding the root token that mints. Read by the actions only. */
|
|
89
|
+
rootTokenSecret: z.string().default('CLOUDFLARE_ROOT_TOKEN'),
|
|
90
|
+
})
|
|
91
|
+
.superRefine((config, ctx) => {
|
|
92
|
+
if (config.permissions.length === 0 && config.buckets === undefined) {
|
|
93
|
+
ctx.addIssue({
|
|
94
|
+
code: z.ZodIssueCode.custom,
|
|
95
|
+
path: ['permissions'],
|
|
96
|
+
message: 'a token with no permissions and no buckets can do nothing: declare one of them',
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
if (!config.store.tokenValue && config.buckets === undefined) {
|
|
100
|
+
ctx.addIssue({
|
|
101
|
+
code: z.ZodIssueCode.custom,
|
|
102
|
+
path: ['store'],
|
|
103
|
+
message:
|
|
104
|
+
'storing only the S3 keys leaves apply nothing to check them against: declare `buckets`, or store `tokenValue` too',
|
|
105
|
+
})
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
type Config = z.infer<typeof configSchema>
|
|
109
|
+
|
|
110
|
+
/** The account, zone and bucket policies the declaration asks for. Pure; exported for tests. */
|
|
111
|
+
export function buildPolicies(config: Config, available: PermissionGroup[]): Policy[] {
|
|
112
|
+
const resolve = (name: string): PermissionGroup[] => {
|
|
113
|
+
const matches = available.filter((g) => g.name === name)
|
|
114
|
+
if (matches.length === 0) {
|
|
115
|
+
throw new Error(
|
|
116
|
+
`Permission group "${name}" not found. Available: ${available.map((g) => g.name).join(', ')}`,
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
return matches
|
|
120
|
+
}
|
|
121
|
+
const policies: Policy[] = buildScopedPolicies(
|
|
122
|
+
config.accountId,
|
|
123
|
+
config.permissions.flatMap(resolve),
|
|
124
|
+
config.zoneIds,
|
|
125
|
+
)
|
|
126
|
+
if (config.buckets) {
|
|
127
|
+
policies.push({
|
|
128
|
+
effect: 'allow',
|
|
129
|
+
permission_groups: config.buckets.permissions.flatMap(resolve).map((g) => ({ id: g.id })),
|
|
130
|
+
resources: Object.fromEntries(
|
|
131
|
+
config.buckets.names.map((b) => [BUCKET_RESOURCE(config.accountId, b), '*']),
|
|
132
|
+
),
|
|
133
|
+
})
|
|
134
|
+
}
|
|
135
|
+
return policies
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** What goes into secrets.yaml for one token id and value. Pure; exported for tests. */
|
|
139
|
+
export function storedValues(
|
|
140
|
+
config: Config,
|
|
141
|
+
tokenId: string,
|
|
142
|
+
tokenValue: string,
|
|
143
|
+
): Record<string, string> {
|
|
144
|
+
const s3 = deriveS3Credentials(tokenId, tokenValue)
|
|
145
|
+
const out: Record<string, string> = {}
|
|
146
|
+
if (config.store.tokenValue) out[config.store.tokenValue] = tokenValue
|
|
147
|
+
if (config.store.s3AccessKeyId) out[config.store.s3AccessKeyId] = s3.s3AccessKeyId
|
|
148
|
+
if (config.store.s3SecretAccessKey) out[config.store.s3SecretAccessKey] = s3.s3SecretAccessKey
|
|
149
|
+
return out
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The one call this module makes that is not the Cloudflare API: listing a
|
|
154
|
+
* bucket with the derived S3 keys, which is the only proof they work when the
|
|
155
|
+
* token's own value was not stored. An object so a test can replace it.
|
|
156
|
+
*/
|
|
157
|
+
export const s3Probe = {
|
|
158
|
+
async list(opts: {
|
|
159
|
+
accountId: string
|
|
160
|
+
bucket: string
|
|
161
|
+
accessKeyId: string
|
|
162
|
+
secretAccessKey: string
|
|
163
|
+
}): Promise<void> {
|
|
164
|
+
const client = new Bun.S3Client({
|
|
165
|
+
accessKeyId: opts.accessKeyId,
|
|
166
|
+
secretAccessKey: opts.secretAccessKey,
|
|
167
|
+
bucket: opts.bucket,
|
|
168
|
+
endpoint: `https://${opts.accountId}.r2.cloudflarestorage.com`,
|
|
169
|
+
region: 'auto',
|
|
170
|
+
})
|
|
171
|
+
await client.list({ maxKeys: 1 })
|
|
172
|
+
},
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Prove the stored credential works, by the call its holder will make. Returns the token id. */
|
|
176
|
+
async function check(config: Config, read: (key: string) => string): Promise<string> {
|
|
177
|
+
if (config.store.tokenValue) {
|
|
178
|
+
const verified = await cf<{ id: string; status: string }>(
|
|
179
|
+
read(config.store.tokenValue),
|
|
180
|
+
'GET',
|
|
181
|
+
`/accounts/${config.accountId}/tokens/verify`,
|
|
182
|
+
)
|
|
183
|
+
if (verified.status !== 'active') {
|
|
184
|
+
throw new Error(`token "${config.tokenName}" is ${verified.status}`)
|
|
185
|
+
}
|
|
186
|
+
return verified.id
|
|
187
|
+
}
|
|
188
|
+
// The schema guarantees both S3 keys and `buckets` on this branch.
|
|
189
|
+
const accessKeyId = read(config.store.s3AccessKeyId as string)
|
|
190
|
+
const secretAccessKey = read(config.store.s3SecretAccessKey as string)
|
|
191
|
+
for (const bucket of config.buckets?.names ?? []) {
|
|
192
|
+
await s3Probe.list({ accountId: config.accountId, bucket, accessKeyId, secretAccessKey })
|
|
193
|
+
}
|
|
194
|
+
return accessKeyId
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Timing of the wait after a mint or a roll. An object so a test need not wait. */
|
|
198
|
+
export const settle = { timeoutMs: 60_000, intervalMs: 3_000 }
|
|
199
|
+
|
|
200
|
+
/** A new or rolled token is refused for some seconds after Cloudflare returns it. */
|
|
201
|
+
async function untilWorks(config: Config, values: Record<string, string>): Promise<void> {
|
|
202
|
+
const deadline = Date.now() + settle.timeoutMs
|
|
203
|
+
for (;;) {
|
|
204
|
+
try {
|
|
205
|
+
await check(config, (key) => values[key] ?? '')
|
|
206
|
+
return
|
|
207
|
+
} catch (err) {
|
|
208
|
+
if (Date.now() >= deadline) {
|
|
209
|
+
throw new Error(
|
|
210
|
+
`token "${config.tokenName}" is stored but still refused after ${Math.round(settle.timeoutMs / 1000)}s: ${(err as Error).message}`,
|
|
211
|
+
{ cause: err },
|
|
212
|
+
)
|
|
213
|
+
}
|
|
214
|
+
await new Promise((resolve) => setTimeout(resolve, settle.intervalMs))
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function rootToken(config: Config, ctx: ApplyContext): string {
|
|
220
|
+
const token = ctx.secrets[config.rootTokenSecret] || process.env[config.rootTokenSecret]
|
|
221
|
+
if (!token) {
|
|
222
|
+
throw new Error(
|
|
223
|
+
`minting "${config.tokenName}" needs ${config.rootTokenSecret}: an account-owned token with ` +
|
|
224
|
+
'"Account API Tokens Write", in this environment\'s secrets.yaml or in the environment of this command.',
|
|
225
|
+
)
|
|
226
|
+
}
|
|
227
|
+
return token
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function resolvePolicies(config: Config, root: string): Promise<Policy[]> {
|
|
231
|
+
const available = await cf<PermissionGroup[]>(
|
|
232
|
+
root,
|
|
233
|
+
'GET',
|
|
234
|
+
`/accounts/${config.accountId}/tokens/permission_groups`,
|
|
235
|
+
)
|
|
236
|
+
return buildPolicies(config, available)
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function findToken(config: Config, root: string) {
|
|
240
|
+
const tokens = await cf<Array<{ id: string; name: string }>>(
|
|
241
|
+
root,
|
|
242
|
+
'GET',
|
|
243
|
+
`/accounts/${config.accountId}/tokens?per_page=500`,
|
|
244
|
+
)
|
|
245
|
+
return tokens.find((t) => t.name === config.tokenName)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Store every key, then prove the token works. Stored first: the value exists
|
|
250
|
+
* nowhere else, and a wait that times out must not be what loses it.
|
|
251
|
+
*/
|
|
252
|
+
async function storeAndProve(
|
|
253
|
+
config: Config,
|
|
254
|
+
ctx: ApplyContext,
|
|
255
|
+
tokenId: string,
|
|
256
|
+
tokenValue: string,
|
|
257
|
+
): Promise<void> {
|
|
258
|
+
const values = storedValues(config, tokenId, tokenValue)
|
|
259
|
+
for (const [key, value] of Object.entries(values)) {
|
|
260
|
+
try {
|
|
261
|
+
await ctx.storeSecret(key, value)
|
|
262
|
+
} catch (err) {
|
|
263
|
+
throw new Error(
|
|
264
|
+
`token "${config.tokenName}" has a new value and storing ${key} failed: ${(err as Error).message}\n` +
|
|
265
|
+
' That value is not kept anywhere else. Fix what stopped the write, then run the rotate action (with --yes).',
|
|
266
|
+
{ cause: err },
|
|
267
|
+
)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
await untilWorks(config, values)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export const cloudflareStoredTokenModule = defineModule({
|
|
274
|
+
name: 'cloudflare-stored-token',
|
|
275
|
+
configSchema,
|
|
276
|
+
outputs: z.object({
|
|
277
|
+
tokenName: z.string(),
|
|
278
|
+
/** Not a secret: it names the token, and is the S3 access key id. */
|
|
279
|
+
tokenId: z.string(),
|
|
280
|
+
}),
|
|
281
|
+
async apply(config, ctx) {
|
|
282
|
+
const keys = Object.values(config.store).filter((key): key is string => Boolean(key))
|
|
283
|
+
const missing = keys.filter((key) => !ctx.secrets[key])
|
|
284
|
+
if (missing.length > 0) {
|
|
285
|
+
throw new Error(
|
|
286
|
+
`token "${config.tokenName}" is not minted: ${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} missing from secrets.yaml. ` +
|
|
287
|
+
'An apply does not mint it. Run `zbc run <env> <this instance> mint` and commit secrets.yaml.',
|
|
288
|
+
)
|
|
289
|
+
}
|
|
290
|
+
const tokenId = await check(config, (key) => ctx.secret(key))
|
|
291
|
+
console.log(` Token "${config.tokenName}" (${tokenId}) works; not rolled`)
|
|
292
|
+
return { tokenName: config.tokenName, tokenId }
|
|
293
|
+
},
|
|
294
|
+
actions: {
|
|
295
|
+
mint: {
|
|
296
|
+
description:
|
|
297
|
+
'Create the token and store it in secrets.yaml under the keys `store` names; refuses if a token of this name exists',
|
|
298
|
+
async run(config, ctx) {
|
|
299
|
+
const root = rootToken(config, ctx)
|
|
300
|
+
const policies = await resolvePolicies(config, root)
|
|
301
|
+
if (await findToken(config, root)) {
|
|
302
|
+
throw new Error(
|
|
303
|
+
`Token "${config.tokenName}" already exists, and Cloudflare does not show an existing token's value. ` +
|
|
304
|
+
'Run the rotate action (with --yes) to replace it; what holds the old value stops working at once.',
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
const created = await cf<{ id: string; value: string }>(
|
|
308
|
+
root,
|
|
309
|
+
'POST',
|
|
310
|
+
`/accounts/${config.accountId}/tokens`,
|
|
311
|
+
{ name: config.tokenName, policies },
|
|
312
|
+
)
|
|
313
|
+
await storeAndProve(config, ctx, created.id, created.value)
|
|
314
|
+
console.log(` Created token "${config.tokenName}" (${created.id}), stored and verified`)
|
|
315
|
+
},
|
|
316
|
+
},
|
|
317
|
+
rotate: {
|
|
318
|
+
description:
|
|
319
|
+
"Re-apply the token's policies and roll its value; the stored value stops working at once",
|
|
320
|
+
irreversible: true,
|
|
321
|
+
async run(config, ctx) {
|
|
322
|
+
const root = rootToken(config, ctx)
|
|
323
|
+
const policies = await resolvePolicies(config, root)
|
|
324
|
+
const existing = await findToken(config, root)
|
|
325
|
+
if (!existing) {
|
|
326
|
+
throw new Error(`Token "${config.tokenName}" does not exist. Run the mint action.`)
|
|
327
|
+
}
|
|
328
|
+
await cf(root, 'PUT', `/accounts/${config.accountId}/tokens/${existing.id}`, {
|
|
329
|
+
name: config.tokenName,
|
|
330
|
+
policies,
|
|
331
|
+
})
|
|
332
|
+
const value = await cf<string>(
|
|
333
|
+
root,
|
|
334
|
+
'PUT',
|
|
335
|
+
`/accounts/${config.accountId}/tokens/${existing.id}/value`,
|
|
336
|
+
{},
|
|
337
|
+
)
|
|
338
|
+
await storeAndProve(config, ctx, existing.id, value)
|
|
339
|
+
console.log(` Rolled token "${config.tokenName}" (${existing.id}), stored and verified`)
|
|
340
|
+
},
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
})
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cloudflare-stored-token",
|
|
3
|
+
"modules": ["cloudflare-api", "cloudflare-token"],
|
|
4
|
+
"description": "A Cloudflare API token minted once by an action and kept in secrets.yaml, for a holder outside any apply; apply only proves it still works",
|
|
5
|
+
"files": [{ "path": "index.ts" }],
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"zod": "^3.24.0"
|
|
8
|
+
},
|
|
9
|
+
"secrets": [],
|
|
10
|
+
"tokenUrl": "https://dash.cloudflare.com/?to=/:account/api-tokens",
|
|
11
|
+
"instructions": "For a token something outside an apply holds (a laptop, a job in another repository, a reader of one bucket). `cloudflare-token` rolls its value on every apply, which would break such a holder; this one is created once and never rolled by an apply.\n\nInstance example:\n\n // packages/infra/environments/production/reader-token.ts\n import { cloudflareStoredTokenModule } from '../../modules/cloudflare-stored-token'\n export default cloudflareStoredTokenModule.instance({\n name: 'reader-token',\n config: {\n accountId: '<account id>',\n tokenName: 'myproject reader',\n buckets: { names: ['myproject-files'], permissions: ['Workers R2 Storage Bucket Item Read'] },\n store: { s3AccessKeyId: 'READER_S3_ACCESS_KEY_ID', s3SecretAccessKey: 'READER_S3_SECRET_ACCESS_KEY' },\n },\n })\n\nMint it once: `zbc run production reader-token mint`, then commit secrets.yaml. Minting needs a root token (account-owned, with 'Account API Tokens Write') under CLOUDFLARE_ROOT_TOKEN, or the key `rootTokenSecret` names, in secrets.yaml or in the environment of that one command; an apply never needs it. `zbc run production reader-token rotate --yes` rolls the value and stores the new one: whatever holds the old one stops working at once. `zbc apply` creates and rolls nothing; it fails if the stored keys are missing or no longer work. The module emits no credential: a holder reads the keys `store` names, with `zbc secret get` or by name in `workerSecrets`."
|
|
12
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
2
|
import { z } from 'zod'
|
|
3
3
|
import { defineModule } from '../../src/define-module'
|
|
4
|
-
import { cf } from '../cloudflare-api'
|
|
4
|
+
import { CfError, cf } from '../cloudflare-api'
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* cloudflare-token — mints scoped Cloudflare API tokens from ONE root
|
|
@@ -10,7 +10,7 @@ import { cf } from '../cloudflare-api'
|
|
|
10
10
|
*
|
|
11
11
|
* The root credential is an ACCOUNT-OWNED token (dash → Manage Account → API
|
|
12
12
|
* Tokens) holding "Account API Tokens Write" — plus "Zone Read" if instances
|
|
13
|
-
*
|
|
13
|
+
* name a zone in `zones` (an id needs none). It is the only Cloudflare secret at rest in secrets.yaml;
|
|
14
14
|
* everything else is minted here and flows to dependents through imports.
|
|
15
15
|
*
|
|
16
16
|
* WHICH root is per-instance: `rootTokenSecret` names the secrets.yaml key,
|
|
@@ -33,7 +33,7 @@ import { cf } from '../cloudflare-api'
|
|
|
33
33
|
* Permissions are configured by permission-group NAME (exact match against
|
|
34
34
|
* `GET /accounts/{id}/tokens/permission_groups`, e.g. "Workers Scripts
|
|
35
35
|
* Write"). Groups scoped `com.cloudflare.api.account.zone` land on a zone
|
|
36
|
-
* policy — restricted to `zones` when given (
|
|
36
|
+
* policy — restricted to `zones` when given (a name is resolved via GET /zones; an id is not),
|
|
37
37
|
* else all zones of the account. Account-scoped groups land on an account
|
|
38
38
|
* policy. Unknown names/zones are hard errors before anything mutates.
|
|
39
39
|
*
|
|
@@ -200,11 +200,25 @@ export const cloudflareTokenModule = defineModule({
|
|
|
200
200
|
*/
|
|
201
201
|
permissions: z.array(z.string()).nonempty(),
|
|
202
202
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
*
|
|
203
|
+
* The zones zone-scoped permission groups are restricted to. Omit to grant
|
|
204
|
+
* them on all zones of the account.
|
|
205
|
+
*
|
|
206
|
+
* An entry is a zone name, `{ id }`, or `{ from, output }` into an imported
|
|
207
|
+
* instance's output (a `cloudflare-zone`'s `zoneId`). A name is resolved
|
|
208
|
+
* via GET /zones, which the root token can only do if it also holds "Zone
|
|
209
|
+
* Read". A root that can create tokens and nothing else cannot, and three
|
|
210
|
+
* consumers with such a root left this unset, minting tokens that cover
|
|
211
|
+
* every zone. The id forms need no lookup.
|
|
206
212
|
*/
|
|
207
|
-
zones: z
|
|
213
|
+
zones: z
|
|
214
|
+
.array(
|
|
215
|
+
z.union([
|
|
216
|
+
z.string(),
|
|
217
|
+
z.object({ id: z.string() }),
|
|
218
|
+
z.object({ from: z.string(), output: z.string() }),
|
|
219
|
+
]),
|
|
220
|
+
)
|
|
221
|
+
.default([]),
|
|
208
222
|
/**
|
|
209
223
|
* Which secrets.yaml key holds the root credential this instance mints
|
|
210
224
|
* from. Defaults to CLOUDFLARE_ROOT_TOKEN — one name is enough until a repo
|
|
@@ -271,17 +285,32 @@ export const cloudflareTokenModule = defineModule({
|
|
|
271
285
|
return matches
|
|
272
286
|
})
|
|
273
287
|
|
|
274
|
-
// 2. Resolve
|
|
288
|
+
// 2. Resolve zones → ids (only when zone scoping is requested). An id or a
|
|
289
|
+
// reference is taken as given; only a name costs a call.
|
|
275
290
|
const zoneIds = await Promise.all(
|
|
276
|
-
config.zones.map(async (
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
291
|
+
config.zones.map(async (zone, i) => {
|
|
292
|
+
if (typeof zone !== 'string') {
|
|
293
|
+
return 'id' in zone ? zone.id : ctx.output(zone, `zones[${i}]`)
|
|
294
|
+
}
|
|
295
|
+
let found: Array<{ id: string; name: string }>
|
|
296
|
+
try {
|
|
297
|
+
found = await cf<Array<{ id: string; name: string }>>(
|
|
298
|
+
rootToken,
|
|
299
|
+
'GET',
|
|
300
|
+
`/zones?name=${encodeURIComponent(zone)}`,
|
|
301
|
+
)
|
|
302
|
+
} catch (err) {
|
|
303
|
+
if (!(err instanceof CfError)) throw err
|
|
304
|
+
throw new Error(
|
|
305
|
+
`Could not look up zone "${zone}" by name: ${err.message}\n` +
|
|
306
|
+
` Looking a zone up needs "Zone Read" on the root token. A root that only creates tokens does not have it: ` +
|
|
307
|
+
`give the zone by id instead, \`zones: [{ id: '<zone id>' }]\`, or \`{ from, output }\` into a cloudflare-zone instance's \`zoneId\`.`,
|
|
308
|
+
{ cause: err },
|
|
309
|
+
)
|
|
310
|
+
}
|
|
311
|
+
const match = found[0]
|
|
312
|
+
if (!match) throw new Error(`Zone "${zone}" not found (root token needs "Zone Read")`)
|
|
313
|
+
return match.id
|
|
285
314
|
}),
|
|
286
315
|
)
|
|
287
316
|
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
"secrets": ["CLOUDFLARE_ROOT_TOKEN"],
|
|
10
10
|
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
11
11
|
"tokenUrl": "https://dash.cloudflare.com/?to=/:account/api-tokens",
|
|
12
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Create ONE account-owned root token in the dashboard (Manage Account → API Tokens) with 'Account API Tokens Write' — plus 'Zone Read' if
|
|
12
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Create ONE account-owned root token in the dashboard (Manage Account → API Tokens) with 'Account API Tokens Write' — plus 'Zone Read' if an instance names a zone in `zones` (a zone given as `{ id }`, or `{ from, output }` into a cloudflare-zone instance's `zoneId`, needs no lookup and so no 'Zone Read') — and put it in secrets.yaml as CLOUDFLARE_ROOT_TOKEN. An instance minting into a SECOND Cloudflare account (a client's, say) sets `rootTokenSecret` to the key holding that account's root instead; omitting it keeps CLOUDFLARE_ROOT_TOKEN. Instances mint per-purpose tokens by permission-group NAME (as listed by GET /accounts/{id}/tokens/permission_groups). The minted value is ROLLED on every apply and exists only in memory: consume it downstream via imports (`{ name, from, output: 'tokenValue' }`), never store it, and never hand it to a human for local use (mint them a separate named token instead). Tokens with R2 permissions also emit s3AccessKeyId/s3SecretAccessKey (access key = token id, secret = sha256 of the value)."
|
|
13
13
|
}
|