Files
Oday BakkourandClaude Fable 5.1 f0dc5a16fc feat(self-host): run Mailflare as a Docker container on any host
Adds a second runtime next to Cloudflare Workers. One Node process serves
the Next app, a realtime WebSocket hub, the job queues, the backup schedule
and an SMTP listener; SQLite and local files replace D1 and R2. The
application code is unchanged: the runtime builds an object with the same
binding interfaces (`server/runtime/`) and publishes it before Next starts,
so `getEnv()` hands route handlers the same shape on both platforms.

Runtime (server/)
- `sqlite-database.ts`: the D1 API over better-sqlite3, so Drizzle's D1
  driver, the raw `env.DB.prepare` callers, the FTS5 index and its triggers
  all work as-is. Migrations are applied from drizzle/migrations at start,
  recorded in `d1_migrations` like Wrangler does.
- `file-bucket.ts`: the R2 API over a directory, with metadata sidecars and
  byte ranges. `mailer.ts`: the send_email builder over nodemailer (any SMTP
  relay) or Cloudflare's Email Sending REST API; generates the Message-ID so
  threading matches Workers. `queue.ts`: in-process queues with the same
  retry policy. `realtime.ts`: per-user WebSocket fan-out in place of the
  Durable Object. `misc.ts`: rate limiter and ASSETS fetcher.
- `smtp.ts`: inbound SMTP on port 25 via smtp-server; reject rules answer
  550, forward rules relay the raw message through the outbound SMTP.
- `index.ts`: the custom server; `scripts/build-server.mjs` bundles it with
  esbuild to dist/server.mjs.

Application changes
- `src/lib/runtime.ts` + `getEnv()` prefer the Node env when present.
- `src/lib/email/intake.ts` factors the Worker email handler's logic so the
  SMTP listener and the new signed `/api/inbound` webhook share it.
- Domains without Cloudflare credentials are recorded with zone id
  "manual": Cloudflare calls no-op, the domain is active at once, and the
  DNS page lists MX/SPF/DMARC records to create. Setup checks, the domains
  page copy and the self-update button adapt to the runtime; `/api/auth/me`
  exposes `runtime` and `managesDns`.
- `APP_URL` overrides the origin for reset links and the JMAP session
  behind a proxy. The direct `getCloudflareContext` import in the update
  route is replaced with `getEnv()`.

Deployment
- Dockerfile (multi-stage, 1.1 GB, Workers toolchain pruned), compose file,
  `.env.docker.example`, `docs/self-hosting.md`, README section.
- `deploy/cloudflare-email-relay`: a Worker that keeps MX on Cloudflare
  Email Routing and posts messages to the server with an HMAC signature,
  acting on the reject/forward decision it returns.

Verified on a fresh data directory and again inside the built image:
migrations apply, first-run setup and registration work with no Cloudflare
credentials, mail over SMTP lands in the inbox with the raw copy on disk,
a reject rule answers 550, a send through SMTP_URL loops back and is stored
as sent and received, an inbound reply threads with the sent copy, FTS
search finds body text, a backup completes to the volume, the WebSocket
delivers a push, the relay webhook rejects a bad signature and returns
store/reject decisions, JMAP serves a session with the APP_URL origin.
Container healthcheck reports healthy. tsc (11) and eslint (105) unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PGeWDVSkXtVEmDAN2AtB9h
2026-09-12 14:34:11 +03:00

135 lines
5.0 KiB
TypeScript

