Repository Public
1import Fastify from "fastify"2import cookie from "@fastify/cookie"3import fastifyStatic from "@fastify/static"4import fs from "node:fs"5import path from "node:path"6import crypto from "node:crypto"7import { adminRoutes } from "./admin.js"8import { adminApiRoutes } from "./adminapi.js"9import { syncAddresses } from "./addresses.js"10import { authRoutes } from "./auth.js"11import { config } from "./config.js"12import { migrate, sql } from "./db.js"13import { imageRoutes } from "./images.js"14import { jmapRoutes } from "./jmap.js"15import { looksLikeApiToken } from "./keys.js"16import { reauthRoutes } from "./reauth.js"17import { bearerOf } from "./session.js"18import { templateRoutes } from "./templates.js"19import { HttpError, rateLimit } from "./util.js"20import { registerV1 } from "./v1/index.js"21import { nextRoutes } from "./next/index.js"22import { errorBody } from "./v1/registry.js"23import { startWorkers, stopWorkers } from "./workers/index.js"2425const app = Fastify({26 trustProxy: config.trustProxy,27 bodyLimit: 1024 * 1024,28 genReqId: () => `req_${crypto.randomBytes(9).toString("base64url")}`,29 // Journal des requêtes : méthode, chemin et statut seulement — jamais de corps, cookie, jeton ni chaîne de requête.30 logger: {31 level: process.env.SPMAIL_LOG_LEVEL ?? "info",32 redact: ["req.headers.authorization", "req.headers.cookie", "headers.authorization", "headers.cookie"],33 serializers: {34 req: (r) => ({ method: r.method, url: String(r.url).split("?")[0].replace(/\/download\/.*/, "/download/…"), ip: r.ip }),35 res: (r) => ({ status: r.statusCode }),36 },37 },38})3940await app.register(cookie)41// Les téléversements (pièces jointes) traversent en flux, sans être tamponnés ni interprétés.42app.addContentTypeParser("*", (_req, payload, done) => done(null, payload))4344const csp = [45 "default-src 'self'",46 "script-src 'self'",47 "style-src 'self' 'unsafe-inline'",48 "img-src 'self' blob: data:",49 "connect-src 'self'",50 "font-src 'self'",51 "frame-src 'self' blob:", // lecture des messages HTML dans un cadre isolé (sandbox, sans scripts)52 "worker-src 'self'", // service worker de la coque applicative (/sw.js) : même origine seulement53 "manifest-src 'self'", // manifeste d'application web (/manifest.webmanifest)54 "object-src 'none'",55 "base-uri 'none'",56 "form-action 'self'",57 "frame-ancestors 'none'",58].join("; ")5960app.addHook("onRequest", async (req, reply) => {61 reply.header("content-security-policy", csp)62 reply.header("x-content-type-options", "nosniff")63 reply.header("x-frame-options", "DENY")64 reply.header("referrer-policy", "no-referrer")65 reply.header("cross-origin-opener-policy", "same-origin")66 reply.header("permissions-policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()")67 reply.header("x-robots-tag", "noindex, nofollow")68 if (config.secureCookies) reply.header("strict-transport-security", "max-age=63072000")69 if (req.url.startsWith("/api/")) {70 reply.header("cache-control", "no-store")71 rateLimit(`global:${req.ip}`, 3000, 60_000)72 if (req.method !== "GET" && req.method !== "HEAD") {73 // CSRF. Navigateur : cookie SameSite=Strict + même origine + en-tête qu'un formulaire intersite ne peut pas poser.74 // Apps natives : jeton porteur (ou, avant connexion, aucune en-tête Origin : un navigateur en envoie toujours une).75 // Clés d'API : une requête « Authorization: Bearer spm_… » n'est JAMAIS traitée comme une requête à cookie (le cookie est76 // ignoré par l'authentification), donc aucune action ne peut être forgée depuis un navigateur : pas de contrôle CSRF.77 const origin = req.headers.origin78 const bearer = bearerOf(req)79 const apiKey = looksLikeApiToken(bearer)80 const native = origin === undefined && (bearer !== undefined || req.headers["x-spmail-client"] === "native")81 const web = origin === config.origin && req.headers["x-spmail"] === "1"82 if (!apiKey && !native && !web) throw new HttpError(403, "csrf", "Cross-origin request refused")83 }84 }85})8687// /api/v1 répond toujours avec l'enveloppe {error:{code,message,details?}} ; les routes historiques gardent {error,message}.88const isV1 = (url: string) => url.startsWith("/api/v1/") || url === "/api/v1"89const FASTIFY_CODES: Record<string, string> = { FST_ERR_CTP_BODY_TOO_LARGE: "payload_too_large", FST_ERR_CTP_INVALID_MEDIA_TYPE: "unsupported_media_type", FST_ERR_CTP_EMPTY_JSON_BODY: "invalid_request", FST_ERR_CTP_INVALID_JSON_BODY: "invalid_request" }90app.setErrorHandler((err: Error & { statusCode?: number; code?: string }, req, reply) => {91 const v1 = isV1(req.url)92 if (err instanceof HttpError) return reply.status(err.status).send(v1 ? errorBody(err.code, err.message, err.details) : { error: err.code, message: err.message })93 if (err.statusCode && err.statusCode < 500) {94 if (v1) return reply.status(err.statusCode).send(errorBody(FASTIFY_CODES[err.code ?? ""] ?? (err instanceof SyntaxError ? "invalid_request" : "bad_request"), err.message))95 return reply.status(err.statusCode).send({ error: err.code ?? "bad_request", message: err.message })96 }97 req.log.error({ err: { message: err.message, stack: err.stack } }, "unhandled error")98 return reply.status(500).send(v1 ? errorBody("internal", "Internal error") : { error: "internal", message: "Internal error" })99})100101app.get("/api/health/live", async () => ({ ok: true }))102app.get("/api/health/ready", async (_req, reply) => {103 try {104 await sql`select 1`105 const r = await fetch(`${config.stalwartUrl}/jmap/session`, { signal: AbortSignal.timeout(4000) }).catch(() => null)106 return { ok: true, version: config.version, mail_server: r ? "reachable" : "unreachable" } // 401 attendu sans identifiants = joignable107 } catch {108 return reply.status(503).send({ ok: false })109 }110})111112authRoutes(app)113jmapRoutes(app)114imageRoutes(app)115adminRoutes(app)116adminApiRoutes(app)117reauthRoutes(app)118templateRoutes(app)119registerV1(app)120nextRoutes(app)121122// Associated Domains : les apps natives Apple partagent les clés d'accès du web.123app.get("/.well-known/apple-app-site-association", async (_req, reply) =>124 reply.type("application/json").header("cache-control", "public, max-age=3600").send(JSON.stringify({ webcredentials: { apps: config.appleAppIds } })))125app.get("/robots.txt", async (_req, reply) => reply.type("text/plain").send("User-agent: *\nDisallow: /\n"))126127if (fs.existsSync(config.webDir)) {128 await app.register(fastifyStatic, {129 root: config.webDir,130 wildcard: false,131 setHeaders(res, p) {132 if (p.includes(`${path.sep}assets${path.sep}`)) res.header("cache-control", "public, max-age=31536000, immutable")133 else res.header("cache-control", "no-cache")134 // Service worker : toujours revalidé (une nouvelle version est vue dès la navigation suivante), portée = l'origine entière.135 // Le manifeste suit la même règle (no-cache ci-dessus) et reçoit son type MIME officiel.136 if (path.basename(p) === "sw.js") res.header("service-worker-allowed", "/")137 if (p.endsWith(".webmanifest")) res.header("content-type", "application/manifest+json; charset=utf-8")138 },139 })140}141// Chemin inconnu : JSON pour l'API (jamais la page du webmail), repli SPA pour le reste quand le webmail est servi.142const index = fs.existsSync(config.webDir) ? fs.readFileSync(path.join(config.webDir, "index.html")) : null143app.setNotFoundHandler((req, reply) => {144 if (isV1(req.url)) return reply.status(404).send(errorBody("not_found", "Unknown API route"))145 if (!index || req.url.startsWith("/api/") || req.url.startsWith("/.well-known/") || req.method !== "GET") return reply.status(404).send({ error: "not_found" })146 return reply.header("cache-control", "no-cache").type("text/html").send(index)147})148149await migrate((m) => app.log.info(m))150// Première mise en service de la table des adresses : reprise idempotente des boîtes et des alias existants (lecture seule côté Stalwart).151try {152 const [{ n }] = await sql`select count(*)::int as n from addresses`153 const [{ m }] = await sql`select count(*)::int as m from mailboxes`154 if (n === 0 && m > 0) app.log.info(await syncAddresses(), "addresses backfilled")155} catch (e) {156 app.log.error({ err: String((e as Error).message) }, "address backfill failed (run: cli addresses-sync)")157}158await app.listen({ port: config.port, host: config.host })159startWorkers(app.log)160setInterval(() => void sql`delete from challenges where expires_at < now()`.catch(() => {}), 10 * 60_000).unref()161162for (const sig of ["SIGTERM", "SIGINT"] as const)163 process.on(sig, async () => {164 await stopWorkers()165 await app.close()166 await sql.end({ timeout: 5 })167 process.exit(0)168 })169