SPB Git

Repository Public

next-push.test.ts 37.5 KB 540 lines typescript

1// SP Mail Next — push : fonctions pures (charge utile, heures calmes, priorités, aperçus, classement), puis le pipeline réel :2// courrier S → B sur stg.spboucher.ai, veilleur, file durable, faux serveur APNs HTTP/2 local qui consigne chaque requête.3import assert from "node:assert/strict"4import crypto from "node:crypto"5import fs from "node:fs"6import http2 from "node:http2"7import os from "node:os"8import path from "node:path"9import { after, before, test } from "node:test"10import { ApiError, ApiKey, Client, cli, haltServer, reauth, restartServer, sleep, sql, startServerWith, stopServer, tokenOf, until } from "../harness"11import { buildHeaders, buildPayload, classifyApns, inQuietHours, isPrioritySender, localMinutes, previewText, signProviderToken } from "../../server/src/next/apns"12import { mkKey, mkMailbox, purgeAll, sendAndWait, setupAdmin, type Box } from "./v1-helpers"1314// ------- faux serveur APNs (HTTP/2 en clair, 127.0.0.1) : consigne tout, répond selon un script ou une liste de jetons morts15type Hit = { token: string; headers: http2.IncomingHttpHeaders; payload: any; status: number }16class FakeApns {17  hits: Hit[] = []18  /** Statuts à répondre aux prochaines requêtes (ensuite 200). */19  script: number[] = []20  dead = new Set<string>()21  port = 022  private srv = http2.createServer()23  private open = new Set<http2.ServerHttp2Session>()24  async start() {25    this.srv.on("session", (s) => { this.open.add(s); s.on("close", () => this.open.delete(s)) })26    this.srv.on("stream", (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders) => {27      let body = ""28      stream.on("data", (d) => (body += d))29      stream.on("end", () => {30        const token = String(headers[":path"]).replace("/3/device/", "")31        const status = this.dead.has(token) ? 410 : (this.script.shift() ?? 200)32        this.hits.push({ token, headers, payload: JSON.parse(body), status })33        const reason = ({ 410: "Unregistered", 429: "TooManyRequests", 503: "ServiceUnavailable", 400: "BadDeviceToken" } as Record<number, string>)[status]34        stream.respond({ ":status": status, "apns-id": crypto.randomUUID(), "content-type": "application/json" })35        stream.end(reason ? JSON.stringify({ reason }) : "")36      })37    })38    await new Promise<void>((r) => this.srv.listen(0, "127.0.0.1", () => r()))39    this.port = (this.srv.address() as { port: number }).port40  }41  async stop() {42    for (const s of this.open) s.destroy()43    await new Promise<void>((r) => this.srv.close(() => r()))44  }45  of(token: string, kind?: string, from = 0) { return this.hits.slice(from).filter((h) => h.token === token && (!kind || h.payload.kind === kind)) }46}4748const fake = new FakeApns()49const { privateKey, publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" })50const keyFile = path.join(os.tmpdir(), `spmail-apns-test-${process.pid}.p8`)51const KEY_ID = "TESTKEY123", TEAM_ID = "TESTTEAM12", BUNDLE = "ai.spboucher.spmail.ios"52let ENV: Record<string, string> = {}5354let admin: Client, member: Client55let dev1: Client, dev2: Client, devM: Client56const tok = () => crypto.randomBytes(32).toString("hex")57const T1 = tok(), T2 = tok(), TM = tok()58let id1 = "", id2 = ""59let S: Box, B: Box, B2: Box60let ks: ApiKey61let acctB = ""62const tag = crypto.randomBytes(3).toString("hex")6364async function rejects(p: Promise<unknown>, status: number, code?: string) {65  await assert.rejects(p, (e: unknown) => e instanceof ApiError && e.status === status && (!code || e.code === code))66}67const acctOf = async (c: Client, b: Box) => (await c.call("GET", `/api/jmap/${b.id}/session`)).primaryAccounts["urn:ietf:params:jmap:mail"] as string68const register = (c: Client, token: string, extra: Record<string, unknown> = {}) => c.call("POST", "/api/push/register", { apns_token: token, environment: "sandbox", bundle_id: BUNDLE, ...extra })69/** Envoie un vrai message S → boîte, attend sa remise puis son passage par le veilleur ; rend son identifiant JMAP. */70async function deliver(to: Box, subject: string, text = "Corps du message d'essai."): Promise<{ id: string; threadId: string }> {71  const o = await sendAndWait(ks, { from: S.address, to: [to.address], subject, text })72  assert.equal(o.status, "delivered")73  const acct = await acctOf(admin, to)74  const e = await until(async () => {75    const r = await admin.jmap(to.id, [["Email/query", { accountId: acct, filter: { subject } }, "q"], ["Email/get", { accountId: acct, "#ids": { resultOf: "q", name: "Email/query", path: "/ids" }, properties: ["threadId", "subject"] }, "g"]])76    return (r[1][1].list as any[]).find((m) => m.subject === subject)77  }, `réception de « ${subject} »`)78  await until(async () => (await sql`select 1 from watched_messages where mailbox_id = ${to.id} and email_id = ${e.id}`).length, `veilleur : « ${subject} »`)79  return { id: e.id, threadId: e.threadId }80}81const alertFor = (token: string, emailId: string) => fake.hits.filter((h) => h.token === token && h.payload.kind === "new" && h.payload.email === emailId)82const waitAlert = (token: string, emailId: string) => until(async () => alertFor(token, emailId)[0], "alerte APNs", 20000)83const unreadInbox = async (b: Box) => {84  const acct = await acctOf(admin, b)85  const r = await admin.jmap(b.id, [["Mailbox/get", { accountId: acct, properties: ["role", "unreadEmails"] }, "m"]])86  return (r[0][1].list as any[]).find((m) => m.role === "inbox").unreadEmails as number87}88const quietNow = (tz: string) => {89  const m = localMinutes(new Date(), tz), f = (x: number) => `${String(Math.floor(((x + 1440) % 1440) / 60)).padStart(2, "0")}:${String(((x + 1440) % 1440) % 60).padStart(2, "0")}`90  return { start: f(m - 60), end: f(m + 120), tz }91}9293before(async () => {94  fs.writeFileSync(keyFile, privateKey.export({ type: "pkcs8", format: "pem" }), { mode: 0o600 })95  await fake.start()96  ENV = { SPMAIL_APNS_HOST_OVERRIDE: `http://127.0.0.1:${fake.port}`, SPMAIL_APNS_KEY_FILE: keyFile, SPMAIL_APNS_KEY_ID: KEY_ID, SPMAIL_APNS_TEAM_ID: TEAM_ID, SPMAIL_PUSH_BACKOFF: "1,1" }97  await startServerWith(ENV)98  admin = await setupAdmin()99  member = new Client("web")100  await member.enroll(tokenOf(await cli("invite")), "membre", "Membre")101  const m = (await admin.call("GET", "/api/admin/users")).find((u: any) => u.handle === "membre")102  // S (expéditeur) appartient au membre ; B et B2 (destinataires) au propriétaire.103  ;[S, B, B2] = await Promise.all([mkMailbox(admin, `ps${tag}`, m.id), mkMailbox(admin, `pb${tag}`), mkMailbox(admin, `pc${tag}`)])104  ks = await mkKey(admin, { scopes: ["mail.send", "mail.read"], addresses: [S.addressId] })105  acctB = await acctOf(admin, B)106  dev1 = new Client("native"); dev2 = new Client("native"); devM = new Client("native")107  await dev1.login(admin); await dev2.login(admin); await devM.login(member)108  // le veilleur doit avoir initialisé l'état des boîtes avant le premier envoi109  await until(async () => (await sql`select count(*)::int as n from mailbox_sync where email_state is not null`)[0].n >= 3, "initialisation du veilleur")110})111after(async () => {112  try {113    if (admin) {114      await reauth(admin)115      await purgeAll(admin)116    }117  } finally {118    await stopServer()119    await fake.stop()120    fs.rmSync(keyFile, { force: true })121  }122})123124// ------- fonctions pures125test("charge utile et en-têtes : alerte, mise à jour silencieuse, rappel", () => {126  const item = { kind: "new" as const, mailboxId: "mb-1", emailId: "e1", threadId: "t1", notice: { title: "Alice", subtitle: "Objet", body: "Début", timeSensitive: true } }127  assert.deepEqual(buildPayload(item, 7), {128    aps: { alert: { title: "Alice", subtitle: "Objet", body: "Début" }, badge: 7, sound: "default", "thread-id": "mb-1:t1", category: "MAIL_NEW", "mutable-content": 1, "interruption-level": "time-sensitive" },129    mb: "mb-1", email: "e1", thread: "t1", kind: "new",130  })131  const plain = buildPayload({ kind: "new", mailboxId: "mb-1", emailId: "e1", threadId: "t1", notice: { title: "A", body: "b", sound: false } }, null) as any132  assert.equal(plain.aps.sound, undefined)133  assert.equal(plain.aps.badge, undefined, "pastille « none » : clé absente")134  assert.equal(plain.aps["interruption-level"], "active")135  assert.deepEqual(buildPayload({ kind: "badge", notice: {} }, 3), { aps: { "content-available": 1, badge: 3 }, kind: "badge" })136  assert.deepEqual(buildPayload({ kind: "new", mailboxId: "m", emailId: "e", notice: { silent: true } }, 0), { aps: { "content-available": 1, badge: 0 }, kind: "badge" }, "heures calmes : rien du message")137  const rem = buildPayload({ kind: "reminder", mailboxId: "m", emailId: "e", threadId: "t", notice: { title: "Bob", body: "Rappel" } }, 1) as any138  assert.equal(rem.aps.category, "MAIL_REMINDER")139  assert.equal(rem.kind, "reminder")140  const now = new Date("2026-11-20T12:00:00Z")141  const h = buildHeaders(item, "ai.example.app", now)142  assert.equal(h["apns-topic"], "ai.example.app")143  assert.equal(h["apns-push-type"], "alert")144  assert.equal(h["apns-priority"], "10")145  assert.match(h["apns-collapse-id"], /^[0-9a-f]{40}$/)146  assert.equal(h["apns-expiration"], String(now.getTime() / 1000 + 86400))147  const hs = buildHeaders({ kind: "badge", notice: {} }, "ai.example.app", now)148  assert.deepEqual([hs["apns-push-type"], hs["apns-priority"], hs["apns-collapse-id"]], ["background", "5", "badge"])149  assert.ok(Buffer.byteLength(JSON.stringify(buildPayload({ kind: "new", mailboxId: crypto.randomUUID(), emailId: "x".repeat(40), threadId: "y".repeat(40), notice: previewText("full", { fromName: "N".repeat(500), subject: "S".repeat(2000), preview: "é".repeat(5000) }) }, 12))) < 4096, "sous la limite APNs de 4 Ko")150})151152test("heures calmes : fuseau IANA, plage enjambant minuit, réglages invalides", () => {153  const q = { start: "22:00", end: "07:00", tz: "America/Toronto" }154  assert.equal(inQuietHours(q, new Date("2026-11-20T04:30:00Z")), true, "23 h 30 à Toronto (UTC−5)")155  assert.equal(inQuietHours(q, new Date("2026-11-20T11:59:00Z")), true, "6 h 59")156  assert.equal(inQuietHours(q, new Date("2026-11-20T12:00:00Z")), false, "7 h 00 : fin exclue")157  assert.equal(inQuietHours(q, new Date("2026-11-20T20:00:00Z")), false, "15 h")158  assert.equal(inQuietHours(q, new Date("2026-07-01T02:30:00Z")), true, "heure d'été : 22 h 30 (UTC−4)")159  assert.equal(inQuietHours(q, new Date("2026-07-01T01:30:00Z")), false, "heure d'été : 21 h 30")160  assert.equal(inQuietHours({ ...q, tz: "Europe/Paris" }, new Date("2026-11-20T20:00:00Z")), false, "21 h à Paris")161  assert.equal(inQuietHours({ ...q, tz: "Europe/Paris" }, new Date("2026-11-20T21:00:00Z")), true, "22 h à Paris")162  assert.equal(inQuietHours({ start: "09:00", end: "17:00", tz: "UTC" }, new Date("2026-11-20T12:00:00Z")), true)163  assert.equal(inQuietHours({ start: "09:00", end: "17:00", tz: "UTC" }, new Date("2026-11-20T17:00:00Z")), false)164  assert.equal(inQuietHours(null), false)165  assert.equal(inQuietHours({ start: "09:00", end: "09:00", tz: "UTC" }, new Date("2026-11-20T09:00:00Z")), false, "plage vide")166  assert.equal(inQuietHours({ start: "09:00", end: "17:00", tz: "Mars/Olympus" }, new Date("2026-11-20T12:00:00Z")), false, "fuseau inconnu")167  assert.equal(inQuietHours({ start: "9h", end: "17:00", tz: "UTC" }, new Date("2026-11-20T12:00:00Z")), false)168  assert.equal(localMinutes(new Date("2026-11-20T05:07:00Z"), "America/Toronto"), 7, "minuit passé de 7 minutes")169})170171test("expéditeurs prioritaires, niveaux d'aperçu, classement des réponses APNs", () => {172  assert.equal(isPrioritySender(["Boss@Example.org"], "boss@example.org"), true)173  assert.equal(isPrioritySender(["@example.org"], "Anyone@EXAMPLE.org"), true)174  assert.equal(isPrioritySender(["@example.org"], "a@sub.example.org"), false, "domaine exact")175  assert.equal(isPrioritySender(["@example.org"], "a@notexample.org"), false)176  assert.equal(isPrioritySender(["boss@example.org"], "other@example.org"), false)177  assert.equal(isPrioritySender([], "a@b.c"), false)178  assert.equal(isPrioritySender(["a@b.c"], null), false)179180  const msg = { fromName: "Alice Martin", fromEmail: "alice@example.org", subject: "Budget 2027", preview: "Voici les chiffres…" }181  assert.deepEqual(previewText("none", msg), { title: "SP Mail", body: "New message" })182  assert.deepEqual(previewText("none", msg, "fr-CA"), { title: "SP Mail", body: "Nouveau message" })183  assert.deepEqual(previewText("sender", msg), { title: "Alice Martin", body: "New message" })184  assert.deepEqual(previewText("sender", { ...msg, fromName: "" }), { title: "alice@example.org", body: "New message" })185  assert.deepEqual(previewText("full", msg), { title: "Alice Martin", subtitle: "Budget 2027", body: "Voici les chiffres…" })186  assert.deepEqual(previewText("full", { ...msg, preview: "" }), { title: "Alice Martin", body: "Budget 2027" })187188  assert.equal(classifyApns(200), "ok")189  for (const [s, r] of [[429, "TooManyRequests"], [500, "InternalServerError"], [503, "ServiceUnavailable"], [0, "network"], [403, "ExpiredProviderToken"]] as const) assert.equal(classifyApns(s, r), "retry", `${s} ${r}`)190  for (const [s, r] of [[410, "Unregistered"], [410, ""], [400, "BadDeviceToken"], [400, "DeviceTokenNotForTopic"]] as const) assert.equal(classifyApns(s, r), "drop-token", `${s} ${r}`)191  for (const [s, r] of [[400, "BadCollapseId"], [400, "PayloadEmpty"], [403, "InvalidProviderToken"], [413, "PayloadTooLarge"], [404, "BadPath"]] as const) assert.equal(classifyApns(s, r), "fail", `${s} ${r}`)192})193194test("jeton fournisseur ES256 : vérifiable avec la clé publique", () => {195  const jwt = signProviderToken(privateKey, "KID1234567", "TEAM123456", 1_800_000_000)196  const [h, c, s] = jwt.split(".")197  assert.deepEqual(JSON.parse(Buffer.from(h, "base64url").toString()), { alg: "ES256", kid: "KID1234567" })198  assert.deepEqual(JSON.parse(Buffer.from(c, "base64url").toString()), { iss: "TEAM123456", iat: 1_800_000_000 })199  assert.equal(crypto.verify("sha256", Buffer.from(`${h}.${c}`), { key: publicKey, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url")), true)200})201202// ------- pipeline réel203test("enregistrement : natif seulement, réenregistrement, liste, préférences d'appareil, cloisonnement entre utilisateurs", async () => {204  await rejects(admin.call("POST", "/api/push/register", { apns_token: T1, environment: "sandbox", bundle_id: BUNDLE }), 400, "native_only")205  await rejects(register(dev1, "pas-un-jeton"), 400, "invalid_request")206  await rejects(new Client("native").call("GET", "/api/next/push/devices"), 401)207  const r1 = await register(dev1, T1, { device_name: "iPhone d'essai", locale: "en-CA", app_version: "2.0.0" })208  assert.equal(r1.ok, true)209  assert.match(r1.device_id, /^[0-9a-f-]{36}$/)210  id1 = r1.device_id211  id2 = (await register(dev2, T2, { device_name: "iPad d'essai", locale: "fr-CA" })).device_id212  await register(devM, TM, { device_name: "iPhone du membre" })213  const list = (await dev1.call("GET", "/api/next/push/devices")).data214  assert.deepEqual(list.map((d: any) => [d.id, d.device_name, d.bundle_id, d.environment, d.enabled, d.current]), [[id1, "iPhone d'essai", BUNDLE, "sandbox", true, true], [id2, "iPad d'essai", BUNDLE, "sandbox", true, false]])215  assert.ok(list[0].created_at && list[0].last_registered_at && list[0].last_push_at === null && list[0].last_error === null)216  assert.ok(!JSON.stringify(list).includes(T1), "le jeton APNs n'est jamais rendu")217  assert.deepEqual((await admin.call("GET", "/api/next/push/devices")).data.map((d: any) => d.current), [false, false], "la session web voit les appareils, aucun n'est le sien")218  // coupure puis réenregistrement du même jeton : même ligne, réactivée219  assert.equal((await dev1.call("PATCH", `/api/next/push/devices/${id1}`, { enabled: false, prefs: { sound: false } })).enabled, false)220  const again = await register(dev1, T1, { app_version: "2.0.1" })221  assert.equal(again.device_id, id1)222  const d1 = (await dev1.call("GET", "/api/next/push/devices")).data.find((d: any) => d.id === id1)223  assert.deepEqual([d1.enabled, d1.app_version, d1.device_name, d1.prefs.sound], [true, "2.0.1", "iPhone d'essai", false])224  await dev1.call("PATCH", `/api/next/push/devices/${id1}`, { prefs: { sound: true } })225  // boîte d'autrui dans les préférences d'appareil : écartée226  assert.deepEqual((await dev1.call("PATCH", `/api/next/push/devices/${id1}`, { prefs: { mailboxes: { [S.id]: false } } })).prefs.mailboxes, {})227  // cloisonnement228  assert.deepEqual((await devM.call("GET", "/api/next/push/devices")).data.map((d: any) => d.device_name), ["iPhone du membre"])229  await rejects(devM.call("PATCH", `/api/next/push/devices/${id1}`, { enabled: false }), 404, "not_found")230  await rejects(devM.call("DELETE", `/api/next/push/devices/${id1}`), 404, "not_found")231  await rejects(devM.call("POST", "/api/next/push/test", { device_id: id1 }), 404, "not_found")232  await rejects(dev1.call("PATCH", "/api/next/push/devices/nope", { enabled: false }), 404, "not_found")233  const st = await dev1.call("GET", "/api/next/push/status")234  assert.equal(st.configured, true)235  assert.deepEqual(st.queue, { pending: 0, failed_24h: 0, sent_24h: 0 })236  assert.equal(st.last_error, null)237  // préférences par défaut, validation238  assert.deepEqual(await dev1.call("GET", "/api/next/push/prefs"), { enabled: true, preview: "sender", quiet_hours: null, priority_senders: [], priority_only: false, mailboxes: {}, badge: "inbox" })239  await rejects(dev1.call("PUT", "/api/next/push/prefs", { quiet_hours: { start: "22:00", end: "07:00", tz: "Mars/Olympus" } }), 400, "invalid_request")240  await rejects(dev1.call("PUT", "/api/next/push/prefs", { preview: "everything" }), 400, "invalid_request")241  await rejects(dev1.call("PUT", "/api/next/push/prefs", { priority_senders: ["pas une adresse"] }), 400, "invalid_request")242})243244let first: { id: string; threadId: string }245test("une alerte par appareil et par message ; jeton ES256 vérifié ; aperçu « sender » par défaut ; pastille", async () => {246  const subject = `Secret d'essai ${tag}-1`247  first = await deliver(B, subject)248  const [a1, a2] = await Promise.all([waitAlert(T1, first.id), waitAlert(T2, first.id)])249  // en-têtes APNs250  assert.equal(a1.headers[":method"], "POST")251  assert.equal(a1.headers["apns-topic"], BUNDLE)252  assert.equal(a1.headers["apns-push-type"], "alert")253  assert.equal(a1.headers["apns-priority"], "10")254  assert.match(String(a1.headers["apns-collapse-id"]), /^[0-9a-f]{40}$/)255  assert.ok(Number(a1.headers["apns-expiration"]) > Date.now() / 1000 + 3600)256  // jeton fournisseur : signature vérifiée avec la clé publique de l'essai257  const m = /^bearer (.+)$/.exec(String(a1.headers.authorization))!258  const [h, c, s] = m[1].split(".")259  assert.deepEqual(JSON.parse(Buffer.from(h, "base64url").toString()), { alg: "ES256", kid: KEY_ID })260  const claims = JSON.parse(Buffer.from(c, "base64url").toString())261  assert.equal(claims.iss, TEAM_ID)262  assert.ok(Math.abs(claims.iat - Date.now() / 1000) < 120)263  assert.equal(crypto.verify("sha256", Buffer.from(`${h}.${c}`), { key: publicKey, dsaEncoding: "ieee-p1363" }, Buffer.from(s, "base64url")), true)264  assert.equal(a2.headers.authorization, a1.headers.authorization, "jeton mis en cache et réutilisé")265  // charge utile : nom de l'expéditeur seulement, identifiants opaques, regroupement par fil266  assert.deepEqual(a1.payload, {267    aps: { alert: { title: `Essai ps${tag}`, body: "New message" }, badge: 1, sound: "default", "thread-id": `${B.id}:${first.threadId}`, category: "MAIL_NEW", "mutable-content": 1, "interruption-level": "active" },268    mb: B.id, email: first.id, thread: first.threadId, kind: "new",269  })270  assert.equal(a2.payload.aps.alert.body, "Nouveau message", "appareil en fr-CA")271  assert.ok(!JSON.stringify([a1.payload, a2.payload]).includes("Secret"), "l'objet ne sort pas au niveau « sender »")272  // une seule requête par appareil, rien pour le membre (qui ne lit pas B)273  await sleep(1500)274  assert.equal(alertFor(T1, first.id).length, 1)275  assert.equal(alertFor(T2, first.id).length, 1)276  assert.equal(fake.of(TM).length, 0)277  const rows = await sql`select status, attempts, apns_id, last_status, sent_at, dedup_key from push_outbox where email_id = ${first.id} order by dedup_key`278  assert.equal(rows.length, 2)279  for (const r of rows) assert.deepEqual([r.status, r.attempts, r.last_status, !!r.apns_id, !!r.sent_at], ["sent", 1, 200, true, true])280  const d1 = (await dev1.call("GET", "/api/next/push/devices")).data.find((d: any) => d.id === id1)281  assert.ok(d1.last_push_at)282  assert.equal((await dev1.call("GET", "/api/next/push/status")).queue.sent_24h, 2)283})284285test("déduplication à travers un redémarrage : le veilleur rejoue le lot, aucune seconde alerte", async () => {286  // État d'avant le message : on y ramène le veilleur, et on efface sa mémoire du message — il le « reçoit » de nouveau.287  const subject = `Rejeu ${tag}`288  const [{ email_state: stateBefore }] = await sql`select email_state from mailbox_sync where mailbox_id = ${B.id}`289  const e = await deliver(B, subject)290  await Promise.all([waitAlert(T1, e.id), waitAlert(T2, e.id)])291  await haltServer()292  const [{ n: eventsBefore }] = await sql`select count(*)::int as n from webhook_events where type = 'message.received'`293  await sql`delete from watched_messages where mailbox_id = ${B.id} and email_id = ${e.id}`294  await sql`update mailbox_sync set email_state = ${stateBefore}, locked_until = null where mailbox_id = ${B.id}`295  await restartServer(ENV)296  await until(async () => (await sql`select 1 from watched_messages where mailbox_id = ${B.id} and email_id = ${e.id}`).length, "rejeu du lot par le veilleur")297  assert.ok((await sql`select count(*)::int as n from webhook_events where type = 'message.received'`)[0].n > eventsBefore, "le veilleur a bien rejoué la réception")298  await sleep(2500)299  assert.equal(alertFor(T1, e.id).length, 1, "une seule alerte malgré le rejeu")300  assert.equal(alertFor(T2, e.id).length, 1)301  assert.equal((await sql`select count(*)::int as n from push_outbox where email_id = ${e.id}`)[0].n, 2)302  assert.equal((await sql`select resyncs from mailbox_sync where mailbox_id = ${B.id}`)[0].resyncs, 0)303})304305test("niveaux d'aperçu : « full » (expéditeur, objet, début), « none » (rien du message)", async () => {306  assert.equal((await dev1.call("PUT", "/api/next/push/prefs", { preview: "full" })).preview, "full")307  const e = await deliver(B, `Aperçu complet ${tag}`, "Première ligne du corps, visible en aperçu complet.")308  const a = await waitAlert(T1, e.id)309  assert.equal(a.payload.aps.alert.title, `Essai ps${tag}`)310  assert.equal(a.payload.aps.alert.subtitle, `Aperçu complet ${tag}`)311  assert.match(a.payload.aps.alert.body, /Première ligne du corps/)312  await dev1.call("PUT", "/api/next/push/prefs", { preview: "none" })313  const e2 = await deliver(B, `Aperçu nul ${tag}`, "Texte confidentiel.")314  const a2 = await waitAlert(T1, e2.id)315  assert.deepEqual(a2.payload.aps.alert, { title: "SP Mail", body: "New message" })316  const raw = JSON.stringify(a2.payload)317  for (const leak of ["Aperçu nul", "confidentiel", S.address, "Essai ps"]) assert.ok(!raw.includes(leak), `« none » ne laisse rien passer : ${leak}`)318  assert.deepEqual([a2.payload.mb, a2.payload.email], [B.id, e2.id], "les identifiants opaques restent")319  // PUT n'applique que les clés présentes320  const p = await dev1.call("PUT", "/api/next/push/prefs", { preview: "sender" })321  assert.deepEqual([p.preview, p.enabled, p.badge], ["sender", true, "inbox"])322})323324test("heures calmes : mise à jour silencieuse seulement ; un expéditeur prioritaire (adresse, contact vip) passe", async () => {325  const quiet = quietNow("America/Toronto")326  assert.equal(inQuietHours(quiet), true)327  assert.deepEqual((await dev1.call("PUT", "/api/next/push/prefs", { quiet_hours: quiet })).quiet_hours, quiet)328  let mark = fake.hits.length329  const e = await deliver(B, `Heures calmes ${tag}`)330  const silent = await until(async () => fake.hits.slice(mark).find((h) => h.token === T1 && h.headers["apns-push-type"] === "background"), "mise à jour silencieuse")331  assert.equal(silent.headers["apns-priority"], "5")332  assert.deepEqual(silent.payload, { aps: { "content-available": 1, badge: await unreadInbox(B) }, kind: "badge" })333  await sleep(1500)334  assert.equal(alertFor(T1, e.id).length, 0, "aucune alerte pendant les heures calmes")335  const [row] = await sql`select kind, status, payload from push_outbox where email_id = ${e.id} and device_id = ${id1}`336  assert.deepEqual([row.kind, row.status, row.payload], ["new", "sent", { silent: true }], "la ligne existe, sans aucun texte du message")337  // expéditeur prioritaire : alerte « time-sensitive » malgré les heures calmes338  await dev1.call("PUT", "/api/next/push/prefs", { priority_senders: [S.address.toUpperCase()] })339  const e2 = await deliver(B, `Prioritaire ${tag}`)340  const a = await waitAlert(T1, e2.id)341  assert.equal(a.payload.aps["interruption-level"], "time-sensitive")342  assert.equal(a.headers["apns-push-type"], "alert")343  // « prioritaires seulement » sans heures calmes : un expéditeur ordinaire reste silencieux344  await dev1.call("PUT", "/api/next/push/prefs", { quiet_hours: null, priority_senders: ["someone-else@stg.spboucher.ai"], priority_only: true })345  mark = fake.hits.length346  const e3 = await deliver(B, `Pas prioritaire ${tag}`)347  await until(async () => fake.hits.slice(mark).find((h) => h.token === T1 && h.headers["apns-push-type"] === "background"), "mise à jour silencieuse (priority_only)")348  await sleep(1000)349  assert.equal(alertFor(T1, e3.id).length, 0)350  // contact « vip » (tables du module contacts, si elles sont présentes dans ce schéma)351  const [{ ok: hasContacts }] = await sql`select (to_regclass('contacts') is not null and to_regclass('contact_emails') is not null) as ok`352  if (hasContacts) {353    const [{ id: me }] = await sql`select id from users where handle = 'owner'`354    // le module contacts peut déjà avoir récolté cet expéditeur : on marque alors sa fiche355    let [c] = await sql`select contact_id as id from contact_emails where user_id = ${me} and email = ${S.address}`356    if (c) await sql`update contacts set vip = true where id = ${c.id}`357    else {358      ;[c] = await sql`insert into contacts (user_id, name, vip) values (${me}, 'Expéditeur vip', true) returning id`359      await sql`insert into contact_emails (contact_id, user_id, email) values (${c.id}, ${me}, ${S.address})`360    }361    const e4 = await deliver(B, `Contact vip ${tag}`)362    assert.equal((await waitAlert(T1, e4.id)).payload.aps["interruption-level"], "time-sensitive")363    await sql`update contacts set vip = false where id = ${c.id}`364  } else console.error("# contact vip : tables contacts/contact_emails absentes de ce schéma — cas NON exécuté")365  await dev1.call("PUT", "/api/next/push/prefs", { priority_senders: [], priority_only: false })366})367368test("boîte coupée : par l'utilisateur (aucune ligne), par un appareil (les autres continuent)", async () => {369  assert.deepEqual((await dev1.call("PUT", "/api/next/push/prefs", { mailboxes: { [B2.id]: false, [S.id]: false } })).mailboxes, { [B2.id]: false }, "la boîte d'autrui est écartée")370  const mark = fake.hits.length371  const e = await deliver(B2, `Boîte coupée ${tag}`)372  await sleep(3000)373  assert.equal((await sql`select count(*)::int as n from push_outbox where mailbox_id = ${B2.id}`)[0].n, 0)374  assert.equal(fake.hits.slice(mark).filter((h) => h.payload.email === e.id).length, 0)375  // coupure au niveau d'un appareil376  await dev2.call("PATCH", `/api/next/push/devices/${id2}`, { prefs: { mailboxes: { [B.id]: false } } })377  const e2 = await deliver(B, `Coupée sur un appareil ${tag}`)378  const a = await waitAlert(T1, e2.id)379  // la pastille ignore la boîte coupée par l'utilisateur (B2 a un non-lu)380  assert.equal(await unreadInbox(B2), 1)381  assert.equal(a.payload.aps.badge, await unreadInbox(B))382  await sleep(1500)383  assert.equal(alertFor(T2, e2.id).length, 0)384  await dev2.call("PATCH", `/api/next/push/devices/${id2}`, { prefs: { mailboxes: {} } })385  await dev1.call("PUT", "/api/next/push/prefs", { mailboxes: {} })386})387388test("nouvelle tentative après 503 puis 429, puis succès ; état de l'appareil", async () => {389  await dev2.call("PATCH", `/api/next/push/devices/${id2}`, { enabled: false })390  fake.script = [503, 429]391  const mark = fake.hits.length392  const e = await deliver(B, `Reprise ${tag}`)393  await until(async () => (await sql`select 1 from push_outbox where email_id = ${e.id} and status = 'sent'`).length, "envoi après deux échecs", 30000)394  const tries = fake.hits.slice(mark).filter((h) => h.token === T1 && h.payload.email === e.id)395  assert.deepEqual(tries.map((h) => h.status), [503, 429, 200])396  assert.equal(new Set(tries.map((h) => h.headers["apns-collapse-id"])).size, 1, "même identifiant de regroupement à chaque tentative")397  const [row] = await sql`select attempts, last_status, last_error from push_outbox where email_id = ${e.id} and device_id = ${id1}`398  assert.deepEqual([row.attempts, row.last_status, row.last_error], [3, 200, null])399  assert.equal(fake.of(T2, undefined, mark).length, 0, "appareil désactivé : rien")400  assert.equal((await sql`select count(*)::int as n from push_outbox where email_id = ${e.id}`)[0].n, 1)401  const [d] = await sql`select last_error, failure_count from push_devices where id = ${id1}`402  assert.deepEqual([d.last_error, d.failure_count], [null, 0])403  // une erreur en cours est visible sur l'appareil404  fake.script = [503]405  const e2 = await deliver(B, `Reprise visible ${tag}`)406  await until(async () => (await sql`select 1 from push_devices where id = ${id1} and last_error = '503 ServiceUnavailable'`).length, "erreur consignée sur l'appareil")407  await until(async () => (await sql`select 1 from push_outbox where email_id = ${e2.id} and status = 'sent'`).length, "reprise")408  await dev2.call("PATCH", `/api/next/push/devices/${id2}`, { enabled: true })409})410411test("410 Unregistered : le jeton est supprimé, les autres appareils continuent", async () => {412  fake.dead.add(T2)413  const e = await deliver(B, `Jeton mort ${tag}`)414  await waitAlert(T1, e.id)415  await until(async () => !(await sql`select 1 from push_devices where id = ${id2}`).length, "suppression du jeton mort")416  assert.equal(fake.hits.filter((h) => h.token === T2 && h.status === 410).length, 1, "une seule tentative sur un jeton mort")417  assert.deepEqual((await dev1.call("GET", "/api/next/push/devices")).data.map((d: any) => d.id), [id1])418  assert.equal((await sql`select count(*)::int as n from push_outbox where device_id = ${id2}`)[0].n, 0)419  fake.dead.delete(T2)420  // l'app se réenregistre : nouvel appareil421  id2 = (await register(dev2, T2, { device_name: "iPad d'essai", locale: "fr-CA" })).device_id422})423424test("pastille : total des non-lus ; lecture ailleurs → une seule mise à jour silencieuse par rafale", async () => {425  const e = await deliver(B, `Pastille ${tag}`)426  const a = await waitAlert(T1, e.id)427  const unread = await unreadInbox(B)428  assert.ok(unread >= 5)429  assert.equal(a.payload.aps.badge, unread + (await unreadInbox(B2)), "pastille = non-lus des boîtes de réception de l'utilisateur")430  await waitAlert(T2, e.id)431  await sleep(2500) // laisse passer toute mise à jour encore en file432  let mark = fake.hits.length433  // un message lu depuis un autre client434  await admin.jmap(B.id, [["Email/set", { accountId: acctB, update: { [e.id]: { "keywords/$seen": true } } }, "s"]])435  const s1 = await until(async () => fake.of(T1, "badge", mark)[0], "mise à jour silencieuse après lecture", 20000)436  assert.deepEqual(s1.payload, { aps: { "content-available": 1, badge: a.payload.aps.badge - 1 }, kind: "badge" })437  assert.deepEqual([s1.headers["apns-push-type"], s1.headers["apns-priority"], s1.headers["apns-collapse-id"]], ["background", "5", "badge"])438  await until(async () => fake.of(T2, "badge", mark)[0], "mise à jour silencieuse du second appareil")439  await sleep(2500)440  assert.equal(fake.of(T1, "badge", mark).length, 1)441  // rafale : trois lectures d'un coup → une seule mise à jour, avec le total final442  mark = fake.hits.length443  const r = await admin.jmap(B.id, [["Email/query", { accountId: acctB, filter: { notKeyword: "$seen" }, limit: 3 }, "q"]])444  const three = r[0][1].ids as string[]445  assert.equal(three.length, 3)446  for (const id of three) await admin.jmap(B.id, [["Email/set", { accountId: acctB, update: { [id]: { "keywords/$seen": true } } }, "s"]])447  const s2 = await until(async () => fake.of(T1, "badge", mark)[0], "mise à jour silencieuse après rafale", 20000)448  await sleep(4000)449  const burst = fake.of(T1, "badge", mark)450  assert.equal(burst.length, 1, "une rafale = une mise à jour")451  assert.equal(s2.payload.aps.badge, a.payload.aps.badge - 4)452  // un changement sans effet sur le total (drapeau) n'émet rien453  mark = fake.hits.length454  await admin.jmap(B.id, [["Email/set", { accountId: acctB, update: { [e.id]: { "keywords/$flagged": true } } }, "s"]])455  await sleep(5000)456  assert.equal(fake.of(T1, "badge", mark).length, 0)457  assert.equal((await sql`select count(*)::int as n from push_outbox where kind = 'badge' and device_id = ${id1}`)[0].n, 1, "une seule ligne de pastille par appareil, réarmée")458})459460test("notification d'essai ; pastille « none » ; push coupé par l'utilisateur", async () => {461  let mark = fake.hits.length462  assert.deepEqual(await dev1.call("POST", "/api/next/push/test", { device_id: id1 }), { queued: 1 })463  const t = await until(async () => fake.of(T1, "test", mark)[0], "notification d'essai")464  assert.deepEqual(t.payload.aps.alert, { title: "SP Mail", body: "Test notification" })465  assert.equal(fake.of(T2, "test", mark).length, 0)466  assert.deepEqual(await dev1.call("POST", "/api/next/push/test", {}), { queued: 2 })467  await until(async () => fake.of(T2, "test", mark)[0], "notification d'essai (tous les appareils)")468  await dev1.call("PUT", "/api/next/push/prefs", { badge: "none" })469  mark = fake.hits.length470  const e = await deliver(B, `Sans pastille ${tag}`)471  assert.equal((await waitAlert(T1, e.id)).payload.aps.badge, undefined)472  await dev1.call("PUT", "/api/next/push/prefs", { badge: "inbox", enabled: false })473  const e2 = await deliver(B, `Push coupé ${tag}`)474  await sleep(3000)475  assert.equal((await sql`select count(*)::int as n from push_outbox where email_id = ${e2.id}`)[0].n, 0)476  assert.deepEqual(await dev1.call("POST", "/api/next/push/test", {}), { queued: 0 })477  await dev1.call("PUT", "/api/next/push/prefs", { enabled: true })478})479480test("révocation de session, déconnexion, suppression : l'appareil ne reçoit plus rien", async () => {481  const sessions = await admin.call("GET", "/api/sessions")482  const [{ session_id: s1 }] = await sql`select session_id from push_devices where id = ${id1}`483  assert.ok(sessions.some((s: any) => s.id === s1))484  await admin.call("DELETE", `/api/sessions/${s1}`)485  assert.equal((await sql`select count(*)::int as n from push_devices where id = ${id1}`)[0].n, 0, "révocation à distance : jeton supprimé")486  await rejects(dev1.call("GET", "/api/next/push/devices"), 401)487  // déconnexion depuis l'appareil488  const dev3 = new Client("native")489  await dev3.login(admin)490  const T3 = tok()491  const id3 = (await register(dev3, T3)).device_id492  await dev3.call("POST", "/api/logout", {})493  assert.equal((await sql`select count(*)::int as n from push_devices where id = ${id3}`)[0].n, 0, "déconnexion : jeton supprimé")494  // session révoquée hors de l'API (ligne de commande) : le travailleur retire l'appareil au lieu d'envoyer495  const dev4 = new Client("native")496  await dev4.login(admin)497  const T4 = tok()498  const id4 = (await register(dev4, T4)).device_id499  assert.deepEqual(await dev4.call("POST", "/api/next/push/test", { device_id: id4 }), { queued: 1 })500  await until(async () => fake.of(T4, "test")[0], "essai avant révocation")501  await sql.begin(async (tx) => {502    await tx`insert into push_outbox (device_id, user_id, kind, payload, dedup_key) select id, user_id, 'test', '{"title":"x","body":"y"}', ${`test:${id4}:manual`} from push_devices where id = ${id4}`503    await tx`update sessions set revoked_at = now() where id = (select session_id from push_devices where id = ${id4})`504  })505  await until(async () => !(await sql`select 1 from push_devices where id = ${id4}`).length, "retrait de l'appareil d'une session révoquée")506  assert.equal(fake.of(T4, "test").length, 1, "rien n'est parti après la révocation")507  const mark = fake.hits.length508  const e = await deliver(B, `Après révocation ${tag}`)509  await waitAlert(T2, e.id)510  await sleep(1000)511  assert.equal(fake.hits.slice(mark).filter((h) => [T1, T3, T4].includes(h.token)).length, 0)512  // suppression explicite513  await dev2.call("DELETE", `/api/next/push/devices/${id2}`)514  assert.deepEqual((await dev2.call("GET", "/api/next/push/devices")).data, [])515  // le jeton d'un appareil qui change d'utilisateur ne garde ni réglages ni file516  const idM = (await devM.call("GET", "/api/next/push/devices")).data[0].id517  await devM.call("PATCH", `/api/next/push/devices/${idM}`, { prefs: { mailboxes: { [S.id]: false }, sound: false } })518  const moved = await register(dev2, TM)519  assert.equal(moved.device_id, idM)520  assert.deepEqual((await dev2.call("GET", "/api/next/push/devices")).data.map((d: any) => [d.id, d.prefs]), [[idM, {}]])521  assert.deepEqual((await devM.call("GET", "/api/next/push/devices")).data, [])522})523524test("sans réglage APNs : rien n'est mis en file, l'état le dit, aucune remise n'est simulée", async () => {525  await restartServer({}) // même base, sans SPMAIL_APNS_*526  const st = await dev2.call("GET", "/api/next/push/status")527  assert.equal(st.configured, false)528  assert.match(st.last_error, /not configured/)529  assert.deepEqual(st.environment_hosts, { production: "api.push.apple.com", sandbox: "api.sandbox.push.apple.com" })530  const [{ n: before }] = await sql`select count(*)::int as n from push_outbox`531  const mark = fake.hits.length532  await deliver(B, `Non configuré ${tag}`)533  assert.deepEqual(await dev2.call("POST", "/api/next/push/test", {}), { queued: 0 })534  await sleep(3000)535  assert.equal((await sql`select count(*)::int as n from push_outbox`)[0].n, before)536  assert.equal(fake.hits.length, mark)537  // l'enregistrement d'un appareil reste possible (il servira dès que le push sera configuré)538  assert.equal((await register(dev2, tok())).ok, true)539})540
Files main
Menu

Theme