@zabaca/zbc 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,174 @@
1
+ import type { Inbox } from './inbox-do'
2
+ import { type MailEnv, emitWebhook, makeSnippet, newId, normalizeMsgId, sendMail } from './shared'
3
+
4
+ /**
5
+ * The one send operation, shared by POST /api/send and the MCP send_email
6
+ * tool (a Worker cannot fetch its own routes, so this is a function, not a
7
+ * self-request). Validates, dispatches now or queues for the DO alarm
8
+ * (sendAt), records the outbound row, and emits the message.sent webhook.
9
+ */
10
+
11
+ export interface SendBody {
12
+ to: string
13
+ subject: string
14
+ text?: string
15
+ html?: string
16
+ from?: string
17
+ /** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
18
+ inReplyTo?: string
19
+ /**
20
+ * ISO timestamp: instead of sending now, queue the message for the DO
21
+ * alarm to dispatch at (or shortly after) this time.
22
+ */
23
+ sendAt?: string
24
+ }
25
+
26
+ export interface SendEnv extends MailEnv {
27
+ DEFAULT_FROM?: string
28
+ }
29
+
30
+ export interface SendOutcome {
31
+ status: number
32
+ body: Record<string, unknown>
33
+ }
34
+
35
+ export async function performSend(
36
+ env: SendEnv,
37
+ stub: DurableObjectStub<Inbox>,
38
+ body: SendBody,
39
+ ): Promise<SendOutcome> {
40
+ if (!body.to || !body.subject || (!body.text && !body.html)) {
41
+ return { status: 400, body: { error: 'required: to, subject, and text or html' } }
42
+ }
43
+ const from = body.from ?? env.DEFAULT_FROM
44
+ if (!from) {
45
+ return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or pass from)' } }
46
+ }
47
+
48
+ // Email Sending only accepts whitelisted custom headers (a Message-ID of
49
+ // our own is rejected), so the wire Message-ID is provider-chosen and
50
+ // unknown to us. We store a synthetic one for OUR send chain; recipient
51
+ // replies thread via the subject+participant fallback.
52
+ const id = newId()
53
+ const messageId = `${id}@${from.split('@')[1] ?? 'localhost'}`
54
+ const inReplyTo = normalizeMsgId(body.inReplyTo)
55
+ const text = body.text ?? ''
56
+ const snippet = makeSnippet(text, body.html ?? '')
57
+
58
+ // sendAt → queue for the DO alarm instead of dispatching now.
59
+ if (body.sendAt !== undefined) {
60
+ const at = new Date(body.sendAt)
61
+ if (Number.isNaN(at.getTime())) {
62
+ return { status: 400, body: { error: 'sendAt is not a valid date' } }
63
+ }
64
+ await stub.insert({
65
+ id,
66
+ status: 'scheduled',
67
+ scheduled_at: at.toISOString(),
68
+ direction: 'outbound',
69
+ in_reply_to: inReplyTo,
70
+ message_id: messageId,
71
+ from_addr: from,
72
+ to_addr: body.to,
73
+ subject: body.subject,
74
+ date: at.toISOString(),
75
+ snippet,
76
+ text_body: text,
77
+ html_body: body.html ?? '',
78
+ r2_key: '',
79
+ attachments_json: '[]',
80
+ size: text.length + (body.html?.length ?? 0),
81
+ })
82
+ return { status: 202, body: { ok: true, id, status: 'scheduled', sendAt: at.toISOString() } }
83
+ }
84
+
85
+ try {
86
+ await sendMail(env, {
87
+ from,
88
+ to: body.to,
89
+ subject: body.subject,
90
+ text: body.text,
91
+ html: body.html,
92
+ inReplyTo,
93
+ })
94
+ } catch (err) {
95
+ return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
96
+ }
97
+
98
+ // Record the outbound message so the inbox shows both sides of a
99
+ // conversation. No raw MIME (we never see the provider's final wire form),
100
+ // so r2_key stays empty and /raw 404s for these.
101
+ const { threadId } = await stub.insert({
102
+ id,
103
+ direction: 'outbound',
104
+ in_reply_to: inReplyTo,
105
+ message_id: messageId,
106
+ from_addr: from,
107
+ to_addr: body.to,
108
+ subject: body.subject,
109
+ date: new Date().toISOString(),
110
+ snippet,
111
+ text_body: text,
112
+ html_body: body.html ?? '',
113
+ r2_key: '',
114
+ attachments_json: '[]',
115
+ size: text.length + (body.html?.length ?? 0),
116
+ })
117
+ await emitWebhook(env, 'message.sent', {
118
+ id,
119
+ threadId,
120
+ from,
121
+ to: body.to,
122
+ subject: body.subject,
123
+ snippet,
124
+ direction: 'outbound',
125
+ })
126
+ return { status: 200, body: { ok: true, id, from, to: body.to, messageId, threadId } }
127
+ }
128
+
129
+ /** Send an existing draft: validate completeness, dispatch, flip to sent. */
130
+ export async function performDraftSend(
131
+ env: SendEnv,
132
+ stub: DurableObjectStub<Inbox>,
133
+ draftId: string,
134
+ ): Promise<SendOutcome> {
135
+ const draft = await stub.get(draftId)
136
+ if (!draft || draft.status !== 'draft') return { status: 404, body: { error: 'not a draft' } }
137
+ const from = draft.from_addr || env.DEFAULT_FROM
138
+ if (!from) {
139
+ return { status: 400, body: { error: 'no from address (set DEFAULT_FROM or the draft from)' } }
140
+ }
141
+ if (!draft.to_addr || !draft.subject || (!draft.text_body && !draft.html_body)) {
142
+ return { status: 400, body: { error: 'draft incomplete: needs to, subject, and text or html' } }
143
+ }
144
+ try {
145
+ await sendMail(env, {
146
+ from,
147
+ to: draft.to_addr,
148
+ subject: draft.subject,
149
+ text: draft.text_body || undefined,
150
+ html: draft.html_body || undefined,
151
+ inReplyTo: draft.in_reply_to,
152
+ })
153
+ } catch (err) {
154
+ return { status: 502, body: { error: `send failed: ${(err as Error).message}` } }
155
+ }
156
+ // Persist the from that was actually used (may have come from
157
+ // DEFAULT_FROM), then flip the row to sent — thread resolves NOW.
158
+ if (from !== draft.from_addr) await stub.updateDraft(draftId, { from_addr: from })
159
+ const sent = await stub.markDraftSent(draftId, new Date().toISOString())
160
+ if (!sent) return { status: 500, body: { error: 'draft vanished during send' } }
161
+ await emitWebhook(env, 'message.sent', {
162
+ id: draftId,
163
+ threadId: sent.threadId,
164
+ from,
165
+ to: draft.to_addr,
166
+ subject: draft.subject,
167
+ snippet: draft.snippet,
168
+ direction: 'outbound',
169
+ })
170
+ return {
171
+ status: 200,
172
+ body: { ok: true, id: draftId, from, to: draft.to_addr, threadId: sent.threadId },
173
+ }
174
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Helpers shared by the Worker entry (index.ts) and the Inbox Durable Object
3
+ * (inbox-do.ts — its alarm() dispatches scheduled sends). Lives apart from
4
+ * both to avoid an import cycle.
5
+ */
6
+
7
+ /**
8
+ * Email Service send binding (the NEW object-based API, not the legacy
9
+ * EmailMessage one). The legacy `new EmailMessage(from, to, raw)` path routes
10
+ * through Email Routing and only delivers to VERIFIED destination addresses;
11
+ * the object form goes through Email Sending and accepts any recipient as
12
+ * long as the From domain is onboarded.
13
+ */
14
+ export interface SendEmailBinding {
15
+ send(message: {
16
+ from: string
17
+ to: string
18
+ subject: string
19
+ text?: string
20
+ html?: string
21
+ headers?: Record<string, string>
22
+ }): Promise<unknown>
23
+ }
24
+
25
+ /** The env slice mail dispatch + webhooks need (subset of the worker Env). */
26
+ export interface MailEnv {
27
+ EMAIL: SendEmailBinding
28
+ WEBHOOK_URL?: string
29
+ WEBHOOK_SECRET?: string
30
+ }
31
+
32
+ /** Time-ordered id: ms timestamp (base36, padded) + random suffix. Sortable as TEXT. */
33
+ export function newId(): string {
34
+ const time = Date.now().toString(36).padStart(9, '0')
35
+ const rand = crypto.getRandomValues(new Uint8Array(8))
36
+ const suffix = Array.from(rand, (b) => b.toString(36).padStart(2, '0'))
37
+ .join('')
38
+ .slice(0, 12)
39
+ return `${time}-${suffix}`
40
+ }
41
+
42
+ /**
43
+ * Normalize an RFC 5322 Message-ID to its bare form (no angle brackets or
44
+ * whitespace) so stored ids and In-Reply-To references compare equal.
45
+ */
46
+ export function normalizeMsgId(id: string | undefined | null): string {
47
+ return (id ?? '').replace(/[\s<>]/g, '')
48
+ }
49
+
50
+ /** First 200 chars of the text (or tag-stripped html) body. */
51
+ export function makeSnippet(text: string, html: string): string {
52
+ return (text || html.replace(/<[^>]+>/g, ' ')).replace(/\s+/g, ' ').trim().slice(0, 200)
53
+ }
54
+
55
+ /**
56
+ * Dispatch via the Email Sending binding. In-Reply-To/References are the only
57
+ * threading headers Cloudflare accepts (a custom Message-ID is rejected).
58
+ */
59
+ export async function sendMail(
60
+ env: MailEnv,
61
+ msg: {
62
+ from: string
63
+ to: string
64
+ subject: string
65
+ text?: string
66
+ html?: string
67
+ inReplyTo?: string
68
+ },
69
+ ): Promise<void> {
70
+ const inReplyTo = normalizeMsgId(msg.inReplyTo)
71
+ await env.EMAIL.send({
72
+ from: msg.from,
73
+ to: msg.to,
74
+ subject: msg.subject,
75
+ ...(msg.text ? { text: msg.text } : {}),
76
+ ...(msg.html ? { html: msg.html } : {}),
77
+ ...(inReplyTo
78
+ ? { headers: { 'In-Reply-To': `<${inReplyTo}>`, References: `<${inReplyTo}>` } }
79
+ : {}),
80
+ })
81
+ }
82
+
83
+ /**
84
+ * POST an event to WEBHOOK_URL (if configured): fire-and-forget with one
85
+ * retry — callers run it inside ctx.waitUntil so it never delays mail
86
+ * handling. Body is `{ event, message }`; signed when WEBHOOK_SECRET is set.
87
+ */
88
+ export async function emitWebhook(
89
+ env: MailEnv,
90
+ event: 'message.received' | 'message.sent',
91
+ message: Record<string, unknown>,
92
+ ): Promise<void> {
93
+ if (!env.WEBHOOK_URL) return
94
+ const body = JSON.stringify({ event, message })
95
+ const headers: Record<string, string> = { 'content-type': 'application/json' }
96
+ if (env.WEBHOOK_SECRET) {
97
+ const key = await crypto.subtle.importKey(
98
+ 'raw',
99
+ new TextEncoder().encode(env.WEBHOOK_SECRET),
100
+ { name: 'HMAC', hash: 'SHA-256' },
101
+ false,
102
+ ['sign'],
103
+ )
104
+ const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(body))
105
+ headers['x-inbox-signature'] =
106
+ `sha256=${Array.from(new Uint8Array(sig), (b) => b.toString(16).padStart(2, '0')).join('')}`
107
+ }
108
+ for (let attempt = 0; attempt < 2; attempt++) {
109
+ try {
110
+ const res = await fetch(env.WEBHOOK_URL, { method: 'POST', headers, body })
111
+ if (res.ok) return
112
+ } catch {
113
+ // fall through to retry
114
+ }
115
+ }
116
+ console.warn(`webhook delivery failed after 2 attempts: ${event}`)
117
+ }
@@ -7,7 +7,12 @@
7
7
  // minimal static web UI. Outbound mail goes through the send_email binding
