// Pure graph helpers and visibility state for the vuln-notif record viewer. // // No DOM access lives here, so GraphModel and the serializers can be exercised // from a plain ES module test as well as from main.js. export const WANTED_COLLECTIONS = [ "com.nahdig.cve.atprotoV1", "software.release.project", "software.release.channel", "software.release.version", "software.release.manifest", "software.release.status", "com.nahdig.release.projectMeta", ]; export const COLLECTIONS = { "com.nahdig.cve.atprotoV1": ["cve.atprotoV1", "#c62828"], "software.release.project": ["release.project", "#9b59b6"], "software.release.version": ["release.version", "#1abc9c"], "software.release.channel": ["release.channel", "#e67e22"], "software.release.status": ["release.status", "#e74c3c"], "software.release.manifest": ["release.manifest", "#8e44ad"], "com.nahdig.release.projectMeta": ["release.projectMeta", "#2ecc71"], }; const FALLBACK_COLORS = [ "#6c7a89", "#c0392b", "#16a085", "#8e44ad", "#d35400", "#2980b9", "#27ae60", "#7f8c8d", ]; function hashString(value) { let hash = 0; for (let i = 0; i < value.length; i++) { hash = (hash * 31 + value.charCodeAt(i)) >>> 0; } return hash; } export function nsidLabel(collection) { return COLLECTIONS[collection]?.[0] || collection; } export function nsidColor(collection) { const meta = COLLECTIONS[collection]; if (meta) return meta[1]; return FALLBACK_COLORS[hashString(collection) % FALLBACK_COLORS.length]; } // --------------------------------------------------------------------------- // Link extraction (port of src/links.rs LINK_SPECS) // --------------------------------------------------------------------------- const LINK_SPECS = { "com.nahdig.cve.atprotoV1": [ "nvd.uri", "software[].project.uri", "software[].channels[].uri", "software[].versions[].uri", "software[].manifests[].uri", ], "software.release.project": ["parent", "renamedTo"], "software.release.manifest": ["project"], "software.release.version": ["project", "manifest.uri"], "software.release.channel": ["project", "version.uri"], "software.release.status": ["subject"], "com.nahdig.release.projectMeta": ["project"], }; function linkTarget(value) { if (typeof value === "string") { return value.startsWith("at://") ? value : null; } if (!value || typeof value !== "object") return null; return typeof value.uri === "string" && value.uri.startsWith("at://") ? value.uri : null; } function walk(value, segments) { if (segments.length === 0) { const target = linkTarget(value); return target ? [target] : []; } if (!value || typeof value !== "object") return []; const [head, ...rest] = segments; if (head.endsWith("[]")) { const items = value[head.slice(0, -2)]; if (!Array.isArray(items)) return []; return items.flatMap((item) => walk(item, rest)); } if (!(head in value)) return []; return walk(value[head], rest); } /** * Return [{source, target, label, collection}] for a record, mirroring the * LINK_SPECS paths used by the Rust indexer. strongRefs yield their URI. */ export function extractEdges(uri, collection, record) { const paths = LINK_SPECS[collection] || []; if (!uri || !record) return []; const edges = []; const seen = new Set(); for (const path of paths) { let segments = path.split("."); if (segments[segments.length - 1] === "uri") segments = segments.slice(0, -1); for (const target of walk(record, segments)) { const key = `${path}\u0000${target}`; if (seen.has(key)) continue; seen.add(key); edges.push({ source: uri, target, label: path, collection }); } } return edges; } // --------------------------------------------------------------------------- // YAML serialisation (hand-rolled, no dependency) // --------------------------------------------------------------------------- /** * Serialise any value to a readable YAML-ish string. Handles nested objects, * arrays, strings, numbers, booleans and null. $type is hoisted to the first * key for atproto records. This is not a full YAML 1.2 emitter, but the output * is faithful enough for inspection and highlight.js. */ export function toYaml(value, indent = 0) { const pad = " ".repeat(indent); const deeper = indent + 1; if (value === null || value === undefined) return `${pad}null`; if (typeof value === "string") { if (value.includes("\n")) { const lines = value.split("\n"); const out = [`${pad}|`]; for (const line of lines) out.push(`${pad} ${line}`); return out.join("\n"); } if (/[:\{\}\[\],&*#?|>!%@`"'\n]/.test(value) || /^\s/.test(value) || /\s$/.test(value)) { return `${pad}"${value.replace(/"/g, '\\"')}"`; } if (value === "true" || value === "false" || value === "yes" || value === "no" || value === "null" || value === "~" || /^-?[\d.]+$/.test(value)) { return `${pad}"${value}"`; } return `${pad}${value}`; } if (typeof value === "number") return `${pad}${String(value)}`; if (typeof value === "boolean") return `${pad}${String(value)}`; if (Array.isArray(value)) { if (value.length === 0) return `${pad}[]`; const out = []; for (const item of value) { if (typeof item === "object" && item !== null) { const child = toYaml(item, deeper); out.push(`${pad}-${child.slice(pad.length + 1)}`); } else { const child = toYaml(item, 0); out.push(`${pad}- ${child.trimStart()}`); } } return out.join("\n"); } if (typeof value === "object") { const keys = Object.keys(value); if (keys.length === 0) return `${pad}{}`; const ordered = keys.filter((key) => key !== "$type"); if (keys.includes("$type")) ordered.unshift("$type"); const out = []; for (const key of ordered) { const childValue = value[key]; if (typeof childValue === "object" && childValue !== null) { out.push(`${pad}${key}:`); out.push(toYaml(childValue, deeper)); } else { const valStr = toYaml(childValue, 0).trimStart(); out.push(`${pad}${key}: ${valStr}`); } } return out.join("\n"); } return `${pad}${String(value)}`; } export function pdslsUrl(uri) { return `https://pdsls.dev/${uri}`; } export function shortDid(did, maxLen = 20) { if (!did) return ""; if (did.length <= maxLen) return did; const parts = did.split(":"); if (parts.length >= 3) { const method = parts.slice(0, 2).join(":"); const id = parts.slice(2).join(":"); const keep = maxLen - method.length - 5; if (keep <= 0) return `${method}:...`; return `${method}:${id.slice(0, keep)}...`; } return `${did.slice(0, maxLen - 1)}...`; } // --------------------------------------------------------------------------- // Graph build and visibility state // --------------------------------------------------------------------------- /** * Normalise graph.json into D3-friendly nodes and edges. Edge `from`/`to` * remain string URIs; d3.forceLink mutates `source`/`target` in place, so the * visibility code must key off from/to. */ export function buildGraph(data) { const nodes = []; const nodeIds = new Set(); for (const node of data?.nodes || []) { if (!node || typeof node.uri !== "string" || nodeIds.has(node.uri)) continue; nodeIds.add(node.uri); nodes.push({ ...node, id: node.id || node.uri }); } const edges = []; const edgeKeys = new Set(); for (const edge of data?.edges || []) { if (!edge || !nodeIds.has(edge.source) || !nodeIds.has(edge.target)) continue; const key = `${edge.source}\u0000${edge.target}\u0000${edge.label || ""}`; if (edgeKeys.has(key)) continue; edgeKeys.add(key); edges.push({ ...edge, from: edge.source, to: edge.target }); } return { nodes, edges }; } /** * Holds collection filters, the focused node, and the derived 1-hop * neighbourhood. UI code only asks it what should be visible or highlighted. */ export class GraphModel { constructor(nodes, edges) { this.nodes = nodes; this.edges = edges; this.hiddenCollections = new Set(); this.focus = null; this.byId = new Map(); this.neighbors = new Map(); for (const node of nodes) { this.byId.set(node.id, node); this.neighbors.set(node.id, new Set()); } for (const edge of edges) { this.neighbors.get(edge.from)?.add(edge.to); this.neighbors.get(edge.to)?.add(edge.from); } } setCollectionVisible(collection, visible) { if (visible) this.hiddenCollections.delete(collection); else this.hiddenCollections.add(collection); } isCollectionVisible(collection) { return !this.hiddenCollections.has(collection); } visibleNodes() { return this.nodes.filter((node) => this.isCollectionVisible(node.collection)); } visibleEdges() { const ids = new Set(this.visibleNodes().map((node) => node.id)); return this.edges.filter((edge) => ids.has(edge.from) && ids.has(edge.to)); } collectionCounts() { const counts = new Map(); for (const node of this.nodes) { counts.set(node.collection, (counts.get(node.collection) || 0) + 1); } return [...counts.entries()].sort((a, b) => nsidLabel(a[0]).localeCompare(nsidLabel(b[0]))); } setFocus(id) { this.focus = this.byId.has(id) ? id : null; return this.focus !== null; } clearFocus() { this.focus = null; } toggleFocus(id) { if (this.focus === id) { this.clearFocus(); return false; } return this.setFocus(id); } hasFocus() { return this.focus !== null; } focusNode() { return this.focus ? this.byId.get(this.focus) : null; } isFocusConnected(id) { if (!this.focus) return true; return id === this.focus || this.neighbors.get(this.focus)?.has(id) === true; } }