@zabaca/zbc 0.24.0 → 0.26.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 (71) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/package.json +3 -2
  3. package/src/commands/add.ts +78 -5
  4. package/src/commands/init.ts +105 -10
  5. package/src/commands/list.ts +6 -3
  6. package/src/commands/update.ts +75 -6
  7. package/src/engine/destroy.ts +23 -2
  8. package/src/engine/resolve.ts +5 -0
  9. package/src/utils/detect-mode.ts +1 -1
  10. package/src/utils/host-workspaces.ts +57 -0
  11. package/src/utils/subtree.ts +78 -9
  12. package/src/utils/vendor-audit.ts +12 -8
  13. package/src/utils/vendor-stamp.ts +102 -1
  14. package/src/utils/vendored-app.ts +356 -0
  15. package/templates/CLAUDE.md +1 -1
  16. package/templates/apps/walgit/CONTEXT.md +45 -4
  17. package/templates/apps/walgit/README.md +394 -11
  18. package/templates/apps/walgit/shared/browse.ts +61 -0
  19. package/templates/apps/walgit/shared/capabilities.ts +26 -0
  20. package/templates/apps/walgit/shared/container-env.ts +12 -0
  21. package/templates/apps/walgit/shared/container-lifecycle.ts +1 -1
  22. package/templates/apps/walgit/shared/credentials.ts +4 -0
  23. package/templates/apps/walgit/shared/events.ts +35 -1
  24. package/templates/apps/walgit/shared/instructions.ts +4 -1
  25. package/templates/apps/walgit/shared/landing.ts +2 -1
  26. package/templates/apps/walgit/shared/llms.ts +73 -5
  27. package/templates/apps/walgit/shared/mcp.ts +19 -3
  28. package/templates/apps/walgit/shared/protocol.ts +40 -3
  29. package/templates/apps/walgit/shared/repo-list.ts +46 -6
  30. package/templates/apps/walgit/shared/scoped-token.ts +500 -0
  31. package/templates/apps/walgit/shared/token-revocation.ts +134 -0
  32. package/templates/apps/walgit/shared/wal-index.ts +19 -0
  33. package/templates/apps/walgit/shared/webhook.ts +281 -0
  34. package/templates/apps/walgit/src/admin.ts +510 -0
  35. package/templates/apps/walgit/src/announce-main.ts +17 -9
  36. package/templates/apps/walgit/src/announce.ts +86 -0
  37. package/templates/apps/walgit/src/browse.ts +255 -2
  38. package/templates/apps/walgit/src/cli.ts +140 -0
  39. package/templates/apps/walgit/src/expire.ts +5 -0
  40. package/templates/apps/walgit/src/git.ts +103 -0
  41. package/templates/apps/walgit/src/hook-main.ts +6 -3
  42. package/templates/apps/walgit/src/http.ts +563 -3
  43. package/templates/apps/walgit/src/limits.ts +3 -0
  44. package/templates/apps/walgit/src/merge.ts +525 -0
  45. package/templates/apps/walgit/src/rate-limit.ts +51 -14
  46. package/templates/apps/walgit/src/server.ts +65 -1
  47. package/templates/apps/walgit/worker/events-do.ts +218 -3
  48. package/templates/apps/walgit/worker/index.ts +134 -9
  49. package/templates/apps/walgit/worker/mcp.ts +18 -4
  50. package/templates/apps/warehouse/worker/router.ts +1 -2
  51. package/templates/apps/warehouse/worker/test-setup.ts +1 -2
  52. package/templates/infra/modules/cloudflare-access/index.ts +245 -28
  53. package/templates/infra/modules/cloudflare-access/registry.json +1 -1
  54. package/templates/infra/modules/d1/index.ts +133 -4
  55. package/templates/infra/modules/d1/registry.json +4 -1
  56. package/templates/infra/modules/queue/index.ts +313 -0
  57. package/templates/infra/modules/queue/registry.json +13 -0
  58. package/templates/infra/modules/r2/registry.json +1 -1
  59. package/templates/infra/src/define-module.ts +19 -2
  60. package/templates/infra/src/types.ts +24 -0
  61. package/templates/apps/inbox/package.json +0 -26
  62. package/templates/apps/inbox/public/index.html +0 -379
  63. package/templates/apps/inbox/registry.json +0 -9
  64. package/templates/apps/inbox/tsconfig.json +0 -19
  65. package/templates/apps/inbox/worker/api.ts +0 -197
  66. package/templates/apps/inbox/worker/commands.ts +0 -299
  67. package/templates/apps/inbox/worker/inbox-do.ts +0 -577
  68. package/templates/apps/inbox/worker/index.ts +0 -195
  69. package/templates/apps/inbox/worker/mcp.ts +0 -228
  70. package/templates/apps/inbox/worker/shared.ts +0 -117
  71. package/templates/apps/inbox/wrangler.jsonc +0 -48
