From 3203a760bed34d400e53f2bf6b168242374fcac0 Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:24:50 +0800 Subject: [PATCH] fix(security): mask every string field at the log sink, not only named keys (#694) --- .../694-mask-log-identities.security.md | 1 + docs/architecture.md | 10 +- docs/deploy.md | 11 +- docs/security.md | 22 ++- scripts/outbox.mjs | 38 ++++- src/email/mailer.ts | 7 +- src/lib/log.ts | 62 ++++++- src/lib/redact.ts | 26 +++ src/lib/secrets.ts | 5 +- src/views/pages.ts | 23 +-- test/logMask.test.ts | 153 ++++++++++++++++++ test/mailerOutbox.test.ts | 70 ++++++++ 12 files changed, 391 insertions(+), 37 deletions(-) create mode 100644 changelog.d/694-mask-log-identities.security.md create mode 100644 test/logMask.test.ts create mode 100644 test/mailerOutbox.test.ts diff --git a/changelog.d/694-mask-log-identities.security.md b/changelog.d/694-mask-log-identities.security.md new file mode 100644 index 00000000..173fe5db --- /dev/null +++ b/changelog.d/694-mask-log-identities.security.md @@ -0,0 +1 @@ +Account identifiers no longer reach the log sink, and a development outbox file no longer carries the recipient in its name. A log line masks an email, a GitHub login, a user id, a token and an IP address in every string field — including fields the sink does not name and values nested inside an object or an array — while the stored job row and the job page keep the real value an operator needs; `npm run mail:outbox` expires every `.eml` older than `MAIL_OUTBOX_RETENTION_DAYS` (7 days by default) and then prints the newest one. diff --git a/docs/architecture.md b/docs/architecture.md index a4d1ec00..d8bfa187 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1295,7 +1295,15 @@ same pull request and work item; a review that already recorded a posted. `summary` is the job's progress line, written on every running heartbeat, not a post marker, so it does not block a retry; it and `error` pass through `src/lib/secrets.ts` before the row is written and again when the page renders -them (`docs/decisions/0015`). If a review posted its comments +them (`docs/decisions/0015`). + +Identifier masking is the other half and lives on the sink, not in `redact()`: +`src/lib/log.ts` masks an account identifier in every line it writes — by shape in +every string value, by field name for a login the shape cannot see, and through +nested objects and arrays — while the row, the inbox and the job page keep the +real value the operator acts on (#694). `maskEmail` and `maskIp` are in +`src/lib/redact.ts` and are imported back by `src/views/pages.ts`, so a page and a +log line cannot drift onto two masks. If a review posted its comments and then lost the terminal callback, nothing stored tells that apart from a review that never posted; that residual case is manual. `github`, `quota`, `credential` and `review` failures stay manual. diff --git a/docs/deploy.md b/docs/deploy.md index 427915c5..99114802 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -35,6 +35,7 @@ Key settings: | `MAIL_TRANSPORT` | `smtp` in production, `console` for a local demo | | `SMTP_HOST/PORT/SECURE/USER/PASS` | For yeah.net: `smtp.yeah.net`, 465, secure | | `MAIL_FROM` / `ADMIN_EMAIL` | `fledge@hugoxk.online` / `admin@example.com` | +| `MAIL_OUTBOX_RETENTION_DAYS` | Window for `npm run mail:outbox` to expire `$DATA_DIR/mail-outbox/*.eml`, in days; `7` by default | | `FEEDBACK_EMAIL` | Optional feedback/error-report destination; defaults to `ADMIN_EMAIL` | | `FLEDGE_LEAD_REPO_ID` | Repo connected to Fledge whose FlyBot Lead triages feedback | | `FLEDGE_LEAD_BRIDGE_URL/TOKEN/SESSION_ID` | Direct bridge target when the Fledge Lead is external | @@ -1117,9 +1118,13 @@ your nginx config), skip this file and let the distribution's nginx rotation own those paths — never rotate the same file from two stanzas. Development mail (`MAIL_TRANSPORT=console`) is written to -`$DATA_DIR/mail-outbox/*.eml` and is never pruned: it is a dev aid -(`npm run mail:outbox`), an instance with SMTP does not write it, and the -directory may be deleted at any time. +`$DATA_DIR/mail-outbox/*.eml`. It is a dev aid (`npm run mail:outbox`), and an +instance with SMTP does not write it. Each run of `npm run mail:outbox` first +deletes every `.eml` older than `MAIL_OUTBOX_RETENTION_DAYS` (7 by default) and +then prints the newest one, so the directory is never a store of account +identifiers: the file name is a stamp plus an opaque id, never the recipient, +and the address lives only inside the file. The directory may be deleted at any +time. ### Workspace snapshot retention diff --git a/docs/security.md b/docs/security.md index ff74a56e..e1a0377a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -912,8 +912,28 @@ and settings do not offer a disabled provider as an allowlist entry. `redact()` removes GitHub tokens, `sk-…` keys, `flg_…` tokens, bearer values and Upstream `api_key:` hashes from log messages. Request bodies are never logged. + +The log sink (`src/lib/log.ts`) additionally masks **account identifiers**, which +are not secrets and which `redact()` deliberately leaves alone: an email becomes +`a***@example.com`, a GitHub login or a `usr_` id keeps its first character, and +an address loses its last IPv4 octet. Every string field value goes through the +shape pass — an email or a `usr_` id is masked wherever it appears, including in +a field whose name the sink does not know — and nested objects and arrays are +walked rather than copied, so `{ user: { email } }` cannot carry the address +through. Names still add what shape cannot see: a login has no shape, so the key +table (`email`, `to`, `login`, `user`, `userId`, `ip`, `admin`, …) masks those +values by name, and a `repo`/`repository` field keeps the repository name while +masking the `owner/` login in front of it. The mask lives in the sink, never in +`redact()`: the stored job row, the inbox and the job page still carry the real +identifier an operator has to act on, and that difference is asserted in +`test/logMask.test.ts`. A post-hoc rewrite of `fledge.log` is not a policy; the +identifier must not be written in the first place. + The development mail outbox is written with mode 0600 and contains approval links; -treat it as a secret. +treat it as a secret. A file is named `-.eml`, never the +recipient, so the name alone keeps no account alive, and `npm run mail:outbox` +expires every `.eml` older than `MAIL_OUTBOX_RETENTION_DAYS` (7 by default) +before it prints the newest one. The evolution export uses a read-only database handle and passes every exported string through the same `redact()` before serialisation. It reads only diff --git a/scripts/outbox.mjs b/scripts/outbox.mjs index 2cb3a145..5da9356b 100644 --- a/scripts/outbox.mjs +++ b/scripts/outbox.mjs @@ -1,12 +1,44 @@ #!/usr/bin/env node -// Print the newest development email and any approval links it contains. -import { readdirSync, readFileSync } from 'node:fs' +// Print the newest development email and any approval links it contains, and +// expire the ones past the retention window. +// +// #694: the file name carries a stamp and an opaque id, never the recipient, so +// the window below can delete every `.eml` in the directory without keeping one +// account identifier alive forever. Deletion is by mtime, takes no exception, +// and happens before the newest file is read. +// +// DATA_DIR=./data npm run mail:outbox +// MAIL_OUTBOX_RETENTION_DAYS=14 npm run mail:outbox # 7 by default +import { readdirSync, readFileSync, statSync, unlinkSync } from 'node:fs' import { join } from 'node:path' +const DAY_MS = 86_400_000 + +function retentionDays() { + const raw = String(process.env.MAIL_OUTBOX_RETENTION_DAYS ?? '7').trim() + const days = Number(raw) + if (raw === '' || !Number.isFinite(days) || days < 0) { + console.error(`MAIL_OUTBOX_RETENTION_DAYS must be a non-negative number of days, got "${raw}".`) + process.exit(1) + } + return days +} + const dir = join(process.env.DATA_DIR ?? './data', 'mail-outbox') +const cutoff = Date.now() - retentionDays() * DAY_MS let files = [] try { - files = readdirSync(dir).filter((name) => name.endsWith('.eml')).sort() + for (const name of readdirSync(dir)) { + if (!name.endsWith('.eml')) continue + const path = join(dir, name) + if (statSync(path).mtimeMs < cutoff) { + unlinkSync(path) + console.log(`expired ${name}`) + continue + } + files.push(name) + } + files.sort() } catch { console.error(`No outbox at ${dir}. Start with MAIL_TRANSPORT=console and log in once.`) process.exit(1) diff --git a/src/email/mailer.ts b/src/email/mailer.ts index af8cee0c..cd1f45a6 100644 --- a/src/email/mailer.ts +++ b/src/email/mailer.ts @@ -1,3 +1,4 @@ +import { randomUUID } from 'node:crypto' import { mkdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import nodemailer, { type Transporter } from 'nodemailer' @@ -26,7 +27,11 @@ export class ConsoleMailer implements Mailer { async send(message: MailMessage): Promise { mkdirSync(this.outbox, { recursive: true }) const stamp = new Date().toISOString().replace(/[:.]/g, '-') - const file = join(this.outbox, `${stamp}-${message.to.replace(/[^a-z0-9@._-]/gi, '_')}.eml`) + // #694: the name is not the recipient. An addressed name means "keep the + // newest file" keeps one identifier forever, so no retention window could + // ever delete the whole directory. The stamp keeps the lexical order + // `scripts/outbox.mjs` reads, and the address stays inside the file. + const file = join(this.outbox, `${stamp}-${randomUUID().slice(0, 8)}.eml`) const body = [ `Date: ${new Date().toUTCString()}`, `From: Fledge <${this.from}>`, diff --git a/src/lib/log.ts b/src/lib/log.ts index 6943ad02..cc397f7b 100644 --- a/src/lib/log.ts +++ b/src/lib/log.ts @@ -1,15 +1,67 @@ -import { redact } from './secrets.js' +import { maskEmail, maskIp, redact } from './secrets.js' export type Level = 'debug' | 'info' | 'warn' | 'error' export type LogFields = Record +// #694: a log line outlives the account it names — it is rotated, shipped and +// read long after a purge — so the sink is the one surface that never carries an +// account identifier. The row, the inbox and the job page keep the real value +// (masking lives here, not in `redact()`, which cleans what is stored and shown). +// Fields are decided by name because a login and a `usr_` id have no shape; text +// is decided by shape because a call site can glue one into a sentence. +const EMAIL_KEY = /^(?:admin|admin_?email|e-?mail|feedback_?email|from|recipient|reply_?to|to)$/i +const LOGIN_KEY = /^(?:account|login|user|user_?name)$/i +const ID_KEY = /^(?:account_?id|user_?id)$/i +const IP_KEY = /^(?:client_?ip|ip|ip_?address|remote_?addr|remote_?ip)$/i +// A repository field is `owner/name`: the owner is a GitHub login and is masked, +// the repository name is not an account and is kept so a line still says which +// repo it is about. Left out of the table, `owner/name` passed through whole. +const REPO_KEY = /^(?:repos?|repository|repo_?name)$/i + +const EMAIL_SHAPE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g +const USER_ID_SHAPE = /\busr_[A-Za-z0-9]{3,}\b/g +const IPV4_SHAPE = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g + +function maskName(value: string): string { + return value === '' ? '' : `${value.slice(0, 1)}***` +} + +function maskText(text: string): string { + return text.replace(EMAIL_SHAPE, maskEmail).replace(USER_ID_SHAPE, 'usr_***').replace(IPV4_SHAPE, maskIp) +} + +function maskField(key: string, value: string): string { + if (EMAIL_KEY.test(key)) return value.includes('@') ? maskEmail(value) : maskName(value) + if (LOGIN_KEY.test(key) || ID_KEY.test(key)) return maskName(value) + if (IP_KEY.test(key)) return maskIp(value) + if (REPO_KEY.test(key)) return value.replace(/^([^/]+)\//, (_match, owner: string) => `${maskName(owner)}/`) + return value +} + +// The key table is an optimisation, not the contract: a field the table does not +// name is still a string on its way to a sink that promises no account +// identifier, so the shape pass runs over every value (#694 review). An email +// glued into an unlisted field, a nested `{ user: { email } }` or an array of +// logins therefore cannot slip through just because a call site invented a key. +function maskValue(key: string, value: unknown, seen: WeakSet): unknown { + if (typeof value === 'string') return redact(maskText(maskField(key, value))) + if (value === null || typeof value !== 'object') return value + if (seen.has(value)) return '[circular]' + seen.add(value) + if (Array.isArray(value)) return value.map((item) => maskValue(key, item, seen)) + const nested: Record = {} + for (const [nestedKey, nestedValue] of Object.entries(value)) { + nested[nestedKey] = maskValue(nestedKey, nestedValue, seen) + } + return nested +} + function write(level: Level, message: string, fields?: LogFields): void { - const line: Record = { ts: new Date().toISOString(), level, msg: redact(message) } + const line: Record = { ts: new Date().toISOString(), level, msg: redact(maskText(message)) } if (fields !== undefined) { - for (const [key, value] of Object.entries(fields)) { - line[key] = typeof value === 'string' ? redact(value) : value - } + const seen = new WeakSet() + for (const [key, value] of Object.entries(fields)) line[key] = maskValue(key, value, seen) } const output = JSON.stringify(line) if (level === 'error') process.stderr.write(`${output}\n`) diff --git a/src/lib/redact.ts b/src/lib/redact.ts index 45e5c9d8..163520a9 100644 --- a/src/lib/redact.ts +++ b/src/lib/redact.ts @@ -1,3 +1,29 @@ +// #694: an account identifier is not a secret, so `redact()` leaves it alone — a +// job row, the inbox and the job page keep the real address because that is where +// an operator acts on it. These two helpers exist for the surfaces that must not +// carry it: the log sink and the session/list pages. One function per shape, so a +// page and a log line cannot drift onto different masks. +export function maskEmail(email: string): string { + const at = email.lastIndexOf('@') + if (at <= 0) return '***' + const local = email.slice(0, at) + const domain = email.slice(at + 1) + return `${local.slice(0, 1)}***@${domain}` +} + +// #356: a session row is recognisable without handing out the address. The last +// IPv4 octet and everything past the second IPv6 group are dropped, so a user can +// tell their own sessions apart but the page never carries a full address. +export function maskIp(ip: string | null): string { + if (ip === null || ip === '') return '—' + if (ip.includes(':')) { + const groups = ip.split(':').filter((group) => group !== '') + return `${groups.slice(0, 2).join(':')}::` + } + const parts = ip.split('.') + return parts.length === 4 ? `${parts[0]}.${parts[1]}.${parts[2]}.0` : ip +} + // Configured secrets (an SMTP password, a model key) have no shape a pattern can // recognise, so the config registers its literal values here. The set is // replaced per call, not appended: tests call loadConfig() repeatedly, and diff --git a/src/lib/secrets.ts b/src/lib/secrets.ts index 1e396d98..6e0984ff 100644 --- a/src/lib/secrets.ts +++ b/src/lib/secrets.ts @@ -4,7 +4,10 @@ const VERSION = 'v1' // The recogniser lives in one module so a job log, a callback and a URL cannot // drift onto different rules. This re-export keeps the existing import path. -export { redact, registerRedactionSecrets } from './redact.js' +// `maskEmail` / `maskIp` (#694) are shapes an account is rendered by, not +// secrets, so they live beside `redact()` and are re-exported here too: the log +// sink and the pages import from one place. +export { maskEmail, maskIp, redact, registerRedactionSecrets } from './redact.js' export function decodeKey(keyBase64: string): Buffer { const key = Buffer.from(keyBase64, 'base64') diff --git a/src/views/pages.ts b/src/views/pages.ts index 4acc3fe4..4b1707c2 100644 --- a/src/views/pages.ts +++ b/src/views/pages.ts @@ -15,7 +15,7 @@ import { DECISION_KINDS, DEFAULT_DECISION, decisionKindLabel } from '../lib/task import { ITERATION_INTERVALS, REVIEW_INTERVALS, intervalLabel, normalizeInterval } from '../lib/intervals.js' import { escapeHtml, FLEDGE_GITHUB_URL, layout, money, quotaMoney, starIcon, type PageNotification, type Viewer } from './layout.js' import { renderState, stateCell, type StateAction } from './states.js' -import { redact } from '../lib/secrets.js' +import { maskEmail, maskIp, redact } from '../lib/secrets.js' import { REVIEW_INSTRUCTION_LABEL, reviewInstructionFromGoal } from '../lib/followUpInstruction.js' import { isTemporalStatus, summariseDelta, type TemporalDelta } from '../lib/temporal.js' import { firstRunOutcome, setupChecklist, type SetupState, type SetupStepKey } from './checklist.js' @@ -258,27 +258,6 @@ function readinessBadge(t: Translate, state: 'ready' | 'blocked' | 'unknown'): s return `${escapeHtml(readinessLabel(t, state))}` } -function maskEmail(email: string): string { - const at = email.lastIndexOf('@') - if (at <= 0) return '***' - const local = email.slice(0, at) - const domain = email.slice(at + 1) - return `${local.slice(0, 1)}***@${domain}` -} - -// #356: a session row is recognisable without handing out the address. The last -// IPv4 octet and everything past the second IPv6 group are dropped, so a user can -// tell their own sessions apart but the page never carries a full address. -function maskIp(ip: string | null): string { - if (ip === null || ip === '') return '—' - if (ip.includes(':')) { - const groups = ip.split(':').filter((group) => group !== '') - return `${groups.slice(0, 2).join(':')}::` - } - const parts = ip.split('.') - return parts.length === 4 ? `${parts[0]}.${parts[1]}.${parts[2]}.0` : ip -} - function agreementHtml(text: string): string { return text .split(/\n\n/) diff --git a/test/logMask.test.ts b/test/logMask.test.ts new file mode 100644 index 00000000..6805a39f --- /dev/null +++ b/test/logMask.test.ts @@ -0,0 +1,153 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { log } from '../src/lib/log.js' +import { redact } from '../src/lib/secrets.js' + +// #694: an account identifier must not reach a log sink, but it has to stay in +// the row and on the page, because that is where an operator acts on it. The two +// surfaces are therefore deliberately different and both are asserted here: the +// sink masks, `redact()` — which cleans what is stored and shown — does not grow +// a second job. +function captureLog(): { text: () => string; restore: () => void } { + let captured = '' + const stdout = process.stdout.write + const stderr = process.stderr.write + const tap = (write: typeof process.stdout.write): typeof process.stdout.write => + ((chunk: string | Uint8Array, ...rest: unknown[]) => { + captured += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8') + return (write as unknown as (value: string | Uint8Array, ...args: unknown[]) => boolean)(chunk, ...rest) + }) as unknown as typeof process.stdout.write + process.stdout.write = tap(stdout.bind(process.stdout)) + process.stderr.write = tap(stderr.bind(process.stderr)) + return { + text: () => captured, + restore: () => { + process.stdout.write = stdout + process.stderr.write = stderr + }, + } +} + +const TOKEN = `ghp_${'a1B2c3D4e5'.repeat(3)}` + +test('the log sink masks an email, a login, a user id and a token in every field', () => { + const capture = captureLog() + try { + log.info('sign-in for alice@example.com', { + email: 'alice@example.com', + login: 'alicegh', + userId: 'usr_abc123', + token: TOKEN, + }) + } finally { + capture.restore() + } + const output = capture.text() + for (const raw of ['alice@example.com', 'alicegh', 'usr_abc123', TOKEN]) { + assert.ok(!output.includes(raw), `sink still carries ${raw}: ${output}`) + } + // Masked, not blanked: the operator can still tell two accounts apart. + assert.match(output, /a\*\*\*@example\.com/) + assert.match(output, /\[redacted-github-token\]/) +}) + +test('the log sink masks an email and a user id inside the message text', () => { + const capture = captureLog() + try { + log.info('owner alice@example.com removed account usr_abc123 from the repo') + } finally { + capture.restore() + } + const output = capture.text() + assert.ok(!output.includes('alice@example.com'), output) + assert.ok(!output.includes('usr_abc123'), output) + assert.match(output, /a\*\*\*@example\.com/) +}) + +test('the log sink masks an address but leaves a job id and a repo id alone', () => { + const capture = captureLog() + try { + log.info('job finished', { jobId: 'job_01HXY', repoId: 'repo_42', ip: '203.0.113.7' }) + } finally { + capture.restore() + } + const output = capture.text() + assert.match(output, /job_01HXY/) + assert.match(output, /repo_42/) + assert.ok(!output.includes('203.0.113.7'), output) + assert.match(output, /203\.0\.113\.0/) +}) + +test('what is stored and shown keeps the real identifier: redact() does not mask it', () => { + // The row writer and the page read through `redact()`; masking there would + // blank the account in the inbox, the job page and the stored row (#694). + assert.equal(redact('alice@example.com'), 'alice@example.com') +}) + +// #694 review: the key table is an optimisation, not the contract. These four +// cases are the ones the first tip missed — an unlisted key, a nested object, an +// array and the live approval line — and each fails on the pre-review sink +// because it decided a string only by its key. +test('an unlisted field is masked by the shape of its value', () => { + const capture = captureLog() + try { + log.info('approval requested', { user: 'alicegh', admin: 'root-admin@example.com' }) + log.info('owner removed', { note: 'contact alice@example.com about usr_abc123' }) + } finally { + capture.restore() + } + const output = capture.text() + for (const raw of ['root-admin@example.com', 'alice@example.com', 'usr_abc123', 'alicegh']) { + assert.ok(!output.includes(raw), `sink still carries ${raw}: ${output}`) + } + assert.match(output, /r\*\*\*@example\.com/) + assert.match(output, /"user":"a\*\*\*"/) +}) + +test('a nested object and an array cannot carry an identifier past the sink', () => { + const capture = captureLog() + try { + log.info('account touched', { + user: { email: 'alice@example.com', login: 'alicegh', id: 'usr_abc123' }, + repos: ['alicegh/fledge', 'bob/flybot'], + meta: { contact: { to: 'bob@example.com' } }, + }) + } finally { + capture.restore() + } + const output = capture.text() + for (const raw of ['alice@example.com', 'alicegh', 'bob/flybot', 'bob@example.com', 'usr_abc123']) { + assert.ok(!output.includes(raw), `sink still carries ${raw}: ${output}`) + } + assert.match(output, /a\*\*\*@example\.com/) + assert.match(output, /a\*\*\*\/fledge/) +}) + +test('a repository field keeps the name and masks the owner login', () => { + const capture = captureLog() + try { + log.info('job finished', { repo: 'alicegh/fledge', repository: 'bob/flybot', repoId: 'repo_42' }) + } finally { + capture.restore() + } + const output = capture.text() + assert.ok(!output.includes('alicegh'), output) + assert.ok(!output.includes('bob/flybot'), output) + assert.match(output, /a\*\*\*\/fledge/) + assert.match(output, /b\*\*\*\/flybot/) + assert.match(output, /repo_42/, 'a repository id is not an account identifier') +}) + +test('a cyclic field is cut, not thrown', () => { + const capture = captureLog() + const cyclic: Record = { email: 'alice@example.com' } + cyclic.self = cyclic + try { + log.info('cycle', { user: cyclic }) + } finally { + capture.restore() + } + const output = capture.text() + assert.ok(!output.includes('alice@example.com'), output) + assert.match(output, /"self":"\[circular\]"/) +}) diff --git a/test/mailerOutbox.test.ts b/test/mailerOutbox.test.ts new file mode 100644 index 00000000..d89af38b --- /dev/null +++ b/test/mailerOutbox.test.ts @@ -0,0 +1,70 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { spawnSync } from 'node:child_process' +import { ConsoleMailer } from '../src/email/mailer.js' + +// #694: an outbox file used to be named `-
.eml`, so "keep the +// newest file" kept one identifier alive forever and no retention window could +// delete everything. The name is opaque now, which is what makes a window safe. +// The address still lives inside the file (that is what a dev reads); only the +// name and the sink are clean. +const DAY_MS = 86_400_000 + +function outboxDir(): { root: string; dir: string } { + const root = mkdtempSync(join(tmpdir(), 'fledge-outbox-')) + return { root, dir: join(root, 'mail-outbox') } +} + +function names(dir: string): string[] { + return readdirSync(dir).sort() +} + +test('the console mailer names the file without the recipient and keeps the address in the body', async () => { + const { root, dir } = outboxDir() + try { + await new ConsoleMailer(dir).send({ + to: 'alice@example.com', + subject: 'Approve repo', + text: 'Open https://fledge.test/approve/tok_ABC123 to approve.', + }) + const written = names(dir) + assert.equal(written.length, 1) + const [name] = written + assert.ok(name !== undefined) + assert.match(name, /^\d{4}-.*\.eml$/) + assert.ok(!name.includes('@'), `name carries the address: ${name}`) + const body = readFileSync(join(dir, name), 'utf8') + assert.match(body, /^To: alice@example\.com$/m) + } finally { + rmSync(root, { recursive: true, force: true }) + } +}) + +test('mail:outbox removes an .eml past the window, keeps a recent one and prints the newest', () => { + const { root, dir } = outboxDir() + mkdirSync(dir, { recursive: true }) + try { + const old = join(dir, '2026-01-01T00-00-00-000Z-aaaaaa.eml') + const recent = join(dir, '2026-11-16T00-00-00-000Z-bbbbbb.eml') + writeFileSync(old, 'Subject: Old\r\n\r\nold\r\n') + writeFileSync(recent, 'Subject: New\r\n\r\nhttps://fledge.test/approve/tok_ABC123\r\n') + const past = new Date(Date.now() - 30 * DAY_MS) + utimesSync(old, past, past) + + const run = spawnSync(process.execPath, ['scripts/outbox.mjs'], { + env: { ...process.env, DATA_DIR: root, MAIL_OUTBOX_RETENTION_DAYS: '7' }, + encoding: 'utf8', + }) + assert.equal(run.status, 0, run.stderr) + const remaining = names(dir) + assert.deepEqual(remaining, ['2026-11-16T00-00-00-000Z-bbbbbb.eml']) + assert.ok(!remaining.some((name) => name.includes('@')), remaining.join(',')) + assert.match(run.stdout, /2026-11-16T00-00-00-000Z-bbbbbb\.eml/) + assert.match(run.stdout, /https:\/\/fledge\.test\/approve\/tok_ABC123/) + } finally { + rmSync(root, { recursive: true, force: true }) + } +})