Software supply chain malicious package detection method and system based on file dependency graph

CN122020651APending Publication Date: 2026-05-12BEIJING UNIV OF POSTS & TELECOMM
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING UNIV OF POSTS & TELECOMM
Filing Date
2026-02-10
Publication Date
2026-05-12

AI Technical Summary

Technical Problem

Existing methods for detecting malicious packages in the software supply chain are easily circumvented by obfuscation techniques when faced with complex malicious code, resulting in insufficient detection accuracy and robustness. In particular, the false negative rate is high in cloud-native monitoring scenarios, and traditional methods are difficult to effectively capture the multi-dimensional interaction relationships between software entities.

Method used

The paper adopts the Topology-Driven Neural Network (TDGNN-A) framework based on file dependency graphs. By constructing heterogeneous topological dependency graphs of code, it introduces an edge attribute embedding module for semantic enhancement, combines a two-layer graph attention network and a graph information bottleneck mechanism to filter key subgraph features, and uses a cost-sensitive learning strategy to build a classifier to achieve efficient detection of malicious code.

Benefits of technology

It improves the accuracy and robustness of malicious code detection, reduces the false negative rate, and optimizes the detection efficiency after version updates through the incremental differential detection mechanism, adapting to the high-frequency iteration characteristics of the open-source software ecosystem.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122020651A_ABST
    Figure CN122020651A_ABST
Patent Text Reader

Abstract

The invention discloses a software supply chain malicious package detection method and system based on a file dependency graph, and belongs to the technical field of information security. The method comprises the following steps: constructing a reference data set containing malicious and benign samples and extracting initial security semantic features of file nodes; a code heterogeneous topological dependency graph is constructed, hierarchical division is performed through an edge attribute embedding module, edge attribute vectors are quantized, and semantic enhancement is achieved through fusion; taking a double-layer graph attention network as a backbone network to extract graph features, and screening key sub-graph features in combination with a graph information bottleneck mechanism; a cost-sensitive learning strategy is adopted to construct a classifier to complete malicious and benign code discrimination, and an increment difference detection step is added to improve the detection efficiency. The system comprises a user interaction layer, a gateway and service layer, a core computing layer, an infrastructure and data layer, a matched increment difference detection module and the like. According to the method, the accuracy, robustness and efficiency of detection are improved, and NPM ecological high-frequency iteration characteristics are adapted.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of information security technology, specifically to a method and system for detecting malicious software supply chains based on file dependency graphs. Background Technology

[0002] With the rapid expansion of the open-source software ecosystem, software supply chain security has become a critical security issue for global digital infrastructure. NPM (Node Package Manager), as the world's largest software registry, hosts millions of software packages and supports the core architecture of modern web development. Its openness and interconnectivity, while improving development efficiency, also make it a primary target for cyberattacks. In recent years, attackers have gradually shifted from traditional vulnerability exploitation to the deliberate injection of malicious code. Attack methods have become more complex and covert; for example, phishing attacks inject malicious scripts into popular software packages, affecting millions of downloads in a short period, posing a serious threat to software supply chain security.

[0003] Current malware detection methods are mainly divided into two categories: dynamic detection and static detection. Dynamic detection runs code in a controlled environment such as a sandbox or virtual machine and extracts execution behavior features to determine malicious attacks; static detection does not require running code, but extracts static features and matches them with malware features, or builds a deep learning detection model based on structures such as abstract syntax trees and control flow graphs.

[0004] However, existing detection methods have significant drawbacks: static detection is easily evaded by obfuscation techniques such as string encryption and control flow flattening, while dynamic detection is often interfered with by malware through countermeasures such as identifying sandbox environments, leading to unreliable analysis results; traditional signature-based static scanning or text keyword matching methods have gradually become ineffective in the face of advanced obfuscation techniques, especially in cloud-native monitoring scenarios, where attackers disrupt code syntax or mask text semantics, making it difficult for detection models that rely on syntax tree traversal and natural language processing to extract effective features, and malicious payloads are wrapped in a large amount of benign code or noisy logic, resulting in extremely high false negative rates; although some research has attempted to transform code into graph structures and use graph neural networks for detection, a single graph structure cannot fully depict the multidimensional interaction relationships between software entities, and problems such as noise redundancy, missing node features, and imbalance between malicious and benign sample categories in graph data lead to insufficient detection accuracy and robustness, failing to meet the actual needs of NPM supply chain malware detection. Summary of the Invention

[0005] To address the shortcomings of existing technologies, this invention discloses a method and system for detecting malicious software supply chains based on file dependency graphs, in order to solve the problems mentioned in the background.

[0006] To achieve the above objectives, the present invention provides the following technical solution: a method for detecting malicious software packages based on file dependency graphs, comprising the following steps:

[0007] S1. First, a benchmark dataset is constructed, which includes malicious and benign samples. A static security analysis tool adapted to the JavaScript / Node.js environment is used to extract features from the source code of each sample in the benchmark dataset to obtain the initial security semantic features of the file nodes in each sample. Due to the use of heterogeneous graph modeling, the actual data scale processed increases exponentially at the node level. Then, malicious code is detected based on the Topology-Driven Graph Neural Network with Attention (TDGNN-A) framework. The framework steps include four core stages: heterogeneous graph construction and semantic injection, two-layer attention feature extraction, key subgraph mining, and cost-sensitive classification.

[0008] S2. Construct a heterogeneous topological dependency graph of code, with files in the sample as nodes and dependency references between files as edges. Introduce an edge attribute embedding module to perform hierarchical division of edges and quantize them into edge attribute vectors. Merge the edge attribute vectors with the graph topological structure to complete semantic enhancement.

[0009] S3. A two-layer graph attention network is used as the backbone network to extract features from the semantically enhanced heterogeneous topological dependency graph obtained in step 2. Multi-layer attention mechanism is used to capture multi-dimensional features of nodes and high-order topological association information. After nonlinear activation and regularization, graph features are obtained.

[0010] S4. Introduce a graph information bottleneck mechanism. Use a differentiable mask generator to dynamically evaluate the importance of each node and edge pair in the graph for the classification task, filter key features and remove confusing noise to obtain purified key subgraph features.

[0011] S5. A cost-sensitive learning strategy is used to construct a classifier. The key subgraph features obtained in step 4 are input into the classifier to distinguish between malicious code and benign code, thus solving the problem of missed detection caused by the scarcity of malicious samples.

[0012] Preferably, the malicious dataset is extracted from real attack samples of DataDog in cloud-native monitoring scenarios and OpenSSFMaliciousPackagesDataset, while the benign dataset comes from the top-ranked mainstream function packages in the NPM official repository. The total number of samples is 2000 npm packages, including 400 malicious samples and 1600 benign samples. Due to the use of heterogeneous graph modeling, the actual data scale processed increases exponentially at the node level.

