fix: make the app keyboard-reachable, and close four DoS-able patterns

The bulk of what SonarQube still had open on the reliability side, read site by
site rather than swept. Two clusters are worth calling out because they are
defects, not lint.

**Four regexes could be made to hang the process.** The worst is
`/.+@.+\..+/` in the forgot-password path: three unbounded `.+` that all
overlap, unanchored, on an endpoint that needs no login and whose schema is a
bare z.string() under a 100kb body cap. A thousand '@' characters had not
finished after 100 seconds — one request pins the event loop, and Node has one.
EMAIL_REGEX in auth.helpers is the same shape on register and profile update
(310ms for 8kb). The two tag strippers over an uploaded KML description and over
Commons metadata took 0.52s on a 16k run of '<'. Each rewrite was proven
equivalent by brute force against the original — millions of strings for the
coordinate patterns, 671,876 for the tag stripper — because a subtly different
regex on a parsing path is worse than the finding.

`<[^>]+>` could not be fixed in the pattern: `[^>]` matches `<` too, so the only
unambiguous form changes what happens to malformed markup. It is now a scan in
common/stripHtmlTags.ts, quirks included — `<>` is left alone, `<a<b>` is one
tag — with the equivalence pinned by a test that compares against the old regex
over every string up to length six.

**And roughly 500 places could only be reached with a mouse.** Clickable divs
became real buttons where the markup allowed (52 of them), took
role + tabIndex + Enter/Space where they had to stay divs, and modal backdrops
took role="presentation" — the honest role, since a backdrop is a mouse shortcut
for a Cancel control that is already in the tab order, and making it a button
plants a nameless full-screen tab stop around its own contents.

Alongside those: `.sort()` calls that now say the order they always had, `{n &&
<X/>}` guards that rendered a literal "0" for a zero-byte file and for a place at
latitude 0, an optimistic budget write that stored a boolean where the contract
and both transports use 0/1, and the Number statics.

