UNPKG

vlt

Version:
1,863 lines (1,815 loc) 70.7 kB
var global = globalThis; import {Buffer} from "node:buffer"; import {setTimeout,clearTimeout,setImmediate,clearImmediate,setInterval,clearInterval} from "node:timers"; import {createRequire as _vlt_createRequire} from "node:module"; var require = _vlt_createRequire(import.meta.filename); import { AbortError, pRetry } from "./chunk-M34JYYXI.js"; import { asAttributeNode, asCombinatorNode, asIdentifierNode, asPostcssNodeWithChildren, asPseudoNode, asStringNode, asTagNode, isAttributeNode, isIdentifierNode, isPostcssNodeWithChildren, isPseudoNode, isSelectorNode, isStringNode, isTagNode, parse as parse2 } from "./chunk-HFPRNHS6.js"; import { minimatch } from "./chunk-6YRWYWZQ.js"; import { hydrate, joinDepIDTuple, splitDepID } from "./chunk-L3TCSQZJ.js"; import { asError, asManifest, compare, eq, gt, gte, lt, lte, major, minor, neq, parse, parseRange, patch, satisfies } from "./chunk-X4RDKJKD.js"; import { error } from "./chunk-RV3EHS4P.js"; // ../../src/query/src/pseudo/helpers.ts var removeNode = (state, node) => { for (const edge of node.edgesIn) { state.partial.edges.delete(edge); } state.partial.nodes.delete(node); }; var removeEdge = (state, edge) => { state.partial.edges.delete(edge); if (edge.to) { state.partial.nodes.delete(edge.to); } }; var removeDanglingEdges = (state) => { for (const edge of state.partial.edges) { if (!edge.to) { state.partial.edges.delete(edge); } } }; var removeUnlinkedNodes = (state) => { for (const node of state.partial.nodes) { if (node.edgesIn.size === 0) { state.partial.nodes.delete(node); } } }; var removeQuotes = (value) => value.replace(/^"(.*?)"$/, "$1"); var assertSecurityArchive = (state, name) => { if (!state.securityArchive) { throw error( `Missing security archive while trying to parse the :${name} selector`, { found: state } ); } }; var clear = (state) => { state.partial.nodes.clear(); state.partial.edges.clear(); return state; }; var createSecuritySelectorFilter = (name, type2) => { return async (state) => { assertSecurityArchive(state, name); for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); const exclude = !report?.alerts.some( (alert) => alert.type === type2 ); if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; }; // ../../src/query/src/attribute.ts var jsonFieldToString = (v) => String(v); var getManifestPropertyValues = (node, properties, attribute2) => { if (!node.manifest) return; const traverse = /* @__PURE__ */ new Set([node.manifest]); const props = /* @__PURE__ */ new Set(); for (const key of properties) { for (const prop of traverse) { if (!prop) { throw error("failed to find nested property in :attr", { found: properties }); } if (Array.isArray(prop)) { for (const p of prop) { traverse.add(p); } continue; } if (typeof prop === "string" || typeof prop === "number" || typeof prop === "boolean") { continue; } if (key in prop) { const nextValue = prop[key]; if (nextValue) { if (key === attribute2) { props.add(nextValue); } else { traverse.delete(prop); traverse.add(nextValue); } } } } } if (!props.size) return; const collect = /* @__PURE__ */ new Set(); for (const prop of props) { if (Array.isArray(prop)) { for (const p of prop) { collect.add(p ? jsonFieldToString(p) : ""); } } else { collect.add(jsonFieldToString(prop)); } } return [...collect]; }; var filterAttributes = (state, comparator, value, propertyName, insensitive, prefixProperties = []) => { const check = (attr2) => comparator?.( insensitive ? jsonFieldToString(attr2).toLowerCase() : jsonFieldToString(attr2), insensitive ? value.toLowerCase() : value ); const deleteNode = (node) => { for (const edge of node.edgesIn) { state.partial.edges.delete(edge); } state.partial.nodes.delete(node); }; for (const node of state.partial.nodes) { const prefixes = prefixProperties.length ? prefixProperties : [propertyName]; const attrs = getManifestPropertyValues( node, prefixes, propertyName ); if (!attrs?.length) { deleteNode(node); continue; } if (comparator && !attrs.some(check)) { deleteNode(node); } } removeDanglingEdges(state); return state; }; var attributeSelectors = { "=": (attr2, value = "") => attr2 === value, "^=": (attr2, value = "") => attr2.startsWith(value), "$=": (attr2, value = "") => attr2.endsWith(value), "~=": (attr2, value = "") => new Set(attr2.match(/\w+/g)).has(value), "*=": (attr2, value = "") => attr2.includes(value), "|=": (attr2, value = "") => attr2 === value || attr2.startsWith(`${value}-`), undefined: (attr2) => !!attr2 }; var attributeSelectorsMap = new Map( Object.entries(attributeSelectors) ); var attribute = async (state) => { await state.cancellable(); const curr = asAttributeNode(state.current); const operatorFn = attributeSelectorsMap.get(String(curr.operator)); if (!operatorFn) { if (state.loose) { return state; } throw error(`Unsupported attribute operator: ${curr.operator}`, { found: state.current }); } const value = curr.value || ""; const propertyName = curr.attribute; const insensitive = !!curr.insensitive; state.specificity.commonCounter += 1; return filterAttributes( state, operatorFn, value, propertyName, insensitive ); }; // ../../src/query/src/combinator.ts var childCombinator = async (state) => { const traverse = new Set(state.partial.nodes); state.partial.edges.clear(); state.partial.nodes.clear(); for (const node of traverse) { for (const edge of node.edgesOut.values()) { if (edge.to) { state.partial.edges.add(edge); state.partial.nodes.add(edge.to); } } } return state; }; var subsequentSiblingCombinator = async (state) => { const traverse = new Set(state.partial.nodes); state.partial.edges.clear(); state.partial.nodes.clear(); for (const node of traverse) { for (const edge of node.edgesIn) { const parents = edge.from.edgesOut.values(); for (const edge2 of parents) { if (edge2.to && edge2.to !== node) { state.partial.edges.add(edge2); state.partial.nodes.add(edge2.to); } } } } return state; }; var descendentCombinator = async (state) => { if (state.prev?.type === "tag" || state.next?.type === "tag") { return state; } const traverse = new Set(state.partial.nodes); state.partial.edges.clear(); state.partial.nodes.clear(); for (const node of traverse) { const children = /* @__PURE__ */ new Set(); for (const edge of node.edgesOut.values()) { if (edge.to) { children.add(edge.to); state.partial.edges.add(edge); state.partial.nodes.add(edge.to); } } for (const child of children) { traverse.add(child); } } return state; }; var combinatorSelectors = { ">": childCombinator, "~": subsequentSiblingCombinator, " ": descendentCombinator }; var combinatorSelectorsMap = new Map( Object.entries(combinatorSelectors) ); var combinator = async (state) => { await state.cancellable(); const curr = asCombinatorNode(state.current); const parserFn = curr.value && combinatorSelectorsMap.get(curr.value); if (!parserFn) { if (state.loose) { return state; } throw error(`Unsupported combinator: ${state.current.value}`, { found: state.current }); } return parserFn(state); }; // ../../src/query/src/id.ts var id = async (state) => { const { value } = asIdentifierNode(state.current); if (!value) { throw error("Missing identifier name"); } for (const edge of state.partial.edges) { if (edge.name !== value) { state.partial.edges.delete(edge); if (edge.to) { state.partial.nodes.delete(edge.to); } } } for (const node of state.partial.nodes) { if (node.edgesIn.size === 0 && node.name !== value && state.partial.nodes.has(node)) { state.partial.nodes.delete(node); } } state.specificity.idCounter += 1; return state; }; // ../../src/query/src/pseudo/abandoned.ts var abandoned = createSecuritySelectorFilter( "abandoned", "missingAuthor" ); // ../../src/query/src/pseudo/attr.ts var parseInternals = (nodes) => { const attributeSelector = asAttributeNode( asPostcssNodeWithChildren(nodes.pop()).nodes[0] ); const properties = []; for (const selector of nodes) { const selectorNode = asPostcssNodeWithChildren(selector).nodes[0]; if (isStringNode(selectorNode)) { properties.push(removeQuotes(asStringNode(selectorNode).value)); } else { properties.push(asTagNode(selectorNode).value); } } properties.push(attributeSelector.attribute); return { attribute: attributeSelector.attribute, insensitive: attributeSelector.insensitive || false, operator: attributeSelector.operator, value: attributeSelector.value, properties }; }; var attr = async (state) => { let internals; try { internals = parseInternals( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :attr selector", { cause: err }); } const comparator = internals.operator ? attributeSelectorsMap.get(internals.operator) : void 0; const value = internals.value || ""; const propertyName = internals.attribute; const insensitive = internals.insensitive; const prefixProperties = internals.properties; return filterAttributes( state, comparator, value, propertyName, insensitive, prefixProperties ); }; // ../../src/query/src/pseudo/confused.ts var confused = async (state) => { assertSecurityArchive(state, "confused"); for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); const exclude = !node.confused && !report?.alerts.some( (alert) => alert.type === "manifestConfusion" ); if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/cve.ts var parseInternals2 = (nodes) => { let cveId = ""; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { cveId = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { cveId = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ).value; } if (!cveId) { throw error("Expected a CVE ID", { found: asPostcssNodeWithChildren(nodes[0]).nodes[0] }); } return { cveId }; }; var cve = async (state) => { assertSecurityArchive(state, "cve"); let internals; try { internals = parseInternals2( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :cve selector", { cause: err }); } const { cveId } = internals; for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); const exclude = !report?.alerts.some( (alert) => alert.props?.cveId?.trim().toLowerCase() === cveId.trim().toLowerCase() ); if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/cwe.ts var parseInternals3 = (nodes) => { let cweId = ""; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { cweId = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { cweId = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ).value; } if (!cweId) { throw error("Expected a CWE ID", { found: asPostcssNodeWithChildren(nodes[0]).nodes[0] }); } return { cweId }; }; var cwe = async (state) => { assertSecurityArchive(state, "cwe"); let internals; try { internals = parseInternals3( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :cwe selector", { cause: err }); } const { cweId } = internals; for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); const exclude = !report?.alerts.some( (alert) => alert.props?.cwes?.some( (cwe2) => cwe2.id.trim().toLowerCase() === cweId.trim().toLowerCase() ) ); if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/debug.ts var debug = createSecuritySelectorFilter( "debug", "debugAccess" ); // ../../src/query/src/pseudo/deprecated.ts var deprecated = createSecuritySelectorFilter( "deprecated", "deprecated" ); // ../../src/query/src/pseudo/dev.ts var dev = async (state) => { for (const edge of state.partial.edges) { if (edge.type !== "dev") { removeEdge(state, edge); } } removeUnlinkedNodes(state); return state; }; // ../../src/query/src/pseudo/dynamic.ts var dynamic = createSecuritySelectorFilter( "dynamic", "dynamicRequire" ); // ../../src/query/src/pseudo/empty.ts var empty = async (state) => { for (const node of state.partial.nodes) { if (node.edgesOut.size > 0) { removeNode(state, node); } } return state; }; // ../../src/query/src/pseudo/entropic.ts var entropic = createSecuritySelectorFilter( "entropic", "highEntropyStrings" ); // ../../src/query/src/pseudo/env.ts var env = createSecuritySelectorFilter("env", "envVars"); // ../../src/query/src/pseudo/eval.ts var evalParser = createSecuritySelectorFilter( "eval", "usesEval" ); // ../../src/query/src/pseudo/fs.ts var fs = createSecuritySelectorFilter( "fs", "filesystemAccess" ); // ../../src/query/src/pseudo/license.ts var kindsMap = /* @__PURE__ */ new Map([ ["unlicensed", "explicitlyUnlicensedItem"], ["misc", "miscLicenseIssues"], ["restricted", "nonpermissiveLicense"], ["ambiguous", "ambiguousClassifier"], ["copyleft", "copyleftLicense"], ["unknown", "unidentifiedLicense"], ["none", "noLicenseFound"], ["exception", "licenseException"], [void 0, void 0] ]); var kinds = new Set(kindsMap.keys()); var isLicenseKind = (value) => kinds.has(value); var asLicenseKind = (value) => { if (!isLicenseKind(value)) { throw error("Expected a valid license kind", { found: value, validOptions: Array.from(kinds) }); } return value; }; var parseInternals4 = (nodes) => { let kind; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kind = asLicenseKind( removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ) ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kind = asLicenseKind( asTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } return { kind }; }; var license = async (state) => { assertSecurityArchive(state, "license"); let internals; try { internals = parseInternals4( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :license selector", { cause: err }); } const { kind } = internals; const alertName = kindsMap.get(kind); for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); const exclude = !report?.alerts.some( (alert) => alert.type === alertName ); if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/link.ts var link = async (state) => { for (const node of state.partial.nodes) { const [type2, path2] = splitDepID(node.id); if (type2 !== "file" || path2.endsWith("tar.gz") || path2 === ".") { removeNode(state, node); } } for (const edge of state.partial.edges) { if (!edge.spec.file || edge.spec.file.endsWith("tar.gz") || edge.spec.file === ".") { state.partial.edges.delete(edge); } } return state; }; // ../../src/query/src/pseudo/malware.ts var kindsMap2 = /* @__PURE__ */ new Map([ ["critical", "malware"], ["high", "gptMalware"], ["medium", "gptSecurity"], ["low", "gptAnomaly"], ["0", "malware"], ["1", "gptMalware"], ["2", "gptSecurity"], ["3", "gptAnomaly"] ]); var kindLevelMap = /* @__PURE__ */ new Map([ ["critical", 0], ["high", 1], ["medium", 2], ["low", 3], ["0", 0], ["1", 1], ["2", 2], ["3", 3] ]); var kinds2 = new Set(kindsMap2.keys()); var isMalwareKind = (value) => kinds2.has(value); var asMalwareKind = (value) => { if (!isMalwareKind(value)) { throw error("Expected a valid malware kind", { found: value, validOptions: Array.from(kinds2) }); } return value; }; var parseInternals5 = (nodes) => { let kindValue = ""; let comparator = void 0; let kind; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ).value; } if (kindValue.startsWith(">=")) { comparator = ">="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith("<=")) { comparator = "<="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith(">")) { comparator = ">"; kindValue = kindValue.substring(1); } else if (kindValue.startsWith("<")) { comparator = "<"; kindValue = kindValue.substring(1); } if (!comparator) { kind = asMalwareKind(kindValue); } else { if (isMalwareKind(kindValue)) { kind = kindValue; } else { throw error( "Expected a valid malware kind or number between 0-3", { found: kindValue } ); } } return { kind, comparator }; }; var malware = async (state) => { assertSecurityArchive(state, "malware"); let internals; try { internals = parseInternals5( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :malware selector", { cause: err }); } const { kind, comparator } = internals; const alertName = comparator ? void 0 : kindsMap2.get(kind); for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); if (!report?.alerts || report.alerts.length === 0) { removeNode(state, node); } } for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); let exclude = true; if (report) { if (comparator) { const kindLevel = kindLevelMap.get(kind); if (!kindLevel) break; for (const alert of report.alerts) { const alertType = alert.type; const currentAlertLevelKey = [...kindsMap2.entries()].find( ([_, alertValue]) => alertValue === alertType )?.[0]; if (currentAlertLevelKey) { const currentAlertLevel = kindLevelMap.get( currentAlertLevelKey ); if (currentAlertLevel == null) continue; switch (comparator) { case ">": if (currentAlertLevel > kindLevel) { exclude = false; } break; case "<": if (currentAlertLevel < kindLevel) { exclude = false; } break; case ">=": if (currentAlertLevel >= kindLevel) { exclude = false; } break; case "<=": if (currentAlertLevel <= kindLevel) { exclude = false; } break; } if (!exclude) break; } } } else { exclude = !report.alerts.some( (alert) => alert.type === alertName ); } } if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/minified.ts var minified = createSecuritySelectorFilter( "minified", "minifiedFile" ); // ../../src/query/src/pseudo/missing.ts var missing = async (state) => { for (const edge of state.partial.edges) { if (edge.to) { state.partial.edges.delete(edge); } } state.partial.nodes.clear(); return state; }; // ../../src/query/src/pseudo/native.ts var nativeParser = createSecuritySelectorFilter( "native", "hasNativeCode" ); // ../../src/query/src/pseudo/network.ts var network = createSecuritySelectorFilter( "network", "networkAccess" ); // ../../src/query/src/pseudo/obfuscated.ts var obfuscated = createSecuritySelectorFilter( "obfuscated", "obfuscatedFile" ); // ../../src/query/src/pseudo/optional.ts var optional = async (state) => { for (const edge of state.partial.edges) { if (!edge.optional) { removeEdge(state, edge); } } removeUnlinkedNodes(state); return state; }; // ../../src/query/src/pseudo/outdated.ts var kinds3 = /* @__PURE__ */ new Set([ "any", "major", "minor", "patch", "in-range", "out-of-range" ]); var isOutdatedKind = (value) => kinds3.has(value); var asOutdatedKind = (value) => { if (!isOutdatedKind(value)) { throw error("Expected a valid outdated kind", { found: value, validOptions: Array.from(kinds3) }); } return value; }; var retrieveRemoteVersions = async (node, specOptions, signal) => { const spec = hydrate(node.id, String(node.name), specOptions); if (!spec.registry || !node.name) { return []; } const url = new URL(spec.registry); url.pathname = `/${node.name}`; const response = await fetch(String(url), { headers: { Accept: "application/vnd.npm.install-v1+json" }, signal }); if (response.status === 404) { throw new AbortError("Missing API"); } if (!response.ok) { throw error("Failed to fetch packument", { name: String(node.name), spec, response }); } const packument = await response.json(); return Object.keys(packument.versions).sort(compare); }; var parseInternals6 = (nodes) => { let kind = "any"; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kind = asOutdatedKind( removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ) ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kind = asOutdatedKind( asTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } return { kind }; }; var queueNode = async (state, node, kind) => { if (!node.name || !node.version) { return node; } const nodeVersion = node.version; let versions; try { versions = await pRetry( () => retrieveRemoteVersions(node, state.specOptions, state.signal), { retries: state.retries, signal: state.signal } ); } catch (err) { console.warn( error("Could not retrieve registry versions", { name: String(node.name), cause: err }) ); versions = []; } const greaterVersions = versions.filter( (version) => gt(version, nodeVersion) ); if (!greaterVersions.length) { return node; } const checkKind = /* @__PURE__ */ new Map([ ["major", major], ["minor", minor], ["patch", patch] ]); switch (kind) { case "any": return; case "major": case "minor": case "patch": { return greaterVersions.some((version) => { const va = checkKind.get(kind)?.(version); const vb = checkKind.get(kind)?.(nodeVersion); if (va === void 0 || vb === void 0) return false; return va > vb; }) ? void 0 : node; } // the node should be part of the result as long as it has at least // one parent node that has a spec definition that satisfies one // of the available remove versions case "in-range": { for (const edge of node.edgesIn) { if (!state.partial.edges.has(edge)) continue; if (greaterVersions.some( (version) => edge.spec.final.range && satisfies(version, edge.spec.final.range) )) { return; } } return node; } // the node is part of the result as long as none of its parents has // a spec definition that satisfies one of the available remote versions case "out-of-range": { for (const edge of node.edgesIn) { if (!state.partial.edges.has(edge)) continue; if (greaterVersions.some( (version) => edge.spec.final.range && satisfies(version, edge.spec.final.range) )) { return node; } } return; } } }; var outdated = async (state) => { let internals; try { internals = parseInternals6( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { if (asError(err).message === "Expected a query node") { internals = { kind: "any" }; } else { throw error("Failed to parse :outdated selector", { cause: err }); } } const { kind } = internals; const queue = []; for (const node of state.partial.nodes) { if (node.mainImporter || node.manifest?.private || splitDepID(node.id)[0] !== "registry") { removeNode(state, node); continue; } queue.push(queueNode(state, node, kind)); } const removeNodeQueue = await Promise.all(queue); for (const node of removeNodeQueue) { if (node) { removeNode(state, node); } } return state; }; // ../../src/query/src/pseudo/overridden.ts var overridden = async (state) => { for (const edge of state.partial.edges) { if (!edge.spec.overridden) { removeEdge(state, edge); } } removeUnlinkedNodes(state); return state; }; // ../../src/query/src/pseudo/path.ts function normalizePath(path2) { const trimmed = path2.trim(); if (trimmed === ".") { return ""; } if (trimmed.startsWith("./")) { return trimmed.slice(2); } return trimmed; } function createPathMatcher(pattern, loose = false) { const normalizedPattern = normalizePath(pattern); const isRoot = normalizedPattern === "" || pattern.trim() === "."; return (path2) => { const normalizedPath = normalizePath(path2); if (isRoot) { return normalizedPath === "" || normalizedPath === "."; } try { return minimatch(normalizedPath, normalizedPattern, { dot: true, nocase: false, matchBase: normalizedPattern === "*" }); } catch (err) { if (loose) { return false; } throw error( "Invalid glob pattern in :path selector", asError(err) ); } }; } var path = async (state) => { const pathContainer = asPostcssNodeWithChildren(state.current); if (!pathContainer.nodes[0]) { return clear(state); } const selector = asPostcssNodeWithChildren(pathContainer.nodes[0]); if (!selector.nodes[0]) { return clear(state); } let pathPattern = ""; if (isStringNode(selector.nodes[0])) { pathPattern = removeQuotes(asStringNode(selector.nodes[0]).value); } else { if (state.loose) { return clear(state); } throw error( "Failed to parse path pattern in :path selector", new Error("Path pattern must be a quoted string") ); } if (!pathPattern) { return clear(state); } if (pathPattern === "[" || pathPattern.includes("[") && !pathPattern.includes("]")) { if (state.loose) { return clear(state); } throw error( "Invalid glob pattern in :path selector", new Error(`Unmatched bracket in pattern: ${pathPattern}`) ); } const matchPath = createPathMatcher(pathPattern, state.loose); for (const node of state.partial.nodes) { const nodePath = node.location || ""; const [type2] = splitDepID(node.id); if (pathPattern === "." && node.mainImporter) { continue; } const pathBased = type2 === "workspace" || type2 === "file"; if (!pathBased || !matchPath(nodePath)) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/peer.ts var peer = async (state) => { for (const edge of state.partial.edges) { if (!edge.peer) { removeEdge(state, edge); } } removeUnlinkedNodes(state); return state; }; // ../../src/query/src/pseudo/prerelease.ts var prerelease = async (state) => { for (const node of state.partial.nodes) { const version = node.manifest?.version; if (!version) { removeNode(state, node); continue; } const parsedVersion = parse(version); if (!parsedVersion) { removeNode(state, node); continue; } if (!parsedVersion.prerelease?.length) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/published.ts var retrieveRemoteDate = async (node, specOptions, signal) => { const spec = hydrate(node.id, String(node.name), specOptions); if (!spec.registry || !node.name || !node.version) { return void 0; } const url = new URL(spec.registry); url.pathname = `/${node.name}`; const response = await fetch(String(url), { signal }); if (response.status === 404) { throw new AbortError("Missing API"); } if (!response.ok) { throw error("Failed to fetch packument", { name: String(node.name), spec, response }); } const packument = await response.json(); const res = packument.time?.[node.version]; return res; }; var parseInternals7 = (nodes) => { let value = ""; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { value = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { const tagNode = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ); value = tagNode.value; } let comparator; let relativeDate = value; if (value.startsWith(">=")) { comparator = ">="; relativeDate = value.slice(2); } else if (value.startsWith("<=")) { comparator = "<="; relativeDate = value.slice(2); } else if (value.startsWith(">")) { comparator = ">"; relativeDate = value.slice(1); } else if (value.startsWith("<")) { comparator = "<"; relativeDate = value.slice(1); } return { relativeDate, comparator }; }; var queueNode2 = async (state, node, relativeDate, comparator) => { if (!node.name || !node.version) { return node; } let publishedDate; try { publishedDate = await pRetry( () => retrieveRemoteDate(node, state.specOptions, state.signal), { retries: state.retries, signal: state.signal } ); } catch (err) { console.warn( error("Could not retrieve registry publish date", { name: String(node.name), cause: err }) ); return node; } if (!publishedDate) { return node; } const nodeDate = new Date( publishedDate.slice(0, relativeDate.length) ); const compareDate = new Date(relativeDate); switch (comparator) { case ">": return nodeDate > compareDate ? void 0 : node; case "<": return nodeDate < compareDate ? void 0 : node; case ">=": return nodeDate >= compareDate ? void 0 : node; case "<=": return nodeDate <= compareDate ? void 0 : node; default: return nodeDate.getTime() === compareDate.getTime() ? void 0 : node; } }; var published = async (state) => { let internals; try { internals = parseInternals7( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :published selector", { cause: err }); } const { relativeDate, comparator } = internals; const queue = []; for (const node of state.partial.nodes) { if (node.mainImporter || node.manifest?.private || splitDepID(node.id)[0] !== "registry") { removeNode(state, node); continue; } queue.push(queueNode2(state, node, relativeDate, comparator)); } const removeNodeQueue = await Promise.all(queue); for (const node of removeNodeQueue) { if (node) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/private.ts var privateParser = async (state) => { for (const node of state.partial.nodes) { if (!node.manifest || !asManifest(node.manifest).private) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/prod.ts var prod = async (state) => { for (const edge of state.partial.edges) { if (edge.type !== "prod") { removeEdge(state, edge); } } removeUnlinkedNodes(state); return state; }; // ../../src/query/src/pseudo/root.ts var root = async (state) => { const [anyNode] = state.initial.nodes.values(); const mainImporter = anyNode?.graph.mainImporter; if (!mainImporter) { throw error(":root pseudo-element works on local graphs only"); } for (const edge of state.partial.edges) { if (edge.to !== mainImporter) { state.partial.edges.delete(edge); } } state.partial.nodes.clear(); state.partial.nodes.add(mainImporter); return state; }; // ../../src/query/src/pseudo/scanned.ts var scanned = async (state) => { for (const node of state.partial.nodes) { if (!state.securityArchive?.has(node.id)) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/score.ts var kinds4 = /* @__PURE__ */ new Set([ "overall", "license", "maintenance", "quality", "supplyChain", "vulnerability", void 0 ]); var isScoreKind = (value) => kinds4.has(value); var asScoreKind = (value) => { if (!isScoreKind(value)) { throw error("Expected a valid score kind", { found: value, validOptions: Array.from(kinds4) }); } return value; }; var parseInternals8 = (nodes) => { let rateStr = ""; let comparator = "="; let kind = "overall"; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { rateStr = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { const tagNode = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ); rateStr = tagNode.value; } if (rateStr.startsWith(">=")) { comparator = ">="; rateStr = rateStr.substring(2); } else if (rateStr.startsWith("<=")) { comparator = "<="; rateStr = rateStr.substring(2); } else if (rateStr.startsWith(">")) { comparator = ">"; rateStr = rateStr.substring(1); } else if (rateStr.startsWith("<")) { comparator = "<"; rateStr = rateStr.substring(1); } let rate = parseFloat(rateStr); if (rate > 1) { rate = rate / 100; } if (rate < 0 || rate > 1) { throw error("Expected rate to be between 0 and 100", { found: rateStr }); } if (nodes.length > 1) { if (isStringNode(asPostcssNodeWithChildren(nodes[1]).nodes[0])) { kind = asScoreKind( removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[1]).nodes[0]).value ) ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[1]).nodes[0])) { kind = asScoreKind( asTagNode(asPostcssNodeWithChildren(nodes[1]).nodes[0]).value ); } } return { comparator, rate, kind }; }; var score = async (state) => { assertSecurityArchive(state, "score"); let internals; try { internals = parseInternals8( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :score selector", { cause: err }); } const { comparator, rate, kind } = internals; for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); if (!report) { removeNode(state, node); continue; } const scoreValue = report.score[kind]; let exclude = false; switch (comparator) { case ">": exclude = scoreValue <= rate; break; case "<": exclude = scoreValue >= rate; break; case ">=": exclude = scoreValue < rate; break; case "<=": exclude = scoreValue > rate; break; default: exclude = scoreValue !== rate; break; } if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/scripts.ts var scripts = createSecuritySelectorFilter( "scripts", "installScripts" ); // ../../src/query/src/pseudo/shell.ts var shell = createSecuritySelectorFilter( "shell", "shellAccess" ); // ../../src/query/src/pseudo/semver.ts var semverFunctionNames = /* @__PURE__ */ new Set([ "satisfies", "gt", "gte", "lt", "lte", "eq", "neq" ]); var isSemverFunctionName = (name) => semverFunctionNames.has(name); var asSemverFunctionName = (name) => { if (!isSemverFunctionName(name)) { throw error("Invalid semver function name", { found: name, validOptions: Array.from(semverFunctionNames) }); } return name; }; var semverFunctions = /* @__PURE__ */ new Map([ ["satisfies", satisfies], ["gt", gt], ["gte", gte], ["lt", lt], ["lte", lte], ["eq", eq], ["neq", neq] ]); var parseInternals9 = (nodes, loose) => { let semverValue = ""; try { semverValue = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } catch (err) { if (asError(err).message === "Mismatching query node" && isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { const tagNode = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ); semverValue = tagNode.value; } else { throw err; } } let fnName = "satisfies"; try { if (nodes[1]) { try { fnName = asSemverFunctionName( removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[1]).nodes[0]).value ) ); } catch (err) { if (asError(err).message === "Mismatching query node") { fnName = asSemverFunctionName( asTagNode(asPostcssNodeWithChildren(nodes[1]).nodes[0]).value ); } else { throw err; } } } } catch (e) { if (!loose) { throw e; } } const semverFunction = semverFunctions.get(fnName); if (!semverFunction) { throw error("Invalid semver function name", { found: fnName, validOptions: Array.from(semverFunctions.keys()) }); } let compareAttribute; if (nodes[2]) { const parentNode = asPostcssNodeWithChildren(nodes[2]); const currNode = parentNode.nodes[0]; if (isAttributeNode(currNode)) { const { attribute: attribute2 } = asAttributeNode(currNode); compareAttribute = { attribute: attribute2, properties: [attribute2] }; } else if (isPseudoNode(currNode)) { compareAttribute = parseInternals( asPseudoNode(currNode).nodes ); } else if (isStringNode(currNode)) { const attribute2 = removeQuotes(asStringNode(currNode).value); compareAttribute = { attribute: attribute2, properties: [attribute2] }; } } return { semverValue, semverFunction, compareAttribute }; }; var semverParser = async (state) => { let internals; try { internals = parseInternals9( asPostcssNodeWithChildren(state.current).nodes, !!state.loose ); } catch (err) { throw error("Failed to parse :semver selector", { cause: err }); } const { semverValue, semverFunction, compareAttribute } = internals; for (const node of state.partial.nodes) { if (compareAttribute) { const compareValues = getManifestPropertyValues( node, compareAttribute.properties, compareAttribute.attribute ); const compareValue = compareValues?.[0]; const semverValueVersion = parse(semverValue); const compareValueRange = compareValue && parseRange(compareValue); if (semverFunction === satisfies && semverValueVersion && compareValueRange) { if (!satisfies(semverValueVersion, compareValueRange)) { removeNode(state, node); } } else if (!compareValue || !semverFunction(compareValue, semverValue)) { removeNode(state, node); } } else { const manifestVersion = node.manifest?.version; if (!manifestVersion || !semverFunction(manifestVersion, semverValue)) { removeNode(state, node); } } } return state; }; // ../../src/query/src/pseudo/severity.ts var kindsMap3 = /* @__PURE__ */ new Map([ ["critical", "criticalCVE"], ["high", "cve"], ["medium", "potentialVulnerability"], ["low", "mildCVE"], ["0", "criticalCVE"], ["1", "cve"], ["2", "potentialVulnerability"], ["3", "mildCVE"] ]); var kindLevelMap2 = /* @__PURE__ */ new Map([ ["critical", 0], ["high", 1], ["medium", 2], ["low", 3], ["0", 0], ["1", 1], ["2", 2], ["3", 3] ]); var kinds5 = new Set(kindsMap3.keys()); var isSeverityKind = (value) => kinds5.has(value); var parseInternals10 = (nodes) => { let kind; let comparator; if (nodes.length === 0) { throw error("Missing severity kind parameter"); } let kindValue = ""; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ).value; } if (kindValue.startsWith(">=")) { comparator = ">="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith("<=")) { comparator = "<="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith(">")) { comparator = ">"; kindValue = kindValue.substring(1); } else if (kindValue.startsWith("<")) { comparator = "<"; kindValue = kindValue.substring(1); } if (kindValue) { if (isSeverityKind(kindValue)) { kind = kindValue; } else { throw error( "Expected a valid severity kind or number between 0-3", { found: kindValue } ); } } return { kind, comparator }; }; var severity = async (state) => { assertSecurityArchive(state, "severity"); let internals; try { internals = parseInternals10( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :severity selector", { cause: err }); } const { kind, comparator } = internals; for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); if (!report?.alerts || report.alerts.length === 0) { removeNode(state, node); } } for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); let exclude = true; if (report) { if (comparator) { const kindLevel = kindLevelMap2.get(kind); if (!kindLevel) break; for (const alert of report.alerts) { const alertType = alert.type; const currentAlertLevelKey = [...kindsMap3.entries()].find( ([_, alertValue]) => alertValue === alertType )?.[0]; if (currentAlertLevelKey) { const currentAlertLevel = kindLevelMap2.get( currentAlertLevelKey ); if (currentAlertLevel == null) continue; switch (comparator) { case ">": if (currentAlertLevel > kindLevel) { exclude = false; } break; case "<": if (currentAlertLevel < kindLevel) { exclude = false; } break; case ">=": if (currentAlertLevel >= kindLevel) { exclude = false; } break; case "<=": if (currentAlertLevel <= kindLevel) { exclude = false; } break; } } } } else { const alertName = kindsMap3.get(kind); exclude = !report.alerts.some( (alert) => alert.type === alertName ); } } if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/shrinkwrap.ts var shrinkwrap = createSecuritySelectorFilter( "shrinkwrap", "shrinkwrap" ); // ../../src/query/src/pseudo/squat.ts var kindsMap4 = /* @__PURE__ */ new Map([ ["critical", "didYouMean"], ["medium", "gptDidYouMean"], ["0", "didYouMean"], ["2", "gptDidYouMean"], [void 0, void 0] ]); var kindLevelMap3 = /* @__PURE__ */ new Map([ ["critical", 0], ["medium", 2], ["0", 0], ["2", 2] ]); var kinds6 = new Set(kindsMap4.keys()); var isSquatKind = (value) => kinds6.has(value); var parseInternals11 = (nodes) => { let kind; let comparator; let kindValue = ""; if (isStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = removeQuotes( asStringNode(asPostcssNodeWithChildren(nodes[0]).nodes[0]).value ); } else if (isTagNode(asPostcssNodeWithChildren(nodes[0]).nodes[0])) { kindValue = asTagNode( asPostcssNodeWithChildren(nodes[0]).nodes[0] ).value; } if (kindValue.startsWith(">=")) { comparator = ">="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith("<=")) { comparator = "<="; kindValue = kindValue.substring(2); } else if (kindValue.startsWith(">")) { comparator = ">"; kindValue = kindValue.substring(1); } else if (kindValue.startsWith("<")) { comparator = "<"; kindValue = kindValue.substring(1); } if (kindValue) { if (isSquatKind(kindValue)) { kind = kindValue; } else { throw error("Expected a valid squat kind for comparison", { found: kindValue, validOptions: Array.from(kinds6) }); } } return { kind, comparator }; }; var squat = async (state) => { assertSecurityArchive(state, "squat"); let internals; try { internals = parseInternals11( asPostcssNodeWithChildren(state.current).nodes ); } catch (err) { throw error("Failed to parse :squat selector", { cause: err }); } const { kind, comparator } = internals; for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); if (!report?.alerts || report.alerts.length === 0) { removeNode(state, node); } } for (const node of state.partial.nodes) { const report = state.securityArchive.get(node.id); if (!report) continue; let exclude = true; if (comparator) { const kindLevel = kindLevelMap3.get(kind); if (kindLevel === void 0) break; let matchesComparison = false; for (const alert of report.alerts) { const alertType = alert.type; const alertLevelKey = [...kindsMap4.entries()].find( ([_, value]) => value === alertType )?.[0]; if (alertLevelKey) { const alertLevel = kindLevelMap3.get(alertLevelKey); if (alertLevel === void 0) continue; switch (comparator) { case ">": if (alertLevel > kindLevel) { matchesComparison = true; } break; case "<": if (alertLevel < kindLevel) { matchesComparison = true; } break; case ">=": if (alertLevel >= kindLevel) { matchesComparison = true; } break; case "<=": if (alertLevel <= kindLevel) { matchesComparison = true; } break; } if (matchesComparison) break; } } exclude = !matchesComparison; } else { const alertName = kindsMap4.get(kind); exclude = !report.alerts.some((alert) => alert.type === alertName); } if (exclude) { removeNode(state, node); } } removeDanglingEdges(state); return state; }; // ../../src/query/src/pseudo/suspicious.ts var suspicious = createSecuritySelectorFilter( "suspicious", "suspiciousStarActivity" ); // ../../src/query/src/pseudo/tracker.ts var tracker = createSecuritySelectorFilter( "tracker", "telemetry" ); // ../../src/query/src/pseudo/trivial.ts var trivial = createSecuritySelectorFilter( "trivial", "trivialPackage" ); // ../../src/query/src/pseudo/type.ts var type = async (state) => { const type2 = asPostcssNodeWithChildren(state.current); const selector = asPostcssNodeWithChildren(type2.nodes[0]); const name = asTagNode(selector.nodes[0]).value; for (const node of state.partial.nodes) { const nodeType = splitDepID(node.id)[0]; if (nodeType !== name) { removeNode(state, node); } } removeDanglingEdges(s