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/src/mcp.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
1
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
3
|
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import type { Access } from "./auth.ts";
|
|
5
6
|
import { appUrl, threadPath } from "./config.ts";
|
|
6
7
|
import { ConflictError, toView, type Mail, type MessageView } from "./core/mail.ts";
|
|
7
|
-
import type { Actor, InboxerConfig, Message, Thread } from "./types.ts";
|
|
8
|
+
import type { Actor, AttachmentMeta, InboxerConfig, Message, Thread } from "./types.ts";
|
|
8
9
|
|
|
9
|
-
const VERSION =
|
|
10
|
+
const { version: VERSION } = createRequire(import.meta.url)("../package.json") as { version: string };
|
|
10
11
|
|
|
11
12
|
function json(value: unknown) {
|
|
12
13
|
return { content: [{ type: "text" as const, text: JSON.stringify(value, null, 2) }] };
|
|
@@ -20,7 +21,7 @@ function messageView(cfg: Cfg, m: MessageView) {
|
|
|
20
21
|
}
|
|
21
22
|
|
|
22
23
|
function draftView(cfg: Cfg, d: Message) {
|
|
23
|
-
return { ...messageView(cfg, toView(d)), bcc: d.bcc, html: d.html };
|
|
24
|
+
return { ...messageView(cfg, toView(d)), bcc: d.bcc, html: d.html, pending: d.pending };
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
function threadView(cfg: Cfg, t: Thread) {
|
|
@@ -39,6 +40,17 @@ function wrap<A>(cfg: Cfg, fn: (args: A) => Promise<unknown>) {
|
|
|
39
40
|
};
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
const IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
|
|
44
|
+
const TEXT_TYPES = /^(text\/|application\/(json|xml|csv)$)/;
|
|
45
|
+
|
|
46
|
+
function attachmentContent(cfg: Cfg, messageId: string, meta: AttachmentMeta, body: Uint8Array) {
|
|
47
|
+
const data = Buffer.from(body).toString("base64");
|
|
48
|
+
if (IMAGE_TYPES.has(meta.content_type)) return { type: "image" as const, data, mimeType: meta.content_type };
|
|
49
|
+
if (TEXT_TYPES.test(meta.content_type)) return { type: "text" as const, text: new TextDecoder().decode(body) };
|
|
50
|
+
const uri = appUrl(cfg, `/attachments/${encodeURIComponent(messageId)}/${encodeURIComponent(meta.id)}`);
|
|
51
|
+
return { type: "resource" as const, resource: { uri, mimeType: meta.content_type, blob: data } };
|
|
52
|
+
}
|
|
53
|
+
|
|
42
54
|
const addresses = z.array(z.string()).describe("Addresses, e.g. \"Ana <ana@example.com>\" or \"ana@example.com\"");
|
|
43
55
|
const isoDate = z.string().describe("ISO 8601 timestamp");
|
|
44
56
|
const metaFilter = z.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
|
|
@@ -177,9 +189,19 @@ function buildServer(mail: Mail, access: Access, actor: Actor): McpServer {
|
|
|
177
189
|
}, wrap(cfg, async ({ message_id, text, reply_all }) => messageView(cfg, toView(await mail.reply(message_id, text, reply_all ?? false, actor)))));
|
|
178
190
|
|
|
179
191
|
server.registerTool("get_attachment", {
|
|
180
|
-
description: "
|
|
192
|
+
description: "Content of an inbound attachment: images as images, text as text, anything else (e.g. PDF) as an embedded resource. Larger than the server's limit returns an error.",
|
|
181
193
|
inputSchema: { message_id: z.string(), attachment_id: z.string() },
|
|
182
|
-
},
|
|
194
|
+
}, async ({ message_id, attachment_id }) => {
|
|
195
|
+
try {
|
|
196
|
+
const { meta, body } = await mail.getAttachment(message_id, attachment_id, actor.scope);
|
|
197
|
+
if (body.byteLength > cfg.mcp.maxAttachmentMb * 1024 * 1024) {
|
|
198
|
+
throw new Error(`Attachment is ${(body.byteLength / 1048576).toFixed(1)} MB, over the ${cfg.mcp.maxAttachmentMb} MB limit`);
|
|
199
|
+
}
|
|
200
|
+
return { content: [{ type: "text" as const, text: JSON.stringify(meta) }, attachmentContent(cfg, message_id, meta, body)] };
|
|
201
|
+
} catch (err) {
|
|
202
|
+
return { ...json({ error: (err as Error).message }), isError: true };
|
|
203
|
+
}
|
|
204
|
+
});
|
|
183
205
|
|
|
184
206
|
server.registerTool("create_login_link", {
|
|
185
207
|
description: "One-time link that signs one browser into the review UI, limited to the mailboxes this token reaches. Expires unused after a few minutes. Pass thread_id to land on that thread after signing in. Browsers already signed in can open a result's url directly.",
|
package/src/provider/resend.ts
CHANGED
|
@@ -43,6 +43,8 @@ interface ResendAttachment {
|
|
|
43
43
|
filename: string;
|
|
44
44
|
content_type: string;
|
|
45
45
|
size?: number;
|
|
46
|
+
content_id?: string | null;
|
|
47
|
+
content_disposition?: string | null;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
interface ResendReceivedEmail {
|
|
@@ -181,22 +183,39 @@ export function createResendProvider(config: Record<string, unknown>): MailProvi
|
|
|
181
183
|
if (message.cc.length) body.cc = message.cc;
|
|
182
184
|
if (message.bcc.length) body.bcc = message.bcc;
|
|
183
185
|
if (message.replyTo.length) body.reply_to = message.replyTo;
|
|
186
|
+
if (message.attachments.length) {
|
|
187
|
+
body.attachments = message.attachments.map(a => ({
|
|
188
|
+
filename: a.filename,
|
|
189
|
+
content: Buffer.from(a.content).toString("base64"),
|
|
190
|
+
content_type: a.contentType,
|
|
191
|
+
}));
|
|
192
|
+
}
|
|
184
193
|
const res = await request<{ id: string }>("POST", "/emails", body, { "Idempotency-Key": idempotencyKey });
|
|
185
194
|
return { providerId: res.id };
|
|
186
195
|
},
|
|
187
196
|
|
|
188
|
-
async
|
|
189
|
-
const
|
|
197
|
+
async getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array> {
|
|
198
|
+
const { download_url } = await request<{ download_url: string }>(
|
|
190
199
|
"GET",
|
|
191
200
|
`/emails/receiving/${encodeURIComponent(providerMessageId)}/attachments/${encodeURIComponent(attachmentId)}`,
|
|
192
201
|
);
|
|
193
|
-
|
|
202
|
+
const res = await fetch(download_url);
|
|
203
|
+
if (!res.ok) throw new Error(`Resend attachment ${attachmentId} download failed: ${res.status}`);
|
|
204
|
+
return new Uint8Array(await res.arrayBuffer());
|
|
194
205
|
},
|
|
195
206
|
};
|
|
196
207
|
}
|
|
197
208
|
|
|
198
209
|
function toAttachmentMeta(a: ResendAttachment): AttachmentMeta {
|
|
199
|
-
|
|
210
|
+
const contentId = a.content_id ? a.content_id.replace(/^<|>$/g, "") : null;
|
|
211
|
+
return {
|
|
212
|
+
id: a.id,
|
|
213
|
+
filename: a.filename,
|
|
214
|
+
content_type: a.content_type,
|
|
215
|
+
size: a.size ?? null,
|
|
216
|
+
inline: a.content_disposition === "inline" && !!contentId,
|
|
217
|
+
content_id: contentId,
|
|
218
|
+
};
|
|
200
219
|
}
|
|
201
220
|
|
|
202
221
|
function normalizeHeaders(headers: Record<string, string | string[]>): Record<string, string> {
|
package/src/provider/types.ts
CHANGED
|
@@ -36,6 +36,13 @@ export interface OutboundMessage {
|
|
|
36
36
|
text: string;
|
|
37
37
|
html: string;
|
|
38
38
|
headers: Record<string, string>;
|
|
39
|
+
attachments: OutboundAttachment[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface OutboundAttachment {
|
|
43
|
+
filename: string;
|
|
44
|
+
contentType: string;
|
|
45
|
+
content: Uint8Array;
|
|
39
46
|
}
|
|
40
47
|
|
|
41
48
|
export interface OutboundStatus {
|
|
@@ -61,7 +68,8 @@ export interface MailProvider {
|
|
|
61
68
|
listOutbound(since: Date): AsyncIterable<OutboundStatus>;
|
|
62
69
|
/** Sends once per `idempotencyKey`; a retry with the same key must not send again. */
|
|
63
70
|
send(message: OutboundMessage, idempotencyKey: string): Promise<{ providerId: string }>;
|
|
64
|
-
|
|
71
|
+
/** The bytes of an inbound attachment. */
|
|
72
|
+
getAttachment(providerMessageId: string, attachmentId: string): Promise<Uint8Array>;
|
|
65
73
|
}
|
|
66
74
|
|
|
67
75
|
export type ProviderFactory = (config: Record<string, unknown>) => MailProvider;
|
package/src/types.ts
CHANGED
|
@@ -19,8 +19,8 @@ export interface InboxerConfig {
|
|
|
19
19
|
threadWindowDays: number;
|
|
20
20
|
mailboxes: Record<string, MailboxConfig>;
|
|
21
21
|
provider: ProviderConfig;
|
|
22
|
-
mcp: { tokens: Record<string, string
|
|
23
|
-
ui: { cookieSecret: string; loginLinkTtlMin: number };
|
|
22
|
+
mcp: { tokens: Record<string, string>; maxAttachmentMb: number };
|
|
23
|
+
ui: { cookieSecret: string; loginLinkTtlMin: number; undoSec: number; maxUploadMb: number };
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
export const CATCHALL = "catchall";
|
|
@@ -36,6 +36,9 @@ export interface AttachmentMeta {
|
|
|
36
36
|
filename: string;
|
|
37
37
|
content_type: string;
|
|
38
38
|
size: number | null;
|
|
39
|
+
/** Shown inside the body (e.g. an embedded image referenced by `cid:`), not offered as a file. */
|
|
40
|
+
inline: boolean;
|
|
41
|
+
content_id: string | null;
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
export interface Message {
|
|
@@ -68,6 +71,14 @@ export interface Message {
|
|
|
68
71
|
sent_at: string | null;
|
|
69
72
|
version: number;
|
|
70
73
|
edited_by_human: boolean;
|
|
74
|
+
/** A send or discard a human started, carried out at `at` unless undone first. */
|
|
75
|
+
pending: PendingAction | null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface PendingAction {
|
|
79
|
+
action: "send" | "discard";
|
|
80
|
+
at: string;
|
|
81
|
+
by: string;
|
|
71
82
|
}
|
|
72
83
|
|
|
73
84
|
export interface Thread {
|
package/src/ui/assets.ts
CHANGED
|
@@ -17,4 +17,5 @@ function load(file: string, type: string): Asset {
|
|
|
17
17
|
export const ASSETS: Record<string, Asset> = {
|
|
18
18
|
"style.css": load("style.css", "text/css; charset=utf-8"),
|
|
19
19
|
"htmx.min.js": load("htmx.min.js", "text/javascript; charset=utf-8"),
|
|
20
|
+
"app.js": load("app.js", "text/javascript; charset=utf-8"),
|
|
20
21
|
};
|
package/src/ui/routes.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { Context, Hono } from "hono";
|
|
2
2
|
import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from "hono/cookie";
|
|
3
3
|
import type { Access } from "../auth.ts";
|
|
4
|
-
import { bareAddress, splitAddresses } from "../core/address.ts";
|
|
5
|
-
import { ConflictError, InvalidRequestError, type Mail, type MessageView } from "../core/mail.ts";
|
|
6
|
-
import type
|
|
4
|
+
import { bareAddress, domainOf, splitAddresses } from "../core/address.ts";
|
|
5
|
+
import { ConflictError, InvalidRequestError, type Mail, type MessageView, type ThreadStatus } from "../core/mail.ts";
|
|
6
|
+
import { CATCHALL, type Actor, type InboxerConfig, type Message, type Session } from "../types.ts";
|
|
7
7
|
import { S } from "./strings.ts";
|
|
8
8
|
import * as V from "./views.ts";
|
|
9
9
|
|
|
@@ -25,6 +25,12 @@ function clientInfo(c: Context) {
|
|
|
25
25
|
return { ip: forwarded || c.req.header("x-real-ip") || null, userAgent: c.req.header("user-agent") ?? null };
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
/** htmx sends the page URL; draft cards on a thread page leave out the thread around them. */
|
|
29
|
+
function onThreadPage(c: Context): boolean {
|
|
30
|
+
const current = c.req.header("hx-current-url");
|
|
31
|
+
return !!current && new URL(current).pathname.startsWith("/threads/");
|
|
32
|
+
}
|
|
33
|
+
|
|
28
34
|
function uiActor(session: Session): Actor {
|
|
29
35
|
return { kind: "ui", name: session.label ?? session.id.slice(0, 12), scope: session.scope };
|
|
30
36
|
}
|
|
@@ -33,20 +39,42 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
33
39
|
const secret = cfg.ui.cookieSecret;
|
|
34
40
|
const cookieOptions = { httpOnly: true, secure: true, sameSite: "Lax", path: "/", maxAge: COOKIE_MAX_AGE } as const;
|
|
35
41
|
|
|
36
|
-
const
|
|
42
|
+
const own = new Set(Object.values(cfg.mailboxes).map(m => bareAddress(m.address)));
|
|
43
|
+
/** Recipients that are our own mailboxes are implied by the mailbox badge. */
|
|
44
|
+
const shown = (m: MessageView): MessageView => ({
|
|
45
|
+
...m,
|
|
46
|
+
to: m.to.filter(a => !own.has(bareAddress(a))),
|
|
47
|
+
cc: m.cc.filter(a => !own.has(bareAddress(a))),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
/** Mailboxes a session can send from: every one in its scope but the catch-all. */
|
|
51
|
+
const senders = (session: Session): V.Mailbox[] => mail.listMailboxes(session.scope).filter(m => m.id !== CATCHALL);
|
|
52
|
+
const domainsOf = (session: Session): string[] => [...new Set(senders(session).map(m => domainOf(m.address)))];
|
|
53
|
+
|
|
54
|
+
const page = async (c: Context<UiEnv>, title: string, body: V.View, current: V.Page, status: 200 | 400 | 401 | 404 = 200, fullScreen = false) => {
|
|
37
55
|
const session = c.get("session");
|
|
38
|
-
const
|
|
39
|
-
|
|
56
|
+
const shell = session
|
|
57
|
+
? { draftCount: (await mail.listDrafts(undefined, session.scope)).length, domains: domainsOf(session), senders: senders(session) }
|
|
58
|
+
: {};
|
|
59
|
+
return c.html(V.layout(title, body, { theme: theme(c), page: current, signedIn: !!session, fullScreen, ...shell }), status);
|
|
40
60
|
};
|
|
41
61
|
|
|
42
62
|
// Sign-in: GET only shows a button, so link previews and scanners do not burn the link.
|
|
63
|
+
// A used or expired link on a browser that is already signed in just opens the app.
|
|
64
|
+
const signedInSession = async (c: Context<UiEnv>): Promise<Session | null> => {
|
|
65
|
+
const value = await getSignedCookie(c, secret, SESSION_COOKIE);
|
|
66
|
+
return value ? access.authenticate(value) : null;
|
|
67
|
+
};
|
|
68
|
+
|
|
43
69
|
app.get("/auth/:token", async c => {
|
|
44
70
|
const valid = await access.isLinkValid(c.req.param("token"));
|
|
71
|
+
if (!valid && (await signedInSession(c))) return c.redirect("/", 303);
|
|
45
72
|
return page(c, S.signInTitle, V.signIn(c.req.param("token"), valid), null, valid ? 200 : 404);
|
|
46
73
|
});
|
|
47
74
|
|
|
48
75
|
app.post("/auth/:token", async c => {
|
|
49
76
|
const signedIn = await access.consumeLoginLink(c.req.param("token"), clientInfo(c));
|
|
77
|
+
if (!signedIn && (await signedInSession(c))) return c.redirect("/", 303);
|
|
50
78
|
if (!signedIn) return page(c, S.signInTitle, V.signIn("", false), null, 404);
|
|
51
79
|
await setSignedCookie(c, SESSION_COOKIE, signedIn.secret, secret, cookieOptions);
|
|
52
80
|
return c.redirect(signedIn.next, 303);
|
|
@@ -61,7 +89,7 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
61
89
|
return c.redirect(path, 303);
|
|
62
90
|
});
|
|
63
91
|
|
|
64
|
-
const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/devices", "/devices/*", "/logout"];
|
|
92
|
+
const ui = ["/", "/inbox", "/threads/*", "/drafts/*", "/attachments/*", "/compose", "/devices", "/devices/*", "/settings", "/logout"];
|
|
65
93
|
for (const path of ui) {
|
|
66
94
|
app.use(path, async (c, next) => {
|
|
67
95
|
const value = await getSignedCookie(c, secret, SESSION_COOKIE);
|
|
@@ -77,10 +105,22 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
77
105
|
});
|
|
78
106
|
}
|
|
79
107
|
|
|
80
|
-
/** The sent and received messages around a draft, and the context of its thread. */
|
|
108
|
+
/** The sent and received messages around a draft, newest first, and the context of its thread. */
|
|
81
109
|
const draftExtras = async (draft: Message, session: Session): Promise<{ history: MessageView[]; ctx: V.ContextView }> => {
|
|
82
110
|
const { messages, context, contacts } = await mail.getThread(draft.thread_id, session.scope);
|
|
83
|
-
|
|
111
|
+
const history = messages.filter(m => m.id !== draft.id && m.status !== "draft").reverse().map(shown);
|
|
112
|
+
return { history, ctx: { context, contacts } };
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
/** The card for a draft in whatever state it is now. */
|
|
116
|
+
const draftView = async (c: Context<UiEnv>, id: string): Promise<V.View> => {
|
|
117
|
+
const session = c.get("session");
|
|
118
|
+
const draft = await mail.requireMessage(id, session.scope);
|
|
119
|
+
if (draft.status === "discarded") return V.draftDone(id, S.discarded);
|
|
120
|
+
if (draft.status !== "draft") return V.draftDone(id, `${S.sentTo} ${draft.to.join(", ")}`);
|
|
121
|
+
if (onThreadPage(c)) return V.draftCard(draft, [], null);
|
|
122
|
+
const { history, ctx } = await draftExtras(draft, session);
|
|
123
|
+
return V.draftCard(draft, history, ctx);
|
|
84
124
|
};
|
|
85
125
|
|
|
86
126
|
app.get("/", async c => {
|
|
@@ -90,16 +130,11 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
90
130
|
return page(c, S.navDrafts, V.draftsPage(items), "drafts");
|
|
91
131
|
});
|
|
92
132
|
|
|
93
|
-
app.get("/drafts/:id/card", async c =>
|
|
94
|
-
const draft = await mail.requireMessage(c.req.param("id"), c.get("session").scope);
|
|
95
|
-
if (draft.status !== "draft") return c.html(V.draftDone(draft.id, `${S.status}: ${draft.status}`));
|
|
96
|
-
const { history, ctx } = await draftExtras(draft, c.get("session"));
|
|
97
|
-
return c.html(V.draftCard(draft, history, ctx));
|
|
98
|
-
});
|
|
133
|
+
app.get("/drafts/:id/card", async c => c.html(await draftView(c, c.req.param("id"))));
|
|
99
134
|
|
|
100
135
|
app.get("/drafts/:id/edit", async c => {
|
|
101
136
|
const draft = await mail.requireMessage(c.req.param("id"), c.get("session").scope);
|
|
102
|
-
if (draft.status !== "draft") return c.html(
|
|
137
|
+
if (draft.status !== "draft" || draft.pending) return c.html(await draftView(c, draft.id));
|
|
103
138
|
const form = { to: draft.to.join(", "), cc: draft.cc.join(", "), subject: draft.subject, text: draft.text };
|
|
104
139
|
return c.html(V.draftEditor(draft, form, null));
|
|
105
140
|
});
|
|
@@ -116,13 +151,8 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
116
151
|
subject: form.subject,
|
|
117
152
|
text: form.text,
|
|
118
153
|
}, actor);
|
|
119
|
-
if (body.send === "1")
|
|
120
|
-
|
|
121
|
-
return c.html(V.draftDone(id, `${S.sentTo} ${sent.to.join(", ")}`));
|
|
122
|
-
}
|
|
123
|
-
const draft = await mail.requireMessage(id, actor.scope);
|
|
124
|
-
const { history, ctx } = await draftExtras(draft, c.get("session"));
|
|
125
|
-
return c.html(V.draftCard(draft, history, ctx));
|
|
154
|
+
if (body.send === "1") await mail.schedule(id, "send", actor);
|
|
155
|
+
return c.html(await draftView(c, id));
|
|
126
156
|
} catch (err) {
|
|
127
157
|
if (err instanceof ConflictError) return c.html(V.draftEditor(err.current, form, err.current));
|
|
128
158
|
if (err instanceof InvalidRequestError) return c.html(V.draftDone(id, err.message));
|
|
@@ -130,51 +160,118 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
130
160
|
}
|
|
131
161
|
});
|
|
132
162
|
|
|
133
|
-
app.post("/drafts/:id/
|
|
163
|
+
app.post("/drafts/:id/attachments", async c => {
|
|
134
164
|
const id = c.req.param("id");
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
165
|
+
const actor = uiActor(c.get("session"));
|
|
166
|
+
const body = await c.req.parseBody({ all: true });
|
|
167
|
+
const files = ([] as unknown[]).concat(body.files ?? []).filter((f): f is File => f instanceof File);
|
|
168
|
+
const limit = cfg.ui.maxUploadMb * 1024 * 1024;
|
|
169
|
+
let error: string | null = null;
|
|
170
|
+
for (const file of files) {
|
|
171
|
+
if (file.size > limit) {
|
|
172
|
+
error = `${file.name} ${S.tooLarge} ${cfg.ui.maxUploadMb} MB`;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
await mail.attach(id, { filename: file.name, contentType: file.type, body: new Uint8Array(await file.arrayBuffer()) }, actor);
|
|
141
176
|
}
|
|
177
|
+
return c.html(V.draftFiles(await mail.requireMessage(id, actor.scope), error));
|
|
142
178
|
});
|
|
143
179
|
|
|
144
|
-
app.post("/drafts/:id/
|
|
145
|
-
const
|
|
146
|
-
|
|
147
|
-
await mail.discardDraft(id, uiActor(c.get("session")));
|
|
148
|
-
return c.html(V.draftDone(id, S.discarded));
|
|
149
|
-
} catch (err) {
|
|
150
|
-
if (err instanceof InvalidRequestError) return c.html(V.draftDone(id, err.message));
|
|
151
|
-
throw err;
|
|
152
|
-
}
|
|
180
|
+
app.post("/drafts/:id/attachments/:attachmentId/remove", async c => {
|
|
181
|
+
const draft = await mail.detach(c.req.param("id"), c.req.param("attachmentId"), uiActor(c.get("session")));
|
|
182
|
+
return c.html(V.draftFiles(draft, null));
|
|
153
183
|
});
|
|
154
184
|
|
|
155
|
-
|
|
156
|
-
|
|
185
|
+
// Send, discard and undo answer with the draft's current card, so a late click shows what happened.
|
|
186
|
+
for (const [path, act] of [
|
|
187
|
+
["send", (id: string, actor: Actor) => mail.schedule(id, "send", actor)],
|
|
188
|
+
["discard", (id: string, actor: Actor) => mail.schedule(id, "discard", actor)],
|
|
189
|
+
["undo", (id: string, actor: Actor) => mail.undo(id, actor)],
|
|
190
|
+
] as const) {
|
|
191
|
+
app.post(`/drafts/:id/${path}`, async c => {
|
|
192
|
+
const id = c.req.param("id");
|
|
193
|
+
try {
|
|
194
|
+
await act(id, uiActor(c.get("session")));
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (!(err instanceof InvalidRequestError)) throw err;
|
|
197
|
+
}
|
|
198
|
+
return c.html(await draftView(c, id));
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The inbox filter from the query, carried along when a thread opens beside the list. */
|
|
203
|
+
const inboxFilter = (c: Context<UiEnv>): V.InboxFilter => {
|
|
157
204
|
const requested = c.req.query("status");
|
|
158
205
|
const status = requested === "all" || requested === "archived" ? requested : "unanswered";
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
206
|
+
return { mailbox: c.req.query("mailbox") ?? "", status };
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const threadList = async (c: Context<UiEnv>, current: string | null): Promise<V.View> => {
|
|
210
|
+
const session = c.get("session");
|
|
211
|
+
const filter = inboxFilter(c);
|
|
212
|
+
const threads = await mail.listThreads({ mailbox: filter.mailbox || undefined, status: filter.status as ThreadStatus, limit: 200 }, session.scope);
|
|
213
|
+
const mailboxes = mail.listMailboxes(session.scope).map(m => m.id);
|
|
214
|
+
return V.threadList(threads, { mailboxes, domains: domainsOf(session), filter, own, current });
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
app.get("/inbox", async c => page(c, S.navInbox, V.inboxPage(await threadList(c, null), null), "inbox"));
|
|
165
218
|
|
|
166
219
|
app.get("/threads/:id", async c => {
|
|
167
220
|
const id = c.req.param("id");
|
|
168
|
-
const
|
|
169
|
-
let thread = await mail.requireThread(id, scope);
|
|
221
|
+
const session = c.get("session");
|
|
222
|
+
let thread = await mail.requireThread(id, session.scope);
|
|
170
223
|
if (thread.unread) {
|
|
171
|
-
await mail.mark([id], { read: true }, uiActor(
|
|
172
|
-
thread = await mail.requireThread(id, scope);
|
|
224
|
+
await mail.mark([id], { read: true }, uiActor(session));
|
|
225
|
+
thread = await mail.requireThread(id, session.scope);
|
|
226
|
+
}
|
|
227
|
+
const { messages, context, contacts } = await mail.getThread(id, session.scope);
|
|
228
|
+
const people = thread.participants.filter(p => !own.has(p));
|
|
229
|
+
const entries = await Promise.all(messages.map(async m => ({
|
|
230
|
+
at: m.date,
|
|
231
|
+
view: m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id), [], null) : V.messageBubble(shown(m), people.length > 1),
|
|
232
|
+
})));
|
|
233
|
+
const reply = { allowed: senders(session).some(m => m.id === thread.mailbox), replyAll: people.length > 1 };
|
|
234
|
+
const view = V.threadView(thread, entries, { context, contacts }, { filter: inboxFilter(c), own, reply });
|
|
235
|
+
return page(c, thread.subject || S.navInbox, V.inboxPage(await threadList(c, id), view), "inbox", 200, true);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
/** Replies to the latest message; a reply sent from here gets the same undo window as a draft. */
|
|
239
|
+
app.post("/threads/:id/reply", async c => {
|
|
240
|
+
const id = c.req.param("id");
|
|
241
|
+
const actor = uiActor(c.get("session"));
|
|
242
|
+
const body = await c.req.parseBody();
|
|
243
|
+
const text = String(body.text ?? "");
|
|
244
|
+
const { messages } = await mail.getThread(id, actor.scope);
|
|
245
|
+
const latest = messages.filter(m => m.status !== "draft").at(-1);
|
|
246
|
+
const back = `/threads/${id}?${V.inboxQuery(inboxFilter(c))}`;
|
|
247
|
+
if (!latest || !text.trim()) return c.redirect(back, 303);
|
|
248
|
+
try {
|
|
249
|
+
const draft = await mail.createDraft({ replyToId: latest.id, replyAll: body.reply_all === "1", text }, actor);
|
|
250
|
+
if (body.action === "send") await mail.schedule(draft.id, "send", actor);
|
|
251
|
+
} catch (err) {
|
|
252
|
+
if (err instanceof InvalidRequestError) return page(c, S.reply, V.message([err.message]), "inbox", 400);
|
|
253
|
+
throw err;
|
|
254
|
+
}
|
|
255
|
+
return c.redirect(back, 303);
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
app.post("/compose", async c => {
|
|
259
|
+
const actor = uiActor(c.get("session"));
|
|
260
|
+
const body = await c.req.parseBody();
|
|
261
|
+
try {
|
|
262
|
+
const draft = await mail.createDraft({
|
|
263
|
+
mailbox: String(body.mailbox ?? ""),
|
|
264
|
+
to: splitAddresses(String(body.to ?? "")),
|
|
265
|
+
cc: splitAddresses(String(body.cc ?? "")),
|
|
266
|
+
subject: String(body.subject ?? ""),
|
|
267
|
+
text: String(body.text ?? ""),
|
|
268
|
+
}, actor);
|
|
269
|
+
if (body.action === "send") await mail.schedule(draft.id, "send", actor);
|
|
270
|
+
return c.redirect(`/threads/${draft.thread_id}?status=all`, 303);
|
|
271
|
+
} catch (err) {
|
|
272
|
+
if (err instanceof InvalidRequestError) return page(c, S.newMail, V.message([err.message]), null, 400);
|
|
273
|
+
throw err;
|
|
173
274
|
}
|
|
174
|
-
const { messages, context, contacts } = await mail.getThread(id, scope);
|
|
175
|
-
const items = await Promise.all(messages.map(async m =>
|
|
176
|
-
m.status === "draft" ? V.draftCard(await mail.store.requireMessage(m.id), [], null) : V.messageCard(m)));
|
|
177
|
-
return page(c, thread.subject || S.navInbox, V.threadPage(thread, items, { context, contacts }), "inbox");
|
|
178
275
|
});
|
|
179
276
|
|
|
180
277
|
app.post("/threads/:id/archive", async c => {
|
|
@@ -184,11 +281,26 @@ export function registerUi(app: Hono<UiEnv>, mail: Mail, access: Access, cfg: In
|
|
|
184
281
|
return c.html(V.archiveButton(await mail.store.requireThread(id)));
|
|
185
282
|
});
|
|
186
283
|
|
|
284
|
+
// Attachments are untrusted: only plain images and PDFs open in the browser, everything runs sandboxed.
|
|
285
|
+
app.get("/attachments/:messageId/:attachmentId", async c => {
|
|
286
|
+
const { meta, body } = await mail.getAttachment(c.req.param("messageId"), c.req.param("attachmentId"), c.get("session").scope);
|
|
287
|
+
const opens = V.isPreviewable(meta.content_type) || meta.content_type === "application/pdf";
|
|
288
|
+
return c.body(body as Uint8Array<ArrayBuffer>, 200, {
|
|
289
|
+
"Content-Type": opens ? meta.content_type : "application/octet-stream",
|
|
290
|
+
"Content-Disposition": `${opens ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(meta.filename)}`,
|
|
291
|
+
"Content-Security-Policy": "sandbox; default-src 'none'; img-src 'self'; style-src 'unsafe-inline'",
|
|
292
|
+
"X-Content-Type-Options": "nosniff",
|
|
293
|
+
"Cache-Control": "private, max-age=31536000, immutable",
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
|
|
187
297
|
app.get("/devices", async c => {
|
|
188
298
|
const session = c.get("session");
|
|
189
299
|
return page(c, S.navDevices, V.devicesPage(await access.listSessions(session.scope), session.id), "devices");
|
|
190
300
|
});
|
|
191
301
|
|
|
302
|
+
app.get("/settings", async c => page(c, S.navSettings, V.settingsPage(theme(c)), "settings"));
|
|
303
|
+
|
|
192
304
|
app.post("/devices/:id/revoke", async c => {
|
|
193
305
|
await access.revokeSession(c.req.param("id"), uiActor(c.get("session")));
|
|
194
306
|
return c.body(null, 200);
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// New mail opens as a modal sheet; a click on its backdrop or a [data-close] button closes it.
|
|
2
|
+
document.addEventListener("click", event => {
|
|
3
|
+
const target = event.target instanceof Element ? event.target : null;
|
|
4
|
+
if (!target) return;
|
|
5
|
+
if (target.closest("[data-compose]")) {
|
|
6
|
+
const dialog = document.getElementById("compose");
|
|
7
|
+
dialog.showModal();
|
|
8
|
+
dialog.querySelector("#compose-to").focus();
|
|
9
|
+
} else if (target.closest("[data-close]")) {
|
|
10
|
+
target.closest("dialog").close();
|
|
11
|
+
} else if (target instanceof HTMLDialogElement && target.open) {
|
|
12
|
+
target.close();
|
|
13
|
+
} else if (target.closest("[data-context-toggle]")) {
|
|
14
|
+
document.body.classList.toggle("context-open");
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
document.addEventListener("keydown", event => {
|
|
19
|
+
if (event.key === "Escape") document.body.classList.remove("context-open");
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// A thread opens at its latest message.
|
|
23
|
+
document.addEventListener("DOMContentLoaded", () => {
|
|
24
|
+
const messages = document.querySelector("[data-scroll-end]");
|
|
25
|
+
if (messages) messages.scrollTop = messages.scrollHeight;
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Files dropped on a [data-drop] zone go to its file input, which uploads them through htmx.
|
|
29
|
+
const zoneOf = event => event.target instanceof Element ? event.target.closest("[data-drop]") : null;
|
|
30
|
+
const hasFiles = event => [...(event.dataTransfer?.types ?? [])].includes("Files");
|
|
31
|
+
|
|
32
|
+
document.addEventListener("dragover", event => {
|
|
33
|
+
if (!hasFiles(event)) return;
|
|
34
|
+
event.preventDefault();
|
|
35
|
+
const zone = zoneOf(event);
|
|
36
|
+
event.dataTransfer.dropEffect = zone ? "copy" : "none";
|
|
37
|
+
zone?.classList.add("dragging");
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
document.addEventListener("dragleave", event => {
|
|
41
|
+
const zone = zoneOf(event);
|
|
42
|
+
if (zone && !zone.contains(event.relatedTarget)) zone.classList.remove("dragging");
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
document.addEventListener("drop", event => {
|
|
46
|
+
if (!hasFiles(event)) return;
|
|
47
|
+
event.preventDefault();
|
|
48
|
+
const zone = zoneOf(event);
|
|
49
|
+
if (!zone) return;
|
|
50
|
+
zone.classList.remove("dragging");
|
|
51
|
+
const input = zone.querySelector("input[type=file]");
|
|
52
|
+
input.files = event.dataTransfer.files;
|
|
53
|
+
input.dispatchEvent(new Event("change", { bubbles: true }));
|
|
54
|
+
});
|