Repository Public
1// Passerelle JMAP : les clients (web, macOS, iOS) parlent du JMAP standard à SP Mail, qui authentifie la2// session de l'appareil puis relaie vers Stalwart avec le secret de la boîte. Aucun identifiant Stalwart ne sort d'ici.3import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify"4import { Readable } from "node:stream"5import { config } from "./config.js"6import { sql } from "./db.js"7import { hasServerPolicy, reconcileSieve } from "./addresses.js"8import { mailboxById } from "./mailjmap.js"9import { requireUser } from "./session.js"10import { basic, unseal } from "./stalwart.js"11import { bad, rateLimit, zUuid } from "./util.js"1213const FORBIDDEN_CAPS = new Set(["urn:stalwart:jmap"]) // la gestion du serveur ne passe jamais par la passerelle1415async function upstreamAuth(req: FastifyRequest): Promise<{ auth: string; mb: string; canSend: boolean }> {16 const a = await requireUser(req)17 const { mb } = req.params as { mb: string }18 if (!zUuid.safeParse(mb).success) throw bad("not_found", 404)19 // Propriétaire, ou utilisateur à qui la boîte est partagée en lecture (mailbox_grants).20 const [row] = await sql`select m.address, m.secret_enc, m.user_id, g.can_send from mailboxes m21 left join mailbox_grants g on g.mailbox_id = m.id and g.user_id = ${a.userId}22 where m.id = ${mb} and (m.user_id = ${a.userId} or g.can_read)`23 if (!row) throw bad("not_found", 404) // boîte d'un autre utilisateur : indiscernable d'une boîte inexistante24 rateLimit(`jmap:${a.sessionId}`, 1200, 60_000)25 return { auth: basic(row.address, unseal(Buffer.from(row.secret_enc))), mb, canSend: row.user_id === a.userId || !!row.can_send }26}2728function rewriteSession(s: Record<string, any>, mb: string) {29 const base = `${config.origin}/api/jmap/${mb}`30 s.apiUrl = `${base}/api`31 s.uploadUrl = `${base}/upload/{accountId}/`32 s.downloadUrl = `${base}/download/{accountId}/{blobId}/{name}?accept={type}`33 s.eventSourceUrl = `${base}/eventsource?types={types}&closeafter={closeafter}&ping={ping}`34 for (const cap of FORBIDDEN_CAPS) {35 delete s.capabilities?.[cap]36 delete s.primaryAccounts?.[cap]37 for (const acc of Object.values<any>(s.accounts ?? {})) delete acc.accountCapabilities?.[cap]38 }39 if (s.capabilities?.["urn:ietf:params:jmap:websocket"]) delete s.capabilities["urn:ietf:params:jmap:websocket"]40 return s41}4243async function up(path: string, init: RequestInit & { duplex?: "half" }) {44 try {45 return await fetch(`${config.stalwartUrl}${path}`, init)46 } catch {47 throw bad("mail_server_unavailable", 502, "The mail server is unreachable")48 }49}5051/**52 * Un 401 / 403 de Stalwart (compte de courrier en cours de purge, secret désynchronisé) n'est PAS une session SP Mail expirée :53 * relayé tel quel, il déconnecterait l'utilisateur. Sur chaque relais, il devient une panne du serveur de courrier (502 mail_server_auth).54 */55function refuseUpstreamAuth(r: Response) {56 if (r.status !== 401 && r.status !== 403) return57 void r.body?.cancel().catch(() => {})58 throw bad("mail_server_auth", 502, "The mail server refused the mailbox credentials")59}6061export function jmapRoutes(app: FastifyInstance) {62 app.get("/api/jmap/:mb/session", async (req) => {63 const { auth, mb } = await upstreamAuth(req)64 const r = await up("/jmap/session", { headers: { authorization: auth }, signal: AbortSignal.timeout(15_000) })65 refuseUpstreamAuth(r)66 if (!r.ok) throw bad("mail_server_error", 502, `session ${r.status}`)67 return rewriteSession((await r.json()) as Record<string, any>, mb)68 })6970 app.post("/api/jmap/:mb/api", { bodyLimit: 10 * 1024 * 1024 }, async (req, reply) => {71 const { auth, mb, canSend } = await upstreamAuth(req)72 const body = req.body as { using?: unknown; methodCalls?: unknown }73 if (!body || !Array.isArray(body.using) || !Array.isArray(body.methodCalls)) throw bad("invalid_request", 400)74 if (body.using.some((u) => FORBIDDEN_CAPS.has(String(u)))) throw bad("forbidden_capability", 403)75 if (body.methodCalls.some((c) => Array.isArray(c) && String(c[0]).startsWith("x:"))) throw bad("forbidden_method", 403)76 const names = body.methodCalls.map((c) => (Array.isArray(c) ? String(c[0]) : ""))77 // Boîte partagée en lecture seule : aucune soumission.78 if (!canSend && names.some((n) => n.startsWith("EmailSubmission/set"))) throw bad("send_not_granted", 403, "This shared mailbox is read-only for you")79 const r = await up("/jmap/", { method: "POST", headers: { authorization: auth, "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(120_000) })80 // Un client vient d'écrire le script Sieve : le bloc de politique du serveur (adresses « discard », réexpédition) y est réinjecté.81 if (r.ok && names.includes("SieveScript/set"))82 void hasServerPolicy(mb).then(async (yes) => { const box = yes ? await mailboxById(mb) : null; if (box) await reconcileSieve(box) }).catch((e) => req.log.error({ err: String(e?.message ?? e) }, "sieve policy re-injection failed"))83 refuseUpstreamAuth(r)84 reply.status(r.status).type(r.headers.get("content-type") ?? "application/json")85 return reply.send(Buffer.from(await r.arrayBuffer()))86 })8788 // Téléversement : dans un contexte isolé où AUCUN type n'est interprété (un fichier .json ou .txt reste un flux d'octets).89 app.register(async (raw) => {90 raw.removeAllContentTypeParsers()91 raw.addContentTypeParser("*", (_req, payload, done) => done(null, payload))92 raw.post("/api/jmap/:mb/upload/:accountId/", { bodyLimit: 50 * 1024 * 1024 }, async (req, reply) => {93 const { auth } = await upstreamAuth(req)94 const { accountId } = req.params as { accountId: string }95 const r = await up(`/jmap/upload/${encodeURIComponent(accountId)}/`, {96 method: "POST",97 headers: { authorization: auth, "content-type": String(req.headers["content-type"] ?? "application/octet-stream") },98 body: Readable.toWeb(req.body as Readable) as never,99 duplex: "half",100 signal: AbortSignal.timeout(300_000),101 })102 refuseUpstreamAuth(r)103 reply.status(r.status).type(r.headers.get("content-type") ?? "application/json")104 return reply.send(Buffer.from(await r.arrayBuffer()))105 })106 })107108 const INLINE_OK = /^image\/(png|jpeg|gif|webp)$/109 app.get("/api/jmap/:mb/download/:accountId/:blobId/:name", async (req, reply) => {110 const { auth } = await upstreamAuth(req)111 const { accountId, blobId, name } = req.params as Record<string, string>112 const q = req.query as { accept?: string; inline?: string }113 const accept = String(q.accept ?? "application/octet-stream")114 const r = await up(`/jmap/download/${encodeURIComponent(accountId)}/${encodeURIComponent(blobId)}/${encodeURIComponent(name)}?accept=${encodeURIComponent(accept)}`, {115 headers: { authorization: auth }, signal: AbortSignal.timeout(300_000),116 })117 refuseUpstreamAuth(r)118 if (!r.ok || !r.body) throw bad(r.status === 404 ? "not_found" : "mail_server_error", r.status === 404 ? 404 : 502)119 // Une pièce jointe n'est jamais interprétée par le navigateur dans l'origine du webmail.120 const inline = q.inline === "1" && INLINE_OK.test(accept)121 const safeName = name.replace(/[^\w.\- ()À-ɏ]/g, "_").slice(0, 150) || "fichier"122 reply.header("content-type", inline ? accept : "application/octet-stream")123 reply.header("content-disposition", `${inline ? "inline" : "attachment"}; filename*=UTF-8''${encodeURIComponent(safeName)}`)124 reply.header("content-security-policy", "sandbox; default-src 'none'")125 reply.header("cache-control", "private, max-age=3600")126 const len = r.headers.get("content-length")127 if (len) reply.header("content-length", len)128 return reply.send(Readable.fromWeb(r.body as never))129 })130131 // Notifications de changement d'état (RFC 8620 §7.3), relayées telles quelles : types et états, jamais de contenu.132 app.get("/api/jmap/:mb/eventsource", async (req: FastifyRequest, reply: FastifyReply) => {133 const { auth } = await upstreamAuth(req)134 const q = req.query as Record<string, string>135 const qs = new URLSearchParams({ types: q.types ?? "*", closeafter: q.closeafter === "state" ? "state" : "no", ping: String(Math.min(300, Math.max(10, Number(q.ping ?? 30) || 30))) })136 const ctrl = new AbortController()137 req.raw.on("close", () => ctrl.abort())138 const r = await up(`/jmap/eventsource/?${qs}`, { headers: { authorization: auth, accept: "text/event-stream" }, signal: ctrl.signal })139 refuseUpstreamAuth(r)140 if (!r.ok || !r.body) throw bad("mail_server_error", 502)141 reply.raw.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", "x-accel-buffering": "no", connection: "keep-alive" })142 reply.hijack()143 Readable.fromWeb(r.body as never).on("error", () => reply.raw.end()).pipe(reply.raw)144 })145}146