@tokenoftrust/storefront-runner 6.12.13 → 6.12.14

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.
@@ -278,6 +278,12 @@ export function isBypassPrivilegedPath(pathname: string): boolean {
278
278
  * instead of the holding page; the route reads `locals.storeNotPublic` and records
279
279
  * nothing (the footer/homepage newsletter form confirms "off in preview").
280
280
  *
281
+ * The preview feedback bridge (`/api/preview/feedback` and its `/context` renewal) is the
282
+ * one member with an effect: it forwards a reviewer's anonymous annotation to tot-mcp and
283
+ * returns only that submitter's own receipt — it lists, reads and comments on nothing. A
284
+ * preview grant is exactly its audience, and the route re-verifies that grant, its own
285
+ * signed render receipt and the reviewer cookie itself; it never touches store state.
286
+ *
281
287
  * Membership is earned by that property, not by being visitor-facing. The checkout
282
288
  * handoff and the compliance preflight stay refused: the preflight is the checkout
283
289
  * enforcement gate and returns a real decision, and no preview credential may reach
@@ -287,7 +293,11 @@ export function isBypassPrivilegedPath(pathname: string): boolean {
287
293
  *
288
294
  * Exact paths, in BOTH addressing forms (the gate sees the PRE-STRIP path).
289
295
  */
290
- export const PREVIEW_VISITOR_API_PATHS = ["/api/newsletter"] as const;
296
+ export const PREVIEW_VISITOR_API_PATHS = [
297
+ "/api/newsletter",
298
+ "/api/preview/feedback",
299
+ "/api/preview/feedback/context",
300
+ ] as const;
291
301
 
292
302
  export function isPreviewVisitorApiPath(pathname: string): boolean {
293
303
  if ((PREVIEW_VISITOR_API_PATHS as readonly string[]).includes(pathname)) return true;
@@ -452,9 +462,9 @@ export function evaluateLoginGate(input: LoginGateInput): LoginGateDecision {
452
462
  // public content only. NEVER for admin/cockpit/api — that guard lives here (not
453
463
  // just in middleware) so /admin stays gated even if the flag is set upstream.
454
464
  if (input.qaBypass && !isBypassPrivilegedPath(input.pathname)) return { action: "pass" };
455
- // Signed, tenant-bound preview grants admit public content and the side-effect-free
456
- // visitor forms on it. Admin, cockpit, and every other API route still require a
457
- // session.
465
+ // Signed, tenant-bound preview grants admit public content, the side-effect-free
466
+ // visitor forms on it, and anonymous preview feedback (own receipt only). Admin,
467
+ // cockpit, and every other API route still require a session.
458
468
  if (
459
469
  (input.previewTokenValid || input.candidatePinValid) &&
460
470
  (!isBypassPrivilegedPath(input.pathname) || isPreviewVisitorApiPath(input.pathname))
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The preview-annotation bootstrap a decorator adds to one authorized interactive preview
3
+ * document: a JSON config element (the browser client's `PreviewAnnotationBootstrapConfig`) and
4
+ * one nonce'd module script that mounts the client from it.
5
+ *
6
+ * Callers decide eligibility; this module only refuses what can never carry the bootstrap (a
7
+ * non-200, non-HTML or already-decorated response, or an unidentified document). Every response
8
+ * it decorates leaves `private, no-store`, because it embeds a per-viewer receipt. Renderer-safe:
9
+ * WebCrypto and string work only.
10
+ */
11
+ import {
12
+ PREVIEW_REVIEWER_COOKIE,
13
+ REVIEWER_COOKIE_OPTIONS,
14
+ documentIsValid,
15
+ mintReviewerCookieValue,
16
+ receiptExpiry,
17
+ reviewerPseudonym,
18
+ signRenderReceipt,
19
+ verifyReviewerCookieValue,
20
+ type RenderedDocument,
21
+ } from "./renderContext";
22
+
23
+ /** The DOM id the browser client reads its config from. */
24
+ export const PREVIEW_ANNOTATION_CONFIG_ELEMENT_ID = "tot-preview-annotation-config";
25
+ /** The browser client's versioned, same-origin module entry. */
26
+ export const PREVIEW_ANNOTATIONS_MODULE_PATH = "/_tot/preview-annotations/v1.js";
27
+ /** The capture policy this platform build asks the client to apply. */
28
+ export const PREVIEW_CAPTURE_POLICY_VERSION = "capture-1";
29
+
30
+ /** Structurally identical to the browser client's `PreviewAnnotationBootstrapConfig`. */
31
+ export interface PreviewAnnotationBootstrapConfig {
32
+ pageBase: string;
33
+ apiBase: string;
34
+ renderedContextReceipt: string;
35
+ capturePolicyVersion: string;
36
+ nonce?: string;
37
+ receiptExpiresAt: string;
38
+ }
39
+
40
+ export interface ReviewerCookieJar {
41
+ get(name: string): { value: string } | undefined;
42
+ set(name: string, value: string, options: typeof REVIEWER_COOKIE_OPTIONS): void;
43
+ }
44
+
45
+ export interface AnnotationBootstrapInput {
46
+ secret: string | null;
47
+ nowSeconds: number;
48
+ document: RenderedDocument;
49
+ /** Expiry of the preview capability this render rode in on, when it has one. */
50
+ capabilityExpiresAt?: number | null;
51
+ cookies: ReviewerCookieJar;
52
+ pageBase: string;
53
+ apiBase: string;
54
+ nonce: string;
55
+ moduleUrl?: string;
56
+ }
57
+
58
+ const BASE_PATTERN = /^(?:\/[A-Za-z0-9._~%!$&'()*+,;=:@-]+)*$/;
59
+ const NONCE_PATTERN = /^[A-Za-z0-9+/=_-]{1,256}$/;
60
+ const SCRIPT_UNSAFE = new Set(["<", ">", "&", String.fromCharCode(0x2028), String.fromCharCode(0x2029)]);
61
+
62
+ /** JSON safe inside an inline <script>: `<`, `>`, `&` and the line separators become escapes. */
63
+ export function jsonForScript(value: unknown): string {
64
+ let out = "";
65
+ for (const ch of JSON.stringify(value)) {
66
+ out += SCRIPT_UNSAFE.has(ch) ? `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}` : ch;
67
+ }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * The reviewer key for this browser: the signed cookie's when it verifies, otherwise a fresh
73
+ * one set on the response. Issued at render only — a submission never mints an identity.
74
+ */
75
+ async function reviewerKeyFor(secret: string, cookies: ReviewerCookieJar): Promise<string | null> {
76
+ const existing = await verifyReviewerCookieValue(secret, cookies.get(PREVIEW_REVIEWER_COOKIE)?.value);
77
+ if (existing) return existing;
78
+ const value = await mintReviewerCookieValue(secret);
79
+ cookies.set(PREVIEW_REVIEWER_COOKIE, value, REVIEWER_COOKIE_OPTIONS);
80
+ return verifyReviewerCookieValue(secret, value);
81
+ }
82
+
83
+ /** The config for one render, or null when the document cannot be identified. */
84
+ export async function buildAnnotationBootstrap(
85
+ input: AnnotationBootstrapInput,
86
+ ): Promise<PreviewAnnotationBootstrapConfig | null> {
87
+ if (!input.secret || !documentIsValid(input.document)) return null;
88
+ if (!BASE_PATTERN.test(input.pageBase) || input.pageBase.includes("//")) return null;
89
+ if (!BASE_PATTERN.test(input.apiBase) || input.apiBase.includes("//")) return null;
90
+ if (!NONCE_PATTERN.test(input.nonce)) return null;
91
+ const key = await reviewerKeyFor(input.secret, input.cookies);
92
+ if (!key) return null;
93
+ const expiresAt = receiptExpiry(input.nowSeconds, input.capabilityExpiresAt);
94
+ const receipt = await signRenderReceipt(input.secret, {
95
+ ...input.document,
96
+ reviewer: await reviewerPseudonym(input.secret, input.document.tenant, key),
97
+ originalIssuedAt: input.nowSeconds,
98
+ issuedAt: input.nowSeconds,
99
+ expiresAt,
100
+ });
101
+ return {
102
+ pageBase: input.pageBase,
103
+ apiBase: input.apiBase,
104
+ renderedContextReceipt: receipt,
105
+ capturePolicyVersion: PREVIEW_CAPTURE_POLICY_VERSION,
106
+ nonce: input.nonce,
107
+ receiptExpiresAt: new Date(expiresAt * 1000).toISOString(),
108
+ };
109
+ }
110
+
111
+ export function annotationBootstrapTags(
112
+ config: PreviewAnnotationBootstrapConfig,
113
+ moduleUrl: string = PREVIEW_ANNOTATIONS_MODULE_PATH,
114
+ ): string {
115
+ const nonce = config.nonce ?? "";
116
+ return (
117
+ `<script type="application/json" id="${PREVIEW_ANNOTATION_CONFIG_ELEMENT_ID}">${jsonForScript(config)}</script>` +
118
+ `<script type="module" nonce="${nonce}">import { initPreviewAnnotationsFromDocument } from ${jsonForScript(moduleUrl)}; initPreviewAnnotationsFromDocument();</script>`
119
+ );
120
+ }
121
+
122
+ const MARKER = `id="${PREVIEW_ANNOTATION_CONFIG_ELEMENT_ID}"`;
123
+
124
+ /** Insert the tags before the document's last `</body>`, or append them. Idempotent. */
125
+ export function injectAnnotationTags(html: string, tags: string): string {
126
+ if (html.includes(MARKER)) return html;
127
+ const close = html.toLowerCase().lastIndexOf("</body>");
128
+ return close < 0 ? html + tags : html.slice(0, close) + tags + html.slice(close);
129
+ }
130
+
131
+ /** Can this response carry the bootstrap at all? */
132
+ export function isDecoratableDocument(response: Response): boolean {
133
+ return response.status === 200 &&
134
+ (response.headers.get("content-type") ?? "").toLowerCase().includes("text/html") &&
135
+ response.body !== null;
136
+ }
137
+
138
+ /**
139
+ * Decorate one authorized interactive preview response. Returns the response unchanged when it
140
+ * cannot carry the bootstrap; otherwise a copy with the tags injected and `private, no-store`.
141
+ */
142
+ export async function injectPreviewAnnotations(
143
+ response: Response,
144
+ input: AnnotationBootstrapInput,
145
+ ): Promise<Response> {
146
+ if (!isDecoratableDocument(response)) return response;
147
+ const config = await buildAnnotationBootstrap(input);
148
+ if (!config) return response;
149
+ const html = await response.text();
150
+ const headers = new Headers(response.headers);
151
+ headers.set("cache-control", "private, no-store");
152
+ headers.delete("content-length");
153
+ headers.delete("etag");
154
+ return new Response(injectAnnotationTags(html, annotationBootstrapTags(config, input.moduleUrl)), {
155
+ status: response.status,
156
+ statusText: response.statusText,
157
+ headers,
158
+ });
159
+ }
@@ -0,0 +1,255 @@
1
+ /**
2
+ * Server-owned evidence for a preview annotation: which document a reviewer was
3
+ * looking at, and which anonymous reviewer was looking at it.
4
+ *
5
+ * Three signed values, each under its own domain-separated HMAC of
6
+ * `CUSTOMIZATION_PREVIEW_SECRET` (the secret that already signs preview links):
7
+ *
8
+ * - the reviewer-session cookie: a random key, signed, Secure/HttpOnly/SameSite=Lax,
9
+ * host-only and session-scoped. It carries no account, contact or preview
10
+ * authority, and survives preview-token renewal and sign-in changes;
11
+ * - the tenant-scoped reviewer pseudonym (`rv1_…`), derived server-side from that
12
+ * key, so one browser has unrelated pseudonyms on different stores;
13
+ * - the rendered-context receipt: tenant, preview kind, rendered revision, platform
14
+ * build, safe page reference, the reviewer pseudonym, and an expiry. It is
15
+ * minted at render from server state only and verified again on submission.
16
+ *
17
+ * The receipt is evidence, never authority: every submission and renewal re-checks
18
+ * current preview access. Renderer-safe: WebCrypto only, no control-plane imports.
19
+ */
20
+
21
+ export const PREVIEW_REVIEWER_COOKIE = "tot_pf_reviewer";
22
+ export const RENDER_RECEIPT_PREFIX = "pfr1";
23
+ /** A receipt lives at most this long, and never past the preview link it rode in on. */
24
+ export const RENDER_RECEIPT_TTL_SECONDS = 600;
25
+ /** A receipt may be renewed until this long after the render that first issued it. */
26
+ export const RENDER_RECEIPT_MAX_RENEWAL_AGE_SECONDS = 24 * 3600;
27
+ export const MAX_RENDER_RECEIPT_LENGTH = 4096;
28
+
29
+ const RECEIPT_DOMAIN = "tot-preview-feedback-render-v1";
30
+ const REVIEWER_DOMAIN = "tot-preview-feedback-reviewer-v1";
31
+ const PSEUDONYM_DOMAIN = "tot-preview-feedback-pseudonym-v1";
32
+
33
+ // The MCP contract's patterns (tot-mcp src/modules/feedback/preview-context-schema.ts).
34
+ export const TENANT_PATTERN = /^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;
35
+ export const REVIEWER_PATTERN = /^rv1_[A-Za-z0-9_-]{22,86}$/;
36
+ export const REVISION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
37
+ export const PLATFORM_SHA_PATTERN = /^[0-9a-f]{7,64}$/;
38
+ const PAGE_SEGMENT = String.raw`[A-Za-z0-9_~\-[\]]+(?:\.[A-Za-z0-9_~\-[\]]+)*`;
39
+ const PAGE_PATH_PATTERN = new RegExp(`^/(?:${PAGE_SEGMENT}(?:/${PAGE_SEGMENT})*/?)?$`);
40
+ const PAGE_OPAQUE_PATTERN = /^page:[A-Za-z0-9._-]{1,128}$/;
41
+
42
+ export function isSafePageRef(value: string): boolean {
43
+ if (value.length > 256) return false;
44
+ return PAGE_OPAQUE_PATTERN.test(value) || PAGE_PATH_PATTERN.test(value);
45
+ }
46
+
47
+ export type PreviewKind = "shared" | "candidate";
48
+
49
+ /** The document a receipt attests. Never read from the browser. */
50
+ export interface RenderedDocument {
51
+ tenant: string;
52
+ previewKind: PreviewKind;
53
+ revision: string;
54
+ platformSha: string;
55
+ pageRef: string;
56
+ }
57
+
58
+ export interface RenderReceiptClaims extends RenderedDocument {
59
+ reviewer: string;
60
+ /** Issue time of the render that first produced this document identity. */
61
+ originalIssuedAt: number;
62
+ issuedAt: number;
63
+ expiresAt: number;
64
+ }
65
+
66
+ const encoder = new TextEncoder();
67
+
68
+ function b64url(bytes: Uint8Array): string {
69
+ let bin = "";
70
+ for (const b of bytes) bin += String.fromCharCode(b);
71
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
72
+ }
73
+
74
+ function fromB64url(value: string): Uint8Array | null {
75
+ // Base64url alphabet and a length no encoding produces (4n+1) are the only inputs atob rejects.
76
+ if (!/^[A-Za-z0-9_-]*$/.test(value) || value.length % 4 === 1) return null;
77
+ const bin = atob(value.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((value.length + 3) % 4));
78
+ return Uint8Array.from(bin, (c) => c.charCodeAt(0));
79
+ }
80
+
81
+ const keyCache = new Map<string, Promise<CryptoKey>>();
82
+ function hmacKey(secret: string): Promise<CryptoKey> {
83
+ let key = keyCache.get(secret);
84
+ if (!key) {
85
+ key = crypto.subtle.importKey("raw", encoder.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
86
+ keyCache.set(secret, key);
87
+ }
88
+ return key;
89
+ }
90
+
91
+ async function mac(secret: string, domain: string, message: string): Promise<string> {
92
+ const sig = await crypto.subtle.sign("HMAC", await hmacKey(secret), encoder.encode(`${domain}\n${message}`));
93
+ return b64url(new Uint8Array(sig));
94
+ }
95
+
96
+ /** Constant-time string comparison (equal-length inputs; length leaks nothing secret here). */
97
+ function safeEqual(a: string, b: string): boolean {
98
+ if (a.length !== b.length) return false;
99
+ let diff = 0;
100
+ for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
101
+ return diff === 0;
102
+ }
103
+
104
+ // ---- reviewer session ------------------------------------------------------
105
+
106
+ /** A fresh signed reviewer-session cookie value (`rk1.<key>.<mac>`). */
107
+ export async function mintReviewerCookieValue(secret: string): Promise<string> {
108
+ const key = b64url(crypto.getRandomValues(new Uint8Array(32)));
109
+ return `rk1.${key}.${await mac(secret, REVIEWER_DOMAIN, key)}`;
110
+ }
111
+
112
+ /** The reviewer key a cookie value carries, or null when it is absent, malformed or unsigned. */
113
+ export async function verifyReviewerCookieValue(
114
+ secret: string,
115
+ value: string | null | undefined,
116
+ ): Promise<string | null> {
117
+ if (!value || value.length > 256) return null;
118
+ const parts = value.split(".");
119
+ if (parts.length !== 3 || parts[0] !== "rk1") return null;
120
+ const [, key, sig] = parts as [string, string, string];
121
+ if (!/^[A-Za-z0-9_-]{43}$/.test(key)) return null;
122
+ return safeEqual(sig, await mac(secret, REVIEWER_DOMAIN, key)) ? key : null;
123
+ }
124
+
125
+ /** The tenant-scoped pseudonym for a reviewer key. Stable for (tenant, key); unlinkable across tenants. */
126
+ export async function reviewerPseudonym(secret: string, tenant: string, reviewerKey: string): Promise<string> {
127
+ return `rv1_${await mac(secret, PSEUDONYM_DOMAIN, `${tenant}\n${reviewerKey}`)}`;
128
+ }
129
+
130
+ export const REVIEWER_COOKIE_OPTIONS = {
131
+ httpOnly: true,
132
+ secure: true,
133
+ sameSite: "lax",
134
+ path: "/",
135
+ } as const;
136
+
137
+ // ---- rendered-context receipt ---------------------------------------------
138
+
139
+ export function documentIsValid(doc: RenderedDocument): boolean {
140
+ return TENANT_PATTERN.test(doc.tenant) &&
141
+ (doc.previewKind === "shared" || doc.previewKind === "candidate") &&
142
+ REVISION_PATTERN.test(doc.revision) &&
143
+ PLATFORM_SHA_PATTERN.test(doc.platformSha) &&
144
+ isSafePageRef(doc.pageRef);
145
+ }
146
+
147
+ export async function signRenderReceipt(secret: string, claims: RenderReceiptClaims): Promise<string> {
148
+ const payload = b64url(encoder.encode(JSON.stringify({
149
+ v: 1,
150
+ t: claims.tenant,
151
+ k: claims.previewKind,
152
+ r: claims.revision,
153
+ p: claims.platformSha,
154
+ g: claims.pageRef,
155
+ rv: claims.reviewer,
156
+ oiat: claims.originalIssuedAt,
157
+ iat: claims.issuedAt,
158
+ exp: claims.expiresAt,
159
+ })));
160
+ return `${RENDER_RECEIPT_PREFIX}.${payload}.${await mac(secret, RECEIPT_DOMAIN, payload)}`;
161
+ }
162
+
163
+ export type ReceiptVerdict =
164
+ | { ok: true; claims: RenderReceiptClaims; expired: boolean }
165
+ | { ok: false };
166
+
167
+ /** Verify a receipt's signature and shape. Expiry is reported, not refused, so renewal can read it. */
168
+ export async function verifyRenderReceipt(
169
+ secret: string,
170
+ receipt: unknown,
171
+ nowSeconds: number,
172
+ ): Promise<ReceiptVerdict> {
173
+ if (typeof receipt !== "string" || receipt.length === 0 || receipt.length > MAX_RENDER_RECEIPT_LENGTH) {
174
+ return { ok: false };
175
+ }
176
+ const parts = receipt.split(".");
177
+ if (parts.length !== 3 || parts[0] !== RENDER_RECEIPT_PREFIX) return { ok: false };
178
+ const [, payload, sig] = parts as [string, string, string];
179
+ if (!safeEqual(sig, await mac(secret, RECEIPT_DOMAIN, payload))) return { ok: false };
180
+ const bytes = fromB64url(payload);
181
+ if (!bytes) return { ok: false };
182
+ let raw: Record<string, unknown>;
183
+ try {
184
+ raw = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>;
185
+ } catch {
186
+ return { ok: false };
187
+ }
188
+ const int = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v);
189
+ if (raw.v !== 1 || !int(raw.iat) || !int(raw.exp) || !int(raw.oiat) || raw.exp <= raw.iat ||
190
+ typeof raw.rv !== "string" || !REVIEWER_PATTERN.test(raw.rv)) {
191
+ return { ok: false };
192
+ }
193
+ const claims: RenderReceiptClaims = {
194
+ tenant: String(raw.t ?? ""),
195
+ previewKind: raw.k as PreviewKind,
196
+ revision: String(raw.r ?? ""),
197
+ platformSha: String(raw.p ?? ""),
198
+ pageRef: String(raw.g ?? ""),
199
+ reviewer: raw.rv,
200
+ originalIssuedAt: raw.oiat,
201
+ issuedAt: raw.iat,
202
+ expiresAt: raw.exp,
203
+ };
204
+ if (!documentIsValid(claims)) return { ok: false };
205
+ return { ok: true, claims, expired: nowSeconds >= claims.expiresAt };
206
+ }
207
+
208
+ /** A receipt's expiry: ten minutes, capped by the preview capability's own remaining life. */
209
+ export function receiptExpiry(nowSeconds: number, capabilityExpiresAt?: number | null): number {
210
+ const cap = nowSeconds + RENDER_RECEIPT_TTL_SECONDS;
211
+ return typeof capabilityExpiresAt === "number" && capabilityExpiresAt > nowSeconds
212
+ ? Math.min(cap, capabilityExpiresAt)
213
+ : cap;
214
+ }
215
+
216
+ // ---- safe page reference ---------------------------------------------------
217
+
218
+ /**
219
+ * Routes whose path segments can name a customer, an order or a credential. Only
220
+ * their first segment survives; every segment under them becomes a placeholder.
221
+ */
222
+ const PRIVATE_ROOTS = new Set([
223
+ "account", "accounts", "admin", "api", "auth", "cart", "checkout", "cockpit", "customer",
224
+ "customers", "invite", "invites", "login", "logout", "member", "members", "my", "order",
225
+ "orders", "password", "profile", "register", "reset", "signup", "subscription",
226
+ "subscriptions", "unsubscribe", "verify",
227
+ ]);
228
+ const SAFE_SEGMENT = /^[a-z](?:[a-z-]{0,62}[a-z])?$/;
229
+ const MAX_PAGE_SEGMENTS = 12;
230
+
231
+ /**
232
+ * A page reference safe to store: the tenant-relative route with every segment that
233
+ * could carry a dynamic or private value replaced by `[segment]`. Query and fragment
234
+ * never survive. A segment is kept only when it is a short lowercase word or
235
+ * hyphenated words with no digits, no encoding and no dots — so ids, slugs with
236
+ * numbers, emails, tokens and encoded values are never presumed public.
237
+ */
238
+ export function safePageRef(renderPath: string): string {
239
+ const path = renderPath.split(/[?#]/, 1)[0] ?? "";
240
+ const segments = path.split("/").filter((s) => s.length > 0);
241
+ if (segments.length === 0) return "/";
242
+ const out: string[] = [];
243
+ let privateRoot = false;
244
+ for (const [i, segment] of segments.entries()) {
245
+ if (i >= MAX_PAGE_SEGMENTS) {
246
+ out.push("[rest]");
247
+ break;
248
+ }
249
+ const keep = !privateRoot && SAFE_SEGMENT.test(segment);
250
+ out.push(keep ? segment : "[segment]");
251
+ if (i === 0 && keep && PRIVATE_ROOTS.has(segment)) privateRoot = true;
252
+ }
253
+ const ref = `/${out.join("/")}`;
254
+ return isSafePageRef(ref) ? ref : "page:unresolved";
255
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Which rendered responses get the preview-annotation bootstrap, decided at the render chain's
3
+ * response-decoration seam from authoritative request state only:
4
+ *
5
+ * - a shared preview: a verified, tenant-bound preview token made this a `test` render, no
6
+ * candidate pin is present, and the preview channel names the revision it served;
7
+ * - a pinned candidate route: a server-minted candidate content pin (`integrationStage`
8
+ * `candidate`, never `staged`) names the exact revision.
9
+ *
10
+ * Never for a publication capture or materialization, an internal publication, a non-GET, a
11
+ * live/public render, or a document whose revision or platform build cannot be named. A host
12
+ * name or `NODE_ENV` alone never qualifies a render. The bootstrap is evidence for a later
13
+ * submission, never authority: the bridge re-checks current preview access on every call.
14
+ */
15
+ import { verifyPreviewToken } from "@tot/public-runtime";
16
+ import { injectPreviewAnnotations, type ReviewerCookieJar } from "./inject";
17
+ import { PLATFORM_SHA_PATTERN, REVISION_PATTERN, safePageRef, type PreviewKind } from "./renderContext";
18
+
19
+ declare const __GIT_SHA__: string | undefined;
20
+
21
+ /** The platform build that rendered this response, when it is a real commit. */
22
+ export function renderingPlatformSha(): string | null {
23
+ const sha = typeof __GIT_SHA__ !== "undefined" ? (__GIT_SHA__ ?? "") : "";
24
+ return PLATFORM_SHA_PATTERN.test(sha) ? sha : null;
25
+ }
26
+
27
+ export interface PreviewAnnotationDecoration {
28
+ request: Request;
29
+ customizationEnv: "live" | "test";
30
+ /** The verified preview token this render rode in on, or null. */
31
+ previewToken: string | null;
32
+ candidatePin: { versionId: string; integrationStage: "candidate" | "staged" } | null;
33
+ tenantId: string;
34
+ renderPath: string;
35
+ secret: string | null;
36
+ nowSeconds: number;
37
+ cookies: ReviewerCookieJar;
38
+ pageBase: string;
39
+ apiBase: string;
40
+ nonce: string;
41
+ /** True for a publication capture/materialize render (probe header or materialize binding). */
42
+ capture: boolean;
43
+ internalPublication: boolean;
44
+ /** The shared preview channel's served revision, read through the render's own memo. */
45
+ sharedRevision: () => Promise<string | null>;
46
+ platformSha?: string | null;
47
+ }
48
+
49
+ async function previewKindAndRevision(
50
+ input: PreviewAnnotationDecoration,
51
+ ): Promise<{ previewKind: PreviewKind; revision: string } | null> {
52
+ if (input.candidatePin) {
53
+ return input.candidatePin.integrationStage === "candidate"
54
+ ? { previewKind: "candidate", revision: input.candidatePin.versionId }
55
+ : null;
56
+ }
57
+ if (input.customizationEnv !== "test" || !input.previewToken) return null;
58
+ const revision = await input.sharedRevision().catch(() => null);
59
+ return revision ? { previewKind: "shared", revision } : null;
60
+ }
61
+
62
+ export async function decoratePreviewAnnotations(
63
+ response: Response,
64
+ input: PreviewAnnotationDecoration,
65
+ ): Promise<Response> {
66
+ if (input.request.method !== "GET" || input.capture || input.internalPublication || !input.secret) {
67
+ return response;
68
+ }
69
+ const platformSha = input.platformSha === undefined ? renderingPlatformSha() : input.platformSha;
70
+ if (!platformSha || !PLATFORM_SHA_PATTERN.test(platformSha)) return response;
71
+ const identified = await previewKindAndRevision(input);
72
+ if (!identified || !REVISION_PATTERN.test(identified.revision)) return response;
73
+ let capabilityExpiresAt: number | null = null;
74
+ if (input.previewToken) {
75
+ const verified = await verifyPreviewToken(input.secret, input.previewToken, input.nowSeconds);
76
+ if (verified.ok) capabilityExpiresAt = verified.claims.exp;
77
+ }
78
+ return injectPreviewAnnotations(response, {
79
+ secret: input.secret,
80
+ nowSeconds: input.nowSeconds,
81
+ document: {
82
+ tenant: input.tenantId,
83
+ previewKind: identified.previewKind,
84
+ revision: identified.revision,
85
+ platformSha,
86
+ pageRef: safePageRef(input.renderPath),
87
+ },
88
+ capabilityExpiresAt,
89
+ cookies: input.cookies,
90
+ pageBase: input.pageBase,
91
+ apiBase: input.apiBase,
92
+ nonce: input.nonce,
93
+ });
94
+ }
@@ -30,6 +30,7 @@ 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
34
  import {
34
35
  resolveCustomizationEnv,
35
36
  buildCsp,
@@ -842,6 +843,31 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
842
843
  nonce: cspNonce,
843
844
  });
844
845
 
846
+ // Preview annotations: an authorized interactive preview (shared preview token, or a
847
+ // pinned candidate) carries the Feedback bootstrap and a signed rendered-context receipt.
848
+ // Capture, materialization, internal publication and live renders never do; the
849
+ // decorator marks what it decorates `private, no-store`.
850
+ response = await decoratePreviewAnnotations(response, {
851
+ request,
852
+ customizationEnv: customization.env,
853
+ previewToken,
854
+ candidatePin: candidatePin ?? null,
855
+ tenantId: tenant.tenant_id,
856
+ renderPath,
857
+ secret: previewSecret,
858
+ nowSeconds,
859
+ cookies: context.cookies,
860
+ pageBase: locals.basePath ?? basePath,
861
+ apiBase: basePath,
862
+ nonce: cspNonce,
863
+ capture: request.headers.has(HTML_CACHE_POLICY_CAPTURE_PROBE) ||
864
+ (await readEnv(MATERIALIZE_MODE_BINDING)) === "1",
865
+ internalPublication: isInternalPublication,
866
+ sharedRevision: async () => publicationSource.status === "selected"
867
+ ? publicationSource.cacheScope.versionId
868
+ : (await resolveServableChannelVersion(kvGet, tenant.tenant_id, "preview")).versionId,
869
+ });
870
+
845
871
  // Distinct tenant theme sheets are render-blocking `/tenants/` fetches. Inline
846
872
  // them into this preview document. Publication capture keeps the source links
847
873
  // so the asset pipeline concatenates the same run for both CDNs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.12.13",
3
+ "version": "6.12.14",
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",