@zabaca/zbc 0.12.0 → 0.14.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/package.json +6 -2
  3. package/src/commands/add.ts +13 -0
  4. package/src/commands/init.ts +1 -0
  5. package/src/engine/apply.ts +60 -21
  6. package/src/engine/destroy.ts +183 -14
  7. package/src/engine/discover.ts +1 -1
  8. package/src/engine/resolve.ts +56 -11
  9. package/src/utils/copy-template.ts +10 -0
  10. package/templates/apps/inbox/package.json +4 -2
  11. package/templates/apps/inbox/tsconfig.json +3 -1
  12. package/templates/apps/inbox/worker/api.ts +197 -0
  13. package/templates/apps/inbox/worker/commands.ts +299 -0
  14. package/templates/apps/inbox/worker/inbox-do.ts +53 -10
  15. package/templates/apps/inbox/worker/index.ts +15 -202
  16. package/templates/apps/inbox/worker/mcp.ts +49 -100
  17. package/templates/apps/walgit/CONTEXT.md +135 -0
  18. package/templates/apps/walgit/Dockerfile +40 -18
  19. package/templates/apps/walgit/README.md +518 -55
  20. package/templates/apps/walgit/e2e/README.md +100 -6
  21. package/templates/apps/walgit/e2e/harness.ts +262 -1
  22. package/templates/apps/walgit/e2e/live.ts +588 -0
  23. package/templates/apps/walgit/e2e/scenarios.ts +367 -5
  24. package/templates/apps/walgit/e2e/suite.ts +5 -5
  25. package/templates/apps/walgit/examples/watch.ts +209 -0
  26. package/templates/apps/walgit/package.json +12 -3
  27. package/templates/apps/walgit/registry.json +6 -11
  28. package/templates/apps/walgit/shared/capabilities.ts +189 -0
  29. package/templates/apps/walgit/shared/container-env.ts +114 -0
  30. package/templates/apps/walgit/shared/credentials.ts +81 -0
  31. package/templates/apps/walgit/shared/events.ts +277 -0
  32. package/templates/apps/walgit/shared/landing.ts +1241 -0
  33. package/templates/apps/walgit/shared/llms.ts +463 -0
  34. package/templates/apps/walgit/shared/outbox.ts +266 -0
  35. package/templates/apps/walgit/shared/policy.ts +59 -0
  36. package/templates/apps/walgit/shared/protocol.ts +197 -0
  37. package/templates/apps/walgit/shared/provenance.ts +154 -0
  38. package/templates/apps/walgit/shared/ref-cache.ts +181 -0
  39. package/templates/apps/walgit/shared/telemetry.ts +219 -0
  40. package/templates/apps/walgit/src/announce-main.ts +37 -0
  41. package/templates/apps/walgit/src/announce.ts +98 -0
  42. package/templates/apps/walgit/src/append-only.ts +112 -0
  43. package/templates/apps/walgit/src/cache.ts +172 -0
  44. package/templates/apps/walgit/src/cli.ts +493 -0
  45. package/templates/apps/walgit/src/compact.ts +25 -23
  46. package/templates/apps/walgit/src/delete-repo.ts +237 -0
  47. package/templates/apps/walgit/src/expire.ts +248 -0
  48. package/templates/apps/walgit/src/gc.ts +8 -16
  49. package/templates/apps/walgit/src/git-backend.ts +29 -0
  50. package/templates/apps/walgit/src/git.ts +78 -0
  51. package/templates/apps/walgit/src/hook-main.ts +259 -17
  52. package/templates/apps/walgit/src/hooks.ts +4 -3
  53. package/templates/apps/walgit/src/http.ts +237 -45
  54. package/templates/apps/walgit/src/instructions.ts +240 -0
  55. package/templates/apps/walgit/src/keys.ts +126 -0
  56. package/templates/apps/walgit/src/limits.ts +158 -0
  57. package/templates/apps/walgit/src/materialize.bench.ts +10 -10
  58. package/templates/apps/walgit/src/materialize.ts +48 -40
  59. package/templates/apps/walgit/src/mkdir-lock.ts +66 -0
  60. package/templates/apps/walgit/src/orphans.ts +2 -5
  61. package/templates/apps/walgit/src/pending.ts +201 -0
  62. package/templates/apps/walgit/src/push-cert.ts +254 -0
  63. package/templates/apps/walgit/src/push.ts +233 -46
  64. package/templates/apps/walgit/src/reconcile.ts +5 -8
  65. package/templates/apps/walgit/src/repo.ts +22 -77
  66. package/templates/apps/walgit/src/server.ts +148 -26
  67. package/templates/apps/walgit/src/signers.ts +577 -0
  68. package/templates/apps/walgit/src/store-env.ts +5 -4
  69. package/templates/apps/walgit/src/store.ts +47 -24
  70. package/templates/apps/walgit/src/usage.ts +404 -0
  71. package/templates/apps/walgit/src/verify.ts +171 -0
  72. package/templates/apps/walgit/src/wal-index.ts +189 -11
  73. package/templates/apps/walgit/tsconfig.json +8 -2
  74. package/templates/apps/walgit/tsconfig.worker.json +24 -0
  75. package/templates/apps/walgit/worker/events-do.ts +259 -0
  76. package/templates/apps/walgit/worker/index.ts +572 -0
  77. package/templates/apps/walgit/wrangler.jsonc +95 -0
  78. package/templates/apps/warehouse/package.json +1 -1
  79. package/templates/infra/modules/cloudflare/index.ts +93 -67
  80. package/templates/infra/modules/cloudflare-access/index.ts +3 -3
  81. package/templates/infra/modules/cloudflare-api/index.ts +144 -32
  82. package/templates/infra/modules/cloudflare-api/registry.json +1 -1
  83. package/templates/infra/modules/cloudflare-email/index.ts +103 -144
  84. package/templates/infra/modules/cloudflare-email/registry.json +1 -1
  85. package/templates/infra/modules/cloudflare-token/index.ts +10 -30
  86. package/templates/infra/modules/cloudflare-token/registry.json +1 -1
  87. package/templates/infra/modules/cloudflare-tunnel/index.ts +3 -3
  88. package/templates/infra/modules/cloudflare-zone/index.ts +2 -2
  89. package/templates/infra/modules/fly/index.ts +158 -35
  90. package/templates/infra/modules/host-file/index.ts +6 -7
  91. package/templates/infra/modules/provision-core/index.ts +21 -15
  92. package/templates/infra/modules/r2/index.ts +38 -55
  93. package/templates/infra/modules/r2/registry.json +1 -1
  94. package/templates/infra/modules/remote-provision/index.ts +1 -3
  95. package/templates/infra/modules/turso/index.ts +45 -7
  96. package/templates/infra/modules/vm-provision/index.ts +10 -3
  97. package/templates/infra/package.json +1 -1
  98. package/templates/infra/src/context.ts +115 -0
  99. package/templates/infra/src/define-module.ts +8 -2
  100. package/templates/infra/src/index.ts +11 -1
  101. package/templates/infra/src/types.ts +72 -3
  102. package/src/commands/add-registry.test.ts +0 -92
  103. package/src/commands/secret.test.ts +0 -717
  104. package/src/commands/vendor-mode.test.ts +0 -183
  105. package/src/infra-types.ts +0 -38
  106. package/src/utils/subtree.test.ts +0 -127
  107. package/templates/apps/inbox/worker/send-op.ts +0 -174
  108. package/templates/apps/walgit/entrypoint.sh +0 -59
  109. package/templates/apps/walgit/fly.toml +0 -52
  110. package/templates/apps/walgit/src/ssh-shell.ts +0 -36
  111. package/templates/apps/walgit/sshd_config +0 -38
