mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-29 19:34:29 +01:00
make-pdf blocks javascript: links written with tabs or entity letters, plus four small fixes (GST-3641) (#4848)
make-pdf now removes `javascript:` links in untrusted Markdown even when the scheme is split by a tab or line break or written with entity letters, and it fixes curly quotes at the start of a paragraph, SVG sizing, one learnings crash and one lost timeline event. Why: these spellings still produced live links in the HTML make-pdf prints, and the other four bugs were verified on main by an independent check. Nothing for readers to do; ordinary Markdown prints the same apart from opening quotes, which now curl the right way. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p2/outside-voice#1 reader=outside-voice Review-Finding: p2/outside-voice#3 reader=outside-voice Review-Finding: p3/red-team#1 reader=red-team
This commit is contained in:
1 parent
4ec576aaa5
commit
f5b42d682c
13 files changed
+366
-22
No files matched your search
@@ -89,6 +89,9 @@ if (j.source && !ALLOWED_SOURCES.includes(j.source)) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// files is a list of paths; one path given as a string is stored as a one-item list.
|
||||
if (typeof j.files === 'string') j.files = [j.files];
|
||||
|
||||
// Content sanitization: shared injection patterns (lib/jsonl-store.ts, D2A) —
|
||||
// one audited list across learnings + decisions, no drift.
|
||||
if (j.insight && hasInjection(j.insight)) {
|
||||
|
||||
@@ -153,6 +153,7 @@ for (const taggedLine of lines) {
|
||||
const line = tabIndex === -1 ? taggedLine : taggedLine.slice(tabIndex + 1);
|
||||
const e = JSON.parse(line);
|
||||
if (!e.key || !e.type) continue;
|
||||
e.files = Array.isArray(e.files) ? e.files.map(String) : typeof e.files === 'string' ? [e.files] : [];
|
||||
|
||||
// Apply confidence decay: observed/inferred lose 1pt per 30 days
|
||||
let conf = e.confidence || 5;
|
||||
@@ -182,12 +183,16 @@ for (const taggedLine of lines) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Dedup: latest winner per key+type
|
||||
// Dedup: latest winner per key+type. This project's own entry always beats
|
||||
// another project's entry for the same key+type, whatever their dates: other
|
||||
// projects add learnings, they never replace this project's answer.
|
||||
const seen = new Map();
|
||||
for (const e of entries) {
|
||||
const dk = e.key + '|' + e.type;
|
||||
const existing = seen.get(dk);
|
||||
if (!existing || new Date(e.ts) > new Date(existing.ts)) {
|
||||
const ownBeatsCross = existing && existing._crossProject && !e._crossProject;
|
||||
const sameOrigin = existing && existing._crossProject === e._crossProject;
|
||||
if (!existing || ownBeatsCross || (sameOrigin && new Date(e.ts) > new Date(existing.ts))) {
|
||||
seen.set(dk, e);
|
||||
}
|
||||
}
|
||||
@@ -202,7 +207,7 @@ if (type) results = results.filter(e => e.type === type);
|
||||
// must not become a sort key.
|
||||
const tokenHits = new Map();
|
||||
if (queryTokens.length > 0) results = results.filter(e => {
|
||||
const haystacks = [String(e.key || '').toLowerCase(), String(e.insight || '').toLowerCase(), ...(Array.isArray(e.files) ? e.files : []).map(f => String(f).toLowerCase())];
|
||||
const haystacks = [String(e.key || '').toLowerCase(), String(e.insight || '').toLowerCase(), ...e.files.map(f => f.toLowerCase())];
|
||||
const hits = [...new Set(queryTokens)].filter(tok => haystacks.some(h => h.includes(tok))).length;
|
||||
tokenHits.set(e, hits);
|
||||
return hits > 0;
|
||||
@@ -245,8 +250,8 @@ for (const [t, arr] of Object.entries(byType)) {
|
||||
console.log('## ' + t.charAt(0).toUpperCase() + t.slice(1) + 's');
|
||||
for (const e of arr) {
|
||||
const cross = e._crossProject ? ' [cross-project]' : '';
|
||||
const files = e.files?.length ? ' (files: ' + e.files.join(', ') + ')' : '';
|
||||
console.log('- [' + e.key + '] (confidence: ' + e._effectiveConfidence + '/10, ' + e.source + ', ' + (e.ts || '').split('T')[0] + ')' + cross);
|
||||
const files = e.files.length ? ' (files: ' + e.files.join(', ') + ')' : '';
|
||||
console.log('- [' + e.key + '] (confidence: ' + e._effectiveConfidence + '/10, ' + e.source + ', ' + String(e.ts || '').split('T')[0] + ')' + cross);
|
||||
console.log(' ' + e.insight + files);
|
||||
}
|
||||
console.log('');
|
||||
|
||||
@@ -56,14 +56,13 @@ case "$VALIDATE_OUT" in
|
||||
*) echo "gstack-timeline-log: bun printed no verdict while validating the event; nothing was logged" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
# Inject timestamp if not present
|
||||
if ! printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "const j=JSON.parse(await Bun.stdin.text()); if(!j.ts) process.exit(1)" 2>/dev/null; then
|
||||
STAMPED=$(printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "
|
||||
const j = JSON.parse(await Bun.stdin.text());
|
||||
j.ts = new Date().toISOString();
|
||||
console.log(JSON.stringify(j));
|
||||
" 2>/dev/null) && [ -n "$STAMPED" ] && INPUT=$STAMPED || true
|
||||
fi
|
||||
# Inject timestamp if not present, and store the event as one line: a
|
||||
# multi-line event appended as given is unreadable to every JSONL reader.
|
||||
STAMPED=$(printf '%s' "$INPUT" | bun --no-env-file --config="${GSTACK_BUN_CONFIG:-/dev/null}" -e "
|
||||
const j = JSON.parse(await Bun.stdin.text());
|
||||
if (!j.ts) j.ts = new Date().toISOString();
|
||||
console.log(JSON.stringify(j));
|
||||
" 2>/dev/null) && [ -n "$STAMPED" ] && INPUT=$STAMPED || true
|
||||
|
||||
echo "$INPUT" >> "$GSTACK_HOME/projects/$SLUG/timeline.jsonl"
|
||||
|
||||
|
||||
@@ -154,7 +154,7 @@ if (countStr) {
|
||||
console.log('');
|
||||
console.log('## Recent Events');
|
||||
for (const e of recent) {
|
||||
const ts = (e.ts || '').replace('T', ' ').replace(/\.\d+Z$/, 'Z');
|
||||
const ts = String(e.ts || '').replace('T', ' ').replace(/\.\d+Z$/, 'Z');
|
||||
const dur = e.duration_s ? ' (' + e.duration_s + 's)' : '';
|
||||
const outcome = e.outcome ? ' [' + e.outcome + ']' : '';
|
||||
console.log('- ' + ts + ' /' + e.skill + ' ' + e.event + outcome + dur + (e.branch ? ' on ' + e.branch : ''));
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
---
|
||||
important: security
|
||||
---
|
||||
**make-pdf removes `javascript:` links spelled with tabs, line breaks or entity letters.** Untrusted Markdown could still produce a live `javascript:` link in the HTML make-pdf prints by putting a tab or line break inside the scheme (`java	script:`) or by writing its letters as entities (`javascript:`). Those links now become harmless `#` fragments. Two smaller fixes in the same code: removing a click handler whose value contains `>` no longer mangles the rest of the tag, and an entity such as `Ϋ` that only starts like a colon no longer rewrites an ordinary link.
|
||||
|
||||
- **Quotes at the start of a paragraph, heading, list item or table cell now curl the right way in make-pdf.** `"Hello," she said` used to render as `”Hello,”`, including in the page title and running header.
|
||||
- **Wide SVG diagrams are printed on a sideways page again.** make-pdf read an SVG's `stroke-width` (or `data-height`) as its size, so a 3000px-wide diagram looked 2px wide and stayed on an upright page.
|
||||
- **One malformed learning no longer breaks every later `gstack-learnings-search`.** A row with `files` saved as a single string (or `ts` as a number) crashed the search until someone edited the file by hand. Search now reads those rows, and `gstack-learnings-log` stores a single path as a one-item list.
|
||||
- **Cross-project learnings add to this project's own and never replace them.** A newer learning with the same key from another repo used to replace this repo's answer, for example its test command.
|
||||
- **A pretty-printed timeline event that already has a timestamp is saved as one line**, so `gstack-timeline-read` no longer skips it without a word.
|
||||
@@ -105,7 +105,7 @@ export function svgTagDims(markup: string): { width: number; height: number } |
|
||||
const tag = markup.match(/<svg\b[^>]*>/i)?.[0];
|
||||
if (!tag) return null;
|
||||
const attr = (name: string): number | null => {
|
||||
const m = tag.match(new RegExp(`\\b${name}\\s*=\\s*["']\\s*([0-9.]+)(px)?\\s*["']`, "i"));
|
||||
const m = tag.match(new RegExp(`(?<![-\\w:])${name}\\s*=\\s*["']\\s*([0-9.]+)(px)?\\s*["']`, "i"));
|
||||
return m ? parseFloat(m[1]) : null;
|
||||
};
|
||||
const w = attr("width");
|
||||
|
||||
+67
-3
@@ -219,6 +219,42 @@ export function sanitizeUntrustedHtml(html: string): string {
|
||||
return escapeHtml(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the text at offset starts an attribute of the tag that contains it,
|
||||
* read the way the browser's tokenizer reads that tag from its "<": not
|
||||
* inside a name or a value, and the tag not yet closed.
|
||||
*/
|
||||
function startsAttribute(str: string, offset: number): boolean {
|
||||
const tagStart = str.lastIndexOf("<", offset);
|
||||
if (tagStart === -1 || !/[a-zA-Z]/.test(str[tagStart + 1] ?? "")) return false;
|
||||
const endsAtSpace = /\s/.test(str[offset] ?? "");
|
||||
let i = tagStart + 1;
|
||||
while (i < offset && !/[\s/>]/.test(str[i]!)) i++;
|
||||
while (i < offset) {
|
||||
if (/[\s/]/.test(str[i]!)) { i++; continue; }
|
||||
if (str[i] === ">") return false;
|
||||
while (i < offset && !/[\s/>=]/.test(str[i]!)) i++;
|
||||
if (i === offset) return endsAtSpace;
|
||||
let j = i;
|
||||
while (j < offset && /\s/.test(str[j]!)) j++;
|
||||
if (str[j] !== "=") continue;
|
||||
j++;
|
||||
while (j < offset && /\s/.test(str[j]!)) j++;
|
||||
if (j >= offset) return false;
|
||||
const q = str[j];
|
||||
if (q === '"' || q === "'") {
|
||||
const close = str.indexOf(q, j + 1);
|
||||
if (close === -1 || close >= offset) return false;
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
while (j < offset && !/[\s>]/.test(str[j]!)) j++;
|
||||
if (j === offset) return endsAtSpace;
|
||||
i = j;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function sanitizePass(html: string): string {
|
||||
let s = html;
|
||||
|
||||
@@ -253,9 +289,14 @@ function sanitizePass(html: string): string {
|
||||
// whole page, text included, so "/on…=" inside a URL or code goes too.
|
||||
// A quoted value goes with its name only when it holds no "<" or ">":
|
||||
// otherwise the quote may belong to a later element, so the last rule
|
||||
// removes just the name and the rest stays where it was.
|
||||
// removes just the name and the rest stays where it was. A value holding
|
||||
// ">" but no "<" also goes when the handler starts an attribute of the tag
|
||||
// it sits in (<div onclick="a > b" class="x">); inside another attribute's
|
||||
// value (title="docs/onload='x">…') the quote may be text, so it stays.
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*"[^"<>]*"/gi, "");
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*'[^'<>]*'/gi, "");
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*(?:"[^"<]*"|'[^'<]*')/gi, (m, offset: number, str: string) =>
|
||||
startsAttribute(str, offset) ? "" : m);
|
||||
s = s.replace(/(?:\s+|(?<=[/"']))on[a-zA-Z]+\s*=\s*[^\s>"'`<]*/gi, "");
|
||||
|
||||
// javascript: URLs in href/src/action/formaction (same attribute starts).
|
||||
@@ -264,8 +305,9 @@ function sanitizePass(html: string): string {
|
||||
'$1"#"',
|
||||
);
|
||||
// Any other javascript: value (unquoted, or quoted around "<" or ">") loses
|
||||
// only its scheme, so no quote is added or removed.
|
||||
s = s.replace(/([\s/"']\s*(?:href|src|action|formaction|xlink:href)\s*=\s*["']?[\s\x01-\x20]*)javascript(?::|:|�*58;?|�*3a;?)/gi, "$1#");
|
||||
// only its scheme, so no quote is added or removed. A numeric reference
|
||||
// with more digits after 58 or 3a is another character, not a colon.
|
||||
s = s.replace(/([\s/"']\s*(?:href|src|action|formaction|xlink:href)\s*=\s*["']?[\s\x01-\x20]*)javascript(?::|:|�*58(?![0-9]);?|�*3a(?![0-9a-f]);?)/gi, "$1#");
|
||||
|
||||
// srcdoc attribute (iframe escape hatch — already stripped via iframe above,
|
||||
// but defense-in-depth).
|
||||
@@ -354,6 +396,28 @@ function sanitizePass(html: string): string {
|
||||
return NAMED_REFS[legacy];
|
||||
});
|
||||
|
||||
// javascript: spelled the way only the browser reads it: entity letters
|
||||
// (javascript:), or a tab or line break anywhere in the scheme, which
|
||||
// URL parsing drops (java	script:). Decode the start of each URL
|
||||
// attribute value as the parser will, drop tabs and line breaks, and when
|
||||
// it is still javascript: put "#" in front, which makes the whole value a
|
||||
// fragment. Only the name and the opening quote are matched, so a quote
|
||||
// that really closes an earlier attribute can't hide a later value, and no
|
||||
// quote is added or removed. A value longer than the window that is still
|
||||
// nothing but padding and the start of "javascript:" counts as one.
|
||||
s = s.replace(/(?<=[\s/"'])(\s*(?:href|src|action|formaction|xlink:href)\s*=\s*)(["']?)/gi,
|
||||
(m, pre, q, offset: number, str: string) => {
|
||||
const start = offset + m.length;
|
||||
let end = q ? str.indexOf(q, start) : str.slice(start, start + 2048).search(/[\s>]/);
|
||||
end = end === -1 ? str.length : q ? end : start + end;
|
||||
const truncated = end - start > 2048;
|
||||
let value = str.slice(start, Math.min(end, start + 2048));
|
||||
if (truncated) value = value.replace(/&[#\w]*$/, "");
|
||||
const url = decodeStyleAttrEntities(value).replace(/[\t\n\r]/g, "").replace(/^[\x00-\x20]+/, "").toLowerCase();
|
||||
const live = url.startsWith("javascript:") || (truncated && "javascript:".startsWith(url));
|
||||
return live ? `${pre}${q}#` : m;
|
||||
});
|
||||
|
||||
// Inline style attributes — quoted AND unquoted. HTML spec: an unquoted
|
||||
// attribute value runs until whitespace or `>`, so
|
||||
// <div style=background:url(https://…)> is live markup Chromium honors;
|
||||
|
||||
@@ -54,7 +54,7 @@ export function smartypants(html: string): string {
|
||||
s = carve(s, TAG_RE);
|
||||
s = carve(s, URL_RE);
|
||||
|
||||
s = transformText(s);
|
||||
s = transformSegments(s, preserved);
|
||||
|
||||
// Step 2: restore preserved zones.
|
||||
// Use a function to avoid $-substitution gotchas.
|
||||
@@ -65,6 +65,43 @@ export function smartypants(html: string): string {
|
||||
return s;
|
||||
}
|
||||
|
||||
const PLACEHOLDER_SPLIT_RE = /(\u0000SMARTPANTS_PRESERVED_\d+\u0000)/;
|
||||
const BLOCK_TAG_RE = /^<\/?(?:address|article|aside|blockquote|br|caption|dd|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|table|tbody|td|tfoot|th|thead|tr|ul)\b/i;
|
||||
const INLINE_TAG_RE = /^<\/?(?:a|abbr|b|cite|del|dfn|em|i|ins|mark|q|s|small|span|strong|sub|sup|u)\b/i;
|
||||
const QUOTE_START_RE = /^(?:["']|"|'|'|')/;
|
||||
const OPENING_CONTEXT_RE = /[\s\(\[\{\-\uff1a\uff08\u3010\u300c\u300e\u3008\u300a]/;
|
||||
|
||||
/**
|
||||
* Transform each run of text between placeholders, reading a quote at the
|
||||
* start of a run by the visible text before it: a block tag (<p>, <li>, <h1>)
|
||||
* or the start of the document opens, an inline tag that wraps text (<em>,
|
||||
* <a>) is skipped, and anything else (code, a URL, an image, an unknown tag)
|
||||
* counts as a word. A run that starts with a quote is transformed behind a
|
||||
* one-character prefix that stands for that context; any other run keeps the
|
||||
* placeholder's own character before it, so "--flag" at the start of a cell
|
||||
* stays as it was, and a run that ends before a placeholder keeps that
|
||||
* character after it, so "wait --" before a tag does too. No rule changes the
|
||||
* character before or after its match, so both come back unchanged and are cut.
|
||||
*/
|
||||
function transformSegments(s: string, preserved: string[]): string {
|
||||
let context = " ";
|
||||
const parts = s.split(PLACEHOLDER_SPLIT_RE);
|
||||
return parts.map((part, i) => {
|
||||
if (i % 2 === 1) {
|
||||
const zone = preserved[parseInt(part.slice("\u0000SMARTPANTS_PRESERVED_".length), 10)] ?? "";
|
||||
if (BLOCK_TAG_RE.test(zone)) context = " ";
|
||||
else if (!INLINE_TAG_RE.test(zone)) context = "x";
|
||||
return part;
|
||||
}
|
||||
if (!part) return part;
|
||||
const prefix = QUOTE_START_RE.test(part) ? context : i === 0 ? "" : "\u0000";
|
||||
const suffix = i < parts.length - 1 ? "\u0000" : "";
|
||||
const out = transformText(prefix + part + suffix).slice(prefix.length, suffix ? -1 : undefined);
|
||||
context = OPENING_CONTEXT_RE.test(part[part.length - 1]!) ? " " : "x";
|
||||
return out;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform plain text (no HTML, no code, no URLs).
|
||||
*
|
||||
|
||||
@@ -207,6 +207,12 @@ describe("auto-landscape: diagram figures", () => {
|
||||
);
|
||||
expect(r.hasLandscape).toBe(true);
|
||||
});
|
||||
// stroke-width="2" sat before width= on the root, and the width lookup
|
||||
// matched inside it: a 3000px diagram measured 2px wide and stayed portrait.
|
||||
test("measures width and height, not stroke-width or data-height", () => {
|
||||
const r = applyImagePolicy(fig(`stroke-width="2" data-height="9" width="3000" height="600"`), OPTS);
|
||||
expect(r.hasLandscape).toBe(true);
|
||||
});
|
||||
test("diagnostic blocks are never promoted", () => {
|
||||
const html = `<figure class="diagram diagram-error" role="img" aria-label="x"><svg viewBox="0 0 4000 600"></svg></figure>`;
|
||||
const r = applyImagePolicy(html, OPTS);
|
||||
|
||||
@@ -84,6 +84,44 @@ describe("smartypants", () => {
|
||||
expect(out).toContain("</a>");
|
||||
});
|
||||
|
||||
// A quote that opens a paragraph, heading or list item sits right after a
|
||||
// tag, and was read as a closing quote: "Hello," rendered as ”Hello,”.
|
||||
test("opens a quote at the start of a paragraph, heading or list item", () => {
|
||||
expect(smartypants(`<p>"Hello," she said.</p>`)).toBe(`<p>\u201cHello,\u201d she said.</p>`);
|
||||
expect(smartypants(`<h1>"Quoted" title</h1>`)).toBe(`<h1>\u201cQuoted\u201d title</h1>`);
|
||||
expect(smartypants(`<ul>\n<li>'one'</li>\n</ul>`)).toBe(`<ul>\n<li>\u2018one\u2019</li>\n</ul>`);
|
||||
expect(smartypants(`<p>x</p><p>"y"</p>`)).toBe(`<p>x</p><p>\u201cy\u201d</p>`);
|
||||
expect(smartypants(`<p><em>"quoted"</em> word</p>`)).toBe(`<p><em>\u201cquoted\u201d</em> word</p>`);
|
||||
});
|
||||
|
||||
test("reads a quote after an inline tag by the text before the tag", () => {
|
||||
expect(smartypants(`<p>He said "<em>stop</em>" twice.</p>`)).toBe(`<p>He said \u201c<em>stop</em>\u201d twice.</p>`);
|
||||
expect(smartypants(`<p><em>Garry</em>'s book</p>`)).toBe(`<p><em>Garry</em>\u2019s book</p>`);
|
||||
});
|
||||
|
||||
test("a flag at the start of a cell, list item or bold run keeps its dashes", () => {
|
||||
expect(smartypants(`<td>--og</td><li>--check</li><p><strong>--resume</strong></p>`))
|
||||
.toBe(`<td>--og</td><li>--check</li><p><strong>--resume</strong></p>`);
|
||||
});
|
||||
|
||||
test("dashes at the end of a run before a tag keep their dashes", () => {
|
||||
expect(smartypants(`<p>wait --</p><p>run --<code>x</code></p>`))
|
||||
.toBe(`<p>wait --</p><p>run --<code>x</code></p>`);
|
||||
});
|
||||
|
||||
test("a quote after an image or an unknown tag still closes", () => {
|
||||
expect(smartypants(`<p>"check out <PR link>" today</p>`)).toBe(`<p>\u201ccheck out <PR link>\u201d today</p>`);
|
||||
expect(smartypants(`<p>"see <img src="a.png">" here</p>`)).toBe(`<p>\u201csee <img src="a.png">\u201d here</p>`);
|
||||
});
|
||||
|
||||
test("renders a document whose paragraph and heading open with a quote", () => {
|
||||
const html = render({ markdown: `# "Quoted" title\n\n"Hello," she said.\n` }).html;
|
||||
expect(html).toContain(`\u201cQuoted\u201d title`);
|
||||
expect(html).toContain(`<p>\u201cHello,\u201d she said.</p>`);
|
||||
expect(html).not.toContain(`\u201dQuoted`);
|
||||
expect(html).not.toContain(`\u201dHello`);
|
||||
});
|
||||
|
||||
test("does NOT touch HTML attribute values", () => {
|
||||
const out = smartypants(`<a href="it's-a-test.html">link</a>`);
|
||||
expect(out).toContain(`href="it's-a-test.html"`);
|
||||
@@ -382,16 +420,22 @@ function browserAttrs(html: string): Array<{ tag: string; name: string; value: s
|
||||
}
|
||||
|
||||
function decodeAttr(v: string): string {
|
||||
return v.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(quot|apos|amp));?/gi, (_m, hex, dec, named) =>
|
||||
return v.replace(/&(?:#x([0-9a-f]+)|#(\d+)|(quot|apos|amp)|(Tab|NewLine|colon););?/gi, (m, hex, dec, named, withSemi) =>
|
||||
hex ? String.fromCodePoint(parseInt(hex, 16))
|
||||
: dec ? String.fromCodePoint(parseInt(dec, 10))
|
||||
: ({ quot: '"', apos: "'", amp: "&" } as Record<string, string>)[named.toLowerCase()]!);
|
||||
: named ? ({ quot: '"', apos: "'", amp: "&" } as Record<string, string>)[named.toLowerCase()]!
|
||||
: ({ Tab: "\t", NewLine: "\n", colon: ":" } as Record<string, string>)[withSemi] ?? m);
|
||||
}
|
||||
|
||||
/** A URL the way the browser reads it: decoded, tabs and line breaks removed. */
|
||||
function browserUrl(v: string): string {
|
||||
return decodeAttr(v).replace(/[\t\n\r]/g, "");
|
||||
}
|
||||
|
||||
function liveScript(html: string): string[] {
|
||||
return browserAttrs(html)
|
||||
.filter((a) => a.name.startsWith("on") ||
|
||||
(/^(?:href|src|xlink:href|action|formaction)$/.test(a.name) && /^\s*javascript:/i.test(decodeAttr(a.value))))
|
||||
(/^(?:href|src|xlink:href|action|formaction)$/.test(a.name) && /^[\x00-\x20]*javascript:/i.test(browserUrl(a.value))))
|
||||
.map((a) => `<${a.tag} ${a.name}=${a.value}>`);
|
||||
}
|
||||
|
||||
@@ -509,6 +553,91 @@ describe("render() — characters dropped after sanitizing cannot revive script"
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeUntrustedHtml — handlers and javascript: links in any spelling the browser reads", () => {
|
||||
// A ">" inside a quoted handler value is still part of that value, so the
|
||||
// whole handler goes and the attributes after it stay.
|
||||
test("a handler whose quoted value holds > is removed with its value", () => {
|
||||
expect(sanitizeUntrustedHtml(`<div onclick="return a > b" class="notice">Keep me</div>`))
|
||||
.toBe(`<div class="notice">Keep me</div>`);
|
||||
expect(sanitizeUntrustedHtml(`<div onclick='return a > b' class="notice">Keep me</div>`))
|
||||
.toBe(`<div class="notice">Keep me</div>`);
|
||||
expect(sanitizeUntrustedHtml(`<input disabled onclick="a > b" x=1 onfocus='c > d' name=n>`))
|
||||
.toBe(`<input disabled x=1 name=n>`);
|
||||
});
|
||||
|
||||
// Handler-looking text inside another attribute's value is not an
|
||||
// attribute, so a quote after it may be text: only the name goes.
|
||||
test("handler text inside an attribute value never swallows the text after the tag", () => {
|
||||
const out = sanitizeUntrustedHtml(`<div title="docs/onload='example">Keep me ' and the rest</div>`);
|
||||
expect(out).toContain("Keep me ' and the rest</div>");
|
||||
expect(liveScript(out)).toEqual([]);
|
||||
});
|
||||
|
||||
// Ϋ is the character U+03AB, not a colon followed by "b".
|
||||
test("an entity that only starts like a colon is left alone", () => {
|
||||
for (const href of ["javascriptΫguide", "javascriptᜋguide", "javascriptΠx"]) {
|
||||
const html = `<a href="${href}">g</a>`;
|
||||
expect(sanitizeUntrustedHtml(html)).toBe(html);
|
||||
}
|
||||
expect(liveScript(sanitizeUntrustedHtml(`<a href="javascript:alert(1)">g</a>`))).toEqual([]);
|
||||
expect(liveScript(sanitizeUntrustedHtml(`<a href="javascript:alert(1)">g</a>`))).toEqual([]);
|
||||
});
|
||||
|
||||
// Browsers drop tabs and line breaks from a URL and decode entities first,
|
||||
// so all of these still run as javascript: links.
|
||||
test("javascript: written with tabs, line breaks or entity letters is neutralized", () => {
|
||||
const spellings = [
|
||||
"java\tscript:alert(1)", "java\nscript:alert(1)", "java\rscript:alert(1)",
|
||||
"java	script:alert(1)", "java	script:alert(1)", "java	script:alert(1)", "java
script:alert(1)",
|
||||
"javascript:alert(1)", "javascript:alert(1)", "javascript:alert(1)",
|
||||
" javascript:alert(1)", "javascript:alert(1)",
|
||||
];
|
||||
for (const v of spellings) {
|
||||
for (const attr of [`href="${v}"`, `href='${v}'`, `src="${v}"`, `formaction="${v}"`]) {
|
||||
const out = sanitizeUntrustedHtml(`<a ${attr}>j</a>`);
|
||||
expect(liveScript(out)).toEqual([]);
|
||||
expect(out).toContain(">j</a>");
|
||||
}
|
||||
if (!/\s/.test(v)) expect(liveScript(sanitizeUntrustedHtml(`<a href=${v}>j</a>`))).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("a javascript: value holding < or > keeps its quotes and loses its scheme", () => {
|
||||
const out = sanitizeUntrustedHtml(`<a href='java	script:a>b' title="t">j</a><p>after</p>`);
|
||||
expect(liveScript(out)).toEqual([]);
|
||||
expect(attrsOf(out, "a")).toEqual(["href", "title"]);
|
||||
expect(out).toContain("<p>after</p>");
|
||||
});
|
||||
|
||||
test("a later attribute is checked even when an earlier quote pairs with it", () => {
|
||||
const out = sanitizeUntrustedHtml(`<p title=' href='>x</p><a href='java	script:alert(1)'>j</a>`);
|
||||
expect(liveScript(out)).toEqual([]);
|
||||
for (const v of ["javascript:alert(1)", "java	script:alert(1)"]) {
|
||||
expect(liveScript(sanitizeUntrustedHtml(`<a title='x href='href=${v}>b</a>`))).toEqual([]);
|
||||
}
|
||||
});
|
||||
|
||||
test("ordinary links are untouched", () => {
|
||||
const html = `<a href="https://example.com/a?b=1&c=2">a</a><a href="#top">t</a><a href="java.html">j</a><img src="javascript.png">`;
|
||||
expect(sanitizeUntrustedHtml(html)).toBe(html);
|
||||
});
|
||||
|
||||
test("render() neutralizes the same spellings in raw HTML and links", () => {
|
||||
const md = [
|
||||
"<div>",
|
||||
`<a href="java	script:alert(1)">a</a>`,
|
||||
`<a href="javascript:alert(1)">b</a>`,
|
||||
"</div>",
|
||||
"",
|
||||
"[c](java	script:alert(1)) [d](javascript:alert(1))",
|
||||
"",
|
||||
].join("\n");
|
||||
const html = render({ markdown: md }).bodyHtml;
|
||||
expect(liveScript(html)).toEqual([]);
|
||||
for (const t of [">a</a>", ">b</a>"]) expect(html).toContain(t);
|
||||
});
|
||||
});
|
||||
|
||||
describe("render() — removing script keeps the page's structure", () => {
|
||||
test("handler-looking text inside a quoted attribute never eats the elements after it", () => {
|
||||
for (const md of [
|
||||
|
||||
@@ -95,6 +95,39 @@ describe('gstack-learnings-search cross-project trust gating', () => {
|
||||
// B5 (#2790): both query scripts ended in `2>/dev/null || exit 0`, so a
|
||||
// missing bun or a crashed embedded script printed nothing and exited 0,
|
||||
// exactly like "nothing recorded".
|
||||
// Value: protects=with cross-project learnings on (the recommended answer), a review or QA run still reads this
|
||||
// project's own learning for a key; fails_when=a newer trusted learning with the same key+type in another project
|
||||
// replaces this project's entry, so the agent is told another repo's answer (pytest instead of bun test);
|
||||
// why_new=the latest-wins dedup ran across projects; seam=none
|
||||
describe('gstack-learnings-search cross-project rows never replace this project\'s own', () => {
|
||||
const ownCwd = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-search-own-cwd-'));
|
||||
const ownDir = path.join(tmpHome, 'projects', path.basename(ownCwd).replace(/[^a-zA-Z0-9._-]/g, ''));
|
||||
const row = (over: Record<string, unknown>) => JSON.stringify({ skill: 'qa', type: 'tool', key: 'test-command', confidence: 9, source: 'user-stated', trusted: true, files: [], ...over });
|
||||
beforeAll(() => {
|
||||
fs.mkdirSync(ownDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(ownDir, 'learnings.jsonl'), [
|
||||
row({ ts: '2026-05-01T00:00:00Z', insight: 'This repo runs its tests with bun test' }),
|
||||
].join('\n') + '\n');
|
||||
fs.appendFileSync(path.join(otherProjDir, 'learnings.jsonl'), [
|
||||
row({ ts: '2026-06-01T00:00:00Z', insight: 'That repo runs its tests with pytest' }),
|
||||
row({ ts: '2026-06-02T00:00:00Z', key: 'foreign-only-tool', insight: 'A tool learning only the other project has' }),
|
||||
].join('\n') + '\n');
|
||||
});
|
||||
afterAll(() => fs.rmSync(ownCwd, { recursive: true, force: true }));
|
||||
const search = (args: string[]) => execFileSync(BIN, args, { timeout: 30_000, env: { ...process.env, GSTACK_HOME: tmpHome }, cwd: ownCwd, encoding: 'utf-8' });
|
||||
|
||||
test('this project\'s entry wins over a newer same-key entry from another project', () => {
|
||||
const out = search(['--cross-project', '--all']);
|
||||
expect(out).toContain('This repo runs its tests with bun test');
|
||||
expect(out).not.toContain('That repo runs its tests with pytest');
|
||||
});
|
||||
|
||||
test('other projects still add the keys this project lacks', () => {
|
||||
const out = search(['--cross-project', '--all']);
|
||||
expect(out).toMatch(/\[foreign-only-tool\].*\[cross-project\]/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('B5: query scripts never report a failed read as an empty result', () => {
|
||||
const TOOLS = ['bash', 'sh', 'env', 'dirname', 'basename', 'git', 'tr', 'sed', 'cat', 'head', 'tail', 'grep', 'find',
|
||||
'ls', 'mkdir', 'mktemp', 'mv', 'rm', 'cp', 'awk', 'wc', 'sort', 'uname', 'date', 'cut', 'readlink', 'realpath', 'stat', 'touch', 'id', 'printf'];
|
||||
@@ -231,4 +264,25 @@ describe('B6: rank by matched tokens and disclose truncation', () => {
|
||||
for (const k of ['healthy-0', 'healthy-1', 'healthy-2']) expect(got).toContain(k);
|
||||
});
|
||||
}
|
||||
|
||||
// Value: protects=skills read every learning at start, so one malformed row must not hide the rest;
|
||||
// fails_when=a row whose files is a string or whose ts is a number crashes the
|
||||
// formatter and exits 1 after printing only part of the list; why_new=gstack-learnings-log stores files and ts
|
||||
// as given, so '"files":"src/a.ts"' made every later search fail; seam=none
|
||||
for (const [label, over] of [
|
||||
['files is a string', { files: 'src/a.ts' }],
|
||||
['ts is a number', { ts: 1700000000000 }],
|
||||
] as const) {
|
||||
test(`a row whose ${label} cannot blank the whole store`, () => {
|
||||
write(badDir, [
|
||||
row({ ts: '2026-05-01T00:00:00Z', type: 'pitfall', key: 'healthy-pitfall', insight: 'a healthy pitfall', files: ['src/b.ts'] }),
|
||||
row({ key: 'malformed-row', insight: 'the malformed row', ...over }),
|
||||
row({ ts: '2026-05-02T00:00:00Z', type: 'tool', key: 'healthy-tool', insight: 'a healthy tool' }),
|
||||
]);
|
||||
const r = runIn(badCwd, ['--all']);
|
||||
expect(r.status).toBe(0);
|
||||
expect(keys(r.stdout)).toEqual(expect.arrayContaining(['healthy-pitfall', 'healthy-tool']));
|
||||
expect(r.stdout).toContain('(files: src/b.ts)');
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -254,6 +254,13 @@ describe('gstack-learnings-log edge cases', () => {
|
||||
const parsed = JSON.parse(fs.readFileSync(f!, 'utf-8').trim());
|
||||
expect(parsed.files).toEqual(['src/auth.ts', 'src/db.ts']);
|
||||
});
|
||||
|
||||
test('stores a single files string as a one-item list', () => {
|
||||
runLog(JSON.stringify({ skill: 'review', type: 'pitfall', key: 'files-string', insight: 'test', confidence: 7, source: 'observed', files: 'src/auth.ts' }));
|
||||
|
||||
const parsed = JSON.parse(fs.readFileSync(findLearningsFile()!, 'utf-8').trim());
|
||||
expect(parsed.files).toEqual(['src/auth.ts']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gstack-learnings-search edge cases', () => {
|
||||
@@ -303,6 +310,18 @@ describe('gstack-learnings-search edge cases', () => {
|
||||
expect(output).not.toContain('no-type');
|
||||
});
|
||||
|
||||
test('a stored row whose files is not a list does not break the search', () => {
|
||||
runLog(JSON.stringify({ skill: 'review', type: 'pattern', key: 'good-row', insight: 'good entry', confidence: 7, source: 'observed' }));
|
||||
const f = findLearningsFile();
|
||||
expect(f).not.toBeNull();
|
||||
fs.appendFileSync(f!, JSON.stringify({ skill: 'review', type: 'pitfall', key: 'string-files', insight: 'files as a string', confidence: 7, source: 'observed', files: 'src/auth.ts', ts: new Date().toISOString() }) + '\n');
|
||||
|
||||
const output = runSearch();
|
||||
expect(output).toContain('good-row');
|
||||
expect(output).toContain('[string-files]');
|
||||
expect(output).toContain('files as a string (files: src/auth.ts)');
|
||||
});
|
||||
|
||||
test('confidence decay floors at 0 (never negative)', () => {
|
||||
// Entry from 1 year ago with confidence 3 — decay would be 12, clamped to 0
|
||||
const ts = new Date(Date.now() - 365 * 86400000).toISOString();
|
||||
|
||||
@@ -128,6 +128,24 @@ describe('gstack-timeline-log', () => {
|
||||
expect(parsed.ts).toBe('2025-06-15T10:00:00Z');
|
||||
});
|
||||
|
||||
test('a multi-line event with its own ts is stored as one line and read back', () => {
|
||||
runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'main', ts: new Date().toISOString() }, null, 2));
|
||||
|
||||
const lines = fs.readFileSync(findTimelineFile()!, 'utf-8').trim().split('\n');
|
||||
expect(lines).toHaveLength(1);
|
||||
expect(JSON.parse(lines[0]).skill).toBe('review');
|
||||
expect(runRead()).toContain('/review completed');
|
||||
});
|
||||
|
||||
test('an event whose ts is a number does not stop the read', () => {
|
||||
runLog(JSON.stringify({ skill: 'review', event: 'completed', branch: 'main', ts: 1764160000000 }));
|
||||
runLog(JSON.stringify({ skill: 'qa', event: 'completed', branch: 'main' }));
|
||||
|
||||
const out = runRead();
|
||||
expect(out).toContain('/qa completed');
|
||||
expect(out).toContain('/review completed');
|
||||
});
|
||||
|
||||
test('validates required fields (skill, event) - exits 0 if missing skill', () => {
|
||||
const result = runLog('{"event":"started","branch":"main"}');
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
Reference in new issue
Block a user