@faststore/core 3.100.3 → 3.100.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +22 -22
  3. package/.next/cache/.tsbuildinfo +1 -1
  4. package/.next/cache/config.json +3 -3
  5. package/.next/cache/webpack/client-production/0.pack +2 -2
  6. package/.next/cache/webpack/client-production/index.pack +0 -0
  7. package/.next/cache/webpack/edge-server-production/0.pack +0 -0
  8. package/.next/cache/webpack/edge-server-production/index.pack +0 -0
  9. package/.next/cache/webpack/server-production/0.pack +2 -2
  10. package/.next/cache/webpack/server-production/index.pack +0 -0
  11. package/.next/prerender-manifest.js +1 -1
  12. package/.next/prerender-manifest.json +1 -1
  13. package/.next/react-loadable-manifest.json +6 -6
  14. package/.next/routes-manifest.json +1 -1
  15. package/.next/server/chunks/7098.js +2 -2
  16. package/.next/server/functions-config-manifest.json +1 -1
  17. package/.next/server/middleware-build-manifest.js +1 -1
  18. package/.next/server/middleware-react-loadable-manifest.js +1 -1
  19. package/.next/server/pages/api/graphql.js +3 -3
  20. package/.next/server/pages/en-US/404.html +2 -2
  21. package/.next/server/pages/en-US/500.html +2 -2
  22. package/.next/server/pages/en-US/checkout.html +2 -2
  23. package/.next/server/pages/en-US/login.html +2 -2
  24. package/.next/server/pages/en-US/password-protection.html +2 -2
  25. package/.next/server/pages/en-US/s.html +2 -2
  26. package/.next/server/pages/en-US.html +2 -2
  27. package/.next/server/pages-manifest.json +1 -1
  28. package/.next/static/chunks/{2927.5a79877943a6bf7c.js → 2927.23bae2c79f0ac0f3.js} +1 -1
  29. package/.next/static/chunks/{UIToast.19a8664c01a00d3a.js → UIToast.de15325248043ce5.js} +1 -1
  30. package/.next/static/chunks/{webpack-25c67512e1907efd.js → webpack-6a844a3f6a390f62.js} +1 -1
  31. package/.next/trace +156 -156
  32. package/.turbo/turbo-build.log +9 -9
  33. package/.turbo/turbo-test.log +12 -10
  34. package/CHANGELOG.md +18 -0
  35. package/package.json +2 -2
  36. package/src/pages/api/graphql.ts +40 -26
  37. package/src/sdk/redirects/index.ts +20 -2
  38. package/src/utils/trustedForwardedHost.ts +50 -0
  39. package/test/sdk/redirects/index.test.ts +134 -0
  40. package/test/utils/trustedForwardedHost.test.ts +103 -0
  41. /package/.next/static/{0OKcQtIHO8diwBsczup15 → TfWW2xib3Snr8xF4Ldqws}/_buildManifest.js +0 -0
  42. /package/.next/static/{0OKcQtIHO8diwBsczup15 → TfWW2xib3Snr8xF4Ldqws}/_ssgManifest.js +0 -0
@@ -1,23 +1,23 @@
1
1
 
2
- > @faststore/core@3.100.2 prebuild /home/runner/work/faststore/faststore/packages/core
2
+ > @faststore/core@3.100.4 prebuild /home/runner/work/faststore/faststore/packages/core
3
3
  > na run partytown && na run generate
4
4
 
5
5
 
6
- > @faststore/core@3.100.2 partytown /home/runner/work/faststore/faststore/packages/core
6
+ > @faststore/core@3.100.4 partytown /home/runner/work/faststore/faststore/packages/core
7
7
  > partytown copylib ./public/~partytown
8
8
 
9
9
  Partytown lib copied to: /home/runner/work/faststore/faststore/packages/core/public/~partytown
10
10
 
11
- > @faststore/core@3.100.2 generate /home/runner/work/faststore/faststore/packages/core
11
+ > @faststore/core@3.100.4 generate /home/runner/work/faststore/faststore/packages/core
12
12
  > na run generate:schema && na run generate:codegen && na run format:generated
13
13
 
14
14
 
