@akinon/next 2.0.79-rc.0 → 2.0.79-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,5 +1,37 @@
1
1
  # @akinon/next
2
2
 
3
+ ## 2.0.79-rc.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 86187b1c: ZERO-4879: Repair sync-merge corruption in default middleware and server data loaders — remove a duplicated block that left an unbalanced brace, and restore the awaited `result` binding the payload optimization reads
8
+ - 0cf9ea239: BRDG-16491: Prevent redirect when iframe payment is active
9
+ - 324f97d55: ZERO-4219: replace masterpass-rest-complete with masterpass-rest-callback
10
+ - 51ea06888: ZERO-4377: Fix checkout card type state being cleared after valid bin number responses.
11
+ - ZERO-4160: Enhance oauth-login middleware with improved request handling and logging
12
+ - 2fea4143: ZERO-4620: Add runtime access to `NEXT_PUBLIC_*` environment variables from Client Components
13
+ - b55acb768: ZERO-2577: Fix pagination bug and update usePagination hook and ensure pagination controls rendering correctly
14
+ - 760258c1c: ZERO-4160: Enhance oauth-login middleware to handle fetch errors and improve response handling
15
+ - 143be2b9d: ZERO-3457: Crop styles are customizable and logic improved for rendering similar products modal
16
+ - 7889b08fe: ZERO-4276: Enhance route generation by adding .env loading and custom skip segments support
17
+ - 9f8cd3bc5: ZERO-3449: AI Search Active Filters & Crop Style changes have been implemented
18
+ - bfafa3f49: ZERO-4160: Refactor oauth-login middleware to use fetchCommerce for API calls and improve cookie handling
19
+ - 57d7eb305: ZERO-4276: Refactor route generation logic by removing environment loading and simplifying skip segments handling
20
+ - d99a6a7d5: ZERO-3457_1: Fixed the settings prop and made sure everything is customizable.
21
+ - 9db81a714: ZERO-4365: Remove brand `@theme/*` alias imports from library packages
22
+ - 591e345e1: ZERO-3855: Enhance credit card payment handling in checkout middlewares
23
+ - 4de5303c5: ZERO-2504: add cookie filter to api client request
24
+ - 95b139dc1: ZERO-3795: Remove duplicate entry for SavedCard in PluginComponents map
25
+ - 1d00f2d06: BRDG-16664: Set secure flag for CSRF token cookies in useCaptcha and default middleware
26
+ - 4ac7b2a1e: ZERO-4219: fix masterpass-rest callback route format and double-encoded error cookie
27
+ - e9598c71: ZERO-4622: Images remotePatterns for improved readability
28
+ - 4998a9631: ZERO-4168: Add server-side payload optimization
29
+ - 804d2bd6: ZERO-4536: Add akinon.net domain to CSP frame-ancestors directive
30
+ - 3909d3224: Edit the duplicate Plugin.SimilarProducts in the plugin-module.
31
+ - 6a3d8a63: ZERO-4541: Fix URL query string formatting in getOrders and getOldOrders functions
32
+ - e18836b20: ZERO-4160: Restore scope in Sentry addon configuration in akinon.json
33
+ - b1111d7b: ZERO-4841: Guard `withPrettyUrl` against calling `String.prototype.replace` with an `undefined` locale prefix on projects without a URL locale prefix (e.g. `HideDefaultLocale`) — previously this coerced to the literal string `"undefined"` and silently stripped a trailing `/undefined` segment from the path before the pretty-url lookup, causing bogus URLs like `/{product-slug}/undefined` to resolve and rewrite to the real product page (200) instead of 404
34
+
3
35
  ## 2.0.79-rc.0
4
36
 
5
37
  ### Patch Changes
@@ -1,19 +1,192 @@
1
1
  import { Cache, CacheKey } from '../../lib/cache';
2
2
  import 'server-only';
3
+ import { draftMode } from 'next/headers';
3
4
  import { CacheOptions, WidgetResultType, WidgetSchemaType } from '../../types';
4
5
  import appFetch from '../../utils/app-fetch';
5
6
  import { widgets } from '../urls';
