Skip to content

Commit

Permalink
fix: add interception route check
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongliang02 committed Jan 13, 2025
1 parent 87e2bb5 commit 8eb4bea
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 7 deletions.
2 changes: 1 addition & 1 deletion packages/validators/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@opengovsg/starter-kitty-validators",
"version": "1.2.10",
"version": "1.2.11",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
Expand Down
17 changes: 17 additions & 0 deletions packages/validators/src/url/nextjs-dynamic-route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// regex from https://github.com/vercel/next.js/blob/8cb8edb686ec8ddf7e24c69545d11175fcb9df02/packages/next/src/shared/lib/router/utils/is-dynamic.ts#L7
const DYNAMIC_ROUTE_SEGMENT_REGEX = /\/\[[^/]+?\](?=\/|$)/

// from https://github.com/vercel/next.js/blob/94bda4995ee5ea0bb5b73288d21918ceeb2b35be/packages/next/src/server/lib/interception-routes.ts#L11
function isInterceptionRouteAppPath(path: string): boolean {
const INTERCEPTION_ROUTE_MARKERS = ['(..)(..)', '(.)', '(..)', '(...)'] as const

return path.split('/').find(segment => INTERCEPTION_ROUTE_MARKERS.find(m => segment.startsWith(m))) !== undefined
}

export const isDynamicRoute = (url: URL): boolean => {
const route = url.pathname
if (isInterceptionRouteAppPath(route)) {
return true
}
return DYNAMIC_ROUTE_SEGMENT_REGEX.test(route)
}
7 changes: 1 addition & 6 deletions packages/validators/src/url/utils.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { UrlValidationError } from '@/url/errors'
import { isDynamicRoute } from '@/url/nextjs-dynamic-route'
import { UrlValidatorWhitelist } from '@/url/options'

// regex from https://github.com/vercel/next.js/blob/8cb8edb686ec8ddf7e24c69545d11175fcb9df02/packages/next/src/shared/lib/router/utils/is-dynamic.ts#L7
const DYNAMIC_ROUTE_SEGMENT_REGEX = /\/\[[^/]+?\](?=\/|$)/
const IS_NOT_HOSTNAME_REGEX = /[^.]+\.[^.]+/g

export const resolveRelativeUrl = (url: string, baseOrigin?: URL): URL => {
Expand All @@ -27,10 +26,6 @@ export const resolveRelativeUrl = (url: string, baseOrigin?: URL): URL => {
return normalizedUrl
}

export const isDynamicRoute = (url: URL): boolean => {
return DYNAMIC_ROUTE_SEGMENT_REGEX.test(url.pathname)
}

export const isSafeUrl = (url: URL, whitelist: UrlValidatorWhitelist) => {
// only allow whitelisted protocols
if (!whitelist.protocols.some(protocol => url.protocol === `${protocol}:`)) {
Expand Down

0 comments on commit 8eb4bea

Please sign in to comment.