SPB Git

Repository Public

maintenance.ts 5.1 KB 81 lines typescript

1// Expiration (adresses temporaires, approbations, fichiers, jetons), conservation (suppression datée, sur demande explicite), purge des journaux.2import { addressesOfMailbox, reconcileMailbox, type AddressRow } from "../addresses.js"3import { sql } from "../db.js"4import { jmapOk, mailboxById, roleFolder } from "../mailjmap.js"5import { cancelOutbound, type OutboundRow } from "../outbound.js"6import { emitEvent } from "../webhooks.js"78/** Adresses arrivées à expiration : suspendues en base PUIS sur le serveur de courrier (alias désactivé, réception refusée). */9export async function expire() {10  const due = (await sql`select * from addresses where expires_at is not null and expires_at <= now() and status = 'active' and not protected`) as unknown as AddressRow[]11  for (const a of due) {12    await sql`update addresses set status = 'suspended', suspended_reason = 'expired', updated_at = now() where id = ${a.id}`13    try {14      await reconcileMailbox(a.mailbox_id)15      await emitEvent({ type: "address.suspended", addressId: a.id, address: a.address, mailboxId: a.mailbox_id, data: { address_id: a.id, address: a.address, reason: "expired" } })16      await sql`insert into audit_log (action, target, meta) values ('address.expired', ${a.address}, ${sql.json({ expires_at: a.expires_at } as never)})`17    } catch {18      // serveur de courrier injoignable : on réessaiera au prochain tour (l'API refuse déjà l'adresse expirée)19      await sql`update addresses set status = 'active', suspended_reason = null where id = ${a.id}`20    }21  }22  const stale = (await sql`update send_approvals set status = 'expired', decided_at = now() where status = 'pending' and expires_at <= now() returning outbound_id`) as unknown as { outbound_id: string }[]23  for (const s of stale) {24    const [o] = await sql`select * from outbound_messages where id = ${s.outbound_id}`25    if (o) await cancelOutbound(o as unknown as OutboundRow, "approval expired after 7 days").catch(() => {})26  }27  await sql`delete from files where expires_at <= now()`28  await sql`delete from explorer_tokens where expires_at <= now()`29}3031/**32 * Conservation : supprime définitivement les messages plus vieux que la durée choisie. Rien n'est supprimé par défaut33 * (durées nulles) ; chaque passage est journalisé. `force` ignore l'intervalle de 24 h (bouton d'administration, tests).34 */35export async function retention(force: boolean): Promise<{ mailbox: string; deleted: Record<string, number> }[]> {36  if (!force) {37    const [w] = await sql`select last_run_at from worker_state where name = 'retention'`38    if (w && Date.now() - new Date(w.last_run_at).getTime() < 24 * 3600_000) return []39  }40  await sql`insert into worker_state (name, last_run_at) values ('retention', now()) on conflict (name) do update set last_run_at = now()`41  const rows = (await sql`select a.* from addresses a join mailboxes m on m.id = a.mailbox_id and m.address = a.address42    where a.retention_days is not null or a.retention_trash_days is not null or a.retention_junk_days is not null`) as unknown as AddressRow[]43  const report: { mailbox: string; deleted: Record<string, number> }[] = []44  for (const a of rows) {45    const mb = await mailboxById(a.mailbox_id)46    if (!mb) continue47    const deleted: Record<string, number> = {}48    const sweep = async (label: string, days: number | null, folder?: string | null) => {49      if (!days || folder === null) return50      const before = new Date(Date.now() - days * 86400_000).toISOString().replace(/\.\d{3}Z$/, "Z")51      for (let round = 0; round < 50; round++) {52        const [q] = await jmapOk(mb, [["Email/query", { filter: folder ? { operator: "AND", conditions: [{ inMailbox: folder }, { before }] } : { before }, limit: 200 }]])53        const ids = q.ids as string[]54        if (!ids.length) break55        const [d] = await jmapOk(mb, [["Email/set", { destroy: ids }]])56        deleted[label] = (deleted[label] ?? 0) + ((d.destroyed as string[] | undefined)?.length ?? 0)57        if (ids.length < 200) break58      }59    }60    try {61      await sweep("trash", a.retention_trash_days, await roleFolder(mb, "trash"))62      await sweep("junk", a.retention_junk_days, await roleFolder(mb, "junk"))63      await sweep("all", a.retention_days)64      await sql`insert into audit_log (action, target, meta) values ('retention.run', ${mb.address}, ${sql.json({ deleted, retention_days: a.retention_days, trash_days: a.retention_trash_days, junk_days: a.retention_junk_days } as never)})`65      report.push({ mailbox: mb.address, deleted })66    } catch (e) {67      await sql`insert into audit_log (action, target, meta) values ('retention.error', ${mb.address}, ${sql.json({ error: String((e as Error).message).slice(0, 200) } as never)})`68    }69  }70  return report71}7273export async function prune() {74  await sql`delete from idempotency_keys where created_at < now() - interval '24 hours'`75  await sql`delete from api_usage where at < now() - interval '90 days'`76  await sql`delete from webhook_events where occurred_at < now() - interval '30 days'`77  await sql`delete from watched_messages where received_at < now() - interval '30 days'`78  await sql`delete from challenges where expires_at < now()`79}80void addressesOfMailbox81
Files main
Menu

Theme