@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
|
@@ -4,8 +4,16 @@ import * as os from 'node:os'
|
|
|
4
4
|
import * as path from 'node:path'
|
|
5
5
|
import { z } from 'zod'
|
|
6
6
|
import { defineModule } from '../../src/define-module'
|
|
7
|
-
import
|
|
8
|
-
|
|
7
|
+
import {
|
|
8
|
+
type ApiTokenSource,
|
|
9
|
+
apiTokenFor,
|
|
10
|
+
apiTokenSchema,
|
|
11
|
+
CfError,
|
|
12
|
+
type CfOptions,
|
|
13
|
+
cf,
|
|
14
|
+
cfRaw,
|
|
15
|
+
tokenScopeHint,
|
|
16
|
+
} from '../cloudflare-api'
|
|
9
17
|
|
|
10
18
|
/**
|
|
11
19
|
* d1 — provisions a Cloudflare D1 database via the REST API (r2-style:
|
|
@@ -33,14 +41,9 @@ import { CfError, type CfOptions, cf, cfRaw } from '../cloudflare-api'
|
|
|
33
41
|
*/
|
|
34
42
|
|
|
35
43
|
/** Named per-code guidance for this module's calls — see `../cloudflare-api`. */
|
|
36
|
-
const
|
|
37
|
-
hints: {
|
|
38
|
-
|
|
39
|
-
`rejected the token (10000 Authentication error). ` +
|
|
40
|
-
`CLOUDFLARE_API_TOKEN is likely missing the Account → D1: Edit scope. ` +
|
|
41
|
-
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
42
|
-
},
|
|
43
|
-
}
|
|
44
|
+
const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
|
|
45
|
+
hints: { 10000: tokenScopeHint(source, 'the Account → D1: Edit scope') },
|
|
46
|
+
})
|
|
44
47
|
|
|
45
48
|
interface D1Database {
|
|
46
49
|
uuid: string
|
|
@@ -56,7 +59,11 @@ interface D1Database {
|
|
|
56
59
|
* not show it, and apply creates a second one under a name that is already
|
|
57
60
|
* taken.
|
|
58
61
|
*/
|
|
59
|
-
async function listDatabases(
|
|
62
|
+
async function listDatabases(
|
|
63
|
+
token: string,
|
|
64
|
+
accountId: string,
|
|
65
|
+
OPTS: CfOptions,
|
|
66
|
+
): Promise<D1Database[]> {
|
|
60
67
|
const all: D1Database[] = []
|
|
61
68
|
// Bounded: `total_pages` is the provider's number, and a loop whose only exit
|
|
62
69
|
// is the provider agreeing to stop hangs rather than failing when it does not.
|
|
@@ -101,6 +108,7 @@ async function query(
|
|
|
101
108
|
accountId: string,
|
|
102
109
|
databaseId: string,
|
|
103
110
|
sql: string,
|
|
111
|
+
OPTS: CfOptions,
|
|
104
112
|
): Promise<void> {
|
|
105
113
|
const results = await cf<D1StatementResult[] | null>(
|
|
106
114
|
token,
|
|
@@ -202,20 +210,6 @@ function applyMigrations(opts: {
|
|
|
202
210
|
}
|
|
203
211
|
}
|
|
204
212
|
|
|
205
|
-
/**
|
|
206
|
-
* The credential every call below uses: an imported instance's output when
|
|
207
|
-
* `apiToken` is set, else CLOUDFLARE_API_TOKEN from secrets.yaml. One helper
|
|
208
|
-
* so apply, destroy and the readiness probe can never disagree on it.
|
|
209
|
-
*/
|
|
210
|
-
function apiTokenFor(
|
|
211
|
-
config: { apiToken?: { from: string; output: string } },
|
|
212
|
-
ctx: ApplyContext,
|
|
213
|
-
): string {
|
|
214
|
-
return config.apiToken
|
|
215
|
-
? ctx.output(config.apiToken, 'apiToken')
|
|
216
|
-
: ctx.secret('CLOUDFLARE_API_TOKEN')
|
|
217
|
-
}
|
|
218
|
-
|
|
219
213
|
export const d1Module = defineModule({
|
|
220
214
|
name: 'd1',
|
|
221
215
|
configSchema: z.object({
|
|
@@ -226,9 +220,10 @@ export const d1Module = defineModule({
|
|
|
226
220
|
* this environment's secrets.yaml. Set `{ from, output }` to pull it from
|
|
227
221
|
* an imported instance's outputs instead — e.g. a minted `cloudflare-token`
|
|
228
222
|
* whose permissions include D1 Read and D1 Write — so it never sits at
|
|
229
|
-
* rest. Mirrors the `cloudflare` module's `apiToken`.
|
|
223
|
+
* rest. Mirrors the `cloudflare` module's `apiToken`. `{ secret }` reads
|
|
224
|
+
* another key of secrets.yaml instead.
|
|
230
225
|
*/
|
|
231
|
-
apiToken:
|
|
226
|
+
apiToken: apiTokenSchema.optional(),
|
|
232
227
|
/** Database name — account-scoped, so namespace it per project/env. */
|
|
233
228
|
databaseName: z.string(),
|
|
234
229
|
/**
|
|
@@ -280,7 +275,8 @@ export const d1Module = defineModule({
|
|
|
280
275
|
databaseId: z.string(),
|
|
281
276
|
}),
|
|
282
277
|
async apply(config, ctx) {
|
|
283
|
-
const apiToken = apiTokenFor(config, ctx)
|
|
278
|
+
const apiToken = apiTokenFor(config.apiToken, ctx)
|
|
279
|
+
const OPTS = optsFor(config.apiToken)
|
|
284
280
|
const { accountId, databaseName } = config
|
|
285
281
|
|
|
286
282
|
// Checked before anything is called: a typo'd folder must not leave a
|
|
@@ -294,7 +290,9 @@ export const d1Module = defineModule({
|
|
|
294
290
|
)
|
|
295
291
|
}
|
|
296
292
|
|
|
297
|
-
const existing = (await listDatabases(apiToken, accountId)).find(
|
|
293
|
+
const existing = (await listDatabases(apiToken, accountId, OPTS)).find(
|
|
294
|
+
(d) => d.name === databaseName,
|
|
295
|
+
)
|
|
298
296
|
|
|
299
297
|
let databaseId: string
|
|
300
298
|
if (existing) {
|
|
@@ -341,7 +339,7 @@ export const d1Module = defineModule({
|
|
|
341
339
|
}
|
|
342
340
|
|
|
343
341
|
for (const statement of config.statements) {
|
|
344
|
-
await query(apiToken, accountId, databaseId, statement)
|
|
342
|
+
await query(apiToken, accountId, databaseId, statement, OPTS)
|
|
345
343
|
}
|
|
346
344
|
if (config.statements.length > 0) {
|
|
347
345
|
console.log(` Applied ${config.statements.length} statement(s)`)
|
|
@@ -350,7 +348,7 @@ export const d1Module = defineModule({
|
|
|
350
348
|
for (const { table, column, definition } of config.additiveColumns) {
|
|
351
349
|
const sql = `ALTER TABLE ${table} ADD COLUMN ${column} ${definition}`
|
|
352
350
|
try {
|
|
353
|
-
await query(apiToken, accountId, databaseId, sql)
|
|
351
|
+
await query(apiToken, accountId, databaseId, sql, OPTS)
|
|
354
352
|
console.log(` Added column ${table}.${column}`)
|
|
355
353
|
} catch (err) {
|
|
356
354
|
if (!isDuplicateColumn(err)) throw err
|
|
@@ -366,13 +364,16 @@ export const d1Module = defineModule({
|
|
|
366
364
|
* strand every instance behind it in a `zbc destroy`.
|
|
367
365
|
*/
|
|
368
366
|
async destroy(config, ctx) {
|
|
369
|
-
const apiToken = apiTokenFor(config, ctx)
|
|
367
|
+
const apiToken = apiTokenFor(config.apiToken, ctx)
|
|
368
|
+
const OPTS = optsFor(config.apiToken)
|
|
370
369
|
const { accountId, databaseName } = config
|
|
371
370
|
// The lookup is deliberately OUTSIDE the try: the forgiving case is
|
|
372
371
|
// "already gone", and that is the `!existing` branch. A listing that failed
|
|
373
372
|
// — a rejected token, a 5xx — proves nothing about whether the database is
|
|
374
373
|
// there, and reporting it as a skipped delete leaves the resource standing.
|
|
375
|
-
const existing = (await listDatabases(apiToken, accountId)).find(
|
|
374
|
+
const existing = (await listDatabases(apiToken, accountId, OPTS)).find(
|
|
375
|
+
(d) => d.name === databaseName,
|
|
376
|
+
)
|
|
376
377
|
if (!existing) {
|
|
377
378
|
console.log(` Database "${databaseName}" is already gone`)
|
|
378
379
|
return
|
|
@@ -401,8 +402,9 @@ export const d1Module = defineModule({
|
|
|
401
402
|
ready: {
|
|
402
403
|
proves: 'the database answers a query',
|
|
403
404
|
async probe(outputs, config, ctx) {
|
|
404
|
-
const apiToken = apiTokenFor(config, ctx)
|
|
405
|
-
|
|
405
|
+
const apiToken = apiTokenFor(config.apiToken, ctx)
|
|
406
|
+
const OPTS = optsFor(config.apiToken)
|
|
407
|
+
await query(apiToken, config.accountId, outputs.databaseId, 'SELECT 1', OPTS)
|
|
406
408
|
},
|
|
407
409
|
},
|
|
408
410
|
})
|
|
@@ -12,5 +12,5 @@
|
|
|
12
12
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
13
13
|
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
14
14
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
15
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }
|
|
15
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → D1: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/app-db.ts\n import { d1Module } from '../../modules/d1'\n export default d1Module.instance({\n name: 'app-db',\n config: {\n accountId: '<account id>',\n databaseName: 'myproject-production',\n statements: ['CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY)'],\n },\n })\n\nWire it into a Worker via the cloudflare module — the binding must ALREADY be declared in that package's wrangler.jsonc (placeholder database_id and all); zbc only supplies the id:\n\n imports: [appDb],\n config: { ..., bindings: [{ type: 'd1_databases', binding: 'DB', field: 'database_id', from: 'app-db', output: 'databaseId' }] }\n\nTo use a minted token instead of secrets.yaml (a `cloudflare-token` instance with 'D1 Read' and 'D1 Write'), import it and set `apiToken: { from: '<token instance>', output: 'tokenValue' }`. `apiToken: { secret: '<key>' }` reads another key of secrets.yaml.\n\n`statements` are replayed on every apply, so each must be idempotent (`CREATE TABLE IF NOT EXISTS`). Use `additiveColumns` for `ALTER TABLE … ADD COLUMN`, which SQLite cannot spell idempotently — an already-present column is treated as success.\n\nFor a versioned history (`0001_init.sql`, …) set `migrationsDir: 'packages/app/migrations'` (relative to the project root): it is applied with `wrangler d1 migrations apply --remote` and wrangler's own `d1_migrations` ledger on this instance's apply, before `statements`, so a Worker that imports this instance deploys only after its schema is there.\n\n`destroy` deletes the database. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
|
|
16
16
|
}
|
|
@@ -12,7 +12,9 @@ export const dockerComposeStackModule = defineModule({
|
|
|
12
12
|
dir: z.string(),
|
|
13
13
|
// empty = whole stack. Names are interpolated into the compose command —
|
|
14
14
|
// compose-legal characters only, so a stray space is a config error.
|
|
15
|
-
services: z
|
|
15
|
+
services: z
|
|
16
|
+
.array(z.string().regex(/^[A-Za-z0-9_.-]+$/, 'not a compose service name'))
|
|
17
|
+
.default([]),
|
|
16
18
|
}),
|
|
17
19
|
outputs: z.object({ dir: z.string(), running: z.number() }),
|
|
18
20
|
apply: async (config) => {
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
type ApiTokenSource,
|
|
5
|
+
apiTokenFor,
|
|
6
|
+
apiTokenSchema,
|
|
7
|
+
type CfOptions,
|
|
8
|
+
cf,
|
|
9
|
+
cfRaw,
|
|
10
|
+
tokenScopeHint,
|
|
11
|
+
} from '../cloudflare-api'
|
|
4
12
|
|
|
5
13
|
/**
|
|
6
14
|
* queue: a Cloudflare Queue and the Email Sending event subscriptions that fill
|
|
@@ -36,20 +44,15 @@ import { type CfOptions, cf, cfRaw } from '../cloudflare-api'
|
|
|
36
44
|
* source reads back as a different domain or zone is a hard error rather than
|
|
37
45
|
* an overwrite.
|
|
38
46
|
*
|
|
39
|
-
* Token scope: CLOUDFLARE_API_TOKEN needs Account → Queues: Edit. Creating an
|
|
47
|
+
* Token scope: CLOUDFLARE_API_TOKEN (or the token `apiToken` names) needs Account → Queues: Edit. Creating an
|
|
40
48
|
* event subscription may ask for more on some accounts; the refusal names the
|
|
41
49
|
* call that was refused.
|
|
42
50
|
*/
|
|
43
51
|
|
|
44
52
|
/** Named per-code guidance for this module's calls; see `../cloudflare-api`. */
|
|
45
|
-
const
|
|
46
|
-
hints: {
|
|
47
|
-
|
|
48
|
-
`rejected the token (10000 Authentication error). ` +
|
|
49
|
-
`CLOUDFLARE_API_TOKEN is likely missing the Account → Queues: Edit scope. ` +
|
|
50
|
-
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
51
|
-
},
|
|
52
|
-
}
|
|
53
|
+
const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
|
|
54
|
+
hints: { 10000: tokenScopeHint(source, 'the Account → Queues: Edit scope') },
|
|
55
|
+
})
|
|
53
56
|
|
|
54
57
|
export const subscriptionSchema = z.object({
|
|
55
58
|
/** The subscription's name, unique on the queue: this is how an apply finds the one it made. */
|
|
@@ -160,7 +163,7 @@ interface QueueRow {
|
|
|
160
163
|
* page. Bounded, so a provider that never says "last page" fails rather than
|
|
161
164
|
* hangs.
|
|
162
165
|
*/
|
|
163
|
-
async function listAll<T>(token: string, path: string): Promise<T[]> {
|
|
166
|
+
async function listAll<T>(token: string, path: string, OPTS: CfOptions): Promise<T[]> {
|
|
164
167
|
const all: T[] = []
|
|
165
168
|
const sep = path.includes('?') ? '&' : '?'
|
|
166
169
|
for (let page = 1; page <= 100; page++) {
|
|
@@ -182,8 +185,9 @@ async function findQueue(
|
|
|
182
185
|
token: string,
|
|
183
186
|
accountId: string,
|
|
184
187
|
queueName: string,
|
|
188
|
+
opts: CfOptions,
|
|
185
189
|
): Promise<QueueRow | undefined> {
|
|
186
|
-
const queues = await listAll<QueueRow>(token, `/accounts/${accountId}/queues
|
|
190
|
+
const queues = await listAll<QueueRow>(token, `/accounts/${accountId}/queues`, opts)
|
|
187
191
|
return queues.find((q) => q.queue_name === queueName)
|
|
188
192
|
}
|
|
189
193
|
|
|
@@ -191,10 +195,12 @@ function listSubscriptions(
|
|
|
191
195
|
token: string,
|
|
192
196
|
accountId: string,
|
|
193
197
|
queueId: string,
|
|
198
|
+
opts: CfOptions,
|
|
194
199
|
): Promise<ListedSubscription[]> {
|
|
195
200
|
return listAll<ListedSubscription>(
|
|
196
201
|
token,
|
|
197
202
|
`/accounts/${accountId}/event_subscriptions/subscriptions?queue_id=${encodeURIComponent(queueId)}`,
|
|
203
|
+
opts,
|
|
198
204
|
)
|
|
199
205
|
}
|
|
200
206
|
|
|
@@ -203,6 +209,8 @@ export const queueModule = defineModule({
|
|
|
203
209
|
configSchema: z.object({
|
|
204
210
|
/** Cloudflare account id (not a secret: it is in the dashboard URL). */
|
|
205
211
|
accountId: z.string(),
|
|
212
|
+
/** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
|
|
213
|
+
apiToken: apiTokenSchema.optional(),
|
|
206
214
|
/** Queue name: account-scoped, and what the consuming Worker's wrangler config names. */
|
|
207
215
|
queueName: z.string(),
|
|
208
216
|
/** Email Sending event subscriptions that fill the queue, one per sending domain. */
|
|
@@ -215,10 +223,11 @@ export const queueModule = defineModule({
|
|
|
215
223
|
subscriptionIds: z.record(z.string()),
|
|
216
224
|
}),
|
|
217
225
|
async apply(config, ctx) {
|
|
218
|
-
const token = ctx
|
|
226
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
227
|
+
const OPTS = optsFor(config.apiToken)
|
|
219
228
|
const base = `/accounts/${config.accountId}`
|
|
220
229
|
|
|
221
|
-
let queue = await findQueue(token, config.accountId, config.queueName)
|
|
230
|
+
let queue = await findQueue(token, config.accountId, config.queueName, OPTS)
|
|
222
231
|
if (queue) {
|
|
223
232
|
console.log(` Queue "${config.queueName}" already exists`)
|
|
224
233
|
} else {
|
|
@@ -234,7 +243,7 @@ export const queueModule = defineModule({
|
|
|
234
243
|
|
|
235
244
|
const existing =
|
|
236
245
|
config.subscriptions.length > 0
|
|
237
|
-
? await listSubscriptions(token, config.accountId, queue.queue_id)
|
|
246
|
+
? await listSubscriptions(token, config.accountId, queue.queue_id, OPTS)
|
|
238
247
|
: []
|
|
239
248
|
const subscriptionIds: Record<string, string> = {}
|
|
240
249
|
for (const wanted of config.subscriptions) {
|
|
@@ -286,15 +295,16 @@ export const queueModule = defineModule({
|
|
|
286
295
|
* down, so a destroy that reported it as done would be the lie.
|
|
287
296
|
*/
|
|
288
297
|
async destroy(config, ctx) {
|
|
289
|
-
const token = ctx
|
|
290
|
-
const
|
|
298
|
+
const token = apiTokenFor(config.apiToken, ctx)
|
|
299
|
+
const OPTS = optsFor(config.apiToken)
|
|
300
|
+
const queue = await findQueue(token, config.accountId, config.queueName, OPTS)
|
|
291
301
|
if (!queue) {
|
|
292
302
|
console.log(` Queue "${config.queueName}" is already gone`)
|
|
293
303
|
return
|
|
294
304
|
}
|
|
295
305
|
const existing =
|
|
296
306
|
config.subscriptions.length > 0
|
|
297
|
-
? await listSubscriptions(token, config.accountId, queue.queue_id)
|
|
307
|
+
? await listSubscriptions(token, config.accountId, queue.queue_id, OPTS)
|
|
298
308
|
: []
|
|
299
309
|
for (const wanted of config.subscriptions) {
|
|
300
310
|
const found = findMine(existing, wanted.name, queue.queue_id)
|
|
@@ -9,5 +9,5 @@
|
|
|
9
9
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
10
10
|
"signupUrl": "https://dash.cloudflare.com/sign-up",
|
|
11
11
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
12
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Queues: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/delivery.ts\n import { queueModule } from '../../modules/queue'\n export default queueModule.instance({\n name: 'delivery',\n config: {\n accountId: '<account id>',\n queueName: 'myproject-delivery',\n subscriptions: [{ name: 'myproject-sending', zoneId: '<zone id>', domain: 'example.com', events: ['message.delivered', 'message.bounced'] }],\n },\n })\n\nThe consuming Worker declares the queue by name in its own wrangler config (`queues.consumers: [{ queue: 'myproject-delivery' }]`) and imports this instance, so the queue exists before wrangler attaches the consumer. `destroy` removes the subscriptions this instance names and leaves the queue."
|
|
12
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Queues: Edit scope. 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.\n\nInstance example:\n\n // packages/infra/environments/production/delivery.ts\n import { queueModule } from '../../modules/queue'\n export default queueModule.instance({\n name: 'delivery',\n config: {\n accountId: '<account id>',\n queueName: 'myproject-delivery',\n subscriptions: [{ name: 'myproject-sending', zoneId: '<zone id>', domain: 'example.com', events: ['message.delivered', 'message.bounced'] }],\n },\n })\n\nThe consuming Worker declares the queue by name in its own wrangler config (`queues.consumers: [{ queue: 'myproject-delivery' }]`) and imports this instance, so the queue exists before wrangler attaches the consumer. `destroy` removes the subscriptions this instance names and leaves the queue."
|
|
13
13
|
}
|
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { z } from 'zod'
|
|
2
2
|
import { defineModule } from '../../src/define-module'
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
type ApiTokenSource,
|
|
5
|
+
apiTokenFor,
|
|
6
|
+
apiTokenSchema,
|
|
7
|
+
cf,
|
|
8
|
+
type CfOptions,
|
|
9
|
+
tokenScopeHint,
|
|
10
|
+
} from '../cloudflare-api'
|
|
4
11
|
|
|
5
12
|
/**
|
|
6
13
|
* r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
|
|
@@ -12,6 +19,9 @@ import { cf, type CfOptions } from '../cloudflare-api'
|
|
|
12
19
|
* as a `{ binding, from, output }` reference into this instance's outputs.
|
|
13
20
|
*
|
|
14
21
|
* Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
|
|
22
|
+
* Or set `apiToken` to take the token from an imported instance's output
|
|
23
|
+
* (`{ from, output }`, e.g. a `cloudflare-token`'s `tokenValue`) or from another
|
|
24
|
+
* key of secrets.yaml (`{ secret }`).
|
|
15
25
|
*/
|
|
16
26
|
|
|
17
27
|
/**
|
|
@@ -19,20 +29,17 @@ import { cf, type CfOptions } from '../cloudflare-api'
|
|
|
19
29
|
* per-module part of a Cloudflare failure. Everything else about the envelope
|
|
20
30
|
* (the base URL, the error shapes, the typed throw) is `../cloudflare-api`'s.
|
|
21
31
|
*/
|
|
22
|
-
const
|
|
23
|
-
hints: {
|
|
24
|
-
|
|
25
|
-
`rejected the token (10000 Authentication error). ` +
|
|
26
|
-
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
27
|
-
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
28
|
-
},
|
|
29
|
-
}
|
|
32
|
+
const optsFor = (source: ApiTokenSource | undefined): CfOptions => ({
|
|
33
|
+
hints: { 10000: tokenScopeHint(source, 'the Account → Workers R2 Storage: Edit scope') },
|
|
34
|
+
})
|
|
30
35
|
|
|
31
36
|
export const r2Module = defineModule({
|
|
32
37
|
name: 'r2',
|
|
33
38
|
configSchema: z.object({
|
|
34
39
|
/** Cloudflare account id (not a secret — it's in the dashboard URL). */
|
|
35
40
|
accountId: z.string(),
|
|
41
|
+
/** Where the token comes from when it is not CLOUDFLARE_API_TOKEN; see `apiTokenSchema`. */
|
|
42
|
+
apiToken: apiTokenSchema.optional(),
|
|
36
43
|
/** Bucket name — account-scoped, so namespace it per project/env. */
|
|
37
44
|
bucketName: z.string(),
|
|
38
45
|
/**
|
|
@@ -45,7 +52,8 @@ export const r2Module = defineModule({
|
|
|
45
52
|
bucketName: z.string(),
|
|
46
53
|
}),
|
|
47
54
|
async apply(config, ctx) {
|
|
48
|
-
const apiToken = ctx
|
|
55
|
+
const apiToken = apiTokenFor(config.apiToken, ctx)
|
|
56
|
+
const OPTS = optsFor(config.apiToken)
|
|
49
57
|
const base = `/accounts/${config.accountId}/r2/buckets`
|
|
50
58
|
|
|
51
59
|
const listing = await cf<{ buckets: Array<{ name: string }> }>(
|
|
@@ -87,7 +95,8 @@ export const r2Module = defineModule({
|
|
|
87
95
|
* there would strand every instance behind it.
|
|
88
96
|
*/
|
|
89
97
|
async destroy(config, ctx) {
|
|
90
|
-
const apiToken = ctx
|
|
98
|
+
const apiToken = apiTokenFor(config.apiToken, ctx)
|
|
99
|
+
const OPTS = optsFor(config.apiToken)
|
|
91
100
|
try {
|
|
92
101
|
await cf(
|
|
93
102
|
apiToken,
|
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
"files": [{ "path": "index.ts" }],
|
|
6
6
|
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
7
7
|
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
8
|
-
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }\n\n`destroy` deletes the bucket when it is empty. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
|
|
8
|
+
"instructions": "Reads the Cloudflare API through `../cloudflare-api`; CLOUDFLARE_API_TOKEN needs the Account → Workers R2 Storage: Edit scope. 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.\n\nInstance example:\n\n // packages/infra/environments/production/inbox-raw.ts\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: 'myproject-inbox-raw' },\n })\n\nWire it into a Worker via the cloudflare module:\n\n imports: [inboxRaw],\n config: { ..., r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }] }\n\n`destroy` deletes the bucket when it is empty. For one holding records no teardown may remove, set `retain: true` on the instance (beside `name`): `zbc destroy` then leaves it standing and refuses to target it."
|
|
9
9
|
}
|
|
@@ -144,6 +144,42 @@ export function createApplyContext(input: ApplyContextInput): ApplyContext {
|
|
|
144
144
|
outputValue(ref, field) {
|
|
145
145
|
return resolveOutputValue(ref, input.imports, field)
|
|
146
146
|
},
|
|
147
|
+
storeSecret: storeSecretOver(input),
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** A secrets.yaml key: what sops, a shell and an env var can all spell. */
|
|
152
|
+
const SECRET_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* `ctx.storeSecret`, over whatever writer the engine supplied.
|
|
156
|
+
*
|
|
157
|
+
* With no writer this is an apply, a destroy or a probe, and the refusal is the
|
|
158
|
+
* point: see `ApplyContext.storeSecret`. The key and the value are checked
|
|
159
|
+
* before the writer is asked, so a typo does not become a line in an encrypted
|
|
160
|
+
* file that then has to be found and removed.
|
|
161
|
+
*/
|
|
162
|
+
export function storeSecretOver(
|
|
163
|
+
input: ApplyContextInput,
|
|
164
|
+
): (key: string, value: string) => Promise<void> {
|
|
165
|
+
return async (key, value) => {
|
|
166
|
+
if (!input.storeSecret) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
`ctx.storeSecret("${key}") was called outside an action. A secret is stored only by ` +
|
|
169
|
+
'`zbc run <env> <instance> <action>`: an apply runs in CI, where a changed secrets.yaml is lost, ' +
|
|
170
|
+
'and must be safe to run twice. Move the mint into an action and let apply read the stored key.',
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
if (!SECRET_KEY.test(key)) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`ctx.storeSecret: "${key}" is not a secrets.yaml key (letters, digits and underscores, not starting with a digit)`,
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
if (typeof value !== 'string' || value === '') {
|
|
179
|
+
throw new Error(`ctx.storeSecret("${key}") was given no value to store`)
|
|
180
|
+
}
|
|
181
|
+
await input.storeSecret(key, value)
|
|
182
|
+
input.secrets[key] = value
|
|
147
183
|
}
|
|
148
184
|
}
|
|
149
185
|
|
|
@@ -169,7 +205,12 @@ export function ensureApplyContext(ctx: ApplyContextInput | ApplyContext): Apply
|
|
|
169
205
|
return {
|
|
170
206
|
...candidate,
|
|
171
207
|
outputValue: (ref, field) => resolveOutputValue(ref, candidate.imports, field),
|
|
208
|
+
storeSecret: candidate.storeSecret ?? storeSecretOver(candidate),
|
|
172
209
|
}
|
|
173
210
|
}
|
|
211
|
+
// The same, one release on: a full context from before `storeSecret`.
|
|
212
|
+
if (typeof candidate.storeSecret !== 'function') {
|
|
213
|
+
return { ...candidate, storeSecret: storeSecretOver(candidate) }
|
|
214
|
+
}
|
|
174
215
|
return candidate
|
|
175
216
|
}
|
|
@@ -21,6 +21,13 @@ export interface TestContextOptions {
|
|
|
21
21
|
imports?: Record<string, unknown>
|
|
22
22
|
/** Default `/zbc-test-project` — a path no test should be writing to. */
|
|
23
23
|
projectRoot?: string
|
|
24
|
+
/**
|
|
25
|
+
* This context is an action's: `ctx.storeSecret` records what it was given
|
|
26
|
+
* in `secretsStored`. Default false, where it throws as it does in a real
|
|
27
|
+
* apply, so a module that stores from `apply` fails its test and not its
|
|
28
|
+
* first deploy.
|
|
29
|
+
*/
|
|
30
|
+
action?: boolean
|
|
24
31
|
}
|
|
25
32
|
|
|
26
33
|
export interface TestApplyContext extends ApplyContext {
|
|
@@ -31,6 +38,8 @@ export interface TestApplyContext extends ApplyContext {
|
|
|
31
38
|
* through either `output` or `outputValue`.
|
|
32
39
|
*/
|
|
33
40
|
readonly outputsRead: string[]
|
|
41
|
+
/** What `ctx.storeSecret` was asked to store, by key. Empty unless `action`. */
|
|
42
|
+
readonly secretsStored: Record<string, string>
|
|
34
43
|
}
|
|
35
44
|
|
|
36
45
|
/**
|
|
@@ -51,10 +60,18 @@ export interface TestApplyContext extends ApplyContext {
|
|
|
51
60
|
* ```
|
|
52
61
|
*/
|
|
53
62
|
export function createTestContext(opts: TestContextOptions = {}): TestApplyContext {
|
|
63
|
+
const secretsStored: Record<string, string> = {}
|
|
54
64
|
const base = createApplyContext({
|
|
55
|
-
secrets: opts.secrets
|
|
65
|
+
secrets: { ...opts.secrets },
|
|
56
66
|
imports: opts.imports ?? {},
|
|
57
67
|
projectRoot: opts.projectRoot ?? '/zbc-test-project',
|
|
68
|
+
...(opts.action
|
|
69
|
+
? {
|
|
70
|
+
storeSecret: async (key: string, value: string) => {
|
|
71
|
+
secretsStored[key] = value
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
: {}),
|
|
58
75
|
})
|
|
59
76
|
|
|
60
77
|
const secretsRead: string[] = []
|
|
@@ -64,6 +81,7 @@ export function createTestContext(opts: TestContextOptions = {}): TestApplyConte
|
|
|
64
81
|
...base,
|
|
65
82
|
secretsRead,
|
|
66
83
|
outputsRead,
|
|
84
|
+
secretsStored,
|
|
67
85
|
// Recorded before resolution, not after: a test asserting "this module
|
|
68
86
|
// reads the secret its registry.json declares" has to see the ask even
|
|
69
87
|
// when the ask is what failed.
|
|
@@ -99,6 +99,12 @@ export interface ApplyContextInput {
|
|
|
99
99
|
secrets: Record<string, string>
|
|
100
100
|
imports: Record<string, unknown>
|
|
101
101
|
projectRoot: string
|
|
102
|
+
/**
|
|
103
|
+
* How `ctx.storeSecret` writes, when this context may write at all. The
|
|
104
|
+
* engine supplies it to an action's body and to nothing else; see
|
|
105
|
+
* `ApplyContext.storeSecret`.
|
|
106
|
+
*/
|
|
107
|
+
storeSecret?: (key: string, value: string) => Promise<void>
|
|
102
108
|
}
|
|
103
109
|
|
|
104
110
|
/** A `{ from, output }` reference into an imported instance's outputs. */
|
|
@@ -162,6 +168,23 @@ export interface ApplyContext extends ApplyContextInput {
|
|
|
162
168
|
* it.
|
|
163
169
|
*/
|
|
164
170
|
outputValue(ref: OutputRef, field: string): unknown
|
|
171
|
+
/**
|
|
172
|
+
* Put a value into this environment's secrets.yaml under `key`, encrypted as
|
|
173
|
+
* the rest of the file is. For the credential a provider shows once, at
|
|
174
|
+
* creation, and that something outside any apply will need later: an Access
|
|
175
|
+
* service token's client secret, a tunnel's run token, a key pair for a
|
|
176
|
+
* reader that is not this project.
|
|
177
|
+
*
|
|
178
|
+
* ONLY IN AN ACTION ([ADR-0023](../../../../../docs/adr/0023-a-credential-shown-once-is-stored-by-an-action.md)).
|
|
179
|
+
* Called from `apply`, `destroy` or a readiness probe it throws. An apply
|
|
180
|
+
* runs in CI, where a changed secrets.yaml is thrown away with the runner,
|
|
181
|
+
* and an apply that rewrites a committed file is no longer something that
|
|
182
|
+
* can be run twice to the same effect. An action is run by an operator, at a
|
|
183
|
+
* checkout, on purpose, and leaves a diff to commit.
|
|
184
|
+
*
|
|
185
|
+
* After it resolves, `ctx.secret(key)` in the same run returns the new value.
|
|
186
|
+
*/
|
|
187
|
+
storeSecret(key: string, value: string): Promise<void>
|
|
165
188
|
}
|
|
166
189
|
|
|
167
190
|
/**
|