inboxer 0.1.0 → 0.3.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.
- package/README.md +37 -49
- package/dist/config.js +3 -0
- package/dist/core/attachments.d.ts +9 -0
- package/dist/core/attachments.js +30 -0
- package/dist/core/mail.d.ts +31 -3
- package/dist/core/mail.js +149 -13
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -0
- package/dist/mcp.js +27 -4
- package/dist/provider/resend.js +22 -4
- package/dist/provider/types.d.ts +8 -1
- package/dist/types.d.ts +13 -0
- package/dist/ui/assets.js +1 -0
- package/dist/ui/routes.d.ts +1 -1
- package/dist/ui/routes.js +88 -42
- package/dist/ui/static/app.js +27 -0
- package/dist/ui/static/style.css +35 -0
- package/dist/ui/strings.d.ts +7 -3
- package/dist/ui/strings.js +7 -3
- package/dist/ui/views.d.ts +5 -0
- package/dist/ui/views.js +68 -9
- package/package.json +9 -8
- package/skills/inboxer/SKILL.md +13 -25
- package/src/config.ts +3 -0
- package/src/core/attachments.ts +33 -0
- package/src/core/mail.ts +150 -14
- package/src/index.ts +3 -0
- package/src/mcp.ts +27 -5
- package/src/provider/resend.ts +23 -4
- package/src/provider/types.ts +9 -1
- package/src/types.ts +13 -2
- package/src/ui/assets.ts +1 -0
- package/src/ui/routes.ts +167 -55
- package/src/ui/static/app.js +54 -0
- package/src/ui/static/style.css +303 -55
- package/src/ui/strings.ts +19 -5
- package/src/ui/views.ts +358 -84
package/README.md
CHANGED
|
@@ -35,12 +35,10 @@ Requires **Node.js 22.16 or later**, or **Bun**.
|
|
|
35
35
|
npm install inboxer
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
`createInboxer` takes
|
|
39
|
-
|
|
40
|
-
Create `config/index.cjs` with the public settings:
|
|
38
|
+
`createInboxer` takes one plain object:
|
|
41
39
|
|
|
42
40
|
```javascript
|
|
43
|
-
|
|
41
|
+
const config = {
|
|
44
42
|
publicUrl: "https://inboxer.example.com",
|
|
45
43
|
dataDir: "/var/lib/inboxer", // absolute path
|
|
46
44
|
syncIntervalMin: 10,
|
|
@@ -50,20 +48,13 @@ module.exports = {
|
|
|
50
48
|
signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>" },
|
|
51
49
|
feedback: { address: "feedback@example.com", name: "Example" }
|
|
52
50
|
},
|
|
53
|
-
provider: { type: "resend" },
|
|
54
|
-
|
|
51
|
+
provider: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." },
|
|
52
|
+
mcp: { tokens: { "support-schedule": "...", "laptop": "..." }, maxAttachmentMb: 10 },
|
|
53
|
+
ui: { cookieSecret: "...", loginLinkTtlMin: 10, undoSec: 10, maxUploadMb: 20 }
|
|
55
54
|
};
|
|
56
55
|
```
|
|
57
56
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
```javascript
|
|
61
|
-
module.exports = {
|
|
62
|
-
provider: { apiKey: "re_...", webhookSecret: "whsec_..." },
|
|
63
|
-
mcp: { tokens: { "support-schedule": "...", "laptop": "..." } },
|
|
64
|
-
ui: { cookieSecret: "..." }
|
|
65
|
-
};
|
|
66
|
-
```
|
|
57
|
+
Load it from wherever your project keeps configuration: a JSON file, environment variables, a secrets manager. `provider.apiKey`, `provider.webhookSecret`, the MCP tokens and `ui.cookieSecret` are secrets, so keep them out of Git. [Configre](https://github.com/clasen/Configre) is one way to do that: it merges a public file and an encrypted secret file into one object.
|
|
67
58
|
|
|
68
59
|
Generate each token and the cookie secret with:
|
|
69
60
|
|
|
@@ -74,11 +65,9 @@ openssl rand -hex 32
|
|
|
74
65
|
Serve it with Bun:
|
|
75
66
|
|
|
76
67
|
```typescript
|
|
77
|
-
import Configre from "configre";
|
|
78
|
-
import { join } from "node:path";
|
|
79
68
|
import { createInboxer } from "inboxer";
|
|
80
69
|
|
|
81
|
-
const inboxer = createInboxer(
|
|
70
|
+
const inboxer = createInboxer(config);
|
|
82
71
|
Bun.serve({ port: 4000, fetch: inboxer.fetch });
|
|
83
72
|
```
|
|
84
73
|
|
|
@@ -124,12 +113,11 @@ The function is synchronous, so a host that needs a synchronous factory can call
|
|
|
124
113
|
```typescript
|
|
125
114
|
// www/inboxer.example.com/index.ts
|
|
126
115
|
import type { SiteFactory } from "roster-server";
|
|
127
|
-
import Configre from "configre";
|
|
128
|
-
import { join } from "node:path";
|
|
129
116
|
import { createInboxer } from "inboxer";
|
|
117
|
+
import { config } from "./config.ts"; // however you load it
|
|
130
118
|
|
|
131
119
|
const site: SiteFactory = server => {
|
|
132
|
-
const inboxer = createInboxer(
|
|
120
|
+
const inboxer = createInboxer(config);
|
|
133
121
|
server.onClose(() => inboxer.close());
|
|
134
122
|
return inboxer.handler;
|
|
135
123
|
};
|
|
@@ -143,17 +131,20 @@ With roster's default isolation the site runs in its own process, so the databas
|
|
|
143
131
|
| Key | Meaning |
|
|
144
132
|
| --- | --- |
|
|
145
133
|
| `publicUrl` | Base URL used in login links |
|
|
146
|
-
| `dataDir` | Absolute directory for `inboxer.db` |
|
|
134
|
+
| `dataDir` | Absolute directory for `inboxer.db` and the `attachments/` folder |
|
|
147
135
|
| `syncIntervalMin` | Minutes between backup syncs with the provider |
|
|
148
136
|
| `threadWindowDays` | How far back a subject match may join an existing thread |
|
|
149
137
|
| `mailboxes.<id>` | `address`, `name`, optional `signatureText` and `signatureHtml` |
|
|
150
|
-
| `provider` | `type` plus the provider's own options
|
|
138
|
+
| `provider` | `type` plus the provider's own options, such as Resend's `apiKey` and `webhookSecret` |
|
|
151
139
|
| `mcp.tokens.<name>` | Bearer tokens for MCP that reach every mailbox; the name is recorded as the actor in the audit log |
|
|
152
140
|
| `mailboxes.<id>.tokens.<name>` | Bearer tokens that reach only that mailbox |
|
|
141
|
+
| `mcp.maxAttachmentMb` | Largest attachment `get_attachment` returns as content |
|
|
153
142
|
| `ui.cookieSecret` | Signs the UI session cookie |
|
|
154
143
|
| `ui.loginLinkTtlMin` | Minutes before an unused login link expires |
|
|
144
|
+
| `ui.undoSec` | Seconds a Send or Discard in the UI waits before it happens, with an Undo button |
|
|
145
|
+
| `ui.maxUploadMb` | Largest file a reviewer can attach to a draft |
|
|
155
146
|
|
|
156
|
-
`mailboxes` is an object keyed by id rather than an array, so a
|
|
147
|
+
`mailboxes` is an object keyed by id rather than an array, so a per-environment override can replace 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
148
|
|
|
158
149
|
## Providers
|
|
159
150
|
|
|
@@ -167,7 +158,7 @@ interface MailProvider {
|
|
|
167
158
|
listInbound(since: Date): AsyncIterable<string>;
|
|
168
159
|
listOutbound(since: Date): AsyncIterable<{ providerId: string; status: DeliveryStatus }>;
|
|
169
160
|
send(message: OutboundMessage, idempotencyKey: string): Promise<{ providerId: string }>;
|
|
170
|
-
|
|
161
|
+
getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array>;
|
|
171
162
|
}
|
|
172
163
|
|
|
173
164
|
type ProviderEvent =
|
|
@@ -177,7 +168,7 @@ type ProviderEvent =
|
|
|
177
168
|
type DeliveryStatus = "sent" | "delivered" | "bounced" | "failed";
|
|
178
169
|
```
|
|
179
170
|
|
|
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`.
|
|
171
|
+
`OutboundMessage.attachments` carries the draft's files as `{ filename, contentType, content }`. `InboundMessage.attachments` lists `{ id, filename, content_type, size, inline, content_id }`; `inline` marks an image embedded in the body by `cid:`. `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
172
|
|
|
182
173
|
### Resend
|
|
183
174
|
|
|
@@ -188,7 +179,7 @@ Resend handles sending and receiving. Inboxer talks to it in three ways:
|
|
|
188
179
|
| Direction | How |
|
|
189
180
|
| --- | --- |
|
|
190
181
|
| 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
|
|
182
|
+
| Inboxer → Resend | The REST API with your API key: fetch received emails and their attachments, send, read delivery status |
|
|
192
183
|
| Backup | Every `syncIntervalMin` minutes Inboxer lists recent received and sent emails, in case a webhook was lost |
|
|
193
184
|
|
|
194
185
|
#### Setting up Resend and your domain
|
|
@@ -220,17 +211,15 @@ The MCP server is at `<publicUrl>/mcp`. It speaks Streamable HTTP without sessio
|
|
|
220
211
|
|
|
221
212
|
### Connecting a client
|
|
222
213
|
|
|
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
|
|
214
|
+
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`:
|
|
224
215
|
|
|
225
216
|
```javascript
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
"laptop": "a71e..."
|
|
231
|
-
}
|
|
217
|
+
mcp: {
|
|
218
|
+
tokens: {
|
|
219
|
+
"support-schedule": "3f9c...", // openssl rand -hex 32
|
|
220
|
+
"laptop": "a71e..."
|
|
232
221
|
}
|
|
233
|
-
}
|
|
222
|
+
}
|
|
234
223
|
```
|
|
235
224
|
|
|
236
225
|
Restart Inboxer to load it. To revoke a token, delete its entry and restart.
|
|
@@ -240,13 +229,11 @@ Restart Inboxer to load it. To revoke a token, delete its entry and restart.
|
|
|
240
229
|
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
230
|
|
|
242
231
|
```javascript
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
}
|
|
249
|
-
};
|
|
232
|
+
mcp: { tokens: { "admin": "3f9c..." } }, // every mailbox
|
|
233
|
+
mailboxes: {
|
|
234
|
+
feedback: { address: "feedback@example.com", name: "Example", tokens: { "feedback-bot": "a71e..." } }, // only feedback
|
|
235
|
+
legal: { address: "legal@example.com", name: "Legal", tokens: { "legal-team": "c2d4..." } } // only legal
|
|
236
|
+
}
|
|
250
237
|
```
|
|
251
238
|
|
|
252
239
|
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.
|
|
@@ -290,7 +277,7 @@ Ask the client to call `list_mailboxes` to check the connection. Connectors that
|
|
|
290
277
|
| `update_draft(id, version, ..., force?)` | Requires the current `version`; refuses a draft a human edited unless `force: true` |
|
|
291
278
|
| `list_drafts(mailbox?)` · `discard_draft(id)` · `send_draft(id)` | Draft lifecycle; `send_draft` sends the last saved version |
|
|
292
279
|
| `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)` |
|
|
280
|
+
| `get_attachment(message_id, attachment_id)` | The attachment itself: images as image content the model can see, text as text, anything else (PDF, documents) as an embedded resource. Up to `mcp.maxAttachmentMb` |
|
|
294
281
|
| `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
282
|
|
|
296
283
|
### Context
|
|
@@ -308,10 +295,10 @@ Every thread, message and draft in a result carries a `url` that opens it in the
|
|
|
308
295
|
|
|
309
296
|
The UI is server-rendered with Hono and htmx, without a front-end build, and works on a phone.
|
|
310
297
|
|
|
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.
|
|
298
|
+
- **Drafts:** mailbox, recipient, the agent's note and the thread underneath, newest first, with Edit, Send and Discard. Send and Discard happen after `ui.undoSec` seconds, with an Undo button meanwhile; the wait runs on the server, so closing the tab does not cancel it and a restart resumes it. Agents cannot change a draft during that window.
|
|
299
|
+
- **Editing:** To, Cc, Subject and a plain-text body, with Save and Save & Send. Attach files with the Attach button or by dropping them on the editor; they go out with the message. 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
300
|
- **Inbox:** threads per mailbox, filtered by mailbox and by unanswered, all or archived.
|
|
314
|
-
- **Thread:** messages
|
|
301
|
+
- **Thread:** messages newest first, as plain text, with the context agents stored for the thread and its participants. Incoming HTML is never rendered. Images, embedded ones included, show as thumbnails under the message and other attachments as file links. Only common image types and PDFs open in the browser, sandboxed; everything else downloads.
|
|
315
302
|
- **Devices:** the browsers signed in, each with a Revoke button.
|
|
316
303
|
|
|
317
304
|
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`.
|
|
@@ -329,11 +316,10 @@ If you have no MCP client at hand, mint a link from a script on the server, with
|
|
|
329
316
|
|
|
330
317
|
```javascript
|
|
331
318
|
// login-link.mjs
|
|
332
|
-
import Configre from "configre";
|
|
333
|
-
import { join } from "node:path";
|
|
334
319
|
import { createLoginLink } from "inboxer";
|
|
320
|
+
import { config } from "./config.js"; // however the app loads it
|
|
335
321
|
|
|
336
|
-
const { url } = await createLoginLink(
|
|
322
|
+
const { url } = await createLoginLink(config, { label: process.argv[2] });
|
|
337
323
|
console.log(url);
|
|
338
324
|
```
|
|
339
325
|
|
|
@@ -358,6 +344,8 @@ DeepBase is a nested key-value store without secondary indexes, so Inboxer maint
|
|
|
358
344
|
| `audit/<id>` | Sends, edits, discards, labels, context changes, login links and session changes, with the actor |
|
|
359
345
|
| `login_links/<sha256>` · `sessions/<sha256>` | UI access |
|
|
360
346
|
|
|
347
|
+
Inbound attachments are copied to `<dataDir>/attachments/<message id>/` when the message arrives, so they outlive the provider's retention. One that fails to download is fetched again the first time it is opened.
|
|
348
|
+
|
|
361
349
|
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
350
|
|
|
363
351
|
## Agent skill
|
package/dist/config.js
CHANGED
|
@@ -44,8 +44,11 @@ export function assertConfig(cfg, { requireProvider }) {
|
|
|
44
44
|
for (const [name, token] of Object.entries(cfg.mcp.tokens))
|
|
45
45
|
requireString(token, `mcp.tokens.${name}`);
|
|
46
46
|
mcpTokens(cfg);
|
|
47
|
+
requirePositive(cfg.mcp.maxAttachmentMb, "mcp.maxAttachmentMb");
|
|
47
48
|
requireString(cfg.ui?.cookieSecret, "ui.cookieSecret");
|
|
48
49
|
requirePositive(cfg.ui?.loginLinkTtlMin, "ui.loginLinkTtlMin");
|
|
50
|
+
requirePositive(cfg.ui?.undoSec, "ui.undoSec");
|
|
51
|
+
requirePositive(cfg.ui?.maxUploadMb, "ui.maxUploadMb");
|
|
49
52
|
}
|
|
50
53
|
/**
|
|
51
54
|
* Tokens in `mcp.tokens` reach every mailbox; tokens under `mailboxes.<id>.tokens` reach only that
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Inbound attachment bytes on disk, under `<dataDir>/attachments/<message id>/`, so they outlive the provider's retention. */
|
|
2
|
+
export declare class AttachmentFiles {
|
|
3
|
+
private readonly dir;
|
|
4
|
+
constructor(dataDir: string);
|
|
5
|
+
private path;
|
|
6
|
+
read(messageId: string, attachmentId: string): Promise<Uint8Array | null>;
|
|
7
|
+
/** Writes through a temporary file, so a crash never leaves a partial attachment behind. */
|
|
8
|
+
write(messageId: string, attachmentId: string, body: Uint8Array): Promise<void>;
|
|
9
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
/** Inbound attachment bytes on disk, under `<dataDir>/attachments/<message id>/`, so they outlive the provider's retention. */
|
|
5
|
+
export class AttachmentFiles {
|
|
6
|
+
dir;
|
|
7
|
+
constructor(dataDir) {
|
|
8
|
+
this.dir = join(dataDir, "attachments");
|
|
9
|
+
}
|
|
10
|
+
path(messageId, attachmentId) {
|
|
11
|
+
return join(this.dir, messageId, createHash("sha1").update(attachmentId).digest("hex"));
|
|
12
|
+
}
|
|
13
|
+
async read(messageId, attachmentId) {
|
|
14
|
+
try {
|
|
15
|
+
return await readFile(this.path(messageId, attachmentId));
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
if (err.code === "ENOENT")
|
|
19
|
+
return null;
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Writes through a temporary file, so a crash never leaves a partial attachment behind. */
|
|
24
|
+
async write(messageId, attachmentId, body) {
|
|
25
|
+
const target = this.path(messageId, attachmentId);
|
|
26
|
+
await mkdir(join(this.dir, messageId), { recursive: true });
|
|
27
|
+
await writeFile(`${target}.tmp`, body);
|
|
28
|
+
await rename(`${target}.tmp`, target);
|
|
29
|
+
}
|
|
30
|
+
}
|
package/dist/core/mail.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { DeliveryStatus, MailProvider, ProviderEvent } from "../provider/types.ts";
|
|
2
2
|
import { type Store } from "../store.ts";
|
|
3
|
-
import { type Actor, type Contact, type Context, type InboxerConfig, type Message, type MetaValue, type Scope, type Thread } from "../types.ts";
|
|
3
|
+
import { type Actor, type Contact, type Context, type AttachmentMeta, type InboxerConfig, type Message, type MetaValue, type PendingAction, type Scope, type Thread } from "../types.ts";
|
|
4
4
|
import { type ContextPatch } from "./context.ts";
|
|
5
5
|
export declare class ConflictError extends Error {
|
|
6
6
|
readonly current: Message;
|
|
@@ -74,6 +74,8 @@ export declare class Mail {
|
|
|
74
74
|
readonly provider: MailProvider;
|
|
75
75
|
readonly cfg: InboxerConfig;
|
|
76
76
|
private readonly ownAddresses;
|
|
77
|
+
private readonly timers;
|
|
78
|
+
private readonly files;
|
|
77
79
|
constructor(store: Store, provider: MailProvider, cfg: InboxerConfig);
|
|
78
80
|
listMailboxes(scope: Scope): {
|
|
79
81
|
id: string;
|
|
@@ -86,8 +88,12 @@ export declare class Mail {
|
|
|
86
88
|
private requireContactAccess;
|
|
87
89
|
private mailboxFor;
|
|
88
90
|
private sendingMailbox;
|
|
89
|
-
/**
|
|
91
|
+
/**
|
|
92
|
+
* Stores an inbound message once per provider id and returns its id. Attachments are copied to
|
|
93
|
+
* disk right away; one that fails to download is fetched again the first time it is opened.
|
|
94
|
+
*/
|
|
90
95
|
ingest(providerId: string): Promise<string>;
|
|
96
|
+
private storeInbound;
|
|
91
97
|
applyEvent(event: ProviderEvent): Promise<void>;
|
|
92
98
|
/** Status updates never move backwards: a late `sent` does not overwrite `delivered`. */
|
|
93
99
|
applyStatus(providerId: string, status: DeliveryStatus, messageId: string | null): Promise<void>;
|
|
@@ -128,6 +134,23 @@ export declare class Mail {
|
|
|
128
134
|
*/
|
|
129
135
|
updateDraft(id: string, version: number, patch: DraftPatch, actor: Actor, force?: boolean): Promise<Message>;
|
|
130
136
|
discardDraft(id: string, actor: Actor): Promise<void>;
|
|
137
|
+
private discardDraftUnlocked;
|
|
138
|
+
/** Attaching does not change `version`: it never conflicts with text edits in flight. */
|
|
139
|
+
attach(id: string, file: {
|
|
140
|
+
filename: string;
|
|
141
|
+
contentType: string;
|
|
142
|
+
body: Uint8Array;
|
|
143
|
+
}, actor: Actor): Promise<Message>;
|
|
144
|
+
detach(id: string, attachmentId: string, actor: Actor): Promise<Message>;
|
|
145
|
+
/** Starts the undo window for a send or discard. Calling it again keeps the first one. */
|
|
146
|
+
schedule(id: string, action: PendingAction["action"], actor: Actor): Promise<Message>;
|
|
147
|
+
undo(id: string, actor: Actor): Promise<Message>;
|
|
148
|
+
/** Re-arms undo windows left by a previous process; overdue ones run now. */
|
|
149
|
+
resumePending(): Promise<void>;
|
|
150
|
+
stopPending(): void;
|
|
151
|
+
private arm;
|
|
152
|
+
/** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
|
|
153
|
+
private runPending;
|
|
131
154
|
sendDraft(id: string, actor: Actor): Promise<Message>;
|
|
132
155
|
/**
|
|
133
156
|
* The draft id is the idempotency key and the Message-ID is stored before the provider call,
|
|
@@ -137,6 +160,11 @@ export declare class Mail {
|
|
|
137
160
|
/** Direct send. If the provider fails, the message stays as a pending draft. */
|
|
138
161
|
send(input: CreateDraftInput, actor: Actor): Promise<Message>;
|
|
139
162
|
reply(messageId: string, text: string, replyAll: boolean, actor: Actor): Promise<Message>;
|
|
140
|
-
|
|
163
|
+
/** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
|
|
164
|
+
getAttachment(messageId: string, attachmentId: string, scope: Scope): Promise<{
|
|
165
|
+
meta: AttachmentMeta;
|
|
166
|
+
body: Uint8Array;
|
|
167
|
+
}>;
|
|
168
|
+
private attachmentBody;
|
|
141
169
|
}
|
|
142
170
|
export declare function toView(m: Message): MessageView;
|
package/dist/core/mail.js
CHANGED
|
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import { reaches } from "../config.js";
|
|
3
3
|
import { NotFoundError, nid } from "../store.js";
|
|
4
4
|
import { CATCHALL } from "../types.js";
|
|
5
|
+
import { AttachmentFiles } from "./attachments.js";
|
|
5
6
|
import { bareAddress, domainOf, formatAddress } from "./address.js";
|
|
6
7
|
import { mergeContext, metaMatches } from "./context.js";
|
|
7
8
|
import { htmlToText, replySubject, textToHtml, tokenize } from "./text.js";
|
|
@@ -27,11 +28,14 @@ export class Mail {
|
|
|
27
28
|
provider;
|
|
28
29
|
cfg;
|
|
29
30
|
ownAddresses;
|
|
31
|
+
timers = new Map();
|
|
32
|
+
files;
|
|
30
33
|
constructor(store, provider, cfg) {
|
|
31
34
|
this.store = store;
|
|
32
35
|
this.provider = provider;
|
|
33
36
|
this.cfg = cfg;
|
|
34
37
|
this.ownAddresses = new Set(Object.values(cfg.mailboxes).map(m => bareAddress(m.address)));
|
|
38
|
+
this.files = new AttachmentFiles(cfg.dataDir);
|
|
35
39
|
}
|
|
36
40
|
listMailboxes(scope) {
|
|
37
41
|
return [
|
|
@@ -76,12 +80,23 @@ export class Mail {
|
|
|
76
80
|
return mailbox;
|
|
77
81
|
}
|
|
78
82
|
// Inbound
|
|
79
|
-
/**
|
|
83
|
+
/**
|
|
84
|
+
* Stores an inbound message once per provider id and returns its id. Attachments are copied to
|
|
85
|
+
* disk right away; one that fails to download is fetched again the first time it is opened.
|
|
86
|
+
*/
|
|
80
87
|
async ingest(providerId) {
|
|
81
88
|
const known = await this.store.lookupProviderId(this.provider.name, providerId);
|
|
82
89
|
if (known)
|
|
83
90
|
return known;
|
|
84
91
|
const inbound = await this.provider.getInbound(providerId);
|
|
92
|
+
const id = await this.storeInbound(providerId, inbound);
|
|
93
|
+
const message = await this.store.requireMessage(id);
|
|
94
|
+
for (const meta of message.attachments) {
|
|
95
|
+
await this.attachmentBody(message, meta).catch(err => console.error(`inboxer: attachment ${meta.id} of message ${id} not stored`, err));
|
|
96
|
+
}
|
|
97
|
+
return id;
|
|
98
|
+
}
|
|
99
|
+
storeInbound(providerId, inbound) {
|
|
85
100
|
return this.store.serialize(async () => {
|
|
86
101
|
const existing = await this.store.lookupProviderId(this.provider.name, providerId);
|
|
87
102
|
if (existing)
|
|
@@ -126,6 +141,7 @@ export class Mail {
|
|
|
126
141
|
sent_at: null,
|
|
127
142
|
version: 1,
|
|
128
143
|
edited_by_human: false,
|
|
144
|
+
pending: null,
|
|
129
145
|
};
|
|
130
146
|
await this.store.putMessage(message);
|
|
131
147
|
await this.store.indexProviderId(this.provider.name, inbound.providerId, message.id);
|
|
@@ -385,6 +401,7 @@ export class Mail {
|
|
|
385
401
|
sent_at: null,
|
|
386
402
|
version: 1,
|
|
387
403
|
edited_by_human: actor.kind === "ui",
|
|
404
|
+
pending: null,
|
|
388
405
|
};
|
|
389
406
|
await this.store.putMessage(draft);
|
|
390
407
|
await this.store.setDraft(draft.id, true);
|
|
@@ -407,6 +424,8 @@ export class Mail {
|
|
|
407
424
|
const draft = await this.requireDraft(id, actor.scope);
|
|
408
425
|
if (draft.version !== version)
|
|
409
426
|
throw new ConflictError(draft);
|
|
427
|
+
if (draft.pending)
|
|
428
|
+
throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
410
429
|
if (actor.kind !== "ui" && draft.edited_by_human && !force) {
|
|
411
430
|
throw new InvalidRequestError(`Draft ${id} was edited by a human; pass force to overwrite it`);
|
|
412
431
|
}
|
|
@@ -425,13 +444,115 @@ export class Mail {
|
|
|
425
444
|
});
|
|
426
445
|
}
|
|
427
446
|
discardDraft(id, actor) {
|
|
447
|
+
return this.store.serialize(() => this.discardDraftUnlocked(id, actor));
|
|
448
|
+
}
|
|
449
|
+
async discardDraftUnlocked(id, actor) {
|
|
450
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
451
|
+
draft.status = "discarded";
|
|
452
|
+
draft.pending = null;
|
|
453
|
+
await this.store.putMessage(draft);
|
|
454
|
+
await this.store.setDraft(id, false);
|
|
455
|
+
await refreshThread(this.store, draft.thread_id);
|
|
456
|
+
await this.store.audit("draft.discard", actor, id);
|
|
457
|
+
}
|
|
458
|
+
/** Attaching does not change `version`: it never conflicts with text edits in flight. */
|
|
459
|
+
attach(id, file, actor) {
|
|
428
460
|
return this.store.serialize(async () => {
|
|
429
461
|
const draft = await this.requireDraft(id, actor.scope);
|
|
430
|
-
draft.
|
|
462
|
+
if (draft.pending)
|
|
463
|
+
throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
464
|
+
const meta = {
|
|
465
|
+
id: nid(),
|
|
466
|
+
filename: file.filename,
|
|
467
|
+
content_type: file.contentType || "application/octet-stream",
|
|
468
|
+
size: file.body.byteLength,
|
|
469
|
+
inline: false,
|
|
470
|
+
content_id: null,
|
|
471
|
+
};
|
|
472
|
+
await this.files.write(draft.id, meta.id, file.body);
|
|
473
|
+
draft.attachments.push(meta);
|
|
431
474
|
await this.store.putMessage(draft);
|
|
432
|
-
await this.store.
|
|
433
|
-
|
|
434
|
-
|
|
475
|
+
await this.store.audit("draft.attach", actor, id, { filename: meta.filename, size: meta.size });
|
|
476
|
+
return draft;
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
detach(id, attachmentId, actor) {
|
|
480
|
+
return this.store.serialize(async () => {
|
|
481
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
482
|
+
if (draft.pending)
|
|
483
|
+
throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
484
|
+
const index = draft.attachments.findIndex(a => a.id === attachmentId);
|
|
485
|
+
if (index < 0)
|
|
486
|
+
throw new NotFoundError(`Attachment ${attachmentId} not found in draft ${id}`);
|
|
487
|
+
const [removed] = draft.attachments.splice(index, 1);
|
|
488
|
+
await this.store.putMessage(draft);
|
|
489
|
+
await this.store.audit("draft.detach", actor, id, { filename: removed.filename });
|
|
490
|
+
return draft;
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
// Undo window: a human's send or discard waits `ui.undoSec` and survives a restart.
|
|
494
|
+
/** Starts the undo window for a send or discard. Calling it again keeps the first one. */
|
|
495
|
+
schedule(id, action, actor) {
|
|
496
|
+
return this.store.serialize(async () => {
|
|
497
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
498
|
+
if (!draft.pending) {
|
|
499
|
+
draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
|
|
500
|
+
await this.store.putMessage(draft);
|
|
501
|
+
await this.store.audit("draft.schedule", actor, id, { action });
|
|
502
|
+
}
|
|
503
|
+
this.arm(draft);
|
|
504
|
+
return draft;
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
undo(id, actor) {
|
|
508
|
+
return this.store.serialize(async () => {
|
|
509
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
510
|
+
clearTimeout(this.timers.get(id));
|
|
511
|
+
this.timers.delete(id);
|
|
512
|
+
if (draft.pending) {
|
|
513
|
+
const { action } = draft.pending;
|
|
514
|
+
draft.pending = null;
|
|
515
|
+
await this.store.putMessage(draft);
|
|
516
|
+
await this.store.audit("draft.undo", actor, id, { action });
|
|
517
|
+
}
|
|
518
|
+
return draft;
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
/** Re-arms undo windows left by a previous process; overdue ones run now. */
|
|
522
|
+
async resumePending() {
|
|
523
|
+
for (const id of await this.store.draftIds()) {
|
|
524
|
+
const draft = await this.store.requireMessage(id);
|
|
525
|
+
if (draft.pending)
|
|
526
|
+
this.arm(draft);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
stopPending() {
|
|
530
|
+
for (const timer of this.timers.values())
|
|
531
|
+
clearTimeout(timer);
|
|
532
|
+
this.timers.clear();
|
|
533
|
+
}
|
|
534
|
+
arm(draft) {
|
|
535
|
+
clearTimeout(this.timers.get(draft.id));
|
|
536
|
+
const delay = Math.max(0, Date.parse(draft.pending.at) - Date.now());
|
|
537
|
+
this.timers.set(draft.id, setTimeout(() => {
|
|
538
|
+
this.runPending(draft.id).catch(err => console.error(`inboxer: pending action on draft ${draft.id} failed`, err));
|
|
539
|
+
}, delay));
|
|
540
|
+
}
|
|
541
|
+
/** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
|
|
542
|
+
runPending(id) {
|
|
543
|
+
this.timers.delete(id);
|
|
544
|
+
return this.store.serialize(async () => {
|
|
545
|
+
const draft = await this.store.getMessage(id);
|
|
546
|
+
if (!draft || draft.status !== "draft" || !draft.pending)
|
|
547
|
+
return;
|
|
548
|
+
const { action, by } = draft.pending;
|
|
549
|
+
const actor = { kind: "ui", name: by, scope: null };
|
|
550
|
+
draft.pending = null;
|
|
551
|
+
await this.store.putMessage(draft);
|
|
552
|
+
if (action === "send")
|
|
553
|
+
await this.sendDraftUnlocked(id, actor);
|
|
554
|
+
else
|
|
555
|
+
await this.discardDraftUnlocked(id, actor);
|
|
435
556
|
});
|
|
436
557
|
}
|
|
437
558
|
sendDraft(id, actor) {
|
|
@@ -453,6 +574,11 @@ export class Mail {
|
|
|
453
574
|
headers["In-Reply-To"] = draft.in_reply_to;
|
|
454
575
|
if (draft.references.length)
|
|
455
576
|
headers["References"] = draft.references.join(" ");
|
|
577
|
+
const attachments = await Promise.all(draft.attachments.map(async (a) => ({
|
|
578
|
+
filename: a.filename,
|
|
579
|
+
contentType: a.content_type,
|
|
580
|
+
content: await this.attachmentBody(draft, a),
|
|
581
|
+
})));
|
|
456
582
|
const { providerId } = await this.provider.send({
|
|
457
583
|
from: draft.from,
|
|
458
584
|
to: draft.to,
|
|
@@ -463,8 +589,10 @@ export class Mail {
|
|
|
463
589
|
text: sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
|
|
464
590
|
html: (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
|
|
465
591
|
headers,
|
|
592
|
+
attachments,
|
|
466
593
|
}, draft.id);
|
|
467
594
|
draft.status = "sent";
|
|
595
|
+
draft.pending = null;
|
|
468
596
|
draft.provider_id = providerId;
|
|
469
597
|
draft.sent_at = new Date().toISOString();
|
|
470
598
|
draft.headers = headers;
|
|
@@ -486,15 +614,23 @@ export class Mail {
|
|
|
486
614
|
reply(messageId, text, replyAll, actor) {
|
|
487
615
|
return this.send({ replyToId: messageId, replyAll, text }, actor);
|
|
488
616
|
}
|
|
489
|
-
|
|
617
|
+
/** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
|
|
618
|
+
async getAttachment(messageId, attachmentId, scope) {
|
|
490
619
|
const message = await this.requireMessage(messageId, scope);
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
620
|
+
const meta = message.attachments.find(a => a.id === attachmentId);
|
|
621
|
+
if (!meta)
|
|
622
|
+
throw new NotFoundError(`Attachment ${attachmentId} not found in message ${messageId}`);
|
|
623
|
+
return { meta, body: await this.attachmentBody(message, meta) };
|
|
624
|
+
}
|
|
625
|
+
async attachmentBody(message, meta) {
|
|
626
|
+
const stored = await this.files.read(message.id, meta.id);
|
|
627
|
+
if (stored)
|
|
628
|
+
return stored;
|
|
629
|
+
if (!message.provider_id || message.direction !== "in")
|
|
630
|
+
throw new NotFoundError(`Attachment ${meta.id} not found`);
|
|
631
|
+
const body = await this.provider.getAttachment(message.provider_id, meta.id);
|
|
632
|
+
await this.files.write(message.id, meta.id, body);
|
|
633
|
+
return body;
|
|
498
634
|
}
|
|
499
635
|
}
|
|
500
636
|
export function toView(m) {
|
package/dist/index.d.ts
CHANGED
|
@@ -31,5 +31,5 @@ export declare function createLoginLink(cfg: InboxerConfig, options?: LoginLinkO
|
|
|
31
31
|
expires_at: string;
|
|
32
32
|
}>;
|
|
33
33
|
export { WebhookSignatureError } from "./provider/types.ts";
|
|
34
|
-
export type { DeliveryStatus, InboundMessage, MailProvider, OutboundMessage, OutboundStatus, ProviderEvent, WebhookRequest, } from "./provider/types.ts";
|
|
34
|
+
export type { DeliveryStatus, InboundMessage, MailProvider, OutboundAttachment, OutboundMessage, OutboundStatus, ProviderEvent, WebhookRequest, } from "./provider/types.ts";
|
|
35
35
|
export type { InboxerConfig, MailboxConfig, ProviderConfig } from "./types.ts";
|
package/dist/index.js
CHANGED
|
@@ -15,6 +15,7 @@ export function createInboxer(cfg, options = {}) {
|
|
|
15
15
|
const sync = new Sync(mail, cfg.syncIntervalMin);
|
|
16
16
|
const ready = (async () => {
|
|
17
17
|
await store.connect();
|
|
18
|
+
await mail.resumePending();
|
|
18
19
|
await sync.run().catch(err => console.error("inboxer: initial sync failed", err));
|
|
19
20
|
sync.start();
|
|
20
21
|
})();
|
|
@@ -26,6 +27,7 @@ export function createInboxer(cfg, options = {}) {
|
|
|
26
27
|
ready,
|
|
27
28
|
async close() {
|
|
28
29
|
await ready.catch(() => { });
|
|
30
|
+
mail.stopPending();
|
|
29
31
|
await sync.stop();
|
|
30
32
|
await store.close();
|
|
31
33
|
},
|