@zabaca/zbc 0.23.1 → 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 (36) 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/cloudflare-zone/index.ts +141 -22
  18. package/templates/infra/modules/cloudflare-zone/registry.json +2 -2
  19. package/templates/infra/modules/d1/index.ts +133 -4
  20. package/templates/infra/modules/d1/registry.json +4 -1
  21. package/templates/infra/modules/queue/index.ts +313 -0
  22. package/templates/infra/modules/queue/registry.json +13 -0
  23. package/templates/infra/modules/r2/registry.json +1 -1
  24. package/templates/infra/src/define-module.ts +19 -2
  25. package/templates/infra/src/types.ts +24 -0
  26. package/templates/apps/inbox/package.json +0 -26
  27. package/templates/apps/inbox/public/index.html +0 -379
  28. package/templates/apps/inbox/registry.json +0 -9
  29. package/templates/apps/inbox/tsconfig.json +0 -19
  30. package/templates/apps/inbox/worker/api.ts +0 -197
  31. package/templates/apps/inbox/worker/commands.ts +0 -299
  32. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  33. package/templates/apps/inbox/worker/index.ts +0 -195
  34. package/templates/apps/inbox/worker/mcp.ts +0 -228
  35. package/templates/apps/inbox/worker/shared.ts +0 -117
  36. 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
  }
@@ -70,18 +70,30 @@ import { cf, cfRaw } from '../cloudflare-api'
70
70
  // the account's plan; one absent from the zone's own list is an id Cloudflare
71
71
  // does not offer. Both refuse in the plan, ahead of the first record write —
72
72
  // discovering either from a half-applied PATCH would leave the zone in a state
73
- // neither the file nor the previous apply describes.
73
+ // neither the file nor the previous apply describes. The one thing that can
74
+ // already exist by then is the zone itself, when this apply created it, and
75
+ // the refusal says so.
74
76
  //
75
77
  // ── Account-parameterised ─────────────────────────────────────────────────
76
78
  // `accountId` is instance config, never a constant: each client's
77
79
  // zone in that Client's own Cloudflare account. Apply refuses outright if the
78
- // looked-up zone belongs to a different account than the one declared — the
80
+ // looked-up zone belongs to a different account than the one declared, the
79
81
  // cheapest possible guard against converging the right records into the wrong
80
82
  // tenant.
81
83
  //
82
- // There is deliberately no `destroy`. Deleting a zone detaches a live domain
83
- // from its nameservers and is registrar-adjacent; it is a human action with a
84
- // human's attention on it, not something a converge loop should be able to do.
84
+ // ── Creating the zone is opt-in ───────────────────────────────────────────
85
+ // A domain registered anywhere but Cloudflare Registrar has no zone until
86
+ // someone makes one. With `createIfAbsent: true` an absent zone is created
87
+ // (`type: full`, in the declared account) and the next apply finds it. Every
88
+ // apply prints the zone's nameservers and status as soon as the zone is
89
+ // resolved, before anything else can fail, because the pair is what an
90
+ // operator carries to the registrar.
91
+ //
92
+ // There is deliberately no `destroy`, and the asymmetry with creation is
93
+ // intended. A new zone answers for nothing until a registrar points at it;
94
+ // deleting one detaches a live domain from its nameservers and is
95
+ // registrar-adjacent, a human action with a human's attention on it, not
96
+ // something a converge loop should be able to do.
85
97
 
86
98
  // ── Schema ────────────────────────────────────────────────────────────────
87
99
 
@@ -223,6 +235,28 @@ const configSchema = z
223
235
  * records are always reported, never removed, until an operator opts in.
224
236
  */
225
237
  allowDelete: z.boolean().default(false),
238
+ /**
239
+ * Create the zone when the lookup does not find it.
240
+ *
241
+ * The creating apply needs "Zone Write" granted account-wide, on a token
242
+ * minted with no `zones` restriction: a grant scoped to a zone that does
243
+ * not exist yet cannot create it, and a `cloudflare-token` instance naming
244
+ * the zone in `zones` fails at mint time, with nothing to resolve the name
245
+ * to. Narrow the token to the zone once it exists, if wanted.
246
+ *
247
+ * Defaults to false, and an absent zone stays a hard error. An empty zone
248
+ * list is the answer to a mistyped name and to a token that lost "Zone
249
+ * Read" as much as to a domain nobody has added, so creation is one
250
+ * declared line per domain rather than what every empty lookup turns into.
251
+ *
252
+ * An account-owned token lists only its own account's zones, so a zone
253
+ * held in ANOTHER account reads as absent and the wrong-account refusal
254
+ * cannot fire for it. Creating then either fails (and the error says the
255
+ * zone may exist where this token cannot read it) or, if Cloudflare
256
+ * accepts it, makes a second zone here, pending, which answers for nothing
257
+ * unless the registrar is pointed at it.
258
+ */
259
+ createIfAbsent: z.boolean().default(false),
226
260
  })
