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/dist/ui/views.js
CHANGED
|
@@ -28,6 +28,7 @@ export function layout(title, body, opts) {
|
|
|
28
28
|
<title>${title} · ${S.appName}</title>
|
|
29
29
|
<link rel="stylesheet" href="${ASSETS["style.css"].url}">
|
|
30
30
|
<script src="${ASSETS["htmx.min.js"].url}" defer></script>
|
|
31
|
+
<script src="${ASSETS["app.js"].url}" defer></script>
|
|
31
32
|
</head>
|
|
32
33
|
<body>
|
|
33
34
|
${when(opts.signedIn, () => h `<header>
|
|
@@ -43,7 +44,7 @@ ${when(opts.signedIn, () => h `<header>
|
|
|
43
44
|
</form>
|
|
44
45
|
<form method="post" action="/logout"><button class="link">${S.logout}</button></form>
|
|
45
46
|
</header>`)}
|
|
46
|
-
<main>${body}</main>
|
|
47
|
+
<main>${when(opts.domains?.length, () => h `<div class="domain">${opts.domains.join(" · ")}</div>`)}${body}</main>
|
|
47
48
|
</body>
|
|
48
49
|
</html>`;
|
|
49
50
|
}
|
|
@@ -61,6 +62,39 @@ export function signIn(token, valid) {
|
|
|
61
62
|
function mailboxBadge(mailbox) {
|
|
62
63
|
return h `<span class="badge">${mailbox}</span>`;
|
|
63
64
|
}
|
|
65
|
+
const PREVIEWABLE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]);
|
|
66
|
+
/** Image types a browser renders without running code; SVG is left out on purpose. */
|
|
67
|
+
export function isPreviewable(contentType) {
|
|
68
|
+
return PREVIEWABLE.has(contentType);
|
|
69
|
+
}
|
|
70
|
+
function formatSize(bytes) {
|
|
71
|
+
if (bytes === null)
|
|
72
|
+
return "";
|
|
73
|
+
if (bytes < 1024)
|
|
74
|
+
return `${bytes} B`;
|
|
75
|
+
if (bytes < 1048576)
|
|
76
|
+
return `${Math.round(bytes / 1024)} KB`;
|
|
77
|
+
return `${(bytes / 1048576).toFixed(1)} MB`;
|
|
78
|
+
}
|
|
79
|
+
/** Images first as thumbnails, inline ones included; the rest as file links. */
|
|
80
|
+
function attachments(m) {
|
|
81
|
+
if (!m.attachments.length)
|
|
82
|
+
return "";
|
|
83
|
+
const href = (id) => `/attachments/${encodeURIComponent(m.id)}/${encodeURIComponent(id)}`;
|
|
84
|
+
const images = m.attachments.filter(a => isPreviewable(a.content_type));
|
|
85
|
+
const files = m.attachments.filter(a => !isPreviewable(a.content_type));
|
|
86
|
+
return h `${when(images.length, () => h `<div class="images">${join(images.map(a => h `<a href="${href(a.id)}" target="_blank" rel="noopener"><img src="${href(a.id)}" alt="${a.filename}" loading="lazy"></a>`))}</div>`)}
|
|
87
|
+
${when(files.length, () => h `<div class="files">${join(files.map(a => h `<a class="file" href="${href(a.id)}" target="_blank" rel="noopener"><span>${a.filename}</span><span class="size">${formatSize(a.size)}</span></a>`))}</div>`)}`;
|
|
88
|
+
}
|
|
89
|
+
/** Mail clients write "[image: name.png]" in the text part where an image sat; the image shows below instead. */
|
|
90
|
+
function withoutImagePlaceholders(m) {
|
|
91
|
+
let text = m.text;
|
|
92
|
+
for (const a of m.attachments) {
|
|
93
|
+
if (isPreviewable(a.content_type))
|
|
94
|
+
text = text.split(`[image: ${a.filename}]`).join("");
|
|
95
|
+
}
|
|
96
|
+
return text.replace(/\n{3,}/g, "\n\n").trim();
|
|
97
|
+
}
|
|
64
98
|
export function messageCard(m) {
|
|
65
99
|
return h `<article class="card ${m.direction}">
|
|
66
100
|
<div class="meta">
|
|
@@ -68,8 +102,9 @@ export function messageCard(m) {
|
|
|
68
102
|
<span>${formatDate(m.date)}</span>
|
|
69
103
|
${when(m.direction === "out" && m.status !== "draft", () => h `<span>${m.status}</span>`)}
|
|
70
104
|
</div>
|
|
71
|
-
|
|
72
|
-
<pre class="body">${m
|
|
105
|
+
${when(m.to.length || m.cc.length, () => h `<div class="meta">${when(m.to.length, () => h `<span>${S.to}: ${m.to.join(", ")}</span>`)}${when(m.cc.length, () => h `<span>${S.cc}: ${m.cc.join(", ")}</span>`)}</div>`)}
|
|
106
|
+
<pre class="body">${withoutImagePlaceholders(m)}</pre>
|
|
107
|
+
${attachments(m)}
|
|
73
108
|
</article>`;
|
|
74
109
|
}
|
|
75
110
|
/** Read-only context agents attached to the thread and its participants. */
|
|
@@ -88,7 +123,20 @@ function contextBlock(ctx) {
|
|
|
88
123
|
${when(r.note, () => h `<p>${r.note}</p>`)}
|
|
89
124
|
</section>`))}</details>`;
|
|
90
125
|
}
|
|
126
|
+
/** A send or discard in its undo window; reloads itself when the window closes. */
|
|
127
|
+
function pendingCard(d) {
|
|
128
|
+
const left = Math.max(0, Date.parse(d.pending.at) - Date.now());
|
|
129
|
+
return h `<article class="card pending" id="draft-${d.id}" hx-get="/drafts/${d.id}/card" hx-trigger="load delay:${left + 400}ms" hx-swap="outerHTML">
|
|
130
|
+
<div class="pending-row">
|
|
131
|
+
<span>${d.pending.action === "send" ? h `${S.sending} <strong>${d.to.join(", ")}</strong>` : S.discarding}</span>
|
|
132
|
+
<button hx-post="/drafts/${d.id}/undo" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.undo}</button>
|
|
133
|
+
</div>
|
|
134
|
+
<i class="countdown" style="animation-duration: ${left}ms"></i>
|
|
135
|
+
</article>`;
|
|
136
|
+
}
|
|
91
137
|
export function draftCard(d, history, ctx) {
|
|
138
|
+
if (d.pending)
|
|
139
|
+
return pendingCard(d);
|
|
92
140
|
return h `<article class="card" id="draft-${d.id}">
|
|
93
141
|
<div class="meta">
|
|
94
142
|
${mailboxBadge(d.mailbox)}
|
|
@@ -101,10 +149,11 @@ export function draftCard(d, history, ctx) {
|
|
|
101
149
|
${contextBlock(ctx)}
|
|
102
150
|
${when(d.note, () => h `<div class="note">${d.note}</div>`)}
|
|
103
151
|
<pre class="body">${d.text}</pre>
|
|
152
|
+
${attachments(d)}
|
|
104
153
|
<div class="actions">
|
|
105
154
|
<button hx-get="/drafts/${d.id}/edit" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.edit}</button>
|
|
106
|
-
<button class="primary" hx-post="/drafts/${d.id}/send" hx-target="#draft-${d.id}" hx-swap="outerHTML"
|
|
107
|
-
<button class="danger" hx-post="/drafts/${d.id}/discard" hx-target="#draft-${d.id}" hx-swap="outerHTML"
|
|
155
|
+
<button class="primary" hx-post="/drafts/${d.id}/send" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.send}</button>
|
|
156
|
+
<button class="danger" hx-post="/drafts/${d.id}/discard" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.discard}</button>
|
|
108
157
|
</div>
|
|
109
158
|
${when(history.length, () => h `<details>
|
|
110
159
|
<summary>${S.thread} (${history.length})</summary>
|
|
@@ -114,7 +163,8 @@ export function draftCard(d, history, ctx) {
|
|
|
114
163
|
}
|
|
115
164
|
export function draftEditor(d, form, conflict) {
|
|
116
165
|
const version = conflict ? conflict.version : d.version;
|
|
117
|
-
return h `<article class="card ${conflict ? "conflict" : ""}" id="draft-${d.id}">
|
|
166
|
+
return h `<article class="card ${conflict ? "conflict" : ""}" id="draft-${d.id}" data-drop>
|
|
167
|
+
<div class="drop-hint">${S.dropFiles}</div>
|
|
118
168
|
<div class="meta">${mailboxBadge(d.mailbox)}<span class="badge draft">${S.draft}</span></div>
|
|
119
169
|
${when(d.note, () => h `<div class="note">${d.note}</div>`)}
|
|
120
170
|
${when(conflict, () => h `<p class="warn">${S.conflictTitle}</p><div class="subject">${S.yourVersion}</div>`)}
|
|
@@ -134,9 +184,10 @@ export function draftEditor(d, form, conflict) {
|
|
|
134
184
|
<input id="subject-${d.id}" name="subject" value="${form.subject}" required>
|
|
135
185
|
</div>
|
|
136
186
|
<textarea id="text-${d.id}" name="text" aria-label="${S.body}" required>${form.text}</textarea>
|
|
187
|
+
${draftFiles(d, null)}
|
|
137
188
|
<div class="actions">
|
|
138
189
|
<button type="submit">${S.save}</button>
|
|
139
|
-
<button type="submit" name="send" value="1" class="primary"
|
|
190
|
+
<button type="submit" name="send" value="1" class="primary">${S.saveAndSend}</button>
|
|
140
191
|
<button type="button" class="link" hx-get="/drafts/${d.id}/card" hx-target="#draft-${d.id}" hx-swap="outerHTML">${S.cancel}</button>
|
|
141
192
|
</div>
|
|
142
193
|
</form>
|
|
@@ -150,6 +201,14 @@ export function draftEditor(d, form, conflict) {
|
|
|
150
201
|
</details>`)}
|
|
151
202
|
</article>`;
|
|
152
203
|
}
|
|
204
|
+
/** The editor's attachment list with remove buttons, and the picker that drag and drop also feeds. */
|
|
205
|
+
export function draftFiles(d, error) {
|
|
206
|
+
return h `<div class="draft-files" id="files-${d.id}">
|
|
207
|
+
${join(d.attachments.map(a => h `<span class="file"><span>${a.filename}</span><span class="size">${formatSize(a.size)}</span><button type="button" class="link" aria-label="${S.remove} ${a.filename}" hx-post="/drafts/${d.id}/attachments/${a.id}/remove" hx-target="#files-${d.id}" hx-swap="outerHTML">×</button></span>`))}
|
|
208
|
+
<label class="file attach">${S.attach}<input type="file" name="files" multiple hidden hx-post="/drafts/${d.id}/attachments" hx-encoding="multipart/form-data" hx-trigger="change" hx-target="#files-${d.id}" hx-swap="outerHTML" hx-include="this"></label>
|
|
209
|
+
${when(error, () => h `<p class="warn">${error}</p>`)}
|
|
210
|
+
</div>`;
|
|
211
|
+
}
|
|
153
212
|
export function draftDone(id, text) {
|
|
154
213
|
return h `<article class="card notice" id="draft-${id}">${text}</article>`;
|
|
155
214
|
}
|
|
@@ -187,7 +246,7 @@ function threadRow(t, own) {
|
|
|
187
246
|
}
|
|
188
247
|
export function threadPage(thread, items, ctx) {
|
|
189
248
|
return h `<h1>${thread.subject || "—"}</h1>
|
|
190
|
-
<div class="meta">${mailboxBadge(thread.mailbox)}${archiveButton(thread)}</div>
|
|
249
|
+
<div class="meta thread-head">${mailboxBadge(thread.mailbox)}${archiveButton(thread)}</div>
|
|
191
250
|
${contextBlock(ctx)}
|
|
192
251
|
<section class="messages">${join(items)}</section>`;
|
|
193
252
|
}
|
|
@@ -211,6 +270,6 @@ ${sessions.length ? join(sessions.map(s => h `<article class="card" id="session-
|
|
|
211
270
|
<span>${S.lastSeen}: ${formatDate(s.last_seen)}</span>
|
|
212
271
|
<span>${S.createdBy}: ${s.created_by}</span>
|
|
213
272
|
</div>
|
|
214
|
-
${when(s.id !== currentId, () => h `<div class="actions"><button class="danger" hx-post="/devices/${s.id}/revoke" hx-target="#session-${s.id}" hx-swap="delete"
|
|
273
|
+
${when(s.id !== currentId, () => h `<div class="actions"><button class="danger" hx-post="/devices/${s.id}/revoke" hx-target="#session-${s.id}" hx-swap="delete">${S.revoke}</button></div>`)}
|
|
215
274
|
</article>`)) : h `<p class="empty">${S.devicesEmpty}</p>`}`;
|
|
216
275
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "inboxer",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A self-hosted mail layer for agents: persists every inbound and outbound email, exposes an MCP server, and ships a minimal UI to review drafts.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -19,6 +19,13 @@
|
|
|
19
19
|
"engines": {
|
|
20
20
|
"node": ">=22.16.0"
|
|
21
21
|
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsc -p tsconfig.json && node -e \"require('node:fs').cpSync('src/ui/static','dist/ui/static',{recursive:true})\"",
|
|
24
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
25
|
+
"test": "node --test 'test/**/*.test.ts'",
|
|
26
|
+
"test:bun": "bun test test",
|
|
27
|
+
"prepack": "npm run build"
|
|
28
|
+
},
|
|
22
29
|
"keywords": [
|
|
23
30
|
"email",
|
|
24
31
|
"mail",
|
|
@@ -72,11 +79,5 @@
|
|
|
72
79
|
"devDependencies": {
|
|
73
80
|
"@types/node": "^22.20.5",
|
|
74
81
|
"typescript": "^7.0.2"
|
|
75
|
-
},
|
|
76
|
-
"scripts": {
|
|
77
|
-
"build": "tsc -p tsconfig.json && node -e \"require('node:fs').cpSync('src/ui/static','dist/ui/static',{recursive:true})\"",
|
|
78
|
-
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
79
|
-
"test": "node --test 'test/**/*.test.ts'",
|
|
80
|
-
"test:bun": "bun test test"
|
|
81
82
|
}
|
|
82
|
-
}
|
|
83
|
+
}
|
package/skills/inboxer/SKILL.md
CHANGED
|
@@ -12,50 +12,37 @@ Inboxer stores every inbound and outbound email in one SQLite file, exposes MCP
|
|
|
12
12
|
|
|
13
13
|
## Set up
|
|
14
14
|
|
|
15
|
-
Install with `npm install inboxer`; requires Node.js 22.16+ or Bun. `createInboxer` takes
|
|
16
|
-
|
|
17
|
-
`config/index.cjs` (public):
|
|
15
|
+
Install with `npm install inboxer`; requires Node.js 22.16+ or Bun. `createInboxer` takes one plain object; load it the way the project already loads configuration (JSON file, environment variables, a loader such as Configre).
|
|
18
16
|
|
|
19
17
|
```javascript
|
|
20
|
-
|
|
18
|
+
const config = {
|
|
21
19
|
publicUrl: "https://inboxer.example.com",
|
|
22
20
|
dataDir: "/var/lib/inboxer", // absolute
|
|
23
21
|
syncIntervalMin: 10,
|
|
24
22
|
threadWindowDays: 30,
|
|
25
23
|
mailboxes: {
|
|
26
24
|
support: { address: "support@example.com", name: "Example Support",
|
|
27
|
-
signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>"
|
|
25
|
+
signatureText: "-- Example Support", signatureHtml: "<p>-- Example Support</p>",
|
|
26
|
+
tokens: { "support-schedule": "<openssl rand -hex 32>" } } // support only
|
|
28
27
|
},
|
|
29
|
-
provider: { type: "resend" },
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
```
|
|
33
|
-
|
|
34
|
-
`config/index.secret.cjs` (Configre encrypts it):
|
|
35
|
-
|
|
36
|
-
```javascript
|
|
37
|
-
module.exports = {
|
|
38
|
-
provider: { apiKey: "re_...", webhookSecret: "whsec_..." },
|
|
39
|
-
mcp: { tokens: { "admin": "<openssl rand -hex 32>" } }, // every mailbox
|
|
40
|
-
mailboxes: { support: { tokens: { "support-schedule": "<openssl rand -hex 32>" } } }, // support only
|
|
41
|
-
ui: { cookieSecret: "<openssl rand -hex 32>" }
|
|
28
|
+
provider: { type: "resend", apiKey: "re_...", webhookSecret: "whsec_..." },
|
|
29
|
+
mcp: { tokens: { "admin": "<openssl rand -hex 32>" }, maxAttachmentMb: 10 }, // every mailbox
|
|
30
|
+
ui: { cookieSecret: "<openssl rand -hex 32>", loginLinkTtlMin: 10, undoSec: 10, maxUploadMb: 20 }
|
|
42
31
|
};
|
|
43
32
|
```
|
|
44
33
|
|
|
45
|
-
- Every key above is required except the mailbox signatures; `createInboxer` throws on a missing or invalid one. There are no defaults.
|
|
34
|
+
- Every key above is required except the mailbox signatures and mailbox tokens; `createInboxer` throws on a missing or invalid one. There are no defaults.
|
|
46
35
|
- `mailboxes` is an object keyed by id. `catchall` is reserved: unknown recipients land there, and it cannot send.
|
|
47
|
-
-
|
|
36
|
+
- `provider.apiKey`, `provider.webhookSecret`, every token and `ui.cookieSecret` are secrets: keep them out of Git and out of logs.
|
|
48
37
|
|
|
49
38
|
## Serve
|
|
50
39
|
|
|
51
40
|
`createInboxer(cfg, { provider? })` is synchronous, does not listen, and returns `{ fetch, handler, ready, close }`. Requests wait for `ready`.
|
|
52
41
|
|
|
53
42
|
```typescript
|
|
54
|
-
import Configre from "configre";
|
|
55
|
-
import { join } from "node:path";
|
|
56
43
|
import { createInboxer } from "inboxer";
|
|
57
44
|
|
|
58
|
-
const inboxer = createInboxer(
|
|
45
|
+
const inboxer = createInboxer(config);
|
|
59
46
|
Bun.serve({ port: 4000, fetch: inboxer.fetch }); // or createServer(inboxer.handler) on Node
|
|
60
47
|
```
|
|
61
48
|
|
|
@@ -85,7 +72,7 @@ Implement `MailProvider` (exported types) and pass it as `createInboxer(cfg, { p
|
|
|
85
72
|
|
|
86
73
|
One token per client, so the audit log names the actor and revoking one leaves the rest. Revoke by deleting the entry and restarting.
|
|
87
74
|
|
|
88
|
-
Tokens in `mcp.tokens` reach every mailbox. A token under `mailboxes.<id>.tokens`
|
|
75
|
+
Tokens in `mcp.tokens` reach every mailbox. A token under `mailboxes.<id>.tokens` reaches only that mailbox: everything else reads as not found, it reaches only contacts in its own threads, and its login links sign browsers into the same mailboxes. Repeat the same name and token under several mailboxes to reach all of them.
|
|
89
76
|
|
|
90
77
|
```bash
|
|
91
78
|
claude mcp add --transport http inboxer https://inboxer.example.com/mcp --header "Authorization: Bearer <token>"
|
|
@@ -108,11 +95,12 @@ Rules for agents:
|
|
|
108
95
|
- Put what the reviewer must do or check in `note`, not in the body. The note is never sent.
|
|
109
96
|
- A new conversation needs `mailbox`, `to` and `subject`.
|
|
110
97
|
- `update_draft` needs the draft's current `version`. On a conflict the error includes `current`; re-read it before retrying.
|
|
98
|
+
- A draft whose `pending` is set is in the reviewer's undo window and is about to be sent or discarded; `update_draft` fails until it ends.
|
|
111
99
|
- Never `force` an update of a draft with `edited_by_human: true` unless the user explicitly asks; the human's edit wins.
|
|
112
100
|
- `send_draft` sends the last saved version. A failed send leaves the draft pending and retrying is safe.
|
|
113
101
|
- `label` and `mark` accept message ids or thread ids; a thread id applies to every message in it. Archived threads come back to the inbox when a new message arrives.
|
|
114
102
|
- `search` matches every term, ignoring case and accents, across subject, body, from and to; narrow with `mailbox`, `from`, `since`, `until`, `meta`. Pass `query`, `meta`, or both.
|
|
115
|
-
- `get_attachment` returns
|
|
103
|
+
- Messages list their `attachments` (`inline: true` is an image embedded in the body). `get_attachment` returns the content: images as images you can look at, text as text, other files (PDF, documents) as an embedded resource. Files over `mcp.maxAttachmentMb` return an error. Agents cannot attach files to drafts; the reviewer can, in the UI, and they are listed in the draft's `attachments`.
|
|
116
104
|
- Threads, messages and drafts in results carry `url`, which opens them in the review UI (scrolled to the draft). When telling the user what you drafted or sent, include that `url`.
|
|
117
105
|
- Times are ISO 8601. `catchall` messages can be read and labeled but not answered from Inboxer.
|
|
118
106
|
|
package/src/config.ts
CHANGED
|
@@ -43,8 +43,11 @@ export function assertConfig(cfg: InboxerConfig, { requireProvider }: { requireP
|
|
|
43
43
|
if (!cfg.mcp?.tokens || typeof cfg.mcp.tokens !== "object") fail("mcp.tokens", "an object of named tokens");
|
|
44
44
|
for (const [name, token] of Object.entries(cfg.mcp.tokens)) requireString(token, `mcp.tokens.${name}`);
|
|
45
45
|
mcpTokens(cfg);
|
|
46
|
+
requirePositive(cfg.mcp.maxAttachmentMb, "mcp.maxAttachmentMb");
|
|
46
47
|
requireString(cfg.ui?.cookieSecret, "ui.cookieSecret");
|
|
47
48
|
requirePositive(cfg.ui?.loginLinkTtlMin, "ui.loginLinkTtlMin");
|
|
49
|
+
requirePositive(cfg.ui?.undoSec, "ui.undoSec");
|
|
50
|
+
requirePositive(cfg.ui?.maxUploadMb, "ui.maxUploadMb");
|
|
48
51
|
}
|
|
49
52
|
|
|
50
53
|
export interface McpToken {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Inbound attachment bytes on disk, under `<dataDir>/attachments/<message id>/`, so they outlive the provider's retention. */
|
|
6
|
+
export class AttachmentFiles {
|
|
7
|
+
private readonly dir: string;
|
|
8
|
+
|
|
9
|
+
constructor(dataDir: string) {
|
|
10
|
+
this.dir = join(dataDir, "attachments");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
private path(messageId: string, attachmentId: string): string {
|
|
14
|
+
return join(this.dir, messageId, createHash("sha1").update(attachmentId).digest("hex"));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async read(messageId: string, attachmentId: string): Promise<Uint8Array | null> {
|
|
18
|
+
try {
|
|
19
|
+
return await readFile(this.path(messageId, attachmentId));
|
|
20
|
+
} catch (err) {
|
|
21
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
|
|
22
|
+
throw err;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Writes through a temporary file, so a crash never leaves a partial attachment behind. */
|
|
27
|
+
async write(messageId: string, attachmentId: string, body: Uint8Array): Promise<void> {
|
|
28
|
+
const target = this.path(messageId, attachmentId);
|
|
29
|
+
await mkdir(join(this.dir, messageId), { recursive: true });
|
|
30
|
+
await writeFile(`${target}.tmp`, body);
|
|
31
|
+
await rename(`${target}.tmp`, target);
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/core/mail.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import type { DeliveryStatus, MailProvider, ProviderEvent } from "../provider/types.ts";
|
|
3
3
|
import { reaches } from "../config.ts";
|
|
4
4
|
import { NotFoundError, nid, type Store } from "../store.ts";
|
|
5
|
-
import { CATCHALL, type Actor, type Contact, type Context, type InboxerConfig, type MailboxConfig, type Message, type MetaValue, type Scope, type Thread } from "../types.ts";
|
|
5
|
+
import { CATCHALL, type Actor, type Contact, type Context, type AttachmentMeta, type InboxerConfig, type MailboxConfig, type Message, type MetaValue, type PendingAction, type Scope, type Thread } from "../types.ts";
|
|
6
|
+
import { AttachmentFiles } from "./attachments.ts";
|
|
6
7
|
import { bareAddress, domainOf, formatAddress } from "./address.ts";
|
|
7
8
|
import { mergeContext, metaMatches, type ContextPatch } from "./context.ts";
|
|
8
9
|
import { htmlToText, replySubject, textToHtml, tokenize } from "./text.ts";
|
|
@@ -97,12 +98,15 @@ export class Mail {
|
|
|
97
98
|
readonly provider: MailProvider;
|
|
98
99
|
readonly cfg: InboxerConfig;
|
|
99
100
|
private readonly ownAddresses: Set<string>;
|
|
101
|
+
private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
102
|
+
private readonly files: AttachmentFiles;
|
|
100
103
|
|
|
101
104
|
constructor(store: Store, provider: MailProvider, cfg: InboxerConfig) {
|
|
102
105
|
this.store = store;
|
|
103
106
|
this.provider = provider;
|
|
104
107
|
this.cfg = cfg;
|
|
105
108
|
this.ownAddresses = new Set(Object.values(cfg.mailboxes).map(m => bareAddress(m.address)));
|
|
109
|
+
this.files = new AttachmentFiles(cfg.dataDir);
|
|
106
110
|
}
|
|
107
111
|
|
|
108
112
|
listMailboxes(scope: Scope): { id: string; address: string; name: string }[] {
|
|
@@ -151,12 +155,24 @@ export class Mail {
|
|
|
151
155
|
|
|
152
156
|
// Inbound
|
|
153
157
|
|
|
154
|
-
/**
|
|
158
|
+
/**
|
|
159
|
+
* Stores an inbound message once per provider id and returns its id. Attachments are copied to
|
|
160
|
+
* disk right away; one that fails to download is fetched again the first time it is opened.
|
|
161
|
+
*/
|
|
155
162
|
async ingest(providerId: string): Promise<string> {
|
|
156
163
|
const known = await this.store.lookupProviderId(this.provider.name, providerId);
|
|
157
164
|
if (known) return known;
|
|
158
165
|
const inbound = await this.provider.getInbound(providerId);
|
|
166
|
+
const id = await this.storeInbound(providerId, inbound);
|
|
167
|
+
const message = await this.store.requireMessage(id);
|
|
168
|
+
for (const meta of message.attachments) {
|
|
169
|
+
await this.attachmentBody(message, meta).catch(err =>
|
|
170
|
+
console.error(`inboxer: attachment ${meta.id} of message ${id} not stored`, err));
|
|
171
|
+
}
|
|
172
|
+
return id;
|
|
173
|
+
}
|
|
159
174
|
|
|
175
|
+
private storeInbound(providerId: string, inbound: Awaited<ReturnType<MailProvider["getInbound"]>>): Promise<string> {
|
|
160
176
|
return this.store.serialize(async () => {
|
|
161
177
|
const existing = await this.store.lookupProviderId(this.provider.name, providerId);
|
|
162
178
|
if (existing) return existing;
|
|
@@ -206,6 +222,7 @@ export class Mail {
|
|
|
206
222
|
sent_at: null,
|
|
207
223
|
version: 1,
|
|
208
224
|
edited_by_human: false,
|
|
225
|
+
pending: null,
|
|
209
226
|
};
|
|
210
227
|
await this.store.putMessage(message);
|
|
211
228
|
await this.store.indexProviderId(this.provider.name, inbound.providerId, message.id);
|
|
@@ -457,6 +474,7 @@ export class Mail {
|
|
|
457
474
|
sent_at: null,
|
|
458
475
|
version: 1,
|
|
459
476
|
edited_by_human: actor.kind === "ui",
|
|
477
|
+
pending: null,
|
|
460
478
|
};
|
|
461
479
|
await this.store.putMessage(draft);
|
|
462
480
|
await this.store.setDraft(draft.id, true);
|
|
@@ -479,6 +497,7 @@ export class Mail {
|
|
|
479
497
|
return this.store.serialize(async () => {
|
|
480
498
|
const draft = await this.requireDraft(id, actor.scope);
|
|
481
499
|
if (draft.version !== version) throw new ConflictError(draft);
|
|
500
|
+
if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
482
501
|
if (actor.kind !== "ui" && draft.edited_by_human && !force) {
|
|
483
502
|
throw new InvalidRequestError(`Draft ${id} was edited by a human; pass force to overwrite it`);
|
|
484
503
|
}
|
|
@@ -497,13 +516,117 @@ export class Mail {
|
|
|
497
516
|
}
|
|
498
517
|
|
|
499
518
|
discardDraft(id: string, actor: Actor): Promise<void> {
|
|
519
|
+
return this.store.serialize(() => this.discardDraftUnlocked(id, actor));
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
private async discardDraftUnlocked(id: string, actor: Actor): Promise<void> {
|
|
523
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
524
|
+
draft.status = "discarded";
|
|
525
|
+
draft.pending = null;
|
|
526
|
+
await this.store.putMessage(draft);
|
|
527
|
+
await this.store.setDraft(id, false);
|
|
528
|
+
await refreshThread(this.store, draft.thread_id);
|
|
529
|
+
await this.store.audit("draft.discard", actor, id);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** Attaching does not change `version`: it never conflicts with text edits in flight. */
|
|
533
|
+
attach(id: string, file: { filename: string; contentType: string; body: Uint8Array }, actor: Actor): Promise<Message> {
|
|
534
|
+
return this.store.serialize(async () => {
|
|
535
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
536
|
+
if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
537
|
+
const meta: AttachmentMeta = {
|
|
538
|
+
id: nid(),
|
|
539
|
+
filename: file.filename,
|
|
540
|
+
content_type: file.contentType || "application/octet-stream",
|
|
541
|
+
size: file.body.byteLength,
|
|
542
|
+
inline: false,
|
|
543
|
+
content_id: null,
|
|
544
|
+
};
|
|
545
|
+
await this.files.write(draft.id, meta.id, file.body);
|
|
546
|
+
draft.attachments.push(meta);
|
|
547
|
+
await this.store.putMessage(draft);
|
|
548
|
+
await this.store.audit("draft.attach", actor, id, { filename: meta.filename, size: meta.size });
|
|
549
|
+
return draft;
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
detach(id: string, attachmentId: string, actor: Actor): Promise<Message> {
|
|
500
554
|
return this.store.serialize(async () => {
|
|
501
555
|
const draft = await this.requireDraft(id, actor.scope);
|
|
502
|
-
draft.
|
|
556
|
+
if (draft.pending) throw new InvalidRequestError(`Draft ${id} is about to ${draft.pending.action}; undo it first`);
|
|
557
|
+
const index = draft.attachments.findIndex(a => a.id === attachmentId);
|
|
558
|
+
if (index < 0) throw new NotFoundError(`Attachment ${attachmentId} not found in draft ${id}`);
|
|
559
|
+
const [removed] = draft.attachments.splice(index, 1);
|
|
503
560
|
await this.store.putMessage(draft);
|
|
504
|
-
await this.store.
|
|
505
|
-
|
|
506
|
-
|
|
561
|
+
await this.store.audit("draft.detach", actor, id, { filename: removed!.filename });
|
|
562
|
+
return draft;
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// Undo window: a human's send or discard waits `ui.undoSec` and survives a restart.
|
|
567
|
+
|
|
568
|
+
/** Starts the undo window for a send or discard. Calling it again keeps the first one. */
|
|
569
|
+
schedule(id: string, action: PendingAction["action"], actor: Actor): Promise<Message> {
|
|
570
|
+
return this.store.serialize(async () => {
|
|
571
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
572
|
+
if (!draft.pending) {
|
|
573
|
+
draft.pending = { action, at: new Date(Date.now() + this.cfg.ui.undoSec * 1000).toISOString(), by: actor.name };
|
|
574
|
+
await this.store.putMessage(draft);
|
|
575
|
+
await this.store.audit("draft.schedule", actor, id, { action });
|
|
576
|
+
}
|
|
577
|
+
this.arm(draft);
|
|
578
|
+
return draft;
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
undo(id: string, actor: Actor): Promise<Message> {
|
|
583
|
+
return this.store.serialize(async () => {
|
|
584
|
+
const draft = await this.requireDraft(id, actor.scope);
|
|
585
|
+
clearTimeout(this.timers.get(id));
|
|
586
|
+
this.timers.delete(id);
|
|
587
|
+
if (draft.pending) {
|
|
588
|
+
const { action } = draft.pending;
|
|
589
|
+
draft.pending = null;
|
|
590
|
+
await this.store.putMessage(draft);
|
|
591
|
+
await this.store.audit("draft.undo", actor, id, { action });
|
|
592
|
+
}
|
|
593
|
+
return draft;
|
|
594
|
+
});
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/** Re-arms undo windows left by a previous process; overdue ones run now. */
|
|
598
|
+
async resumePending(): Promise<void> {
|
|
599
|
+
for (const id of await this.store.draftIds()) {
|
|
600
|
+
const draft = await this.store.requireMessage(id);
|
|
601
|
+
if (draft.pending) this.arm(draft);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
stopPending(): void {
|
|
606
|
+
for (const timer of this.timers.values()) clearTimeout(timer);
|
|
607
|
+
this.timers.clear();
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
private arm(draft: Message): void {
|
|
611
|
+
clearTimeout(this.timers.get(draft.id));
|
|
612
|
+
const delay = Math.max(0, Date.parse(draft.pending!.at) - Date.now());
|
|
613
|
+
this.timers.set(draft.id, setTimeout(() => {
|
|
614
|
+
this.runPending(draft.id).catch(err => console.error(`inboxer: pending action on draft ${draft.id} failed`, err));
|
|
615
|
+
}, delay));
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** A failed send leaves a plain pending draft, so the reviewer sees it was not sent. */
|
|
619
|
+
private runPending(id: string): Promise<void> {
|
|
620
|
+
this.timers.delete(id);
|
|
621
|
+
return this.store.serialize(async () => {
|
|
622
|
+
const draft = await this.store.getMessage(id);
|
|
623
|
+
if (!draft || draft.status !== "draft" || !draft.pending) return;
|
|
624
|
+
const { action, by } = draft.pending;
|
|
625
|
+
const actor: Actor = { kind: "ui", name: by, scope: null };
|
|
626
|
+
draft.pending = null;
|
|
627
|
+
await this.store.putMessage(draft);
|
|
628
|
+
if (action === "send") await this.sendDraftUnlocked(id, actor);
|
|
629
|
+
else await this.discardDraftUnlocked(id, actor);
|
|
507
630
|
});
|
|
508
631
|
}
|
|
509
632
|
|
|
@@ -526,6 +649,11 @@ export class Mail {
|
|
|
526
649
|
if (draft.in_reply_to) headers["In-Reply-To"] = draft.in_reply_to;
|
|
527
650
|
if (draft.references.length) headers["References"] = draft.references.join(" ");
|
|
528
651
|
|
|
652
|
+
const attachments = await Promise.all(draft.attachments.map(async a => ({
|
|
653
|
+
filename: a.filename,
|
|
654
|
+
contentType: a.content_type,
|
|
655
|
+
content: await this.attachmentBody(draft, a),
|
|
656
|
+
})));
|
|
529
657
|
const { providerId } = await this.provider.send(
|
|
530
658
|
{
|
|
531
659
|
from: draft.from,
|
|
@@ -537,11 +665,13 @@ export class Mail {
|
|
|
537
665
|
text: sender.signatureText ? `${draft.text}\n\n${sender.signatureText}` : draft.text,
|
|
538
666
|
html: (draft.html ?? textToHtml(draft.text)) + (sender.signatureHtml ? `\n${sender.signatureHtml}` : ""),
|
|
539
667
|
headers,
|
|
668
|
+
attachments,
|
|
540
669
|
},
|
|
541
670
|
draft.id,
|
|
542
671
|
);
|
|
543
672
|
|
|
544
673
|
draft.status = "sent";
|
|
674
|
+
draft.pending = null;
|
|
545
675
|
draft.provider_id = providerId;
|
|
546
676
|
draft.sent_at = new Date().toISOString();
|
|
547
677
|
draft.headers = headers;
|
|
@@ -566,15 +696,21 @@ export class Mail {
|
|
|
566
696
|
return this.send({ replyToId: messageId, replyAll, text }, actor);
|
|
567
697
|
}
|
|
568
698
|
|
|
569
|
-
|
|
699
|
+
/** An inbound attachment's metadata and bytes, from disk or, the first time, from the provider. */
|
|
700
|
+
async getAttachment(messageId: string, attachmentId: string, scope: Scope): Promise<{ meta: AttachmentMeta; body: Uint8Array }> {
|
|
570
701
|
const message = await this.requireMessage(messageId, scope);
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
702
|
+
const meta = message.attachments.find(a => a.id === attachmentId);
|
|
703
|
+
if (!meta) throw new NotFoundError(`Attachment ${attachmentId} not found in message ${messageId}`);
|
|
704
|
+
return { meta, body: await this.attachmentBody(message, meta) };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
private async attachmentBody(message: Message, meta: AttachmentMeta): Promise<Uint8Array> {
|
|
708
|
+
const stored = await this.files.read(message.id, meta.id);
|
|
709
|
+
if (stored) return stored;
|
|
710
|
+
if (!message.provider_id || message.direction !== "in") throw new NotFoundError(`Attachment ${meta.id} not found`);
|
|
711
|
+
const body = await this.provider.getAttachment(message.provider_id, meta.id);
|
|
712
|
+
await this.files.write(message.id, meta.id, body);
|
|
713
|
+
return body;
|
|
578
714
|
}
|
|
579
715
|
}
|
|
580
716
|
|
package/src/index.ts
CHANGED
|
@@ -36,6 +36,7 @@ export function createInboxer(cfg: InboxerConfig, options: InboxerOptions = {}):
|
|
|
36
36
|
|
|
37
37
|
const ready = (async () => {
|
|
38
38
|
await store.connect();
|
|
39
|
+
await mail.resumePending();
|
|
39
40
|
await sync.run().catch(err => console.error("inboxer: initial sync failed", err));
|
|
40
41
|
sync.start();
|
|
41
42
|
})();
|
|
@@ -49,6 +50,7 @@ export function createInboxer(cfg: InboxerConfig, options: InboxerOptions = {}):
|
|
|
49
50
|
ready,
|
|
50
51
|
async close() {
|
|
51
52
|
await ready.catch(() => {});
|
|
53
|
+
mail.stopPending();
|
|
52
54
|
await sync.stop();
|
|
53
55
|
await store.close();
|
|
54
56
|
},
|
|
@@ -82,6 +84,7 @@ export type {
|
|
|
82
84
|
DeliveryStatus,
|
|
83
85
|
InboundMessage,
|
|
84
86
|
MailProvider,
|
|
87
|
+
OutboundAttachment,
|
|
85
88
|
OutboundMessage,
|
|
86
89
|
OutboundStatus,
|
|
87
90
|
ProviderEvent,
|