diff --git a/src/http/router.ts b/src/http/router.ts index 193970b..0c9d381 100644 --- a/src/http/router.ts +++ b/src/http/router.ts @@ -166,11 +166,64 @@ export function compilePattern(pattern: string): CompiledPattern { return compiled; } +/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */ +const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i; + +/** + * Classifies one path segment as `.`, `..`, or neither. + * + * `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same + * path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the + * plain form resolves away from. + */ +function dotSegment(segment: string): '.' | '..' | undefined { + if (segment === '.' || segment === '..') return segment; + if (segment.length > 6 || !segment.includes('%')) return undefined; + const decoded = segment.toLowerCase().replace(/%2e/g, '.'); + return decoded === '.' || decoded === '..' ? decoded : undefined; +} + +/** + * Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do. + * + * This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd — + * resolves dot segments inside the `Request` constructor, before green-tea is handed anything: + * `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is + * simply not recoverable there, so rejecting dot segments outright — which is what this module + * does for `//`, and would be the stricter policy — cannot be implemented on three of the four + * runtimes. Resolving is the only rule all four can agree on. + * + * Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin` + * reached a `/admin` route under Deno/Bun/edge and 404'd under Node. + */ +function resolveDotSegments(path: string): string { + const out: string[] = []; + + for (const segment of path.split('/').slice(1)) { + const dots = dotSegment(segment); + if (dots === '.') continue; + + if (dots === '..') { + out.pop(); + continue; + } + + out.push(segment); + } + + return `/${out.join('/')}`; +} + /** Applies the public trailing-slash policy and validates every segment's percent encoding. */ export function normalizeRequestPath(path: string): string { if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash'); if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash'); - const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path; + + // Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no + // `%` at all — which is most of them — pays only the scans. + const resolved = + (path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path; + const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved; // Validation only — the decoded value is deliberately discarded, matching is done on the raw // path. So the work is skipped entirely unless there is something to validate. diff --git a/test/parity.test.ts b/test/parity.test.ts index 9d18135..cceabe8 100644 --- a/test/parity.test.ts +++ b/test/parity.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import type { Server } from 'http'; +import { connect } from 'net'; import { createApp, Provider, Route, Get, Head, Options, Post, Module, needs, body, Sse } from '../src/index'; @Provider({ provides: 'db' }) @@ -69,6 +70,25 @@ async function both(path: string, init?: RequestInit) { return { node, web }; } +/** + * Sends a request line verbatim, bypassing `fetch`. + * + * `both()` cannot reach the cases below: `fetch()` normalizes the URL before it hits the wire, and + * `new Request()` does the same, so a dot segment written into either is already resolved by the + * time the adapter sees it. Only a hand-written request line proves what Node does with one. + */ +function rawStatus(target: string): Promise { + return new Promise((resolve, reject) => { + const socket = connect(Number(new URL(base).port), '127.0.0.1', () => { + socket.write(`GET ${target} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n`); + }); + let raw = ''; + socket.on('data', (chunk) => (raw += chunk.toString())); + socket.on('error', reject); + socket.on('end', () => resolve(Number(raw.split(' ')[1]))); + }); +} + describe('Node vs app.fetch parity (Node is truth)', () => { it('GET /api/x', async () => { const { node, web } = await both('/api/x'); @@ -125,6 +145,21 @@ describe('Node vs app.fetch parity (Node is truth)', () => { expect(web.headers.get('x-content-type-options')).toBe('nosniff'); } }); + // Regression: the same bytes on the wire used to route differently per runtime. Deno, Bun and + // workerd resolve dot segments inside the `Request` constructor before green-tea sees anything, + // and the raw target is unrecoverable there — so Node had to be taught to resolve them too. + it('resolves dot segments to the same route the fetch adapter reaches', async () => { + for (const target of ['/api/nope/../x', '/api/./x', '/api/nope/%2e%2e/x', '/nope/../api/x']) { + expect(await rawStatus(target), `node ${target}`).toBe(200); + expect((await app.fetch(new Request(base + target))).status, `fetch ${target}`).toBe(200); + } + }); + + it('does not treat dots inside a segment as dot segments', async () => { + expect(await rawStatus('/api/x.y')).toBe(404); + expect((await app.fetch(new Request(base + '/api/x.y'))).status).toBe(404); + }); + it('SSE first two events', async () => { const nodeText = await (await fetch(base + '/api/s')).text(); const webText = await (await app.fetch(new Request(base + '/api/s'))).text(); diff --git a/test/router.test.ts b/test/router.test.ts index 72177ba..3f61b1c 100644 --- a/test/router.test.ts +++ b/test/router.test.ts @@ -76,6 +76,33 @@ describe('normalizeRequestPath', () => { expect(() => normalizeRequestPath('/users//42')).toThrow(/repeated slash/); expect(() => normalizeRequestPath('/users/%E0%A4%A')).toThrow(/malformed path encoding/); }); + + // The reference for every case below is `new URL('http://x' + path).pathname`, because that is + // what Deno, Bun and workerd apply before green-tea is handed the request. Node has no such step, + // so this is where the two adapters are made to agree. + it('resolves dot segments the way the URL parser does', () => { + expect(normalizeRequestPath('/public/../admin')).toBe('/admin'); + expect(normalizeRequestPath('/./admin')).toBe('/admin'); + expect(normalizeRequestPath('/a/b/../../c')).toBe('/c'); + expect(normalizeRequestPath('/a/.')).toBe('/a'); + expect(normalizeRequestPath('/..')).toBe('/'); + expect(normalizeRequestPath('/a/../..')).toBe('/'); + }); + + it('resolves percent-encoded dot segments, which the URL parser also treats as dots', () => { + expect(normalizeRequestPath('/public/%2e%2e/admin')).toBe('/admin'); + expect(normalizeRequestPath('/public/%2E%2E/admin')).toBe('/admin'); + expect(normalizeRequestPath('/%2e/admin')).toBe('/admin'); + expect(normalizeRequestPath('/public/.%2e/admin')).toBe('/admin'); + }); + + it('leaves dots that are not whole segments alone', () => { + expect(normalizeRequestPath('/assets/logo.png')).toBe('/assets/logo.png'); + expect(normalizeRequestPath('/files/.hidden')).toBe('/files/.hidden'); + expect(normalizeRequestPath('/v1.2/status')).toBe('/v1.2/status'); + // %2f is not a separator to the URL parser, so `..%2fb` is one ordinary segment. + expect(normalizeRequestPath('/a/..%2fb')).toBe('/a/..%2fb'); + }); }); describe('matchRoute precedence', () => {