@tokenoftrust/storefront-runner 6.12.14 → 6.12.16

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.
@@ -63,6 +63,7 @@ import { devAuthOutbox } from "./dev-plugins/dev-auth-outbox.mjs";
63
63
  import { materializeGuard } from "./integrations/materialize-guard.mjs";
64
64
  import { lifecycleHostAsset } from "./integrations/lifecycle-host-asset.mjs";
65
65
  import { googleMeasurementSandboxAsset } from "./integrations/google-measurement-sandbox-asset.mjs";
66
+ import { previewAnnotationsClientBundle } from "./integrations/preview-annotations-client-bundle.mjs";
66
67
 
67
68
  // SSR on Cloudflare Workers. `output: 'server'` because every response is
68
69
  // tenant-resolved at the edge from the Host header (see src/middleware).
@@ -116,6 +117,7 @@ export default defineConfig({
116
117
  // marketing mount has no bundler to hoist a module import through.
117
118
  lifecycleHostAsset(),
118
119
  googleMeasurementSandboxAsset(),
120
+ previewAnnotationsClientBundle(),
119
121
  preact({ compat: true }),
120
122
  // Astro's file-based router ignores ANY path segment starting with "_" (see
121
123
  // `astro/dist/core/routing/create-manifest.js`), so a page literally named
@@ -167,6 +167,11 @@ declare global {
167
167
  * origin. Same-origin checks compare `Origin` against THIS.
168
168
  */
169
169
  requestOrigin?: string;
170
+ /**
171
+ * True for an authenticated CDN forward (ADR 0013 Tier 3): the response reaches a viewer
172
+ * through the tenant's CDN, so it is never decorated with preview annotations.
173
+ */
174
+ cdnForwarded?: boolean;
170
175
  /**
171
176
  * True when this request was admitted to a store that is NOT public on this
172
177
  * host (a login-gated host, tenant without `access.public`) — by session,
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Vite plugin: `import source from "<entry>?tot-client-bundle"` is the entry's browser bundle as one
3
+ * string (single self-contained ES module, no imports), built with the esbuild Astro ships. The
4
+ * Worker serves that string itself from its preview control plane; nothing is written to the
5
+ * public client output, so no static-asset, CDN or publication path can reach it.
6
+ */
7
+ import { createRequire } from "node:module";
8
+ import { isAbsolute, resolve, sep } from "node:path";
9
+
10
+ export const CLIENT_BUNDLE_QUERY = "?tot-client-bundle";
11
+
12
+ const SERVER_ONLY_INPUT = /(?:^|\/)(?:server|node_modules)\//;
13
+
14
+ export async function bundleBrowserEntry(entry) {
15
+ const require = createRequire(import.meta.url);
16
+ const esbuild = createRequire(require.resolve("astro/package.json"))("esbuild");
17
+ const result = await esbuild.build({
18
+ entryPoints: [entry],
19
+ bundle: true,
20
+ write: false,
21
+ metafile: true,
22
+ format: "esm",
23
+ platform: "browser",
24
+ target: "es2022",
25
+ minify: true,
26
+ treeShaking: true,
27
+ legalComments: "none",
28
+ sourcemap: false,
29
+ logLevel: "silent",
30
+ });
31
+ if (result.outputFiles.length !== 1) {
32
+ throw new Error(`${entry} emitted ${result.outputFiles.length} files; expected one.`);
33
+ }
34
+ for (const output of Object.values(result.metafile.outputs)) {
35
+ if ((output.imports ?? []).length > 0) throw new Error(`${entry} must bundle to an import-free module.`);
36
+ }
37
+ const inputs = Object.keys(result.metafile.inputs);
38
+ const forbidden = inputs.find((input) => SERVER_ONLY_INPUT.test(input.split(sep).join("/")));
39
+ if (forbidden) throw new Error(`${entry} bundles server-only or third-party input ${forbidden}.`);
40
+ return { code: result.outputFiles[0].text.trim(), inputs };
41
+ }
42
+
43
+ export function clientBundleSourceModule(code) {
44
+ return `export default ${JSON.stringify(code)};\n`;
45
+ }
46
+
47
+ export function previewAnnotationsClientBundle() {
48
+ return {
49
+ name: "tot-client-bundle-integration",
50
+ hooks: {
51
+ "astro:config:setup": ({ updateConfig }) => {
52
+ updateConfig({ vite: { plugins: [clientBundleVitePlugin()] } });
53
+ },
54
+ },
55
+ };
56
+ }
57
+
58
+ export function clientBundleVitePlugin() {
59
+ let root = process.cwd();
60
+ return {
61
+ name: "tot-client-bundle",
62
+ enforce: "pre",
63
+ configResolved(config) {
64
+ root = config.root;
65
+ },
66
+ async resolveId(source, importer) {
67
+ if (!source.endsWith(CLIENT_BUNDLE_QUERY)) return null;
68
+ const resolved = await this.resolve(source.slice(0, -CLIENT_BUNDLE_QUERY.length), importer, { skipSelf: true });
69
+ if (!resolved) return null;
70
+ return `${resolved.id.split("?")[0]}${CLIENT_BUNDLE_QUERY}`;
71
+ },
72
+ async load(id) {
73
+ if (!id.endsWith(CLIENT_BUNDLE_QUERY)) return null;
74
+ const entry = id.slice(0, -CLIENT_BUNDLE_QUERY.length);
75
+ const { code, inputs } = await bundleBrowserEntry(entry);
76
+ for (const input of inputs) this.addWatchFile(isAbsolute(input) ? input : resolve(root, input));
77
+ return clientBundleSourceModule(code);
78
+ },
79
+ };
80
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Serving the preview-annotation client module (`PREVIEW_ANNOTATIONS_MODULE_PATH`).
3
+ *
4
+ * The bytes are one build-time bundle string, answered by the Worker only to a request that may
5
+ * load it (`mayLoadAnnotationModule`: a browser this origin handed a decorated document). They hold
6
+ * no secret, tenant datum or server module, and the response carries nothing per viewer. Access
7
+ * depends on the request's cookie, so the response is `private` (no shared cache answers another
8
+ * requester); `no-cache` plus an ETag makes every deploy visible at once. Every other request gets
9
+ * a 404 that names nothing. Renderer-safe: WebCrypto only.
10
+ */
11
+ import { PREVIEW_ANNOTATIONS_MODULE_PATH } from "./inject";
12
+
13
+ export function isPreviewAnnotationsModulePath(pathname: string): boolean {
14
+ return pathname === PREVIEW_ANNOTATIONS_MODULE_PATH;
15
+ }
16
+
17
+ let memo: { source: string; etag: string } | null = null;
18
+
19
+ async function etagFor(source: string): Promise<string> {
20
+ if (memo?.source === source) return memo.etag;
21
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(source));
22
+ const hex = [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
23
+ memo = { source, etag: `"${hex}"` };
24
+ return memo.etag;
25
+ }
26
+
27
+ function notFound(): Response {
28
+ return new Response("Not Found", {
29
+ status: 404,
30
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
31
+ });
32
+ }
33
+
34
+ export interface PreviewAnnotationsModuleRequest {
35
+ method: string;
36
+ /** The verdict of `mayLoadAnnotationModule` for this request. */
37
+ mayLoad: boolean;
38
+ ifNoneMatch: string | null;
39
+ }
40
+
41
+ /**
42
+ * The response for a request already known to name the module path. `source` is read lazily so a
43
+ * refused request never touches the bundle.
44
+ */
45
+ export async function servePreviewAnnotationsModule(
46
+ input: PreviewAnnotationsModuleRequest,
47
+ source: () => Promise<string>,
48
+ ): Promise<Response> {
49
+ if (!input.mayLoad) return notFound();
50
+ if (input.method !== "GET" && input.method !== "HEAD") {
51
+ return new Response("Method Not Allowed", { status: 405, headers: { allow: "GET, HEAD" } });
52
+ }
53
+ const code = await source();
54
+ const etag = await etagFor(code);
55
+ const headers = new Headers({
56
+ "content-type": "text/javascript; charset=utf-8",
57
+ "cache-control": "private, no-cache",
58
+ etag,
59
+ "cross-origin-resource-policy": "same-origin",
60
+ });
61
+ if (input.ifNoneMatch?.split(",").some((candidate) => candidate.trim() === etag)) {
62
+ return new Response(null, { status: 304, headers });
63
+ }
64
+ return new Response(input.method === "HEAD" ? null : code, { status: 200, headers });
65
+ }
@@ -7,17 +7,52 @@
7
7
  * - a pinned candidate route: a server-minted candidate content pin (`integrationStage`
8
8
  * `candidate`, never `staged`) names the exact revision.
9
9
  *
10
- * Never for a publication capture or materialization, an internal publication, a non-GET, a
10
+ * Never for a CDN-forwarded render, a publication capture or materialization, an internal publication, a non-GET, a
11
11
  * live/public render, or a document whose revision or platform build cannot be named. A host
12
12
  * name or `NODE_ENV` alone never qualifies a render. The bootstrap is evidence for a later
13
13
  * submission, never authority: the bridge re-checks current preview access on every call.
14
14
  */
15
- import { verifyPreviewToken } from "@tot/public-runtime";
15
+ import { HTML_CACHE_POLICY_CAPTURE_PROBE, verifyPreviewToken } from "@tot/public-runtime";
16
16
  import { injectPreviewAnnotations, type ReviewerCookieJar } from "./inject";
17
- import { PLATFORM_SHA_PATTERN, REVISION_PATTERN, safePageRef, type PreviewKind } from "./renderContext";
17
+ import {
18
+ PLATFORM_SHA_PATTERN,
19
+ PREVIEW_REVIEWER_COOKIE,
20
+ REVISION_PATTERN,
21
+ safePageRef,
22
+ verifyReviewerCookieValue,
23
+ type PreviewKind,
24
+ } from "./renderContext";
18
25
 
19
26
  declare const __GIT_SHA__: string | undefined;
20
27
 
28
+ /**
29
+ * A publication capture or materialization request: the capture probe header, or the Worker's
30
+ * materialize binding (`MATERIALIZE_MODE_BINDING`) read as `"1"`. Never decorated, never handed
31
+ * the annotation client.
32
+ */
33
+ export function isPublicationCapture(headers: Headers, materializeMode: string | null | undefined): boolean {
34
+ return headers.has(HTML_CACHE_POLICY_CAPTURE_PROBE) || materializeMode === "1";
35
+ }
36
+
37
+ export interface AnnotationModuleAccess {
38
+ cdnForwarded: boolean;
39
+ capture: boolean;
40
+ secret: string | null;
41
+ cookies: Pick<ReviewerCookieJar, "get">;
42
+ }
43
+
44
+ /**
45
+ * May this request load the annotation client module? Exactly the browsers this origin handed a
46
+ * decorated document: decoration always leaves a verified reviewer cookie (`path=/`) on the origin
47
+ * it rendered for, on whatever host that was, and nothing else mints one. A CDN-forwarded request
48
+ * and a capture or materialization request never qualify.
49
+ */
50
+ export async function mayLoadAnnotationModule(input: AnnotationModuleAccess): Promise<boolean> {
51
+ if (input.cdnForwarded || input.capture || !input.secret) return false;
52
+ const cookie = input.cookies.get(PREVIEW_REVIEWER_COOKIE)?.value;
53
+ return (await verifyReviewerCookieValue(input.secret, cookie)) !== null;
54
+ }
55
+
21
56
  /** The platform build that rendered this response, when it is a real commit. */
22
57
  export function renderingPlatformSha(): string | null {
23
58
  const sha = typeof __GIT_SHA__ !== "undefined" ? (__GIT_SHA__ ?? "") : "";
@@ -40,6 +75,8 @@ export interface PreviewAnnotationDecoration {
40
75
  nonce: string;
41
76
  /** True for a publication capture/materialize render (probe header or materialize binding). */
42
77
  capture: boolean;
78
+ /** True for an authenticated CDN forward: the response reaches viewers through the tenant's CDN. */
79
+ cdnForwarded: boolean;
43
80
  internalPublication: boolean;
44
81
  /** The shared preview channel's served revision, read through the render's own memo. */
45
82
  sharedRevision: () => Promise<string | null>;
@@ -63,6 +100,7 @@ export async function decoratePreviewAnnotations(
63
100
  response: Response,
64
101
  input: PreviewAnnotationDecoration,
65
102
  ): Promise<Response> {
103
+ if (input.cdnForwarded) return response;
66
104
  if (input.request.method !== "GET" || input.capture || input.internalPublication || !input.secret) {
67
105
  return response;
68
106
  }
@@ -38,11 +38,34 @@ export function buildPreviewReloadScript(opts: {
38
38
  const pollMs = Math.max(250, Math.floor(opts.pollMs ?? DEFAULT_POLL_MS));
39
39
  // The version endpoint is fetched UNDER basePath so the same tenant-routing the
40
40
  // page used resolves it (path-routed previews carry a /<domain> prefix).
41
+ // Draft hold: an unsent preview annotation draft (preview/annotations/reloadHold.ts) registers a
42
+ // hold in window.__totPreviewHolds. While any hold exists a newer version is recorded as pending
43
+ // and announced with "tot:preview-update-available" instead of reloading; the reload happens
44
+ // only once the last hold is released (submit, discard or close). Nothing is ever submitted on
45
+ // the way out.
41
46
  return `(() => {
42
47
  const TENANT = ${tenant}, BASE = ${base}, POLL_MS = ${pollMs};
43
48
  const url = BASE + "/api/preview/version?tenant=" + encodeURIComponent(TENANT);
44
49
  let known = null;
45
50
  let timer = null;
51
+ const holdBag = () => {
52
+ let bag = window.__totPreviewHolds;
53
+ if (!bag || !(bag.holds instanceof Set)) { bag = { holds: new Set(), pending: false }; window.__totPreviewHolds = bag; }
54
+ return bag;
55
+ };
56
+ const reloadUnlessHeld = () => {
57
+ const bag = holdBag();
58
+ if (bag.holds.size > 0) {
59
+ if (!bag.pending) { bag.pending = true; window.dispatchEvent(new CustomEvent("tot:preview-update-available")); }
60
+ return false;
61
+ }
62
+ location.reload();
63
+ return true;
64
+ };
65
+ window.addEventListener("tot:preview-hold-change", () => {
66
+ const bag = holdBag();
67
+ if (bag.pending && bag.holds.size === 0) location.reload();
68
+ });
46
69
  // A hidden tab cannot see a reload, so polling it is pure waste — and an
47
70
  // unconditional once-a-second fetch leaves the tab in perpetual network
48
71
  // activity, which reads to a reviewer as a preview that never finishes
@@ -80,7 +103,7 @@ export function buildPreviewReloadScript(opts: {
80
103
  // TODO(theme-hot-swap): when the change is theme-only, swap the CSS custom
81
104
  // properties in place (no reload). Needs the reconcile to report a
82
105
  // theme-only delta; gated behind this same version signal until then.
83
- else if (v !== known) { location.reload(); return; }
106
+ else if (v !== known) { if (reloadUnlessHeld()) return; }
84
107
  }
85
108
  } catch (_e) { /* offline / aborted — genuinely transient, keep the cadence */ }
86
109
  schedule();
@@ -27,7 +27,7 @@ import { resolveCdnForwardRouting, resolveTenantRouting } from "@/lib/access/sha
27
27
  import { crossSiteFormRefusal, verifyCdnForward } from "@/lib/publication/shared/cdnForward";
28
28
  import { SAMPLE_CART_HANDOFF_URL, commerceTenantId, compileRouteTierIndexV1, resolvePublicationRoutePlanV1, type RouteTierIndexV1 , storefrontModeRequiresSignIn } from "@tot/public-runtime";
29
29
  import type { PublicationArtifactBucketV1, TenantConfig } from "@tot/public-runtime";
30
- import { HTML_CACHE_POLICY_CAPTURE_PROBE } from "@tot/public-runtime";
30
+ import { HTML_CACHE_POLICY_CAPTURE_PROBE, MATERIALIZE_MODE_BINDING } from "@tot/public-runtime";
31
31
  import { resolveCapturedRequestVersion, resolveCustomizationEnv } from "@tot/public-runtime";
32
32
  import type { RenditionRegistryBucket } from "@/lib/assets/registeredRenditions";
33
33
  import { DEV_DRAFT_COOKIE } from "@/lib/developer-experience/dev/devDraft";
@@ -154,6 +154,7 @@ async function serveRequest(
154
154
  // the host the viewer addressed, never this Worker's own.
155
155
  const cdn = await verifyCdnForward(request.headers, await readEnv("CDN_ORIGIN_SECRET"));
156
156
  seen.cdnForwarded = !!cdn;
157
+ locals.cdnForwarded = !!cdn;
157
158
  if (cdn) host = cdn.viewerHost;
158
159
  const origin = cdn ? `https://${cdn.viewerHost}` : url.origin;
159
160
  locals.requestOrigin = origin;
@@ -30,7 +30,10 @@ import {
30
30
  import { STATIC_SCRIPT_HASHES, STATIC_STYLE_HASHES } from "@/lib/access/shared/cspStaticHashes";
31
31
  import { applySecurityHeaders } from "@/lib/access/shared/securityHeaders";
32
32
  import { maybeInjectPreviewReload } from "@/lib/publication/shared/previewReload";
33
- import { decoratePreviewAnnotations } from "@/lib/publication/shared/previewAnnotations/renderDecorator";
33
+ import {
34
+ decoratePreviewAnnotations,
35
+ isPublicationCapture,
36
+ } from "@/lib/publication/shared/previewAnnotations/renderDecorator";
34
37
  import {
35
38
  resolveCustomizationEnv,
36
39
  buildCsp,
@@ -860,8 +863,8 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
860
863
  pageBase: locals.basePath ?? basePath,
861
864
  apiBase: basePath,
862
865
  nonce: cspNonce,
863
- capture: request.headers.has(HTML_CACHE_POLICY_CAPTURE_PROBE) ||
864
- (await readEnv(MATERIALIZE_MODE_BINDING)) === "1",
866
+ capture: isPublicationCapture(request.headers, await readEnv(MATERIALIZE_MODE_BINDING)),
867
+ cdnForwarded: locals.cdnForwarded === true,
865
868
  internalPublication: isInternalPublication,
866
869
  sharedRevision: async () => publicationSource.status === "selected"
867
870
  ? publicationSource.cacheScope.versionId
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.14",
3
+ "version": "6.12.16",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "description": "World-shareable storefront runner: multi-tenant renderer on Astro/Cloudflare. No control plane.",
6
6
  "packageManager": "pnpm@11.9.0",