Repository Public
1#!/usr/bin/env node2// Author: Simon-Pierre Boucher — contact@spboucher.ai3// File: Scripts/dev-bootstrap.mjs4// Description: Prepares (and later purges) the test fixtures of SP Mail's native apps on a LOCAL development backend:5// enrolls an administrator with a software WebAuthn authenticator (same pattern as sp-mail/tests/harness.ts),6// creates two staging mailboxes apple-<x>-<random>@stg.spboucher.ai, one sendable alias apple-alias-<random>@stg.spboucher.ai on the first,7// and mints native bearer tokens with `cli dev-token`.8//9// Usage:10// node Scripts/dev-bootstrap.mjs up → writes Build/dev-env.json and Build/dev-env.sh (never committed)11// node Scripts/dev-bootstrap.mjs fresh → purges the current pair and creates a new one (the mail server limits each SENDER to ~25 messages12// per hour and answers 452 beyond that: a new pair gets a new allowance)13// node Scripts/dev-bootstrap.mjs token → prints one more native bearer token for the test user14// node Scripts/dev-bootstrap.mjs purge → deletes the test mailboxes AND their mail from the mail server15// Environment: SPMAIL_DEV_PORT (default 8821), SPMAIL_DEV_DB (default postgres://127.0.0.1/sp_mail_apple2dev), SPMAIL_BACKEND_DIR.16// Hard rules: staging domain only, never an address on spboucher.ai, never a mailbox this script did not create.17import { execFileSync } from "node:child_process"18import crypto from "node:crypto"19import fs from "node:fs"20import os from "node:os"21import path from "node:path"22import { fileURLToPath } from "node:url"2324const HERE = path.dirname(fileURLToPath(import.meta.url))25const OUT = path.join(HERE, "..", "Build")26const STATE = path.join(OUT, "dev-env.json")27const PORT = Number(process.env.SPMAIL_DEV_PORT ?? 8821)28const DB = process.env.SPMAIL_DEV_DB ?? "postgres://127.0.0.1/sp_mail_apple2dev"29const BACKEND = process.env.SPMAIL_BACKEND_DIR ?? path.join(os.homedir(), "Desktop/Cluster/projets/sp-mail")30const ORIGIN = `http://localhost:${PORT}`31const DOMAIN = "stg.spboucher.ai"32if ([8731, 8741, 8751].includes(PORT) || /sp_mail_(dev|test|webdev)$/.test(DB)) throw new Error("refusing to touch somebody else's stack")3334const cli = (...args) => execFileSync("scripts/dev.sh", ["node", "dist/cli.mjs", ...args], { cwd: BACKEND, env: { ...process.env, PORT: String(PORT), DATABASE_URL: DB }, encoding: "utf8" })3536// ---- software authenticator (ES256, "none" attestation)37const b64u = (b) => Buffer.from(b).toString("base64url")38const cborBytes = (b) => b.length < 24 ? Buffer.concat([Buffer.from([0x40 + b.length]), b]) : b.length < 256 ? Buffer.concat([Buffer.from([0x58, b.length]), b]) : Buffer.concat([Buffer.from([0x59, b.length >> 8, b.length & 255]), b])39const cborText = (s) => Buffer.concat([Buffer.from([0x60 + s.length]), Buffer.from(s)])40function createCredential(options) {41 const { publicKey } = crypto.generateKeyPairSync("ec", { namedCurve: "P-256" })42 const jwk = publicKey.export({ format: "jwk" })43 const id = crypto.randomBytes(16)44 const cose = Buffer.concat([Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21]), cborBytes(Buffer.from(jwk.x, "base64url")), Buffer.from([0x22]), cborBytes(Buffer.from(jwk.y, "base64url"))])45 const authData = Buffer.concat([crypto.createHash("sha256").update(options.rp.id).digest(), Buffer.from([0x5d]), Buffer.alloc(4), Buffer.alloc(16), Buffer.from([0, id.length]), id, cose])46 const attestationObject = Buffer.concat([Buffer.from([0xa3]), cborText("fmt"), cborText("none"), cborText("attStmt"), Buffer.from([0xa0]), cborText("authData"), cborBytes(authData)])47 const clientDataJSON = Buffer.from(JSON.stringify({ type: "webauthn.create", challenge: options.challenge, origin: ORIGIN, crossOrigin: false }))48 return { id: b64u(id), rawId: b64u(id), type: "public-key", clientExtensionResults: {}, authenticatorAttachment: "platform",49 response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ["internal"] } }50}5152async function call(method, url, body, bearer) {53 const headers = { "x-spmail-client": "native" }54 if (bearer) headers.authorization = `Bearer ${bearer}`55 if (body !== undefined) headers["content-type"] = "application/json"56 const r = await fetch(ORIGIN + url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })57 const j = await r.json().catch(() => ({}))58 if (!r.ok) throw new Error(`${method} ${url} → ${r.status} ${j.error ?? ""}`)59 return j60}61const load = () => (fs.existsSync(STATE) ? JSON.parse(fs.readFileSync(STATE, "utf8")) : null)62function save(s) {63 fs.mkdirSync(OUT, { recursive: true })64 fs.writeFileSync(STATE, JSON.stringify(s, null, 1), { mode: 0o600 })65 const sh = [`export SPMAIL_TEST_BASE_URL=${s.baseURL}`, `export SPMAIL_TEST_TOKEN=${s.token}`, `export SPMAIL_TEST_TOKEN_VICTIM=${s.victimToken}`,66 `export SPMAIL_TEST_MAILBOX_A=${s.mailboxes[0].id}`, `export SPMAIL_TEST_MAILBOX_B=${s.mailboxes[1].id}`,67 `export SPMAIL_TEST_ADDRESS_A=${s.mailboxes[0].address}`, `export SPMAIL_TEST_ADDRESS_B=${s.mailboxes[1].address}`, `export SPMAIL_TEST_ALIAS=${s.alias?.address ?? ""}`, ""].join("\n")68 fs.writeFileSync(path.join(OUT, "dev-env.sh"), sh, { mode: 0o600 })69}7071async function createPair(adminToken) {72 const run = crypto.randomBytes(3).toString("hex")73 const mailboxes = []74 for (const [k, name] of [["a", "Apple Essai A"], ["b", "Apple Essai B"]]) {75 const address = `apple-${k}-${run}@${DOMAIN}`76 const m = await call("POST", "/api/admin/mailboxes", { address, display_name: name }, adminToken)77 mailboxes.push({ id: m.id, address, name })78 }79 return mailboxes80}81// A sendable alias of mailbox A (sender identities). It lives on the mail server as an alias of that account: purging the mailbox removes it.82async function createAlias(adminToken, mailboxes) {83 const address = mailboxes[0].address.replace(/^apple-a-/, "apple-alias-")84 if (!/^apple-alias-[a-z0-9]+@stg\.spboucher\.ai$/.test(address)) throw new Error(`refusing alias ${address}`)85 const a = await call("POST", "/api/v1/aliases", { address, mailbox: mailboxes[0].address, display_name: "Apple Alias", signature_text: "Alias — signature d’essai" }, adminToken)86 return { id: a.id, address }87}88async function purgePair(s) {89 for (const m of s.mailboxes) {90 if (!/^apple-[a-z0-9-]+@stg\.spboucher\.ai$/.test(m.address)) throw new Error(`refusing to purge ${m.address}`)91 try { await call("DELETE", `/api/admin/mailboxes/${m.id}?purge=delete-all-mail`, undefined, s.adminToken); console.log("purged", m.address) }92 catch (e) { console.log("purge failed for", m.address, String(e.message)) }93 }94}9596const cmd = process.argv[2] ?? "up"97if (cmd === "up") {98 let s = load()99 if (!s) {100 const handle = "appledev"101 const link = cli("bootstrap").match(/#([A-Za-z0-9_-]{20,})/)?.[1]102 if (!link) throw new Error("no bootstrap link (an administrator already exists and Build/dev-env.json is gone: drop the database and start again)")103 const { challenge_id, options } = await call("POST", "/api/enroll/options", { token: link, handle, display_name: "Apple Dev" })104 const res = await call("POST", "/api/enroll/verify", { challenge_id, response: createCredential(options), client: { kind: "native", deviceName: "dev-bootstrap", platform: "node" } })105 s = { baseURL: ORIGIN, handle, adminToken: res.token, mailboxes: await createPair(res.token) }106 }107 if (!s.alias) s.alias = await createAlias(s.adminToken, s.mailboxes)108 s.token = cli("dev-token", s.handle).trim()109 s.victimToken = cli("dev-token", s.handle).trim()110 save(s)111 console.log(`ready: ${s.mailboxes.map((m) => m.address).join(", ")} — tokens written to Build/dev-env.{json,sh}`)112} else if (cmd === "fresh") {113 const s = load()114 if (!s) throw new Error("run `up` first")115 await purgePair(s)116 s.mailboxes = await createPair(s.adminToken)117 s.alias = await createAlias(s.adminToken, s.mailboxes)118 s.token = cli("dev-token", s.handle).trim()119 s.victimToken = cli("dev-token", s.handle).trim()120 save(s)121 console.log(`fresh pair: ${s.mailboxes.map((m) => m.address).join(", ")}`)122} else if (cmd === "token") {123 const s = load()124 if (!s) throw new Error("run `up` first")125 console.log(cli("dev-token", s.handle).trim())126} else if (cmd === "purge") {127 const s = load()128 if (!s) { console.log("nothing to purge"); process.exit(0) }129 await purgePair(s)130 fs.renameSync(STATE, STATE + ".purged")131 fs.rmSync(path.join(OUT, "dev-env.sh"), { force: true })132} else throw new Error("usage: dev-bootstrap.mjs up|fresh|token|purge")133