mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 07:30:04 +00:00
fix: close the backtracking patterns SonarCloud's profile turns up
The move to SonarCloud brought a wider rule set with it, and 23 more regexes that can be made to hang on a crafted near-match. 21 are fixed here, each proven equivalent to the pattern it replaces by brute force rather than by reading. Two of them are reachable across users, not just by yourself. A reservation endpoint name is free text any trip member types, stored and then read back in every other member's browser while the map draws its labels, and the pattern over it takes 2.3 seconds on a 32k paste - so one member could freeze the map for the whole trip. The mobile transport sheet reads the same field. Both now scan instead of backtrack, and both were matched against the desktop twin the earlier sweep had already fixed rather than given a third spelling. The markdown link stripper needed the same treatment as the tag stripper before it: the label class cannot be disambiguated in the pattern, because it matches an opening bracket as well, and narrowing it changes what "[a[b](c)" produces. It is a scan now, with all four of the regex's quirks intact. Also here: the two encoding warnings the scanner reported. A decorative comment line in JourneyDetailPage.test.tsx had picked up a replacement character somewhere along the way, and calendar.service.test.ts asserts on one deliberately - that one is now written as a U+FFFD escape, so the file no longer carries the raw bytes while the test says exactly what it said before. Seven findings were deliberately not changed and are flagged in SonarCloud with the reasoning. Five are false positives - patterns with no overlapping quantifier pair, where the only cure would change how nested brackets parse. Two are marked accepted rather than dismissed, because they are real: the readme check's heading pattern has a proven linear replacement that cannot land until the registry's copy of the same script can move with it, and `export let JWT_SECRET` is what makes an admin's key rotation take effect in-process instead of silently waiting for a restart.
This commit is contained in:
@@ -16,7 +16,11 @@ const TOOL_NAME = 'emit_reservations';
|
||||
*/
|
||||
export class AnthropicClient implements LlmExtractionClient {
|
||||
async extract(input: LlmExtractionInput): Promise<Record<string, unknown>[]> {
|
||||
const base = (input.baseUrl ?? 'https://api.anthropic.com').replace(/\/+$/, '');
|
||||
// The lookbehind pins the run to its own start. Without it `\/+$` restarts at every
|
||||
// slash of a trailing run that turns out not to end the string, rescanning to the
|
||||
// end each time; the assertion only rules out start positions the leftmost match
|
||||
// could never have used, so the trimmed result is unchanged.
|
||||
const base = (input.baseUrl ?? 'https://api.anthropic.com').replace(/(?<!\/)\/+$/, '');
|
||||
const url = `${base}/v1/messages`;
|
||||
|
||||
const content: unknown[] = [];
|
||||
|
||||
@@ -83,8 +83,12 @@ export function extractBookingRef(text: string): string | undefined {
|
||||
// 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.
|
||||
// "Confirmation" carries its own spacing INSIDE the optional suffix: spelled
|
||||
// `Confirmation\s*(?:number|code)?`, a dropped suffix left that \s* sitting directly
|
||||
// against the separator's \s*, and two adjacent runs can split a stretch of spaces
|
||||
// in n ways — quadratic on "Confirmation" followed by a long indent.
|
||||
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-Z]*\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];
|
||||
}
|
||||
@@ -103,15 +107,23 @@ export function normCurrency(token: string): string | undefined {
|
||||
export function extractTotalPrice(text: string): { price: string; currency?: string } | null {
|
||||
const strip = (s: string) => s.replace(/[€$£¥\s]/g, '');
|
||||
// A labeled total: "Gesamtpreis: 1.234,56 €", "Total Amount 99 USD", "Bezahlter Betrag 651,86 €".
|
||||
// The symbol keeps the space that trails IT inside its own optional group: spelled
|
||||
// `[€$£¥]?\s*`, a missing symbol left that \s* directly against the separator's \s*,
|
||||
// and two adjacent runs split a stretch of spaces in n ways — quadratic on a label
|
||||
// followed by a long indent and no amount.
|
||||
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. 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);
|
||||
// U+2028/U+2029 are line terminators too — /m starts a line after each one — so they
|
||||
// have to leave the class for the same reason \r\n do. `[^\S\r\n]` still contained
|
||||
// them (they are \s), which made a run of them both a line start and indent the class
|
||||
// could eat: 16k of U+2028 took 348ms, and the run grows quadratically.
|
||||
const symbol = text.match(/^[^\S\r\n\u2028\u2029]*([€$£¥]\s?\d[\d.,]*)\b/m);
|
||||
if (symbol) return { price: strip(symbol[1]), currency: normCurrency(symbol[1]) };
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -32,7 +32,12 @@ export interface EnforcedExtractInput {
|
||||
|
||||
/** Resolve the native API base from a config base URL that may end in `/v1`. */
|
||||
export function toNativeBase(baseUrl: string): string {
|
||||
return baseUrl.replace(/\/+$/, '').replace(/\/v1$/, '');
|
||||
// Trailing slashes come off as a scan, not /\/+$/: that pattern is unanchored at the
|
||||
// front, so the engine restarts it at every slash of a run and rescans to the end each
|
||||
// time (quadratic — 25s on 200k). Same result: the maximal trailing run goes.
|
||||
let end = baseUrl.length;
|
||||
while (end > 0 && baseUrl[end - 1] === '/') end--;
|
||||
return baseUrl.slice(0, end).replace(/\/v1$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -265,7 +265,9 @@ function stripPageMarkers(text: string): string {
|
||||
function cleanPdfText(text: string): string {
|
||||
return stripPageMarkers(text)
|
||||
.replace(/[ \t]+/g, ' ')
|
||||
.replace(/\b(?:[A-Z] ){2,}[A-Z]\b/g, m => m.replaceAll(' ', ''))
|
||||
// Same run of three-or-more spaced capitals, written so the repeated group no
|
||||
// longer overlaps the [A-Z] behind it and has to hand characters back to it.
|
||||
.replace(/\b[A-Z](?: [A-Z]){2,}\b/g, m => m.replaceAll(' ', ''))
|
||||
.replace(/ *\n */g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
|
||||
@@ -87,8 +87,19 @@ export function sameScopes(a: string[] | null, b: string[] | null): boolean {
|
||||
return left.every((scope, i) => scope === right[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the trailing slashes of a base URL, as a scan rather than /\/+$/: that pattern
|
||||
* is unanchored at the front, so the engine restarts it at every slash of a run and
|
||||
* rescans to the end each time (quadratic — 25s on 200k). Same string either way.
|
||||
*/
|
||||
function trimTrailingSlashes(value: string): string {
|
||||
let end = value.length;
|
||||
while (end > 0 && value[end - 1] === '/') end--;
|
||||
return value.slice(0, end);
|
||||
}
|
||||
|
||||
export function setAuthChallenge(res: Response, error = 'invalid_token'): void {
|
||||
const base = (getMcpSafeUrl() || '').replace(/\/+$/, '');
|
||||
const base = trimTrailingSlashes(getMcpSafeUrl() || '');
|
||||
// RFC 9728 §5: resource with path component /mcp → PRM URL must include the path
|
||||
res.set('WWW-Authenticate',
|
||||
`Bearer realm="TREK MCP", resource_metadata="${base}/.well-known/oauth-protected-resource/mcp", error="${error}"`);
|
||||
@@ -129,7 +140,7 @@ export class McpTransportService {
|
||||
if (!result) return null;
|
||||
// RFC 8707: audience must always match this resource endpoint.
|
||||
// Pre-audit tokens with audience=null are revoked by the SEC-H6 migration.
|
||||
const expected = `${(getMcpSafeUrl() || '').replace(/\/+$/, '')}/mcp`;
|
||||
const expected = `${trimTrailingSlashes(getMcpSafeUrl() || '')}/mcp`;
|
||||
if (result.audience !== expected) return null;
|
||||
return { user: result.user, scopes: result.scopes, clientId: result.clientId, isStaticToken: false };
|
||||
}
|
||||
|
||||
@@ -52,7 +52,9 @@ export class OidcController {
|
||||
res.status(500).json({ error: 'APP_URL is not configured. OIDC cannot be used.' });
|
||||
return;
|
||||
}
|
||||
const redirectUri = `${appUrl.replace(/\/+$/, '')}/api/auth/oidc/callback`;
|
||||
// `(?<!\/)` as in oidc.service.ts: it pins the run to its own start so a trailing
|
||||
// run that does not end the string is not rescanned from every slash in it.
|
||||
const redirectUri = `${appUrl.replace(/(?<!\/)\/+$/, '')}/api/auth/oidc/callback`;
|
||||
// Lenient parse: a malformed query must never 400 a login redirect, so
|
||||
// unknown values simply fall back to the raw invite + default duration.
|
||||
const query = oidcLoginQuerySchema.safeParse(req.query);
|
||||
@@ -130,7 +132,9 @@ export class OidcController {
|
||||
tokenData.id_token,
|
||||
doc,
|
||||
config.clientId,
|
||||
(doc.issuer ?? '').replace(/\/+$/, '') || config.issuer,
|
||||
// Same trim as oidc.service.ts, and the same reason for the lookbehind — this one
|
||||
// runs over an issuer read out of a fetched discovery document.
|
||||
(doc.issuer ?? '').replace(/(?<!\/)\/+$/, '') || config.issuer,
|
||||
);
|
||||
if (idVerify.ok !== true) {
|
||||
const reason = 'error' in idVerify ? idVerify.error : 'unknown';
|
||||
|
||||
@@ -22,7 +22,7 @@ export class DiscoveryMetadataService {
|
||||
|
||||
getOAuthMetadata(): OAuthMetadata {
|
||||
if (this.oauthMetadata) return this.oauthMetadata;
|
||||
const base = getMcpSafeUrl().replace(/\/+$/, '');
|
||||
const base = getMcpSafeUrl().replace(/(?<!\/)\/+$/, '');
|
||||
this.oauthMetadata = {
|
||||
issuer: base,
|
||||
authorization_endpoint: `${base}/oauth/authorize`,
|
||||
|
||||
Reference in New Issue
Block a user