Skip to content

Commit e623031

Browse files
fix(studio): a sealed preview's element reads are bounded, and a frame with no agent answers at once (#8055)
* fix(studio): a sealed preview's element reads are bounded, and a frame with no agent answers at once * fix(studio): a sealed preview's sources and style names are bounded too, never cut
1 parent e95cdf7 commit e623031

6 files changed

Lines changed: 142 additions & 27 deletions

File tree

‎packages/core/src/runtime/editingHandles.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,14 @@ describe("element handles over the editing port", () => {
164164
}
165165
});
166166

167+
it("leaves out an id, selector or attribute name it would have to cut, and says so", async () => {
168+
const long = "x".repeat(MAX_ELEMENT_VALUE + 1);
169+
document.body.innerHTML = `<div id="${long}" data-${long}="1" data-kept="2"></div>`;
170+
const described = await describeOne(document.querySelector("div")!);
171+
expect(described).toMatchObject({ id: null, selector: null, truncated: true });
172+
expect(described.attributes.map(([name]) => name)).toEqual(["id", "data-kept"]);
173+
});
174+
167175
it("cuts long values, keeps only a long data: value's header, and leaves script and style text out", async () => {
168176
const long = "x".repeat(MAX_ELEMENT_VALUE + 50);
169177
document.body.innerHTML = `<div class="card" title="${long}" style="--note: ${long}">
@@ -246,6 +254,28 @@ describe("element handles over the editing port", () => {
246254
expect(top!.parent).not.toBeNull();
247255
});
248256

257+
it("describes no element whose inherited source it would have to cut, and leaves out a style name it would", async () => {
258+
const long = "x".repeat(MAX_ELEMENT_VALUE + 1);
259+
document.body.innerHTML = `<div data-composition-file="${long}.html"><p class="t"></p></div>
260+
<div data-composition-id="${long}"><p class="t"></p></div>
261+
<div data-hf-original-composition-id="${long}" data-composition-id="c"><p class="t"></p></div>`;
262+
for (const p of document.querySelectorAll("p")) expect(await describeOne(p)).toBeNull();
263+
const { result } = await ask<never>("query", { selector: ".t" });
264+
expect(result).toEqual({ matches: [], truncated: true });
265+
266+
document.body.innerHTML = `<div data-composition-file="${long}.html"><i class="u"></i></div><i class="u"></i>`;
267+
const later = document.querySelectorAll("i")[1]!;
268+
later.style.setProperty(`--${long}`, "1");
269+
later.style.setProperty("left", "4px");
270+
const described = await describeOne(later);
271+
expect(described).toMatchObject({
272+
selector: ".u",
273+
matchesBefore: null,
274+
inlineStyles: { left: "4px" },
275+
truncated: true,
276+
});
277+
});
278+
249279
it("answers a query with each match's handle and source, in document order", async () => {
250280
document.body.innerHTML = `<p class="t" id="a"></p>
251281
<div data-composition-file="cards.html"><p class="t" id="b"></p></div>`;

‎packages/core/src/runtime/editingHandles.ts‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,15 @@ const sameSource = (a: EditingElementSource, b: EditingElementSource) =>
6565
a.compositionId === b.compositionId &&
6666
a.originalCompositionId === b.originalCompositionId;
6767

68+
/** The element's source when every field fits the port; null otherwise, since a cut path or id names another file. */
69+
function boundedSource(element: Element): EditingElementSource | null {
70+
const source = readElementSource(element);
71+
const fields = [source.file, source.compositionId, source.originalCompositionId];
72+
return fields.every((field) => field === null || field.length <= MAX_ELEMENT_VALUE)
73+
? source
74+
: null;
75+
}
76+
6877
function matchesBefore(element: Element, selector: string | undefined) {
6978
if (!selector?.startsWith(".")) return null;
7079
const groups: Array<{ source: EditingElementSource; count: number }> = [];
@@ -76,7 +85,8 @@ function matchesBefore(element: Element, selector: string | undefined) {
7685
}
7786
for (const match of matches) {
7887
if (match === element) return groups;
79-
const source = readElementSource(match);
88+
const source = boundedSource(match);
89+
if (!source) return null;
8090
const group = groups.find((entry) => sameSource(entry.source, source));
8191
if (group) group.count += 1;
8292
else if (groups.push({ source, count: 1 }) > MAX_SOURCE_GROUPS) return null;
@@ -105,14 +115,19 @@ function inlineStyles(element: Element, state: Cut): Record<string, string> {
105115
if (declared.length > MAX_ELEMENT_ENTRIES) state.truncated = true;
106116
for (let index = 0; index < Math.min(declared.length, MAX_ELEMENT_ENTRIES); index += 1) {
107117
const name = declared.item(index);
118+
if (name.length > MAX_ELEMENT_VALUE) {
119+
state.truncated = true;
120+
continue;
121+
}
108122
styles[name] = cut(declared.getPropertyValue(name), MAX_ELEMENT_VALUE, state, true);
109123
}
110124
return styles;
111125
}
112126

113127
function attributes(element: Element, state: Cut): EditingElementDescription["attributes"] {
114-
const kept = Array.from(element.attributes).filter((attribute) => attribute.name !== "style");
115-
if (kept.length > MAX_ELEMENT_ENTRIES) state.truncated = true;
128+
const named = Array.from(element.attributes).filter((attribute) => attribute.name !== "style");
129+
const kept = named.filter((attribute) => attribute.name.length <= MAX_ELEMENT_VALUE);
130+
if (kept.length < named.length || kept.length > MAX_ELEMENT_ENTRIES) state.truncated = true;
116131
return kept
117132
.slice(0, MAX_ELEMENT_ENTRIES)
118133
.map((attribute) => [attribute.name, cut(attribute.value, MAX_ELEMENT_VALUE, state, true)]);
@@ -137,22 +152,27 @@ export function elementHit(element: Element): EditingElementHit {
137152
const rect = element.getBoundingClientRect();
138153
return {
139154
handle: handleFor(element),
140-
tag: element.tagName.toLowerCase(),
155+
tag: element.tagName.toLowerCase().slice(0, MAX_ELEMENT_VALUE),
141156
rect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
142157
};
143158
}
144159

145-
function describeElement(element: Element): EditingElementDescription {
146-
const selector = buildStableSelector(element);
160+
const whole = (value: string | undefined) =>
161+
value && value.length <= MAX_ELEMENT_VALUE ? value : undefined;
162+
163+
function describeElement(element: Element): EditingElementDescription | null {
164+
const source = boundedSource(element);
165+
if (!source) return null;
166+
const selector = whole(buildStableSelector(element));
147167
const state: Cut = { truncated: false };
148168
return {
149169
...elementHit(element),
150-
label: buildElementLabel(element),
170+
label: buildElementLabel(element).slice(0, MAX_ELEMENT_VALUE),
151171
parent: element.parentElement ? handleFor(element.parentElement) : null,
152-
id: element.id || null,
172+
id: whole(element.id) ?? null,
153173
selector: selector ?? null,
154174
matchesBefore: matchesBefore(element, selector),
155-
source: readElementSource(element),
175+
source,
156176
locked: element.closest("[data-timeline-locked]") !== null,
157177
attributes: attributes(element, state),
158178
inlineStyles: inlineStyles(element, state),
@@ -195,9 +215,12 @@ export function queryElements(selector: string): {
195215
truncated: boolean;
196216
} {
197217
const matches: EditingElementMatch[] = [];
218+
let truncated = false;
198219
for (const element of document.querySelectorAll(selector)) {
199220
if (matches.length === MAX_QUERY_MATCHES) return { matches, truncated: true };
200-
matches.push({ handle: handleFor(element), source: readElementSource(element) });
221+
const source = boundedSource(element);
222+
if (source) matches.push({ handle: handleFor(element), source });
223+
else truncated = true;
201224
}
202-
return { matches, truncated: false };
225+
return { matches, truncated };
203226
}

‎packages/studio/src/player/lib/previewChannel.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ describe("previewEditingClient", () => {
120120
expect(Date.now() - started).toBeLessThan(AGENT_PROBE_MS + 500);
121121
});
122122

123+
it("answers a frame whose runtime never came at once, rather than after another probe", async () => {
124+
const { iframe } = opaqueFrame();
125+
const started = Date.now();
126+
await previewSeekPainted(iframe, 15_000);
127+
expect(Date.now() - started).toBeGreaterThanOrEqual(AGENT_PROBE_MS - 50);
128+
const again = Date.now();
129+
await previewSeekPainted(iframe, 15_000);
130+
expect(Date.now() - again).toBeLessThan(100);
131+
});
132+
123133
it("returns the runtime's manifest only when its reply has the manifest's shape", async () => {
124134
const manifest = { clips: [], durationInFrames: 30, scenes: [] };
125135
let reply: unknown = { clipManifest: manifest };

‎packages/studio/src/player/lib/previewChannel.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,15 @@ export function setFrameLoopStart(iframe: HTMLIFrameElement, seconds: number | n
5454

5555
export const AGENT_PROBE_MS = 1_000;
5656

57+
const agents = new WeakMap<EditingPortClient, boolean>();
58+
5759
async function agentConnected(client: EditingPortClient): Promise<boolean> {
60+
const known = agents.get(client);
61+
if (known !== undefined) return known;
62+
client.ready.then(
63+
() => agents.set(client, true),
64+
() => agents.set(client, false),
65+
);
5866
let timer: ReturnType<typeof setTimeout> | undefined;
5967
const probe = new Promise<boolean>(
6068
(resolve) => (timer = setTimeout(resolve, AGENT_PROBE_MS, false)),
@@ -67,6 +75,7 @@ async function agentConnected(client: EditingPortClient): Promise<boolean> {
6775
probe,
6876
]);
6977
clearTimeout(timer);
78+
if (!agents.has(client)) agents.set(client, connected);
7079
return connected;
7180
}
7281

‎packages/studio/src/player/lib/previewElements.test.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
// @vitest-environment happy-dom
22

33
import { afterEach, describe, expect, it, vi } from "vitest";
4-
import type { EditingElementDescription } from "@hyperframes/core/runtime/editing-port";
4+
import {
5+
MAX_ELEMENT_ENTRIES,
6+
MAX_ELEMENT_TEXT,
7+
MAX_ELEMENT_VALUE,
8+
type EditingElementDescription,
9+
} from "@hyperframes/core/runtime/editing-port";
510
import {
611
describePreviewElements,
712
previewElementSelectorIndex,
@@ -93,6 +98,34 @@ describe("readPreviewElement", () => {
9398
expect(readPreviewElement(bad)).toBeNull();
9499
}
95100
});
101+
102+
it("refuses a description longer anywhere than the runtime ever sends one", () => {
103+
const value = "x".repeat(MAX_ELEMENT_VALUE);
104+
const atLimit = described(1, { selector: value, id: value, attributes: [["src", value]] });
105+
expect(readPreviewElement(atLimit)).toEqual(atLimit);
106+
const over = `${value}x`;
107+
const text = "y".repeat(MAX_ELEMENT_TEXT + 1);
108+
const many = Array.from({ length: MAX_ELEMENT_ENTRIES + 1 }, (_, i) => [`data-${i}`, ""]);
109+
for (const bad of [
110+
described(1, { selector: over }),
111+
described(1, { id: over }),
112+
described(1, { tag: over }),
113+
described(1, { label: over }),
114+
described(1, { attributes: [["src", over]] }),
115+
described(1, { attributes: [[`data-${over}`, "1"]] }),
116+
described(1, { attributes: many as never }),
117+
described(1, { inlineStyles: { left: over } }),
118+
described(1, { inlineStyles: { [`--${over}`]: "1" } }),
119+
described(1, { source: { ...NO_SOURCE, file: over } }),
120+
described(1, { source: { ...NO_SOURCE, compositionId: over } }),
121+
described(1, { source: { ...NO_SOURCE, originalCompositionId: over } }),
122+
described(1, { matchesBefore: [{ source: { ...NO_SOURCE, file: over }, count: 1 }] }),
123+
described(1, { text }),
124+
described(1, { children: [{ text }] }),
125+
]) {
126+
expect(readPreviewElement(bad)).toBeNull();
127+
}
128+
});
96129
});
97130

98131
describe("element requests over an opaque frame's port", () => {

‎packages/studio/src/player/lib/previewElements.ts‎

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import {
77
MAX_DESCRIBE_HANDLES,
88
MAX_DRAFT_PX,
99
MAX_ELEMENT_ENTRIES,
10+
MAX_ELEMENT_TEXT,
1011
MAX_ELEMENT_VALUE,
1112
MAX_GEOMETRY_CHILDREN,
1213
MAX_SNAP_TARGETS,
14+
MAX_SOURCE_GROUPS,
1315
type EditingElementBox,
1416
type EditingElementDescription,
1517
type EditingElementGeometry,
@@ -33,48 +35,57 @@ export const isFields = (value: unknown): value is Fields =>
3335
export const isHandle = (value: unknown) =>
3436
typeof value === "string" && EDITING_ELEMENT_HANDLE.test(value);
3537
const isText = (value: unknown) => typeof value === "string";
36-
const isTextOrNull = (value: unknown) => value === null || typeof value === "string";
38+
const isValue = (value: unknown) => isText(value) && (value as string).length <= MAX_ELEMENT_VALUE;
39+
const isLongText = (value: unknown) =>
40+
isText(value) && (value as string).length <= MAX_ELEMENT_TEXT;
41+
const isValueOrNull = (value: unknown) => value === null || isValue(value);
42+
const isEntries = (value: unknown): value is unknown[] =>
43+
Array.isArray(value) && value.length <= MAX_ELEMENT_ENTRIES;
3744
const isCount = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0;
3845

3946
const isSource = (value: unknown): value is EditingElementSource =>
4047
isFields(value) &&
41-
isTextOrNull(value.file) &&
42-
isTextOrNull(value.compositionId) &&
43-
isTextOrNull(value.originalCompositionId);
48+
isValueOrNull(value.file) &&
49+
isValueOrNull(value.compositionId) &&
50+
isValueOrNull(value.originalCompositionId);
4451

45-
const isTextRecord = (value: unknown) => isFields(value) && Object.values(value).every(isText);
52+
const isStyles = (value: unknown) =>
53+
isFields(value) &&
54+
isEntries(Object.keys(value)) &&
55+
Object.entries(value).every(([name, style]) => isValue(name) && isValue(style));
4656

4757
function hasPlainFields(value: Fields): boolean {
4858
const { matchesBefore, attributes, children } = value;
4959
const groupsOk =
5060
matchesBefore === null ||
5161
(Array.isArray(matchesBefore) &&
62+
matchesBefore.length <= MAX_SOURCE_GROUPS &&
5263
matchesBefore.every((g) => isFields(g) && isSource(g.source) && isCount(g.count)));
5364
const attributesOk =
54-
Array.isArray(attributes) &&
55-
attributes.every((a) => Array.isArray(a) && a.length === 2 && a.every(isText));
65+
isEntries(attributes) &&
66+
attributes.every((a) => Array.isArray(a) && a.length === 2 && a.every(isValue));
5667
const childrenOk =
57-
Array.isArray(children) &&
58-
children.every((c) => isFields(c) && (isHandle(c.handle) || isText(c.text)));
68+
isEntries(children) &&
69+
children.every((c) => isFields(c) && (isHandle(c.handle) || isLongText(c.text)));
5970
return groupsOk && attributesOk && childrenOk && typeof value.truncated === "boolean";
6071
}
6172

6273
const isRect = (value: unknown) =>
6374
isFields(value) && [value.x, value.y, value.width, value.height].every(Number.isFinite);
6475

6576
function readHit(value: unknown): PreviewElementHit | null {
66-
if (!isFields(value) || !isHandle(value.handle) || !isText(value.tag)) return null;
77+
if (!isFields(value) || !isHandle(value.handle) || !isValue(value.tag)) return null;
6778
return isRect(value.rect) ? (value as unknown as PreviewElementHit) : null;
6879
}
6980

7081
/** Frame data checked against `EditingElementDescription`; null when any field is off. */
7182
export function readPreviewElement(value: unknown): PreviewElement | null {
7283
if (!readHit(value) || !isFields(value)) return null;
7384
if (value.parent !== null && !isHandle(value.parent)) return null;
74-
if (value.label !== undefined && !isText(value.label)) return null;
75-
if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
85+
if (value.label !== undefined && !isValue(value.label)) return null;
86+
if (!isValueOrNull(value.id) || !isValueOrNull(value.selector)) return null;
7687
if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
77-
if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
88+
if (!isStyles(value.inlineStyles) || !isLongText(value.text)) return null;
7889
return hasPlainFields(value) ? (value as unknown as PreviewElement) : null;
7990
}
8091

@@ -183,8 +194,7 @@ const isSourceBox = (value: unknown) =>
183194
isSizeOrNull(value.declaredWidth) &&
184195
isSizeOrNull(value.declaredHeight));
185196

186-
const isClipPath = (value: unknown) =>
187-
value === null || (isText(value) && (value as string).length <= MAX_ELEMENT_VALUE);
197+
const isClipPath = isValueOrNull;
188198

189199
const isBox = (value: unknown): value is EditingElementBox =>
190200
isFields(value) &&

0 commit comments

Comments
 (0)