@zabaca/zbc 0.6.2 → 0.8.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.
@@ -0,0 +1,429 @@
1
+ import * as path from 'node:path'
2
+ import { defineCommand } from 'citty'
3
+ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
4
+ import {
5
+ decryptSubmission,
6
+ decryptWithDocumentKey,
7
+ type EncryptedDocument,
8
+ encryptWithDocumentKey,
9
+ generateChannelKeypair,
10
+ generateDocumentKey,
11
+ pairingCode,
12
+ type SubmissionPayload,
13
+ } from '../../templates/apps/secret-relay/src/crypto'
14
+ import { applyEnvironment } from '../engine/apply'
15
+ import { discoverInstances } from '../engine/discover'
16
+ import { loadSecrets } from '../engine/secrets'
17
+ import { findProjectRoot } from '../utils/find-project-root'
18
+
19
+ const POLL_INTERVAL_MS = 250
20
+
21
+ /**
22
+ * Best-effort browser open, only when a human is plausibly at this terminal
23
+ * (TTY). Remote/CI/agent sessions just get the printed URL. Never fails the
24
+ * request: the URL is always printed first.
25
+ */
26
+ function tryOpenBrowser(url: string): void {
27
+ if (!process.stdout.isTTY) return
28
+ const cmd =
29
+ process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open'
30
+ try {
31
+ Bun.spawn([cmd, url], { stdout: 'ignore', stderr: 'ignore' })
32
+ } catch {
33
+ // printed URL is the fallback
34
+ }
35
+ }
36
+
37
+ function sleep(ms: number): Promise<void> {
38
+ return new Promise((resolve) => setTimeout(resolve, ms))
39
+ }
40
+
41
+ /**
42
+ * Merge `values` into the environment's secrets.yaml. With a `.sops.yaml` at
43
+ * the project root, writes go through sops so plaintext never lands on disk:
44
+ * `sops set` per key into an existing encrypted file, or a stdin-piped
45
+ * `sops -e` (with --filename-override so creation rules match) to create one.
46
+ * Without `.sops.yaml`, falls back to plain YAML (development mode, mirroring
47
+ * loadSecrets).
48
+ */
49
+ async function writeSecrets(
50
+ projectRoot: string,
51
+ envDir: string,
52
+ values: Record<string, string>,
53
+ ): Promise<void> {
54
+ const secretsPath = path.join(envDir, 'secrets.yaml')
55
+ const file = Bun.file(secretsPath)
56
+ const exists = await file.exists()
57
+ const hasSopsConfig = await Bun.file(path.join(projectRoot, '.sops.yaml')).exists()
58
+
59
+ if (!hasSopsConfig) {
60
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
61
+ await Bun.write(secretsPath, stringifyYaml({ ...existing, ...values }))
62
+ return
63
+ }
64
+
65
+ const alreadyEncrypted = exists && parseYaml(await file.text())?.sops
66
+ if (alreadyEncrypted) {
67
+ for (const [key, value] of Object.entries(values)) {
68
+ const proc = Bun.spawnSync(
69
+ ['sops', 'set', secretsPath, `["${key}"]`, JSON.stringify(value)],
70
+ { cwd: projectRoot, stderr: 'pipe' },
71
+ )
72
+ if (proc.exitCode !== 0) {
73
+ throw new Error(`sops set failed for ${key}: ${proc.stderr.toString()}`)
74
+ }
75
+ }
76
+ return
77
+ }
78
+
79
+ // Missing (or plain, pre-sops) file: merge in memory, encrypt via stdin so
80
+ // plaintext never touches the filesystem.
81
+ const existing = exists ? (parseYaml(await file.text()) ?? {}) : {}
82
+ const plaintext = stringifyYaml({ ...existing, ...values })
83
+ const proc = Bun.spawnSync(
84
+ [
85
+ 'sops',
86
+ '--config',
87
+ path.join(projectRoot, '.sops.yaml'),
88
+ '--filename-override',
89
+ secretsPath,
90
+ '-e',
91
+ '--input-type',
92
+ 'yaml',
93
+ '--output-type',
94
+ 'yaml',
95
+ '/dev/stdin',
96
+ ],
97
+ { cwd: projectRoot, stdin: new TextEncoder().encode(plaintext), stderr: 'pipe' },
98
+ )
99
+ if (proc.exitCode !== 0) {
100
+ throw new Error(`sops encrypt failed: ${proc.stderr.toString()}`)
101
+ }
102
+ await Bun.write(secretsPath, proc.stdout)
103
+ }
104
+
105
+ /**
106
+ * Find the project's Secret Relay and converge it through the normal apply
107
+ * graph (outputs are per-run, not persisted — ADR-0003), returning its
108
+ * deployUrl. Prefers a `secret-relay` instance in production, then any env.
109
+ */
110
+ async function resolveRelayUrl(projectRoot: string): Promise<string> {
111
+ const environmentsDir = path.join(projectRoot, 'packages/infra/environments')
112
+ const envDirs = Array.from(
113
+ new Bun.Glob('*/').scanSync({ cwd: environmentsDir, onlyFiles: false }),
114
+ )
115
+ .map((d) => d.replace(/\/$/, ''))
116
+ .sort((a, b) => (a === 'production' ? -1 : b === 'production' ? 1 : a.localeCompare(b)))
117
+
118
+ for (const env of envDirs) {
119
+ const envDir = path.join(environmentsDir, env)
120
+ const instances = await discoverInstances(envDir)
121
+ if (!instances.some((i) => i.name === 'secret-relay')) continue
122
+ const outputs = await applyEnvironment(projectRoot, envDir, 'secret-relay')
123
+ const relayOutputs = outputs.get('secret-relay') as { deployUrl?: string } | undefined
124
+ if (!relayOutputs?.deployUrl) {
125
+ throw new Error(`secret-relay instance in ${env} did not emit a deployUrl output`)
126
+ }
127
+ return relayOutputs.deployUrl
128
+ }
129
+
130
+ throw new Error(
131
+ 'no Secret Relay found — run `zbc add secret-relay` to scaffold and deploy one, or pass --relay <url>',
132
+ )
133
+ }
134
+
135
+ async function requestViaRelay(opts: {
136
+ relayUrl: string
137
+ keys: string[]
138
+ env: string
139
+ reason?: string
140
+ timeoutMs: number
141
+ }): Promise<Record<string, string>> {
142
+ const { publicKeyB64, privateKey } = await generateChannelKeypair()
143
+
144
+ const created = await fetch(`${opts.relayUrl}/channels`, {
145
+ method: 'POST',
146
+ headers: { 'content-type': 'application/json' },
147
+ body: JSON.stringify({
148
+ keys: opts.keys,
149
+ env: opts.env,
150
+ reason: opts.reason,
151
+ ttlSeconds: Math.ceil(opts.timeoutMs / 1000),
152
+ }),
153
+ })
154
+ if (!created.ok) throw new Error(`relay refused to open a channel (${created.status})`)
155
+ const { id } = (await created.json()) as { id: string }
156
+
157
+ const channelUrl = `${opts.relayUrl}/channels/${id}#${publicKeyB64}`
158
+ console.log(`Waiting for ${opts.keys.join(', ')} (${opts.env}) — open:`)
159
+ console.log(` ${channelUrl}`)
160
+ console.log(`Pairing code: ${await pairingCode(publicKeyB64)} — confirm it matches the page.`)
161
+ tryOpenBrowser(channelUrl)
162
+
163
+ const deadline = Date.now() + opts.timeoutMs
164
+ while (Date.now() < deadline) {
165
+ const res = await fetch(`${opts.relayUrl}/channels/${id}/submission`)
166
+ if (res.ok) {
167
+ const payload = (await res.json()) as SubmissionPayload
168
+ try {
169
+ return JSON.parse(await decryptSubmission(privateKey, payload)) as Record<string, string>
170
+ } catch {
171
+ throw new Error(
172
+ 'submission failed to decrypt — possibly tampered or sent to the wrong channel; nothing was written',
173
+ )
174
+ }
175
+ }
176
+ await sleep(POLL_INTERVAL_MS)
177
+ }
178
+ throw new Error(`timed out — still missing: ${opts.keys.join(', ')}`)
179
+ }
180
+
181
+ const requestCommand = defineCommand({
182
+ meta: {
183
+ name: 'request',
184
+ description:
185
+ 'Ask a human for secret values via the browser; writes them into the environment secrets.yaml',
186
+ },
187
+ args: {
188
+ keys: {
189
+ type: 'positional',
190
+ description: 'Secret key names to request',
191
+ required: true,
192
+ },
193
+ env: {
194
+ type: 'string',
195
+ description: 'Target environment (default: production)',
196
+ default: 'production',
197
+ },
198
+ relay: {
199
+ type: 'string',
200
+ description: 'Secret Relay URL (default: resolved from the secret-relay instance)',
201
+ },
202
+ reason: {
203
+ type: 'string',
204
+ description: 'Shown to the human on the request page',
205
+ },
206
+ timeout: {
207
+ type: 'string',
208
+ description: 'Seconds to wait for the submission (default: 300)',
209
+ default: '300',
210
+ },
211
+ },
212
+ async run({ args }) {
213
+ const keys = [
214
+ ...new Set([args.keys, ...args._].filter((k): k is string => typeof k === 'string')),
215
+ ]
216
+ await collectSecrets({
217
+ projectRoot: await findProjectRoot(),
218
+ env: args.env,
219
+ keys,
220
+ relayUrl: args.relay,
221
+ reason: args.reason,
222
+ timeoutSeconds: Number(args.timeout),
223
+ })
224
+ },
225
+ })
226
+
227
+ /**
228
+ * The Secret Request flow, programmatically: skip set keys, collect the rest
229
+ * through the relay, write via sops. Used by `zbc secret request` and by
230
+ * `zbc add`'s post-install secret collection.
231
+ */
232
+ export async function collectSecrets(opts: {
233
+ projectRoot: string
234
+ env: string
235
+ keys: string[]
236
+ relayUrl?: string
237
+ reason?: string
238
+ timeoutSeconds?: number
239
+ }): Promise<void> {
240
+ const envDir = path.join(opts.projectRoot, 'packages/infra/environments', opts.env)
241
+ const existing = await loadSecrets(envDir)
242
+
243
+ const missing: string[] = []
244
+ for (const key of opts.keys) {
245
+ if (key in existing) {
246
+ console.log(`✓ ${key} already set in ${opts.env}/secrets.yaml — skipping`)
247
+ } else {
248
+ missing.push(key)
249
+ }
250
+ }
251
+ if (missing.length === 0) return
252
+
253
+ const relayUrl = opts.relayUrl ?? (await resolveRelayUrl(opts.projectRoot))
254
+
255
+ const submitted = await requestViaRelay({
256
+ relayUrl,
257
+ keys: missing,
258
+ env: opts.env,
259
+ reason: opts.reason,
260
+ timeoutMs: (opts.timeoutSeconds ?? 300) * 1000,
261
+ })
262
+
263
+ const values: Record<string, string> = {}
264
+ for (const key of missing) {
265
+ const value = submitted[key]?.trim()
266
+ if (!value) throw new Error(`submission is missing a value for ${key}`)
267
+ values[key] = value
268
+ }
269
+
270
+ await writeSecrets(opts.projectRoot, envDir, values)
271
+ for (const key of missing) {
272
+ console.log(`✓ ${key} written to ${opts.env}/secrets.yaml`)
273
+ }
274
+ }
275
+
276
+ /** Registry-declared secret keys across all vendored modules/apps. */
277
+ async function declaredSecretKeys(projectRoot: string): Promise<Set<string>> {
278
+ const declared = new Set<string>()
279
+ const modulesDir = path.join(projectRoot, 'packages/infra/modules')
280
+ for (const file of new Bun.Glob('*/registry.json').scanSync({ cwd: modulesDir })) {
281
+ const registry = (await Bun.file(path.join(modulesDir, file)).json()) as {
282
+ secrets?: string[]
283
+ }
284
+ for (const key of registry.secrets ?? []) declared.add(key)
285
+ }
286
+ return declared
287
+ }
288
+
289
+ const listCommand = defineCommand({
290
+ meta: {
291
+ name: 'list',
292
+ description: 'Show which registry-declared secrets are set vs missing (names only, no values)',
293
+ },
294
+ args: {
295
+ env: {
296
+ type: 'string',
297
+ description: 'Target environment (default: production)',
298
+ default: 'production',
299
+ },
300
+ },
301
+ async run({ args }) {
302
+ const projectRoot = await findProjectRoot()
303
+ const envDir = path.join(projectRoot, 'packages/infra/environments', args.env)
304
+ const existing = await loadSecrets(envDir)
305
+ const declared = await declaredSecretKeys(projectRoot)
306
+
307
+ const keys = [...new Set([...declared, ...Object.keys(existing)])].sort()
308
+ for (const key of keys) {
309
+ const status = key in existing ? 'set' : 'missing'
310
+ const note = declared.has(key) ? '' : ' (not declared by any module)'
311
+ console.log(`${key.padEnd(32)} ${status}${note}`)
312
+ }
313
+ },
314
+ })
315
+
316
+ const editCommand = defineCommand({
317
+ meta: {
318
+ name: 'edit',
319
+ description: 'Edit an environment secrets.yaml in the browser (sops decrypts/re-encrypts)',
320
+ },
321
+ args: {
322
+ env: {
323
+ type: 'positional',
324
+ description: 'Target environment (default: production)',
325
+ required: false,
326
+ },
327
+ relay: {
328
+ type: 'string',
329
+ description: 'Secret Relay URL (default: resolved from the secret-relay instance)',
330
+ },
331
+ timeout: {
332
+ type: 'string',
333
+ description: 'Seconds to wait for the browser save (default: 600)',
334
+ default: '600',
335
+ },
336
+ },
337
+ async run({ args }) {
338
+ const env = args.env ?? 'production'
339
+ const projectRoot = await findProjectRoot()
340
+ const secretsPath = path.join(projectRoot, 'packages/infra/environments', env, 'secrets.yaml')
341
+ if (!(await Bun.file(secretsPath).exists())) {
342
+ throw new Error(`${env}/secrets.yaml does not exist — nothing to edit`)
343
+ }
344
+ const relayUrl = args.relay ?? (await resolveRelayUrl(projectRoot))
345
+
346
+ // sops decrypts to a temp file and invokes us back as the "editor"
347
+ // (`secret _editor`), which ships the plaintext to the browser through the
348
+ // relay and writes the edited result; sops then re-encrypts.
349
+ const proc = Bun.spawn(['sops', secretsPath], {
350
+ cwd: projectRoot,
351
+ stdio: ['inherit', 'inherit', 'inherit'],
352
+ env: {
353
+ ...process.env,
354
+ SOPS_EDITOR: `${process.execPath} ${process.argv[1]} secret _editor`,
355
+ ZBC_RELAY_URL: relayUrl,
356
+ ZBC_EDIT_ENV: env,
357
+ ZBC_EDIT_TIMEOUT: args.timeout,
358
+ },
359
+ })
360
+ const code = await proc.exited
361
+ if (code !== 0) throw new Error(`sops exited with code ${code} — secrets.yaml unchanged`)
362
+ console.log(`✓ ${env}/secrets.yaml updated`)
363
+ },
364
+ })
365
+
366
+ /** Invoked BY sops as $SOPS_EDITOR with the decrypted temp file. Hidden. */
367
+ const editorCommand = defineCommand({
368
+ meta: { name: '_editor', description: 'internal: browser editor invoked by sops' },
369
+ args: {
370
+ file: { type: 'positional', description: 'Decrypted temp file from sops', required: true },
371
+ },
372
+ async run({ args }) {
373
+ const relayUrl = process.env.ZBC_RELAY_URL
374
+ if (!relayUrl) throw new Error('_editor must be invoked via `zbc secret edit`')
375
+ const timeoutMs = Number(process.env.ZBC_EDIT_TIMEOUT ?? '600') * 1000
376
+ const plaintext = await Bun.file(args.file).text()
377
+
378
+ const documentKey = await generateDocumentKey()
379
+ const created = await fetch(`${relayUrl}/channels`, {
380
+ method: 'POST',
381
+ headers: { 'content-type': 'application/json' },
382
+ body: JSON.stringify({
383
+ mode: 'editor',
384
+ env: process.env.ZBC_EDIT_ENV,
385
+ document: await encryptWithDocumentKey(documentKey, plaintext),
386
+ ttlSeconds: Math.ceil(timeoutMs / 1000),
387
+ }),
388
+ })
389
+ if (!created.ok) throw new Error(`relay refused to open a channel (${created.status})`)
390
+ const { id } = (await created.json()) as { id: string }
391
+
392
+ const channelUrl = `${relayUrl}/channels/${id}#${documentKey}`
393
+ console.log(`Editing ${process.env.ZBC_EDIT_ENV}/secrets.yaml — open:`)
394
+ console.log(` ${channelUrl}`)
395
+ console.log(`Pairing code: ${await pairingCode(documentKey)} — confirm it matches the page.`)
396
+ tryOpenBrowser(channelUrl)
397
+
398
+ const deadline = Date.now() + timeoutMs
399
+ while (Date.now() < deadline) {
400
+ const res = await fetch(`${relayUrl}/channels/${id}/submission`)
401
+ if (res.ok) {
402
+ const { document } = (await res.json()) as { document: EncryptedDocument }
403
+ let edited: string
404
+ try {
405
+ edited = await decryptWithDocumentKey(documentKey, document)
406
+ } catch {
407
+ throw new Error('edited document failed to decrypt — nothing was written')
408
+ }
409
+ await Bun.write(args.file, edited)
410
+ return
411
+ }
412
+ await sleep(POLL_INTERVAL_MS)
413
+ }
414
+ throw new Error('timed out waiting for the browser save — secrets.yaml unchanged')
415
+ },
416
+ })
417
+
418
+ export const secretCommand = defineCommand({
419
+ meta: {
420
+ name: 'secret',
421
+ description: 'Manage environment secrets (request, list, edit)',
422
+ },
423
+ subCommands: {
424
+ request: requestCommand,
425
+ list: listCommand,
426
+ edit: editCommand,
427
+ _editor: editorCommand,
428
+ },
429
+ })
@@ -7,7 +7,7 @@ export async function applyEnvironment(
7
7
  projectRoot: string,
8
8
  envDir: string,
9
9
  target?: string,
10
- ): Promise<void> {
10
+ ): Promise<Map<string, unknown>> {
11
11
  const instances = await discoverInstances(envDir)
12
12
  const sorted = resolveOrder(instances, target)
13
13
  const secrets = await loadSecrets(envDir)
@@ -32,4 +32,6 @@ export async function applyEnvironment(
32
32
  outputs.set(instance.name, result)
33
33
  console.log(`✓ ${instance.moduleName}:${instance.name} applied`)
34
34
  }
35
+
36
+ return outputs
35
37
  }
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ import { addCommand } from './commands/add'
5
5
  import { applyCommand } from './commands/apply'
