@zabaca/zbc 0.4.0 → 0.6.1

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,141 @@
1
+ import { DurableObject } from 'cloudflare:workers'
2
+
3
+ /**
4
+ * Inbox — a single SQLite-backed Durable Object holding message metadata and
5
+ * parsed bodies. Raw MIME lives in R2 (DO SQLite caps a value at ~2 MB while
6
+ * a message can be 5 MiB); `r2_key` points at it.
7
+ *
8
+ * One DO instance for the whole inbox (idFromName('inbox')) — transactional
9
+ * ordering beats sharding at this scale.
10
+ */
11
+
12
+ export interface MessageMeta {
13
+ id: string
14
+ from_addr: string
15
+ to_addr: string
16
+ subject: string
17
+ date: string
18
+ snippet: string
19
+ size: number
20
+ created_at: string
21
+ }
22
+
23
+ export interface MessageFull extends MessageMeta {
24
+ message_id: string
25
+ text_body: string
26
+ html_body: string
27
+ r2_key: string
28
+ attachments: Array<{ filename: string; mimeType: string; size: number }>
29
+ }
30
+
31
+ export interface InsertMessage {
32
+ id: string
33
+ message_id: string
34
+ from_addr: string
35
+ to_addr: string
36
+ subject: string
37
+ date: string
38
+ snippet: string
39
+ text_body: string
40
+ html_body: string
41
+ r2_key: string
42
+ attachments_json: string
43
+ size: number
44
+ }
45
+
46
+ export class Inbox extends DurableObject {
47
+ private sql: SqlStorage
48
+
49
+ constructor(ctx: DurableObjectState, env: unknown) {
50
+ super(ctx, env as never)
51
+ this.sql = ctx.storage.sql
52
+ this.sql.exec(`
53
+ CREATE TABLE IF NOT EXISTS messages (
54
+ id TEXT PRIMARY KEY,
55
+ message_id TEXT,
56
+ from_addr TEXT NOT NULL,
57
+ to_addr TEXT NOT NULL,
58
+ subject TEXT,
59
+ date TEXT,
60
+ snippet TEXT,
61
+ text_body TEXT,
62
+ html_body TEXT,
63
+ r2_key TEXT NOT NULL,
64
+ attachments_json TEXT NOT NULL DEFAULT '[]',
65
+ size INTEGER NOT NULL DEFAULT 0,
66
+ created_at TEXT NOT NULL
67
+ );
68
+ CREATE INDEX IF NOT EXISTS idx_messages_created ON messages (created_at DESC, id DESC);
69
+ `)
70
+ }
71
+
72
+ insert(msg: InsertMessage): void {
73
+ this.sql.exec(
74
+ `INSERT INTO messages
75
+ (id, message_id, from_addr, to_addr, subject, date, snippet,
76
+ text_body, html_body, r2_key, attachments_json, size, created_at)
77
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
78
+ msg.id,
79
+ msg.message_id,
80
+ msg.from_addr,
81
+ msg.to_addr,
82
+ msg.subject,
83
+ msg.date,
84
+ msg.snippet,
85
+ msg.text_body,
86
+ msg.html_body,
87
+ msg.r2_key,
88
+ msg.attachments_json,
89
+ msg.size,
90
+ new Date().toISOString(),
91
+ )
92
+ }
93
+
94
+ /** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
95
+ list(limit = 50, cursor?: string): { messages: MessageMeta[]; nextCursor: string | null } {
96
+ const capped = Math.min(Math.max(limit, 1), 200)
97
+ const rows = (cursor
98
+ ? this.sql
99
+ .exec(
100
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
101
+ FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
102
+ cursor,
103
+ capped + 1,
104
+ )
105
+ .toArray()
106
+ : this.sql
107
+ .exec(
108
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at
109
+ FROM messages ORDER BY id DESC LIMIT ?`,
110
+ capped + 1,
111
+ )
112
+ .toArray()) as unknown as MessageMeta[]
113
+ const hasMore = rows.length > capped
114
+ const page = hasMore ? rows.slice(0, capped) : rows
115
+ return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
116
+ }
117
+
118
+ get(id: string): MessageFull | null {
119
+ const row = this.sql
120
+ .exec(
121
+ `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
122
+ text_body, html_body, r2_key, attachments_json, size, created_at
123
+ FROM messages WHERE id = ?`,
124
+ id,
125
+ )
126
+ .toArray()[0] as unknown as (MessageFull & { attachments_json: string }) | undefined
127
+ if (!row) return null
128
+ const { attachments_json, ...rest } = row
129
+ return { ...rest, attachments: JSON.parse(attachments_json || '[]') }
130
+ }
131
+
132
+ /** Deletes the row; returns the r2_key so the caller can delete the raw blob. */
133
+ delete(id: string): string | null {
134
+ const row = this.sql.exec(`SELECT r2_key FROM messages WHERE id = ?`, id).toArray()[0] as
135
+ | { r2_key: string }
136
+ | undefined
137
+ if (!row) return null
138
+ this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
139
+ return row.r2_key
140
+ }
141
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Inbox Worker: an agent-accessible inbox for your email domain.
3
+ *
4
+ * - `email()` handler: Email Routing (catch-all) delivers inbound mail here.
5
+ * Raw MIME → R2; parsed metadata + bodies → the Inbox Durable Object.
6
+ * - `/api/*`: bearer-authed JSON API (list / read / raw / delete / send).
7
+ * - Everything else: the static UI in public/ (ASSETS binding).
8
+ */
9
+ import PostalMime from 'postal-mime'
10
+ import { Inbox } from './inbox-do'
11
+
12
+ export { Inbox }
13
+
14
+ /**
15
+ * Email Service send binding (the NEW object-based API, not the legacy
16
+ * EmailMessage one). The legacy `new EmailMessage(from, to, raw)` path routes
17
+ * through Email Routing and only delivers to VERIFIED destination addresses;
18
+ * the object form goes through Email Sending and accepts any recipient as
19
+ * long as the From domain is onboarded.
20
+ */
21
+ interface SendEmailBinding {
22
+ send(message: {
23
+ from: string
24
+ to: string
25
+ subject: string
26
+ text?: string
27
+ html?: string
28
+ headers?: Record<string, string>
29
+ }): Promise<unknown>
30
+ }
31
+
32
+ export interface Env {
33
+ ASSETS: { fetch: (request: Request) => Promise<Response> }
34
+ INBOX: DurableObjectNamespace<Inbox>
35
+ RAW: R2Bucket
36
+ EMAIL: SendEmailBinding
37
+ /** Bearer token guarding /api/* (worker secret, pushed by zbc apply). */
38
+ INBOX_TOKEN?: string
39
+ /** Default From address for /api/send (wrangler var). */
40
+ DEFAULT_FROM?: string
41
+ }
42
+
43
+ /** Time-ordered id: ms timestamp (base36, padded) + random suffix. Sortable as TEXT. */
44
+ function newId(): string {
45
+ const time = Date.now().toString(36).padStart(9, '0')
46
+ const rand = crypto.getRandomValues(new Uint8Array(8))
47
+ const suffix = Array.from(rand, (b) => b.toString(36).padStart(2, '0'))
48
+ .join('')
49
+ .slice(0, 12)
50
+ return `${time}-${suffix}`
51
+ }
52
+
53
+ /** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
54
+ async function authorized(request: Request, env: Env): Promise<boolean> {
55
+ if (!env.INBOX_TOKEN) return false
56
+ const header = request.headers.get('authorization') ?? ''
57
+ const presented = header.startsWith('Bearer ') ? header.slice(7) : ''
58
+ const enc = new TextEncoder()
59
+ const [a, b] = await Promise.all([
60
+ crypto.subtle.digest('SHA-256', enc.encode(presented)),
61
+ crypto.subtle.digest('SHA-256', enc.encode(env.INBOX_TOKEN)),
62
+ ])
63
+ return crypto.subtle.timingSafeEqual(a, b)
64
+ }
65
+
66
+ function json(data: unknown, status = 200): Response {
67
+ return Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
68
+ }
69
+
70
+ function inboxStub(env: Env) {
71
+ return env.INBOX.get(env.INBOX.idFromName('inbox'))
72
+ }
73
+
74
+ interface SendBody {
75
+ to: string
76
+ subject: string
77
+ text?: string
78
+ html?: string
79
+ from?: string
80
+ /** RFC 5322 Message-ID of the message being replied to → In-Reply-To/References. */
81
+ inReplyTo?: string
82
+ }
83
+
84
+ export default {
85
+ async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
86
+ const id = newId()
87
+ const r2Key = `msgs/${id}`
88
+
89
+ // Raw MIME first (source of truth), then parse.
90
+ const raw = await new Response(message.raw).arrayBuffer()
91
+ await env.RAW.put(r2Key, raw, {
92
+ customMetadata: { from: message.from, to: message.to },
93
+ })
94
+
95
+ const parsed = await PostalMime.parse(raw)
96
+ const text = parsed.text ?? ''
97
+ const snippet = (text || (parsed.html ?? '').replace(/<[^>]+>/g, ' '))
98
+ .replace(/\s+/g, ' ')
99
+ .trim()
100
+ .slice(0, 200)
101
+
102
+ await inboxStub(env).insert({
103
+ id,
104
+ message_id: parsed.messageId ?? '',
105
+ // Prefer the header From (what the sender shows as) over the SMTP
106
+ // envelope sender (often a bounce address like bounces@cf-bounce.…).
107
+ from_addr: parsed.from?.address ?? message.from,
108
+ to_addr: message.to,
109
+ subject: parsed.subject ?? '',
110
+ date: parsed.date ?? new Date().toISOString(),
111
+ snippet,
112
+ text_body: text,
113
+ html_body: parsed.html ?? '',
114
+ r2_key: r2Key,
115
+ attachments_json: JSON.stringify(
116
+ (parsed.attachments ?? []).map((a) => ({
117
+ filename: a.filename ?? 'attachment',
118
+ mimeType: a.mimeType,
119
+ size: typeof a.content === 'string' ? a.content.length : (a.content?.byteLength ?? 0),
120
+ })),
121
+ ),
122
+ size: raw.byteLength,
123
+ })
124
+ },
125
+
126
+ async fetch(request: Request, env: Env): Promise<Response> {
127
+ const url = new URL(request.url)
128
+ const { pathname } = url
129
+
130
+ if (!pathname.startsWith('/api/')) {
131
+ return env.ASSETS.fetch(request)
132
+ }
133
+
134
+ if (!(await authorized(request, env))) {
135
+ return json({ error: 'unauthorized' }, 401)
136
+ }
137
+
138
+ const stub = inboxStub(env)
139
+
140
+ // GET /api/messages?limit=&cursor=
141
+ if (pathname === '/api/messages' && request.method === 'GET') {
142
+ const limit = Number(url.searchParams.get('limit') ?? '50')
143
+ const cursor = url.searchParams.get('cursor') ?? undefined
144
+ return json(await stub.list(Number.isFinite(limit) ? limit : 50, cursor))
145
+ }
146
+
147
+ // POST /api/send
148
+ if (pathname === '/api/send' && request.method === 'POST') {
149
+ let body: SendBody
150
+ try {
151
+ body = (await request.json()) as SendBody
152
+ } catch {
153
+ return json({ error: 'invalid JSON body' }, 400)
154
+ }
155
+ if (!body.to || !body.subject || (!body.text && !body.html)) {
156
+ return json({ error: 'required: to, subject, and text or html' }, 400)
157
+ }
158
+ const from = body.from ?? env.DEFAULT_FROM
159
+ if (!from) return json({ error: 'no from address (set DEFAULT_FROM or pass from)' }, 400)
160
+
161
+ const headers: Record<string, string> | undefined = body.inReplyTo
162
+ ? { 'In-Reply-To': body.inReplyTo, References: body.inReplyTo }
163
+ : undefined
164
+
165
+ try {
166
+ await env.EMAIL.send({
167
+ from,
168
+ to: body.to,
169
+ subject: body.subject,
170
+ ...(body.text ? { text: body.text } : {}),
171
+ ...(body.html ? { html: body.html } : {}),
172
+ ...(headers ? { headers } : {}),
173
+ })
174
+ } catch (err) {
175
+ return json({ error: `send failed: ${(err as Error).message}` }, 502)
176
+ }
177
+ return json({ ok: true, from, to: body.to })
178
+ }
179
+
180
+ // /api/messages/:id[/raw]
181
+ const match = pathname.match(/^\/api\/messages\/([^/]+)(\/raw)?$/)
182
+ if (match) {
183
+ const [, id, rawSuffix] = match
184
+
185
+ if (rawSuffix && request.method === 'GET') {
186
+ const msg = await stub.get(id!)
187
+ if (!msg) return json({ error: 'not found' }, 404)
188
+ const obj = await env.RAW.get(msg.r2_key)
189
+ if (!obj) return json({ error: 'raw MIME missing from R2' }, 404)
190
+ return new Response(obj.body, {
191
+ headers: { 'content-type': 'message/rfc822', 'cache-control': 'no-store' },
192
+ })
193
+ }
194
+
195
+ if (!rawSuffix && request.method === 'GET') {
196
+ const msg = await stub.get(id!)
197
+ return msg ? json(msg) : json({ error: 'not found' }, 404)
198
+ }
199
+
200
+ if (!rawSuffix && request.method === 'DELETE') {
201
+ const r2Key = await stub.delete(id!)
202
+ if (!r2Key) return json({ error: 'not found' }, 404)
203
+ await env.RAW.delete(r2Key)
204
+ return json({ ok: true })
205
+ }
206
+ }
207
+
208
+ return json({ error: 'not found' }, 404)
209
+ },
210
+ }
@@ -0,0 +1,35 @@
1
+ {
2
+ "$schema": "node_modules/wrangler/config-schema.json",
3
+ // Agent-accessible inbox. Receives mail via the email() handler (point your
4
+ // Email Routing catch-all at this worker — the cloudflare-email module does
5
+ // that), stores metadata + parsed bodies in a SQLite Durable Object and raw
6
+ // MIME in R2, and exposes a bearer-authed JSON API (list/read/send) plus a
7
+ // minimal static web UI. Outbound mail goes through the send_email binding
8
+ // (Cloudflare Email Sending — the cloudflare-email module onboards the
9
+ // domain).
10
+ "name": "{{PROJECT_NAME}}-inbox",
11
+ "main": "worker/index.ts",
12
+ // Must be recent enough for the Email Service object-form EMAIL.send();
13
+ // older dates fall back to legacy Email Routing semantics (verified
14
+ // destinations only).
15
+ "compatibility_date": "2026-07-01",
16
+ "compatibility_flags": ["nodejs_compat"],
17
+ "observability": { "enabled": true },
18
+ "assets": {
19
+ "directory": "./public",
20
+ "binding": "ASSETS"
21
+ },
22
+ "durable_objects": {
23
+ "bindings": [{ "name": "INBOX", "class_name": "Inbox" }]
24
+ },
25
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Inbox"] }],
26
+ "r2_buckets": [{ "binding": "RAW", "bucket_name": "{{PROJECT_NAME}}-inbox-raw" }],
27
+ // Unrestricted destination: once your domain is onboarded for Email Sending,
28
+ // the worker may send to arbitrary recipients.
29
+ "send_email": [{ "name": "EMAIL" }],
30
+ "vars": {
31
+ // 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"
34
+ }
35
+ }
@@ -1,7 +1,8 @@
1
1
  node_modules
2
2
  .turbo
3
3
  dist
4
- .vercel
4
+ .wrangler
5
+ out
5
6
  .env
6
7
  .env.*
7
8
  *.dec.yaml