15
- > @faststore/core@3.100.2 generate:schema /home/runner/work/faststore/faststore/packages/core
15
+ > @faststore/core@3.100.4 generate:schema /home/runner/work/faststore/faststore/packages/core
16
16
  > tsx src/server/generator/generateGraphQLSchemaFile.ts
17
17
 
18
18
  Schema GraphQL file generated successfully
19
19
 
20
- > @faststore/core@3.100.2 generate:codegen /home/runner/work/faststore/faststore/packages/core
20
+ > @faststore/core@3.100.4 generate:codegen /home/runner/work/faststore/faststore/packages/core
21
21
  > graphql-codegen
22
22
 
23
23
  [STARTED] Parse Configuration
@@ -37,11 +37,11 @@ Running lifecycle hook "afterStart" scripts...
37
37
  [CLI] Loading Documents
38
38
  [CLI] Generating output
39
39
 
40
- > @faststore/core@3.100.2 format:generated /home/runner/work/faststore/faststore/packages/core
40
+ > @faststore/core@3.100.4 format:generated /home/runner/work/faststore/faststore/packages/core
41
41
  > prettier --write "@generated/**/*.{ts,js,tsx,jsx,json}" --loglevel error
42
42
 
43
43
 
44
- > @faststore/core@3.100.2 build /home/runner/work/faststore/faststore/packages/core
44
+ > @faststore/core@3.100.4 build /home/runner/work/faststore/faststore/packages/core
45
45
  > next build
46
46
 
47
47
  ⚠ No build cache found. Please configure build caching for faster rebuilds. Read more: https://nextjs.org/docs/messages/no-cache
@@ -58,7 +58,7 @@ Browserslist: caniuse-lite is outdated. Please run:
58
58
  Creating an optimized production build ...
59
59
  Disabled SWC as replacement for Babel because of custom Babel configuration ".babelrc.js" https://nextjs.org/docs/messages/swc-disabled
60
60
  Using external babel configuration from /home/runner/work/faststore/faststore/packages/core/.babelrc.js
61
- Browserslist: browsers data (caniuse-lite) is 17 months old. Please run:
61
+ Browserslist: browsers data (caniuse-lite) is 21 months old. Please run:
62
62
  npx update-browserslist-db@latest
63
63
  Why you should do it regularly: https://github.com/browserslist/update-db#readme
64
64
  <w> [webpack.cache.PackFileCacheStrategy] Skipped not serializable cache item 'Compilation/modules|/home/runner/work/faststore/faststore/node_modules/.pnpm/next@13.5.11_@babel+core@7.26.7_@opentelemetry+api@1.4.1_react-dom@18.3.1_react@18.3.1__react@18.3.1_sass@1.83.4/node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[7].oneOf[9].use[1]!/home/runner/work/faststore/faststore/node_modules/.pnpm/next@13.5.11_@babel+core@7.26.7_@opentelemetry+api@1.4.1_react-dom@18.3.1_react@18.3.1__react@18.3.1_sass@1.83.4/node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[7].oneOf[9].use[2]!/home/runner/work/faststore/faststore/node_modules/.pnpm/next@13.5.11_@babel+core@7.26.7_@opentelemetry+api@1.4.1_react-dom@18.3.1_react@18.3.1__react@18.3.1_sass@1.83.4/node_modules/next/dist/build/webpack/loaders/resolve-url-loader/index.js??ruleSet[1].rules[7].oneOf[9].use[3]!/home/runner/work/faststore/faststore/node_modules/.pnpm/next@13.5.11_@babel+core@7.26.7_@opentelemetry+api@1.4.1_react-dom@18.3.1_react@18.3.1__react@18.3.1_sass@1.83.4/node_modules/next/dist/compiled/sass-loader/cjs.js??ruleSet[1].rules[7].oneOf[9].use[4]!/home/runner/work/faststore/faststore/packages/core/src/components/common/Toast/section.module.scss': No serializer registered for Warning
@@ -154,7 +154,7 @@ Route (pages) Size First Load JS
154
154
  ├ chunks/framework-d514426edf885c68.js 45.4 kB
