@zabaca/zbc 0.7.0 → 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
 
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "secret-relay",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "zbc Secret Relay — brokers E2E-encrypted Secret Requests between the CLI and a browser",
6
+ "devDependencies": {
7
+ "wrangler": "^4.0.0",
8
+ "@cloudflare/workers-types": "^4.20250620.0"
9
+ }
10
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "secret-relay",
3
+ "kind": "app",
4
+ "description": "Secret Relay: a tiny permanent Cloudflare Worker that brokers Secret Requests between the zbc CLI and a human's browser. Carries only E2E-encrypted ciphertext (ADR-0003).",
5
+ "targetDir": "packages/secret-relay",
6
+ "modules": ["cloudflare"],
7
+ "secrets": ["CLOUDFLARE_API_TOKEN"],
8
+ "instanceFile": "secret-relay.ts",
9
+ "instanceTemplate": "import { cloudflareModule } from '../../modules/cloudflare'\n\nexport default cloudflareModule.instance({\n name: 'secret-relay',\n config: {\n workdir: 'packages/secret-relay',\n accountId: '{{ACCOUNT_ID}}',\n workerName: '{{PROJECT_NAME}}-secret-relay',\n },\n})\n",
10
+ "instructions": "The relay is permanent, single-tenant infrastructure: deploy it once (production) and every environment's `zbc secret request` uses it. Deploying needs CLOUDFLARE_API_TOKEN in production/secrets.yaml (Workers Scripts: Edit scope)."
11
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * E2E crypto for Secret Requests (ADR-0003): the CLI generates an ephemeral
3
+ * ECDH P-256 keypair per Channel; the public key travels only in the URL
4
+ * fragment. The browser generates its own ephemeral pair, derives an AES-GCM
5
+ * key via ECDH, and encrypts. The relay only ever sees `SubmissionPayload`
6
+ * ciphertext. WebCrypto-only — runs identically in browsers, workerd, and Bun.
7
+ */
8
+
9
+ export interface SubmissionPayload {
10
+ /** Browser's ephemeral public key (raw P-256 point, base64url) */
11
+ epk: string
12
+ /** AES-GCM IV (base64url) */
13
+ iv: string
14
+ /** Ciphertext (base64url) */
15
+ ct: string
16
+ }
17
+
18
+ function toB64url(buf: ArrayBuffer | Uint8Array): string {
19
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
20
+ let bin = ''
21
+ for (const b of bytes) bin += String.fromCharCode(b)
22
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
23
+ }
24
+
25
+ function fromB64url(s: string): Uint8Array {
26
+ const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'))
27
+ const bytes = new Uint8Array(bin.length)
28
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
29
+ return bytes
30
+ }
31
+
32
+ const ECDH = { name: 'ECDH', namedCurve: 'P-256' } as const
33
+
34
+ export async function generateChannelKeypair(): Promise<{
35
+ publicKeyB64: string
36
+ privateKey: CryptoKey
37
+ }> {
38
+ const pair = await crypto.subtle.generateKey(ECDH, false, ['deriveKey'])
39
+ const raw = await crypto.subtle.exportKey('raw', pair.publicKey)
40
+ return { publicKeyB64: toB64url(raw), privateKey: pair.privateKey }
41
+ }
42
+
43
+ async function deriveAesKey(privateKey: CryptoKey, peerPublicRaw: Uint8Array): Promise<CryptoKey> {
44
+ const peer = await crypto.subtle.importKey('raw', peerPublicRaw as BufferSource, ECDH, false, [])
45
+ return crypto.subtle.deriveKey(
46
+ { name: 'ECDH', public: peer },
47
+ privateKey,
48
+ { name: 'AES-GCM', length: 256 },
49
+ false,
50
+ ['encrypt', 'decrypt'],
51
+ )
52
+ }
53
+
54
+ /** Browser side: encrypt `plaintext` to the channel's public key. */
55
+ export async function encryptForChannel(
56
+ channelPublicKeyB64: string,
57
+ plaintext: string,
58
+ ): Promise<SubmissionPayload> {
59
+ const pair = await crypto.subtle.generateKey(ECDH, false, ['deriveKey'])
60
+ const aes = await deriveAesKey(pair.privateKey, fromB64url(channelPublicKeyB64))
61
+ const iv = crypto.getRandomValues(new Uint8Array(12))
62
+ const ct = await crypto.subtle.encrypt(
63
+ { name: 'AES-GCM', iv },
64
+ aes,
65
+ new TextEncoder().encode(plaintext),
66
+ )
67
+ const epk = await crypto.subtle.exportKey('raw', pair.publicKey)
68
+ return { epk: toB64url(epk), iv: toB64url(iv), ct: toB64url(ct) }
69
+ }
70
+
71
+ export interface EncryptedDocument {
72
+ /** AES-GCM IV (base64url) */
73
+ iv: string
74
+ /** Ciphertext (base64url) */
75
+ ct: string
76
+ }
77
+
78
+ /**
79
+ * Editor mode carries the document CLI→browser and back, so both ends need
80
+ * the same key: a symmetric AES-GCM key generated by the CLI and carried in
81
+ * the URL fragment (never sent to the server), mirroring the ECDH flow's
82
+ * fragment discipline.
83
+ */
84
+ export async function generateDocumentKey(): Promise<string> {
85
+ return toB64url(crypto.getRandomValues(new Uint8Array(32)))
86
+ }
87
+
88
+ async function importDocumentKey(keyB64: string): Promise<CryptoKey> {
89
+ return crypto.subtle.importKey('raw', fromB64url(keyB64) as BufferSource, 'AES-GCM', false, [
90
+ 'encrypt',
91
+ 'decrypt',
92
+ ])
93
+ }
94
+
95
+ export async function encryptWithDocumentKey(
96
+ keyB64: string,
97
+ plaintext: string,
98
+ ): Promise<EncryptedDocument> {
99
+ const key = await importDocumentKey(keyB64)
100
+ const iv = crypto.getRandomValues(new Uint8Array(12))
101
+ const ct = await crypto.subtle.encrypt(
102
+ { name: 'AES-GCM', iv },
103
+ key,
104
+ new TextEncoder().encode(plaintext),
105
+ )
106
+ return { iv: toB64url(iv), ct: toB64url(ct) }
107
+ }
108
+
109
+ export async function decryptWithDocumentKey(
110
+ keyB64: string,
111
+ doc: EncryptedDocument,
112
+ ): Promise<string> {
113
+ const key = await importDocumentKey(keyB64)
114
+ const pt = await crypto.subtle.decrypt(
115
+ { name: 'AES-GCM', iv: fromB64url(doc.iv) as BufferSource },
116
+ key,
117
+ fromB64url(doc.ct) as BufferSource,
118
+ )
119
+ return new TextDecoder().decode(pt)
120
+ }
121
+
122
+ /**
123
+ * Short human-checkable code derived from the channel public key. The CLI
124
+ * prints it; the page derives the same from the URL fragment. A visual match
125
+ * confirms the human is answering the request they think they are.
126
+ * Alphabet omits 0/O/1/I to stay unambiguous when read aloud.
127
+ */
128
+ export async function pairingCode(channelPublicKeyB64: string): Promise<string> {
129
+ const digest = await crypto.subtle.digest(
130
+ 'SHA-256',
131
+ fromB64url(channelPublicKeyB64) as BufferSource,
132
+ )
133
+ const bytes = new Uint8Array(digest)
134
+ const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
135
+ const chars = Array.from({ length: 4 }, (_, i) => alphabet[(bytes[i] ?? 0) % alphabet.length])
136
+ return `${chars[0]}${chars[1]}-${chars[2]}${chars[3]}`
137
+ }
138
+
139
+ /** CLI side: decrypt a browser submission with the channel's private key. */
140
+ export async function decryptSubmission(
141
+ privateKey: CryptoKey,
142
+ payload: SubmissionPayload,
143
+ ): Promise<string> {
144
+ const aes = await deriveAesKey(privateKey, fromB64url(payload.epk))
145
+ const pt = await crypto.subtle.decrypt(
146
+ { name: 'AES-GCM', iv: fromB64url(payload.iv) as BufferSource },
147
+ aes,
148
+ fromB64url(payload.ct) as BufferSource,
149
+ )
150
+ return new TextDecoder().decode(pt)
151
+ }