[0013] Preferably, step S2 specifically includes the following steps: performing abstract syntax tree parsing on the source code of each sample in the benchmark dataset, identifying all files in the samples and the dependency relationships between files, using each file as an independent node in the heterogeneous topological dependency graph, and using the dependency relationships between files as edges of the graph to construct a basic topological structure; activating the edge attribute embedding module, using regular expression matching static analysis technology to identify the type and hierarchy of each dependency reference edge in the graph, dividing the edges into three levels: internal module calls, native sensitive API calls, and third-party library dependencies; quantizing the dependency reference edges of each level after division to generate edge attribute vectors corresponding to each level, wherein the edge attribute vectors carry semantic information of the corresponding dependency type; and deeply integrating the edge attribute vectors with the constructed basic topological structure through injection operations to achieve semantic enhancement of the graph structure, obtaining a semantically complete heterogeneous topological dependency graph of the code, providing input rich in prior security knowledge for subsequent feature extraction, wherein the mathematical expression of the heterogeneous dependency graph is:

[0014] G=(V,E, ,ψ),

[0015] ,

[0016] Where V is the set of nodes and E is the set of edges. Let ψ be a node type mapping function that maps nodes to a set of node types A, and let ψ be an edge type mapping function that maps edges to a set of relation types R. The sum of the number of node types and edge types is greater than 2. The node is at least one of the following abstracted from the source code of the software package: file, function, variable, external library. The edge is at least one of the following abstracted from the source code: call, definition, reference relationship.

[0017] Preferably, step S3 specifically includes:

[0018] Step 3.1: Combine the semantically complete heterogeneous topological dependency graph of the code obtained in Step 2 with the initial security semantic features of the file nodes extracted in Step 1 to form graph data of the backbone network to be input. The graph data includes a node feature matrix and an adjacency matrix.

[0019] Step 3.2: Start the first layer (Layer 1) of the dual-layer graph attention network (GATv2). Layer 1 adopts a four-head parallel attention mechanism. The four attention heads correspond to different semantic subspaces and simultaneously capture code obfuscation features, graph topology features, dependency features and node security semantic features in the graph data to achieve parallel extraction of multi-dimensional features.

[0020] Step 3.3: Aggregate the four-head attention features output by Layer 1 to obtain the fused features of Layer 1. Then, perform ELU nonlinear activation and Dropout regularization on the fused features in sequence to suppress model overfitting and improve the model's nonlinear fitting ability.

[0021] Step 3.4: Input the fused features processed in Step 3.3 into the second layer, Layer 2, of the dual-layer graph attention network. Layer 2 adopts a single-head attention mechanism, which focuses on aggregating the high-order topological association information of nodes in the graph and integrating local first-order neighbor features into a global code logic representation.

[0022] Step 3.5: Standardize the global code logic representation output by Layer2 to obtain the final graph features. The graph features fully preserve the multidimensional semantics of the nodes and the high-order association information of the graph topology, which are used for subsequent denoising and classification tasks.

[0023] Preferably, step 4 specifically includes the following:

[0024] Step 4.1: Input the graph features obtained in Step 3 into the Graph Information Bottleneck (GIB) mechanism and start the differentiable mask generator. The mask generator dynamically calculates the importance score of each node and each edge in the graph based on the graph features and the classification task objective. The importance score is positively correlated with the contribution of the feature to the classification task. The optimization objective formula of the graph information bottleneck mechanism is:

[0025] min Gsub −I(G sub ,Y)+β·I(G sub ,G),

[0026] Among them G sub G is the key subgraph to be mined, Y is the original heterogeneous dependency graph, I(·,·) is the mutual information, and β is the adjustment coefficient. The nodes and edges are softly weighted by training a differentiable mask generator, and redundant nodes and noisy edges are adaptively removed by a preheating strategy.

[0027] Step 4.2: Set an importance score threshold to filter nodes and edges in the graph. Keep nodes and edges with importance scores higher than the threshold and remove redundant nodes, redundant edges, and noise (including nodes corresponding to dead code and edges corresponding to meaningless dependencies) with importance scores lower than the threshold.

[0028] Step 4.3: Optimize the mask generator through mutual information constraints, minimize the mutual information between the sub-image obtained after filtering and the original image, and maximize the mutual information between the sub-image and the sample label, so as to ensure that the filtering process removes confusing noise without losing key classification features.

[0029] Step 4.4: Perform feature aggregation processing on the filtered subgraphs to obtain purified key subgraph features. The key subgraph features are free from obfuscation and interference, focusing on the core semantic and topological information related to malicious code detection.

[0030] Preferably, step S5 specifically includes:

[0031] Step 5.1: Based on the imbalance between malicious and benign samples in the benchmark dataset, a cost-sensitive learning (CSL) strategy is used to construct a classifier. This classifier introduces an asymmetric weighting mechanism, assigning a higher penalty to misclassifying malicious samples than to misclassifying benign samples, with the penalty ratio set at 1:4. The loss function of the cost-sensitive learning strategy is:

[0032] ,

[0033] Where C 1,0 C represents the cost (underreporting cost) of misclassifying a positive (malicious) sample as a negative (benign) sample. 0,1 The cost of a false alarm is typically set. Based on the basic loss function (such as log loss), y i f(x) represents the true label of the sample. i The value is the model prediction; the cost of underreporting is much higher than the cost of false positives, and the optimal weight ratio is 4:1.

[0034] Step 5.2: Compress the purified key subgraph features obtained in Step 4 into a fixed-dimensional graph-level vector through global pooling, and use the graph-level vector as the input feature of the classifier;

[0035] Step 5.3: Train the classifier by minimizing the loss function with asymmetric penalty cost using the gradient descent algorithm. This forces the model to focus on the feature distribution of minority malicious samples during training, thus optimizing the model's decision boundary.

[0036] Step 5.4: Obtain the key subgraph features of the NPM package to be detected through the processing in steps 1-4, input them into the trained classifier, and the classifier outputs the judgment result of whether the NPM package is malicious or benign, so as to achieve highly robust malicious code detection and effectively reduce the false negative rate.

[0037] Preferably, the method further includes an incremental differential detection step: performing fingerprint calculation on the software package file and caching the historical heterogeneous dependency graph; when detecting a new version of the software package, identifying the changed file and recalculating only the changed part and its affected neighborhood; and performing subgraph fusion of the generated local graph structure with the historical graph to achieve incremental detection.

