diff --git a/src/http/router.ts b/src/http/router.ts index 6b7aedf..ac851e4 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -1,63 +1,213 @@ import type { RouteDef, MatchedRoute } from './types'; -/** - * Matches a route pattern against a request path. Supports static segments, `:param` (one segment), - * and a trailing `:name*` catch-all that captures the rest of the path (slashes included) into `params.name`. - * @returns Extracted params (decoded) when the path matches, otherwise undefined. - */ -export function matchPattern(pattern: string, path: string): Record | undefined { +type CompiledSegment = + | { kind: 'static'; value: string } + | { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string } + | { kind: 'catchAll'; name: string }; + +/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */ +export interface CompiledPattern { + source: string; + normalized: string; + shape: string; + segments: CompiledSegment[]; + kinds: number[]; + catchAll: boolean; +} + +const compiledCache = new Map(); +const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; +const MAX_CONSTRAINT_LENGTH = 128; + +interface ConstraintToken { + length: number; + unbounded: boolean; + separator: boolean; +} + +/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */ +function readConstraintToken(source: string): ConstraintToken | undefined { + const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0]; + if (!atom) return undefined; + + const rest = source.slice(atom.length); + const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? ''; + if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier); + + return { + length: atom.length + quantifier.length, + unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'), + separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom), + }; +} + +/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */ +function assertBoundedQuantifier(quantifier: string): void { + const [minText, maxText] = quantifier.slice(1, -1).split(','); + const min = Number(minText); + const max = maxText === undefined || maxText === '' ? min : Number(maxText); + if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`); +} + +/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */ +function assertSafeConstraint(source: string): void { + if (!source || source.length > MAX_CONSTRAINT_LENGTH) + throw new Error('unsafe route constraint: expression must contain 1-128 characters'); + + let offset = 0; + let previousUnbounded = false; + + while (offset < source.length) { + const token = readConstraintToken(source.slice(offset)); + if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`); + if (previousUnbounded && token.unbounded) + throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`); + previousUnbounded = token.separator ? false : token.unbounded; + offset += token.length; + } +} + +function assertParamName(name: string, pattern: string): void { + if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`); +} + +function compileParam(segment: string, pattern: string): Extract { + const constraintStart = segment.indexOf('('); + + if (constraintStart < 0) { + const name = segment.slice(1); + assertParamName(name, pattern); + return { kind: 'param', name }; + } + + if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`); + const name = segment.slice(1, constraintStart); + const constraintSource = segment.slice(constraintStart + 1, -1); + assertParamName(name, pattern); + assertSafeConstraint(constraintSource); + return { + kind: 'param', + name, + constraintSource, + constraint: new RegExp(`^(?:${constraintSource})$`, 'u'), + }; +} + +function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] { + const names = new Set(); + const compiled: CompiledSegment[] = []; + + for (let index = 0; index < rawSegments.length; index++) { + const raw = rawSegments[index]; + let segment: CompiledSegment; + + if (raw.startsWith(':') && raw.endsWith('*')) { + const name = raw.slice(1, -1); + assertParamName(name, pattern); + if (index !== rawSegments.length - 1) + throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`); + segment = { kind: 'catchAll', name }; + } else if (raw.startsWith(':')) { + segment = compileParam(raw, pattern); + } else { + segment = { kind: 'static', value: raw }; + } + + if (segment.kind !== 'static') { + if (names.has(segment.name)) + throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`); + names.add(segment.name); + } + + compiled.push(segment); + } + + return compiled; +} + +function segmentShape(segment: CompiledSegment): string { + if (segment.kind === 'static') return `s:${segment.value}`; + if (segment.kind === 'catchAll') return 'c'; + return segment.constraintSource ? `r:${segment.constraintSource}` : 'p'; +} + +/** Compiles and validates one route pattern. Results are cached by source string. */ +export function compilePattern(pattern: string): CompiledPattern { + const cached = compiledCache.get(pattern); + if (cached) return cached; + if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`); + if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`); + + const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern; + const rawSegments = normalized.split('/').slice(1); + const segments = compileSegments(pattern, rawSegments); + const compiled: CompiledPattern = { + source: pattern, + normalized, + shape: segments.map(segmentShape).join('/'), + segments, + kinds: segments + .filter((segment) => segment.kind !== 'catchAll') + .map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)), + catchAll: segments.at(-1)?.kind === 'catchAll', + }; + compiledCache.set(pattern, compiled); + return compiled; +} + +function decodeSegment(value: string): string { + return decodeURIComponent(value); +} + +function matchCompiled(compiled: CompiledPattern, path: string): Record | undefined { const pathSegs = path.split('/').filter(Boolean); - const patternSegs = pattern.split('/').filter(Boolean); const params: Record = {}; - for (let i = 0; i < patternSegs.length; i++) { - const seg = patternSegs[i]; + for (let index = 0; index < compiled.segments.length; index++) { + const segment = compiled.segments[index]; - // Trailing catch-all: capture every remaining segment (possibly none) as one decoded value. - if (seg.startsWith(':') && seg.endsWith('*')) { - params[seg.slice(1, -1)] = pathSegs.slice(i).map(decodeURIComponent).join('/'); + if (segment.kind === 'catchAll') { + params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/'); return params; } - if (i >= pathSegs.length) return undefined; // pattern longer than path + if (index >= pathSegs.length) return undefined; - if (seg.startsWith(':')) params[seg.slice(1)] = decodeURIComponent(pathSegs[i]); - else if (seg !== pathSegs[i]) return undefined; + if (segment.kind === 'static') { + if (segment.value !== pathSegs[index]) return undefined; + continue; + } + + const value = decodeSegment(pathSegs[index]); + if (segment.constraint && !segment.constraint.test(value)) return undefined; + params[segment.name] = value; } - // No catch-all consumed the tail, so the lengths must match exactly. - return patternSegs.length === pathSegs.length ? params : undefined; + return compiled.segments.length === pathSegs.length ? params : undefined; } -/** Splits a pattern into its fixed-prefix segment kinds (2 = static, 1 = param) and whether it ends in a catch-all. */ -function segScores(pattern: string): { catchAll: boolean; kinds: number[] } { - const kinds: number[] = []; - - for (const seg of pattern.split('/').filter(Boolean)) { - if (seg.startsWith(':') && seg.endsWith('*')) return { catchAll: true, kinds }; - kinds.push(seg.startsWith(':') ? 1 : 2); - } - - return { catchAll: false, kinds }; +/** Matches a compiled segment pattern and returns its decoded parameters. */ +export function matchPattern(pattern: string, path: string): Record | undefined { + return matchCompiled(compilePattern(pattern), path); } -/** Orders two matching patterns by specificity: exact beats catch-all, then static beats param, then longer wins. */ +/** Orders matching patterns by exactness, then static/constrained/plain segment specificity. */ function moreSpecific(a: string, b: string): number { - const scoreA = segScores(a); - const scoreB = segScores(b); + const scoreA = compilePattern(a); + const scoreB = compilePattern(b); if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); - for (let i = 0; i < length; i++) { - const kindA = scoreA.kinds[i] ?? -1; - const kindB = scoreB.kinds[i] ?? -1; + for (let index = 0; index < length; index++) { + const kindA = scoreA.kinds[index] ?? -1; + const kindB = scoreB.kinds[index] ?? -1; if (kindA !== kindB) return kindA - kindB; } return 0; } -/** Finds the most specific route matching both method and path (static > param > catch-all; ties keep registration order). */ +/** Finds the most specific route matching both method and path; ties keep registration order. */ export function matchRoute(routes: RouteDef[], method: string, path: string): MatchedRoute | undefined { let best: MatchedRoute | undefined; let bestPattern = ''; diff --git a/test/router.test.ts b/test/router.test.ts index 8211960..c6aa657 100644 --- a/test/router.test.ts +++ b/test/router.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { matchPattern, matchRoute, allowedMethods } from '../src/http/router'; +import { compilePattern, matchPattern, matchRoute, allowedMethods } from '../src/http/router'; import type { RouteDef } from '../src/http/types'; const route = (method: string, pattern: string): RouteDef => ({ @@ -24,6 +24,33 @@ describe('matchPattern', () => { it(':name* matches zero remaining segments as an empty string', () => { expect(matchPattern('/files/:path*', '/files')).toEqual({ path: '' }); }); + + it('matches safe constraints against the complete decoded segment', () => { + expect(matchPattern('/users/:id(\\d+)', '/users/42')).toEqual({ id: '42' }); + expect(matchPattern('/users/:id(\\d+)', '/users/42x')).toBeUndefined(); + expect(matchPattern('/posts/:slug([a-z0-9_-]+)', '/posts/green-tea_26')).toEqual({ slug: 'green-tea_26' }); + expect(matchPattern('/build/:version(\\d{2}\\.\\d{1,2})', '/build/26.8')).toEqual({ version: '26.8' }); + }); +}); + +describe('compilePattern', () => { + it('records a stable shape independent of parameter names', () => { + expect(compilePattern('/users/:id').shape).toBe(compilePattern('/users/:name').shape); + expect(compilePattern('/users/:id(\\d+)').shape).not.toBe(compilePattern('/users/:id').shape); + }); + + it.each([ + '/files/:rest*/tail', + '/users/:', + '/users/:id/:id', + '/users//:id', + '/users/:id((a+)+)', + '/users/:id((?=a)a)', + '/users/:id(\\1)', + '/users/:id(a|b)', + ])('rejects invalid or unsafe pattern %s', (pattern) => { + expect(() => compilePattern(pattern)).toThrow(/invalid route pattern|unsafe route constraint/); + }); }); describe('matchRoute precedence', () => { @@ -34,6 +61,12 @@ describe('matchRoute precedence', () => { expect(matchRoute(routes, 'GET', '/a/x/y')?.def.pattern).toBe('/a/:rest*'); }); + it('constrained params beat unconstrained params regardless of registration order', () => { + const routes = [route('GET', '/users/:value'), route('GET', '/users/:id(\\d+)')]; + expect(matchRoute(routes, 'GET', '/users/42')?.def.pattern).toBe('/users/:id(\\d+)'); + expect(matchRoute(routes, 'GET', '/users/diego')?.def.pattern).toBe('/users/:value'); + }); + it('returns undefined when no pattern matches the path', () => { expect(matchRoute([route('GET', '/a')], 'GET', '/b')).toBeUndefined(); });