@@ -1,195 +0,0 @@
1
- /**
2
- * Inbox Worker: an agent-accessible email inbox.
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 — handled by `api.ts`.
7
- * - `/mcp`: the MCP server over the same operations — handled by `mcp.ts`.
8
- * - Everything else: the static UI in public/ (ASSETS binding).
9
- *
10
- * This file is the runtime entry only: the Env, the bearer check, inbound mail
11
- * and the dispatch. Both adapters live beside it so a test can load them —
12
- * see the note atop `api.ts`.
13
- */
14
- import PostalMime from 'postal-mime'
15
- import { type ApiEnv, handleApi, json } from './api'
16
- import { Inbox, type InboxStore } from './inbox-do'
17
- import { handleMcp } from './mcp'
18
- import { type SendEmailBinding, emitWebhook, makeSnippet, newId, normalizeMsgId } from './shared'
19
-
20
- export { Inbox }
21
-
22
- export interface Env extends ApiEnv {
23
- ASSETS: { fetch: (request: Request) => Promise<Response> }
24
- INBOX: DurableObjectNamespace<Inbox>
25
- RAW: R2Bucket
26
- EMAIL: SendEmailBinding
27
- /** Bearer token guarding /api/* (worker secret, pushed by zbc apply). */
28
- INBOX_TOKEN?: string
29
- /** Default From address for /api/send (wrangler var). */
30
- DEFAULT_FROM?: string
31
- /**
32
- * Optional webhook: POSTed a JSON event on every received/sent message.
33
- * Best-effort (one retry, never blocks mail handling). Signed with
34
- * WEBHOOK_SECRET when set (x-inbox-signature: sha256=<hex HMAC of body>).
35
- */
36
- WEBHOOK_URL?: string
37
- WEBHOOK_SECRET?: string
38
- /**
39
- * Optional inbound labeling: when both ANTHROPIC_API_KEY (worker secret)
40
- * and LABELS (comma-separated set, e.g. "billing,support,spam,other") are
41
- * set, each received message is classified into one label after insert.
42
- * Best-effort — a classifier failure just leaves label = ''.
43
- */
44
- ANTHROPIC_API_KEY?: string
45
- LABELS?: string
46
- }
47
-
48
- /** Constant-time bearer check: compare SHA-256 digests so length never leaks. */
49
- async function authorized(request: Request, env: Env): Promise<boolean> {
50
- if (!env.INBOX_TOKEN) return false
51
- const header = request.headers.get('authorization') ?? ''
52
- const presented = header.startsWith('Bearer ') ? header.slice(7) : ''
53
- const enc = new TextEncoder()
54
- const [a, b] = await Promise.all([
55
- crypto.subtle.digest('SHA-256', enc.encode(presented)),
56
- crypto.subtle.digest('SHA-256', enc.encode(env.INBOX_TOKEN)),
57
- ])
58
- return crypto.subtle.timingSafeEqual(a, b)
59
- }
60
-
61
- function inboxStub(env: Env) {
62
- return env.INBOX.get(env.INBOX.idFromName('inbox'))
63
- }
64
-
65
- /**
66
- * Classify an inbound message into one of env.LABELS via the Anthropic API.
67
- * Returns '' (no label) on any failure or an answer outside the label set —
68
- * labeling is strictly best-effort and must never block ingestion.
69
- */
70
- async function classify(env: Env, subject: string, snippet: string): Promise<string> {
71
- if (!env.ANTHROPIC_API_KEY || !env.LABELS) return ''
72
- const labels = env.LABELS.split(',')
73
- .map((l) => l.trim())
74
- .filter(Boolean)
75
- if (labels.length === 0) return ''
76
- try {
77
- const res = await fetch('https://api.anthropic.com/v1/messages', {
78
- method: 'POST',
79
- headers: {
80
- 'x-api-key': env.ANTHROPIC_API_KEY,
81
- 'anthropic-version': '2023-06-01',
82
- 'content-type': 'application/json',
83
- },
84
- body: JSON.stringify({
85
- model: 'claude-haiku-4-5-20251001',
86
- max_tokens: 16,
87
- messages: [
88
- {
89
- role: 'user',
90
- content:
91
- `Classify this email into exactly one of these labels: ${labels.join(', ')}.\n` +
92
- `Reply with the label only.\n\nSubject: ${subject}\nBody: ${snippet}`,
93
- },
94
- ],
95
- }),
96
- })
97
- if (!res.ok) return ''
98
- const data = (await res.json()) as { content?: Array<{ type: string; text?: string }> }
99
- const answer = (data.content?.find((b) => b.type === 'text')?.text ?? '').trim().toLowerCase()
100
- return labels.find((l) => l.toLowerCase() === answer) ?? ''
101
- } catch {
102
- return ''
103
- }
104
- }
105
-
106
- export default {
107
- async email(message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext): Promise<void> {
108
- const id = newId()
109
- const r2Key = `msgs/${id}`
110
-
111
- // Raw MIME first (source of truth), then parse.
112
- const raw = await new Response(message.raw).arrayBuffer()
113
- await env.RAW.put(r2Key, raw, {
114
- customMetadata: { from: message.from, to: message.to },
115
- })
116
-
117
- const parsed = await PostalMime.parse(raw)
118
- const text = parsed.text ?? ''
119
- const snippet = makeSnippet(text, parsed.html ?? '')
120
-
121
- const stub = inboxStub(env)
122
- const fromAddr = parsed.from?.address ?? message.from
123
- const subject = parsed.subject ?? ''
124
- const { threadId } = await stub.insert({
125
- id,
126
- direction: 'inbound',
127
- in_reply_to: normalizeMsgId(parsed.inReplyTo),
128
- message_id: normalizeMsgId(parsed.messageId),
129
- // Prefer the header From (what the sender shows as) over the SMTP
130
- // envelope sender (often a bounce address like bounces@cf-bounce.…).
131
- from_addr: fromAddr,
132
- to_addr: message.to,
133
- subject,
134
- date: parsed.date ?? new Date().toISOString(),
135
- snippet,
136
- text_body: text,
137
- html_body: parsed.html ?? '',
138
- r2_key: r2Key,
139
- attachments_json: JSON.stringify(
140
- (parsed.attachments ?? []).map((a) => ({
141
- filename: a.filename ?? 'attachment',
142
- mimeType: a.mimeType,
143
- size: typeof a.content === 'string' ? a.content.length : (a.content?.byteLength ?? 0),
144
- })),
145
- ),
146
- size: raw.byteLength,
147
- })
148
-
149
- // Post-insert extras, off the critical path: webhook push + optional
150
- // labeling. waitUntil keeps the email handler's completion independent of
151
- // either — a webhook receiver outage or classifier failure never bounces
152
- // mail.
153
- ctx.waitUntil(
154
- emitWebhook(env, 'message.received', {
155
- id,
156
- threadId,
157
- from: fromAddr,
158
- to: message.to,
159
- subject,
160
- snippet,
161
- direction: 'inbound',
162
- }),
163
- )
164
- ctx.waitUntil(
165
- classify(env, subject, snippet).then((label) =>
166
- label ? stub.setLabel(id, label) : undefined,
167
- ),
168
- )
169
- },
170
-
171
- async fetch(request: Request, env: Env, _ctx: ExecutionContext): Promise<Response> {
172
- const url = new URL(request.url)
173
- const { pathname } = url
174
-
175
- if (pathname !== '/mcp' && !pathname.startsWith('/api/')) {
176
- return env.ASSETS.fetch(request)
177
- }
178
-
179
- if (!(await authorized(request, env))) {
180
- return json({ error: 'unauthorized' }, 401)
181
- }
182
-
183
- // The DO stub reaches both adapters as an InboxStore: `DurableObjectStub<
184
- // Inbox>` expands workers-types' recursive RPC generics inside mcp.ts's
185
- // registerTool inference and trips TS2589. This is the one cast.
186
- const store = inboxStub(env) as unknown as InboxStore
187
-
188
- // POST/GET/DELETE /mcp — MCP server (Streamable HTTP), same bearer token
189
- if (pathname === '/mcp') {
190
- return handleMcp(request, { env, store })
191
- }
192
-
193
- return handleApi(request, { env, store })
194
- },
195
- }
@@ -1,228 +0,0 @@
1
- import { StreamableHTTPTransport } from '@hono/mcp'
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
3
- import { Hono } from 'hono'
4
- import { z } from 'zod'
5
- import * as commands from './commands'
6
- import type { SendEnv } from './commands'
7
- import type { InboxStore } from './inbox-do'
8
-
9
- /**
10
- * MCP server over the inbox — the same operations as /api/*, exposed as
11
- * tools for MCP clients (Claude Code, claude.ai, etc.) at POST /mcp with
12
- * Streamable HTTP transport (cedarpad's pattern: stateless per request, a
13
- * fresh McpServer each call — workers isolates hold no session).
14
- *
15
- * Auth is the SAME bearer token as /api/* — the caller checks it before
16
- * invoking this, and MCP clients send it as a normal Authorization header.
17
- *
18
- * This file is wiring, not logic: every mutation is a call into `commands.ts`
19
- * — the same function `api.ts` calls — and every read is a single `store.*`
20
- * call. Nothing here decides what a mutation does.
21
- */
22
-
23
- const text = (v: unknown) => ({
24
- content: [{ type: 'text' as const, text: JSON.stringify(v, null, 2) }],
25
- })
26
-
27
- /** Unwrap a command Outcome into MCP result-or-error. */
28
- const outcome = (o: { status: number; body: Record<string, unknown> }) => {
29
- if (o.status >= 400) throw new Error(String(o.body.error ?? `failed (${o.status})`))
30
- return text(o.body)
31
- }
32
-
33
- interface McpDeps {
34
- env: SendEnv & { RAW: R2Bucket }
35
- store: InboxStore
36
- }
37
-
38
- export async function handleMcp(request: Request, deps: McpDeps): Promise<Response> {
39
- const { env, store } = deps
40
- const server = new McpServer({ name: 'inbox', version: '1.0.0' })
41
-
42
- server.registerTool(
43
- 'list_threads',
44
- {
45
- description:
46
- 'List conversation threads, newest first. Each row is the latest message of its thread plus thread_count. Page with cursor = the last id from the previous page.',
47
- inputSchema: { limit: z.number().optional(), cursor: z.string().optional() },
48
- },
49
- async ({ limit, cursor }) => text(await store.listThreads(limit ?? 50, cursor)),
50
- )
51
- server.registerTool(
52
- 'read_thread',
53
- {
54
- description:
55
- 'Read every message in a thread (oldest first) with full text/html bodies and attachment metadata.',
56
- inputSchema: { thread_id: z.string() },
57
- },
58
- async ({ thread_id }) => {
59
- const messages = await store.getThread(thread_id)
60
- if (!messages.length) throw new Error('thread not found')
61
- return text({ messages })
62
- },
63
- )
64
- server.registerTool(
65
- 'list_messages',
66
- {
67
- description:
68
- 'List individual messages, newest first (both directions; drafts and scheduled excluded). Optional label filter (see labeling). Page with cursor.',
69
- inputSchema: {
70
- limit: z.number().optional(),
71
- cursor: z.string().optional(),
72
- label: z.string().optional(),
73
- },
74
- },
75
- async ({ limit, cursor, label }) => text(await store.list(limit ?? 50, cursor, label)),
76
- )
77
- server.registerTool(
78
- 'read_message',
79
- {
80
- description: 'Read one message by id: full bodies, headers, attachment metadata.',
81
- inputSchema: { id: z.string() },
82
- },
83
- async ({ id }) => {
84
- const msg = await store.get(id)
85
- if (!msg) throw new Error('message not found')
86
- return text(msg)
87
- },
88
- )
89
- server.registerTool(
90
- 'search_messages',
91
- {
92
- description: 'Keyword search over subject + text body (case-insensitive), newest first.',
93
- inputSchema: { q: z.string(), limit: z.number().optional() },
94
- },
95
- async ({ q, limit }) => text({ messages: await store.search(q, limit ?? 50) }),
96
- )
97
- server.registerTool(
98
- 'send_email',
99
- {
100
- description:
101
- 'Send an email now, or pass send_at (ISO timestamp) to schedule it. from defaults to DEFAULT_FROM. To reply into an existing thread, pass in_reply_to = the message_id of the message being replied to.',
102
- inputSchema: {
103
- to: z.string(),
104
- subject: z.string(),
105
- text: z.string().optional(),
106
- html: z.string().optional(),
107
- from: z.string().optional(),
108
- in_reply_to: z.string().optional(),
109
- send_at: z.string().optional(),
110
- },
111
- },
112
- async (input) =>
113
- outcome(
114
- await commands.send(env, store, {
115
- to: input.to,
116
- subject: input.subject,
117
- text: input.text,
118
- html: input.html,
119
- from: input.from,
120
- inReplyTo: input.in_reply_to,
121
- sendAt: input.send_at,
122
- }),
123
- ),
124
- )
125
- server.registerTool(
126
- 'create_draft',
127
- {
128
- description:
129
- 'Store an outbound draft without sending. All fields optional — completeness is checked at send_draft time.',
130
- inputSchema: {
131
- to: z.string().optional(),
132
- subject: z.string().optional(),
133
- text: z.string().optional(),
134
- html: z.string().optional(),
135
- from: z.string().optional(),
136
- in_reply_to: z.string().optional(),
137
- },
138
- },
139
- async (input) =>
140
- outcome(
141
- await commands.createDraft(env, store, {
142
- to: input.to,
143
- subject: input.subject,
144
- text: input.text,
145
- html: input.html,
146
- from: input.from,
147
- inReplyTo: input.in_reply_to,
148
- }),
149
- ),
150
- )
151
- server.registerTool(
152
- 'list_drafts',
153
- { description: 'List unsent drafts, newest first.' },
154
- async () => text({ drafts: await store.listDrafts(50) }),
155
- )
156
- server.registerTool(
157
- 'update_draft',
158
- {
159
- description: 'Update an unsent draft. Only the fields passed change.',
160
- inputSchema: {
161
- id: z.string(),
162
- to: z.string().optional(),
163
- subject: z.string().optional(),
164
- text: z.string().optional(),
165
- html: z.string().optional(),
166
- from: z.string().optional(),
167
- in_reply_to: z.string().optional(),
168
- },
169
- },
170
- async ({ id, ...input }) =>
171
- outcome(
172
- await commands.updateDraft(store, id, {
173
- to: input.to,
174
- subject: input.subject,
175
- text: input.text,
176
- html: input.html,
177
- from: input.from,
178
- inReplyTo: input.in_reply_to,
179
- }),
180
- ),
181
- )
182
- server.registerTool(
183
- 'send_draft',
184
- {
185
- description: 'Send an existing draft (must have to, subject, and text or html).',
186
- inputSchema: { id: z.string() },
187
- },
188
- async ({ id }) => outcome(await commands.sendDraft(env, store, id)),
189
- )
190
- server.registerTool(
191
- 'list_scheduled',
192
- {
193
- description:
194
- 'List pending scheduled sends (and failed ones, with send_error), soonest first.',
195
- },
196
- async () => text({ scheduled: await store.listScheduled(50) }),
197
- )
198
- server.registerTool(
199
- 'cancel_scheduled',
200
- {
201
- description: 'Cancel a pending scheduled send (or dismiss a failed one). Deletes the row.',
202
- inputSchema: { id: z.string() },
203
- },
204
- async ({ id }) => outcome(await commands.cancelScheduled(store, id)),
205
- )
206
- server.registerTool(
207
- 'delete_message',
208
- {
209
- description: 'Delete a message (any status) and its raw MIME blob.',
210
- inputSchema: { id: z.string() },
211
- },
212
- async ({ id }) => {
213
- const result = await commands.deleteMessage(env, store, id)
214
- // The one place an adapter renders a command's error in its own words:
215
- // this tool has always said 'message not found' where the JSON route
216
- // says 'not found', and MCP clients see the string. The command decides
217
- // WHETHER it is a 404; the tool only spells it.
218
- if (result.status === 404) throw new Error('message not found')
219
- return outcome(result)
220
- },
221
- )
222
-
223
- const transport = new StreamableHTTPTransport()
224
- await server.connect(transport)
225
- const app = new Hono()
226
- app.all('/mcp', (c) => transport.handleRequest(c))
227
- return app.fetch(request)
228
- }
@@ -1,117 +0,0 @@
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
- }
@@ -1,48 +0,0 @@
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
- // 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",
16
- "main": "worker/index.ts",
17
- // Must be recent enough for the Email Service object-form EMAIL.send();
18
- // older dates fall back to legacy Email Routing semantics (verified
19
- // destinations only).
20
- "compatibility_date": "2026-07-01",
21
- "compatibility_flags": ["nodejs_compat"],
22
- "observability": { "enabled": true },
23
- "assets": {
24
- "directory": "./public",
25
- "binding": "ASSETS"
26
- },
27
- "durable_objects": {
28
- "bindings": [{ "name": "INBOX", "class_name": "Inbox" }]
29
- },
30
- "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Inbox"] }],
31
- "r2_buckets": [{ "binding": "RAW", "bucket_name": "inbox-raw" }],
32
- // Unrestricted destination: once your domain is onboarded for Email Sending,
33
- // the worker may send to arbitrary recipients.
34
- "send_email": [{ "name": "EMAIL" }],
35
- "vars": {
36
- // Default From when /api/send omits one. Must be on your onboarded email
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": ""
47
- }
48
- }