Skip to content
Myr

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

12 files+87 added−49 removed

modified:deno_dist/router/linear-router/router.ts+2 added-2 removed
modified:deno_dist/router/pattern-router/router.ts+1 added-1 removed
modified:deno_dist/router/reg-exp-router/node.ts+1 added-1 removed
43 unmodified lines
4445export class Node {46 index?: number47 varIndex?: number48 children: Record<string, Node> = {}48 children: Record<string, Node> = Object.create(null)4950 insert(51 tokens: readonly string[],52 index: number,
107 unmodified lines
modified:deno_dist/router/reg-exp-router/router.ts+10 added-10 removed
14 unmodified lines
15type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]1617const emptyParam: string[] = []18// eslint-disable-next-line @typescript-eslint/no-explicit-any19const nullMatcher: Matcher<any> = [/^$/, [], {}]19const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]2021let wildcardRegExpCache: Record<string, RegExp> = {}21let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)22function buildWildcardRegExp(path: string): RegExp {23 return (wildcardRegExpCache[path] ??= new RegExp(24 path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`25 ))26}2728function clearWildcardRegExpCache() {29 wildcardRegExpCache = {}29 wildcardRegExpCache = Object.create(null)30}3132function buildMatcherFromPreprocessedRoutes<T>(33 routes: [string, HandlerWithMetadata<T>[]][]
11 unmodified lines
45 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>46 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length47 )4849 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 lines
66 continue67 }6869 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] = value
47 unmodified lines
122 middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>123 routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>124125 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 }129130 add(method: string, path: string, handler: T) {131 const { middleware, routes } = this
3 unmodified lines
135 }136137 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 lines
225 return this.match(method, path)226 }227228 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)230231 ;[...Object.keys(this.routes!), ...Object.keys(this.middleware!)].forEach((method) => {232 matchers[method] ||= this.buildMatcher(method)233 })
36 unmodified lines
modified:deno_dist/router/trie-router/node.ts+12 added-10 removed
19 unmodified lines
20 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)2526 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 lines
74 if (!curNode.methods.length) {75 curNode.methods = []76 }7778 const m: Record<string, HandlerSet<T>> = {}78 const m: Record<string, HandlerSet<T>> = Object.create(null)7980 const handlerSet: HandlerSet<T> = {81 handler,82 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
17 unmodified lines
100 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 lines
117 }118119 search(method: string, path: string): [[T, Params][]] {120 const handlerSets: HandlerParamsSet<T>[] = []121 this.params = {}121 this.params = Object.create(null)122123 // eslint-disable-next-line @typescript-eslint/no-this-alias124 const curNode: Node<T> = this125 let curNodes = [curNode]
12 unmodified lines
138 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 lines
158 // '/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 lines
modified:src/router/linear-router/router.ts+2 added-2 removed
2 unmodified lines
3import { checkOptionalParameter } from '../../utils/url'45type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }67const emptyParams = {}7const emptyParams = Object.create(null)89const splitPathRe = /\/(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/[^\/\?]+|(\?)/g10const splitByStarRe = /\*/11export class LinearRouter<T> implements Router<T> {
53 unmodified lines
65 }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[]7172 const lastIndex = parts.length - 173 for (let j = 0, pos = 0, len = parts.length; j < len; j++) {
59 unmodified lines
modified:src/router/pattern-router/router.ts+1 added-1 removed
42 unmodified lines
43 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 lines
modified:src/router/reg-exp-router/node.ts+1 added-1 removed
43 unmodified lines
4445export class Node {46 index?: number47 varIndex?: number48 children: Record<string, Node> = {}48 children: Record<string, Node> = Object.create(null)4950 insert(51 tokens: readonly string[],52 index: number,
107 unmodified lines
modified:src/router/reg-exp-router/router.ts+10 added-10 removed
14 unmodified lines
15type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]1617const emptyParam: string[] = []18// eslint-disable-next-line @typescript-eslint/no-explicit-any19const nullMatcher: Matcher<any> = [/^$/, [], {}]19const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]2021let wildcardRegExpCache: Record<string, RegExp> = {}21let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)22function buildWildcardRegExp(path: string): RegExp {23 return (wildcardRegExpCache[path] ??= new RegExp(24 path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`25 ))26}2728function clearWildcardRegExpCache() {29 wildcardRegExpCache = {}29 wildcardRegExpCache = Object.create(null)30}3132function buildMatcherFromPreprocessedRoutes<T>(33 routes: [string, HandlerWithMetadata<T>[]][]
11 unmodified lines
45 .sort(([isStaticA, pathA], [isStaticB, pathB]) =>46 isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length47 )4849 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 lines
66 continue67 }6869 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] = value
47 unmodified lines
122 middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>123 routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>124125 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 }129130 add(method: string, path: string, handler: T) {131 const { middleware, routes } = this
3 unmodified lines
135 }136137 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 lines
225 return this.match(method, path)226 }227228 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)230231 ;[...Object.keys(this.routes!), ...Object.keys(this.middleware!)].forEach((method) => {232 matchers[method] ||= this.buildMatcher(method)233 })
36 unmodified lines
modified:src/router/trie-router/node.test.ts+9 added
26 unmodified lines
27 expect(node.search('get', '/hello')[0].length).toBe(1)28 })29})3031describe('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})3940describe('Basic Usage', () => {41 const node = new Node()42 node.insert('get', '/hello', 'get hello')43 node.insert('post', '/hello', 'post hello')
752 unmodified lines
modified:src/router/trie-router/node.ts+12 added-10 removed
19 unmodified lines
20 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)2526 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 lines
74 if (!curNode.methods.length) {75 curNode.methods = []76 }7778 const m: Record<string, HandlerSet<T>> = {}78 const m: Record<string, HandlerSet<T>> = Object.create(null)7980 const handlerSet: HandlerSet<T> = {81 handler,82 possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
17 unmodified lines
100 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 lines
117 }118119 search(method: string, path: string): [[T, Params][]] {120 const handlerSets: HandlerParamsSet<T>[] = []121 this.params = {}121 this.params = Object.create(null)122123 // eslint-disable-next-line @typescript-eslint/no-this-alias124 const curNode: Node<T> = this125 let curNodes = [curNode]
12 unmodified lines
138 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 lines
158 // '/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 lines
modified:src/router/common.case.test.ts+26 added-1 removed
44 unmodified lines
45 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 res
23 unmodified lines
77 expect(res.length).toBe(0)78 })79 })8081 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 })8990 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 })9697 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 })105106 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