@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,173 @@
1
+ /**
2
+ * The Secret Request page: fetches channel meta, shows the pairing code
3
+ * (derived from the URL fragment — the channel public key the server never
4
+ * sees), and encrypts submitted values in-browser before POSTing.
5
+ *
6
+ * The inline script mirrors the ECDH P-256 + AES-GCM suite and pairing-code
7
+ * derivation in crypto.ts; if you change one, change both.
8
+ */
9
+ export function requestPageHtml(): string {
10
+ return `<!doctype html>
11
+ <html lang="en">
12
+ <head>
13
+ <meta charset="utf-8">
14
+ <meta name="viewport" content="width=device-width, initial-scale=1">
15
+ <title>Secret Request</title>
16
+ <style>
17
+ :root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
18
+ body { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; line-height: 1.5; }
19
+ .code { font-size: 2rem; font-family: ui-monospace, monospace; letter-spacing: .1em; }
20
+ label { display: block; margin-top: 1rem; font-weight: 600; }
21
+ input { width: 100%; padding: .5rem; font-family: ui-monospace, monospace; }
22
+ textarea { width: 100%; min-height: 20rem; padding: .5rem; font-family: ui-monospace, monospace; white-space: pre; }
23
+ button { margin-top: 1.5rem; padding: .6rem 1.4rem; font-size: 1rem; cursor: pointer; }
24
+ .muted { opacity: .7; }
25
+ #status { margin-top: 1rem; font-weight: 600; }
26
+ </style>
27
+ </head>
28
+ <body>
29
+ <h1>Secret Request</h1>
30
+ <p>Pairing code — confirm it matches your terminal before pasting anything:</p>
31
+ <p class="code" id="pairing">…</p>
32
+ <p class="muted" id="context"></p>
33
+ <form id="form" hidden>
34
+ <div id="fields"></div>
35
+ <button type="submit">Submit securely</button>
36
+ </form>
37
+ <p id="status"></p>
38
+ <script>
39
+ const b64u = {
40
+ to(buf) {
41
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
42
+ let s = ''
43
+ for (const b of bytes) s += String.fromCharCode(b)
44
+ return btoa(s).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')
45
+ },
46
+ from(s) {
47
+ const bin = atob(s.replace(/-/g, '+').replace(/_/g, '/'))
48
+ const bytes = new Uint8Array(bin.length)
49
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
50
+ return bytes
51
+ },
52
+ }
53
+ const ECDH = { name: 'ECDH', namedCurve: 'P-256' }
54
+
55
+ async function pairingCode(pubB64) {
56
+ const digest = await crypto.subtle.digest('SHA-256', b64u.from(pubB64))
57
+ const bytes = new Uint8Array(digest)
58
+ const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
59
+ const c = (i) => alphabet[bytes[i] % alphabet.length]
60
+ return c(0) + c(1) + '-' + c(2) + c(3)
61
+ }
62
+
63
+ async function encryptForChannel(pubB64, plaintext) {
64
+ const pair = await crypto.subtle.generateKey(ECDH, false, ['deriveKey'])
65
+ const peer = await crypto.subtle.importKey('raw', b64u.from(pubB64), ECDH, false, [])
66
+ const aes = await crypto.subtle.deriveKey(
67
+ { name: 'ECDH', public: peer }, pair.privateKey,
68
+ { name: 'AES-GCM', length: 256 }, false, ['encrypt'])
69
+ const iv = crypto.getRandomValues(new Uint8Array(12))
70
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, aes, new TextEncoder().encode(plaintext))
71
+ const epk = await crypto.subtle.exportKey('raw', pair.publicKey)
72
+ return { epk: b64u.to(epk), iv: b64u.to(iv), ct: b64u.to(ct) }
73
+ }
74
+
75
+ async function importDocKey(keyB64) {
76
+ return crypto.subtle.importKey('raw', b64u.from(keyB64), 'AES-GCM', false, ['encrypt', 'decrypt'])
77
+ }
78
+ async function decryptDocument(keyB64, doc) {
79
+ const key = await importDocKey(keyB64)
80
+ const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64u.from(doc.iv) }, key, b64u.from(doc.ct))
81
+ return new TextDecoder().decode(pt)
82
+ }
83
+ async function encryptDocument(keyB64, plaintext) {
84
+ const key = await importDocKey(keyB64)
85
+ const iv = crypto.getRandomValues(new Uint8Array(12))
86
+ const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext))
87
+ return { iv: b64u.to(iv), ct: b64u.to(ct) }
88
+ }
89
+
90
+ async function editorMode(fragmentKey, status) {
91
+ const doc = await (await fetch(location.pathname + '/document')).json()
92
+ let plaintext
93
+ try { plaintext = await decryptDocument(fragmentKey, doc) }
94
+ catch { status.textContent = 'Could not decrypt — reopen the exact URL from your terminal.'; return }
95
+
96
+ const fields = document.getElementById('fields')
97
+ const textarea = document.createElement('textarea')
98
+ textarea.value = plaintext
99
+ textarea.spellcheck = false
100
+ fields.appendChild(textarea)
101
+ const form = document.getElementById('form')
102
+ form.querySelector('button').textContent = 'Save securely'
103
+ form.hidden = false
104
+ form.addEventListener('submit', async (e) => {
105
+ e.preventDefault()
106
+ const res = await fetch(location.pathname + '/submission', {
107
+ method: 'POST',
108
+ headers: { 'content-type': 'application/json' },
109
+ body: JSON.stringify({ document: await encryptDocument(fragmentKey, textarea.value) }),
110
+ })
111
+ if (res.ok) {
112
+ form.hidden = true
113
+ status.textContent = 'Saved. You can close this tab — sops re-encrypts from here.'
114
+ } else {
115
+ status.textContent = 'Save rejected (' + res.status + ') — the session may have expired.'
116
+ }
117
+ })
118
+ }
119
+
120
+ async function main() {
121
+ const publicKey = location.hash.slice(1)
122
+ const status = document.getElementById('status')
123
+ if (!publicKey) { status.textContent = 'Missing key fragment — reopen the exact URL from your terminal.'; return }
124
+ document.getElementById('pairing').textContent = await pairingCode(publicKey)
125
+
126
+ const meta = await (await fetch(location.pathname + '/meta')).json()
127
+ if (meta.error) { status.textContent = 'This request has expired or was already answered.'; return }
128
+ document.getElementById('context').textContent =
129
+ 'Environment: ' + (meta.env || 'unknown') + (meta.reason ? ' — ' + meta.reason : '')
130
+
131
+ if (meta.mode === 'editor') { await editorMode(publicKey, status); return }
132
+
133
+ const fields = document.getElementById('fields')
134
+ for (const key of meta.keys) {
135
+ const label = document.createElement('label')
136
+ label.textContent = key
137
+ const input = document.createElement('input')
138
+ input.type = 'password'
139
+ input.autocomplete = 'off'
140
+ input.spellcheck = false
141
+ input.dataset.key = key
142
+ input.required = true
143
+ label.appendChild(input)
144
+ fields.appendChild(label)
145
+ }
146
+ const form = document.getElementById('form')
147
+ form.hidden = false
148
+ form.addEventListener('submit', async (e) => {
149
+ e.preventDefault()
150
+ const values = {}
151
+ for (const input of fields.querySelectorAll('input')) {
152
+ if (!input.value.trim()) { status.textContent = input.dataset.key + ' is empty.'; return }
153
+ values[input.dataset.key] = input.value
154
+ }
155
+ const payload = await encryptForChannel(publicKey, JSON.stringify(values))
156
+ const res = await fetch(location.pathname + '/submission', {
157
+ method: 'POST',
158
+ headers: { 'content-type': 'application/json' },
159
+ body: JSON.stringify(payload),
160
+ })
161
+ if (res.ok) {
162
+ form.hidden = true
163
+ status.textContent = 'Delivered. You can close this tab — the terminal has it from here.'
164
+ } else {
165
+ status.textContent = 'Submission rejected (' + res.status + ') — the request may have expired or already been answered.'
166
+ }
167
+ })
168
+ }
169
+ main()
170
+ </script>
171
+ </body>
172
+ </html>`
173
+ }
@@ -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
+ }