Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions bin/gstack-learnings-log
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand Down
15 changes: 10 additions & 5 deletions bin/gstack-learnings-search
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}
Expand All @@ -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;
Expand Down Expand Up @@ -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('');
Expand Down
15 changes: 7 additions & 8 deletions bin/gstack-timeline-log
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
2 changes: 1 addition & 1 deletion bin/gstack-timeline-read
Original file line number Diff line number Diff line change
Expand Up @@ -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 : ''));
Expand Down
10 changes: 10 additions & 0 deletions changelog.d/make-pdf-sanitizer-gaps-and-small-fixes.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion make-pdf/src/image-size.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
70 changes: 67 additions & 3 deletions make-pdf/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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).
Expand All @@ -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(?::|&colon;|&#0*58;?|&#x0*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(?::|&colon;|&#0*58(?![0-9]);?|&#x0*3a(?![0-9a-f]);?)/gi, "$1#");

// srcdoc attribute (iframe escape hatch — already stripped via iframe above,
// but defense-in-depth).
Expand Down Expand Up @@ -354,6 +396,28 @@ function sanitizePass(html: string): string {
return NAMED_REFS[legacy];
});

// javascript: spelled the way only the browser reads it: entity letters
// (&#106;avascript:), or a tab or line break anywhere in the scheme, which
// URL parsing drops (java&Tab;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;
Expand Down
39 changes: 38 additions & 1 deletion make-pdf/src/smartypants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 = /^(?:["']|&quot;|&#39;|&apos;|&#x27;)/;
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).
*
Expand Down
6 changes: 6 additions & 0 deletions make-pdf/test/image-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading