next-csrf
Version:
CSRF mitigation library for Next.js
1 lines • 17.8 kB
JSON
{"ast":null,"code":"\"use strict\";\n\nvar _regeneratorRuntime = require(\"@babel/runtime/regenerator\");\n\nvar _asyncToGenerator = require(\"@babel/runtime/helpers/asyncToGenerator\");\n\nexports.__esModule = true;\nexports.execOnce = execOnce;\nexports.getLocationOrigin = getLocationOrigin;\nexports.getURL = getURL;\nexports.getDisplayName = getDisplayName;\nexports.isResSent = isResSent;\nexports.loadGetInitialProps = loadGetInitialProps;\nexports.formatWithValidation = formatWithValidation;\nexports.ST = exports.SP = exports.urlObjectKeys = void 0;\n\nvar _formatUrl = require(\"./router/utils/format-url\");\n/**\n* Utils\n*/\n\n\nfunction execOnce(fn) {\n var used = false;\n var result;\n return function () {\n if (!used) {\n used = true;\n result = fn.apply(void 0, arguments);\n }\n\n return result;\n };\n}\n\nfunction getLocationOrigin() {\n var _window$location = window.location,\n protocol = _window$location.protocol,\n hostname = _window$location.hostname,\n port = _window$location.port;\n return \"\".concat(protocol, \"//\").concat(hostname).concat(port ? ':' + port : '');\n}\n\nfunction getURL() {\n var href = window.location.href;\n var origin = getLocationOrigin();\n return href.substring(origin.length);\n}\n\nfunction getDisplayName(Component) {\n return typeof Component === 'string' ? Component : Component.displayName || Component.name || 'Unknown';\n}\n\nfunction isResSent(res) {\n return res.finished || res.headersSent;\n}\n\nfunction loadGetInitialProps(_x, _x2) {\n return _loadGetInitialProps.apply(this, arguments);\n}\n\nfunction _loadGetInitialProps() {\n _loadGetInitialProps = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(App, ctx) {\n var _App$prototype, message, res, props, _message;\n\n return _regeneratorRuntime.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n if (!true) {\n _context.next = 4;\n break;\n }\n\n if (!((_App$prototype = App.prototype) === null || _App$prototype === void 0 ? void 0 : _App$prototype.getInitialProps)) {\n _context.next = 4;\n break;\n }\n\n message = \"\\\"\".concat(getDisplayName(App), \".getInitialProps()\\\" is defined as an instance method - visit https://err.sh/vercel/next.js/get-initial-props-as-an-instance-method for more information.\");\n throw new Error(message);\n\n case 4:\n // when called from _app `ctx` is nested in `ctx`\n res = ctx.res || ctx.ctx && ctx.ctx.res;\n\n if (App.getInitialProps) {\n _context.next = 12;\n break;\n }\n\n if (!(ctx.ctx && ctx.Component)) {\n _context.next = 11;\n break;\n }\n\n _context.next = 9;\n return loadGetInitialProps(ctx.Component, ctx.ctx);\n\n case 9:\n _context.t0 = _context.sent;\n return _context.abrupt(\"return\", {\n pageProps: _context.t0\n });\n\n case 11:\n return _context.abrupt(\"return\", {});\n\n case 12:\n _context.next = 14;\n return App.getInitialProps(ctx);\n\n case 14:\n props = _context.sent;\n\n if (!(res && isResSent(res))) {\n _context.next = 17;\n break;\n }\n\n return _context.abrupt(\"return\", props);\n\n case 17:\n if (props) {\n _context.next = 20;\n break;\n }\n\n _message = \"\\\"\".concat(getDisplayName(App), \".getInitialProps()\\\" should resolve to an object. But found \\\"\").concat(props, \"\\\" instead.\");\n throw new Error(_message);\n\n case 20:\n if (true) {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\"\".concat(getDisplayName(App), \" returned an empty object from `getInitialProps`. This de-optimizes and prevents automatic static optimization. https://err.sh/vercel/next.js/empty-object-getInitialProps\"));\n }\n }\n\n return _context.abrupt(\"return\", props);\n\n case 22:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n }));\n return _loadGetInitialProps.apply(this, arguments);\n}\n\nvar urlObjectKeys = ['auth', 'hash', 'host', 'hostname', 'href', 'path', 'pathname', 'port', 'protocol', 'query', 'search', 'slashes'];\nexports.urlObjectKeys = urlObjectKeys;\n\nfunction formatWithValidation(url) {\n if (true) {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach(function (key) {\n if (urlObjectKeys.indexOf(key) === -1) {\n console.warn(\"Unknown key passed via urlObject into url.format: \".concat(key));\n }\n });\n }\n }\n\n return (0, _formatUrl.formatUrl)(url);\n}\n\nvar SP = typeof performance !== 'undefined';\nexports.SP = SP;\nvar ST = SP && typeof performance.mark === 'function' && typeof performance.measure === 'function';\nexports.ST = ST;","map":{"version":3,"sources":["../../../next-server/lib/utils.ts"],"names":["used","result","fn","window","protocol","hostname","port","origin","getLocationOrigin","href","Component","res","App","message","getDisplayName","ctx","pageProps","loadGetInitialProps","props","isResSent","Object","console","urlObjectKeys","url","key","SP","ST","performance"],"mappings":";;;;;;;;;;;;;;;;AAIA,IAAA,UAAA,GAAA,OAAA,CAAA,2BAAA,CAAA;AAkQA;;;;;AAGO,SAAA,QAAA,CAAA,EAAA,EAEF;AACH,MAAIA,IAAI,GAAR,KAAA;AACA,MAAA,MAAA;AAEA,SAAQ,YAAoB;AAC1B,QAAI,CAAJ,IAAA,EAAW;AACTA,MAAAA,IAAI,GAAJA,IAAAA;AACAC,MAAAA,MAAM,GAAGC,EAATD,MAASC,mBAATD;AAEF;;AAAA,WAAA,MAAA;AALF,GAAA;AASK;;AAAA,SAAA,iBAAA,GAA6B;AAAA,yBACGE,MAAM,CAA3C,QADkC;AAAA,MAC5B,QAD4B,oBAC5B,QAD4B;AAAA,MAC5B,QAD4B,oBAC5B,QAD4B;AAAA,MAC5B,IAD4B,oBAC5B,IAD4B;AAElC,mBAAUC,QAAV,eAAuBC,QAAvB,SAAkCC,IAAI,GAAG,MAAH,IAAA,GAAtC,EAAA;AAGK;;AAAA,SAAA,MAAA,GAAkB;AAAA,MACjB,IADiB,GACNH,MAAM,CAAvB,QADuB,CACjB,IADiB;AAEvB,MAAMI,MAAM,GAAGC,iBAAf,EAAA;AACA,SAAOC,IAAI,CAAJA,SAAAA,CAAeF,MAAM,CAA5B,MAAOE,CAAP;AAGK;;AAAA,SAAA,cAAA,CAAA,SAAA,EAAwD;AAC7D,SAAO,OAAA,SAAA,KAAA,QAAA,GAAA,SAAA,GAEHC,SAAS,CAATA,WAAAA,IAAyBA,SAAS,CAAlCA,IAAAA,IAFJ,SAAA;A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AAAA,kBAoCG,IAAA,KAAA,CAAN,QAAM,CApCH;;AAAA;AAuCL,sBAA2C;AACzC,kBAAIM,MAAM,CAANA,IAAAA,CAAAA,KAAAA,EAAAA,MAAAA,KAAAA,CAAAA,IAAmC,CAACL,GAAG,CAA3C,GAAA,EAAiD;AAC/CM,gBAAAA,OAAO,CAAPA,IAAAA,WACKP,cAAc,CADnBO,GACmB,CADnBA;AAMH;AAED;;AAjDK,6CAiDL,KAjDK;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,G;;;;AAoDA,IAAMC,aAAa,GAAG,CAAA,MAAA,EAAA,MAAA,EAAA,MAAA,EAAA,UAAA,EAAA,MAAA,EAAA,MAAA,EAAA,UAAA,EAAA,MAAA,EAAA,UAAA,EAAA,OAAA,EAAA,QAAA,EAAtB,SAAsB,CAAtB;;;AAeA,SAAA,oBAAA,CAAA,GAAA,EAAsD;AAC3D,YAA4C;AAC1C,QAAIC,GAAG,KAAHA,IAAAA,IAAgB,OAAA,GAAA,KAApB,QAAA,EAA6C;AAC3CH,MAAAA,MAAM,CAANA,IAAAA,CAAAA,GAAAA,EAAAA,OAAAA,CAA0BI,UAAAA,GAAD,EAAS;AAChC,YAAIF,aAAa,CAAbA,OAAAA,CAAAA,GAAAA,MAA+B,CAAnC,CAAA,EAAuC;AACrCD,UAAAA,OAAO,CAAPA,IAAAA,6DAAAA,GAAAA;AAIH;AANDD,OAAAA;AAQH;AAED;;AAAA,SAAO,CAAA,GAAA,UAAA,CAAA,SAAA,EAAP,GAAO,CAAP;AAGK;;AAAA,IAAMK,EAAE,GAAG,OAAA,WAAA,KAAX,WAAA;;AACA,IAAMC,EAAE,GACbD,EAAE,IACF,OAAOE,WAAW,CAAlB,IAAA,KADAF,UAAAA,IAEA,OAAOE,WAAW,CAAlB,OAAA,KAHK,UAAA","sourcesContent":["import { IncomingMessage, ServerResponse } from 'http'\nimport { ParsedUrlQuery } from 'querystring'\nimport { ComponentType } from 'react'\nimport { UrlObject } from 'url'\nimport { formatUrl } from './router/utils/format-url'\nimport { ManifestItem } from '../server/load-components'\nimport { NextRouter } from './router/router'\nimport { Env } from '../../lib/load-env-config'\nimport { BuildManifest } from '../server/get-page-files'\n\n/**\n * Types used by both next and next-server\n */\n\nexport type NextComponentType<\n C extends BaseContext = NextPageContext,\n IP = {},\n P = {}\n> = ComponentType<P> & {\n /**\n * Used for initial page load data population. Data returned from `getInitialProps` is serialized when server rendered.\n * Make sure to return plain `Object` without using `Date`, `Map`, `Set`.\n * @param ctx Context of `page`\n */\n getInitialProps?(context: C): IP | Promise<IP>\n}\n\nexport type DocumentType = NextComponentType<\n DocumentContext,\n DocumentInitialProps,\n DocumentProps\n> & {\n renderDocument(\n Document: DocumentType,\n props: DocumentProps\n ): React.ReactElement\n}\n\nexport type AppType = NextComponentType<\n AppContextType,\n AppInitialProps,\n AppPropsType\n>\n\nexport type AppTreeType = ComponentType<\n AppInitialProps & { [name: string]: any }\n>\n\n/**\n * Web vitals provided to _app.reportWebVitals by Core Web Vitals plugin developed by Google Chrome team.\n * https://nextjs.org/blog/next-9-4#integrated-web-vitals-reporting\n */\nexport type NextWebVitalsMetric = {\n id: string\n label: string\n name: string\n startTime: number\n value: number\n}\n\nexport type Enhancer<C> = (Component: C) => C\n\nexport type ComponentsEnhancer =\n | {\n enhanceApp?: Enhancer<AppType>\n enhanceComponent?: Enhancer<NextComponentType>\n }\n | Enhancer<NextComponentType>\n\nexport type RenderPageResult = {\n html: string\n head?: Array<JSX.Element | null>\n}\n\nexport type RenderPage = (\n options?: ComponentsEnhancer\n) => RenderPageResult | Promise<RenderPageResult>\n\nexport type BaseContext = {\n res?: ServerResponse\n [k: string]: any\n}\n\nexport type NEXT_DATA = {\n props: Record<string, any>\n page: string\n query: ParsedUrlQuery\n buildId: string\n assetPrefix?: string\n runtimeConfig?: { [key: string]: any }\n nextExport?: boolean\n autoExport?: boolean\n isFallback?: boolean\n dynamicIds?: string[]\n err?: Error & { statusCode?: number }\n gsp?: boolean\n gssp?: boolean\n customServer?: boolean\n gip?: boolean\n appGip?: boolean\n}\n\n/**\n * `Next` context\n */\nexport interface NextPageContext {\n /**\n * Error object if encountered during rendering\n */\n err?: (Error & { statusCode?: number }) | null\n /**\n * `HTTP` request object.\n */\n req?: IncomingMessage\n /**\n * `HTTP` response object.\n */\n res?: ServerResponse\n /**\n * Path section of `URL`.\n */\n pathname: string\n /**\n * Query string section of `URL` parsed as an object.\n */\n query: ParsedUrlQuery\n /**\n * `String` of the actual path including query.\n */\n asPath?: string\n /**\n * `Component` the tree of the App to use if needing to render separately\n */\n AppTree: AppTreeType\n}\n\nexport type AppContextType<R extends NextRouter = NextRouter> = {\n Component: NextComponentType<NextPageContext>\n AppTree: AppTreeType\n ctx: NextPageContext\n router: R\n}\n\nexport type AppInitialProps = {\n pageProps: any\n}\n\nexport type AppPropsType<\n R extends NextRouter = NextRouter,\n P = {}\n> = AppInitialProps & {\n Component: NextComponentType<NextPageContext, any, P>\n router: R\n __N_SSG?: boolean\n __N_SSP?: boolean\n}\n\nexport type DocumentContext = NextPageContext & {\n renderPage: RenderPage\n}\n\nexport type DocumentInitialProps = RenderPageResult & {\n styles?: React.ReactElement[] | React.ReactFragment\n}\n\nexport type DocumentProps = DocumentInitialProps & {\n __NEXT_DATA__: NEXT_DATA\n dangerousAsPath: string\n docComponentsRendered: {\n Html?: boolean\n Main?: boolean\n Head?: boolean\n NextScript?: boolean\n }\n buildManifest: BuildManifest\n ampPath: string\n inAmpMode: boolean\n hybridAmp: boolean\n isDevelopment: boolean\n dynamicImports: ManifestItem[]\n assetPrefix?: string\n canonicalBase: string\n headTags: any[]\n unstable_runtimeJS?: false\n devOnlyCacheBusterQueryString: string\n}\n\n/**\n * Next `API` route request\n */\nexport interface NextApiRequest extends IncomingMessage {\n /**\n * Object of `query` values from url\n */\n query: {\n [key: string]: string | string[]\n }\n /**\n * Object of `cookies` from header\n */\n cookies: {\n [key: string]: string\n }\n\n body: any\n\n env: Env\n\n preview?: boolean\n /**\n * Preview data set on the request, if any\n * */\n previewData?: any\n}\n\n/**\n * Send body of response\n */\ntype Send<T> = (body: T) => void\n\n/**\n * Next `API` route response\n */\nexport type NextApiResponse<T = any> = ServerResponse & {\n /**\n * Send data `any` data in response\n */\n send: Send<T>\n /**\n * Send data `json` data in response\n */\n json: Send<T>\n status: (statusCode: number) => NextApiResponse<T>\n redirect(url: string): NextApiResponse<T>\n redirect(status: number, url: string): NextApiResponse<T>\n\n /**\n * Set preview data for Next.js' prerender mode\n */\n setPreviewData: (\n data: object | string,\n options?: {\n /**\n * Specifies the number (in seconds) for the preview session to last for.\n * The given number will be converted to an integer by rounding down.\n * By default, no maximum age is set and the preview session finishes\n * when the client shuts down (browser is closed).\n */\n maxAge?: number\n }\n ) => NextApiResponse<T>\n clearPreviewData: () => NextApiResponse<T>\n}\n\n/**\n * Next `API` route handler\n */\nexport type NextApiHandler<T = any> = (\n req: NextApiRequest,\n res: NextApiResponse<T>\n) => void | Promise<void>\n\n/**\n * Utils\n */\nexport function execOnce<T extends (...args: any[]) => ReturnType<T>>(\n fn: T\n): T {\n let used = false\n let result: ReturnType<T>\n\n return ((...args: any[]) => {\n if (!used) {\n used = true\n result = fn(...args)\n }\n return result\n }) as T\n}\n\nexport function getLocationOrigin() {\n const { protocol, hostname, port } = window.location\n return `${protocol}//${hostname}${port ? ':' + port : ''}`\n}\n\nexport function getURL() {\n const { href } = window.location\n const origin = getLocationOrigin()\n return href.substring(origin.length)\n}\n\nexport function getDisplayName<P>(Component: ComponentType<P>) {\n return typeof Component === 'string'\n ? Component\n : Component.displayName || Component.name || 'Unknown'\n}\n\nexport function isResSent(res: ServerResponse) {\n return res.finished || res.headersSent\n}\n\nexport async function loadGetInitialProps<\n C extends BaseContext,\n IP = {},\n P = {}\n>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {\n if (process.env.NODE_ENV !== 'production') {\n if (App.prototype?.getInitialProps) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" is defined as an instance method - visit https://err.sh/vercel/next.js/get-initial-props-as-an-instance-method for more information.`\n throw new Error(message)\n }\n }\n // when called from _app `ctx` is nested in `ctx`\n const res = ctx.res || (ctx.ctx && ctx.ctx.res)\n\n if (!App.getInitialProps) {\n if (ctx.ctx && ctx.Component) {\n // @ts-ignore pageProps default\n return {\n pageProps: await loadGetInitialProps(ctx.Component, ctx.ctx),\n }\n }\n return {} as IP\n }\n\n const props = await App.getInitialProps(ctx)\n\n if (res && isResSent(res)) {\n return props\n }\n\n if (!props) {\n const message = `\"${getDisplayName(\n App\n )}.getInitialProps()\" should resolve to an object. But found \"${props}\" instead.`\n throw new Error(message)\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (Object.keys(props).length === 0 && !ctx.ctx) {\n console.warn(\n `${getDisplayName(\n App\n )} returned an empty object from \\`getInitialProps\\`. This de-optimizes and prevents automatic static optimization. https://err.sh/vercel/next.js/empty-object-getInitialProps`\n )\n }\n }\n\n return props\n}\n\nexport const urlObjectKeys = [\n 'auth',\n 'hash',\n 'host',\n 'hostname',\n 'href',\n 'path',\n 'pathname',\n 'port',\n 'protocol',\n 'query',\n 'search',\n 'slashes',\n]\n\nexport function formatWithValidation(url: UrlObject): string {\n if (process.env.NODE_ENV === 'development') {\n if (url !== null && typeof url === 'object') {\n Object.keys(url).forEach((key) => {\n if (urlObjectKeys.indexOf(key) === -1) {\n console.warn(\n `Unknown key passed via urlObject into url.format: ${key}`\n )\n }\n })\n }\n }\n\n return formatUrl(url)\n}\n\nexport const SP = typeof performance !== 'undefined'\nexport const ST =\n SP &&\n typeof performance.mark === 'function' &&\n typeof performance.measure === 'function'\n"]},"metadata":{},"sourceType":"script"}