Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(brands): ignore inactive HTML icon declarations

asts-top15a0c1a8ecd6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 811041b0..3d7c8966 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
- **Repository evidence for every diagram type (#59).** `meta.repository` and node `sources` are now accepted by Workflow, Sequence, Data Flow, and Lifecycle as well as Architecture, and `--repo-root` reaches `render`, `validate`, `deliver`, and `preview` for all five. Each mode authors sources on its own node collection (`components`, `nodes`, `participants`, `states`) while verification is unchanged: Git top level, origin match, commit, blob, path containment, and line bounds all still have to hold, GitHub, Gitee, and `link_mode: "local-only"` repositories behave identically in every mode, and the verified payload stays keyed by node id. Architecture output is unchanged and the `repository-evidence/type-unsupported` diagnostic is removed as unreachable.
### Fixed
+- **Inactive brand icon declarations.** Capture ignores icon markup in comments, raw text, quoted attributes and templates, so inactive page edits cannot replace the selected image or break its pinned digest. Complete link attributes keep quoted delimiters and distinguish `href` from `data-href`.
- **Escaped brand icon URLs (#454).** Favicon discovery decodes basic named and numeric HTML character references once before URL resolution, preserving percent escapes and the existing network and digest checks.
- **Brand HTML head boundaries.** Favicon capture ignores apparent head endings inside comments, raw text and quoted attributes while retaining bounded, streaming head reads.
- **Conservative VS15 text-width estimates.** Text-presentation selectors retain the base character's estimated width instead of forcing every sequence to one unit. This prevents wide labels, including CJK text whose font ignores VS15, from passing layout checks at half their estimated width. Actual glyph widths remain font-dependent; some text-presentation labels may now need more space. VS16 emoji estimates and text without selectors are unchanged.
diff --git a/archify.zip b/archify.zip
index 9f943839..7b9ac420 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/references/brand-marks.md b/archify/references/brand-marks.md
index 1c127493..8876e2ba 100644
--- a/archify/references/brand-marks.md
+++ b/archify/references/brand-marks.md
@@ -58,6 +58,9 @@ HTML reads stop at an explicit head ending outside comments, raw-text elements
and quoted attributes, including when those tokens span network chunks. The
256 KiB head limit and capture deadline still apply; a larger body after the
head is not read for icon discovery.
+Icon candidates come from complete `link` tags outside comments, raw text and
+template contents. Attribute values and lookalike names such as `data-href`
+cannot supply icon declarations; quoted `>` characters stay within their tags.
Unknown URL capture accepts only bounded raster image formats, blocks
credentials, nonstandard public ports, and private or link-local destinations,
uses bounded concurrency and one total deadline, and returns the captured
diff --git a/archify/renderers/shared/brand-marks.mjs b/archify/renderers/shared/brand-marks.mjs
index 0b4a7678..d3176556 100644
--- a/archify/renderers/shared/brand-marks.mjs
+++ b/archify/renderers/shared/brand-marks.mjs
@@ -271,18 +271,20 @@ async function readLimited(response, maximum) {
// Read only the bounded head, independent of network chunk boundaries. Scan
// bytes once so many tiny chunks cannot cause repeated concatenation/rescanning.
-// This is a boundary scanner, not a DOM parser: comments, quoted attributes and
-// raw-text elements must not turn a literal </head> into an early stop.
-async function readHtmlHead(response, maximum) {
+// Collect link tags in the same pass: markup in comments, raw text, attributes
+// or templates must not become an icon candidate or an early head ending.
+async function readHtmlHeadLinks(response, maximum) {
const chunks = response.body && typeof response.body[Symbol.asyncIterator] === 'function'
? response.body : [await readLimited(response, maximum)];
const buffer = Buffer.alloc(maximum);
+ const links = [];
let total = 0;
let tagStart = -1;
let quote = 0;
let comment = false;
let rawClosing = '';
let matched = 0;
+ let templateDepth = 0;
for await (const value of chunks) {
const chunk = Buffer.from(value);
const length = Math.min(chunk.length, maximum - total);
@@ -328,10 +330,13 @@ async function readHtmlHead(response, maximum) {
}
if (byte === 0x3e) {
const tag = buffer.toString('utf8', tagStart, position + 1);
- if (/^<\/head[\t\n\f\r ]*>$/i.test(tag)) {
+ if (!templateDepth && /^<\/head[\t\n\f\r ]*>$/i.test(tag)) {
response.body?.destroy?.();
- return buffer.toString('utf8', 0, position + 1);
+ return links;
}
+ if (/^<template(?=[\t\n\f\r />])/i.test(tag)) templateDepth += 1;
+ else if (/^<\/template(?=[\t\n\f\r />])/i.test(tag)) templateDepth = Math.max(0, templateDepth - 1);
+ else if (!templateDepth && /^<link(?=[\t\n\f\r />])/i.test(tag)) links.push(tag);
const raw = /^<(script|style|title|textarea|xmp|iframe|noembed|noframes)(?=[\t\n\f\r />])/i.exec(tag);
if (raw) rawClosing = `</${raw[1].toLowerCase()}`;
tagStart = -1;
@@ -343,12 +348,17 @@ async function readHtmlHead(response, maximum) {
throw new Error('brand asset is too large');
}
}
- return buffer.toString('utf8', 0, total);
+ return links;
}
-function attribute(tag, name) {
- const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));
- return match ? (match[1] ?? match[2] ?? match[3] ?? '') : '';
+function linkAttribute(tag, name) {
+ // Consume entire attributes so data-href and quoted examples cannot supply
+ // a real href. As in HTML, the first occurrence wins, even when valueless.
+ const attributes = tag.slice(5, -1).matchAll(/([^\t\n\f\r />=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g);
+ for (const match of attributes) {
+ if (match[1].toLowerCase() === name) return match[2] ?? match[3] ?? match[4] ?? '';
+ }
+ return '';
}
// HTML numeric references in the C1 range use the legacy Windows-1252 mapping.
@@ -374,19 +384,18 @@ function decodeIconHref(value) {
});
}
-function iconCandidates(html, pageUrl) {
+function iconCandidates(links, pageUrl) {
const candidates = [];
- for (const match of html.matchAll(/<link\b[^>]*>/gi)) {
- const tag = match[0];
- const rel = attribute(tag, 'rel').toLocaleLowerCase('en-US').split(/\s+/);
+ for (const tag of links) {
+ const rel = linkAttribute(tag, 'rel').toLocaleLowerCase('en-US').split(/\s+/);
if (!rel.some((value) => value === 'icon' || value === 'apple-touch-icon' || value === 'mask-icon')) continue;
- const href = decodeIconHref(attribute(tag, 'href'));
+ const href = decodeIconHref(linkAttribute(tag, 'href'));
if (!href) continue;
try {
const url = new URL(href, pageUrl);
if (!['https:', 'http:'].includes(url.protocol)) continue;
- const type = attribute(tag, 'type').toLocaleLowerCase('en-US');
- const sizes = attribute(tag, 'sizes');
+ const type = linkAttribute(tag, 'type').toLocaleLowerCase('en-US');
+ const sizes = linkAttribute(tag, 'sizes');
const area = [...sizes.matchAll(/(\d+)x(\d+)/gi)]
.reduce((best, size) => Math.max(best, Number(size[1]) * Number(size[2])), 0);
const score = (type.includes('svg') || /\.svg(?:$|[?#])/i.test(url.href) ? 1000000 : 0)
@@ -478,9 +487,9 @@ async function captureRemoteBrand(value, deadline = Date.now() + captureTimeoutM
page.response.body?.destroy?.();
return fallback('linked page is not HTML');
}
- const html = await readHtmlHead(page.response, MAX_HTML_BYTES);
+ const links = await readHtmlHeadLinks(page.response, MAX_HTML_BYTES);
const iconErrors = [];
- for (const candidate of iconCandidates(html, page.finalUrl)) {
+ for (const candidate of iconCandidates(links, page.finalUrl)) {
try {
const fetched = await checkedFetch(candidate.url, 'image/*', deadline);
const image = await imageData(fetched.response);
diff --git a/archify/test/brand-icon-contexts.test.mjs b/archify/test/brand-icon-contexts.test.mjs
new file mode 100644
index 00000000..8a1e84e1
--- /dev/null
+++ b/archify/test/brand-icon-contexts.test.mjs
@@ -0,0 +1,191 @@
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+// Valid blue and red PNGs: a wrong candidate must not fall through after a 404.
+const icon = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYPj/HwADAgH/5ncLrgAAAABJRU5ErkJggg==', 'base64');
+const inactiveIcon = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==', 'base64');
+const digest = createHash('sha256').update(icon).digest('hex');
+const activeLink = '<link rel="icon" href="/active.png">';
+const inactiveLink = '<link rel="icon" href="/inactive.png">';
+
+function run(args) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [cli, ...args], {
+ cwd: skillRoot,
+ env: { ...process.env, ARCHIFY_BRAND_ALLOW_PRIVATE: '1' },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ timeout: 15000,
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; });
+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });
+ child.once('error', reject);
+ child.once('close', (status) => resolve({ status, stdout, stderr }));
+ });
+}
+
+async function fixture(t, markup, { byteChunks = false } = {}) {
+ const data = { markup, requests: [] };
+ const server = http.createServer(async (request, response) => {
+ data.requests.push(request.url);
+ if (request.url === '/studio') {
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
+ const html = `<head>${data.markup}</head>`;
+ if (byteChunks) {
+ for (const byte of Buffer.from(html)) {
+ if (response.destroyed) return;
+ response.write(Buffer.from([byte]));
+ await new Promise((resolve) => setTimeout(resolve, 2));
+ }
+ } else {
+ response.write(html);
+ }
+ response.end();
+ } else if (['/active.png', '/active.png?a=1&b=2', '/favicon.ico'].includes(request.url)) {
+ response.writeHead(200, { 'content-type': 'image/png' });
+ response.end(icon);
+ } else if (request.url === '/inactive.png') {
+ response.writeHead(200, { 'content-type': 'image/png' });
+ response.end(inactiveIcon);
+ } else {
+ response.writeHead(404);
+ response.end('no icon');
+ }
+ });
+ await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', resolve);
+ });
+ t.after(() => new Promise((resolve) => {
+ server.closeAllConnections?.();
+ server.close(resolve);
+ }));
+ data.url = `http://127.0.0.1:${server.address().port}/studio`;
+ return data;
+}
+
+async function capture(data, paths = ['/active.png']) {
+ const result = await run(['brands', 'capture', data.url, '--json']);
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.deepEqual(data.requests, ['/studio', ...paths]);
+ assert.equal(receipt.ok, true);
+ assert.deepEqual(receipt.brand, { url: data.url, sha256: digest });
+ assert.equal(receipt.evidence.status, 'captured');
+ return receipt.brand;
+}
+
+for (const [name, prefix] of [
+ ['comment', `<!-- ${inactiveLink} -->`],
+ ['script string', `<script>const example = '${inactiveLink}';</script>`],
+ ['style string', `<style>p::after { content: '${inactiveLink}'; }</style>`],
+ ['title text', `<title>Example ${inactiveLink}</title>`],
+ ['quoted attribute', `<meta name="example" content='${inactiveLink}'>`],
+ ['template', `<template>${inactiveLink}</template>`],
+ ['nested template', `<template><template>${inactiveLink}</template>${inactiveLink}</template>`],
+ ['template with literal closing tags', `<template><script>const end = '</template></head>';</script>${inactiveLink}</template>`],
+ ['raw closing-tag prefix', `<script>"</scripture>${inactiveLink}";</script>`],
+ ['self-closing script flag', `<script/>"${inactiveLink}";</script>`],
+ ['lookalike tag name', '<link-preview rel="icon" href="/inactive.png"></link-preview>'],
+ ['lookalike rel attribute', '<link data-rel="icon" href="/inactive.png">'],
+]) {
+ test(`capture ignores icon declarations in ${name}`, async (t) => {
+ await capture(await fixture(t, prefix + activeLink));
+ });
+}
+
+for (const [name, markup] of [
+ ['ordinary icon', activeLink],
+ ['quoted greater-than', '<link title="size > zero" rel="icon" href="/active.png">'],
+ ['lookalike href attribute', '<link data-href="/inactive.png" HREF="/active.png" REL="icon">'],
+ ['attribute value containing declarations', '<link data-example=\'rel="icon" href="/inactive.png"\' rel="icon" href="/active.png">'],
+ ['unquoted attributes', '<link data-note=example rel=icon href=/active.png>'],
+ ['first duplicate attribute', '<link rel="icon" href="/active.png" HREF="/inactive.png">'],
+ ['empty first duplicate attribute', '<link rel="icon" href href="/inactive.png">' + activeLink],
+ ['existing size ranking', '<link rel="icon" sizes="16x16" href="/inactive.png"><link rel="icon" sizes="32x32" href="/active.png">'],
+]) {
+ test(`capture reads complete link attributes: ${name}`, async (t) => {
+ await capture(await fixture(t, markup));
+ });
+}
+
+test('inactive declarations do not consume the five icon candidate slots', async (t) => {
+ const removed = Array.from({ length: 5 }, (_, index) => `<link rel="icon" href="/missing-${index}.png">`).join('');
+ await capture(await fixture(t, `<!-- ${removed} -->${activeLink}`));
+});
+
+test('active declarations retain the five-candidate limit and favicon fallback', async (t) => {
+ const paths = Array.from({ length: 5 }, (_, index) => `/missing-${index}.png`);
+ const markup = paths.map((href) => `<link rel="icon" href="${href}">`).join('') + activeLink;
+ await capture(await fixture(t, markup), [...paths, '/favicon.ico']);
+});
+
+for (const [name, markup] of [
+ ['unclosed comment', `<!-- ${inactiveLink}`],
+ ['unclosed script', `<script>const example = '${inactiveLink}';`],
+ ['unclosed template', `<template>${inactiveLink}`],
+]) {
+ test(`capture uses the favicon fallback for an ${name}`, async (t) => {
+ await capture(await fixture(t, markup), ['/favicon.ico']);
+ });
+}
+
+for (const [name, prefix] of [
+ ['comment', `<!-- ${inactiveLink} </head> -->`],
+ ['script', `<ScRiPt data-note=">">'${inactiveLink}'</sCrIpT \n>`],
+ ['template', `<template>${inactiveLink}</template>`],
+]) {
+ test(`link attributes and ${name} context survive one-byte response chunks`, { timeout: 20000 }, async (t) => {
+ // Keep each response short enough for the real request deadline, including
+ // hosts with coarse timer resolution. Do not relax the capture timeout.
+ const markup = prefix + '<LiNk title="图 > icon" REL=icon HREF="/active.png?a=1&amp;b=2">';
+ await capture(await fixture(t, markup, { byteChunks: true }), ['/active.png?a=1&b=2']);
+ });
+}
+
+for (const [type, example, collection] of [
+ ['architecture', 'web-app.architecture.json', 'components'],
+ ['workflow', 'agent-tool-call.workflow.json', 'nodes'],
+ ['sequence', 'cache-miss-request.sequence.json', 'participants'],
+ ['dataflow', 'product-analytics.dataflow.json', 'nodes'],
+ ['lifecycle', 'agent-run.lifecycle.json', 'states'],
+]) {
+ test(`inactive HTML changes preserve pinned ${type} validation and rendered bytes`, { timeout: 45000 }, async (t) => {
+ const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-brand-context-'));
+ t.after(() => fs.rmSync(temporary, { recursive: true, force: true }));
+ const data = await fixture(t, activeLink);
+ const brand = await capture(data);
+ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', example), 'utf8'));
+ diagram[collection][0].brand = brand;
+ const input = path.join(temporary, 'diagram.json');
+ const output = path.join(temporary, 'diagram.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ let original;
+ for (const prefix of ['', `<!-- ${inactiveLink} --><script>const sample = '${inactiveLink}';</script>`]) {
+ data.markup = prefix + activeLink;
+ for (const command of ['validate', 'render']) {
+ data.requests.length = 0;
+ const args = [command, type, input, ...(command === 'render' ? [output] : ['--json'])];
+ const result = await run(args);
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ assert.deepEqual(data.requests, ['/studio', '/active.png']);
+ }
+ const html = fs.readFileSync(output, 'utf8');
+ assert.ok(html.includes(`data-brand-sha256="${digest}"`));
+ assert.ok(html.includes(`data:image/png;base64,${icon.toString('base64')}`));
+ assert.ok(!html.includes(inactiveIcon.toString('base64')));
+ if (original) assert.equal(html, original, 'inactive source markup must not change the final artifact');
+ original = html;
+ }
+ });
+}