@@ -1,717 +0,0 @@
1
- import { afterEach, describe, expect, test } from 'bun:test'
2
- import * as fs from 'node:fs'
3
- import * as os from 'node:os'
4
- import * as path from 'node:path'
5
- import { parse as parseYamlDoc } from 'yaml'
6
-
7
- /**
8
- * Command-level tests for `zbc secret …` (spec: Zabaca/zbc#18).
9
- *
10
- * The CLI runs as a real subprocess against a throwaway project directory, so
11
- * everything is exercised through the public interface: argv in, exit code +
12
- * stdout out, secrets.yaml on disk. The relay, when needed, is the REAL relay
13
- * handler running in-process via Bun.serve — only the browser is simulated.
14
- */
15
-
16
- import { createRelay } from '../../templates/apps/secret-relay/src/relay'
17
- import {
18
- decryptWithDocumentKey,
19
- encryptForChannel,
20
- encryptWithDocumentKey,
21
- generateChannelKeypair,
22
- pairingCode,
23
- } from '../../templates/apps/secret-relay/src/crypto'
24
-
25
- const CLI = path.join(import.meta.dir, '../index.ts')
26
-
27
- const createdRoots: string[] = []
28
-
29
- afterEach(() => {
30
- for (const root of createdRoots.splice(0)) {
31
- fs.rmSync(root, { recursive: true, force: true })
32
- }
33
- })
34
-
35
- /** Minimal zbc project: zbc.config.ts + one environment dir. */
36
- function makeProject(opts: { env?: string; secrets?: string } = {}): string {
37
- const env = opts.env ?? 'production'
38
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'zbc-secret-test-'))
39
- createdRoots.push(root)
40
- fs.writeFileSync(
41
- path.join(root, 'zbc.config.ts'),
42
- `export default { project: 'testproj', environments: ['${env}'] }\n`,
43
- )
44
- fs.writeFileSync(
45
- path.join(root, 'package.json'),
46
- JSON.stringify({ name: 'testproj', workspaces: ['packages/*'], private: true }),
47
- )
48
- const infraDir = path.join(root, 'packages/infra')
49
- fs.mkdirSync(infraDir, { recursive: true })
50
- fs.writeFileSync(path.join(infraDir, 'package.json'), JSON.stringify({ name: 'infra' }))
51
- const envDir = path.join(root, 'packages/infra/environments', env)
52
- fs.mkdirSync(envDir, { recursive: true })
53
- if (opts.secrets !== undefined) {
54
- fs.writeFileSync(path.join(envDir, 'secrets.yaml'), opts.secrets)
55
- }
56
- return root
57
- }
58
-
59
- interface CliProc {
60
- proc: ReturnType<typeof Bun.spawn>
61
- /** Resolves with all captured stdout once the process exits. */
62
- result: Promise<{ exitCode: number; stdout: string; stderr: string }>
63
- /** Waits until stdout matches `re`, returning the first capture group (or whole match). */
64
- waitForStdout(re: RegExp): Promise<string>
65
- }
66
-
67
- /** Spawn the CLI without waiting for exit, so the test can play the browser. */
68
- function spawnCli(cwd: string, args: string[], env: Record<string, string> = {}): CliProc {
69
- const proc = Bun.spawn(['bun', CLI, ...args], {
70
- cwd,
71
- stdout: 'pipe',
72
- stderr: 'pipe',
73
- env: { ...process.env, ...env },
74
- })
75
- let stdoutSoFar = ''
76
- const reader = (proc.stdout as ReadableStream<Uint8Array>).getReader()
77
- const decoder = new TextDecoder()
78
- const waiters: Array<{ re: RegExp; resolve: (m: string) => void }> = []
79
- const capture = (m: RegExpMatchArray): string => m[1] ?? m[0]
80
- const done = (async () => {
81
- while (true) {
82
- const { value, done } = await reader.read()
83
- if (done) break
84
- stdoutSoFar += decoder.decode(value, { stream: true })
85
- for (let i = waiters.length - 1; i >= 0; i--) {
86
- const waiter = waiters[i]!
87
- const m = stdoutSoFar.match(waiter.re)
88
- if (m) {
89
- waiters.splice(i, 1)
90
- waiter.resolve(capture(m))
91
- }
92
- }
93
- }
94
- return stdoutSoFar
95
- })()
96
- return {
97
- proc,
98
- result: (async () => {
99
- const [stdout, stderr, exitCode] = await Promise.all([
100
- done,
101
- new Response(proc.stderr as ReadableStream).text(),
102
- proc.exited,
103
- ])
104
- return { exitCode, stdout, stderr }
105
- })(),
106
- waitForStdout(re: RegExp) {
107
- const m = stdoutSoFar.match(re)
108
- if (m) return Promise.resolve(capture(m))
109
- return new Promise<string>((resolve) => waiters.push({ re, resolve }))
110
- },
111
- }
112
- }
113
-
114
- async function runCli(
115
- cwd: string,
116
- args: string[],
117
- ): Promise<{ exitCode: number; stdout: string; stderr: string }> {
118
- const proc = Bun.spawn(['bun', CLI, ...args], {
119
- cwd,
120
- stdout: 'pipe',
121
- stderr: 'pipe',
122
- env: { ...process.env },
123
- })
124
- const [stdout, stderr, exitCode] = await Promise.all([
125
- new Response(proc.stdout).text(),
126
- new Response(proc.stderr).text(),
127
- proc.exited,
128
- ])
129
- return { exitCode, stdout, stderr }
130
- }
131
-
132
- describe('zbc add secret-relay', () => {
133
- test('scaffolds the app, vendors the cloudflare module, and generates the instance file', async () => {
134
- const root = makeProject()
135
- const result = await runCli(root, [
136
- 'add',
137
- 'secret-relay',
138
- '--account-id',
139
- 'cf-acct-123',
140
- '--no-prompt',
141
- ])
142
- expect(result.exitCode).toBe(0)
143
-
144
- // app package scaffolded
145
- expect(fs.existsSync(path.join(root, 'packages/secret-relay/package.json'))).toBe(true)
146
- expect(fs.existsSync(path.join(root, 'packages/secret-relay/src/relay.ts'))).toBe(true)
147
- // module dependency vendored
148
- expect(fs.existsSync(path.join(root, 'packages/infra/modules/cloudflare/registry.json'))).toBe(
149
- true,
150
- )
151
- // instance file generated — committed declarative state, not an imperative deploy
152
- const instancePath = path.join(root, 'packages/infra/environments/production/secret-relay.ts')
153
- const instance = fs.readFileSync(instancePath, 'utf8')
154
- expect(instance).toContain("name: 'secret-relay'")
155
- expect(instance).toContain("accountId: 'cf-acct-123'")
156
- expect(instance).toContain('cloudflareModule.instance')
157
- // convergence stays in the graph: the command points at apply, not deploys itself
158
- expect(result.stdout).toContain('zbc apply production secret-relay')
159
- })
160
- })
161
-
162
- describe('zbc add auto-requests missing secrets', () => {
163
- test('after add, missing registry-declared secrets are collected via the relay', async () => {
164
- const relay = createRelay()
165
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
166
- try {
167
- const root = makeProject()
168
- // module already vendored (no network), declaring one secret
169
- const modDir = path.join(root, 'packages/infra/modules/turso')
170
- fs.mkdirSync(modDir, { recursive: true })
171
- fs.writeFileSync(
172
- path.join(modDir, 'registry.json'),
173
- JSON.stringify({ name: 'turso', secrets: ['TURSO_API_TOKEN'] }),
174
- )
175
- // project has a relay instance the graph can converge
176
- fs.writeFileSync(
177
- path.join(root, 'packages/infra/environments/production/secret-relay.ts'),
178
- `const id = { parse: (x) => x }
179
- export default {
180
- name: 'secret-relay', moduleName: 'cloudflare', imports: [], config: {},
181
- _definition: { configSchema: id, outputsSchema: id,
182
- apply: async () => ({ deployUrl: 'http://localhost:${server.port}', workerName: 'secret-relay' }) },
183
- }
184
- `,
185
- )
186
-
187
- const cli = spawnCli(root, ['add', 'turso'])
188
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
189
- const url = new URL(channelUrl)
190
- const meta = (await (await fetch(`${url.origin}${url.pathname}/meta`)).json()) as {
191
- keys: string[]
192
- }
193
- expect(meta.keys).toEqual(['TURSO_API_TOKEN'])
194
- await fetch(`${url.origin}${url.pathname}/submission`, {
195
- method: 'POST',
196
- body: JSON.stringify(
197
- await encryptForChannel(
198
- url.hash.slice(1),
199
- JSON.stringify({ TURSO_API_TOKEN: 'tok-from-add' }),
200
- ),
201
- ),
202
- })
203
- const result = await cli.result
204
- expect(result.exitCode).toBe(0)
205
- const written = fs.readFileSync(
206
- path.join(root, 'packages/infra/environments/production/secrets.yaml'),
207
- 'utf8',
208
- )
209
- expect(parseYamlDoc(written).TURSO_API_TOKEN).toBe('tok-from-add')
210
- } finally {
211
- server.stop(true)
212
- }
213
- })
214
-
215
- test('--no-prompt skips the request and just prints what is missing', async () => {
216
- const root = makeProject()
217
- const modDir = path.join(root, 'packages/infra/modules/turso')
218
- fs.mkdirSync(modDir, { recursive: true })
219
- fs.writeFileSync(
220
- path.join(modDir, 'registry.json'),
221
- JSON.stringify({ name: 'turso', secrets: ['TURSO_API_TOKEN'] }),
222
- )
223
- const result = await runCli(root, ['add', 'turso', '--no-prompt'])
224
- expect(result.exitCode).toBe(0)
225
- expect(result.stdout).toContain('TURSO_API_TOKEN')
226
- expect(
227
- fs.existsSync(path.join(root, 'packages/infra/environments/production/secrets.yaml')),
228
- ).toBe(false)
229
- })
230
- })
231
-
232
- describe('zbc secret edit', () => {
233
- test('full sops round-trip: browser edits the decrypted YAML, sops re-encrypts on save', async () => {
234
- const { execSync } = await import('node:child_process')
235
- const keyOut = execSync('age-keygen 2>/dev/null').toString()
236
- const ageSecretKey = keyOut.match(/AGE-SECRET-KEY-\S+/)![0]
237
- const agePublicKey = keyOut.match(/public key: (\S+)/)![1]
238
-
239
- const root = makeProject()
240
- fs.writeFileSync(path.join(root, '.sops.yaml'), `creation_rules:\n - age: ${agePublicKey}\n`)
241
- const secretsPath = path.join(root, 'packages/infra/environments/production/secrets.yaml')
242
- execSync(
243
- `sops --config ${root}/.sops.yaml --filename-override ${secretsPath} -e --input-type yaml --output-type yaml /dev/stdin > ${secretsPath}`,
244
- { input: 'OLD_KEY: old-value\n', env: { ...process.env } },
245
- )
246
-
247
- const relay = createRelay()
248
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
249
- try {
250
- const cli = spawnCli(
251
- root,
252
- ['secret', 'edit', 'production', '--relay', `http://localhost:${server.port}`],
253
- { SOPS_AGE_KEY: ageSecretKey },
254
- )
255
- // editor prints channel URL with a symmetric document key in the fragment
256
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
257
- const url = new URL(channelUrl)
258
- const docKey = url.hash.slice(1)
259
- const base = `${url.origin}${url.pathname}`
260
-
261
- // simulated browser: fetch + decrypt the document, edit it, submit back
262
- const doc = (await (await fetch(`${base}/document`)).json()) as { iv: string; ct: string }
263
- const plaintext = await decryptWithDocumentKey(docKey, doc)
264
- expect(plaintext).toContain('OLD_KEY: old-value')
265
-
266
- const edited = plaintext + 'NEW_KEY: new-value\n'
267
- await fetch(`${base}/submission`, {
268
- method: 'POST',
269
- body: JSON.stringify({ document: await encryptWithDocumentKey(docKey, edited) }),
270
- })
271
-
272
- const result = await cli.result
273
- expect(result.exitCode).toBe(0)
274
-
275
- const onDisk = fs.readFileSync(secretsPath, 'utf8')
276
- expect(onDisk).not.toContain('new-value')
277
- expect(onDisk).toContain('ENC[')
278
- const decrypted = execSync(`sops -d ${secretsPath}`, {
279
- env: { ...process.env, SOPS_AGE_KEY: ageSecretKey },
280
- }).toString()
281
- expect(decrypted).toContain('OLD_KEY: old-value')
282
- expect(decrypted).toContain('NEW_KEY: new-value')
283
- } finally {
284
- server.stop(true)
285
- }
286
- }, 20000)
287
- })
288
-
289
- describe('zbc secret list', () => {
290
- test('reports set vs missing for registry-declared keys, names only — never values', async () => {
291
- const root = makeProject({ secrets: 'TURSO_API_TOKEN: tok-secret-77\nEXTRA_KEY: extra-val\n' })
292
- // a vendored module declaring its required secrets
293
- const modDir = path.join(root, 'packages/infra/modules/turso')
294
- fs.mkdirSync(modDir, { recursive: true })
295
- fs.writeFileSync(
296
- path.join(modDir, 'registry.json'),
297
- JSON.stringify({ name: 'turso', secrets: ['TURSO_API_TOKEN', 'TURSO_ORG'] }),
298
- )
299
-
300
- const result = await runCli(root, ['secret', 'list'])
301
- expect(result.exitCode).toBe(0)
302
- expect(result.stdout).toMatch(/TURSO_API_TOKEN\s+set/)
303
- expect(result.stdout).toMatch(/TURSO_ORG\s+missing/)
304
- expect(result.stdout).toMatch(/EXTRA_KEY\s+set/)
305
- expect(result.stdout).not.toContain('tok-secret-77')
306
- expect(result.stdout).not.toContain('extra-val')
307
- })
308
- })
309
-
310
- describe('zbc secret request', () => {
311
- test('collects a missing key through the relay: browser submits E2E-encrypted, CLI writes secrets.yaml', async () => {
312
- const root = makeProject({ secrets: 'EXISTING: keep-me\n' })
313
- const relay = createRelay()
314
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
315
- try {
316
- const cli = spawnCli(root, [
317
- 'secret',
318
- 'request',
319
- 'TURSO_API_TOKEN',
320
- '--relay',
321
- `http://localhost:${server.port}`,
322
- ])
323
-
324
- // CLI prints the channel URL with the public key in the fragment
325
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
326
- const url = new URL(channelUrl)
327
- const channelPublicKey = url.hash.slice(1)
328
-
329
- // Simulated browser: fetch channel meta, then submit encrypted values
330
- const meta = (await (await fetch(`${url.origin}${url.pathname}/meta`)).json()) as {
331
- keys: string[]
332
- }
333
- expect(meta.keys).toEqual(['TURSO_API_TOKEN'])
334
-
335
- const payload = await encryptForChannel(
336
- channelPublicKey,
337
- JSON.stringify({ TURSO_API_TOKEN: 'tok-new-secret-42' }),
338
- )
339
- const submit = await fetch(`${url.origin}${url.pathname}/submission`, {
340
- method: 'POST',
341
- headers: { 'content-type': 'application/json' },
342
- body: JSON.stringify(payload),
343
- })
344
- expect(submit.ok).toBe(true)
345
-
346
- const result = await cli.result
347
- expect(result.exitCode).toBe(0)
348
- expect(result.stdout).toContain('✓ TURSO_API_TOKEN written to production/secrets.yaml')
349
- // the value never surfaces anywhere observable
350
- expect(result.stdout).not.toContain('tok-new-secret-42')
351
- expect(result.stderr).not.toContain('tok-new-secret-42')
352
-
353
- const written = fs.readFileSync(
354
- path.join(root, 'packages/infra/environments/production/secrets.yaml'),
355
- 'utf8',
356
- )
357
- expect(written).toContain('TURSO_API_TOKEN: tok-new-secret-42')
358
- expect(written).toContain('EXISTING: keep-me')
359
- } finally {
360
- server.stop(true)
361
- }
362
- })
363
-
364
- test('the channel URL serves the request page to the human', async () => {
365
- const relay = createRelay()
366
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
367
- try {
368
- const root = makeProject()
369
- const cli = spawnCli(root, [
370
- 'secret',
371
- 'request',
372
- 'PAGE_KEY',
373
- '--relay',
374
- `http://localhost:${server.port}`,
375
- '--timeout',
376
- '1',
377
- ])
378
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
379
- const url = new URL(channelUrl)
380
- const res = await fetch(`${url.origin}${url.pathname}`)
381
- expect(res.headers.get('content-type')).toContain('text/html')
382
- const html = await res.text()
383
- expect(html.toLowerCase()).toContain('pairing code')
384
- await cli.result
385
- } finally {
386
- server.stop(true)
387
- }
388
- })
389
-
390
- test('channels are single-use: a second submission is rejected and a consumed channel is gone', async () => {
391
- const root = makeProject()
392
- const relay = createRelay()
393
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
394
- try {
395
- const cli = spawnCli(root, [
396
- 'secret',
397
- 'request',
398
- 'ONE_SHOT',
399
- '--relay',
400
- `http://localhost:${server.port}`,
401
- ])
402
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
403
- const url = new URL(channelUrl)
404
- const base = `${url.origin}${url.pathname}`
405
-
406
- const payload = await encryptForChannel(
407
- url.hash.slice(1),
408
- JSON.stringify({ ONE_SHOT: 'first-value' }),
409
- )
410
- expect(
411
- (await fetch(`${base}/submission`, { method: 'POST', body: JSON.stringify(payload) })).ok,
412
- ).toBe(true)
413
-
414
- // second submission: rejected
415
- const second = await fetch(`${base}/submission`, {
416
- method: 'POST',
417
- body: JSON.stringify(
418
- await encryptForChannel(url.hash.slice(1), JSON.stringify({ ONE_SHOT: 'attacker' })),
419
- ),
420
- })
421
- expect(second.status).toBe(409)
422
-
423
- const result = await cli.result
424
- expect(result.exitCode).toBe(0)
425
- const written = fs.readFileSync(
426
- path.join(root, 'packages/infra/environments/production/secrets.yaml'),
427
- 'utf8',
428
- )
429
- expect(written).toContain('ONE_SHOT: first-value')
430
-
431
- // consumed channel is deleted entirely
432
- expect((await fetch(`${base}/meta`)).status).toBe(404)
433
- } finally {
434
- server.stop(true)
435
- }
436
- })
437
-
438
- test('channels expire with the request timeout: a late submission is rejected server-side', async () => {
439
- const root = makeProject()
440
- const relay = createRelay()
441
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
442
- try {
443
- const cli = spawnCli(root, [
444
- 'secret',
445
- 'request',
446
- 'TOO_LATE',
447
- '--relay',
448
- `http://localhost:${server.port}`,
449
- '--timeout',
450
- '1',
451
- ])
452
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
453
- const url = new URL(channelUrl)
454
- const publicKey = url.hash.slice(1)
455
- await cli.result // CLI has given up; channel TTL has passed
456
-
457
- const late = await fetch(`${url.origin}${url.pathname}/submission`, {
458
- method: 'POST',
459
- body: JSON.stringify(await encryptForChannel(publicKey, JSON.stringify({ TOO_LATE: 'x' }))),
460
- })
461
- expect(late.ok).toBe(false)
462
- } finally {
463
- server.stop(true)
464
- }
465
- })
466
-
467
- test('a submission that fails decryption fails the request loudly and writes nothing', async () => {
468
- const root = makeProject()
469
- const relay = createRelay()
470
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
471
- try {
472
- const cli = spawnCli(root, [
473
- 'secret',
474
- 'request',
475
- 'TAMPERED',
476
- '--relay',
477
- `http://localhost:${server.port}`,
478
- ])
479
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
480
- const url = new URL(channelUrl)
481
-
482
- // encrypt to the WRONG key — as an interloper without the fragment would
483
- const { publicKeyB64: wrongKey } = await generateChannelKeypair()
484
- await fetch(`${url.origin}${url.pathname}/submission`, {
485
- method: 'POST',
486
- body: JSON.stringify(
487
- await encryptForChannel(wrongKey, JSON.stringify({ TAMPERED: 'evil' })),
488
- ),
489
- })
490
-
491
- const result = await cli.result
492
- expect(result.exitCode).not.toBe(0)
493
- expect((result.stdout + result.stderr).toLowerCase()).toMatch(/decrypt|tamper/)
494
- expect(
495
- fs.existsSync(path.join(root, 'packages/infra/environments/production/secrets.yaml')),
496
- ).toBe(false)
497
- } finally {
498
- server.stop(true)
499
- }
500
- })
501
-
502
- test('CLI prints a pairing code derived from the channel public key in the URL fragment', async () => {
503
- const root = makeProject()
504
- const relay = createRelay()
505
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
506
- try {
507
- const cli = spawnCli(root, [
508
- 'secret',
509
- 'request',
510
- 'PAIRED',
511
- '--relay',
512
- `http://localhost:${server.port}`,
513
- '--timeout',
514
- '1',
515
- ])
516
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
517
- const fragmentKey = new URL(channelUrl).hash.slice(1)
518
-
519
- // the code the browser page would derive from the fragment must be printed by the CLI
520
- const expected = await pairingCode(fragmentKey)
521
- expect(expected).toMatch(/^[A-Z2-9]{2}-[A-Z2-9]{2}$/)
522
- const printed = await cli.waitForStdout(/[Pp]airing code:\s+(\S+)/)
523
- expect(printed).toBe(expected)
524
- await cli.result
525
- } finally {
526
- server.stop(true)
527
- }
528
- })
529
-
530
- test('with .sops.yaml present, auto-creates secrets.yaml encrypted — value never lands in plaintext', async () => {
531
- const root = makeProject() // no secrets.yaml yet
532
- const { execSync } = await import('node:child_process')
533
- const keyOut = execSync('age-keygen 2>/dev/null').toString()
534
- const ageSecretKey = keyOut.match(/AGE-SECRET-KEY-\S+/)![0]
535
- const agePublicKey = keyOut.match(/public key: (\S+)/)![1]
536
- fs.writeFileSync(path.join(root, '.sops.yaml'), `creation_rules:\n - age: ${agePublicKey}\n`)
537
-
538
- const relay = createRelay()
539
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
540
- try {
541
- const cli = spawnCli(root, [
542
- 'secret',
543
- 'request',
544
- 'ENCRYPTED_KEY',
545
- '--relay',
546
- `http://localhost:${server.port}`,
547
- ])
548
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
549
- const url = new URL(channelUrl)
550
- await fetch(`${url.origin}${url.pathname}/submission`, {
551
- method: 'POST',
552
- body: JSON.stringify(
553
- await encryptForChannel(
554
- url.hash.slice(1),
555
- JSON.stringify({ ENCRYPTED_KEY: 'sekrit-99' }),
556
- ),
557
- ),
558
- })
559
- const result = await cli.result
560
- expect(result.exitCode).toBe(0)
561
-
562
- const secretsPath = path.join(root, 'packages/infra/environments/production/secrets.yaml')
563
- const onDisk = fs.readFileSync(secretsPath, 'utf8')
564
- expect(onDisk).not.toContain('sekrit-99')
565
- expect(onDisk).toContain('sops')
566
- expect(onDisk).toContain('ENC[')
567
-
568
- const decrypted = execSync(`sops -d ${secretsPath}`, {
569
- env: { ...process.env, SOPS_AGE_KEY: ageSecretKey },
570
- }).toString()
571
- expect(decrypted).toContain('ENCRYPTED_KEY: sekrit-99')
572
- } finally {
573
- server.stop(true)
574
- }
575
- })
576
-
577
- test('trims pasted whitespace; an all-whitespace value fails the request and writes nothing', async () => {
578
- const relay = createRelay()
579
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
580
- try {
581
- // trailing newline (the classic paste bug) is trimmed
582
- const root = makeProject()
583
- const cli = spawnCli(root, [
584
- 'secret',
585
- 'request',
586
- 'PADDED',
587
- '--relay',
588
- `http://localhost:${server.port}`,
589
- ])
590
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
591
- const url = new URL(channelUrl)
592
- await fetch(`${url.origin}${url.pathname}/submission`, {
593
- method: 'POST',
594
- body: JSON.stringify(
595
- await encryptForChannel(url.hash.slice(1), JSON.stringify({ PADDED: ' tok-pad\n' })),
596
- ),
597
- })
598
- expect((await cli.result).exitCode).toBe(0)
599
- const written = fs.readFileSync(
600
- path.join(root, 'packages/infra/environments/production/secrets.yaml'),
601
- 'utf8',
602
- )
603
- expect(parseYamlDoc(written).PADDED).toBe('tok-pad')
604
-
605
- // all-whitespace value: request fails, nothing written
606
- const root2 = makeProject()
607
- const cli2 = spawnCli(root2, [
608
- 'secret',
609
- 'request',
610
- 'BLANK',
611
- '--relay',
612
- `http://localhost:${server.port}`,
613
- ])
614
- const channelUrl2 = await cli2.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
615
- const url2 = new URL(channelUrl2)
616
- await fetch(`${url2.origin}${url2.pathname}/submission`, {
617
- method: 'POST',
618
- body: JSON.stringify(
619
- await encryptForChannel(url2.hash.slice(1), JSON.stringify({ BLANK: ' \n' })),
620
- ),
621
- })
622
- const result2 = await cli2.result
623
- expect(result2.exitCode).not.toBe(0)
624
- expect(
625
- fs.existsSync(path.join(root2, 'packages/infra/environments/production/secrets.yaml')),
626
- ).toBe(false)
627
- } finally {
628
- server.stop(true)
629
- }
630
- })
631
-
632
- test('without --relay and no secret-relay instance, errors telling you to run zbc add secret-relay', async () => {
633
- const root = makeProject()
634
- const result = await runCli(root, ['secret', 'request', 'SOME_KEY'])
635
- expect(result.exitCode).not.toBe(0)
636
- expect(result.stdout + result.stderr).toContain('zbc add secret-relay')
637
- })
638
-
639
- test('resolves the relay by converging the secret-relay instance and reading its deployUrl output', async () => {
640
- const relay = createRelay()
641
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
642
- try {
643
- const root = makeProject()
644
- // A minimal instance the engine can discover and apply: its `apply`
645
- // "deploys" nothing and emits the in-process relay's URL as deployUrl.
646
- fs.writeFileSync(
647
- path.join(root, 'packages/infra/environments/production/secret-relay.ts'),
648
- `const id = { parse: (x) => x }
649
- export default {
650
- name: 'secret-relay',
651
- moduleName: 'cloudflare',
652
- imports: [],
653
- config: {},
654
- _definition: {
655
- configSchema: id,
656
- outputsSchema: id,
657
- apply: async () => ({ deployUrl: 'http://localhost:${server.port}', workerName: 'secret-relay' }),
658
- },
659
- }
660
- `,
661
- )
662
-
663
- const cli = spawnCli(root, ['secret', 'request', 'VIA_GRAPH'])
664
- const channelUrl = await cli.waitForStdout(/(http:\/\/\S+\/channels\/\S+#\S+)/)
665
- const url = new URL(channelUrl)
666
- await fetch(`${url.origin}${url.pathname}/submission`, {
667
- method: 'POST',
668
- body: JSON.stringify(
669
- await encryptForChannel(url.hash.slice(1), JSON.stringify({ VIA_GRAPH: 'graph-val' })),
670
- ),
671
- })
672
- const result = await cli.result
673
- expect(result.exitCode).toBe(0)
674
- const written = fs.readFileSync(
675
- path.join(root, 'packages/infra/environments/production/secrets.yaml'),
676
- 'utf8',
677
- )
678
- expect(parseYamlDoc(written).VIA_GRAPH).toBe('graph-val')
679
- } finally {
680
- server.stop(true)
681
- }
682
- })
683
-
684
- test('times out when nobody submits: non-zero exit, names the still-missing keys', async () => {
685
- const root = makeProject()
686
- const relay = createRelay()
687
- const server = Bun.serve({ port: 0, fetch: relay.fetch })
688
- try {
689
- const result = await runCli(root, [
690
- 'secret',
691
- 'request',
692
- 'NEVER_ARRIVES',
693
- '--relay',
694
- `http://localhost:${server.port}`,
695
- '--timeout',
696
- '1',
697
- ])
698
- expect(result.exitCode).not.toBe(0)
699
- expect(result.stdout + result.stderr).toContain('still missing: NEVER_ARRIVES')
700
- } finally {
701
- server.stop(true)
702
- }
703
- })
704
-
705
- test('skips keys that are already set: exit 0, reports "already set", never needs a relay', async () => {
706
- const root = makeProject({ secrets: 'TURSO_API_TOKEN: tok-abc123\n' })
707
-
708
- const result = await runCli(root, ['secret', 'request', 'TURSO_API_TOKEN'])
709
-
710
- expect(result.exitCode).toBe(0)
711
- expect(result.stdout).toContain('TURSO_API_TOKEN')
712
- expect(result.stdout.toLowerCase()).toContain('already set')
713
- // the value must never surface on stdout/stderr
714
- expect(result.stdout).not.toContain('tok-abc123')
715
- expect(result.stderr).not.toContain('tok-abc123')
716
- })
717
- })