inboxer 0.0.0-stage → 0.1.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 (68) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +388 -2
  3. package/dist/app.d.ts +6 -0
  4. package/dist/app.js +56 -0
  5. package/dist/auth.d.ts +33 -0
  6. package/dist/auth.js +111 -0
  7. package/dist/config.d.ts +23 -0
  8. package/dist/config.js +87 -0
  9. package/dist/core/address.d.ts +6 -0
  10. package/dist/core/address.js +16 -0
  11. package/dist/core/context.d.ts +10 -0
  12. package/dist/core/context.js +21 -0
  13. package/dist/core/mail.d.ts +142 -0
  14. package/dist/core/mail.js +520 -0
  15. package/dist/core/sync.d.ts +16 -0
  16. package/dist/core/sync.js +44 -0
  17. package/dist/core/text.d.ts +8 -0
  18. package/dist/core/text.js +45 -0
  19. package/dist/core/threads.d.ts +21 -0
  20. package/dist/core/threads.js +81 -0
  21. package/dist/index.d.ts +35 -0
  22. package/dist/index.js +49 -0
  23. package/dist/mcp.d.ts +5 -0
  24. package/dist/mcp.js +175 -0
  25. package/dist/provider/index.d.ts +3 -0
  26. package/dist/provider/index.js +11 -0
  27. package/dist/provider/resend.d.ts +8 -0
  28. package/dist/provider/resend.js +166 -0
  29. package/dist/provider/types.d.ts +70 -0
  30. package/dist/provider/types.js +6 -0
  31. package/dist/store.d.ts +54 -0
  32. package/dist/store.js +148 -0
  33. package/dist/types.d.ts +125 -0
  34. package/dist/types.js +1 -0
  35. package/dist/ui/assets.d.ts +8 -0
  36. package/dist/ui/assets.js +12 -0
  37. package/dist/ui/routes.d.ts +11 -0
  38. package/dist/ui/routes.js +186 -0
  39. package/dist/ui/static/htmx.min.js +1 -0
  40. package/dist/ui/static/style.css +144 -0
  41. package/dist/ui/strings.d.ts +63 -0
  42. package/dist/ui/strings.js +63 -0
  43. package/dist/ui/views.d.ts +40 -0
  44. package/dist/ui/views.js +216 -0
  45. package/package.json +79 -3
  46. package/skills/inboxer/SKILL.md +130 -0
  47. package/src/app.ts +56 -0
  48. package/src/auth.ts +119 -0
  49. package/src/config.ts +89 -0
  50. package/src/core/address.ts +19 -0
  51. package/src/core/context.ts +28 -0
  52. package/src/core/mail.ts +601 -0
  53. package/src/core/sync.ts +51 -0
  54. package/src/core/text.ts +52 -0
  55. package/src/core/threads.ts +102 -0
  56. package/src/index.ts +90 -0
  57. package/src/mcp.ts +211 -0
  58. package/src/provider/index.ts +14 -0
  59. package/src/provider/resend.ts +216 -0
  60. package/src/provider/types.ts +74 -0
  61. package/src/store.ts +187 -0
  62. package/src/types.ts +129 -0
  63. package/src/ui/assets.ts +20 -0
  64. package/src/ui/routes.ts +203 -0
  65. package/src/ui/static/htmx.min.js +1 -0
  66. package/src/ui/static/style.css +144 -0
  67. package/src/ui/strings.ts +69 -0
  68. package/src/ui/views.ts +253 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Martin Clasen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,389 @@