[0038] This invention also provides a software supply chain malicious package detection system based on file dependency graphs, comprising a user interaction layer, a gateway and service layer, a core computing layer, and an infrastructure and data layer that work collaboratively from top to bottom. The core computing layer is pre-trained with a detection model corresponding to the detection method and performs a full-process inference process, including heterogeneous dependency graph construction, feature extraction, key subgraph mining, and cost-sensitive classification. The user interaction layer enables detection task operation, threat intelligence presentation, and attack path visualization. The gateway and service layer enables access, authentication, load balancing, and task scheduling of detection requests. The core computing layer adopts a producer-consumer model, including static parsing nodes and inference nodes, which respectively complete the syntax tree extraction of source code, intermediate representation transformation, and inference calculation of the detection model. The infrastructure and data layer provides the system with a containerized operating environment and persistent storage and retrieval of data.

[0039] Preferably, the system further includes an incremental difference detection module, which uses a fingerprint calculation mechanism to uniquely identify the package file, identify the changed file after the version update, recalculate only the changed part and its affected neighborhood, and stitches the local graph structure with the historical graph through subgraph fusion technology to reduce the overhead of repeated calculations.

[0040] Preferably, the system further includes a front-end interaction module, a graph construction module, a core inference module, and a state management module. The front-end interaction module supports multi-source uploading and visualization of detection results. The graph construction module implements syntax tree extraction, edge attribute embedding projection, and heterogeneous graph tensor transformation. The core inference module encapsulates the detection model and executes full-process algorithm inference. The state management module achieves asynchronous decoupling of detection tasks through a task queue, monitors the task lifecycle in real time, and supports dynamic configuration and updating of sensitive API rules.

[0041] Compared with the prior art, the beneficial effects of the present invention are as follows:

[0042] 1. This invention constructs a heterogeneous topological dependency graph of code and incorporates edge attribute semantic information, enabling the detection model to accurately capture the security-critical features in the code, making it less susceptible to obfuscation by malicious code and improving the effectiveness of detection.

[0043] 2. This invention combines a two-layer graph attention network with a graph information bottleneck mechanism, which not only fully captures the multi-dimensional features of nodes and high-order topological association information, but also dynamically removes redundant nodes, noisy edges and confusing information in graph data, allowing the model to focus on the core features of malicious detection and improving the accuracy and robustness of detection.

[0044] 3. This invention assigns a higher penalty cost to the misjudgment of malicious samples through a cost-sensitive learning strategy, forcing the model to focus on the feature distribution of minority malicious samples. At the same time, it is combined with an incremental differential detection mechanism to reduce the false negative rate and significantly reduce the repetitive computation overhead after version updates, thus balancing the accuracy and efficiency of detection and adapting to the high-frequency iteration characteristics of the open source software ecosystem. Attached Figure Description

[0045] The accompanying drawings are provided to further illustrate the invention and form part of the specification. They are used together with the embodiments of the invention to explain the invention and do not constitute a limitation thereof.

[0046] In the attached diagram:

[0047] Figure 1 This is a diagram of the TDGNN-A architecture of the present invention;

[0048] Figure 2 This is a diagram of the two-layer attention mechanism architecture of the present invention;

[0049] Figure 3 This is a comparison chart of the ablation experimental performance of the EEP module of the present invention;

[0050] Figure 4 This is a comparison chart of the convergence speed of the EEP module ablation experiment of the present invention;

[0051] Figure 5 This is a comparison chart of the ablation experimental performance of the GIB module of the present invention;

[0052] Figure 6 This is a comparison chart of the noise reduction performance of the GIB module in the ablation experiment of the present invention;

[0053] Figure 7 This is a comparison chart of CSL malicious weight parameters of the present invention;

[0054] Figure 8 This is a system architecture diagram of the software supply chain malicious package detection based on file dependency graph of this invention;

[0055] Figure 9 This is a module design diagram of the software supply chain malicious package detection system based on file dependency graph of the present invention;

[0056] Figure 10 This is a technical architecture diagram of the present invention;

[0057] Figure 11 This is a schematic diagram of the upload page of the front-end interaction subsystem of the present invention;

[0058] Figure 12 This is a schematic diagram of the difference detection page of the front-end interaction subsystem of the present invention;

[0059] Figure 13 This is a schematic diagram of the state management page of the front-end interaction subsystem of the present invention. Detailed Implementation

[0060] The preferred embodiments of the present invention will be described below with reference to the accompanying drawings. It should be understood that the preferred embodiments described herein are for illustration and explanation only and are not intended to limit the present invention.

[0061] Example: Figure 1 As shown, a method for detecting malicious software packages based on file dependency graphs includes the following steps:

[0062] S1. First, a benchmark dataset is constructed. A static security analysis tool adapted to the JavaScript / Node.js environment is used to extract features from the source code of each sample in the benchmark dataset to obtain the initial security semantic features of the file nodes in each sample. The malicious dataset is extracted from real attack samples of the cloud-native monitoring scenario DataDog and OpenSSFMaliciousPackagesDataset. The benign dataset comes from the mainstream functional packages with the top-ranking download volume in the NPM official repository. The total number of samples is 2000 npm packages, including 400 malicious samples and 1600 benign samples. Due to the use of heterogeneous graph modeling, the actual data scale processed shows a multiple increase at the node level. The malicious code is detected based on the Topology-Driven Graph Neural Network with Attention (TDGNN-A) structural framework. The framework steps include four core stages: heterogeneous graph construction and semantic injection, two-layer attention feature extraction, key subgraph mining, and cost-sensitive classification.

[0063] S2. Construct a heterogeneous topological dependency graph. Perform abstract syntax tree parsing on the source code of each sample in the benchmark dataset to identify all files and their dependencies. Use each file as an independent node in the heterogeneous topological dependency graph, and the dependencies between files as edges to construct the basic topological structure. Start the edge attribute embedding module (EEP), which sits between graph construction and the GNN, acting as a semantic decoder. Rule matching and type parsing: Use static analysis tools (such as AST traversal) combined with regular expressions to scan the `require()`, `import`, and `process.binding()` statements in the source code. The system maintains a sensitive API whitelist. Based on the matching results, map each dependency edge to a discrete index T(v). i ,v j ):

[0064] Type 0 (Internal): Index 0 represents a file reference within the package, reflecting the code structure.

[0065] Type 1 (Sensitive): Index 1 indicates a call to a natively sensitive module, which is a strong signal for determining malice.

[0066] Type 2 (External): Index 2 indicates a reference to a regular third-party library.

[0067] Vectorized Projection: Instantiate an m.Embedding layer in PyTorch. This layer is a learnable lookup table that maps discrete class indices to continuous dense vectors e. ij ∈ℝ D , where D is consistent with the node feature dimension for ease of calculation.