8
8
  // (Cloudflare Email Sending — the cloudflare-email module onboards the
9
9
  // domain).
10
- "name": "{{PROJECT_NAME}}-inbox",
10
+ // Generic defaults below (name, bucket_name, DEFAULT_FROM) — the per-project
11
+ // values live in the zbc instance file instead of here: the cloudflare
12
+ // module's `workerName` overrides the worker name, `r2Bindings` overrides
13
+ // the bucket, and a `workerVars` literal sets DEFAULT_FROM. That keeps this
14
+ // file identical across projects.
15
+ "name": "inbox",
11
16
  "main": "worker/index.ts",
12
17
  // Must be recent enough for the Email Service object-form EMAIL.send();
13
18
  // older dates fall back to legacy Email Routing semantics (verified
@@ -23,13 +28,21 @@
23
28
  "bindings": [{ "name": "INBOX", "class_name": "Inbox" }]
24
29
  },
25
30
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Inbox"] }],
26
- "r2_buckets": [{ "binding": "RAW", "bucket_name": "{{PROJECT_NAME}}-inbox-raw" }],
31
+ "r2_buckets": [{ "binding": "RAW", "bucket_name": "inbox-raw" }],
27
32
  // Unrestricted destination: once your domain is onboarded for Email Sending,
28
33
  // the worker may send to arbitrary recipients.
29
34
  "send_email": [{ "name": "EMAIL" }],
30
35
  "vars": {
31
36
  // Default From when /api/send omits one. Must be on your onboarded email
32
- // domain — EDIT THIS after `zbc add inbox`.
33
- "DEFAULT_FROM": "inbox@mail.YOUR-DOMAIN.example"
37
+ // domain. Set it per project via the instance file:
38
+ // workerVars: [{ name: 'DEFAULT_FROM', value: 'inbox@mail.example.com' }]
39
+ "DEFAULT_FROM": "",
40
+ // Optional webhook: every received/sent message POSTs { event, message }
41
+ // here (signed with the WEBHOOK_SECRET worker secret when set).
42
+ "WEBHOOK_URL": "",
43
+ // Optional inbound labeling: comma-separated label set (e.g.
44
+ // "billing,support,spam,other"). Requires the ANTHROPIC_API_KEY worker
45
+ // secret; leave empty to disable.
46
+ "LABELS": ""
34
47
  }
35
48
  }
@@ -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
+ }
@@ -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
+ }