1
- # Temporary Holding Version
1
+ # Inboxer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Your own mail layer for agents. Inboxer stores every email that comes in or goes out, gives agents an MCP server to read, draft and send, and gives you a small web UI to review drafts from your phone before they leave.
4
+
5
+ Inboxer has no business rules. It does not decide what to answer or when. Each consumer, such as a scheduled agent, a support bot or you in a chat, brings its own rules in its prompt and uses the same tools. Sending goes through a **provider**. Inboxer ships with [Resend](https://resend.com), and the provider interface lets you plug in another service without touching the rest.
6
+
7
+ - **One process, one SQLite file.** Persistence uses [DeepBase](https://github.com/clasen/DeepBase) on the runtime's built-in `node:sqlite`, so there is nothing to compile and no external database.
8
+ - **Webhooks plus a backup sync.** Inbound mail and delivery events arrive by webhook. A periodic sync picks up anything a webhook missed.
9
+ - **Threads that hold together.** Messages join threads by `In-Reply-To` / `References`, then by subject and participants, so replies stay grouped even when a client drops headers.
10
+ - **Drafts with a human in the loop.** Agents write drafts with a note for the reviewer. You edit and send them from the UI. Concurrent edits are detected, never silently overwritten.
11
+ - **No passwords.** The UI uses one-time login links that an agent requests through MCP. Every link signs in one browser.
12
+ - **Runs on Node.js and Bun.** It works standalone or as a [roster-server](https://github.com/clasen/RosterServer) site.
13
+
14
+ ## Use cases
15
+
16
+ Inboxer handles storage, threading and delivery. The decisions belong to whoever calls the tools, so the same instance can serve very different workflows.
17
+
18
+ **Support with a human in the loop.** A scheduled agent runs every hour with a prompt that holds your support rules. It calls `list_threads({ mailbox: "support", status: "unanswered" })` and reads each thread with `get_thread`. It looks the sender up in your own systems, such as a license server or a CRM, and writes a reply with `create_draft`, adding a `note` for you: "Extend the trial by 7 days before sending." It sends you the draft's `url` wherever it reports to you. You open it on your phone, do what the note asks, adjust the text if needed and press Send.
19
+
20
+ **Automatic answers for the easy cases.** The same agent can be allowed to answer some questions directly. Its prompt says which ones, for example "if the question is only about pricing, `reply` with the pricing page". Everything else still becomes a draft. Inboxer does not enforce the split; the prompt does, and the audit log records which token sent what.
21
+
22
+ **Several addresses, one inbox.** `support@`, `billing@` and `feedback@` are separate mailboxes with their own sender name and signature. Agents filter by mailbox, and mail to any other address of the domain lands in `catchall` instead of bouncing.
23
+
24
+ **Triage and follow-up.** An agent labels threads (`label`), archives the ones that need no answer (`mark`), and finds earlier conversations with a customer before replying (`search({ query: "license", from: "ana@" })`).
25
+
26
+ **Linking mail to your own data.** After looking a sender up, the agent records what it found with `set_contact("ana@customer.test", { meta: { license_id: "BL-2231" }, note: "Paying customer since 2024" })`. The next `get_thread` with Ana returns that context without another lookup, the reviewer sees it above the draft, and `list_threads({ status: "all", meta: { license_id: "BL-2231" } })` finds every conversation with that customer, whichever address they wrote from.
27
+
28
+ **Ad hoc work from your own assistant.** Connect Inboxer to the agent you use day to day and ask it to "summarize what customers asked this week" or "find every thread about refunds since Monday and draft a reply for each". It uses the same tools as the scheduled jobs, under its own token.
29
+
30
+ ## Quick start
31
+
32
+ Requires **Node.js 22.16 or later**, or **Bun**.
33
+
34
+ ```bash
35
+ npm install inboxer
36
+ ```
37
+
38
+ `createInboxer` takes a plain config object, so load it however your project does. The examples use [Configre](https://github.com/clasen/Configre) (`npm install configre`), which merges a public and a secret file and keeps the secrets encrypted in Git.
39
+
40
+ Create `config/index.cjs` with the public settings:
41
+
42
+ ```javascript
43
+ module.exports = {
44
+ publicUrl: "https://inboxer.example.com",
45
+ dataDir: "/var/lib/inboxer", // absolute path
46
+ syncIntervalMin: 10,
47
+ threadWindowDays: 30,
48
+ mailboxes: {
49
+ support: { address: "support@example.com", name: "Example Support",
50
+ signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>" },
51
+ feedback: { address: "feedback@example.com", name: "Example" }
52
+ },
53
+ provider: { type: "resend" },
54
+ ui: { loginLinkTtlMin: 10 }
55
+ };
56
+ ```
57
+
58
+ Put the secrets in `config/index.secret.cjs`; Configre merges them over the public file:
59
+
60
+ ```javascript
61
+ module.exports = {
62
+ provider: { apiKey: "re_...", webhookSecret: "whsec_..." },
63
+ mcp: { tokens: { "support-schedule": "...", "laptop": "..." } },
64
+ ui: { cookieSecret: "..." }
65
+ };
66
+ ```
67
+
68
+ Generate each token and the cookie secret with:
69
+
70
+ ```bash
71
+ openssl rand -hex 32
72
+ ```
73
+
74
+ Serve it with Bun:
75
+
76
+ ```typescript
77
+ import Configre from "configre";
78
+ import { join } from "node:path";
79
+ import { createInboxer } from "inboxer";
80
+
81
+ const inboxer = createInboxer(Configre(join(import.meta.dirname, "config")));
82
+ Bun.serve({ port: 4000, fetch: inboxer.fetch });
83
+ ```
84
+
85
+ Or with Node.js:
86
+
87
+ ```typescript
88
+ import { createServer } from "node:http";
89
+
90
+ createServer(inboxer.handler).listen(4000);
91
+ ```
92
+
93
+ Everything lives under one origin:
94
+
95
+ | Route | Purpose |
96
+ | --- | --- |
97
+ | `/` | Review UI |
98
+ | `/static/*` | CSS and the vendored htmx script |
99
+ | `/mcp` | MCP server (Streamable HTTP, stateless) |
100
+ | `/webhooks/<provider>` | Provider webhooks, e.g. `/webhooks/resend` |
101
+ | `/auth/<token>` | One-time login links |
102
+
103
+ ## The `createInboxer` API
104
+
105
+ `createInboxer(cfg, options?)` does not listen on a port. It returns:
106
+
107
+ ```typescript
108
+ {
109
+ fetch: (req: Request) => Promise<Response>, // Bun.serve, Hono, any fetch-based server
110
+ handler: (req, res) => void, // Node-style, e.g. for roster-server
111
+ ready: Promise<void>, // database open and first sync done
112
+ close: () => Promise<void> // stops the sync and closes the database
113
+ }
114
+ ```
115
+
116
+ The function is synchronous, so a host that needs a synchronous factory can call it directly. Requests wait for `ready` before they are handled.
117
+
118
+ `options.provider` takes a provider instance instead of resolving `cfg.provider.type`. See [Providers](#providers).
119
+
120
+ `createLoginLink(cfg, { label?, threadId? })` mints a one-time login link from a script on the server. See [Signing in](#signing-in).
121
+
122
+ ### As a roster-server site
123
+
124
+ ```typescript
125
+ // www/inboxer.example.com/index.ts
126
+ import type { SiteFactory } from "roster-server";
127
+ import Configre from "configre";
128
+ import { join } from "node:path";
129
+ import { createInboxer } from "inboxer";
130
+
131
+ const site: SiteFactory = server => {
132
+ const inboxer = createInboxer(Configre(join(import.meta.dirname, "config")));
133
+ server.onClose(() => inboxer.close());
134
+ return inboxer.handler;
135
+ };
136
+ export default site;
137
+ ```
138
+
139
+ With roster's default isolation the site runs in its own process, so the database and the sync timer are never duplicated. Inboxer assumes a single process: login-link consumption and draft versioning rely on an in-process write queue.
140
+
141
+ ## Configuration
142
+
143
+ | Key | Meaning |
144
+ | --- | --- |
145
+ | `publicUrl` | Base URL used in login links |
146
+ | `dataDir` | Absolute directory for `inboxer.db` |
147
+ | `syncIntervalMin` | Minutes between backup syncs with the provider |
148
+ | `threadWindowDays` | How far back a subject match may join an existing thread |
149
+ | `mailboxes.<id>` | `address`, `name`, optional `signatureText` and `signatureHtml` |
150
+ | `provider` | `type` plus the provider's own options (secrets go in the secret file) |
151
+ | `mcp.tokens.<name>` | Bearer tokens for MCP that reach every mailbox; the name is recorded as the actor in the audit log |
152
+ | `mailboxes.<id>.tokens.<name>` | Bearer tokens that reach only that mailbox |
153
+ | `ui.cookieSecret` | Signs the UI session cookie |
154
+ | `ui.loginLinkTtlMin` | Minutes before an unused login link expires |
155
+
156
+ `mailboxes` is an object keyed by id rather than an array, so a Configre profile can override one mailbox without repeating the others. Mail sent to an address that matches no mailbox lands in the reserved `catchall` mailbox, which can be read but cannot send.
157
+
158
+ ## Providers
159
+
160
+ A provider adapts one email service to the `MailProvider` interface. Nothing outside the provider knows which service is in use: messages store the provider's name and id, and the webhook route is `/webhooks/<name>`.
161
+
162
+ ```typescript
163
+ interface MailProvider {
164
+ readonly name: string;
165
+ parseWebhook(req: { headers: Headers; body: string }): ProviderEvent[]; // throws WebhookSignatureError
166
+ getInbound(providerId: string): Promise<InboundMessage>;
167
+ listInbound(since: Date): AsyncIterable<string>;
168
+ listOutbound(since: Date): AsyncIterable<{ providerId: string; status: DeliveryStatus }>;
169
+ send(message: OutboundMessage, idempotencyKey: string): Promise<{ providerId: string }>;
170
+ getAttachmentUrl(providerMessageId: string, attachmentId: string): Promise<string>;
171
+ }
172
+
173
+ type ProviderEvent =
174
+ | { type: "received"; providerId: string }
175
+ | { type: "status"; providerId: string; status: DeliveryStatus; messageId: string | null };
176
+
177
+ type DeliveryStatus = "sent" | "delivered" | "bounced" | "failed";
178
+ ```
179
+
180
+ `send()` must not deliver twice for the same `idempotencyKey`. Inboxer uses the draft id, so retrying a failed send is safe. Pass your own implementation with `createInboxer(cfg, { provider })`. All the types above are exported from `inboxer`.
181
+
182
+ ### Resend
183
+
184
+ `provider: { type: "resend", apiKey, webhookSecret }`.
185
+
186
+ Resend handles sending and receiving. Inboxer talks to it in three ways:
187
+
188
+ | Direction | How |
189
+ | --- | --- |
190
+ | Resend → Inboxer | A webhook to `<publicUrl>/webhooks/resend` for every received email and delivery event, signed with Svix |
191
+ | Inboxer → Resend | The REST API with your API key: fetch received emails, send, read delivery status, get attachment URLs |
192
+ | Backup | Every `syncIntervalMin` minutes Inboxer lists recent received and sent emails, in case a webhook was lost |
193
+
194
+ #### Setting up Resend and your domain
195
+
196
+ Two domains are involved, and they are configured separately:
197
+
198
+ | What | Example | DNS |
199
+ | --- | --- | --- |
200
+ | The app: UI, `/mcp`, webhooks, login links | `inboxer.example.com` | `A`/`AAAA` to your server, served over HTTPS; this URL is `publicUrl` |
201
+ | The mail addresses | `support@example.com` | `MX` to Resend, plus SPF, DKIM and DMARC |
202
+
203
+ The app's host name does not have to match the addresses. A name like `inboxer.` avoids confusion with mail-server hosts such as `mail.`. The steps below use these two examples.
204
+
205
+ 1. **Deploy Inboxer first.** Point `inboxer.example.com` at your server, serve it over HTTPS (roster-server issues certificates on its own; otherwise use your reverse proxy), and set `publicUrl` to that URL. The webhook and login links depend on it.
206
+ 2. **Add the domain in Resend.** In *Domains*, add `example.com`. Resend lists the DNS records to create at your DNS provider: the SPF and DKIM records for sending, and the MX record for receiving. Enable receiving for the domain. Wait until Resend shows the domain as verified.
207
+ 3. **Mind the MX switch.** Once the MX record points to Resend, every address of the domain is delivered to Resend and no longer to your previous mail host or forwarding rules. Mail to addresses you did not configure still reaches Inboxer, in the `catchall` mailbox. If you need to keep the root domain on another host, use a subdomain such as `help.example.com` for Inboxer's addresses.
208
+ 4. **Add DMARC.** Create a TXT record at `_dmarc.example.com`, for example `v=DMARC1; p=none; rua=mailto:dmarc@example.com`, and tighten the policy once reports look clean.
209
+ 5. **Create an API key.** In *API Keys*, create a key with full access: Inboxer reads received and sent emails, not just sends. Put it in `provider.apiKey`.
210
+ 6. **Create the webhook.** In *Webhooks*, add an endpoint at `https://inboxer.example.com/webhooks/resend` with the `email.received`, `email.sent`, `email.delivered`, `email.bounced`, `email.failed` and `email.suppressed` events. Copy its signing secret into `provider.webhookSecret`.
211
+ 7. **Restart and test.** Restart Inboxer so it loads the secrets. Send an email from an outside account to `support@example.com`. Within seconds it should appear in the UI's Inbox and in `list_threads`. Resend's webhook page shows each delivery and Inboxer's response; a `401` means the signing secret is wrong.
212
+
213
+ Inbound webhooks carry no body, so Inboxer fetches each message from the receiving API. The webhook answers `500` when processing fails, so Resend retries; processing is idempotent by Resend id.
214
+
215
+ Inboxer sets its own `Message-ID` (`<uuid@your-domain>`) on outgoing mail. If the provider reports a different one in a delivery event, Inboxer adopts it, so replies still find the thread. When neither header matches, the subject-and-participant rule keeps the conversation together.
216
+
217
+ ## MCP
218
+
219
+ The MCP server is at `<publicUrl>/mcp`. It speaks Streamable HTTP without sessions, and every request carries `Authorization: Bearer <token>`.
220
+
221
+ ### Connecting a client
222
+
223
+ Give each client its own token, so the audit log shows who did what and you can revoke one without touching the rest. Add it under `mcp.tokens` in `config/index.secret.cjs`:
224
+
225
+ ```javascript
226
+ module.exports = {
227
+ mcp: {
228
+ tokens: {
229
+ "support-schedule": "3f9c...", // openssl rand -hex 32
230
+ "laptop": "a71e..."
231
+ }
232
+ }
233
+ };
234
+ ```
235
+
236
+ Restart Inboxer to load it. To revoke a token, delete its entry and restart.
237
+
238
+ ### Mailbox tokens
239
+
240
+ A token under `mcp.tokens` reaches every mailbox and the catch-all. To give a team or a job access to one mailbox only, put its token under that mailbox instead:
241
+
242
+ ```javascript
243
+ module.exports = {
244
+ mcp: { tokens: { "admin": "3f9c..." } }, // every mailbox
245
+ mailboxes: {
246
+ feedback: { tokens: { "feedback-bot": "a71e..." } }, // only feedback
247
+ legal: { tokens: { "legal-team": "c2d4..." } } // only legal
248
+ }
249
+ };
250
+ ```
251
+
252
+ A mailbox token sees nothing else: other mailboxes' threads, messages and drafts read as not found, and it cannot send from them. Contacts are shared by address, but it reaches only the contacts that take part in its own threads. A login link it creates signs a browser into the same mailboxes, and it lists and revokes only those browsers. To reach several mailboxes, put the same name and token under each. A name always maps to one token, and a token to one name.
253
+
254
+ With Claude Code:
255
+
256
+ ```bash
257
+ claude mcp add --transport http inboxer https://inboxer.example.com/mcp --header "Authorization: Bearer <token>"
258
+ ```
259
+
260
+ With a client configured by JSON, such as a project `.mcp.json`:
261
+
262
+ ```json
263
+ {
264
+ "mcpServers": {
265
+ "inboxer": {
266
+ "type": "http",
267
+ "url": "https://inboxer.example.com/mcp",
268
+ "headers": { "Authorization": "Bearer ${INBOXER_TOKEN}" }
269
+ }
270
+ }
271
+ }
272
+ ```
273
+
274
+ Ask the client to call `list_mailboxes` to check the connection. Connectors that require OAuth, such as the ones added from the claude.ai web interface, are not supported yet; they need a client that can send a static header.
275
+
276
+ ### Tools
277
+
278
+
279
+ | Tool | What it does |
280
+ | --- | --- |
281
+ | `list_mailboxes` | Configured mailboxes plus `catchall` |
282
+ | `list_threads(mailbox?, status?, label?, since?, meta?, limit?)` | `status`: `unanswered` (default; last message inbound and no pending draft), `all` or `archived` |
283
+ | `search(query?, meta?, mailbox?, from?, since?, until?, limit?)` | Full text over subject, body, from and to; accent and case insensitive |
284
+ | `get_thread(thread_id)` | Messages as plain text, pending drafts included, plus the thread's context and its participants' contacts |
285
+ | `set_contact(address, meta?, note?)` · `get_contact(address)` | Context for an email address, such as ids in other systems |
286
+ | `set_thread_meta(thread_id, meta?, note?)` | Context for one conversation, such as a ticket number |
287
+ | `label(ids, add?, remove?)` | Labels on messages, or on every message of a thread when given a thread id |
288
+ | `mark(ids, read?, archived?)` | Read and archived flags, same id rules |
289
+ | `create_draft(reply_to_id \| mailbox+to+subject, text, html?, note?, reply_all?, cc?, bcc?)` | A draft for review; `note` is shown highlighted to the reviewer |
290
+ | `update_draft(id, version, ..., force?)` | Requires the current `version`; refuses a draft a human edited unless `force: true` |
291
+ | `list_drafts(mailbox?)` · `discard_draft(id)` · `send_draft(id)` | Draft lifecycle; `send_draft` sends the last saved version |
292
+ | `send(mailbox, to, subject, text, ...)` · `reply(message_id, text, reply_all?)` | Direct sending, for consumers whose rules allow it |
293
+ | `get_attachment(message_id, attachment_id)` | Temporary download URL |
294
+ | `create_login_link(label?, thread_id?)` · `list_sessions` · `revoke_session(id)` | Access to the UI; with `thread_id` the link lands on that thread |
295
+
296
+ ### Context
297
+
298
+ `set_contact` and `set_thread_meta` attach context that Inboxer stores without interpreting:
299
+
300
+ - `meta` holds plain key/value pairs (text, numbers, booleans), typically ids in your own systems: `{ license_id: "BL-2231", crm_id: 991 }`. Updates merge by key, and `null` removes a key, so agents writing different keys do not overwrite each other.
301
+ - `note` is free text; a new value replaces it and `null` clears it.
302
+
303
+ Contacts are keyed by bare address, so `Ana <ANA@customer.test>` and `ana@customer.test` are the same contact. `get_thread` includes the thread's context and the contacts of its external participants. The `meta` filter of `list_threads` and `search` matches a thread when its own context or any participant's contact has every given pair; values compare as text, so `991` matches `"991"`. `list_threads` still applies its `status` filter, so pass `status: "all"` to find every conversation with a customer.
304
+
305
+ Every thread, message and draft in a result carries a `url` that opens it in the review UI, scrolled to the draft when it is one. An agent can pass it on as is: "Ana asked about her trial; I drafted a reply: https://inboxer.example.com/threads/…". A browser that is already signed in opens it directly; for one that is not, `create_login_link({ thread_id })` signs it in and lands on the same thread.
306
+
307
+ ## The review UI
308
+
309
+ The UI is server-rendered with Hono and htmx, without a front-end build, and works on a phone.
310
+
311
+ - **Drafts:** mailbox, recipient, the agent's note and the thread underneath, with Edit, Send and Discard.
312
+ - **Editing:** To, Cc, Subject and a plain-text body, with Save and Save & Send. HTML is generated from the text at send time, with the mailbox signature. If the agent changed the draft while you were editing, saving shows both versions instead of overwriting. Your edits mark the draft `edited_by_human`, so agents leave it alone.
313
+ - **Inbox:** threads per mailbox, filtered by mailbox and by unanswered, all or archived.
314
+ - **Thread:** messages in order, as plain text, with the context agents stored for the thread and its participants. Incoming HTML is never rendered.
315
+ - **Devices:** the browsers signed in, each with a Revoke button.
316
+
317
+ The theme follows the system setting, with a System / Light / Dark switch stored in a cookie. Every UI string lives in `src/ui/strings.ts`.
318
+
319
+ ### Signing in
320
+
321
+ 1. An MCP client calls `create_login_link`. Inboxer stores only a SHA-256 hash of the token.
322
+ 2. Opening the link shows a **Sign in on this device** button. Link previews and mail scanners only issue GET requests, so they do not use up the link.
323
+ 3. The button's POST consumes the link and creates a session. Any later attempt sees "This link was already used or expired."
324
+ 4. The session cookie is `HttpOnly`, `Secure`, `SameSite=Lax` and signed. Sessions do not expire; the cookie is re-issued on every visit so browsers keep it. A session ends on logout or revocation.
325
+
326
+ Each link creates one independent session. Revoking a phone does not sign out a laptop. A session reaches the mailboxes of the token that created its link; **Devices** shows them on each session that is limited.
327
+
328
+ If you have no MCP client at hand, mint a link from a script on the server, with the same config the app uses:
329
+
330
+ ```javascript
331
+ // login-link.mjs
332
+ import Configre from "configre";
333
+ import { join } from "node:path";
334
+ import { createLoginLink } from "inboxer";
335
+
336
+ const { url } = await createLoginLink(Configre(join(import.meta.dirname, "config")), { label: process.argv[2] });
337
+ console.log(url);
338
+ ```
339
+
340
+ ```bash
341
+ node login-link.mjs "my phone"
342
+ ```
343
+
344
+ `threadId` lands the browser on that thread after signing in. The session reaches every mailbox.
345
+
346
+ ## Data
347
+
348
+ DeepBase is a nested key-value store without secondary indexes, so Inboxer maintains its own indexes in the same serialized write as the record they point to:
349
+
350
+ | Path | Content |
351
+ | --- | --- |
352
+ | `messages/<id>` | Every message: direction, status, headers, body, attachment metadata, labels, draft note and version |
353
+ | `threads/<id>` | Thread summary used by `list_threads` |
354
+ | `drafts/<id>` | Pending drafts |
355
+ | `msgid/<sha1(Message-ID)>` | Message lookup for threading |
356
+ | `ext/<provider>/<sha1(provider id)>` | Idempotent ingest and delivery updates |
357
+ | `contacts/<sha1(address)>` · `thread_context/<id>` | Context set through MCP |
358
+ | `audit/<id>` | Sends, edits, discards, labels, context changes, login links and session changes, with the actor |
359
+ | `login_links/<sha256>` · `sessions/<sha256>` | UI access |
360
+
361
+ Search scans messages in memory. That is enough for support volumes; a dedicated full-text index can be added later without changing the tools.
362
+
363
+ ## Agent skill
364
+
365
+ The [Inboxer skill](skills/inboxer/SKILL.md) teaches a coding agent to set up Inboxer, configure Resend and the domain, connect MCP clients, and work with mail through the tools:
366
+
367
+ ```bash
368
+ npx skills add https://github.com/clasen/Inboxer --skill inboxer
369
+ ```
370
+
371
+ ## Development
372
+
373
+ ```bash
374
+ npm test # Node.js test runner
375
+ npm run test:bun # the same suite under Bun
376
+ npm run build # compiles to dist/
377
+ ```
378
+
379
+ ## License
380
+
381
+ The MIT License (MIT)
382
+
383
+ Copyright (c) Martin Clasen
384
+
385
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
386
+
387
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
388
+
389
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/dist/app.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { Hono } from "hono";
2
+ import { type Access } from "./auth.ts";
3
+ import { type Mail } from "./core/mail.ts";
4
+ import type { InboxerConfig } from "./types.ts";
5
+ import { type UiEnv } from "./ui/routes.ts";
6
+ export declare function buildApp(mail: Mail, access: Access, cfg: InboxerConfig, ready: Promise<void>): Hono<UiEnv>;
package/dist/app.js ADDED
@@ -0,0 +1,56 @@
1
+ import { Hono } from "hono";
2
+ import { matchBearer } from "./auth.js";
3
+ import { mcpTokens } from "./config.js";
4
+ import { InvalidRequestError } from "./core/mail.js";
5
+ import { handleMcp } from "./mcp.js";
6
+ import { WebhookSignatureError } from "./provider/types.js";
7
+ import { NotFoundError } from "./store.js";
8
+ import { ASSETS } from "./ui/assets.js";
9
+ import { registerUi } from "./ui/routes.js";
10
+ export function buildApp(mail, access, cfg, ready) {
11
+ const app = new Hono();
12
+ const tokens = mcpTokens(cfg);
13
+ app.use("*", async (_c, next) => {
14
+ await ready;
15
+ await next();
16
+ });
17
+ app.onError((err, c) => {
18
+ if (err instanceof NotFoundError)
19
+ return c.text(err.message, 404);
20
+ if (err instanceof InvalidRequestError)
21
+ return c.text(err.message, 400);
22
+ console.error("inboxer:", err);
23
+ return c.text("Internal error", 500);
24
+ });
25
+ app.get("/static/:file", c => {
26
+ const file = ASSETS[c.req.param("file")];
27
+ if (!file)
28
+ return c.notFound();
29
+ return c.body(file.body, 200, { "Content-Type": file.type, "Cache-Control": "public, max-age=31536000, immutable" });
30
+ });
31
+ // A failure answers 500 so the provider retries; ingest is idempotent.
32
+ app.post("/webhooks/:provider", async (c) => {
33
+ if (c.req.param("provider") !== mail.provider.name)
34
+ return c.notFound();
35
+ let events;
36
+ try {
37
+ events = mail.provider.parseWebhook({ headers: c.req.raw.headers, body: await c.req.text() });
38
+ }
39
+ catch (err) {
40
+ if (err instanceof WebhookSignatureError)
41
+ return c.text("Invalid signature", 401);
42
+ throw err;
43
+ }
44
+ for (const event of events)
45
+ await mail.applyEvent(event);
46
+ return c.json({ ok: true });
47
+ });
48
+ app.all("/mcp", async (c) => {
49
+ const token = matchBearer(c.req.header("authorization"), tokens);
50
+ if (!token)
51
+ return c.text("Unauthorized", 401, { "WWW-Authenticate": "Bearer" });
52
+ return handleMcp(c.req.raw, mail, access, { kind: "agent", name: token.name, scope: token.scope });
53
+ });
54
+ registerUi(app, mail, access, cfg);
55
+ return app;
56
+ }
package/dist/auth.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { type McpToken } from "./config.ts";
2
+ import { type Store } from "./store.ts";
3
+ import type { Actor, InboxerConfig, Scope, Session } from "./types.ts";
4
+ /** The MCP token in `Authorization: Bearer <token>`, or null. Every token is compared in constant time. */
5
+ export declare function matchBearer(header: string | undefined, tokens: McpToken[]): McpToken | null;
6
+ export interface ClientInfo {
7
+ ip: string | null;
8
+ userAgent: string | null;
9
+ }
10
+ /**
11
+ * One-time login links and the browser sessions they create. Only hashes are stored: a leaked
12
+ * database does not reveal a usable link or cookie.
13
+ */
14
+ export declare class Access {
15
+ private readonly store;
16
+ private readonly cfg;
17
+ constructor(store: Store, cfg: InboxerConfig);
18
+ /** The session the link creates reaches the actor's mailboxes. `threadId` makes it open that thread after signing in. */
19
+ createLoginLink(actor: Actor, label: string | null, threadId?: string | null): Promise<{
20
+ url: string;
21
+ expires_at: string;
22
+ }>;
23
+ isLinkValid(token: string): Promise<boolean>;
24
+ /** Check-and-delete runs inside the write queue, so only one caller can turn a link into a session. */
25
+ consumeLoginLink(token: string, client: ClientInfo): Promise<{
26
+ secret: string;
27
+ next: string;
28
+ } | null>;
29
+ authenticate(secret: string): Promise<Session | null>;
30
+ /** Sessions whose mailboxes `scope` reaches. */
31
+ listSessions(scope: Scope): Promise<Session[]>;
32
+ revokeSession(id: string, actor: Actor, action?: string): Promise<boolean>;
33
+ }
package/dist/auth.js ADDED
@@ -0,0 +1,111 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { appUrl, covers, reaches, threadPath } from "./config.js";
3
+ import { NotFoundError, sha256 } from "./store.js";
4
+ /** The MCP token in `Authorization: Bearer <token>`, or null. Every token is compared in constant time. */
5
+ export function matchBearer(header, tokens) {
6
+ const match = /^Bearer\s+(\S+)$/i.exec(header ?? "");
7
+ if (!match)
8
+ return null;
9
+ const presented = createHash("sha256").update(match[1]).digest();
10
+ let found = null;
11
+ for (const entry of tokens) {
12
+ const expected = createHash("sha256").update(entry.token).digest();
13
+ if (timingSafeEqual(presented, expected))
14
+ found = entry;
15
+ }
16
+ return found;
17
+ }
18
+ /**
19
+ * One-time login links and the browser sessions they create. Only hashes are stored: a leaked
20
+ * database does not reveal a usable link or cookie.
21
+ */
22
+ export class Access {
23
+ store;
24
+ cfg;
25
+ constructor(store, cfg) {
26
+ this.store = store;
27
+ this.cfg = cfg;
28
+ }
29
+ /** The session the link creates reaches the actor's mailboxes. `threadId` makes it open that thread after signing in. */
30
+ async createLoginLink(actor, label, threadId = null) {
31
+ if (threadId && !reaches(actor.scope, (await this.store.requireThread(threadId)).mailbox))
32
+ throw new NotFoundError(`Thread ${threadId} not found`);
33
+ const token = randomBytes(32).toString("base64url");
34
+ const now = Date.now();
35
+ const link = {
36
+ created_at: new Date(now).toISOString(),
37
+ expires_at: new Date(now + this.cfg.ui.loginLinkTtlMin * 60_000).toISOString(),
38
+ created_by: actor.name,
39
+ label,
40
+ next: threadId ? threadPath(threadId) : null,
41
+ scope: actor.scope,
42
+ };
43
+ await this.store.serialize(async () => {
44
+ await this.store.putLoginLink(sha256(token), link);
45
+ await this.store.audit("login_link.create", actor, null, { label });
46
+ });
47
+ return { url: appUrl(this.cfg, `/auth/${token}`), expires_at: link.expires_at };
48
+ }
49
+ async isLinkValid(token) {
50
+ const link = await this.store.getLoginLink(sha256(token));
51
+ return !!link && link.expires_at > new Date().toISOString();
52
+ }
53
+ /** Check-and-delete runs inside the write queue, so only one caller can turn a link into a session. */
54
+ consumeLoginLink(token, client) {
55
+ const hash = sha256(token);
56
+ return this.store.serialize(async () => {
57
+ const link = await this.store.getLoginLink(hash);
58
+ if (!link)
59
+ return null;
60
+ await this.store.deleteLoginLink(hash);
61
+ if (link.expires_at <= new Date().toISOString())
62
+ return null;
63
+ const secret = randomBytes(32).toString("base64url");
64
+ const now = new Date().toISOString();
65
+ const session = {
66
+ id: sha256(secret),
67
+ created_at: now,
68
+ last_seen: now,
69
+ user_agent: client.userAgent,
70
+ ip: client.ip,
71
+ label: link.label,
72
+ created_by: link.created_by,
73
+ scope: link.scope,
74
+ };
75
+ await this.store.putSession(session);
76
+ await this.store.audit("login_link.use", { kind: "ui", name: session.id.slice(0, 12), scope: session.scope }, null, {
77
+ ip: client.ip,
78
+ user_agent: client.userAgent,
79
+ created_by: link.created_by,
80
+ });
81
+ return { secret, next: link.next ?? "/" };
82
+ });
83
+ }
84
+ async authenticate(secret) {
85
+ const session = await this.store.getSession(sha256(secret));
86
+ if (!session)
87
+ return null;
88
+ session.last_seen = new Date().toISOString();
89
+ await this.store.serialize(async () => {
90
+ if (await this.store.getSession(session.id))
91
+ await this.store.putSession(session);
92
+ });
93
+ return session;
94
+ }
95
+ /** Sessions whose mailboxes `scope` reaches. */
96
+ async listSessions(scope) {
97
+ return (await this.store.allSessions())
98
+ .filter(s => covers(scope, s.scope))
99
+ .sort((a, b) => b.last_seen.localeCompare(a.last_seen));
100
+ }
101
+ revokeSession(id, actor, action = "session.revoke") {
102
+ return this.store.serialize(async () => {
103
+ const session = await this.store.getSession(id);
104
+ if (!session || !covers(actor.scope, session.scope))
105
+ return false;
106
+ await this.store.deleteSession(id);
107
+ await this.store.audit(action, actor, id);
108
+ return true;
109
+ });
110
+ }
111
+ }
@@ -0,0 +1,23 @@
1
+ import { type InboxerConfig, type Scope } from "./types.ts";
2
+ /** Absolute URL of an app path under `publicUrl`. */
3
+ export declare function appUrl(cfg: Pick<InboxerConfig, "publicUrl">, path: string): string;
4
+ /** UI path of a thread, scrolled to one of its drafts when given. */
5
+ export declare function threadPath(threadId: string, draftId?: string): string;
6
+ /** Asserts the shape `createInboxer` relies on. */
7
+ export declare function assertConfig(cfg: InboxerConfig, { requireProvider }: {
8
+ requireProvider: boolean;
9
+ }): void;
10
+ export interface McpToken {
11
+ name: string;
12
+ token: string;
13
+ scope: Scope;
14
+ }
15
+ /**
16
+ * Tokens in `mcp.tokens` reach every mailbox; tokens under `mailboxes.<id>.tokens` reach only that
17
+ * mailbox. The same name and token under several mailboxes reach all of them.
18
+ */
19
+ export declare function mcpTokens(cfg: InboxerConfig): McpToken[];
20
+ /** Whether `scope` reaches `mailbox`. */
21
+ export declare function reaches(scope: Scope, mailbox: string): boolean;
22
+ /** Whether `outer` reaches every mailbox `inner` does. */
23
+ export declare function covers(outer: Scope, inner: Scope): boolean;