227
261
  .superRefine((config, ctx) => {
228
262
  config.records.forEach((record, index) => {
@@ -655,13 +689,60 @@ function recordBody(record: DesiredRecord): Record<string, unknown> {
655
689
  return body
656
690
  }
657
691
 
692
+ interface CfZone {
693
+ id: string
694
+ name: string
695
+ /** `pending` until the registrar points at `name_servers`, then `active`. */
696
+ status?: string
697
+ account?: { id: string }
698
+ name_servers?: string[]
699
+ }
700
+
701
+ /**
702
+ * Create the zone in the declared account.
703
+ *
704
+ * `type: full`, not `partial`: a full setup is the one that gets its own
705
+ * nameserver pair, and moving the domain onto that pair is the point. A partial
706
+ * (CNAME) setup leaves the nameservers where they are.
707
+ *
708
+ * A failure is wrapped rather than passed through, because the likeliest one is
709
+ * not what it looks like. The zone list comes back EMPTY rather than forbidden
710
+ * for a token that cannot read the zone, so the lookup that decided this zone
711
+ * was absent cannot tell "no such zone" from "no permission to see it".
712
+ * Cloudflare catches the difference at the create, and the message has to say
713
+ * so, or the next reader concludes the account is empty and makes a second one.
714
+ */
715
+ async function createZone(token: string, name: string, accountId: string): Promise<CfZone> {
716
+ try {
717
+ return await cf<CfZone>(token, 'POST', '/zones', {
718
+ name,
719
+ account: { id: accountId },
720
+ type: 'full',
721
+ })
722
+ } catch (cause) {
723
+ throw new Error(
724
+ `refusing to apply: creating zone "${name}" in Cloudflare account ${accountId} failed: ` +
725
+ `${(cause as Error).message}. The lookup just before reported no such zone, but a token ` +
726
+ `that cannot read a zone gets an empty list rather than a refusal, so "absent" and ` +
727
+ `"invisible to this token" read the same. If Cloudflare says the zone already exists, it ` +
728
+ `exists somewhere this token cannot read: check the token holds "Zone Read" across the ` +
729
+ `account, and find which account holds the zone, rather than making a second one.`,
730
+ { cause },
731
+ )
732
+ }
733
+ }
734
+
658
735
  export const cloudflareZoneModule = defineModule({
659
736
  name: 'cloudflare-zone',
660
737
  configSchema,
661
738
  outputs: z.object({
662
739
  zoneId: z.string(),
663
740
  zoneName: z.string(),
664
- /** Cloudflare's assigned nameservers — what the registrar must be pointing at. */
741
+ /** True when this apply is the one that brought the zone into existence. */
742
+ zoneCreated: z.boolean(),
743
+ /** Cloudflare's word for the zone: `pending` until the registrar points here, then `active`. */
744
+ zoneStatus: z.string(),
745
+ /** Cloudflare's assigned nameservers, which the registrar must be pointing at. */
665
746
  nameServers: z.array(z.string()),
666
747
  created: z.number(),
667
748
  updated: z.number(),
@@ -677,25 +758,57 @@ export const cloudflareZoneModule = defineModule({
677
758
  async apply(config, ctx) {
678
759
  const token = ctx.output(config.apiToken, 'apiToken')
679
760
 
680
- // 1. Resolve the zone, and refuse a zone that lives somewhere else.
681
- const zones = await cf<
682
- Array<{ id: string; name: string; account?: { id: string }; name_servers?: string[] }>
683
- >(token, 'GET', `/zones?name=${encodeURIComponent(config.zone)}`)
684
- const zone = zones.find((z) => z.name.toLowerCase() === config.zone.toLowerCase())
685
- if (!zone) {
686
- throw new Error(
687
- `Zone "${config.zone}" not found — either it is not in this Cloudflare account, or the ` +
688
- `imported token lacks "Zone Read".`,
689
- )
690
- }
691
- if (zone.account && zone.account.id !== config.accountId) {
761
+ // 1. Resolve the zone: refuse one that lives somewhere else, and create one
762
+ // that is not there at all only when the instance opts in.
763
+ //
764
+ // The order matters. A zone this token can see in another account is
765
+ // refused BEFORE anything decides whether to create, so that refusal
766
+ // cannot turn into a second zone for the same name beside the first. A
767
+ // zone the token cannot see is a different case; see `createIfAbsent`.
768
+ const zones = await cf<CfZone[]>(token, 'GET', `/zones?name=${encodeURIComponent(config.zone)}`)
769
+ const found = zones.find((each) => each.name.toLowerCase() === config.zone.toLowerCase())
770
+ if (found?.account && found.account.id !== config.accountId) {
692
771
  throw new Error(
693
- `refusing to apply: zone "${config.zone}" lives in Cloudflare account ${zone.account.id}, ` +
772
+ `refusing to apply: zone "${config.zone}" lives in Cloudflare account ${found.account.id}, ` +
694
773
  `but this instance declares ${config.accountId}. Each zone belongs to exactly one ` +
695
774
  `account; converging the right records into the wrong tenant is not a ` +
696
775
  `mistake worth being able to make.`,
697
776
  )
698
777
  }
778
+ if (!found && !config.createIfAbsent) {
779
+ throw new Error(
780
+ `Zone "${config.zone}" not found. Either it is not in this Cloudflare account, or the ` +
781
+ `imported token lacks "Zone Read". Set createIfAbsent: true on this instance to create ` +
782
+ `it (the token then also needs "Zone Write" across the account).`,
783
+ )
784
+ }
785
+ const zone = found ?? (await createZone(token, config.zone, config.accountId))
786
+ const zoneCreated = found === undefined
787
+ if (zoneCreated) {
788
+ console.log(
789
+ ` Created zone ${config.zone} (${zone.id}) in Cloudflare account ${config.accountId}`,
790
+ )
791
+ }
792
+
793
+ // The nameserver pair, printed here rather than at the end so that an
794
+ // apply which creates the zone and then fails on a later step still hands
795
+ // the operator the pair to carry to the registrar.
796
+ const nameServers = zone.name_servers ?? []
797
+ const zoneStatus = zone.status ?? 'unknown'
798
+ if (nameServers.length > 0) {
799
+ console.log(` Nameservers (${zoneStatus}): ${nameServers.join(', ')}`)
800
+ if (zoneStatus !== 'active') {
801
+ console.log(
802
+ ` ${config.zone} answers from these only once its registrar points at them; until ` +
803
+ `then its records have no effect.`,
804
+ )
805
+ }
806
+ } else {
807
+ console.log(
808
+ ` Cloudflare reported no nameservers for ${config.zone} (status ${zoneStatus}). Read ` +
809
+ `them off the dashboard before touching the registrar.`,
810
+ )
811
+ }
699
812
 
700
813
  // 2. Diff the whole zone before mutating any of it.
701
814
  const desired = config.records.map((record) => desiredRecord(record, config.zone))
@@ -744,8 +857,12 @@ export const cloudflareZoneModule = defineModule({
744
857
  }
745
858
  throw new Error(
746
859
  `refusing to apply: zone "${config.zone}" cannot converge every declared setting. ` +
747
- `${parts.join('; ')}. Nothing was written — not the settings that could be, and not ` +
748
- `the records — so this zone is exactly as the last apply left it.`,
860
+ `${parts.join('; ')}. ` +
861
+ (zoneCreated
862
+ ? `This apply created the zone itself (${zoneStatus}) and wrote nothing else: not ` +
863
+ `the settings that could be, and not the records.`
864
+ : `Nothing was written, not the settings that could be and not the records, so ` +
865
+ `this zone is exactly as the last apply left it.`),
749
866
  )
750
867
  }
751
868
  }
@@ -797,7 +914,9 @@ export const cloudflareZoneModule = defineModule({
797
914
  return {
798
915
  zoneId: zone.id,
799
916
  zoneName: zone.name,
800
- nameServers: zone.name_servers ?? [],
917
+ zoneCreated,
918
+ zoneStatus,
919
+ nameServers,
801
920
  created: plan.create.length,
802
921
  updated: plan.update.length,
803
922
  deleted,