@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.
Files changed (74) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/package.json +1 -1
  3. package/src/commands/init.ts +105 -10
  4. package/src/commands/secret.ts +1 -66
  5. package/src/commands/update.ts +77 -7
  6. package/src/engine/actions.ts +35 -3
  7. package/src/engine/on-demand.ts +9 -1
  8. package/src/engine/secret-outputs.ts +15 -0
  9. package/src/engine/secrets.ts +81 -1
  10. package/src/utils/copy-refresh.ts +124 -19
  11. package/src/utils/detect-mode.ts +1 -1
  12. package/src/utils/host-workspaces.ts +57 -0
  13. package/src/utils/subtree.ts +54 -15
  14. package/src/utils/template-history.ts +66 -0
  15. package/src/utils/vendor-audit.ts +12 -8
  16. package/src/utils/vendor-stamp.ts +10 -0
  17. package/src/utils/vendored-app.ts +3 -0
  18. package/templates/apps/walgit/CONTEXT.md +45 -4
  19. package/templates/apps/walgit/README.md +394 -11
  20. package/templates/apps/walgit/shared/browse.ts +61 -0
  21. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  22. package/templates/apps/walgit/shared/container-env.ts +12 -0
  23. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  24. package/templates/apps/walgit/shared/credentials.ts +4 -0
  25. package/templates/apps/walgit/shared/events.ts +35 -1
  26. package/templates/apps/walgit/shared/instructions.ts +4 -1
  27. package/templates/apps/walgit/shared/landing.ts +2 -1
  28. package/templates/apps/walgit/shared/llms.ts +73 -5
  29. package/templates/apps/walgit/shared/mcp.ts +19 -3
  30. package/templates/apps/walgit/shared/protocol.ts +40 -3
  31. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  32. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  33. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  34. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  35. package/templates/apps/walgit/shared/webhook.ts +281 -0
  36. package/templates/apps/walgit/src/admin.ts +510 -0
  37. package/templates/apps/walgit/src/announce-main.ts +17 -9
  38. package/templates/apps/walgit/src/announce.ts +86 -0
  39. package/templates/apps/walgit/src/browse.ts +255 -2
  40. package/templates/apps/walgit/src/cli.ts +140 -0
  41. package/templates/apps/walgit/src/expire.ts +5 -0
  42. package/templates/apps/walgit/src/git.ts +103 -0
  43. package/templates/apps/walgit/src/hook-main.ts +6 -3
  44. package/templates/apps/walgit/src/http.ts +563 -3
  45. package/templates/apps/walgit/src/limits.ts +3 -0
  46. package/templates/apps/walgit/src/merge.ts +525 -0
  47. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  48. package/templates/apps/walgit/src/server.ts +65 -1
  49. package/templates/apps/walgit/worker/events-do.ts +218 -3
  50. package/templates/apps/walgit/worker/index.ts +134 -9
  51. package/templates/apps/walgit/worker/mcp.ts +17 -2
  52. package/templates/history.json +1 -0
  53. package/templates/infra/modules/cloudflare/index.ts +140 -1
  54. package/templates/infra/modules/cloudflare-access/index.ts +176 -65
  55. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  56. package/templates/infra/modules/cloudflare-api/index.ts +56 -0
  57. package/templates/infra/modules/cloudflare-email/index.ts +44 -17
  58. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  59. package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
  60. package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
  61. package/templates/infra/modules/cloudflare-token/index.ts +46 -17
  62. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  63. package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
  64. package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
  65. package/templates/infra/modules/d1/index.ts +37 -35
  66. package/templates/infra/modules/d1/registry.json +1 -1
  67. package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
  68. package/templates/infra/modules/queue/index.ts +28 -18
  69. package/templates/infra/modules/queue/registry.json +1 -1
  70. package/templates/infra/modules/r2/index.ts +20 -11
  71. package/templates/infra/modules/r2/registry.json +1 -1
  72. package/templates/infra/src/context.ts +41 -0
  73. package/templates/infra/src/testing.ts +19 -1
  74. package/templates/infra/src/types.ts +23 -0
@@ -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
  }
@@ -4,8 +4,16 @@ import * as os from 'node:os'
4
4
  import * as path from 'node:path'
5
5
  import { z } from 'zod'
6
6
  import { defineModule } from '../../src/define-module'