6
6
  import { destroyCommand } from './commands/destroy'
7
7
  import { initCommand } from './commands/init'
8
+ import { secretCommand } from './commands/secret'
8
9
 
9
10
  const main = defineCommand({
10
11
  meta: {
@@ -17,6 +18,7 @@ const main = defineCommand({
17
18
  destroy: destroyCommand,
18
19
  init: initCommand,
19
20
  add: addCommand,
21
+ secret: secretCommand,
20
22
  },
21
23
  })
22
24
 
@@ -13,7 +13,7 @@ This project uses [zbc](https://github.com/Zabaca/zbc) for infrastructure scaffo
13
13
  ## Common commands
14
14
 
15
15
  - `bun install` — install dependencies
16
- - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`) or scaffold an app template (`inbox` — an agent-accessible email inbox; auto-vendors its module dependencies)
16
+ - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; auto-vendors its module dependencies)
17
17
  - `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
18
18
  - `bunx @zabaca/zbc destroy <env>` — tear down an ephemeral environment
19
19
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "name": "@{{PROJECT_NAME}}/inbox",
2
+ "name": "@zbc/inbox",
3
3
  "version": "0.0.1",
4
4
  "private": true,
5
5
  "type": "module",
@@ -9,7 +9,11 @@
9
9
  "typecheck": "tsc --noEmit"
10
10
  },
11
11
  "dependencies": {
12
- "postal-mime": "^2.4.4"
12
+ "@hono/mcp": "^0.3.1",
13
+ "@modelcontextprotocol/sdk": "^1.29.0",
14
+ "hono": "^4.12.30",
15
+ "postal-mime": "^2.4.4",
16
+ "zod": "^4.4.3"
13
17
  },
14
18
  "devDependencies": {
15
19
  "@cloudflare/workers-types": "^4.20250101.0",
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>{{PROJECT_NAME}} inbox</title>
6
+ <title>Inbox</title>
7
7
  <style>
8
8
  /* Prose design system tokens (mirrored from packages/design-system/src/tokens.css;
9
9
  the inbox UI is a self-contained static page, so no Tailwind pipeline). */
@@ -156,7 +156,7 @@
156
156
  </head>
157
157
  <body>
158
158
  <header>
159
- <h1>{{PROJECT_NAME}} inbox</h1>
159
+ <h1>Inbox</h1>
160
160
  <span class="domain"></span>
161
161
  <span class="spacer"></span>
162
162
  <div class="actions">
@@ -174,7 +174,7 @@
174
174
  <h3 id="compose-title">New message</h3>
175
175
  <form class="compose" id="compose-form" method="dialog">
176
176
  <input name="to" placeholder="To" required>
177
- <input name="from" placeholder="From (default inbox)">
177
+ <input name="from" placeholder="From (optional, defaults to DEFAULT_FROM)">
178
178
  <input name="subject" placeholder="Subject" required>
179
179
  <input name="inReplyTo" type="hidden">
180
180
  <textarea name="text" placeholder="Message" required></textarea>
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "inbox",
3
3
  "kind": "app",
4
- "description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API plus a minimal web UI",
4
+ "description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API, an MCP server at /mcp (same token), and a minimal web UI",
5
5
  "targetDir": "packages/inbox",
6
- "modules": ["cloudflare-email"],
6
+ "modules": ["cloudflare", "cloudflare-email", "r2"],
7
7
  "secrets": ["INBOX_TOKEN", "CLOUDFLARE_API_TOKEN"],
8
- "instructions": "1) Edit packages/inbox/wrangler.jsonc: set DEFAULT_FROM to an address on your email domain (e.g. inbox@mail.example.com).\n2) Create two instance files in packages/infra/environments/<env>/:\n\n // inbox.ts\n import { cloudflareModule } from '../../modules/cloudflare'\n export default cloudflareModule.instance({\n name: 'inbox',\n config: { workdir: 'packages/inbox', accountId: '<account id>', workerSecrets: ['INBOX_TOKEN'] },\n })\n\n // email.ts\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\n3) Add INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml, and make sure CLOUDFLARE_API_TOKEN has the scopes the cloudflare-email module documents.\n4) `zbc apply <env>`. Create the R2 bucket if wrangler asks for it (`wrangler r2 bucket create <project>-inbox-raw`).\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
8
+ "instructions": "The scaffolded package is generic — all per-project identity (worker name, R2 bucket, default From address) lives in the instance files, not in wrangler.jsonc.\n\nCreate three instance files in packages/infra/environments/<env>/:\n\n // inbox-raw.ts — the R2 bucket for raw MIME\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: '<project>-inbox-raw' },\n })\n\n // inbox.ts — the worker\n import { cloudflareModule } from '../../modules/cloudflare'\n import inboxRaw from './inbox-raw'\n export default cloudflareModule.instance({\n name: 'inbox',\n imports: [inboxRaw],\n config: {\n workdir: 'packages/inbox',\n accountId: '<account id>',\n workerName: '<project>-inbox',\n workerSecrets: ['INBOX_TOKEN'],\n workerVars: [{ name: 'DEFAULT_FROM', value: 'inbox@mail.<your-domain>' }],\n r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }],\n },\n })\n\n // email.ts — sending + routing for the domain\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\nAdd INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml. CLOUDFLARE_API_TOKEN needs the scopes the cloudflare-email module documents PLUS Account → Workers R2 Storage: Edit (for the r2 module).\n\n`zbc apply <env>` provisions the bucket, deploys the worker, and onboards the domain.\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
9
9
  }