@zabaca/zbc 0.26.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.
Files changed (33) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/package.json +1 -1
  3. package/src/commands/secret.ts +1 -66
  4. package/src/commands/update.ts +44 -1
  5. package/src/engine/actions.ts +35 -3
  6. package/src/engine/on-demand.ts +9 -1
  7. package/src/engine/secret-outputs.ts +15 -0
  8. package/src/engine/secrets.ts +81 -1
  9. package/src/utils/copy-refresh.ts +124 -19
  10. package/src/utils/template-history.ts +66 -0
  11. package/templates/history.json +1 -0
  12. package/templates/infra/modules/cloudflare/index.ts +140 -1
  13. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  14. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  15. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  16. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  17. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  18. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  19. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  20. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  21. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  22. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  23. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  24. package/templates/infra/modules/d1/index.ts +37 -35
  25. package/templates/infra/modules/d1/registry.json +1 -1
  26. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  27. package/templates/infra/modules/queue/index.ts +28 -18
  28. package/templates/infra/modules/queue/registry.json +1 -1
  29. package/templates/infra/modules/r2/index.ts +20 -11
  30. package/templates/infra/modules/r2/registry.json +1 -1
  31. package/templates/infra/src/context.ts +41 -0
  32. package/templates/infra/src/testing.ts +19 -1
  33. package/templates/infra/src/types.ts +23 -0
@@ -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
- * use `zones`. It is the only Cloudflare secret at rest in secrets.yaml;
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 (names resolved via GET /zones),
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
- * Zone names restricting zone-scoped permission groups (resolved to zone
204
- * ids via GET /zones — the root token then also needs "Zone Read"). Omit
205
- * to grant zone-scoped groups on all zones of the account.
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.array(z.string()).default([]),
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 zone names → ids (only when zone scoping is requested).
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 (zoneName) => {
277
- const zones = await cf<Array<{ id: string; name: string }>>(
278
- rootToken,
279
- 'GET',
280
- `/zones?name=${encodeURIComponent(zoneName)}`,
281
- )
282
- const zone = zones[0]
283
- if (!zone) throw new Error(`Zone "${zoneName}" not found (root token needs "Zone Read")`)
284
- return zone.id
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 instances use `zones` — 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)."
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
  }
@@ -2,7 +2,7 @@ import * as fs from 'node:fs'
2
2
  import * as path from 'node:path'
3
3
  import { z } from 'zod'
4
4
  import { defineModule } from '../../src/define-module'
5
- import { cf } from '../cloudflare-api'
5
+ import { apiTokenFor, apiTokenSchema, cf } from '../cloudflare-api'
6
6
 
7
7
  // cloudflare-tunnel — a remotely-managed Cloudflare Tunnel as repo state: the
8
8
  // tunnel itself, its ingress rules, the DNS records that point at it, and the