[0068] Feature injection strategy: The generated edge embedding vectors are not used as independent features, but are directly passed to the GATv2 layer through PyG's edge_attr interface to participate in the attention calculation in the above formula. Therefore, once an edge is labeled as Type1, regardless of how obfuscated the content of its neighboring nodes is, the attention mechanism will be forced to assign it extremely high attention.

[0069] By injecting the edge attribute vectors into the constructed basic topology, semantic enhancement of the graph structure is achieved, resulting in a semantically complete heterogeneous topological dependency graph. This provides input rich in prior security knowledge for subsequent feature extraction. The mathematical expression of the heterogeneous dependency graph is as follows:

[0070] G=(V,E, ,ψ),

[0071] ,

[0072] Where V is the set of nodes and E is the set of edges. Let ψ be a node type mapping function that maps nodes to a set of node types A, and let ψ be an edge type mapping function that maps edges to a set of relation types R, where the sum of the number of node types and edge types is greater than 2.

[0073] Structural semantic enhancement is typically achieved by explicitly integrating edge features into the message passing function. Its message aggregation and update paradigm can be expressed as:

[0074]

[0075]

[0076] in, Represents a node In the The hidden state of the layer Gather for neighbors. Represents the connection node and The edge feature vector. MSG(·) is a message function that not only combines the features of the source and target nodes, but also forcibly fuses the edge attributes. The node is at least one of the following abstracted from the source code of the software package: file, function, variable, external library; and the edge is at least one of the following abstracted from the source code: call, definition, reference relationship.

[0077] S3. A two-layer graph attention network is used as the backbone network, such as... Figure 2 As shown;

[0078] Step 3.1: Combine the semantically complete heterogeneous topological dependency graph of the code obtained in Step 2 with the initial security semantic features of the file nodes extracted in Step 1 to form graph data of the backbone network to be input. The graph data includes a node feature matrix and an adjacency matrix.

[0079] Step 3.2: Start the first layer (Layer 1) of the dual-layer graph attention network. Layer 1 adopts a four-head parallel attention mechanism. The four attention heads correspond to different semantic subspaces and simultaneously capture code obfuscation features, graph topology features, dependency features, and node security semantic features in the graph data to achieve parallel extraction of multi-dimensional features.

[0080] Step 3.3: Aggregate the four-head attention features output by Layer 1 to obtain the fused features of Layer 1. Then, perform ELU nonlinear activation and Dropout regularization on the fused features in sequence to suppress model overfitting and improve the model's nonlinear fitting ability.

[0081] Step 3.4: Input the fused features processed in Step 3.3 into the second layer, Layer 2, of the dual-layer graph attention network. Layer 2 adopts a single-head attention mechanism, which focuses on aggregating the high-order topological association information of nodes in the graph and integrating local first-order neighbor features into a global code logic representation.

[0082] Step 3.5: Standardize the global code logic representation output by Layer2 to obtain the final graph features. The graph features fully preserve the multidimensional semantics of the nodes and the high-order association information of the graph topology, which are used for subsequent denoising and classification tasks.

[0083] S4. Introducing a graph information bottleneck mechanism

[0084] Step 4.1: Input the graph features obtained in Step 3 into the graph information bottleneck mechanism and start the differentiable mask generator. The mask generator dynamically calculates the importance score of each node and each edge in the graph based on the graph features and the classification task objective. The importance score is positively correlated with the contribution of the feature to the classification task. The optimization objective formula of the graph information bottleneck mechanism is:

[0085] min Gsub −I(G sub ,Y)+β·I(G sub ,G),

[0086] Among them G sub G is the key subgraph to be mined, Y is the original heterogeneous dependency graph, I(·,·) is the mutual information, and β is the adjustment coefficient. The nodes and edges are softly weighted by training a differentiable mask generator, and redundant nodes and noisy edges are adaptively removed by a preheating strategy.

[0087] Step 4.2: Set an importance score threshold, filter the nodes and edges in the graph, retain nodes and edges with importance scores higher than the threshold, and remove redundant nodes, redundant edges and confusing noise with importance scores lower than the threshold.

[0088] Step 4.3: Optimize the mask generator through mutual information constraints, minimize the mutual information between the sub-image obtained after filtering and the original image, and maximize the mutual information between the sub-image and the sample label, so as to ensure that the filtering process removes confusing noise without losing key classification features.

[0089] Step 4.4: Perform feature aggregation processing on the filtered subgraphs to obtain purified key subgraph features. The key subgraph features are free from obfuscation and interference, focusing on the core semantic and topological information related to malicious code detection.

[0090] S5. Construct a classifier using a cost-sensitive learning strategy:

[0091] Step 5.1: Based on the imbalance between malicious and benign samples in the benchmark dataset, a cost-sensitive learning strategy is used to construct a classifier. This classifier introduces an asymmetric weighting mechanism, assigning a higher penalty to misclassifying malicious samples than to misclassifying benign samples, with the penalty ratio set at 1:4. The loss function of the cost-sensitive learning strategy is:

[0092] ,

[0093] Where C 1,0 C represents the cost of misclassifying a positive sample as a negative sample. 0,1 The cost of a false alarm is typically set. Based on the loss function, y if(x) represents the true label of the sample. i The values ​​are model predictions; the cost of underreporting is much higher than the cost of false positives, and the optimal weight ratio is 4:1.

[0094] Step 5.2: Compress the purified key subgraph features obtained in Step 4 into a fixed-dimensional graph-level vector through global pooling, and use the graph-level vector as the input feature of the classifier;

[0095] Step 5.3: Train the classifier by minimizing the loss function with asymmetric penalty cost using the gradient descent algorithm. This forces the model to focus on the feature distribution of minority malicious samples during training, thus optimizing the model's decision boundary.

[0096] Step 5.4: Obtain the key subgraph features of the NPM package to be detected through the processing in steps 1-4, input them into the trained classifier, and the classifier outputs the judgment result of whether the NPM package is malicious or benign, so as to achieve highly robust malicious code detection and effectively reduce the false negative rate.

[0097] The present invention also includes an incremental differential detection step: fingerprinting the software package file and caching the historical heterogeneous dependency graph; when detecting a new version of the software package, identifying the changed file and recalculating only the changed part and its affected neighborhood; and sub-graph fusion of the generated local graph structure with the historical graph to achieve incremental detection.

