fix(router): wildcard paths when using js reserved words (like constructor and __proto__) (#2357)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Replace `{}` by `Object.create(null)` in a few places * Add test for js reserved word * Run denoify * Add reserved words tests to common routes tests, and fix the failures on other routers too * Fix format * Run denoify again
authored by Leonardo Carreiro · committed by GitHub · parent e675d50 · Browse files · 12 files·+87 added−49 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+87 added−49 removed
- tests:+35 added−1 removed
- other:+52 added−48 removed
Provenance
- Commit
f60ab8b- Tree
307c099- Author
Leonardo Carreiro <github@leo.br.com>- Committer
GitHub <noreply@github.com>- Parent
e675d50
12 files changed+87 added−49 removed
modified:deno_dist/router/linear-router/router.ts+2 added-2 removed
2 unmodified lines34567789101153 unmodified lines6566676869697071727359 unmodified lines2 unmodified linesimport { checkOptionalParameter } from '../../utils/url.ts'
type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }
const emptyParams = {}const emptyParams = Object.create(null)
const splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/gconst splitByStarRe = /\*/export class LinearRouter<T> implements Router<T> {53 unmodified lines } } handlers.push([handler, emptyParams]) } else if (hasLabel && !hasStar) { const params: Record<string, string> = {} const params: Record<string, string> = Object.create(null) const parts = routePath.match(splitPathRe) as string[]
const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) {59 unmodified linesmodified:deno_dist/router/pattern-router/router.ts+1 added-1 removed
42 unmodified lines434445464747484950513 unmodified lines42 unmodified lines for (const [pattern, routeMethod, handler] of this.routes) { if (routeMethod === METHOD_NAME_ALL || routeMethod === method) { const match = pattern.exec(path) if (match) { handlers.push([handler, match.groups || {}]) handlers.push([handler, match.groups || Object.create(null)]) } } }
3 unmodified linesmodified:deno_dist/router/reg-exp-router/node.ts+1 added-1 removed
43 unmodified lines44 45 export class Node {46 index?: number47 varIndex?: number48- children: Record<string, Node> = {}48+ children: Record<string, Node> = Object.create(null)49 50 insert(51 tokens: readonly string[],52 index: number,107 unmodified linesmodified:deno_dist/router/reg-exp-router/router.ts+10 added-10 removed
14 unmodified lines15 type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]16 17 const emptyParam: string[] = []18 // eslint-disable-next-line @typescript-eslint/no-explicit-any19-const nullMatcher: Matcher<any> = [/^$/, [], {}]19+const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]20 21-let wildcardRegExpCache: Record<string, RegExp> = {}21+let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)22 function buildWildcardRegExp(path: string): RegExp {23 return (wildcardRegExpCache[path] ??= new RegExp(24 path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`25 ))26 }27 28 function clearWildcardRegExpCache() {29- wildcardRegExpCache = {}29+ wildcardRegExpCache = Object.create(null)30 }31 32 function buildMatcherFromPreprocessedRoutes<T>(33 routes: [string, HandlerWithMetadata<T>[]][]11 unmodified lines45 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>46 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length47 )48 49- const staticMap: StaticMap<T> = {}49+ const staticMap: StaticMap<T> = Object.create(null)50 for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {51 const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]52 if (pathErrorCheckOnly) {53- staticMap[path] = [handlers.map(([h]) => [h, {}]), emptyParam]53+ staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]54 } else {55 j++56 }57 8 unmodified lines66 continue67 }68 69 handlerData[j] = handlers.map(([h, paramCount]) => {70- const paramIndexMap: ParamIndexMap = {}70+ const paramIndexMap: ParamIndexMap = Object.create(null)71 paramCount -= 172 for (; paramCount >= 0; paramCount--) {73 const [key, value] = paramAssoc[paramCount]74 paramIndexMap[key] = value47 unmodified lines122 middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>123 routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>124 125 constructor() {126- this.middleware = { [METHOD_NAME_ALL]: {} }127- this.routes = { [METHOD_NAME_ALL]: {} }126+ this.middleware = { [METHOD_NAME_ALL]: Object.create(null) }127+ this.routes = { [METHOD_NAME_ALL]: Object.create(null) }128 }129 130 add(method: string, path: string, handler: T) {131 const { middleware, routes } = this3 unmodified lines135 }136 137 if (!middleware[method]) {138 ;[middleware, routes].forEach((handlerMap) => {139- handlerMap[method] = {}139+ handlerMap[method] = Object.create(null)140 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {141 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]142 })143 })81 unmodified lines225 return this.match(method, path)226 }227 228 private buildAllMatchers(): Record<string, Matcher<T> | null> {229- const matchers: Record<string, Matcher<T> | null> = {}229+ const matchers: Record<string, Matcher<T> | null> = Object.create(null)230 231 ;[...Object.keys(this.routes!), ...Object.keys(this.middleware!)].forEach((method) => {232 matchers[method] ||= this.buildMatcher(method)233 })36 unmodified linesmodified:deno_dist/router/trie-router/node.ts+12 added-10 removed
19 unmodified lines20 children: Record<string, Node<T>>21 patterns: Pattern[]22 order: number = 023 name: string24- params: Record<string, string> = {}24+ params: Record<string, string> = Object.create(null)25 26 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {27- this.children = children || {}27+ this.children = children || Object.create(null)28 this.methods = []29 this.name = ''30 if (method && handler) {31- const m: Record<string, HandlerSet<T>> = {}31+ const m: Record<string, HandlerSet<T>> = Object.create(null)32 m[method] = { handler, possibleKeys: [], score: 0, name: this.name }33 this.methods = [m]34 }35 this.patterns = []38 unmodified lines74 if (!curNode.methods.length) {75 curNode.methods = []76 }77 78- const m: Record<string, HandlerSet<T>> = {}78+ const m: Record<string, HandlerSet<T>> = Object.create(null)79 80 const handlerSet: HandlerSet<T> = {81 handler,82 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),17 unmodified lines100 const handlerSets: HandlerParamsSet<T>[] = []101 for (let i = 0, len = node.methods.length; i < len; i++) {102 const m = node.methods[i]103 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>104- const processedSet: Record<string, boolean> = {}104+ const processedSet: Record<string, boolean> = Object.create(null)105 if (handlerSet !== undefined) {106- handlerSet.params = {}106+ handlerSet.params = Object.create(null)107 handlerSet.possibleKeys.forEach((key) => {108 const processed = processedSet[handlerSet.name]109 handlerSet.params[key] =110 params[key] && !processed ? params[key] : nodeParams[key] ?? params[key]6 unmodified lines117 }118 119 search(method: string, path: string): [[T, Params][]] {120 const handlerSets: HandlerParamsSet<T>[] = []121- this.params = {}121+ this.params = Object.create(null)122 123 // eslint-disable-next-line @typescript-eslint/no-this-alias124 const curNode: Node<T> = this125 let curNodes = [curNode]12 unmodified lines138 nextNode.params = node.params139 if (isLast === true) {140 // '/hello/*' => match '/hello'141 if (nextNode.children['*']) {142- handlerSets.push(...this.gHSets(nextNode.children['*'], method, node.params, {}))142+ handlerSets.push(143+ ...this.gHSets(nextNode.children['*'], method, node.params, Object.create(null))144+ )145 }144- handlerSets.push(...this.gHSets(nextNode, method, node.params, {}))146+ handlerSets.push(...this.gHSets(nextNode, method, node.params, Object.create(null)))147 } else {148 tempNodes.push(nextNode)149 }150 }7 unmodified lines158 // '/hello/*/foo' => match /hello/bar/foo159 if (pattern === '*') {160 const astNode = node.children['*']161 if (astNode) {160- handlerSets.push(...this.gHSets(astNode, method, node.params, {}))162+ handlerSets.push(...this.gHSets(astNode, method, node.params, Object.create(null)))163 tempNodes.push(astNode)164 }165 continue166 }43 unmodified linesmodified:src/router/linear-router/router.ts+2 added-2 removed
2 unmodified lines3 import { checkOptionalParameter } from '../../utils/url'4 5 type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }6 7-const emptyParams = {}7+const emptyParams = Object.create(null)8 9 const splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g10 const splitByStarRe = /\*/11 export class LinearRouter<T> implements Router<T> {53 unmodified lines65 }66 }67 handlers.push([handler, emptyParams])68 } else if (hasLabel && !hasStar) {69- const params: Record<string, string> = {}69+ const params: Record<string, string> = Object.create(null)70 const parts = routePath.match(splitPathRe) as string[]71 72 const lastIndex = parts.length - 173 for (let j = 0, pos = 0, len = parts.length; j < len; j++) {59 unmodified linesmodified:src/router/pattern-router/router.ts+1 added-1 removed
42 unmodified lines43 for (const [pattern, routeMethod, handler] of this.routes) {44 if (routeMethod === METHOD_NAME_ALL || routeMethod === method) {45 const match = pattern.exec(path)46 if (match) {47- handlers.push([handler, match.groups || {}])47+ handlers.push([handler, match.groups || Object.create(null)])48 }49 }50 }51 3 unmodified linesmodified:src/router/reg-exp-router/node.ts+1 added-1 removed
43 unmodified lines44 45 export class Node {46 index?: number47 varIndex?: number48- children: Record<string, Node> = {}48+ children: Record<string, Node> = Object.create(null)49 50 insert(51 tokens: readonly string[],52 index: number,107 unmodified linesmodified:src/router/reg-exp-router/router.ts+10 added-10 removed
14 unmodified lines15 type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]16 17 const emptyParam: string[] = []18 // eslint-disable-next-line @typescript-eslint/no-explicit-any19-const nullMatcher: Matcher<any> = [/^$/, [], {}]19+const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]20 21-let wildcardRegExpCache: Record<string, RegExp> = {}21+let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)22 function buildWildcardRegExp(path: string): RegExp {23 return (wildcardRegExpCache[path] ??= new RegExp(24 path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`25 ))26 }27 28 function clearWildcardRegExpCache() {29- wildcardRegExpCache = {}29+ wildcardRegExpCache = Object.create(null)30 }31 32 function buildMatcherFromPreprocessedRoutes<T>(33 routes: [string, HandlerWithMetadata<T>[]][]11 unmodified lines45 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>46 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length47 )48 49- const staticMap: StaticMap<T> = {}49+ const staticMap: StaticMap<T> = Object.create(null)50 for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {51 const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]52 if (pathErrorCheckOnly) {53- staticMap[path] = [handlers.map(([h]) => [h, {}]), emptyParam]53+ staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]54 } else {55 j++56 }57 8 unmodified lines66 continue67 }68 69 handlerData[j] = handlers.map(([h, paramCount]) => {70- const paramIndexMap: ParamIndexMap = {}70+ const paramIndexMap: ParamIndexMap = Object.create(null)71 paramCount -= 172 for (; paramCount >= 0; paramCount--) {73 const [key, value] = paramAssoc[paramCount]74 paramIndexMap[key] = value47 unmodified lines122 middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>123 routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>124 125 constructor() {126- this.middleware = { [METHOD_NAME_ALL]: {} }127- this.routes = { [METHOD_NAME_ALL]: {} }126+ this.middleware = { [METHOD_NAME_ALL]: Object.create(null) }127+ this.routes = { [METHOD_NAME_ALL]: Object.create(null) }128 }129 130 add(method: string, path: string, handler: T) {131 const { middleware, routes } = this3 unmodified lines135 }136 137 if (!middleware[method]) {138 ;[middleware, routes].forEach((handlerMap) => {139- handlerMap[method] = {}139+ handlerMap[method] = Object.create(null)140 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {141 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]142 })143 })81 unmodified lines225 return this.match(method, path)226 }227 228 private buildAllMatchers(): Record<string, Matcher<T> | null> {229- const matchers: Record<string, Matcher<T> | null> = {}229+ const matchers: Record<string, Matcher<T> | null> = Object.create(null)230 231 ;[...Object.keys(this.routes!), ...Object.keys(this.middleware!)].forEach((method) => {232 matchers[method] ||= this.buildMatcher(method)233 })36 unmodified linesmodified:src/router/trie-router/node.test.ts+9 added
26 unmodified lines27 expect(node.search('get', '/hello')[0].length).toBe(1)28 })29 })30 31+describe('Get with * inclusing JS reserved words', () => {32+ const node = new Node()33+ node.insert('get', '*', 'get all')34+ it('get /', () => {35+ expect(node.search('get', '/hello/constructor')[0].length).toBe(1)36+ expect(node.search('get', '/hello/__proto__')[0].length).toBe(1)37+ })38+})39+40 describe('Basic Usage', () => {41 const node = new Node()42 node.insert('get', '/hello', 'get hello')43 node.insert('post', '/hello', 'post hello')752 unmodified linesmodified:src/router/trie-router/node.ts+12 added-10 removed
19 unmodified lines20 children: Record<string, Node<T>>21 patterns: Pattern[]22 order: number = 023 name: string24- params: Record<string, string> = {}24+ params: Record<string, string> = Object.create(null)25 26 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {27- this.children = children || {}27+ this.children = children || Object.create(null)28 this.methods = []29 this.name = ''30 if (method && handler) {31- const m: Record<string, HandlerSet<T>> = {}31+ const m: Record<string, HandlerSet<T>> = Object.create(null)32 m[method] = { handler, possibleKeys: [], score: 0, name: this.name }33 this.methods = [m]34 }35 this.patterns = []38 unmodified lines74 if (!curNode.methods.length) {75 curNode.methods = []76 }77 78- const m: Record<string, HandlerSet<T>> = {}78+ const m: Record<string, HandlerSet<T>> = Object.create(null)79 80 const handlerSet: HandlerSet<T> = {81 handler,82 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),17 unmodified lines100 const handlerSets: HandlerParamsSet<T>[] = []101 for (let i = 0, len = node.methods.length; i < len; i++) {102 const m = node.methods[i]103 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>104- const processedSet: Record<string, boolean> = {}104+ const processedSet: Record<string, boolean> = Object.create(null)105 if (handlerSet !== undefined) {106- handlerSet.params = {}106+ handlerSet.params = Object.create(null)107 handlerSet.possibleKeys.forEach((key) => {108 const processed = processedSet[handlerSet.name]109 handlerSet.params[key] =110 params[key] && !processed ? params[key] : nodeParams[key] ?? params[key]6 unmodified lines117 }118 119 search(method: string, path: string): [[T, Params][]] {120 const handlerSets: HandlerParamsSet<T>[] = []121- this.params = {}121+ this.params = Object.create(null)122 123 // eslint-disable-next-line @typescript-eslint/no-this-alias124 const curNode: Node<T> = this125 let curNodes = [curNode]12 unmodified lines138 nextNode.params = node.params139 if (isLast === true) {140 // '/hello/*' => match '/hello'141 if (nextNode.children['*']) {142- handlerSets.push(...this.gHSets(nextNode.children['*'], method, node.params, {}))142+ handlerSets.push(143+ ...this.gHSets(nextNode.children['*'], method, node.params, Object.create(null))144+ )145 }144- handlerSets.push(...this.gHSets(nextNode, method, node.params, {}))146+ handlerSets.push(...this.gHSets(nextNode, method, node.params, Object.create(null)))147 } else {148 tempNodes.push(nextNode)149 }150 }7 unmodified lines158 // '/hello/*/foo' => match /hello/bar/foo159 if (pattern === '*') {160 const astNode = node.children['*']161 if (astNode) {160- handlerSets.push(...this.gHSets(astNode, method, node.params, {}))162+ handlerSets.push(...this.gHSets(astNode, method, node.params, Object.create(null)))163 tempNodes.push(astNode)164 }165 continue166 }43 unmodified linesmodified:src/router/common.case.test.ts+26 added-1 removed
44 unmodified lines45 handler: r[0],46 params: Object.keys(r[1]).reduce((acc, key) => {47 acc[key] = stash[(r[1] as ParamIndexMap)[key]]48 return acc49- }, {} as Params),49+ }, Object.create(null) as Params),50 }51 : { handler: r[0], params: r[1] as Params }52 )53 return res23 unmodified lines77 expect(res.length).toBe(0)78 })79 })80 81+ describe('Reserved words', () => {82+ it('Reserved words and named parameter', async () => {83+ router.add('GET', '/entry/:constructor', 'get entry')84+ const res = match('GET', '/entry/123')85+ expect(res.length).toBe(1)86+ expect(res[0].handler).toEqual('get entry')87+ expect(res[0].params['constructor']).toBe('123')88+ })89+90+ it('Reserved words and wildcard', async () => {91+ router.add('GET', '/wild/*/card', 'get wildcard')92+ const res = match('GET', '/wild/constructor/card')93+ expect(res.length).toBe(1)94+ expect(res[0].handler).toEqual('get wildcard')95+ })96+97+ it('Reserved words and optional named parameter', async () => {98+ router.add('GET', '/api/animals/:constructor?', 'animals')99+ const res = match('GET', '/api/animals')100+ expect(res.length).toBe(1)101+ expect(res[0].handler).toEqual('animals')102+ expect(res[0].params['constructor']).toBeUndefined()103+ })104+ })105+106 describe('Complex', () => {107 it('Named Param', async () => {108 router.add('GET', '/entry/:id', 'get entry')109 const res = match('GET', '/entry/123')668 unmodified lines