Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : SP Mail8 * File : tests/integration/v1-helpers.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/sp-mail11 * Project Website : https://mail.spboucher.ai12 * Created : 2026-11-1913 * Last Modified : 2026-11-1914 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// Aides communes aux suites /api/v1 : administrateur, boîtes d'essai sur stg.spboucher.ai, clés d'API, purge finale.44import assert from "node:assert/strict"45import { ApiKey, Client, RUN, STG, cli, reauth, sql, tokenOf, v1Session } from "../harness"4647export const addr = (name: string) => `api-${name}-${RUN}@${STG}`48export type Box = { id: string; address: string; addressId: string }4950export async function setupAdmin(): Promise<Client> {51 const admin = new Client("web")52 await admin.enroll(tokenOf(await cli("bootstrap")), "owner", "Propriétaire")53 await reauth(admin)54 return admin55}56export async function mkMailbox(admin: Client, name: string, userId?: string): Promise<Box> {57 const address = addr(name)58 const { id } = await admin.call("POST", "/api/admin/mailboxes", { address, display_name: `Essai ${name}`, ...(userId ? { user_id: userId } : {}) })59 const [a] = await sql`select id from addresses where address = ${address}`60 assert.ok(a, "l'adresse de première classe suit la création de la boîte")61 return { id, address, addressId: a.id }62}63export type KeyOpts = { scopes: string[]; addresses?: string[]; all?: boolean; external?: "allow" | "approval" | "deny"; rate?: number; daily?: number; expires_at?: string | null; domains?: string[]; name?: string }64export async function mkKey(admin: Client, o: KeyOpts): Promise<ApiKey> {65 await reauth(admin)66 const r = await admin.call("POST", "/api/admin/api-keys", {67 name: o.name ?? `key-${Math.random().toString(36).slice(2, 8)}`, scopes: o.scopes, address_ids: o.addresses ?? [], all_addresses: !!o.all,68 external_send_policy: o.external ?? "allow", rate_per_minute: o.rate ?? 600, daily_send_limit: o.daily ?? 500, expires_at: o.expires_at ?? null, allowed_recipient_domains: o.domains ?? [],69 })70 assert.match(r.token, /^spm_[a-z0-9]{10}_[A-Za-z0-9_-]{43}$/)71 return new ApiKey(r.token, r.key.id)72}73export const addressId = async (address: string) => (await sql`select id from addresses where address = ${address}`)[0]?.id as string7475/** Supprime du serveur de courrier tout ce que la suite a créé (boîtes, alias, listes), puis vérifie qu'il ne reste rien. */76export async function purgeAll(admin: Client) {77 await sql`update addresses set protected = false`.catch(() => {})78 const boxes = await sql`select id, address from mailboxes`.catch(() => [])79 for (const b of boxes) {80 assert.ok(String(b.address).endsWith(`@${STG}`), "les essais ne touchent que le domaine de recette")81 await admin.call("DELETE", `/api/admin/mailboxes/${b.id}?purge=delete-all-mail`).catch((e) => console.error(`purge ${b.address}: ${e}`))82 }83 const o = await admin.call("GET", "/api/admin/overview").catch(() => null)84 const left = (o?.accounts ?? []).filter((a: any) => String(a.address).includes(`-${RUN}@`))85 assert.deepEqual(left.map((a: any) => a.address), [], "aucun compte d'essai ne reste sur le serveur de courrier")86}87export const sess = v1Session8889// ---- lecture directe de l'état du serveur de courrier (vérifie que l'application des états est réelle, pas cosmétique)90import fs from "node:fs"91import os from "node:os"92import path from "node:path"93import { STALWART, until } from "../harness"94const S = process.env.SPMAIL_SECRETS ?? path.join(os.homedir(), "Desktop/Cluster/secrets/sp-mail")95export async function stalwartAccount(address: string): Promise<any | null> {96 const auth = "Basic " + Buffer.from(`spmail-admin@spboucher.ai:${fs.readFileSync(path.join(S, "stalwart-admin.pw"), "utf8").trim()}`).toString("base64")97 const r = await fetch(`${STALWART}/jmap/`, { method: "POST", headers: { authorization: auth, "content-type": "application/json" }, body: JSON.stringify({ using: ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], methodCalls: [["x:Account/query", { limit: 500 }, "q"], ["x:Account/get", { "#ids": { resultOf: "q", name: "x:Account/query", path: "/ids" }, properties: ["emailAddress", "aliases", "quotas", "permissions"] }, "g"]] }) })98 const list = ((await r.json()) as any).methodResponses[1][1].list as any[]99 return list.find((a) => a.emailAddress === address) ?? null100}101export const aliasOf = (acct: any, address: string) => Object.values<any>(acct?.aliases ?? {}).find((a) => a.name === address.split("@")[0])102103/** Envoie puis attend l'état définitif de remise (delivered, bounced, failed). */104export async function sendAndWait(k: ApiKey, body: Record<string, unknown>, timeout = 30000): Promise<any> {105 const sent = await k.call("POST", "/messages/send", body)106 return until(async () => {107 const o = await k.call("GET", `/messages/outbound/${sent.id}`)108 return ["delivered", "bounced", "failed"].includes(o.status) ? o : null109 }, `remise de « ${body.subject} »`, timeout)110}111