6
7
  import { ServerVariables } from '../../utils/server-variables';
7
- import { optimizeWidgetResponse } from '../../utils/payload-optimizer';
8
- import logger from '../../utils/log';
9
- import settings from 'settings';
8
+ import {
9
+ isPreviewCopySlug,
10
+ isValidPreviewId,
11
+ previewSlug
12
+ } from '../../utils/preview';
13
+
14
+ /**
15
+ * Widget preview (draft mode): the theme editor keeps any number of NAMED
16
+ * previews, each storing its pages under `<slug>-preview-<previewId>`. With
17
+ * draft mode on (entered via /api/preview, toggled by `?preview` on any page
18
+ * url) and a preview id on the request, every widget fetch first tries that
19
+ * preview's copy and falls back to the live slug when none exists — a
20
+ * preview renders as "live + that preview's overlay". Preview fetches bypass
21
+ * Redis and the fetch data cache so the editor's latest save is visible.
22
+ *
23
+ * BOTH signals are required: draft mode alone renders live (no id ⇒ no
24
+ * preview slug to try), and an id alone does nothing without draft mode.
25
+ */
26
+ const PREVIEW_SNAPSHOT_ATTRIBUTE = 'preview_snapshot';
27
+
28
+ const PREVIEW_NO_STORE = { revalidate: 0 };
29
+
30
+ // The snapshot blob owns theme settings/data sources in preview, so the
31
+ // theme-config widget itself is never slug-transformed; a slug that is
32
+ // already this preview's copy is never transformed twice. Checked against
33
+ // the CURRENT id, not a shape — a live slug may legitimately end in
34
+ // `-preview-<something>` (a custom page named `summer-preview-2026`).
35
+ const isPreviewTransformableSlug = (slug: string, previewId: string): boolean =>
36
+ slug !== 'theme-config' && !isPreviewCopySlug(slug, previewId);
37
+
38
+ /**
39
+ * The editor's directory of previews that exist (`theme-previews` widget,
40
+ * `theme_previews` attribute). Deleting a preview removes it here first and
41
+ * clears only the pages the editor had loaded — so this is what makes a
42
+ * deleted preview stop rendering, even for a browser that still carries its
43
+ * cookie. Read uncached, remembered briefly across requests: a deleted
44
+ * preview may linger for at most REGISTRY_TTL_MS. An unreadable registry
45
+ * fails OPEN (behaves as before the check existed) rather than blanking
46
+ * every preview on a transient backend error.
47
+ */
48
+ const PREVIEW_REGISTRY_SLUG = 'theme-previews';
49
+ const PREVIEW_REGISTRY_ATTRIBUTE = 'theme_previews';
50
+ const REGISTRY_TTL_MS = 5_000;
51
+
52
+ let registryMemo: { ids: Set<string> | null; expires: number } = {
53
+ ids: null,
54
+ expires: 0
55
+ };
56
+
57
+ const unwrapAttribute = (raw: unknown): unknown =>
58
+ typeof raw === 'object' && raw !== null && 'value' in raw
59
+ ? (raw as { value?: unknown }).value
60
+ : raw;
61
+
62
+ const registryKnowsPreview = async (
63
+ previewId: string,
64
+ locale: string,
65
+ currency: string
66
+ ): Promise<boolean> => {
67
+ const now = Date.now();
68
+ if (registryMemo.expires <= now) {
69
+ let ids: Set<string> | null = null;
70
+ try {
71
+ const widget = await getWidgetDataHandler(
72
+ PREVIEW_REGISTRY_SLUG,
73
+ locale,
74
+ currency,
75
+ undefined,
76
+ PREVIEW_NO_STORE
77
+ )();
78
+ const raw = unwrapAttribute(
79
+ (widget as { attributes?: Record<string, unknown> } | null)
80
+ ?.attributes?.[PREVIEW_REGISTRY_ATTRIBUTE]
81
+ );
82
+ if (typeof raw === 'string' && raw) {
83
+ const parsed = JSON.parse(raw);
84
+ if (Array.isArray(parsed?.previews)) {
85
+ ids = new Set(
86
+ (parsed.previews as Array<{ id?: unknown }>)
87
+ .map((entry) => entry?.id)
88
+ .filter((id): id is string => typeof id === 'string')
89
+ );
90
+ }
91
+ }
92
+ } catch {
93
+ ids = null;
94
+ }
95
+ registryMemo = { ids, expires: now + REGISTRY_TTL_MS };
96
+ }
97
+ return registryMemo.ids ? registryMemo.ids.has(previewId) : true;
98
+ };
99
+
100
+ /**
101
+ * The named preview this render belongs to, or '' when the request is not a
102
+ * preview at all. The id is decoded from the pz route segment (see
103
+ * utils/preview.ts) and re-validated here — it originates from a cookie.
104
+ */
105
+ const previewIdForRequest = async (
106
+ locale: string = ServerVariables.locale,
107
+ currency: string = ServerVariables.currency
108
+ ): Promise<string> => {
109
+ try {
110
+ if (!(await draftMode()).isEnabled) return '';
111
+ } catch {
112
+ // No request scope (e.g. build-time prerender) — never a preview.
113
+ return '';
114
+ }
115
+ const previewId = ServerVariables.previewId;
116
+ if (!isValidPreviewId(previewId)) return '';
117
+ return (await registryKnowsPreview(previewId, locale, currency))
118
+ ? previewId
119
+ : '';
120
+ };
121
+
122
+ /**
123
+ * Whole-placeholder preview snapshot written by the theme editor into the
124
+ * `preview_snapshot` attribute of `<placeholderSlug>-preview-<previewId>`.
125
+ * When present (draft mode only), the placeholder renders straight from this
126
+ * blob — no per-section fetches.
127
+ */
128
+ export type PreviewSnapshot = {
129
+ version: number;
130
+ savedAt?: string;
131
+ themeSettings?: Record<string, unknown> | null;
132
+ dataSources?: unknown[];
133
+ sections: unknown[];
134
+ };
135
+
136
+ export const getPreviewSnapshot = async ({
137
+ slug,
138
+ locale = ServerVariables.locale,
139
+ currency = ServerVariables.currency
140
+ }: {
141
+ slug: string;
142
+ locale?: string;
143
+ currency?: string;
144
+ }): Promise<PreviewSnapshot | null> => {
145
+ const previewId = slug ? await previewIdForRequest(locale, currency) : '';
146
+ if (!previewId) {
147
+ return null;
148
+ }
149
+
150
+ const widget = await getWidgetDataHandler(
151
+ previewSlug(slug, previewId),
152
+ locale,
153
+ currency,
154
+ undefined,
155
+ PREVIEW_NO_STORE
156
+ )();
157
+
158
+ const rawAttribute = (
159
+ widget as { attributes?: Record<string, unknown> } | null
160
+ )?.attributes?.[PREVIEW_SNAPSHOT_ATTRIBUTE];
161
+ const rawValue =
162
+ typeof rawAttribute === 'object' &&
163
+ rawAttribute !== null &&
164
+ 'value' in rawAttribute
165
+ ? (rawAttribute as { value?: unknown }).value
166
+ : rawAttribute;
167
+
168
+ if (typeof rawValue !== 'string' || !rawValue) {
169
+ return null;
170
+ }
171
+
172
+ try {
173
+ const parsed = JSON.parse(rawValue);
174
+ if (parsed?.version === 1 && Array.isArray(parsed.sections)) {
175
+ return parsed as PreviewSnapshot;
176
+ }
177
+ } catch {
178
+ // Malformed snapshot — fall back to the live render path.
179
+ }
180
+ return null;
181
+ };
10
182
 
