fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate

Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and
+/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding
(rule 22 extension) — the program-wide fail-safe for any caller that still
passes an unguarded Number(untrusted) into a converted statement.

PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing
that: verifyTripAccess parses once with toRowId and threads the parsed id
through create/import/bulk/rating/export.gpx (deleting the seven
toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard.
DaysService gets the same treatment across list/create/getDay/reorder/
insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id
could renumber a real trip's days while the raw-bind inverted-accommodation
guard silently matched nothing.

DatabaseService.getTripTitle is deleted; PlacesService injects
TripsRepository directly and calls getTitle itself.

Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses
$castTo instead of an unknown bridge; the duplicated TagRow interface in
Places.repository.ts is now imported from Tags.repository.ts;
AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of
restating its columns; PlaceShadowPicksRepository.totals drops its
unreachable ??-fallback branch; Places.repository.ts's updatePlace types
the NOT NULL name column as string; trip-members.service.ts's
transferOwnership threads one parsed trip id through all three writes and
corrects two stale "raw-bind seam" docstrings that were actually Number()
seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts.

Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed
(lint back to 2416); HTTP and WS regression coverage for the non-finite
and non-canonical id shapes across places/days routes, mutation-proved;
TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of
>= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's
measured transaction-yield/dirty-read/nested-BEGIN behaviour.
This commit is contained in:
jubnl
2026-09-23 12:22:36 +02:00
parent 46a3246e82
commit 175eb3b11b
25 changed files with 996 additions and 205 deletions
+130 -1
View File
@@ -28,7 +28,7 @@ vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.
import { db as testDb } from '../../src/db/database';
import { buildApp } from '../../src/bootstrap';
import { resetTestDb, resetRateLimits } from '../helpers/test-db';
import { createUser, createTrip, createDay, createPlace, addTripMember } from '../helpers/factories';
import { createUser, createTrip, createDay, createPlace, addTripMember, createDayAccommodation, createReservation } from '../helpers/factories';
import { authCookie } from '../helpers/auth';
let nestApp: INestApplication;
@@ -535,3 +535,132 @@ describe('Accommodations', () => {
expect(budgetAfter).toBeUndefined();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plan 3c Task 9 fix wave — A-H2 (live regression): `DaysService` was
// converted with a bare `Number(tripId)` at every entry point while
// `restampReservationDates`/`assertNoInvertedAccommodation` (Plan 3d
// survivors) kept binding the RAW route string — an affinity seam a
// hex-spelled trip id never matches. `TripAccessGuard` authorises a
// hex-spelled id whose `Number()` value is a real trip (`Number('0x12')`
// is `18`), so one `PUT .../days/reorder` request could renumber that real
// trip's days (the `Number()` half) while its own inverted-accommodation
// guard silently matched zero rows (the raw-string half) — writing a stay
// whose end precedes its start with no error. Every entry point now parses
// ONCE with `toRowId` and threads that value into every survivor; a
// `toRowId` miss answers a legacy-shaped not-found instead of letting the
// guard's wider `Number()` grant reach a downstream raw bind that disagrees
// with it.
// ─────────────────────────────────────────────────────────────────────────────
describe('A-H2 — DaysService trip id parsed once, threaded to every survivor (Task 9 fix wave)', () => {
it('GET /days by the hex-spelled trip id answers the legacy-shaped miss ({ days: [] }), not the real trip\'s days', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip', start_date: '2026-09-01', end_date: '2026-09-03' });
const hexTripId = '0x' + trip.id.toString(16);
const res = await request(app)
.get(`/api/trips/${hexTripId}/days`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(200);
expect(res.body).toEqual({ days: [] });
});
it('PUT /days/:id by the hex-spelled trip id 404s "Day not found" (getDay\'s own toRowId gate), not the real trip\'s day', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
const day = createDay(testDb, trip.id, { title: 'Original' });
const hexTripId = '0x' + trip.id.toString(16);
const res = await request(app)
.put(`/api/trips/${hexTripId}/days/${day.id}`)
.set('Cookie', authCookie(user.id))
.send({ title: 'Renamed' });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Day not found' });
const row = testDb.prepare('SELECT title FROM days WHERE id = ?').get(day.id) as { title: string };
expect(row.title).toBe('Original');
});
it('POST /days by the hex-spelled trip id (append, no position) 500s the legacy-shaped miss and writes no day', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip' });
const hexTripId = '0x' + trip.id.toString(16);
const before = (testDb.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(trip.id) as { n: number }).n;
const res = await request(app)
.post(`/api/trips/${hexTripId}/days`)
.set('Cookie', authCookie(user.id))
.send({});
expect(res.status).toBe(500);
expect(res.body).toEqual({ error: 'Internal server error' });
const after = (testDb.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(trip.id) as { n: number }).n;
expect(after).toBe(before);
});
it('POST /days {position} (insert) by the hex-spelled trip id 500s the legacy-shaped miss and writes no day', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip', start_date: '2026-09-01', end_date: '2026-09-02' });
const hexTripId = '0x' + trip.id.toString(16);
const before = (testDb.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(trip.id) as { n: number }).n;
const res = await request(app)
.post(`/api/trips/${hexTripId}/days`)
.set('Cookie', authCookie(user.id))
.send({ position: 1 });
expect(res.status).toBe(500);
expect(res.body).toEqual({ error: 'Internal server error' });
const after = (testDb.prepare('SELECT COUNT(*) AS n FROM days WHERE trip_id = ?').get(trip.id) as { n: number }).n;
expect(after).toBe(before);
});
it('PUT /days/reorder by the hex-spelled trip id 400s "orderedIds must be a permutation…" and writes NOTHING — the live H2 bug: it used to 200 and invert a real accommodation', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip', start_date: '2026-06-01', end_date: '2026-06-03' });
const days = testDb.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number; day_number: number; date: string }[];
expect(days).toHaveLength(3);
const [d1, d2, d3] = days;
const place = createPlace(testDb, trip.id, { name: 'Hotel' });
// A valid (non-inverted) stay d1 -> d2, and a reservation on d1 — exactly
// the shape the compiled-boot evidence used to catch reorder inverting.
const stay = createDayAccommodation(testDb, trip.id, place.id, d1.id, d2.id);
const reservation = createReservation(testDb, trip.id, { day_id: d1.id, title: 'Dinner' });
testDb.prepare('UPDATE reservations SET reservation_time = ? WHERE id = ?').run('2026-06-01T19:00:00', reservation.id);
const hexTripId = '0x' + trip.id.toString(16);
const res = await request(app)
.put(`/api/trips/${hexTripId}/days/reorder`)
.set('Cookie', authCookie(user.id))
.send({ orderedIds: [d2.id, d1.id, d3.id] });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'orderedIds must be a permutation of the trip day ids.' });
// Nothing renumbered.
const after = testDb.prepare('SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number; day_number: number; date: string }[];
expect(after).toEqual(days);
// The stay is still d1 -> d2, never inverted.
const stayAfter = testDb.prepare('SELECT start_day_id, end_day_id FROM day_accommodations WHERE id = ?').get(stay.id) as { start_day_id: number; end_day_id: number };
expect(stayAfter).toEqual({ start_day_id: d1.id, end_day_id: d2.id });
// The reservation's stamped time is untouched.
const resAfter = testDb.prepare('SELECT reservation_time FROM reservations WHERE id = ?').get(reservation.id) as { reservation_time: string };
expect(resAfter.reservation_time).toBe('2026-06-01T19:00:00');
});
it('PUT /days/reorder with the REAL numeric trip id still works and can still be legitimately rejected for inverting a stay (unchanged, base 400)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id, { title: 'Trip', start_date: '2026-06-01', end_date: '2026-06-03' });
const days = testDb.prepare('SELECT id FROM days WHERE trip_id = ? ORDER BY day_number').all(trip.id) as { id: number }[];
const [d1, d2, d3] = days;
const place = createPlace(testDb, trip.id, { name: 'Hotel' });
const stay = createDayAccommodation(testDb, trip.id, place.id, d1.id, d3.id);
const res = await request(app)
.put(`/api/trips/${trip.id}/days/reorder`)
.set('Cookie', authCookie(user.id))
.send({ orderedIds: [d3.id, d2.id, d1.id] });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: 'This move would make an accommodation end before it starts.' });
const stayAfter = testDb.prepare('SELECT start_day_id, end_day_id FROM day_accommodations WHERE id = ?').get(stay.id) as { start_day_id: number; end_day_id: number };
expect(stayAfter).toEqual({ start_day_id: d1.id, end_day_id: d3.id });
});
});
+154 -10
View File
@@ -1074,7 +1074,7 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
expect(res.body).toEqual({ error: 'Place not found' });
});
it('PUT with tags by the hex-spelled trip id 404s and leaves the tags untouched (H1 live: they used to be wiped)', async () => {
it('PUT with tags by the hex-spelled trip id 404s "Trip not found" (Task 9 fix wave: `verifyTripAccess` now gates BEFORE the place-id read, so the string changed from "Place not found") and leaves the tags untouched (H1 live: they used to be wiped)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tagResult = testDb.prepare('INSERT INTO tags (name, user_id) VALUES (?, ?)').run('Original', user.id);
@@ -1092,7 +1092,7 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
.set('Cookie', authCookie(user.id))
.send({ name: 'Renamed', tags: [] });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Place not found' });
expect(res.body).toEqual({ error: 'Trip not found' });
const after = await request(app)
.get(`/api/trips/${trip.id}/places/${placeId}`)
@@ -1101,7 +1101,7 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
expect((after.body.place.tags as { id: number }[]).some((t) => t.id === tagId)).toBe(true);
});
it('PUT :id/rating by the hex-spelled trip id 404s', async () => {
it('PUT :id/rating by the hex-spelled trip id 404s "Trip not found" (Task 9 fix wave: was "Place not found" — see the PUT :id case above)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
@@ -1112,11 +1112,11 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
.set('Cookie', authCookie(user.id))
.send({ rating: 4 });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Place not found' });
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id)).toEqual({ n: 0 });
});
it('POST create by the hex-spelled trip id mirrors the legacy 500 (base 94c6efbbc: FK violation on the raw-bound trip id) — every OTHER route 404s, this is the one documented exception', async () => {
it('POST create by the hex-spelled trip id now 404s "Trip not found" (Task 9 fix wave, M1: `verifyTripAccess` gates with `toRowId` before `create()` is ever reached — the base 94c6efbbc 500 this test used to mirror was ruled a defect, not the contract to preserve, once the gate itself refuses the id)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const hexTripId = '0x' + trip.id.toString(16);
@@ -1125,8 +1125,8 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
.post(`/api/trips/${hexTripId}/places`)
.set('Cookie', authCookie(user.id))
.send({ name: 'Should not land' });
expect(res.status).toBe(500);
expect(res.body).toEqual({ error: 'Internal server error' });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });
});
@@ -1148,7 +1148,7 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
expect(broadcast).not.toHaveBeenCalled();
});
it('POST bulk-delete by the hex-spelled trip id deletes nothing (scopedIds already binds the trip id raw, so this was never divergent — kept as a regression alongside the single-delete case)', async () => {
it('POST bulk-delete by the hex-spelled trip id now 404s "Trip not found" and deletes nothing (Task 9 fix wave: `verifyTripAccess` gates before `scopedIds`/`removeMany` ever run — was a 200 with `count: 0`)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
@@ -1160,13 +1160,157 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => {
.post(`/api/trips/${hexTripId}/places/bulk-delete`)
.set('Cookie', authCookie(user.id))
.send({ ids: [place.id] });
expect(res.status).toBe(200);
expect(res.body).toEqual({ deleted: [], count: 0 });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(place.id)).toBeTruthy();
expect(broadcast).not.toHaveBeenCalled();
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plan 3c Task 9 fix wave — A-H1 / A-M1 / B-H1: `verifyTripAccess` parses
// ONCE with `toRowId` (never `Number()`) and answers 404 `Trip not found`
// before ANY read or write on the 10 `requireTrip`-gated routes above,
// closing two live regressions at once:
// - A-H1: a non-numeric id (`abc`, `1abc`) used to become `NaN` and 500
// (`no such column: NaN`) instead of the legacy 404 — every one of
// these routes now answers the SAME 404 a stranger's clean miss does.
// - A-M1 / B-H1: a numeric-but-non-canonical id (`1.0`, `' 1'`, `'+1'`,
// `'1e0'`) used to pass the old loose `Number()` gate and then
// manufacture a FRESH 500 at the write (`toRowId(tripId) ?? -1`, an FK
// violation on `-1`) — an id the gate itself authorised. It now 404s at
// the gate instead: an ACCEPTED rule-15 narrowing (legacy's raw-bind
// affinity matched these forms; `toRowId` deliberately does not), named
// here rather than claimed as parity.
// ─────────────────────────────────────────────────────────────────────────────
describe('A-H1 / A-M1 / B-H1 — verifyTripAccess parses once with toRowId (Task 9 fix wave)', () => {
const nonCanonicalShapes: [label: string, spell: (id: number) => string][] = [
['a non-numeric id (abc)', () => 'abc'],
['a numeric-suffixed id (1abc)', (id) => `${id}abc`],
['a decimal-spelled id (1.0) — rule-15 narrowing, base 201', (id) => `${id}.0`],
['a leading-space id (\' 1\') — rule-15 narrowing, base 201', (id) => ` ${id}`],
['a leading-plus id (+1) — rule-15 narrowing, base 201', (id) => `+${id}`],
['an exponent-spelled id (1e0) — rule-15 narrowing, base 201', (id) => `${id}e0`],
];
describe.each(nonCanonicalShapes)('POST create — %s', (_label, spell) => {
it('404s "Trip not found" and creates nothing', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spelled = spell(trip.id);
const res = await request(app)
.post(`/api/trips/${spelled}/places`)
.set('Cookie', authCookie(user.id))
.send({ name: 'Should not land' });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });
});
});
describe.each(nonCanonicalShapes)('PUT :id — %s', (_label, spell) => {
it('404s "Trip not found" and leaves the place untouched', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Untouched' });
const spelled = spell(trip.id);
const res = await request(app)
.put(`/api/trips/${spelled}/places/${place.id}`)
.set('Cookie', authCookie(user.id))
.send({ name: 'Renamed' });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
const row = testDb.prepare('SELECT name FROM places WHERE id = ?').get(place.id) as { name: string };
expect(row.name).toBe('Untouched');
});
});
describe.each(nonCanonicalShapes)('POST bulk-delete — %s', (_label, spell) => {
it('404s "Trip not found" and deletes nothing', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre' });
const spelled = spell(trip.id);
vi.mocked(broadcast).mockClear();
const res = await request(app)
.post(`/api/trips/${spelled}/places/bulk-delete`)
.set('Cookie', authCookie(user.id))
.send({ ids: [place.id] });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT id FROM places WHERE id = ?').get(place.id)).toBeTruthy();
expect(broadcast).not.toHaveBeenCalled();
});
});
describe.each(nonCanonicalShapes)('POST bulk-update — %s', (_label, spell) => {
it('404s "Trip not found" and updates nothing', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Louvre', category_id: null });
const spelled = spell(trip.id);
const res = await request(app)
.post(`/api/trips/${spelled}/places/bulk-update`)
.set('Cookie', authCookie(user.id))
.send({ ids: [place.id], category_id: null });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
});
describe.each(nonCanonicalShapes)('PUT :id/rating — %s', (_label, spell) => {
it('404s "Trip not found" and writes no rating', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Rated' });
const spelled = spell(trip.id);
const res = await request(app)
.put(`/api/trips/${spelled}/places/${place.id}/rating`)
.set('Cookie', authCookie(user.id))
.send({ rating: 4 });
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT COUNT(*) AS n FROM place_ratings WHERE place_id = ?').get(place.id)).toEqual({ n: 0 });
});
});
describe.each(nonCanonicalShapes)('GET export.gpx — %s', (_label, spell) => {
it('404s "Trip not found"', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spelled = spell(trip.id);
const res = await request(app)
.get(`/api/trips/${spelled}/places/export.gpx`)
.set('Cookie', authCookie(user.id));
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
});
describe.each(nonCanonicalShapes)('POST import/gpx — %s', (_label, spell) => {
it('404s "Trip not found" and imports nothing', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const spelled = spell(trip.id);
const res = await request(app)
.post(`/api/trips/${spelled}/places/import/gpx`)
.set('Cookie', authCookie(user.id))
.attach('file', GPX_FIXTURE);
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
expect(testDb.prepare('SELECT COUNT(*) AS n FROM places WHERE trip_id = ?').get(trip.id)).toEqual({ n: 0 });
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// M1 / program rule 22 (task-4-review.md) — a NUL byte in a user string no
// longer 500s: the platform override restores the legacy raw-bind's