@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.
- package/package.json +1 -1
- package/src/commands/add.ts +107 -4
- package/src/commands/secret.test.ts +717 -0
- package/src/commands/secret.ts +429 -0
- package/src/engine/apply.ts +3 -1
- package/src/index.ts +2 -0
- package/templates/CLAUDE.md +1 -1
- package/templates/apps/inbox/package.json +6 -2
- package/templates/apps/inbox/public/index.html +3 -3
- package/templates/apps/inbox/registry.json +3 -3
- package/templates/apps/inbox/worker/inbox-do.ts +291 -36
- package/templates/apps/inbox/worker/index.ts +212 -97
- package/templates/apps/inbox/worker/mcp.ts +279 -0
- package/templates/apps/inbox/worker/send-op.ts +174 -0
- package/templates/apps/inbox/worker/shared.ts +117 -0
- package/templates/apps/inbox/wrangler.jsonc +17 -4
- package/templates/apps/secret-relay/package.json +10 -0
- package/templates/apps/secret-relay/registry.json +11 -0
- package/templates/apps/secret-relay/src/crypto.ts +151 -0
- package/templates/apps/secret-relay/src/page.ts +173 -0
- package/templates/apps/secret-relay/src/relay.ts +139 -0
- package/templates/apps/secret-relay/src/worker.ts +42 -0
- package/templates/apps/secret-relay/wrangler.jsonc +11 -0
- package/templates/infra/modules/cloudflare/index.ts +214 -5
- package/templates/infra/modules/r2/index.ts +137 -0
- package/templates/infra/modules/r2/registry.json +8 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import type { EncryptedDocument, SubmissionPayload } from './crypto'
|
|
2
|
+
import { requestPageHtml } from './page'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The Secret Relay's request handler, deployment-agnostic: `createRelay()`
|
|
6
|
+
* returns a plain fetch handler over a pluggable channel store. The worker
|
|
7
|
+
* entrypoint wraps this in a Durable Object (storage-backed store); tests run
|
|
8
|
+
* it directly over the in-memory default.
|
|
9
|
+
*
|
|
10
|
+
* The relay never sees plaintext — submissions are ciphertext encrypted to a
|
|
11
|
+
* key it never receives (the channel public key lives in the URL fragment).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const DEFAULT_TTL_SECONDS = 300
|
|
15
|
+
|
|
16
|
+
export interface Channel {
|
|
17
|
+
keys: string[]
|
|
18
|
+
reason?: string
|
|
19
|
+
env?: string
|
|
20
|
+
project?: string
|
|
21
|
+
/** 'request' (masked key/value form) or 'editor' (YAML document editor) */
|
|
22
|
+
mode?: 'request' | 'editor'
|
|
23
|
+
/** editor mode: the document ciphertext, encrypted to the fragment key */
|
|
24
|
+
document?: EncryptedDocument
|
|
25
|
+
expiresAt: number
|
|
26
|
+
submission?: SubmissionPayload | { document: EncryptedDocument }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ChannelStore {
|
|
30
|
+
get(id: string): Promise<Channel | undefined>
|
|
31
|
+
put(id: string, channel: Channel): Promise<void>
|
|
32
|
+
delete(id: string): Promise<void>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function memoryStore(): ChannelStore {
|
|
36
|
+
const channels = new Map<string, Channel>()
|
|
37
|
+
return {
|
|
38
|
+
async get(id) {
|
|
39
|
+
return channels.get(id)
|
|
40
|
+
},
|
|
41
|
+
async put(id, channel) {
|
|
42
|
+
channels.set(id, channel)
|
|
43
|
+
},
|
|
44
|
+
async delete(id) {
|
|
45
|
+
channels.delete(id)
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function json(body: unknown, status = 200): Response {
|
|
51
|
+
return new Response(JSON.stringify(body), {
|
|
52
|
+
status,
|
|
53
|
+
headers: { 'content-type': 'application/json' },
|
|
54
|
+
})
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createRelay(store: ChannelStore = memoryStore()): {
|
|
58
|
+
fetch(req: Request): Promise<Response>
|
|
59
|
+
} {
|
|
60
|
+
return {
|
|
61
|
+
async fetch(req: Request): Promise<Response> {
|
|
62
|
+
const url = new URL(req.url)
|
|
63
|
+
const parts = url.pathname.split('/').filter(Boolean)
|
|
64
|
+
|
|
65
|
+
// POST /channels — open a channel
|
|
66
|
+
if (req.method === 'POST' && url.pathname === '/channels') {
|
|
67
|
+
const body = (await req.json()) as {
|
|
68
|
+
keys?: string[]
|
|
69
|
+
reason?: string
|
|
70
|
+
env?: string
|
|
71
|
+
mode?: 'request' | 'editor'
|
|
72
|
+
document?: EncryptedDocument
|
|
73
|
+
ttlSeconds?: number
|
|
74
|
+
}
|
|
75
|
+
const id = crypto.randomUUID()
|
|
76
|
+
await store.put(id, {
|
|
77
|
+
keys: body.keys ?? [],
|
|
78
|
+
reason: body.reason,
|
|
79
|
+
env: body.env,
|
|
80
|
+
mode: body.mode ?? 'request',
|
|
81
|
+
document: body.document,
|
|
82
|
+
expiresAt: Date.now() + (body.ttlSeconds ?? DEFAULT_TTL_SECONDS) * 1000,
|
|
83
|
+
})
|
|
84
|
+
return json({ id })
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (parts[0] === 'channels' && (parts.length === 2 || parts.length === 3) && parts[1]) {
|
|
88
|
+
const id = parts[1]
|
|
89
|
+
const channel = await store.get(id)
|
|
90
|
+
if (channel && Date.now() >= channel.expiresAt) {
|
|
91
|
+
await store.delete(id)
|
|
92
|
+
return json({ error: 'channel expired' }, 410)
|
|
93
|
+
}
|
|
94
|
+
if (!channel) return json({ error: 'no such channel' }, 404)
|
|
95
|
+
|
|
96
|
+
// GET /channels/:id — the request page the human opens
|
|
97
|
+
if (req.method === 'GET' && parts.length === 2) {
|
|
98
|
+
return new Response(requestPageHtml(), {
|
|
99
|
+
headers: { 'content-type': 'text/html; charset=utf-8' },
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// GET /channels/:id/meta — what the page renders
|
|
104
|
+
if (req.method === 'GET' && parts[2] === 'meta') {
|
|
105
|
+
return json({
|
|
106
|
+
keys: channel.keys,
|
|
107
|
+
reason: channel.reason,
|
|
108
|
+
env: channel.env,
|
|
109
|
+
mode: channel.mode ?? 'request',
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// GET /channels/:id/document — editor mode: the ciphertext to edit
|
|
114
|
+
if (req.method === 'GET' && parts[2] === 'document') {
|
|
115
|
+
if (!channel.document) return json({ error: 'no document on this channel' }, 404)
|
|
116
|
+
return json(channel.document)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// POST /channels/:id/submission — browser submits ciphertext, once
|
|
120
|
+
if (req.method === 'POST' && parts[2] === 'submission') {
|
|
121
|
+
if (channel.submission) return json({ error: 'already submitted' }, 409)
|
|
122
|
+
channel.submission = (await req.json()) as SubmissionPayload
|
|
123
|
+
await store.put(id, channel)
|
|
124
|
+
return json({ ok: true })
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// GET /channels/:id/submission — CLI collects the ciphertext; the
|
|
128
|
+
// channel dies on first read (single-use)
|
|
129
|
+
if (req.method === 'GET' && parts[2] === 'submission') {
|
|
130
|
+
if (!channel.submission) return json({ error: 'not yet submitted' }, 404)
|
|
131
|
+
await store.delete(id)
|
|
132
|
+
return json(channel.submission)
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return json({ error: 'not found' }, 404)
|
|
137
|
+
},
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type Channel, type ChannelStore, createRelay } from './relay'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Cloudflare Worker entrypoint: all channel traffic is routed to a single
|
|
5
|
+
* Durable Object so channel state is strongly consistent, with DO storage
|
|
6
|
+
* backing so channels survive isolate eviction within their TTL.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
interface Env {
|
|
10
|
+
CHANNELS: DurableObjectNamespace
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class SecretRelayChannels {
|
|
14
|
+
private relay: ReturnType<typeof createRelay>
|
|
15
|
+
|
|
16
|
+
constructor(private ctx: DurableObjectState) {
|
|
17
|
+
const storage = ctx.storage
|
|
18
|
+
const store: ChannelStore = {
|
|
19
|
+
async get(id) {
|
|
20
|
+
return (await storage.get<Channel>(`ch:${id}`)) ?? undefined
|
|
21
|
+
},
|
|
22
|
+
async put(id, channel) {
|
|
23
|
+
await storage.put(`ch:${id}`, channel)
|
|
24
|
+
},
|
|
25
|
+
async delete(id) {
|
|
26
|
+
await storage.delete(`ch:${id}`)
|
|
27
|
+
},
|
|
28
|
+
}
|
|
29
|
+
this.relay = createRelay(store)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
fetch(req: Request): Promise<Response> {
|
|
33
|
+
return this.relay.fetch(req)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export default {
|
|
38
|
+
fetch(req: Request, env: Env): Promise<Response> {
|
|
39
|
+
const id = env.CHANNELS.idFromName('relay')
|
|
40
|
+
return env.CHANNELS.get(id).fetch(req)
|
|
41
|
+
},
|
|
42
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
// Worker name is supplied per-instance by the cloudflare module (workerName);
|
|
3
|
+
// this file only describes the shape of the worker.
|
|
4
|
+
"name": "secret-relay",
|
|
5
|
+
"main": "src/worker.ts",
|
|
6
|
+
"compatibility_date": "2025-06-01",
|
|
7
|
+
"durable_objects": {
|
|
8
|
+
"bindings": [{ "name": "CHANNELS", "class_name": "SecretRelayChannels" }]
|
|
9
|
+
},
|
|
10
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["SecretRelayChannels"] }]
|
|
11
|
+
}
|
|
@@ -87,12 +87,20 @@ const buildSchema = z.object({
|
|
|
87
87
|
})
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
|
-
* A worker secret/var entry:
|
|
91
|
-
*
|
|
92
|
-
*
|
|
90
|
+
* A worker secret/var entry: a plain name (resolved from this environment's
|
|
91
|
+
* secrets.yaml), a `{ name, value }` literal (vars that are per-instance
|
|
92
|
+
* config rather than secrets — e.g. DEFAULT_FROM — so a generic wrangler.jsonc
|
|
93
|
+
* needs no editing), or a `{ name, from, output }` reference into an imported
|
|
94
|
+
* instance's outputs (`ctx.imports[from][output]`).
|
|
93
95
|
*/
|
|
94
96
|
const workerValueSchema = z.union([
|
|
95
97
|
z.string(),
|
|
98
|
+
z.object({
|
|
99
|
+
/** Env var name inside the Worker. */
|
|
100
|
+
name: z.string(),
|
|
101
|
+
/** Literal value, straight from this instance's config file. */
|
|
102
|
+
value: z.string(),
|
|
103
|
+
}),
|
|
96
104
|
z.object({
|
|
97
105
|
/** Env var name inside the Worker. */
|
|
98
106
|
name: z.string(),
|
|
@@ -121,6 +129,10 @@ function resolveWorkerValue(
|
|
|
121
129
|
return { name: entry, value }
|
|
122
130
|
}
|
|
123
131
|
|
|
132
|
+
if ('value' in entry) {
|
|
133
|
+
return { name: entry.name, value: entry.value }
|
|
134
|
+
}
|
|
135
|
+
|
|
124
136
|
const instanceOutputs = ctx.imports[entry.from]
|
|
125
137
|
if (instanceOutputs === undefined) {
|
|
126
138
|
throw new Error(
|
|
@@ -136,6 +148,165 @@ function resolveWorkerValue(
|
|
|
136
148
|
return { name: entry.name, value }
|
|
137
149
|
}
|
|
138
150
|
|
|
151
|
+
/**
|
|
152
|
+
* An R2 binding override: which bucket the named `r2_buckets` binding in the
|
|
153
|
+
* package's wrangler config should attach to. Either a literal bucket name or
|
|
154
|
+
* a `{ from, output }` reference into an imported instance's outputs (the r2
|
|
155
|
+
* module emits `bucketName`). Wrangler has no CLI flag for this, so the module
|
|
156
|
+
* patches a generated copy of the wrangler config and deploys with --config —
|
|
157
|
+
* which is what lets a scaffolded package's wrangler.jsonc stay generic while
|
|
158
|
+
* the per-project bucket name lives in the instance file.
|
|
159
|
+
*/
|
|
160
|
+
const r2BindingSchema = z.union([
|
|
161
|
+
z.object({
|
|
162
|
+
/** Binding name inside the Worker (the `binding` field in r2_buckets). */
|
|
163
|
+
binding: z.string(),
|
|
164
|
+
/** Literal bucket name. */
|
|
165
|
+
bucketName: z.string(),
|
|
166
|
+
}),
|
|
167
|
+
z.object({
|
|
168
|
+
binding: z.string(),
|
|
169
|
+
/** Instance name — must be listed in this instance's `imports`. */
|
|
170
|
+
from: z.string(),
|
|
171
|
+
/** Which output of that instance holds the bucket name. */
|
|
172
|
+
output: z.string(),
|
|
173
|
+
}),
|
|
174
|
+
])
|
|
175
|
+
|
|
176
|
+
type R2BindingEntry = z.infer<typeof r2BindingSchema>
|
|
177
|
+
|
|
178
|
+
function resolveR2Binding(
|
|
179
|
+
entry: R2BindingEntry,
|
|
180
|
+
ctx: { imports: Record<string, unknown> },
|
|
181
|
+
): { binding: string; bucketName: string } {
|
|
182
|
+
if ('bucketName' in entry) return { binding: entry.binding, bucketName: entry.bucketName }
|
|
183
|
+
const instanceOutputs = ctx.imports[entry.from]
|
|
184
|
+
if (instanceOutputs === undefined) {
|
|
185
|
+
throw new Error(
|
|
186
|
+
`r2Bindings entry "${entry.binding}" references instance "${entry.from}", which is not in this instance's imports`,
|
|
187
|
+
)
|
|
188
|
+
}
|
|
189
|
+
const value = (instanceOutputs as Record<string, unknown> | null)?.[entry.output]
|
|
190
|
+
if (typeof value !== 'string') {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`r2Bindings entry "${entry.binding}" references output "${entry.output}" on instance "${entry.from}", which doesn't emit it`,
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
return { binding: entry.binding, bucketName: value }
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Strip line and block comments from JSONC, string-aware. */
|
|
199
|
+
function stripJsoncComments(src: string): string {
|
|
200
|
+
let out = ''
|
|
201
|
+
let i = 0
|
|
202
|
+
let inStr = false
|
|
203
|
+
while (i < src.length) {
|
|
204
|
+
const c = src[i]!
|
|
205
|
+
if (inStr) {
|
|
206
|
+
out += c
|
|
207
|
+
if (c === '\\') {
|
|
208
|
+
out += src[i + 1] ?? ''
|
|
209
|
+
i += 2
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
if (c === '"') inStr = false
|
|
213
|
+
i++
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
if (c === '"') {
|
|
217
|
+
inStr = true
|
|
218
|
+
out += c
|
|
219
|
+
i++
|
|
220
|
+
continue
|
|
221
|
+
}
|
|
222
|
+
if (c === '/' && src[i + 1] === '/') {
|
|
223
|
+
while (i < src.length && src[i] !== '\n') i++
|
|
224
|
+
continue
|
|
225
|
+
}
|
|
226
|
+
if (c === '/' && src[i + 1] === '*') {
|
|
227
|
+
i += 2
|
|
228
|
+
while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) i++
|
|
229
|
+
i += 2
|
|
230
|
+
continue
|
|
231
|
+
}
|
|
232
|
+
out += c
|
|
233
|
+
i++
|
|
234
|
+
}
|
|
235
|
+
return out
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Remove trailing commas (`,}` / `,]`), string-aware — JSONC allows them. */
|
|
239
|
+
function stripTrailingCommas(src: string): string {
|
|
240
|
+
let out = ''
|
|
241
|
+
let inStr = false
|
|
242
|
+
for (let i = 0; i < src.length; i++) {
|
|
243
|
+
const c = src[i]!
|
|
244
|
+
if (inStr) {
|
|
245
|
+
out += c
|
|
246
|
+
if (c === '\\') {
|
|
247
|
+
out += src[i + 1] ?? ''
|
|
248
|
+
i++
|
|
249
|
+
continue
|
|
250
|
+
}
|
|
251
|
+
if (c === '"') inStr = false
|
|
252
|
+
continue
|
|
253
|
+
}
|
|
254
|
+
if (c === '"') {
|
|
255
|
+
inStr = true
|
|
256
|
+
out += c
|
|
257
|
+
continue
|
|
258
|
+
}
|
|
259
|
+
if (c === ',') {
|
|
260
|
+
let j = i + 1
|
|
261
|
+
while (j < src.length && /\s/.test(src[j]!)) j++
|
|
262
|
+
if (src[j] === '}' || src[j] === ']') continue
|
|
263
|
+
}
|
|
264
|
+
out += c
|
|
265
|
+
}
|
|
266
|
+
return out
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
interface WranglerR2Entry {
|
|
270
|
+
binding: string
|
|
271
|
+
bucket_name?: string
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Rewrite `bucket_name` for each resolved r2Bindings entry, in the top-level
|
|
276
|
+
* `r2_buckets` and (when `wranglerEnv` is set) the matching `env.<name>` block.
|
|
277
|
+
* A binding with no matching r2_buckets entry is a hard config error.
|
|
278
|
+
*/
|
|
279
|
+
function patchR2Buckets(
|
|
280
|
+
config: Record<string, unknown>,
|
|
281
|
+
resolved: Array<{ binding: string; bucketName: string }>,
|
|
282
|
+
wranglerEnv?: string,
|
|
283
|
+
): void {
|
|
284
|
+
const blocks: Array<Record<string, unknown>> = [config]
|
|
285
|
+
if (wranglerEnv) {
|
|
286
|
+
const envBlock = (config.env as Record<string, Record<string, unknown>> | undefined)?.[
|
|
287
|
+
wranglerEnv
|
|
288
|
+
]
|
|
289
|
+
if (envBlock) blocks.push(envBlock)
|
|
290
|
+
}
|
|
291
|
+
for (const { binding, bucketName } of resolved) {
|
|
292
|
+
let found = false
|
|
293
|
+
for (const block of blocks) {
|
|
294
|
+
const entry = (block.r2_buckets as WranglerR2Entry[] | undefined)?.find(
|
|
295
|
+
(b) => b.binding === binding,
|
|
296
|
+
)
|
|
297
|
+
if (entry) {
|
|
298
|
+
entry.bucket_name = bucketName
|
|
299
|
+
found = true
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (!found) {
|
|
303
|
+
throw new Error(
|
|
304
|
+
`r2Bindings entry "${binding}" has no matching r2_buckets binding in the package's wrangler config`,
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
139
310
|
export const cloudflareModule = defineModule({
|
|
140
311
|
name: 'cloudflare',
|
|
141
312
|
configSchema: z.object({
|
|
@@ -164,6 +335,14 @@ export const cloudflareModule = defineModule({
|
|
|
164
335
|
* route sensitive values through this field.
|
|
165
336
|
*/
|
|
166
337
|
workerVars: z.array(workerValueSchema).default([]),
|
|
338
|
+
/**
|
|
339
|
+
* Override which R2 bucket each named `r2_buckets` binding attaches to.
|
|
340
|
+
* Entries are `{ binding, bucketName }` literals or `{ binding, from,
|
|
341
|
+
* output }` references into an imported instance's outputs (the r2 module
|
|
342
|
+
* emits `bucketName`). Lets the package's wrangler config stay generic —
|
|
343
|
+
* the per-project bucket lives here, next to the other identifiers.
|
|
344
|
+
*/
|
|
345
|
+
r2Bindings: z.array(r2BindingSchema).default([]),
|
|
167
346
|
/**
|
|
168
347
|
* For container-backed Workers: roll the running container to the new image
|
|
169
348
|
* IMMEDIATELY on deploy (`--containers-rollout immediate`). The wrangler
|
|
@@ -235,20 +414,50 @@ export const cloudflareModule = defineModule({
|
|
|
235
414
|
const resolvedSecrets = config.workerSecrets.map((entry) =>
|
|
236
415
|
resolveWorkerValue(entry, ctx, 'workerSecrets'),
|
|
237
416
|
)
|
|
417
|
+
const resolvedR2 = config.r2Bindings.map((entry) => resolveR2Binding(entry, ctx))
|
|
418
|
+
|
|
419
|
+
// 2b. r2Bindings: wrangler has no CLI flag for bucket overrides, so patch
|
|
420
|
+
// a generated copy of the package's wrangler config and deploy with
|
|
421
|
+
// --config. Written next to the original so relative paths (main,
|
|
422
|
+
// assets dir) still resolve; comments don't survive the round-trip,
|
|
423
|
+
// but the file is throwaway (deleted after deploy).
|
|
424
|
+
let generatedConfig: string | undefined
|
|
425
|
+
if (resolvedR2.length > 0) {
|
|
426
|
+
const configPath = ['wrangler.jsonc', 'wrangler.json']
|
|
427
|
+
.map((f) => path.join(workdir, f))
|
|
428
|
+
.find((f) => fs.existsSync(f))
|
|
429
|
+
if (!configPath) {
|
|
430
|
+
throw new Error(
|
|
431
|
+
`r2Bindings requires a wrangler.jsonc/wrangler.json in ${config.workdir} (wrangler.toml is not supported)`,
|
|
432
|
+
)
|
|
433
|
+
}
|
|
434
|
+
const parsed = JSON.parse(
|
|
435
|
+
stripTrailingCommas(stripJsoncComments(fs.readFileSync(configPath, 'utf8'))),
|
|
436
|
+
) as Record<string, unknown>
|
|
437
|
+
patchR2Buckets(parsed, resolvedR2, config.wranglerEnv)
|
|
438
|
+
generatedConfig = path.join(workdir, 'wrangler.zbc-generated.json')
|
|
439
|
+
fs.writeFileSync(generatedConfig, JSON.stringify(parsed, null, 2))
|
|
440
|
+
}
|
|
238
441
|
|
|
239
442
|
// 3. Deploy. Creates/updates the Worker script (+ assets, DO, container).
|
|
240
443
|
// --env selects the named wrangler environment (e.g. preview) so it ships
|
|
241
444
|
// a distinct worker from the same package; --name overrides the worker
|
|
242
445
|
// name (per-PR preview workers); both omitted = the package's default.
|
|
243
446
|
const deployArgs = ['deploy']
|
|
447
|
+
if (generatedConfig) deployArgs.push('--config', generatedConfig)
|
|
244
448
|
if (config.wranglerEnv) deployArgs.push('--env', config.wranglerEnv)
|
|
245
449
|
if (config.workerName) deployArgs.push('--name', config.workerName)
|
|
246
450
|
if (config.immediateContainerRollout) deployArgs.push('--containers-rollout', 'immediate')
|
|
247
451
|
for (const { name, value } of resolvedVars) deployArgs.push('--var', `${name}:${value}`)
|
|
248
452
|
console.log(
|
|
249
|
-
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}`,
|
|
453
|
+
` Deploying via wrangler (in ${config.workdir})${config.wranglerEnv ? ` [env: ${config.wranglerEnv}]` : ''}${config.workerName ? ` [name: ${config.workerName}]` : ''}${config.immediateContainerRollout ? ' [immediate container rollout]' : ''}${resolvedVars.length ? ` [vars: ${resolvedVars.map((v) => v.name).join(', ')}]` : ''}${resolvedR2.length ? ` [r2: ${resolvedR2.map((b) => `${b.binding}→${b.bucketName}`).join(', ')}]` : ''}`,
|
|
250
454
|
)
|
|
251
|
-
|
|
455
|
+
let out: string
|
|
456
|
+
try {
|
|
457
|
+
out = wrangler(workdir, deployArgs, env)
|
|
458
|
+
} finally {
|
|
459
|
+
if (generatedConfig) fs.rmSync(generatedConfig, { force: true })
|
|
460
|
+
}
|
|
252
461
|
// Success theater guard: wrangler can exit 0 without actually deploying
|
|
253
462
|
// (the --bun incident above). Require the deploy confirmation line — and
|
|
254
463
|
// capture the deployed script name from it for the workerName output.
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import { defineModule } from '../../src/define-module'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* r2 — provisions a Cloudflare R2 bucket via the REST API (turso-style:
|
|
6
|
+
* token from ctx.secrets, idempotent list→create, console.log progress).
|
|
7
|
+
*
|
|
8
|
+
* Exists so bucket lifecycle is owned by infra instead of being a side effect
|
|
9
|
+
* of `wrangler deploy` prompting to create a missing bucket. A worker wires
|
|
10
|
+
* the bucket in through the cloudflare module's `r2Bindings` config, typically
|
|
11
|
+
* as a `{ binding, from, output }` reference into this instance's outputs.
|
|
12
|
+
*
|
|
13
|
+
* Token scope: CLOUDFLARE_API_TOKEN needs Account → Workers R2 Storage: Edit.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const API = 'https://api.cloudflare.com/client/v4'
|
|
17
|
+
|
|
18
|
+
interface CfEnvelope<T> {
|
|
19
|
+
success: boolean
|
|
20
|
+
errors: Array<{ code: number; message: string }>
|
|
21
|
+
result: T
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function cfFetch<T>(
|
|
25
|
+
token: string,
|
|
26
|
+
path: string,
|
|
27
|
+
init?: { method?: string; body?: unknown },
|
|
28
|
+
): Promise<T> {
|
|
29
|
+
const res = await fetch(`${API}${path}`, {
|
|
30
|
+
method: init?.method ?? 'GET',
|
|
31
|
+
headers: {
|
|
32
|
+
Authorization: `Bearer ${token}`,
|
|
33
|
+
'Content-Type': 'application/json',
|
|
34
|
+
},
|
|
35
|
+
body: init?.body === undefined ? undefined : JSON.stringify(init.body),
|
|
36
|
+
})
|
|
37
|
+
let envelope: CfEnvelope<T>
|
|
38
|
+
try {
|
|
39
|
+
envelope = (await res.json()) as CfEnvelope<T>
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Error(`Cloudflare API ${path}: HTTP ${res.status} (non-JSON body)`)
|
|
42
|
+
}
|
|
43
|
+
if (!res.ok || !envelope.success) {
|
|
44
|
+
const codes = (envelope.errors ?? []).map((e) => e.code)
|
|
45
|
+
const detail = (envelope.errors ?? []).map((e) => `${e.code}: ${e.message}`).join('; ')
|
|
46
|
+
if (codes.includes(10000)) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`Cloudflare API ${path} rejected the token (10000 Authentication error). ` +
|
|
49
|
+
`CLOUDFLARE_API_TOKEN is likely missing the Account → Workers R2 Storage: Edit scope. ` +
|
|
50
|
+
`Edit the token at https://dash.cloudflare.com/profile/api-tokens and re-run zbc apply.`,
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
throw new Error(`Cloudflare API ${path} failed (HTTP ${res.status}): ${detail}`)
|
|
54
|
+
}
|
|
55
|
+
return envelope.result
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const r2Module = defineModule({
|
|
59
|
+
name: 'r2',
|
|
60
|
+
configSchema: z.object({
|
|
61
|
+
/** Cloudflare account id (not a secret — it's in the dashboard URL). */
|
|
62
|
+
accountId: z.string(),
|
|
63
|
+
/** Bucket name — account-scoped, so namespace it per project/env. */
|
|
64
|
+
bucketName: z.string(),
|
|
65
|
+
/**
|
|
66
|
+
* Location hint for new buckets (e.g. 'wnam', 'enam', 'weur'). Only
|
|
67
|
+
* applied at creation; Cloudflare doesn't support relocating a bucket.
|
|
68
|
+
*/
|
|
69
|
+
locationHint: z.string().optional(),
|
|
70
|
+
/**
|
|
71
|
+
* Destroy+recreate on every apply (preview environments). NOTE: deleting
|
|
72
|
+
* a non-empty bucket fails — the management API has no object purge, so
|
|
73
|
+
* ephemeral only works cleanly for buckets whose objects the app cleans
|
|
74
|
+
* up, or that stay small enough to purge by hand.
|
|
75
|
+
*/
|
|
76
|
+
ephemeral: z.boolean().default(false),
|
|
77
|
+
}),
|
|
78
|
+
outputs: z.object({
|
|
79
|
+
bucketName: z.string(),
|
|
80
|
+
}),
|
|
81
|
+
async apply(config, ctx) {
|
|
82
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
83
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
84
|
+
const base = `/accounts/${config.accountId}/r2/buckets`
|
|
85
|
+
|
|
86
|
+
if (config.ephemeral) {
|
|
87
|
+
try {
|
|
88
|
+
await cfFetch(apiToken, `${base}/${encodeURIComponent(config.bucketName)}`, {
|
|
89
|
+
method: 'DELETE',
|
|
90
|
+
})
|
|
91
|
+
console.log(` Deleted ephemeral bucket "${config.bucketName}"`)
|
|
92
|
+
} catch {
|
|
93
|
+
// Didn't exist (or non-empty — creation below will then no-op via the
|
|
94
|
+
// existence check, which for ephemeral means stale objects persist).
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const listing = await cfFetch<{ buckets: Array<{ name: string }> }>(
|
|
99
|
+
apiToken,
|
|
100
|
+
`${base}?per_page=1000`,
|
|
101
|
+
)
|
|
102
|
+
const exists = listing.buckets.some((b) => b.name === config.bucketName)
|
|
103
|
+
|
|
104
|
+
if (exists) {
|
|
105
|
+
console.log(` Bucket "${config.bucketName}" already exists`)
|
|
106
|
+
} else {
|
|
107
|
+
await cfFetch(apiToken, base, {
|
|
108
|
+
method: 'POST',
|
|
109
|
+
body: {
|
|
110
|
+
name: config.bucketName,
|
|
111
|
+
...(config.locationHint ? { locationHint: config.locationHint } : {}),
|
|
112
|
+
},
|
|
113
|
+
})
|
|
114
|
+
console.log(
|
|
115
|
+
` Created bucket "${config.bucketName}"${config.locationHint ? ` (${config.locationHint})` : ''}`,
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return { bucketName: config.bucketName }
|
|
120
|
+
},
|
|
121
|
+
async destroy(config, ctx) {
|
|
122
|
+
const apiToken = ctx.secrets['CLOUDFLARE_API_TOKEN']
|
|
123
|
+
if (!apiToken) throw new Error('Missing secret: CLOUDFLARE_API_TOKEN')
|
|
124
|
+
try {
|
|
125
|
+
await cfFetch(
|
|
126
|
+
apiToken,
|
|
127
|
+
`/accounts/${config.accountId}/r2/buckets/${encodeURIComponent(config.bucketName)}`,
|
|
128
|
+
{ method: 'DELETE' },
|
|
129
|
+
)
|
|
130
|
+
console.log(` Deleted bucket "${config.bucketName}"`)
|
|
131
|
+
} catch (err) {
|
|
132
|
+
// Most common cause: bucket not empty (the API refuses). Surface it —
|
|
133
|
+
// silent skips here would strand storage.
|
|
134
|
+
console.log(` Bucket delete skipped: ${(err as Error).message}`)
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
})
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "r2",
|
|
3
|
+
"description": "Cloudflare R2 bucket, provisioned via the REST API. Pair with the cloudflare module's r2Bindings to wire the bucket into a Worker at deploy time.",
|
|
4
|
+
"files": [{ "path": "index.ts" }],
|
|
5
|
+
"secrets": ["CLOUDFLARE_API_TOKEN"],
|
|
6
|
+
"tokenUrl": "https://dash.cloudflare.com/profile/api-tokens",
|
|
7
|
+
"instructions": "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' }] }"
|
|
8
|
+
}
|