commit
BCC and demo
diff --git a/README.md b/README.md
index 1e5f6a6..a37cd4f 100644
--- a/README.md
+++ b/README.md
@@ -67,6 +67,16 @@ Then:
Resend. The list re-syncs on those webhooks, daily, and whenever Admin →
Domains is opened. That page is where you switch one off or pick a catch-all.
+## Demo
+
+`/demo` (e.g. https://mail.doughmination.gay/demo) is the same app with made-up
+mail and no sign-in. Under that path the API is swapped for an in-memory fake
+(`src/web/lib/demo.ts`), so nothing touches the Worker, D1, R2 or Resend, and no
+real email comes in or goes out. Sending moves a message to Sent, mail to one of
+the demo's own addresses lands in its inbox, anyone else gets a pretend reply a
+few seconds later, and reloading starts over. Locally it's at
+http://localhost:5173/demo.
+
## Scripts
| | |
diff --git a/migrations/0003_bcc.sql b/migrations/0003_bcc.sql
new file mode 100644
index 0000000..b66e69d
--- /dev/null
+++ b/migrations/0003_bcc.sql
@@ -0,0 +1,3 @@
+-- Bcc is only ever known for mail we send: it's kept on drafts and Sent so
+-- you can see who you Bcc'd, and stays '[]' on everything received.
+ALTER TABLE messages ADD COLUMN bcc_addrs TEXT NOT NULL DEFAULT '[]';
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 97aec47..05cc910 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -47,6 +47,8 @@ export interface Message {
from: string;
to: string[];
cc: string[];
+ /** Only on messages we sent (or drafts); always empty for received mail. */
+ bcc: string[];
subject: string;
/** Plain-text preview, shown while the message is collapsed. */
snippet: string;
@@ -68,6 +70,7 @@ export interface ComposeInput {
from: string;
to: string[];
cc: string[];
+ bcc: string[];
subject: string;
/** Plain text; the server renders the HTML part from it. */
text: string;
diff --git a/src/web/App.svelte b/src/web/App.svelte
index 49b4d5a..acd7b06 100644
--- a/src/web/App.svelte
+++ b/src/web/App.svelte
@@ -7,7 +7,7 @@
import Sidebar from "./components/Sidebar.svelte";
import ThreadList from "./components/ThreadList.svelte";
import ThreadView from "./components/ThreadView.svelte";
- import { router } from "./lib/router.svelte";
+ import { isDemo, router } from "./lib/router.svelte";
import { composer, loadSession, session } from "./lib/state.svelte";
import Admin from "./pages/Admin.svelte";
import Settings from "./pages/Settings.svelte";
@@ -19,7 +19,7 @@
const reading = $derived(route.name === "folder" && route.threadId !== null);
$effect(() => {
- if (location.pathname === "/") router.go("/inbox", { replace: true });
+ if (router.path === "/") router.go("/inbox", { replace: true });
});
</script>
@@ -49,6 +49,10 @@
{/if}
{/if}
+{#if isDemo}
+ <p class="demo" role="status">Demo: nothing is really sent, and reloading starts over.</p>
+{/if}
+
<style>
/* Panels float over the wallpaper, like the site's cards. */
.shell {
@@ -73,6 +77,25 @@
padding: 2rem;
}
+ .demo {
+ position: fixed;
+ bottom: 0.75rem;
+ left: 50%;
+ z-index: 20;
+ max-width: calc(100% - 2rem);
+ margin: 0;
+ padding: 0.35rem 0.9rem;
+ transform: translateX(-50%);
+ border: 1px solid var(--accent-line);
+ border-radius: 999px;
+ background: var(--panel);
+ backdrop-filter: blur(14px);
+ color: var(--muted);
+ font-size: 0.75rem;
+ text-align: center;
+ pointer-events: none;
+ }
+
/* Phones: one column at a time. The list shows until a thread opens. */
@media (max-width: 800px) {
.shell {
diff --git a/src/web/components/Composer.svelte b/src/web/components/Composer.svelte
index 0d47f39..3a2232e 100644
--- a/src/web/components/Composer.svelte
+++ b/src/web/components/Composer.svelte
@@ -31,6 +31,7 @@
from: form.from,
to: splitList(form.to),
cc: splitList(form.cc),
+ bcc: splitList(form.bcc),
subject: form.subject,
text: form.text,
attachmentIds: form.attachments.map((a) => a.id),
@@ -117,6 +118,7 @@
{/if}
<label class="field">To <input bind:value={form.to} placeholder="[email protected], …" required /></label>
<label class="field">Cc <input bind:value={form.cc} /></label>
+ <label class="field">Bcc <input bind:value={form.bcc} /></label>
<label class="field">Subject <input bind:value={form.subject} required /></label>
<label class="field grow">Message <textarea bind:value={form.text} rows="12"></textarea></label>
diff --git a/src/web/components/EmailFrame.svelte b/src/web/components/EmailFrame.svelte
index 73dd3be..1801855 100644
--- a/src/web/components/EmailFrame.svelte
+++ b/src/web/components/EmailFrame.svelte
@@ -21,6 +21,7 @@
<script lang="ts">
import ImageIcon from "@lucide/svelte/icons/image";
import type { AttachmentInfo } from "../../shared/types";
+ import { api } from "../lib/api";
let { html, attachments }: { html: string; attachments: AttachmentInfo[] } = $props();
@@ -39,7 +40,7 @@
);
return html.replace(/cid:([^"'\s>)]+)/gi, (whole, raw: string) => {
const id = byCid.get(raw.replace(/^<|>$/g, "").toLowerCase());
- return id ? `/api/attachments/${id}?inline=1` : whole;
+ return id ? api.attachmentUrl(id, true) : whole;
});
});
diff --git a/src/web/components/Sidebar.svelte b/src/web/components/Sidebar.svelte
index 91c53c4..a329835 100644
--- a/src/web/components/Sidebar.svelte
+++ b/src/web/components/Sidebar.svelte
@@ -57,7 +57,7 @@
<ul class="folders">
{#each folders as f (f.folder)}
<li>
- <a class="item" class:active={current === f.folder} href={folderHref(f.folder)}>
+ <a class="item" class:active={current === f.folder} href={router.href(folderHref(f.folder))}>
<f.icon size={16} />
<span>{f.label}</span>
{#if f.folder === "inbox" && total}<span class="count">{total}</span>{/if}
@@ -70,13 +70,13 @@
<h3 class="mailboxes-title">Mailboxes</h3>
<ul class="mailboxes">
<li>
- <a class="item" class:active={!router.mailbox} href={folderHref(current ?? "inbox", null)}>
+ <a class="item" class:active={!router.mailbox} href={router.href(folderHref(current ?? "inbox", null))}>
<span>All</span>
</a>
</li>
{#each byDomain as [domain, addresses] (domain)}
<li>
- <a class="item domain" class:active={router.mailbox === `@${domain}`} href={folderHref(current ?? "inbox", `@${domain}`)}>
+ <a class="item domain" class:active={router.mailbox === `@${domain}`} href={router.href(folderHref(current ?? "inbox", `@${domain}`))}>
<Globe size={14} />
<span>{domain}</span>
{#if unreadFor(domain)}<span class="count">{unreadFor(domain)}</span>{/if}
@@ -84,7 +84,7 @@
<ul>
{#each addresses as addr (addr)}
<li>
- <a class="item address" class:active={router.mailbox === addr} href={folderHref(current ?? "inbox", addr)}>
+ <a class="item address" class:active={router.mailbox === addr} href={router.href(folderHref(current ?? "inbox", addr))}>
<span>{addr.slice(0, addr.lastIndexOf("@"))}</span>
{#if session.unread[addr]}<span class="count">{session.unread[addr]}</span>{/if}
</a>
@@ -113,9 +113,9 @@
{/if}
<ul class="bottom">
- <li><a class="item" class:active={route.name === "settings"} href="/settings"><SettingsIcon size={16} /> <span class="label">Settings</span></a></li>
+ <li><a class="item" class:active={route.name === "settings"} href={router.href("/settings")}><SettingsIcon size={16} /> <span class="label">Settings</span></a></li>
{#if session.me?.isAdmin}
- <li><a class="item" class:active={route.name === "admin"} href="/admin"><Shield size={16} /> <span class="label">Admin</span></a></li>
+ <li><a class="item" class:active={route.name === "admin"} href={router.href("/admin")}><Shield size={16} /> <span class="label">Admin</span></a></li>
{/if}
<li><button class="item" onclick={logout}><LogOut size={16} /> <span class="label">Log out</span></button></li>
</ul>
diff --git a/src/web/components/ThreadList.svelte b/src/web/components/ThreadList.svelte
index c998201..e0cfffe 100644
--- a/src/web/components/ThreadList.svelte
+++ b/src/web/components/ThreadList.svelte
@@ -68,7 +68,7 @@
{#each items as t (t.id)}
<li>
<a
- href="/{folder}/{t.id}{router.search}"
+ href={router.href(`/${folder}/${t.id}${router.search}`)}
class="row"
class:selected={selected === t.id}
class:unread={t.unread > 0}
diff --git a/src/web/components/ThreadView.svelte b/src/web/components/ThreadView.svelte
index e98257c..22a9ffe 100644
--- a/src/web/components/ThreadView.svelte
+++ b/src/web/components/ThreadView.svelte
@@ -129,7 +129,7 @@
<span class="badge {m.folder}">{m.folder === "inbox" ? "received" : m.folder === "sent" ? "sent" : "draft"}</span>
<strong>{m.from}</strong>
{#if open}
- <span class="muted">to {m.to.join(", ")}{m.cc.length ? `, cc ${m.cc.join(", ")}` : ""}</span>
+ <span class="muted">to {m.to.join(", ")}{m.cc.length ? `, cc ${m.cc.join(", ")}` : ""}{m.bcc.length ? `, bcc ${m.bcc.join(", ")}` : ""}</span>
{:else}
<span class="muted snippet">{m.snippet}</span>
{/if}
@@ -169,11 +169,11 @@
{#each files(m) as a (a.id)}
<li>
{#if isImage(a.contentType)}
- <a href="/api/attachments/{a.id}?inline=1" target="_blank" rel="noopener">
- <img src="/api/attachments/{a.id}?inline=1" alt={a.filename} />
+ <a href={api.attachmentUrl(a.id, true)} target="_blank" rel="noopener">
+ <img src={api.attachmentUrl(a.id, true)} alt={a.filename} />
</a>
{/if}
- <a href="/api/attachments/{a.id}" download={a.filename}><Paperclip size={12} /> {a.filename}</a>
+ <a href={api.attachmentUrl(a.id)} download={a.filename}><Paperclip size={12} /> {a.filename}</a>
<span class="muted">({fmtSize(a.size)})</span>
</li>
{/each}
diff --git a/src/web/lib/api.ts b/src/web/lib/api.ts
index ff53c89..569f8b7 100644
--- a/src/web/lib/api.ts
+++ b/src/web/lib/api.ts
@@ -11,6 +11,8 @@ import type {
ThreadSummary,
UserInfo,
} from "../../shared/types";
+import { createDemoApi } from "./demo";
+import { isDemo } from "./router.svelte";
export class ApiError extends Error {
constructor(
@@ -49,7 +51,7 @@ const del = <T>(path: string) => request<T>("DELETE", path);
type Unread = { unread: Record<string, number> };
-export const api = {
+const server = {
me: () => get<Me>("/api/me"),
logout: () => post<{ endSession: string | null }>("/auth/logout"),
@@ -65,6 +67,7 @@ export const api = {
message: (id: string) => get<Message>(`/api/messages/${id}`),
deleteMessage: (id: string) => del<{ count: number }>(`/api/messages/${id}`),
unread: () => get<Unread>("/api/unread"),
+ attachmentUrl: (id: string, inline = false) => `/api/attachments/${id}${inline ? "?inline=1" : ""}`,
upload(file: File) {
const form = new FormData();
@@ -96,3 +99,8 @@ export const api = {
del<{ deletedMail: number }>(`/api/admin/users/${encodeURIComponent(username)}`),
},
};
+
+export type Api = typeof server;
+
+/** Under /demo the server is swapped for an in-memory fake; see demo.ts. */
+export const api: Api = isDemo ? createDemoApi() : server;
diff --git a/src/web/lib/demo.ts b/src/web/lib/demo.ts
new file mode 100644
index 0000000..0a499fe
--- /dev/null
+++ b/src/web/lib/demo.ts
@@ -0,0 +1,550 @@
+// An in-memory stand-in for the API, used when the app is opened under /demo
+// so people can try it without an account. Nothing leaves the browser:
+// "sent" mail goes to Sent, mail to one of your own addresses lands in your
+// inbox, and everyone else answers with a canned auto-reply. Reloading the page
+// starts over.
+//
+// It mirrors the server's rules (routing, threading by folder, unread counts)
+// closely enough to show how the app behaves, not exactly.
+
+import type {
+ AliasInfo,
+ AttachmentInfo,
+ ComposeInput,
+ DomainInfo,
+ Folder,
+ Me,
+ Message,
+ Page,
+ Thread,
+ ThreadSummary,
+ UserInfo,
+} from "../../shared/types";
+import type { Api } from "./api";
+// A cycle (state.svelte -> api -> demo), but changed() is only called from a
+// timer, long after every module has loaded.
+import { changed } from "./state.svelte";
+
+const ME = "demo";
+const MINUTE = 60_000;
+const HOUR = 60 * MINUTE;
+const DAY = 24 * HOUR;
+
+type Stored = Message;
+
+function bare(addr: string): string {
+ return (addr.match(/<([^>]*)>/)?.[1] ?? addr).trim().toLowerCase();
+}
+
+function snippetOf(text: string | null, html: string | null): string {
+ const source = text ?? (html ?? "").replace(/<(style|head)[\s\S]*?<\/\1>/gi, " ").replace(/<[^>]+>/g, " ");
+ return source.replace(/\s+/g, " ").trim().slice(0, 200);
+}
+
+function escapeHtml(s: string): string {
+ return s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
+}
+
+function renderHtml(text: string): string {
+ const body = text
+ .split(/\n{2,}/)
+ .map((p) => `<p>${escapeHtml(p).replace(/\n/g, "<br>")}</p>`)
+ .join("");
+ return `<div style="font-family: sans-serif; font-size: 14px; line-height: 1.5">${body}</div>`;
+}
+
+function textFile(name: string, text: string): { info: AttachmentInfo; url: string } {
+ return {
+ info: {
+ id: crypto.randomUUID(),
+ filename: name,
+ contentType: "text/plain",
+ size: new TextEncoder().encode(text).length,
+ contentId: null,
+ },
+ url: `data:text/plain;charset=utf-8,${encodeURIComponent(text)}`,
+ };
+}
+
+const WELCOME_HTML = `
+<div style="font-family: system-ui, sans-serif; max-width: 560px; margin: 0 auto; color: #1d1b20">
+ <h1 style="font-size: 22px; margin: 0 0 12px">Welcome to the Inbox demo 👋</h1>
+ <p>This is the real app running against a pretend server in your browser. Nothing you do here
+ sends an email, and everything resets when you reload.</p>
+ <p style="margin: 18px 0 6px"><strong>Things to try</strong></p>
+ <ul style="padding-left: 20px; line-height: 1.7">
+ <li><strong>Send yourself a message</strong>: pick any of your addresses as the recipient and it lands in your inbox.</li>
+ <li><strong>Send one to anyone else</strong>: it goes to Sent, and a pretend reply comes back a few seconds later.</li>
+ <li><strong>Use Cc and Bcc</strong>. Bcc'd addresses only show on your own copy in Sent.</li>
+ <li><strong>Switch mailboxes</strong> in the sidebar to see one address or one whole domain at a time.</li>
+ <li><strong>Open Admin</strong> to switch domains off, set a catch-all, or hand yourself a new alias.</li>
+ </ul>
+ <p style="color: #6b6570; font-size: 13px; margin-top: 20px">Email HTML like this renders in a sandboxed frame with no script and its own styles.</p>
+</div>`;
+
+const NEWSLETTER_HTML = `
+<table role="presentation" width="100%" style="background: #f4f1ee; font-family: Georgia, serif">
+ <tr><td align="center" style="padding: 24px">
+ <table role="presentation" width="560" style="background: #fff; border-radius: 8px; overflow: hidden">
+ <tr><td><img src="https://picsum.photos/seed/inbox-demo/560/180" width="560" height="180" alt="A photo" style="display: block"></td></tr>
+ <tr><td style="padding: 24px">
+ <h2 style="margin: 0 0 8px; font-size: 24px">The Weekly Loaf</h2>
+ <p style="color: #555">Issue 42: why your sourdough starter is sulking, and what to feed it.</p>
+ <p>The picture above is a remote image. The inbox blocks those until you click
+ <em>Load remote images</em>, because most of them are tracking pixels.</p>
+ <p><a href="https://example.com" style="color: #b0306e">Read it on the web</a></p>
+ </td></tr>
+ </table>
+ </td></tr>
+</table>`;
+
+export function createDemoApi(): Api {
+ let domains: DomainInfo[] = [
+ {
+ name: "example.com",
+ enabled: true,
+ active: true,
+ catchAll: ME,
+ syncedAt: Date.now() - 3 * HOUR,
+ resend: { status: "verified", sending: true, receiving: true },
+ },
+ {
+ name: "example.net",
+ enabled: true,
+ active: true,
+ catchAll: null,
+ syncedAt: Date.now() - 3 * HOUR,
+ resend: { status: "verified", sending: true, receiving: true },
+ },
+ {
+ name: "example.org",
+ enabled: true,
+ active: false,
+ catchAll: null,
+ syncedAt: Date.now() - 3 * HOUR,
+ resend: { status: "verified", sending: true, receiving: false },
+ },
+ ];
+ let aliases: AliasInfo[] = [
+ { localPart: "hello", domain: "example.com", username: ME },
+ { localPart: "support", domain: "", username: "ari" },
+ ];
+ const users = [
+ { username: ME, isAdmin: true, createdAt: Date.now() - 90 * DAY, lastLoginAt: Date.now() },
+ { username: "ari", isAdmin: false, createdAt: Date.now() - 60 * DAY, lastLoginAt: Date.now() - 2 * DAY },
+ ];
+
+ /** Blob or data: URLs for attachment bytes, by attachment id. */
+ const files = new Map<string, string>();
+ /** Uploaded, not yet part of a message. */
+ const uploads = new Map<string, AttachmentInfo>();
+ const messages: Stored[] = [];
+
+ function addressesOf(username: string): string[] {
+ const out: string[] = [];
+ for (const d of domains.filter((d) => d.enabled && d.active)) {
+ // A specific-domain alias wins over the every-domain one.
+ const here = new Map(aliases.filter((a) => a.domain === "").map((a) => [a.localPart, a.username]));
+ for (const a of aliases.filter((a) => a.domain === d.name)) here.set(a.localPart, a.username);
+ if (!here.has(username)) out.push(`${username}@${d.name}`);
+ for (const [local, owner] of here) if (owner === username) out.push(`${local}@${d.name}`);
+ }
+ return out.sort();
+ }
+
+ /** Our address mail to `addr` would reach, if any. */
+ function routesToMe(addr: string): string | null {
+ const [local, domain] = bare(addr).split("@");
+ const d = domains.find((d) => d.name === domain && d.enabled && d.active);
+ if (!d || !local) return null;
+ const mine = addressesOf(ME);
+ const exact = `${local}@${d.name}`;
+ if (mine.includes(exact)) return exact;
+ const owned = aliases.some((a) => a.localPart === local && (a.domain === d.name || a.domain === ""));
+ const isUser = users.some((u) => u.username === local);
+ return !owned && !isUser && d.catchAll === ME ? exact : null;
+ }
+
+ function add(m: Omit<Stored, "snippet" | "attachments" | "cc" | "bcc" | "read"> & Partial<Stored>) {
+ const msg: Stored = {
+ cc: [],
+ bcc: [],
+ read: true,
+ attachments: [],
+ ...m,
+ snippet: snippetOf(m.text, m.html),
+ };
+ messages.push(msg);
+ return msg;
+ }
+
+ // --- Seed mail -----------------------------------------------------------
+
+ const now = Date.now();
+ add({
+ id: "welcome",
+ threadId: "t-welcome",
+ folder: "inbox",
+ mailbox: "[email protected]",
+ from: "Inbox <[email protected]>",
+ to: ["[email protected]"],
+ subject: "Welcome to the demo",
+ html: WELCOME_HTML,
+ text: null,
+ sentAt: now - 4 * MINUTE,
+ read: false,
+ });
+
+ const notes = textFile("trip-notes.txt", "Day 1: train up, check in, find food.\nDay 2: the long walk.\nDay 3: home.\n");
+ files.set(notes.info.id, notes.url);
+ add({
+ id: "ari-1",
+ threadId: "t-ari",
+ folder: "inbox",
+ mailbox: "[email protected]",
+ from: "Ari Lane <[email protected]>",
+ to: ["[email protected]"],
+ subject: "Weekend trip?",
+ html: null,
+ text: "Hey!\n\nStill up for the trip on the 8th? I wrote down a rough plan, it's attached.\n\nAri",
+ sentAt: now - 2 * DAY,
+ attachments: [notes.info],
+ });
+ add({
+ id: "ari-2",
+ threadId: "t-ari",
+ folder: "sent",
+ mailbox: "[email protected]",
+ from: "[email protected]",
+ to: ["Ari Lane <[email protected]>"],
+ subject: "Re: Weekend trip?",
+ html: null,
+ text: "Yes! The plan looks good. Can we leave a bit later on day 1?\n\n> Still up for the trip on the 8th?",
+ sentAt: now - 2 * DAY + 3 * HOUR,
+ });
+ add({
+ id: "ari-3",
+ threadId: "t-ari",
+ folder: "inbox",
+ mailbox: "[email protected]",
+ from: "Ari Lane <[email protected]>",
+ to: ["[email protected]"],
+ subject: "Re: Weekend trip?",
+ html: null,
+ text: "Sure, 11 instead of 9. See you then!\n\nAri",
+ sentAt: now - 50 * MINUTE,
+ read: false,
+ });
+
+ add({
+ id: "news-1",
+ threadId: "t-news",
+ folder: "inbox",
+ mailbox: "[email protected]",
+ from: "The Weekly Loaf <[email protected]>",
+ to: ["[email protected]"],
+ subject: "Issue 42: a sulking starter",
+ html: NEWSLETTER_HTML,
+ text: null,
+ sentAt: now - 6 * HOUR,
+ });
+
+ add({
+ id: "hello-1",
+ threadId: "t-hello",
+ folder: "inbox",
+ mailbox: "[email protected]",
+ from: "Sam Okafor <[email protected]>",
+ to: ["[email protected]"],
+ subject: "Quote for the new site",
+ html: null,
+ text: "Hi there,\n\nCould you send over a quote for the redesign we talked about? No rush.\n\nThanks,\nSam",
+ sentAt: now - 1 * DAY,
+ read: false,
+ });
+
+ add({
+ id: "sent-bcc",
+ threadId: "t-party",
+ folder: "sent",
+ mailbox: "[email protected]",
+ from: "[email protected]",
+ to: ["[email protected]"],
+ cc: ["Ari Lane <[email protected]>"],
+ bcc: ["[email protected]"],
+ subject: "Saturday 🎉",
+ html: null,
+ text: "Party at mine on Saturday from 7. Bring snacks!\n\n(The Bcc above is only on this copy. Nobody else sees it.)",
+ sentAt: now - 3 * DAY,
+ });
+
+ add({
+ id: "draft-1",
+ threadId: "t-draft",
+ folder: "drafts",
+ mailbox: "[email protected]",
+ from: "[email protected]",
+ to: ["[email protected]"],
+ subject: "Boiler",
+ html: null,
+ text: "Hi,\n\nThe boiler is making the noise again. Could someone",
+ sentAt: now - 5 * HOUR,
+ });
+
+ // --- Helpers -------------------------------------------------------------
+
+ /** Feels like a network, and lets the app's loading states show. */
+ const later = <T>(value: () => T, ms = 120): Promise<T> =>
+ new Promise((resolve, reject) =>
+ setTimeout(() => {
+ try {
+ resolve(structuredClone(value()));
+ } catch (e) {
+ reject(e);
+ }
+ }, ms),
+ );
+
+ function unread(): Record<string, number> {
+ const out: Record<string, number> = {};
+ for (const m of messages) if (m.folder === "inbox" && !m.read) out[m.mailbox] = (out[m.mailbox] ?? 0) + 1;
+ return out;
+ }
+
+ function remove(pred: (m: Stored) => boolean): number {
+ let n = 0;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (pred(messages[i]!)) {
+ messages.splice(i, 1);
+ n++;
+ }
+ }
+ if (!n) throw new Error("Not found");
+ return n;
+ }
+
+ function attachmentsFor(ids: string[], keep: AttachmentInfo[] = []): AttachmentInfo[] {
+ const known = new Map(messages.flatMap((m) => m.attachments).map((a) => [a.id, a]));
+ for (const a of keep) known.set(a.id, a);
+ return ids.map((id) => {
+ const a = uploads.get(id) ?? known.get(id);
+ if (!a) throw new Error("One of the attachments is gone.");
+ uploads.delete(id);
+ return a;
+ });
+ }
+
+ function saveDraft(input: ComposeInput, draftId?: string | null): Stored {
+ const mine = addressesOf(ME);
+ if (!mine.includes(bare(input.from))) throw new Error(`You can't send from ${bare(input.from) || "that address"}.`);
+ const fields = {
+ mailbox: bare(input.from),
+ from: bare(input.from),
+ to: input.to,
+ cc: input.cc,
+ bcc: input.bcc,
+ subject: input.subject,
+ text: input.text,
+ html: renderHtml(input.text),
+ snippet: snippetOf(input.text, null),
+ sentAt: Date.now(),
+ };
+
+ if (draftId) {
+ const draft = messages.find((m) => m.id === draftId && m.folder === "drafts");
+ if (!draft) throw new Error("That draft doesn't exist any more.");
+ Object.assign(draft, fields, { attachments: attachmentsFor(input.attachmentIds, draft.attachments) });
+ return draft;
+ }
+ const original = input.replyTo ? messages.find((m) => m.id === input.replyTo) : null;
+ if (input.replyTo && !original) throw new Error("The message you're replying to is gone.");
+ return add({
+ id: crypto.randomUUID(),
+ threadId: original?.threadId ?? crypto.randomUUID(),
+ folder: "drafts",
+ ...fields,
+ attachments: attachmentsFor(input.attachmentIds),
+ });
+ }
+
+ function deliver(sent: Stored) {
+ const everyone = [...sent.to, ...sent.cc, ...sent.bcc];
+ const ours = new Set(everyone.map(routesToMe).filter((a): a is string => a !== null));
+ for (const mailbox of ours) {
+ add({ ...sent, id: crypto.randomUUID(), folder: "inbox", mailbox, bcc: [], read: false });
+ }
+
+ // Anyone outside answers after a moment, so there's something to read.
+ const outside = everyone.find((a) => routesToMe(a) === null && !users.some((u) => addressesOf(u.username).includes(bare(a))));
+ if (!outside) return;
+ setTimeout(() => {
+ if (!messages.some((m) => m.threadId === sent.threadId)) return;
+ add({
+ id: crypto.randomUUID(),
+ threadId: sent.threadId,
+ folder: "inbox",
+ mailbox: sent.mailbox,
+ from: outside,
+ to: [sent.from],
+ subject: /^re:/i.test(sent.subject) ? sent.subject : `Re: ${sent.subject}`,
+ html: null,
+ text:
+ "Thanks, got it!\n\n(This is a pretend reply from the demo. Your message wasn't really sent anywhere.)\n\n" +
+ (sent.text ?? "").split("\n").map((l) => `> ${l}`).join("\n"),
+ sentAt: Date.now(),
+ read: false,
+ });
+ changed();
+ }, 5000);
+ }
+
+ function summaries(folder: Folder, mailbox: string | null): ThreadSummary[] {
+ const inFolder = messages.filter(
+ (m) =>
+ m.folder === folder &&
+ (!mailbox || (mailbox.startsWith("@") ? m.mailbox.endsWith(mailbox.toLowerCase()) : m.mailbox === mailbox.toLowerCase())),
+ );
+ const byThread = new Map<string, Stored[]>();
+ for (const m of inFolder) byThread.set(m.threadId, [...(byThread.get(m.threadId) ?? []), m]);
+ return [...byThread]
+ .map(([id, list]) => {
+ const latest = list.reduce((a, b) => (b.sentAt > a.sentAt ? b : a));
+ return {
+ id,
+ latestId: latest.id,
+ mailbox: latest.mailbox,
+ subject: latest.subject,
+ from: latest.from,
+ to: latest.to,
+ snippet: latest.snippet,
+ lastAt: latest.sentAt,
+ count: list.length,
+ unread: list.filter((m) => !m.read).length,
+ hasAttachments: messages.some((m) => m.threadId === id && m.attachments.some((a) => !a.contentId)),
+ };
+ })
+ .sort((a, b) => b.lastAt - a.lastAt);
+ }
+
+ function userInfo(u: (typeof users)[number]): UserInfo {
+ return { ...u, messageCount: u.username === ME ? messages.length : 7, addresses: addressesOf(u.username) };
+ }
+
+ function domainInfo(d: DomainInfo): DomainInfo {
+ return { ...d, active: d.enabled && (d.resend?.receiving ?? false) };
+ }
+
+ // --- The API -------------------------------------------------------------
+
+ return {
+ me: () =>
+ later<Me>(() => ({
+ username: ME,
+ isAdmin: users.find((u) => u.username === ME)!.isAdmin,
+ addresses: addressesOf(ME),
+ domains: domains.filter((d) => d.enabled).map((d) => d.name),
+ pushPublicKey: null,
+ })),
+ // Reloading the page starts the demo over.
+ logout: () => later(() => ({ endSession: "/demo" as string | null })),
+
+ threads: (folder, mailbox) =>
+ later<Page<ThreadSummary>>(() => ({ items: summaries(folder, mailbox), nextCursor: null })),
+ thread: (id) =>
+ later<Thread>(() => {
+ const list = messages.filter((m) => m.threadId === id).sort((a, b) => a.sentAt - b.sentAt);
+ if (!list.length) throw new Error("Not found");
+ return { id, subject: list.at(-1)!.subject, messages: list };
+ }),
+ markThread: (id, read) =>
+ later(() => {
+ for (const m of messages) if (m.threadId === id && m.folder === "inbox") m.read = read;
+ return { unread: unread() };
+ }),
+ deleteThread: (id) => later(() => ({ count: remove((m) => m.threadId === id) })),
+ message: (id) =>
+ later<Message>(() => {
+ const m = messages.find((m) => m.id === id);
+ if (!m) throw new Error("Not found");
+ return m;
+ }),
+ deleteMessage: (id) => later(() => ({ count: remove((m) => m.id === id) })),
+ unread: () => later(() => ({ unread: unread() })),
+ attachmentUrl: (id) => files.get(id) ?? "data:text/plain,This%20attachment%20is%20gone.",
+
+ upload: (file) =>
+ later<AttachmentInfo>(() => {
+ if (file.size > 25 * 1024 * 1024) throw new Error("Attachments can be up to 25 MB each.");
+ const info: AttachmentInfo = {
+ id: crypto.randomUUID(),
+ filename: file.name,
+ contentType: file.type || "application/octet-stream",
+ size: file.size,
+ contentId: null,
+ };
+ files.set(info.id, URL.createObjectURL(file));
+ uploads.set(info.id, info);
+ return info;
+ }, 400),
+ createDraft: (input) => later(() => ({ id: saveDraft(input).id })),
+ updateDraft: (id, input) => later(() => ({ id: saveDraft(input, id).id })),
+ send: (input, draftId) =>
+ later(() => {
+ const draft = saveDraft(input, draftId);
+ if (!draft.to.length) throw new Error("Add at least one recipient.");
+ if (!draft.subject.trim()) throw new Error("Add a subject.");
+ draft.folder = "sent";
+ draft.sentAt = Date.now();
+ deliver(draft);
+ return { id: draft.id, threadId: draft.threadId };
+ }, 500),
+
+ pushSubscribe: () => later(() => ({})),
+ pushUnsubscribe: () => later(() => ({})),
+ pushTest: () => later(() => ({ sent: 0 })),
+
+ admin: {
+ domains: () =>
+ later(() => {
+ for (const d of domains) d.syncedAt = Date.now();
+ return { domains: domains.map(domainInfo), syncError: null as string | null };
+ }),
+ saveDomain: (name, enabled, catchAll) =>
+ later(() => {
+ domains = domains.map((d) => (d.name === name ? domainInfo({ ...d, enabled, catchAll }) : d));
+ return {};
+ }),
+ aliases: () => later(() => aliases),
+ addAlias: (a) =>
+ later(() => {
+ const localPart = a.localPart.trim().toLowerCase();
+ if (!/^[a-z0-9._+-]+$/.test(localPart)) throw new Error("That isn't a valid local part.");
+ if (!users.some((u) => u.username === a.username)) throw new Error("Pick a user.");
+ if (aliases.some((x) => x.localPart === localPart && x.domain === a.domain)) throw new Error("That alias already exists.");
+ aliases = [...aliases, { ...a, localPart }];
+ return {};
+ }),
+ deleteAlias: (a) =>
+ later(() => {
+ aliases = aliases.filter((x) => !(x.localPart === a.localPart && x.domain === a.domain));
+ return {};
+ }),
+ users: () => later(() => users.map(userInfo)),
+ setAdmin: (username, isAdmin) =>
+ later(() => {
+ const u = users.find((u) => u.username === username);
+ if (u) u.isAdmin = isAdmin;
+ return {};
+ }),
+ deleteUser: (username) =>
+ later(() => {
+ if (username === ME) throw new Error("You can't delete yourself.");
+ const i = users.findIndex((u) => u.username === username);
+ if (i < 0) throw new Error("Not found");
+ users.splice(i, 1);
+ aliases = aliases.filter((a) => a.username !== username);
+ return { deletedMail: 7 };
+ }),
+ },
+ };
+}
diff --git a/src/web/lib/router.svelte.ts b/src/web/lib/router.svelte.ts
index 6559ac0..dcfdb5b 100644
--- a/src/web/lib/router.svelte.ts
+++ b/src/web/lib/router.svelte.ts
@@ -5,6 +5,18 @@ export type Route =
| { name: "settings" }
| { name: "admin" };
+/**
+ * The demo runs the same app under /demo, against the in-memory fake in
+ * demo.ts. Routes and links are written without this prefix; the router adds
+ * and strips it.
+ */
+export const base = /^\/demo(\/|$)/.test(location.pathname) ? "/demo" : "";
+export const isDemo = base !== "";
+
+function strip(pathname: string): string {
+ return pathname.slice(base.length) || "/";
+}
+
function parse(path: string): Route {
const [first, second] = path.split("/").filter(Boolean);
if (first === "settings") return { name: "settings" };
@@ -14,7 +26,7 @@ function parse(path: string): Route {
}
class Router {
- path = $state(location.pathname);
+ path = $state(strip(location.pathname));
search = $state(location.search);
route = $derived(parse(this.path));
/** ?in=addr@domain for one address, ?in=@domain for a whole domain. */
@@ -25,13 +37,18 @@ class Router {
}
private sync() {
- this.path = location.pathname;
+ this.path = strip(location.pathname);
this.search = location.search;
}
+ /** An app path as a real URL, for href attributes. */
+ href(url: string): string {
+ return base + url;
+ }
+
go(url: string, { replace = false } = {}) {
- if (url === location.pathname + location.search) return;
- history[replace ? "replaceState" : "pushState"](null, "", url);
+ if (base + url === location.pathname + location.search) return;
+ history[replace ? "replaceState" : "pushState"](null, "", base + url);
this.sync();
}
@@ -52,7 +69,8 @@ export function interceptLinks(root: HTMLElement) {
const a = (ev.target as Element).closest("a");
if (!a || a.target || a.hasAttribute("download") || a.origin !== location.origin) return;
if (a.pathname.startsWith("/api/") || a.pathname.startsWith("/auth/")) return;
+ if (base && !a.pathname.startsWith(base)) return;
ev.preventDefault();
- router.go(a.pathname + a.search);
+ router.go(strip(a.pathname) + a.search);
});
}
diff --git a/src/web/lib/state.svelte.ts b/src/web/lib/state.svelte.ts
index 0c94aaf..527c681 100644
--- a/src/web/lib/state.svelte.ts
+++ b/src/web/lib/state.svelte.ts
@@ -28,6 +28,7 @@ export interface ComposeInit {
from: string;
to: string;
cc: string;
+ bcc: string;
subject: string;
text: string;
attachments: AttachmentInfo[];
@@ -63,6 +64,7 @@ export function composeNew() {
from: defaultFrom(),
to: "",
cc: "",
+ bcc: "",
subject: "",
text: "",
attachments: [],
@@ -78,6 +80,7 @@ export function composeReply(m: Message) {
from: ourAddress(m),
to: outbound ? m.to.join(", ") : m.from,
cc: "",
+ bcc: "",
subject: prefixed("Re", m.subject),
text: quote(m),
attachments: [],
@@ -92,6 +95,7 @@ export function composeForward(m: Message) {
from: ourAddress(m),
to: "",
cc: "",
+ bcc: "",
subject: prefixed("Fwd", m.subject),
text: `\n\n---------- Forwarded message ----------\nFrom: ${m.from}\nTo: ${m.to.join(", ")}\nSubject: ${m.subject}\n\n${m.text ?? ""}`,
attachments: m.attachments.filter((a) => !a.contentId),
@@ -106,6 +110,7 @@ export function composeDraft(m: Message) {
from: m.from,
to: m.to.join(", "),
cc: m.cc.join(", "),
+ bcc: m.bcc.join(", "),
subject: m.subject,
text: m.text ?? "",
attachments: m.attachments,
diff --git a/src/worker/routes/mail.ts b/src/worker/routes/mail.ts
index 43b0aca..327a733 100644
--- a/src/worker/routes/mail.ts
+++ b/src/worker/routes/mail.ts
@@ -24,6 +24,7 @@ const compose = z.object({
from: z.string().max(320),
to: z.array(address).max(50),
cc: z.array(address).max(50).default([]),
+ bcc: z.array(address).max(50).default([]),
subject: z.string().max(998),
text: z.string().max(1_000_000),
attachmentIds: z.array(z.uuid()).max(50).default([]),
diff --git a/src/worker/services/messages.ts b/src/worker/services/messages.ts
index a3589f8..3ae1d34 100644
--- a/src/worker/services/messages.ts
+++ b/src/worker/services/messages.ts
@@ -17,6 +17,7 @@ type MessageRow = {
from_addr: string;
to_addrs: string;
cc_addrs: string;
+ bcc_addrs: string;
subject: string;
snippet: string;
html: string | null;
@@ -34,7 +35,11 @@ type AttachmentRow = {
content_id: string | null;
};
-export type NewMessage = Omit<MessageRow, "read" | "snippet" | "thread_id"> & { read: boolean };
+export type NewMessage = Omit<MessageRow, "read" | "snippet" | "thread_id" | "bcc_addrs"> & {
+ read: boolean;
+ /** Defaults to none; only outgoing mail has a Bcc. */
+ bcc_addrs?: string;
+};
function toAttachment(row: AttachmentRow): AttachmentInfo {
return {
@@ -55,6 +60,7 @@ function toMessage(row: MessageRow, attachments: AttachmentInfo[]): Message {
from: row.from_addr,
to: JSON.parse(row.to_addrs) as string[],
cc: JSON.parse(row.cc_addrs) as string[],
+ bcc: JSON.parse(row.bcc_addrs) as string[],
subject: row.subject,
snippet: row.snippet,
html: row.html,
@@ -141,8 +147,8 @@ export async function insertMessage(env: Env, threadId: string, m: NewMessage):
export function insertMessageStatement(env: Env, threadId: string, m: NewMessage): D1PreparedStatement {
return env.DB.prepare(
"INSERT INTO messages (id, owner, thread_id, folder, mailbox, resend_id, message_id, in_reply_to, refs, " +
- "from_addr, to_addrs, cc_addrs, subject, snippet, html, text, sent_at, read) " +
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (resend_id, owner) DO NOTHING",
+ "from_addr, to_addrs, cc_addrs, bcc_addrs, subject, snippet, html, text, sent_at, read) " +
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (resend_id, owner) DO NOTHING",
)
.bind(
m.id,
@@ -157,6 +163,7 @@ export function insertMessageStatement(env: Env, threadId: string, m: NewMessage
m.from_addr,
m.to_addrs,
m.cc_addrs,
+ m.bcc_addrs ?? "[]",
m.subject,
snippetOf(m.text, m.html),
m.html,
diff --git a/src/worker/services/outbound.ts b/src/worker/services/outbound.ts
index d912baf..16716d3 100644
--- a/src/worker/services/outbound.ts
+++ b/src/worker/services/outbound.ts
@@ -34,7 +34,7 @@ export async function saveDraft(env: Env, user: string, input: ComposeInput, dra
if (draftId) {
const res = await env.DB.prepare(
- "UPDATE messages SET mailbox = ?, from_addr = ?, to_addrs = ?, cc_addrs = ?, subject = ?, text = ?, " +
+ "UPDATE messages SET mailbox = ?, from_addr = ?, to_addrs = ?, cc_addrs = ?, bcc_addrs = ?, subject = ?, text = ?, " +
"html = ?, snippet = ?, sent_at = ? WHERE id = ? AND owner = ? AND folder = 'drafts'",
)
.bind(
@@ -42,6 +42,7 @@ export async function saveDraft(env: Env, user: string, input: ComposeInput, dra
from,
JSON.stringify(input.to),
JSON.stringify(input.cc),
+ JSON.stringify(input.bcc),
input.subject,
input.text,
html,
@@ -84,6 +85,7 @@ export async function saveDraft(env: Env, user: string, input: ComposeInput, dra
from_addr: from,
to_addrs: JSON.stringify(input.to),
cc_addrs: JSON.stringify(input.cc),
+ bcc_addrs: JSON.stringify(input.bcc),
subject: input.subject,
html,
text: input.text,
@@ -101,6 +103,7 @@ export async function sendDraft(env: Env, user: string, draftId: string): Promis
const to = JSON.parse(draft.to_addrs) as string[];
const cc = JSON.parse(draft.cc_addrs) as string[];
+ const bcc = JSON.parse(draft.bcc_addrs) as string[];
if (!to.length) throw new ComposeError("Add at least one recipient.");
if (!draft.subject.trim()) throw new ComposeError("Add a subject.");
@@ -119,6 +122,7 @@ export async function sendDraft(env: Env, user: string, draftId: string): Promis
from,
to,
cc: cc.length ? cc : undefined,
+ bcc: bcc.length ? bcc : undefined,
subject: draft.subject,
html: draft.html ?? renderHtml(draft.text ?? ""),
text: draft.text ?? undefined,