[0098] like Figure 8 As shown, this invention also provides a software supply chain malicious package detection system based on file dependency graphs. Given the current state of the NPM ecosystem, where code parsing and deep learning inference rely on two heterogeneous technology stacks—Node.js and Python—the system adopts the design principles of "separation of storage and computation" and "asynchronous decoupling." The overall architecture is divided into four logical layers from top to bottom: a user interaction layer, a gateway and service layer, a core computing layer, and an infrastructure and data layer. This architecture aims to solve the computational bottleneck caused by large-scale dependency graph construction and ensure system throughput and stability when handling high-concurrency scanning requests. The user interaction layer is the entry point for security analysts to interact with the detection system, primarily responsible for presenting threat intelligence and visualizing attack paths. The front-end is built using the React framework and integrates a deeply customized Cytoscape.js graph rendering engine. To address the pain point of the "black box" nature of deep learning models, this layer is deeply integrated with the back-end inference results, mapping the mask weights output by the graph information bottleneck module in the TDGNN-A model to the visual attributes of the edges.

[0099] The gateway and service layer act as the system's traffic hub, responsible for request access, authentication, and task scheduling. To handle high-concurrency file upload requests, the system deploys Nginx as a load balancer and reverse proxy, responsible for SSL offloading and static resource hosting.

[0100] The core computation layer adopts a producer-consumer pattern based on the Redis message broker. This layer contains two types of independently extended worker nodes: First, the static parsing node runs in a Node.js container environment; it listens to the parsing queue, uses the js-x-ray engine to traverse NPM packages, and extracts the Abstract Syntax Tree (AST) and file reference relationships. This process can effectively identify preliminary obfuscation features such as string encoding and dead code injection, and transform the extracted unstructured data into a standardized intermediate representation. Second, the inference node runs in a Python environment with GPU acceleration. After obtaining intermediate data from the queue, this node first performs graph construction and edge attribute embedding projection (EEP) operations to transform the code structure into a heterogeneous graph tensor supported by PyTorchGeometric. Subsequently, the system loads the pre-trained TDGNN-A model for forward propagation, uses GATv2 to aggregate topological features, and outputs the final malicious probability determination and interpretable subgraph data through the Cost Sensitive Learning (CSL) module.

[0101] The infrastructure and data layer provides a robust operating environment and data support for upper-layer applications. The system uses Docker container technology to encapsulate each microservice, establishing a standardized and isolated operating environment that facilitates elastic scaling via Kubernetes.

[0102] To achieve efficient and accurate detection of NPM malware, this system adheres to the engineering design principle of "high cohesion and low coupling," dividing the overall architecture into five core functional modules: a front-end interaction module, an incremental differential detection module, a graph construction module, a core inference module, and a state management module. These modules work collaboratively to support the entire lifecycle processing flow from source code ingestion to threat awareness. The module design is as follows: Figure 9 As shown.

[0103] The front-end interaction module serves as the interface layer for information exchange between the system and users, comprising two sub-units: upload input and result display. The upload input unit supports multi-source upload strategies, not only compatible with direct delivery of local NPM compressed packages but also providing standardized API input interfaces to adapt to automated calls in CI / CD pipelines. It also features comprehensive version archiving capabilities to ensure the traceability of historical detection records. The result display unit is responsible for transforming the backend detection results into a visualized audit report, highlighting the probability of malicious detection and attack path analysis to help security analysts quickly understand the threat context.

[0104] The incremental differential detection module is a performance optimization component designed for the high-frequency iteration characteristics of the NPM ecosystem. Given that package version updates often involve only minor code changes, this module introduces a fingerprinting mechanism (such as SimHash) to uniquely identify files. When processing new version scanning tasks, the system first identifies the changed files using differential selection logic, recalculates only the changed parts and their affected neighborhoods, and then uses subgraph fusion technology to stitch the newly generated local graph structure with the cached historical graph. This mechanism significantly reduces redundant computation overhead and substantially improves the throughput of continuous version detection.

[0105] The graph construction module undertakes the core preprocessing task of transforming unstructured source code into heterogeneous graph data, serving as a bridge between code semantics and deep learning models. This module first uses static analysis tools to extract the Abstract Syntax Tree (AST), parsing the internal syntax structure and external dependencies of the file. Subsequently, the core EEP projection engine is activated, explicitly classifying call edges into different types—internal calls, sensitive system calls, and external dependency calls—based on a predefined sensitive API rule base, and assigning corresponding semantic embeddings. Finally, the heterogeneous graph conversion unit serializes the node and edge attributes into a tensor format adapted for graph neural network input.

[0106] The core inference module encapsulates the TDGNN-A model proposed in this application and serves as the intelligent decision-making center of the system. This module receives heterogeneous graph data as input and utilizes a topology-aware graph neural network to perform deep aggregation of node features. During inference, the model's built-in GIB mechanism dynamically filters noise dependencies, preserves the structure of key attack subgraphs, and combines cost-sensitive learning strategies to address class imbalance issues, ultimately outputting a high-confidence malicious code discrimination result.

[0107] The state management module is responsible for ensuring the system's stability and the orderly scheduling of tasks under high concurrency environments. By introducing a high-performance message queue, this module achieves asynchronous decoupling and peak shaving for tasks, ensuring that parsing and inference tasks can be elastically queued according to computing resource load. Simultaneously, the state tracking unit monitors the lifecycle of each detection task in real time, providing reliable data support for front-end progress feedback and system fault recovery.

[0108] like Figure 10As shown, to transform the proposed TDGNN-A model from a theoretical algorithm into a viable engineering application, this system designs a layered technical architecture based on hybrid microservices. This architecture follows the design principles of "separation of storage and computation" and "asynchronous decoupling," organically linking system functions from top to bottom. The front-end interaction layer is built on the React framework, providing not only standard command-line interaction but also a visual audit interface that can intuitively map the mask weights output by the backend GIB module to an attack path graph. The gateway layer utilizes an Nginx reverse proxy and a FastAPI service cluster to handle traffic scheduling and authentication tasks, ensuring stability under high concurrency scenarios. The core of the system lies in the asynchronous computation layer, which achieves deep integration of Node.js and Python heterogeneous technology stacks: using a Redis message broker as an asynchronous bus, the system first uses a Node.js parser to efficiently extract the AST features of the source code, then transfers the intermediate data to a Python inference container to perform heterogeneous graph construction based on explicit edge attribute embedding (EEP), and loads the pre-trained TDGNN-A model for cost-sensitive (CSL) inference. The entire architecture relies on a full-stack Docker containerized environment and infrastructure such as PostgreSQL and MinIO, effectively solving the computational bottleneck caused by large-scale code attribute graph construction and inference, and realizing full-process automation and second-level response from source code upload to threat perception.

