@akinon/next 2.0.79-rc.0 → 2.0.79

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.
@@ -26,28 +26,13 @@ import {
26
26
  } from '../../redux/reducers/checkout';
27
27
  import { RootState, TypedDispatch } from 'redux/store';
28
28
  import { checkoutApi } from '../../data/client/checkout';
29
- import { CheckoutContext, MiddlewareAction, PreOrder } from '../../types';
29
+ import { CheckoutContext, PreOrder } from '../../types';
30
30
  import { getCookie } from '../../utils';
31
31
  import settings from 'settings';
32
32
  import { LocaleUrlStrategy } from '../../localization';
33
33
  import { showMobile3dIframe } from '../../utils/mobile-3d-iframe';
34
34
  import { showRedirectionIframe } from '../../utils/redirection-iframe';
35
35
 
36
- const IFRAME_REDIRECTION_KEY = 'pz-iframe-redirection-active';
37
-
38
- const isIframeRedirectionActive = () =>
39
- typeof window !== 'undefined' &&
40
- sessionStorage.getItem(IFRAME_REDIRECTION_KEY) === 'true';
41
-
42
- const setIframeRedirectionActive = (active: boolean) => {
43
- if (typeof window === 'undefined') return;
44
- if (active) {
45
- sessionStorage.setItem(IFRAME_REDIRECTION_KEY, 'true');
46
- } else {
47
- sessionStorage.removeItem(IFRAME_REDIRECTION_KEY);
48
- }
49
- };
50
-
51
36
  interface CheckoutResult {
52
37
  payload: {
53
38
  errors?: Record<string, string[]>;
@@ -84,7 +69,7 @@ export const redirectUrlMiddleware: Middleware = () => {
84
69
  const result = next(action) as CheckoutResult;
85
70
  const redirectUrl = result?.payload?.redirect_url;
86
71
 
87
- if (redirectUrl && !isIframeRedirectionActive()) {
72
+ if (redirectUrl) {
88
73
  const currentLocale = getCookie('pz-locale');
89
74
 
90
75
  let url = redirectUrl;
@@ -114,15 +99,8 @@ export const contextListMiddleware: Middleware = ({
114
99
  const { isMobileApp, userPhoneNumber } = getState().root;
115
100
  const result = next(action) as CheckoutResult;
116
101
  const preOrder = result?.payload?.pre_order;
117
- const act = action as MiddlewareAction;
118
102
 
119
103
  if (result?.payload?.context_list) {
120
- const endpointName = act.meta?.arg?.endpointName;
121
- const isBinNumberResponse = endpointName === 'setBinNumber';
122
- const hasCardTypeInContextList = result.payload.context_list.some(
123
- (ctx) => ctx.page_context.card_type
124
- );
125
-
126
104
  result.payload.context_list.forEach((context) => {
127
105
  const redirectUrl = context.page_context.redirect_url;
128
106
  const isIframe = context.page_context.is_iframe ?? false;
@@ -156,7 +134,6 @@ export const contextListMiddleware: Middleware = ({
156
134
  if (isMobileDevice && isIframePaymentOptionIncluded) {
157
135
  showMobile3dIframe(urlObj.toString());
158
136
  } else if (isIframe) {
159
- setIframeRedirectionActive(true);
160
137
  showRedirectionIframe(urlObj.toString());
161
138
  } else {
162
139
  window.location.href = urlObj.toString();
@@ -232,34 +209,15 @@ export const contextListMiddleware: Middleware = ({
232
209
  (ctx) => ctx.page_name === 'DeliveryOptionSelectionPage'
233
210
  )
234
211
  ) {
235
- const isCreditCardPayment =
236
- preOrder?.payment_option?.payment_type === 'credit_card' ||
237
- preOrder?.payment_option?.payment_type === 'masterpass';
238
-
239
212
  if (context.page_context.card_type) {
240
213
  dispatch(setCardType(context.page_context.card_type));
241
- } else if (
242
- isCreditCardPayment &&
243
- isBinNumberResponse &&
244
- !hasCardTypeInContextList
245
- ) {
246
- dispatch(setCardType(null));
247
- dispatch(setInstallmentOptions([]));
248
214
  }
249
215
 
250
216
  if (
251
217
  context.page_context.installments &&
252
218
  preOrder?.payment_option?.payment_type !== 'masterpass_rest'
253
219
  ) {
254
- if (
255
- !isCreditCardPayment ||
256
- context.page_context.card_type ||
257
- hasCardTypeInContextList
258
- ) {
259
- dispatch(
260
- setInstallmentOptions(context.page_context.installments)
261
- );
262
- }
220
+ dispatch(setInstallmentOptions(context.page_context.installments));
263
221
  }
264
222
  }
265
223
 
@@ -14,17 +14,9 @@ export const installmentOptionMiddleware: Middleware = ({
14
14
  return result;
15
15
  }
16
16
 
17
- const { installmentOptions, cardType } = getState().checkout;
17
+ const { installmentOptions } = getState().checkout;
18
18
  const { endpoints: apiEndpoints } = checkoutApi;
19
19
 
20
- const isCreditCardPayment =
21
- preOrder?.payment_option?.payment_type === 'credit_card' ||
22
- preOrder?.payment_option?.payment_type === 'masterpass';
23
-
24
- if (isCreditCardPayment && !cardType) {
25
- return result;
26
- }
27
-
28
20
  if (
29
21
  !preOrder?.installment &&
30
22
  preOrder?.payment_option?.payment_type !== 'saved_card' &&
package/types/index.ts CHANGED
@@ -85,12 +85,6 @@ export interface Settings {
85
85
  };
86
86
  usePrettyUrlRoute?: boolean;
87
87
  commerceUrl: string;
88
- /**
89
- * This option allows you to track Sentry events on the client side, in addition to server and edge environments.
90
- *
91
- * It overrides process.env.NEXT_PUBLIC_SENTRY_DSN and process.env.SENTRY_DSN.
92
- */
93
- sentryDsn?: string;
94
88
  /**
95
89
  * CSRF cookie hardening settings.
96
90
  *
@@ -242,7 +236,6 @@ export interface Settings {
242
236
  separator?: string;
243
237
  segments: PzSegmentDefinition[];
244
238
  };
245
- payloadOptimization?: import('../utils/payload-optimizer').PayloadOptimizationConfig;
246
239
  }
247
240
 
248
241
  export interface CacheOptions {
@@ -302,9 +295,7 @@ export interface PzSegmentsConfig {
302
295
  }
303
296
 
304
297
  // Search params type compatible with both Next.js resolved searchParams and URLSearchParams
305
- export type SearchParams =
306
- | Record<string, string | string[] | undefined>
307
- | URLSearchParams;
298
+ export type SearchParams = Record<string, string | string[] | undefined> | URLSearchParams;
308
299
 
309
300
  // Raw Next 16 server prop shape, used at the middleware/HOC boundary before normalization
310
301
  export type RawSearchParams = Record<string, string | string[] | undefined>;
@@ -337,16 +328,14 @@ export interface RootLayoutProps<T = any> extends LayoutProps<T> {
337
328
 
338
329
  // Async versions for Next.js 16 generateMetadata and internal use
339
330
  export interface AsyncPageProps<T = any> {
340
- params: Promise<
341
- T & {
342
- pz?: string;
343
- commerce?: string;
344
- locale?: string;
345
- currency?: string;
346
- url?: string;
347
- [key: string]: any;
348
- }
349
- >;
331
+ params: Promise<T & {
332
+ pz?: string;
333
+ commerce?: string;
334
+ locale?: string;
335
+ currency?: string;
336
+ url?: string;
337
+ [key: string]: any;
338
+ }>;
350
339
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
351
340
  }
352
341
 
@@ -76,7 +76,9 @@ const appFetch = async <T>({
76
76
  'x-forwarded-for': ip
77
77
  };
78
78
 
79
- init.next = {
79
+ // Callers may pass their own cache directives (e.g. widget preview
80
+ // fetches use revalidate: 0); only apply the default when they don't.
81
+ init.next = init.next ?? {
80
82
  revalidate: Settings.usePrettyUrlRoute ? 0 : 60
81
83
  };
82
84
 
package/utils/csrf.ts CHANGED
@@ -46,7 +46,7 @@ export function getCsrfCookieFlags(): CsrfCookieFlags {
46
46
 
47
47
  return {
48
48
  httpOnly,
49
- secure: process.env.NODE_ENV === 'production',
49
+ secure: httpOnly && process.env.NODE_ENV === 'production',
50
50
  sameSite: 'lax'
51
51
  };
52
52
  }
@@ -0,0 +1,111 @@
1
+ import { isValidPreviewId } from './preview';
2
+
3
+ /**
4
+ * Signed, expiring preview entry tokens.
5
+ *
6
+ * The storefront never hands out its PREVIEW_SECRET: the editor asks
7
+ * `/api/preview/link` (proving it is an editor user with its Omnitron token)
8
+ * and receives a token that names ONE preview and dies at `expiresAt`. A leaked
9
+ * link therefore exposes nothing lasting, and rotating the secret invalidates
10
+ * every outstanding link at once.
11
+ *
12
+ * Format: `v1.<previewId>.<expiresAt unix seconds>.<base64url HMAC-SHA256>`.
13
+ * Web Crypto only, so the same code runs in Node route handlers and on the
14
+ * edge.
15
+ */
16
+ export const PREVIEW_TOKEN_VERSION = 'v1';
17
+
18
+ /** How long an editor-issued preview link stays valid unless configured. */
19
+ export const DEFAULT_PREVIEW_LINK_TTL_SECONDS = 24 * 60 * 60;
20
+
21
+ export interface PreviewTokenClaims {
22
+ previewId: string;
23
+ /** Unix time in SECONDS. */
24
+ expiresAt: number;
25
+ }
26
+
27
+ export type PreviewTokenVerdict =
28
+ | { ok: true; claims: PreviewTokenClaims }
29
+ | { ok: false; reason: 'malformed' | 'expired' | 'invalid-signature' };
30
+
31
+ // Created per call: the module is also imported where TextEncoder only shows
32
+ // up after a polyfill (jsdom), and the cost is negligible.
33
+ const encode = (value: string) => new TextEncoder().encode(value);
34
+
35
+ const base64url = (bytes: ArrayBuffer): string => {
36
+ const view = new Uint8Array(bytes);
37
+ let binary = '';
38
+ for (let i = 0; i < view.length; i++) {
39
+ binary += String.fromCharCode(view[i]);
40
+ }
41
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
42
+ };
43
+
44
+ const hmac = async (secret: string, payload: string): Promise<string> => {
45
+ const key = await crypto.subtle.importKey(
46
+ 'raw',
47
+ encode(secret),
48
+ { name: 'HMAC', hash: 'SHA-256' },
49
+ false,
50
+ ['sign']
51
+ );
52
+ return base64url(await crypto.subtle.sign('HMAC', key, encode(payload)));
53
+ };
54
+
55
+ /** Constant-time string equality — a signature check must not leak by timing. */
56
+ const timingSafeEqual = (a: string, b: string): boolean => {
57
+ if (a.length !== b.length) return false;
58
+ let diff = 0;
59
+ for (let i = 0; i < a.length; i++) {
60
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
61
+ }
62
+ return diff === 0;
63
+ };
64
+
65
+ const payloadOf = ({ previewId, expiresAt }: PreviewTokenClaims): string =>
66
+ `${PREVIEW_TOKEN_VERSION}.${previewId}.${expiresAt}`;
67
+
68
+ export const signPreviewToken = async (
69
+ claims: PreviewTokenClaims,
70
+ secret: string
71
+ ): Promise<string> => {
72
+ if (!isValidPreviewId(claims.previewId)) {
73
+ throw new Error('signPreviewToken: invalid preview id');
74
+ }
75
+ if (!Number.isInteger(claims.expiresAt) || claims.expiresAt <= 0) {
76
+ throw new Error('signPreviewToken: invalid expiry');
77
+ }
78
+ const payload = payloadOf(claims);
79
+ return `${payload}.${await hmac(secret, payload)}`;
80
+ };
81
+
82
+ export const verifyPreviewToken = async (
83
+ token: string,
84
+ secret: string,
85
+ nowMs: number = Date.now()
86
+ ): Promise<PreviewTokenVerdict> => {
87
+ const parts = typeof token === 'string' ? token.split('.') : [];
88
+ if (parts.length !== 4 || parts[0] !== PREVIEW_TOKEN_VERSION) {
89
+ return { ok: false, reason: 'malformed' };
90
+ }
91
+ const [, previewId, expiresAtRaw, signature] = parts;
92
+ const expiresAt = Number(expiresAtRaw);
93
+ if (
94
+ !isValidPreviewId(previewId) ||
95
+ !/^\d+$/.test(expiresAtRaw) ||
96
+ !Number.isSafeInteger(expiresAt) ||
97
+ !signature
98
+ ) {
99
+ return { ok: false, reason: 'malformed' };
100
+ }
101
+ // Signature before expiry: an attacker must not learn which expired tokens
102
+ // were once valid.
103
+ const expected = await hmac(secret, payloadOf({ previewId, expiresAt }));
104
+ if (!timingSafeEqual(signature, expected)) {
105
+ return { ok: false, reason: 'invalid-signature' };
106
+ }
107
+ if (expiresAt * 1000 <= nowMs) {
108
+ return { ok: false, reason: 'expired' };
109
+ }
110
+ return { ok: true, claims: { previewId, expiresAt } };
111
+ };
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Widget preview contract — shared by the middleware/route handler that
3
+ * enters preview, the pz segment that carries which preview is being viewed,
4
+ * and the widget fetch layer that resolves the preview copies.
5
+ *
6
+ * The theme editor writes the other half of this contract: it creates named
7
+ * previews and stores each one's pages under `<slug>-preview-<id>`. The two
8
+ * sides must never drift.
9
+ */
10
+
11
+ /** Suffix before the preview id — hyphenated because Omnitron slugifies. */
12
+ export const PREVIEW_SLUG_SUFFIX = '-preview';
13
+
14
+ /** Remembers which named preview this browser is viewing. */
15
+ export const PREVIEW_ID_COOKIE = 'pz-preview-id';
16
+
17
+ /** Next.js's own draft-mode cookie — set by `draftMode().enable()`. */
18
+ export const DRAFT_MODE_COOKIE = '__prerender_bypass';
19
+
20
+ /** Query key on the editor's link, consumed by the /api/preview handler. */
21
+ export const PREVIEW_ID_QUERY_PARAM = 'preview_id';
22
+
23
+ /**
24
+ * The pz segment carrying the preview id into the render.
25
+ *
26
+ * A cookie cannot be used directly: the pages that render widgets are
27
+ * `dynamic = 'force-static'`, and Next.js blanks `cookies()`/`headers()`
28
+ * under that config (draftMode is the exception). Route params always
29
+ * survive, so the middleware resolves the cookie into this segment and the
30
+ * server components read it from there. See settings.js `pzSegments`.
31
+ */
32
+ export const PREVIEW_PZ_SEGMENT = 'preview';
33
+
34
+ /**
35
+ * Ids come from a cookie, so they are validated everywhere they are used:
36
+ * lowercase slug words joined by single hyphens, bounded length — exactly
37
+ * what the editor produces (see slugifyPreviewId there). No `--` anywhere:
38
+ * that is the pz segment separator, and an id containing it would make the
39
+ * segment undecodable.
40
+ */
41
+ export const isValidPreviewId = (id: unknown): id is string =>
42
+ typeof id === 'string' &&
43
+ id.length <= 32 &&
44
+ /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id);
45
+
46
+ /** The slug a widget's copy lives under inside one named preview. */
47
+ export const previewSlug = (slug: string, previewId: string): string =>
48
+ `${slug}${PREVIEW_SLUG_SUFFIX}-${previewId}`;
49
+
50
+ /**
51
+ * True for slugs shaped like a preview copy of something. A HEURISTIC — a
52
+ * live slug can legitimately end this way (a custom page named
53
+ * `summer-preview-2026`), so the fetch layer does not use it to decide
54
+ * whether to overlay; see `isPreviewCopySlug`.
55
+ */
56
+ export const isPreviewSlug = (slug: string): boolean =>
57
+ /-preview-[a-z0-9-]+$/.test(slug);
58
+
59
+ /**
60
+ * True when `slug` is already the copy of something inside THIS preview —
61
+ * the exact check the fetch layer needs so preview slugs are never nested,
62
+ * without misreading live slugs that merely look like one.
63
+ */
64
+ export const isPreviewCopySlug = (slug: string, previewId: string): boolean =>
65
+ previewId !== '' && slug.endsWith(previewSlug('', previewId));
66
+
67
+ /**
68
+ * Resolves the pz segment value from the request — used by settings.js.
69
+ * An invalid or absent cookie yields '' (no preview), which the fetch layer
70
+ * treats as "render live".
71
+ *
72
+ * The id only counts alongside Next's draft-mode cookie: without it the
73
+ * request renders live anyway, and folding an unauthenticated cookie value
74
+ * into the route segment would let any visitor mint a fresh ISR/Redis cache
75
+ * key per request.
76
+ */
77
+ export const resolvePreviewSegment = (req: {
78
+ cookies: { get: (name: string) => { value: string } | undefined };
79
+ }): string => {
80
+ if (!req.cookies.get(DRAFT_MODE_COOKIE)?.value) return '';
81
+ const value = req.cookies.get(PREVIEW_ID_COOKIE)?.value ?? '';
82
+ return isValidPreviewId(value) ? value : '';
83
+ };
@@ -40,15 +40,44 @@ export function encodePzValue(
40
40
  .join(config.separator);
41
41
  }
42
42
 
43
+ /**
44
+ * Inverse of `encodePzValue`.
45
+ *
46
+ * The `url` segment is `encodeURIComponent(fullUrl)`, and that leaves `-`
47
+ * alone — so a pathname containing the separator (`/collections/summer--sale`)
48
+ * splits into extra parts. Only `url` can do that (locale, currency and the
49
+ * custom segments are validated slugs), so the segments before it are read
50
+ * from the front, the ones after it from the back, and whatever is left in
51
+ * the middle is the url re-joined. A purely positional read would hand the
52
+ * url's tail to the segment after it — with a preview segment present that
53
+ * meant rendering the wrong preview (or live) with a misleading banner.
54
+ */
43
55
  export function decodePzValue(
44
56
  pzValue: string,
45
57
  config: PzSegmentsConfig
46
58
  ): Record<string, string> {
47
59
  const parts = pzValue.split(config.separator);
48
60
  const result: Record<string, string> = {};
61
+ const urlIndex = config.segments.findIndex((seg) => seg.name === 'url');
49
62
 
63
+ if (urlIndex === -1 || parts.length <= config.segments.length) {
64
+ config.segments.forEach((seg, index) => {
65
+ result[seg.name] = parts[index] ?? '';
66
+ });
67
+ return result;
68
+ }
69
+
70
+ const trailing = config.segments.length - urlIndex - 1;
50
71
  config.segments.forEach((seg, index) => {
51
- result[seg.name] = parts[index] ?? '';
72
+ if (index < urlIndex) {
73
+ result[seg.name] = parts[index] ?? '';
74
+ } else if (index === urlIndex) {
75
+ result[seg.name] = parts
76
+ .slice(urlIndex, parts.length - trailing)
77
+ .join(config.separator);
78
+ } else {
79
+ result[seg.name] = parts[parts.length - trailing + (index - urlIndex - 1)] ?? '';
80
+ }
52
81
  });
53
82
 
54
83
  return result;
@@ -6,5 +6,12 @@ const { locales, defaultLocaleValue, defaultCurrencyCode } =
6
6
  export const ServerVariables = {
7
7
  locale: locales.find((l) => l.value === defaultLocaleValue)?.value ?? '',
8
8
  currency: defaultCurrencyCode,
9
- globalHeaders: {}
9
+ globalHeaders: {},
10
+ /**
11
+ * Which named widget preview the current render belongs to, decoded from
12
+ * the pz route segment by withSegmentDefaults. Empty for ordinary traffic.
13
+ * Only ever acted on together with draft mode, so a value left behind by a
14
+ * concurrent request cannot leak preview content to a normal visitor.
15
+ */
16
+ previewId: ''
10
17
  };
package/with-pz-config.js CHANGED
@@ -30,10 +30,6 @@ const defaultConfig = {
30
30
  {
31
31
  protocol: 'https',
32
32
  hostname: '**.akinoncdn.com'
33
- },
34
- {
35
- protocol: 'https',
36
- hostname: '**.akinoncloudcdn.com'
37
33
  }
38
34
  ]
39
35
  },
@@ -78,8 +74,7 @@ const defaultConfig = {
78
74
  acc[`@akinon/${plugin}`] = false;
79
75
  return acc;
80
76
  }, {}),
81
- translations: false,
82
- '@opentelemetry/exporter-jaeger': false
77
+ translations: false
83
78
  };
84
79
  // Ensure webpack can resolve deps from the app's node_modules when
85
80
  // compiling transpiled packages (e.g. @akinon/next) whose imports
package/api/client-env.ts DELETED
@@ -1,78 +0,0 @@
1
- import { NextRequest, NextResponse } from 'next/server';
2
-
3
- /**
4
- * Runtime access to public (`NEXT_PUBLIC_*`) environment variables.
5
- *
6
- * Next.js inlines `process.env.NEXT_PUBLIC_*` into the bundle at *build* time.
7
- * On hosting platforms where the build has no access to the environment (e.g.
8
- * Akinon Cloud Commerce), those references resolve to `undefined` in the
9
- * browser. This route reads the variables from the *server runtime* instead —
10
- * `process.env[name]` is a computed lookup, so webpack never statically inlines
11
- * it — and hands them back to the client.
12
- *
13
- * Only `NEXT_PUBLIC_`-prefixed names are resolvable. These values are public by
14
- * design (they are shipped to the browser anyway), so nothing secret can leak
15
- * through here; the prefix check is what keeps server-only secrets unreadable.
16
- *
17
- * Query: one or more `env` params, repeated (`?env=A&env=B`) and/or comma
18
- * separated (`?env=A,B`). Names must include the full prefix. Responds with a
19
- * `{ [name]: value | null }` map (`null` when the variable is not set).
20
- *
21
- * The consuming route file must set `export const dynamic = 'force-dynamic'` so
22
- * Next never statically caches a build-time (empty) response.
23
- *
24
- * @see `@akinon/next/hooks` — `useClientEnv` / `getClientEnv` read from here.
25
- */
26
-
27
- const CLIENT_ENV_NAME = /^NEXT_PUBLIC_[A-Za-z0-9_]+$/;
28
-
29
- export async function GET(request: NextRequest) {
30
- try {
31
- const { searchParams } = new URL(request.url);
32
-
33
- const names = Array.from(
34
- new Set(
35
- searchParams
36
- .getAll('env')
37
- .flatMap((value) => value.split(','))
38
- .map((value) => value.trim())
39
- .filter(Boolean)
40
- )
41
- );
42
-
43
- if (names.length === 0) {
44
- return NextResponse.json(
45
- { message: 'At least one `env` query parameter is required.' },
46
- { status: 400 }
47
- );
48
- }
49
-
50
- const invalid = names.filter((name) => !CLIENT_ENV_NAME.test(name));
51
-
52
- if (invalid.length > 0) {
53
- return NextResponse.json(
54
- {
55
- message:
56
- 'Only NEXT_PUBLIC_-prefixed environment variables can be read.',
57
- invalid
58
- },
59
- { status: 400 }
60
- );
61
- }
62
-
63
- const values = names.reduce<Record<string, string | null>>((acc, name) => {
64
- acc[name] = process.env[name] ?? null;
65
- return acc;
66
- }, {});
67
-
68
- return NextResponse.json(values, {
69
- headers: { 'Cache-Control': 'no-store' }
70
- });
71
- } catch (error) {
72
- console.error('Error in client-env API:', error);
73
- return NextResponse.json(
74
- { message: 'Internal server error' },
75
- { status: 500 }
76
- );
77
- }
78
- }