@@ -104,11 +104,18 @@ const configSchema = z.object({
104
104
  tunnelName: z.string().min(1),
105
105
  /**
106
106
  * Where the API credential comes from: `{ from, output }` into an imported
107
- * `cloudflare-token` instance's `tokenValue`. Same shape cloudflare-zone and
108
- * vendor/zbc/modules/cloudflare use. Needs "Cloudflare Tunnel Write" for the
109
- * tunnel, plus "Zone Read" and "DNS Write" for the hostname records.
107
+ * `cloudflare-token` instance's `tokenValue`, or `{ secret }` for a token
108
+ * held under that key in secrets.yaml. Needs "Cloudflare Tunnel Write" for
109
+ * the tunnel, plus "Zone Read" and "DNS Write" for the hostname records.
110
110
  */
111
- apiToken: z.object({ from: z.string(), output: z.string() }),
111
+ apiToken: apiTokenSchema,
112
+ /**
113
+ * The key in this environment's secrets.yaml the `store-run-token` action
114
+ * writes the run token under, for a cloudflared that reads it from there and
115
+ * not from this instance's outputs. Optional: without it the action has
116
+ * nowhere to write and says so.
117
+ */
118
+ runTokenSecret: z.string().min(1).optional(),
112
119
  /** Zone apex every ingress hostname must live under, e.g. `cedarpad.com`. */
113
120
  zone: z.string().min(1),
114
121
  /** Ordered ingress rules. The catch-all is appended automatically. */
@@ -250,15 +257,29 @@ export const cloudflareTunnelModule = defineModule({
250
257
  configSchema,
251
258
  outputs: z.object({
252
259
  tunnelId: z.string(),
253
- /** `TUNNEL_TOKEN` for `cloudflared tunnel run`. Stable for the tunnel's life. */
260
+ /**
261
+ * `TUNNEL_TOKEN` for `cloudflared tunnel run`. Stable for the tunnel's life,
262
+ * and a credential: declared in `secretOutputs` below.
263
+ */
254
264
  runToken: z.string(),
255
265
  hostnames: z.array(z.string()),
256
266
  /** True when this apply created the tunnel — the unit needs a restart. */
257
267
  createdTunnel: z.boolean(),
258
268
  changed: z.boolean(),
259
269
  }),
270
+ /**
271
+ * The run token lets its holder serve this tunnel's hostnames, so it is kept
272
+ * out of every printed message and out of `zbc apply --json` (ADR-0016). It
273
+ * was a plain output, written to that file verbatim.
274
+ *
275
+ * `'never'`, because the holder is a cloudflared that no apply reaches. An
276
+ * `ephemeral` tunnel is recreated on every apply and gets a new token each
277
+ * time, which that cloudflared would learn only by failing to connect, so the
278
+ * engine now refuses one before anything is applied.
279
+ */
280
+ secretOutputs: { runToken: { rotates: 'never' } },
260
281
  async apply(config, ctx) {
261
- const token = ctx.output(config.apiToken, 'apiToken')
282
+ const token = apiTokenFor(config.apiToken, ctx)
262
283
  assertHostnamesInZone(config.ingress, config.zone)
263
284
 
264
285
  // 1. Converge the tunnel by name. `is_deleted=false` matters: Cloudflare
@@ -418,7 +439,7 @@ export const cloudflareTunnelModule = defineModule({
418
439
  }
419
440
  },
420
441
  async destroy(config, ctx) {
421
- const token = ctx.output(config.apiToken, 'apiToken')
442
+ const token = apiTokenFor(config.apiToken, ctx)
422
443
  const found = await cf<CfTunnel[]>(
423
444
  token,
424
445
  'GET',
@@ -438,4 +459,38 @@ export const cloudflareTunnelModule = defineModule({
438
459
  ` Deleted tunnel "${config.tunnelName}" (${existing.id}); DNS records left in place`,
439
460
  )
440
461
  },
462
+ actions: {
463
+ 'store-run-token': {
464
+ description:
465
+ "Write the tunnel's run token into secrets.yaml under runTokenSecret, for a cloudflared that reads it from there",
466
+ async run(config, ctx) {
467
+ if (config.runTokenSecret === undefined) {
468
+ throw new Error(
469
+ 'this instance names no place to keep the run token: set runTokenSecret to a secrets.yaml key.',
470
+ )
471
+ }
472
+ const token = apiTokenFor(config.apiToken, ctx)
473
+ const found = await cf<CfTunnel[]>(
474
+ token,
475
+ 'GET',
476
+ `/accounts/${config.accountId}/cfd_tunnel?is_deleted=false&name=${encodeURIComponent(config.tunnelName)}`,
477
+ )
478
+ const tunnel = found.find((t) => t.name === config.tunnelName && !t.deleted_at)
479
+ if (!tunnel) {
480
+ throw new Error(
481
+ `Tunnel "${config.tunnelName}" does not exist yet. An action does not create it: apply this instance first.`,
482
+ )
483
+ }
484
+ const runToken = await cf<string>(
485
+ token,
486
+ 'GET',
487
+ `/accounts/${config.accountId}/cfd_tunnel/${tunnel.id}/token`,
488
+ )
489
+ await ctx.storeSecret(config.runTokenSecret, runToken)
490
+ console.log(
491
+ ` Run token of "${config.tunnelName}" (${tunnel.id}) is under ${config.runTokenSecret}`,
492
+ )
493
+ },
494
+ },
495
+ },
441
496
  })
@@ -7,5 +7,5 @@
7
7
  "zod": "^3.24.0"
8
8
  },
9
9
  "secrets": [],
10
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Tunnel and DNS write. It refuses to adopt a locally-managed tunnel, because that kind ignores the configuration API while returning success — the resulting drift is invisible from the dashboard and from an apply alike. The connector token is an output; write it to disk with a file-converging module rather than pasting it into a unit."
10
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Tunnel and DNS write (the `runToken` output is a declared secret: redacted from logs and `--json`, and an `ephemeral` instance is refused because it would change the token under a running cloudflared; `zbc run <env> <instance> store-run-token` writes it to secrets.yaml under `runTokenSecret` for a cloudflared that reads it from there), named by `apiToken`: `{ from, output }` for an imported `cloudflare-token` instance's `tokenValue`, or `{ secret }` for a key of secrets.yaml. It refuses to adopt a locally-managed tunnel, because that kind ignores the configuration API while returning success — the resulting drift is invisible from the dashboard and from an apply alike. The connector token is an output; write it to disk with a file-converging module rather than pasting it into a unit."
11
11
  }