[0109] To bridge the semantic gap between deep learning models and security analysts, this application constructs a front-end interactive subsystem integrating task management, performance verification, and dynamic configuration. The system homepage adopts a minimalist "search engine-style" layout to reduce user cognitive load. The core operation area not only integrates multimodal file input functionality but also features a specially designed "Enable Incremental Differential Detection" control switch that directly maps to the back-end differential logic. Figure 11 As shown, by subscribing to the consumption status of the Redis message queue, the frontend maps the asynchronous collaborative pipeline of "parsing-inference" into dynamically flowing state capsules in real time, ensuring that users can keep track of task progress immediately. In response to the high-frequency iteration characteristics of the NPM ecosystem, the system designed a version difference visualization interface to verify the engineering value of the incremental detection module. The dashboard intuitively displays a graph structure reuse rate of up to 92% and an order-of-magnitude reduction in processing time. It also utilizes a "ghost node" visual strategy to gray out unchanged historical dependencies and highlight only newly added or modified logical nodes, helping analysts quickly focus on risk changes, such as... Figure 12 As shown. Furthermore, to enhance the system's scalability, the configuration interface deeply integrates operation and maintenance monitoring with a "human-in-the-loop" expert knowledge injection mechanism, such as... Figure 13As shown, the system provides real-time feedback on the back pressure status of the Redis queue and the health of the compute nodes through a digital dashboard, and also provides a dynamic console for the EEP module, allowing analysts to manually add new sensitive API signatures and define risk levels. This real-time interactive design of expert prior knowledge and deep learning models significantly improves the system's continuous adaptability and detection robustness in the face of unknown attack methods.

[0110] I. Ablation Experiment

[0111] 1) Edge Attribute Embedding: This invention conducted targeted ablation experiments, verifying the crucial role of edge attribute semantics in malicious code identification by comparing the quantitative differences in detection performance between the complete model and the variant with the EEP module removed. For example... Figure 3 As shown, the experimental results intuitively demonstrate the comprehensive improvement of the model in various key indicators after introducing EEP. The F1 score significantly increased from 0.9264 in the ablation group to 0.9577 in the complete model, establishing the module's enhancing effect on the overall model performance. The most significant difference was in recall; removing EEP caused this indicator to drop sharply from 0.9714 to 0.9143, powerfully revealing the limitations of pure topological models in capturing covert attacks: without explicit modeling of equilateral attributes such as "sensitive calls" or "external dependencies," the model struggles to effectively identify attack samples with simple structures but containing key malicious payloads. In conclusion, the ablation experiment data fully demonstrates that the EEP module successfully compensates for the shortcomings of traditional graph neural networks that rely solely on structural features, and is a core component ensuring TDGNN-A achieves a high detection rate in the NPM malware detection task.

[0112] Furthermore, the EEP module aims to enhance the graph neural network's ability to understand code behavior through explicit semantic labels. Figure 4 The graph shows the F1 score convergence curves of the full model and the variant with the module removed (NoEEPModel) during training. It is clear from the graph that TDGNN-A exhibits extremely high training efficiency. In the early stages of training, the model's performance increases exponentially, quickly surpassing the 0.90 F1 threshold, and enters a high-stability region after approximately 30 epochs. This indicates that the edge type information provided by EEP acts as a strong inductive bias, providing the model with a clear gradient descent direction, enabling it to quickly identify feature subspaces strongly correlated with malicious behavior. In contrast, NoEEPModel exhibits significant oscillations throughout the training cycle and a slower convergence speed. This is due to the lack of explicit edge semantic guidance; the model is forced to implicitly infer edge importance from the pure topological structure. When faced with subgraphs with similar topologies but vastly different semantics, the model is prone to semantic ambiguity, leading to repeated trial and error in different batch updates, resulting in dramatic fluctuations in the performance curve.

[0113] 2) Key subgraph mining

[0114] This invention also conducted ablation experiments on the GIB module, comprehensively comparing the complete model (TDGNN-A) with the baseline variant (NoGIBModel) that removes the GIB module under the same experimental settings. The experimental results are as follows: Figure 5 As shown, TDGNN-A outperforms the model without GIB in all four key metrics: accuracy, precision, recall, and F1 score.

[0115] Specifically, the data shows that the introduction of the GIB module brought significant performance gains: the model's F1 score improved from 0.9451 to 0.9577, demonstrating an enhanced overall classification ability. Simultaneously, while recall steadily increased from 0.9629 to 0.9714, precision achieved a more significant increase, jumping from 0.9279 to 0.9444. This strongly proves that the GIB mechanism does not simply trade off metrics, but substantially improves representation quality by optimizing information flow. By introducing mutual information constraints at this layer, TDGNN-A can effectively identify redundant structures and noise interference unrelated to malicious semantics, enabling the model to focus on the most discriminative key attack subgraphs.

[0116] To verify the stability of the TDGNN-A model in complex adversarial environments and to explore the denoising mechanism of the graph information bottleneck module, this invention conducted targeted robust ablation experiments. The experiments injected 0% to 80% structural noise into the test set and compared the dynamic changes in F1 scores between the complete model (WithGIB) and the variant with the module removed (NoGIBModel). The experimental results are as follows: Figure 6 As shown. From Figure 6It is clearly observed that the performance of the two models exhibits drastically different trends as noise levels increase: the NoGIBModel shows extremely high sensitivity to structural noise. In a noise-free environment, its F1 score can still reach approximately 0.95; however, once disturbance is introduced, its performance drops precipitously, especially under extreme noise levels of 80%, where the F1 score falls to around 0.40. This indicates that without a denoising mechanism, the backbone network easily aggregates neighborhood information indiscriminately, causing the model to be misled by false sensitive edges, resulting in severe overfitting and false alarms. In contrast, the TDGNN-A model with the GIB module demonstrates superior robustness. Despite the noise level climbing to 80%, the model's F1 score only slowly decreased from approximately 0.96 to 0.88, remaining consistently high. This gentle decline curve proves that the model did not lose its discriminative ability due to increased noise. The above experimental results strongly validate the core assumption of the GIB module: by minimizing the mutual information between the representation and the input, the model can automatically eliminate redundant structures. When faced with deceptive attacks, the NoGIB model tends to capture all edges labeled "sensitive," falling into the trap of local features. The GIB module, however, acts as an adaptive information filter. By optimizing the objective function, it forces the model to ignore spurious edges that, while possessing sensitive attributes, lack topological logic support. This mechanism ensures that the model retains only the key subgraphs that contribute most to the determination of malicious behavior, thereby cutting off the propagation path of noisy information.

[0117] II. Parameter Sensitivity Analysis

[0118] Given the severe class imbalance problem in NPM malware detection scenarios, where the number of benign samples far exceeds that of malicious samples, the standard cross-entropy loss function often dominates the gradient descent direction due to majority class samples, resulting in insufficient recall of malicious samples. To alleviate this bias and establish the optimal cost-sensitive learning strategy, this application conducts a fine-grained sensitivity analysis on the malicious class weight parameter ω in the loss function. The experiment fixes the benign sample weight at 1.0 and adjusts the malicious sample weight ω in steps within the interval [1,8] to explore the nonlinear impact of this hyperparameter on model precision, recall, and F1 score. The experimental results are as follows: Figure 7 As shown.

