SPB Git

Repository Public

rules.ts 27.5 KB 391 lines typescript

1// SP Mail Next — moteur de règles après livraison (D-N9) : complète Sieve, ne le remplace pas. Le crochet du veilleur met les réceptions2// en file ; un travailleur évalue les conditions (fonction pure) et exécute les actions par JMAP. Une exécution par (règle, boîte, message),3// consignée avec ce qui a été fait et les erreurs. Une règle ne peut JAMAIS envoyer de courrier : « draft_reply » ne crée qu'un brouillon.4import type { FastifyInstance } from "fastify"5import { z } from "zod"6import { config } from "../config.js"7import { sql } from "../db.js"8import { folders, jmapOk, mailboxById, roleFolder, type Mbx } from "../mailjmap.js"9import { seal, unseal } from "../stalwart.js"10import { audit, bad, parse, zUuid } from "../util.js"11import { deliveredTo } from "../v1/context.js"12import { msgId, threadId } from "../v1/ids.js"13import { emitEvent } from "../webhooks.js"14import { aiEnabled, extractFields, headerFacts, loadEmails, ownAddresses, suggestReplies, triageEmails } from "./ai.js"15import { CATEGORIES, TONES, zExtractSchema } from "./ai-prompts.js"16import { nextUser, userMailbox, userMailboxes } from "./common.js"17import { onInbound } from "./hooks.js"18import type { NextWorker } from "./index.js"19import { beat } from "./ops.js"2021// ------------------------------------------------------------------ schéma d'une règle22const zName = z.string().regex(/^[a-z0-9][a-z0-9_.-]{0,63}$/)23export const zCondition = z.object({24  field: z.enum(["from", "to", "subject", "list", "has_attachment", "is_newsletter", "ai_category", "size"]),25  op: z.enum(["contains", "equals", "matches_domain", "is", "gt"]),26  value: z.union([z.string().trim().min(1).max(300), z.number().min(0), z.boolean()]),27}).strict().superRefine((c, ctx) => {28  const err = (message: string) => ctx.addIssue({ code: "custom", message })29  const ops: Record<string, string[]> = { from: ["contains", "equals", "matches_domain"], to: ["contains", "equals", "matches_domain"], subject: ["contains", "equals"], list: ["contains", "equals"], has_attachment: ["is"], is_newsletter: ["is"], ai_category: ["is", "equals"], size: ["gt"] }30  if (!ops[c.field].includes(c.op)) return err(`operator "${c.op}" does not apply to "${c.field}" (allowed: ${ops[c.field].join(", ")})`)31  const want = c.field === "size" ? "number" : c.field === "has_attachment" || c.field === "is_newsletter" ? "boolean" : "string"32  if (typeof c.value !== want) return err(`"${c.field}" expects a ${want} value`)33  if (c.field === "ai_category" && !(CATEGORIES as readonly string[]).includes(String(c.value))) return err(`unknown category (allowed: ${CATEGORIES.join(", ")})`)34})35export type Condition = z.infer<typeof zCondition>36export const UNTIL_RULE = /^(later_today|tomorrow|weekend|next_week|[1-9]\d{0,2}h|[1-9]\d?d)$/37export const zAction = z.discriminatedUnion("type", [38  z.object({ type: z.literal("label"), label_id: zUuid }).strict(),39  z.object({ type: z.literal("star") }).strict(),40  z.object({ type: z.literal("mark_read") }).strict(),41  z.object({ type: z.literal("pin") }).strict(),42  z.object({ type: z.literal("snooze"), until_rule: z.string().regex(UNTIL_RULE) }).strict(),43  z.object({ type: z.literal("remind"), after_hours: z.number().positive().max(24 * 365) }).strict(),44  z.object({ type: z.literal("event"), name: zName }).strict(),45  z.object({ type: z.literal("notify_app"), app: zName }).strict(),46  z.object({ type: z.literal("draft_reply"), snippet_id: zUuid.optional(), ai_tone: z.enum(TONES).optional() }).strict().refine((a) => !!a.snippet_id !== !!a.ai_tone, "draft_reply takes exactly one of snippet_id or ai_tone"),47  z.object({ type: z.literal("extract"), schema: zExtractSchema }).strict(),48])49export type Action = z.infer<typeof zAction>50const zRule = z.object({51  name: z.string().trim().min(1).max(80), enabled: z.boolean().default(true), position: z.number().int().min(0).max(10_000).optional(), mailbox_ids: z.array(zUuid).min(1).max(50).nullable().default(null),52  match: z.enum(["all", "any"]).default("all"), conditions: z.array(zCondition).max(20).default([]), actions: z.array(zAction).min(1).max(10), stop: z.boolean().default(false),53}).strict()54type RuleRow = { id: string; user_id: string; name: string; enabled: boolean; position: number; mailbox_ids: string[] | null; match: "all" | "any"; conditions: Condition[]; actions: Action[]; stop: boolean; created_at: Date; updated_at: Date; enabled_at: Date }55const present = (r: RuleRow) => ({ id: r.id, name: r.name, enabled: r.enabled, position: r.position, mailbox_ids: r.mailbox_ids, match: r.match, conditions: r.conditions, actions: r.actions, stop: r.stop, created_at: r.created_at, updated_at: r.updated_at, enabled_at: r.enabled_at })5657// ------------------------------------------------------------------ évaluation (pure)58export type RuleFacts = {59  /** « nom <adresse> » en minuscules, et les adresses seules. */60  from: { text: string; email: string }[]; to: { text: string; email: string }[]61  subject: string; list: string; has_attachment: boolean; is_newsletter: boolean; size: number; ai_category?: string | null62}63const norm = (s: unknown) => String(s ?? "").toLowerCase().trim()64export function matchCondition(c: Condition, f: RuleFacts): boolean {65  const v = norm(c.value)66  switch (c.field) {67    case "from": case "to": {68      const list = f[c.field]69      if (c.op === "equals") return list.some((a) => a.email === v)70      if (c.op === "matches_domain") { const d = v.replace(/^@/, ""); return !!d && list.some((a) => a.email.endsWith(`@${d}`) || a.email.endsWith(`.${d}`)) }71      return list.some((a) => a.text.includes(v))72    }73    case "subject": return c.op === "equals" ? norm(f.subject) === v : norm(f.subject).includes(v)74    case "list": return c.op === "equals" ? norm(f.list).replace(/^.*<|>.*$/g, "") === v.replace(/^<|>$/g, "") : norm(f.list).includes(v)75    case "has_attachment": return f.has_attachment === c.value76    case "is_newsletter": return f.is_newsletter === c.value77    case "ai_category": return !!f.ai_category && f.ai_category === v78    case "size": return f.size > Number(c.value)79  }80}81/** Une règle sans condition s'applique à tout message reçu. `all` : toutes les conditions ; `any` : au moins une. */82export function matchRule(rule: { match: "all" | "any"; conditions: Condition[] }, f: RuleFacts): { matched: boolean; results: boolean[] } {83  const results = rule.conditions.map((c) => matchCondition(c, f))84  return { matched: !results.length || (rule.match === "all" ? results.every(Boolean) : results.some(Boolean)), results }85}86type Addr = { name?: string | null; email?: string | null }87const addrs = (l: Addr[] | null | undefined) => (l ?? []).map((a) => ({ email: norm(a.email), text: `${norm(a.name)} <${norm(a.email)}>` }))88export function factsOf(e: Record<string, any>): RuleFacts {89  const h = headerFacts(e as never)90  return { from: addrs(e.from), to: [...addrs(e.to), ...addrs(e.cc)], subject: String(e.subject ?? ""), list: h.list, has_attachment: !!e.hasAttachment, is_newsletter: h.is_newsletter, size: Number(e.size ?? 0) }91}9293/** Heure locale (fuseau `tz`) → instant UTC, pour « demain 8 h ». */94function localTime(y: number, m: number, d: number, hour: number, tz: string): Date {95  const guess = Date.UTC(y, m - 1, d, hour)96  const p = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric" }).formatToParts(new Date(guess)).map((x) => [x.type, Number(x.value)]))97  return new Date(guess - (Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute) - guess))98}99/** Échéance d'une mise en veille : `3h`, `2d`, `later_today` (+3 h), `tomorrow` (8 h), `weekend` (samedi 8 h), `next_week` (lundi 8 h), heure locale. */100export function resolveUntil(rule: string, now: Date, tz = "UTC"): Date {101  const m = /^(\d+)([hd])$/.exec(rule)102  if (m) return new Date(now.getTime() + Number(m[1]) * (m[2] === "h" ? 3600_000 : 86400_000))103  if (rule === "later_today") return new Date(now.getTime() + 3 * 3600_000)104  const p = Object.fromEntries(new Intl.DateTimeFormat("en-US", { timeZone: tz, year: "numeric", month: "numeric", day: "numeric", weekday: "short" }).formatToParts(now).map((x) => [x.type, x.value]))105  const dow = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(p.weekday)106  const add = rule === "tomorrow" ? 1 : rule === "weekend" ? ((6 - dow + 7) % 7 || 7) : rule === "next_week" ? ((1 - dow + 7) % 7 || 7) : NaN107  if (Number.isNaN(add)) throw new Error(`unknown until_rule ${rule}`)108  const day = new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) + add))109  return localTime(day.getUTCFullYear(), day.getUTCMonth() + 1, day.getUTCDate(), 8, tz)110}111112// ------------------------------------------------------------------ modules voisins (présents ou non) et tables d'autres migrations113type SnoozeApi = {114  snoozeMessages?: (userId: string, mailboxId: string, emailIds: string[], until: Date) => Promise<{ id: string; email_id: string }[]>115  createReminder?: (userId: string, input: { mailboxId: string; emailId: string; dueAt: Date; onlyIfNoReply?: boolean; note?: string }) => Promise<{ id: string }>116}117const snoozeApi = async (): Promise<SnoozeApi> => { try { return (await import("./snooze.js")) as unknown as SnoozeApi } catch { return {} } }118const hasTable = async (name: string) => !!(await sql`select to_regclass(${`public.${name}`}) as t`)[0].t119120// ------------------------------------------------------------------ exécution des actions121export type ActionResult = { type: Action["type"]; status: "ok" | "skipped" | "error"; detail?: string; [k: string]: unknown }122type Ctx = { userId: string; mb: Mbx; e: Record<string, any> & { id: string }; rule: RuleRow; address: string }123124async function setKeyword(mb: Mbx, emailId: string, keyword: string) {125  const [r] = await jmapOk(mb, [["Email/set", { update: { [emailId]: { [`keywords/${keyword}`]: true } } }]])126  if (!r.updated || !(emailId in r.updated)) throw new Error(`keyword not set: ${JSON.stringify(r.notUpdated?.[emailId]?.type ?? "unknown")}`)127}128129/** Brouillon de réponse dans le dossier Brouillons (Email/set create). Aucune soumission : seul le propriétaire peut l'envoyer, après relecture. */130async function createReplyDraft(c: Ctx, body: { text: string; html?: string }): Promise<string> {131  const drafts = await roleFolder(c.mb, "drafts", true)132  const subject = String(c.e.subject ?? "")133  const bodyValues: Record<string, { value: string }> = { t: { value: body.text } }134  if (body.html) bodyValues.h = { value: body.html }135  const [r] = await jmapOk(c.mb, [["Email/set", { create: { d: {136    mailboxIds: { [drafts!]: true }, keywords: { $draft: true, $seen: true }, from: [{ name: c.mb.display_name || null, email: c.address }],137    to: (c.e.replyTo?.length ? c.e.replyTo : c.e.from) ?? [], subject: /^\s*re\s*:/i.test(subject) ? subject : `Re: ${subject}`,138    inReplyTo: c.e.messageId ?? null, references: [...(c.e.references ?? []), ...(c.e.messageId ?? [])].slice(-20),139    bodyValues, textBody: [{ partId: "t", type: "text/plain" }], ...(body.html ? { htmlBody: [{ partId: "h", type: "text/html" }] } : {}),140  } } }]])141  const id = r.created?.d?.id as string | undefined142  if (!id) throw new Error(`draft not created: ${JSON.stringify(r.notCreated?.d?.type ?? "unknown")}`)143  return id144}145146async function execAction(c: Ctx, a: Action): Promise<ActionResult> {147  const skipped = (detail: string): ActionResult => ({ type: a.type, status: "skipped", detail })148  switch (a.type) {149    case "label": {150      if (!(await hasTable("labels"))) return skipped("labels_unavailable")151      const [l] = await sql`select keyword from labels where id = ${a.label_id} and user_id = ${c.userId}`152      if (!l) return skipped("label_not_found")153      await setKeyword(c.mb, c.e.id, l.keyword)154      return { type: a.type, status: "ok", keyword: l.keyword }155    }156    case "star": await setKeyword(c.mb, c.e.id, "$flagged"); return { type: a.type, status: "ok" }157    case "mark_read": await setKeyword(c.mb, c.e.id, "$seen"); return { type: a.type, status: "ok" }158    case "pin": await setKeyword(c.mb, c.e.id, "$pinned"); return { type: a.type, status: "ok" }159    case "snooze": {160      const fn = (await snoozeApi()).snoozeMessages161      if (!fn) return skipped("snooze_unavailable")162      const until = resolveUntil(a.until_rule, new Date(), config.defaultTz)163      const rows = await fn(c.userId, c.mb.id, [c.e.id], until)164      return { type: a.type, status: "ok", until: until.toISOString(), snooze_id: rows[0]?.id ?? null }165    }166    case "remind": {167      const fn = (await snoozeApi()).createReminder168      if (!fn) return skipped("reminders_unavailable")169      const dueAt = new Date(Date.now() + a.after_hours * 3600_000)170      const r = await fn(c.userId, { mailboxId: c.mb.id, emailId: c.e.id, dueAt, onlyIfNoReply: false, note: `Rule: ${c.rule.name}`.slice(0, 200) })171      return { type: a.type, status: "ok", due_at: dueAt.toISOString(), reminder_id: r.id }172    }173    case "event": case "notify_app": {174      // Événement interne `rule.matched` : identifiants et adresses seulement ; sujet et aperçu ne partent qu'aux webhooks « include_content ».175      const id = await emitEvent({176        type: "rule.matched", mailboxId: c.mb.id, address: c.address, content: { subject: c.e.subject ?? "", preview: c.e.preview ?? "" },177        data: {178          rule_id: c.rule.id, rule_name: c.rule.name, ...(a.type === "event" ? { name: a.name } : { name: "notify_app", app: a.app }), message_id: msgId(c.mb.id, c.e.id), thread_id: threadId(c.mb.id, c.e.threadId),179          address: c.address, from: (c.e.from ?? []).map((x: Addr) => x.email), received_at: c.e.receivedAt,180        },181      })182      return { type: a.type, status: "ok", event_id: id }183    }184    case "draft_reply": {185      const h = headerFacts(c.e as never)186      const own = await ownAddresses(c.mb)187      if (h.automated || h.is_newsletter || (c.e.from ?? []).some((x: Addr) => own.has(norm(x.email)))) return skipped("not_replyable")188      if (a.snippet_id) {189        if (!(await hasTable("snippets"))) return skipped("snippets_unavailable")190        const [s] = await sql`select html, text from snippets where id = ${a.snippet_id} and user_id = ${c.userId}`191        if (!s) return skipped("snippet_not_found")192        return { type: a.type, status: "ok", source: "snippet", draft_id: await createReplyDraft(c, { text: s.text || "", html: s.html || undefined }) }193      }194      if (!(await aiEnabled(c.userId, "reply"))) return skipped("ai_disabled")195      const r = await suggestReplies(c.userId, c.mb, c.e.id, a.ai_tone!)196      return { type: a.type, status: "ok", source: "ai", provider: r.provider, model: r.model, draft_id: await createReplyDraft(c, { text: r.suggestions[0].text }) }197    }198    case "extract": {199      if (!(await aiEnabled(c.userId, "triage"))) return skipped("ai_disabled")200      const r = await extractFields(c.userId, c.mb, c.e.id, a.schema)201      // Le résultat dérive du contenu du message : il est scellé dans le journal d'exécution.202      return { type: a.type, status: "ok", provider: r.provider, model: r.model, result_enc: seal(JSON.stringify(r.data)).toString("base64") }203    }204  }205}206207// ------------------------------------------------------------------ travailleur208type Job = { id: number; user_id: string; mailbox_id: string; email_id: string; attempts: number }209const inScope = (r: RuleRow, mailboxId: string) => !r.mailbox_ids || r.mailbox_ids.includes(mailboxId)210/** Écart d'horloge toléré entre le serveur de courrier (date de réception) et SP Mail (date d'activation de la règle). */211export const RULE_CLOCK_SKEW_MS = 2000212/**213 * Une règle ne s'applique qu'au courrier reçu APRÈS son activation (pure). Le travail est mis en file pour chaque réception puis évalué214 * plus tard : sans cette garde, une règle créée entre-temps s'appliquait à un message arrivé avant elle.215 */216export function appliesTo(rule: { enabled_at: Date | string }, receivedAt: string | null | undefined): boolean {217  const t = Date.parse(String(receivedAt ?? ""))218  return !Number.isNaN(t) && t >= new Date(rule.enabled_at).getTime() - RULE_CLOCK_SKEW_MS219}220const usesAi = (rules: { conditions: Condition[] }[]) => rules.some((r) => r.conditions.some((c) => c.field === "ai_category"))221async function aiCategory(userId: string, mb: Mbx, emailId: string): Promise<string | null> {222  if (!(await aiEnabled(userId, "triage"))) return null223  try { return (await triageEmails(userId, mb, [emailId])).data[0]?.category ?? null } catch { return null }224}225226async function runJob(job: Job) {227  const mb = await mailboxById(job.mailbox_id)228  if (!mb) return229  const rules = ((await sql`select * from rules where user_id = ${mb.user_id} and enabled order by position, created_at`) as unknown as RuleRow[]).filter((r) => inScope(r, mb.id))230  if (!rules.length) return231  const [e] = await loadEmails(mb, [job.email_id])232  if (!e || e.keywords?.$draft) return // message disparu entre-temps : rien à faire233  if (!rules.some((r) => appliesTo(r, e.receivedAt))) return // reçu avant l'activation de toutes les règles234  const fl = await folders(mb, false, Object.keys(e.mailboxIds ?? {}))235  const roles = Object.keys(e.mailboxIds ?? {}).map((id) => fl.find((f) => f.id === id)?.role ?? null)236  if (roles.length && roles.every((r) => r === "junk" || r === "trash")) return // indésirables et corbeille : aucune règle237  const facts = factsOf(e)238  if (usesAi(rules)) facts.ai_category = await aiCategory(mb.user_id, mb, e.id)239  const address = deliveredTo(e).find((a) => a === mb.address) ?? (await sql`select address from addresses where mailbox_id = ${mb.id} and can_send and address = any(${deliveredTo(e)}) limit 1`)[0]?.address ?? mb.address240  for (const rule of rules) {241    if (!appliesTo(rule, e.receivedAt) || !matchRule(rule, facts).matched) continue242    // Idempotence : la ligne d'exécution est posée AVANT les actions. Si elle existe déjà (reprise après arrêt), les actions ne sont pas rejouées.243    const [run] = await sql`insert into rule_runs (rule_id, user_id, mailbox_id, email_id, thread_id) values (${rule.id}, ${mb.user_id}, ${mb.id}, ${e.id}, ${(e.threadId as string | undefined) ?? null}) on conflict (rule_id, mailbox_id, email_id) do nothing returning id`244    if (!run) {245      await sql`update rule_runs set status = 'interrupted', finished_at = now() where rule_id = ${rule.id} and mailbox_id = ${mb.id} and email_id = ${e.id} and status = 'running' and at < now() - interval '2 minutes'`246      if (rule.stop) break247      continue248    }249    const results: ActionResult[] = []250    for (const a of rule.actions) {251      try { results.push(await execAction({ userId: mb.user_id, mb, e, rule, address }, a)) } catch (err) {252        results.push({ type: a.type, status: "error", detail: String((err as { code?: string }).code ?? (err as Error).message ?? err).slice(0, 200) })253      }254    }255    const errors = results.filter((r) => r.status === "error").length256    const status = errors === 0 ? "ok" : errors === results.length ? "error" : "partial"257    await sql`update rule_runs set status = ${status}, actions = ${sql.json(results as never)}, error = ${errors ? results.filter((r) => r.status === "error").map((r) => `${r.type}: ${r.detail}`).join("; ").slice(0, 500) : null}, finished_at = now() where id = ${run.id}`258    if (rule.stop) break259  }260}261262async function processJobs() {263  const jobs = (await sql`update rule_jobs set locked_until = now() + interval '2 minutes'264    where id in (select id from rule_jobs where next_attempt_at <= now() and (locked_until is null or locked_until < now()) order by id limit 10 for update skip locked)265    returning id, user_id, mailbox_id, email_id, attempts`) as unknown as Job[]266  for (const job of jobs) {267    try {268      await runJob(job)269      await sql`delete from rule_jobs where id = ${job.id}`270    } catch (e) {271      // Serveur de courrier injoignable avant toute exécution : nouvelle tentative avec recul, abandon consigné après 6 essais.272      const msg = String((e as Error).message ?? e).slice(0, 200)273      if (job.attempts >= 5) {274        await sql`delete from rule_jobs where id = ${job.id}`275        await sql`insert into audit_log (actor, action, target, meta) values (${job.user_id}, 'rule.job_abandoned', ${job.mailbox_id}, ${sql.json({ email_id: job.email_id, error: msg } as never)})`276      } else await sql`update rule_jobs set attempts = attempts + 1, locked_until = null, last_error = ${msg}, next_attempt_at = now() + make_interval(secs => ${Math.min(600, 5 * 2 ** job.attempts)}) where id = ${job.id}`277    }278  }279}280281// ------------------------------------------------------------------ routes282async function ruleOf(userId: string, id: string): Promise<RuleRow> {283  if (!zUuid.safeParse(id).success) throw bad("not_found", 404)284  const [r] = await sql`select * from rules where id = ${id} and user_id = ${userId}`285  if (!r) throw bad("not_found", 404)286  return r as RuleRow287}288/** Références d'une règle : boîtes de l'utilisateur, étiquettes et extraits qui lui appartiennent. */289async function checkRefs(userId: string, r: { mailbox_ids?: string[] | null; actions?: Action[] }) {290  if (r.mailbox_ids) {291    const owned = new Set((await userMailboxes(userId)).filter((m) => m.owner).map((m) => m.id))292    if (r.mailbox_ids.some((id) => !owned.has(id))) throw bad("unknown_mailbox", 400, "mailbox_ids: a rule only applies to mailboxes you own")293  }294  for (const a of r.actions ?? []) {295    if (a.type === "label" && (!(await hasTable("labels")) || !(await sql`select 1 from labels where id = ${a.label_id} and user_id = ${userId}`).length)) throw bad("unknown_label", 400, "label_id: unknown label")296    if (a.type === "draft_reply" && a.snippet_id && (!(await hasTable("snippets")) || !(await sql`select 1 from snippets where id = ${a.snippet_id} and user_id = ${userId}`).length)) throw bad("unknown_snippet", 400, "snippet_id: unknown snippet")297  }298}299const describe = (a: Action): string => ({300  label: "add the label", star: "flag the message", mark_read: "mark the message as read", pin: "pin the message", snooze: "snooze the message", remind: "create a follow-up reminder",301  event: "emit a rule.matched event", notify_app: "emit a rule.matched event for the application", draft_reply: "create a reply DRAFT (never sent)", extract: "extract fields with AI into the run record",302}[a.type])303304export function ruleRoutes(app: FastifyInstance) {305  // Crochet du veilleur : une écriture en base par message reçu, seulement si le propriétaire de la boîte a au moins une règle active.306  onInbound("rules", async (tx, batch) => {307    if (!batch.received.length) return308    const [on] = await tx`select 1 from rules where user_id = ${batch.mb.user_id} and enabled limit 1`309    if (!on) return310    for (const r of batch.received) await tx`insert into rule_jobs (user_id, mailbox_id, email_id) values (${batch.mb.user_id}, ${batch.mb.id}, ${r.email.id}) on conflict (mailbox_id, email_id) do nothing`311  })312313  app.get("/api/next/rules", async (req) => {314    const a = await nextUser(req)315    return { data: ((await sql`select * from rules where user_id = ${a.userId} order by position, created_at`) as unknown as RuleRow[]).map(present) }316  })317318  app.post("/api/next/rules", async (req, reply) => {319    const a = await nextUser(req)320    const b = parse(zRule, req.body)321    await checkRefs(a.userId, b)322    const [{ n, next }] = await sql`select count(*)::int as n, coalesce(max(position), -1) + 1 as next from rules where user_id = ${a.userId}`323    if (n >= 100) throw bad("too_many_rules", 409, "A user can have at most 100 rules")324    const [row] = await sql`insert into rules (user_id, name, enabled, position, mailbox_ids, match, conditions, actions, stop)325      values (${a.userId}, ${b.name}, ${b.enabled}, ${b.position ?? next}, ${b.mailbox_ids}, ${b.match}, ${sql.json(b.conditions as never)}, ${sql.json(b.actions as never)}, ${b.stop}) returning *`326    await audit(req, a.userId, "rule.create", row.id, { name: b.name, actions: b.actions.map((x) => x.type) })327    return reply.status(201).send(present(row as RuleRow))328  })329330  app.patch("/api/next/rules/:id", async (req) => {331    const a = await nextUser(req)332    const cur = await ruleOf(a.userId, (req.params as { id: string }).id)333    const b = parse(zRule.partial().strict(), req.body)334    // zod garde les valeurs par défaut en mode partiel : seules les clés réellement envoyées sont appliquées.335    const raw = (req.body ?? {}) as Record<string, unknown>336    const cols: Record<string, unknown> = { updated_at: new Date() }337    for (const k of ["name", "enabled", "position", "mailbox_ids", "match", "stop"] as const) if (k in raw && b[k] !== undefined) cols[k] = b[k]338    if ("conditions" in raw && b.conditions) cols.conditions = sql.json(b.conditions as never)339    if ("actions" in raw && b.actions) cols.actions = sql.json(b.actions as never)340    // Réactivation : la règle repart de maintenant, elle ne rattrape pas le courrier reçu pendant qu'elle était coupée.341    if (cols.enabled === true && !cur.enabled) cols.enabled_at = new Date()342    await checkRefs(a.userId, { mailbox_ids: "mailbox_ids" in raw ? b.mailbox_ids : undefined, actions: "actions" in raw ? b.actions : undefined })343    const [row] = await sql`update rules set ${sql(cols as never)} where id = ${cur.id} returning *`344    await audit(req, a.userId, "rule.update", cur.id, { fields: Object.keys(cols).filter((k) => k !== "updated_at") })345    return present(row as RuleRow)346  })347348  app.delete("/api/next/rules/:id", async (req) => {349    const a = await nextUser(req)350    const cur = await ruleOf(a.userId, (req.params as { id: string }).id)351    await sql`delete from rules where id = ${cur.id}`352    await audit(req, a.userId, "rule.delete", cur.id, { name: cur.name })353    return { ok: true }354  })355356  // Journal d'exécution d'une règle : actions faites, ignorées, en erreur. Les extractions scellées sont rendues en clair à leur propriétaire.357  app.get("/api/next/rules/:id/runs", async (req) => {358    const a = await nextUser(req)359    const cur = await ruleOf(a.userId, (req.params as { id: string }).id)360    const { limit } = parse(z.object({ limit: z.coerce.number().int().min(1).max(200).default(50) }), req.query)361    const rows = await sql`select id, mailbox_id, email_id, thread_id, status, actions, error, at, finished_at from rule_runs where rule_id = ${cur.id} order by id desc limit ${limit}`362    return { data: rows.map((r) => ({ ...r, actions: (r.actions as ActionResult[]).map(({ result_enc, ...x }) => {363      if (typeof result_enc !== "string") return x364      try { return { ...x, result: JSON.parse(unseal(Buffer.from(result_enc, "base64"))) } } catch { return x }365    }) })) }366  })367368  // Essai à blanc : dit si la règle s'appliquerait à ce message et ce qu'elle ferait. Aucune action n'est exécutée, rien n'est consigné.369  app.post("/api/next/rules/test", async (req) => {370    const a = await nextUser(req, "rules-test", 60)371    const b = parse(z.object({ rule: zRule.partial({ name: true }), mailbox_id: zUuid, email_id: z.string().min(1).max(255).regex(/^[A-Za-z0-9_-]+$/) }).strict(), req.body)372    const mb = await userMailbox(a.userId, b.mailbox_id)373    const [e] = await loadEmails(mb, [b.email_id])374    if (!e) throw bad("not_found", 404)375    const facts = factsOf(e)376    if (usesAi([b.rule])) facts.ai_category = await aiCategory(a.userId, mb, e.id)377    const m = matchRule(b.rule, facts)378    return {379      matched: m.matched, dry_run: true,380      conditions: b.rule.conditions.map((c, i) => ({ ...c, result: m.results[i] })),381      actions: m.matched ? b.rule.actions.map((x) => ({ type: x.type, would: describe(x) })) : [],382      facts: { has_attachment: facts.has_attachment, is_newsletter: facts.is_newsletter, size: facts.size, list: facts.list, ai_category: facts.ai_category ?? null },383    }384  })385}386387export function ruleWorkers(): NextWorker[] {388  const intervalMs = Math.max(500, config.workerTickMs)389  return [{ name: "rules engine", intervalMs, run: async () => { await processJobs(); beat("rules engine", intervalMs) } }]390}391
Files main
Menu

Theme