@zabaca/zbc 0.10.9 → 0.11.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.
@@ -1,101 +1,694 @@
1
1
  import { z } from 'zod'
2
2
  import { defineModule } from '../../src/define-module'
3
- import { cf, resolveApiToken } from '../cloudflare-api'
3
+ import { cf, resolveApiToken, resolveRef } from '../cloudflare-api'
4
4
 
5
- // cloudflare-access — a Zero Trust application, its policy, and the service
6
- // token a machine caller presents, as repo state.
5
+ // cloudflare-access — a Zero Trust application and the list of principals that
6
+ // may reach it, as repo state instead of dashboard state.
7
7
  //
8
8
  // What this exists for: `cloudflare-tunnel` puts a hostname on the internet,
9
- // and a tunnel with no policy in front of it is an open door. Here that door
10
- // leads to a vite dev server with no auth of its own and a bridge that can run
11
- // agent turns with a real Claude token, so "add the route and secure it after"
12
- // is not a sequence worth being able to run. The two land together.
9
+ // and a tunnel with no policy in front of it is an open door. Declaring the two
10
+ // together means "add the route and secure it after" is not a sequence anybody
11
+ // has to be trusted to finish.
12
+ //
13
+ // ── TWO KINDS OF PRINCIPAL, AND THEY DO NOT SHARE A POLICY ────────────────
14
+ // A person is admitted by their address, on a policy whose decision is `allow`.
15
+ // A machine is admitted by a service token, on a policy whose decision is
16
+ // `non_identity` — Service Auth in the dashboard. The two are NOT
17
+ // interchangeable: an `allow` policy demands an identity, so a service token on
18
+ // one is admitted by nothing while the policy looks perfectly configured, and
19
+ // an address on a `non_identity` policy is the mirror of that.
20
+ //
21
+ // So each declared policy is compared against its OWN idea of a match, and this
22
+ // is the property most easily lost by a later edit. Declaring a service-token
23
+ // policy makes a non-address rule a legitimate thing for SOME policy to carry,
24
+ // and the cheap way to permit that is to loosen the check for all of them —
25
+ // which would let an `everyone` rule sit beside the addresses on the people
26
+ // policy and read as unchanged. `planPolicies` is the seam that keeps it, and
27
+ // `index.test.ts` fails if anybody widens it.
28
+ //
29
+ // ── THE ORGANISATION IS NOT SCOPED TO THIS APPLICATION ────────────────────
30
+ // `teamDomain`, `orgName` and `identityProviders` are properties of the whole
31
+ // Zero Trust organisation, not of the application this instance declares. An
32
+ // instance pointed at an account converges the provider set behind EVERY
33
+ // application in it. That is why undeclared providers are reported and never
34
+ // removed, and why `identityProviders` defaults to empty: an instance that says
35
+ // nothing about providers converges nothing about them, so adding this module
36
+ // to an account cannot disturb it by omission.
37
+ //
38
+ // ── `auth_domain` IS COMPARED AND NEVER CHOSEN ───────────────────────────
39
+ // A consumer's Worker derives the issuer it verifies every assertion against
40
+ // from the team domain. An apply that could CHOOSE that value would turn the
41
+ // guard into the exact failure the guard exists to catch: edit the file, apply,
42
+ // and the issuer plus every live session break at once while the apply reports
43
+ // success. So the live value is compared first and only ever echoed back.
44
+ // `orgName` is cosmetic, and is the only organisation field this module decides.
45
+ //
46
+ // ── Deletion is opt-in, and here that is a sharper trade than usual ───────
47
+ // `allowDelete` defaults to false, matching cloudflare-zone. The asymmetry
48
+ // worth stating: an undeclared DNS record is inert, and an undeclared ALLOW
49
+ // policy on this application is an open door somebody added by hand. So an
50
+ // extra policy is reported at the top of its voice and counted into the
51
+ // outputs, and removing it is still a deliberate second edit rather than
52
+ // something a converge loop does on sight.
13
53
  //
14
54
  // ── The service token secret is NOT rolled on every apply ─────────────────
15
55
  // `cloudflare-token` rolls its value every apply and persists nothing, which is
16
56
  // the better discipline — a minted value that lives only in memory cannot go
17
- // stale in a file somewhere. That does NOT work here, and the difference is
18
- // worth stating because the asymmetry looks like an oversight otherwise.
19
- //
20
- // A Cloudflare API token's consumer is this apply. An Access service token's
21
- // consumer is somebody ELSE — cedarpad's edge Worker, deployed from a different
22
- // repo on a different cadence. Rolling on every apply would invalidate the
23
- // credential the running Worker holds, so every unrelated `bun run apply` on
24
- // this box would take the canvas down until the Worker was redeployed. That is
25
- // a worse failure than the one rolling protects against.
57
+ // stale in a file somewhere. That does NOT work here, and the asymmetry looks
58
+ // like an oversight otherwise. A Cloudflare API token's consumer is this apply.
59
+ // An Access service token's consumer is somebody ELSE, deployed from a
60
+ // different repo on a different cadence, so rolling on every apply would
61
+ // invalidate the credential that consumer holds and take it down until it was
62
+ // redeployed. So: created once, thereafter REUSED, never rotated. `rotate: true`
63
+ // is the deliberate escape hatch for the day it leaks.
26
64
  //
