Sparrow On-Demand Node SDK
With the Node SDK, you can easily perform source code analysis, open source analysis, and web vulnerability analysis without directly calling the Sparrow On-Demand API.
Tip: Sparrow On-Demand Node SDK supports TypeScript.
Table of Contents
- Environment Setup
- Initialization
- Analysis Request
- Status Inquiry
- Download Analysis Result Files
- Read Analysis Results
- Stop Analysis
- Exception Handling
- Object Information
Environment Setup
-
Install Node 20 or higher
-
npm Configuration
npm install @sparrowai/ondemand-node-sdk -
Sparrow On-Demand API Token required
Tip: Refer to Token Issuance.
Initialization
Create a client object OndemandNodeClient to call the API. You can specify settings with OndemandClientConfig.
import { OndemandNodeClient, OndemandClientConfig } from "@sparrowai/ondemand-node-sdk";
// config
const config = new OndemandClientConfig({ apiKey: "API_KEY" });
// create client
const client = new OndemandNodeClient(config);
- apiKey A token (API_KEY) issued by Sparrow On-Demand for authentication in API requests.
Analysis Request
Common Method
The Node SDK provides the following method based on analysis type, such as source code analysis, open source analysis, and web vulnerability analysis.
const requestInfo = await client.doAnalysis(analysisRequest);
- analysisRequest: Request object by analysis type
- SastAnalysisRequest Source Code Analysis
- ScaAnalysisRequest Open Source Analysis
- DastAnalysisRequest Web Vulnerability Analysis
Source Code Analysis
import { getSastAnalysisRequest } from "@sparrowai/ondemand-node-sdk";
const sastVcsRequest = getSastAnalysisRequest({
analysisSource: {
type: 'Vcs',
source: {
url: 'https://github.com/jhkim593/PayProject.git',
branch: 'master',
authToken: 'authToken',
},
}
options: {
extensions: ['java'],
issueSimilarity: true,
},
callbacks: [
{
url: 'url',
type : ['ANALYSIS_PROGRESS'],
headers: { key: 'key', value: 'value' }
},
],
})
const requestInfo = await client.doAnalysis(sastVcsRequest);
- callbacks Callback list
List- type Callback event type
ANALYSIS_COMPLETE: Receives only analysis completion eventsANALYSIS_PROGRESS: Receives analysis progress events except analysis completionSRC_UPLOAD: Source upload
- url Callback URL
- headers Header list
- key Callback header key
- value Callback header value
- type Callback event type
🔽 Source Code Analysis Options
-
sastOptions
-
analysisSource
-
VCS
- url VCS URL
Requiredstring - branch Branch
string - commitId Commit ID
string - tag Tag
string - id VCS ID
string - password VCS Password
string - authToken VCS Token
string
Tip: If only the url is entered, files included in the latest commit of the branch set as default in the Git repository are analyzed.
- url VCS URL
-
ObjectStorage
- endPoint Storage endpoint
Requiredstring - bucket Storage bucket
Requiredstring - object Storage object name
Requiredstring - accessKey Storage access key
string - secretKey Storage secret key
string
- endPoint Storage endpoint
-
-
extensions List of file extensions to analyze
Tip: Enter one of the following:
["java", "go"]["*"]For compressed files, if the extension of the compressed file is included in the analysis targets, all files inside the compressed file are included in the analysis.
-
excludedPath Paths to exclude from analysis
Tip: Case-insensitive and
*can be used.*AA*: Matches all strings containing AAAA*: Matches all strings starting with AA For other ways to set analysis exclusion paths, refer to the following.
-
maxSourceSize Maximum source size
numberThe maximum size of the analysis target to check in source code analysis or open source analysis. If the size of the analysis target downloaded during source code analysis or open source analysis is larger thanSOURCE_SIZE, the analysis is terminated. You can enter an integer between1and200(unit: MB)
-
Tip: Returns a RequestInfo object.
Open Source Analysis
import { getScaAnalysisRequest } from "@sparrowai/ondemand-node-sdk";
const scaObjectStorageRequest = getScaAnalysisRequest({
analysisSource: {
type: 'ObjectStorage',
source: {
bucket: 'bucket',
object: 'object',
accessKey: 'accessKey',
secretKey: 'secretKey',
},
}
options: {
sbomCreatorEmail : 'email'
},
callbacks: [
{
url: 'url',
type : ['ANALYSIS_PROGRESS'],
headers: { key: 'key', value: 'value' }
},
],
})
const requestInfo = await client.doAnalysis(scaObjectStorageRequest);
- callbacks Callback list
List- type Callback event type
ANALYSIS_COMPLETE: Receives only analysis completion eventsANALYSIS_PROGRESS: Receives analysis progress events except analysis completionSRC_UPLOAD: Source upload
- url Callback URL
- headers Header list
- key Callback header key
- value Callback header value
- type Callback event type
🔽 Open Source Analysis Options
-
scaOptions
-
analysisSource
-
VCS
- url Git URL
Requiredstring - branch Branch
string - commitId Commit ID
string - tag Tag
string - id VCS ID
string - password VCS Password
string - authToken VCS Token
string
Tip: If only the url is entered, files included in the latest commit of the branch set as default in the Git repository are analyzed.
- url Git URL
-
ObjectStorage
- endPoint Storage endpoint
Requiredstring - bucket Storage bucket
Requiredstring - object Storage object name
Requiredstring - accessKey Storage access key
string - secretKey Storage secret key
string
- endPoint Storage endpoint
-
-
extensions List of file extensions to analyze
Tip: Enter one of the following:
["java", "go"]["*"]For compressed files, if the extension of the compressed file is included in the analysis targets, all files inside the compressed file are included in the analysis.
-
excludedPath Paths to exclude from analysis
Tip: Case-insensitive and
*can be used.*AA*: Matches all strings containing AAAA*: Matches all strings starting with AA For other ways to set analysis exclusion paths, refer to the following.
-
maxSourceSize Maximum source size
numberThe maximum size of the analysis target to check in source code analysis or open source analysis. If the size of the analysis target downloaded during source code analysis or open source analysis is larger thanSOURCE_SIZE, the analysis is terminated. You can enter an integer between1and200(unit: MB) -
sbomTypes SBOM type list If the list is empty, SBOM is not generated. You can enter the following values:
- SPDX 2.2:
SPDX22(.spdx),SPDX22_JSON(.json),SPDX22_SPREADSHEET(.xlsx),SPDX22_RDF(.rdf) - SPDX 2.3:
SPDX23(.spdx),SPDX23_JSON(.json),SPDX23_SPREADSHEET(.xlsx),SPDX23_RDF(.rdf) - SPDX 3.0:
SPDX30_JSON(.json) - CycloneDX:
CycloneDX14,CycloneDX15,CycloneDX16(.json) - SWID:
SWID(.zip) - NIS SBOM:
NIS_CSV(.csv),NIS_PDF(.pdf),NIS_JSON(.json)
- SPDX 2.2:
-
sbomCreatorUsername SBOM creator
string -
sbomCreatorEmail SBOM creator email
string
-
Tip: Returns a RequestInfo object.
Web Vulnerability Analysis
import { getDastAnalysisRequest } from "@sparrowai/ondemand-node-sdk";
const dastRequest = getDastAnalysisRequest({
options : {
crawlerTargetSeedUrls : ['url'],
},
callbacks : [
{
url : 'url',
type : ['ANALYSIS_COMPLETE'],
headers : { key: 'key', value: 'value' }
}
]
})
const requestInfo = await client.doAnalysis(dastRequest);
- callbacks Callback list
List- type Callback event type
ANALYSIS_COMPLETE: Receives only analysis completion eventsANALYSIS_PROGRESS: Receives analysis progress events except analysis completionSRC_UPLOAD: Source upload
- url Callback URL
- headers Header list
- key Callback header key
- value Callback header value
- type Callback event type
🔽 Web Vulnerability Analysis Options
-
targetUrl Target URL for analysis
Requiredstring -
commonRecordsLogin Login record file
stringTip: Download Sparrow Event Clipboard and save the login process as a file to use.
-
crawlerTargetContainEntireSeed Collect only sub-paths
boolean -
crawlerRequestAcceptLanguage Client language
Tip: Enter in locale format such as
ko_KR. -
crawlerCrawlMaxUrl Maximum number of URLs to collect
numberTip: Enter the default value
0to not limit the number of URLs that can be collected. -
crawlerCrawlTimeout Maximum collection time
numberTip: Enter the default value
0to not limit the collection time. -
analyzerAnalyzeTimeout Maximum analysis time
numberTip: Enter the default value
0to not limit the analysis time. -
crawlerSkipUrl URLs to exclude from collection
string -
analyzerSkipUrl URLs to exclude from analysis
string -
crawlerSkipUrlSuffix URL suffix to exclude
string -
crawlerExcludeCssSelector Elements to exclude from event execution (CSS selector)
-
crawlerIncludeCssSelector Elements to include for event execution (CSS selector)
-
crawlerExcludeXpath Elements to exclude from event execution (XPath)
-
crawlerIncludeXpath Elements to include for event execution (XPath)
-
crawlerRequestCustomHeaders Custom HTTP headers
-
crawlerLimitUrlDepthDegree URL collection depth
Tip: Enter
high,medium, orlow. -
crawlerLimitDomDepthDegree DOM collection depth
Tip: Enter
high,medium, orlow. -
crawlerBrowserExplicitTimeout Event wait time
number -
crawlerRequestCountPerSecond Number of HTTP requests
numberTip: Enter the default value
-1to not limit the number of HTTP requests that can be sent. -
crawlerClientTimeout HTTP client wait time
number
Tip: Returns a RequestInfo object.
Status Inquiry
Request Status Inquiry
You can check the request status after requesting an analysis.
const requestInfo = await client.getRequest(requestId: number)
- requestId Request ID
Requirednumber
Tip: Returns a RequestInfo object.
Analysis Status Inquiry
You can check the analysis status through the analysis ID after the analysis has started.
const analysisInfo = await client.getAnalysis(analysisId: number)
- analysisId Analysis ID
Requirednumber
Tip: Returns an AnalysisInfo object.
Download Analysis Result Files
You can download the analysis results as a file after the analysis is completed.
await client.downloadAnalysisResult(analysisId: number, filePath: string);
-
analysisId Analysis ID
Requirednumber -
filePath Download path
RequiredstringTip : Enter a file name with a zip extension in the download path. /home/result.zip
Read Analysis Results
After the analysis is completed, you can download the result file, extract it, and read the results through tool-specific Reader objects.
Common Method
const resultReader = client.getAnalysiResultReader<T extends ResultReader>(analysisId: number ,filePath: string);
- ResultReader Result reading object by analysis type
- SastResultReader Read Source Code Analysis Results
- ScaResultReader Read Open Source Analysis Results
- DastResultReader Read Web Vulnerability Analysis Results
Read Source Code Analysis Results
import { SastResultReader } from "@sparrowai/ondemand-node-sdk/types";
// 1. Create SastResultReader
const sastResultReader = await client.getAnalysiResultReader<SastResultReader>(analysisId: number ,filePath: string);
// 2. Read analysis result summary
const sastSummary : SastSummary = sastResultReader.readSummary();
// 3. Read analysis asset list
const assets : string[] = sastResultReader.readAsset();
// 4. Return the number of issue files
const size : number = sastResultReader.issueSize();
// 5. Return SastIssue list from issue file
const sastIssues : SastIssue[] = sastResultReader.readIssue(index: number);
// 6. Return WorkMessage list from work messages
const workMessages : WorkMessage[] = sastResultReader.readWorkMessage();
-
SastResultReader
- analysisId Analysis ID
Requirednumber - filePath Download path
Requiredstring
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
string[]. -
issueSize Method to return the number of issue files
Tip: Returns
number. -
readIssue Method to return SastIssue list
- index
Tip: Returns
SastIssue[]and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
WorkMessage[].
Read Open Source Analysis Results
import { ScaResultReader, SbomType } from "@sparrowai/ondemand-node-sdk/types";
// 1. Create ScaResultReader
const scaResultReader = await client.getAnalysiResultReader<ScaResultReader>(analysisId: number ,filePath: string);
// 2. Read analysis result summary
const scaSummary : ScaSummary = scaResultReader.readSummary();
// 3. Read analysis asset list
const assets : string[] = scaResultReader.readAsset();
// 4. Return the number of issue files
const size : number = scaResultReader.issueSize();
// 5. Return SastIssue list from issue file
const scaComponents : ScaComponent[] = scaResultReader.readIssue(index: number);
// 6. Return WorkMessage list from work messages
const workMessages : WorkMessage[] = scaResultReader.readWorkMessage();
// 7. Return SBOM file path
const sbomPath : string = scaResultReader.getSbomPath(sbomType: SbomType);
// ex. const sbomPath : string = scaResultReader.getSbomPath(SbomType.SPDX22);
// 8. Return license notice file (HTML) path
const path : string = scaResultReader.getLicenseNoticeHtmlPath();
// 9. Return license notice file (Markdown) path
const path : string = scaResultReader.getLicenseNoticeMarkDownPath();
// 10. Return license notice file (Text) path
const path : string = scaResultReader.getLicenseNoticeTextPath();
-
SastResultReader
- analysisId Analysis ID
Requirednumber - filePath Download path
Requiredstring
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
string[]. -
issueSize Method to return the number of issue files
Tip: Returns
number. -
readIssue Method to return SastIssue list
- index
Tip: Returns
SastIssue[]and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
WorkMessage[]. -
getSbomPath Method to return SBOM file path
- sbomType SBOM type
Required
Tip: Returns SBOM file path sbomPath.
- sbomType SBOM type
-
getLicenseNoticeHtmlPath Method to return license notice file (HTML) path
Tip: Returns license notice file path path.
-
getLicenseNoticeMarkDownPath Method to return license notice file (Markdown) path
Tip: Returns license notice file path path.
-
getLicenseNoticeTextPath Method to return license notice file (Text) path
Tip: Returns license notice file path path.
Read Web Vulnerability Analysis Results
import { DastResultReader } from "@sparrowai/ondemand-node-sdk/types";
// 1. Create DastResultReader
const dastResultReader = await client.getAnalysiResultReader<DastResultReader>(analysisId: number ,filePath: string);
// 2. Read analysis result summary
const dastSummary : DastSummary = dastResultReader.readSummary();
// 3. Read analysis asset list
const assets : string[] = dastResultReader.readAsset();
// 4. Return the number of issue files
const size : number = dastResultReader.issueSize();
// 5. Return SastIssue list from issue file
const dastIssues : DastIssue[] = dastResultReader.readIssue(index: number);
// 6. Return WorkMessage list from work messages
const workMessages : WorkMessage[] = dastResultReader.readWorkMessage();
-
SastResultReader
- analysisId Analysis ID
Requirednumber - filePath Download path
Requiredstring
- analysisId Analysis ID
-
readSummary Method to read analysis result summary
-
readAsset Method to read analysis asset list
Tip: Returns
string[]. -
issueSize Method to return the number of issue files
Tip: Returns
number. -
readIssue Method to return SastIssue list
- index
Tip: Returns
SastIssue[]and the maximum value can be checked through theissueSize()method.
- index
-
readWorkMessage Method to return WorkMessage list
Tip: Returns
WorkMessage[].
Stop Analysis
You can stop an ongoing analysis.
await client.stopAnalysis(analysisId: number);
- analysisId Analysis ID
Requirednumber
Tip: Returns nothing.
Exception Handling
You can perform analysis by calling methods of the OndemandNodeClient instance created in Initialization. When OndemandException occurs while executing a method, refer to the following for its meaning and handling. OndemandException delivers exceptions through RuntimeException and is classified into two types.
- OndmandClientException
May occur when the client sends a request to Sparrow On-Demand or processes a response from Sparrow On-Demand.
- resultCode Result code
stringDifferent codes are displayed depending on the cause of the exception. For details, refer to Result Codes. - message Message
stringA message about the cause of the exception.
- resultCode Result code
- OndmandServerException
Occurs when Sparrow On-Demand successfully receives a request but cannot process it.
- resultCode Result code
stringDifferent codes are displayed depending on the cause of the exception. For details, refer to Result Codes. - message Message
stringA message about the cause of the exception. - statusCode Status code
numberIndicates the response status code. - validationErrors Validation error message
stringA message returned from the server when validation of the request fails.
- resultCode Result code
Object Information
RequestInfo
- requestId Request ID
number - result Request result
stringThe result when the analysis is terminated, which can have the following values:SUCCESS: Analysis successfully completedFAIL: Analysis failed without proper completionSTOP: Analysis stopped after receiving a stop request
- analysisList Analysis list
AnalysisInfo[]Tip: A list of AnalysisInfo objects.
AnalysisInfo
- analysisId Analysis ID
number - requestId Request ID
number - status Analysis status
string
Status according to the analysis progress stage, displayed as one of the following:STOP_PROCESS: Stopping analysis after receiving a stop requestINIT: Preparing environment for analysisREADY: Environment configured and preparing analysis targetPRE_PROCESS: Preprocessing analysis target for analysisANALYSIS: Performing analysisPOST_PROCESS: Processing results after analysis completionCOMPLETE: Analysis terminated
- toolType Analysis type
string - memo Memo
string