import nodemailer from "nodemailer";
import type { Transporter } from "nodemailer";
import { getEmailAddress } from "@/lib/email/address";
type Builder = {
from: string | { name?: string; email: string };
to: string | string[];
cc?: string | string[];
bcc?: string | string[];
replyTo?: string | { name?: string; email: string };
subject: string;
headers?: Record<string, string>;
text?: string;
html?: string;
attachments?: Array<{ filename: string; type: string; content: ArrayBuffer | ArrayBufferView | string; disposition?: string; contentId?: string }>;
};
export type MailerConfig =
| { kind: "smtp"; url: string }
| { kind: "cloudflare"; accountId: string; token: string }
| { kind: "none" };
function addressString(value: string | { name?: string; email: string }): string {
if (typeof value === "string") return value;
return value.name ? `"${value.name.replace(/"/g, '\\"')}" <${value.email}>` : value.email;
}
function messageIdFor(from: Builder["from"]): string {
const domain = getEmailAddress(addressString(from)).split("@")[1] || "mailflare.local";
return `<${crypto.randomUUID()}@${domain}>`;
}
/**
* The `send_email` binding's builder API over SMTP (any provider, or your
* own MTA) or Cloudflare's Email Sending REST endpoint. A Message-ID is
* generated here and passed as a header so threading behaves the same as on
* Workers, where Cloudflare returns the id it assigned.
*/
export class Mailer {
private transporter: Transporter | null = null;
constructor(private readonly config: MailerConfig) {
if (config.kind === "smtp") {
// Self-signed relays are common on private networks; opt in explicitly.
const rejectUnauthorized = process.env.SMTP_TLS_REJECT_UNAUTHORIZED !== "false";
this.transporter = nodemailer.createTransport({ url: config.url, tls: { rejectUnauthorized } });
}
}
get configured() {
return this.config.kind !== "none";
}
async send(message: Builder): Promise<{ messageId: string }> {
const messageId = message.headers?.["Message-ID"] ?? messageIdFor(message.from);
const headers = { ...(message.headers ?? {}), "Message-ID": messageId };
if (this.config.kind === "smtp" && this.transporter) {
await this.transporter.sendMail({
from: addressString(message.from),
to: message.to,
cc: message.cc,
bcc: message.bcc,
replyTo: message.replyTo ? addressString(message.replyTo) : undefined,
subject: message.subject,
text: message.text,
html: message.html,
headers: Object.fromEntries(Object.entries(headers).filter(([key]) => key !== "Message-ID")),
messageId,
attachments: (message.attachments ?? []).map((attachment) => ({
filename: attachment.filename,
contentType: attachment.type,
content: toBuffer(attachment.content),
contentDisposition: attachment.disposition === "inline" ? "inline" : "attachment",
cid: attachment.contentId ?? undefined,
})),
});
return { messageId };
}
if (this.config.kind === "cloudflare") {
const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/email/sending/send`, {
method: "POST",
headers: { Authorization: `Bearer ${this.config.token}`, "Content-Type": "application/json" },
body: JSON.stringify({
from: addressString(message.from),
to: message.to,
cc: message.cc,
bcc: message.bcc,
reply_to: message.replyTo ? addressString(message.replyTo) : undefined,
subject: message.subject,
text: message.text,
html: message.html,
headers,
attachments: (message.attachments ?? []).map((attachment) => ({
filename: attachment.filename,
type: attachment.type,
content: base64(toBuffer(attachment.content)),
disposition: attachment.disposition === "inline" ? "inline" : "attachment",
...(attachment.contentId ? { content_id: attachment.contentId } : {}),
})),
}),
});
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new Error(`Cloudflare Email Sending failed (${response.status}): ${detail.slice(0, 300)}`);
}
return { messageId };
}
throw new Error("Outbound mail is not configured. Set SMTP_URL, or CF_ACCOUNT_ID and CF_TOKEN.");
}
/** Relay a raw RFC 5322 message unchanged, for forwarding rules. SMTP only. */
async sendRaw(envelopeFrom: string, to: string, raw: Buffer): Promise<boolean> {
if (!this.transporter) return false;
await this.transporter.sendMail({ envelope: { from: envelopeFrom, to }, raw });
return true;
}
}
function base64(buffer: Buffer): string {
return (buffer as unknown as { toString(encoding: string): string }).toString("base64");
}
function toBuffer(content: ArrayBuffer | ArrayBufferView | string): Buffer {
if (typeof content === "string") return Buffer.from(content);
if (content instanceof ArrayBuffer) return Buffer.from(new Uint8Array(content));
return Buffer.from(content.buffer, content.byteOffset, content.byteLength);
}
export function openMailer(config: MailerConfig): SendEmail & Mailer {
return new Mailer(config) as unknown as SendEmail & Mailer;
}