@zabaca/zbc 0.24.0 → 0.25.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 (34) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/list.ts +6 -3
  5. package/src/commands/update.ts +42 -0
  6. package/src/engine/destroy.ts +23 -2
  7. package/src/engine/resolve.ts +5 -0
  8. package/src/utils/subtree.ts +37 -7
  9. package/src/utils/vendor-stamp.ts +92 -1
  10. package/src/utils/vendored-app.ts +353 -0
  11. package/templates/CLAUDE.md +1 -1
  12. package/templates/apps/walgit/worker/mcp.ts +1 -2
  13. package/templates/apps/warehouse/worker/router.ts +1 -2
  14. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  15. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  16. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  17. package/templates/infra/modules/d1/index.ts +133 -4
  18. package/templates/infra/modules/d1/registry.json +4 -1
  19. package/templates/infra/modules/queue/index.ts +313 -0
  20. package/templates/infra/modules/queue/registry.json +13 -0
  21. package/templates/infra/modules/r2/registry.json +1 -1
  22. package/templates/infra/src/define-module.ts +19 -2
  23. package/templates/infra/src/types.ts +24 -0
  24. package/templates/apps/inbox/package.json +0 -26
  25. package/templates/apps/inbox/public/index.html +0 -379
  26. package/templates/apps/inbox/registry.json +0 -9
  27. package/templates/apps/inbox/tsconfig.json +0 -19
  28. package/templates/apps/inbox/worker/api.ts +0 -197
  29. package/templates/apps/inbox/worker/commands.ts +0 -299
  30. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  31. package/templates/apps/inbox/worker/index.ts +0 -195
  32. package/templates/apps/inbox/worker/mcp.ts +0 -228
  33. package/templates/apps/inbox/worker/shared.ts +0 -117
  34. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
+ import type { ApplyContext } from '../../src/types'
3
4
  import { cf } from '../cloudflare-api'
4
5
 
5
6
  // cloudflare-access — a Zero Trust application and the list of principals that
@@ -26,6 +27,17 @@ import { cf } from '../cloudflare-api'
26
27
  // policy and read as unchanged. `planPolicies` is the seam that keeps it, and
27
28
  // `index.test.ts` fails if anybody widens it.
28
29
  //
30
+ // ── A THIRD KIND, AND IT IS THE DANGEROUS ONE: BYPASS ─────────────────────
31
+ // `bypass: true` declares an application whose one policy is Cloudflare's
32
+ // Bypass for everyone: the edge asks for no sign-in on that path and passes the
33
+ // request through with no assertion. It exists for a path nested under a gated
34
+ // host whose Worker authenticates every request on it itself (a guest's link,
35
+ // a signer's private URL). It has its own reader (`policyEveryone`), it refuses
36
+ // to be declared beside people or tokens, and the people and Service Auth
37
+ // readers still return null on it, so it cannot be mistaken for a match and a
38
+ // people policy that gains an `everyone` rule is still rewritten. Every apply
39
+ // of one prints a BYPASS line.
40
+ //
29
41
  // ── THE ORGANISATION IS NOT SCOPED TO THIS APPLICATION ────────────────────
30
42
  // `teamDomain`, `orgName` and `identityProviders` are properties of the whole
31
43
  // Zero Trust organisation, not of the application this instance declares. An
@@ -80,11 +92,20 @@ const configSchema = z
80
92
  * `tokenValue`. Not a secrets.yaml key, so nothing that can edit who
81
93
  * reaches this application comes to rest in the consuming repo.
82
94
  *
95
+ * Or `{ secret }`: a key of this environment's secrets.yaml, for an
96
+ * environment that mints no tokens and applies Access with the deploy
97
+ * credential it already holds (`{ secret: 'CLOUDFLARE_API_TOKEN' }`). That
98
+ * credential is at rest in the consuming repo, so this form trades the
99
+ * property above for not needing a root token to mint one.
100
+ *
83
101
  * Needs "Access: Apps and Policies Write", plus "Access: Service Tokens
84
102
  * Write" if `serviceTokenName` is declared, and "Access: Organizations" /
