Files
redefined-designs/backend/src/mailer.ts
T
bermudalamb f32913ef51
Linting / lint (pull_request) Successful in 1m57s
SonarQube Analysis / sonarqube (pull_request) Failing after 5m3s
refactor: turn on noUncheckedIndexedAccess in both workspaces (#101)
Indexing an array now yields `T | undefined`, which is what it always did — the compiler simply says so. Enabled in backend/tsconfig.json and frontend/tsconfig.json, and in tsconfig.sonar.json alongside it so the drift guard stays satisfied.

The sequencing this issue insisted on was right, and the numbers show why. Before #159 typed the query results, `rows[0]` was `any` and `any` indexes to `any`: the flag would have found close to nothing and the count would have changed completely afterwards. With the rows typed it finds 57 — 50 in the backend, 4 in the frontend, 3 in the Playwright suite — and they fall into three kinds.

Thirty are `rows[0]` after a `rows.length` guard. TypeScript cannot connect the two, and rewriting them as `const [row] = rows; if (!row) …` makes the guard and the use the same check, which is better code independently of the flag.

Ten are rows a statement guarantees — `INSERT … RETURNING`, or a lookup for an id the session middleware has already matched. These get `requireRow(rows, what)`, a new helper in db.ts that throws naming the query. A thrown error rather than a non-null assertion: if the assumption is ever wrong, an assertion hands `undefined` to the next line and fails somewhere unrelated, whereas this fails at the query and says which. asyncRoute turns it into a 500, which is the right answer for "the database did not do what the statement says it does". It also states the assumption once instead of ten times.

The rest is ordinary indexing the compiler cannot prove: a regex capture group that the pattern guarantees, `split('+')[0]`, a modulo kept in range, `hasOwnProperty` failing to narrow an index signature, and Express typing route params as an index signature so `req.params.itemId` is `string | undefined` on a route that cannot match without it.

One correction to this issue's premise, which matters for what it was expected to find. The body says "in a handful it does not guard at all", and the unguarded-500 risk it describes was not found. Every `rows[0]` either sits behind a length check or behind a statement that guarantees a row. What the flag actually bought was the ten places where that guarantee was real but unstated, and those now say so.

Two changes worth calling out because they are not mechanical. TAG_COLORS is typed `[string, ...string[]]` in both copies rather than `as const` — the first attempt used `as const`, which narrowed the elements to literals and broke adminTags, so the annotation keeps `string` while telling the compiler index 0 exists. And the filter drawer's slider falls back to the bounds it was given rather than to null, because null there reads as "no filter" and would widen the results rather than leave them unchanged.

Test files needed changes too, since ts-jest compiles them against the same config: a regex destructure in the compose guard, and ten `mock.calls[0][0]` reads where the surrounding assertions already establish the call happened.

Verified: tsc clean over backend, frontend src and the Playwright suite; unit 254/254; integration 238/238; frontend build clean; lint unchanged in both workspaces.

Closes #101
2026-08-24 15:25:09 -05:00

114 lines
4.1 KiB
TypeScript
Executable File

import nodemailer from 'nodemailer';
// Defaults written for Gmail. An environment on a different provider — QA is on
// Brevo — has to set host, port and SMTP_SECURE explicitly rather than
// inheriting these, and getting that wrong fails at send time rather than at
// boot. See #64 on validating this at startup instead.
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST || 'smtp.gmail.com',
port: parseInt(process.env.SMTP_PORT || '465', 10),
secure: process.env.SMTP_SECURE !== 'false',
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASSWORD
}
});
interface ParsedAddress {
local: string;
domain: string;
}
// Lowercased, and with any `+suffix` removed from the local part. Returns null
// for anything that is not a usable address, so a caller can refuse rather than
// compare nonsense.
function parseAddress(address: string): ParsedAddress | null {
const trimmed = address.trim().toLowerCase();
const at = trimmed.lastIndexOf('@');
// Needs something on both sides of a single trailing @.
if (at <= 0 || at === trimmed.length - 1) {
return null;
}
const localWithSuffix = trimmed.slice(0, at);
return {
// split always yields at least one element, so this cannot actually be
// undefined — but String.split's type cannot express that.
local: localWithSuffix.split('+')[0] ?? localWithSuffix,
domain: trimmed.slice(at + 1)
};
}
/**
* Whether this environment is permitted to email this recipient.
*
* `allowlist` is the raw MAIL_ALLOWLIST value: a comma-separated list where an
* entry is either a full address, which also covers its `+suffix` variants, or
* `@domain`, which covers every mailbox there.
*
* Undefined means unrestricted, which is production — it must be able to mail
* real customers. Present but empty means refuse everyone: someone writing
* `MAIL_ALLOWLIST=` is expressing an intent to restrict, and reading that as
* "no restriction" would turn a typo into an outbound mail incident.
*
* Comparison is by exact equality on both halves, never a suffix test, so a
* lookalike domain ending in an allowed one does not get through.
*
* Exported for its unit test. This function is the entire safety property of
* mail in a non-production environment, and it is pure, so it is worth testing
* directly rather than through a send.
*/
export function isAllowedRecipient(to: string, allowlist: string | undefined): boolean {
if (allowlist === undefined) {
return true;
}
const entries = allowlist
.split(',')
.map((entry) => entry.trim().toLowerCase())
.filter((entry) => entry !== '');
if (entries.length === 0) {
return false;
}
const recipient = parseAddress(to);
if (!recipient) {
return false;
}
return entries.some((entry) => {
if (entry.startsWith('@')) {
return recipient.domain === entry.slice(1);
}
const allowed = parseAddress(entry);
return allowed !== null && allowed.local === recipient.local && allowed.domain === recipient.domain;
});
}
export async function sendMail(to: string, subject: string, html: string): Promise<void> {
if (!process.env.SMTP_USER || !process.env.SMTP_PASSWORD) {
console.warn(`SMTP not configured — skipping email to ${to}: "${subject}"`);
return;
}
// Guarded here rather than at the four call sites, so every sender is covered
// by construction and a fifth added later cannot bypass it by forgetting.
//
// Skipping rather than throwing, and returning as though it sent: three of
// the callers already swallow send failures into a log, so throwing would
// mostly be caught and logged anyway while risking a 500 on the signup path.
// The flow under test finishes, and the log says why no mail arrived — which
// is the part that was missing when QA was simply muted.
if (!isAllowedRecipient(to, process.env.MAIL_ALLOWLIST)) {
console.warn(`[mail-blocked] ${to} is not on MAIL_ALLOWLIST — skipping "${subject}"`);
return;
}
await transporter.sendMail({
from: process.env.SMTP_FROM || process.env.SMTP_USER,
to,
subject,
html
});
}