@zabaca/zbc 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +97 -0
- package/package.json +1 -1
- package/src/commands/secret.ts +1 -66
- package/src/commands/update.ts +44 -1
- package/src/engine/actions.ts +35 -3
- package/src/engine/on-demand.ts +9 -1
- package/src/engine/secret-outputs.ts +15 -0
- package/src/engine/secrets.ts +81 -1
- package/src/utils/copy-refresh.ts +124 -19
- package/src/utils/template-history.ts +66 -0
- package/templates/history.json +1 -0
- package/templates/infra/modules/cloudflare/index.ts +140 -1
- package/templates/infra/modules/cloudflare-access/index.ts +176 -65
- package/templates/infra/modules/cloudflare-access/registry.json +1 -1
- package/templates/infra/modules/cloudflare-api/index.ts +56 -0
- package/templates/infra/modules/cloudflare-email/index.ts +44 -17
- package/templates/infra/modules/cloudflare-email/registry.json +1 -1
- package/templates/infra/modules/cloudflare-stored-token/index.ts +343 -0
- package/templates/infra/modules/cloudflare-stored-token/registry.json +12 -0
- package/templates/infra/modules/cloudflare-token/index.ts +46 -17
- package/templates/infra/modules/cloudflare-token/registry.json +1 -1
- package/templates/infra/modules/cloudflare-tunnel/index.ts +63 -8
- package/templates/infra/modules/cloudflare-tunnel/registry.json +1 -1
- package/templates/infra/modules/d1/index.ts +37 -35
- package/templates/infra/modules/d1/registry.json +1 -1
- package/templates/infra/modules/docker-compose-stack/index.ts +3 -1
- package/templates/infra/modules/queue/index.ts +28 -18
- package/templates/infra/modules/queue/registry.json +1 -1
- package/templates/infra/modules/r2/index.ts +20 -11
- package/templates/infra/modules/r2/registry.json +1 -1
- package/templates/infra/src/context.ts +41 -0
- package/templates/infra/src/testing.ts +19 -1
- package/templates/infra/src/types.ts +23 -0
|
@@ -71,8 +71,16 @@ import { cf } from '../cloudflare-api'
|
|
|
71
71
|
// An Access service token's consumer is somebody ELSE, deployed from a
|
|
72
72
|
// different repo on a different cadence, so rolling on every apply would
|
|
73
73
|
// invalidate the credential that consumer holds and take it down until it was
|
|
74
|
-
// redeployed. So: created once, thereafter REUSED, never rotated
|
|
75
|
-
//
|
|
74
|
+
// redeployed. So: created once, thereafter REUSED, never rotated by an apply.
|
|
75
|
+
//
|
|
76
|
+
// ── Its secret is minted and stored by an action (ADR-0023) ──────────────
|
|
77
|
+
// Cloudflare returns the secret once, at creation. `apply` used to create the
|
|
78
|
+
// token and print the pair, and six consumers caught it there: from the log,
|
|
79
|
+
// from `--json`, or by hand. Now `zbc run <env> <instance> mint` creates the
|
|
80
|
+
// token and stores the secret under `serviceTokenSecret` in secrets.yaml, and
|
|
81
|
+
// `rotate` does the same for the day it leaks. `apply` creates no token and
|
|
82
|
+
// prints no secret: it requires the stored key and the token to exist, and
|
|
83
|
+
// says which action to run when either does not.
|
|
76
84
|
//
|
|
77
85
|
// There is deliberately no `destroy`. Destroying an Access application does not
|
|
78
86
|
// tidy anything up, it takes the lock off the door.
|
|
@@ -206,14 +214,21 @@ const configSchema = z
|
|
|
206
214
|
* A service token this module MINTS and owns, by name.
|
|
207
215
|
*
|
|
208
216
|
* Kept from the module this replaces, where it was required. Cloudflare
|
|
209
|
-
* returns a service token's secret exactly once, at creation, so the
|
|
210
|
-
*
|
|
217
|
+
* returns a service token's secret exactly once, at creation, so the token
|
|
218
|
+
* is created by the `mint` action, which stores the secret, and never by
|
|
219
|
+
* `apply`. Needs `serviceTokenSecret`.
|
|
211
220
|
*/
|
|
212
221
|
serviceTokenName: z.string().min(1).optional(),
|
|
213
222
|
/**
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
223
|
+
* The key in this environment's secrets.yaml that holds the client secret
|
|
224
|
+
* of `serviceTokenName`. Required with it. `mint` and `rotate` write it;
|
|
225
|
+
* `apply` requires it to be there. A token minted before this key existed:
|
|
226
|
+
* put the secret you hold under the key, or run `rotate` if nobody holds it.
|
|
227
|
+
*/
|
|
228
|
+
serviceTokenSecret: z.string().min(1).optional(),
|
|
229
|
+
/**
|
|
230
|
+
* Gone: rotating is the `rotate` action now. `false` is still accepted so
|
|
231
|
+
* an instance that spelled the old default out keeps parsing.
|
|
217
232
|
*/
|
|
218
233
|
rotate: z.boolean().default(false),
|
|
219
234
|
/**
|
|
@@ -356,13 +371,38 @@ const configSchema = z
|
|
|
356
371
|
})
|
|
357
372
|
}
|
|
358
373
|
|
|
359
|
-
if (config.rotate
|
|
374
|
+
if (config.rotate) {
|
|
360
375
|
ctx.addIssue({
|
|
361
376
|
code: z.ZodIssueCode.custom,
|
|
362
377
|
path: ['rotate'],
|
|
363
378
|
message:
|
|
364
|
-
'rotate: true
|
|
365
|
-
'
|
|
379
|
+
'rotate: true is no longer read. An apply does not rotate a service token: run ' +
|
|
380
|
+
'`zbc run <env> <instance> rotate --yes`, which stores the new secret under ' +
|
|
381
|
+
'serviceTokenSecret, and remove this key.',
|
|
382
|
+
})
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (config.serviceTokenName !== undefined && config.serviceTokenSecret === undefined) {
|
|
386
|
+
ctx.addIssue({
|
|
387
|
+
code: z.ZodIssueCode.custom,
|
|
388
|
+
path: ['serviceTokenSecret'],
|
|
389
|
+
message:
|
|
390
|
+
'serviceTokenName needs serviceTokenSecret: the key in secrets.yaml that holds this ' +
|
|
391
|
+
"token's client secret. For a token that already exists, name the key the secret is " +
|
|
392
|
+
'under (or put it there); if nobody holds the secret, name a key and run ' +
|
|
393
|
+
'`zbc run <env> <instance> rotate --yes`. For a new token, name a key and run ' +
|
|
394
|
+
'`zbc run <env> <instance> mint` before the first apply.',
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (config.serviceTokenSecret !== undefined && config.serviceTokenName === undefined) {
|
|
399
|
+
ctx.addIssue({
|
|
400
|
+
code: z.ZodIssueCode.custom,
|
|
401
|
+
path: ['serviceTokenSecret'],
|
|
402
|
+
message:
|
|
403
|
+
'serviceTokenSecret names where a minted token keeps its secret, and this instance ' +
|
|
404
|
+
'mints none: set serviceTokenName, or remove the key. A token reached through ' +
|
|
405
|
+
'serviceTokens keeps its secret where it is minted.',
|
|
366
406
|
})
|
|
367
407
|
}
|
|
368
408
|
})
|
|
@@ -949,20 +989,59 @@ interface ServiceToken {
|
|
|
949
989
|
client_secret?: string
|
|
950
990
|
}
|
|
951
991
|
|
|
992
|
+
/** The token this instance owns, looked up by name. */
|
|
993
|
+
async function findServiceToken(
|
|
994
|
+
token: string,
|
|
995
|
+
account: string,
|
|
996
|
+
name: string,
|
|
997
|
+
): Promise<ServiceToken | undefined> {
|
|
998
|
+
const tokens = await cf<ServiceToken[]>(token, 'GET', `${account}/access/service_tokens`)
|
|
999
|
+
return tokens.find((t) => t.name === name)
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
/** What an action needs from the config, checked once and said plainly. */
|
|
1003
|
+
function mintedToken(config: { serviceTokenName?: string; serviceTokenSecret?: string }): {
|
|
1004
|
+
name: string
|
|
1005
|
+
secretKey: string
|
|
1006
|
+
} {
|
|
1007
|
+
if (config.serviceTokenName === undefined || config.serviceTokenSecret === undefined) {
|
|
1008
|
+
throw new Error(
|
|
1009
|
+
'this instance mints no service token: it declares no serviceTokenName. ' +
|
|
1010
|
+
'A token reached through serviceTokens is minted and rotated where it is declared.',
|
|
1011
|
+
)
|
|
1012
|
+
}
|
|
1013
|
+
return { name: config.serviceTokenName, secretKey: config.serviceTokenSecret }
|
|
1014
|
+
}
|
|
1015
|
+
|
|
952
1016
|
/**
|
|
953
|
-
*
|
|
1017
|
+
* Store a secret Cloudflare has just returned and will not return again.
|
|
954
1018
|
*
|
|
955
|
-
*
|
|
956
|
-
*
|
|
957
|
-
*
|
|
958
|
-
* the secret was minted, never shown, and unrecoverable except by rotating.
|
|
959
|
-
* Anything that can fail between minting a write-once value and showing it is a
|
|
960
|
-
* chance to lose it, so nothing goes between.
|
|
1019
|
+
* Nothing goes between the call that returned it and this. If the write fails
|
|
1020
|
+
* the secret is gone, and the error has to say what that means and what to
|
|
1021
|
+
* run, because "sops set failed" alone leaves a live token nobody can use.
|
|
961
1022
|
*/
|
|
962
|
-
function
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1023
|
+
async function storeShownOnce(
|
|
1024
|
+
ctx: ApplyContext,
|
|
1025
|
+
secretKey: string,
|
|
1026
|
+
secret: string,
|
|
1027
|
+
tokenName: string,
|
|
1028
|
+
): Promise<void> {
|
|
1029
|
+
if (!secret) {
|
|
1030
|
+
throw new Error(
|
|
1031
|
+
`Cloudflare returned no client secret for service token "${tokenName}". Nothing was stored. ` +
|
|
1032
|
+
'Run the rotate action to get one.',
|
|
1033
|
+
)
|
|
1034
|
+
}
|
|
1035
|
+
try {
|
|
1036
|
+
await ctx.storeSecret(secretKey, secret)
|
|
1037
|
+
} catch (err) {
|
|
1038
|
+
throw new Error(
|
|
1039
|
+
`Service token "${tokenName}" has a new secret and storing it under ${secretKey} failed: ` +
|
|
1040
|
+
`${(err as Error).message}\n Cloudflare will not show that secret again. Fix what stopped ` +
|
|
1041
|
+
'the write, then run the rotate action (with --yes) to mint one that can be stored.',
|
|
1042
|
+
{ cause: err },
|
|
1043
|
+
)
|
|
1044
|
+
}
|
|
966
1045
|
}
|
|
967
1046
|
|
|
968
1047
|
export const cloudflareAccessModule = defineModule({
|
|
@@ -998,9 +1077,10 @@ export const cloudflareAccessModule = defineModule({
|
|
|
998
1077
|
serviceTokenId: z.string(),
|
|
999
1078
|
/** Safe to output — the id is not a secret. */
|
|
1000
1079
|
clientId: z.string(),
|
|
1001
|
-
/**
|
|
1002
|
-
|
|
1003
|
-
|
|
1080
|
+
/**
|
|
1081
|
+
* Always false: an apply creates no service token (the `mint` action does).
|
|
1082
|
+
* Kept so an importer that reads it keeps resolving.
|
|
1083
|
+
*/
|
|
1004
1084
|
created: z.boolean(),
|
|
1005
1085
|
/** Whether the application was created by this apply. */
|
|
1006
1086
|
appCreated: z.boolean(),
|
|
@@ -1013,6 +1093,15 @@ export const cloudflareAccessModule = defineModule({
|
|
|
1013
1093
|
const account = `/accounts/${config.accountId}`
|
|
1014
1094
|
const domain = normalizeDomain(config.domain)
|
|
1015
1095
|
|
|
1096
|
+
// The secret the minted token's holders use. Not needed to converge
|
|
1097
|
+
// anything here; required so that a token whose secret nobody stored is
|
|
1098
|
+
// found on an apply and not on the day a caller needs it.
|
|
1099
|
+
if (config.serviceTokenSecret !== undefined) {
|
|
1100
|
+
ctx.secret(config.serviceTokenSecret, {
|
|
1101
|
+
field: `serviceTokenSecret (the client secret of "${config.serviceTokenName}"; the mint and rotate actions store it)`,
|
|
1102
|
+
})
|
|
1103
|
+
}
|
|
1104
|
+
|
|
1016
1105
|
// Resolved before anything is called, so a service token instance that is
|
|
1017
1106
|
// not imported fails while nothing has been touched.
|
|
1018
1107
|
const referencedTokenIds = config.serviceTokens.map((ref, index) =>
|
|
@@ -1240,43 +1329,21 @@ export const cloudflareAccessModule = defineModule({
|
|
|
1240
1329
|
)
|
|
1241
1330
|
}
|
|
1242
1331
|
|
|
1243
|
-
// 4. The service token this module owns, if one is declared.
|
|
1244
|
-
//
|
|
1245
|
-
//
|
|
1246
|
-
// `announce` exist was a 403 on creating the app, which — with the mint
|
|
1247
|
-
// first — burned a write-once secret for an application that was never
|
|
1248
|
-
// created. Minting after means the same 403 costs nothing, and the
|
|
1249
|
-
// policy below is the only thing that needs the id.
|
|
1332
|
+
// 4. The service token this module owns, if one is declared. Found, never
|
|
1333
|
+
// made: an apply that created it would hold a secret it may not store
|
|
1334
|
+
// (ADR-0023) and must not print.
|
|
1250
1335
|
let mintedTokenId = ''
|
|
1251
1336
|
let clientId = ''
|
|
1252
|
-
let clientSecret = ''
|
|
1253
|
-
let tokenCreated = false
|
|
1254
|
-
let rotated = false
|
|
1255
1337
|
if (config.serviceTokenName !== undefined) {
|
|
1256
|
-
const
|
|
1257
|
-
let svc = tokens.find((t) => t.name === config.serviceTokenName)
|
|
1338
|
+
const svc = await findServiceToken(token, account, config.serviceTokenName)
|
|
1258
1339
|
if (!svc) {
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
clientSecret = svc.client_secret ?? ''
|
|
1264
|
-
tokenCreated = true
|
|
1265
|
-
console.log(` Created service token "${config.serviceTokenName}" (${svc.id})`)
|
|
1266
|
-
announce(svc.client_id, clientSecret)
|
|
1267
|
-
} else if (config.rotate) {
|
|
1268
|
-
const fresh = await cf<ServiceToken>(
|
|
1269
|
-
token,
|
|
1270
|
-
'POST',
|
|
1271
|
-
`${account}/access/service_tokens/${svc.id}/rotate`,
|
|
1340
|
+
throw new Error(
|
|
1341
|
+
`Service token "${config.serviceTokenName}" does not exist yet. An apply does not create it, ` +
|
|
1342
|
+
'because its secret is shown once and only an action may store it: run ' +
|
|
1343
|
+
'`zbc run <env> <this instance> mint`, commit secrets.yaml, and apply again.',
|
|
1272
1344
|
)
|
|
1273
|
-
clientSecret = fresh.client_secret ?? ''
|
|
1274
|
-
rotated = true
|
|
1275
|
-
console.log(` ROTATED service token "${config.serviceTokenName}" — the old secret is dead`)
|
|
1276
|
-
announce(svc.client_id, clientSecret)
|
|
1277
|
-
} else {
|
|
1278
|
-
console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists, not rotated`)
|
|
1279
1345
|
}
|
|
1346
|
+
console.log(` Service token "${config.serviceTokenName}" (${svc.id}) exists`)
|
|
1280
1347
|
mintedTokenId = svc.id
|
|
1281
1348
|
clientId = svc.client_id
|
|
1282
1349
|
}
|
|
@@ -1429,19 +1496,63 @@ export const cloudflareAccessModule = defineModule({
|
|
|
1429
1496
|
serviceTokenIds,
|
|
1430
1497
|
serviceTokenId: mintedTokenId,
|
|
1431
1498
|
clientId,
|
|
1432
|
-
|
|
1433
|
-
created: tokenCreated,
|
|
1499
|
+
created: false,
|
|
1434
1500
|
appCreated: found === undefined,
|
|
1435
1501
|
// What is still undeclared AFTER this apply, not what was before it.
|
|
1436
1502
|
undeclared: remaining.map((policy) => `${policy.name} (${policy.decision})`),
|
|
1437
|
-
changed:
|
|
1438
|
-
appChanged ||
|
|
1439
|
-
rewrote ||
|
|
1440
|
-
deleted > 0 ||
|
|
1441
|
-
orgRenamed ||
|
|
1442
|
-
idpsCreated > 0 ||
|
|
1443
|
-
tokenCreated ||
|
|
1444
|
-
rotated,
|
|
1503
|
+
changed: appChanged || rewrote || deleted > 0 || orgRenamed || idpsCreated > 0,
|
|
1445
1504
|
}
|
|
1446
1505
|
},
|
|
1506
|
+
actions: {
|
|
1507
|
+
mint: {
|
|
1508
|
+
description:
|
|
1509
|
+
'Create the service token named by serviceTokenName and store its client secret under serviceTokenSecret',
|
|
1510
|
+
async run(config, ctx) {
|
|
1511
|
+
const { name, secretKey } = mintedToken(config)
|
|
1512
|
+
const token = resolveAccessToken(config.apiToken, ctx)
|
|
1513
|
+
const account = `/accounts/${config.accountId}`
|
|
1514
|
+
const existing = await findServiceToken(token, account, name)
|
|
1515
|
+
if (existing) {
|
|
1516
|
+
throw new Error(
|
|
1517
|
+
`Service token "${name}" (${existing.id}) already exists, and Cloudflare does not show an ` +
|
|
1518
|
+
`existing token's secret. If you hold it, put it in secrets.yaml under ${secretKey}. ` +
|
|
1519
|
+
'If nobody does, run the rotate action (with --yes): the old secret stops working at once.',
|
|
1520
|
+
)
|
|
1521
|
+
}
|
|
1522
|
+
const svc = await cf<ServiceToken>(token, 'POST', `${account}/access/service_tokens`, {
|
|
1523
|
+
name,
|
|
1524
|
+
duration: '8760h', // one year; Cloudflare's max, and expiry here is an outage
|
|
1525
|
+
})
|
|
1526
|
+
await storeShownOnce(ctx, secretKey, svc.client_secret ?? '', name)
|
|
1527
|
+
console.log(` Created service token "${name}" (${svc.id}), client id ${svc.client_id}`)
|
|
1528
|
+
console.log(` Its secret is under ${secretKey}. Apply this instance to admit the token.`)
|
|
1529
|
+
},
|
|
1530
|
+
},
|
|
1531
|
+
rotate: {
|
|
1532
|
+
description:
|
|
1533
|
+
"Replace the service token's client secret and store the new one; the old secret stops working at once",
|
|
1534
|
+
irreversible: true,
|
|
1535
|
+
async run(config, ctx) {
|
|
1536
|
+
const { name, secretKey } = mintedToken(config)
|
|
1537
|
+
const token = resolveAccessToken(config.apiToken, ctx)
|
|
1538
|
+
const account = `/accounts/${config.accountId}`
|
|
1539
|
+
const svc = await findServiceToken(token, account, name)
|
|
1540
|
+
if (!svc) {
|
|
1541
|
+
throw new Error(
|
|
1542
|
+
`Service token "${name}" does not exist, so there is nothing to rotate. Run the mint action.`,
|
|
1543
|
+
)
|
|
1544
|
+
}
|
|
1545
|
+
const fresh = await cf<ServiceToken>(
|
|
1546
|
+
token,
|
|
1547
|
+
'POST',
|
|
1548
|
+
`${account}/access/service_tokens/${svc.id}/rotate`,
|
|
1549
|
+
)
|
|
1550
|
+
await storeShownOnce(ctx, secretKey, fresh.client_secret ?? '', name)
|
|
1551
|
+
console.log(` ROTATED service token "${name}" (${svc.id}): the old secret is dead`)
|
|
1552
|
+
console.log(
|
|
1553
|
+
` The new one is under ${secretKey}. Whatever holds the old secret needs it now.`,
|
|
1554
|
+
)
|
|
1555
|
+
},
|
|
1556
|
+
},
|
|
1557
|
+
},
|
|
1447
1558
|
})
|
|
@@ -7,5 +7,5 @@
|
|
|
7
7
|
"zod": "^3.24.0"
|
|
8
8
|
},
|
|
9
9
|
"secrets": [],
|
|
10
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Access: Apps and Policies write on the account, plus Access: Service Tokens write if `serviceTokenName` is declared and Access: Organizations / Identity Providers for the organisation-level fields. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. THREE FIELDS ARE ORGANISATION-LEVEL, not per-application — `teamDomain`, `orgName` and `identityProviders` converge the Zero Trust organisation shared by every Access application in the account; undeclared identity providers are reported and never removed, and declaring none converges none. `emails: []` plus `serviceTokenName` is the machine-only shape (say `sessionDuration: '0s'`, so no cookie is ever issued); `emails: [...]` plus `identityProviders: ['onetimepin']` is the human shape. A minted service token's secret is returned exactly once, on the apply that creates it — put it somewhere a caller can read it, not in the declaration. `bypass: true` with no emails or tokens is the third shape: Cloudflare's Bypass for everyone on a narrow path (`host/prefix/*`) under a gated host, for a path whose Worker authenticates every request itself. For an application nested under another on the same host, `pathCookieAttribute: true` keeps the two sessions apart; `sameSiteCookieAttribute: 'lax'` is written only when declared. The credential is `apiToken: { from, output }` (an imported `cloudflare-token`), or `apiToken: { secret: 'CLOUDFLARE_API_TOKEN' }` to use the environment's deploy credential."
|
|
10
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; needs a token with Access: Apps and Policies write on the account, plus Access: Service Tokens write if `serviceTokenName` is declared (then `serviceTokenSecret` is required too: the secrets.yaml key the token's client secret is kept under. The token is created by `zbc run <env> <instance> mint`, which stores the secret there, and replaced by `zbc run <env> <instance> rotate --yes`; an apply neither creates nor rotates it and prints no secret) and Access: Organizations / Identity Providers for the organisation-level fields. Declare it beside the tunnel that exposes the hostname: a hostname on the internet with no policy in front of it is an open door, which is the failure this module exists to make hard to reach. THREE FIELDS ARE ORGANISATION-LEVEL, not per-application — `teamDomain`, `orgName` and `identityProviders` converge the Zero Trust organisation shared by every Access application in the account; undeclared identity providers are reported and never removed, and declaring none converges none. `emails: []` plus `serviceTokenName` is the machine-only shape (say `sessionDuration: '0s'`, so no cookie is ever issued); `emails: [...]` plus `identityProviders: ['onetimepin']` is the human shape. A minted service token's secret is returned exactly once, on the apply that creates it — put it somewhere a caller can read it, not in the declaration. `bypass: true` with no emails or tokens is the third shape: Cloudflare's Bypass for everyone on a narrow path (`host/prefix/*`) under a gated host, for a path whose Worker authenticates every request itself. For an application nested under another on the same host, `pathCookieAttribute: true` keeps the two sessions apart; `sameSiteCookieAttribute: 'lax'` is written only when declared. The credential is `apiToken: { from, output }` (an imported `cloudflare-token`), or `apiToken: { secret: 'CLOUDFLARE_API_TOKEN' }` to use the environment's deploy credential."
|
|
11
11
|
}
|
|
@@ -24,7 +24,9 @@
|
|
|
24
24
|
// is `CfOptions.hints`. `c9s/src/cf.ts` is a fifth copy and stays: it lives in
|
|
25
25
|
// a separate package and cannot import a template.
|
|
26
26
|
|
|
27
|
+
import { z } from 'zod'
|
|
27
28
|
import { resolveOutput } from '../../src/context'
|
|
29
|
+
import type { ApplyContext } from '../../src/types'
|
|
28
30
|
|
|
29
31
|
export const API = 'https://api.cloudflare.com/client/v4'
|
|
30
32
|
|
|
@@ -290,3 +292,57 @@ export function resolveRef(
|
|
|
290
292
|
): string {
|
|
291
293
|
return resolveOutput(ref, imports, field)
|
|
292
294
|
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Where a Cloudflare module's API token comes from, when it is not
|
|
298
|
+
* `CLOUDFLARE_API_TOKEN` in this environment's secrets.yaml.
|
|
299
|
+
*
|
|
300
|
+
* `{ from, output }` is an imported instance's output: a `cloudflare-token`
|
|
301
|
+
* mints a token scoped to one job and nothing keeps a copy at rest. `{ secret }`
|
|
302
|
+
* is another key of secrets.yaml: an environment that reaches two accounts
|
|
303
|
+
* holds two tokens, and one name cannot be both.
|
|
304
|
+
*
|
|
305
|
+
* Three consumers kept forks of `r2` and `cloudflare-email` for this field
|
|
306
|
+
* alone: their environment holds a root token that can only mint, so a module
|
|
307
|
+
* that reads `CLOUDFLARE_API_TOKEN` and nothing else has no token to read.
|
|
308
|
+
*/
|
|
309
|
+
export const apiTokenSchema = z.union([
|
|
310
|
+
z.object({ from: z.string(), output: z.string() }),
|
|
311
|
+
z.object({ secret: z.string() }),
|
|
312
|
+
])
|
|
313
|
+
export type ApiTokenSource = z.infer<typeof apiTokenSchema>
|
|
314
|
+
|
|
315
|
+
/**
|
|
316
|
+
* The token a module's calls use. One function so a module's apply, destroy
|
|
317
|
+
* and readiness probe cannot disagree about it.
|
|
318
|
+
*/
|
|
319
|
+
export function apiTokenFor(
|
|
320
|
+
source: ApiTokenSource | undefined,
|
|
321
|
+
ctx: Pick<ApplyContext, 'secret' | 'output'>,
|
|
322
|
+
): string {
|
|
323
|
+
if (!source) return ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
324
|
+
return 'secret' in source
|
|
325
|
+
? ctx.secret(source.secret, { field: 'apiToken' })
|
|
326
|
+
: ctx.output(source, 'apiToken')
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* The 10000 hint for a module, naming the token that was actually refused.
|
|
331
|
+
*
|
|
332
|
+
* A hint that says `CLOUDFLARE_API_TOKEN` about a token an import supplied
|
|
333
|
+
* sends the reader to edit a token the call never used. `needs` is the module's
|
|
334
|
+
* own part, written to follow "is likely missing".
|
|
335
|
+
*/
|
|
336
|
+
export function tokenScopeHint(source: ApiTokenSource | undefined, needs: string): string {
|
|
337
|
+
const refused = 'rejected the token (10000 Authentication error). '
|
|
338
|
+
const edit =
|
|
339
|
+
'Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.'
|
|
340
|
+
if (!source) return `${refused}CLOUDFLARE_API_TOKEN is likely missing ${needs}. ${edit}`
|
|
341
|
+
if ('secret' in source) {
|
|
342
|
+
return `${refused}${source.secret} (this instance's apiToken) is likely missing ${needs}. ${edit}`
|
|
343
|
+
}
|
|
344
|
+
return (
|
|
345
|
+
`${refused}The token this instance takes from \`${source.from}\` (its \`${source.output}\` output) ` +
|
|
346
|
+
`is likely missing ${needs}. Grant it where that instance mints the token, and re-run zbc apply.`
|
|
347
|
+
)
|
|
348
|
+
}
|
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
3
|
import type { ApplyContext } from '../../src/types'
|
|
4
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type ApiTokenSource,
|
|
6
|
+
apiTokenFor,
|
|
7
|
+
apiTokenSchema,
|
|
8
|
+
CfError,
|
|
9
|
+
cf,
|
|
10
|
+
type CfOptions,
|
|
11
|
+
tokenScopeHint,
|
|
12
|
+
} from '../cloudflare-api'
|
|
5
13
|
|
|
6
14
|
/**
|
|
7
15
|
* cloudflare-email — provisions Cloudflare Email Service (public beta) for a
|
|
@@ -34,20 +42,20 @@ import { CfError, cf, type CfOptions } from '../cloudflare-api'
|
|
|
34
42
|
* exists. Everything else about the envelope (the base URL, the error shapes,
|
|
35
43
|
* the non-JSON guard, the typed throw) is `../cloudflare-api`'s.
|
|
36
44
|
*/
|
|
37
|
-
const
|
|
45
|
+
const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
|
|
38
46
|
hints: {
|
|
39
|
-
10000:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
10000: tokenScopeHint(
|
|
48
|
+
source,
|
|
49
|
+
'a scope — it needs: ' +
|
|
50
|
+
'Zone → Email Routing Rules: Edit, Zone → Zone Settings: Edit (the routing ' +
|
|
51
|
+
'enable/settings/DNS endpoints live under generic Zone Settings), Zone → DNS: Edit, ' +
|
|
52
|
+
'Account → Email Sending: Edit, Account → Email Routing Addresses: Edit',
|
|
53
|
+
),
|
|
46
54
|
10105:
|
|
47
55
|
`failed: the account is not entitled to Email Sending (10105). ` +
|
|
48
56
|
`Email Sending requires a Workers Paid plan — upgrade the account, then re-run zbc apply.`,
|
|
49
57
|
},
|
|
50
|
-
}
|
|
58
|
+
})
|
|
51
59
|
|
|
52
60
|
/**
|
|
53
61
|
* A worker name: either a literal script name, or a `{ from, output }`
|
|
@@ -135,6 +143,7 @@ async function ensureDestinationVerified(
|
|
|
135
143
|
token: string,
|
|
136
144
|
accountId: string,
|
|
137
145
|
email: string,
|
|
146
|
+
OPTS: CfOptions,
|
|
138
147
|
): Promise<void> {
|
|
139
148
|
const addresses = await cf<Array<{ email: string; verified?: string | null }>>(
|
|
140
149
|
token,
|
|
@@ -211,13 +220,27 @@ export function classifySendingDns(readings: SendingDnsReading[]): SendingDnsVer
|
|
|
211
220
|
}
|
|
212
221
|
}
|
|
213
222
|
|
|
223
|
+
/** The zone id: the literal, or the imported instance's output a reference names. */
|
|
224
|
+
function zoneIdFor(
|
|
225
|
+
zoneId: string | { from: string; output: string },
|
|
226
|
+
ctx: Pick<ApplyContext, 'output'>,
|
|
227
|
+
): string {
|
|
228
|
+
return typeof zoneId === 'string' ? zoneId : ctx.output(zoneId, 'zoneId')
|
|
229
|
+
}
|
|
230
|
+
|
|
214
231
|
export const cloudflareEmailModule = defineModule({
|
|
215
232
|
name: 'cloudflare-email',
|
|
216
233
|
configSchema: z.object({
|
|
217
234
|
/** Cloudflare account id (dashboard URL — not a secret). */
|
|
218
235
|
accountId: z.string(),
|
|
219
|
-
/**
|
|
220
|
-
|
|
236
|
+
/** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
|
|
237
|
+
apiToken: apiTokenSchema.optional(),
|
|
238
|
+
/**
|
|
239
|
+
* Zone id of the apex zone (e.g. cedarpad.com's zone): the id itself, or
|
|
240
|
+
* `{ from, output }` into an imported `cloudflare-zone` instance's `zoneId`,
|
|
241
|
+
* so a zone this environment creates is not pasted back in by hand.
|
|
242
|
+
*/
|
|
243
|
+
zoneId: z.union([z.string(), z.object({ from: z.string(), output: z.string() })]),
|
|
221
244
|
/** Email domain — the zone apex or a subdomain of it (e.g. mail.cedarpad.com). */
|
|
222
245
|
domain: z.string(),
|
|
223
246
|
/** Onboard the domain for outbound sending (SPF/DKIM/DMARC/bounce-MX). */
|
|
@@ -240,9 +263,11 @@ export const cloudflareEmailModule = defineModule({
|
|
|
240
263
|
domain: z.string(),
|
|
241
264
|
}),
|
|
242
265
|
async apply(config, ctx) {
|
|
243
|
-
const token = ctx
|
|
266
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
267
|
+
const OPTS = optsFor(config.apiToken)
|
|
244
268
|
|
|
245
|
-
const { accountId,
|
|
269
|
+
const { accountId, domain } = config
|
|
270
|
+
const zoneId = zoneIdFor(config.zoneId, ctx)
|
|
246
271
|
const dnsStatus: Record<string, string> = {}
|
|
247
272
|
let sendingEnabled = false
|
|
248
273
|
let routingEnabled = false
|
|
@@ -378,7 +403,7 @@ export const cloudflareEmailModule = defineModule({
|
|
|
378
403
|
forwardTargets.add(config.catchAll.destination)
|
|
379
404
|
}
|
|
380
405
|
for (const dest of forwardTargets) {
|
|
381
|
-
await ensureDestinationVerified(token, accountId, dest)
|
|
406
|
+
await ensureDestinationVerified(token, accountId, dest, OPTS)
|
|
382
407
|
}
|
|
383
408
|
|
|
384
409
|
// Upsert literal rules for each address.
|
|
@@ -450,8 +475,10 @@ export const cloudflareEmailModule = defineModule({
|
|
|
450
475
|
}
|
|
451
476
|
},
|
|
452
477
|
async destroy(config, ctx) {
|
|
453
|
-
const token = ctx
|
|
454
|
-
const
|
|
478
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
479
|
+
const OPTS = optsFor(config.apiToken)
|
|
480
|
+
const { domain } = config
|
|
481
|
+
const zoneId = zoneIdFor(config.zoneId, ctx)
|
|
455
482
|
|
|
456
483
|
console.log(` ⚠ DESTROYING email config for ${domain} — mail for this domain WILL STOP.`)
|
|
457
484
|
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
10
10
|
"signupUrl": "https://dash.cloudflare.com",
|
|
11
11
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
12
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run."
|
|
12
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`. Set `apiToken` to take the token from elsewhere: `{ from, output }` for an imported instance's output (a `cloudflare-token`'s `tokenValue`), or `{ secret }` for another key of secrets.yaml. `zoneId` is the id itself or `{ from, output }` into an imported `cloudflare-zone` instance's `zoneId`. Reuses CLOUDFLARE_API_TOKEN from secrets.yaml, but the token needs extra scopes: Zone > Email Routing Rules: Edit, Zone > Zone Settings: Edit (the routing enable/settings/DNS endpoints require it), Zone > DNS: Edit, Account > Email Sending: Edit, and Account > Email Routing Addresses: Edit. Email Sending requires a Workers Paid plan (API error 10105 = not entitled). Caveats: the service is in public beta with unpublished rate limits (pilot before high-volume use); outbound messages are capped at 5 MiB total; onboarding adds an SPF record, so if the domain already has one you must merge them manually (two SPF records break SPF); 'forward' destinations require a manual email-click verification — apply sends the verification email, then fails with instructions until you click it and re-run."
|
|
13
13
|
}
|