diff --git a/changelog.txt b/changelog.txt index aa83e2ca..717d67c5 100644 --- a/changelog.txt +++ b/changelog.txt @@ -1,3 +1,4 @@ - *Breaking:* The `env` middleware no longer calls `next()` after serving `/__/env.json` or `/__/env.js`. - *Breaking:* Updated `mime-types` to v3; JavaScript files (`.js`, `.mjs`, `/__/env.js`) are now served as `text/javascript; charset=utf-8` (RFC 9239) instead of `application/javascript; charset=utf-8`, and `mime-db` v1.54+ updates several MIME mappings and marks `application/octet-stream` compressible. +- *Breaking:* Replaced `path-to-regexp` v1 with a built-in linear-time redirect path matcher and compiler. Undocumented inline regular expressions inside `redirects[].source` (e.g. `/:id(\d+)`) are no longer supported (use `redirects[].regex` instead), and ambiguous multi-parameter segments separated by non-`.` characters (e.g. `/:a-:b`) now match non-greedily from left to right. diff --git a/package-lock.json b/package-lock.json index 21d8f371..bb00ed70 100644 --- a/package-lock.json +++ b/package-lock.json @@ -21,7 +21,6 @@ "morgan": "^1.8.2", "on-finished": "^2.2.0", "on-headers": "^1.0.0", - "path-to-regexp": "^1.9.0", "router": "^2.0.0", "update-notifier-cjs": "^5.1.6" }, @@ -3553,11 +3552,6 @@ "resolved": "https://registry.npmjs.org/is-yarn-global/-/is-yarn-global-0.3.0.tgz", "integrity": "sha512-VjSeb/lHmkoyd8ryPVIKvOCn4D1koMqY+vqyjjUfc3xyKtP4dYOxM44sZrnqQSzSds3xyOrUTLTC9LVCVgLngw==" }, - "node_modules/isarray": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ==" - }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -4613,15 +4607,6 @@ "node": "20 || >=22" } }, - "node_modules/path-to-regexp": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-1.9.0.tgz", - "integrity": "sha512-xIp7/apCFJuUHdDLWe8O1HIkb0kQrOMb/0u6FXQjemHn/ii5LrIzU6bdECnsiTF/GjZkMEKg1xdiZwNqDYlZ6g==", - "license": "MIT", - "dependencies": { - "isarray": "0.0.1" - } - }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", diff --git a/package.json b/package.json index f237c002..8375d713 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,6 @@ "morgan": "^1.8.2", "on-finished": "^2.2.0", "on-headers": "^1.0.0", - "path-to-regexp": "^1.9.0", "router": "^2.0.0", "update-notifier-cjs": "^5.1.6" }, diff --git a/src/middleware/redirects.ts b/src/middleware/redirects.ts index 80e3e4f3..c0307458 100644 --- a/src/middleware/redirects.ts +++ b/src/middleware/redirects.ts @@ -25,10 +25,14 @@ import { } from "connect"; import isUrl from "is-url"; import { ServerResponse } from "node:http"; -import pathToRegexp from "path-to-regexp"; - import { Configuration, Redirect as RedirectConfig } from "../config"; import { MiddlewareOptions } from "../options"; +import { + createPathCompiler, + createPathMatcher, + PathCompiler, + PathMatcher, +} from "../utils/path-pattern"; import { slasher } from "../utils/pathutils"; import * as patterns from "../utils/patterns"; @@ -71,10 +75,9 @@ class Redirect { private readonly glob?: string; private readonly regex?: string; private readonly destination: string; - private readonly captureKeys: pathToRegexp.Key[] = []; - private readonly engine?: "glob" | "pattern"; - private readonly capture?: RegExp; - private readonly compileDestination?: pathToRegexp.PathFunction; + private readonly matchGlob?: PathMatcher; + private readonly captureRegex?: RegExp; + private readonly compileDestination?: PathCompiler; constructor(redir: RedirectConfig) { this.type = redir.type ?? 301; @@ -84,40 +87,20 @@ class Redirect { this.destination = redir.destination; if (/(?:^|\/):/.test(this.destination)) { - if (this.glob) { - this.engine = "glob"; - this.capture = pathToRegexp(this.glob, this.captureKeys); - } if (this.regex) { - this.engine = "pattern"; - this.capture = patterns.createRaw(this.regex); + this.captureRegex = patterns.createRaw(this.regex); + } else if (this.glob) { + this.matchGlob = createPathMatcher(this.glob); } - this.compileDestination = pathToRegexp.compile(this.destination); + this.compileDestination = createPathCompiler(this.destination); } } test(pathname: string, qs = ""): RedirectResult | undefined { - const match = this.capture?.exec(pathname); - if (match && this.compileDestination) { - const params: Record = {}; - if (this.engine === "glob") { - for (let i = 0; i < this.captureKeys.length; i++) { - const rawMatch = match[i + 1]; - params[this.captureKeys[i].name] = rawMatch?.includes("/") - ? rawMatch.split("/") - : rawMatch; - } - } else { - for (let j = 0; j < match.length; j++) { - params[j.toString()] = match[j]; - } - if (match.groups) { - Object.assign(params, match.groups); - } - } - + const params = this.extractParams(pathname); + if (params && this.compileDestination) { try { - const dest = decodeURIComponent(this.compileDestination(params)); + const dest = this.compileDestination(params); return { type: this.type, destination: formatDestination(dest, qs), @@ -134,6 +117,29 @@ class Redirect { return undefined; } + private extractParams( + pathname: string, + ): Record | undefined { + if (this.captureRegex) { + const match = this.captureRegex.exec(pathname); + if (!match) { + return undefined; + } + const params = Object.create(null) as Record; + for (let j = 0; j < match.length; j++) { + params[j.toString()] = match[j]; + } + if (match.groups) { + Object.assign(params, match.groups); + } + return params; + } + if (this.matchGlob) { + return this.matchGlob(pathname); + } + return undefined; + } + private matchesPattern(url: string): boolean { if (this.glob) { return patterns.configMatcher(url, { glob: this.glob }); diff --git a/src/utils/path-pattern.ts b/src/utils/path-pattern.ts new file mode 100644 index 00000000..96c05d5f --- /dev/null +++ b/src/utils/path-pattern.ts @@ -0,0 +1,571 @@ +/** + * Copyright (c) 2026 Google LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +interface LiteralToken { + readonly type: "literal"; + readonly value: string; +} +interface ParamToken { + readonly type: "param"; + readonly name: string; + readonly prefix: string; + readonly delimiter: string; + readonly optional: boolean; + readonly repeat: boolean; + readonly partial: boolean; +} +interface WildcardToken { + readonly type: "wildcard"; + readonly name: string; + readonly prefix: string; +} +type PathToken = LiteralToken | ParamToken | WildcardToken; + +type Op = + | { readonly kind: "literal"; readonly value: string; readonly lower: string } + | { readonly kind: "charNot"; readonly excluded: string } + | { readonly kind: "anyChar" } + | { readonly kind: "saveStart"; readonly slot: number } + | { readonly kind: "saveEnd"; readonly slot: number } + | { readonly kind: "split"; readonly first: number; readonly second: number } + | { readonly kind: "jump"; readonly target: number } + | { readonly kind: "end" }; + +/** + * Parameter map extracted from a matched path or passed to a destination template. + */ +export type PathParams = Record; + +/** + * Function that matches a URL pathname against a compiled redirect source pattern. + */ +export type PathMatcher = ( + pathname: string, +) => Record | undefined; + +/** + * Function that interpolates captured parameters into a redirect destination template. + */ +export type PathCompiler = (params?: PathParams) => string; + +const FRAME_TRY = 0; +const FRAME_UNDO_START = 1; +const FRAME_UNDO_END = 2; + +const WORD_CHAR = /^[A-Za-z0-9_]$/; + +/** + * Finds the start and end indices of an explicit numeric port in an HTTP(S) + * URL authority (e.g. `:8080` in `https://example.com:8080/:path`) so it is + * preserved as literal text rather than parsed as a numbered parameter. + * @param str The template string to inspect. + * @returns The `[start, end)` range of the port, or `undefined` if none. + */ +function findUrlPortSpan(str: string): [number, number] | undefined { + const authorityMatch = /^https?:\/\/[^/?#]+/i.exec(str); + if (!authorityMatch) { + return undefined; + } + const authority = authorityMatch[0]; + const portMatch = /:\d+$/.exec(authority); + if (!portMatch) { + return undefined; + } + return [portMatch.index, authority.length]; +} + +/** + * Parses a redirect source or destination pattern into literal, parameter, and + * optional bare-wildcard tokens. + * @param str The pattern string. + * @param allowWildcard Whether bare `*` characters act as unnamed wildcards. + * @param preserveUrlPort Whether to keep numeric ports in `http(s)://host:port` literal. + * @returns Ordered list of parsed tokens. + */ +function parsePathTokens( + str: string, + allowWildcard: false, + preserveUrlPort: boolean, +): (LiteralToken | ParamToken)[]; +function parsePathTokens( + str: string, + allowWildcard: boolean, + preserveUrlPort: boolean, +): PathToken[]; +function parsePathTokens( + str: string, + allowWildcard: boolean, + preserveUrlPort: boolean, +): PathToken[] { + const tokens: PathToken[] = []; + const portSpan = preserveUrlPort ? findUrlPortSpan(str) : undefined; + let literal = ""; + let unnamedKey = 0; + let i = 0; + + const flushLiteral = (): void => { + if (literal.length > 0) { + tokens.push({ type: "literal", value: literal }); + literal = ""; + } + }; + + while (i < str.length) { + const ch = str[i]; + + // Escaped character: treat the following character as a literal. + if (ch === "\\" && i + 1 < str.length) { + literal += str[i + 1]; + i += 2; + continue; + } + + // Keep explicit numeric URL ports (e.g. https://example.com:8080) literal. + if (portSpan?.[0] === i) { + literal += str.slice(portSpan[0], portSpan[1]); + i = portSpan[1]; + continue; + } + + // Optional `/` or `.` prefix immediately before `:name` or `*`. + let prefix = ""; + let tokenStart = i; + if ((ch === "/" || ch === ".") && i + 1 < str.length) { + const next = str[i + 1]; + const isParamAfterPrefix = + next === ":" && + portSpan?.[0] !== i + 1 && + i + 2 < str.length && + WORD_CHAR.test(str[i + 2]); + const isWildcardAfterPrefix = allowWildcard && next === "*"; + + if (isParamAfterPrefix || isWildcardAfterPrefix) { + prefix = ch; + tokenStart = i + 1; + } + } + + // Named parameter: `:name`, `:name?`, `:name*`, `:name+`. + if ( + str[tokenStart] === ":" && + portSpan?.[0] !== tokenStart && + tokenStart + 1 < str.length && + WORD_CHAR.test(str[tokenStart + 1]) + ) { + let nameEnd = tokenStart + 1; + while (nameEnd < str.length && WORD_CHAR.test(str[nameEnd])) { + nameEnd += 1; + } + const name = str.slice(tokenStart + 1, nameEnd); + let nextIdx = nameEnd; + let modifier = ""; + if ( + nextIdx < str.length && + (str[nextIdx] === "?" || str[nextIdx] === "*" || str[nextIdx] === "+") + ) { + modifier = str[nextIdx]; + nextIdx += 1; + } + + const nextChar = nextIdx < str.length ? str[nextIdx] : undefined; + const partial = + prefix.length > 0 && nextChar !== undefined && nextChar !== prefix; + + flushLiteral(); + tokens.push({ + type: "param", + name, + prefix, + delimiter: prefix || "/", + optional: modifier === "?" || modifier === "*", + repeat: modifier === "+" || modifier === "*", + partial, + }); + i = nextIdx; + continue; + } + + // Unnamed bare wildcard `*` in source patterns. + if (allowWildcard && str[tokenStart] === "*") { + flushLiteral(); + tokens.push({ + type: "wildcard", + name: String(unnamedKey++), + prefix, + }); + i = tokenStart + 1; + continue; + } + + literal += ch; + i += 1; + } + + flushLiteral(); + return tokens; +} + +/** + * Emits NFA instructions matching a single non-empty segment without `delimiter` + * (`[^delimiter]+?`). + * @param ops Instruction buffer to append to. + * @param delimiter Delimiter character excluded from the segment. + */ +function emitSegmentOps(ops: Op[], delimiter: string): void { + ops.push({ kind: "charNot", excluded: delimiter }); + const morePc = ops.length; + // Non-greedy `+?`: try finishing the segment before extending it. + ops.push({ kind: "split", first: morePc + 3, second: morePc + 1 }); + ops.push({ kind: "charNot", excluded: delimiter }); + ops.push({ kind: "jump", target: morePc }); +} + +/** + * Emits NFA instructions matching a parameter's inner value (single segment, or + * repeated segments separated by `delimiter`). + * @param ops Instruction buffer to append to. + * @param delimiter Delimiter character separating repeated segments. + * @param repeat Whether multiple delimiter-separated segments are matched. + */ +function emitParamValueOps( + ops: Op[], + delimiter: string, + repeat: boolean, +): void { + emitSegmentOps(ops, delimiter); + if (!repeat) { + return; + } + + const repLoopPc = ops.length; + const repSplitIdx = ops.length; + // Greedy `*`: try matching another `delimiter + segment` before finishing. + ops.push({ kind: "split", first: repLoopPc + 1, second: 0 }); + ops.push({ kind: "literal", value: delimiter, lower: delimiter }); + emitSegmentOps(ops, delimiter); + ops.push({ kind: "jump", target: repLoopPc }); + ops[repSplitIdx] = { + kind: "split", + first: repLoopPc + 1, + second: ops.length, + }; +} + +/** + * Compiles a redirect source pattern into a linear-time NFA matcher. + * + * Supports named segments (`:name`), optional segments (`:name?`), zero-or-more + * splats (`:name*`), one-or-more repeats (`:name+`), and bare wildcards (`*`). + * Matching is case-insensitive on literals, allows an optional trailing `/`, + * and runs in guaranteed O(ops * pathname.length) worst-case time without + * catastrophic regex backtracking. + * @param pattern Redirect `source` / `glob` pattern. + * @returns A matcher returning captured parameter values, or `undefined` on no match. + */ +export function createPathMatcher(pattern: string): PathMatcher { + const tokens = parsePathTokens(pattern, true, false); + + // Non-strict trailing slash normalization: if the pattern ends with a literal + // `/`, trim it so the final `end` op uniformly permits 0 or 1 trailing `/`. + const last = tokens[tokens.length - 1]; + if (last?.type === "literal" && last.value.endsWith("/")) { + const trimmed = last.value.slice(0, -1); + if (trimmed.length > 0) { + tokens[tokens.length - 1] = { type: "literal", value: trimmed }; + } else { + tokens.pop(); + } + } + + const ops: Op[] = []; + const keyNames: string[] = []; + + for (const token of tokens) { + if (token.type === "literal") { + ops.push({ + kind: "literal", + value: token.value, + lower: token.value.toLowerCase(), + }); + continue; + } + + const slot = keyNames.length; + keyNames.push(token.name); + + if (token.type === "wildcard") { + if (token.prefix.length > 0) { + ops.push({ + kind: "literal", + value: token.prefix, + lower: token.prefix, + }); + } + ops.push({ kind: "saveStart", slot }); + const loopPc = ops.length; + // Greedy `.*`: consume another char before finishing. + ops.push({ kind: "split", first: loopPc + 1, second: loopPc + 3 }); + ops.push({ kind: "anyChar" }); + ops.push({ kind: "jump", target: loopPc }); + ops.push({ kind: "saveEnd", slot }); + continue; + } + + if (token.optional) { + if (token.partial) { + ops.push({ + kind: "literal", + value: token.prefix, + lower: token.prefix, + }); + } + + const splitIdx = ops.length; + ops.push({ kind: "split", first: splitIdx + 1, second: 0 }); + + if (!token.partial && token.prefix.length > 0) { + ops.push({ + kind: "literal", + value: token.prefix, + lower: token.prefix, + }); + } + ops.push({ kind: "saveStart", slot }); + emitParamValueOps(ops, token.delimiter, token.repeat); + ops.push({ kind: "saveEnd", slot }); + + ops[splitIdx] = { + kind: "split", + first: splitIdx + 1, + second: ops.length, + }; + continue; + } + + if (token.prefix.length > 0) { + ops.push({ + kind: "literal", + value: token.prefix, + lower: token.prefix, + }); + } + ops.push({ kind: "saveStart", slot }); + emitParamValueOps(ops, token.delimiter, token.repeat); + ops.push({ kind: "saveEnd", slot }); + } + + ops.push({ kind: "end" }); + + return function matchPath( + pathname: string, + ): Record | undefined { + const len = pathname.length; + const stride = len + 1; + const numStates = ops.length * stride; + const visited = new Uint8Array((numStates + 7) >>> 3); + + const starts = new Int32Array(keyNames.length).fill(-1); + const ends = new Int32Array(keyNames.length).fill(-1); + + // Flat stack storing triples: [frameKind, argA, argB]. + const stack: number[] = [FRAME_TRY, 0, 0]; + + while (stack.length > 0) { + const argB = stack.pop()!; + const argA = stack.pop()!; + const frameKind = stack.pop()!; + + if (frameKind === FRAME_UNDO_START) { + starts[argA] = argB; + continue; + } + if (frameKind === FRAME_UNDO_END) { + ends[argA] = argB; + continue; + } + + let pc = argA; + let pos = argB; + + for (;;) { + const stateIdx = pc * stride + pos; + const byteIdx = stateIdx >>> 3; + const bitMask = 1 << (stateIdx & 7); + if ((visited[byteIdx] & bitMask) !== 0) { + break; + } + visited[byteIdx] |= bitMask; + + const op = ops[pc]; + if (op.kind === "end") { + if (pos === len || (pos === len - 1 && pathname[pos] === "/")) { + const params = Object.create(null) as Record< + string, + string | undefined + >; + for (let i = 0; i < keyNames.length; i++) { + const start = starts[i]; + const end = ends[i]; + params[keyNames[i]] = + start >= 0 && end >= start + ? pathname.slice(start, end) + : undefined; + } + return params; + } + break; + } + + if (op.kind === "literal") { + const endPos = pos + op.value.length; + if ( + endPos > len || + pathname.slice(pos, endPos).toLowerCase() !== op.lower + ) { + break; + } + pc += 1; + pos = endPos; + continue; + } + + if (op.kind === "charNot") { + if (pos >= len || pathname[pos] === op.excluded) { + break; + } + pc += 1; + pos += 1; + continue; + } + + if (op.kind === "anyChar") { + if (pos >= len) { + break; + } + pc += 1; + pos += 1; + continue; + } + + if (op.kind === "saveStart") { + stack.push(FRAME_UNDO_START, op.slot, starts[op.slot]); + starts[op.slot] = pos; + pc += 1; + continue; + } + + if (op.kind === "saveEnd") { + stack.push(FRAME_UNDO_END, op.slot, ends[op.slot]); + ends[op.slot] = pos; + pc += 1; + continue; + } + + if (op.kind === "jump") { + pc = op.target; + continue; + } + + // Split: push fallback first so `first` is explored before `second`. + stack.push(FRAME_TRY, op.second, pos); + pc = op.first; + } + } + + return undefined; + }; +} + +/** + * Compiles a redirect destination template into a function that substitutes + * captured parameters (`:name`, `:1`, `:name?`, `:name*`, `:name+`). + * @param template Redirect `destination` template string. + * @returns A function that produces the interpolated destination string. + */ +export function createPathCompiler(template: string): PathCompiler { + const tokens = parsePathTokens(template, false, true); + + return function compilePath(params: PathParams = {}): string { + let result = ""; + + for (const token of tokens) { + if (token.type === "literal") { + result += token.value; + continue; + } + + const value = Object.prototype.hasOwnProperty.call(params, token.name) + ? params[token.name] + : undefined; + + if (value === undefined) { + if (token.optional) { + if (token.partial) { + result += token.prefix; + } + continue; + } + throw new TypeError(`Expected "${token.name}" to be defined`); + } + + if (Array.isArray(value)) { + if (!token.repeat) { + throw new TypeError(`Expected "${token.name}" to not repeat`); + } + if (value.length === 0) { + if (token.optional) { + if (token.partial) { + result += token.prefix; + } + continue; + } + throw new TypeError(`Expected "${token.name}" to not be empty`); + } + for (const segment of value) { + if (segment.length === 0 || segment.includes(token.delimiter)) { + throw new TypeError( + `Expected all "${token.name}" segments to be non-empty and exclude "${token.delimiter}"`, + ); + } + } + result += token.prefix + value.join(token.delimiter); + continue; + } + + if (value.length === 0) { + throw new TypeError(`Expected "${token.name}" to be non-empty`); + } + if ( + token.delimiter !== "/" && + !token.repeat && + value.includes(token.delimiter) + ) { + throw new TypeError( + `Expected "${token.name}" to exclude "${token.delimiter}"`, + ); + } + + result += token.prefix + value; + } + + return result; + }; +} diff --git a/test/unit/middleware/redirects.spec.ts b/test/unit/middleware/redirects.spec.ts index 42057e5f..08dfe099 100644 --- a/test/unit/middleware/redirects.spec.ts +++ b/test/unit/middleware/redirects.spec.ts @@ -455,6 +455,135 @@ describe("redirect middleware", () => { .get("/blog/this/old/post") .expect(301) .expect("location", "/new/this/old/post"); + + await request(app).get("/blog/").expect(301).expect("location", "/new"); + }); + + it("redirects a splat segment into a non-splat external destination", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + source: "/blog/:post*", + destination: "https://blog.myapp.com/:post", + type: 301, + }, + ], + }), + ); + + await request(app) + .get("/blog/this/old/post") + .expect(301) + .expect("location", "https://blog.myapp.com/this/old/post"); + + await request(app).get("/blog/").expect(404); + }); + + it("redirects a one-or-more repeating segment", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + source: "/blog/:post+", + destination: "/new/:post+", + type: 301, + }, + ], + }), + ); + + await request(app) + .get("/blog/this/old/post") + .expect(301) + .expect("location", "/new/this/old/post"); + + await request(app).get("/blog/").expect(404); + }); + + it("redirects using a bare wildcard alongside a named capture", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + source: "/old/*/item/:id", + destination: "/new/:id", + type: 301, + }, + ], + }), + ); + + await request(app) + .get("/old/any/nested/item/42") + .expect(301) + .expect("location", "/new/42"); + }); + + it("redirects to an external URL with an explicit port and captures", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + source: "/old/:id", + destination: "https://example.com:8080/:id", + type: 301, + }, + ], + }), + ); + + await request(app) + .get("/old/42") + .expect(301) + .expect("location", "https://example.com:8080/42"); + }); + + it("skips a regex capture redirect when the request path does not match", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + regex: "^/old/(.+)$", + destination: "/new/:1", + type: 301, + }, + ], + }), + ); + + await request(app).get("/other/path").expect(404); + }); + + it("preserves encoded and raw percent query params in captured destinations", async () => { + const app = connect() + .use(superstaticSetup) + .use( + redirect({ + redirects: [ + { + source: "/captured/:foo", + destination: "/:foo/bar?filter=a%26b&discount=50%", + type: 301, + }, + ], + }), + ); + + await request(app) + .get("/captured/wat?extra=1") + .expect(301) + .expect("Location", "/wat/bar?filter=a%26b&discount=50%&extra=1"); }); it("redirects using segments in the url path with a 302", async () => { diff --git a/test/unit/utils/path-pattern.spec.ts b/test/unit/utils/path-pattern.spec.ts new file mode 100644 index 00000000..21582c2f --- /dev/null +++ b/test/unit/utils/path-pattern.spec.ts @@ -0,0 +1,309 @@ +/** + * Copyright (c) 2026 Google LLC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +import { expect } from "chai"; + +import { + createPathCompiler, + createPathMatcher, +} from "../../../src/utils/path-pattern"; + +describe("path-pattern", () => { + describe("createPathMatcher", () => { + it("matches basic named parameters and preserves original value case", () => { + const match = createPathMatcher("/Old/:value/Path/:loc"); + + expect(match("/old/Redirect/path/There")).to.deep.equal({ + value: "Redirect", + loc: "There", + }); + expect(match("/old/Redirect/path/There/")).to.deep.equal({ + value: "Redirect", + loc: "There", + }); + expect(match("/old/Redirect/path/There//")).to.equal(undefined); + expect(match("/other/Redirect/path/There")).to.equal(undefined); + }); + + it("handles trailing slashes consistently in non-strict mode", () => { + const rootMatch = createPathMatcher("/"); + expect(rootMatch("/")).to.deep.equal({}); + expect(rootMatch("//")).to.equal(undefined); + + const dirMatch = createPathMatcher("/old/"); + expect(dirMatch("/old")).to.deep.equal({}); + expect(dirMatch("/old/")).to.deep.equal({}); + expect(dirMatch("/old//")).to.equal(undefined); + + const paramSlashMatch = createPathMatcher("/old/:value/"); + expect(paramSlashMatch("/old/foo")).to.deep.equal({ value: "foo" }); + expect(paramSlashMatch("/old/foo/")).to.deep.equal({ value: "foo" }); + expect(paramSlashMatch("/old/foo//")).to.equal(undefined); + }); + + it("matches optional segments including mid-path, partial, and dot-prefixed", () => { + const trailingOpt = createPathMatcher("/old/:value?"); + expect(trailingOpt("/old")).to.deep.equal({ value: undefined }); + expect(trailingOpt("/old/")).to.deep.equal({ value: undefined }); + expect(trailingOpt("/old/derp")).to.deep.equal({ value: "derp" }); + expect(trailingOpt("/old/derp/")).to.deep.equal({ value: "derp" }); + expect(trailingOpt("/old//")).to.equal(undefined); + + const midOpt = createPathMatcher("/:lang?/about"); + expect(midOpt("/about")).to.deep.equal({ lang: undefined }); + expect(midOpt("/en/about")).to.deep.equal({ lang: "en" }); + + const partialOpt = createPathMatcher("/:lang?-about"); + expect(partialOpt("/-about")).to.deep.equal({ lang: undefined }); + expect(partialOpt("/en-about")).to.deep.equal({ lang: "en" }); + + const dotOpt = createPathMatcher("/files/:name.:ext?"); + expect(dotOpt("/files/foo")).to.deep.equal({ + name: "foo", + ext: undefined, + }); + expect(dotOpt("/files/foo.html")).to.deep.equal({ + name: "foo", + ext: "html", + }); + expect(dotOpt("/files/foo.bar.html")).to.deep.equal({ + name: "foo.bar", + ext: "html", + }); + }); + + it("matches zero-or-more splats (:post*) and one-or-more repeats (:post+)", () => { + const splat = createPathMatcher("/blog/:post*"); + expect(splat("/blog")).to.deep.equal({ post: undefined }); + expect(splat("/blog/")).to.deep.equal({ post: undefined }); + expect(splat("/blog/hello")).to.deep.equal({ post: "hello" }); + expect(splat("/blog/this/old/post")).to.deep.equal({ + post: "this/old/post", + }); + expect(splat("/blog/this/old/post/")).to.deep.equal({ + post: "this/old/post", + }); + expect(splat("/blog/a//b")).to.equal(undefined); + expect(splat("/blogger")).to.equal(undefined); + + const midSplat = createPathMatcher("/:prefix*/end"); + expect(midSplat("/end")).to.deep.equal({ prefix: undefined }); + expect(midSplat("/a/b/c/end")).to.deep.equal({ prefix: "a/b/c" }); + + const plus = createPathMatcher("/blog/:post+"); + expect(plus("/blog")).to.equal(undefined); + expect(plus("/blog/")).to.equal(undefined); + expect(plus("/blog/a")).to.deep.equal({ post: "a" }); + expect(plus("/blog/a/b/c")).to.deep.equal({ post: "a/b/c" }); + }); + + it("matches multi-parameter segments and bare wildcards", () => { + const dotPair = createPathMatcher("/:file.:ext"); + expect(dotPair("/foo.json.html")).to.deep.equal({ + file: "foo.json", + ext: "html", + }); + + const dashPair = createPathMatcher("/:a-:b"); + expect(dashPair("/foo-bar-baz")).to.deep.equal({ + a: "foo", + b: "bar-baz", + }); + + const adjacent = createPathMatcher("/:a:b"); + expect(adjacent("/xy")).to.deep.equal({ a: "x", b: "y" }); + + const bareWildcard = createPathMatcher("/old/*/item/:id"); + expect(bareWildcard("/old/a/b/item/42")).to.deep.equal({ + 0: "a/b", + id: "42", + }); + + const trailingWildcard = createPathMatcher("/old/*"); + expect(trailingWildcard("/old")).to.equal(undefined); + expect(trailingWildcard("/old/")).to.deep.equal({ 0: "" }); + expect(trailingWildcard("/old/a/b/")).to.deep.equal({ 0: "a/b/" }); + + const unprefixedWildcard = createPathMatcher("/old*"); + expect(unprefixedWildcard("/old/anything")).to.deep.equal({ + 0: "/anything", + }); + }); + + it("handles escaped characters, trailing backslashes, Unicode, and literal parens", () => { + const escaped = createPathMatcher("/literal/\\:id/:val"); + expect(escaped("/literal/:id/42")).to.deep.equal({ val: "42" }); + + const trailingBackslash = createPathMatcher("/a/:val\\"); + expect(trailingBackslash("/a/foo\\")).to.deep.equal({ val: "foo" }); + + const unicode = createPathMatcher("/äöü/:slug"); + expect(unicode("/äöü/🚀-post")).to.deep.equal({ slug: "🚀-post" }); + + const literalParens = createPathMatcher("/users/(v1)/:id"); + expect(literalParens("/users/(v1)/123")).to.deep.equal({ id: "123" }); + expect(literalParens("/users/v1/123")).to.equal(undefined); + }); + + it("avoids catastrophic backtracking on ReDoS-prone patterns", () => { + // Multi-param segment (CVE-2026-4867 class) + const multiParam = createPathMatcher("/:a-:b-:c-:d-:e-:f/end"); + const start1 = performance.now(); + expect(multiParam(`/${"-".repeat(10000)}!`)).to.equal(undefined); + expect(performance.now() - start1).to.be.lessThan(500); + + // Multiple repeating splats (CVE-2026-4923 class) + const multiSplat = createPathMatcher("/:a*/:b*/:c*/end"); + const start2 = performance.now(); + expect(multiSplat(`/${"x/".repeat(5000)}nope`)).to.equal(undefined); + expect(performance.now() - start2).to.be.lessThan(500); + + // Sequential optional groups (CVE-2026-4926 class) + const seqOpt = createPathMatcher( + "/:a1?/:a2?/:a3?/:a4?/:a5?/:a6?/:a7?/:a8?/:a9?/:a10?/:a11?/:a12?/:a13?/:a14?/:a15?/:a16?/:a17?/:a18?/:a19?/:a20?/end", + ); + const start3 = performance.now(); + expect(seqOpt(`${"/x".repeat(20)}/nope`)).to.equal(undefined); + expect(performance.now() - start3).to.be.lessThan(500); + + // Multiple bare wildcards + const multiWild = createPathMatcher("/*/*/*/end"); + const start4 = performance.now(); + expect(multiWild(`/${"a/".repeat(5000)}nope`)).to.equal(undefined); + expect(performance.now() - start4).to.be.lessThan(500); + }); + }); + + describe("createPathCompiler", () => { + it("interpolates named, numbered, optional, partial, and repeating parameters", () => { + expect( + createPathCompiler("/new/:value/path/:loc")({ + value: "a", + loc: "b", + }), + ).to.equal("/new/a/path/b"); + + expect( + createPathCompiler("/new/:1/path/:2")({ 1: "first", 2: "second" }), + ).to.equal("/new/first/path/second"); + + const opt = createPathCompiler("/new/:value?"); + expect(opt({})).to.equal("/new"); + expect(opt({ value: undefined })).to.equal("/new"); + expect(opt({ value: "derp" })).to.equal("/new/derp"); + + const partialOpt = createPathCompiler("/:lang?-about"); + expect(partialOpt({})).to.equal("/-about"); + expect(partialOpt({ lang: "en" })).to.equal("/en-about"); + + const dotOpt = createPathCompiler("/files/:name.:ext?"); + expect(dotOpt({ name: "foo" })).to.equal("/files/foo"); + expect(dotOpt({ name: "foo", ext: "html" })).to.equal("/files/foo.html"); + + const splat = createPathCompiler("/new/:post*"); + expect(splat({})).to.equal("/new"); + expect(splat({ post: [] })).to.equal("/new"); + expect(splat({ post: "this/old/post" })).to.equal("/new/this/old/post"); + expect(splat({ post: ["this", "old", "post"] })).to.equal( + "/new/this/old/post", + ); + + const partialSplat = createPathCompiler("/:post*-tail"); + expect(partialSplat({ post: [] })).to.equal("/-tail"); + + const plus = createPathCompiler("/new/:post+"); + expect(plus({ post: ["a", "b"] })).to.equal("/new/a/b"); + }); + + it("preserves external URLs, numeric ports, query strings, and escaped colons", () => { + expect( + createPathCompiler("https://blog.myapp.com/:post")({ + post: "this/old/post", + }), + ).to.equal("https://blog.myapp.com/this/old/post"); + + expect( + createPathCompiler("https://example.com:8080/:post")({ + post: "article", + }), + ).to.equal("https://example.com:8080/article"); + + expect( + createPathCompiler("https://:sub.example.com:8080/:post")({ + sub: "docs", + post: "intro", + }), + ).to.equal("https://docs.example.com:8080/intro"); + + expect( + createPathCompiler("https://example.com.:8080/:post")({ + post: "intro", + }), + ).to.equal("https://example.com.:8080/intro"); + + expect( + createPathCompiler("/new/:foo/bar?filter=a%26b&discount=50%")({ + foo: "wat", + }), + ).to.equal("/new/wat/bar?filter=a%26b&discount=50%"); + + expect( + createPathCompiler("/new/\\:literal/:val")({ val: "42" }), + ).to.equal("/new/:literal/42"); + }); + + it("ignores Object.prototype properties and rejects invalid parameter values", () => { + const protoTemplate = createPathCompiler("/new/:toString"); + expect(() => protoTemplate({})).to.throw( + TypeError, + 'Expected "toString" to be defined', + ); + expect(() => protoTemplate()).to.throw( + TypeError, + 'Expected "toString" to be defined', + ); + + const required = createPathCompiler("/new/:id"); + expect(() => required({ id: "" })).to.throw( + TypeError, + 'Expected "id" to be non-empty', + ); + expect(() => required({ id: ["a", "b"] })).to.throw( + TypeError, + 'Expected "id" to not repeat', + ); + + const plus = createPathCompiler("/new/:post+"); + expect(() => plus({ post: [] })).to.throw( + TypeError, + 'Expected "post" to not be empty', + ); + expect(() => plus({ post: ["a", ""] })).to.throw(TypeError); + expect(() => plus({ post: ["a/b"] })).to.throw(TypeError); + + const dotParam = createPathCompiler("/files/:name.:ext"); + expect(() => dotParam({ name: "foo", ext: "tar.gz" })).to.throw( + TypeError, + 'Expected "ext" to exclude "."', + ); + }); + }); +});