sonar-project.properties documents the six that were deliberately left: two wiki
patterns with no overlapping quantifier pair whose "fix" would stop parsing
`[see [1]](url)`, four tar header fields bounded at 12-155 bytes by the format,
two djb2 hashes where the 32-bit wrap is the algorithm, two `| 0` that are also
coercing undefined to 0 on a path where the API sends no user_id, and the MCP
session maps Sonar reads as empty because they are filled from another module.
This commit is contained in:
Maurice
2026-08-25 18:28:40 +02:00
committed by Maurice
parent 52d1a0720f
commit 1ad2e92142
225 changed files with 1721 additions and 735 deletions
@@ -26,7 +26,9 @@ const MAX_TOKENS = 4096;
*/
export class OpenAiCompatibleClient implements LlmExtractionClient {
async extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]> {
const base = (input.baseUrl ?? 'https://api.openai.com/v1').replace(/\/+$/, '');
// The lookbehind matches only the first slash of the trailing run. Without it the
// engine retries from every slash, which is quadratic on a slash-heavy value.
const base = (input.baseUrl ?? 'https://api.openai.com/v1').replace(/(?<!\/)\/+$/, '');
const url = `${base}/chat/completions`;
const nuextract = isNuExtractModel(input.model);
@@ -23,7 +23,11 @@ export class LlmLocalService {
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new HttpException({ error: 'Base URL must be http(s)' }, 400);
}
return raw.replace(/\/+$/, '').replace(/\/v1$/, '');
// Trailing slashes are scanned off instead of `/\/+$/`-replaced: that pattern
// re-walks the slash run from every start position of the admin-supplied URL.
let end = raw.length;
while (end > 0 && raw.charCodeAt(end - 1) === 47 /* '/' */) end--;
return raw.slice(0, end).replace(/\/v1$/, '');
}
/** List models already pulled on the local server. */
+3 -3
View File
@@ -218,10 +218,10 @@ function decodeQuotedPrintable(payload: string): Buffer {
for (let i = 0; i < joined.length; i++) {
const hex = joined[i] === '=' ? joined.slice(i + 1, i + 3) : '';
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
out[len++] = parseInt(hex, 16);
out[len++] = Number.parseInt(hex, 16);
i += 2;
} else {
out[len++] = joined.charCodeAt(i) & 0xff;
out[len++] = joined.codePointAt(i) & 0xff;
}
}
return out.subarray(0, len);
@@ -245,7 +245,7 @@ function decodeEncodedWords(value: string): string {
return value
.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (whole, charset: string, encoding: string, payload: string) => {
const bytes =
encoding.toUpperCase() === 'B' ? decodeBase64(payload) : decodeQuotedPrintable(payload.replace(/_/g, ' '));
encoding.toUpperCase() === 'B' ? decodeBase64(payload) : decodeQuotedPrintable(payload.replaceAll('_', ' '));
const decoded = decodeCharset(bytes, charset);
return decoded || whole;
})
@@ -79,9 +79,12 @@ export function detectFlightNumbers(text: string): string[] {
export function extractBookingRef(text: string): string | undefined {
// The captured code must contain a digit: real PNRs/booking codes effectively always
// do, while the case-insensitive [A-Z0-9] class would otherwise grab a following prose
// word ("Confirmation\nThank you…" → "Thank") after a bare label.
// word ("Confirmation\nThank you…" → "Thank") after a bare label. The lookahead asserts
// exactly that (the run's first digit is only ever preceded by letters), and the
// separator says "spaces, then optionally a colon and more spaces" — both spellings
// avoid quantifiers that overlap and make document text backtrack.
const m = text.match(
/(?:PNR|Buchungs(?:code|nummer|referenz)|Booking\s*(?:reference|code|number)|Confirmation\s*(?:number|code)?|Reservierungsnummer|Reservation\s*(?:No\.?|Number|Nr\.?)|Best(?:ä|ae)tigungs[-\s]?(?:nummer|code)|(?:Expedia[-\s]*)?Reiseplan|Reference)\s*:?\s*((?=[A-Z0-9]*\d)[A-Z0-9]{5,})/i,
/(?:PNR|Buchungs(?:code|nummer|referenz)|Booking\s*(?:reference|code|number)|Confirmation\s*(?:number|code)?|Reservierungsnummer|Reservation\s*(?:No\.?|Number|Nr\.?)|Best(?:ä|ae)tigungs[-\s]?(?:nummer|code)|(?:Expedia[-\s]*)?Reiseplan|Reference)\s*(?::\s*)?((?=[A-Z]*\d)[A-Z0-9]{5,})/i,
);
return m?.[1];
}
@@ -101,12 +104,14 @@ export function extractTotalPrice(text: string): { price: string; currency?: str
const strip = (s: string) => s.replace(/[€$£¥\s]/g, '');
// A labeled total: "Gesamtpreis: 1.234,56 €", "Total Amount 99 USD", "Bezahlter Betrag 651,86 €".
const labeled = text.match(
/(?:Gesamtpreis|Gesamtbetrag|Gesamtsumme|Total(?:\s*(?:price|amount))?|Amount|Summe|Betrag)\s*:?\s*([€$£¥]?\s*\d[\d.,]*)\s*(EUR|USD|GBP|CHF|JPY|€|\$|£|¥)?/i,
/(?:Gesamtpreis|Gesamtbetrag|Gesamtsumme|Total(?:\s*(?:price|amount))?|Amount|Summe|Betrag)\s*(?::\s*)?([€$£¥]?\s*\d[\d.,]*)\s*(EUR|USD|GBP|CHF|JPY|€|\$|£|¥)?/i,
);
if (labeled) return { price: strip(labeled[1]), currency: normCurrency(labeled[2] ?? labeled[1]) };
// Fallback: a standalone amount carrying a currency symbol on its own line (e.g. a voucher's
// "¥9,400") — the price sits far from any label the pattern above can anchor to.
const symbol = text.match(/^\s*([€$£¥]\s?\d[\d.,]*)\b/m);
// "¥9,400") — the price sits far from any label the pattern above can anchor to. The
// indent is horizontal whitespace only: under /m the anchor already sits at every line
// start, so a \s* run that could also eat the newlines just re-scans the document.
const symbol = text.match(/^[^\S\r\n]*([€$£¥]\s?\d[\d.,]*)\b/m);
if (symbol) return { price: strip(symbol[1]), currency: normCurrency(symbol[1]) };
return null;
}
+138 -8
View File
@@ -57,7 +57,7 @@ const HTML_ENTITIES = new Map<string, string>([
['larr', '←'],
['rarr', '→'],
['harr', '↔'],
...LATIN1_ENTITIES.map((name, i): [string, string] => [name, String.fromCharCode(0xa0 + i)]),
...LATIN1_ENTITIES.map((name, i): [string, string] => [name, String.fromCodePoint(0xa0 + i)]),
]);
function entityCodePoint(code: number): string | null {
@@ -85,12 +85,34 @@ function decodeEntities(s: string): string {
});
}
/**
* Replace every tag with a space. Hand-rolled rather than a /<[^>]+>/g replace: a
* match can only start at a "<", so a run of brackets with no ">" behind it — an
* uploaded .eml or .html is free to carry one — makes the engine rescan the tail
* once per bracket. Character for character the same result, including the two
* cases the regex leaves alone: a "<" that nothing closes, and an empty "<>",
* which [^>]+ cannot match.
*/
function stripTags(s: string): string {
let out = '';
let i = 0;
for (;;) {
const lt = s.indexOf('<', i);
if (lt === -1) break;
const gt = s.indexOf('>', lt + 1);
if (gt === -1) break; // nothing closes it, so the rest of the string is text
// An empty "<>" has nothing for [^>]+ to match, so both brackets stay literal.
out += s.slice(i, lt) + (gt === lt + 1 ? '<>' : ' ');
i = gt + 1;
}
return out + s.slice(i);
}
/** Strip HTML/XML tags, resolve entities and collapse whitespace for a cleaner LLM prompt. */
function stripMarkup(s: string): string {
const withoutTags = s
.replace(/<script[\s\S]*?<\/script>/gi, ' ')
.replace(/<style[\s\S]*?<\/style>/gi, ' ')
.replace(/<[^>]+>/g, ' ');
const withoutTags = stripTags(
s.replace(/<script[\s\S]*?<\/script>/gi, ' ').replace(/<style[\s\S]*?<\/style>/gi, ' '),
);
// Entities come last so that a decoded `&lt;` cannot turn into a tag the
// stripper would then eat.
return decodeEntities(withoutTags)
@@ -137,6 +159,115 @@ async function extractPdfText(buffer: Buffer): Promise<string> {
}
}
/** Exactly the code points JS `\s` matches — the class the page-marker pattern walks over. */
const SPACE_CODES = new Set([
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20, 0xa0, 0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005,
0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000, 0xfeff,
]);
/** The line breaks a multiline `^` starts after and `$` ends before. */
const LINE_END_CODES = new Set([0x0a, 0x0d, 0x2028, 0x2029]);
function isSpaceAt(text: string, i: number): boolean {
return SPACE_CODES.has(text.charCodeAt(i));
}
function isLineEndAt(text: string, i: number): boolean {
return LINE_END_CODES.has(text.charCodeAt(i));
}
function isDigitAt(text: string, i: number): boolean {
const c = text.charCodeAt(i);
return c >= 0x30 && c <= 0x39;
}
function isDashAt(text: string, i: number): boolean {
return text.charCodeAt(i) === 0x2d;
}
function skipRun(text: string, from: number, matches: (text: string, i: number) => boolean): number {
let i = from;
while (i < text.length && matches(text, i)) i++;
return i;
}
/**
* A page marker from its first dash on: `-+\s*\d+\s+of\s+\d+\s*-+\s*$`. Returns
* where the match ends, or -1 when there is none. Every quantifier in there is
* followed by a class that excludes what it just matched, so each one can only
* take its whole run — giving characters back never opens a second way through,
* which is why one forward pass is enough.
*/
function markerEnd(text: string, dashStart: number): number {
let i = skipRun(text, skipRun(text, dashStart, isDashAt), isSpaceAt);
const pageNo = i;
i = skipRun(text, i, isDigitAt);
if (i === pageNo) return -1;
const beforeOf = i;
i = skipRun(text, i, isSpaceAt);
if (i === beforeOf) return -1;
const o = text.charCodeAt(i);
const f = text.charCodeAt(i + 1);
if ((o !== 0x6f && o !== 0x4f) || (f !== 0x66 && f !== 0x46)) return -1;
const afterOf = i + 2;
i = skipRun(text, afterOf, isSpaceAt);
if (i === afterOf) return -1;
const pageCount = i;
i = skipRun(text, i, isDigitAt);
if (i === pageCount) return -1;
const closing = skipRun(text, i, isSpaceAt);
i = skipRun(text, closing, isDashAt);
if (i === closing) return -1;
// `\s*$` hands the trailing run back until `$` sits on a line end; with no
// line end in it and text still to come, `$` never matches and neither does
// the marker.
let lastLineEnd = -1;
let end = i;
while (end < text.length && isSpaceAt(text, end)) {
if (isLineEndAt(text, end)) lastLineEnd = end;
end++;
}
return end === text.length ? end : lastLineEnd;
}
/** The first `^` in `[from, to]` — the earliest position the marker can start at. */
function markerStart(text: string, from: number, to: number): number {
if (from === 0 || isLineEndAt(text, from - 1)) return from;
for (let i = from; i < to; i++) if (isLineEndAt(text, i)) return i + 1;
return -1;
}
/**
* Drop `-- N of M --` page markers: `/^\s*-+\s*\d+\s+of\s+\d+\s*-+\s*$/gim` as a
* single left-to-right pass. As a regex it is quadratic — `\s` matches line
* breaks, so under `m` every line start inside a whitespace run walks that same
* run again looking for a dash (40k of `" \n"` took ~0.6 s, and this runs first
* over the raw text layer of an uploaded PDF).
*/
function stripPageMarkers(text: string): string {
let kept = '';
let done = 0; // the pattern's lastIndex: nothing before it can match any more
let i = 0;
while (i < text.length) {
const dashStart = text.indexOf('-', i);
if (dashStart === -1) break;
// The leading `\s*` reaches back across the whole whitespace run, and the
// match then starts at the first `^` — string start or line start — in it.
let runStart = dashStart;
while (runStart > done && isSpaceAt(text, runStart - 1)) runStart--;
const start = markerStart(text, runStart, dashStart);
const end = start === -1 ? -1 : markerEnd(text, dashStart);
if (end === -1) {
i = dashStart + 1;
continue;
}
kept += text.slice(done, start);
done = end;
i = end;
}
return done === 0 ? text : kept + text.slice(done);
}
/**
* Clean up pdf-parse output for the LLM:
* - strip `-- N of M --` page markers
@@ -145,10 +276,9 @@ async function extractPdfText(buffer: Buffer): Promise<string> {
* a common PDF kerning artifact that otherwise hides booking fields
*/
function cleanPdfText(text: string): string {
return text
.replace(/^\s*-+\s*\d+\s+of\s+\d+\s*-+\s*$/gim, '')
return stripPageMarkers(text)
.replace(/[ \t]+/g, ' ')
.replace(/\b(?:[A-Z] ){2,}[A-Z]\b/g, m => m.replace(/ /g, ''))
.replace(/\b(?:[A-Z] ){2,}[A-Z]\b/g, m => m.replaceAll(' ', ''))
.replace(/ *\n */g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();