[0119] Observing the trend of the curves reveals that the model performance is highly sensitive to the choice of weight parameters, exhibiting a typical trade-off between precision and recall. In the low-weight range (ω≤3), the model shows a clear conservative tendency. Although it maintains a high precision of over 0.90 by fitting the majority class, the recall hovers between 0.60 and 0.85, indicating that the penalty is insufficient to force the model to pay sufficient attention to the minority malicious samples, resulting in a high false negative rate. As the weights increase, the model's decision boundary gradually tilts towards the minority class, and the recall shows a significant upward trend. The key inflection point of the experiment occurs at weight ω=4. With this configuration, the F1 score reaches the global maximum for the entire cycle, and the recall jumps to over 0.97, while the precision remains robust at around 0.90. In contrast, when the weights are further increased to ω≥5, although the recall remains close to the saturation zone of 1.0, the precision experiences a precipitous drop, causing the F1 score to fall significantly. This indicates that an excessively high penalty coefficient introduces the risk of overfitting, making the model overly sensitive to noise and generating a large number of unacceptable false positives. Based on the above quantitative analysis, this application ultimately determined 1:4 as the optimal class weight configuration. This setting not only maximizes the comprehensive metric of the F1 score but also maintains the model's usability in practical deployments while ensuring an extremely high detection rate.

[0120] III. Comparative Experiment

[0121] To fully verify the performance advantages of the TDGNN-A model in the NPM malware detection task, this application compared the model with four mainstream benchmark models, including traditional machine learning methods (RF, XGBoost) and classic graph neural network models (GCN, GraphSAGE). The specific performance of each model in terms of accuracy, precision, recall, and F1 score is shown in Table 1.

[0122] RandomForest (RF) is an ensemble learning algorithm based on the Bagging strategy. It constructs multiple decision trees and outputs the final result by voting or averaging their predictions. In the industry of malware detection, RF is often used as the first line of defense due to its extremely high interpretability, robustness to outliers, and fast training speed.

[0123] XGBoost is a gradient boosting tree algorithm. Unlike the parallel construction of Random Forest (RF), XGBoost is trained sequentially, with each new tree dedicated to correcting the residuals of the previous tree. With proper feature engineering, it often achieves excellent results in non-deep learning models and performs exceptionally well when handling structured data. In malware detection, it is currently the most powerful non-graph benchmark model, and many modern detection systems still use XGBoost as a core component due to its extremely high inference efficiency and support for GPU acceleration.

[0124] GCN defines convolution operations through spectral graph theory, enabling nodes to aggregate information from their first-order neighbors. Specifically, Kipf and Welling proposed an efficient hierarchical propagation rule by approximating the Chebyshev polynomial of the graph Laplacian operator with a first-order approximation. This design successfully transforms expensive spectral domain computation into efficient spatial domain neighbor aggregation, significantly reducing computational complexity and becoming the academic standard baseline. Almost all GNN papers published after 2019 use GCN as a comparison object to verify the effectiveness of new models in capturing graph structure information.

[0125] GraphSAGE is an inductive learning framework. Unlike GCN, which must be trained on the entire graph, GraphSAGE generates node embeddings by sampling neighbors and aggregating features. This means it can generate embeddings for nodes not seen during training. In the dynamic ecosystem of NPM, where new packages are released daily, GraphSAGE's inductive learning capabilities make it a highly relevant baseline model. It addresses the challenge GCN faces in handling dynamic and large-scale graphs.

[0126] Table 1 Comparison of experimental performance

[0127] Model Accuracy Precision Recall F1Score RF 0.9650 0.9150 0.7920 0.8491 XGBoost 0.9710 0.9280 0.8350 0.8790 GCN 0.9765 0.9120 0.8950 0.9034 GraphSAGE 0.9810 0.9310 0.9450 0.9379 TDGNN-A 0.9850 0.9444 0.9714 0.9577

[0128] The TDGNN-A model achieves an F1 score of 0.9577 and maintains a high precision of 0.9444 while maintaining an extremely high recall (0.9714). This result strongly validates the effectiveness of the core improvements in this application: the EEP module enhances the model's ability to perceive sensitive calls through semantic edge attributes, significantly reducing false negatives; while the GIB module effectively eliminates redundant noise in the graph structure through an information bottleneck mechanism, suppressing false positives. The TDGNN-A model demonstrates excellent robustness and accuracy in the NPM malware detection task.

[0129] Finally, it should be noted that the above descriptions are merely preferred embodiments of the present invention and are not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A method for detecting malicious packages in a software supply chain based on file dependency graphs, characterized in that, Includes the following steps: S1. First, construct a benchmark dataset, which includes malicious samples and benign samples. Extract features from the source code of each sample in the benchmark dataset to obtain the initial security semantic features of the file nodes in each sample. It also detects malicious code based on a topological graph neural network structure framework; S2. Construct a heterogeneous topological dependency graph of code, with files in the sample as nodes and dependency references between files as edges. Introduce an edge attribute embedding module to perform hierarchical division of edges and quantize them into edge attribute vectors. Merge the edge attribute vectors with the graph topological structure to complete semantic enhancement. S3. A two-layer graph attention network is used as the backbone network to extract features from heterogeneous topological dependency graphs. Multi-layer attention mechanism is used to capture multi-dimensional features of nodes and high-order topological association information. After nonlinear activation and regularization, graph features are obtained. S4. Introduce a graph information bottleneck mechanism. Use a differentiable mask generator to dynamically evaluate the importance of each node and edge pair in the graph for the classification task, filter key features and remove confusing noise to obtain purified key subgraph features. S5. A cost-sensitive learning strategy is used to construct a classifier. Key subgraph features are input into the classifier to distinguish between malicious and benign code.

2. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: In step S1, the malicious dataset is extracted from real attack samples of DataDog in cloud-native monitoring scenarios and OpenSSFMalicious Packages Dataset, while the benign dataset comes from the top-ranked mainstream function packages in the NPM official repository.

3. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: Step S2 specifically includes the following steps: Abstract syntax tree parsing is performed on the source code of each sample in the benchmark dataset to identify all files in the samples and the dependency relationships between files. Each file is used as an independent node in the heterogeneous topological dependency graph, and the dependency relationships between files are used as edges of the graph to construct the basic topological structure. The edge attribute embedding module is activated, and static analysis using regular expression matching is employed to identify the type and hierarchical division of each dependency reference edge in the graph. The partitioned dependency reference edges at each level are then quantized to generate edge attribute vectors corresponding to each level. These edge attribute vectors carry semantic information about the corresponding dependency type. Through injection, these edge attribute vectors are deeply integrated with the constructed basic topology to obtain a semantically complete heterogeneous topology dependency graph. The mathematical expression of this heterogeneous dependency graph is: G=(V,E, ,ψ), , Where V is the set of nodes and E is the set of edges. Let ψ be a node type mapping function that maps nodes to a set of node types A, and let ψ be an edge type mapping function that maps edges to a set of relation types R, such that |A| + |R| >

