-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: ensure RegExp[] origin can be passed to appSecurityOptions
- Loading branch information
Showing
3 changed files
with
72 additions
and
14 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
import type { CorsOptions } from '../module'; | ||
|
||
const REG_SERIALIZE_KEY = '_nuxt_security_origin_serialized_regexp'; | ||
|
||
export const modifyRegExpToJSON = (reg: RegExp) => { | ||
(reg as any).toJSON = () => ({ | ||
[REG_SERIALIZE_KEY]: reg.toString(), | ||
}); | ||
}; | ||
|
||
export const getDeserializedRegExp = (regObj: Record<string, string>) => { | ||
const regStr = regObj?.[REG_SERIALIZE_KEY]; | ||
if (typeof regStr !== 'string') return null; | ||
const fragments = regStr.match(/\/(.*?)\/([a-z]*)?$/i); | ||
if (!fragments?.length) return null; | ||
return new RegExp(fragments?.[1], fragments?.[2] || ''); | ||
}; | ||
|
||
export const modifyCorsHandlerOriginRegExpToJSON = (corsHandler?: CorsOptions | false) => { | ||
if (typeof corsHandler === 'object' && Array.isArray(corsHandler.origin)) { | ||
corsHandler.origin.forEach((o) => { | ||
o instanceof RegExp && modifyRegExpToJSON(o); | ||
}); | ||
} | ||
}; | ||
|
||
export const getRegExpOriginRestoredCorsHandler = (corsHandler?: CorsOptions | false) => { | ||
let originOption = typeof corsHandler === 'object' ? corsHandler.origin : undefined; | ||
if (typeof corsHandler !== 'object') return corsHandler; | ||
if (Array.isArray(corsHandler.origin)) { | ||
originOption = corsHandler.origin.map((o) => { | ||
const origin = getDeserializedRegExp(o as any); | ||
return origin ?? o; | ||
}); | ||
} | ||
const result: CorsOptions = { | ||
...corsHandler, | ||
origin: originOption, | ||
}; | ||
return result; | ||
}; |