11
183
  const getWidgetDataHandler =
12
184
  (
13
185
  slug: string,
14
186
  locale: string,
15
187
  currency: string,
16
- headers?: Record<string, string>
188
+ headers?: Record<string, string>,
189
+ next?: { revalidate: number }
17
190
  ) =>
18
191
  async () => {
19
192
  if (!slug) {
@@ -25,13 +198,20 @@ const getWidgetDataHandler =
25
198
  locale,
26
199
  currency,
27
200
  init: {
28
- headers
201
+ headers,
202
+ ...(next ? { next } : {})
29
203
  }
30
204
  });
31
205
  };
32
206
 
33
207
  const getWidgetSchemaDataHandler =
34
- (widgetSlug: string, locale: string, currency: string) => async () => {
208
+ (
209
+ widgetSlug: string,
210
+ locale: string,
211
+ currency: string,
212
+ next?: { revalidate: number }
213
+ ) =>
214
+ async () => {
35
215
  if (!widgetSlug) {
36
216
  return null;
37
217
  }
@@ -39,7 +219,8 @@ const getWidgetSchemaDataHandler =
39
219
  return await appFetch({
40
220
  url: widgets.getWidgetSchema(widgetSlug),
41
221
  locale,
42
- currency
222
+ currency,
223
+ init: next ? { next } : {}
43
224
  });
44
225
  };
45
226
 
@@ -56,7 +237,36 @@ export const getWidgetData = async <T>({
56
237
  cacheOptions?: CacheOptions;
57
238
  headers?: Record<string, string>;
58
239
  }): Promise<WidgetResultType<T>> => {
59
- const result = await Cache.wrap(
240
+ const requestPreviewId =
241
+ slug === 'theme-config' ? '' : await previewIdForRequest(locale, currency);
242
+ const previewId = isPreviewTransformableSlug(slug, requestPreviewId)
243
+ ? requestPreviewId
244
+ : '';
245
+ if (previewId) {
246
+ const previewData = await getWidgetDataHandler(
247
+ previewSlug(slug, previewId),
248
+ locale,
249
+ currency,
250
+ headers,
251
+ PREVIEW_NO_STORE
252
+ )();
253
+
254
+ // A snapshot HOLDER (placeholder blob carrier, consumed exclusively via
255
+ // getPreviewSnapshot) is not a per-widget preview copy — returning it
256
+ // here would shadow the live widget with an attribute-less shell when
257
+ // its blob is malformed and the caller fell back to the live path.
258
+ const previewAttributes = (
259
+ previewData as { attributes?: Record<string, unknown> } | null
260
+ )?.attributes;
261
+ if (
262
+ previewAttributes &&
263
+ previewAttributes[PREVIEW_SNAPSHOT_ATTRIBUTE] === undefined
264
+ ) {
265
+ return previewData as WidgetResultType<T>;
266
+ }
267
+ }
268
+
269
+ return Cache.wrap(
60
270
  CacheKey.Widget(slug),
61
271
  locale,
62
272
  getWidgetDataHandler(slug, locale, currency, headers),
@@ -78,7 +288,13 @@ export const getWidgetData = async <T>({
78
288
  };
79
289
 
80
290
  const getCollectionWidgetDataHandler =
81
- (slug: string, locale: string, currency: string) => async () => {
291
+ (
292
+ slug: string,
293
+ locale: string,
294
+ currency: string,
295
+ next?: { revalidate: number }
296
+ ) =>
297
+ async () => {
82
298
  if (!slug) {
83
299
  return null;
84
300
  }
@@ -86,7 +302,8 @@ const getCollectionWidgetDataHandler =
86
302
  return await appFetch({
87
303
  url: widgets.getCollectionWidget(slug),
88
304
  locale,
89
- currency
305
+ currency,
306
+ init: next ? { next } : {}
90
307
  });
91
308
  };
92
309
 
@@ -101,6 +318,24 @@ export const getCollectionWidgetData = async <T>({
101
318
  currency?: string;
102
319
  cacheOptions?: CacheOptions;
103
320
  }): Promise<WidgetResultType<T>> => {
321
+ const requestPreviewId =
322
+ slug === 'theme-config' ? '' : await previewIdForRequest(locale, currency);
323
+ const previewId = isPreviewTransformableSlug(slug, requestPreviewId)
324
+ ? requestPreviewId
325
+ : '';
326
+ if (previewId) {
327
+ const previewData = await getCollectionWidgetDataHandler(
328
+ previewSlug(slug, previewId),
329
+ locale,
330
+ currency,
331
+ PREVIEW_NO_STORE
332
+ )();
333
+
334
+ if ((previewData as { attributes?: unknown } | null)?.attributes) {
335
+ return previewData as WidgetResultType<T>;
336
+ }
337
+ }
338
+
104
339
  return Cache.wrap(
105
340
  CacheKey.Widget(`collection:${slug}`),
106
341
  locale,
@@ -123,6 +358,26 @@ export const getWidgetSchemaData = async <T>({
123
358
  currency?: string;
124
359
  cacheOptions?: CacheOptions;
125
360
  }): Promise<WidgetSchemaType<T>> => {
361
+ const requestPreviewId =
362
+ widgetSlug === 'theme-config'
363
+ ? ''
364
+ : await previewIdForRequest(locale, currency);
365
+ const previewId = isPreviewTransformableSlug(widgetSlug, requestPreviewId)
366
+ ? requestPreviewId
367
+ : '';
368
+ if (previewId) {
369
+ const previewData = await getWidgetSchemaDataHandler(
370
+ previewSlug(widgetSlug, previewId),
371
+ locale,
372
+ currency,
373
+ PREVIEW_NO_STORE
374
+ )();
375
+
376
+ if ((previewData as { schema?: unknown } | null)?.schema) {
377
+ return previewData as WidgetSchemaType<T>;
378
+ }
379
+ }
380
+
126
381
  return Cache.wrap(
127
382
  CacheKey.WidgetSchema(widgetSlug),
128
383
  locale,
@@ -15,6 +15,7 @@ import {
15
15
  getBuiltInSegments,
16
16
  isLegacyMode
17
17
  } from '../../utils/pz-segments';
18
+ import { isValidPreviewId, PREVIEW_PZ_SEGMENT } from '../../utils/preview';
18
19
 
19
20
  type SegmentType = 'root-layout' | 'layout' | 'page';
20
21
 
@@ -60,6 +61,9 @@ export const withSegmentDefaults =
60
61
 
61
62
  let localeValue: string;
62
63
  let currencyValue: string;
64
+ // Which named widget preview this render belongs to, if any — see
65
+ // utils/preview.ts for why it travels in the route rather than a cookie.
66
+ let previewValue = '';
63
67
 
64
68
  if (isLegacyMode(settings)) {
65
69
  localeValue = resolvedParams.locale;
@@ -70,6 +74,10 @@ export const withSegmentDefaults =
70
74
  const builtIn = getBuiltInSegments(parsed, settings);
71
75
  localeValue = builtIn.locale;
72
76
  currencyValue = builtIn.currency;
77
+ // Cookie-derived, so re-validated here rather than trusted.
78
+ previewValue = isValidPreviewId(parsed[PREVIEW_PZ_SEGMENT])
79
+ ? parsed[PREVIEW_PZ_SEGMENT]
80
+ : '';
73
81
  }
74
82
 
75
83
  if (options.segmentType === 'root-layout') {
@@ -83,6 +91,7 @@ export const withSegmentDefaults =
83
91
 
84
92
  ServerVariables.locale = localeValue;
85
93
  ServerVariables.currency = currencyValue;
94
+ ServerVariables.previewId = previewValue;
86
95
 
87
96
  return await (
88
97
  <>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@akinon/next",
3
3
  "description": "Core package for Project Zero Next",
4
- "version": "2.0.79-rc.0",
4
+ "version": "2.0.79-rc.1",
5
5
  "private": false,
6
6
  "license": "MIT",
7
7
  "bin": {
@@ -36,7 +36,7 @@
36
36
  "set-cookie-parser": "2.6.0"
37
37
  },
38
38
  "devDependencies": {
39
- "@akinon/eslint-plugin-projectzero": "2.0.79-rc.0",
39
+ "@akinon/eslint-plugin-projectzero": "2.0.79-rc.1",
40
40
  "@babel/core": "7.26.10",
41
41
  "@babel/preset-env": "7.26.9",
42
42
  "@babel/preset-typescript": "7.27.0",
@@ -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
 
@@ -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
  };