fix: clear every open Sonar security issue, and half the reliability ones (#2037)

* 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.
This commit is contained in:
Maurice
2026-08-25 15:22:38 +02:00
committed by GitHub
parent 7da0080557
commit 2c2d008dc2
239 changed files with 1303 additions and 1097 deletions
+3 -3
View File
@@ -163,8 +163,8 @@ export function formatDate(dateStr: string | null | undefined, locale: string, t
export function parseMeridiemTime(value: string | null | undefined): string | null {
const match = (value || '').trim().match(/^(\d{1,2}):?(\d{2})?\s*(am|pm)$/i)
if (!match) return null
let h = parseInt(match[1])
const m = match[2] ? parseInt(match[2]) : 0
let h = Number.parseInt(match[1])
const m = match[2] ? Number.parseInt(match[2]) : 0
const isPm = match[3].toLowerCase() === 'pm'
if (h === 12) h = isPm ? 12 : 0
else if (isPm) h += 12
@@ -300,7 +300,7 @@ export function dayTotalCost(
): string | null {
const da = assignments[String(dayId)] || []
const entries = da.map(a => ({
amount: parseFloat(String(a.place?.price ?? '')) || 0,
amount: Number.parseFloat(String(a.place?.price ?? '')) || 0,
currency: a.place?.currency || tripCurrency,
}))
return formatMoneySum(entries, base, locale, rates, { decimals: 0 })
+39
View File
@@ -0,0 +1,39 @@
/**
* The one place idempotency keys are minted.
*
* Both producers — the offline queue's mutation id and the axios interceptor's
* per-request key — end up in the same `X-Idempotency-Key` header, which the
* server caches on (key, user_id, method, path). Two writes that share a key
* therefore collapse into one: the second gets the first one's cached response
* instead of being applied, and the user loses an edit with no error anywhere.
*
* `crypto.randomUUID` needs a secure context, and TREK's own quickstart is plain
* http://localhost:3000 with LAN installs on http://192.168.x.x — so on the
* deployments the README documents, randomUUID is undefined and the fallback is
* what actually runs. It has to be a real one. `getRandomValues` has no
* secure-context requirement and covers that gap; the Math.random rung below it
* exists only for a runtime with no Web Crypto at all.
*
* Lives in its own module rather than next to either caller because
* sync/mutationQueue imports api/client, so the dependency can only go one way.
*/
export function randomId(): string {
const c = globalThis.crypto
if (c && typeof c.randomUUID === 'function') return c.randomUUID()
if (c && typeof c.getRandomValues === 'function') {
const bytes = new Uint8Array(16)
c.getRandomValues(bytes)
// RFC 4122 version + variant bits, so the value still reads as a v4 UUID.
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
// Padded on purpose: `Math.random().toString(36).slice(2)` is not
// length-stable — 0.5 yields a single character and 0 yields the empty
// string, which the server reads as "no key" and skips deduplication for.
const rand = () => Math.random().toString(36).slice(2).padStart(10, '0').slice(0, 10)
return `${Date.now().toString(36)}-${rand()}-${rand()}`
}