@tokenoftrust/storefront-runner 6.13.2 → 6.14.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tokenoftrust/storefront-runner",
3
- "version": "6.13.2",
3
+ "version": "6.14.1",
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
+ }