mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
2c2d008dc2
* fix(security): mint idempotency keys properly, and resolve the extractor by path Three findings out of a sweep of every open Sonar security issue. The other 49 turned out to be false positives and are documented in sonar-project.properties rather than changed — each entry scoped to a file, never a whole rule, so a future Math.random() on an auth path still fails. The idempotency key is the one that can lose data. Both producers fell back to Math.random when crypto.randomUUID was missing, and randomUUID needs a secure context — TREK's own quickstart is http://localhost:3000 and LAN installs run on http://192.168.x.x, so on the deployments the README documents the fallback is what actually runs. The axios one was `Math.random().toString(36).slice(2)`, which is not length-stable: 0.5 yields a single character and 0 yields the empty string, which the interceptor reads as "no key" and skips deduplication for entirely. Two writes sharing a key collapse into one — the second gets the first one's cached response and the edit is gone with no error anywhere. Both now come from utils/randomId, which has the getRandomValues rung that works in insecure contexts too. The extractor probe stored the bare binary name, so every extraction re-resolved it through whatever PATH held at that moment. The official image sets KITINERARY_EXTRACTOR_PATH and never reaches that branch, but a bare-metal install without it ran an unqualified name from a PATH it does not control. It now walks the search path itself and keeps the absolute path of the file it verified; execFileSync also drops the /bin/sh hop the old probe needed. PATH comes through app-config because process.env is walled off in src/. * fix: four tests and sorts that were not doing what they claimed Sonar reported 43 high-impact reliability issues. Reading all of them, four are real; the rest are cosmetic or would be made worse by the suggested change. budget.test.ts hand-built `paid: true`, but both emitters send `paid: body.paid ? 1 : 0` and the handler stores the value verbatim — the test asserted a payload the server never sends. The line below it already used a number. admin.controller.test.ts had a `.resolves` assertion with no await. The promise was dropped, so that line could not fail the test. The two to-do category lists sorted with a bare .sort(), which is byte order: every accented name files behind the whole ASCII range, so in a German trip "Übernachtung" lands after "Zelt". TREK ships 23 locales, so this is real data. One side effect worth knowing: katColor picks a category's dot colour by its index, so re-sorting can move which category shows which colour — it already moves whenever a category is added, and the colour carries no meaning. Deliberately not changed: the two `| 0` truncations (Math.trunc is not equivalent — `| 0` wraps at 32 bits and these carry millisecond timestamps), the two .map() callbacks whose second parameter is declared and used, and the sha1 in thumbnail.service (its own comment says a swap would orphan every existing thumbnail). * refactor: give every button a type, and prefer the Number statics Two mechanical sweeps, no behaviour change intended in either. A <button> with no type attribute is type="submit" per the HTML spec. Outside a form that does nothing today, but it turns into a surprise the moment the markup is wrapped in one, which is what Sonar's S9011 is warning about. 870 buttons get an explicit type="button". Two things were left alone on purpose: buttons that take a {...spread}, because the spread may carry a type and the merge order decides which wins, and anything inside a <form> — there the answer is a judgement call, and checking all eleven form files found every real submit button already carrying type="submit". The Number sweep covers only the three globals that are exactly equivalent to their Number twin: parseInt, parseFloat and NaN. isNaN is NOT in it — the global coerces its argument, so isNaN('abc') is true where Number.isNaN('abc') is false, and renaming it would change what the code does. It reaches server and plugin-sdk as well as the client; both copies of egress-policy.ts got the identical edit, so the mirror the SDK's parity test guards stays intact.
87 lines
3.4 KiB
TypeScript
87 lines
3.4 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import crypto from 'crypto';
|
|
import { DatabaseService } from '../database/database.service';
|
|
|
|
/**
|
|
* Registration invites: the tokens an admin hands out so someone can create an
|
|
* account on a closed instance, optionally dropping them straight into a trip.
|
|
*
|
|
* This lives in auth/ and not in trip-invite/, which is the trap the name sets.
|
|
* invite_tokens and trip_invite_tokens are different tables for different
|
|
* things — the first gates signup, the second adds an existing user to a trip.
|
|
* The consumer of this one is the registration path in AuthService, so the
|
|
* table belongs to the auth domain.
|
|
*
|
|
* The four methods moved verbatim out of AdminService, which held them only
|
|
* because the management routes are under /api/admin. Those routes keep their
|
|
* paths and their guards; AdminController now injects this instead of carrying
|
|
* another domain's SQL.
|
|
*/
|
|
@Injectable()
|
|
export class RegistrationInvitesService {
|
|
constructor(private readonly db: DatabaseService) {}
|
|
|
|
listInvites() {
|
|
return this.db.all(`
|
|
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
|
FROM invite_tokens i
|
|
JOIN users u ON i.created_by = u.id
|
|
LEFT JOIN trips t ON i.trip_id = t.id
|
|
ORDER BY i.created_at DESC
|
|
`);
|
|
}
|
|
|
|
/** Trips an admin can bind an invite to — id + title only, for the picker (#1402). */
|
|
listTripsForInvite() {
|
|
return this.db.all('SELECT id, title FROM trips ORDER BY title COLLATE NOCASE ASC');
|
|
}
|
|
|
|
createInvite(
|
|
createdBy: number,
|
|
data: { max_uses?: string | number; expires_in_days?: string | number; trip_id?: string | number | null },
|
|
) {
|
|
const rawUses = Number.parseInt(String(data.max_uses));
|
|
const uses = rawUses === 0 ? 0 : Math.min(Math.max(rawUses || 1, 1), 5);
|
|
const token = crypto.randomBytes(16).toString('hex');
|
|
const expiresAt = data.expires_in_days
|
|
? new Date(Date.now() + Number.parseInt(String(data.expires_in_days)) * 86400000).toISOString()
|
|
: null;
|
|
|
|
// Optional trip binding: only persist a trip that actually exists, so a stale
|
|
// or forged id can never bind (and never auto-adds anyone on registration).
|
|
let tripId: number | null = null;
|
|
if (data.trip_id != null && String(data.trip_id).trim() !== '') {
|
|
const parsed = Number.parseInt(String(data.trip_id));
|
|
if (!Number.isInteger(parsed) || !this.db.get('SELECT id FROM trips WHERE id = ?', parsed)) {
|
|
// Used to bind null silently, handing back a plain registration invite
|
|
// the admin never asked for.
|
|
return { error: 'Trip not found', status: 404 };
|
|
}
|
|
tripId = parsed;
|
|
}
|
|
|
|
const ins = this.db.run(
|
|
'INSERT INTO invite_tokens (token, max_uses, expires_at, created_by, trip_id) VALUES (?, ?, ?, ?, ?)',
|
|
token, uses, expiresAt, createdBy, tripId,
|
|
);
|
|
|
|
const inviteId = Number(ins.lastInsertRowid);
|
|
const invite = this.db.get(`
|
|
SELECT i.*, u.username as created_by_name, t.title as trip_title
|
|
FROM invite_tokens i
|
|
JOIN users u ON i.created_by = u.id
|
|
LEFT JOIN trips t ON i.trip_id = t.id
|
|
WHERE i.id = ?
|
|
`, inviteId);
|
|
|
|
return { invite, inviteId, uses, expiresInDays: data.expires_in_days ?? null, tripId };
|
|
}
|
|
|
|
deleteInvite(id: string) {
|
|
const invite = this.db.get('SELECT id FROM invite_tokens WHERE id = ?', id);
|
|
if (!invite) return { error: 'Invite not found', status: 404 };
|
|
this.db.run('DELETE FROM invite_tokens WHERE id = ?', id);
|
|
return {};
|
|
}
|
|
}
|