85
103
  * "Access: Identity Providers" for the organisation-level fields.
86
104
  */
87
- apiToken: z.object({ from: z.string(), output: z.string() }),
105
+ apiToken: z.union([
106
+ z.object({ from: z.string(), output: z.string() }),
107
+ z.object({ secret: z.string() }),
108
+ ]),
88
109
  /**
89
110
  * The Zero Trust team domain, bare, with no scheme and no path.
90
111
  *
@@ -224,19 +245,88 @@ const configSchema = z
224
245
  enableBindingCookie: z.boolean().default(false),
225
246
  /** `HttpOnly` on the Access cookie. On, matching Cloudflare's own default. */
226
247
  httpOnlyCookieAttribute: z.boolean().default(true),
248
+ /**
249
+ * Scope the application's session cookie to its path (Cloudflare's
250
+ * `path_cookie_attribute`). Off by default, which is Cloudflare's own
251
+ * default.
252
+ *
253
+ * ON for an application nested under another on the same host (one on
254
+ * `/forms` under a whole-host one). With it off, both applications write
255
+ * ONE `CF_Authorization` cookie on the host with `Path=/`, and signing in
256
+ * to the narrower one replaces the wider one's session, so a month's
257
+ * sign-in falls to the narrower one's day. With it on, the narrow
258
+ * application's cookie is `Path=/forms` and the wide one's is never
259
+ * touched. That relies on browsers sending the cookie with the longer path
260
+ * first and Access reading the first `CF_Authorization` it is sent.
261
+ */
262
+ pathCookieAttribute: z.boolean().default(false),
263
+ /**
264
+ * The `SameSite` attribute of the application's session cookie
265
+ * (Cloudflare's `same_site_cookie_attribute`).
266
+ *
267
+ * NOT SET by default, and then the field is left out of the body AND out
268
+ * of the comparison: an application that does not declare it is neither
269
+ * written nor reported, and Cloudflare's own default (`none`) stays.
270
+ *
271
+ * `lax` suits an application whose pages and API are only ever used from
272
+ * its own host: a cookie a cross-site POST would carry is then not sent, so
273
+ * a page on another site cannot make the browser carry the sign-in into a
274
+ * write, while top-level navigations (Access's own callback, a followed
275
+ * link) still carry it. Leave it unset where a flow needs the cookie across
276
+ * sites, such as a silent renewal inside a frame.
277
+ */
278
+ sameSiteCookieAttribute: z.enum(['strict', 'lax', 'none']).optional(),
227
279
  /**
228
280
  * Perform the deletions this module prints. False by default: an undeclared
229
281
  * policy is always reported, never removed, until an operator has read the
230
282
  * line and opted in.
231
283
  */
232
284
  allowDelete: z.boolean().default(false),
285
+ /**
286
+ * Make this a BYPASS application: Cloudflare's Bypass action for everyone,
287
+ * so the edge asks for no sign-in on `domain` and passes the request
288
+ * through with NO assertion. For a path whose own Worker authenticates
289
+ * every request itself (a guest's link, a signer's private URL).
290
+ *
291
+ * Off by default. When on, the application admits nobody by address or
292
+ * token (`emails`, `serviceTokens` and `serviceTokenName` must be empty),
293
+ * because an application that both bypasses and names people would read
294
+ * as a lock and be a door. It declares exactly one policy, named
295
+ * `policyName`, of kind `everyone`, compared by its own reader
296
+ * (`policyEveryone`).
297
+ *
298
+ * Declare `domain` as narrowly as the Worker's open paths are
299
+ * (`host/prefix/*`): Cloudflare serves the most specific application a
300
+ * request matches, so a bypass on a path takes that path, and nothing
301
+ * else, off a whole-host application's gate.
302
+ */
303
+ bypass: z.boolean().default(false),
233
304
  })
