@akinon/next 2.0.16-beta.0 → 2.0.16-rc.1

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.
package/CHANGELOG.md CHANGED
@@ -1,10 +1,39 @@
1
1
  # @akinon/next
2
2
 
3
- ## 2.0.16-beta.0
3
+ ## 2.0.16-rc.1
4
4
 
5
5
  ### Patch Changes
6
6
 
7
- - cbbbfd75: ZERO-4376: Bootstrap beta cycle (next-main pre-release motor)
7
+ - 378607d1: ZERO-4430: Harden CSRF handling for the BFF proxy
8
+
9
+ When `settings.csrf.httpOnly` is enabled, the Django `csrftoken` cookie is set `HttpOnly` + `Secure` + `SameSite=Lax` and the token is never exposed to the browser. The Next.js proxy validates the request `Origin` and injects the `x-csrftoken` header server-side from the cookie before forwarding state-changing requests, instead of round-tripping the token through client JavaScript.
10
+
11
+ ## 2.0.16-rc.0
12
+
13
+ ### Patch Changes
14
+
15
+ - 0cf9ea23: BRDG-16491: Prevent redirect when iframe payment is active
16
+ - 324f97d5: ZERO-4219: replace masterpass-rest-complete with masterpass-rest-callback
17
+ - 51ea0688: ZERO-4377: Fix checkout card type state being cleared after valid bin number responses.
18
+ - ZERO-4160: Enhance oauth-login middleware with improved request handling and logging
19
+ - b55acb768: ZERO-2577: Fix pagination bug and update usePagination hook and ensure pagination controls rendering correctly
20
+ - 760258c1: ZERO-4160: Enhance oauth-login middleware to handle fetch errors and improve response handling
21
+ - 143be2b9d: ZERO-3457: Crop styles are customizable and logic improved for rendering similar products modal
22
+ - 7889b08f: ZERO-4276: Enhance route generation by adding .env loading and custom skip segments support
23
+ - 9f8cd3bc5: ZERO-3449: AI Search Active Filters & Crop Style changes have been implemented
24
+ - d51fa68e: ZERO-4399: add card rewards to pz-masterpass-rest
25
+ - bfafa3f4: ZERO-4160: Refactor oauth-login middleware to use fetchCommerce for API calls and improve cookie handling
26
+ - 57d7eb30: ZERO-4276: Refactor route generation logic by removing environment loading and simplifying skip segments handling
27
+ - d99a6a7d5: ZERO-3457_1: Fixed the settings prop and made sure everything is customizable.
28
+ - 9db81a71: ZERO-4365: Remove brand `@theme/*` alias imports from library packages
29
+ - 591e345e: ZERO-3855: Enhance credit card payment handling in checkout middlewares
30
+ - 4de5303c5: ZERO-2504: add cookie filter to api client request
31
+ - 95b139dc1: ZERO-3795: Remove duplicate entry for SavedCard in PluginComponents map
32
+ - 1d00f2d0: BRDG-16664: Set secure flag for CSRF token cookies in useCaptcha and default middleware
33
+ - 4ac7b2a1: ZERO-4219: fix masterpass-rest callback route format and double-encoded error cookie
34
+ - 4998a963: ZERO-4168: Add server-side payload optimization
35
+ - 3909d3224: Edit the duplicate Plugin.SimilarProducts in the plugin-module.
36
+ - e18836b2: ZERO-4160: Restore scope in Sentry addon configuration in akinon.json
8
37
 
9
38
  ## 2.0.15
10
39
 
package/api/auth.ts CHANGED
@@ -6,7 +6,10 @@ import Settings from 'settings';
6
6
  import { urlLocaleMatcherRegex } from '../utils';
7
7
  import logger from '@akinon/next/utils/log';
8
8
  import { AuthError } from '../types';
9
- import getRootHostname from '../utils/get-root-hostname';
9
+ import getRootHostname, {
10
+ getRequestRootHostname
11
+ } from '../utils/get-root-hostname';
12
+ import { getCsrfCookieFlags } from '../utils/csrf';
10
13
  import { LocaleUrlStrategy } from '../localization';
11
14
  import { cookies, headers } from 'next/headers';
12
15
 