7
- import type { ApplyContext } from '../../src/types'
8
- import { CfError, type CfOptions, cf, cfRaw } from '../cloudflare-api'
7
+ import {
8
+ type ApiTokenSource,
9
+ apiTokenFor,
10
+ apiTokenSchema,
11
+ CfError,
12
+ type CfOptions,
13
+ cf,
14
+ cfRaw,
15
+ tokenScopeHint,
16
+ } from '../cloudflare-api'
9
17
 
10
18
  /**
11
19
  * d1 — provisions a Cloudflare D1 database via the REST API (r2-style:
@@ -33,14 +41,9 @@ import { CfError, type CfOptions, cf, cfRaw } from '../cloudflare-api'
33
41
  */
34
42
 
35
43
  /** Named per-code guidance for this module's calls — see `../cloudflare-api`. */
36
- const OPTS: CfOptions = {
37
- hints: {
38
- 10000:
39
- `rejected the token (10000 Authentication error). ` +
40
- `CLOUDFLARE_API_TOKEN is likely missing the Account → D1: Edit scope. ` +
41
- `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
42
- },
43
- }
44
+ const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
45
+ hints: { 10000: tokenScopeHint(source, 'the Account → D1: Edit scope') },
46
+ })
44
47
 
45
48
  interface D1Database {
46
49
  uuid: string
@@ -56,7 +59,11 @@ interface D1Database {
56
59
  * not show it, and apply creates a second one under a name that is already
57
60
  * taken.
58
61
  */
59
- async function listDatabases(token: string, accountId: string): Promise<D1Database[]> {
62
+ async function listDatabases(
63
+ token: string,
64
+ accountId: string,
65
+ OPTS: CfOptions,
66
+ ): Promise<D1Database[]> {
60
67
  const all: D1Database[] = []
61
68
  // Bounded: `total_pages` is the provider's number, and a loop whose only exit
62
69
  // is the provider agreeing to stop hangs rather than failing when it does not.
@@ -101,6 +108,7 @@ async function query(
101
108
  accountId: string,
102
109
  databaseId: string,
103
110
  sql: string,
111
+ OPTS: CfOptions,
104
112
  ): Promise<void> {
105
113
  const results = await cf<D1StatementResult[] | null>(
106
114
  token,
@@ -202,20 +210,6 @@ function applyMigrations(opts: {
202
210
  }
203
211
  }
204
212
 
205
- /**
206
- * The credential every call below uses: an imported instance's output when
207
- * `apiToken` is set, else CLOUDFLARE_API_TOKEN from secrets.yaml. One helper
208
- * so apply, destroy and the readiness probe can never disagree on it.
209
- */
210
- function apiTokenFor(
211
- config: { apiToken?: { from: string; output: string } },
212
- ctx: ApplyContext,
213
- ): string {
214
- return config.apiToken
215
- ? ctx.output(config.apiToken, 'apiToken')
216
- : ctx.secret('CLOUDFLARE_API_TOKEN')
217
- }
218
-
219
213
  export const d1Module = defineModule({
220
214
  name: 'd1',
221
215
  configSchema: z.object({
@@ -226,9 +220,10 @@ export const d1Module = defineModule({
226
220
  * this environment's secrets.yaml. Set `{ from, output }` to pull it from
227
221
  * an imported instance's outputs instead — e.g. a minted `cloudflare-token`
228
222
  * whose permissions include D1 Read and D1 Write — so it never sits at
229
- * rest. Mirrors the `cloudflare` module's `apiToken`.
223
+ * rest. Mirrors the `cloudflare` module's `apiToken`. `{ secret }` reads
224
+ * another key of secrets.yaml instead.
230
225
  */
231
- apiToken: z.object({ from: z.string(), output: z.string() }).optional(),
226
+ apiToken: apiTokenSchema.optional(),
232
227
  /** Database name — account-scoped, so namespace it per project/env. */
233
228
  databaseName: z.string(),
234
229
  /**
@@ -280,7 +275,8 @@ export const d1Module = defineModule({
280
275
  databaseId: z.string(),
281
276
  }),
282
277
  async apply(config, ctx) {
283
- const apiToken = apiTokenFor(config, ctx)
278
+ const apiToken = apiTokenFor(config.apiToken, ctx)
279
+ const OPTS = optsFor(config.apiToken)
284
280
  const { accountId, databaseName } = config
285
281
 
286
282
  // Checked before anything is called: a typo'd folder must not leave a
@@ -294,7 +290,9 @@ export const d1Module = defineModule({
294
290
  )
295
291
  }
296
292
 
297
- const existing = (await listDatabases(apiToken, accountId)).find((d) => d.name === databaseName)
293
+ const existing = (await listDatabases(apiToken, accountId, OPTS)).find(
294
+ (d) => d.name === databaseName,
295
+ )
298
296
 
299
297
  let databaseId: string
300
298
  if (existing) {
@@ -341,7 +339,7 @@ export const d1Module = defineModule({
341
339
  }
342
340
 
343
341
  for (const statement of config.statements) {
344
- await query(apiToken, accountId, databaseId, statement)
342
+ await query(apiToken, accountId, databaseId, statement, OPTS)
345
343
  }
346
344
  if (config.statements.length > 0) {
347
345
  console.log(` Applied ${config.statements.length} statement(s)`)
@@ -350,7 +348,7 @@ export const d1Module = defineModule({
350
348
  for (const { table, column, definition } of config.additiveColumns) {
351
349
  const sql = `ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`
352
350
  try {
353
- await query(apiToken, accountId, databaseId, sql)
351
+ await query(apiToken, accountId, databaseId, sql, OPTS)
354
352
  console.log(` Added column ${table}.${column}`)
355
353
  } catch (err) {
356
354
  if (!isDuplicateColumn(err)) throw err
@@ -366,13 +364,16 @@ export const d1Module = defineModule({
366
364
  * strand every instance behind it in a `zbc destroy`.
367
365
  */
368
366
  async destroy(config, ctx) {
369
- const apiToken = apiTokenFor(config, ctx)
367
+ const apiToken = apiTokenFor(config.apiToken, ctx)
368
+ const OPTS = optsFor(config.apiToken)
370
369
  const { accountId, databaseName } = config
371
370
  // The lookup is deliberately OUTSIDE the try: the forgiving case is
372
371
  // "already gone", and that is the `!existing` branch. A listing that failed
373
372
  // — a rejected token, a 5xx — proves nothing about whether the database is
374
373
  // there, and reporting it as a skipped delete leaves the resource standing.
375
- const existing = (await listDatabases(apiToken, accountId)).find((d) => d.name === databaseName)
374
+ const existing = (await listDatabases(apiToken, accountId, OPTS)).find(
375
+ (d) => d.name === databaseName,
376
+ )
376
377
  if (!existing) {
377
378
  console.log(` Database "${databaseName}" is already gone`)
378
379
  return
@@ -401,8 +402,9 @@ export const d1Module = defineModule({
401
402
  ready: {
402
403
  proves: 'the database answers a query',
403
404
  async probe(outputs, config, ctx) {
404
- const apiToken = apiTokenFor(config, ctx)
405
- await query(apiToken, config.accountId, outputs.databaseId, 'SELECT 1')
405
+ const apiToken = apiTokenFor(config.apiToken, ctx)
406
+ const OPTS = optsFor(config.apiToken)
407
+ await query(apiToken, config.accountId, outputs.databaseId, 'SELECT 1', OPTS)
406
408
  },
407
409
  },
408
410
  })
@@ -12,5 +12,5 @@
12
12
  "secrets": ["CLOUDFLARE_API_TOKEN"],
13
13
  "signupUrl": "https://dash.cloudflare.com/sign-up",
14
14
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
15
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }`.\n\n`statements` are replayed on every apply, so each must be idempotent (`CREATE TABLE IF NOT EXISTS`). Use `additiveColumns` for `ALTER TABLE … ADD COLUMN`, which SQLite cannot spell idempotently — an already-present column is treated as success.\n\nFor a versioned history (`0001_init.sql`, …) set `migrationsDir: 'packages/app/migrations'` (relative to the project root): it is applied with `wrangler d1 migrations apply --remote` and wrangler's own `d1_migrations` ledger on this instance's apply, before `statements`, so a Worker that imports this instance deploys only after its schema is there.\n\n`destroy` deletes the database. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
15
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }`. `apiToken: { secret: '<key>' }` reads another key of secrets.yaml.\n\n`statements` are replayed on every apply, so each must be idempotent (`CREATE TABLE IF NOT EXISTS`). Use `additiveColumns` for `ALTER TABLE … ADD COLUMN`, which SQLite cannot spell idempotently — an already-present column is treated as success.\n\nFor a versioned history (`0001_init.sql`, …) set `migrationsDir: 'packages/app/migrations'` (relative to the project root): it is applied with `wrangler d1 migrations apply --remote` and wrangler's own `d1_migrations` ledger on this instance's apply, before `statements`, so a Worker that imports this instance deploys only after its schema is there.\n\n`destroy` deletes the database. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
16
16
  }
@@ -12,7 +12,9 @@ export const dockerComposeStackModule = defineModule({
12
12
  dir: z.string(),
13
13
  // empty = whole stack. Names are interpolated into the compose command —
14
14
  // compose-legal characters only, so a stray space is a config error.
15
- services: z.array(z.string().regex(/^[A-Za-z0-9_.-]+$/, 'not a compose service name')).default([]),
15
+ services: z
16
+ .array(z.string().regex(/^[A-Za-z0-9_.-]+$/, 'not a compose service name'))
17
+ .default([]),
16
18
  }),
17
19
  outputs: z.object({ dir: z.string(), running: z.number() }),
18
20
  apply: async (config) => {
@@ -1,6 +1,14 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
- import { type CfOptions, cf, cfRaw } from '../cloudflare-api'
3
+ import {
4
+ type ApiTokenSource,
5
+ apiTokenFor,
6
+ apiTokenSchema,
7
+ type CfOptions,
8
+ cf,
9
+ cfRaw,
10
+ tokenScopeHint,
11
+ } from '../cloudflare-api'
4
12
 
5
13
  /**
6
14
  * queue: a Cloudflare Queue and the Email Sending event subscriptions that fill
@@ -36,20 +44,15 @@ import { type CfOptions, cf, cfRaw } from '../cloudflare-api'
36
44
  * source reads back as a different domain or zone is a hard error rather than
37
45
  * an overwrite.
38
46
  *
39
- * Token scope: CLOUDFLARE_API_TOKEN needs Account → Queues: Edit. Creating an
47
+ * Token scope: CLOUDFLARE_API_TOKEN (or the token `apiToken` names) needs Account → Queues: Edit. Creating an
40
48
  * event subscription may ask for more on some accounts; the refusal names the
41
49
  * call that was refused.
42
50
  */
43
51
 
44
52
  /** Named per-code guidance for this module's calls; see `../cloudflare-api`. */
45
- const OPTS: CfOptions = {
46
- hints: {
47
- 10000:
48
- `rejected the token (10000 Authentication error). ` +
49
- `CLOUDFLARE_API_TOKEN is likely missing the Account → Queues: Edit scope. ` +
50
- `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
51
- },
52
- }
53
+ const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
54
+ hints: { 10000: tokenScopeHint(source, 'the Account → Queues: Edit scope') },
55
+ })
53
56
 