2.

4. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: Step S3 specifically includes: Step 3.1: Combine the semantically complete heterogeneous topological dependency graph of the code obtained in Step 2 with the initial security semantic features of the file nodes extracted in Step 1 to form graph data of the backbone network to be input. The graph data includes a node feature matrix and an adjacency matrix. Step 3.2: Start the first layer 1 of the two-layer graph attention network. The first layer 1 adopts a four-head parallel attention mechanism. The four attention heads correspond to different semantic subspaces and simultaneously capture code obfuscation features, graph topology features, dependency features and node security semantic features in the graph data to achieve parallel extraction of multi-dimensional features. Step 3.3: Aggregate the four-head attention features output by Layer 1 to obtain the fused features of Layer 1. Then, perform ELU nonlinear activation and Dropout regularization on the fused features in sequence to suppress model overfitting and improve the model's nonlinear fitting ability. Step 3.4: Input the fused features processed in Step 3.3 into the second layer, Layer 2, of the two-layer graph attention network. Layer 2 adopts a single-head attention mechanism, which focuses on aggregating the high-order topological association information of nodes in the graph and integrating local first-order neighbor features into a global code logic representation. Step 3.5: Standardize the global code logic representation output by Layer 2 to obtain the final graph features. The graph features fully retain the multidimensional semantics of the nodes and the high-order association information of the graph topology, which are used for subsequent denoising and classification tasks.

5. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: Step 4 specifically includes the following: Step 4.1: Input the graph features obtained in Step 3 into the graph information bottleneck mechanism and start the differentiable mask generator. The mask generator dynamically calculates the importance score of each node and each edge in the graph based on the graph features and the classification task objective. The importance score is positively correlated with the contribution of the feature to the classification task. The optimization objective formula of the graph information bottleneck mechanism is: min Gsub −I(G sub ,Y)+β·I(G sub ,G), Among them G sub G is the key subgraph to be mined, Y is the original heterogeneous dependency graph, I(·,·) is the mutual information, and β is the adjustment coefficient. The nodes and edges are softly weighted by training a differentiable mask generator, and redundant nodes and noisy edges are adaptively removed by a preheating strategy. Step 4.2: Set an importance score threshold, filter the nodes and edges in the graph, retain nodes and edges with importance scores higher than the threshold, and remove redundant nodes, redundant edges and confusing noise with importance scores lower than the threshold. Step 4.3: Optimize the mask generator through mutual information constraints, minimize the mutual information between the sub-image obtained after filtering and the original image, and maximize the mutual information between the sub-image and the sample label, so as to ensure that the filtering process removes confusing noise without losing key classification features. Step 4.4: Perform feature aggregation processing on the filtered subgraphs to obtain purified key subgraph features. The key subgraph features are free from obfuscation and interference, focusing on the core semantic and topological information related to malicious code detection.

6. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: Step S5 specifically includes: Step 5.1: Based on the imbalance between malicious and benign samples in the benchmark dataset, a cost-sensitive learning strategy is used to construct a classifier. This classifier introduces an asymmetric weighting mechanism, assigning a higher penalty to misclassifying malicious samples than to misclassifying benign samples. The loss function of the cost-sensitive learning strategy is: , Where C 1,0 C represents the cost of misclassifying a positive sample as a negative sample. 0,1 Represents the cost of misreporting Based on the loss function, y i f(x) represents the true label of the sample. i () represents the model's predicted value; Step 5.2: Compress the purified key subgraph features obtained in Step 4 into a fixed-dimensional graph-level vector through global pooling, and use the graph-level vector as the input feature of the classifier; Step 5.3: Train the classifier by minimizing the loss function with asymmetric penalty cost using the gradient descent algorithm. This forces the model to focus on the feature distribution of minority malicious samples during training, thus optimizing the model's decision boundary. Step 5.4: Obtain the key subgraph features of the NPM package to be detected through the processing in steps 1-4, input them into the trained classifier, and the classifier outputs the judgment result of whether the NPM package is malicious or benign, so as to achieve highly robust malicious code detection and effectively reduce the false negative rate.

7. The method for detecting malicious software supply chains based on file dependency graphs according to claim 1, characterized in that: The method also includes an incremental differential detection step: fingerprinting of the software package file and caching of historical heterogeneous dependency graphs; when detecting a new version of the software package, identifying the changed file and recalculating only the changed part and its affected neighborhood; and sub-graph fusion of the generated local graph structure with the historical graph to achieve incremental detection.

8. A software supply chain malicious package detection system based on file dependency graphs, characterized in that: The system comprises a user interaction layer, a gateway and service layer, a core computing layer, and an infrastructure and data layer. The core computing layer is pre-trained with a detection model corresponding to the detection method described in any one of claims 1-7, and performs a full-process inference process including heterogeneous dependency graph construction, feature extraction, key subgraph mining, and cost-sensitive classification. The user interaction layer enables detection task operation, threat intelligence presentation, and attack path visualization. The gateway and service layer enables access, authentication, load balancing, and task scheduling of detection requests. The core computing layer adopts a producer-consumer model, including static parsing nodes and inference nodes, which respectively complete the syntax tree extraction of source code, intermediate representation transformation, and inference calculation of the detection model. The infrastructure and data layer provides the system with a containerized operating environment and persistent storage and retrieval of data.

9. A software supply chain malicious packet detection system based on file dependency graphs according to claim 8, characterized in that: The system also includes an incremental differential detection module, which uses a fingerprint calculation mechanism to uniquely identify the package file, identify the changed files after the version update, recalculate only the changed parts and their affected neighborhoods, and stitches the local graph structure with the historical graph through subgraph fusion technology.

10. A software supply chain malicious package detection system based on file dependency graphs according to claim 8, characterized in that: The system also includes a front-end interaction module, a graph construction module, a core inference module, and a state management module. The front-end interaction module supports multi-source uploading and visualization of detection results. The graph construction module implements syntax tree extraction, edge attribute embedding projection, and heterogeneous graph tensor transformation. The core inference module encapsulates the detection model and executes full-process algorithm inference. The state management module achieves asynchronous decoupling of detection tasks through a task queue, monitors the task lifecycle in real time, and supports dynamic configuration and updates of sensitive API rules.