27
- // So: created once, and thereafter REUSED, never rotated. Cloudflare returns a
28
- // service token's secret exactly once, at creation — so on the apply that
29
- // creates it, this module prints the pair and that is the only chance to
30
- // capture it. `rotate: true` is the deliberate escape hatch for the day it
31
- // leaks or the Worker loses it; it mints a new secret and prints it, and
32
- // whoever sets it does so knowing the old one dies.
33
- //
34
- // ── Why `include` and not `require` ───────────────────────────────────────
35
- // The policy lists the service token in `include`, which is an OR — any listed
36
- // principal gets in. `require` is an AND across every entry, so a second
37
- // principal added later (an email for a human) would have to satisfy the
38
- // service-token rule too, which no browser can. `include` is what makes the
39
- // policy extensible without a rewrite.
40
-
41
- const configSchema = z.object({
42
- accountId: z.string(),
43
- /** Credential source: a `cloudflare-token` instance's `tokenValue`. Needs
44
- * "Access: Apps and Policies Write" and "Access: Service Tokens Write". */
45
- apiToken: z.object({ from: z.string(), output: z.string() }),
46
- /** Human-facing application name in the Zero Trust dashboard. Converge identity. */
47
- name: z.string().min(1),
48
- /** The hostname this application protects, e.g. `ws.cedarpad.com`. */
49
- domain: z.string().min(1),
50
- /** Service token name — the machine caller (cedarpad's edge Worker). */
51
- serviceTokenName: z.string().min(1),
52
- /**
53
- * Mint a NEW secret for an existing service token. Off by default: the
54
- * consumer is a separately-deployed Worker, and rotating without redeploying
55
- * it takes the canvas down. See the header.
56
- */
57
- rotate: z.boolean().default(false),
58
- /**
59
- * How long a session lasts. `0s` means every request is evaluated — correct
60
- * for a machine caller, which presents its token on each request anyway and
61
- * should never be handed a cookie.
62
- */
63
- sessionDuration: z.string().default('0s'),
64
- })
65
+ // There is deliberately no `destroy`. Destroying an Access application does not
66
+ // tidy anything up, it takes the lock off the door.
67
+
68
+ // ── Schema ────────────────────────────────────────────────────────────────
69
+
70
+ /** `<team>.cloudflareaccess.com`, bare. An issuer is derived from it. */
71
+ const TEAM_DOMAIN = /^[a-z0-9][a-z0-9-]*\.cloudflareaccess\.com$/
72
+
73
+ const configSchema = z
74
+ .object({
75
+ /** Cloudflare account id. Instance config, never a constant. */
76
+ accountId: z.string(),
77
+ /**
78
+ * Where the credential comes from: `{ from, output }` into an imported
79
+ * instance's outputs, normally a `cloudflare-token` instance's
80
+ * `tokenValue`. Not a secrets.yaml key, so nothing that can edit who
81
+ * reaches this application comes to rest in the consuming repo.
82
+ *
83
+ * Needs "Access: Apps and Policies Write", plus "Access: Service Tokens
84
+ * Write" if `serviceTokenName` is declared, and "Access: Organizations" /
85
+ * "Access: Identity Providers" for the organisation-level fields.
86
+ */
87
+ apiToken: z.object({ from: z.string(), output: z.string() }),
88
+ /**
89
+ * The Zero Trust team domain, bare, with no scheme and no path.
90
+ *
91
+ * OPTIONAL, and that is a deliberate widening over the module this was
92
+ * promoted from. Where a Worker verifies an Access assertion, this is the
93
+ * one value its issuer and JWKS URL are both derived from and it must be
94
+ * declared. A machine-only application verifies nothing and derives
95
+ * nothing, so requiring the field there would make a consumer write down a
96
+ * value that plays no part — and a value nobody uses is a value nobody
97
+ * keeps right.
98
+ *
99
+ * When declared it is COMPARED against the live organisation and never
100
+ * written. See the header.
101
+ */
102
+ teamDomain: z
103
+ .string()
104
+ .regex(TEAM_DOMAIN, 'must be <team>.cloudflareaccess.com, bare')
105
+ .optional(),
106
+ /**
107
+ * What the organisation is CALLED. A different field from `teamDomain`, on
108
+ * the same endpoint, treated the opposite way: this one is the only
109
+ * organisation field this module decides.
110
+ *
111
+ * Cloudflare seeds it with a generated name like
112
+ * `plain-brook-fb33.cloudflareaccess.com`, and it is the string on the
113
+ * sign-in screen, so on a customer-facing application the customer reads
114
+ * it. Optional: an organisation whose name nobody reads is not worth a
115
+ * required field, and omitting it leaves the name alone rather than
116
+ * clearing it.
117
+ */
118
+ orgName: z.string().min(1).optional(),
119
+ /**
120
+ * The identity providers the ORGANISATION must offer. HOW people
121
+ * authenticate, as against WHICH people the policies then admit.
122
+ *
123
+ * WHY THIS BELONGS HERE. An instance's claim is to be the list of who may
124
+ * sign in, and that claim is false while the provider set lives only in the
125
+ * dashboard: an application whose policy names exactly the right people
126
+ * admits nobody if the organisation offers those people no way to
127
+ * authenticate.
128
+ *
129
+ * ONLY `onetimepin`, deliberately. It is the one provider that takes no
130
+ * configuration at all: Cloudflare emails a code and there is nothing to
131
+ * store. Any real SSO provider needs a client id and a secret, which is a
132
+ * credential at rest, which is a different module and a different argument.
133
+ *
134
+ * Undeclared providers are REPORTED, never removed. Not laziness: the
135
+ * `cloudflare` provider beside this one is how an operator signs in, and a
136
+ * converge loop that removed it on sight would lock out the person running
137
+ * the apply — across every application in the account, not just this one.
138
+ */
139
+ identityProviders: z.array(z.enum(['onetimepin'])).default([]),
140
+ /** The application's display name in the dashboard. */
141
+ name: z.string().min(1),
142
+ /**
143
+ * What the application covers: `host/path`, with no scheme.
144
+ *
145
+ * Written down to the path deliberately. `example.com` without `/admin`
146
+ * puts a sign-in wall in front of every public page the host serves.
147
+ */
148
+ domain: z.string().min(1),
149
+ /**
150
+ * Who may sign in. Lowercased and de-duplicated so the diff is about people
151
+ * rather than about capitalisation.
152
+ *
153
+ * Empty means NO people policy is declared at all — not an empty one, which
154
+ * would be a policy admitting nobody sitting on the application waiting for
155
+ * somebody to fill it in. An application that then has one anyway is drift
156
+ * and is reported.
157
+ */
158
+ emails: z
159
+ .array(z.string().trim().toLowerCase().email())
160
+ .default([])
161
+ .transform((emails) => Array.from(new Set(emails)).sort()),
162
+ /**
163
+ * How long a sign-in lasts before Cloudflare asks again.
164
+ *
165
+ * `24h` for a person. A machine caller should say `0s`, which means every
166
+ * request is evaluated and no cookie is ever issued: it presents its token
167
+ * on each request anyway, and a cookie would let a leaked one outlive the
168
+ * token. `0s` was the DEFAULT in the module this replaces, which is right
169
+ * for a machine and is a fresh one-time-PIN email per navigation for a
170
+ * person.
171
+ */
172
+ sessionDuration: z.string().default('24h'),
173
+ /** The people policy this module owns, by name. Anything else on the app is drift. */
174
+ policyName: z.string().min(1).default('allowed people'),
175
+ /**
176
+ * Service tokens minted ELSEWHERE that may reach this application without a
177
+ * person. `{ from, output }` into an imported instance's outputs.
178
+ *
179
+ * A reference rather than a literal id for the same reason `apiToken` is
180
+ * one: the id does not exist until the token is minted, and a hand-copied
181
+ * one goes stale silently the first time the token is recreated.
182
+ */
183
+ serviceTokens: z.array(z.object({ from: z.string(), output: z.string() })).default([]),
184
+ /**
185
+ * A service token this module MINTS and owns, by name.
186
+ *
187
+ * Kept from the module this replaces, where it was required. Cloudflare
188
+ * returns a service token's secret exactly once, at creation, so the apply
189
+ * that creates it prints the pair and that is the only chance to capture it.
190
+ */
191
+ serviceTokenName: z.string().min(1).optional(),
192
+ /**
193
+ * Mint a NEW secret for the existing `serviceTokenName`. Off by default:
194
+ * the consumer is separately deployed, and rotating without redeploying it
195
+ * takes that consumer down. See the header.
196
+ */
197
+ rotate: z.boolean().default(false),
198
+ /**
199
+ * The Service Auth policy this module owns, by name.
200
+ *
201
+ * Defaulted rather than required, and the default is computed — see
202
+ * `serviceTokenPolicyNameFor`. A minted token names its own policy exactly
203
+ * as the module this replaces did, so a consumer migrating finds its
204
+ * existing policy and converges it instead of creating a second one beside
205
+ * it and reporting the first as drift.
206
+ */
207
+ serviceTokenPolicyName: z.string().min(1).optional(),
208
+ /** Whether the application shows as a tile in the App Launcher. */
209
+ appLauncherVisible: z.boolean().default(false),
210
+ /**
211
+ * Cloudflare's binding cookie. Off, matching Cloudflare's own default and
212
+ * the module this replaces: a machine caller should never be handed one.
213
+ */
214
+ enableBindingCookie: z.boolean().default(false),
215
+ /** `HttpOnly` on the Access cookie. On, matching Cloudflare's own default. */
216
+ httpOnlyCookieAttribute: z.boolean().default(true),
217
+ /**
218
+ * Perform the deletions this module prints. False by default: an undeclared
219
+ * policy is always reported, never removed, until an operator has read the
220
+ * line and opted in.
221
+ */
222
+ allowDelete: z.boolean().default(false),
223
+ })
224
+ .superRefine((config, ctx) => {
225
+ // An application with neither a person nor a machine on it is one nobody
226
+ // can reach, and it should be deleted rather than emptied. The generalised
227
+ // form of "refuse an empty allow list": emails are no longer the only kind
228
+ // of principal, so the rule is about the union.
229
+ if (
230
+ config.emails.length === 0 &&
231
+ config.serviceTokens.length === 0 &&
232
+ config.serviceTokenName === undefined
233
+ ) {
234
+ ctx.addIssue({
235
+ code: z.ZodIssueCode.custom,
236
+ path: ['emails'],
237
+ message:
238
+ 'this application declares no way in — no emails, no serviceTokens and no ' +
239
+ 'serviceTokenName. An application nobody can reach should be deleted rather than ' +
240
+ 'emptied; declare a principal or remove the instance.',
241
+ })
242
+ }
243
+
244
+ // The rename PUT must carry `auth_domain` (Cloudflare has no PATCH for the
245
+ // resource), and what makes echoing it safe is that the value has already
246
+ // been compared against a declared one. With nothing declared there is
247
+ // nothing to compare, so the write would be CHOOSING the issuer — the exact
248
+ // failure the comparison exists to prevent.
249
+ if (config.orgName !== undefined && config.teamDomain === undefined) {
250
+ ctx.addIssue({
251
+ code: z.ZodIssueCode.custom,
252
+ path: ['orgName'],
253
+ message:
254
+ 'orgName requires teamDomain: renaming the organisation is a full replace that must ' +
255
+ 'echo auth_domain, and echoing a value nothing has compared is choosing the issuer.',
256
+ })
257
+ }
65
258
 
66
- /** Cloudflare wants the apex-less form for `domain`; it derives the zone itself. */
67
- export interface AccessApp {
259
+ if (config.rotate && config.serviceTokenName === undefined) {
260
+ ctx.addIssue({
261
+ code: z.ZodIssueCode.custom,
262
+ path: ['rotate'],
263
+ message:
264
+ 'rotate: true has nothing to rotate — this module only owns the token named by ' +
265
+ 'serviceTokenName. A token reached through serviceTokens is rotated where it is minted.',
266
+ })
267
+ }
268
+ })
269
+
270
+ // ── The diff, which is pure and is where the thinking is ──────────────────
271
+
272
+ /** One `include` rule as Cloudflare stores it. */
273
+ export type IncludeRule = Record<string, unknown>
274
+
275
+ export interface AccessPolicy {
68
276
  id: string
69
277
  name: string
70
- domain: string
278
+ decision: string
279
+ include: IncludeRule[]
280
+ exclude?: IncludeRule[]
281
+ require?: IncludeRule[]
282
+ /** Absent on a policy that inherits the application's. */
283
+ session_duration?: string
284
+ }
285
+
286
+ /** The `include` list for a set of addresses. One rule per person. */
287
+ export function emailIncludes(emails: readonly string[]): Array<{ email: { email: string } }> {
288
+ return emails.map((email) => ({ email: { email } }))
289
+ }
290
+
291
+ /**
292
+ * The addresses a live policy admits, or NULL if it admits anything else.
293
+ *
294
+ * Null is the important half. An `include` list is a set of OR'd rules, so one
295
+ * `{ everyone: {} }`, one `{ ip: … }` or one `{ email_domain: … }` beside the
296
+ * addresses widens the policy to people nobody named, and it does it without
297
+ * changing a single address. Returning null makes any such policy differ from
298
+ * what is declared, so it is REWRITTEN rather than read as a match.
299
+ *
300
+ * That is a real failure mode and not a hypothetical: "let me just add everyone
301
+ * for a minute to test something" is one click in the dashboard, and it leaves
302
+ * a policy whose email list still looks exactly right.
303
+ */
304
+ export function policyEmails(policy: Pick<AccessPolicy, 'include'>): string[] | null {
305
+ const emails: string[] = []
306
+ for (const rule of policy.include ?? []) {
307
+ const keys = Object.keys(rule)
308
+ if (keys.length !== 1 || keys[0] !== 'email') return null
309
+ const value = (rule as { email?: { email?: unknown } }).email?.email
310
+ if (typeof value !== 'string' || value.trim() === '') return null
311
+ emails.push(value.trim().toLowerCase())
312
+ }
313
+ return Array.from(new Set(emails)).toSorted()
314
+ }
315
+
316
+ /** The `include` list for a set of service tokens. One rule per token. */
317
+ export function serviceTokenIncludes(
318
+ tokenIds: readonly string[],
319
+ ): Array<{ service_token: { token_id: string } }> {
320
+ return tokenIds.map((token_id) => ({ service_token: { token_id } }))
321
+ }
322
+
323
+ /**
324
+ * The service tokens a live policy admits, or NULL if it admits anything else.
325
+ *
326
+ * The exact counterpart of `policyEmails`, and it exists for exactly the same
327
+ * reason: an `include` list is OR'd, so one extra rule beside the token widens
328
+ * the policy without changing a single declared value.
329
+ *
330
+ * ⚠️ THE RULE THIS EXISTS TO CATCH IS `any_valid_service_token`. It is one
331
+ * click in the dashboard, it reads like a small convenience, and it admits
332
+ * EVERY service token in the account, including one somebody minted for
333
+ * something else entirely. It is not the declared token id and never matches,
334
+ * so a policy carrying it is rewritten.
335
+ */
336
+ export function policyServiceTokens(policy: Pick<AccessPolicy, 'include'>): string[] | null {
337
+ const tokens: string[] = []
338
+ for (const rule of policy.include ?? []) {
339
+ const keys = Object.keys(rule)
340
+ if (keys.length !== 1 || keys[0] !== 'service_token') return null
341
+ const value = (rule as { service_token?: { token_id?: unknown } }).service_token?.token_id
342
+ if (typeof value !== 'string' || value.trim() === '') return null
343
+ tokens.push(value.trim())
344
+ }
345
+ return Array.from(new Set(tokens)).toSorted()
346
+ }
347
+
348
+ /**
349
+ * One policy this instance declares, and the whole of what it admits.
350
+ *
351
+ * TWO KINDS, and the difference between them is precisely the thing that must
352
+ * not be blurred. A policy of addresses is `allow` and admits people by their
353
+ * address, and a rule of any other shape on it is a hole. A policy of service
354
+ * tokens is Service Auth and admits named tokens, and a rule of any other shape
355
+ * on IT is a hole too. Each is checked against its own idea of a match, so
356
+ * declaring the second could not loosen the first.
357
+ */
358
+ export type DeclaredPolicy =
359
+ | {
360
+ name: string
361
+ admits: 'emails'
362
+ emails: readonly string[]
363
+ sessionDuration?: string
364
+ }
365
+ | {
366
+ name: string
367
+ admits: 'service-tokens'
368
+ tokenIds: readonly string[]
369
+ sessionDuration?: string
370
+ }
371
+
372
+ /**
373
+ * What Cloudflare calls the action, per kind.
374
+ *
375
+ * `non_identity` is Service Auth in the dashboard, and it is not
376
+ * interchangeable with `allow`: an allow policy demands an identity, so a
377
+ * service token on one is admitted by nothing while the policy looks perfectly
378
+ * configured. That is a failure with no visible cause, which is why the
379
+ * decision is part of what is compared rather than something set once at
380
+ * creation.
381
+ */
382
+ export function decisionFor(declared: DeclaredPolicy): 'allow' | 'non_identity' {
383
+ return declared.admits === 'emails' ? 'allow' : 'non_identity'
384
+ }
385
+
386
+ /** The `include` list a declared policy should carry. */
387
+ export function includesFor(declared: DeclaredPolicy): IncludeRule[] {
388
+ return declared.admits === 'emails'
389
+ ? emailIncludes(declared.emails)
390
+ : serviceTokenIncludes(declared.tokenIds)
391
+ }
392
+
393
+ /**
394
+ * The whole body written for a declared policy. Pure; exported for tests.
395
+ *
396
+ * `exclude` and `require` are sent EMPTY rather than omitted, because a PUT is
397
+ * a full replace and an omitted field would leave whatever somebody added by
398
+ * hand in place. A narrowing rule is not a hole, but a policy that silently
399
+ * requires something nobody wrote down locks the right principal out with no
400
+ * visible cause.
401
+ */
402
+ export function policyBodyFor(declared: DeclaredPolicy): Record<string, unknown> {
403
+ return {
404
+ name: declared.name,
405
+ decision: decisionFor(declared),
406
+ include: includesFor(declared),
407
+ exclude: [],
408
+ require: [],
409
+ ...(declared.sessionDuration === undefined
410
+ ? {}
411
+ : { session_duration: declared.sessionDuration }),
412
+ }
413
+ }
414
+
415
+ /** What a declared policy admits, in words, for the apply log. */
416
+ function admits(entry: DeclaredPolicy): string {
417
+ return entry.admits === 'emails' ? entry.emails.join(', ') : entry.tokenIds.join(', ')
418
+ }
419
+
420
+ export interface PolicyPlan {
421
+ /** The declaration this plan is for. */
422
+ declared: DeclaredPolicy
423
+ action: 'create' | 'update' | 'unchanged'
424
+ /** The live policy of that name, once it has been found. */
425
+ mine?: AccessPolicy
426
+ /** Why an update is needed, in words, for the apply log. */
427
+ reason?: string
428
+ }
429
+
430
+ export interface PoliciesPlan {
431
+ /** One plan per declared policy, in the order they were declared. */
432
+ plans: PolicyPlan[]
433
+ /** Every other policy on the application. Each one can let somebody in. */
434
+ undeclared: AccessPolicy[]
435
+ }
436
+
437
+ /**
438
+ * What to do with the application's policies. Pure; exported for tests.
439
+ *
440
+ * Each declared policy is found by NAME, and everything else on the application
441
+ * is undeclared, whatever it is called and whichever way it decides.
442
+ */
443
+ export function planPolicies(input: {
444
+ declared: readonly DeclaredPolicy[]
445
+ actual: AccessPolicy[]
446
+ }): PoliciesPlan {
447
+ const claimed = new Set<AccessPolicy>()
448
+
449
+ const plans = input.declared.map((declared): PolicyPlan => {
450
+ const mine = input.actual.find(
451
+ (policy) => policy.name === declared.name && !claimed.has(policy),
452
+ )
453
+ if (mine) claimed.add(mine)
454
+ return planOne(declared, mine)
455
+ })
456
+
457
+ return { plans, undeclared: input.actual.filter((policy) => !claimed.has(policy)) }
458
+ }
459
+
460
+ function planOne(declared: DeclaredPolicy, mine: AccessPolicy | undefined): PolicyPlan {
461
+ if (!mine) return { declared, action: 'create' }
462
+
463
+ const decision = decisionFor(declared)
464
+ if (mine.decision !== decision) {
465
+ return {
466
+ declared,
467
+ action: 'update',
468
+ mine,
469
+ reason: `decision is "${mine.decision}" and should be "${decision}"`,
470
+ }
471
+ }
472
+
473
+ // Each kind is read by its OWN reader, and each returns null the moment the
474
+ // policy admits by anything else. That is what keeps "an everyone rule beside
475
+ // the addresses is rewritten" true after a policy that admits by something
476
+ // other than an address became a legitimate thing to declare.
477
+ const current = declared.admits === 'emails' ? policyEmails(mine) : policyServiceTokens(mine)
478
+
479
+ if (current === null) {
480
+ return {
481
+ declared,
482
+ action: 'update',
483
+ mine,
484
+ reason:
485
+ declared.admits === 'emails'
486
+ ? 'it admits people by something other than their address'
487
+ : 'it admits by something other than the declared service tokens',
488
+ }
489
+ }
490
+
491
+ const wanted = (declared.admits === 'emails' ? declared.emails : declared.tokenIds).toSorted()
492
+ if (current.join(',') !== wanted.join(',')) {
493
+ return {
494
+ declared,
495
+ action: 'update',
496
+ mine,
497
+ reason: `admits ${current.join(', ') || '(nobody)'}`,
498
+ }
499
+ }
500
+
501
+ // A narrowing rule is not a hole, but it is undeclared, and a policy that
502
+ // silently requires something nobody wrote down is a policy that locks the
503
+ // right principal out for no visible reason.
504
+ if ((mine.exclude ?? []).length > 0 || (mine.require ?? []).length > 0) {
505
+ return { declared, action: 'update', mine, reason: 'it carries exclude or require rules' }
506
+ }
507
+
508
+ // The cookie's lifetime is part of what the policy decides: a policy that
509
+ // admits exactly the right people for a week when the file says an hour is
510
+ // drift no address comparison can see.
511
+ //
512
+ // KNOWN LIMIT, stated rather than left to be discovered. Cloudflare OMITS the
513
+ // field on a policy that inherits the application's, and an absent field is
514
+ // read here as "not drift" — so a policy that has been reset to inherit is
515
+ // indistinguishable from one that never declared a duration. Reading the
516
+ // absence as a mismatch is the worse trade: it makes every apply a rewrite,
517
+ // and a converge that always writes is one whose drift lines nobody reads.
518
+ const live = mine.session_duration
519
+ if (
520
+ declared.sessionDuration !== undefined &&
521
+ typeof live === 'string' &&
522
+ live !== '' &&
523
+ live !== declared.sessionDuration
524
+ ) {
525
+ return {
526
+ declared,
527
+ action: 'update',
528
+ mine,
529
+ reason: `its session lasts "${live}" and should last "${declared.sessionDuration}"`,
530
+ }
531
+ }
532
+
533
+ return { declared, action: 'unchanged', mine }
71
534
  }
72
535
 
73
- export interface ServiceToken {
536
+ /** One identity provider on the organisation, as Cloudflare stores it. */
537
+ export interface IdentityProvider {
74
538
  id: string
75
- name: string
76
- client_id: string
77
- client_secret?: string
539
+ /** `onetimepin`, `cloudflare`, `google`, and so on. The match key. */
540
+ type: string
541
+ name?: string
542
+ }
543
+
544
+ export interface IdentityProvidersPlan {
545
+ /** Declared types the organisation does not offer yet. */
546
+ create: string[]
547
+ /** Declared types already there, so nothing is created twice. */
548
+ present: IdentityProvider[]
549
+ /** Everything else. Reported, never removed. */
550
+ undeclared: IdentityProvider[]
551
+ }
552
+
553
+ /**
554
+ * What the next apply does to the ORGANISATION's identity providers. Pure;
555
+ * exported for tests.
556
+ *
557
+ * MATCHED BY TYPE, not by name. `onetimepin` carries no name at all
558
+ * (Cloudflare returns `""`), so a name match would create a second one on every
559
+ * apply forever. The question this answers is whether the organisation offers a
560
+ * way in, not how many copies of it there are.
561
+ *
562
+ * Declaring nothing plans nothing and still reports everything, so an
563
+ * organisation whose providers nobody has declared is described rather than
564
+ * emptied. That is what makes this field safe to point at a shared account.
565
+ */
566
+ export function planIdentityProviders(input: {
567
+ declared: readonly string[]
568
+ actual: readonly IdentityProvider[]
569
+ }): IdentityProvidersPlan {
570
+ const declared = Array.from(new Set(input.declared))
571
+ const has = (type: string) => input.actual.some((provider) => provider.type === type)
572
+ return {
573
+ create: declared.filter((type) => !has(type)),
574
+ present: input.actual.filter((provider) => declared.includes(provider.type)),
575
+ undeclared: input.actual.filter((provider) => !declared.includes(provider.type)),
576
+ }
577
+ }
578
+
579
+ /**
580
+ * What to call a provider this module creates. Cloudflare shows the name in the
581
+ * dashboard and on the sign-in screen when more than one provider exists, so it
582
+ * is worth being the same string a person would have typed.
583
+ */
584
+ const IDENTITY_PROVIDER_NAMES: Record<string, string> = {
585
+ onetimepin: 'One-time PIN',
78
586
  }
79
587
 
80
- /** The policy body: one `include` naming the service token. Pure; exported for tests. */
81
- export function policyBody(name: string, serviceTokenId: string, sessionDuration: string) {
588
+ /** `https://host/path/` and `host/path` are the same application. */
589
+ export function normalizeDomain(domain: string): string {
590
+ return domain
591
+ .trim()
592
+ .toLowerCase()
593
+ .replace(/^https?:\/\//, '')
594
+ .replace(/\/+$/, '')
595
+ }
596
+
597
+ /**
598
+ * What the Service Auth policy is called. Pure; exported for tests.
599
+ *
600
+ * The default is computed rather than constant, and that is a migration
601
+ * decision rather than a stylistic one. The module this replaces named its
602
+ * policy `"<serviceTokenName> service token"`, so a consumer moving to this one
603
+ * finds its existing policy under the same name and converges it. A constant
604
+ * default would create a second policy beside the live one and report the live
605
+ * one as drift — on the application it is currently the only way into.
606
+ */
607
+ export function serviceTokenPolicyNameFor(config: {
608
+ serviceTokenName?: string
609
+ serviceTokenPolicyName?: string
610
+ }): string {
611
+ if (config.serviceTokenPolicyName !== undefined) return config.serviceTokenPolicyName
612
+ if (config.serviceTokenName !== undefined) return `${config.serviceTokenName} service token`
613
+ return 'service tokens'
614
+ }
615
+
616
+ /** The application body. Pure; exported for tests. `domain` is already normalized. */
617
+ export function appBody(config: {
618
+ name: string
619
+ domain: string
620
+ sessionDuration: string
621
+ appLauncherVisible: boolean
622
+ enableBindingCookie: boolean
623
+ httpOnlyCookieAttribute: boolean
624
+ }): Record<string, unknown> {
82
625
  return {
83
- name,
84
- decision: 'non_identity' as const,
85
- // `non_identity` is required for a service-token policy: an identity
86
- // decision expects a human principal and rejects a token outright.
87
- include: [{ service_token: { token_id: serviceTokenId } }],
88
- session_duration: sessionDuration,
626
+ name: config.name,
627
+ domain: config.domain,
628
+ type: 'self_hosted',
629
+ session_duration: config.sessionDuration,
630
+ app_launcher_visible: config.appLauncherVisible,
631
+ enable_binding_cookie: config.enableBindingCookie,
632
+ http_only_cookie_attribute: config.httpOnlyCookieAttribute,
89
633
  }
90
634
  }
91
635
 
636
+ /**
637
+ * The application this instance converges, and how it was recognised.
638
+ *
639
+ * TWO RULES, IN ORDER, and each is here because of a failure the other does not
640
+ * catch. The DOMAIN is tried first: two applications on one hostname and path
641
+ * is a configuration nobody can reason about, and creating the second one is
642
+ * how it happens. The NAME is tried second: without it, editing `domain` in the
643
+ * instance file would leave the live application standing with the old
644
+ * hostname, unowned by anything, and build a second one beside it.
645
+ *
646
+ * Pure; exported for tests.
647
+ */
648
+ export function findApp<T extends { id: string; name: string; domain: string }>(
649
+ apps: readonly T[],
650
+ want: { name: string; domain: string },
651
+ ): { app: T; by: 'domain' | 'name' } | undefined {
652
+ const byDomain = apps.find((app) => normalizeDomain(app.domain) === want.domain)
653
+ if (byDomain) return { app: byDomain, by: 'domain' }
654
+ const byName = apps.find((app) => app.name === want.name)
655
+ return byName ? { app: byName, by: 'name' } : undefined
656
+ }
657
+
658
+ // ── Apply ─────────────────────────────────────────────────────────────────
659
+
660
+ /** The Zero Trust organisation. Two fields, deliberately handled apart. */
661
+ interface CfOrg {
662
+ /** The issuer, and never written by this module. */
663
+ auth_domain?: string
664
+ /** The display name, and converged when `orgName` is declared. */
665
+ name?: string
666
+ }
667
+
668
+ interface CfApp {
669
+ id: string
670
+ /** The audience tag: 64 hex characters, and what a verifying Worker checks. */
671
+ aud?: string
672
+ name: string
673
+ domain: string
674
+ type?: string
675
+ session_duration?: string
676
+ }
677
+
678
+ interface ServiceToken {
679
+ id: string
680
+ name: string
681
+ client_id: string
682
+ client_secret?: string
683
+ }
684
+
92
685
  /**
93
686
  * Surface a freshly-minted pair the moment it exists.
94
687
  *
95
688
  * Cloudflare returns a service token's secret exactly once, at creation. The
96
- * first version of this module printed it at the END of apply, after the app
97
- * and policy were converged — and the very first real apply 403'd on the app,
98
- * so the secret was minted, never shown, and unrecoverable except by rotating.
689
+ * first version of this printed it at the END of apply, after the app and
690
+ * policy were converged — and the very first real apply 403'd on the app, so
691
+ * the secret was minted, never shown, and unrecoverable except by rotating.
99
692
  * Anything that can fail between minting a write-once value and showing it is a
100
693
  * chance to lose it, so nothing goes between.
101
694
  */
@@ -110,110 +703,457 @@ export const cloudflareAccessModule = defineModule({
110
703
  configSchema,
111
704
  outputs: z.object({
112
705
  appId: z.string(),
706
+ /**
707
+ * The application's audience tag, for a Worker that verifies assertions.
708
+ * Empty when Cloudflare did not return one.
709
+ */
710
+ aud: z.string(),
711
+ /** Passed on so a Worker derives its issuer and JWKS URL from one value. */
712
+ teamDomain: z.string(),
713
+ /** What the organisation is called after this apply. Cosmetic. */
714
+ orgName: z.string(),
715
+ /** How a person may authenticate after this apply. Empty means nobody can. */
716
+ identityProviders: z.array(z.string()),
717
+ /** Providers the organisation offers that nothing here declares. */
718
+ undeclaredIdentityProviders: z.array(z.string()),
719
+ appDomain: z.string(),
720
+ /** Who the people policy admits, after this apply. */
721
+ emails: z.array(z.string()),
722
+ /** The people policy's id, or empty when no people are declared. */
113
723
  policyId: z.string(),
724
+ /** Every policy this instance declares, by id, people first. */
725
+ policyIds: z.array(z.string()),
726
+ /** Every service token admitted without a person: referenced and minted. */
727
+ serviceTokenIds: z.array(z.string()),
728
+ /** The token this module MINTS, if one is declared. Empty otherwise. */
114
729
  serviceTokenId: z.string(),
115
730
  /** Safe to output — the id is not a secret. */
116
731
  clientId: z.string(),
117
- /** Only non-empty on the apply that CREATED or rotated the token. */
732
+ /** Only non-empty on the apply that CREATED or rotated the minted token. */
118
733
  clientSecret: z.string(),
734
+ /** Whether the minted service token was created by this apply. */
119
735
  created: z.boolean(),
736
+ /** Whether the application was created by this apply. */
737
+ appCreated: z.boolean(),
738
+ /** Policies on this application that nothing here declares, after this apply. */
739
+ undeclared: z.array(z.string()),
120
740
  changed: z.boolean(),
121
741
  }),
122
742
  async apply(config, ctx) {
123
743
  const token = resolveApiToken(config.apiToken, ctx.imports)
124
- const base = `/accounts/${config.accountId}`
125
- let changed = false
744
+ const account = `/accounts/${config.accountId}`
745
+ const domain = normalizeDomain(config.domain)
126
746
 
127
- // 1. The service token, first: the policy needs its id.
128
- const tokens = await cf<ServiceToken[]>(token, 'GET', `${base}/access/service_tokens`)
129
- let svc = tokens.find((t) => t.name === config.serviceTokenName)
130
- let created = false
131
- let clientSecret = ''
132
- if (!svc) {
133
- svc = await cf<ServiceToken>(token, 'POST', `${base}/access/service_tokens`, {
134
- name: config.serviceTokenName,
135
- duration: '8760h', // one year; Cloudflare's max, and expiry here is an outage
136
- })
137
- clientSecret = svc.client_secret ?? ''
138
- created = true
139
- changed = true
140
- console.log(` Created service token "${config.serviceTokenName}" (${svc.id})`)
141
- announce(svc.client_id, clientSecret)
142
- } else if (config.rotate) {
143
- const rotated = await cf<ServiceToken>(
747
+ // Resolved before anything is called, so a service token instance that is
748
+ // not imported fails while nothing has been touched.
749
+ const referencedTokenIds = config.serviceTokens.map((ref, index) =>
750
+ resolveRef(ref, ctx.imports, `serviceTokens[${index}]`),
751
+ )
752
+
753
+ // 1. The organisation. Two fields off one endpoint, treated in OPPOSITE
754
+ // ways, and the asymmetry is the whole of this step.
755
+ //
756
+ // `auth_domain` is COMPARED FIRST and only ever ECHOED BACK. A consumer
757
+ // Worker derives the issuer it verifies every assertion against from
758
+ // that string, so a rename in the dashboard that nobody wrote down here
759
+ // is a silent lockout and this is the only place it can be caught. The
760
+ // rename below cannot omit the field, because Cloudflare has no PATCH
761
+ // for this resource and refuses a partial write; what makes that safe is
762
+ // that the comparison has already thrown unless the value being echoed
763
+ // is the one live on the account.
764
+ //
765
+ // Reading needs a scope this module can otherwise live without, so a
766
+ // failure to READ is a warning and the guard is skipped. A failure to
767
+ // WRITE is not a warning: somebody asked for that rename in a file.
768
+ let orgName = ''
769
+ let orgRenamed = false
770
+ try {
771
+ const org = await cf<CfOrg>(token, 'GET', `${account}/access/organizations`)
772
+ const live = (org.auth_domain ?? '').trim()
773
+ const normalized = live.toLowerCase()
774
+ if (config.teamDomain === undefined) {
775
+ console.log(
776
+ ` Zero Trust organisation: ${normalized || '(no team domain)'} — this instance ` +
777
+ `declares no teamDomain, so nothing is compared. Declare it if anything verifies ` +
778
+ `an Access assertion issued by this organisation.`,
779
+ )
780
+ } else if (normalized !== '' && normalized !== config.teamDomain) {
781
+ throw new Error(
782
+ `refusing to apply: this instance declares teamDomain "${config.teamDomain}", but the ` +
783
+ `Zero Trust organisation on account ${config.accountId} answers "${normalized}". A ` +
784
+ `Worker derives the issuer it verifies every assertion against from that value, so ` +
785
+ `applying over this would leave an application nobody can reach and nothing saying ` +
786
+ `why. Somebody renamed the team: put the new name in this file.`,
787
+ )
788
+ } else {
789
+ console.log(` Zero Trust organisation: ${normalized} (matches this instance)`)
790
+ }
791
+ orgName = (org.name ?? '').trim()
792
+
793
+ if (config.orgName !== undefined && orgName !== config.orgName) {
794
+ // ⚠️ THE WRITE HAS TO CARRY `auth_domain`, and this is the one place in
795
+ // this module where that is true. Measured on a live account on
796
+ // 2026-08-18: `PUT /access/organizations` with `{name}` alone is
797
+ // refused with `11004 access.api.error.invalid_auth_domain`. There is
798
+ // no PATCH for this resource, so the update is a full replace and the
799
+ // field cannot be left out.
800
+ //
801
+ // What keeps the guarantee is the ORDER, not the omission. The check
802
+ // above has already run and has already thrown unless the live
803
+ // `auth_domain` equals the declared `teamDomain`, so what goes back is
804
+ // the value that was just read and verified. The apply can therefore
805
+ // ECHO the team domain and can never CHANGE it, which is the property
806
+ // the guard exists to hold. Read `live` here as "the verified value",
807
+ // and never replace it with `config.teamDomain`: they are equal by the
808
+ // time this line runs, and only one of them is a fact about the account
809
+ // rather than a hope from a file.
810
+ if (live === '') {
811
+ throw new Error(
812
+ `refusing to apply: this organisation reports no auth_domain, so renaming it would ` +
813
+ `have to invent one, and a Worker's issuer is derived from that value. Set the ` +
814
+ `team domain in the dashboard first, then apply.`,
815
+ )
816
+ }
817
+ const was = orgName === '' ? '(unnamed)' : orgName
818
+ await cf<CfOrg>(token, 'PUT', `${account}/access/organizations`, {
819
+ name: config.orgName,
820
+ auth_domain: live,
821
+ })
822
+
823
+ // Read it back with a FRESH GET rather than trusting the response to
824
+ // the write. `name` and `auth_domain` are two fields on one object and
825
+ // "does renaming the organisation move the team domain too" is not a
826
+ // question to settle by assumption on an application somebody is signed
827
+ // in to. If it ever does move, this is a hard error naming both values,
828
+ // because the application is unreachable from that moment and no later
829
+ // step would notice.
830
+ const after = await cf<CfOrg>(token, 'GET', `${account}/access/organizations`)
831
+ const domainAfter = (after.auth_domain ?? '').trim().toLowerCase()
832
+ if (domainAfter !== '' && domainAfter !== config.teamDomain) {
833
+ throw new Error(
834
+ `refusing to apply: renaming the organisation to "${config.orgName}" also moved ` +
835
+ `auth_domain from "${config.teamDomain}" to "${domainAfter}". A Worker's issuer is ` +
836
+ `derived from that value, so the application is unreachable until one of the two ` +
837
+ `is put back by hand in the dashboard.`,
838
+ )
839
+ }
840
+ orgName = (after.name ?? '').trim()
841
+ orgRenamed = true
842
+ console.log(` renamed the organisation: ${was} -> ${orgName}`)
843
+ }
844
+ } catch (cause) {
845
+ if ((cause as Error).message.startsWith('refusing to apply')) throw cause
846
+ // A read this instance can live without is a warning. A read it CANNOT is
847
+ // not: `orgName` is a rename somebody asked for in a file, and warning
848
+ // about it would leave the apply reporting success over a sign-in screen
849
+ // that still says whatever it said before. Same rule as the identity
850
+ // providers below, for the same reason.
851
+ if (config.orgName !== undefined) throw cause
852
+ console.log(
853
+ ` ⚠️ Could not read the Zero Trust organisation (${(cause as Error).message}). Any ` +
854
+ `declared teamDomain is therefore UNCHECKED this apply. Grant "Access: Organizations ` +
855
+ `Read" to the token this instance imports to get the check back, and "Access: ` +
856
+ `Organizations Write" as well if it declares an orgName.`,
857
+ )
858
+ }
859
+
860
+ // 2. The identity providers: HOW a person authenticates, as against WHICH
861
+ // people the policies further down then admit. Both are required and
862
+ // neither is sufficient, which is why they live in one file.
863
+ //
864
+ // ORGANISATION-LEVEL. Undeclared providers are reported and kept. An
865
+ // extra provider is NOT an open door the way an extra allow policy is,
866
+ // because the policies still decide who gets through; it is a way to
867
+ // authenticate that nobody wrote down, which is worth a line and not
868
+ // worth a deletion — least of all a deletion that reaches every other
869
+ // application in the account.
870
+ const identityProviders: string[] = []
871
+ const undeclaredIdps: string[] = []
872
+ let idpsCreated = 0
873
+ try {
874
+ const actual = await cf<IdentityProvider[]>(
144
875
  token,
145
- 'POST',
146
- `${base}/access/service_tokens/${svc.id}/rotate`,
876
+ 'GET',
877
+ `${account}/access/identity_providers`,
878
+ )
879
+ const plan = planIdentityProviders({ declared: config.identityProviders, actual })
880
+
881
+ for (const type of plan.create) {
882
+ await cf(token, 'POST', `${account}/access/identity_providers`, {
883
+ type,
884
+ name: IDENTITY_PROVIDER_NAMES[type] ?? type,
885
+ config: {},
886
+ })
887
+ idpsCreated++
888
+ identityProviders.push(type)
889
+ console.log(` + added the "${IDENTITY_PROVIDER_NAMES[type] ?? type}" way to sign in`)
890
+ }
891
+ for (const provider of plan.present) {
892
+ identityProviders.push(provider.type)
893
+ }
894
+ for (const provider of plan.undeclared) {
895
+ undeclaredIdps.push(provider.type)
896
+ console.log(
897
+ ` · "${provider.type}" is offered by this organisation and is declared nowhere. ` +
898
+ `Kept: the policies still decide who gets through, so it is not an open door, and ` +
899
+ `this list is shared with every other application in the account.`,
900
+ )
901
+ }
902
+ if (
903
+ config.emails.length > 0 &&
904
+ config.identityProviders.length === 0 &&
905
+ plan.undeclared.length === 0
906
+ ) {
907
+ console.log(
908
+ ` ⚠️ This organisation offers NO way to sign in, and this instance declares none. ` +
909
+ `Every person on the policy below will be refused. Add 'onetimepin' to ` +
910
+ `identityProviders, or add a provider in the dashboard.`,
911
+ )
912
+ }
913
+ } catch (cause) {
914
+ if (config.identityProviders.length > 0) throw cause
915
+ console.log(
916
+ ` ⚠️ Could not read the identity providers (${(cause as Error).message}). This instance ` +
917
+ `declares none, so nothing was going to change; grant "Access: Identity Providers ` +
918
+ `Read" to see how people sign in.`,
919
+ )
920
+ }
921
+
922
+ // 3. List before creating, always. An account with no Zero Trust
923
+ // organisation fails here, which is the right place for it to fail:
924
+ // creating the organisation is a console step and is nobody's apply.
925
+ let apps: CfApp[]
926
+ try {
927
+ apps = await cf<CfApp[]>(token, 'GET', `${account}/access/apps?per_page=500`)
928
+ } catch (cause) {
929
+ throw new Error(
930
+ `refusing to apply: could not list Access applications on account ${config.accountId}: ` +
931
+ `${(cause as Error).message}. If this account has no Zero Trust organisation yet, that ` +
932
+ `is a one-time step in the Cloudflare dashboard and nothing here can do it. If it has ` +
933
+ `one, check the imported token holds "Access: Apps and Policies Read".`,
934
+ { cause },
935
+ )
936
+ }
937
+
938
+ const found = findApp(apps, { name: config.name, domain })
939
+ const body = appBody({ ...config, domain })
940
+
941
+ let app: CfApp
942
+ let appChanged: boolean
943
+ if (found) {
944
+ // ALWAYS a PUT, even when the compared fields agree. This module declares
945
+ // more of the application than it can read back reliably, and a converge
946
+ // that skips the write leaves whatever the dashboard did to the fields it
947
+ // does not compare. `changed` is computed from the compared subset
948
+ // instead, so a re-apply reports honestly without silently accepting
949
+ // drift in a field nobody looked at.
950
+ appChanged =
951
+ found.app.name !== config.name ||
952
+ normalizeDomain(found.app.domain) !== domain ||
953
+ (typeof found.app.session_duration === 'string' &&
954
+ found.app.session_duration !== config.sessionDuration)
955
+ app = await cf<CfApp>(token, 'PUT', `${account}/access/apps/${found.app.id}`, body)
956
+ console.log(
957
+ ` Converged Access application "${config.name}" on ${domain} (${app.id}, matched by ` +
958
+ `${found.by})`,
147
959
  )
148
- clientSecret = rotated.client_secret ?? ''
149
- changed = true
150
- console.log(` ROTATED service token "${config.serviceTokenName}" — the old secret is dead`)
151
- announce(svc.client_id, clientSecret)
152
- } else {
153
- console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists, not rotated`)
154
- }
155
-
156
- // 2. The application, converged by name.
157
- const apps = await cf<AccessApp[]>(token, 'GET', `${base}/access/apps`)
158
- let app = apps.find((a) => a.name === config.name)
159
- const appBody = {
160
- name: config.name,
161
- domain: config.domain,
162
- type: 'self_hosted',
163
- session_duration: config.sessionDuration,
164
- // A machine caller presents its token on every request; handing it a
165
- // cookie would let a leaked cookie outlive the token.
166
- enable_binding_cookie: false,
167
- // The Worker reads no identity from this; leaving JWT injection off keeps
168
- // the request the Worker forwards byte-identical to what the pad expects.
169
- http_only_cookie_attribute: true,
170
- }
171
- if (!app) {
172
- app = await cf<AccessApp>(token, 'POST', `${base}/access/apps`, appBody)
173
- changed = true
174
- console.log(` Created Access app "${config.name}" for ${config.domain} (${app.id})`)
175
- } else if (app.domain !== config.domain) {
176
- app = await cf<AccessApp>(token, 'PUT', `${base}/access/apps/${app.id}`, appBody)
177
- changed = true
178
- console.log(` Updated Access app "${config.name}" -> ${config.domain}`)
179
960
  } else {
180
- console.log(` Access app "${config.name}" (${app.id}) unchanged`)
961
+ app = await cf<CfApp>(token, 'POST', `${account}/access/apps`, body)
962
+ appChanged = true
963
+ console.log(` Created Access application "${config.name}" on ${domain} (${app.id})`)
181
964
  }
182
965
 
183
- // 3. The policy. Converged by name within the app.
184
- const policyName = `${config.serviceTokenName} service token`
185
- const policies = await cf<Array<{ id: string; name: string }>>(
966
+ // 4. The service token this module owns, if one is declared.
967
+ //
968
+ // AFTER the application, deliberately. The measured failure that made
969
+ // `announce` exist was a 403 on creating the app, which — with the mint
970
+ // first — burned a write-once secret for an application that was never
971
+ // created. Minting after means the same 403 costs nothing, and the
972
+ // policy below is the only thing that needs the id.
973
+ let mintedTokenId = ''
974
+ let clientId = ''
975
+ let clientSecret = ''
976
+ let tokenCreated = false
977
+ let rotated = false
978
+ if (config.serviceTokenName !== undefined) {
979
+ const tokens = await cf<ServiceToken[]>(token, 'GET', `${account}/access/service_tokens`)
980
+ let svc = tokens.find((t) => t.name === config.serviceTokenName)
981
+ if (!svc) {
982
+ svc = await cf<ServiceToken>(token, 'POST', `${account}/access/service_tokens`, {
983
+ name: config.serviceTokenName,
984
+ duration: '8760h', // one year; Cloudflare's max, and expiry here is an outage
985
+ })
986
+ clientSecret = svc.client_secret ?? ''
987
+ tokenCreated = true
988
+ console.log(` Created service token "${config.serviceTokenName}" (${svc.id})`)
989
+ announce(svc.client_id, clientSecret)
990
+ } else if (config.rotate) {
991
+ const fresh = await cf<ServiceToken>(
992
+ token,
993
+ 'POST',
994
+ `${account}/access/service_tokens/${svc.id}/rotate`,
995
+ )
996
+ clientSecret = fresh.client_secret ?? ''
997
+ rotated = true
998
+ console.log(` ROTATED service token "${config.serviceTokenName}" — the old secret is dead`)
999
+ announce(svc.client_id, clientSecret)
1000
+ } else {
1001
+ console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists, not rotated`)
1002
+ }
1003
+ mintedTokenId = svc.id
1004
+ clientId = svc.client_id
1005
+ }
1006
+
1007
+ const serviceTokenIds = [...referencedTokenIds, ...(mintedTokenId ? [mintedTokenId] : [])]
1008
+
1009
+ // 5. Converge the policies this instance owns, and report every other.
1010
+ //
1011
+ // Up to TWO: the people, and the machines. They are planned separately
1012
+ // and each is compared against its OWN idea of a match, so a Service Auth
1013
+ // policy existing cannot make an `everyone` rule beside the addresses
1014
+ // look acceptable.
1015
+ const declared: DeclaredPolicy[] = [
1016
+ ...(config.emails.length > 0
1017
+ ? [
1018
+ {
1019
+ name: config.policyName,
1020
+ admits: 'emails' as const,
1021
+ emails: config.emails,
1022
+ sessionDuration: config.sessionDuration,
1023
+ },
1024
+ ]
1025
+ : []),
1026
+ ...(serviceTokenIds.length > 0
1027
+ ? [
1028
+ {
1029
+ name: serviceTokenPolicyNameFor(config),
1030
+ admits: 'service-tokens' as const,
1031
+ tokenIds: serviceTokenIds,
1032
+ sessionDuration: config.sessionDuration,
1033
+ },
1034
+ ]
1035
+ : []),
1036
+ ]
1037
+
1038
+ const actual = await cf<AccessPolicy[]>(
186
1039
  token,
187
1040
  'GET',
188
- `${base}/access/apps/${app.id}/policies`,
1041
+ `${account}/access/apps/${app.id}/policies`,
189
1042
  )
190
- const body = policyBody(policyName, svc.id, config.sessionDuration)
191
- const existingPolicy = policies.find((p) => p.name === policyName)
192
- let policyId: string
193
- if (!existingPolicy) {
194
- const made = await cf<{ id: string }>(
195
- token,
196
- 'POST',
197
- `${base}/access/apps/${app.id}/policies`,
198
- body,
1043
+ const plan = planPolicies({ declared, actual })
1044
+
1045
+ const policyIds: string[] = []
1046
+ let rewrote = false
1047
+ for (const step of plan.plans) {
1048
+ const policyBody = policyBodyFor(step.declared)
1049
+
1050
+ if (step.action === 'create') {
1051
+ const created = await cf<{ id: string }>(
1052
+ token,
1053
+ 'POST',
1054
+ `${account}/access/apps/${app.id}/policies`,
1055
+ policyBody,
1056
+ )
1057
+ policyIds.push(created.id)
1058
+ rewrote = true
1059
+ console.log(
1060
+ ` + created policy "${step.declared.name}" admitting ${admits(step.declared)}`,
1061
+ )
1062
+ } else if (step.action === 'update') {
1063
+ policyIds.push(step.mine!.id)
1064
+ rewrote = true
1065
+ await cf(
1066
+ token,
1067
+ 'PUT',
1068
+ `${account}/access/apps/${app.id}/policies/${step.mine!.id}`,
1069
+ policyBody,
1070
+ )
1071
+ console.log(
1072
+ ` ~ rewrote policy "${step.declared.name}" (${step.reason}) to admit ` +
1073
+ `${admits(step.declared)}`,
1074
+ )
1075
+ } else {
1076
+ policyIds.push(step.mine!.id)
1077
+ console.log(` = policy "${step.declared.name}" already admits ${admits(step.declared)}`)
1078
+ }
1079
+ }
1080
+
1081
+ // The people policy is first when it is declared at all; empty otherwise.
1082
+ const policyId = config.emails.length > 0 ? (policyIds[0] ?? '') : ''
1083
+
1084
+ // 6. Anything else on this application. Loud, because unlike an undeclared
1085
+ // DNS record, an undeclared policy is somebody's way in.
1086
+ //
1087
+ // `remaining` is what is still there when this loop ends, and it is what
1088
+ // the `undeclared` output reports. Reporting `plan.undeclared` instead
1089
+ // would be reporting the policies this apply just deleted, which reads as
1090
+ // drift that survived rather than drift that was fixed.
1091
+ const remaining: AccessPolicy[] = []
1092
+ let deleted = 0
1093
+ for (const policy of plan.undeclared) {
1094
+ const admittedBy =
1095
+ policyEmails(policy)?.join(', ') ??
1096
+ policyServiceTokens(policy)
1097
+ ?.map((id) => `service token ${id}`)
1098
+ .join(', ') ??
1099
+ 'not by address or service token'
1100
+ const description = `"${policy.name}" (${policy.decision}, ${admittedBy})`
1101
+ if (config.allowDelete) {
1102
+ await cf(token, 'DELETE', `${account}/access/apps/${app.id}/policies/${policy.id}`)
1103
+ deleted++
1104
+ console.log(` - deleted undeclared policy ${description}`)
1105
+ } else {
1106
+ remaining.push(policy)
1107
+ console.log(
1108
+ ` ‼️ DRIFT: policy ${description} is on this application and is declared nowhere. ` +
1109
+ `If it decides "allow", somebody can reach this application who is not in this ` +
1110
+ `file. Remove it in the dashboard, or set allowDelete: true on this instance.`,
1111
+ )
1112
+ }
1113
+ }
1114
+
1115
+ // 7. What a verifying consumer needs, printed as well as returned: an apply
1116
+ // nobody can read is an apply nobody can check.
1117
+ console.log(` Access is now the way in to ${domain}:`)
1118
+ if (config.teamDomain !== undefined) console.log(` team domain ${config.teamDomain}`)
1119
+ if (app.aud) console.log(` audience ${app.aud}`)
1120
+ if (config.emails.length > 0) {
1121
+ console.log(
1122
+ ` sign in with ${identityProviders.join(', ') || '(nothing, so nobody can sign in)'}`,
199
1123
  )
200
- policyId = made.id
201
- changed = true
202
- console.log(` Created policy "${policyName}"`)
203
- } else {
204
- policyId = existingPolicy.id
205
- await cf(token, 'PUT', `${base}/access/apps/${app.id}/policies/${policyId}`, body)
206
- console.log(` Policy "${policyName}" converged`)
1124
+ console.log(` admits ${config.emails.join(', ')}`)
1125
+ }
1126
+ if (serviceTokenIds.length > 0) {
1127
+ console.log(` and ${serviceTokenIds.length} service token(s), without a person`)
207
1128
  }
208
1129
 
209
1130
  return {
210
1131
  appId: app.id,
1132
+ aud: app.aud ?? '',
1133
+ teamDomain: config.teamDomain ?? '',
1134
+ orgName,
1135
+ identityProviders,
1136
+ undeclaredIdentityProviders: undeclaredIdps,
1137
+ appDomain: domain,
1138
+ emails: [...config.emails],
211
1139
  policyId,
212
- serviceTokenId: svc.id,
213
- clientId: svc.client_id,
1140
+ policyIds,
1141
+ serviceTokenIds,
1142
+ serviceTokenId: mintedTokenId,
1143
+ clientId,
214
1144
  clientSecret,
215
- created,
216
- changed,
1145
+ created: tokenCreated,
1146
+ appCreated: found === undefined,
1147
+ // What is still undeclared AFTER this apply, not what was before it.
1148
+ undeclared: remaining.map((policy) => `${policy.name} (${policy.decision})`),
1149
+ changed:
1150
+ appChanged ||
1151
+ rewrote ||
1152
+ deleted > 0 ||
1153
+ orgRenamed ||
1154
+ idpsCreated > 0 ||
1155
+ tokenCreated ||
1156
+ rotated,
217
1157
  }
218
1158
  },
219
1159
  })