@tokenoftrust/storefront-runner 6.14.0 → 6.14.2

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.
@@ -35,6 +35,8 @@ export interface PreviewAnnotationBootstrapConfig {
35
35
  capturePolicyVersion: string;
36
36
  nonce?: string;
37
37
  receiptExpiresAt: string;
38
+ /** May a session record capture this document? Mirrors the receipt's claim. */
39
+ recordable: boolean;
38
40
  }
39
41
 
40
42
  export interface ReviewerCookieJar {
@@ -46,6 +48,8 @@ export interface AnnotationBootstrapInput {
46
48
  secret: string | null;
47
49
  nowSeconds: number;
48
50
  document: RenderedDocument;
51
+ /** The server's recording verdict for this route (`protectedSurfaces.ts`). */
52
+ recordable: boolean;
49
53
  /** Expiry of the preview capability this render rode in on, when it has one. */
50
54
  capabilityExpiresAt?: number | null;
51
55
  cookies: ReviewerCookieJar;
@@ -94,6 +98,7 @@ export async function buildAnnotationBootstrap(
94
98
  const receipt = await signRenderReceipt(input.secret, {
95
99
  ...input.document,
96
100
  reviewer: await reviewerPseudonym(input.secret, input.document.tenant, key),
101
+ recordable: input.recordable,
97
102
  originalIssuedAt: input.nowSeconds,
98
103
  issuedAt: input.nowSeconds,
99
104
  expiresAt,
@@ -105,6 +110,7 @@ export async function buildAnnotationBootstrap(
105
110
  capturePolicyVersion: PREVIEW_CAPTURE_POLICY_VERSION,
106
111
  nonce: input.nonce,
107
112
  receiptExpiresAt: new Date(expiresAt * 1000).toISOString(),
113
+ recordable: input.recordable,
108
114
  };
109
115
  }
110
116
 
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Surfaces a preview record never captures, and the route roots whose deeper segments never
3
+ * survive into a stored page reference. One list, imported by `safePageRef` (server) and by the
4
+ * session recorder (browser), so the two can never disagree.
5
+ *
6
+ * The server decides: a route is recordable only when its first segment is not a platform root
7
+ * below and it falls under no tenant-declared or member-area prefix. The receipt and bootstrap carry
8
+ * that verdict as `recordable`; the browser probe (`protectedProbe.ts`) can only narrow it.
9
+ *
10
+ * Pure and dependency-free: it ships in the Worker and in the browser client.
11
+ */
12
+
13
+ /**
14
+ * Route roots that can name a customer, an order, a credential or a payment, or that are platform
15
+ * surfaces: checkout, cart, payment, authentication, account and member areas, admin, `/cockpit`,
16
+ * `/api`, and age and identity verification.
17
+ */
18
+ export const PROTECTED_ROUTE_ROOTS: ReadonlySet<string> = new Set([
19
+ "account", "accounts", "admin", "api", "auth", "cart", "checkout", "cockpit", "customer",
20
+ "customers", "invite", "invites", "login", "logout", "member", "members", "my", "order",
21
+ "orders", "password", "pay", "payment", "profile", "register", "reset", "signup",
22
+ "subscription", "subscriptions", "unsubscribe", "verify",
23
+ ]);
24
+
25
+ /**
26
+ * Origins whose iframes collect payment details. A page embedding one is never recorded. A payment
27
+ * provider is added here, never by tenant config.
28
+ */
29
+ export const PAYMENT_FRAME_ORIGINS: ReadonlySet<string> = new Set([
30
+ "https://js.stripe.com",
31
+ "https://checkout.stripe.com",
32
+ "https://hooks.stripe.com",
33
+ "https://www.paypal.com",
34
+ "https://www.sandbox.paypal.com",
35
+ "https://assets.braintreegateway.com",
36
+ "https://web.squarecdn.com",
37
+ "https://sandbox.web.squarecdn.com",
38
+ "https://accept.authorize.net",
39
+ "https://test.authorize.net",
40
+ "https://checkoutshopper-live.adyen.com",
41
+ "https://checkoutshopper-test.adyen.com",
42
+ "https://pay.google.com",
43
+ "https://js.klarna.com",
44
+ "https://foxycart.tokenoftrust.com",
45
+ ]);
46
+
47
+ /** The declared tenant configuration this module reads: additive prefixes only. */
48
+ export interface ProtectedSurfaceConfig {
49
+ /** Tenant-declared prefixes that are never recorded (`recording.protectedPrefixes`). */
50
+ recording?: { protectedPrefixes?: readonly string[] } | null;
51
+ /** ADR 0013 gated member-area prefixes (`serving.memberPrefixes`). */
52
+ serving?: { memberPrefixes?: readonly string[] } | null;
53
+ }
54
+
55
+ const PREFIX_PATTERN = /^\/[A-Za-z0-9._~-]+(?:\/[A-Za-z0-9._~-]+)*$/;
56
+ const MAX_PREFIXES = 64;
57
+
58
+ /** One prefix in canonical form (leading slash, no trailing slash, lowercase), or null. */
59
+ export function normalizeProtectedPrefix(value: unknown): string | null {
60
+ if (typeof value !== "string" || value.length > 256) return null;
61
+ const trimmed = value.trim().replace(/\/+$/, "");
62
+ if (!PREFIX_PATTERN.test(trimmed)) return null;
63
+ if (trimmed.split("/").some((segment) => segment === "." || segment === "..")) return null;
64
+ return trimmed.toLowerCase();
65
+ }
66
+
67
+ /**
68
+ * The tenant's protected prefixes: its declared `recording.protectedPrefixes` merged with its ADR
69
+ * 0013 member-area prefixes. Additive only: a tenant can protect more, never unprotect a platform
70
+ * root. A malformed entry is dropped (it could only ever have narrowed, never widened, recording).
71
+ */
72
+ export function tenantProtectedPrefixes(config: ProtectedSurfaceConfig | null | undefined): string[] {
73
+ const declared = [
74
+ ...(config?.recording?.protectedPrefixes ?? []),
75
+ ...(config?.serving?.memberPrefixes ?? []),
76
+ ];
77
+ const out = new Set<string>();
78
+ for (const entry of declared) {
79
+ const prefix = normalizeProtectedPrefix(entry);
80
+ if (prefix) out.add(prefix);
81
+ if (out.size >= MAX_PREFIXES) break;
82
+ }
83
+ return [...out].sort();
84
+ }
85
+
86
+ function decodedSegments(path: string): string[] | null {
87
+ const segments: string[] = [];
88
+ for (const raw of path.split("/")) {
89
+ if (raw.length === 0) continue;
90
+ try {
91
+ segments.push(decodeURIComponent(raw).toLowerCase());
92
+ } catch (error) {
93
+ if (error instanceof URIError) return null;
94
+ throw error;
95
+ }
96
+ }
97
+ return segments;
98
+ }
99
+
100
+ /** Is this route root a platform-protected surface? */
101
+ export function isProtectedRoot(segment: string): boolean {
102
+ return PROTECTED_ROUTE_ROOTS.has(segment.toLowerCase());
103
+ }
104
+
105
+ /**
106
+ * May a record capture this tenant-relative route? False for a platform root, a route under any
107
+ * declared prefix, or a path that cannot be decoded (fails closed).
108
+ */
109
+ export function isRecordableRoute(renderPath: string, protectedPrefixes: readonly string[]): boolean {
110
+ const path = renderPath.split(/[?#]/, 1)[0] ?? "";
111
+ const segments = decodedSegments(path);
112
+ if (!segments) return false;
113
+ const first = segments[0];
114
+ if (first !== undefined && isProtectedRoot(first)) return false;
115
+ const canonical = `/${segments.join("/")}`;
116
+ for (const entry of protectedPrefixes) {
117
+ const prefix = normalizeProtectedPrefix(entry);
118
+ if (!prefix) continue;
119
+ if (canonical === prefix || canonical.startsWith(`${prefix}/`)) return false;
120
+ }
121
+ return true;
122
+ }
@@ -11,12 +11,14 @@
11
11
  * - the tenant-scoped reviewer pseudonym (`rv1_…`), derived server-side from that
12
12
  * key, so one browser has unrelated pseudonyms on different stores;
13
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.
14
+ * build, safe page reference, the reviewer pseudonym, whether a session record may
15
+ * capture the page, and an expiry. It is minted at render from server state only
16
+ * and verified again on submission.
16
17
  *
17
18
  * The receipt is evidence, never authority: every submission and renewal re-checks
18
19
  * current preview access. Renderer-safe: WebCrypto only, no control-plane imports.
19
20
  */
21
+ import { isProtectedRoot } from "./protectedSurfaces";
20
22
 
21
23
  export const PREVIEW_REVIEWER_COOKIE = "tot_pf_reviewer";
22
24
  export const RENDER_RECEIPT_PREFIX = "pfr1";
@@ -57,6 +59,11 @@ export interface RenderedDocument {
57
59
 
58
60
  export interface RenderReceiptClaims extends RenderedDocument {
59
61
  reviewer: string;
62
+ /**
63
+ * May a session record capture this document? Decided at render from the route and the
64
+ * tenant's declared protected prefixes; an absent claim reads as false.
65
+ */
66
+ recordable: boolean;
60
67
  /** Issue time of the render that first produced this document identity. */
61
68
  originalIssuedAt: number;
62
69
  issuedAt: number;
@@ -153,6 +160,7 @@ export async function signRenderReceipt(secret: string, claims: RenderReceiptCla
153
160
  p: claims.platformSha,
154
161
  g: claims.pageRef,
155
162
  rv: claims.reviewer,
163
+ rc: claims.recordable,
156
164
  oiat: claims.originalIssuedAt,
157
165
  iat: claims.issuedAt,
158
166
  exp: claims.expiresAt,
@@ -197,6 +205,7 @@ export async function verifyRenderReceipt(
197
205
  platformSha: String(raw.p ?? ""),
198
206
  pageRef: String(raw.g ?? ""),
199
207
  reviewer: raw.rv,
208
+ recordable: raw.rc === true,
200
209
  originalIssuedAt: raw.oiat,
201
210
  issuedAt: raw.iat,
202
211
  expiresAt: raw.exp,
@@ -215,22 +224,13 @@ export function receiptExpiry(nowSeconds: number, capabilityExpiresAt?: number |
215
224
 
216
225
  // ---- safe page reference ---------------------------------------------------
217
226
 
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
227
  const SAFE_SEGMENT = /^[a-z](?:[a-z-]{0,62}[a-z])?$/;
229
228
  const MAX_PAGE_SEGMENTS = 12;
230
229
 
231
230
  /**
232
231
  * 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
232
+ * could carry a dynamic or private value replaced by `[segment]`. Under a protected route root
233
+ * (`protectedSurfaces.ts`) only the root survives. Query and fragment
234
234
  * never survive. A segment is kept only when it is a short lowercase word or
235
235
  * hyphenated words with no digits, no encoding and no dots — so ids, slugs with
236
236
  * numbers, emails, tokens and encoded values are never presumed public.
@@ -248,7 +248,7 @@ export function safePageRef(renderPath: string): string {
248
248
  }
249
249
  const keep = !privateRoot && SAFE_SEGMENT.test(segment);
250
250
  out.push(keep ? segment : "[segment]");
251
- if (i === 0 && keep && PRIVATE_ROOTS.has(segment)) privateRoot = true;
251
+ if (i === 0 && keep && isProtectedRoot(segment)) privateRoot = true;
252
252
  }
253
253
  const ref = `/${out.join("/")}`;
254
254
  return isSafePageRef(ref) ? ref : "page:unresolved";
@@ -11,9 +11,14 @@
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
+ *
15
+ * Every decorated document also carries the server's recording verdict: a route under a platform
16
+ * protected root or a tenant-declared or member-area prefix (`protectedSurfaces.ts`) is minted
17
+ * `recordable:false`, and the client then mounts no recorder for it.
14
18
  */
15
19
  import { HTML_CACHE_POLICY_CAPTURE_PROBE, verifyPreviewToken } from "@tot/public-runtime";
16
20
  import { injectPreviewAnnotations, type ReviewerCookieJar } from "./inject";
21
+ import { isRecordableRoute } from "./protectedSurfaces";
17
22
  import {
18
23
  PLATFORM_SHA_PATTERN,
19
24
  PREVIEW_REVIEWER_COOKIE,
@@ -67,6 +72,8 @@ export interface PreviewAnnotationDecoration {
67
72
  candidatePin: { versionId: string; integrationStage: "candidate" | "staged" } | null;
68
73
  tenantId: string;
69
74
  renderPath: string;
75
+ /** The tenant's declared protected prefixes (`tenantProtectedPrefixes(tenant)`). */
76
+ protectedPrefixes: readonly string[];
70
77
  secret: string | null;
71
78
  nowSeconds: number;
72
79
  cookies: ReviewerCookieJar;
@@ -123,6 +130,7 @@ export async function decoratePreviewAnnotations(
123
130
  platformSha,
124
131
  pageRef: safePageRef(input.renderPath),
125
132
  },
133
+ recordable: isRecordableRoute(input.renderPath, input.protectedPrefixes),
126
134
  capabilityExpiresAt,
127
135
  cookies: input.cookies,
128
136
  pageBase: input.pageBase,
@@ -34,6 +34,7 @@ import {
34
34
  decoratePreviewAnnotations,
35
35
  isPublicationCapture,
36
36
  } from "@/lib/publication/shared/previewAnnotations/renderDecorator";
37
+ import { tenantProtectedPrefixes } from "@/lib/publication/shared/previewAnnotations/protectedSurfaces";
37
38
  import {
38
39
  resolveCustomizationEnv,
39
40
  buildCsp,
@@ -865,6 +866,7 @@ export async function runRenderChain(input: RenderChainInput): Promise<Response>
865
866
  candidatePin: candidatePin ?? null,
866
867
  tenantId: tenant.tenant_id,
867
868
  renderPath,
869
+ protectedPrefixes: tenantProtectedPrefixes(tenant),
868
870
  secret: previewSecret,
869
871
  nowSeconds,
870
872
  cookies: context.cookies,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.14.0",
3
+ "version": "6.14.2",
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",
@@ -10,6 +10,7 @@
10
10
  "exports": {
11
11
  ".": "./src/index.ts",
12
12
  "./v1": "./src/v1/index.ts",
13
+ "./tour": "./src/tour/index.ts",
13
14
  "./primitives": "./src/primitives/index.ts"
14
15
  },
15
16
  "files": [
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Canonical bytes of a published tour: recursively sorted keys, no whitespace, UTF-8. Pure and
3
+ * runtime-neutral (TextEncoder only), so Node and browser builds hash identically.
4
+ */
5
+ export const MAX_TOUR_BYTES = 32 * 1024;
6
+
7
+ function emit(value: unknown): string {
8
+ if (value === null) return "null";
9
+ if (Array.isArray(value)) return `[${value.map((v) => (v === undefined ? "null" : emit(v))).join(",")}]`;
10
+ if (typeof value === "object") {
11
+ const rec = value as Record<string, unknown>;
12
+ const keys = Object.keys(rec)
13
+ .filter((k) => rec[k] !== undefined)
14
+ .sort();
15
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${emit(rec[k])}`).join(",")}}`;
16
+ }
17
+ if (typeof value === "number") {
18
+ if (!Number.isFinite(value)) throw new TypeError("non-finite number");
19
+ return JSON.stringify(value);
20
+ }
21
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
22
+ throw new TypeError("unsupported value");
23
+ }
24
+
25
+ export function canonicalTourBytes(doc: unknown): Uint8Array {
26
+ return new TextEncoder().encode(emit(doc));
27
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./schema.js";
2
+ export { checkText, type TextRefusalCode, type TextRule } from "./sanitize.js";
3
+ export { MAX_TOUR_BYTES } from "./canonical.js";
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Bounded-text sanitization for tour copy. Refuses, never rewrites: what the author typed is what
3
+ * visitors see. Pure and dependency-light; safe in a browser build.
4
+ */
5
+ import { redactText } from "../primitives/redaction.js";
6
+
7
+ export type TextRefusalCode =
8
+ | "TOUR_TEXT_LENGTH"
9
+ | "TOUR_TEXT_BLANK"
10
+ | "TOUR_TEXT_CONTROL"
11
+ | "TOUR_TEXT_MARKUP"
12
+ | "TOUR_TEXT_URL"
13
+ | "TOUR_TEXT_PII";
14
+
15
+ export interface TextRule {
16
+ min: number;
17
+ max: number;
18
+ /** LF is allowed only in body fields. */
19
+ allowLf?: boolean;
20
+ }
21
+
22
+ // Bidi controls, line/paragraph separators, and invisible format characters that split a token.
23
+ const INVISIBLE_RANGES: ReadonlyArray<readonly [number, number]> = [
24
+ [0x00ad, 0x00ad], [0x061c, 0x061c], [0x180e, 0x180e], [0x200b, 0x200f], [0x2028, 0x2029],
25
+ [0x202a, 0x202e], [0x2060, 0x2064], [0x2066, 0x206f], [0xfeff, 0xfeff],
26
+ ];
27
+ const INVISIBLE = {
28
+ test(text: string): boolean {
29
+ for (let i = 0; i < text.length; i += 1) {
30
+ const c = text.charCodeAt(i);
31
+ if (INVISIBLE_RANGES.some(([lo, hi]) => c >= lo && c <= hi)) return true;
32
+ }
33
+ return false;
34
+ },
35
+ };
36
+ const MARKUP = /<[A-Za-z/!?]|&[#A-Za-z0-9]+;/;
37
+ const URL_SCHEME = /(?:^|[^A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]*:\/\//;
38
+ const DANGEROUS_SCHEME = /(?:^|[^A-Za-z0-9+.-])(?:javascript|data|vbscript|blob):/i;
39
+ const WWW_HOST = /(?:^|[^A-Za-z0-9])www\./i;
40
+
41
+ const NONE: ReadonlySet<TextRefusalCode> = new Set();
42
+
43
+ function hasControl(text: string, allowLf: boolean): boolean {
44
+ for (let i = 0; i < text.length; i += 1) {
45
+ const c = text.charCodeAt(i);
46
+ if (c === 0x0a && allowLf) continue;
47
+ if (c < 0x20 || (c >= 0x7f && c <= 0x9f)) return true;
48
+ }
49
+ return INVISIBLE.test(text);
50
+ }
51
+
52
+ /**
53
+ * The first refusal for `value` under `rule`, or null when it is acceptable. `disabled` switches
54
+ * rules off so a tamper test can prove each fixture is caught by exactly its own rule.
55
+ */
56
+ export function checkText(
57
+ value: string,
58
+ rule: TextRule,
59
+ disabled: ReadonlySet<TextRefusalCode> = NONE,
60
+ ): TextRefusalCode | null {
61
+ const text = value.normalize("NFC");
62
+ const on = (code: TextRefusalCode) => !disabled.has(code);
63
+ if (on("TOUR_TEXT_CONTROL") && hasControl(text, rule.allowLf === true)) return "TOUR_TEXT_CONTROL";
64
+ const length = Array.from(text).length;
65
+ if (on("TOUR_TEXT_LENGTH") && (length > rule.max || length < rule.min)) return "TOUR_TEXT_LENGTH";
66
+ if (on("TOUR_TEXT_BLANK") && Array.from(text.trim()).length < rule.min) return "TOUR_TEXT_BLANK";
67
+ if (on("TOUR_TEXT_MARKUP") && MARKUP.test(text)) return "TOUR_TEXT_MARKUP";
68
+ if (on("TOUR_TEXT_URL") && (URL_SCHEME.test(text) || DANGEROUS_SCHEME.test(text) || WWW_HOST.test(text))) {
69
+ return "TOUR_TEXT_URL";
70
+ }
71
+ if (on("TOUR_TEXT_PII")) {
72
+ const { counts } = redactText(text);
73
+ if ((counts.email ?? 0) + (counts.phone ?? 0) + (counts.credential ?? 0) > 0) return "TOUR_TEXT_PII";
74
+ }
75
+ return null;
76
+ }
@@ -0,0 +1,362 @@
1
+ /**
2
+ * `tour-1`: authored tours. Strict objects throughout; the validator refuses and never rewrites;
3
+ * refusals carry a code and a path, never a value. Targets, viewport and page context are validated
4
+ * by the same feedback.v1 functions the annotation bridge uses.
5
+ */
6
+ import type { FeedbackTarget, PageContext, ViewportSnapshot } from "../v1/types.js";
7
+ import { validatePageAt, validateTargetAt, validateViewportAt } from "../v1/guards.js";
8
+ import { isProtectedPath } from "../v1/protectedSurfaces.js";
9
+ import { canonicalTourBytes, MAX_TOUR_BYTES } from "./canonical.js";
10
+ import { checkText, type TextRule } from "./sanitize.js";
11
+
12
+ export const TOUR_SCHEMA_VERSION = "tour-1" as const;
13
+ export const MAX_STEPS = 20;
14
+
15
+ export type TourId = string;
16
+ export type StepId = string;
17
+ export type ViewportBand = "narrow" | "medium" | "wide";
18
+ export type TourTarget = FeedbackTarget;
19
+ export type RecordedActionRef = { recordId: string; seq: number };
20
+
21
+ export type TourTrigger = { kind: "launcher" } | { kind: "first-visit" } | { kind: "link" };
22
+ export type Placement = "auto" | "top" | "bottom" | "left" | "right" | "center";
23
+ export type Corner = "top-start" | "top-end" | "bottom-start" | "bottom-end";
24
+ export type AdvanceRule = { on: "next" } | { on: "dwell"; ms: number } | { on: "target-click" };
25
+
26
+ interface StepBase {
27
+ id: StepId;
28
+ advance: AdvanceRule;
29
+ bandTargets?: Partial<Record<ViewportBand, TourTarget>>;
30
+ hideIn?: ViewportBand[];
31
+ recordedAction?: RecordedActionRef;
32
+ }
33
+
34
+ export interface HighlightStep extends StepBase {
35
+ kind: "highlight";
36
+ target: TourTarget;
37
+ label?: string;
38
+ placement?: Exclude<Placement, "center">;
39
+ tone?: "accent" | "neutral";
40
+ padding?: number;
41
+ onUnresolved?: "skip" | "region";
42
+ }
43
+ export interface ToastStep extends StepBase {
44
+ kind: "toast";
45
+ title?: string;
46
+ body: string;
47
+ target?: TourTarget;
48
+ position?: Corner;
49
+ onUnresolved?: "unanchored";
50
+ }
51
+ export interface ModalStep extends StepBase {
52
+ kind: "modal";
53
+ title: string;
54
+ body: string;
55
+ primaryLabel: string;
56
+ dismissLabel?: string;
57
+ target?: TourTarget;
58
+ placement?: Placement;
59
+ onUnresolved?: "unanchored";
60
+ }
61
+ export interface TextStep extends StepBase {
62
+ kind: "text";
63
+ body: string;
64
+ target: TourTarget;
65
+ placement?: Exclude<Placement, "center">;
66
+ onUnresolved?: "skip" | "unanchored";
67
+ }
68
+ export type TourStep = HighlightStep | ToastStep | ModalStep | TextStep;
69
+
70
+ export interface TourDocument {
71
+ schemaVersion: "tour-1";
72
+ id: TourId;
73
+ revision: number;
74
+ page: PageContext;
75
+ locale?: string;
76
+ title: string;
77
+ trigger: TourTrigger;
78
+ authoredViewport?: ViewportSnapshot;
79
+ steps: TourStep[];
80
+ }
81
+
82
+ type DistributiveOmit<T, K extends keyof never> = T extends unknown ? Omit<T, K> : never;
83
+ export type PublishedTour = Omit<TourDocument, "steps"> & {
84
+ steps: Array<DistributiveOmit<TourStep, "recordedAction">>;
85
+ };
86
+
87
+ export type TourRefusalCode =
88
+ | "TOUR_SHAPE" | "TOUR_SCHEMA_VERSION" | "TOUR_ID" | "TOUR_REVISION" | "TOUR_PAGE" | "TOUR_LOCALE"
89
+ | "TOUR_PAGE_PROTECTED" | "TOUR_STEPS_EMPTY" | "TOUR_STEPS_TOO_MANY" | "TOUR_STEP_ID"
90
+ | "TOUR_STEP_ID_DUPLICATE" | "TOUR_STEP_KIND" | "TOUR_TARGET_REQUIRED" | "TOUR_TARGET_INVALID"
91
+ | "TOUR_TARGET_KIND" | "TOUR_TEXT_LENGTH" | "TOUR_TEXT_BLANK" | "TOUR_TEXT_CONTROL"
92
+ | "TOUR_TEXT_MARKUP" | "TOUR_TEXT_URL" | "TOUR_TEXT_PII" | "TOUR_ADVANCE" | "TOUR_PLACEMENT"
93
+ | "TOUR_FALLBACK" | "TOUR_BAND" | "TOUR_RECORD_REF" | "TOUR_PRIVATE_FIELD" | "TOUR_TOO_LARGE";
94
+
95
+ /** `path` only, never a value. The root of the document is the empty path. */
96
+ export type TourRefusal = { code: TourRefusalCode; path: string };
97
+ export type TourValidation = { ok: true; doc: TourDocument } | { ok: false; refusals: TourRefusal[] };
98
+
99
+ export interface ValidateOptions {
100
+ /** The tenant's declared protected prefixes, added to the platform list. */
101
+ protectedPrefixes?: readonly string[];
102
+ }
103
+
104
+ const MAX_REFUSALS = 20;
105
+ const TOUR_ID = /^tour_[a-z0-9][a-z0-9-]{1,62}$/;
106
+ const STEP_ID = /^s_[a-z0-9][a-z0-9_-]{0,31}$/;
107
+ const LOCALE = /^[a-z]{2,3}(-[A-Z]{2})?$/;
108
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
109
+ const BANDS: readonly string[] = ["narrow", "medium", "wide"];
110
+ const CORNERS: readonly string[] = ["top-start", "top-end", "bottom-start", "bottom-end"];
111
+ const PLACEMENTS: readonly string[] = ["auto", "top", "bottom", "left", "right", "center"];
112
+ const TRIGGERS: readonly string[] = ["launcher", "first-visit", "link"];
113
+
114
+ type Rec = Record<string, unknown>;
115
+ const isRec = (v: unknown): v is Rec => typeof v === "object" && v !== null && !Array.isArray(v);
116
+ const hasOwn = (o: Rec, k: string) => Object.prototype.hasOwnProperty.call(o, k);
117
+ const isInt = (v: unknown, lo: number, hi: number) =>
118
+ typeof v === "number" && Number.isInteger(v) && v >= lo && v <= hi;
119
+
120
+ const BASE_KEYS = ["id", "kind", "advance", "bandTargets", "hideIn", "recordedAction"];
121
+ const STEP_KEYS: Record<string, readonly string[]> = {
122
+ highlight: [...BASE_KEYS, "target", "label", "placement", "tone", "padding", "onUnresolved"],
123
+ toast: [...BASE_KEYS, "title", "body", "target", "position", "onUnresolved"],
124
+ modal: [...BASE_KEYS, "title", "body", "primaryLabel", "dismissLabel", "target", "placement", "onUnresolved"],
125
+ text: [...BASE_KEYS, "body", "target", "placement", "onUnresolved"],
126
+ };
127
+ const FALLBACKS: Record<string, readonly string[]> = {
128
+ highlight: ["skip", "region"],
129
+ toast: ["unanchored"],
130
+ modal: ["unanchored"],
131
+ text: ["skip", "unanchored"],
132
+ };
133
+
134
+ class Collector {
135
+ readonly list: TourRefusal[] = [];
136
+ add(code: TourRefusalCode, path: string): void {
137
+ if (!this.list.some((r) => r.code === code && r.path === path)) this.list.push({ code, path });
138
+ }
139
+ }
140
+
141
+ const join = (base: string, key: string | number) => (base === "" ? String(key) : `${base}.${key}`);
142
+
143
+ function text(c: Collector, value: unknown, path: string, rule: TextRule): void {
144
+ if (typeof value !== "string") {
145
+ c.add("TOUR_SHAPE", path);
146
+ return;
147
+ }
148
+ const refusal = checkText(value, rule);
149
+ if (refusal) c.add(refusal, path);
150
+ }
151
+
152
+ function onlyKeys(c: Collector, obj: Rec, allowed: readonly string[], base: string): void {
153
+ for (const key of Object.keys(obj)) if (!allowed.includes(key)) c.add("TOUR_SHAPE", join(base, key));
154
+ }
155
+
156
+ /** Run the shared feedback.v1 target validator and re-root its findings under `path`. */
157
+ function target(c: Collector, value: unknown, path: string, stepKind?: string): void {
158
+ const found: string[] = [];
159
+ validateTargetAt(value, "$", found);
160
+ for (const finding of found) {
161
+ let rest = finding.slice(1).replace(/\[(\d+)\]/g, ".$1");
162
+ const seg = /^\.structuralPath\.(\d+)$/.exec(rest);
163
+ if (seg && isRec(value)) {
164
+ const item = (value.structuralPath as unknown[])[Number(seg[1])];
165
+ rest += isRec(item) && typeof item.tag === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(item.tag) ? ".childIndex" : ".tag";
166
+ }
167
+ c.add("TOUR_TARGET_INVALID", `${path}${rest}`);
168
+ }
169
+ if (found.length === 0 && isRec(value) && value.kind === "page" && (stepKind === "highlight" || stepKind === "text")) {
170
+ c.add("TOUR_TARGET_KIND", join(path, "kind"));
171
+ }
172
+ }
173
+
174
+ function advance(c: Collector, value: unknown, path: string, hasTarget: boolean): void {
175
+ if (!isRec(value)) {
176
+ c.add("TOUR_SHAPE", path);
177
+ return;
178
+ }
179
+ if (value.on === "next" || value.on === "target-click") {
180
+ onlyKeys(c, value, ["on"], path);
181
+ if (value.on === "target-click" && !hasTarget) c.add("TOUR_ADVANCE", path);
182
+ } else if (value.on === "dwell") {
183
+ onlyKeys(c, value, ["on", "ms"], path);
184
+ if (!isInt(value.ms, 1500, 20000)) c.add("TOUR_ADVANCE", join(path, "ms"));
185
+ } else {
186
+ c.add("TOUR_ADVANCE", join(path, "on"));
187
+ }
188
+ }
189
+
190
+ function step(c: Collector, s: unknown, path: string, mode: "draft" | "published"): void {
191
+ if (!isRec(s)) {
192
+ c.add("TOUR_SHAPE", path);
193
+ return;
194
+ }
195
+ const kind = s.kind;
196
+ const allowedKeys = typeof kind === "string" && hasOwn(STEP_KEYS, kind) ? STEP_KEYS[kind] : undefined;
197
+ if (typeof kind !== "string" || !allowedKeys) {
198
+ c.add("TOUR_STEP_KIND", join(path, "kind"));
199
+ return;
200
+ }
201
+ onlyKeys(c, s, allowedKeys, path);
202
+ const has = (k: string) => hasOwn(s, k) && s[k] !== undefined;
203
+
204
+ const copyRequired = kind === "toast" || kind === "modal" || kind === "text";
205
+ if (copyRequired && !has("body")) c.add("TOUR_SHAPE", join(path, "body"));
206
+ if (kind === "modal") {
207
+ if (!has("title")) c.add("TOUR_SHAPE", join(path, "title"));
208
+ if (!has("primaryLabel")) c.add("TOUR_SHAPE", join(path, "primaryLabel"));
209
+ }
210
+ if (has("title")) text(c, s.title, join(path, "title"), { min: 1, max: kind === "modal" ? 80 : 60 });
211
+ if (has("body")) text(c, s.body, join(path, "body"), { min: 1, max: kind === "modal" ? 600 : 280, allowLf: true });
212
+ if (has("label")) text(c, s.label, join(path, "label"), { min: 1, max: 120 });
213
+ if (has("primaryLabel")) text(c, s.primaryLabel, join(path, "primaryLabel"), { min: 1, max: 24 });
214
+ if (has("dismissLabel")) text(c, s.dismissLabel, join(path, "dismissLabel"), { min: 1, max: 24 });
215
+
216
+ if (has("target")) target(c, s.target, join(path, "target"), kind);
217
+ else if (kind === "highlight" || kind === "text") c.add("TOUR_TARGET_REQUIRED", join(path, "target"));
218
+
219
+ advance(c, s.advance, join(path, "advance"), has("target"));
220
+
221
+ if (has("placement")) {
222
+ const ok =
223
+ typeof s.placement === "string" &&
224
+ PLACEMENTS.includes(s.placement) &&
225
+ (kind === "modal" || s.placement !== "center");
226
+ if (!ok) c.add("TOUR_PLACEMENT", join(path, "placement"));
227
+ }
228
+ if (has("position") && !(typeof s.position === "string" && CORNERS.includes(s.position))) {
229
+ c.add("TOUR_PLACEMENT", join(path, "position"));
230
+ }
231
+ if (has("tone") && s.tone !== "accent" && s.tone !== "neutral") c.add("TOUR_SHAPE", join(path, "tone"));
232
+ if (has("padding") && !isInt(s.padding, 0, 24)) c.add("TOUR_SHAPE", join(path, "padding"));
233
+ if (has("onUnresolved") && !(typeof s.onUnresolved === "string" && (FALLBACKS[kind] ?? []).includes(s.onUnresolved))) {
234
+ c.add("TOUR_FALLBACK", join(path, "onUnresolved"));
235
+ }
236
+
237
+ if (has("bandTargets")) {
238
+ const bt = s.bandTargets;
239
+ if (!isRec(bt)) c.add("TOUR_SHAPE", join(path, "bandTargets"));
240
+ else {
241
+ for (const [band, t] of Object.entries(bt)) {
242
+ const bp = join(join(path, "bandTargets"), band);
243
+ if (!BANDS.includes(band)) c.add("TOUR_BAND", bp);
244
+ else target(c, t, bp, kind);
245
+ }
246
+ }
247
+ }
248
+ if (has("hideIn")) {
249
+ const hide = s.hideIn;
250
+ const hp = join(path, "hideIn");
251
+ if (!Array.isArray(hide)) c.add("TOUR_SHAPE", hp);
252
+ else {
253
+ hide.forEach((b, i) => {
254
+ if (typeof b !== "string" || !BANDS.includes(b)) c.add("TOUR_BAND", join(hp, i));
255
+ });
256
+ const known = hide.filter((b): b is string => typeof b === "string" && BANDS.includes(b));
257
+ if (new Set(known).size !== known.length || new Set(known).size === BANDS.length) c.add("TOUR_BAND", hp);
258
+ }
259
+ }
260
+ if (has("recordedAction")) {
261
+ const rp = join(path, "recordedAction");
262
+ if (mode === "published") c.add("TOUR_PRIVATE_FIELD", rp);
263
+ else {
264
+ const r = s.recordedAction;
265
+ const ok =
266
+ isRec(r) &&
267
+ Object.keys(r).every((k) => k === "recordId" || k === "seq") &&
268
+ typeof r.recordId === "string" &&
269
+ UUID.test(r.recordId) &&
270
+ isInt(r.seq, 0, Number.MAX_SAFE_INTEGER);
271
+ if (!ok) c.add("TOUR_RECORD_REF", rp);
272
+ }
273
+ }
274
+ }
275
+
276
+ function page(c: Collector, value: unknown, opts: ValidateOptions): void {
277
+ const found: string[] = [];
278
+ validatePageAt(value, "$", found);
279
+ if (found.length > 0) {
280
+ for (const f of found) {
281
+ if (f === "$.path") c.add("TOUR_PAGE", "page.path");
282
+ else c.add("TOUR_SHAPE", f === "$" ? "page" : `page${f.slice(1)}`);
283
+ }
284
+ return;
285
+ }
286
+ const p = (value as PageContext).path;
287
+ if (p.includes("[segment]") || p.includes("[rest]")) c.add("TOUR_PAGE", "page.path");
288
+ else if (isProtectedPath(p, opts.protectedPrefixes)) c.add("TOUR_PAGE_PROTECTED", "page.path");
289
+ }
290
+
291
+ function structure(c: Collector, input: unknown, mode: "draft" | "published", opts: ValidateOptions): void {
292
+ if (!isRec(input)) {
293
+ c.add("TOUR_SHAPE", "");
294
+ return;
295
+ }
296
+ onlyKeys(c, input, ["schemaVersion", "id", "revision", "page", "locale", "title", "trigger", "authoredViewport", "steps"], "");
297
+ if (input.schemaVersion !== TOUR_SCHEMA_VERSION) c.add("TOUR_SCHEMA_VERSION", "schemaVersion");
298
+ if (!(typeof input.id === "string" && TOUR_ID.test(input.id))) c.add("TOUR_ID", "id");
299
+ if (!isInt(input.revision, 1, 2 ** 31 - 1)) c.add("TOUR_REVISION", "revision");
300
+ page(c, input.page, opts);
301
+ if (input.locale !== undefined && !(typeof input.locale === "string" && LOCALE.test(input.locale))) {
302
+ c.add("TOUR_LOCALE", "locale");
303
+ }
304
+ text(c, input.title, "title", { min: 1, max: 80 });
305
+ const t = input.trigger;
306
+ if (!isRec(t) || typeof t.kind !== "string" || !TRIGGERS.includes(t.kind) || Object.keys(t).length !== 1) {
307
+ c.add("TOUR_SHAPE", "trigger");
308
+ }
309
+ if (input.authoredViewport !== undefined) {
310
+ const found: string[] = [];
311
+ validateViewportAt(input.authoredViewport, "$", found);
312
+ for (const f of found) c.add("TOUR_SHAPE", `authoredViewport${f.slice(1)}`);
313
+ }
314
+ const steps = input.steps;
315
+ if (!Array.isArray(steps)) {
316
+ c.add("TOUR_SHAPE", "steps");
317
+ return;
318
+ }
319
+ if (steps.length === 0) c.add("TOUR_STEPS_EMPTY", "steps");
320
+ if (steps.length > MAX_STEPS) c.add("TOUR_STEPS_TOO_MANY", "steps");
321
+ const seen = new Set<string>();
322
+ steps.slice(0, MAX_STEPS + 1).forEach((s, i) => {
323
+ const sp = join("steps", i);
324
+ step(c, s, sp, mode);
325
+ if (isRec(s) && s.id !== undefined) {
326
+ if (!(typeof s.id === "string" && STEP_ID.test(s.id))) c.add("TOUR_STEP_ID", join(sp, "id"));
327
+ else if (seen.has(s.id)) c.add("TOUR_STEP_ID_DUPLICATE", join(sp, "id"));
328
+ else seen.add(s.id);
329
+ } else if (isRec(s)) c.add("TOUR_STEP_ID", join(sp, "id"));
330
+ });
331
+ }
332
+
333
+ export function validateTour(input: unknown, mode: "draft" | "published", opts: ValidateOptions = {}): TourValidation {
334
+ const c = new Collector();
335
+ try {
336
+ structure(c, input, mode, opts);
337
+ if (c.list.length === 0) {
338
+ const doc = input as TourDocument;
339
+ if (canonicalTourBytes(publishedProjection(doc)).length > MAX_TOUR_BYTES) c.add("TOUR_TOO_LARGE", "");
340
+ }
341
+ } catch {
342
+ c.list.length = 0;
343
+ c.add("TOUR_SHAPE", "");
344
+ }
345
+ if (c.list.length === 0) return { ok: true, doc: input as TourDocument };
346
+ const refusals = [...c.list]
347
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : a.code < b.code ? -1 : a.code > b.code ? 1 : 0))
348
+ .slice(0, MAX_REFUSALS);
349
+ return { ok: false, refusals };
350
+ }
351
+
352
+ /** The same document with authoring-only fields removed. */
353
+ export function publishedProjection(doc: TourDocument): PublishedTour {
354
+ const steps = doc.steps.map((s) => {
355
+ const rest: Record<string, unknown> = { ...s };
356
+ delete rest.recordedAction;
357
+ return rest;
358
+ });
359
+ return { ...doc, steps } as PublishedTour;
360
+ }
361
+
362
+ export { canonicalTourBytes } from "./canonical.js";
@@ -112,71 +112,88 @@ function header(v: Rec, kind: string, where: string, out: string[]): void {
112
112
  if (v.kind !== kind) out.push(`${where}.kind`);
113
113
  }
114
114
 
115
- function validateEvidenceAt(value: unknown, where: string, out: string[]): void {
116
- if (!isRecord(value)) {
117
- out.push(where);
115
+ /** The target object shared by evidence, annotations and tours: one schema, many importers. */
116
+ export function validateTargetAt(t: unknown, tw: string, out: string[]): void {
117
+ if (!isRecord(t)) {
118
+ out.push(tw);
118
119
  return;
119
120
  }
120
- onlyKeys(value, ["schemaVersion", "kind", "target", "viewport", "page", "selection", "selectors", "domExcerpt"], where, out);
121
- header(value, "feedback.target", where, out);
122
-
123
- const t = value.target;
124
- const tw = `${where}.target`;
125
- if (!isRecord(t)) out.push(tw);
126
- else {
127
- onlyKeys(t, ["kind", "precision", "sourceAnchor", "structuralPath", "bounds", "relativeRegion"], tw, out);
128
- if (!oneOf(t.kind, TARGET_KINDS)) out.push(`${tw}.kind`);
129
- if (!oneOf(t.precision, PRECISIONS)) out.push(`${tw}.precision`);
130
- if (t.kind === "page" && t.precision !== "page") out.push(`${tw}.precision`);
131
- if (t.precision === "source" && t.sourceAnchor === undefined) out.push(`${tw}.sourceAnchor`);
132
- if (t.sourceAnchor !== undefined && !(typeof t.sourceAnchor === "string" && ANCHOR.test(t.sourceAnchor))) {
133
- out.push(`${tw}.sourceAnchor`);
134
- }
135
- if (t.structuralPath !== undefined) {
136
- const p = t.structuralPath;
137
- if (!Array.isArray(p) || p.length < 1 || p.length > MAX_PATH_SEGMENTS) out.push(`${tw}.structuralPath`);
138
- else
139
- p.forEach((seg: unknown, i) => {
140
- const sw = `${tw}.structuralPath[${i}]`;
141
- if (
142
- !isRecord(seg) ||
143
- Object.keys(seg).some((k) => k !== "tag" && k !== "childIndex") ||
144
- !(typeof seg.tag === "string" && TAG.test(seg.tag)) ||
145
- !int(seg.childIndex, 0, 9999)
146
- ) {
147
- out.push(sw);
148
- }
149
- });
121
+ onlyKeys(t, ["kind", "precision", "sourceAnchor", "structuralPath", "bounds", "relativeRegion"], tw, out);
122
+ if (!oneOf(t.kind, TARGET_KINDS)) out.push(`${tw}.kind`);
123
+ if (!oneOf(t.precision, PRECISIONS)) out.push(`${tw}.precision`);
124
+ if (t.kind === "page" && t.precision !== "page") out.push(`${tw}.precision`);
125
+ if (t.precision === "source" && t.sourceAnchor === undefined) out.push(`${tw}.sourceAnchor`);
126
+ if (t.kind === "region" && t.bounds === undefined) out.push(`${tw}.bounds`);
127
+ if (
128
+ t.sourceAnchor !== undefined &&
129
+ !(typeof t.sourceAnchor === "string" && ANCHOR.test(t.sourceAnchor) && !t.sourceAnchor.includes("..") && !t.sourceAnchor.includes("//"))
130
+ ) {
131
+ out.push(`${tw}.sourceAnchor`);
132
+ }
133
+ if (t.structuralPath !== undefined) {
134
+ const p = t.structuralPath;
135
+ if (!Array.isArray(p) || p.length < 1 || p.length > MAX_PATH_SEGMENTS) out.push(`${tw}.structuralPath`);
136
+ else
137
+ p.forEach((seg: unknown, i) => {
138
+ const sw = `${tw}.structuralPath[${i}]`;
139
+ if (
140
+ !isRecord(seg) ||
141
+ Object.keys(seg).some((k) => k !== "tag" && k !== "childIndex") ||
142
+ !(typeof seg.tag === "string" && TAG.test(seg.tag)) ||
143
+ !int(seg.childIndex, 0, 9999)
144
+ ) {
145
+ out.push(sw);
146
+ }
147
+ });
148
+ }
149
+ if (t.bounds !== undefined) rect(t.bounds, -COORD_LIMIT, COORD_LIMIT, `${tw}.bounds`, out);
150
+ if (t.relativeRegion !== undefined) {
151
+ const before = out.length;
152
+ rect(t.relativeRegion, 0, 1, `${tw}.relativeRegion`, out);
153
+ const r = t.relativeRegion;
154
+ if (out.length === before && isRecord(r) && ((r.x as number) + (r.width as number) > 1.000001 || (r.y as number) + (r.height as number) > 1.000001)) {
155
+ out.push(`${tw}.relativeRegion`);
150
156
  }
151
- if (t.bounds !== undefined) rect(t.bounds, -COORD_LIMIT, COORD_LIMIT, `${tw}.bounds`, out);
152
- if (t.relativeRegion !== undefined) rect(t.relativeRegion, 0, 1, `${tw}.relativeRegion`, out);
153
157
  }
158
+ }
154
159
 
155
- const v = value.viewport;
156
- const vw = `${where}.viewport`;
157
- if (!isRecord(v)) out.push(vw);
158
- else {
159
- onlyKeys(v, ["width", "height", "scrollX", "scrollY", "scale", "devicePixelRatio"], vw, out);
160
- if (!int(v.width, 1, 20_000)) out.push(`${vw}.width`);
161
- if (!int(v.height, 1, 20_000)) out.push(`${vw}.height`);
162
- if (!num(v.scrollX, 0, 10_000_000)) out.push(`${vw}.scrollX`);
163
- if (!num(v.scrollY, 0, 10_000_000)) out.push(`${vw}.scrollY`);
164
- if (!num(v.scale, 0, 10, true)) out.push(`${vw}.scale`);
165
- if (!num(v.devicePixelRatio, 0, 10, true)) out.push(`${vw}.devicePixelRatio`);
160
+ export function validateViewportAt(v: unknown, vw: string, out: string[]): void {
161
+ if (!isRecord(v)) {
162
+ out.push(vw);
163
+ return;
166
164
  }
165
+ onlyKeys(v, ["width", "height", "scrollX", "scrollY", "scale", "devicePixelRatio"], vw, out);
166
+ if (!int(v.width, 1, 20_000)) out.push(`${vw}.width`);
167
+ if (!int(v.height, 1, 20_000)) out.push(`${vw}.height`);
168
+ if (!num(v.scrollX, 0, 10_000_000)) out.push(`${vw}.scrollX`);
169
+ if (!num(v.scrollY, 0, 10_000_000)) out.push(`${vw}.scrollY`);
170
+ if (!num(v.scale, 0, 10, true)) out.push(`${vw}.scale`);
171
+ if (!num(v.devicePixelRatio, 0, 10, true)) out.push(`${vw}.devicePixelRatio`);
172
+ }
167
173
 
168
- if (value.page !== undefined) {
169
- const pg = value.page;
170
- const pw = `${where}.page`;
171
- if (!isRecord(pg)) out.push(pw);
172
- else {
173
- onlyKeys(pg, ["path", "routeId"], pw, out);
174
- if (!(typeof pg.path === "string" && pg.path.length <= PAGE_PATH_MAX && PAGE_PATH.test(pg.path) && !hasForbiddenControl(pg.path))) {
175
- out.push(`${pw}.path`);
176
- }
177
- if (pg.routeId !== undefined && !(typeof pg.routeId === "string" && ROUTE_ID.test(pg.routeId))) out.push(`${pw}.routeId`);
178
- }
174
+ export function validatePageAt(pg: unknown, pw: string, out: string[]): void {
175
+ if (!isRecord(pg)) {
176
+ out.push(pw);
177
+ return;
178
+ }
179
+ onlyKeys(pg, ["path", "routeId"], pw, out);
180
+ if (!(typeof pg.path === "string" && pg.path.length <= PAGE_PATH_MAX && PAGE_PATH.test(pg.path) && !hasForbiddenControl(pg.path))) {
181
+ out.push(`${pw}.path`);
182
+ }
183
+ if (pg.routeId !== undefined && !(typeof pg.routeId === "string" && ROUTE_ID.test(pg.routeId))) out.push(`${pw}.routeId`);
184
+ }
185
+
186
+ function validateEvidenceAt(value: unknown, where: string, out: string[]): void {
187
+ if (!isRecord(value)) {
188
+ out.push(where);
189
+ return;
179
190
  }
191
+ onlyKeys(value, ["schemaVersion", "kind", "target", "viewport", "page", "selection", "selectors", "domExcerpt"], where, out);
192
+ header(value, "feedback.target", where, out);
193
+
194
+ validateTargetAt(value.target, `${where}.target`, out);
195
+ validateViewportAt(value.viewport, `${where}.viewport`, out);
196
+ if (value.page !== undefined) validatePageAt(value.page, `${where}.page`, out);
180
197
 
181
198
  if (value.selection !== undefined) {
182
199
  const s = value.selection;
@@ -1,2 +1,3 @@
1
1
  export * from "./types.js";
2
2
  export * from "./guards.js";
3
+ export * from "./protectedSurfaces.js";
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Routes where no recorder, annotation or tour ever runs: money, identity, account and operator
3
+ * surfaces. One list, imported by every feedback feature that must refuse such a page. A tenant
4
+ * may add prefixes; it can never remove a platform root.
5
+ */
6
+ export const PROTECTED_ROOTS: readonly string[] = [
7
+ "account", "accounts", "admin", "api", "auth", "cart", "checkout", "cockpit", "customer",
8
+ "customers", "invite", "invites", "login", "logout", "member", "members", "my", "order",
9
+ "orders", "pay", "payment", "password", "profile", "register", "reset", "signup",
10
+ "subscription", "subscriptions", "unsubscribe", "verify",
11
+ ];
12
+
13
+ const PLATFORM = new Set(PROTECTED_ROOTS);
14
+
15
+ /** The first path segment, lowercased and percent-decoded; null when it cannot be decoded. */
16
+ export function firstSegment(path: string): string | null {
17
+ const raw = path.split("/").find((s) => s.length > 0) ?? "";
18
+ try {
19
+ return decodeURIComponent(raw).toLowerCase();
20
+ } catch (error) {
21
+ if (error instanceof URIError) return null;
22
+ throw error;
23
+ }
24
+ }
25
+
26
+ /** True when `path`'s first segment is a platform root or one of the tenant's declared prefixes. */
27
+ export function isProtectedPath(path: string, tenantPrefixes: readonly string[] = []): boolean {
28
+ const first = firstSegment(path);
29
+ if (first === null) return true;
30
+ if (PLATFORM.has(first)) return true;
31
+ return tenantPrefixes.some((p) => firstSegment(p) === first);
32
+ }
@@ -715,6 +715,20 @@ export interface TenantConfig {
715
715
  * while a fresh one is fetched. All in seconds. Absent ⇒ {@link DEFAULT_HTML_CACHE_POLICY}.
716
716
  */
717
717
  htmlCachePolicy?: HtmlCachePolicy;
718
+ /**
719
+ * Gated member-area route prefixes (ADR 0013: member areas are path-scoped), e.g.
720
+ * `["/club"]`. Each is routed to the Worker origin with caching off, and a preview
721
+ * session record never captures a page under one.
722
+ */
723
+ memberPrefixes?: string[];
724
+ };
725
+ /**
726
+ * Preview session recording (feedback record contract §6). `protectedPrefixes` names
727
+ * tenant routes a record never captures, in addition to the platform's protected roots
728
+ * and `serving.memberPrefixes`. Additive only: it cannot unprotect a platform root.
729
+ */
730
+ recording?: {
731
+ protectedPrefixes?: string[];
718
732
  };
719
733
  /**
720
734
  * Catalog serving (ADR 0033). The store's own `content/catalog/` files are the