@@ -222,12 +225,17 @@ const getDefaultAuthConfig = () => {
222
225
  logger.debug(`Login/Register response: ${JSON.stringify(response)}`);
223
226
 
224
227
  let sessionId = '';
228
+ let rotatedCsrfToken = '';
225
229
  const setCookieHeader = apiRequest.headers.get('set-cookie');
226
230
  if (setCookieHeader) {
227
231
  sessionId =
228
232
  setCookieHeader
229
233
  .match(/osessionid=\w+/)?.[0]
230
234
  .replace(/osessionid=/, '') || '';
235
+ rotatedCsrfToken =
236
+ setCookieHeader
237
+ .match(/csrftoken=[^;,\s]+/)?.[0]
238
+ .replace(/csrftoken=/, '') || '';
231
239
 
232
240
  logger.debug(`Login/Register session id: ${sessionId}`);
233
241
  } else {
@@ -258,6 +266,14 @@ const getDefaultAuthConfig = () => {
258
266
 
259
267
  cookieStore.set('osessionid', sessionId, cookieOptions);
260
268
  cookieStore.set('sessionid', sessionId, cookieOptions);
269
+
270
+ if (rotatedCsrfToken) {
271
+ cookieStore.set('csrftoken', rotatedCsrfToken, {
272
+ path: '/',
273
+ ...getCsrfCookieFlags(),
274
+ ...(rootHostname ? { domain: rootHostname } : {})
275
+ });
276
+ }
261
277
  }
262
278
 
263
279
  if (!response.key) {
@@ -314,14 +330,16 @@ const getDefaultAuthConfig = () => {
314
330
  },
315
331
  signOut: async () => {
316
332
  const cookieStore = await cookies();
317
- cookieStore.set('osessionid', '', {
318
- path: '/',
319
- maxAge: 0
320
- });
321
- cookieStore.set('sessionid', '', {
333
+ const rootHostname = getRequestRootHostname(await headers());
334
+ const expireOptions = {
322
335
  path: '/',
323
- maxAge: 0
324
- });
336
+ maxAge: 0,
337
+ ...(rootHostname ? { domain: rootHostname } : {})
338
+ };
339
+
340
+ cookieStore.set('osessionid', '', expireOptions);
341
+ cookieStore.set('sessionid', '', expireOptions);
342
+ cookieStore.set('csrftoken', '', expireOptions);
325
343
  logger.debug('Successfully signed out');
326
344
  }
327
345
  },
@@ -575,9 +593,19 @@ const defaultNextAuthOptionsV4 = (req: any, res: any) => {
575
593
  logger.debug('Successfully signed in');
576
594
  },
577
595
  signOut: () => {
596
+ const rootHostname = getRequestRootHostname({
597
+ get: (name) => {
598
+ const v = req.headers[name];
599
+ return Array.isArray(v) ? v[0] : (v ?? null);
600
+ }
601
+ });
602
+ const domainAttr = rootHostname ? `; Domain=${rootHostname}` : '';
603
+ const expiry = `Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT${domainAttr}`;
604
+
578
605
  res.setHeader('Set-Cookie', [
579
- `osessionid=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`,
580
- `sessionid=; Path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`
606
+ `osessionid=; ${expiry}`,
607
+ `sessionid=; ${expiry}`,
608
+ `csrftoken=; ${expiry}`
581
609
  ]);
582
610
  logger.debug('Successfully signed out');
583
611
  }
package/api/client.ts CHANGED
@@ -8,6 +8,64 @@ import { cookies } from 'next/headers';
8
8
  import getRootHostname from '../utils/get-root-hostname';
9
9
  import { LocaleUrlStrategy } from '../localization';
10
10
  import { fixtureManager, MockMode } from '../lib/fixture-manager';
11
+ import { user } from '../data/urls';
12
+ import { getCsrfCookieFlags, isCsrfHttpOnly } from '../utils/csrf';
13
+
14
+ const CSRF_TOKEN_SLUG = user.csrfToken.replace(/^\//, '');
15
+
16
+ const STATE_CHANGING_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE'];
17
+
18
+ function getProxyHosts(req: Request): string[] {
19
+ const hosts = new Set<string>();
20
+ const forwarded =
21
+ req.headers.get('x-forwarded-host') || req.headers.get('host');
22
+ if (forwarded) {
23
+ hosts.add(forwarded.split(':')[0].toLowerCase());
24
+ }
25
+ try {
26
+ if (process.env.NEXT_PUBLIC_URL) {
27
+ hosts.add(new URL(process.env.NEXT_PUBLIC_URL).hostname.toLowerCase());
28
+ }
29
+ } catch {
30
+ // ignore malformed NEXT_PUBLIC_URL
31
+ }
32
+ return Array.from(hosts);
33
+ }
34
+
35
+ /**
36
+ * Next.js-layer CSRF defense for the BFF proxy. State-changing requests must
37
+ * originate from our own app: when an `Origin` header is present it has to
38
+ * resolve to the proxy host (or, under the subdomain locale strategy, the
39
+ * same registrable domain). Requests without an `Origin` (non-browser
40
+ * clients, same-origin navigations) fall back to the `SameSite=Lax` cookie
41
+ * guarantee. Only enforced when CSRF hardening is enabled.
42
+ */
43
+ function isOriginAllowed(req: Request): boolean {
44
+ const origin = req.headers.get('origin');
45
+ if (!origin) return true;
46
+
47
+ let originHost: string;
48
+ try {
49
+ originHost = new URL(origin).hostname.toLowerCase();
50
+ } catch {
51
+ return false;
52
+ }
53
+
54
+ const allowedHosts = getProxyHosts(req);
55
+ if (allowedHosts.includes(originHost)) return true;
56
+
57
+ if (settings.localization.localeUrlStrategy === LocaleUrlStrategy.Subdomain) {
58
+ const originRoot = getRootHostname(`https://${originHost}`);
59
+ return (
60
+ !!originRoot &&
61
+ allowedHosts.some(
62
+ (host) => getRootHostname(`https://${host}`) === originRoot
63
+ )
64
+ );
65
+ }
66
+
67
+ return false;
68
+ }
11
69
 
12
70
  interface RouteParams {
13
71
  params: {
@@ -103,6 +161,28 @@ async function proxyRequest(...args) {
103
161
  });
104
162
  }
105
163
 
164
+ // CSRF hardening (BFF model): when the csrftoken cookie is HttpOnly the
165
+ // browser can no longer mirror it into the `x-csrftoken` header, so the
166
+ // proxy validates the request origin and injects the header server-side
167
+ // from the cookie that the browser sent with this request.
168
+ if (isCsrfHttpOnly() && STATE_CHANGING_METHODS.includes(req.method)) {
169
+ if (!isOriginAllowed(req)) {
170
+ logger.warn('Client Proxy Request - Blocked cross-origin request', {
171
+ url: req.url,
172
+ origin: req.headers.get('origin')
173
+ });
174
+ return NextResponse.json(
175
+ { detail: 'CSRF origin check failed.' },
176
+ { status: 403 }
177
+ );
178
+ }
179
+
180
+ const csrfToken = nextCookies.get('csrftoken')?.value;
181
+ if (csrfToken) {
182
+ fetchOptions.headers['x-csrftoken'] = csrfToken;
183
+ }
184
+ }
185
+
106
186
  if (options.contentType) {
107
187
  fetchOptions.headers['Content-Type'] = options.contentType;
108
188
  }
@@ -240,11 +320,25 @@ async function proxyRequest(...args) {
240
320
  if (!cookie.domain && rootHostname) {
241
321
  cookie.domain = rootHostname;
242
322
  }
323
+ if (cookie.name === 'csrftoken') {
324
+ const flags = getCsrfCookieFlags();
325
+ if (flags.httpOnly) {
326
+ cookie.httpOnly = true;
327
+ cookie.secure = flags.secure;
328
+ cookie.sameSite = flags.sameSite;
329
+ }
330
+ }
243
331
  return formatCookieString(cookie);
244
332
  })
245
333
  .join(', ');
246
334
  }
247
335
 
336
+ if (slug === CSRF_TOKEN_SLUG) {
337
+ responseHeaders['Cache-Control'] =
338
+ 'private, no-store, no-cache, must-revalidate';
339
+ responseHeaders['Pragma'] = 'no-cache';
340
+ }
341
+
248
342
  return NextResponse.json(
249
343
  options.responseType === 'text' ? { result: response } : response,
250
344
  { status: request.status, headers: responseHeaders }
@@ -6,6 +6,7 @@ const findBaseDir = require('../utils/find-base-dir');
6
6
 
7
7
  const generateRoutes = () => {
8
8
  const baseDir = findBaseDir();
9
+
9
10
  const srcDir = path.join(baseDir, 'src');
10
11
  const appDir = path.join(srcDir, 'app');
11
12
 
@@ -34,8 +35,10 @@ const generateRoutes = () => {
34
35
  '[segment]',
35
36
  '[url]',
36
37
  '[theme]',
37
- '[member_type]'
38
+ '[member_type]',
39
+ '[clienttype]'
38
40
  ];
41
+
39
42
  const skipCatchAllRoutes = ['[...prettyurl]', '[...not_found]'];
40
43
 
41
44
  const walkDirectory = (dir, basePath = '') => {
@@ -116,7 +116,6 @@ const PluginComponents = new Map([
116
116
  ]
117
117
  ],
118
118
  [Plugin.SavedCard, [Component.SavedCard, Component.IyzicoSavedCard]],
119
- [Plugin.SavedCard, [Component.SavedCard]],
120
119
  [Plugin.FlowPayment, [Component.FlowPayment]],
121
120
  [
122
121
  Plugin.VirtualTryOn,
@@ -738,7 +738,6 @@ export const checkoutApi = api.injectEndpoints({
738
738
  },
739
739
  async onQueryStarted(arg, { dispatch, queryFulfilled }) {
740
740
  dispatch(setPaymentStepBusy(true));
741
- dispatch(setCardType(arg));
742
741
  await queryFulfilled;
743
742
  dispatch(setPaymentStepBusy(false));
744
743
  }
@@ -7,6 +7,8 @@ import { parse } from 'lossless-json';
7
7
  import logger from '../../utils/log';
8
8
  import { headers as nHeaders } from 'next/headers';
9
9
  import { ServerVariables } from '../../utils/server-variables';
10
+ import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
11
+ import settings from 'settings';
10
12
 
11
13
  function getCategoryDataHandler(
12
14
  pk: number,
@@ -80,7 +82,7 @@ function getCategoryDataHandler(
80
82
  };
81
83
  }
82
84
 
83
- export const getCategoryData = ({
85
+ export const getCategoryData = async ({
84
86
  pk,
85
87
  searchParams,
86
88
  headers,
@@ -93,7 +95,7 @@ export const getCategoryData = ({
93
95
  searchParams?: SearchParams;
94
96
  headers?: Record<string, string>;
95
97
  }) => {
96
- return Cache.wrap(
98
+ const result = await Cache.wrap(
97
99
  CacheKey.Category(pk, searchParams, headers),
98
100
  locale,
99
101
  getCategoryDataHandler(pk, locale, currency, searchParams, headers),
@@ -102,6 +104,16 @@ export const getCategoryData = ({
102
104
  compressed: true
103
105
  }
104
106
  );
107
+
108
+ if (settings.payloadOptimization?.enabled && result?.data) {
109
+ try {
110
+ return { ...result, data: optimizeCategoryResponse(result.data, settings.payloadOptimization) };
111
+ } catch (e) {
112
+ logger.error('Payload optimization failed for category', { pk, error: (e as Error).message });
113
+ }
114
+ }
115
+
116
+ return result;
105
117
  };
106
118
 
107
119
  function getCategoryBySlugDataHandler(
@@ -6,6 +6,8 @@ import appFetch, { FetchResponseType } from '../../utils/app-fetch';
6
6
  import { parse } from 'lossless-json';
7
7
  import logger from '../../utils/log';
8
8
  import { ServerVariables } from '../../utils/server-variables';
9
+ import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
10
+ import settings from 'settings';
9
11
 
10
12
  const getListDataHandler = (
11
13
  locale,
@@ -66,7 +68,7 @@ export const getListData = async ({
66
68
  searchParams: SearchParams;
67
69
  headers?: Record<string, string>;
68
70
  }) => {
69
- return Cache.wrap(
71
+ const result = await Cache.wrap(
70
72
  CacheKey.List(searchParams, headers),
71
73
  locale,
72
74
  getListDataHandler(locale, currency, searchParams, headers),
@@ -75,4 +77,14 @@ export const getListData = async ({
75
77
  compressed: true
76
78
  }
77
79
  );
80
+
81
+ if (settings.payloadOptimization?.enabled && result) {
82
+ try {
83
+ return optimizeCategoryResponse(result, settings.payloadOptimization);
84
+ } catch (e) {
85
+ logger.error('Payload optimization failed for list', { error: (e as Error).message });
86
+ }
87
+ }
88
+
89
+ return result;
78
90
  };
@@ -4,6 +4,8 @@ import { ProductCategoryResult, ProductResult, SearchParams } from '../../types'
4
4
  import appFetch from '../../utils/app-fetch';
5
5
  import { ServerVariables } from '../../utils/server-variables';
6
6
  import logger from '../../utils/log';
7
+ import { optimizeProductResponse } from '../../utils/payload-optimizer';
8
+ import settings from 'settings';
7
9
 
8
10
  type GetProduct = {
9
11
  pk: number | string;
@@ -163,5 +165,13 @@ export const getProductData = async ({
163
165
  throw error;
164
166
  }
165
167
 
168
+ if (settings.payloadOptimization?.enabled && result?.data) {
169
+ try {
170
+ return { ...result, data: optimizeProductResponse(result.data, settings.payloadOptimization) };
171
+ } catch (e) {
172
+ logger.error('Payload optimization failed for product', { pk, error: (e as Error).message });
173
+ }
174
+ }
175
+
166
176
  return result;
167
177
  };
@@ -4,6 +4,9 @@ import { GetCategoryResponse, SearchParams } from '../../types';
4
4
  import { generateCommerceSearchParams } from '../../utils';
5
5
  import appFetch from '../../utils/app-fetch';
6
6
  import { ServerVariables } from '../../utils/server-variables';
7
+ import { optimizeCategoryResponse } from '../../utils/payload-optimizer';
8
+ import logger from '../../utils/log';
9
+ import settings from 'settings';
7
10
 
8
11
  const getSpecialPageDataHandler = (
9
12
  pk: number,
@@ -45,7 +48,7 @@ export const getSpecialPageData = async ({
45
48
  searchParams: SearchParams;
46
49
  headers?: Record<string, string>;
47
50
  }) => {
48
- return Cache.wrap(
51
+ const result = await Cache.wrap(
49
52
  CacheKey.SpecialPage(pk, searchParams, headers),
50
53
  locale,
51
54
  getSpecialPageDataHandler(pk, locale, currency, searchParams, headers),
@@ -54,4 +57,14 @@ export const getSpecialPageData = async ({
54
57
  compressed: true
55
58
  }
56
59
  );
60
+
61
+ if (settings.payloadOptimization?.enabled && result) {
62
+ try {
63
+ return optimizeCategoryResponse(result, settings.payloadOptimization);
64
+ } catch (e) {
65
+ logger.error('Payload optimization failed for special-page', { pk, error: (e as Error).message });
66
+ }
67
+ }
68
+
69
+ return result;
57
70
  };
@@ -4,6 +4,9 @@ import { CacheOptions, WidgetResultType, WidgetSchemaType } from '../../types';
4
4
  import appFetch from '../../utils/app-fetch';
5
5
  import { widgets } from '../urls';
6
6
  import { ServerVariables } from '../../utils/server-variables';
7
+ import { optimizeWidgetResponse } from '../../utils/payload-optimizer';
8
+ import logger from '../../utils/log';
9
+ import settings from 'settings';
7
10
 
8
11
  const getWidgetDataHandler =
9
12
  (
@@ -53,7 +56,7 @@ export const getWidgetData = async <T>({
53
56
  cacheOptions?: CacheOptions;
54
57
  headers?: Record<string, string>;
55
58
  }): Promise<WidgetResultType<T>> => {
56
- return Cache.wrap(
59
+ const result = await Cache.wrap(
57
60
  CacheKey.Widget(slug),
58
61
  locale,
59
62
  getWidgetDataHandler(slug, locale, currency, headers),
@@ -62,6 +65,16 @@ export const getWidgetData = async <T>({
62
65
  ...cacheOptions
63
66
  }
64
67
  );
68
+
69
+ if (settings.payloadOptimization?.enabled && result) {
70
+ try {
71
+ return optimizeWidgetResponse(result, settings.payloadOptimization) as WidgetResultType<T>;
72
+ } catch (e) {
73
+ logger.error('Payload optimization failed for widget', { slug, error: (e as Error).message });
74
+ }
75
+ }
76
+
77
+ return result as WidgetResultType<T>;
65
78
  };
66
79
 
67
80
  const getCollectionWidgetDataHandler =
package/data/urls.ts CHANGED
@@ -183,7 +183,11 @@ export const product = {
183
183
  breadcrumbUrl: (menuitemmodel: string) =>
184
184
  `/menus/generate_breadcrumb/?item=${menuitemmodel}&generator_name=menu_item`,
185
185
  bundleProduct: (productPk: string, queryString: string) =>
186
- `/bundle-product/${productPk}/?${queryString}`
186
+ `/bundle-product/${productPk}/?${queryString}`,
187
+ similarProducts: (params?: string) =>
188
+ `/similar-products${params ? `?${params}` : ''}`,
189
+ similarProductsList: (params?: string) =>
190
+ `/similar-product-list${params ? `?${params}` : ''}`
187
191
  };
188
192
 
189
193
  export const wishlist = {
@@ -39,7 +39,7 @@ export const useCaptcha = () => {
39
39
  };
40
40
 
41
41
  if (csrfToken) {
42
- setCookie('csrftoken', csrfToken);
42
+ setCookie('csrftoken', csrfToken, { secure: true });
43
43
  }
44
44
 
45
45
  const onCaptchaChange = useCallback(async (response) => {