web-check / app.js
model-guard's picture
Model Guard web check
0c61687 verified
Raw History Blame Contribute Delete
75 kB
/* Model Guard static web check (browser port of the hf-model-guard CLI, v0.2.2). * Apache-2.0. https://github.com/model-guard/hf-model-guard * * Defensive only: reads public Hugging Face endpoints anonymously from the visitor's browser. * Nothing from a scanned repo is executed, unpickled or rendered as HTML. No analytics, no trackers, * no third-party scripts, no tokens. */ "use strict"; const VERSION = "0.2.2-static"; const HF = "https://huggingface.co"; const MAX_PICKLE_FULL = 25 * 1024 * 1024; const PICKLE_HEADER_STEPS = [1024 * 1024, 8 * 1024 * 1024]; const GGUF_HEADER_STEPS = [4 * 1024 * 1024, 24 * 1024 * 1024]; const MAX_DEPTH = 5; // ---------------------------------------------------------------- rules (mirror of model_guard/rules.py) const PICKLE_EXT = [".bin", ".pt", ".pth", ".pkl", ".pickle", ".ckpt", ".joblib", ".dat", ".npy", ".npz"]; const SAFE_EXT = [".safetensors"]; const KERAS_EXT = [".h5", ".keras", ".hdf5"]; const TEXT_EXT = [".json", ".md", ".py", ".txt", ".yml", ".yaml", ".cfg", ".jinja", ".toml", ".ini", ".env", ".sh"]; const WEIGHT_EXT = [...SAFE_EXT, ...PICKLE_EXT, ".gguf", ".onnx", ".msgpack", ".h5"]; const UNCENSORED_RE = /\b(abliterat\w*|uncensored|unaligned|decensored|lorablated|orthogonali[sz]ed|refusal[- ]?(removed|ablation|direction)|no[- ]?guardrails|jailbr[eo]ak\w*|heretic)\b/gi; const KNOWN_ORGS = ["meta-llama", "facebook", "Qwen", "mistralai", "google", "microsoft", "deepseek-ai", "openai", "nvidia", "ibm-granite", "allenai", "tiiuae", "stabilityai", "black-forest-labs", "HuggingFaceTB", "huggingface", "bigscience", "EleutherAI", "01-ai", "THUDM", "zai-org", "moonshotai", "xai-org", "CohereForAI", "CohereLabs", "apple", "amazon", "Salesforce", "intel", "Nutanix", "unsloth", "bartowski", "TheBloke", "mlx-community", "lmstudio-community", "sentence-transformers"]; const LOOKALIKE_ALLOW = new Set(["openai-community", "mistral-community", "google-bert", "google-t5", "facebookai", "hugging-quants", "huggingfaceh4", "huggingfacem4", "huggingfacefw", "huggingface-course", "nvidia-community", "microsoft-community", "intel-community"]); const FAMILIES = { "llama": ["meta-llama"], "meta-llama": ["meta-llama"], "qwen": ["Qwen"], "qwq": ["Qwen"], "mistral": ["mistralai"], "mixtral": ["mistralai"], "gemma": ["google"], "phi-": ["microsoft"], "deepseek": ["deepseek-ai"], "gpt-oss": ["openai"], "gpt2": ["openai-community"], "olmo": ["allenai"], "falcon": ["tiiuae"], "granite": ["ibm-granite"], "nemotron": ["nvidia"], "glm": ["zai-org", "THUDM"], "chatglm": ["THUDM", "zai-org"], "kimi": ["moonshotai"], "grok": ["xai-org"], "smollm": ["HuggingFaceTB"], "command-r": ["CohereForAI", "CohereLabs"], }; const FIRST_PARTY_ORGS = new Set(Object.values(FAMILIES).flat().map(o => o.toLowerCase())); const SECRET_PATTERNS = { "Hugging Face token": /\bhf_[A-Za-z0-9]{30,}\b/g, "OpenAI-style key": /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g, "Anthropic key": /\bsk-ant-[A-Za-z0-9_-]{20,}\b/g, "AWS access key id": /\bAKIA[0-9A-Z]{16}\b/g, "GitHub token": /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{40,}\b/g, "Slack token": /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g, "Google API key": /\bAIza[0-9A-Za-z_-]{35}\b/g, "W&B key assignment": /WANDB_API_KEY\s*[=:]\s*['"]?[0-9a-f]{40}/g, }; const CODE_PATTERNS = { "process execution": /\b(os\.system|os\.popen|subprocess\.|pty\.spawn)/g, "dynamic code eval": /(?<![.\w])(eval|exec)\s*\(|__import__\s*\(/g, "network access": /\b(requests\.(get|post|put)|urllib\.request|http\.client|socket\.socket|httpx\.)/g, "env / credential access": /os\.environ|os\.getenv|\.netrc|\.ssh\/|HF_TOKEN|AWS_SECRET|OPENAI_API_KEY/g, "encoded / compressed blobs": /base64\.b64decode|codecs\.decode\(|marshal\.loads|zlib\.decompress|bz2\.decompress/g, }; const TEMPLATE_FLAG = /https?:\/\/|\bcurl\s|\bwget\s|base64|\bexec\b|\bimport\s/g; const DISCLAIMER = "A low risk score is not proof of safety. Model Guard reads public metadata and small files only; " + "behaviour hidden inside model weights (for example a trigger-phrase backdoor in safetensors) " + "cannot be detected by static scanning, neither by this tool nor by pickle scanners."; const ADVICE = "Prefer official or verified publishers, pin a revision sha, avoid pickle formats, review remote code " + "before trust_remote_code=True, and run unfamiliar models sandboxed with no secrets in the environment."; const RISK_LEVELS = [[70, "CRITICAL"], [45, "HIGH"], [20, "MEDIUM"], [0, "LOW"]]; const PROV_LEVELS = [[40, "UNVERIFIABLE"], [15, "PARTLY VERIFIABLE"], [0, "TRACEABLE"]]; // ---------------------------------------------------------------- small helpers const ends = (s, exts) => exts.some(e => s.endsWith(e)); const uniqSorted = arr => [...new Set(arr)].sort(); const matchAll = (re, s) => [...String(s || "").matchAll(re)].map(m => m[0]); const nowMs = () => Date.now(); const ageDays = d => d ? Math.floor((nowMs() - d.getTime()) / 86400000) : null; const objectIdTime = oid => { const t = parseInt(String(oid || "").slice(0, 8), 16); return isFinite(t) ? new Date(t * 1000) : null; }; const encPath = p => p.split("/").map(encodeURIComponent).join("/"); const resolveUrl = (repo, rev, path) => `${HF}/${repo}/resolve/${encodeURIComponent(rev)}/${encPath(path)}`; class Stats { constructor(signal) { this.denied = 0; this.requests = 0; this.rateLimited = 0; this.timeouts = 0; this.signal = signal || null; } } class ScanAborted extends Error {} const sleep = (ms, signal) => new Promise((res, rej) => { const t = setTimeout(res, ms); if (signal) signal.addEventListener("abort", () => { clearTimeout(t); rej(new ScanAborted("aborted")); }, { once: true }); }); const JSON_TIMEOUT_MS = 30000, BYTES_TIMEOUT_MS = 120000, RETRIES = 3; // One fetch with a timeout, gentle retries on rate limits / transient errors, and cancellation when a new scan starts. // Returns {status, response} where status 0 means a network error or timeout. Never sends cookies or tokens. async function hfFetch(url, headers, stats, timeoutMs) { for (let attempt = 0; ; attempt++) { if (stats && stats.signal && stats.signal.aborted) throw new ScanAborted("aborted"); if (stats) stats.requests++; const ctl = new AbortController(); const timer = setTimeout(() => ctl.abort(), timeoutMs); const onAbort = () => ctl.abort(); if (stats && stats.signal) stats.signal.addEventListener("abort", onAbort, { once: true }); let r = null, timedOut = false; try { r = await fetch(url, { headers: headers || {}, credentials: "omit", referrerPolicy: "no-referrer", signal: ctl.signal }); } catch (e) { timedOut = !(stats && stats.signal && stats.signal.aborted); } finally { clearTimeout(timer); if (stats && stats.signal) stats.signal.removeEventListener("abort", onAbort); } if (stats && stats.signal && stats.signal.aborted) throw new ScanAborted("aborted"); const transient = !r || r.status === 429 || r.status === 502 || r.status === 503 || r.status === 504; if (!transient || attempt >= (r ? RETRIES - 1 : 1)) { // network errors/timeouts retry once, rate limits up to 3 tries if (r && r.status === 429 && stats) stats.rateLimited++; if (!r && timedOut && stats) stats.timeouts++; return { status: r ? r.status : 0, response: r }; } let wait = 1000 * 2 ** attempt; const ra = r && parseFloat(r.headers.get("retry-after") || ""); if (isFinite(ra) && ra > 0) wait = Math.min(ra * 1000, 15000); if (stats && stats.onWait && r && r.status === 429) stats.onWait(wait); await sleep(wait, stats && stats.signal); } } async function getJSON(url, stats) { const { status, response } = await hfFetch(url, {}, stats, JSON_TIMEOUT_MS); let body = null; if (response) { try { body = await response.json(); } catch (e) { /* not JSON */ } } return { status, body, error: status === 0 ? "network error or timeout" : null }; } async function getBytes(url, limit, rangeOnly, stats, countDenied = true) { const { status, response } = await hfFetch(url, rangeOnly ? { Range: `bytes=0-${limit - 1}` } : {}, stats, BYTES_TIMEOUT_MS); if (status === 401 || status === 403) { if (stats && countDenied) stats.denied++; return null; } if (status !== 200 && status !== 206) return null; let buf; try { buf = new Uint8Array(await response.arrayBuffer()); } catch (e) { if (stats && stats.signal && stats.signal.aborted) throw new ScanAborted("aborted"); return null; } return buf.length > limit ? buf.slice(0, limit) : buf; } async function getRange(url, start, endIncl, stats) { const { status, response } = await hfFetch(url, { Range: `bytes=${start}-${endIncl}` }, stats, BYTES_TIMEOUT_MS); if (status !== 206 && status !== 200) return { status }; const buf = new Uint8Array(await response.arrayBuffer()); return { status, bytes: status === 200 ? buf.slice(start, endIncl + 1) : buf }; } async function pool(items, n, fn) { const out = new Array(items.length); let i = 0; await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => { while (i < items.length) { const k = i++; out[k] = await fn(items[k], k); } })); return out; } const dec = new TextDecoder("utf-8", { fatal: false }); const latin1 = new TextDecoder("latin1"); // ---------------------------------------------------------------- pickle opcode walker (never executes) const SAFE_GLOBALS = { "collections": ["OrderedDict", "defaultdict"], "torch._utils": ["_rebuild_tensor_v2", "_rebuild_parameter", "_rebuild_tensor", "_rebuild_qtensor", "_rebuild_parameter_with_state", "_rebuild_device_tensor_from_numpy"], "torch": ["FloatStorage", "HalfStorage", "BFloat16Storage", "DoubleStorage", "LongStorage", "IntStorage", "ShortStorage", "CharStorage", "ByteStorage", "BoolStorage", "float32", "float16", "bfloat16", "int64", "int32", "Size", "device", "dtype"], "torch._tensor": ["_rebuild_from_type_v2"], "numpy.core.multiarray": ["_reconstruct", "scalar"], "numpy._core.multiarray": ["_reconstruct", "scalar"], "numpy": ["ndarray", "dtype"], "builtins": ["set", "frozenset", "dict", "list", "tuple", "int", "float", "str", "bytes", "bytearray", "slice", "complex"], "_codecs": ["encode"], }; const STAR = "*"; const DANGEROUS = { "os": STAR, "posix": STAR, "nt": STAR, "subprocess": STAR, "sys": STAR, "socket": STAR, "shutil": STAR, "runpy": STAR, "pty": STAR, "webbrowser": STAR, "requests": STAR, "urllib": STAR, "urllib.request": STAR, "http.client": STAR, "importlib": STAR, "pickle": STAR, "_pickle": STAR, "marshal": STAR, "types": STAR, "ctypes": STAR, "code": STAR, "commands": STAR, "asyncio": STAR, "bdb": STAR, "pdb": STAR, "timeit": STAR, "builtins": ["eval", "exec", "compile", "open", "__import__", "getattr", "setattr", "globals", "locals", "breakpoint", "input", "apply"], "__builtin__": ["eval", "exec", "compile", "open", "__import__", "getattr", "apply"], "operator": ["attrgetter", "methodcaller", "itemgetter"], "functools": ["partial", "reduce"], }; function classify(mod, name) { const d = DANGEROUS[mod]; if (d === STAR || (Array.isArray(d) && d.includes(name))) return "dangerous"; if (DANGEROUS[mod.split(".")[0]] === STAR) return "dangerous"; if ((SAFE_GLOBALS[mod] || []).includes(name)) return "safe"; return "unknown"; } // opcode byte -> [name, argument kind] const OPS = { 0x28: ["MARK"], 0x2e: ["STOP"], 0x30: ["POP"], 0x31: ["POP_MARK"], 0x32: ["DUP"], 0x46: ["FLOAT", "line"], 0x49: ["INT", "line"], 0x4a: ["BININT", 4], 0x4b: ["BININT1", 1], 0x4c: ["LONG", "line"], 0x4d: ["BININT2", 2], 0x4e: ["NONE"], 0x50: ["PERSID", "line"], 0x51: ["BINPERSID"], 0x52: ["REDUCE"], 0x53: ["STRING", "line"], 0x54: ["BINSTRING", "len4s"], 0x55: ["SHORT_BINSTRING", "len1"], 0x56: ["UNICODE", "line"], 0x58: ["BINUNICODE", "len4"], 0x61: ["APPEND"], 0x62: ["BUILD"], 0x63: ["GLOBAL", "line2"], 0x64: ["DICT"], 0x7d: ["EMPTY_DICT"], 0x65: ["APPENDS"], 0x67: ["GET", "line"], 0x68: ["BINGET", 1], 0x69: ["INST", "line2"], 0x6a: ["LONG_BINGET", 4], 0x6c: ["LIST"], 0x5d: ["EMPTY_LIST"], 0x6f: ["OBJ"], 0x70: ["PUT", "line"], 0x71: ["BINPUT", 1], 0x72: ["LONG_BINPUT", 4], 0x73: ["SETITEM"], 0x74: ["TUPLE"], 0x29: ["EMPTY_TUPLE"], 0x75: ["SETITEMS"], 0x47: ["BINFLOAT", 8], 0x80: ["PROTO", 1], 0x81: ["NEWOBJ"], 0x82: ["EXT1", 1], 0x83: ["EXT2", 2], 0x84: ["EXT4", 4], 0x85: ["TUPLE1"], 0x86: ["TUPLE2"], 0x87: ["TUPLE3"], 0x88: ["NEWTRUE"], 0x89: ["NEWFALSE"], 0x8a: ["LONG1", "len1"], 0x8b: ["LONG4", "len4s"], 0x42: ["BINBYTES", "len4"], 0x43: ["SHORT_BINBYTES", "len1"], 0x8c: ["SHORT_BINUNICODE", "len1"], 0x8d: ["BINUNICODE8", "len8"], 0x8e: ["BINBYTES8", "len8"], 0x8f: ["EMPTY_SET"], 0x90: ["ADDITEMS"], 0x91: ["FROZENSET"], 0x92: ["NEWOBJ_EX"], 0x93: ["STACK_GLOBAL"], 0x94: ["MEMOIZE"], 0x95: ["FRAME", 8], 0x96: ["BYTEARRAY8", "len8"], 0x97: ["NEXT_BUFFER"], 0x98: ["READONLY_BUFFER"], }; const STRING_OPS = new Set(["SHORT_BINUNICODE", "BINUNICODE", "UNICODE", "BINUNICODE8", "SHORT_BINSTRING", "BINSTRING", "STRING"]); function pyByteRepr(c) { // mirrors Python's repr(bytes([c])) so error text matches the CLI const ch = c === 0x5c ? "\\\\" : c === 0x27 ? null : c === 0x09 ? "\\t" : c === 0x0a ? "\\n" : c === 0x0d ? "\\r" : (c >= 0x20 && c < 0x7f) ? String.fromCharCode(c) : "\\x" + c.toString(16).padStart(2, "0"); return ch === null ? `b"'"` : `b'${ch}'`; } function walkPickle(b, pos) { // returns {found, error, ok, pos} const found = []; let strings = []; const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); const need = n => { if (pos + n > b.length) throw new Error(`not enough data in stream to read ${{1:"uint1",2:"uint2",4:"uint4",8:"uint8"}[n] || n + " byte(s)"}`); }; const line = () => { const i = b.indexOf(0x0a, pos); if (i < 0) throw new Error("no newline found when trying to read line"); const s = latin1.decode(b.subarray(pos, i)); pos = i + 1; return s; }; try { for (;;) { need(1); const code = b[pos++]; const op = OPS[code]; if (!op) throw new Error(`at position ${pos - 1}, opcode ${pyByteRepr(code)} unknown`); const [name, kind] = op; let arg = null; if (kind === "line") arg = line(); else if (kind === "line2") arg = line() + " " + line(); else if (typeof kind === "number") { need(kind); pos += kind; } else if (kind) { let n; if (kind === "len1") { need(1); n = b[pos]; pos += 1; } else if (kind === "len4") { need(4); n = dv.getUint32(pos, true); pos += 4; } else if (kind === "len4s") { need(4); n = dv.getInt32(pos, true); pos += 4; if (n < 0) throw new Error("negative length"); } else { need(8); n = Number(dv.getBigUint64(pos, true)); pos += 8; } need(n); if (STRING_OPS.has(name)) arg = (name.includes("UNICODE") ? dec : latin1).decode(b.subarray(pos, pos + n)); pos += n; } if (STRING_OPS.has(name)) { let s = arg; if (name === "STRING") s = s.replace(/^(['"])(.*)\1$/s, "$2"); strings = strings.concat([s]).slice(-8); } else if (name === "GLOBAL" || name === "INST") { const i = arg.indexOf(" "); found.push([arg.slice(0, i), arg.slice(i + 1)]); } else if (name === "STACK_GLOBAL") { found.push(strings.length >= 2 ? [strings[strings.length - 2], strings[strings.length - 1]] : ["<unresolved>", "<unresolved>"]); } else if (name === "STOP") { return { found, error: null, ok: true, pos }; } } } catch (e) { return { found, error: `ValueError: ${e.message}`, ok: false, pos }; } } function summarise(found, error, member) { const seen = new Set(), out = []; for (const [m, n] of found) { const k = m + "\u0000" + n; if (seen.has(k)) continue; seen.add(k); out.push({ module: m, name: n, class: m === "<unresolved>" ? "unknown" : classify(m, n) }); } return { member: member ?? null, globals: out, error }; } function scanPickleBytes(b, maxPickles = 6) { let pos = 0, all = [], err = null; for (let i = 0; i < maxPickles; i++) { if (pos >= b.length) break; const r = walkPickle(b, pos); all = all.concat(r.found); err = r.error; pos = r.pos; if (!r.ok) break; } return summarise(all, err); } async function inflateRaw(data) { const ds = new DecompressionStream("deflate-raw"); const out = await new Response(new Blob([data]).stream().pipeThrough(ds)).arrayBuffer(); return new Uint8Array(out); } async function scanFileBytes(b) { // whole file: raw pickle(s) or a zip checkpoint (every *.pkl member, via the central directory) if (!(b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04)) return [scanPickleBytes(b)]; const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); let eocd = -1; for (let i = b.length - 22; i >= Math.max(0, b.length - 65557); i--) if (dv.getUint32(i, true) === 0x06054b50) { eocd = i; break; } if (eocd < 0) return [{ member: null, globals: [], error: "BadZipFile: end of central directory not found" }]; const n = dv.getUint16(eocd + 10, true); let p = dv.getUint32(eocd + 16, true); const res = []; for (let k = 0; k < n && p + 46 <= b.length; k++) { if (dv.getUint32(p, true) !== 0x02014b50) break; const method = dv.getUint16(p + 10, true), csize = dv.getUint32(p + 20, true); const nl = dv.getUint16(p + 28, true), xl = dv.getUint16(p + 30, true), cl = dv.getUint16(p + 32, true); const lho = dv.getUint32(p + 42, true); const name = dec.decode(b.subarray(p + 46, p + 46 + nl)); p += 46 + nl + xl + cl; if (!name.endsWith(".pkl")) continue; const start = lho + 30 + dv.getUint16(lho + 26, true) + dv.getUint16(lho + 28, true); let body = b.subarray(start, start + csize); if (method === 8) { try { body = await inflateRaw(body); } catch (e) { res.push({ member: name, globals: [], error: "could not decompress member" }); continue; } } else if (method !== 0) { res.push({ member: name, globals: [], error: `unsupported compression ${method}` }); continue; } res.push({ ...scanPickleBytes(body), member: name }); } return res; } function scanHeaderBytes(head) { if (head[0] === 0x50 && head[1] === 0x4b && head[2] === 0x03 && head[3] === 0x04) { if (head.length < 30) return [[], "header too short"]; const dv = new DataView(head.buffer, head.byteOffset, head.byteLength); const method = dv.getUint16(8, true), csize = dv.getUint32(18, true), nl = dv.getUint16(26, true), xl = dv.getUint16(28, true); const name = dec.decode(head.subarray(30, 30 + nl)), start = 30 + nl + xl; if (!name.endsWith(".pkl")) return [[], `first zip member is '${name}', not a pickle; header scan not possible`]; if (method !== 0) return [[], `first member '${name}' is compressed (method ${method}); header scan not possible`]; const body = (csize !== 0 && csize !== 0xFFFFFFFF) ? head.subarray(start, start + csize) : head.subarray(start); const r = scanPickleBytes(body, 1); r.member = name; return [[r], null]; } if (head[0] === 0x80) return [[scanPickleBytes(head)], null]; return [[], "not a recognised pickle or PyTorch zip header"]; } // ---------------------------------------------------------------- GGUF header (bounded) const GGUF_KEEP = ["general.", "tokenizer.chat_template", "tokenizer.ggml.model", "quantize."]; function parseGguf(b) { const out = { version: null, metadata: {}, complete: false, error: null }; const dv = new DataView(b.buffer, b.byteOffset, b.byteLength); let p = 0; class Trunc extends Error {} const take = n => { if (p + n > b.length) throw new Trunc(); const s = b.subarray(p, p + n); p += n; return s; }; const u32 = () => { take(4); return dv.getUint32(p - 4, true); }; const u64 = () => { take(8); return Number(dv.getBigUint64(p - 8, true)); }; const str = () => { const n = u64(); if (n > 50e6) throw new Error("string length out of bounds"); return dec.decode(take(n)); }; const sizes = { 0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8 }; const scalar = t => { const n = sizes[t]; take(n); const q = p - n; switch (t) { case 0: return dv.getUint8(q); case 1: return dv.getInt8(q); case 2: return dv.getUint16(q, true); case 3: return dv.getInt16(q, true); case 4: return dv.getUint32(q, true); case 5: return dv.getInt32(q, true); case 6: return dv.getFloat32(q, true); case 7: return dv.getUint8(q) !== 0; case 10: return Number(dv.getBigUint64(q, true)); case 11: return Number(dv.getBigInt64(q, true)); case 12: return dv.getFloat64(q, true); } }; const value = (t, keep) => { if (t in sizes) return scalar(t); if (t === 8) { if (keep) return str(); take(u64()); return null; } if (t === 9) { const it = u32(), n = u64(); if (n > 2e6) throw new Error("array length out of bounds"); const small = keep && n <= 16, vals = []; for (let i = 0; i < n; i++) { const v = value(it, small); if (small) vals.push(v); } return small ? vals : `<array of ${n}>`; } throw new Error(`unknown GGUF value type ${t}`); }; try { if (dec.decode(take(4)) !== "GGUF") { out.error = "not a GGUF file"; return out; } out.version = u32(); out.tensor_count = u64(); out.kv_count = u64(); if (out.kv_count > 10000) throw new Error("kv_count out of bounds"); for (let i = 0; i < out.kv_count; i++) { const k = str(), t = u32(), keep = GGUF_KEEP.some(x => k.startsWith(x)), v = value(t, keep); if (keep) out.metadata[k] = v; } out.complete = true; } catch (e) { out.error = e instanceof Trunc ? "header larger than bytes read (partial metadata)" : `ValueError: ${e.message}`; } return out; } // ---------------------------------------------------------------- safetensors header layout (HTTP Range) async function stFileHeader(repo, rev, path, stats) { // one Range request usually covers the 8-byte length prefix and the whole JSON header; a second only if it is bigger const url = resolveUrl(repo, rev, path), FIRST = 256 * 1024; const a = await getRange(url, 0, FIRST - 1, stats); if (a.status === 401 || a.status === 403) throw new Error("gated"); if (!a.bytes || a.bytes.length < 8) throw new Error(`HTTP ${a.status}`); const n = Number(new DataView(a.bytes.buffer, a.bytes.byteOffset, 8).getBigUint64(0, true)); if (n > 100e6) throw new Error("header too large"); let hb; if (8 + n <= a.bytes.length) hb = a.bytes.subarray(8, 8 + n); else { const h = await getRange(url, a.bytes.length, 8 + n - 1, stats); if (!h.bytes) throw new Error(`HTTP ${h.status}`); hb = new Uint8Array(n); hb.set(a.bytes.subarray(8)); hb.set(h.bytes, a.bytes.length - 8); } const j = JSON.parse(dec.decode(hb)); delete j.__metadata__; return j; } async function safetensorsMeta(repo, rev, siblings, stats) { const names = siblings.map(s => s.rfilename); let files; if (names.includes("model.safetensors")) files = ["model.safetensors"]; else if (names.includes("model.safetensors.index.json")) { const r = await getBytes(resolveUrl(repo, rev, "model.safetensors.index.json"), 20e6, false, stats, false); if (!r) throw new Error("gated"); files = uniqSorted(Object.values(JSON.parse(dec.decode(r)).weight_map || {})); } else throw new Error("NotASafetensorsRepoError"); const tensors = {}; const heads = await pool(files, 6, f => stFileHeader(repo, rev, f, stats)); heads.forEach(h => Object.assign(tensors, h)); let params = 0; for (const t of Object.values(tensors)) params += (t.shape || []).reduce((x, y) => x * y, 1); return { tensors, params }; } // ---------------------------------------------------------------- lineage function normBase(b) { if (typeof b !== "string") return null; const s = b.trim().replace(/^https?:\/\/(www\.)?huggingface\.co\//, "").split("?")[0].replace(/^\/+|\/+$/g, ""); const parts = s.split("/"); return parts.length >= 2 && parts[0] && parts[1] ? parts.slice(0, 2).join("/") : null; } function basesOf(card) { const b = (card || {}).base_model; const lst = typeof b === "string" ? [b] : Array.isArray(b) ? b : []; return lst.map(normBase).filter(Boolean); } const isFirstPartyOrg = o => FIRST_PARTY_ORGS.has(String(o || "").toLowerCase()); async function resolveLineage(repoId, bases, fetchNode, maxDepth = MAX_DEPTH) { const owner = repoId.split("/")[0]; const chain = [{ repo: repoId, owner, status: "ok", first_party_org: isFirstPartyOrg(owner), other_bases: bases.slice(1) }]; if (isFirstPartyOrg(owner)) return { chain, end: "first_party", root: repoId, broken_at: null }; if (!bases.length) return { chain, end: "no_base", root: repoId, broken_at: null }; const seen = new Set([repoId.toLowerCase()]); let nxt = bases[0]; for (;;) { if (seen.has(nxt.toLowerCase())) { chain.push({ repo: nxt, owner: nxt.split("/")[0], status: "cycle" }); return { chain, end: "cycle", root: null, broken_at: nxt }; } if (chain.length > maxDepth) { chain.push({ repo: nxt, owner: nxt.split("/")[0], status: "not_followed" }); return { chain, end: "depth_cap", root: null, broken_at: nxt }; } seen.add(nxt.toLowerCase()); const o = nxt.split("/")[0]; const r = (await fetchNode(nxt)) || { status: "error" }; const node = { repo: nxt, owner: o, status: r.status, first_party_org: isFirstPartyOrg(o), other_bases: (r.bases || []).slice(1) }; if (r.message) node.message = r.message; chain.push(node); if (isFirstPartyOrg(o)) return { chain, end: "first_party", root: nxt, broken_at: null }; if (r.status !== "ok") return { chain, end: "broken", root: null, broken_at: nxt }; if (!(r.bases || []).length) return { chain, end: "no_base", root: nxt, broken_at: null }; nxt = r.bases[0]; } } function chainStr(lin) { return lin.chain.map(n => { let tag = { gated: " [gated: chain broken here]", not_found: " [missing: chain broken here]", error: " [unreadable: chain broken here]", cycle: " [cycle]", not_followed: ` [depth cap ${MAX_DEPTH} reached]` }[n.status] || ""; if (n.status === "gated" && n.first_party_org) tag = " [gated]"; return n.repo + tag; }).join(" -> "); } // ---------------------------------------------------------------- collection function familyOf(name) { const n = name.toLowerCase(); for (const fam of Object.keys(FAMILIES).sort((a, b) => b.length - a.length)) if (n.startsWith(fam)) return fam; return null; } function kindOf(fn) { const low = fn.toLowerCase(); if (ends(low, PICKLE_EXT)) return "pickle"; if (ends(low, SAFE_EXT)) return "safetensors"; if (ends(low, KERAS_EXT)) return "keras"; for (const [e, k] of [[".gguf", "gguf"], [".onnx", "onnx"], [".py", "python"]]) if (low.endsWith(e)) return k; return "other"; } const weightsOf = sibs => Object.fromEntries((sibs || []).filter(s => ends(s.rfilename.toLowerCase(), WEIGHT_EXT) && s.lfs) .map(s => [s.rfilename, [s.lfs.sha256, s.size]])); async function modelInfo(repo, rev, stats) { const url = rev ? `${HF}/api/models/${repo}/revision/${encodeURIComponent(rev)}?blobs=true&securityStatus=true` : `${HF}/api/models/${repo}?blobs=true&securityStatus=true`; return getJSON(url, stats); } async function ownerInfo(owner, stats) { const org = await getJSON(`${HF}/api/organizations/${encodeURIComponent(owner)}/overview`, stats); if (org.status === 200 && org.body && org.body._id) { const c = objectIdTime(org.body._id), o = org.body; return { type: "org", name: owner, fullname: o.fullname, verified: !!o.isVerified, plan: o.plan, members: o.numUsers, models: o.numModels, followers: o.numFollowers, created: c ? c.toISOString() : null, age_days: ageDays(c) }; } const usr = await getJSON(`${HF}/api/users/${encodeURIComponent(owner)}/overview`, stats); if (usr.status === 200 && usr.body && usr.body._id) { const c = objectIdTime(usr.body._id), u = usr.body; return { type: "user", name: owner, fullname: u.fullname, verified: false, pro: u.isPro, models: u.numModels, followers: u.numFollowers, orgs: (u.orgs || []).map(x => x.name).slice(0, 15), created: c ? c.toISOString() : null, age_days: ageDays(c) }; } return { type: "unknown", name: owner, verified: false, created: null, age_days: null }; } async function compareBase(facts, info, base, source, cfg, stats) { const out = { name: base, source }; const r = await modelInfo(base, null, stats); if (r.status === 401 || r.status === 404) { out.error = "base repo not found or not public"; return out; } if (r.status !== 200 || !r.body) { out.error = `HTTP ${r.status}`; return out; } const binfo = r.body; const mine = weightsOf(info.siblings), theirs = weightsOf(binfo.siblings); const myH = new Set(Object.values(mine).map(v => v[0])), thH = new Set(Object.values(theirs).map(v => v[0])); const inter = [...myH].filter(h => thH.has(h)).length; const rel = (facts.tags || []).filter(t => t.startsWith("base_model:") && t.split(":").length >= 3); const bcfg = binfo.config || {}; const archDiff = {}; for (const k of ["model_type", "architectures"]) if (cfg[k] && bcfg[k] && JSON.stringify(cfg[k]) !== JSON.stringify(bcfg[k])) archDiff[k] = [cfg[k], bcfg[k]]; Object.assign(out, { owner: binfo.author, base_gated: !!binfo.gated, relation: source === "root" ? "root original" : (rel.length ? rel[0].split(":")[1] : (source === "inferred" ? "same-name" : "unspecified")), weight_files: Object.keys(mine).length, base_weight_files: Object.keys(theirs).length, identical_hashes: inter, all_identical: Object.keys(mine).length > 0 && myH.size === thH.size && inter === myH.size, total_weight_bytes: Object.values(mine).reduce((a, v) => a + (v[1] || 0), 0), base_total_weight_bytes: Object.values(theirs).reduce((a, v) => a + (v[1] || 0), 0), arch_diff: archDiff, }); if (facts.format.safetensors && Object.keys(theirs).some(f => f.endsWith(".safetensors"))) { try { const [sm, sb] = await Promise.all([safetensorsMeta(facts.repo_id, facts.revision, info.siblings, stats), safetensorsMeta(base, binfo.sha || "main", binfo.siblings || [], stats)]); const tm = sm.tensors, tb = sb.tensors; const added = Object.keys(tm).filter(k => !(k in tb)).sort(), removed = Object.keys(tb).filter(k => !(k in tm)).sort(); const common = Object.keys(tm).filter(k => k in tb); out.tensors = { count: Object.keys(tm).length, base_count: Object.keys(tb).length, added: added.slice(0, 30), removed: removed.slice(0, 30), n_added: added.length, n_removed: removed.length, shape_changed: common.filter(k => JSON.stringify(tm[k].shape) !== JSON.stringify(tb[k].shape)).sort().slice(0, 30), dtype_changed: common.filter(k => tm[k].dtype !== tb[k].dtype).length, params: sm.params, base_params: sb.params, adapter_like_added: added.filter(k => /lora|adapter|trigger|hook|extra/i.test(k)).slice(0, 10), }; } catch (e) { out.tensors = { error: /gated|401|403/.test(String(e.message)) ? "gated" : (e.message || "error") }; } } return out; } async function collect(repoId, revision, progress = () => {}, signal = null) { const stats = new Stats(signal); stats.onWait = ms => progress(`Hugging Face asked us to slow down; waiting ${Math.round(ms / 1000)} s`); const facts = { repo_id: repoId, status: "ok", scanned_at: new Date().toISOString(), engine: VERSION }; progress("Reading repo metadata"); const r = await modelInfo(repoId, revision, stats); if (r.status === 401 || r.status === 404) { return Object.assign(facts, { status: "not_found", message: revision && r.status === 404 ? `Revision '${revision}' not found.` : "Repo not found or not public (it may be private, renamed or deleted)." }); } if (r.status === 429) return Object.assign(facts, { status: "rate_limited", message: "Hugging Face's anonymous rate limit was reached. Wait a minute and try again." }); if (r.status === 0) return Object.assign(facts, { status: "error", message: "Could not reach huggingface.co (network error or timeout). Check your connection, or try again later." }); if (r.status !== 200 || !r.body || !Array.isArray(r.body.siblings)) return Object.assign(facts, { status: "error", message: `Hugging Face returned an unexpected response (HTTP ${r.status}). Try again later.` }); const info = r.body; if (info.id && info.id !== repoId) { // the Hub resolves case differences and renamed repos; scan the canonical id it reports facts.requested_as = repoId; repoId = info.id; facts.repo_id = repoId; } const owner = repoId.includes("/") ? repoId.split("/")[0] : (info.author || ""); const name = repoId.split("/").pop(); const card = info.cardData || {}; const created = info.createdAt ? new Date(info.createdAt) : null; progress("Reading publisher profile"); Object.assign(facts, { revision: info.sha, tags: info.tags || [], owner: await ownerInfo(owner, stats), repo: { created: created ? created.toISOString() : null, age_days: ageDays(created), last_modified: info.lastModified || null, downloads_30d: info.downloads, likes: info.likes, gated: info.gated || false, license: card.license ?? null, pipeline: info.pipeline_tag ?? null, library: info.library_name ?? null }, declared_base: basesOf(card), family: familyOf(familyOf(name) === null ? name.toLowerCase().replace(/^meta-/, "") : name), }); facts.official_orgs = facts.family ? FAMILIES[facts.family] : []; facts.hf_security = info.securityRepoStatus || {}; const files = (info.siblings || []).map(s => ({ path: s.rfilename, size: s.size, kind: kindOf(s.rfilename), sha256: s.lfs ? s.lfs.sha256 : null, lfs: !!s.lfs })); facts.files = files; facts.format = Object.fromEntries(["pickle", "safetensors", "python", "gguf", "keras", "onnx"].map(k => [k, files.filter(f => f.kind === k).length])); const rev = info.sha; progress("Opcode-scanning pickle files (static, nothing is executed)"); facts.pickle_scans = await pool(files.filter(f => f.kind === "pickle").slice(0, 40), 6, async f => { const size = f.size || 0, url = resolveUrl(repoId, rev, f.path); if (size <= MAX_PICKLE_FULL) { const data = await getBytes(url, MAX_PICKLE_FULL, false, stats); if (!data) return { path: f.path, mode: "unavailable", results: [] }; return { path: f.path, mode: "full", results: await scanFileBytes(data) }; } let res = [], note = null, head = null; for (const lim of PICKLE_HEADER_STEPS) { head = await getBytes(url, lim, true, stats); if (!head) break; [res, note] = scanHeaderBytes(head); if (!(res.length && res[0].error && /not enough data|no newline|STOP/.test(res[0].error))) break; } if (!head) return { path: f.path, mode: "unavailable", results: [] }; return { path: f.path, mode: res.length ? "header" : "skipped", note, results: res }; }); progress("Reading small text files (configs, model card, code)"); const texts = {}; const cands = files.filter(f => !f.lfs && (f.size || 0) < 1_000_000 && (ends(f.path.toLowerCase(), TEXT_EXT) || !f.path.split("/").pop().includes("."))).slice(0, 60); await pool(cands, 8, async f => { const b = await getBytes(resolveUrl(repoId, rev, f.path), 1_000_000, false, stats); if (b) texts[f.path] = dec.decode(b); }); const js = n => { try { return JSON.parse(texts[n] || "{}") || {}; } catch (e) { return {}; } }; const cfg = Object.keys(js("config.json")).length ? js("config.json") : (info.config || {}); const tok = js("tokenizer_config.json"); facts.auto_map = { ...(cfg.auto_map || {}), ...(tok.auto_map || {}) }; facts.python_files = files.filter(f => f.kind === "python").map(f => f.path); facts.code_patterns = {}; for (const p of facts.python_files) { const hits = {}; for (const [lab, re] of Object.entries(CODE_PATTERNS)) { const n = matchAll(re, texts[p] || "").length; if (n) hits[lab] = n; } if (Object.keys(hits).length) facts.code_patterns[p] = hits; } const readme = texts["README.md"] || ""; facts.readme_trust_remote_code = /trust_remote_code\s*=\s*True/.test(readme); facts.name_tag_terms = uniqSorted(matchAll(UNCENSORED_RE, facts.tags.join(" ") + " " + repoId).map(s => s.toLowerCase())); facts.card_terms = uniqSorted(matchAll(UNCENSORED_RE, readme).map(s => s.toLowerCase())).slice(0, 6); let tmpl = tok.chat_template || texts["chat_template.jinja"] || ""; if (Array.isArray(tmpl)) tmpl = tmpl.filter(t => t && typeof t === "object").map(t => t.template || "").join(" "); facts.chat_template_flags = uniqSorted(matchAll(TEMPLATE_FLAG, tmpl).map(s => s.trim())).slice(0, 6); facts.gguf = null; const ggufs = files.filter(f => f.kind === "gguf").sort((a, b) => (a.path.toLowerCase().includes("mmproj") - b.path.toLowerCase().includes("mmproj")) || ((a.size || 0) - (b.size || 0))); if (ggufs.length) { progress("Reading GGUF header"); const g = ggufs[0]; let meta = null; for (const lim of GGUF_HEADER_STEPS) { const head = await getBytes(resolveUrl(repoId, rev, g.path), lim, true, stats); if (!head) break; meta = parseGguf(head); if (meta.complete || !/partial/.test(meta.error || "")) break; } if (!meta) facts.gguf = { path: g.path, error: "not readable" }; else { const md = meta.metadata, gt = md["tokenizer.chat_template"] || ""; facts.gguf = { path: g.path, files: ggufs.length, version: meta.version, complete: meta.complete, error: meta.error, architecture: md["general.architecture"] ?? null, name: md["general.name"] ?? null, base_models: Object.entries(md).filter(([k]) => k.startsWith("general.base_model.") && k.endsWith(".repo_url")).map(([, v]) => v), file_type: md["general.file_type"] ?? null, has_chat_template: !!gt, chat_template_flags: uniqSorted(matchAll(TEMPLATE_FLAG, gt).map(s => s.trim())).slice(0, 6) }; } } facts.credentials = []; for (const [p, t] of Object.entries(texts)) for (const [lab, re] of Object.entries(SECRET_PATTERNS)) for (const v of matchAll(re, t)) facts.credentials.push({ file: p, type: lab, redacted: v.slice(0, 4) + "…[redacted]" }); progress("Comparing with the base model"); facts.base = null; if (facts.declared_base.length) facts.base = await compareBase(facts, info, facts.declared_base[0], "declared", cfg, stats); else if (facts.official_orgs.length && !facts.official_orgs.includes(owner)) { outer: for (const org of facts.official_orgs) for (const cand of [name, name.replace(/^Meta-/, "")]) { const t = await getJSON(`${HF}/api/models/${org}/${cand}`, stats); if (t.status === 200) { facts.base = await compareBase(facts, info, `${org}/${cand}`, "inferred", cfg, stats); break outer; } } } progress("Following base-model lineage"); const fetchNode = async repo => { const x = await getJSON(`${HF}/api/models/${repo}`, stats); if (x.status === 401 || x.status === 404) return { status: "not_found", message: "not found or not public" }; if (x.status !== 200 || !x.body) return { status: "error", message: `HTTP ${x.status}` }; return { status: "ok", bases: basesOf(x.body.cardData || {}), gated_files: !!x.body.gated }; }; facts.lineage = await resolveLineage(repoId, facts.declared_base, fetchNode); facts.lineage.chain_str = chainStr(facts.lineage); const root = facts.lineage.root; facts.root_base = null; if (root && root !== repoId && (!facts.base || facts.base.name.toLowerCase() !== root.toLowerCase())) { progress("Comparing with the root original"); facts.root_base = await compareBase(facts, info, root, "root", cfg, stats); } facts.files_denied = stats.denied; facts.requests = stats.requests; facts.requests_rate_limited = stats.rateLimited; facts.requests_timed_out = stats.timeouts; return facts; } // ---------------------------------------------------------------- assessment (mirror of model_guard/assess.py) function norm(s) { s = s.toLowerCase(); for (const [a, b] of [["rn", "m"], ["vv", "w"], ["0", "o"], ["1", "l"], ["3", "e"], ["5", "s"], ["i", "l"]]) s = s.split(a).join(b); return s.replace(/[^a-z]/g, ""); } const alnum = s => s.toLowerCase().replace(/[^a-z0-9]/g, ""); function lev(a, b) { if (a.length < b.length) [a, b] = [b, a]; let prev = Array.from({ length: b.length + 1 }, (_, i) => i); for (let i = 1; i <= a.length; i++) { const cur = [i]; for (let j = 1; j <= b.length; j++) cur.push(Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] !== b[j - 1] ? 1 : 0))); prev = cur; } return prev[prev.length - 1]; } const SUFFIX = /^(official|ai|hf|team|org|inc|labs?|research|community|models?|backup|io)$/; function lookalike(owner) { const lo = owner.toLowerCase(); if (KNOWN_ORGS.some(k => k.toLowerCase() === lo) || LOOKALIKE_ALLOW.has(lo)) return []; const hits = [], no = norm(owner); for (const k of KNOWN_ORGS) { const nk = norm(k); if (nk.length < 4) continue; if (no === nk) hits.push([k, "identical after normalising case, punctuation and look-alike characters"]); else if (nk.length >= 5 && lev(no, nk) <= (nk.length < 8 ? 1 : 2)) hits.push([k, `${lev(no, nk)} character(s) different`]); else if (alnum(owner).startsWith(alnum(k)) && SUFFIX.test(alnum(owner).slice(alnum(k).length) || "x")) hits.push([k, `'${k}' plus the suffix '${alnum(owner).slice(alnum(k).length)}'`]); } return hits; } function assess(f) { const findings = []; const add = (category, points, title, detail = "") => findings.push({ category, points, title, detail }); const out = { repo_id: f.repo_id, status: f.status, scanned_at: f.scanned_at, disclaimer: DISCLAIMER, advice: ADVICE }; if (f.status !== "ok") { out.message = f.message; return out; } const o = f.owner, owner = o.name, age = o.age_days, repoAge = f.repo.age_days; const firstParty = !!((f.official_orgs || []).includes(owner) || (o.verified && !(f.declared_base || []).length)); if (o.type === "unknown") add("provenance", 15, "Publisher profile could not be read", `No public profile found for '${owner}'.`); if (o.verified) add("info", 0, "Publisher is a Hugging Face verified organisation", owner); if (age != null && age < 30) add("provenance", 20, "Publisher account is very new", `The '${owner}' account appears to be about ${age} days old.`); else if (age != null && age < 120) add("provenance", 10, "Publisher account is fairly new", `The '${owner}' account appears to be about ${age} days old.`); if (age != null && repoAge != null && age + 7 < repoAge) add("provenance", 5, "Namespace is younger than the repo", `The '${owner}' account id dates to about ${age} days ago but the repo is ${repoAge} days old. This usually means the namespace was renamed or transferred; it may be worth confirming the publisher's current home.`); if (repoAge != null && repoAge < 14) add("provenance", 5, "Repo is very new", `Created ${repoAge} days ago, so there is little public history yet.`); if (f.family && f.official_orgs.length && !firstParty) add("info", 0, "Third-party repo using an official model family name", `'${f.family}' models are originally published by ${f.official_orgs.join(", ")}. Third-party conversions and fine-tunes are common and often legitimate.`); if (f.name_tag_terms.length) add("info", 0, "Safety tuning modified (abliterated/uncensored); informational, no risk points", `Name or tags include: ${f.name_tag_terms.join(", ")}. This is a common, legitimate user choice and does not affect the risk score or provenance gap.`); else if (f.card_terms.length) add("info", 0, "Model card mentions abliterated/uncensored terms; informational, no risk points", f.card_terms.join(", ")); const b = f.base; if (b && !b.error) { const src = b.source === "declared" ? "declared base" : "same-name official repo"; if (b.all_identical) add("info", 0, `Weights are byte-identical to the ${src}`, `All ${b.identical_hashes} weight file hashes match ${b.name}.`); else if (b.identical_hashes) add("provenance", 10, `Some weight files match the ${src}, others differ`, `${b.identical_hashes}/${b.weight_files} files are identical to ${b.name}.`); else if (b.weight_files) { if (firstParty) add("info", 0, `Weights differ from the ${src} (first-party release)`, `Expected for a first-party release built on ${b.name}.`); else if (b.relation === "quantized" || f.format.gguf) add("provenance", 10, `Quantized conversion of the ${src}`, `Weights differ from ${b.name} as expected for quantization; the conversion itself cannot be re-checked statically.`); else add("provenance", 25, `Weights differ from the ${src}`, `0/${b.weight_files} files match ${b.name}. Consistent with a fine-tune, merge or abliteration; what changed inside the weights cannot be verified statically.`); } const t = b.tensors || {}; if ("count" in t) { if (t.adapter_like_added.length) add("risk", 15, "Extra adapter-style tensors not present in the base", t.adapter_like_added.slice(0, 6).join(", ") + ". Worth checking these are documented in the model card."); else if (t.n_added || t.n_removed || t.shape_changed.length) add("provenance", 8, "Tensor layout differs from the base", `+${t.n_added} added, -${t.n_removed} removed, ${t.shape_changed.length} reshaped tensors.`); else add("info", 0, "Tensor names and shapes match the base", `${t.count} tensors with the same layout` + (t.dtype_changed ? ` (${t.dtype_changed} stored in a different dtype)` : "") + "; only the values differ."); } else if (t.error) add("info", 0, "Tensor-layout comparison not available", `${b.name}: ${t.error}`); if (Object.keys(b.arch_diff || {}).length) add("provenance", 8, "Architecture fields differ from the base", JSON.stringify(b.arch_diff)); } else if (b && b.error) add("provenance", 5, "Could not compare against the base", `${b.name}: ${b.error}`); else if (!firstParty && f.files.some(x => ["safetensors", "pickle", "gguf"].includes(x.kind))) add("provenance", 15, "No base model declared", "The model card does not state which model these weights come from, so lineage cannot be checked."); // lineage const lin = f.lineage; if (lin) { const hops = lin.chain.length - 1, cs = lin.chain_str, end = lin.end; if (end === "first_party" && hops) add("info", 0, `Lineage traced to the first-party original (${hops} hop(s))`, cs); else if (end === "no_base" && hops) add("provenance", 10, "Lineage ends at a third-party repo with no declared base", `${cs}. The earliest repo in the chain does not say which original it comes from.`); else if (end === "broken") { const n = lin.chain[lin.chain.length - 1]; const why = { gated: "is gated", not_found: "is missing or not public" }[n.status] || "could not be read"; add("provenance", 10, "Lineage chain broken", `${cs}. ${n.repo} ${why}, so the chain cannot be followed further.`); } else if (end === "cycle") add("provenance", 10, "Base-model declarations form a loop", `${cs}. The chain never reaches an original.`); else if (end === "depth_cap") add("provenance", 10, "Lineage longer than the depth limit", `${cs}. Stopped after ${hops - 1} hops.`); const merges = lin.chain.filter(n => (n.other_bases || []).length); if (merges.length) add("info", 0, "Chain includes merges; only the first listed base is followed", merges.slice(0, 4).map(n => `${n.repo} also lists ${n.other_bases.length} more base(s)`).join("; ")); const rb = f.root_base; if (rb) { if (rb.error) add("info", 0, "Root original not comparable", `${rb.name}: ${rb.error}`); else { if (rb.all_identical) add("info", 0, "Weights are byte-identical to the root original", rb.name); const t = rb.tensors || {}; if ("count" in t) { if (t.adapter_like_added.length) add("risk", 15, "Extra adapter-style tensors not present in the root original", t.adapter_like_added.slice(0, 6).join(", ") + ` (vs ${rb.name}). Worth checking these are documented.`); else if (t.n_added || t.n_removed || t.shape_changed.length) add("provenance", 8, "Tensor layout differs from the root original", `vs ${rb.name}: +${t.n_added} added, -${t.n_removed} removed, ${t.shape_changed.length} reshaped.`); else add("info", 0, "Tensor names and shapes match the root original", `${t.count} tensors, same layout as ${rb.name}; only values differ.`); } else if (t.error) add("info", 0, "Root original header not accessible", `${rb.name}: ${t.error}`); if (Object.keys(rb.arch_diff || {}).length) add("provenance", 8, "Architecture fields differ from the root original", JSON.stringify(rb.arch_diff)); } } } const g = f.gguf; if (g) { if ((g.base_models || []).length) add("info", 0, "GGUF metadata names a base model", g.base_models.slice(0, 3).join(", ")); if (g.error && !g.complete) add("info", 0, "GGUF header only partly read", g.error); } // risk const sec = f.hf_security || {}; const issues = sec.filesWithIssues || []; const unsafe = issues.filter(x => x.level === "unsafe"), caution = issues.filter(x => x.level !== "unsafe"); if (unsafe.length) add("risk", 50, "Hugging Face's scanners marked file(s) unsafe", unsafe.map(x => x.path).join(", ")); if (caution.length) add("review", 0, "Hugging Face's scanners marked file(s) for caution", caution.map(x => x.path).join(", ")); if (Object.keys(sec).length && sec.scansDone === false) add("info", 0, "Hugging Face scan results not reported for this revision"); for (const ps of f.pickle_scans || []) { const gl = (ps.results || []).flatMap(r => r.globals); const bad = gl.filter(x => x.class === "dangerous"), unk = gl.filter(x => x.class === "unknown"); const where = ps.mode === "header" ? "header pickle" : "pickle"; if (bad.length) add("risk", 40, `Code-executing imports in ${where} ${ps.path}`, bad.slice(0, 8).map(x => `${x.module}.${x.name}`).join(", ") + ". Found by static opcode reading; nothing was executed."); else if (unk.length) add("review", 0, `Imports outside the standard allowlist in ${ps.path}`, unk.slice(0, 8).map(x => `${x.module}.${x.name}`).join(", ")); } const skipped = (f.pickle_scans || []).filter(p => p.mode === "skipped" || p.mode === "unavailable"); if (skipped.length) add("info", 0, `${skipped.length} pickle file(s) could not be opcode-scanned`, skipped.slice(0, 4).map(p => `${p.path}: ${p.note || p.mode}`).join("; ") + ". Hugging Face's own scan verdicts still apply."); const fm = f.format; if (fm.pickle && !fm.safetensors && !fm.gguf) add("risk", 10, "Weights only available in pickle format", `${fm.pickle} pickle-format file(s) and no safetensors. Pickle can run code when loaded; use weights_only=True or a safetensors copy.`); else if (fm.pickle) add("review", 0, "Pickle-format files alongside safetensors", "Loaders normally pick safetensors; pickle copies are usually legacy. Load with weights_only=True if needed."); if (fm.keras) add("review", 0, "Keras/H5 files present", "Keras Lambda layers can contain code; not inspected by Model Guard."); for (const [k, why] of lookalike(owner)) add("risk", o.verified ? 5 : 25, `Publisher name resembles '${k}'`, `'${owner}'` + (o.fullname ? ` (display name '${o.fullname}')` : "") + ` vs '${k}': ${why}. This may be an affiliated, backup or unrelated account; confirm it is the publisher you intended.`); if ((f.credentials || []).length) { const c = f.credentials; add("risk", 20, "Text matching a credential format found in repo files", `${c.length} match(es), e.g. a ${c[0].type} pattern in ${c[0].file} (shown redacted). It may be a test or revoked value; if it is real, the owner should rotate it, because a write token allows replacing files in the repo.`); } const tflags = [...(f.chat_template_flags || []), ...((g || {}).chat_template_flags || [])]; if (tflags.length) add("risk", 15, "Chat template contains URLs or command-like text", `Matched: ${uniqSorted(tflags).join(", ")}. Chat templates run on every prompt; worth reading.`); if (Object.keys(f.auto_map || {}).length) add("review", 0, "Loading requires trust_remote_code (custom model code)", "auto_map: " + Object.entries(f.auto_map).slice(0, 3).map(([k, v]) => `${k}->${v}`).join(", ") + ". This runs the repo's Python on your machine; common for new architectures."); else if ((f.python_files || []).length) add("review", 0, "Python files in repo", f.python_files.slice(0, 6).join(", ")); if (f.readme_trust_remote_code && !Object.keys(f.auto_map || {}).length) add("review", 0, "Model card suggests trust_remote_code=True", ""); for (const [p, hits] of Object.entries(f.code_patterns || {})) { add("review", 0, `Code patterns to read in ${p}`, Object.entries(hits).map(([k, v]) => `${k} x${v}`).join("; ")); if ("network access" in hits && "env / credential access" in hits) add("risk", 15, `${p} both reads environment/credentials and makes network calls`, "This combination is sometimes legitimate (e.g. downloading assets) but deserves a careful read before running."); } if (f.requested_as && f.requested_as.toLowerCase() !== f.repo_id.toLowerCase() && f.requested_as.includes("/")) add("info", 0, "Repo was renamed or transferred", `You asked for ${f.requested_as}; Hugging Face now serves it as ${f.repo_id}, so the current publisher is checked. Old links keep working through Hugging Face's redirect.`); if (f.files_denied) add("info", 0, "Some files were not readable anonymously", `${f.files_denied} file(s) need sign-in (gated); scan is partial.`); if (f.requests_rate_limited || f.requests_timed_out) add("info", 0, "Some requests were rate-limited or timed out; scan is partial", `${f.requests_rate_limited || 0} rate-limited, ${f.requests_timed_out || 0} timed out after retries. Re-run the check in a minute for a complete result.`); const sum = cat => Math.min(100, findings.filter(x => x.category === cat).reduce((a, x) => a + x.points, 0)); const level = (s, table) => table.find(([thr]) => s >= thr)[1]; const rs = sum("risk"), pg = sum("provenance"); const order = { risk: 0, provenance: 1, review: 2, info: 3 }; Object.assign(out, { risk_score: rs, risk_level: level(rs, RISK_LEVELS), provenance_gap: pg, provenance_level: firstParty && pg < 15 ? "FIRST-PARTY" : level(pg, PROV_LEVELS), review_items: findings.filter(x => x.category === "review").length, safety_tuning_modified: !!f.name_tag_terms.length, findings: findings.map((x, i) => [x, i]).sort((a, c) => (order[a[0].category] - order[c[0].category]) || (c[0].points - a[0].points) || (a[1] - c[1])).map(x => x[0]), facts: f, }); return out; } // ---------------------------------------------------------------- rendering (DOM only, never innerHTML with repo data) function el(tag, attrs = {}, ...kids) { const e = document.createElement(tag); for (const [k, v] of Object.entries(attrs)) { if (k === "class") e.className = v; else if (k === "text") e.textContent = v; else e.setAttribute(k, v); } for (const k of kids.flat()) if (k != null) e.append(k instanceof Node ? k : document.createTextNode(String(k))); return e; } function summaryRows(d) { const f = d.facts, o = f.owner, r = f.repo, fm = f.format, rows = []; const n = v => (v == null ? "?" : Number(v).toLocaleString("en")); rows.push(["Publisher", `${o.name} (${o.type === "org" ? "organisation" : o.type}${o.verified ? ", HF-verified" : ""}) · account age ${o.age_days != null ? n(o.age_days) + " days" : "unknown"} · ${n(o.models)} models · ${n(o.followers)} followers`]); rows.push(["Repo", `created ${(r.created || "?").slice(0, 10)} (${n(r.age_days)} days ago) · ${n(r.downloads_30d)} downloads in 30 days · ${n(r.likes)} likes · licence ${r.license ?? "not stated"}${r.gated ? " · gated (sign-in needed for files)" : ""}`]); rows.push(["Files", `${n(f.files.length)} total · safetensors ${fm.safetensors} · pickle ${fm.pickle} · GGUF ${fm.gguf} · Python ${fm.python}`]); const b = f.base; if (b) { let v = `${b.name} (${b.source === "declared" ? "declared in the model card" : "same-name official repo"})` + (b.error ? ` · ${b.error}` : ` · relation: ${b.relation} · identical weight files ${b.identical_hashes}/${b.weight_files}`); const t = b.tensors || {}; if ("count" in t) v += ` · tensors ${n(t.count)} vs ${n(t.base_count)} (+${t.n_added}/−${t.n_removed}, ${t.shape_changed.length} reshaped, ${t.dtype_changed} dtype changes) · ${(t.params / 1e9).toFixed(2)}B vs ${(t.base_params / 1e9).toFixed(2)}B params`; rows.push(["Base model", v]); } else rows.push(["Base model", "none declared"]); const lin = f.lineage; if (lin) { const label = { first_party: "reaches the first-party original", no_base: "ends at a repo with no declared base", broken: "chain broken", cycle: "loops back on itself", depth_cap: "stopped at the depth limit" }[lin.end]; const hops = lin.chain.filter(x => x.status !== "not_followed" && x.status !== "cycle").length - 1; rows.push(["Lineage", `${lin.chain_str.split(" -> ").join(" → ")} (${hops} hop(s) followed; ${label})`]); } const rb = f.root_base; if (rb) { const t = rb.tensors || {}; rows.push(["Root original", rb.name + (rb.error ? ` · ${rb.error}` : ` · identical weight files ${rb.identical_hashes}/${rb.weight_files}` + ("count" in t ? ` · tensors ${n(t.count)} vs ${n(t.base_count)} (+${t.n_added}/−${t.n_removed}, ${t.shape_changed.length} reshaped)` : ` · header: ${t.error || "n/a"}`))]); } if (f.gguf) { const g = f.gguf; rows.push(["GGUF", `${g.files} file(s); header of ${g.path}: architecture ${g.architecture ?? "?"}, name ${g.name ?? "?"}, chat template ${g.has_chat_template ? "yes" : "no"}`]); } const ps = f.pickle_scans || []; if (ps.length) { const c = m => ps.filter(x => x.mode === m).length; rows.push(["Pickle scan", `${c("full")} read in full, ${c("header")} from the header; ${c("skipped") + c("unavailable")} not scannable (opcodes are read, never executed)`]); } const sec = f.hf_security || {}; rows.push(["HF scanners", `${sec.scansDone ? "complete" : "not reported"} · flagged: ${(sec.filesWithIssues || []).map(x => `${x.path} (${x.level})`).join(", ") || "none"}`]); return rows; } // Plain-language notes shown under each finding. Matched on the finding title; first match wins. const EXPLAIN = [ [/scanners marked file\(s\) unsafe/, "Hugging Face's own malware and pickle scanners flagged these files. Don't load them outside a disposable sandbox."], [/scanners marked file\(s\) for caution/, "Hugging Face's scanners want a human to look at these files. Often harmless, but worth a read."], [/^Code-executing imports/, "Loading this pickle (for example with torch.load without weights_only=True) would call these functions. Normal model checkpoints don't need them."], [/^Imports outside the standard allowlist/, "These imports aren't on the list of ones normally seen in model checkpoints. Usually benign library classes; check before loading."], [/could not be opcode-scanned/, "These files couldn't be inspected from the browser. Hugging Face's own scan results above still apply."], [/Weights only available in pickle/, "Pickle files can run code when loaded. A safetensors copy can't, so prefer one if it exists."], [/Pickle-format files alongside safetensors/, "Most loaders use the safetensors files and ignore these legacy copies."], [/Keras\/H5/, "Keras models can include Lambda layers with code. This page doesn't inspect them."], [/^Publisher name resembles/, "Lookalike names are a common way to impersonate a well-known publisher. Check the profile is the one you meant."], [/credential format/, "Text that looks like an API key or token. It may be a placeholder or already revoked; the value isn't shown."], [/Chat template contains/, "The chat template formats every prompt you send. URLs or command-like text in it are unusual, so read it."], [/adapter-style tensors/, "Extra tensors with adapter-like names were added compared with the base. They should be explained in the model card."], [/both reads environment/, "This custom code reads environment variables or credentials and also makes network calls. Read it before you run it."], [/trust_remote_code|Python files in repo|Code patterns to read/, "With trust_remote_code=True, this Python runs on your machine. That's common for new architectures, but read it first."], [/Publisher profile could not be read/, "There's no public profile for this account, so its history can't be checked."], [/Publisher account is (very|fairly) new/, "New accounts have little public track record. That isn't a problem in itself, but there's less to go on."], [/Namespace is younger than the repo/, "The account looks newer than the repo, which usually means a rename or transfer. Check you're on the publisher's current page."], [/Repo is very new/, "There's little public history (downloads, discussions, other users) yet."], [/Weights differ from the (declared base|same-name)/, "Expected for a fine-tune or merge. What changed inside the weights can't be verified from metadata."], [/Quantized conversion/, "Quantized files never match the original byte for byte, so the conversion has to be taken on trust."], [/Some weight files match/, "Part of the weights are byte-identical to the base and part aren't. Worth checking against the model card."], [/Tensor layout differs/, "Tensors were added, removed or reshaped compared with the base. That's normal for some architectures but should be explained."], [/Architecture fields differ/, "config.json declares a different architecture from the base model."], [/Could not compare against the base/, "The declared base couldn't be read, so the comparison was skipped."], [/No base model declared/, "The model card doesn't say what this model was built from, so where it came from can't be traced."], [/^Lineage ends at a third-party/, "The chain of declared base models stops at a repo that doesn't name its own origin."], [/^Lineage chain broken/, "A repo in the chain of declared bases is missing, private or gated, so the chain can't be followed further."], [/form a loop/, "The declared base models point back at each other, so no original is ever reached."], [/longer than the depth limit/, "The chain of declared bases is long. It was followed for 5 hops, and anything further back wasn't checked."], [/^Safety tuning modified/, "Abliterated or uncensored models are a common, legitimate choice. This never adds risk points."], [/Model card mentions abliterated/, "The model card mentions these terms. Information only; it never adds points."], [/Third-party repo using an official model family name/, "Conversions and fine-tunes by third parties are normal. This just tells you it isn't the original publisher."], [/Repo was renamed or transferred/, "The address you entered redirects. The current owner is the one checked."], [/not readable anonymously/, "Gated or private files need sign-in, and this page never uses a token, so those files weren't checked."], [/scan results not reported/, "Hugging Face hasn't published scan results for this revision. That's common for large or older repos, and the other checks still ran."], [/Chain includes merges/, "Merged models list several parents. Only the first listed parent is followed."], [/Tensor-layout comparison not available|Root original header not accessible|Root original not comparable/, "The base files couldn't be read anonymously (often because they're gated), so tensor layouts weren't compared."], [/GGUF header only partly read/, "The GGUF metadata is larger than the part read, so some fields may be missing."], [/rate-limited or timed out/, "Hugging Face limited or dropped some anonymous requests. Run the check again in a minute."], ]; const explain = title => { const m = EXPLAIN.find(([re]) => re.test(title)); return m ? m[1] : ""; }; const SIGNAL_TEXT = { risk: { LOW: "No known risk indicators found.", MEDIUM: "Some risk indicators; read the findings.", HIGH: "Several risk indicators; review before use.", CRITICAL: "Strong risk indicators; don't load outside a sandbox." }, prov: { "FIRST-PARTY": "Published by the original model maker.", TRACEABLE: "Origin is mostly traceable from public data.", "PARTLY VERIFIABLE": "Parts of the origin can't be verified.", UNVERIFIABLE: "Little of the origin can be verified." }, }; const SECTIONS = [ ["risk", "Risk findings", "These add to the risk score."], ["provenance", "Provenance gaps", "These add to the provenance gap: things about the model's origin that can't be confirmed."], ["review", "Worth a look", "No points. Common and often fine, but read them before you run the model."], ["info", "For information", "No points."], ]; function render(d, host, revision) { host.replaceChildren(); const hfLink = el("a", { href: `https://huggingface.co/${d.repo_id}`, target: "_blank", rel: "noopener noreferrer" }, d.repo_id); const heading = el("h2", { id: "result-title", tabindex: "-1" }); if (d.status !== "ok") { const tips = { not_found: "Check the spelling (owner/name), or open the repo on Hugging Face. Private repos, and repos that were deleted or renamed without a redirect, can't be checked anonymously.", rate_limited: "Hugging Face limits anonymous requests. Wait a minute, then press Check again.", error: "This is usually temporary. Wait a moment and press Check again." }[d.status] || ""; heading.append("Couldn't check ", hfLink); host.append(el("div", { class: "card notscanned", role: "alert" }, heading, el("p", {}, d.message), tips ? el("p", { class: "muted" }, tips) : null)); heading.focus({ preventScroll: true }); return; } const f = d.facts, lvl = s => "lvl-" + s.toLowerCase().replace(/\s+/g, "-"); heading.append("Result for ", hfLink, " ", el("span", { class: "revsha", title: f.revision }, `@ ${f.revision.slice(0, 10)}`)); const share = shareUrl(d.repo_id, revision); const copyBtn = el("button", { type: "button", class: "secondary", id: "copy" }, "Copy link to this check"); const copyMsg = el("span", { class: "copymsg", role: "status", "aria-live": "polite" }); const linkBox = el("input", { type: "text", readonly: "", value: share, "aria-label": "Link to this check", class: "linkbox" }); copyBtn.addEventListener("click", async () => { let ok = false; try { await navigator.clipboard.writeText(share); ok = true; } catch (e) { /* clipboard may be blocked inside iframes */ } if (!ok) { linkBox.focus(); linkBox.select(); try { ok = document.execCommand("copy"); } catch (e) { ok = false; } } copyMsg.textContent = ok ? "Link copied." : "Couldn't copy automatically. The link is selected; press Ctrl+C (or ⌘C)."; }); host.append(el("div", { class: "result-head" }, heading, el("div", { class: "share" }, copyBtn, linkBox, copyMsg))); const sig = (cls, label, value, score, text) => el("div", { class: "signal " + cls }, el("span", { class: "label" }, label), el("span", { class: "value" }, value), el("span", { class: "score" }, score), el("span", { class: "sigtext" }, text)); host.append(el("div", { class: "signals", role: "group", "aria-label": "Summary" }, sig(lvl(d.risk_level), "Risk", d.risk_level, `${d.risk_score} / 100`, SIGNAL_TEXT.risk[d.risk_level]), sig(lvl(d.provenance_level), "Provenance", d.provenance_level, `gap ${d.provenance_gap} / 100`, SIGNAL_TEXT.prov[d.provenance_level]), sig("review", "Worth a look", String(d.review_items), "item(s), no points", d.review_items ? "Read these before running the model." : "Nothing flagged for manual review."), sig("info", "Safety tuning", d.safety_tuning_modified ? "Modified" : "Not indicated", "information only", d.safety_tuning_modified ? "Abliterated or uncensored. Never adds points." : "No abliterated or uncensored markers."))); const dl = el("dl", { class: "facts" }); for (const [k, v] of summaryRows(d)) dl.append(el("dt", {}, k), el("dd", {}, v)); host.append(el("details", { class: "card factsbox", open: "" }, el("summary", {}, "What was checked"), dl)); for (const [cat, title, sub] of SECTIONS) { const items = d.findings.filter(x => x.category === cat); if (!items.length && cat !== "risk") continue; const sec = el("section", { class: "findings cat-" + cat, "aria-labelledby": `h-${cat}` }, el("h3", { id: `h-${cat}` }, title, el("span", { class: "count" }, ` (${items.length})`)), el("p", { class: "muted small" }, sub)); if (!items.length) sec.append(el("p", { class: "none" }, "None found.")); const ul = el("ul", { class: "flist" }); for (const x of items) { const why = explain(x.title); ul.append(el("li", { class: "finding" }, el("div", { class: "ftitle" }, x.points ? el("span", { class: "pts", "aria-label": `${x.points} points` }, `+${x.points}`) : null, el("strong", {}, x.title)), why ? el("p", { class: "why" }, why) : null, x.detail ? el("p", { class: "detail" }, x.detail) : null)); } if (items.length) sec.append(ul); host.append(sec); } host.append(el("p", { class: "advice" }, el("strong", {}, "General advice: "), d.advice)); host.append(el("details", { class: "raw" }, el("summary", {}, "Raw result (JSON)"), el("pre", { class: "json", tabindex: "0" }, JSON.stringify(d, null, 2)))); const when = new Date(d.scanned_at); host.append(el("p", { class: "meta" }, `Checked ${when.toLocaleString()} in your browser, using ${f.requests} anonymous requests to Hugging Face. Results reflect revision ${f.revision}.`)); heading.focus({ preventScroll: true }); } // ---------------------------------------------------------------- UI wiring const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$/; // Accepts "owner/name", legacy "name", and huggingface.co / hf.co URLs (incl. /tree/<rev>, /blob/<rev>/..., trailing slashes). function parseInput(raw, revisionField) { let s = String(raw || "").trim().replace(/^['"<\s]+|['">\s]+$/g, ""); let rev = String(revisionField || "").trim(); s = s.replace(/^(https?:\/\/)?(www\.)?(huggingface\.co|hf\.co)(\/|$)/i, "").split(/[?#]/)[0]; s = s.replace(/\/{2,}/g, "/").replace(/^\/+|\/+$/g, ""); if (!s) return { error: "Enter a model id like Qwen/Qwen2.5-7B-Instruct, or paste a huggingface.co model link." }; const parts = s.split("/"); if (["datasets", "spaces", "collections", "papers", "organizations", "settings"].includes(parts[0].toLowerCase())) return { error: `That looks like a ${parts[0].replace(/s$/, "")} link. Model Guard checks model repos only; paste a model link such as huggingface.co/owner/model.` }; if (parts[0].toLowerCase() === "models" && parts.length > 2) parts.shift(); let repo = parts.length >= 2 && !["tree", "blob", "resolve", "commit", "discussions"].includes(parts[1]) ? parts.slice(0, 2).join("/") : parts[0]; const rest = parts.slice(repo.split("/").length); if (!rev && ["tree", "blob", "resolve", "commit"].includes(rest[0]) && rest[1]) rev = decodeURIComponent(rest[1]); if (!repo.split("/").every(x => NAME_RE.test(x)) || repo.split("/").some(x => x === "." || x === "..")) return { error: "That doesn't look like a Hugging Face model id. Use the form owner/name, for example Qwen/Qwen2.5-7B-Instruct." }; if (rev && !/^[A-Za-z0-9._\/-]{1,200}$/.test(rev)) return { error: "The revision should be a branch, tag or commit sha." }; return { repo, revision: rev || "" }; } function shareUrl(repo, revision) { const base = location.href.split(/[?#]/)[0]; return `${base}?repo=${repo}` + (revision ? `&revision=${encodeURIComponent(revision)}` : ""); } let currentScan = null; async function runScan(repoInput, revisionInput) { const out = document.getElementById("result"), status = document.getElementById("status"), btn = document.getElementById("go"); const parsed = parseInput(repoInput, revisionInput); if (parsed.error) { status.textContent = parsed.error; status.dataset.kind = "error"; document.body.dataset.done = "1"; window.__mgResult = { status: "invalid_input", message: parsed.error }; return null; } if (currentScan) currentScan.abort(); const ctl = new AbortController(); currentScan = ctl; const { repo, revision } = parsed; document.getElementById("repo").value = repo; document.getElementById("revision").value = revision; try { history.replaceState(null, "", shareUrl(repo, revision)); } catch (e) { /* sandboxed frames may refuse; harmless */ } delete document.body.dataset.done; delete status.dataset.kind; btn.disabled = true; out.replaceChildren(); out.setAttribute("aria-busy", "true"); document.getElementById("empty").hidden = true; const t0 = performance.now(); try { const bar = document.getElementById("progress"); let step = 0; bar.hidden = false; bar.value = 0; const facts = await collect(repo, revision || null, msg => { if (currentScan !== ctl) return; if (!/waiting/.test(msg)) step++; bar.value = Math.min(step / 9, 0.95); status.textContent = msg + "…"; }, ctl.signal); if (currentScan !== ctl) return null; const d = assess(facts); render(d, out, revision); const top = out.getBoundingClientRect().top; if (top > window.innerHeight * 0.7 || top < 0) out.scrollIntoView({ block: "start", behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth" }); status.textContent = d.status === "ok" ? `Check finished in ${((performance.now() - t0) / 1000).toFixed(1)} s: risk ${d.risk_level}, provenance ${d.provenance_level}, ${d.review_items} item(s) worth a look.` : ""; window.__mgResult = d; return d; } catch (e) { if (e instanceof ScanAborted || currentScan !== ctl) return null; status.textContent = `The check stopped unexpectedly: ${e && e.message ? e.message : e}. Please try again.`; status.dataset.kind = "error"; window.__mgResult = { repo_id: repo, status: "error", message: String(e) }; return null; } finally { if (currentScan === ctl) { btn.disabled = false; out.removeAttribute("aria-busy"); document.getElementById("progress").hidden = true; document.body.dataset.done = "1"; currentScan = null; } } } function init() { const form = document.getElementById("form"), input = document.getElementById("repo"), rev = document.getElementById("revision"); document.getElementById("disclaimer").textContent = DISCLAIMER; form.addEventListener("submit", e => { e.preventDefault(); runScan(input.value, rev.value); }); for (const a of document.querySelectorAll("[data-example]")) a.addEventListener("click", e => { e.preventDefault(); input.value = a.dataset.example; rev.value = ""; runScan(input.value, ""); }); const p = new URLSearchParams(location.search); if (p.get("repo")) { input.value = p.get("repo"); rev.value = p.get("revision") || ""; runScan(input.value, rev.value); } } if (typeof document !== "undefined") document.addEventListener("DOMContentLoaded", init);
/* Model Guard static web check (browser port of the hf-model-guard CLI, v0.2.2).
* Apache-2.0. https://github.com/model-guard/hf-model-guard
*
* Defensive only: reads public Hugging Face endpoints anonymously from the visitor's browser.
* Nothing from a scanned repo is executed, unpickled or rendered as HTML. No analytics, no trackers,
* no third-party scripts, no tokens.
*/
"use strict";
const VERSION = "0.2.2-static";
const HF = "https://huggingface.co";
const MAX_PICKLE_FULL = 25 * 1024 * 1024;
const PICKLE_HEADER_STEPS = [1024 * 1024, 8 * 1024 * 1024];
const GGUF_HEADER_STEPS = [4 * 1024 * 1024, 24 * 1024 * 1024];
const MAX_DEPTH = 5;
// ---------------------------------------------------------------- rules (mirror of model_guard/rules.py)
const PICKLE_EXT = [".bin", ".pt", ".pth", ".pkl", ".pickle", ".ckpt", ".joblib", ".dat", ".npy", ".npz"];
const SAFE_EXT = [".safetensors"];
const KERAS_EXT = [".h5", ".keras", ".hdf5"];
const TEXT_EXT = [".json", ".md", ".py", ".txt", ".yml", ".yaml", ".cfg", ".jinja", ".toml", ".ini", ".env", ".sh"];
const WEIGHT_EXT = [...SAFE_EXT, ...PICKLE_EXT, ".gguf", ".onnx", ".msgpack", ".h5"];
const UNCENSORED_RE = /\b(abliterat\w*|uncensored|unaligned|decensored|lorablated|orthogonali[sz]ed|refusal[- ]?(removed|ablation|direction)|no[- ]?guardrails|jailbr[eo]ak\w*|heretic)\b/gi;
const KNOWN_ORGS = ["meta-llama", "facebook", "Qwen", "mistralai", "google", "microsoft", "deepseek-ai", "openai",
"nvidia", "ibm-granite", "allenai", "tiiuae", "stabilityai", "black-forest-labs", "HuggingFaceTB",
"huggingface", "bigscience", "EleutherAI", "01-ai", "THUDM", "zai-org", "moonshotai", "xai-org",
"CohereForAI", "CohereLabs", "apple", "amazon", "Salesforce", "intel", "Nutanix", "unsloth",
"bartowski", "TheBloke", "mlx-community", "lmstudio-community", "sentence-transformers"];
const LOOKALIKE_ALLOW = new Set(["openai-community", "mistral-community", "google-bert", "google-t5", "facebookai",
"hugging-quants", "huggingfaceh4", "huggingfacem4", "huggingfacefw", "huggingface-course", "nvidia-community",
"microsoft-community", "intel-community"]);
const FAMILIES = {
"llama": ["meta-llama"], "meta-llama": ["meta-llama"], "qwen": ["Qwen"], "qwq": ["Qwen"],
"mistral": ["mistralai"], "mixtral": ["mistralai"], "gemma": ["google"], "phi-": ["microsoft"],
"deepseek": ["deepseek-ai"], "gpt-oss": ["openai"], "gpt2": ["openai-community"], "olmo": ["allenai"],
"falcon": ["tiiuae"], "granite": ["ibm-granite"], "nemotron": ["nvidia"], "glm": ["zai-org", "THUDM"],
"chatglm": ["THUDM", "zai-org"], "kimi": ["moonshotai"], "grok": ["xai-org"], "smollm": ["HuggingFaceTB"],
"command-r": ["CohereForAI", "CohereLabs"],
};
const FIRST_PARTY_ORGS = new Set(Object.values(FAMILIES).flat().map(o => o.toLowerCase()));
const SECRET_PATTERNS = {
"Hugging Face token": /\bhf_[A-Za-z0-9]{30,}\b/g,
"OpenAI-style key": /\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,
"Anthropic key": /\bsk-ant-[A-Za-z0-9_-]{20,}\b/g,
"AWS access key id": /\bAKIA[0-9A-Z]{16}\b/g,
"GitHub token": /\b(?:ghp|gho|ghs|ghu)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{40,}\b/g,
"Slack token": /\bxox[abpr]-[A-Za-z0-9-]{10,}\b/g,
"Google API key": /\bAIza[0-9A-Za-z_-]{35}\b/g,
"W&B key assignment": /WANDB_API_KEY\s*[=:]\s*['"]?[0-9a-f]{40}/g,
};
const CODE_PATTERNS = {
"process execution": /\b(os\.system|os\.popen|subprocess\.|pty\.spawn)/g,
"dynamic code eval": /(?<![.\w])(eval|exec)\s*\(|__import__\s*\(/g,
"network access": /\b(requests\.(get|post|put)|urllib\.request|http\.client|socket\.socket|httpx\.)/g,
"env / credential access": /os\.environ|os\.getenv|\.netrc|\.ssh\/|HF_TOKEN|AWS_SECRET|OPENAI_API_KEY/g,
"encoded / compressed blobs": /base64\.b64decode|codecs\.decode\(|marshal\.loads|zlib\.decompress|bz2\.decompress/g,
};
const TEMPLATE_FLAG = /https?:\/\/|\bcurl\s|\bwget\s|base64|\bexec\b|\bimport\s/g;
const DISCLAIMER = "A low risk score is not proof of safety. Model Guard reads public metadata and small files only; " +
"behaviour hidden inside model weights (for example a trigger-phrase backdoor in safetensors) " +
"cannot be detected by static scanning, neither by this tool nor by pickle scanners.";
const ADVICE = "Prefer official or verified publishers, pin a revision sha, avoid pickle formats, review remote code " +
"before trust_remote_code=True, and run unfamiliar models sandboxed with no secrets in the environment.";
const RISK_LEVELS = [[70, "CRITICAL"], [45, "HIGH"], [20, "MEDIUM"], [0, "LOW"]];
const PROV_LEVELS = [[40, "UNVERIFIABLE"], [15, "PARTLY VERIFIABLE"], [0, "TRACEABLE"]];
// ---------------------------------------------------------------- small helpers
const ends = (s, exts) => exts.some(e => s.endsWith(e));
const uniqSorted = arr => [...new Set(arr)].sort();
const matchAll = (re, s) => [...String(s || "").matchAll(re)].map(m => m[0]);
const nowMs = () => Date.now();
const ageDays = d => d ? Math.floor((nowMs() - d.getTime()) / 86400000) : null;
const objectIdTime = oid => { const t = parseInt(String(oid || "").slice(0, 8), 16); return isFinite(t) ? new Date(t * 1000) : null; };
const encPath = p => p.split("/").map(encodeURIComponent).join("/");
const resolveUrl = (repo, rev, path) => `${HF}/${repo}/resolve/${encodeURIComponent(rev)}/${encPath(path)}`;
class Stats {
constructor(signal) { this.denied = 0; this.requests = 0; this.rateLimited = 0; this.timeouts = 0; this.signal = signal || null; }
}
class ScanAborted extends Error {}
const sleep = (ms, signal) => new Promise((res, rej) => {
const t = setTimeout(res, ms);
if (signal) signal.addEventListener("abort", () => { clearTimeout(t); rej(new ScanAborted("aborted")); }, { once: true });
});
const JSON_TIMEOUT_MS = 30000, BYTES_TIMEOUT_MS = 120000, RETRIES = 3;
// One fetch with a timeout, gentle retries on rate limits / transient errors, and cancellation when a new scan starts.
// Returns {status, response} where status 0 means a network error or timeout. Never sends cookies or tokens.
async function hfFetch(url, headers, stats, timeoutMs) {
for (let attempt = 0; ; attempt++) {
if (stats && stats.signal && stats.signal.aborted) throw new ScanAborted("aborted");
if (stats) stats.requests++;
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), timeoutMs);
const onAbort = () => ctl.abort();
if (stats && stats.signal) stats.signal.addEventListener("abort", onAbort, { once: true });
let r = null, timedOut = false;
try { r = await fetch(url, { headers: headers || {}, credentials: "omit", referrerPolicy: "no-referrer", signal: ctl.signal }); }
catch (e) { timedOut = !(stats && stats.signal && stats.signal.aborted); }