@amboras-dev/storefront-core 2026.11.11 → 2026.11.12-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 +130 -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 +11 -7
- 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 +206 -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 +14 -6
- 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 +185 -33
- package/dist/lib/seo.js.map +1 -1
- package/dist/lib/site-url.d.ts +24 -0
- package/dist/lib/site-url.d.ts.map +1 -1
- package/dist/lib/site-url.js +35 -0
- package/dist/lib/site-url.js.map +1 -1
- package/dist/lib/visitor-free-routes.d.ts +18 -0
- package/dist/lib/visitor-free-routes.d.ts.map +1 -0
- package/dist/lib/visitor-free-routes.js +33 -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, requestHostOf, 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,159 @@ 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
|
-
|
|
374
|
-
|
|
442
|
+
// The Host header, as the server's sitemaps and robots read it (`requestHostOf`, never `x-forwarded-host`); under
|
|
443
|
+
// `next start` the URL's hostname is the listen host, so a market host would never match. The URL's only without one.
|
|
444
|
+
const host = requestHostOf(req.headers) ?? req.nextUrl.hostname;
|
|
445
|
+
const primaryHost = siteMetadataBase()?.hostname ?? null;
|
|
446
|
+
const waitUntil = event ? (promise) => event.waitUntil(promise) : undefined;
|
|
447
|
+
const outside = isOutsideMarketTree(pathname);
|
|
448
|
+
// Market URLs exist only on a build that opted in: anything else never reads the map (today's proxy).
|
|
449
|
+
const marketTree = isMarketTreeBuild();
|
|
450
|
+
// A file path no file answers reaches the catch-all under the root key (marketFallbackRewrites), which takes its
|
|
451
|
+
// market from MARKET_KEY_HEADER. From a copy in memory younger than MAX_REDIRECT_AGE_MS only: a file never waits for
|
|
452
|
+
// the map (a due refresh runs in the background), never 503s, never redirects and sends no beacon.
|
|
453
|
+
const filePath = marketTree && subfolders && FILE_PATH_RE.test(pathname);
|
|
454
|
+
const hop = subfolders && !outside ? await verifiedHop(req) : null;
|
|
455
|
+
// A page reads the map (awaited only on a cold instance); a file only peeks at the copy in memory, which starts a
|
|
456
|
+
// due refresh in the background. No read for a hop, (without subfolders) the primary host, or the old tree.
|
|
457
|
+
const needsMap = marketTree && !outside && !hop && (subfolders || host !== primaryHost);
|
|
458
|
+
const fileMap = filePath ? peekUrlMap(process.env, waitUntil) : null;
|
|
459
|
+
const map = needsMap ? await getUrlMap(process.env, waitUntil) : fileMap && fileMap.age < MAX_REDIRECT_AGE_MS ? fileMap : undefined;
|
|
460
|
+
const firstSegment = pathname.split('/', 2)[1] ?? '';
|
|
461
|
+
// A hop this deployment could not verify (MARKET_HOP_HEADER): served as it is. Internal keys only (`_`, a market
|
|
462
|
+
// 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
|
|
463
|
+
// own). A subfolder key (`en-ca`) always goes through resolveMarket, with its draft redirect and every other check.
|
|
464
|
+
const knownKey = firstSegment === ROOT_MARKET_KEY || (isInternalKey(firstSegment) && (!map || presenceOfKey(firstSegment, map.value) !== null));
|
|
465
|
+
const storeHost = host === primaryHost || presenceOfHost(map?.value ?? null, host) !== null;
|
|
466
|
+
const unverifiedHop = subfolders && !outside && !hop && knownKey && !storeHost;
|
|
467
|
+
// Counted whenever a hop came and did not verify (no secret here, an old one, expired, forged), whatever the path,
|
|
468
|
+
// so a secret drift between control and variant stays visible.
|
|
469
|
+
const hopFailed = subfolders && !outside && !hop && req.headers.has(MARKET_HOP_HEADER);
|
|
470
|
+
if (unverifiedHop || hopFailed)
|
|
471
|
+
sendMarketSignal('hop_unverified', waitUntil);
|
|
472
|
+
// A host that is not the store's (an A/B variant deployment, a preview) matches subfolders as the primary does, with
|
|
473
|
+
// every check (draft 302, previous-suffix 301): a subfolder page still renders there while a variant cannot verify
|
|
474
|
+
// a hop. Host presences match only their own hosts, which this one is not.
|
|
475
|
+
const resolveAs = storeHost || !primaryHost ? host : primaryHost;
|
|
476
|
+
const resolved = map === undefined || unverifiedHop ? rootResolution(req.nextUrl) : resolveMarket(req.nextUrl, resolveAs, map, primaryHost, { subfolders });
|
|
477
|
+
const resolution = filePath ? { ...resolved, redirect: undefined, fallback: undefined } : resolved;
|
|
478
|
+
if (resolution.fallback === 'map_stale' || resolution.fallback === 'map_unavailable')
|
|
479
|
+
sendMarketSignal(resolution.fallback, waitUntil);
|
|
480
|
+
// A cold instance that could not read the map does not know whether `/en-ca` is a market: a short 503 the crawler
|
|
481
|
+
// retries (it drops a 404), while the map is retried every 5 s. Only for a first segment that starts like a market
|
|
482
|
+
// URL (`mayBeMarketSegment`, a hint) and is not a template page; every other path is the root's.
|
|
483
|
+
// 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.
|
|
484
|
+
const coldTooLong = coldForMs() >= MAX_COLD_503_MS;
|
|
485
|
+
if (subfolders && map === null && host === primaryHost && mayBeMarketSegment(firstSegment) && !coldTooLong && edgeStoreEnv().medusaUrl) {
|
|
486
|
+
return applyFrameAncestors(new NextResponse(null, { status: 503, headers: { 'retry-after': '5', 'cache-control': 'no-store' } }), pathname);
|
|
487
|
+
}
|
|
488
|
+
const { redirect } = resolution;
|
|
489
|
+
// A long-stale copy routes but does not move people, except to the root checkout, which is never wrong.
|
|
490
|
+
const trusted = map && (map.age < MAX_REDIRECT_AGE_MS || redirect?.kind === 'root_checkout');
|
|
491
|
+
// Only on the store's own hosts: a draft or preview deployment keeps its password gate first and never sends a
|
|
492
|
+
// visitor to the live store's checkout.
|
|
493
|
+
if (redirect && isRead(req) && trusted && storeHost) {
|
|
494
|
+
if (redirect.kind === 'inactive')
|
|
495
|
+
sendMarketSignal('inactive_redirect', waitUntil);
|
|
496
|
+
return applyFrameAncestors(marketRedirect(redirect.location, redirect.status), pathname);
|
|
497
|
+
}
|
|
498
|
+
const servedAsIs = !!hop || unverifiedHop;
|
|
499
|
+
const rewrite = subfolders && !outside && !servedAsIs;
|
|
500
|
+
const { internalKey, innerPath } = resolution;
|
|
501
|
+
const marketId = hop ? hop.m : resolution.marketId;
|
|
502
|
+
const ctx = {
|
|
503
|
+
internalPath: rewrite ? `/${internalKey}${innerPath === '/' ? '' : innerPath}` : pathname,
|
|
504
|
+
rewrite,
|
|
505
|
+
marketId,
|
|
506
|
+
headers: marketRequestHeaders(req, marketId, filePath ? internalKey : null),
|
|
507
|
+
};
|
|
508
|
+
const response = applyVisitorCountry(req, await route(req, ctx), pathname);
|
|
509
|
+
// The control set the home canonical of a hop already.
|
|
510
|
+
const homeBase = !servedAsIs && innerPath === '/' ? marketMetadataBase(internalKey, map?.value ?? null) : undefined;
|
|
511
|
+
return applyRelayCacheControl(applyFrameAncestors(applyHomeCanonical(response, innerPath, homeBase), pathname), pathname);
|
|
375
512
|
}
|
|
376
|
-
async function route(req) {
|
|
513
|
+
async function route(req, ctx) {
|
|
377
514
|
// ── Draft password gate. Runs BEFORE A/B. Inert unless this deployment was
|
|
378
515
|
// baked with DRAFT_PASSWORD_* (draft builds only) — so live + A/B variant
|
|
379
516
|
// deployments skip it entirely and behave exactly as before. When active and
|
|
@@ -392,7 +529,7 @@ async function route(req) {
|
|
|
392
529
|
}
|
|
393
530
|
// ── Hosted checkout: /checkout goes to the platform's checkout app before any A/B routing, so a
|
|
394
531
|
// variant can never send it to a variant deployment. Inert without AMBORAS_CHECKOUT_*. ─────────
|
|
395
|
-
const checkout = await hostedCheckout(req);
|
|
532
|
+
const checkout = await hostedCheckout(req, hostedCheckoutEnv(), Date.now(), ctx.headers);
|
|
396
533
|
if (checkout)
|
|
397
534
|
return checkout;
|
|
398
535
|
// ── H1: short-circuit on flag-off stores. MUST be the first A/B line. ──────
|
|
@@ -401,7 +538,7 @@ async function route(req) {
|
|
|
401
538
|
// the publish-time multi-theme env-var self-heal can be debugged from a
|
|
402
539
|
// simple `curl -I`. No PII, no secrets — just yes/no flags for the
|
|
403
540
|
// canonical env vars. Cheap (one boolean per env on flag-off stores).
|
|
404
|
-
const response =
|
|
541
|
+
const response = passThrough(req, ctx);
|
|
405
542
|
response.headers.set('x-amb-short-circuit', [
|
|
406
543
|
AB_ENABLED ? 'AB_ENABLED' : '!AB_ENABLED',
|
|
407
544
|
ROUTER_URL ? 'ROUTER_URL' : '!ROUTER_URL',
|
|
@@ -432,7 +569,7 @@ async function route(req) {
|
|
|
432
569
|
stripped.searchParams.delete('_v');
|
|
433
570
|
return NextResponse.redirect(stripped);
|
|
434
571
|
}
|
|
435
|
-
return
|
|
572
|
+
return passThrough(req, ctx);
|
|
436
573
|
}
|
|
437
574
|
// ── Asset proxy branch ─────────────────────────────────────────────────────
|
|
438
575
|
// Requests for /_next/static/chunks/* and /_next/static/css/* must be
|
|
@@ -447,22 +584,22 @@ async function route(req) {
|
|
|
447
584
|
if (isAssetRequest) {
|
|
448
585
|
const cookieRaw = req.cookies.get('amb_theme')?.value;
|
|
449
586
|
if (!cookieRaw)
|
|
450
|
-
return
|
|
587
|
+
return passThrough(req, ctx);
|
|
451
588
|
const verified = await verifyCookie(cookieRaw, ROUTER_SECRET);
|
|
452
589
|
if (!verified)
|
|
453
|
-
return
|
|
590
|
+
return passThrough(req, ctx);
|
|
454
591
|
// The signed cookie carries the variant deploy URL (empty ⇒ control).
|
|
455
592
|
// Trusted because the payload is HMAC-verified above. No router/Edge Config
|
|
456
593
|
// call on the asset hot path.
|
|
457
594
|
const variantUrl = verified.deploymentUrl;
|
|
458
595
|
if (!variantUrl)
|
|
459
|
-
return
|
|
596
|
+
return passThrough(req, ctx);
|
|
460
597
|
try {
|
|
461
598
|
const rewriteUrl = new URL(req.nextUrl.pathname + req.nextUrl.search, variantUrl);
|
|
462
599
|
return NextResponse.rewrite(rewriteUrl);
|
|
463
600
|
}
|
|
464
601
|
catch {
|
|
465
|
-
return
|
|
602
|
+
return passThrough(req, ctx);
|
|
466
603
|
}
|
|
467
604
|
}
|
|
468
605
|
// ── ?_v=<slug> preview override (review item C3) ───────────────────────────
|
|
@@ -479,7 +616,7 @@ async function route(req) {
|
|
|
479
616
|
if (isAdmin || PREVIEW_OVERRIDE_ENABLED) {
|
|
480
617
|
const resolved = await callRouter(req, ua, { previewSlug });
|
|
481
618
|
if (resolved) {
|
|
482
|
-
return finalize(req, resolved);
|
|
619
|
+
return finalize(req, ctx, resolved);
|
|
483
620
|
}
|
|
484
621
|
// Router error on explicit preview → fall through to normal flow
|
|
485
622
|
// rather than 5xx the admin.
|
|
@@ -502,7 +639,7 @@ async function route(req) {
|
|
|
502
639
|
const age = typeof verified.resolvedAt === 'number' ? Date.now() - verified.resolvedAt : Infinity;
|
|
503
640
|
const sameDevice = verified.device === classifyDevice(ua);
|
|
504
641
|
if (age >= 0 && age < RESOLVE_TTL_MS && sameDevice) {
|
|
505
|
-
return finalize(req, {
|
|
642
|
+
return finalize(req, ctx, {
|
|
506
643
|
themeId: verified.themeId,
|
|
507
644
|
groupVersion: verified.groupVersion,
|
|
508
645
|
abGroupId: verified.abGroupId ?? null,
|
|
@@ -517,8 +654,8 @@ async function route(req) {
|
|
|
517
654
|
ambFp: req.cookies.get('amb_fp')?.value,
|
|
518
655
|
});
|
|
519
656
|
if (!resolved)
|
|
520
|
-
return applyGeoConsent(req,
|
|
521
|
-
return finalize(req, resolved);
|
|
657
|
+
return applyGeoConsent(req, passThrough(req, ctx)); // router down → control
|
|
658
|
+
return finalize(req, ctx, resolved);
|
|
522
659
|
}
|
|
523
660
|
// Cookie present but signature/structure invalid → treat as miss.
|
|
524
661
|
}
|
|
@@ -527,8 +664,8 @@ async function route(req) {
|
|
|
527
664
|
ambFp: req.cookies.get('amb_fp')?.value,
|
|
528
665
|
});
|
|
529
666
|
if (!resolved)
|
|
530
|
-
return applyGeoConsent(req,
|
|
531
|
-
return finalize(req, resolved);
|
|
667
|
+
return applyGeoConsent(req, passThrough(req, ctx)); // router unreachable → serve control
|
|
668
|
+
return finalize(req, ctx, resolved);
|
|
532
669
|
}
|
|
533
670
|
async function callRouter(req, ua, extras) {
|
|
534
671
|
try {
|
|
@@ -560,10 +697,10 @@ async function callRouter(req, ua, extras) {
|
|
|
560
697
|
return null;
|
|
561
698
|
}
|
|
562
699
|
}
|
|
563
|
-
async function finalize(req, resolved, opts = {}) {
|
|
700
|
+
async function finalize(req, ctx, resolved, opts = {}) {
|
|
564
701
|
let response;
|
|
565
702
|
if (resolved.isControl) {
|
|
566
|
-
response =
|
|
703
|
+
response = passThrough(req, ctx);
|
|
567
704
|
}
|
|
568
705
|
else {
|
|
569
706
|
// Variant deploy URL comes straight from the router's resolve response.
|
|
@@ -576,17 +713,27 @@ async function finalize(req, resolved, opts = {}) {
|
|
|
576
713
|
// No URL yet (snapshot mid-build / propagation lag) — fall back to
|
|
577
714
|
// control. Buyer sees the same control HTML uncookied visitors see; no
|
|
578
715
|
// broken state.
|
|
579
|
-
response =
|
|
716
|
+
response = passThrough(req, ctx);
|
|
580
717
|
}
|
|
581
718
|
else {
|
|
582
719
|
let rewriteUrl;
|
|
583
720
|
try {
|
|
584
|
-
|
|
721
|
+
// The internal path (`/_/products/x` on the `app/[m]/` tree), so the variant renders the same market page.
|
|
722
|
+
rewriteUrl = new URL(ctx.internalPath + req.nextUrl.search, variantUrl);
|
|
585
723
|
}
|
|
586
724
|
catch {
|
|
587
|
-
return applyGeoConsent(req,
|
|
725
|
+
return applyGeoConsent(req, passThrough(req, ctx));
|
|
726
|
+
}
|
|
727
|
+
if (ctx.rewrite && ROUTER_SECRET) {
|
|
728
|
+
// The variant must serve that path as it is (MARKET_HOP_HEADER).
|
|
729
|
+
const headers = new Headers(ctx.headers ?? req.headers);
|
|
730
|
+
const hop = { p: ctx.internalPath, m: ctx.marketId, exp: Math.floor(Date.now() / 1000) + HOP_TTL_S };
|
|
731
|
+
headers.set(MARKET_HOP_HEADER, await signCookie(hop, ROUTER_SECRET));
|
|
732
|
+
response = NextResponse.rewrite(rewriteUrl, { request: { headers } });
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
response = NextResponse.rewrite(rewriteUrl, requestInit(ctx));
|
|
588
736
|
}
|
|
589
|
-
response = NextResponse.rewrite(rewriteUrl);
|
|
590
737
|
}
|
|
591
738
|
}
|
|
592
739
|
if (!opts.skipThemeCookieWrite && ROUTER_SECRET) {
|
|
@@ -630,23 +777,26 @@ async function signCookie(payload, secret) {
|
|
|
630
777
|
const sig = await hmacSign(data, secret);
|
|
631
778
|
return `${data}.${sig}`;
|
|
632
779
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
780
|
+
/** The JSON payload of a `signCookie` token whose signature holds, else null. */
|
|
781
|
+
async function verifySigned(token, secret) {
|
|
782
|
+
const dot = token.indexOf('.');
|
|
783
|
+
if (dot <= 0 || dot === token.length - 1)
|
|
636
784
|
return null;
|
|
637
|
-
const data =
|
|
638
|
-
const sig =
|
|
785
|
+
const data = token.slice(0, dot);
|
|
786
|
+
const sig = token.slice(dot + 1);
|
|
639
787
|
const expected = await hmacSign(data, secret);
|
|
640
788
|
// Constant-time compare (review item C1 hardening).
|
|
641
789
|
if (!timingSafeEqual(sig, expected))
|
|
642
790
|
return null;
|
|
643
|
-
let parsed;
|
|
644
791
|
try {
|
|
645
|
-
|
|
792
|
+
return JSON.parse(new TextDecoder().decode(b64urlDecode(data)));
|
|
646
793
|
}
|
|
647
794
|
catch {
|
|
648
795
|
return null;
|
|
649
796
|
}
|
|
797
|
+
}
|
|
798
|
+
async function verifyCookie(cookie, secret) {
|
|
799
|
+
const parsed = await verifySigned(cookie, secret);
|
|
650
800
|
if (!parsed ||
|
|
651
801
|
typeof parsed !== 'object' ||
|
|
652
802
|
typeof parsed.themeId !== 'string' ||
|