@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
@@ -40,6 +40,7 @@ import { Hono } from 'hono'
40
40
 
41
41
  import type { Capabilities } from '../shared/capabilities'
42
42
  import { parseTokens } from '../shared/credentials'
43
+ import type { ScopedClaims } from '../shared/scoped-token'
43
44
  import { authorizeSubscribe } from '../shared/events'
44
45
  import {
45
46
  type McpDeps,
@@ -82,8 +83,9 @@ export async function handleMcp(
82
83
  caps: Capabilities,
83
84
  operator: Operator | null,
84
85
  host: string,
86
+ scoped: ScopedClaims | null = null,
85
87
  ): Promise<Response> {
86
- const server = createAgentgitMcp(deps(request, env, caps, operator, host))
88
+ const server = createAgentgitMcp(deps(request, env, caps, operator, host, scoped))
87
89
  const transport = new StreamableHTTPTransport()
88
90
  await server.connect(transport)
89
91
  const app = new Hono()
@@ -97,6 +99,7 @@ function deps(
97
99
  caps: Capabilities,
98
100
  operator: Operator | null,
99
101
  host: string,
102
+ scoped: ScopedClaims | null,
100
103
  ): McpDeps {
101
104
  // The caller's own credential, forwarded unchanged to every gated read. An
102
105
  // MCP client sends it as an ordinary Authorization header, which is the same
@@ -136,7 +139,14 @@ function deps(
136
139
  return { ok: true, repo: name, provenance: read.provenance }
137
140
  },
138
141
 
139
- watch: (name, ref, timeoutMs) => watchRef(env, caps, authorization, name, ref, timeoutMs),
142
+ watch: (name, ref, timeoutMs) =>
143
+ watchRef(env, caps, authorization, name, ref, timeoutMs, scoped !== null),
144
+
145
+ // A scoped token (docs/adr/0021) reaches the endpoint — the edge let it
146
+ // through, because the repositories here are named per tool call — and
147
+ // every tool refuses a name outside its claim before any of the reads
148
+ // above runs, so such a name never wakes the container (`shared/mcp.ts`).
149
+ scopedTo: scoped?.repo ?? null,
140
150
  }
141
151
  }
142
152
 
@@ -211,11 +221,16 @@ async function watchRef(
211
221
  repo: string,
212
222
  ref: string | null,
213
223
  timeoutMs: number,
224
+ scoped: boolean,
214
225
  ): Promise<WatchOutcome> {
215
226
  if (!caps.events) {
216
227
  throw new Error('this deployment does not serve the ref-event stream')
217
228
  }
229
+ // A scoped token stands in for the deployment credential, as it does on the
230
+ // socket route (`events()` in `index.ts`); its claim was checked by the
231
+ // caller and is checked again by the Durable Object.
218
232
  if (
233
+ !scoped &&
219
234
  !authorizeSubscribe({
220
235
  authorization,
221
236
  tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
@@ -0,0 +1 @@
1
+ {"src":["03465882c48eda7a","08dfef58c7aaa085","1cb9fbc7287804fd","212058b4cf645126","2166dfb799348b4e","2bd9836e6e9139f3","3058cf40096977ab","347cfb1ee57ec671","3667704de953bdab","4e244104218fe2cb","55da26c9db6f26cb","58e3f0d05357ead2","59bae6268b36701a","5ddd42dcefb92dd0","68bae40f05467752","747228c705b11d4e","88de60f6114a7fa5","8cacee2fbe4f7a09","917dfe4ddd67ec57","af921031cda3165c","b890770a8b136748","bfd77d3bda314e8b","c8bd2a9e9f9551d9","cb09733a2411579e","cb81b204e5f447cc","cc94f18a004aba5d","d13ace1bb2f53755","d92ca991417d1a9b","dabb9f64240b1c6f"],"modules":{"cloudflare":["06bbf1b35604306d","1c7a6e16f1b867f0","2682c5f3ef6cab0c","2d7a7939eb8872ca","36c1bca208793392","37807fe3d5042276","4cc54e3154bcfe9e","4fe2ea871de6e743","536209f853b71749","6084aa4167618322","687b75ceaebb8ef0","6ac1647137df1a85","6eaad97237ac0687","92cece7eabe7c8c5","9a008df8a0f8c9d1","9e86f4ba937b9ee3","b266de092bc97613","b6382f53b98d13e0","c318abe2edcc0753","e084e73c20088c7b"],"cloudflare-access":["0f185f7b77b44fe3","1ed97208e9bbf058","326b4749c6da0610","3c5894ff0be9d477","4aa1213dc6ca925c","726145d710554917","80d5348067acd076","84833035e9aa15d8","a86a8a893cfcc729","b6704b248c37d423","de14a0c490d8f6f6"],"cloudflare-api":["34dc1f1113b93f5f","418719ea73894a66","45d7cdfda8f6dfdd","4e77033aee735ccb","681aefdbdac1c5e0","82aefe0e0dd2e56b","8dcde96f515fa76d","f32ec49f4c9b6735"],"cloudflare-email":["4780e5b903d80935","4903ce268128fada","5bb76c19abae293d","6a0513bb67d78f8d","74f26c9df5c3c0ae","88a1ecd0d2c06ccb","a2bc5bdf74557624","b857bfe6118205f6","df9155611410f279","e0fb57c584823b00"],"cloudflare-stored-token":["9de9c20f4aae04a0","ba1b80b3be96ed86"],"cloudflare-token":["0d00bccd69cb82df","187986600ef2ecf0","1f1f99b00a70ee32","3b9f45de8a20710e","50d7c8a11a53925d","77efc6d02ca10b4f","855c1be1e8c7e937","9dc7111315ac1684","bdc18b0653a3b14f","c07cb05db1bea974","cf7ccc5e4ede8844","d5402f8bc9f5033b","e0259e092bc4da23","f94e4c4deabcca77","fb3761850c423bf5"],"cloudflare-tunnel":["00244f309afe8850","38e9033e4ea59735","97bce322a23fc5e4","9d8efda9c6558d35","9f632f54006fd107","c80ceae3f00e3f28","d5c4dc57698a2eeb","eb0eea2cd0c91e02"],"cloudflare-zone":["04cc6f77d80e40e8","12024ebde5164d70","171448cf37402fb7","41996b00cada53de","9d7080d7555d3bdd","a28bfae8177e278e","b701f20fa82567d0","d3c653b693cdaa1b","debca2ba59daf43e","eec003d0291bd099"],"d1":["3b747b2fb93146c1","675e62f28440fb7b","c046cc4f036f5c34","c0ac33a4a5453512","c996cb2d09f1bca0","ce79df51660a181b"],"docker-compose-stack":["2af7db146de34e07","ccba371fdefa0889","dcc022bd20d60e89"],"fly":["0cce6a3c9943d3bf","23051a397800c5ee","259dfadde9217dc6","374aa12a383556a5","6d21c3301e7e8c26","aef4216f65d05e11","b38e9eb066e2221f","f4a88196670f6a6e","f4bd5c4694d236b1"],"gcp-api":["07eed51dfc04bcdf","91a9afb707ea9355"],"gcp-service-account":["95d06bb603ba6723","c55994a69b49af81"],"host-dir":["50f6831ecaa0c67b","97ee336e322b8110","b835c422ae865d61"],"host-exec":["21bf91bdce04bac6","4e845769ed158498","bd201ddc1f461399"],"host-file":["3298087996013f79","48e5cdb4f00b3952","6eef31d4c54eaea7","a1bfa0f149e4406d"],"host-symlink":["4402e3207c07ab2d","54c8d9dff657e04b"],"incus-core":["00ab57608ef534e6","1d758ab733b3ab59","308f7a771355ac36","34647f78ac61d048","86f7f4b11fb7e20c","d09814b9c7ad573a"],"incus-storage-pool":["1b1202460c0b2de0","aaca83f691541330"],"nats-server":["2be90e33cdff4955","45e1e06c0ec814e9","93a13ff36d57605f"],"provision-core":["36a34ccca800f6ef","6bba00da01fcbaa2","88e945b115cc393d","8aa73f4a61e5375d","8ac1c148fad308cf","93ed7b1498c71a61"],"queue":["7eb1b4b6a04d87df","81f45c9033ad561d","9067f0b998c9e467","9a9be4e0f39dc4ba"],"r2":["186b6825e1d5f7ba","5db07a6753ff2abc","646407efecb52253","71b8f2fec30b0b52","962279eb12a18f73","b134bb16157a30f0","b3d10e22fd46b380","bf95b7c59ea0c6c5","c6d0d6024066b35c"],"remote-provision":["0365de8bb164e6dc","1989e63bc0039e8a","870a5bad136517bb","8c484514a2e0e58a"],"systemd-mask":["7a7685eda8efe67d","e91437190e65edcb"],"systemd-unit":["288ea5990229f30b","3ce315ef7880610b","9232311112f42b3f"],"turso":["2a5a24e5c569ed64","469281443b3cd144","7172345dac8ed40f","7cb03ab396e4f9a5","877e8db2ab8ecff8","ab3b727f963a18fd","b93a33f372c8c705","fab9090110fad4d4"],"vercel":["01e2a82da909a576","3553da00dd75a0aa","423bac1041a24cc9","7f54cdbd467a3a84","b4886210479aae7e"],"vm":["3fc1abaab5b6ba2d","9317e528780643d6","ea77340408170595","f4782518f103519d","f482753fb60c0709"],"vm-provision":["69501352b3131806","8f594f83c5abf037","926b598ddfb678ea","f9117e35d0cabbc8"]}}
@@ -137,6 +137,60 @@ const buildSchema = z.object({
137
137
  cwd: z.string().optional(),
138
138
  })
139
139
 
140
+ /**
141
+ * Poll `url` until its body contains `expected`, `consecutive` times in a row.
142
+ *
143
+ * A refused connection, a 5xx and an old version are all the same answer here,
144
+ * "not yet", because all three are what a deploy looks like from outside for
145
+ * its first seconds. Only the clock ends the wait, and the error then carries
146
+ * the last thing seen, since "timed out" alone does not say whether the Worker
147
+ * was down, old, or answering something else entirely.
148
+ *
149
+ * Exported for tests.
150
+ */
151
+ export async function awaitServed(opts: {
152
+ url: string
153
+ expected: string
154
+ headers: Record<string, string>
155
+ timeoutMs: number
156
+ intervalMs: number
157
+ consecutive: number
158
+ }): Promise<{ attempts: number; ms: number }> {
159
+ const started = Date.now()
160
+ let attempts = 0
161
+ let streak = 0
162
+ let last = 'no answer yet'
163
+ for (;;) {
164
+ attempts++
165
+ try {
166
+ const res = await fetch(opts.url, {
167
+ headers: opts.headers,
168
+ redirect: 'manual',
169
+ signal: AbortSignal.timeout(Math.max(opts.intervalMs, 10_000)),
170
+ })
171
+ const body = await res.text()
172
+ if (res.ok && body.includes(opts.expected)) {
173
+ streak++
174
+ if (streak >= opts.consecutive) return { attempts, ms: Date.now() - started }
175
+ } else {
176
+ streak = 0
177
+ last = `HTTP ${res.status}: ${body.slice(0, 200).replace(/\s+/g, ' ').trim() || '(empty body)'}`
178
+ }
179
+ } catch (err) {
180
+ streak = 0
181
+ last = `no response (${(err as Error).message})`
182
+ }
183
+ if (Date.now() - started + opts.intervalMs > opts.timeoutMs) {
184
+ throw new Error(
185
+ `${opts.url} did not name the deploy ${opts.expected} within ${Math.round(opts.timeoutMs / 1000)}s ` +
186
+ `(${attempts} request(s)). Last answer: ${last}. ` +
187
+ 'wrangler accepted the deploy, so the code is uploaded; what answers at that address is not it yet, or does not report its id.',
188
+ )
189
+ }
190
+ await new Promise((resolve) => setTimeout(resolve, opts.intervalMs))
191
+ }
192
+ }
193
+
140
194
  /**
141
195
  * The origin a route pattern answers on, for `deployUrl` when there is no
142
196
  * workers.dev URL to report.
@@ -549,6 +603,47 @@ export const cloudflareModule = defineModule({
549
603
  * pinning a value outranks the module deriving one.
550
604
  */
551
605
  deployIdVar: z.string().optional(),
606
+ /**
607
+ * Read the deploy id back from the Worker before the apply returns.
608
+ *
609
+ * wrangler exiting 0 says the upload was accepted. It does not say which
610
+ * version answers a request: the edge serves the old one for a while, a
611
+ * container keeps its old image, a route may point somewhere else. Seven
612
+ * consumers each wrote the same loop after `zbc apply` (poll a path until
613
+ * it names the commit just deployed, and only then tag or go on), and none
614
+ * of them shares a line with another.
615
+ *
616
+ * With this set, apply GETs `path` on the deployed Worker until the body
617
+ * contains the value of `deployIdVar`, `consecutive` times in a row, and
618
+ * fails when `timeoutMs` passes first, saying what the last answer was.
619
+ * What the path answers is the payload's job: a handler that returns its
620
+ * own var proves the Worker, and one that also asks its container proves
621
+ * the container.
622
+ *
623
+ * Needs `deployIdVar`: without an id in the artifact there is nothing to
624
+ * look for, and that is refused before anything is built.
625
+ *
626
+ * Why this is not a `ready` probe: the engine runs a probe only at an
627
+ * `imports` edge, and a deployed Worker is usually what nothing imports.
628
+ */
629
+ deployCheck: z
630
+ .object({
631
+ /** The path to GET, e.g. `/api/health`. */
632
+ path: z.string().startsWith('/'),
633
+ /**
634
+ * Where the Worker answers, e.g. `https://app.example.com`. Defaults to
635
+ * `deployUrl`. Required for a Worker whose hostname is a `custom_domain`
636
+ * in its own wrangler config, which leaves `deployUrl` empty.
637
+ */
638
+ origin: z.string().url().optional(),
639
+ /** Request headers: a literal, or `{ secret }` for a key of secrets.yaml. */
640
+ headers: z.record(z.union([z.string(), z.object({ secret: z.string() })])).default({}),
641
+ timeoutMs: z.number().int().positive().default(180_000),
642
+ intervalMs: z.number().int().positive().default(5_000),
643
+ /** Matching answers in a row before it counts: the edge serves old and new together for a while. */
644
+ consecutive: z.number().int().positive().default(2),
645
+ })
646
+ .optional(),
552
647
  /**
553
648
  * For container-backed Workers: roll the CONTAINER APPLICATION to the new
554
649
  * image on deploy (`--containers-rollout immediate`) instead of wrangler's
@@ -627,6 +722,8 @@ export const cloudflareModule = defineModule({
627
722
  }),
628
723
  outputs: z.object({
629
724
  deployUrl: z.string(),
725
+ /** The value of `deployIdVar` this apply shipped; absent when that key is unset. */
726
+ deployId: z.string().optional(),
630
727
  /**
631
728
  * The deployed Worker's script name, parsed from wrangler's "Deployed
632
729
  * <name> triggers" confirmation. Lets dependents reference this worker
@@ -643,6 +740,22 @@ export const cloudflareModule = defineModule({
643
740
  ? ctx.output(config.apiToken, 'apiToken')
644
741
  : ctx.secret('CLOUDFLARE_API_TOKEN')
645
742
 
743
+ if (config.deployCheck && !config.deployIdVar) {
744
+ throw new Error(
745
+ 'deployCheck is set but deployIdVar is not: the check looks for the deploy id in what the Worker answers, ' +
746
+ 'and without deployIdVar no id is put in the Worker. Set deployIdVar to the var the Worker reports.',
747
+ )
748
+ }
749
+ // Read before anything runs, for the same reason as the token.
750
+ const checkHeaders = Object.fromEntries(
751
+ Object.entries(config.deployCheck?.headers ?? {}).map(([name, value]) => [
752
+ name,
753
+ typeof value === 'string'
754
+ ? value
755
+ : ctx.secret(value.secret, { field: `deployCheck.headers.${name}` }),
756
+ ]),
757
+ )
758
+
646
759
  const env: NodeJS.ProcessEnv = {
647
760
  ...process.env,
648
761
  CLOUDFLARE_API_TOKEN: apiToken,
@@ -797,7 +910,33 @@ export const cloudflareModule = defineModule({
797
910
  console.log(` Set Worker secret: ${name}`)
798
911
  }
799
912
 
800
- return { deployUrl, workerName }
913
+ // 5. Read the deploy id back. After the secrets: each push is a new
914
+ // version of the script, and the one that must answer is the last.
915
+ const deployId = config.deployIdVar
916
+ ? resolvedVars.find((v) => v.name === config.deployIdVar)?.value
917
+ : undefined
918
+ if (config.deployCheck && deployId !== undefined) {
919
+ const origin = (config.deployCheck.origin ?? deployUrl).replace(/\/$/, '')
920
+ if (!origin) {
921
+ throw new Error(
922
+ 'deployCheck has nowhere to ask: wrangler printed no workers.dev URL and this instance has no `routes`. ' +
923
+ 'Set deployCheck.origin to where the Worker answers.',
924
+ )
925
+ }
926
+ const url = `${origin}${config.deployCheck.path}`
927
+ console.log(` Waiting for ${url} to name ${deployId}`)
928
+ const { attempts, ms } = await awaitServed({
929
+ url,
930
+ expected: deployId,
931
+ headers: checkHeaders,
932
+ timeoutMs: config.deployCheck.timeoutMs,
933
+ intervalMs: config.deployCheck.intervalMs,
934
+ consecutive: config.deployCheck.consecutive,
935
+ })
936
+ console.log(` Served: ${deployId} (${attempts} request(s), ${Math.round(ms / 1000)}s)`)
937
+ }
938
+
939
+ return { deployUrl, workerName, ...(deployId !== undefined ? { deployId } : {}) }
801
940
  },
802
941
  async destroy(config, ctx) {
803
942
  // Resolved exactly the way `apply` resolves it. The engine applies the
@@ -71,8 +71,16 @@ import { cf } from '../cloudflare-api'
71
71
  // An Access service token's consumer is somebody ELSE, deployed from a
72
72
  // different repo on a different cadence, so rolling on every apply would
73
73
  // invalidate the credential that consumer holds and take it down until it was
74
- // redeployed. So: created once, thereafter REUSED, never rotated. `rotate: true`
75
- // is the deliberate escape hatch for the day it leaks.
74
+ // redeployed. So: created once, thereafter REUSED, never rotated by an apply.
75
+ //
76
+ // ── Its secret is minted and stored by an action (ADR-0023) ──────────────
77
+ // Cloudflare returns the secret once, at creation. `apply` used to create the
78
+ // token and print the pair, and six consumers caught it there: from the log,
79
+ // from `--json`, or by hand. Now `zbc run <env> <instance> mint` creates the
80
+ // token and stores the secret under `serviceTokenSecret` in secrets.yaml, and
81
+ // `rotate` does the same for the day it leaks. `apply` creates no token and
82
+ // prints no secret: it requires the stored key and the token to exist, and
83
+ // says which action to run when either does not.
76
84
  //
77
85
  // There is deliberately no `destroy`. Destroying an Access application does not
78
86
  // tidy anything up, it takes the lock off the door.
@@ -206,14 +214,21 @@ const configSchema = z
206
214
  * A service token this module MINTS and owns, by name.
207
215
  *
208
216
  * Kept from the module this replaces, where it was required. Cloudflare
209
- * returns a service token's secret exactly once, at creation, so the apply
210
- * that creates it prints the pair and that is the only chance to capture it.
217
+ * returns a service token's secret exactly once, at creation, so the token
218
+ * is created by the `mint` action, which stores the secret, and never by
219
+ * `apply`. Needs `serviceTokenSecret`.
211
220
  */
212
221
  serviceTokenName: z.string().min(1).optional(),
213
222
  /**
214
- * Mint a NEW secret for the existing `serviceTokenName`. Off by default:
215
- * the consumer is separately deployed, and rotating without redeploying it
216
- * takes that consumer down. See the header.
223
+ * The key in this environment's secrets.yaml that holds the client secret
224
+ * of `serviceTokenName`. Required with it. `mint` and `rotate` write it;
225
+ * `apply` requires it to be there. A token minted before this key existed:
226
+ * put the secret you hold under the key, or run `rotate` if nobody holds it.
227
+ */
228
+ serviceTokenSecret: z.string().min(1).optional(),
229
+ /**
230
+ * Gone: rotating is the `rotate` action now. `false` is still accepted so
231
+ * an instance that spelled the old default out keeps parsing.
217
232
  */
218
233
  rotate: z.boolean().default(false),
219
234
  /**
@@ -356,13 +371,38 @@ const configSchema = z
356
371
  })
357
372
  }
358
373
 
359
- if (config.rotate && config.serviceTokenName === undefined) {
374
+ if (config.rotate) {
360
375
  ctx.addIssue({
361
376
  code: z.ZodIssueCode.custom,
362
377
  path: ['rotate'],
363
378
  message:
364
- 'rotate: true has nothing to rotate — this module only owns the token named by ' +
365
- 'serviceTokenName. A token reached through serviceTokens is rotated where it is minted.',
379
+ 'rotate: true is no longer read. An apply does not rotate a service token: run ' +
380
+ '`zbc run <env> <instance> rotate --yes`, which stores the new secret under ' +
381
+ 'serviceTokenSecret, and remove this key.',
382
+ })
383
+ }
384
+
385
+ if (config.serviceTokenName !== undefined && config.serviceTokenSecret === undefined) {
386
+ ctx.addIssue({
387
+ code: z.ZodIssueCode.custom,
388
+ path: ['serviceTokenSecret'],
389
+ message:
390
+ 'serviceTokenName needs serviceTokenSecret: the key in secrets.yaml that holds this ' +
391
+ "token's client secret. For a token that already exists, name the key the secret is " +
392
+ 'under (or put it there); if nobody holds the secret, name a key and run ' +
393
+ '`zbc run <env> <instance> rotate --yes`. For a new token, name a key and run ' +
394
+ '`zbc run <env> <instance> mint` before the first apply.',
395
+ })
396
+ }
397
+
398
+ if (config.serviceTokenSecret !== undefined && config.serviceTokenName === undefined) {
399
+ ctx.addIssue({
400
+ code: z.ZodIssueCode.custom,
401
+ path: ['serviceTokenSecret'],
402
+ message:
403
+ 'serviceTokenSecret names where a minted token keeps its secret, and this instance ' +
404
+ 'mints none: set serviceTokenName, or remove the key. A token reached through ' +
405
+ 'serviceTokens keeps its secret where it is minted.',
366
406
  })
367
407
  }
368
408
  })
@@ -949,20 +989,59 @@ interface ServiceToken {
949
989
  client_secret?: string
950
990
  }
951
991
 
992
+ /** The token this instance owns, looked up by name. */
993
+ async function findServiceToken(
994
+ token: string,
995
+ account: string,
996
+ name: string,
997
+ ): Promise<ServiceToken | undefined> {
998
+ const tokens = await cf<ServiceToken[]>(token, 'GET', `${account}/access/service_tokens`)
999
+ return tokens.find((t) => t.name === name)
1000
+ }
1001
+
1002
+ /** What an action needs from the config, checked once and said plainly. */
1003
+ function mintedToken(config: { serviceTokenName?: string; serviceTokenSecret?: string }): {
1004
+ name: string
1005
+ secretKey: string
1006
+ } {
1007
+ if (config.serviceTokenName === undefined || config.serviceTokenSecret === undefined) {
1008
+ throw new Error(
1009
+ 'this instance mints no service token: it declares no serviceTokenName. ' +
1010
+ 'A token reached through serviceTokens is minted and rotated where it is declared.',
1011
+ )
1012
+ }
1013
+ return { name: config.serviceTokenName, secretKey: config.serviceTokenSecret }
1014
+ }
1015
+
952
1016
  /**
953
- * Surface a freshly-minted pair the moment it exists.
1017
+ * Store a secret Cloudflare has just returned and will not return again.
954
1018
  *
955
- * Cloudflare returns a service token's secret exactly once, at creation. The
956
- * first version of this printed it at the END of apply, after the app and
957
- * policy were converged — and the very first real apply 403'd on the app, so
958
- * the secret was minted, never shown, and unrecoverable except by rotating.
959
- * Anything that can fail between minting a write-once value and showing it is a
960
- * chance to lose it, so nothing goes between.
1019
+ * Nothing goes between the call that returned it and this. If the write fails
1020
+ * the secret is gone, and the error has to say what that means and what to
1021
+ * run, because "sops set failed" alone leaves a live token nobody can use.
961
1022
  */
962
- function announce(clientId: string, clientSecret: string): void {
963
- console.log(`\n ── capture these now; the secret is never shown again ──`)
964
- console.log(` CF_ACCESS_CLIENT_ID=${clientId}`)
965
- console.log(` CF_ACCESS_CLIENT_SECRET=${clientSecret}\n`)
1023
+ async function storeShownOnce(
1024
+ ctx: ApplyContext,
1025
+ secretKey: string,
1026
+ secret: string,
1027
+ tokenName: string,
1028
+ ): Promise<void> {
1029
+ if (!secret) {
1030
+ throw new Error(
1031
+ `Cloudflare returned no client secret for service token "${tokenName}". Nothing was stored. ` +
1032
+ 'Run the rotate action to get one.',
1033
+ )
1034
+ }
1035
+ try {
1036
+ await ctx.storeSecret(secretKey, secret)
1037
+ } catch (err) {
1038
+ throw new Error(
1039
+ `Service token "${tokenName}" has a new secret and storing it under ${secretKey} failed: ` +
1040
+ `${(err as Error).message}\n Cloudflare will not show that secret again. Fix what stopped ` +
1041
+ 'the write, then run the rotate action (with --yes) to mint one that can be stored.',
1042
+ { cause: err },
1043
+ )
1044
+ }
966
1045
  }
967
1046
 
968
1047
  export const cloudflareAccessModule = defineModule({
@@ -998,9 +1077,10 @@ export const cloudflareAccessModule = defineModule({
998
1077
  serviceTokenId: z.string(),
999
1078
  /** Safe to output — the id is not a secret. */
1000
1079
  clientId: z.string(),
1001
- /** Only non-empty on the apply that CREATED or rotated the minted token. */
1002
- clientSecret: z.string(),
1003
- /** Whether the minted service token was created by this apply. */
1080
+ /**
1081
+ * Always false: an apply creates no service token (the `mint` action does).
1082
+ * Kept so an importer that reads it keeps resolving.
1083
+ */
1004
1084
  created: z.boolean(),
1005
1085
  /** Whether the application was created by this apply. */
1006
1086
  appCreated: z.boolean(),
@@ -1013,6 +1093,15 @@ export const cloudflareAccessModule = defineModule({
1013
1093
  const account = `/accounts/${config.accountId}`
1014
1094
  const domain = normalizeDomain(config.domain)
1015
1095
 
1096
+ // The secret the minted token's holders use. Not needed to converge
1097
+ // anything here; required so that a token whose secret nobody stored is
1098
+ // found on an apply and not on the day a caller needs it.
1099
+ if (config.serviceTokenSecret !== undefined) {
1100
+ ctx.secret(config.serviceTokenSecret, {
1101
+ field: `serviceTokenSecret (the client secret of "${config.serviceTokenName}"; the mint and rotate actions store it)`,
1102
+ })
1103
+ }
1104
+
1016
1105
  // Resolved before anything is called, so a service token instance that is
1017
1106
  // not imported fails while nothing has been touched.
1018
1107
  const referencedTokenIds = config.serviceTokens.map((ref, index) =>
@@ -1240,43 +1329,21 @@ export const cloudflareAccessModule = defineModule({
1240
1329
  )
1241
1330
  }
1242
1331
 
1243
- // 4. The service token this module owns, if one is declared.
1244
- //
1245
- // AFTER the application, deliberately. The measured failure that made
1246
- // `announce` exist was a 403 on creating the app, which — with the mint
1247
- // first — burned a write-once secret for an application that was never
1248
- // created. Minting after means the same 403 costs nothing, and the
1249
- // policy below is the only thing that needs the id.
1332
+ // 4. The service token this module owns, if one is declared. Found, never
1333
+ // made: an apply that created it would hold a secret it may not store
1334
+ // (ADR-0023) and must not print.
1250
1335
  let mintedTokenId = ''
1251
1336
  let clientId = ''
1252
- let clientSecret = ''
1253
- let tokenCreated = false
1254
- let rotated = false
1255
1337
  if (config.serviceTokenName !== undefined) {
1256
- const tokens = await cf<ServiceToken[]>(token, 'GET', `${account}/access/service_tokens`)
1257
- let svc = tokens.find((t) => t.name === config.serviceTokenName)
1338
+ const svc = await findServiceToken(token, account, config.serviceTokenName)
1258
1339
  if (!svc) {
1259
- svc = await cf<ServiceToken>(token, 'POST', `${account}/access/service_tokens`, {
1260
- name: config.serviceTokenName,
1261
- duration: '8760h', // one year; Cloudflare's max, and expiry here is an outage
1262
- })
1263
- clientSecret = svc.client_secret ?? ''
1264
- tokenCreated = true
1265
- console.log(` Created service token "${config.serviceTokenName}" (${svc.id})`)
1266
- announce(svc.client_id, clientSecret)
1267
- } else if (config.rotate) {
1268
- const fresh = await cf<ServiceToken>(
1269
- token,
1270
- 'POST',
1271
- `${account}/access/service_tokens/${svc.id}/rotate`,
1340
+ throw new Error(
1341
+ `Service token "${config.serviceTokenName}" does not exist yet. An apply does not create it, ` +
1342
+ 'because its secret is shown once and only an action may store it: run ' +
1343
+ '`zbc run <env> <this instance> mint`, commit secrets.yaml, and apply again.',
1272
1344
  )
1273
- clientSecret = fresh.client_secret ?? ''
1274
- rotated = true
1275
- console.log(` ROTATED service token "${config.serviceTokenName}" — the old secret is dead`)
1276
- announce(svc.client_id, clientSecret)
1277
- } else {
1278
- console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists, not rotated`)
1279
1345
  }
1346
+ console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists`)
1280
1347
  mintedTokenId = svc.id
1281
1348
  clientId = svc.client_id
1282
1349
  }
@@ -1429,19 +1496,63 @@ export const cloudflareAccessModule = defineModule({
1429
1496
  serviceTokenIds,
1430
1497
  serviceTokenId: mintedTokenId,
1431
1498
  clientId,
1432
- clientSecret,
1433
- created: tokenCreated,
1499
+ created: false,
1434
1500
  appCreated: found === undefined,
1435
1501
  // What is still undeclared AFTER this apply, not what was before it.
1436
1502
  undeclared: remaining.map((policy) => `${policy.name} (${policy.decision})`),
1437
- changed:
1438
- appChanged ||
1439
- rewrote ||
1440
- deleted > 0 ||
1441
- orgRenamed ||
1442
- idpsCreated > 0 ||
1443
- tokenCreated ||
1444
- rotated,
1503
+ changed: appChanged || rewrote || deleted > 0 || orgRenamed || idpsCreated > 0,
1445
1504
  }
1446
1505
  },
1506
+ actions: {
1507
+ mint: {
1508
+ description:
1509
+ 'Create the service token named by serviceTokenName and store its client secret under serviceTokenSecret',
1510
+ async run(config, ctx) {
1511
+ const { name, secretKey } = mintedToken(config)
1512
+ const token = resolveAccessToken(config.apiToken, ctx)
1513
+ const account = `/accounts/${config.accountId}`
1514
+ const existing = await findServiceToken(token, account, name)
1515
+ if (existing) {
1516
+ throw new Error(
1517
+ `Service token "${name}" (${existing.id}) already exists, and Cloudflare does not show an ` +
1518
+ `existing token's secret. If you hold it, put it in secrets.yaml under ${secretKey}. ` +
1519
+ 'If nobody does, run the rotate action (with --yes): the old secret stops working at once.',
1520
+ )
1521
+ }
1522
+ const svc = await cf<ServiceToken>(token, 'POST', `${account}/access/service_tokens`, {
1523
+ name,
1524
+ duration: '8760h', // one year; Cloudflare's max, and expiry here is an outage
1525
+ })
1526
+ await storeShownOnce(ctx, secretKey, svc.client_secret ?? '', name)
1527
+ console.log(` Created service token "${name}" (${svc.id}), client id ${svc.client_id}`)
1528
+ console.log(` Its secret is under ${secretKey}. Apply this instance to admit the token.`)
1529
+ },
1530
+ },
1531
+ rotate: {
1532
+ description:
1533
+ "Replace the service token's client secret and store the new one; the old secret stops working at once",
1534
+ irreversible: true,
1535
+ async run(config, ctx) {
1536
+ const { name, secretKey } = mintedToken(config)
1537
+ const token = resolveAccessToken(config.apiToken, ctx)
1538
+ const account = `/accounts/${config.accountId}`
1539
+ const svc = await findServiceToken(token, account, name)
1540
+ if (!svc) {
1541
+ throw new Error(
1542
+ `Service token "${name}" does not exist, so there is nothing to rotate. Run the mint action.`,
1543
+ )
1544
+ }
1545
+ const fresh = await cf<ServiceToken>(
1546
+ token,
1547
+ 'POST',
1548
+ `${account}/access/service_tokens/${svc.id}/rotate`,
1549
+ )
1550
+ await storeShownOnce(ctx, secretKey, fresh.client_secret ?? '', name)
1551
+ console.log(` ROTATED service token "${name}" (${svc.id}): the old secret is dead`)
1552
+ console.log(
1553
+ ` The new one is under ${secretKey}. Whatever holds the old secret needs it now.`,
1554
+ )
1555
+ },
1556
+ },
1557
+ },
1447
1558
  })
@@ -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 Access: Apps and Policies write on the account, plus Access: Service Tokens write if `serviceTokenName` is declared and Access: Organizations / Identity Providers for the organisation-level fields. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. THREE FIELDS ARE ORGANISATION-LEVEL, not per-application — `teamDomain`, `orgName` and `identityProviders` converge the Zero Trust organisation shared by every Access application in the account; undeclared identity providers are reported and never removed, and declaring none converges none. `emails: []` plus `serviceTokenName` is the machine-only shape (say `sessionDuration: '0s'`, so no cookie is ever issued); `emails: [...]` plus `identityProviders: ['onetimepin']` is the human shape. A minted service token's secret is returned exactly once, on the apply that creates it — put it somewhere a caller can read it, not in the declaration. `bypass: true` with no emails or tokens is the third shape: Cloudflare's Bypass for everyone on a narrow path (`host/prefix/*`) under a gated host, for a path whose Worker authenticates every request itself. For an application nested under another on the same host, `pathCookieAttribute: true` keeps the two sessions apart; `sameSiteCookieAttribute: 'lax'` is written only when declared. The credential is `apiToken: { from, output }` (an imported `cloudflare-token`), or `apiToken: { secret: 'CLOUDFLARE_API_TOKEN' }` to use the environment's deploy credential."
10
+ "instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Access: Apps and Policies write on the account, plus Access: Service Tokens write if `serviceTokenName` is declared (then `serviceTokenSecret` is required too: the secrets.yaml key the token's client secret is kept under. The token is created by `zbc run <env> <instance> mint`, which stores the secret there, and replaced by `zbc run <env> <instance> rotate --yes`; an apply neither creates nor rotates it and prints no secret) and Access: Organizations / Identity Providers for the organisation-level fields. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. THREE FIELDS ARE ORGANISATION-LEVEL, not per-application — `teamDomain`, `orgName` and `identityProviders` converge the Zero Trust organisation shared by every Access application in the account; undeclared identity providers are reported and never removed, and declaring none converges none. `emails: []` plus `serviceTokenName` is the machine-only shape (say `sessionDuration: '0s'`, so no cookie is ever issued); `emails: [...]` plus `identityProviders: ['onetimepin']` is the human shape. A minted service token's secret is returned exactly once, on the apply that creates it — put it somewhere a caller can read it, not in the declaration. `bypass: true` with no emails or tokens is the third shape: Cloudflare's Bypass for everyone on a narrow path (`host/prefix/*`) under a gated host, for a path whose Worker authenticates every request itself. For an application nested under another on the same host, `pathCookieAttribute: true` keeps the two sessions apart; `sameSiteCookieAttribute: 'lax'` is written only when declared. The credential is `apiToken: { from, output }` (an imported `cloudflare-token`), or `apiToken: { secret: 'CLOUDFLARE_API_TOKEN' }` to use the environment's deploy credential."
11
11
  }
@@ -24,7 +24,9 @@
24
24
  // is `CfOptions.hints`. `c9s/src/cf.ts` is a fifth copy and stays: it lives in
25
25
  // a separate package and cannot import a template.
26
26
 
27
+ import { z } from 'zod'
27
28
  import { resolveOutput } from '../../src/context'
29
+ import type { ApplyContext } from '../../src/types'
28
30
 
29
31
  export const API = 'https://api.cloudflare.com/client/v4'
30
32
 
@@ -290,3 +292,57 @@ export function resolveRef(
290
292
  ): string {
291
293
  return resolveOutput(ref, imports, field)
292
294
  }
295
+
296
+ /**
297
+ * Where a Cloudflare module's API token comes from, when it is not
298
+ * `CLOUDFLARE_API_TOKEN` in this environment's secrets.yaml.
299
+ *
300
+ * `{ from, output }` is an imported instance's output: a `cloudflare-token`
301
+ * mints a token scoped to one job and nothing keeps a copy at rest. `{ secret }`
302
+ * is another key of secrets.yaml: an environment that reaches two accounts
303
+ * holds two tokens, and one name cannot be both.
304
+ *
305
+ * Three consumers kept forks of `r2` and `cloudflare-email` for this field
306
+ * alone: their environment holds a root token that can only mint, so a module
307
+ * that reads `CLOUDFLARE_API_TOKEN` and nothing else has no token to read.
308
+ */
309
+ export const apiTokenSchema = z.union([
310
+ z.object({ from: z.string(), output: z.string() }),
311
+ z.object({ secret: z.string() }),
312
+ ])
313
+ export type ApiTokenSource = z.infer<typeof apiTokenSchema>
314
+
315
+ /**
316
+ * The token a module's calls use. One function so a module's apply, destroy
317
+ * and readiness probe cannot disagree about it.
318
+ */
319
+ export function apiTokenFor(
320
+ source: ApiTokenSource | undefined,
321
+ ctx: Pick<ApplyContext, 'secret' | 'output'>,
322
+ ): string {
323
+ if (!source) return ctx.secret('CLOUDFLARE_API_TOKEN')
324
+ return 'secret' in source
325
+ ? ctx.secret(source.secret, { field: 'apiToken' })
326
+ : ctx.output(source, 'apiToken')
327
+ }
328
+
329
+ /**
330
+ * The 10000 hint for a module, naming the token that was actually refused.
331
+ *
332
+ * A hint that says `CLOUDFLARE_API_TOKEN` about a token an import supplied
333
+ * sends the reader to edit a token the call never used. `needs` is the module's
334
+ * own part, written to follow "is likely missing".
335
+ */
336
+ export function tokenScopeHint(source: ApiTokenSource | undefined, needs: string): string {
337
+ const refused = 'rejected the token (10000 Authentication error). '
338
+ const edit =
339
+ 'Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.'
340
+ if (!source) return `${refused}CLOUDFLARE_API_TOKEN is likely missing ${needs}. ${edit}`
341
+ if ('secret' in source) {
342
+ return `${refused}${source.secret} (this instance's apiToken) is likely missing ${needs}. ${edit}`
343
+ }
344
+ return (
345
+ `${refused}The token this instance takes from \`${source.from}\` (its \`${source.output}\` output) ` +
346
+ `is likely missing ${needs}. Grant it where that instance mints the token, and re-run zbc apply.`
347
+ )
348
+ }