SPB Git

Repository Public

mailjmap.ts 7.6 KB 121 lines typescript

1// Client JMAP « côté serveur » : parle à Stalwart au nom d'une boîte, avec son secret scellé. Sert à /api/v1 et aux travailleurs.2import { Readable } from "node:stream"3import { config } from "./config.js"4import { sql } from "./db.js"5import { basic, unseal } from "./stalwart.js"6import { bad, HttpError } from "./util.js"78export type Mbx = { id: string; user_id: string; address: string; display_name: string; stalwart_id: string; secret_enc: Buffer }9export type JCall = [string, Record<string, any>, string]10export const USING = ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:mail", "urn:ietf:params:jmap:submission", "urn:ietf:params:jmap:sieve", "urn:ietf:params:jmap:vacationresponse", "urn:ietf:params:jmap:blob"]1112const authOf = (mb: Mbx) => basic(mb.address, unseal(Buffer.from(mb.secret_enc)))1314export async function mailboxById(id: string): Promise<Mbx | null> {15  const [row] = await sql`select id, user_id, address, display_name, stalwart_id, secret_enc from mailboxes where id = ${id}`16  return (row as Mbx | undefined) ?? null17}18export async function allMailboxes(): Promise<Mbx[]> {19  return (await sql`select id, user_id, address, display_name, stalwart_id, secret_enc from mailboxes order by position, created_at`) as unknown as Mbx[]20}2122async function up(path: string, init: RequestInit & { duplex?: "half" }) {23  try {24    return await fetch(`${config.stalwartUrl}${path}`, init)25  } catch {26    throw bad("mail_server_unavailable", 502, "The mail server is unreachable")27  }28}2930export const CONCURRENCY_RETRIES = 531/** Refus de Stalwart pour trop de requêtes simultanées sur le compte (pur). */32export const isConcurrencyLimit = (status: number, problem: { type?: string; limit?: string } | null | undefined) =>33  status === 400 && problem?.type === "urn:ietf:params:jmap:error:limit" && problem.limit === "maxConcurrentRequests"34/** Recul avant de rejouer : 80, 160, 320… ms, plus un aléa pour que des requêtes parties ensemble ne reviennent pas ensemble (pur à l'aléa près). */35export const retryDelayMs = (attempt: number, random = Math.random()) => Math.round(80 * 2 ** attempt + random * 120)3637/** Requête JMAP brute : rend les réponses dans l'ordre. `accountId` est injecté dans chaque appel. */38export async function jmap(mb: Mbx, calls: [string, Record<string, any>, string?][], timeoutMs = 60_000): Promise<JCall[]> {39  const methodCalls = calls.map(([name, args, tag], i) => [name, { accountId: mb.stalwart_id, ...args }, tag ?? String(i)])40  const body = JSON.stringify({ using: USING, methodCalls })41  const deadline = Date.now() + timeoutMs42  for (let attempt = 0; ; attempt++) {43    const r = await up("/jmap/", {44      method: "POST", headers: { authorization: authOf(mb), "content-type": "application/json" }, body, signal: AbortSignal.timeout(Math.max(1000, deadline - Date.now())),45    })46    if (r.ok) return ((await r.json()) as { methodResponses: JCall[] }).methodResponses47    // Stalwart borne les requêtes simultanées d'un même compte (400 « limit: maxConcurrentRequests ») : rien n'a été exécuté, la requête est48    // rejouée après un court recul. Sans cela, un écran qui lance plusieurs lectures en parallèle perdait des blocs au hasard.49    const problem = r.status === 400 ? ((await r.json().catch(() => null)) as { type?: string; limit?: string } | null) : null50    if (isConcurrencyLimit(r.status, problem) && attempt < CONCURRENCY_RETRIES && Date.now() + 1000 < deadline) {51      await new Promise((res) => setTimeout(res, retryDelayMs(attempt)))52      continue53    }54    throw bad(r.status === 401 ? "mail_server_auth" : "mail_server_error", 502, `mail server answered ${r.status}${problem?.limit ? ` (${problem.limit})` : ""}`)55  }56}5758export class JmapMethodError extends HttpError {59  constructor(public type: string, public description: string) {60    super(502, "mail_server_error", `${type}${description ? `: ${description}` : ""}`)61  }62}63/** Comme `jmap`, mais toute réponse `error` devient une exception. */64export async function jmapOk(mb: Mbx, calls: [string, Record<string, any>, string?][], timeoutMs?: number): Promise<Record<string, any>[]> {65  const res = await jmap(mb, calls, timeoutMs)66  return res.map(([name, body]) => {67    if (name === "error") throw new JmapMethodError(String(body.type ?? "error"), String(body.description ?? ""))68    return body69  })70}7172export type Folder = { id: string; name: string; role: string | null; parentId: string | null; totalEmails: number; unreadEmails: number }73const folderCache = new Map<string, { at: number; list: Folder[] }>()74/** Dossiers d'une boîte (cache 20 s). `need` : identifiants qui doivent y figurer — s'il en manque un (dossier créé entre-temps), la liste est relue. */75export async function folders(mb: Mbx, fresh = false, need?: Iterable<string>): Promise<Folder[]> {76  const c = folderCache.get(mb.id)77  if (!fresh && c && Date.now() - c.at < 20_000) {78    let ok = true79    if (need) for (const id of need) if (!c.list.some((f) => f.id === id)) { ok = false; break }80    if (ok) return c.list81  }82  const [r] = await jmapOk(mb, [["Mailbox/get", { ids: null, properties: ["name", "role", "parentId", "totalEmails", "unreadEmails"] }]])83  const list = r.list as Folder[]84  folderCache.set(mb.id, { at: Date.now(), list })85  return list86}87export const invalidateFolders = (mailboxId: string) => folderCache.delete(mailboxId)8889const ROLE_NAMES: Record<string, string> = { archive: "Archive", inbox: "Inbox", drafts: "Drafts", sent: "Sent Items", trash: "Deleted Items", junk: "Junk Mail" }90/** Identifiant du dossier portant ce rôle ; créé s'il manque et que `create` est vrai (ex. Archive). */91export async function roleFolder(mb: Mbx, role: string, create = false): Promise<string | null> {92  let f = (await folders(mb)).find((x) => x.role === role) ?? (await folders(mb, true)).find((x) => x.role === role)93  if (f || !create) return f?.id ?? null94  const [r] = await jmapOk(mb, [["Mailbox/set", { create: { n: { name: ROLE_NAMES[role] ?? role, role, parentId: null } } }]])95  invalidateFolders(mb.id)96  const id = r.created?.n?.id as string | undefined97  if (!id) throw bad("mail_server_error", 502, JSON.stringify(r.notCreated ?? {}).slice(0, 200))98  return id99}100101/** Téléverse un blob (flux brut, jamais interprété). */102export async function uploadBlob(mb: Mbx, body: Readable | Buffer | string, type: string): Promise<{ blobId: string; size: number; type: string }> {103  const stream = body instanceof Readable104  const r = await up(`/jmap/upload/${encodeURIComponent(mb.stalwart_id)}/`, {105    method: "POST", headers: { authorization: authOf(mb), "content-type": type || "application/octet-stream" },106    body: (stream ? (Readable.toWeb(body) as never) : body) as never, ...(stream ? { duplex: "half" as const } : {}), signal: AbortSignal.timeout(300_000),107  })108  if (!r.ok) throw bad(r.status === 413 ? "file_too_large" : "mail_server_error", r.status === 413 ? 413 : 502, `upload ${r.status}`)109  return (await r.json()) as { blobId: string; size: number; type: string }110}111export async function downloadBlob(mb: Mbx, blobId: string, name = "blob", type = "application/octet-stream"): Promise<Response> {112  const r = await up(`/jmap/download/${encodeURIComponent(mb.stalwart_id)}/${encodeURIComponent(blobId)}/${encodeURIComponent(name)}?accept=${encodeURIComponent(type)}`, {113    headers: { authorization: authOf(mb) }, signal: AbortSignal.timeout(300_000),114  })115  if (!r.ok || !r.body) throw bad(r.status === 404 ? "not_found" : "mail_server_error", r.status === 404 ? 404 : 502)116  return r117}118export async function blobText(mb: Mbx, blobId: string): Promise<string> {119  return (await downloadBlob(mb, blobId, "blob.txt", "text/plain")).text()120}121
Files main
Menu

Theme