234
305
  .superRefine((config, ctx) => {
306
+ // A bypass names nobody by design: the rule for it is that it names nobody
307
+ // at all, and the "no way in" rule below is the one it is exempt from.
308
+ if (
309
+ config.bypass &&
310
+ (config.emails.length > 0 ||
311
+ config.serviceTokens.length > 0 ||
312
+ config.serviceTokenName !== undefined)
313
+ ) {
314
+ ctx.addIssue({
315
+ code: z.ZodIssueCode.custom,
316
+ path: ['bypass'],
317
+ message:
318
+ 'a bypass application admits everyone without a sign-in, so it cannot also name people ' +
319
+ 'or service tokens: emails, serviceTokens and serviceTokenName must be empty. Declare ' +
320
+ 'the people on the application that gates the rest of the host.',
321
+ })
322
+ }
323
+
235
324
  // An application with neither a person nor a machine on it is one nobody
236
325
  // can reach, and it should be deleted rather than emptied. The generalised
237
326
  // form of "refuse an empty allow list": emails are no longer the only kind
238
327
  // of principal, so the rule is about the union.
239
328
  if (
329
+ !config.bypass &&
240
330
  config.emails.length === 0 &&
241
331
  config.serviceTokens.length === 0 &&
242
332
  config.serviceTokenName === undefined
@@ -355,6 +445,24 @@ export function policyServiceTokens(policy: Pick<AccessPolicy, 'include'>): stri
355
445
  return Array.from(new Set(tokens)).toSorted()
356
446
  }
357
447
 
448
+ /**
449
+ * Whether a live policy admits EXACTLY everyone: its `include` is the one rule
450
+ * `{ everyone: {} }` and nothing else.
451
+ *
452
+ * The third reader, beside `policyEmails` and `policyServiceTokens`, and it
453
+ * keeps their property from the other side. Those two return null on an
454
+ * `everyone` rule, so a bypass can never pass for a people policy; this one is
455
+ * false on anything but a lone `everyone`, so a bypass whose policy also
456
+ * carries a second, narrower include is rewritten rather than read as
457
+ * unchanged.
458
+ */
459
+ export function policyEveryone(policy: Pick<AccessPolicy, 'include'>): boolean {
460
+ const include = policy.include ?? []
461
+ if (include.length !== 1) return false
462
+ const keys = Object.keys(include[0] ?? {})
463
+ return keys.length === 1 && keys[0] === 'everyone'
464
+ }
465
+
358
466
  /**
359
467
  * One policy this instance declares, and the whole of what it admits.
360
468
  *
@@ -378,6 +486,11 @@ export type DeclaredPolicy =
378
486
  tokenIds: readonly string[]
379
487
  sessionDuration?: string
380
488
  }
489
+ | {
490
+ /** Cloudflare's Bypass for everyone: no sign-in at all. Only `bypass: true` declares it. */
491
+ name: string
492
+ admits: 'everyone'
493
+ }
381
494
 
382
495
  /**
383
496
  * What Cloudflare calls the action, per kind.
@@ -389,12 +502,14 @@ export type DeclaredPolicy =
389
502
  * decision is part of what is compared rather than something set once at
390
503
  * creation.
391
504
  */
392
- export function decisionFor(declared: DeclaredPolicy): 'allow' | 'non_identity' {
505
+ export function decisionFor(declared: DeclaredPolicy): 'allow' | 'non_identity' | 'bypass' {
506
+ if (declared.admits === 'everyone') return 'bypass'
393
507
  return declared.admits === 'emails' ? 'allow' : 'non_identity'
394
508
  }
395
509
 
396
510
  /** The `include` list a declared policy should carry. */
397
511
  export function includesFor(declared: DeclaredPolicy): IncludeRule[] {
512
+ if (declared.admits === 'everyone') return [{ everyone: {} }]
398
513
  return declared.admits === 'emails'
399
514
  ? emailIncludes(declared.emails)
400
515
  : serviceTokenIncludes(declared.tokenIds)
@@ -416,7 +531,8 @@ export function policyBodyFor(declared: DeclaredPolicy): Record<string, unknown>
416
531
  include: includesFor(declared),
417
532
  exclude: [],
418
533
  require: [],
419
- ...(declared.sessionDuration === undefined
534
+ // A bypass has no session: nobody signs in.
535
+ ...(declared.admits === 'everyone' || declared.sessionDuration === undefined
420
536
  ? {}
421
537
  : { session_duration: declared.sessionDuration }),
422
538
  }
@@ -424,6 +540,7 @@ export function policyBodyFor(declared: DeclaredPolicy): Record<string, unknown>
424
540
 
425
541
  /** What a declared policy admits, in words, for the apply log. */
426
542
  function admits(entry: DeclaredPolicy): string {
543
+ if (entry.admits === 'everyone') return 'everyone, with no sign-in (a bypass)'
427
544
  return entry.admits === 'emails' ? entry.emails.join(', ') : entry.tokenIds.join(', ')
428
545
  }
429
546
 
@@ -480,6 +597,22 @@ function planOne(declared: DeclaredPolicy, mine: AccessPolicy | undefined): Poli
480
597
  }
481
598
  }
482
599
 
600
+ // A bypass is read by its own reader, and has no session to compare.
601
+ if (declared.admits === 'everyone') {
602
+ if (!policyEveryone(mine)) {
603
+ return {
604
+ declared,
605
+ action: 'update',
606
+ mine,
607
+ reason: 'it admits by something other than a lone rule for everyone',
608
+ }
609
+ }
610
+ if ((mine.exclude ?? []).length > 0 || (mine.require ?? []).length > 0) {
611
+ return { declared, action: 'update', mine, reason: 'it carries exclude or require rules' }
612
+ }
613
+ return { declared, action: 'unchanged', mine }
614
+ }
615
+
483
616
  // Each kind is read by its OWN reader, and each returns null the moment the
484
617
  // policy admits by anything else. That is what keeps "an everyone rule beside
485
618
  // the addresses is rewritten" true after a policy that admits by something
@@ -631,6 +764,8 @@ export function appBody(config: {
631
764
  appLauncherVisible: boolean
632
765
  enableBindingCookie: boolean
633
766
  httpOnlyCookieAttribute: boolean
767
+ pathCookieAttribute?: boolean
768
+ sameSiteCookieAttribute?: 'strict' | 'lax' | 'none'
634
769
  }): Record<string, unknown> {
635
770
  return {
636
771
  name: config.name,
@@ -640,6 +775,12 @@ export function appBody(config: {
640
775
  app_launcher_visible: config.appLauncherVisible,
641
776
  enable_binding_cookie: config.enableBindingCookie,
642
777
  http_only_cookie_attribute: config.httpOnlyCookieAttribute,
778
+ path_cookie_attribute: config.pathCookieAttribute ?? false,
779
+ // Only when declared: an application that says nothing is not written to
780
+ // and not compared (see `sameSiteCookieAttribute`).
781
+ ...(config.sameSiteCookieAttribute !== undefined
782
+ ? { same_site_cookie_attribute: config.sameSiteCookieAttribute }
783
+ : {}),
643
784
  }
644
785
  }
645
786
 
@@ -679,6 +820,13 @@ export function appDiffers(
679
820
  if (key === 'domain') {
680
821
  return normalizeDomain(String(want)) !== normalizeDomain(String(have ?? ''))
681
822
  }
823
+ // Two fields Cloudflare omits while they hold its default. Reading that
824
+ // absence as different from the default would make the first apply of
825
+ // every application that never set them report a change it does not make.
826
+ if (key === 'path_cookie_attribute') return Boolean(want) !== Boolean(have)
827
+ if (key === 'same_site_cookie_attribute') {
828
+ return String(want).toLowerCase() !== String(have ?? 'none').toLowerCase()
829
+ }
682
830
  return JSON.stringify(want) !== JSON.stringify(have)
683
831
  })
684
832
  }
@@ -729,6 +877,51 @@ export function findApp<T extends { id: string; name: string; domain: string }>(
729
877
  return byName ? { app: byName, by: 'name' } : undefined
730
878
  }
731
879
 
880
+ /** An Access application's audience tag: 64 lowercase hex characters. */
881
+ const AUDIENCE_TAG = /^[0-9a-f]{64}$/
882
+
883
+ /**
884
+ * Refuse an audience tag that is present and malformed. Pure; exported for
885
+ * tests.
886
+ *
887
+ * WHY HERE AND NOT ONLY IN THE CONSUMER. A Worker that verifies Access
888
+ * assertions is deployed with this instance's `aud` as a var, and the deploy
889
+ * only checks that the output is a non-empty string. A malformed one would be
890
+ * deployed as the audience every assertion is compared against, so every
891
+ * request, real ones included, would be refused while the apply reports
892
+ * success.
893
+ *
894
+ * EMPTY IS NOT REFUSED, because the `aud` output is documented as empty when
895
+ * Cloudflare did not return one, and an instance whose audience nothing reads
896
+ * (a machine door verified by its token alone) must keep applying. The apply
897
+ * says what an empty one means instead, and an importer that does read it is
898
+ * refused at its own apply by the engine's empty-output rule, before it
899
+ * deploys.
900
+ */
901
+ export function assertAudience(aud: string | undefined, domain: string): void {
902
+ if (aud === undefined || aud === '' || AUDIENCE_TAG.test(aud)) return
903
+ throw new Error(
904
+ `refusing to continue: the Access application on ${domain} came back with an audience ` +
905
+ `tag that is not 64 hex characters ("${aud.slice(0, 12)}${aud.length > 12 ? '...' : ''}"). ` +
906
+ `A Worker verifying its assertions against it would refuse everyone.`,
907
+ )
908
+ }
909
+
910
+ /**
911
+ * The API credential every call uses: an imported instance's output, or a key
912
+ * of this environment's secrets.yaml. Through the engine's own rules
913
+ * (`ctx.output` / `ctx.secret`), so a missing import, output or key fails by
914
+ * name before anything is called.
915
+ */
916
+ export function resolveAccessToken(
917
+ apiToken: { from: string; output: string } | { secret: string },
918
+ ctx: ApplyContext,
919
+ ): string {
920
+ return 'secret' in apiToken
921
+ ? ctx.secret(apiToken.secret, { field: 'apiToken' })
922
+ : ctx.output(apiToken, 'apiToken')
923
+ }
924
+
732
925
  // ── Apply ─────────────────────────────────────────────────────────────────
733
926
 
734
927
  /** The Zero Trust organisation. Two fields, deliberately handled apart. */
@@ -779,7 +972,9 @@ export const cloudflareAccessModule = defineModule({
779
972
  appId: z.string(),
780
973
  /**
781
974
  * The application's audience tag, for a Worker that verifies assertions.
782
- * Empty when Cloudflare did not return one.
975
+ * Empty when Cloudflare did not return one; never malformed, because a
976
+ * present tag that is not 64 hex characters fails the apply
977
+ * (`assertAudience`).
783
978
  */
784
979
  aud: z.string(),
785
980
  /** Passed on so a Worker derives its issuer and JWKS URL from one value. */
@@ -814,7 +1009,7 @@ export const cloudflareAccessModule = defineModule({
814
1009
  changed: z.boolean(),
815
1010
  }),
816
1011
  async apply(config, ctx) {
817
- const token = ctx.output(config.apiToken, 'apiToken')
1012
+ const token = resolveAccessToken(config.apiToken, ctx)
818
1013
  const account = `/accounts/${config.accountId}`
819
1014
  const domain = normalizeDomain(config.domain)
820
1015
 
@@ -1034,6 +1229,17 @@ export const cloudflareAccessModule = defineModule({
1034
1229
  console.log(` Created Access application "${config.name}" on ${domain} (${app.id})`)
1035
1230
  }
1036
1231
 
1232
+ // 3b. The audience, before anything is minted or any policy written: a
1233
+ // malformed one stops here, and an absent one is said out loud.
1234
+ assertAudience(app.aud, domain)
1235
+ if (!app.aud) {
1236
+ console.log(
1237
+ ` ⚠️ The Access application on ${domain} came back with no audience tag. The aud ` +
1238
+ `output is empty, and an instance that reads it (a Worker verifying assertions) ` +
1239
+ `will be refused at its apply.`,
1240
+ )
1241
+ }
1242
+
1037
1243
  // 4. The service token this module owns, if one is declared.
1038
1244
  //
1039
1245
  // AFTER the application, deliberately. The measured failure that made
@@ -1083,28 +1289,32 @@ export const cloudflareAccessModule = defineModule({
1083
1289
  // and each is compared against its OWN idea of a match, so a Service Auth
1084
1290
  // policy existing cannot make an `everyone` rule beside the addresses
1085
1291
  // look acceptable.
1086
- const declared: DeclaredPolicy[] = [
1087
- ...(config.emails.length > 0
1088
- ? [
1089
- {
1090
- name: config.policyName,
1091
- admits: 'emails' as const,
1092
- emails: config.emails,
1093
- sessionDuration: config.sessionDuration,
1094
- },
1095
- ]
1096
- : []),
1097
- ...(serviceTokenIds.length > 0
1098
- ? [
1099
- {
1100
- name: serviceTokenPolicyNameFor(config),
1101
- admits: 'service-tokens' as const,
1102
- tokenIds: serviceTokenIds,
1103
- sessionDuration: config.sessionDuration,
1104
- },
1105
- ]
1106
- : []),
1107
- ]
1292
+ // A bypass declares its one policy and nothing else; the schema has
1293
+ // already refused one that names people or tokens.
1294
+ const declared: DeclaredPolicy[] = config.bypass
1295
+ ? [{ name: config.policyName, admits: 'everyone' as const }]
1296
+ : [
1297
+ ...(config.emails.length > 0
1298
+ ? [
1299
+ {
1300
+ name: config.policyName,
1301
+ admits: 'emails' as const,
1302
+ emails: config.emails,
1303
+ sessionDuration: config.sessionDuration,
1304
+ },
1305
+ ]
1306
+ : []),
1307
+ ...(serviceTokenIds.length > 0
1308
+ ? [
1309
+ {
1310
+ name: serviceTokenPolicyNameFor(config),
1311
+ admits: 'service-tokens' as const,
1312
+ tokenIds: serviceTokenIds,
1313
+ sessionDuration: config.sessionDuration,
1314
+ },
1315
+ ]
1316
+ : []),
1317
+ ]
1108
1318
 
1109
1319
  const actual = await cf<AccessPolicy[]>(
1110
1320
  token,
@@ -1185,7 +1395,14 @@ export const cloudflareAccessModule = defineModule({
1185
1395
 
1186
1396
  // 7. What a verifying consumer needs, printed as well as returned: an apply
1187
1397
  // nobody can read is an apply nobody can check.
1188
- console.log(` Access is now the way in to ${domain}:`)
1398
+ if (config.bypass) {
1399
+ console.log(
1400
+ ` ‼️ BYPASS: ${domain} asks for NO sign-in. Anyone on the internet reaches it, and ` +
1401
+ `what answers there must authenticate every request itself.`,
1402
+ )
1403
+ } else {
1404
+ console.log(` Access is now the way in to ${domain}:`)
1405
+ }
1189
1406
  if (config.teamDomain !== undefined) console.log(` team domain ${config.teamDomain}`)
1190
1407
  if (app.aud) console.log(` audience ${app.aud}`)
1191
1408
  if (config.emails.length > 0) {
@@ -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."
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."
11
11
  }
@@ -1,3 +1,7 @@
1
+ import { spawnSync } from 'node:child_process'
2
+ import * as fs from 'node:fs'
3
+ import * as os from 'node:os'
4
+ import * as path from 'node:path'
1
5
  import { z } from 'zod'
2
6
  import { defineModule } from '../../src/define-module'
3
7
  import type { ApplyContext } from '../../src/types'
@@ -17,6 +21,11 @@ import { CfError, type CfOptions, cf, cfRaw } from '../cloudflare-api'
17
21
  * 'database_id', from: '<this instance>', output: 'databaseId' }` and the
18
22
  * placeholder id in the checked-in wrangler config is never read.
19
23
  *
24
+ * Schema comes two ways, and both run here, before any importing Worker
25
+ * deploys: `migrationsDir`, a versioned history in wrangler's own format and
26
+ * ledger (`d1_migrations`), applied by `wrangler d1 migrations apply`; then
27
+ * `statements` and `additiveColumns`, end-state DDL replayed every apply.
28
+ *
20
29
  * Token scope: CLOUDFLARE_API_TOKEN needs Account → D1: Edit. Or set
21
30
  * `apiToken: { from, output }` to use an imported instance's output instead
22
31
  * (e.g. a `cloudflare-token` instance's `tokenValue`), the same way the
@@ -122,6 +131,77 @@ function isDuplicateColumn(err: unknown): boolean {
122
131
  return err instanceof CfError && /duplicate column name/i.test(err.message)
123
132
  }
124
133
 
134
+ /**
135
+ * Apply a folder of migrations with wrangler's own migrator, against the
136
+ * database by id.
137
+ *
138
+ * Wrangler finds a database's migrations folder in a wrangler config, so it is
139
+ * handed a throwaway one in a temporary directory naming only this database,
140
+ * its id and the folder. The id is given so wrangler uses it verbatim rather
141
+ * than looking the name up. The credential and account reach it through the
142
+ * environment, as they reach the `cloudflare` module's wrangler calls, and
143
+ * wrangler is the project's own (`node_modules/.bin/wrangler`) when there is
144
+ * one, else `bunx wrangler` on node: never `--bun`, which the `cloudflare`
145
+ * module's header explains.
146
+ */
147
+ function applyMigrations(opts: {
148
+ projectRoot: string
149
+ migrationsDir: string
150
+ accountId: string
151
+ apiToken: string
152
+ databaseName: string
153
+ databaseId: string
154
+ }): string {
155
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'zbc-d1-'))
156
+ const configPath = path.join(dir, 'wrangler.json')
157
+ try {
158
+ fs.writeFileSync(
159
+ configPath,
160
+ JSON.stringify({
161
+ name: 'zbc-d1-migrations',
162
+ d1_databases: [
163
+ {
164
+ binding: 'DB',
165
+ database_name: opts.databaseName,
166
+ database_id: opts.databaseId,
167
+ migrations_dir: path.resolve(opts.projectRoot, opts.migrationsDir),
168
+ },
169
+ ],
170
+ }),
171
+ )
172
+ const local = path.join(opts.projectRoot, 'node_modules', '.bin', 'wrangler')
173
+ const [cmd, pre] = fs.existsSync(local) ? [local, []] : ['bunx', ['wrangler']]
174
+ const args = [
175
+ ...pre,
176
+ 'd1',
177
+ 'migrations',
178
+ 'apply',
179
+ opts.databaseName,
180
+ '--remote',
181
+ '--config',
182
+ configPath,
183
+ ]
184
+ const res = spawnSync(cmd, args, {
185
+ cwd: opts.projectRoot,
186
+ env: {
187
+ ...process.env,
188
+ CLOUDFLARE_API_TOKEN: opts.apiToken,
189
+ CLOUDFLARE_ACCOUNT_ID: opts.accountId,
190
+ },
191
+ maxBuffer: 64 * 1024 * 1024,
192
+ })
193
+ const said = `${res.stdout?.toString() ?? ''}\n${res.stderr?.toString() ?? ''}`
194
+ if (res.status !== 0 || res.error) {
195
+ throw new Error(
196
+ `wrangler d1 migrations apply ${opts.databaseName} failed (exit ${res.status}):\n${said.trim() || res.error?.message}`,
197
+ )
198
+ }
199
+ return said
200
+ } finally {
201
+ fs.rmSync(dir, { recursive: true, force: true })
202
+ }
203
+ }
204
+
125
205
  /**
126
206
  * The credential every call below uses: an imported instance's output when
127
207
  * `apiToken` is set, else CLOUDFLARE_API_TOKEN from secrets.yaml. One helper
@@ -159,12 +239,32 @@ export const d1Module = defineModule({
159
239
  /**
160
240
  * End-state DDL, replayed in order on EVERY apply — so every statement has
161
241
  * to be idempotent on its own (`CREATE TABLE IF NOT EXISTS`, `CREATE INDEX
162
- * IF NOT EXISTS`). This is not a migration runner and keeps no ledger: it
163
- * converges a schema the same way the rest of a module converges a
164
- * resource. A versioned migrations directory needs somewhere to run after
165
- * the deploy, which the engine does not have yet.
242
+ * IF NOT EXISTS`). This keeps no ledger: it converges a schema the same
243
+ * way the rest of a module converges a resource. A history that holds
244
+ * run-once steps (a backfill, a dropped table) belongs in `migrationsDir`.
166
245
  */
167
246
  statements: z.array(z.string()).default([]),
247
+ /**
248
+ * A folder of versioned migrations (`0001_init.sql`, …), relative to the
249
+ * project root, applied with wrangler's own migrator and recorded in its
250
+ * `d1_migrations` ledger: `wrangler d1 migrations apply <name> --remote`.
251
+ *
252
+ * Wrangler's format and ledger, not a second migrator: a database that
253
+ * was migrated by hand or by a deploy script already holds that ledger,
254
+ * and a runner keeping its own would replay the whole history over it.
255
+ *
256
+ * Run on THIS instance's apply, after the database resolves and before
257
+ * `statements`, so a Worker that imports this instance deploys only after
258
+ * the schema it reads is there. A migration that fails fails the apply,
259
+ * and the Worker behind it is not deployed. Wrangler is handed a throwaway
260
+ * config naming the database by the id just resolved, so the Worker's own
261
+ * wrangler config, and whether it binds by name or by id, play no part.
262
+ *
263
+ * Needs wrangler (this module's devDependency, run from the project's
264
+ * `node_modules/.bin`; `bunx wrangler` when it is not installed there) and
265
+ * a token that may read and write D1.
266
+ */
267
+ migrationsDir: z.string().optional(),
168
268
  /**
169
269
  * Columns added to an existing table, applied after `statements`. Separate
170
270
  * from them because `ALTER TABLE … ADD COLUMN` is the one thing SQLite
@@ -183,6 +283,17 @@ export const d1Module = defineModule({
183
283
  const apiToken = apiTokenFor(config, ctx)
184
284
  const { accountId, databaseName } = config
185
285
 
286
+ // Checked before anything is called: a typo'd folder must not leave a
287
+ // freshly created, empty database behind it.
288
+ if (
289
+ config.migrationsDir !== undefined &&
290
+ !fs.existsSync(path.resolve(ctx.projectRoot, config.migrationsDir))
291
+ ) {
292
+ throw new Error(
293
+ `migrationsDir "${config.migrationsDir}" does not exist under the project root (${ctx.projectRoot})`,
294
+ )
295
+ }
296
+
186
297
  const existing = (await listDatabases(apiToken, accountId)).find((d) => d.name === databaseName)
187
298
 
188
299
  let databaseId: string
@@ -211,6 +322,24 @@ export const d1Module = defineModule({
211
322
  )
212
323
  }
213
324
 
325
+ if (config.migrationsDir !== undefined) {
326
+ const said = applyMigrations({
327
+ projectRoot: ctx.projectRoot,
328
+ migrationsDir: config.migrationsDir,
329
+ accountId,
330
+ apiToken,
331
+ databaseName,
332
+ databaseId,
333
+ })
334
+ // Wrangler's own lines about what it applied, not the whole table it draws.
335
+ const summary = said
336
+ .split('\n')
337
+ .map((line) => line.trim())
338
+ .filter((line) => /No migrations to apply|✅|Migrations to be applied|\.sql/.test(line))
339
+ .join('; ')
340
+ console.log(` Migrated from ${config.migrationsDir}: ${summary || 'done'}`)
341
+ }
342
+
214
343
  for (const statement of config.statements) {
215
344
  await query(apiToken, accountId, databaseId, statement)
216
345
  }
@@ -6,8 +6,11 @@
6
6
  "dependencies": {
7
7
  "zod": "^3.24.0"
8
8
  },
9
+ "devDependencies": {
10
+ "wrangler": "^4.0.0"
11
+ },
9
12
  "secrets": ["CLOUDFLARE_API_TOKEN"],
10
13
  "signupUrl": "https://dash.cloudflare.com/sign-up",
11
14
  "tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
12
- "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."
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."
13
16
  }