reconcile: machine auth for the scheduled sweep, across all owners
ci / lint-test (push) Successful in 46s

I built the auto-reconcile endpoint and then left nothing calling it —
exactly the gap I had criticised reconcilePendingOrders for. Found by
tracing the pipeline end to end rather than by anything failing.

PATCH now takes two callers. A person in the browser reconciles their own
queue via the session; the scheduled sweep has no session, carries the
machine token, and sweeps EVERY owner with a queue. That distinction is
load-bearing: 169 of the 177 rows outstanding belong to the second
participant, so a sweep scoped to the session user would leave almost all
of the queue untouched.

A wrong machine token does not fail the request outright — it falls
through to session auth, so the all-owner sweep stays gated while a
browser caller is unaffected. Verified live: 403 with a bad token and no
session, dry-run OK with the real one.

3 new tests. Two test-harness bugs fixed while adding them: the request
stub had no `headers` at all, and the statement helper reused one account
number, so two owners collided on uq_statement_identity rather than
modelling two real cards.
This commit is contained in:
2026-08-22 16:50:40 +10:00
parent 3d0d75519a
commit 9b59edcf48
2 changed files with 77 additions and 6 deletions
@@ -15,11 +15,18 @@ import { createPool, resetDB, seedParticipants, insertTransaction } from "./help
* purchase's row. So most of what follows is about refusal. * purchase's row. So most of what follows is about refusal.
*/ */
const MACHINE_TOKEN = "test-wallet-token";
let pool: Pool; let pool: Pool;
let ownerId: number; let ownerId: number;
let autoReconcile: typeof import("../../app/api/transactions/reconcile/route").PATCH; let autoReconcile: typeof import("../../app/api/transactions/reconcile/route").PATCH;
const userReq = (url = "http://x/api/transactions/reconcile") => ({ url }) as never; /** Browser-session caller: no machine token, auth comes from the mocked session. */
const userReq = (url = "http://x/api/transactions/reconcile") =>
({ url, headers: { get: () => null } }) as never;
/** Scheduled caller: machine token, no session, sweeps every owner. */
const machineReq = (url = "http://x/api/transactions/reconcile") =>
({ url, headers: { get: (h: string) => (h === "x-ingest-token" ? MACHINE_TOKEN : null) } }) as never;
async function statementLine( async function statementLine(
amount: number, amount: number,
@@ -29,9 +36,12 @@ async function statementLine(
) { ) {
const owner = opts.owner ?? ownerId; const owner = opts.owner ?? ownerId;
const st = await pool.query( const st = await pool.query(
// Account number varies by owner: uq_statement_identity is
// (bank_name, account_number, billing_end_date), so two owners sharing one
// account collide rather than modelling two real cards.
`INSERT INTO statements (filename, account_number, bank_name, billing_start_date, billing_end_date, owner_id) `INSERT INTO statements (filename, account_number, bank_name, billing_start_date, billing_end_date, owner_id)
VALUES ('s.pdf', '1234-5678-9012-3302', 'Test Bank', $1::date - 20, $1::date + 10, $2) RETURNING id`, VALUES ('s.pdf', $3, 'Test Bank', $1::date - 20, $1::date + 10, $2) RETURNING id`,
[date, owner] [date, owner, `1234-5678-9012-${String(owner).padStart(4, "0")}`]
); );
const t = await pool.query( const t = await pool.query(
`INSERT INTO transactions `INSERT INTO transactions
@@ -66,6 +76,7 @@ const reconciledWith = async (id: number) =>
.rows[0].reconciled_with_id as number | null; .rows[0].reconciled_with_id as number | null;
beforeAll(async () => { beforeAll(async () => {
process.env.WALLET_INGEST_TOKEN = MACHINE_TOKEN;
pool = createPool(); pool = createPool();
vi.doMock("@/lib/auth", () => ({ vi.doMock("@/lib/auth", () => ({
getCurrentUser: async () => ({ id: ownerId, name: "Alice", email: "alice@example.com" }), getCurrentUser: async () => ({ id: ownerId, name: "Alice", email: "alice@example.com" }),
@@ -216,3 +227,45 @@ describe("dry run", () => {
expect(await reconciledWith(manual)).toBeNull(); expect(await reconciledWith(manual)).toBeNull();
}); });
}); });
describe("the scheduled sweep", () => {
it("runs on the machine token with no session at all", async () => {
const manual = await walletRow(13.5, "2026-08-13");
const stmt = await statementLine(13.5, "2026-08-14", "BREADWORLD BAKERY");
const body = await (await autoReconcile(machineReq())).json();
expect(body.reconciled).toBe(1);
expect(await reconciledWith(manual)).toBe(stmt);
});
it("covers EVERY owner, not just one", async () => {
// 169 of the 177 rows outstanding belong to the second participant, so a
// sweep scoped to a single user would leave almost all of the queue alone.
const other = (await pool.query(
`INSERT INTO participants (name) VALUES ('Carol') RETURNING id`
)).rows[0].id as number;
const mine = await walletRow(11, "2026-08-13");
const theirTx = (await pool.query(
`INSERT INTO transactions (owner_id, statement_id, transaction_date, description,
amount, transaction_type, category, row_index)
VALUES ($1, NULL, '2026-08-13', 'Theirs', 22, 'debit', 'other', 0) RETURNING id`, [other]
)).rows[0].id as number;
await statementLine(11, "2026-08-14", "MINE");
await statementLine(22, "2026-08-14", "THEIRS", { owner: other });
const body = await (await autoReconcile(machineReq())).json();
expect(body.reconciled).toBe(2);
expect(await reconciledWith(mine)).not.toBeNull();
expect(await reconciledWith(theirTx)).not.toBeNull();
});
it("rejects a wrong machine token and falls through to session auth", async () => {
const bad = ({ url: "http://x/", headers: { get: () => "not-the-token" } }) as never;
// Session is mocked, so this still succeeds -- but as the session user only,
// proving the bad token did not grant the all-owner sweep.
const body = await (await autoReconcile(bad)).json();
expect(body.reconciled).toBe(0);
});
});
+19 -1
View File
@@ -51,11 +51,29 @@ export async function POST(req: NextRequest) {
* be run the first time after any change to the matching rule. * be run the first time after any change to the matching rule.
*/ */
export async function PATCH(req: NextRequest) { export async function PATCH(req: NextRequest) {
// Two callers, two auth modes. A person in the browser reconciles their own
// queue; the scheduled sweep has no session and carries the machine token,
// and must cover EVERY owner with a queue -- 169 of the 177 rows outstanding
// belong to the second participant, so a sweep scoped to one user would leave
// almost all of it untouched.
const machineToken = req.headers.get("x-ingest-token");
const machineOk = !!machineToken && machineToken === process.env.WALLET_INGEST_TOKEN;
let ownerIds: number[];
if (machineOk) {
ownerIds = (await queryRaw<{ owner_id: number }>(
`SELECT DISTINCT owner_id FROM transactions
WHERE statement_id IS NULL AND owner_id IS NOT NULL
AND reconciled_with_id IS NULL AND superseded_by_id IS NULL`
)).map((r) => r.owner_id);
} else {
const user = await getCurrentUser(req); const user = await getCurrentUser(req);
if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 }); if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
ownerIds = [user.id];
}
const dry = new URL(req.url).searchParams.get("dry") === "1"; const dry = new URL(req.url).searchParams.get("dry") === "1";
const matches = await findAutoMatches(user.id); const matches = (await Promise.all(ownerIds.map((id) => findAutoMatches(id)))).flat();
if (dry) { if (dry) {
return NextResponse.json({ dry_run: true, would_reconcile: matches.length, matches }); return NextResponse.json({ dry_run: true, would_reconcile: matches.length, matches });