155
155
  ├ chunks/main-a2d1cfe626f2fef1.js 33.4 kB
156
156
  ├ chunks/pages/_app-35e8dda638ee2672.js 26.6 kB
157
- ├ chunks/webpack-25c67512e1907efd.js 3.9 kB
157
+ ├ chunks/webpack-6a844a3f6a390f62.js 3.9 kB
158
158
  └ css/146a8678babc61bf.css 9.2 kB
159
159
 
160
160
  ƒ Middleware 44.8 kB
@@ -1,20 +1,22 @@
1
1
 
2
- > @faststore/core@3.100.2 test /home/runner/work/faststore/faststore/packages/core
2
+ > @faststore/core@3.100.4 test /home/runner/work/faststore/faststore/packages/core
3
3
  > jest
4
4
 
5
- PASS test/utils/clearCookies.test.ts (9.746 s)
5
+ PASS test/utils/clearCookies.test.ts (13.987 s)
6
+ PASS test/server/password-protection-service.test.ts (18.623 s)
7
+ PASS test/utils/cookieCacheBusting.test.ts (16.597 s)
6
8
  PASS test/utils/multipleTemplates.test.ts
7
- PASS test/server/password-protection-service.test.ts (16.656 s)
8
- PASS test/utils/cookieCacheBusting.test.ts (15.853 s)
9
- PASS test/server/cms/global.test.ts
9
+ PASS test/sdk/redirects/index.test.ts
10
+ PASS test/utils/trustedForwardedHost.test.ts
10
11
  PASS test/utils/validateSessionRefreshToken.test.ts
12
+ PASS test/server/cms/global.test.ts
11
13
  PASS test/utils/isLocalHost.test.ts
12
- PASS test/server/cms/index.test.ts
13
14
  PASS test/utils/isLocalHost.browser.test.ts
14
- PASS test/server/index.test.ts (11.788 s)
15
+ PASS test/server/cms/index.test.ts (5.82 s)
16
+ PASS test/server/index.test.ts (10.891 s)
15
17
 
16
- Test Suites: 10 passed, 10 total
17
- Tests: 85 passed, 85 total
18
+ Test Suites: 12 passed, 12 total
19
+ Tests: 119 passed, 119 total
18
20
  Snapshots: 0 total
