@zabaca/zbc 0.24.0 → 0.26.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -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,
@@ -71,8 +72,7 @@ interface Claim {
71
72
  /**
72
73
  * Answer one MCP request.
73
74
  *
74
- * A fresh `McpServer` per request, like the inbox's endpoint and for the same
75
- * reason: a Workers isolate is per-request and holds no session, so there is no
75
+ * A fresh `McpServer` per request: a Workers isolate is per-request and holds no session, so there is no
76
76
  * long-lived server to keep. `app.all` because Streamable HTTP puts client
77
77
  * messages on POST and the server-to-client stream on GET, and a transport
78
78
  * mounted for one of them is a client that connects and then hears nothing.
@@ -83,8 +83,9 @@ export async function handleMcp(
83
83
  caps: Capabilities,
84
84
  operator: Operator | null,
85
85
  host: string,
86
+ scoped: ScopedClaims | null = null,
86
87
  ): Promise<Response> {
87
- const server = createAgentgitMcp(deps(request, env, caps, operator, host))
88
+ const server = createAgentgitMcp(deps(request, env, caps, operator, host, scoped))
88
89
  const transport = new StreamableHTTPTransport()
89
90
  await server.connect(transport)
90
91
  const app = new Hono()
@@ -98,6 +99,7 @@ function deps(
98
99
  caps: Capabilities,
99
100
  operator: Operator | null,
100
101
  host: string,
102
+ scoped: ScopedClaims | null,
101
103
  ): McpDeps {
102
104
  // The caller's own credential, forwarded unchanged to every gated read. An
103
105
  // MCP client sends it as an ordinary Authorization header, which is the same
@@ -137,7 +139,14 @@ function deps(
137
139
  return { ok: true, repo: name, provenance: read.provenance }
138
140
  },
139
141
 
140
- 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,
141
150
  }
142
151
  }
143
152
 
@@ -212,11 +221,16 @@ async function watchRef(
212
221
  repo: string,
213
222
  ref: string | null,
214
223
  timeoutMs: number,
224
+ scoped: boolean,
215
225
  ): Promise<WatchOutcome> {
216
226
  if (!caps.events) {
217
227
  throw new Error('this deployment does not serve the ref-event stream')
218
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.
219
232
  if (
233
+ !scoped &&
220
234
  !authorizeSubscribe({
221
235
  authorization,
222
236
  tokens: parseTokens(env.WALGIT_HTTP_TOKENS),
@@ -32,8 +32,7 @@ export interface Env extends MaterializeEnv {
32
32
  }
33
33
 
34
34
  /** Constant-time bearer check: compare SHA-256 digests via crypto.subtle.timingSafeEqual
35
- * so a mismatched length or value can't be distinguished by timing — ported exactly from
36
- * the inbox app template's `authorized()` (worker/index.ts there). */
35
+ * so a mismatched length or value can't be distinguished by timing. */
37
36
  export async function authorized(request: Request, env: Env): Promise<boolean> {
38
37
  if (!env.WAREHOUSE_TOKEN) return false
39
38
  const header = request.headers.get('authorization') ?? ''
@@ -2,8 +2,7 @@
2
2
  // implement `timingSafeEqual` — verified against this package's own Bun (`'timingSafeEqual'
3
3
  // in crypto.subtle` is false; calling it throws "is not a function"). It's a workerd-runtime
4
4
  // extension to SubtleCrypto, not part of the Web Crypto standard, so it's only real under
5
- // wrangler dev/deploy. router.ts's `authorized()` calls it exactly as the inbox app
6
- // template's worker/index.ts does — this shim exists purely so `bun test worker` can
5
+ // wrangler dev/deploy. router.ts's `authorized()` calls it, and this shim exists purely so `bun test worker` can
7
6
  // exercise authorized()'s true/false outcomes locally; it changes nothing about the code
8
7
  // under test, and is never loaded outside the test runner.
9
8
  import { timingSafeEqual as nodeTimingSafeEqual } from 'node:crypto'
@@ -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
  }