@amboras-dev/storefront-core 2026.11.10 → 2026.11.11-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 +107 -0
- package/README.md +29 -3
- package/bin/amboras-check.mjs +2 -1
- package/bin/checks/check-market-routes.mjs +184 -0
- package/bin/checks/check-redirect-boundaries.mjs +10 -2
- package/core-manifest.json +6 -1
- package/dist/edge/hosted-checkout.d.ts +5 -2
- package/dist/edge/hosted-checkout.d.ts.map +1 -1
- package/dist/edge/hosted-checkout.js +8 -6
- package/dist/edge/hosted-checkout.js.map +1 -1
- package/dist/edge/market.d.ts +45 -0
- package/dist/edge/market.d.ts.map +1 -0
- package/dist/edge/market.js +74 -0
- package/dist/edge/market.js.map +1 -0
- package/dist/edge/proxy.d.ts +27 -2
- package/dist/edge/proxy.d.ts.map +1 -1
- package/dist/edge/proxy.js +204 -56
- package/dist/edge/proxy.js.map +1 -1
- package/dist/edge/url-map.d.ts +57 -0
- package/dist/edge/url-map.d.ts.map +1 -0
- package/dist/edge/url-map.js +140 -0
- package/dist/edge/url-map.js.map +1 -0
- package/dist/hooks/use-auth.d.ts.map +1 -1
- package/dist/hooks/use-auth.js +5 -2
- package/dist/hooks/use-auth.js.map +1 -1
- package/dist/lib/market.d.ts +176 -0
- package/dist/lib/market.d.ts.map +1 -0
- package/dist/lib/market.js +228 -0
- package/dist/lib/market.js.map +1 -0
- package/dist/lib/medusa-client.d.ts.map +1 -1
- package/dist/lib/medusa-client.js +30 -1
- package/dist/lib/medusa-client.js.map +1 -1
- package/dist/lib/redirects.d.ts +13 -5
- package/dist/lib/redirects.d.ts.map +1 -1
- package/dist/lib/redirects.js +68 -9
- package/dist/lib/redirects.js.map +1 -1
- package/dist/lib/seo.d.ts +20 -7
- package/dist/lib/seo.d.ts.map +1 -1
- package/dist/lib/seo.js +157 -29
- package/dist/lib/seo.js.map +1 -1
- package/dist/lib/site-url.d.ts +8 -0
- package/dist/lib/site-url.d.ts.map +1 -1
- package/dist/lib/site-url.js +18 -0
- package/dist/lib/site-url.js.map +1 -1
- package/dist/lib/visitor-free-routes.d.ts +17 -0
- package/dist/lib/visitor-free-routes.d.ts.map +1 -0
- package/dist/lib/visitor-free-routes.js +31 -0
- package/dist/lib/visitor-free-routes.js.map +1 -0
- package/dist/next-config/index.d.ts +31 -0
- package/dist/next-config/index.d.ts.map +1 -1
- package/dist/next-config/index.js +32 -1
- package/dist/next-config/index.js.map +1 -1
- package/dist/shell/market-link.d.ts +18 -0
- package/dist/shell/market-link.d.ts.map +1 -0
- package/dist/shell/market-link.js +39 -0
- package/dist/shell/market-link.js.map +1 -0
- package/package.json +5 -1
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { isCheckoutPath } from './hosted-checkout.js';
|
|
2
|
+
import { isAnnounced, keyOfPresence, presenceOfHost, ROOT_MARKET_KEY } from '../lib/market.js';
|
|
3
|
+
/** `https://<host><path><search>`: the path is set on the origin (leading slashes folded), never resolved against it. */
|
|
4
|
+
function onHost(host, path, search) {
|
|
5
|
+
const target = new URL(`https://${host}`);
|
|
6
|
+
target.pathname = path.replace(/^[/\\]+/, '/');
|
|
7
|
+
target.search = search;
|
|
8
|
+
return target;
|
|
9
|
+
}
|
|
10
|
+
/** Whether an inactive presence 302s to the root: Medusa's `inactiveRedirect`. */
|
|
11
|
+
const redirectsWhenInactive = (presence) => presence.status === 'inactive' && presence.inactiveRedirect === 'temporary';
|
|
12
|
+
/** `/en-ca` + `/x` → `/en-ca/x`; `/en-ca` + `/` → `/en-ca`. */
|
|
13
|
+
const joinPrefix = (prefix, inner) => (inner === '/' ? prefix : prefix + inner);
|
|
14
|
+
/** The root: today's behaviour, no market. */
|
|
15
|
+
export function rootResolution(url) {
|
|
16
|
+
return { source: 'root', marketId: null, publicPrefix: '', internalKey: ROOT_MARKET_KEY, innerPath: url.pathname };
|
|
17
|
+
}
|
|
18
|
+
/** `options.subfolders: false` resolves hosts only (the `proxy` export, for a store tree without `app/[m]/`). */
|
|
19
|
+
export function resolveMarket(url, host, map, primaryHost, { subfolders: withSubfolders = true } = {}) {
|
|
20
|
+
const root = rootResolution(url);
|
|
21
|
+
if (!map)
|
|
22
|
+
return { ...root, fallback: 'map_unavailable' };
|
|
23
|
+
const fallback = map.stale ? 'map_stale' : undefined;
|
|
24
|
+
const result = (r) => (fallback ? { ...r, fallback } : r);
|
|
25
|
+
const { presences } = map.value;
|
|
26
|
+
const { search } = url;
|
|
27
|
+
const hosted = presenceOfHost(map.value, host);
|
|
28
|
+
if (hosted) {
|
|
29
|
+
if (hosted.status === 'active') {
|
|
30
|
+
return result({ source: 'host', marketId: hosted.marketId, publicPrefix: '', internalKey: keyOfPresence(hosted), innerPath: url.pathname });
|
|
31
|
+
}
|
|
32
|
+
if (hosted.status === 'pending')
|
|
33
|
+
return { ...root, fallback: fallback ?? 'domain_pending' };
|
|
34
|
+
if (!primaryHost || !redirectsWhenInactive(hosted))
|
|
35
|
+
return result(root);
|
|
36
|
+
return result({ ...root, redirect: { location: onHost(primaryHost, url.pathname, search), status: 302, kind: 'inactive' } });
|
|
37
|
+
}
|
|
38
|
+
if (!withSubfolders || !primaryHost || host !== primaryHost)
|
|
39
|
+
return result(root);
|
|
40
|
+
const slash = url.pathname.indexOf('/', 1);
|
|
41
|
+
const segment = `/${slash < 0 ? url.pathname.slice(1) : url.pathname.slice(1, slash)}`;
|
|
42
|
+
const inner = slash < 0 ? '/' : url.pathname.slice(slash);
|
|
43
|
+
const subfolders = presences.filter((p) => p.kind === 'subfolder' && p.path !== null);
|
|
44
|
+
const current = subfolders.find((p) => p.path === segment);
|
|
45
|
+
if (current?.status === 'active') {
|
|
46
|
+
const market = {
|
|
47
|
+
source: 'subfolder',
|
|
48
|
+
marketId: current.marketId,
|
|
49
|
+
publicPrefix: current.path,
|
|
50
|
+
internalKey: keyOfPresence(current),
|
|
51
|
+
innerPath: inner,
|
|
52
|
+
};
|
|
53
|
+
// The checkout runs at the root until the hosted checkout knows the market path (§13 item 4).
|
|
54
|
+
if (isCheckoutPath(inner))
|
|
55
|
+
return result({ ...market, redirect: { location: onHost(primaryHost, inner, search), status: 302, kind: 'root_checkout' } });
|
|
56
|
+
return result(market);
|
|
57
|
+
}
|
|
58
|
+
if (current && redirectsWhenInactive(current)) {
|
|
59
|
+
return result({ ...root, redirect: { location: onHost(primaryHost, inner, search), status: 302, kind: 'inactive' } });
|
|
60
|
+
}
|
|
61
|
+
if (current)
|
|
62
|
+
return result(root);
|
|
63
|
+
const moved = presences.find((p) => p.previousPaths.includes(segment));
|
|
64
|
+
const relanguaged = moved ? undefined : presences.find((p) => p.languagePaths.includes(segment));
|
|
65
|
+
const target = moved ?? relanguaged;
|
|
66
|
+
if (!target)
|
|
67
|
+
return result(root);
|
|
68
|
+
const to = isAnnounced(target) ? target : null;
|
|
69
|
+
const location = to?.path ? onHost(primaryHost, joinPrefix(to.path, inner), search) : to?.host ? onHost(to.host, inner, search) : null;
|
|
70
|
+
if (location)
|
|
71
|
+
return result({ ...root, redirect: { location, status: 301, kind: moved ? 'previous_path' : 'language' } });
|
|
72
|
+
return result({ ...root, redirect: { location: onHost(primaryHost, inner, search), status: 302, kind: 'unserved' } });
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=market.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"market.js","sourceRoot":"","sources":["../../src/edge/market.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAuB,MAAM,kBAAkB,CAAA;AAqCnH,yHAAyH;AACzH,SAAS,MAAM,CAAC,IAAY,EAAE,IAAY,EAAE,MAAc;IACxD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,WAAW,IAAI,EAAE,CAAC,CAAA;IACzC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,SA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AAU,EAAE,EAAE,CAAC,CAAA;IACzH,OAAO,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,EAAE,QAAQ,EAAE,MAAM,CAAC,WAAW,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,UAAU,EAAE,EAAE,CAAC,CAAA;AACvH,CAAC"}
|
package/dist/edge/proxy.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { NextRequest, NextResponse } from 'next/server';
|
|
1
|
+
import { NextRequest, NextResponse, type NextFetchEvent } from 'next/server';
|
|
2
2
|
/**
|
|
3
3
|
* The matcher the store's proxy.ts must declare. Next reads `config` statically
|
|
4
4
|
* from the proxy file itself, so it cannot be re-exported from a package: the
|
|
@@ -7,5 +7,30 @@ import { NextRequest, NextResponse } from 'next/server';
|
|
|
7
7
|
export declare const proxyConfig: {
|
|
8
8
|
matcher: string[];
|
|
9
9
|
};
|
|
10
|
-
|
|
10
|
+
/** The URL paths served outside a store's `app/[m]/` tree (AMB-2174): one list for the proxy, links and the gate. */
|
|
11
|
+
export { OUTSIDE_MARKET_TREE } from '../lib/market.js';
|
|
12
|
+
/**
|
|
13
|
+
* Edge entrypoint for a store tree without `app/[m]/`: today's proxy. It never rewrites the path, so a core bump never
|
|
14
|
+
* moves a store's routes, and it reads no URL map, sets no `x-amb-market`, sends no market redirect and adds no market
|
|
15
|
+
* canonical: market URLs exist only on a build that opted in (`marketTreeEnv()`, `isMarketTreeBuild()`).
|
|
16
|
+
*/
|
|
17
|
+
export declare function proxy(req: NextRequest, event?: NextFetchEvent): Promise<NextResponse<unknown>>;
|
|
18
|
+
/**
|
|
19
|
+
* Edge entrypoint for the `app/[m]/` tree (AMB-2174): resolves hosts and subfolders and rewrites every page to
|
|
20
|
+
* `/{internalKey}{innerPath}`, so each market renders and caches under its own `[m]` key.
|
|
21
|
+
*/
|
|
22
|
+
export declare function marketProxy(req: NextRequest, event?: NextFetchEvent): Promise<NextResponse<unknown>>;
|
|
23
|
+
/**
|
|
24
|
+
* The A/B hop (AMB-2174): a control deployment that rewrites a page to a variant deployment sends the internal path
|
|
25
|
+
* it resolved (`/_/products/x`), signed with the router secret (the `amb_theme` cookie's HMAC). The variant's
|
|
26
|
+
* `marketProxy` serves that path as it is instead of resolving it again (which would give `/_/_/products/x`). A
|
|
27
|
+
* client copy is deleted. A variant on the old route tree never gets one: the Orchestrator refuses an A/B group that
|
|
28
|
+
* mixes the `app/[m]/` tree with the old one. A token lives 60 s and names the one path it was signed for.
|
|
29
|
+
*
|
|
30
|
+
* A variant that cannot verify it (no secret yet: a first launch builds variants before the env is written; an old
|
|
31
|
+
* one after a rotation) still never resolves an internal path again: on a host that is not one of the store's, a
|
|
32
|
+
* first segment that is an internal key (`_`, `_<marketId>`, never in a public URL) is served as it is, without a
|
|
33
|
+
* market header, and counted as `hop_unverified`.
|
|
34
|
+
*/
|
|
35
|
+
export declare const MARKET_HOP_HEADER = "x-amb-market-hop";
|
|
11
36
|
//# sourceMappingURL=proxy.d.ts.map
|
package/dist/edge/proxy.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../src/edge/proxy.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../src/edge/proxy.ts"],"names":[],"mappings":"AAoCA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAA;AA6H5E;;;;GAIG;AACH,eAAO,MAAM,WAAW;;CAiCvB,CAAA;AAED,qHAAqH;AACrH,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAA;AA8NtD;;;;GAIG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,cAAc,kCAEnE;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,cAAc,kCAEzE;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,qBAAqB,CAAA"}
|
package/dist/edge/proxy.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// The edge proxy of every core store, and its source: edit it here. A core store's proxy.ts re-exports `proxy`
|
|
2
|
+
// (a store tree without `app/[m]/`) or `marketProxy` (the `app/[m]/` tree, AMB-2174) from
|
|
3
|
+
// @amboras-dev/storefront-core/edge. Legacy (pre-core) stores run another file, written by the orchestrator
|
|
4
|
+
// from backend/src/modules/plugins/templates/middleware-template.ts; nothing generates one from the other.
|
|
5
5
|
//
|
|
6
|
-
//
|
|
7
|
-
// AB_ENABLED env-var check on the first line of middleware() short-circuits
|
|
8
|
-
// flag-off stores at zero cost beyond one boolean read per request.
|
|
6
|
+
// route()'s AB_ENABLED check short-circuits flag-off stores at zero cost beyond one boolean read per request.
|
|
9
7
|
//
|
|
10
8
|
// Cookies set here (amb_vid, amb_fp, amb_theme) are strictly-necessary
|
|
11
9
|
// under GDPR/ePrivacy: they exist solely to deliver the variant the buyer
|
|
@@ -34,9 +32,12 @@
|
|
|
34
32
|
// frame-ancestors (CONTRACT v9) is the storefront's only defense against
|
|
35
33
|
// being embedded by a site that isn't ours. See the FRAME_ANCESTORS block
|
|
36
34
|
// below for why it lives at the edge and not in the storefront app.
|
|
37
|
-
import { hostedCheckout, isHostedCheckoutResponse, isPaymentRelayPath } from './hosted-checkout';
|
|
35
|
+
import { hostedCheckout, hostedCheckoutEnv, isHostedCheckoutResponse, isPaymentRelayPath } from './hosted-checkout';
|
|
38
36
|
import { NextResponse } from 'next/server';
|
|
39
|
-
import { siteMetadataBase } from '../lib/site-url.js';
|
|
37
|
+
import { marketMetadataBase, siteMetadataBase } from '../lib/site-url.js';
|
|
38
|
+
import { FILE_PATH, isInternalKey, isOutsideMarketTree, MARKET_HEADER, MARKET_KEY_HEADER, mayBeMarketSegment, presenceOfHost, presenceOfKey, isMarketTreeBuild, ROOT_MARKET_KEY, } from '../lib/market.js';
|
|
39
|
+
import { resolveMarket, rootResolution } from './market.js';
|
|
40
|
+
import { coldForMs, edgeStoreEnv, getUrlMap, MAX_COLD_503_MS, MAX_REDIRECT_AGE_MS, peekUrlMap, sendMarketSignal } from './url-map.js';
|
|
40
41
|
const AB_ENABLED = process.env.AB_ENABLED === 'true';
|
|
41
42
|
const ROUTER_URL = process.env.VARIANT_ROUTER_URL;
|
|
42
43
|
const ROUTER_SECRET = process.env.VARIANT_ROUTER_SECRET;
|
|
@@ -178,6 +179,8 @@ export const proxyConfig = {
|
|
|
178
179
|
'/((?!_next/|api/|favicon\\.ico|robots\\.txt|sitemap\\.xml|sitemaps/sitemap/\\d+\\.xml$).*)',
|
|
179
180
|
],
|
|
180
181
|
};
|
|
182
|
+
/** The URL paths served outside a store's `app/[m]/` tree (AMB-2174): one list for the proxy, links and the gate. */
|
|
183
|
+
export { OUTSIDE_MARKET_TREE } from '../lib/market.js';
|
|
181
184
|
const BOT_UA_RE = /bot|crawl|spider|slurp|googlebot|bingbot|baidu|yandex|duckduckbot|facebookexternalhit|twitterbot|linkedinbot/i;
|
|
182
185
|
// Device classification — MUST mirror the variant-router's targeting.ts so a
|
|
183
186
|
// device switch is detected the same way the router applies device targeting
|
|
@@ -310,18 +313,16 @@ function applyRelayCacheControl(response, pathname) {
|
|
|
310
313
|
}
|
|
311
314
|
return response;
|
|
312
315
|
}
|
|
313
|
-
// The home page
|
|
316
|
+
// The home page canonical, as a `Link` header (AMB-2637). The store owns app/page.tsx and the design run
|
|
314
317
|
// overwrites it wholesale, so a tag set there is lost; the header lives here and survives. Every other page gets
|
|
315
|
-
// its canonical from the
|
|
316
|
-
// host
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
const origin = siteMetadataBase()?.origin;
|
|
321
|
-
if (!origin)
|
|
318
|
+
// its canonical from the layout's metadataBase, and this is the same base (`marketMetadataBase`): the primary
|
|
319
|
+
// host (else the slug URL), or the market URL of an announced market (`https://store.com/en-ca`,
|
|
320
|
+
// `https://store.ca/`). No base, a redirect or an inner path other than `/` → no header.
|
|
321
|
+
function applyHomeCanonical(response, innerPath, base) {
|
|
322
|
+
if (innerPath !== '/' || !base || (response.status >= 300 && response.status < 400))
|
|
322
323
|
return response;
|
|
323
324
|
try {
|
|
324
|
-
response.headers.append('link', `<${
|
|
325
|
+
response.headers.append('link', `<${base.href}>; rel="canonical"`);
|
|
325
326
|
}
|
|
326
327
|
catch {
|
|
327
328
|
// Immutable headers on an exotic Response — never break the page over an SEO hint.
|
|
@@ -357,23 +358,157 @@ function slugHostRedirect(req, env = process.env) {
|
|
|
357
358
|
response.headers.set('cache-control', 'no-store');
|
|
358
359
|
return response;
|
|
359
360
|
}
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
361
|
+
/**
|
|
362
|
+
* Edge entrypoint for a store tree without `app/[m]/`: today's proxy. It never rewrites the path, so a core bump never
|
|
363
|
+
* moves a store's routes, and it reads no URL map, sets no `x-amb-market`, sends no market redirect and adds no market
|
|
364
|
+
* canonical: market URLs exist only on a build that opted in (`marketTreeEnv()`, `isMarketTreeBuild()`).
|
|
365
|
+
*/
|
|
366
|
+
export async function proxy(req, event) {
|
|
367
|
+
return serve(req, event, false);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Edge entrypoint for the `app/[m]/` tree (AMB-2174): resolves hosts and subfolders and rewrites every page to
|
|
371
|
+
* `/{internalKey}{innerPath}`, so each market renders and caches under its own `[m]` key.
|
|
372
|
+
*/
|
|
373
|
+
export async function marketProxy(req, event) {
|
|
374
|
+
return serve(req, event, true);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* The A/B hop (AMB-2174): a control deployment that rewrites a page to a variant deployment sends the internal path
|
|
378
|
+
* it resolved (`/_/products/x`), signed with the router secret (the `amb_theme` cookie's HMAC). The variant's
|
|
379
|
+
* `marketProxy` serves that path as it is instead of resolving it again (which would give `/_/_/products/x`). A
|
|
380
|
+
* client copy is deleted. A variant on the old route tree never gets one: the Orchestrator refuses an A/B group that
|
|
381
|
+
* mixes the `app/[m]/` tree with the old one. A token lives 60 s and names the one path it was signed for.
|
|
382
|
+
*
|
|
383
|
+
* A variant that cannot verify it (no secret yet: a first launch builds variants before the env is written; an old
|
|
384
|
+
* one after a rotation) still never resolves an internal path again: on a host that is not one of the store's, a
|
|
385
|
+
* first segment that is an internal key (`_`, `_<marketId>`, never in a public URL) is served as it is, without a
|
|
386
|
+
* market header, and counted as `hop_unverified`.
|
|
387
|
+
*/
|
|
388
|
+
export const MARKET_HOP_HEADER = 'x-amb-market-hop';
|
|
389
|
+
const HOP_TTL_S = 60;
|
|
390
|
+
/** The hop the control signed for this very path, or null (none, forged, expired, or no router secret here). */
|
|
391
|
+
async function verifiedHop(req) {
|
|
392
|
+
const token = req.headers.get(MARKET_HOP_HEADER);
|
|
393
|
+
if (!token || !ROUTER_SECRET)
|
|
394
|
+
return null;
|
|
395
|
+
const hop = await verifySigned(token, ROUTER_SECRET);
|
|
396
|
+
if (!hop || typeof hop !== 'object')
|
|
397
|
+
return null;
|
|
398
|
+
const { p, m, exp } = hop;
|
|
399
|
+
const live = typeof exp === 'number' && exp * 1000 > Date.now();
|
|
400
|
+
return live && p === req.nextUrl.pathname && (m === null || typeof m === 'string') ? { p, m, exp } : null;
|
|
401
|
+
}
|
|
402
|
+
/** Request headers only the proxy may set: a client copy of each is always deleted. */
|
|
403
|
+
const PROXY_REQUEST_HEADERS = [MARKET_HEADER, MARKET_HOP_HEADER, MARKET_KEY_HEADER];
|
|
404
|
+
/**
|
|
405
|
+
* The request headers with the client's copies of ours deleted and the resolved market set (none on the root), with
|
|
406
|
+
* the market's `[m]` key on a file path (`fileKey`, MARKET_KEY_HEADER).
|
|
407
|
+
*/
|
|
408
|
+
function marketRequestHeaders(req, marketId, fileKey) {
|
|
409
|
+
if (marketId === null && !PROXY_REQUEST_HEADERS.some((name) => req.headers.has(name)))
|
|
410
|
+
return undefined;
|
|
411
|
+
const headers = new Headers(req.headers);
|
|
412
|
+
for (const name of PROXY_REQUEST_HEADERS)
|
|
413
|
+
headers.delete(name);
|
|
414
|
+
if (marketId !== null)
|
|
415
|
+
headers.set(MARKET_HEADER, marketId);
|
|
416
|
+
if (marketId !== null && fileKey !== null)
|
|
417
|
+
headers.set(MARKET_KEY_HEADER, fileKey);
|
|
418
|
+
return headers;
|
|
419
|
+
}
|
|
420
|
+
/** A path only a file answers, as `marketFallbackRewrites` matches it (Next matches a rewrite case-insensitively). */
|
|
421
|
+
const FILE_PATH_RE = new RegExp(`^/${FILE_PATH}$`, 'i');
|
|
422
|
+
/** The middleware init that hands the page `ctx.headers`; none keeps the request's own headers. */
|
|
423
|
+
const requestInit = (ctx) => (ctx.headers ? { request: { headers: ctx.headers } } : undefined);
|
|
424
|
+
/** Every pass-through of `route()`: today's `NextResponse.next()`, or the rewrite to the market's internal path. */
|
|
425
|
+
function passThrough(req, ctx) {
|
|
426
|
+
const init = requestInit(ctx);
|
|
427
|
+
return ctx.rewrite ? NextResponse.rewrite(new URL(ctx.internalPath + req.nextUrl.search, req.url), init) : NextResponse.next(init);
|
|
428
|
+
}
|
|
429
|
+
const isRead = (req) => req.method === 'GET' || req.method === 'HEAD';
|
|
430
|
+
/** Every market redirect: never cached, so reverting a suffix or going live never meets a browser's old 30x. */
|
|
431
|
+
function marketRedirect(location, status) {
|
|
432
|
+
const response = NextResponse.redirect(location, status);
|
|
433
|
+
response.headers.set('cache-control', 'no-store');
|
|
434
|
+
return response;
|
|
435
|
+
}
|
|
436
|
+
async function serve(req, event, subfolders) {
|
|
437
|
+
const { pathname } = req.nextUrl;
|
|
369
438
|
// Before everything else: a redirected request sets no cookie and gets no canonical.
|
|
370
439
|
const toPrimary = slugHostRedirect(req);
|
|
371
440
|
if (toPrimary)
|
|
372
441
|
return applyFrameAncestors(toPrimary, pathname);
|
|
373
|
-
const
|
|
374
|
-
|
|
442
|
+
const host = req.nextUrl.hostname;
|
|
443
|
+
const primaryHost = siteMetadataBase()?.hostname ?? null;
|
|
444
|
+
const waitUntil = event ? (promise) => event.waitUntil(promise) : undefined;
|
|
445
|
+
const outside = isOutsideMarketTree(pathname);
|
|
446
|
+
// Market URLs exist only on a build that opted in: anything else never reads the map (today's proxy).
|
|
447
|
+
const marketTree = isMarketTreeBuild();
|
|
448
|
+
// A file path no file answers reaches the catch-all under the root key (marketFallbackRewrites), which takes its
|
|
449
|
+
// market from MARKET_KEY_HEADER. From a copy in memory younger than MAX_REDIRECT_AGE_MS only: a file never waits for
|
|
450
|
+
// the map (a due refresh runs in the background), never 503s, never redirects and sends no beacon.
|
|
451
|
+
const filePath = marketTree && subfolders && FILE_PATH_RE.test(pathname);
|
|
452
|
+
const hop = subfolders && !outside ? await verifiedHop(req) : null;
|
|
453
|
+
// A page reads the map (awaited only on a cold instance); a file only peeks at the copy in memory, which starts a
|
|
454
|
+
// due refresh in the background. No read for a hop, (without subfolders) the primary host, or the old tree.
|
|
455
|
+
const needsMap = marketTree && !outside && !hop && (subfolders || host !== primaryHost);
|
|
456
|
+
const fileMap = filePath ? peekUrlMap(process.env, waitUntil) : null;
|
|
457
|
+
const map = needsMap ? await getUrlMap(process.env, waitUntil) : fileMap && fileMap.age < MAX_REDIRECT_AGE_MS ? fileMap : undefined;
|
|
458
|
+
const firstSegment = pathname.split('/', 2)[1] ?? '';
|
|
459
|
+
// A hop this deployment could not verify (MARKET_HOP_HEADER): served as it is. Internal keys only (`_`, a market
|
|
460
|
+
// host's `_<marketId>`; with a map, one it holds, so a made-up `/_zz1/x` never mints a page and an ISR copy of its
|
|
461
|
+
// own). A subfolder key (`en-ca`) always goes through resolveMarket, with its draft redirect and every other check.
|
|
462
|
+
const knownKey = firstSegment === ROOT_MARKET_KEY || (isInternalKey(firstSegment) && (!map || presenceOfKey(firstSegment, map.value) !== null));
|
|
463
|
+
const storeHost = host === primaryHost || presenceOfHost(map?.value ?? null, host) !== null;
|
|
464
|
+
const unverifiedHop = subfolders && !outside && !hop && knownKey && !storeHost;
|
|
465
|
+
// Counted whenever a hop came and did not verify (no secret here, an old one, expired, forged), whatever the path,
|
|
466
|
+
// so a secret drift between control and variant stays visible.
|
|
467
|
+
const hopFailed = subfolders && !outside && !hop && req.headers.has(MARKET_HOP_HEADER);
|
|
468
|
+
if (unverifiedHop || hopFailed)
|
|
469
|
+
sendMarketSignal('hop_unverified', waitUntil);
|
|
470
|
+
// A host that is not the store's (an A/B variant deployment, a preview) matches subfolders as the primary does, with
|
|
471
|
+
// every check (draft 302, previous-suffix 301): a subfolder page still renders there while a variant cannot verify
|
|
472
|
+
// a hop. Host presences match only their own hosts, which this one is not.
|
|
473
|
+
const resolveAs = storeHost || !primaryHost ? host : primaryHost;
|
|
474
|
+
const resolved = map === undefined || unverifiedHop ? rootResolution(req.nextUrl) : resolveMarket(req.nextUrl, resolveAs, map, primaryHost, { subfolders });
|
|
475
|
+
const resolution = filePath ? { ...resolved, redirect: undefined, fallback: undefined } : resolved;
|
|
476
|
+
if (resolution.fallback === 'map_stale' || resolution.fallback === 'map_unavailable')
|
|
477
|
+
sendMarketSignal(resolution.fallback, waitUntil);
|
|
478
|
+
// A cold instance that could not read the map does not know whether `/en-ca` is a market: a short 503 the crawler
|
|
479
|
+
// retries (it drops a 404), while the map is retried every 5 s. Only for a first segment that starts like a market
|
|
480
|
+
// URL (`mayBeMarketSegment`, a hint) and is not a template page; every other path is the root's.
|
|
481
|
+
// After MAX_COLD_503_MS with no map (a revoked key, a WAF block) it is the root's again; the map is still retried.
|
|
482
|
+
const coldTooLong = coldForMs() >= MAX_COLD_503_MS;
|
|
483
|
+
if (subfolders && map === null && host === primaryHost && mayBeMarketSegment(firstSegment) && !coldTooLong && edgeStoreEnv().medusaUrl) {
|
|
484
|
+
return applyFrameAncestors(new NextResponse(null, { status: 503, headers: { 'retry-after': '5', 'cache-control': 'no-store' } }), pathname);
|
|
485
|
+
}
|
|
486
|
+
const { redirect } = resolution;
|
|
487
|
+
// A long-stale copy routes but does not move people, except to the root checkout, which is never wrong.
|
|
488
|
+
const trusted = map && (map.age < MAX_REDIRECT_AGE_MS || redirect?.kind === 'root_checkout');
|
|
489
|
+
// Only on the store's own hosts: a draft or preview deployment keeps its password gate first and never sends a
|
|
490
|
+
// visitor to the live store's checkout.
|
|
491
|
+
if (redirect && isRead(req) && trusted && storeHost) {
|
|
492
|
+
if (redirect.kind === 'inactive')
|
|
493
|
+
sendMarketSignal('inactive_redirect', waitUntil);
|
|
494
|
+
return applyFrameAncestors(marketRedirect(redirect.location, redirect.status), pathname);
|
|
495
|
+
}
|
|
496
|
+
const servedAsIs = !!hop || unverifiedHop;
|
|
497
|
+
const rewrite = subfolders && !outside && !servedAsIs;
|
|
498
|
+
const { internalKey, innerPath } = resolution;
|
|
499
|
+
const marketId = hop ? hop.m : resolution.marketId;
|
|
500
|
+
const ctx = {
|
|
501
|
+
internalPath: rewrite ? `/${internalKey}${innerPath === '/' ? '' : innerPath}` : pathname,
|
|
502
|
+
rewrite,
|
|
503
|
+
marketId,
|
|
504
|
+
headers: marketRequestHeaders(req, marketId, filePath ? internalKey : null),
|
|
505
|
+
};
|
|
506
|
+
const response = applyVisitorCountry(req, await route(req, ctx), pathname);
|
|
507
|
+
// The control set the home canonical of a hop already.
|
|
508
|
+
const homeBase = !servedAsIs && innerPath === '/' ? marketMetadataBase(internalKey, map?.value ?? null) : undefined;
|
|
509
|
+
return applyRelayCacheControl(applyFrameAncestors(applyHomeCanonical(response, innerPath, homeBase), pathname), pathname);
|
|
375
510
|
}
|
|
376
|
-
async function route(req) {
|
|
511
|
+
async function route(req, ctx) {
|
|
377
512
|
// ── Draft password gate. Runs BEFORE A/B. Inert unless this deployment was
|
|
378
513
|
// baked with DRAFT_PASSWORD_* (draft builds only) — so live + A/B variant
|
|
379
514
|
// deployments skip it entirely and behave exactly as before. When active and
|
|
@@ -392,7 +527,7 @@ async function route(req) {
|
|
|
392
527
|
}
|
|
393
528
|
// ── Hosted checkout: /checkout goes to the platform's checkout app before any A/B routing, so a
|
|
394
529
|
// variant can never send it to a variant deployment. Inert without AMBORAS_CHECKOUT_*. ─────────
|
|
395
|
-
const checkout = await hostedCheckout(req);
|
|
530
|
+
const checkout = await hostedCheckout(req, hostedCheckoutEnv(), Date.now(), ctx.headers);
|
|
396
531
|
if (checkout)
|
|
397
532
|
return checkout;
|
|
398
533
|
// ── H1: short-circuit on flag-off stores. MUST be the first A/B line. ──────
|
|
@@ -401,7 +536,7 @@ async function route(req) {
|
|
|
401
536
|
// the publish-time multi-theme env-var self-heal can be debugged from a
|
|
402
537
|
// simple `curl -I`. No PII, no secrets — just yes/no flags for the
|
|
403
538
|
// canonical env vars. Cheap (one boolean per env on flag-off stores).
|
|
404
|
-
const response =
|
|
539
|
+
const response = passThrough(req, ctx);
|
|
405
540
|
response.headers.set('x-amb-short-circuit', [
|
|
406
541
|
AB_ENABLED ? 'AB_ENABLED' : '!AB_ENABLED',
|
|
407
542
|
ROUTER_URL ? 'ROUTER_URL' : '!ROUTER_URL',
|
|
@@ -432,7 +567,7 @@ async function route(req) {
|
|
|
432
567
|
stripped.searchParams.delete('_v');
|
|
433
568
|
return NextResponse.redirect(stripped);
|
|
434
569
|
}
|
|
435
|
-
return
|
|
570
|
+
return passThrough(req, ctx);
|
|
436
571
|
}
|
|
437
572
|
// ── Asset proxy branch ─────────────────────────────────────────────────────
|
|
438
573
|
// Requests for /_next/static/chunks/* and /_next/static/css/* must be
|
|
@@ -447,22 +582,22 @@ async function route(req) {
|
|
|
447
582
|
if (isAssetRequest) {
|
|
448
583
|
const cookieRaw = req.cookies.get('amb_theme')?.value;
|
|
449
584
|
if (!cookieRaw)
|
|
450
|
-
return
|
|
585
|
+
return passThrough(req, ctx);
|
|
451
586
|
const verified = await verifyCookie(cookieRaw, ROUTER_SECRET);
|
|
452
587
|
if (!verified)
|
|
453
|
-
return
|
|
588
|
+
return passThrough(req, ctx);
|
|
454
589
|
// The signed cookie carries the variant deploy URL (empty ⇒ control).
|
|
455
590
|
// Trusted because the payload is HMAC-verified above. No router/Edge Config
|
|
456
591
|
// call on the asset hot path.
|
|
457
592
|
const variantUrl = verified.deploymentUrl;
|
|
458
593
|
if (!variantUrl)
|
|
459
|
-
return
|
|
594
|
+
return passThrough(req, ctx);
|
|
460
595
|
try {
|
|
461
596
|
const rewriteUrl = new URL(req.nextUrl.pathname + req.nextUrl.search, variantUrl);
|
|
462
597
|
return NextResponse.rewrite(rewriteUrl);
|
|
463
598
|
}
|
|
464
599
|
catch {
|
|
465
|
-
return
|
|
600
|
+
return passThrough(req, ctx);
|
|
466
601
|
}
|
|
467
602
|
}
|
|
468
603
|
// ── ?_v=<slug> preview override (review item C3) ───────────────────────────
|
|
@@ -479,7 +614,7 @@ async function route(req) {
|
|
|
479
614
|
if (isAdmin || PREVIEW_OVERRIDE_ENABLED) {
|
|
480
615
|
const resolved = await callRouter(req, ua, { previewSlug });
|
|
481
616
|
if (resolved) {
|
|
482
|
-
return finalize(req, resolved);
|
|
617
|
+
return finalize(req, ctx, resolved);
|
|
483
618
|
}
|
|
484
619
|
// Router error on explicit preview → fall through to normal flow
|
|
485
620
|
// rather than 5xx the admin.
|
|
@@ -502,7 +637,7 @@ async function route(req) {
|
|
|
502
637
|
const age = typeof verified.resolvedAt === 'number' ? Date.now() - verified.resolvedAt : Infinity;
|
|
503
638
|
const sameDevice = verified.device === classifyDevice(ua);
|
|
504
639
|
if (age >= 0 && age < RESOLVE_TTL_MS && sameDevice) {
|
|
505
|
-
return finalize(req, {
|
|
640
|
+
return finalize(req, ctx, {
|
|
506
641
|
themeId: verified.themeId,
|
|
507
642
|
groupVersion: verified.groupVersion,
|
|
508
643
|
abGroupId: verified.abGroupId ?? null,
|
|
@@ -517,8 +652,8 @@ async function route(req) {
|
|
|
517
652
|
ambFp: req.cookies.get('amb_fp')?.value,
|
|
518
653
|
});
|
|
519
654
|
if (!resolved)
|
|
520
|
-
return applyGeoConsent(req,
|
|
521
|
-
return finalize(req, resolved);
|
|
655
|
+
return applyGeoConsent(req, passThrough(req, ctx)); // router down → control
|
|
656
|
+
return finalize(req, ctx, resolved);
|
|
522
657
|
}
|
|
523
658
|
// Cookie present but signature/structure invalid → treat as miss.
|
|
524
659
|
}
|
|
@@ -527,8 +662,8 @@ async function route(req) {
|
|
|
527
662
|
ambFp: req.cookies.get('amb_fp')?.value,
|
|
528
663
|
});
|
|
529
664
|
if (!resolved)
|
|
530
|
-
return applyGeoConsent(req,
|
|
531
|
-
return finalize(req, resolved);
|
|
665
|
+
return applyGeoConsent(req, passThrough(req, ctx)); // router unreachable → serve control
|
|
666
|
+
return finalize(req, ctx, resolved);
|
|
532
667
|
}
|
|
533
668
|
async function callRouter(req, ua, extras) {
|
|
534
669
|
try {
|
|
@@ -560,10 +695,10 @@ async function callRouter(req, ua, extras) {
|
|
|
560
695
|
return null;
|
|
561
696
|
}
|
|
562
697
|
}
|
|
563
|
-
async function finalize(req, resolved, opts = {}) {
|
|
698
|
+
async function finalize(req, ctx, resolved, opts = {}) {
|
|
564
699
|
let response;
|
|
565
700
|
if (resolved.isControl) {
|
|
566
|
-
response =
|
|
701
|
+
response = passThrough(req, ctx);
|
|
567
702
|
}
|
|
568
703
|
else {
|
|
569
704
|
// Variant deploy URL comes straight from the router's resolve response.
|
|
@@ -576,17 +711,27 @@ async function finalize(req, resolved, opts = {}) {
|
|
|
576
711
|
// No URL yet (snapshot mid-build / propagation lag) — fall back to
|
|
577
712
|
// control. Buyer sees the same control HTML uncookied visitors see; no
|
|
578
713
|
// broken state.
|
|
579
|
-
response =
|
|
714
|
+
response = passThrough(req, ctx);
|
|
580
715
|
}
|
|
581
716
|
else {
|
|
582
717
|
let rewriteUrl;
|
|
583
718
|
try {
|
|
584
|
-
|
|
719
|
+
// The internal path (`/_/products/x` on the `app/[m]/` tree), so the variant renders the same market page.
|
|
720
|
+
rewriteUrl = new URL(ctx.internalPath + req.nextUrl.search, variantUrl);
|
|
585
721
|
}
|
|
586
722
|
catch {
|
|
587
|
-
return applyGeoConsent(req,
|
|
723
|
+
return applyGeoConsent(req, passThrough(req, ctx));
|
|
724
|
+
}
|
|
725
|
+
if (ctx.rewrite && ROUTER_SECRET) {
|
|
726
|
+
// The variant must serve that path as it is (MARKET_HOP_HEADER).
|
|
727
|
+
const headers = new Headers(ctx.headers ?? req.headers);
|
|
728
|
+
const hop = { p: ctx.internalPath, m: ctx.marketId, exp: Math.floor(Date.now() / 1000) + HOP_TTL_S };
|
|
729
|
+
headers.set(MARKET_HOP_HEADER, await signCookie(hop, ROUTER_SECRET));
|
|
730
|
+
response = NextResponse.rewrite(rewriteUrl, { request: { headers } });
|
|
731
|
+
}
|
|
732
|
+
else {
|
|
733
|
+
response = NextResponse.rewrite(rewriteUrl, requestInit(ctx));
|
|
588
734
|
}
|
|
589
|
-
response = NextResponse.rewrite(rewriteUrl);
|
|
590
735
|
}
|
|
591
736
|
}
|
|
592
737
|
if (!opts.skipThemeCookieWrite && ROUTER_SECRET) {
|
|
@@ -630,23 +775,26 @@ async function signCookie(payload, secret) {
|
|
|
630
775
|
const sig = await hmacSign(data, secret);
|
|
631
776
|
return `${data}.${sig}`;
|
|
632
777
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
778
|
+
/** The JSON payload of a `signCookie` token whose signature holds, else null. */
|
|
779
|
+
async function verifySigned(token, secret) {
|
|
780
|
+
const dot = token.indexOf('.');
|
|
781
|
+
if (dot <= 0 || dot === token.length - 1)
|
|
636
782
|
return null;
|
|
637
|
-
const data =
|
|
638
|
-
const sig =
|
|
783
|
+
const data = token.slice(0, dot);
|
|
784
|
+
const sig = token.slice(dot + 1);
|
|
639
785
|
const expected = await hmacSign(data, secret);
|
|
640
786
|
// Constant-time compare (review item C1 hardening).
|
|
641
787
|
if (!timingSafeEqual(sig, expected))
|
|
642
788
|
return null;
|
|
643
|
-
let parsed;
|
|
644
789
|
try {
|
|
645
|
-
|
|
790
|
+
return JSON.parse(new TextDecoder().decode(b64urlDecode(data)));
|
|
646
791
|
}
|
|
647
792
|
catch {
|
|
648
793
|
return null;
|
|
649
794
|
}
|
|
795
|
+
}
|
|
796
|
+
async function verifyCookie(cookie, secret) {
|
|
797
|
+
const parsed = await verifySigned(cookie, secret);
|
|
650
798
|
if (!parsed ||
|
|
651
799
|
typeof parsed !== 'object' ||
|
|
652
800
|
typeof parsed.themeId !== 'string' ||
|