19
- Time: 27.32 s
21
+ Time: 30.388 s
20
22
  Ran all test suites.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,24 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [3.100.6](https://github.com/vtex/faststore/compare/v3.100.5...v3.100.6) (2026-10-07)
7
+
8
+ ### Bug Fixes
9
+
10
+ - address security & functional concerns from dk review (3.x backport) ([c928a1f](https://github.com/vtex/faststore/commit/c928a1fc04bc3554d83302c4cf760adab0f7e81c))
11
+ - **core:** harden x-forwarded-host handling and drop orderNumber fallback ([55990c1](https://github.com/vtex/faststore/commit/55990c1c6208c06ae482e71816df2035292bf2e9)), closes [#3178](https://github.com/vtex/faststore/issues/3178)
12
+ - **core:** ignore multi-value x-forwarded-host and cover port and case ([81ba26b](https://github.com/vtex/faststore/commit/81ba26b93175878b9cc3e32683f9c13b0abf25e9))
13
+ - **core:** log ignored x-forwarded-host and cover CR/LF hostnames ([e6a326f](https://github.com/vtex/faststore/commit/e6a326f6d0d4a91c75b9f0a10abfdc7c22c897be))
14
+ - **core:** make preview cookies host-only instead of rewriting their domain ([989fc69](https://github.com/vtex/faststore/commit/989fc69c573c980e354d11e3c3d8a719e2833fb2))
15
+ - **core:** reject hostnames that would inject Set-Cookie attributes ([109d819](https://github.com/vtex/faststore/commit/109d81917e1200dd78b9500f4cb81d128c78003d))
16
+ - resolve ValidateCartMutation infinite loop in preview environments (SFS-3034) ([ad7800d](https://github.com/vtex/faststore/commit/ad7800d65493c7477c9fb30119f76925647c40fc)), closes [#3178](https://github.com/vtex/faststore/issues/3178) [#3178](https://github.com/vtex/faststore/issues/3178) [#3190](https://github.com/vtex/faststore/issues/3190) [#3188](https://github.com/vtex/faststore/issues/3188) [#1467584](https://github.com/vtex/faststore/issues/1467584)
17
+
18
+ ## [3.100.4](https://github.com/vtex/faststore/compare/v3.100.3...v3.100.4) (2026-08-28)
19
+
20
+ ### Bug Fixes
21
+
22
+ - **core:** resolve redirect matcher module explicitly ([#3468](https://github.com/vtex/faststore/issues/3468)) ([fe3a3c7](https://github.com/vtex/faststore/commit/fe3a3c7c19237d53061be7b205838b626e225786)), closes [#3467](https://github.com/vtex/faststore/issues/3467) [#1450148](https://github.com/vtex/faststore/issues/1450148)
23
+
6
24
  ## [3.100.3](https://github.com/vtex/faststore/compare/v3.100.2...v3.100.3) (2026-06-30)
7
25
 
8
26
  ### Bug Fixes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faststore/core",
3
- "version": "3.100.3",
3
+ "version": "3.100.6",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -127,5 +127,5 @@
127
127
  "ts-jest": "29.1.1",
128
128
  "typescript": "5.3.2"
129
129
  },
130
- "gitHead": "bf4812f3e3a53108f22ab987098b74f7eed9bfa3"
130
+ "gitHead": "31df58321c484732bd4a69618e9eb09e6a2c0261"
131
131
  }
@@ -10,6 +10,11 @@ import type { NextApiHandler, NextApiRequest } from 'next'
10
10
  import discoveryConfig from 'discovery.config'
11
11
  import { getJWTAutCookie } from 'src/utils/getCookie'
12
12
  import { isLocalHost } from 'src/utils/isLocalHost'
13
+ import {
14
+ isHostAllowed,
15
+ removeCookieDomain,
16
+ singleForwardedHost,
17
+ } from 'src/utils/trustedForwardedHost'
13
18
  import { shouldForceRefreshTokenForValidateSession } from 'src/utils/validateSessionRefreshToken'
14
19
  import { execute } from '../../server'
15
20
 
@@ -20,24 +25,45 @@ const ALLOWED_HOST_SUFFIXES = ['localhost', '.vtex.app', '.localhost']
20
25
  // Example: "Set-Cookie: key=value; Domain=example.com; Path=/"
21
26
  const MATCH_DOMAIN_REGEXP = /(?:^|;\s*)(?:domain=)([^;]+)/i
22
27
 
28
+ const toHostname = (hostHeader: string | undefined) => {
29
+ const trimmed = hostHeader?.trim()
30
+ if (!trimmed) {
31
+ return null
32
+ }
33
+
34
+ try {
35
+ return new URL(`https://${trimmed}`).hostname
36
+ } catch {
37
+ return null
38
+ }
39
+ }
40
+
23
41
  /**
24
- * Extracts hostname from the incoming request.
42
+ * Extracts hostname from the incoming request. The preview ingress forwards a
43
+ * client-supplied x-forwarded-host as is, so it only decides whether the cookie
44
+ * Domain is dropped, never which domain is used. A multi-value header is
45
+ * ignored; a single value is used only if it is on the allowlist.
25
46
  */
26
47
  const getRequestHostname = ({
27
48
  request,
28
49
  }: {
29
50
  request: NextApiRequest
30
51
  }): string | null => {
31
- const hostHeader = request.headers.host?.trim()
32
- if (!hostHeader) {
33
- return null
52
+ const forwardedHeader = request.headers['x-forwarded-host']
53
+ const forwardedHostname = toHostname(singleForwardedHost(forwardedHeader))
54
+ if (forwardedHeader && !forwardedHostname) {
55
+ // The value is client-controllable, so it is not logged.
56
+ console.warn('Ignoring multi-value or malformed x-forwarded-host')
34
57
  }
35
58
 
36
- try {
37
- return new URL(`https://${hostHeader}`).hostname
38
- } catch {
39
- return null
59
+ if (
60
+ forwardedHostname &&
61
+ isHostAllowed(forwardedHostname, ALLOWED_HOST_SUFFIXES)
62
+ ) {
63
+ return forwardedHostname
40
64
  }
65
+
66
+ return toHostname(request.headers.host)
41
67
  }
42
68
 
43
69
  /**
@@ -57,22 +83,10 @@ const shouldReplaceCookieDomain = ({
57
83
  }
58
84
 
59
85
  /**
60
- * Determines if host is eligible for domain normalization.
61
- */
62
- const isAllowedHost = ({
63
- host,
64
- allowList,
65
- }: {
66
- host: string
67
- allowList: string[]
68
- }) => {
69
- const normalizedHost = host.toLowerCase()
70
-
71
- return allowList.some((suffix) => normalizedHost.endsWith(suffix))
72
- }
73
-
74
- /**
75
- * Ensure the cookie domain matches the current host so the browser can store it.
86
+ * On allowlisted hosts (previews, localhost) the upstream cookie domain does not
87
+ * match the browser host, so the Domain attribute is dropped and the cookie
88
+ * becomes host-only. The host is never written into the cookie, so a forged
89
+ * x-forwarded-host cannot choose the cookie scope.
76
90
  */
77
91
  const normalizeSetCookieDomain = ({
78
92
  request,
@@ -93,13 +107,13 @@ const normalizeSetCookieDomain = ({
93
107
  const cookieDomain = domainMatch[1]
94
108
 
95
109
  if (
96
- !isAllowedHost({ host, allowList: ALLOWED_HOST_SUFFIXES }) ||
110
+ !isHostAllowed(host, ALLOWED_HOST_SUFFIXES) ||
97
111
  !shouldReplaceCookieDomain({ cookieDomain, host })
98
112
  ) {
99
113
  return setCookie
100
114
  }
101
115
 
102
- return setCookie.replace(MATCH_DOMAIN_REGEXP, `; domain=${host}`)
116
+ return removeCookieDomain(setCookie)
103
117
  }
104
118
 
105
119
  const parseRequest = (request: NextApiRequest) => {
@@ -1,5 +1,5 @@
1
1
  import storeConfig from 'discovery.config'
2
- import { matcher } from 'src/customizations/src/redirects'
2
+ import { matcher } from 'src/customizations/src/redirects/index'
3
3
 
4
4
  type GetRedirectArgs = {
5
5
  pathname: string
@@ -19,6 +19,23 @@ const PERMANENT_STATUS = 308
19
19
 
20
20
  const ASSET_FILE_REGEX = /\.(js|css|png|jpg|jpeg|svg|gif|webp|ico|json|map)$/i
21
21
 
22
+ let hasWarnedInvalidMatcher = false
23
+
24
+ function resolveLocalMatch(pathname: string) {
25
+ if (typeof matcher === 'function') {
26
+ return matcher({ pathname })
27
+ }
28
+
29
+ if (!hasWarnedInvalidMatcher) {
30
+ hasWarnedInvalidMatcher = true
31
+ console.warn(
32
+ `[redirects] Expected src/redirects to export a \`matcher\` function, got ${typeof matcher}. Falling back to the platform redirect lookup.`
33
+ )
34
+ }
35
+
36
+ return null
37
+ }
38
+
22
39
  export async function getRedirect({
23
40
  pathname,
24
41
  }: GetRedirectArgs): Promise<GetRedirectReturn> {
@@ -29,7 +46,8 @@ export async function getRedirect({
29
46
  }
30
47
 
31
48
  try {
32
- const redirectMatch = matcher({ pathname })
49
+ const redirectMatch = resolveLocalMatch(pathname)
50
+
33
51
  if (redirectMatch) {
34
52
  return {
35
53
  destination: encodeURI(redirectMatch.destination),
@@ -0,0 +1,50 @@
1
+ // The result is written verbatim into a Set-Cookie Domain attribute, so
2
+ // characters such as ";" or spaces would inject cookie attributes.
3
+ const HOSTNAME_PATTERN = /^[a-z0-9.-]+$/
4
+
5
+ /**
6
+ * An entry starting with "." matches subdomains only; any other entry matches
7
+ * the host itself and its subdomains. Matching is anchored on a label boundary,
8
+ * so "evil-localhost" never matches "localhost".
9
+ */
10
+ export function isHostAllowed(host: string, allowList: string[]) {
11
+ const normalizedHost = host.toLowerCase()
12
+
13
+ if (!HOSTNAME_PATTERN.test(normalizedHost)) {
14
+ return false
15
+ }
16
+
17
+ return allowList.some((entry) =>
18
+ entry.startsWith('.')
19
+ ? normalizedHost.endsWith(entry)
20
+ : normalizedHost === entry || normalizedHost.endsWith(`.${entry}`)
21
+ )
22
+ }
23
+
24
+ /**
25
+ * Returns the `x-forwarded-host` value only when exactly one is present.
26
+ *
27
+ * Which hop of a proxy chain is trustworthy is not known here: with several
28
+ * values the leftmost one is whatever the client sent. So a multi-value header
29
+ * (comma-joined by Node, or an array) is ignored and the caller falls back to
30
+ * `host`. A single value still assumes the ingress overwrites the header.
31
+ */
32
+ export function singleForwardedHost(
33
+ header: string | string[] | undefined
34
+ ): string | undefined {
35
+ if (Array.isArray(header)) {
36
+ return header.length === 1 ? singleForwardedHost(header[0]) : undefined
37
+ }
38
+
39
+ const value = header?.trim()
40
+
41
+ return value && !value.includes(',') ? value : undefined
42
+ }
43
+
44
+ /**
45
+ * Drops every Domain attribute so the cookie becomes host-only: the browser
46
+ * scopes it to the exact host it requested, whatever header picked this path.
47
+ */
48
+ export function removeCookieDomain(setCookie: string): string {
49
+ return setCookie.replaceAll(/;\s*domain=[^;]*/gi, '')
50
+ }
@@ -0,0 +1,134 @@
1
+ const STORE_ID = 'teststore'
2
+ const REWRITER_URL = `https://${STORE_ID}.myvtex.com/_v/public/redirect-evaluate`
3
+
4
+ const MATCHER_MODULE = 'src/customizations/src/redirects/index'
5
+
6
+ type GetRedirect = typeof import('../../../src/sdk/redirects').getRedirect
7
+
8
+ async function loadGetRedirect(matcherExport?: unknown): Promise<GetRedirect> {
9
+ jest.resetModules()
10
+
11
+ jest.doMock('discovery.config', () => ({
12
+ __esModule: true,
13
+ default: { api: { storeId: STORE_ID } },
14
+ }))
15
+
16
+ if (matcherExport === undefined) {
17
+ jest.dontMock(MATCHER_MODULE)
18
+ } else {
19
+ jest.doMock(MATCHER_MODULE, () => ({
20
+ __esModule: true,
21
+ matcher: matcherExport,
22
+ }))
23
+ }
24
+
25
+ const { getRedirect } = await import('../../../src/sdk/redirects')
26
+
27
+ return getRedirect
28
+ }
29
+
30
+ function mockRewriter({ ok, body }: { ok: boolean; body?: unknown }) {
31
+ const fetchMock = jest
32
+ .fn()
33
+ .mockResolvedValue({ ok, json: async () => body } as Response)
34
+
35
+ globalThis.fetch = fetchMock as unknown as typeof fetch
36
+
37
+ return fetchMock
38
+ }
39
+
40
+ describe('getRedirect', () => {
41
+ const originalFetch = globalThis.fetch
42
+
43
+ beforeEach(() => {
44
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
45
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined)
46
+ })
47
+
48
+ afterEach(() => {
49
+ globalThis.fetch = originalFetch
50
+ jest.dontMock('discovery.config')
51
+ jest.dontMock(MATCHER_MODULE)
52
+ jest.restoreAllMocks()
53
+ jest.resetModules()
54
+ })
55
+
56
+ it('skips asset paths without querying the rewriter', async () => {
57
+ const fetchMock = mockRewriter({ ok: false })
58
+ const getRedirect = await loadGetRedirect()
59
+
60
+ await expect(getRedirect({ pathname: '/icons.json' })).resolves.toBeNull()
61
+ expect(fetchMock).not.toHaveBeenCalled()
62
+ })
63
+
64
+ it('returns a custom matcher result without querying the rewriter', async () => {
65
+ const fetchMock = mockRewriter({ ok: false })
66
+ const getRedirect = await loadGetRedirect(() => ({
67
+ destination: '/promoção',
68
+ permanent: false,
69
+ }))
70
+
71
+ await expect(getRedirect({ pathname: '/sale' })).resolves.toEqual({
72
+ destination: encodeURI('/promoção'),
73
+ permanent: false,
74
+ })
75
+ expect(fetchMock).not.toHaveBeenCalled()
76
+ expect(console.warn).not.toHaveBeenCalled()
77
+ })
78
+
79
+ it('falls back to the rewriter when the matcher export is not a function', async () => {
80
+ const fetchMock = mockRewriter({
81
+ ok: true,
82
+ body: { location: '/eletrodomesticos', status: 308 },
83
+ })
84
+ // A store shipping `src/redirects.json` can shadow the customization
85
+ // module, which makes the imported `matcher` an array instead of a function.
86
+ const getRedirect = await loadGetRedirect([])
87
+
88
+ await expect(getRedirect({ pathname: '/old-page' })).resolves.toEqual({
89
+ destination: '/eletrodomesticos',
90
+ permanent: true,
91
+ })
92
+ expect(fetchMock).toHaveBeenCalledWith(`${REWRITER_URL}/old-page`)
93
+ expect(console.warn).toHaveBeenCalledTimes(1)
94
+ })
95
+
96
+ it('warns only once about an invalid matcher export', async () => {
97
+ mockRewriter({ ok: false })
98
+ const getRedirect = await loadGetRedirect([])
99
+
100
+ await getRedirect({ pathname: '/first' })
101
+ await getRedirect({ pathname: '/second' })
102
+
103
+ expect(console.warn).toHaveBeenCalledTimes(1)
104
+ })
105
+
106
+ it('does not leak a mocked matcher into a later default load', async () => {
107
+ mockRewriter({ ok: false })
108
+
109
+ const withInvalidMatcher = await loadGetRedirect([])
110
+ await expect(withInvalidMatcher({ pathname: '/first' })).resolves.toBeNull()
111
+
112
+ const withStubMatcher = await loadGetRedirect()
113
+ await expect(withStubMatcher({ pathname: '/second' })).resolves.toBeNull()
114
+
115
+ expect(console.warn).toHaveBeenCalledTimes(1)
116
+ })
117
+
118
+ it('marks non-permanent rewriter redirects as temporary', async () => {
119
+ mockRewriter({ ok: true, body: { location: '/new', status: 307 } })
120
+ const getRedirect = await loadGetRedirect()
121
+
122
+ await expect(getRedirect({ pathname: '/old' })).resolves.toEqual({
123
+ destination: '/new',
124
+ permanent: false,
125
+ })
126
+ })
127
+
128
+ it('returns null when the rewriter has no rule for the path', async () => {
129
+ mockRewriter({ ok: false })
130
+ const getRedirect = await loadGetRedirect()
131
+
132
+ await expect(getRedirect({ pathname: '/no-rule' })).resolves.toBeNull()
133
+ })
134
+ })
@@ -0,0 +1,103 @@
1
+ import {
2
+ singleForwardedHost,
3
+ isHostAllowed,
4
+ removeCookieDomain,
5
+ } from '../../src/utils/trustedForwardedHost'
6
+
7
+ const ALLOW_LIST = ['localhost', '.vtex.app', '.localhost']
8
+
9
+ describe('isHostAllowed', () => {
10
+ it.each([
11
+ 'localhost',
12
+ 'store.vtex.app',
13
+ 'sfj-1--acc.preview.vtex.app',
14
+ 'a.localhost',
15
+ ])('allows %s', (host: string) => {
16
+ expect(isHostAllowed(host, ALLOW_LIST)).toBe(true)
17
+ })
18
+
19
+ it.each([
20
+ 'evil-localhost',
21
+ 'notlocalhost',
22
+ 'evil-vtex.app',
23
+ 'vtex.app.evil.com',
24
+ 'evil.com',
25
+ ])('rejects %s', (host: string) => {
26
+ expect(isHostAllowed(host, ALLOW_LIST)).toBe(false)
27
+ })
28
+ })
29
+
30
+ describe('isHostAllowed normalization', () => {
31
+ it('is case-insensitive', () => {
32
+ expect(isHostAllowed('Store.VTEX.app', ALLOW_LIST)).toBe(true)
33
+ expect(isHostAllowed('LOCALHOST', ALLOW_LIST)).toBe(true)
34
+ })
35
+
36
+ it.each([
37
+ 'x;max-age=0;y.vtex.app',
38
+ 'a b.vtex.app',
39
+ 'x"y.vtex.app',
40
+ 'x=y.vtex.app',
41
+ 'x,y.vtex.app',
42
+ 'x\r\nSet-Cookie: evil=1.vtex.app',
43
+ 'x\ny.vtex.app',
44
+ 'x\ry.vtex.app',
45
+ ])('rejects %s, which would inject cookie attributes', (host: string) => {
46
+ expect(isHostAllowed(host, ALLOW_LIST)).toBe(false)
47
+ })
48
+
49
+ it('accepts punycode hostnames', () => {
50
+ expect(isHostAllowed('xn--lja-bma.vtex.app', ALLOW_LIST)).toBe(true)
51
+ })
52
+
53
+ it('expects a hostname: a port is not stripped here', () => {
54
+ expect(isHostAllowed('store.vtex.app:8080', ALLOW_LIST)).toBe(false)
55
+ expect(isHostAllowed('evil.com:vtex.app', ALLOW_LIST)).toBe(false)
56
+ })
57
+ })
58
+
59
+ describe('singleForwardedHost', () => {
60
+ it('returns the value when there is exactly one', () => {
61
+ expect(singleForwardedHost('a.vtex.app')).toBe('a.vtex.app')
62
+ expect(singleForwardedHost(' a.vtex.app ')).toBe('a.vtex.app')
63
+ expect(singleForwardedHost(['a.vtex.app'])).toBe('a.vtex.app')
64
+ })
65
+
66
+ it('returns undefined when missing or empty', () => {
67
+ expect(singleForwardedHost(undefined)).toBeUndefined()
68
+ expect(singleForwardedHost('')).toBeUndefined()
69
+ expect(singleForwardedHost([])).toBeUndefined()
70
+ })
71
+
72
+ it('ignores multi-value headers instead of picking one', () => {
73
+ expect(singleForwardedHost('a.vtex.app, evil.com')).toBeUndefined()
74
+ expect(singleForwardedHost('evil.com, a.vtex.app')).toBeUndefined()
75
+ expect(singleForwardedHost(['a.vtex.app', 'evil.com'])).toBeUndefined()
76
+ })
77
+ })
78
+
79
+ describe('removeCookieDomain', () => {
80
+ it('drops the Domain attribute and keeps the rest', () => {
81
+ expect(
82
+ removeCookieDomain(
83
+ 'checkout.vtex.com=__ofid=abc; expires=Sun, 04 Apr 2027 18:31:26 GMT; domain=acc.vtexcommercestable.com.br; path=/; secure; samesite=lax; httponly'
84
+ )
85
+ ).toBe(
86
+ 'checkout.vtex.com=__ofid=abc; expires=Sun, 04 Apr 2027 18:31:26 GMT; path=/; secure; samesite=lax; httponly'
87
+ )
88
+ })
89
+
90
+ it('is case-insensitive and removes repeated Domain attributes', () => {
91
+ expect(removeCookieDomain('a=1; Domain=x.com; DOMAIN=y.com; Path=/')).toBe(
92
+ 'a=1; Path=/'
93
+ )
94
+ })
95
+
96
+ it('does not touch a cookie whose name is domain', () => {
97
+ expect(removeCookieDomain('domain=1; path=/')).toBe('domain=1; path=/')
98
+ })
99
+
100
+ it('keeps cookies without a Domain attribute unchanged', () => {
101
+ expect(removeCookieDomain('a=1; path=/')).toBe('a=1; path=/')
102
+ })
103
+ })