54
57
  export const subscriptionSchema = z.object({
55
58
  /** The subscription's name, unique on the queue: this is how an apply finds the one it made. */
@@ -160,7 +163,7 @@ interface QueueRow {
160
163
  * page. Bounded, so a provider that never says "last page" fails rather than
161
164
  * hangs.
162
165
  */
163
- async function listAll<T>(token: string, path: string): Promise<T[]> {
166
+ async function listAll<T>(token: string, path: string, OPTS: CfOptions): Promise<T[]> {
164
167
  const all: T[] = []
165
168
  const sep = path.includes('?') ? '&' : '?'
166
169
  for (let page = 1; page <= 100; page++) {
@@ -182,8 +185,9 @@ async function findQueue(
182
185
  token: string,
183
186
  accountId: string,
184
187
  queueName: string,
188
+ opts: CfOptions,
185
189
  ): Promise<QueueRow | undefined> {
186
- const queues = await listAll<QueueRow>(token, `/accounts/${accountId}/queues`)
190
+ const queues = await listAll<QueueRow>(token, `/accounts/${accountId}/queues`, opts)
187
191
  return queues.find((q) => q.queue_name === queueName)
188
192
  }
189
193
 
@@ -191,10 +195,12 @@ function listSubscriptions(
191
195
  token: string,
192
196
  accountId: string,
193
197
  queueId: string,
198
+ opts: CfOptions,
194
199
  ): Promise<ListedSubscription[]> {
195
200
  return listAll<ListedSubscription>(
196
201
  token,
197
202
  `/accounts/${accountId}/event_subscriptions/subscriptions?queue_id=${encodeURIComponent(queueId)}`,
203
+ opts,
198
204
  )
199
205
  }
200
206
 
@@ -203,6 +209,8 @@ export const queueModule = defineModule({
203
209
  configSchema: z.object({
204
210
  /** Cloudflare account id (not a secret: it is in the dashboard URL). */
205
211
  accountId: z.string(),
212
+ /** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
213
+ apiToken: apiTokenSchema.optional(),
206
214
  /** Queue name: account-scoped, and what the consuming Worker's wrangler config names. */
207
215
  queueName: z.string(),
208
216
  /** Email Sending event subscriptions that fill the queue, one per sending domain. */
@@ -215,10 +223,11 @@ export const queueModule = defineModule({
215
223
  subscriptionIds: z.record(z.string()),
216
224
  }),
217
225
  async apply(config, ctx) {
218
- const token = ctx.secret('CLOUDFLARE_API_TOKEN')
226
+ const token = apiTokenFor(config.apiToken, ctx)
227
+ const OPTS = optsFor(config.apiToken)
219
228
  const base = `/accounts/${config.accountId}`
220
229
 
221
- let queue = await findQueue(token, config.accountId, config.queueName)
230
+ let queue = await findQueue(token, config.accountId, config.queueName, OPTS)
222
231
  if (queue) {
223
232
  console.log(` Queue "${config.queueName}" already exists`)
224
233
  } else {
@@ -234,7 +243,7 @@ export const queueModule = defineModule({
234
243
 
235
244
  const existing =
236
245
  config.subscriptions.length > 0
237
- ? await listSubscriptions(token, config.accountId, queue.queue_id)
246
+ ? await listSubscriptions(token, config.accountId, queue.queue_id, OPTS)
238
247
  : []
239
248
  const subscriptionIds: Record<string, string> = {}
240
249
  for (const wanted of config.subscriptions) {
@@ -286,15 +295,16 @@ export const queueModule = defineModule({
286
295
  * down, so a destroy that reported it as done would be the lie.
287
296
  */
288
297
  async destroy(config, ctx) {
289
- const token = ctx.secret('CLOUDFLARE_API_TOKEN')
290
- const queue = await findQueue(token, config.accountId, config.queueName)
298
+ const token = apiTokenFor(config.apiToken, ctx)
299
+ const OPTS = optsFor(config.apiToken)
300
+ const queue = await findQueue(token, config.accountId, config.queueName, OPTS)
291
301
  if (!queue) {
292
302
  console.log(` Queue "${config.queueName}" is already gone`)
293
303
  return
294
304
  }
295
305
  const existing =
296
306
  config.subscriptions.length > 0
297
- ? await listSubscriptions(token, config.accountId, queue.queue_id)
307
+ ? await listSubscriptions(token, config.accountId, queue.queue_id, OPTS)
298
308
  : []
299
309
  for (const wanted of config.subscriptions) {
300
310
  const found = findMine(existing, wanted.name, queue.queue_id)
@@ -9,5 +9,5 @@
9
9
  "secrets": ["CLOUDFLARE_API_TOKEN"],
10
10
  "signupUrl": "https://dash.cloudflare.com/sign-up",
11
11
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
12
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Queues: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/delivery.ts\n import { queueModule } from '../../modules/queue'\n export default queueModule.instance({\n name: 'delivery',\n config: {\n accountId: '<account id>',\n queueName: 'myproject-delivery',\n subscriptions: [{ name: 'myproject-sending', zoneId: '<zone id>', domain: 'example.com', events: ['message.delivered', 'message.bounced'] }],\n },\n })\n\nThe consuming Worker declares the queue by name in its own wrangler config (`queues.consumers: [{ queue: 'myproject-delivery' }]`) and imports this instance, so the queue exists before wrangler attaches the consumer. `destroy` removes the subscriptions this instance names and leaves the queue."
12
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Queues: Edit scope. 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.\n\nInstance example:\n\n // packages/infra/environments/production/delivery.ts\n import { queueModule } from '../../modules/queue'\n export default queueModule.instance({\n name: 'delivery',\n config: {\n accountId: '<account id>',\n queueName: 'myproject-delivery',\n subscriptions: [{ name: 'myproject-sending', zoneId: '<zone id>', domain: 'example.com', events: ['message.delivered', 'message.bounced'] }],\n },\n })\n\nThe consuming Worker declares the queue by name in its own wrangler config (`queues.consumers: [{ queue: 'myproject-delivery' }]`) and imports this instance, so the queue exists before wrangler attaches the consumer. `destroy` removes the subscriptions this instance names and leaves the queue."
13
13
  }
@@ -1,6 +1,13 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
- import { cf, type CfOptions } from '../cloudflare-api'
3
+ import {
4
+ type ApiTokenSource,
5
+ apiTokenFor,
6
+ apiTokenSchema,
7
+ cf,
8
+ type CfOptions,
9
+ tokenScopeHint,
10
+ } from '../cloudflare-api'
4
11
 
5
12
  /**
6
13
  * r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
@@ -12,6 +19,9 @@ import { cf, type CfOptions } from '../cloudflare-api'
12
19
  * as a `{ binding, from, output }` reference into this instance's outputs.
13
20
  *
14
21
  * Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
22
+ * Or set `apiToken` to take the token from an imported instance's output
23
+ * (`{ from, output }`, e.g. a `cloudflare-token`'s `tokenValue`) or from another
24
+ * key of secrets.yaml (`{ secret }`).
15
25
  */
16
26
 
17
27
  /**
@@ -19,20 +29,17 @@ import { cf, type CfOptions } from '../cloudflare-api'
19
29
  * per-module part of a Cloudflare failure. Everything else about the envelope
20
30
  * (the base URL, the error shapes, the typed throw) is `../cloudflare-api`'s.
21
31
  */
22
- const OPTS: CfOptions = {
23
- hints: {
24
- 10000:
25
- `rejected the token (10000 Authentication error). ` +
26
- `CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
27
- `Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
28
- },
29
- }
32
+ const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
33
+ hints: { 10000: tokenScopeHint(source, 'the Account → Workers R2 Storage: Edit scope') },
34
+ })
30
35
 
31
36
  export const r2Module = defineModule({
32
37
  name: 'r2',
33
38
  configSchema: z.object({
34
39
  /** Cloudflare account id (not a secret — it's in the dashboard URL). */
35
40
  accountId: z.string(),
41
+ /** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
42
+ apiToken: apiTokenSchema.optional(),
36
43
  /** Bucket name — account-scoped, so namespace it per project/env. */
37
44
  bucketName: z.string(),
38
45
  /**
@@ -45,7 +52,8 @@ export const r2Module = defineModule({
45
52
  bucketName: z.string(),
46
53
  }),
47
54
  async apply(config, ctx) {
48
- const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
55
+ const apiToken = apiTokenFor(config.apiToken, ctx)
56
+ const OPTS = optsFor(config.apiToken)
49
57
  const base = `/accounts/${config.accountId}/r2/buckets`
50
58
 
51
59
  const listing = await cf<{ buckets: Array<{ name: string }> }>(
@@ -87,7 +95,8 @@ export const r2Module = defineModule({
87
95
  * there would strand every instance behind it.
88
96
  */
89
97
  async destroy(config, ctx) {
90
- const apiToken = ctx.secret('CLOUDFLARE_API_TOKEN')
98
+ const apiToken = apiTokenFor(config.apiToken, ctx)
99
+ const OPTS = optsFor(config.apiToken)
91
100
  try {
92
101
  await cf(
93
102
  apiToken,
@@ -5,5 +5,5 @@
5
5
  "files": [{ "path": "index.ts" }],
6
6
  "secrets": ["CLOUDFLARE_API_TOKEN"],
7
7
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
8
- "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }\n\n`destroy` deletes the bucket when it is empty. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
8
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope. 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.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }\n\n`destroy` deletes the bucket when it is empty. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
9
9
  }
@@ -144,6 +144,42 @@ export function createApplyContext(input: ApplyContextInput): ApplyContext {
144
144
  outputValue(ref, field) {
145
145
  return resolveOutputValue(ref, input.imports, field)
146
146
  },
147
+ storeSecret: storeSecretOver(input),
148
+ }
149
+ }
150
+
151
+ /** A secrets.yaml key: what sops, a shell and an env var can all spell. */
152
+ const SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/
153
+
154
+ /**
155
+ * `ctx.storeSecret`, over whatever writer the engine supplied.
156
+ *
157
+ * With no writer this is an apply, a destroy or a probe, and the refusal is the
158
+ * point: see `ApplyContext.storeSecret`. The key and the value are checked
159
+ * before the writer is asked, so a typo does not become a line in an encrypted
160
+ * file that then has to be found and removed.
161
+ */
162
+ export function storeSecretOver(
163
+ input: ApplyContextInput,
164
+ ): (key: string, value: string) => Promise<void> {
165
+ return async (key, value) => {
166
+ if (!input.storeSecret) {
167
+ throw new Error(
168
+ `ctx.storeSecret("${key}") was called outside an action. A secret is stored only by ` +
169
+ '`zbc run <env> <instance> <action>`: an apply runs in CI, where a changed secrets.yaml is lost, ' +
170
+ 'and must be safe to run twice. Move the mint into an action and let apply read the stored key.',
171
+ )
172
+ }
173
+ if (!SECRET_KEY.test(key)) {
174
+ throw new Error(
175
+ `ctx.storeSecret: "${key}" is not a secrets.yaml key (letters, digits and underscores, not starting with a digit)`,
176
+ )
177
+ }
178
+ if (typeof value !== 'string' || value === '') {
179
+ throw new Error(`ctx.storeSecret("${key}") was given no value to store`)
180
+ }
181
+ await input.storeSecret(key, value)
182
+ input.secrets[key] = value
147
183
  }
148
184
  }
149
185
 
@@ -169,7 +205,12 @@ export function ensureApplyContext(ctx: ApplyContextInput | ApplyContext): Apply
169
205
  return {
170
206
  ...candidate,
171
207
  outputValue: (ref, field) => resolveOutputValue(ref, candidate.imports, field),
208
+ storeSecret: candidate.storeSecret ?? storeSecretOver(candidate),
172
209
  }
173
210
  }
211
+ // The same, one release on: a full context from before `storeSecret`.
212
+ if (typeof candidate.storeSecret !== 'function') {
213
+ return { ...candidate, storeSecret: storeSecretOver(candidate) }
214
+ }
174
215
  return candidate
175
216
  }
@@ -21,6 +21,13 @@ export interface TestContextOptions {
21
21
  imports?: Record<string, unknown>
22
22
  /** Default `/zbc-test-project` — a path no test should be writing to. */
23
23
  projectRoot?: string
24
+ /**
25
+ * This context is an action's: `ctx.storeSecret` records what it was given
26
+ * in `secretsStored`. Default false, where it throws as it does in a real
27
+ * apply, so a module that stores from `apply` fails its test and not its
28
+ * first deploy.
29
+ */
30
+ action?: boolean
24
31
  }
25
32
 
26
33
  export interface TestApplyContext extends ApplyContext {
@@ -31,6 +38,8 @@ export interface TestApplyContext extends ApplyContext {
31
38
  * through either `output` or `outputValue`.
32
39
  */
33
40
  readonly outputsRead: string[]
41
+ /** What `ctx.storeSecret` was asked to store, by key. Empty unless `action`. */
42
+ readonly secretsStored: Record<string, string>
34
43
  }
35
44
 
36
45
  /**
@@ -51,10 +60,18 @@ export interface TestApplyContext extends ApplyContext {
51
60
  * ```
52
61
  */
53
62
  export function createTestContext(opts: TestContextOptions = {}): TestApplyContext {
63
+ const secretsStored: Record<string, string> = {}
54
64
  const base = createApplyContext({
55
- secrets: opts.secrets ?? {},
65
+ secrets: { ...opts.secrets },
56
66
  imports: opts.imports ?? {},
57
67
  projectRoot: opts.projectRoot ?? '/zbc-test-project',
68
+ ...(opts.action
69
+ ? {
70
+ storeSecret: async (key: string, value: string) => {
71
+ secretsStored[key] = value
72
+ },
73
+ }
74
+ : {}),
58
75
  })
59
76
 
60
77
  const secretsRead: string[] = []
@@ -64,6 +81,7 @@ export function createTestContext(opts: TestContextOptions = {}): TestApplyConte
64
81
  ...base,
65
82
  secretsRead,
66
83
  outputsRead,
84
+ secretsStored,
67
85
  // Recorded before resolution, not after: a test asserting "this module
68
86
  // reads the secret its registry.json declares" has to see the ask even
69
87
  // when the ask is what failed.