├── index.ts ├── model ├── Platform │ ├── AuthRequest.ts │ └── AccessTokenResponse.ts ├── Xray │ ├── Summary │ │ ├── Cve.ts │ │ ├── Error.ts │ │ ├── VulnerableComponent.ts │ │ ├── Component.ts │ │ ├── License.ts │ │ ├── SummaryRequestModel.ts │ │ ├── SummaryResponse.ts │ │ ├── General.ts │ │ ├── Artifact.ts │ │ ├── ComponentDetails.ts │ │ ├── index.ts │ │ └── Issue.ts │ ├── Scan │ │ ├── Reference.ts │ │ ├── ImpactPath.ts │ │ ├── GraphRequestModel.ts │ │ ├── GraphCve.ts │ │ ├── GraphLicense.ts │ │ ├── Violation.ts │ │ ├── Component.ts │ │ ├── GraphResponse.ts │ │ ├── extendedInformation.ts │ │ ├── Vulnerability.ts │ │ └── index.ts │ ├── JasConfig │ │ └── JasConfig.ts │ ├── Details │ │ ├── Error.ts │ │ └── DetailsResponse.ts │ ├── System │ │ └── Version.ts │ ├── Entitlements │ │ └── Feature.ts │ └── Severity.ts ├── Artifactory │ ├── System │ │ ├── UsageFeature.ts │ │ ├── Version.ts │ │ └── UsageData.ts │ └── Search │ │ ├── Property.ts │ │ ├── ChecksumResult.ts │ │ ├── AqlSearchResult.ts │ │ └── SearchEntry.ts ├── ClientError.ts ├── Xsc │ ├── System │ │ └── Version.ts │ └── Event │ │ ├── XscLog.ts │ │ ├── ScanEventResponse.ts │ │ ├── ScanEvent.ts │ │ ├── StartScanRequest.ts │ │ └── index.ts ├── ClientResponse.ts ├── Logger.ts ├── ProxyConfig.ts ├── ClientSpecificConfig.ts ├── JfrogClientConfig.ts ├── ClientConfig.ts └── index.ts ├── src ├── Xray │ ├── XrayScanProgress.ts │ ├── XrayLogger.ts │ ├── XrayEntitlementsClient.ts │ ├── XraySummaryClient.ts │ ├── XrayDetailsClient.ts │ ├── XrayJasConfigClient.ts │ ├── XraySystemClient.ts │ ├── XrayClient.ts │ └── XrayScanClient.ts ├── ClientUtils.ts ├── Xsc │ ├── XscLogger.ts │ ├── XscSystemClient.ts │ ├── XscClient.ts │ └── XscEventClient.ts ├── Platform │ ├── PlatformLogger.ts │ ├── PlatformClient.ts │ └── WebLoginClient.ts ├── Artifactory │ ├── ArtifactoryLogger.ts │ ├── ArtifactorySearchClient.ts │ ├── ArtifactorySystemClient.ts │ ├── ArtifactoryClient.ts │ └── ArtifactoryDownloadClient.ts ├── BaseLogger.ts ├── index.ts ├── JfrogClient.ts └── HttpClient.ts ├── .gitignore ├── .vscode ├── extensions.json ├── settings.json └── launch.json ├── .prettierrc ├── release ├── pipelines.resources.yml └── pipelines.release.yml ├── tsconfig.json ├── .github ├── release.yml └── workflows │ ├── removeLabel.yml │ ├── frogbot-scan-and-fix.yml │ ├── frogbot-scan-pr.yml │ ├── cla.yml │ └── test.yml ├── jest.config.js ├── test ├── tests │ ├── ClientUtils.spec.ts │ ├── Xray │ │ ├── XrayLogger.spec.ts │ │ ├── XrayJasConfig.spec.ts │ │ ├── XrayEntitlementsClient.spec.ts │ │ ├── XrayClient.spec.ts │ │ ├── XrayDetailsClient.spec.ts │ │ ├── XraySummaryClient.spec.ts │ │ ├── XraySystemClient.spec.ts │ │ └── XrayScanClient.spec.ts │ ├── Artifactory │ │ ├── ArtifactoryLogger.spec.ts │ │ ├── ArtifactorySearchClient.spec.ts │ │ ├── ArtifactoryClient.spec.ts │ │ ├── ArtifactoryDownloadClient.spec.ts │ │ └── ArtifactorySystemClient.spec.ts │ ├── Xsc │ │ ├── XscSystem.spec.ts │ │ ├── XscLogger.spec.ts │ │ ├── XscClient.spec.ts │ │ └── XscEventClient.spec.ts │ ├── Platform │ │ ├── PlatformLogger.spec.ts │ │ └── WebLoginClient.spec.ts │ ├── HttpClient.spec.ts │ └── JfrogClient.spec.ts ├── TestUtils.ts └── resources │ └── xrayDetails │ └── details.json ├── .eslintrc.js ├── CONTRIBUTING.md ├── package.json ├── LICENSE └── README.md /index.ts: -------------------------------------------------------------------------------- 1 | export * from "./model" 2 | export * from "./src" 3 | 4 | -------------------------------------------------------------------------------- /model/Platform/AuthRequest.ts: -------------------------------------------------------------------------------- 1 | export interface IAuthRequest { 2 | session: string; 3 | } 4 | -------------------------------------------------------------------------------- /model/Xray/Summary/Cve.ts: -------------------------------------------------------------------------------- 1 | export interface ICve { 2 | cve: string; 3 | cvss_v2: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Artifactory/System/UsageFeature.ts: -------------------------------------------------------------------------------- 1 | export interface IUsageFeature { 2 | featureId: string; 3 | } 4 | -------------------------------------------------------------------------------- /model/ClientError.ts: -------------------------------------------------------------------------------- 1 | export interface IClientError { 2 | message?: string; 3 | code?: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/Scan/Reference.ts: -------------------------------------------------------------------------------- 1 | export interface IReference { 2 | text?: string; 3 | url: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Artifactory/Search/Property.ts: -------------------------------------------------------------------------------- 1 | export interface IProperty { 2 | key: string; 3 | value: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/Summary/Error.ts: -------------------------------------------------------------------------------- 1 | export interface ISummaryError { 2 | error: string; 3 | identifier: string; 4 | } 5 | -------------------------------------------------------------------------------- /src/Xray/XrayScanProgress.ts: -------------------------------------------------------------------------------- 1 | export interface XrayScanProgress { 2 | setPercentage(percentage: number): void; 3 | } 4 | -------------------------------------------------------------------------------- /model/Xray/JasConfig/JasConfig.ts: -------------------------------------------------------------------------------- 1 | export interface IJasConfig { 2 | enable_token_validation_scanning: boolean; 3 | } 4 | -------------------------------------------------------------------------------- /model/Xray/Scan/ImpactPath.ts: -------------------------------------------------------------------------------- 1 | export interface IImpactPath { 2 | component_id: string; 3 | full_path: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xsc/System/Version.ts: -------------------------------------------------------------------------------- 1 | export interface IXscVersion { 2 | xray_version: string; 3 | xsc_version: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/Details/Error.ts: -------------------------------------------------------------------------------- 1 | export interface IDetailsError { 2 | error_code: string; 3 | error_message: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/System/Version.ts: -------------------------------------------------------------------------------- 1 | export interface IXrayVersion { 2 | xray_version: string; 3 | xray_revision: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Artifactory/System/Version.ts: -------------------------------------------------------------------------------- 1 | export interface IArtifactoryVersion { 2 | version: string; 3 | revision: string; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/Entitlements/Feature.ts: -------------------------------------------------------------------------------- 1 | export interface IFeatureEntitlement { 2 | feature_id: string; 3 | entitled: boolean; 4 | } 5 | -------------------------------------------------------------------------------- /model/Xray/Severity.ts: -------------------------------------------------------------------------------- 1 | export type Severity = 'Critical' | 'High' | 'Medium' | 'Low' | 'Normal' | 'Pending' | 'Information' | 'Unknown'; 2 | -------------------------------------------------------------------------------- /model/Xray/Scan/GraphRequestModel.ts: -------------------------------------------------------------------------------- 1 | export interface IGraphRequestModel { 2 | component_id: string; 3 | nodes: IGraphRequestModel[]; 4 | } 5 | -------------------------------------------------------------------------------- /model/Artifactory/Search/ChecksumResult.ts: -------------------------------------------------------------------------------- 1 | export interface IChecksumResult { 2 | sha1: string; 3 | sha256: string; 4 | md5: string; 5 | } 6 | -------------------------------------------------------------------------------- /model/ClientResponse.ts: -------------------------------------------------------------------------------- 1 | export interface IClientResponse { 2 | data?: any; 3 | headers?: { [key: string]: string }; 4 | status: number; 5 | } 6 | -------------------------------------------------------------------------------- /model/Xray/Summary/VulnerableComponent.ts: -------------------------------------------------------------------------------- 1 | export interface IVulnerableComponent { 2 | component_id: string; 3 | fixed_versions: string[]; 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependency 2 | node_modules 3 | 4 | # IDE 5 | .idea 6 | 7 | # Artifacts 8 | *.map 9 | *.tgz 10 | 11 | # Generated 12 | dist 13 | coverage 14 | -------------------------------------------------------------------------------- /model/Logger.ts: -------------------------------------------------------------------------------- 1 | export interface ILogger { 2 | error: (...args: any) => void; 3 | warn: (...args: any) => void; 4 | debug: (...args: any) => void; 5 | } 6 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "orta.vscode-jest", 4 | "dbaeumer.vscode-eslint", 5 | "esbenp.prettier-vscode" 6 | ] 7 | } -------------------------------------------------------------------------------- /model/Artifactory/Search/AqlSearchResult.ts: -------------------------------------------------------------------------------- 1 | import { ISearchEntry } from './SearchEntry'; 2 | 3 | export interface IAqlSearchResult { 4 | results: ISearchEntry[]; 5 | } 6 | -------------------------------------------------------------------------------- /model/ProxyConfig.ts: -------------------------------------------------------------------------------- 1 | export interface IProxyConfig { 2 | host: string; 3 | port: number; 4 | protocol: string; 5 | proxyAuthorizationHeader?: string; 6 | } 7 | -------------------------------------------------------------------------------- /model/Xray/Summary/Component.ts: -------------------------------------------------------------------------------- 1 | import { ComponentDetails } from './ComponentDetails'; 2 | 3 | export interface IComponent { 4 | component_details: ComponentDetails; 5 | } 6 | -------------------------------------------------------------------------------- /model/Xray/Summary/License.ts: -------------------------------------------------------------------------------- 1 | export interface ILicense { 2 | name: string; 3 | full_name: string; 4 | components: string[]; 5 | more_info_url: string[]; 6 | } 7 | -------------------------------------------------------------------------------- /model/ClientSpecificConfig.ts: -------------------------------------------------------------------------------- 1 | import { IClientConfig } from './ClientConfig'; 2 | 3 | export interface IClientSpecificConfig extends IClientConfig { 4 | serverUrl: string; 5 | } 6 | -------------------------------------------------------------------------------- /model/Xsc/Event/XscLog.ts: -------------------------------------------------------------------------------- 1 | import { XscLogLevel } from './index'; 2 | 3 | export interface XscLog { 4 | log_level: XscLogLevel; 5 | source: string; 6 | message: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/ClientUtils.ts: -------------------------------------------------------------------------------- 1 | export class ClientUtils { 2 | public static addTrailingSlashIfMissing(url: string): string { 3 | return url + (url.endsWith('/') ? '' : '/'); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /model/Xray/Summary/SummaryRequestModel.ts: -------------------------------------------------------------------------------- 1 | import { ComponentDetails } from './ComponentDetails'; 2 | 3 | export interface ISummaryRequestModel { 4 | component_details: ComponentDetails[]; 5 | } 6 | -------------------------------------------------------------------------------- /model/Xray/Scan/GraphCve.ts: -------------------------------------------------------------------------------- 1 | export interface IGraphCve { 2 | cve: string; 3 | cvss_v2_score: string; 4 | cvss_v2_vector: string; 5 | cvss_v3_score: string; 6 | cvss_v3_vector: string; 7 | } 8 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 120, 3 | "singleQuote": true, 4 | "overrides": [ 5 | { 6 | "files": "**/*.ts", 7 | "options": { 8 | "tabWidth": 4 9 | } 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /model/Artifactory/System/UsageData.ts: -------------------------------------------------------------------------------- 1 | import { IUsageFeature } from './UsageFeature'; 2 | 3 | export interface IUsageData { 4 | productId: string; 5 | features: IUsageFeature[]; 6 | uniqueClientId?: string; 7 | } 8 | -------------------------------------------------------------------------------- /model/Xsc/Event/ScanEventResponse.ts: -------------------------------------------------------------------------------- 1 | import { ScanEventEndData } from './ScanEvent'; 2 | import { StartScanRequest } from './StartScanRequest'; 3 | 4 | export interface ScanEventResponse extends StartScanRequest, ScanEventEndData {} 5 | -------------------------------------------------------------------------------- /model/JfrogClientConfig.ts: -------------------------------------------------------------------------------- 1 | import { IClientConfig } from './ClientConfig'; 2 | 3 | export interface IJfrogClientConfig extends IClientConfig { 4 | platformUrl?: string; 5 | artifactoryUrl?: string; 6 | xrayUrl?: string; 7 | } 8 | -------------------------------------------------------------------------------- /model/Xray/Summary/SummaryResponse.ts: -------------------------------------------------------------------------------- 1 | import { ISummaryError } from './Error'; 2 | import { IArtifact } from './Artifact'; 3 | 4 | export interface ISummaryResponse { 5 | artifacts: IArtifact[]; 6 | errors: ISummaryError[]; 7 | } 8 | -------------------------------------------------------------------------------- /model/Xray/Scan/GraphLicense.ts: -------------------------------------------------------------------------------- 1 | import { IComponent } from '.'; 2 | export interface IGraphLicense { 3 | license_key: string; 4 | license_name: string; 5 | components: Map; 6 | references: string[]; 7 | } 8 | -------------------------------------------------------------------------------- /model/Xray/Scan/Violation.ts: -------------------------------------------------------------------------------- 1 | import { IGraphLicense, IVulnerability } from '.'; 2 | 3 | export interface IViolation extends IVulnerability, IGraphLicense { 4 | watch_name: string; 5 | ignore_url: string; 6 | updated: string; 7 | } 8 | -------------------------------------------------------------------------------- /model/Platform/AccessTokenResponse.ts: -------------------------------------------------------------------------------- 1 | export interface AccessTokenResponse { 2 | access_token: string; 3 | expires_in: number; 4 | refresh_token: string; 5 | scope: string; 6 | token_id: string; 7 | token_type: string; 8 | } 9 | -------------------------------------------------------------------------------- /release/pipelines.resources.yml: -------------------------------------------------------------------------------- 1 | resources: 2 | - name: jfrogClientJsReleaseGit 3 | type: GitRepo 4 | configuration: 5 | path: jfrog/jfrog-client-js 6 | gitProvider: il_automation 7 | buildOn: 8 | commit: false 9 | -------------------------------------------------------------------------------- /model/Xray/Summary/General.ts: -------------------------------------------------------------------------------- 1 | export interface IGeneral { 2 | name: string; 3 | path: string; 4 | sha1: string; 5 | sha256: string; 6 | pkg_type: string; 7 | parent_sha256: string[]; 8 | component_id: string; 9 | } 10 | -------------------------------------------------------------------------------- /model/Xray/Summary/Artifact.ts: -------------------------------------------------------------------------------- 1 | import { IGeneral } from './General'; 2 | import { IIssue } from './Issue'; 3 | import { ILicense } from './License'; 4 | 5 | export interface IArtifact { 6 | general: IGeneral; 7 | issues: IIssue[]; 8 | licenses: ILicense[]; 9 | } 10 | -------------------------------------------------------------------------------- /src/Xsc/XscLogger.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from '../../model'; 2 | import { BaseLogger } from '../BaseLogger'; 3 | 4 | const PREFIX: string = 'XscClient: '; 5 | 6 | export class XscLogger extends BaseLogger { 7 | constructor(logger: ILogger) { 8 | super(logger, PREFIX); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Xray/XrayLogger.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from '../../model'; 2 | import { BaseLogger } from '../BaseLogger'; 3 | 4 | const PREFIX: string = 'XrayClient: '; 5 | 6 | export class XrayLogger extends BaseLogger { 7 | constructor(logger: ILogger) { 8 | super(logger, PREFIX); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /model/Xray/Summary/ComponentDetails.ts: -------------------------------------------------------------------------------- 1 | export class ComponentDetails { 2 | public component_id: string = ''; 3 | 4 | constructor(componentId: string) { 5 | this.component_id = componentId; 6 | } 7 | public toString(): string { 8 | return this.component_id; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /model/Xray/Scan/Component.ts: -------------------------------------------------------------------------------- 1 | import { IImpactPath } from '.'; 2 | 3 | export interface IComponent { 4 | package_name: string; 5 | package_version: string; 6 | package_type: string; 7 | fixed_versions: string[]; 8 | infected_versions: string[]; 9 | impact_paths: IImpactPath[][]; 10 | } 11 | -------------------------------------------------------------------------------- /src/Platform/PlatformLogger.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from '../../model'; 2 | import { BaseLogger } from '../BaseLogger'; 3 | 4 | const PREFIX: string = 'PlatformClient: '; 5 | 6 | export class PlatformLogger extends BaseLogger { 7 | constructor(logger: ILogger) { 8 | super(logger, PREFIX); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Artifactory/ArtifactoryLogger.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from '../../model'; 2 | import { BaseLogger } from '../BaseLogger'; 3 | 4 | const PREFIX: string = 'ArtifactoryClient: '; 5 | 6 | export class ArtifactoryLogger extends BaseLogger { 7 | constructor(logger: ILogger) { 8 | super(logger, PREFIX); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /model/Xray/Details/DetailsResponse.ts: -------------------------------------------------------------------------------- 1 | import { IArtifact } from '../Summary'; 2 | import { IDetailsError } from './Error'; 3 | 4 | export interface IDetailsResponse { 5 | build_name: string; 6 | build_number: string; 7 | project_key: string; 8 | is_scan_completed: boolean; 9 | components: IArtifact[]; 10 | error_details: IDetailsError; 11 | } 12 | -------------------------------------------------------------------------------- /model/Xsc/Event/ScanEvent.ts: -------------------------------------------------------------------------------- 1 | import { ScanEventStatus } from './index'; 2 | 3 | export interface ScanEvent extends ScanEventEndData { 4 | multi_scan_id: string; 5 | } 6 | 7 | export interface ScanEventEndData { 8 | event_status?: ScanEventStatus; 9 | total_findings?: number; 10 | total_ignored_findings?: number; 11 | total_scan_duration?: string; 12 | } 13 | -------------------------------------------------------------------------------- /model/Artifactory/Search/SearchEntry.ts: -------------------------------------------------------------------------------- 1 | import { IProperty } from './Property'; 2 | 3 | export interface ISearchEntry { 4 | repo: string; 5 | path: string; 6 | name: string; 7 | actual_sha1: string; 8 | actual_md5: string; 9 | size: number; 10 | created: string; 11 | modified: string; 12 | type: string; 13 | virtual_repos: string[]; 14 | properties: IProperty[]; 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es2018", 5 | "sourceMap": true, 6 | "declaration": true, 7 | "outDir": "dist", 8 | "experimentalDecorators": true, 9 | "esModuleInterop": true, 10 | "strict": true, 11 | "rootDirs": ["src", "model"] 12 | }, 13 | "exclude": ["node_modules", "dist", "test"] 14 | } 15 | -------------------------------------------------------------------------------- /model/Xray/Scan/GraphResponse.ts: -------------------------------------------------------------------------------- 1 | import { IGraphLicense } from './GraphLicense'; 2 | import { IViolation } from './Violation'; 3 | import { IVulnerability } from './Vulnerability'; 4 | 5 | export interface IGraphResponse { 6 | scan_id: string; 7 | package_type: string; 8 | progress_percentage: number; 9 | licenses: IGraphLicense[]; 10 | violations: IViolation[]; 11 | vulnerabilities: IVulnerability[]; 12 | } 13 | -------------------------------------------------------------------------------- /model/Xray/Summary/index.ts: -------------------------------------------------------------------------------- 1 | export { IArtifact } from './Artifact'; 2 | export { ComponentDetails } from './ComponentDetails'; 3 | export { ICve } from './Cve'; 4 | export { IGeneral } from './General'; 5 | export { IIssue } from './Issue'; 6 | export { ILicense } from './License'; 7 | export { ISummaryRequestModel } from './SummaryRequestModel'; 8 | export { ISummaryResponse } from './SummaryResponse'; 9 | export { IVulnerableComponent } from './VulnerableComponent'; 10 | -------------------------------------------------------------------------------- /model/Xray/Scan/extendedInformation.ts: -------------------------------------------------------------------------------- 1 | import { Severity } from '../Severity'; 2 | 3 | export interface IExtendedInformation { 4 | short_description: string; 5 | full_description: string; 6 | remediation?: string; 7 | jfrog_research_severity: Severity; 8 | jfrog_research_severity_reasons?: ISeverityReasons[]; 9 | } 10 | 11 | export interface ISeverityReasons { 12 | name: string; 13 | description: string; 14 | is_positive: boolean; 15 | } 16 | -------------------------------------------------------------------------------- /model/Xray/Summary/Issue.ts: -------------------------------------------------------------------------------- 1 | import { Severity } from '../Severity'; 2 | import { ICve } from './Cve'; 3 | import { IVulnerableComponent } from './VulnerableComponent'; 4 | 5 | export interface IIssue { 6 | issue_id: string; 7 | summary: string; 8 | description: string; 9 | severity: Severity; 10 | provider: string; 11 | created: string; 12 | issue_type: string; 13 | impact_path: string; 14 | components: IVulnerableComponent[]; 15 | cves: ICve[]; 16 | } 17 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | labels: 4 | - ignore for release 5 | categories: 6 | - title: Breaking Changes 🚨 7 | labels: 8 | - breaking change 9 | - title: Exciting New Features 🎉 10 | labels: 11 | - new feature 12 | - title: Improvements 🌱 13 | labels: 14 | - improvement 15 | - title: Bug Fixes 🛠 16 | labels: 17 | - bug 18 | - title: Other Changes 📚 19 | labels: 20 | - "*" 21 | -------------------------------------------------------------------------------- /model/Xsc/Event/StartScanRequest.ts: -------------------------------------------------------------------------------- 1 | import { ScanEventType, ScanEventStatus } from './index'; 2 | 3 | export interface StartScanRequest { 4 | event_type?: ScanEventType; 5 | event_status?: ScanEventStatus; 6 | product?: string; 7 | product_version?: string; 8 | jpd_version?: string; 9 | jfrog_user?: string; 10 | os_platform?: string; 11 | os_architecture?: string; 12 | machine_id?: string; 13 | analyzer_manager_version?: string; 14 | is_default_config?: boolean; 15 | } 16 | -------------------------------------------------------------------------------- /model/Xray/Scan/Vulnerability.ts: -------------------------------------------------------------------------------- 1 | import { IComponent } from './Component'; 2 | import { IGraphCve } from './GraphCve'; 3 | import { IExtendedInformation } from './extendedInformation'; 4 | import { Severity } from '../Severity'; 5 | 6 | export interface IVulnerability { 7 | cves: IGraphCve[]; 8 | references: string[]; 9 | summary: string; 10 | edited?: string; 11 | issue_id: string; 12 | severity: Severity; 13 | components: Map; 14 | extended_information?: IExtendedInformation; 15 | } 16 | -------------------------------------------------------------------------------- /model/Xsc/Event/index.ts: -------------------------------------------------------------------------------- 1 | export { ScanEvent } from './ScanEvent'; 2 | export { StartScanRequest } from './StartScanRequest'; 3 | export { ScanEventResponse } from './ScanEventResponse'; 4 | export { XscLog } from './XscLog'; 5 | 6 | export enum ScanEventStatus { 7 | Started = 'started', 8 | Completed = 'completed', 9 | Cancelled = 'cancelled', 10 | Failed = 'failed', 11 | } 12 | 13 | export enum ScanEventType { 14 | SourceCode = 1, 15 | } 16 | 17 | export type XscLogLevel = 'debug' | 'info' | 'warning' | 'error'; 18 | -------------------------------------------------------------------------------- /src/BaseLogger.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from '../model/'; 2 | 3 | export abstract class BaseLogger implements ILogger { 4 | protected constructor(private readonly logger: ILogger, private readonly prefix: string) {} 5 | 6 | public warn(str: string): void { 7 | this.logger.warn(this.prefix + str); 8 | } 9 | 10 | public debug(str: string): void { 11 | this.logger.debug(this.prefix + str); 12 | } 13 | 14 | public error(str: string): void { 15 | this.logger.error(this.prefix + str); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /model/Xray/Scan/index.ts: -------------------------------------------------------------------------------- 1 | export { IComponent } from './Component'; 2 | export { IGraphLicense } from './GraphLicense'; 3 | export { IGraphRequestModel } from './GraphRequestModel'; 4 | export { IGraphResponse } from './GraphResponse'; 5 | export { IImpactPath } from './ImpactPath'; 6 | export { IViolation } from './Violation'; 7 | export { IVulnerability } from './Vulnerability'; 8 | export { IReference } from '../Scan/Reference'; 9 | export { IExtendedInformation, ISeverityReasons } from './extendedInformation'; 10 | export { IGraphCve } from './GraphCve'; 11 | -------------------------------------------------------------------------------- /model/ClientConfig.ts: -------------------------------------------------------------------------------- 1 | import { ILogger } from './Logger'; 2 | import { IProxyConfig } from './ProxyConfig'; 3 | 4 | export interface IClientConfig { 5 | username?: string; 6 | password?: string; 7 | accessToken?: string; 8 | proxy?: IProxyConfig | false; 9 | logger?: ILogger; 10 | headers?: { [key: string]: string }; 11 | retries?: number; 12 | timeout?: number; 13 | // Status codes that trigger retries. 14 | retryOnStatusCode?: RetryOnStatusCode; 15 | // Delay between retries. 16 | retryDelay?: number; 17 | } 18 | 19 | export type RetryOnStatusCode = (statusCode: number) => boolean; 20 | -------------------------------------------------------------------------------- /.github/workflows/removeLabel.yml: -------------------------------------------------------------------------------- 1 | name: Remove Label 2 | on: 3 | pull_request_target: 4 | types: [labeled] 5 | # Ensures that only the latest commit is running for each PR at a time. 6 | concurrency: 7 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}-${{ github.ref }} 8 | cancel-in-progress: true 9 | jobs: 10 | Remove-Label: 11 | if: contains(github.event.pull_request.labels.*.name, 'safe to test') 12 | name: Remove label 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Remove 'safe to test' 16 | uses: actions-ecosystem/action-remove-labels@v1 17 | with: 18 | labels: "safe to test" 19 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Jest is the framework used for testing the client. 3 | * This is the Jest config file. 4 | */ 5 | module.exports = { 6 | preset: 'ts-jest', 7 | setupFiles: ['./test/TestUtils.ts'], 8 | testEnvironment: 'node', 9 | transform: { 10 | '^.+\\.ts$': 'ts-jest' 11 | }, 12 | moduleFileExtensions: ['ts', 'js', 'json', 'node'], 13 | testPathIgnorePatterns: ['/node_modules/', '/dist/', 'TestUtils'], 14 | testRegex: '(/test/.*|(\\.|/)(test|spec))\\.ts$', 15 | collectCoverage: true, 16 | coverageDirectory: 'coverage', 17 | collectCoverageFrom: ['src/**/*.ts', '!src/index.ts', '!*.d.ts'], 18 | testTimeout: 300000 19 | }; 20 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "dist": true, // set this to true to hide the "dist" folder with the compiled JS files 5 | "node_modules": true, 6 | "coverage": true 7 | }, 8 | "search.exclude": { 9 | "dist": true // set this to false to include "dist" folder in search results 10 | }, 11 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 12 | "typescript.tsc.autoDetect": "off", 13 | "workbench.editor.enablePreview": false, 14 | "workbench.editor.enablePreviewFromQuickOpen": false, 15 | "workbench.editor.showTabs": true, 16 | "files.autoSave": "afterDelay" 17 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "name": "vscode-jest-tests", 10 | "request": "launch", 11 | "args": [ 12 | "--runInBand" 13 | ], 14 | "cwd": "${workspaceFolder}", 15 | "console": "integratedTerminal", 16 | "internalConsoleOptions": "neverOpen", 17 | "disableOptimisticBPs": true, 18 | "program": "${workspaceFolder}/node_modules/jest/bin/jest" 19 | } 20 | ] 21 | } -------------------------------------------------------------------------------- /test/tests/ClientUtils.spec.ts: -------------------------------------------------------------------------------- 1 | import { ClientUtils } from '../../src/ClientUtils'; 2 | describe('ClientUtils tests', () => { 3 | describe('AddTrailingSlashIfMissing', () => { 4 | const expectedOutput: string = 'https://example.com/'; 5 | 6 | it('URL without trailing slash', () => { 7 | const input: string = 'https://example.com'; 8 | 9 | const result: string = ClientUtils.addTrailingSlashIfMissing(input); 10 | 11 | expect(result).toBe(expectedOutput); 12 | }); 13 | 14 | it('URL with trailing slash', () => { 15 | const input: string = 'https://example.com/'; 16 | 17 | const result: string = ClientUtils.addTrailingSlashIfMissing(input); 18 | 19 | expect(result).toBe(expectedOutput); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { ArtifactoryDownloadClient } from './Artifactory/ArtifactoryDownloadClient'; 2 | export { ArtifactorySearchClient } from './Artifactory/ArtifactorySearchClient'; 3 | export { ArtifactorySystemClient } from './Artifactory/ArtifactorySystemClient'; 4 | export { HttpClient } from './HttpClient'; 5 | export { JfrogClient } from './JfrogClient'; 6 | export { XrayDetailsClient } from './Xray/XrayDetailsClient'; 7 | export { XrayScanClient as XrayGraphClient } from './Xray/XrayScanClient'; 8 | export { XraySummaryClient } from './Xray/XraySummaryClient'; 9 | export { XraySystemClient } from './Xray/XraySystemClient'; 10 | export { XrayScanProgress } from './Xray/XrayScanProgress'; 11 | export { XscEventClient } from './Xsc/XscEventClient'; 12 | export { XscSystemClient } from './Xsc/XscSystemClient'; 13 | export { ClientUtils } from './ClientUtils'; 14 | -------------------------------------------------------------------------------- /src/Artifactory/ArtifactorySearchClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, IRequestParams } from '../HttpClient'; 2 | import { IAqlSearchResult } from '../../model'; 3 | import { ILogger } from '../../model/'; 4 | 5 | export class ArtifactorySearchClient { 6 | private readonly aqlEndpoint: string = '/api/search/aql'; 7 | 8 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 9 | 10 | public async aqlSearch(aqlQuery: string): Promise { 11 | this.logger.debug('Sending AQL request...'); 12 | const requestParams: IRequestParams = { 13 | url: this.aqlEndpoint, 14 | method: 'POST', 15 | data: aqlQuery, 16 | headers: { 'Content-Type': 'text/plain' }, 17 | }; 18 | this.logger.debug('AQL query: ' + JSON.stringify(aqlQuery)); 19 | return (await this.httpClient.doAuthRequest(requestParams)).data; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayLogger.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import { ILogger } from '../../../model'; 3 | import { XrayLogger } from '../../../src/Xray/XrayLogger'; 4 | 5 | const loggerMock: ILogger = { 6 | debug: jest.fn(), 7 | error: jest.fn(), 8 | warn: jest.fn(), 9 | }; 10 | const logger: XrayLogger = new XrayLogger(loggerMock); 11 | 12 | test('warn log', () => { 13 | const message: string = faker.random.words(5); 14 | logger.warn(message); 15 | expect(loggerMock.warn).toHaveBeenCalledWith('XrayClient: ' + message); 16 | }); 17 | 18 | test('error log', () => { 19 | const message: string = faker.random.words(5); 20 | logger.error(message); 21 | expect(loggerMock.error).toHaveBeenCalledWith('XrayClient: ' + message); 22 | }); 23 | 24 | test('debug log', () => { 25 | const message: string = faker.random.words(5); 26 | logger.debug(message); 27 | expect(loggerMock.debug).toHaveBeenCalledWith('XrayClient: ' + message); 28 | }); 29 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: '@typescript-eslint/parser', 4 | plugins: ['@typescript-eslint'], 5 | extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'prettier'], 6 | rules: { 7 | '@typescript-eslint/typedef': [ 8 | 'error', 9 | { 10 | memberVariableDeclaration: true, 11 | variableDeclaration: true, 12 | objectDestructuring: true, 13 | propertyDeclaration: true, 14 | parameter: true 15 | } 16 | ], 17 | 'prefer-const': 'off', 18 | 'no-extra-boolean-cast': 'off', 19 | '@typescript-eslint/no-inferrable-types': 'off', 20 | '@typescript-eslint/no-explicit-any': 'off' 21 | }, 22 | overrides: [ 23 | { 24 | files: ['*.test.ts'], 25 | rules: { 26 | '@typescript-eslint/no-non-null-assertion': 'off' 27 | } 28 | } 29 | ] 30 | }; 31 | -------------------------------------------------------------------------------- /src/Xray/XrayEntitlementsClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, IRequestParams } from '../HttpClient'; 2 | import { IClientResponse, ILogger } from '../../model/'; 3 | 4 | export class XrayEntitlementsClient { 5 | private readonly entitlementsFeatureEndpoint: string = '/api/v1/entitlements/feature/'; 6 | 7 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 8 | 9 | public async feature(feature: string): Promise { 10 | this.logger.debug("Sending entitlement request for feature '" + feature + "'..."); 11 | const requestParams: IRequestParams = { 12 | url: this.entitlementsFeatureEndpoint + feature, 13 | method: 'GET', 14 | }; 15 | try { 16 | let response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 17 | return response.data?.entitled; 18 | } catch (error) { 19 | this.logger.debug(error); 20 | return false; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Xray/XraySummaryClient.ts: -------------------------------------------------------------------------------- 1 | import { ISummaryRequestModel, ISummaryResponse } from '../../model'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { ILogger } from '../../model/'; 4 | import { IClientResponse } from '../ClientResponse'; 5 | 6 | export class XraySummaryClient { 7 | private readonly summaryComponentsEndpoint: string = '/api/v1/summary/component'; 8 | 9 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 10 | 11 | public async component(model: ISummaryRequestModel): Promise { 12 | this.logger.debug('Sending summary/component request...'); 13 | const requestParams: IRequestParams = { 14 | url: this.summaryComponentsEndpoint, 15 | method: 'POST', 16 | data: model, 17 | }; 18 | this.logger.debug('data: ' + JSON.stringify(model)); 19 | const response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 20 | return response.data; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/tests/Artifactory/ArtifactoryLogger.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import { ILogger } from '../../../model'; 3 | import { ArtifactoryLogger } from '../../../src/Artifactory/ArtifactoryLogger'; 4 | 5 | const loggerMock: ILogger = { 6 | debug: jest.fn(), 7 | error: jest.fn(), 8 | warn: jest.fn(), 9 | }; 10 | const logger: ArtifactoryLogger = new ArtifactoryLogger(loggerMock); 11 | 12 | test('warn log', () => { 13 | const message: string = faker.random.words(5); 14 | logger.warn(message); 15 | expect(loggerMock.warn).toHaveBeenCalledWith('ArtifactoryClient: ' + message); 16 | }); 17 | 18 | test('error log', () => { 19 | const message: string = faker.random.words(5); 20 | logger.error(message); 21 | expect(loggerMock.error).toHaveBeenCalledWith('ArtifactoryClient: ' + message); 22 | }); 23 | 24 | test('debug log', () => { 25 | const message: string = faker.random.words(5); 26 | logger.debug(message); 27 | expect(loggerMock.debug).toHaveBeenCalledWith('ArtifactoryClient: ' + message); 28 | }); 29 | -------------------------------------------------------------------------------- /test/tests/Xsc/XscSystem.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import { IJfrogClientConfig, IXscVersion } from '../../../model'; 3 | import { JfrogClient } from '../../../src'; 4 | import { TestUtils } from '../../TestUtils'; 5 | 6 | describe('Xsc System tests', () => { 7 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 8 | const jfrogClient: JfrogClient = new JfrogClient(clientConfig); 9 | 10 | afterAll(() => { 11 | nock.cleanAll(); 12 | }); 13 | 14 | describe('Version tests', () => { 15 | test('Version', async () => { 16 | if (!(await jfrogClient.xsc().system().enabled())) { 17 | clientConfig.logger?.warn('Xsc is not enabled in the configuration platformUrl, skipping tests...'); 18 | return; 19 | } 20 | 21 | const version: IXscVersion = await jfrogClient.xsc().system().version(); 22 | expect(version.xray_version).toBeTruthy(); 23 | expect(version.xsc_version).toBeTruthy(); 24 | }); 25 | }); 26 | }); 27 | -------------------------------------------------------------------------------- /test/tests/Xsc/XscLogger.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import { ILogger } from '../../../model'; 3 | import { XscLogger } from '../../../src/Xsc/XscLogger'; 4 | 5 | const loggerMock: ILogger = { 6 | debug: jest.fn(), 7 | error: jest.fn(), 8 | warn: jest.fn(), 9 | }; 10 | const logger: XscLogger = new XscLogger(loggerMock); 11 | 12 | describe('Xsc Logger tests', () => { 13 | test('warn log', () => { 14 | const message: string = faker.random.words(5); 15 | logger.warn(message); 16 | expect(loggerMock.warn).toHaveBeenCalledWith('XscClient: ' + message); 17 | }); 18 | 19 | test('error log', () => { 20 | const message: string = faker.random.words(5); 21 | logger.error(message); 22 | expect(loggerMock.error).toHaveBeenCalledWith('XscClient: ' + message); 23 | }); 24 | 25 | test('debug log', () => { 26 | const message: string = faker.random.words(5); 27 | logger.debug(message); 28 | expect(loggerMock.debug).toHaveBeenCalledWith('XscClient: ' + message); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /test/tests/Artifactory/ArtifactorySearchClient.spec.ts: -------------------------------------------------------------------------------- 1 | import { IAqlSearchResult, IJfrogClientConfig } from '../../../model'; 2 | import { JfrogClient } from '../../../src'; 3 | import { TestUtils } from '../../TestUtils'; 4 | 5 | let jfrogClient: JfrogClient; 6 | 7 | describe('Artifactory Search tests', () => { 8 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 9 | beforeAll(() => { 10 | jfrogClient = new JfrogClient(clientConfig); 11 | }); 12 | 13 | describe('Search tests', () => { 14 | test('Build Info Artifact AQL Search', async () => { 15 | const response: IAqlSearchResult = await TestUtils.searchArtifactoryBuildRepo(jfrogClient); 16 | expect(response).toBeTruthy(); 17 | expect(response.results).toHaveLength(1); 18 | expect(response.results[0].name).toBeTruthy(); 19 | expect(response.results[0].repo).toBe('artifactory-build-info'); 20 | expect(response.results[0].path).toBeTruthy(); 21 | expect(response.results[0].created).toBeTruthy(); 22 | }); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/Xsc/XscSystemClient.ts: -------------------------------------------------------------------------------- 1 | import { IClientResponse, IXscVersion } from '../../model'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { ILogger } from '../../model/'; 4 | 5 | export class XscSystemClient { 6 | public static readonly versionEndpoint: string = '/api/v1/system/version'; 7 | 8 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 9 | 10 | public async version(): Promise { 11 | this.logger.debug('Sending version request...'); 12 | const requestParams: IRequestParams = { 13 | url: XscSystemClient.versionEndpoint, 14 | method: 'GET', 15 | }; 16 | let response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 17 | return response.data; 18 | } 19 | 20 | public async enabled(): Promise { 21 | try { 22 | await this.version(); 23 | return true; 24 | } catch (error) { 25 | this.logger.error('Error getting XSC enabled status', error); 26 | return false; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/tests/Platform/PlatformLogger.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import { ILogger } from '../../../model'; 3 | import { PlatformLogger } from '../../../src/Platform/PlatformLogger'; 4 | 5 | const loggerMock: ILogger = { 6 | debug: jest.fn(), 7 | error: jest.fn(), 8 | warn: jest.fn(), 9 | }; 10 | 11 | const logger: PlatformLogger = new PlatformLogger(loggerMock); 12 | 13 | describe('Platform log tests', () => { 14 | test('warn log', () => { 15 | const message: string = faker.random.words(5); 16 | logger.warn(message); 17 | expect(loggerMock.warn).toHaveBeenCalledWith('PlatformClient: ' + message); 18 | }); 19 | 20 | test('error log', () => { 21 | const message: string = faker.random.words(5); 22 | logger.error(message); 23 | expect(loggerMock.error).toHaveBeenCalledWith('PlatformClient: ' + message); 24 | }); 25 | 26 | test('debug log', () => { 27 | const message: string = faker.random.words(5); 28 | logger.debug(message); 29 | expect(loggerMock.debug).toHaveBeenCalledWith('PlatformClient: ' + message); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /model/index.ts: -------------------------------------------------------------------------------- 1 | export { IAqlSearchResult } from './Artifactory/Search/AqlSearchResult'; 2 | export { ISearchEntry } from './Artifactory/Search/SearchEntry'; 3 | export { IUsageData } from './Artifactory/System/UsageData'; 4 | export { IUsageFeature } from './Artifactory/System/UsageFeature'; 5 | export { IArtifactoryVersion } from './Artifactory/System/Version'; 6 | export { IJfrogClientConfig } from './JfrogClientConfig'; 7 | export { IClientResponse } from './ClientResponse'; 8 | export { IClientError } from './ClientError'; 9 | export { IChecksumResult } from './Artifactory/Search/ChecksumResult'; 10 | export { ILogger } from './Logger'; 11 | export { IProxyConfig } from './ProxyConfig'; 12 | export { IDetailsResponse } from './Xray/Details/DetailsResponse'; 13 | export * from './Xray/Scan'; 14 | export { Severity } from './Xray/Severity'; 15 | export * from './Xray/Summary'; 16 | export { IXrayVersion } from './Xray/System/Version'; 17 | export { AccessTokenResponse } from './Platform/AccessTokenResponse'; 18 | export { RetryOnStatusCode } from './ClientConfig'; 19 | export * from './Xsc/Event'; 20 | export { IXscVersion } from './Xsc/System/Version'; 21 | -------------------------------------------------------------------------------- /src/Xray/XrayDetailsClient.ts: -------------------------------------------------------------------------------- 1 | import { IDetailsResponse } from '../../model'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { ILogger } from '../../model/'; 4 | 5 | export class XrayDetailsClient { 6 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 7 | 8 | public async build(buildName: string, buildNumber: string, projectKey?: string): Promise { 9 | this.logger.debug('Sending build details request to Xray...'); 10 | let encodedUrl: string = `api/v1/details/build?build_name=${encodeURIComponent( 11 | buildName 12 | )}&build_number=${encodeURIComponent(buildNumber)}`; 13 | if (projectKey) { 14 | encodedUrl += `&project_key=${encodeURIComponent(projectKey)}`; 15 | } 16 | const requestParams: IRequestParams = { 17 | url: encodedUrl, 18 | method: 'GET', 19 | }; 20 | this.logger.debug('encoded URL: ' + JSON.stringify(encodedUrl)); 21 | return await ( 22 | await this.httpClient.doAuthRequest(requestParams) 23 | ).data; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Xray/XrayJasConfigClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, IRequestParams } from '../HttpClient'; 2 | import { ILogger } from '../../model'; 3 | import { IJasConfig } from '../../model/Xray/JasConfig/JasConfig'; 4 | 5 | export class XrayJasConfigClient { 6 | private readonly jasConfigurationEndpoint: string = '/api/v1/configuration/jas'; 7 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 8 | /** 9 | * 10 | * Sends 'GET /configuration/js requests to Xray and waits for 200 response'. 11 | * @returns the jas config 12 | * @throws an exception if an unexpected response received from Xray 13 | */ 14 | async getJasConfig(): Promise { 15 | this.logger.debug(`Sending GET ${this.jasConfigurationEndpoint} request...`); 16 | const requestParams: IRequestParams = { 17 | url: this.jasConfigurationEndpoint, 18 | method: 'GET', 19 | validateStatus: (status: number): boolean => { 20 | return status === 200; 21 | }, 22 | }; 23 | return await ( 24 | await this.httpClient.doAuthRequest(requestParams) 25 | ).data; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Guidelines 2 | 3 | - If the existing tests do not already cover your changes, please add tests. 4 | - Pull requests should be created on the _master_ branch. 5 | - Please run `npm run format` for formatting the code before submitting the pull request. 6 | 7 | # Building and Testing the Sources 8 | 9 | To build the plugin sources, please follow these steps: 10 | 11 | - Clone the code from git. 12 | 13 | - Install and pack the _jfrog-client-js_ dependency locally, by running the following npm commands: 14 | 15 | ```bash 16 | npm i && npm pack 17 | ``` 18 | 19 | If you'd like run the _jfrog-client-js_ integration tests, follow these steps: 20 | 21 | - Make sure your JFrog platform is up and running. 22 | - Set the _CLIENTTESTS_PLATFORM_URL_ environment variable with your JFrog platform URL. 23 | - Set the _CLIENTTESTS_PLATFORM_ACCESS_TOKEN_ OR _CLIENTTESTS_PLATFORM_USERNAME_ and _CLIENTTESTS_PLATFORM_PASSWORD_ environment variables with your JFrog platform credentials. 24 | - Run the following command: 25 | 26 | ```bash 27 | npm t 28 | ``` 29 | 30 | Important: The tests use port 9090 to set up an HTTP proxy server. If this port is already used on the machines which runs the tests, please replace it in the tests code with a different port. 31 | -------------------------------------------------------------------------------- /.github/workflows/frogbot-scan-and-fix.yml: -------------------------------------------------------------------------------- 1 | name: "Frogbot Scan and Fix" 2 | on: 3 | push: 4 | # Creating fix pull requests will be triggered by any push to one of the these branches. 5 | # You can add or replace to any branch you want to open fix pull requests for. 6 | branches: 7 | - "master" 8 | schedule: 9 | - cron: "0 0 * * *" 10 | permissions: 11 | contents: write 12 | pull-requests: write 13 | security-events: write 14 | jobs: 15 | create-fix-pull-requests: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | # Install prerequisites 21 | - name: Setup NodeJS 22 | uses: actions/setup-node@v3 23 | with: 24 | node-version: "16.x" 25 | 26 | - uses: jfrog/frogbot@v2 27 | env: 28 | # [Mandatory] 29 | # JFrog platform URL 30 | JF_URL: ${{ secrets.FROGBOT_URL }} 31 | 32 | # [Mandatory if JF_USER and JF_PASSWORD are not provided] 33 | # JFrog access token with 'read' permissions on Xray service 34 | JF_ACCESS_TOKEN: ${{ secrets.FROGBOT_ACCESS_TOKEN }} 35 | 36 | # [Mandatory] 37 | # The GitHub token automatically generated for the job 38 | JF_GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | -------------------------------------------------------------------------------- /.github/workflows/frogbot-scan-pr.yml: -------------------------------------------------------------------------------- 1 | name: "Frogbot Scan Pull Request" 2 | on: 3 | pull_request_target: 4 | types: [opened, synchronize] 5 | permissions: 6 | pull-requests: write 7 | contents: read 8 | jobs: 9 | scan-pull-request: 10 | runs-on: ubuntu-latest 11 | # A pull request needs to be approved, before Frogbot scans it. Any GitHub user who is associated with the 12 | # "frogbot" GitHub environment can approve the pull request to be scanned. 13 | environment: frogbot 14 | steps: 15 | - uses: actions/checkout@v3 16 | with: 17 | ref: ${{ github.event.pull_request.head.sha }} 18 | 19 | # Install prerequisites 20 | - name: Setup NodeJS 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: "16.x" 24 | 25 | - uses: jfrog/frogbot@v2 26 | env: 27 | # [Mandatory] 28 | # JFrog platform URL 29 | JF_URL: ${{ secrets.FROGBOT_URL }} 30 | 31 | # [Mandatory if JF_USER and JF_PASSWORD are not provided] 32 | # JFrog access token with 'read' permissions on Xray service 33 | JF_ACCESS_TOKEN: ${{ secrets.FROGBOT_ACCESS_TOKEN }} 34 | 35 | # [Mandatory] 36 | # The GitHub token automatically generated for the job 37 | JF_GIT_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | -------------------------------------------------------------------------------- /.github/workflows/cla.yml: -------------------------------------------------------------------------------- 1 | name: "CLA Assistant" 2 | on: 3 | # issue_comment triggers this action on each comment on issues and pull requests 4 | issue_comment: 5 | types: [created] 6 | pull_request_target: 7 | types: [opened,synchronize] 8 | 9 | jobs: 10 | CLAssistant: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions-ecosystem/action-regex-match@v2 14 | id: sign-or-recheck 15 | with: 16 | text: ${{ github.event.comment.body }} 17 | regex: '\s*(I have read the CLA Document and I hereby sign the CLA)|(recheckcla)\s*' 18 | 19 | - name: "CLA Assistant" 20 | if: ${{ steps.sign-or-recheck.outputs.match != '' || github.event_name == 'pull_request_target' }} 21 | # Alpha Release 22 | uses: cla-assistant/github-action@v2.6.0 23 | env: 24 | # Generated and maintained by github 25 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 26 | # JFrog organization secret 27 | PERSONAL_ACCESS_TOKEN : ${{ secrets.CLA_SIGN_TOKEN }} 28 | with: 29 | path-to-signatures: 'signed_clas.json' 30 | path-to-document: 'https://jfrog.com/cla/' 31 | remote-organization-name: 'jfrog' 32 | remote-repository-name: 'jfrog-signed-clas' 33 | # branch should not be protected 34 | branch: 'master' 35 | allowlist: bot* 36 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | # Triggers the workflow on labeled PRs only. 6 | pull_request_target: 7 | types: [labeled] 8 | 9 | jobs: 10 | test: 11 | if: contains(github.event.pull_request.labels.*.name, 'safe to test') || github.event_name == 'push' 12 | runs-on: ${{ matrix.os }} 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | os: [ubuntu-latest, windows-latest, macOS-latest] 17 | env: 18 | NPM_CONFIG_IGNORE_SCRIPTS: true 19 | 20 | steps: 21 | # Prerequisites 22 | - uses: actions/checkout@v3 23 | with: 24 | ref: ${{ github.event.pull_request.head.sha }} 25 | - name: Setup NodeJS 26 | uses: actions/setup-node@v3 27 | with: 28 | node-version: "16" 29 | 30 | # Clean install project 31 | - name: Clean install 32 | run: npm ci 33 | 34 | # Run lint 35 | - name: Lint 36 | run: npm run lint 37 | 38 | # Run tests 39 | - name: Tests 40 | run: npm run pretest && npm t 41 | env: 42 | CLIENTTESTS_PLATFORM_URL: ${{ secrets.PLATFORM_URL }} 43 | CLIENTTESTS_PLATFORM_ACCESS_TOKEN: ${{ secrets.PLATFORM_ADMIN_TOKEN }} 44 | 45 | # Send tests coverage to Codecov 46 | - name: Send code coverage 47 | uses: codecov/codecov-action@v3 48 | if: runner.os == 'Linux' 49 | -------------------------------------------------------------------------------- /src/Xray/XraySystemClient.ts: -------------------------------------------------------------------------------- 1 | import { IClientResponse, IXrayVersion } from '../../model'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { ILogger } from '../../model/'; 4 | 5 | export class XraySystemClient { 6 | private readonly pingEndpoint: string = '/api/v1/system/ping'; 7 | public static readonly versionEndpoint: string = '/api/v1/system/version'; 8 | 9 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 10 | 11 | public async ping(): Promise { 12 | this.logger.debug('Sending ping request...'); 13 | const requestParams: IRequestParams = { 14 | url: this.pingEndpoint, 15 | method: 'GET', 16 | }; 17 | try { 18 | return await ( 19 | await this.httpClient.doRequest(requestParams) 20 | ).data; 21 | } catch (error) { 22 | return false; 23 | } 24 | } 25 | 26 | public async version(): Promise { 27 | this.logger.debug('Sending version request...'); 28 | const requestParams: IRequestParams = { 29 | url: XraySystemClient.versionEndpoint, 30 | method: 'GET', 31 | beforeRedirect: HttpClient.validateServerIsActive, 32 | }; 33 | let response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 34 | return response.data; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Platform/PlatformClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '../HttpClient'; 2 | import { WebLoginClient } from './WebLoginClient'; 3 | import { ILogger } from '../../model/'; 4 | import { PlatformLogger } from './PlatformLogger'; 5 | import { IClientSpecificConfig } from '../../model/ClientSpecificConfig'; 6 | 7 | export class PlatformClient { 8 | private readonly httpClient: HttpClient; 9 | private logger: ILogger; 10 | 11 | constructor(config: IClientSpecificConfig) { 12 | const { 13 | serverUrl, 14 | logger = console, 15 | username, 16 | password, 17 | accessToken, 18 | proxy, 19 | headers, 20 | retries, 21 | timeout, 22 | retryOnStatusCode, 23 | retryDelay, 24 | }: IClientSpecificConfig = config; 25 | this.logger = new PlatformLogger(logger); 26 | 27 | this.httpClient = new HttpClient( 28 | { 29 | serverUrl, 30 | username, 31 | password, 32 | accessToken, 33 | proxy, 34 | headers, 35 | retries, 36 | timeout, 37 | retryOnStatusCode, 38 | retryDelay, 39 | }, 40 | this.logger 41 | ); 42 | } 43 | 44 | public webLogin(): WebLoginClient { 45 | return new WebLoginClient(this.httpClient); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Platform/WebLoginClient.ts: -------------------------------------------------------------------------------- 1 | import { AccessTokenResponse } from '../../model/'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { IAuthRequest } from './AuthRequest'; 4 | 5 | export class WebLoginClient { 6 | private static readonly REGISTER_SESSION_ID_ENDPOINT: string = `/access/api/v2/authentication/jfrog_client_login/request`; 7 | constructor(private readonly httpClient: HttpClient) {} 8 | 9 | /** 10 | * Sends an authentication request to the specified URL with the provided session ID. 11 | * @param sessionId - The session ID. 12 | * @returns A promise that resolves with the client response. 13 | */ 14 | public async registerSessionId(sessionId: string): Promise { 15 | const body: IAuthRequest = { session: sessionId }; 16 | const requestParams: IRequestParams = { 17 | url: WebLoginClient.REGISTER_SESSION_ID_ENDPOINT, 18 | method: 'POST', 19 | data: body, 20 | }; 21 | await this.httpClient.doRequest(requestParams); 22 | } 23 | 24 | /** 25 | * Get an access token using the provided session ID. 26 | * @param sessionId - The session ID. 27 | */ 28 | public async getToken(sessionId: string): Promise { 29 | const request: IRequestParams = { 30 | url: `/access/api/v2/authentication/jfrog_client_login/token/${sessionId}`, 31 | method: 'GET', 32 | }; 33 | return (await this.httpClient.doRequest(request)).data; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayJasConfig.spec.ts: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import nock from 'nock'; 3 | import { JfrogClient } from '../../../src'; 4 | import { TestUtils } from '../../TestUtils'; 5 | 6 | describe('Xray jas config tests', () => { 7 | test('Get jas config', async () => { 8 | const PLATFORM_URL: string = faker.internet.url(); 9 | const uri: string = `/xray/api/v1/configuration/jas`; 10 | const expectedResource: string = '{"enable_token_validation_scanning": true}'; 11 | nock(PLATFORM_URL).get(uri).reply(200, expectedResource); 12 | const client: JfrogClient = new JfrogClient({ platformUrl: PLATFORM_URL, logger: TestUtils.createTestLogger() }); 13 | const res: any = await client.xray().jasconfig().getJasConfig(); 14 | expect(res).toHaveProperty("enable_token_validation_scanning") 15 | expect(res.enable_token_validation_scanning).toEqual(true) 16 | }); 17 | }); 18 | 19 | describe('Xray jas config tests', () => { 20 | test('Fail get jas config', async () => { 21 | const PLATFORM_URL: string = faker.internet.url(); 22 | const uri: string = `/xray/api/v1/configuration/jas`; 23 | nock(PLATFORM_URL).get(uri).reply(402, { message: 'error' }).persist(); 24 | const client: JfrogClient = new JfrogClient({ platformUrl: PLATFORM_URL, logger: TestUtils.createTestLogger() }) 25 | await expect(async () => { 26 | await client 27 | .xray() 28 | .jasconfig() 29 | .getJasConfig(); 30 | }).rejects.toThrow(`Request failed with status code 402`); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayEntitlementsClient.spec.ts: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import nock from 'nock'; 3 | import { JfrogClient } from '../../../src'; 4 | import { TestUtils } from '../../TestUtils'; 5 | 6 | describe('Xray Entitlements tests', () => { 7 | afterEach(() => { 8 | nock.cleanAll(); 9 | }); 10 | 11 | let tests: any[] = [ 12 | { 13 | test: 'pass', 14 | feature: 'feature', 15 | expected: true, 16 | }, 17 | { 18 | test: 'fail', 19 | feature: 'feature', 20 | expected: false, 21 | }, 22 | ]; 23 | 24 | tests.forEach((testCase) => { 25 | it('Feature - ' + testCase.test, async () => { 26 | const platformUrl: string = faker.internet.url(); 27 | nock(platformUrl) 28 | .get(`/xray/api/v1/entitlements/feature/` + testCase.feature) 29 | .reply(200, { feature_id: testCase.feature, entitled: testCase.expected }); 30 | const client: JfrogClient = new JfrogClient({ platformUrl, logger: TestUtils.createTestLogger() }); 31 | const res: any = await client.xray().entitlements().feature(testCase.feature); 32 | expect(res).toBe(testCase.expected); 33 | }); 34 | }); 35 | 36 | test('Feature failure', async () => { 37 | let feature: string = 'feature'; 38 | const platformUrl: string = faker.internet.url(); 39 | const scope: nock.Scope = nock(platformUrl) 40 | .get(`/xray/api/v1/entitlements/feature/` + feature) 41 | .reply(402, { message: 'error' }); 42 | const client: JfrogClient = new JfrogClient({ platformUrl, logger: TestUtils.createTestLogger() }); 43 | const res: any = await client.xray().entitlements().feature(feature); 44 | expect(res).toBeFalsy(); 45 | expect(scope.isDone()).toBeTruthy(); 46 | }); 47 | }); 48 | -------------------------------------------------------------------------------- /test/tests/Xsc/XscClient.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import { XscClient } from '../../../src/Xsc/XscClient'; 3 | import { TestUtils } from '../../TestUtils'; 4 | import { XscSystemClient } from '../../../src/Xsc/XscSystemClient'; 5 | import { XscEventClient } from '../../../src/Xsc/XscEventClient'; 6 | 7 | const SERVER_URL: string = 'http://localhost:8000'; 8 | 9 | beforeAll(() => { 10 | nock.disableNetConnect(); 11 | nock.enableNetConnect(SERVER_URL); 12 | }); 13 | 14 | afterAll(() => { 15 | nock.cleanAll(); 16 | nock.enableNetConnect(); 17 | }); 18 | 19 | describe('Xsc clients tests', () => { 20 | test('Client initialization', () => { 21 | const client: XscClient = new XscClient({ serverUrl: SERVER_URL }); 22 | expect(client).toBeInstanceOf(XscClient); 23 | }); 24 | test('Client w/o url', () => { 25 | expect(() => { 26 | new XscClient({ serverUrl: '' }); 27 | }).toThrow('Xsc client : must provide platformUrl'); 28 | }); 29 | test('System client', () => { 30 | const client: XscClient = new XscClient({ serverUrl: SERVER_URL }); 31 | expect(client.system()).toBeInstanceOf(XscSystemClient); 32 | }); 33 | test('Event client', () => { 34 | const client: XscClient = new XscClient({ serverUrl: SERVER_URL }); 35 | expect(client.event()).toBeInstanceOf(XscEventClient); 36 | }); 37 | }); 38 | 39 | test('Xsc client header tests', async () => { 40 | const client: XscClient = new XscClient({ 41 | serverUrl: SERVER_URL, 42 | headers: { header1: 'value' }, 43 | logger: TestUtils.createTestLogger(), 44 | }); 45 | const serviceId: string = 'jfrog@some.me'; 46 | const scope: nock.Scope = nock(SERVER_URL) 47 | .matchHeader('header1', 'value') 48 | .get('/api/v1/system/version') 49 | .reply(200, serviceId); 50 | await client.system().version(); 51 | expect(scope.isDone()).toBeTruthy(); 52 | }); 53 | -------------------------------------------------------------------------------- /test/TestUtils.ts: -------------------------------------------------------------------------------- 1 | import { IAqlSearchResult, ILogger } from '../model'; 2 | import { IJfrogClientConfig } from '../model/JfrogClientConfig'; 3 | import { JfrogClient } from '../src'; 4 | 5 | export class TestUtils { 6 | public static getJfrogClientConfig(): IJfrogClientConfig { 7 | expect(process.env.CLIENTTESTS_PLATFORM_URL).toBeDefined(); 8 | if ( 9 | (process.env.CLIENTTESTS_PLATFORM_USERNAME === '' || process.env.CLIENTTESTS_PLATFORM_PASSWORD === '') && 10 | process.env.CLIENTTESTS_PLATFORM_ACCESS_TOKEN === '' 11 | ) { 12 | throw new Error( 13 | 'no valid authentication method was set. Config the Basic Auth or the Access Token env vars to run the tests' 14 | ); 15 | } 16 | return { 17 | platformUrl: process.env.CLIENTTESTS_PLATFORM_URL, 18 | username: process.env.CLIENTTESTS_PLATFORM_USERNAME, 19 | password: process.env.CLIENTTESTS_PLATFORM_PASSWORD, 20 | accessToken: process.env.CLIENTTESTS_PLATFORM_ACCESS_TOKEN, 21 | logger: TestUtils.createTestLogger(), 22 | retries: 5, 23 | retryDelay: 5000, 24 | } as IJfrogClientConfig; 25 | } 26 | 27 | public static async searchArtifactoryBuildRepo(jfrogClient: JfrogClient): Promise { 28 | return await jfrogClient 29 | .artifactory() 30 | .search() 31 | .aqlSearch( 32 | 'items.find({' + 33 | '"repo":"artifactory-build-info",' + 34 | '"path":{"$match":"*"}}' + 35 | ').include("name","repo","path","created","size").sort({"$desc":["created"]}).limit(1)' 36 | ); 37 | } 38 | 39 | public static createTestLogger(): ILogger { 40 | return { 41 | error: (...args) => console.error(args), 42 | warn: (...args) => console.warn(args), 43 | debug: () => { 44 | // Empty body 45 | }, 46 | } as ILogger; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Artifactory/ArtifactorySystemClient.ts: -------------------------------------------------------------------------------- 1 | import { IArtifactoryVersion, IUsageData, IUsageFeature } from '../../model'; 2 | import { HttpClient, IRequestParams } from '../HttpClient'; 3 | import { ILogger } from '../../model/'; 4 | 5 | export class ArtifactorySystemClient { 6 | private readonly pingEndpoint: string = '/api/system/ping'; 7 | private readonly versionEndpoint: string = '/api/system/version'; 8 | private readonly usageEndpoint: string = '/api/system/usage'; 9 | 10 | constructor( 11 | private readonly httpClient: HttpClient, 12 | private readonly logger: ILogger, 13 | private readonly clientId?: string 14 | ) {} 15 | 16 | public async ping(): Promise { 17 | this.logger.debug('Sending ping request...'); 18 | const requestParams: IRequestParams = { 19 | url: this.pingEndpoint, 20 | method: 'GET', 21 | }; 22 | try { 23 | return (await this.httpClient.doRequest(requestParams)).data; 24 | } catch (error) { 25 | return false; 26 | } 27 | } 28 | 29 | public async version(): Promise { 30 | this.logger.debug('Sending version request...'); 31 | const requestParams: IRequestParams = { 32 | url: this.versionEndpoint, 33 | method: 'GET', 34 | }; 35 | return (await this.httpClient.doAuthRequest(requestParams)).data; 36 | } 37 | 38 | public async reportUsage(userAgent: string, featureArray: IUsageFeature[]): Promise { 39 | this.logger.debug('Sending usage report...'); 40 | const usageData: IUsageData = { 41 | productId: userAgent, 42 | features: featureArray, 43 | uniqueClientId: this.clientId, 44 | }; 45 | 46 | const requestParams: IRequestParams = { 47 | url: this.usageEndpoint, 48 | method: 'POST', 49 | data: usageData, 50 | }; 51 | return (await this.httpClient.doAuthRequest(requestParams)).data; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Xsc/XscClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '../HttpClient'; 2 | import { ILogger } from '../../model/'; 3 | import { XscLogger } from './XscLogger'; 4 | import { IClientSpecificConfig } from '../../model/ClientSpecificConfig'; 5 | 6 | import { XscEventClient } from './XscEventClient'; 7 | import { XscSystemClient } from './XscSystemClient'; 8 | import { XrayScanClient } from '../Xray/XrayScanClient'; 9 | 10 | export class XscClient { 11 | static readonly xscScanGraphEndpoint: string = 'api/v1/sca/scan/graph'; 12 | 13 | private readonly httpClient: HttpClient; 14 | private logger: ILogger; 15 | 16 | public constructor(config: IClientSpecificConfig) { 17 | const { 18 | serverUrl, 19 | logger = console, 20 | username, 21 | password, 22 | accessToken, 23 | proxy, 24 | headers, 25 | retries, 26 | timeout, 27 | retryOnStatusCode, 28 | retryDelay, 29 | }: IClientSpecificConfig = config; 30 | if (!serverUrl) { 31 | throw new Error('Xsc client : must provide platformUrl'); 32 | } 33 | this.logger = new XscLogger(logger); 34 | this.httpClient = new HttpClient( 35 | { 36 | serverUrl, 37 | username, 38 | password, 39 | accessToken, 40 | proxy, 41 | headers, 42 | retries, 43 | timeout, 44 | retryOnStatusCode, 45 | retryDelay, 46 | }, 47 | this.logger 48 | ); 49 | } 50 | 51 | public scan(): XrayScanClient { 52 | return new XrayScanClient(this.httpClient, XscClient.xscScanGraphEndpoint, this.logger); 53 | } 54 | 55 | public event(): XscEventClient { 56 | return new XscEventClient(this.httpClient, this.logger); 57 | } 58 | 59 | public system(): XscSystemClient { 60 | return new XscSystemClient(this.httpClient, this.logger); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jfrog-client-js", 3 | "version": "2.9.0", 4 | "description": "JFrog Javascript Client is a javascript library, which wraps some of the REST APIs exposed by JFrog Services's different services.", 5 | "license": "Apache-2.0", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/jfrog/jfrog-client-js" 9 | }, 10 | "bugs": { 11 | "url": "https://github.com/jfrog/jfrog-client-js/issues" 12 | }, 13 | "main": "dist/index.js", 14 | "types": "dist/index.d.ts", 15 | "scripts": { 16 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\" \"model/**/*.ts\"", 17 | "build": "tsc --declaration", 18 | "lint": "eslint -c .eslintrc.js --ext .ts src model test", 19 | "prepare": "npm run build", 20 | "preversion": "npm run lint", 21 | "watch": "tsc -watch -p ./", 22 | "compile": "tsc -p ./", 23 | "pretest": "npm run compile", 24 | "test": "jest --verbose --runInBand" 25 | }, 26 | "files": [ 27 | "dist/**/*" 28 | ], 29 | "dependencies": { 30 | "axios": "~0.27.2", 31 | "axios-retry": "~3.2.5", 32 | "https-proxy-agent": "^5.0.1" 33 | }, 34 | "devDependencies": { 35 | "@types/faker": "^5.5.3", 36 | "@types/http-proxy": "^1.17.9", 37 | "@types/jest": "^27.5.1", 38 | "@types/tmp": "^0.2.3", 39 | "@typescript-eslint/eslint-plugin": "^5.27.0", 40 | "@typescript-eslint/parser": "^5.27.0", 41 | "eslint": "^8.16.0", 42 | "eslint-config-prettier": "^8.5.0", 43 | "faker": "5.5.3", 44 | "http-proxy": "^1.18.1", 45 | "jest": "^29.3.1", 46 | "nock": "^13.2.4", 47 | "prettier": "^2.6.2", 48 | "tmp": "^0.2.1", 49 | "ts-jest": "^29.0.3", 50 | "typescript": "^4.7.2" 51 | }, 52 | "keywords": [ 53 | "artifactory", 54 | "javascript", 55 | "typescript", 56 | "security", 57 | "nodejs", 58 | "devops", 59 | "jfrog", 60 | "xray", 61 | "scan", 62 | "js", 63 | "ts" 64 | ] 65 | } 66 | -------------------------------------------------------------------------------- /src/Artifactory/ArtifactoryClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '../HttpClient'; 2 | import { ArtifactoryLogger } from './ArtifactoryLogger'; 3 | import { ArtifactorySystemClient } from './ArtifactorySystemClient'; 4 | import { ArtifactorySearchClient } from './ArtifactorySearchClient'; 5 | import { ArtifactoryDownloadClient } from './ArtifactoryDownloadClient'; 6 | import { IClientSpecificConfig } from '../../model/ClientSpecificConfig'; 7 | import { ILogger } from '../../model/'; 8 | 9 | export class ArtifactoryClient { 10 | private readonly httpClient: HttpClient; 11 | private logger: ILogger; 12 | 13 | public constructor(config: IClientSpecificConfig, private readonly clientId?: string) { 14 | const { 15 | serverUrl, 16 | logger = console, 17 | username, 18 | password, 19 | accessToken, 20 | proxy, 21 | headers, 22 | retries, 23 | timeout, 24 | retryOnStatusCode, 25 | retryDelay, 26 | }: IClientSpecificConfig = config; 27 | if (!serverUrl) { 28 | throw new Error('Artifactory client : must provide platformUrl or artifactoryUrl'); 29 | } 30 | this.logger = new ArtifactoryLogger(logger); 31 | this.httpClient = new HttpClient( 32 | { 33 | serverUrl, 34 | username, 35 | password, 36 | accessToken, 37 | proxy, 38 | headers, 39 | retries, 40 | timeout, 41 | retryOnStatusCode, 42 | retryDelay, 43 | }, 44 | this.logger 45 | ); 46 | } 47 | 48 | public system(): ArtifactorySystemClient { 49 | return new ArtifactorySystemClient(this.httpClient, this.logger, this.clientId); 50 | } 51 | 52 | public search(): ArtifactorySearchClient { 53 | return new ArtifactorySearchClient(this.httpClient, this.logger); 54 | } 55 | 56 | public download(): ArtifactoryDownloadClient { 57 | return new ArtifactoryDownloadClient(this.httpClient, this.logger); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayClient.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import { XrayDetailsClient, XraySummaryClient, XraySystemClient } from '../../../src'; 3 | import { XrayClient } from '../../../src/Xray/XrayClient'; 4 | import { XrayEntitlementsClient } from '../../../src/Xray/XrayEntitlementsClient'; 5 | import { TestUtils } from '../../TestUtils'; 6 | 7 | const SERVER_URL: string = 'http://localhost:8000'; 8 | 9 | beforeAll(() => { 10 | nock.disableNetConnect(); 11 | nock.enableNetConnect(SERVER_URL); 12 | }); 13 | 14 | afterAll(() => { 15 | nock.cleanAll(); 16 | nock.enableNetConnect(); 17 | }); 18 | 19 | describe('Xray clients tests', () => { 20 | test('Client initialization', () => { 21 | const client: XrayClient = new XrayClient({ serverUrl: SERVER_URL }); 22 | expect(client).toBeInstanceOf(XrayClient); 23 | }); 24 | test('Client w/o url', () => { 25 | expect(() => { 26 | new XrayClient({ serverUrl: '' }); 27 | }).toThrow('Xray client : must provide platformUrl or xrayUrl'); 28 | }); 29 | test('System client', () => { 30 | const client: XrayClient = new XrayClient({ serverUrl: SERVER_URL }); 31 | expect(client.system()).toBeInstanceOf(XraySystemClient); 32 | }); 33 | test('Summary client', () => { 34 | const client: XrayClient = new XrayClient({ serverUrl: SERVER_URL }); 35 | expect(client.summary()).toBeInstanceOf(XraySummaryClient); 36 | }); 37 | test('Details client', () => { 38 | const client: XrayClient = new XrayClient({ serverUrl: SERVER_URL }); 39 | expect(client.details()).toBeInstanceOf(XrayDetailsClient); 40 | }); 41 | test('Entitlements client', () => { 42 | const client: XrayClient = new XrayClient({ serverUrl: SERVER_URL }); 43 | expect(client.entitlements()).toBeInstanceOf(XrayEntitlementsClient); 44 | }); 45 | }); 46 | 47 | test('Xray client header tests', async () => { 48 | const client: XrayClient = new XrayClient({ 49 | serverUrl: SERVER_URL, 50 | headers: { header1: 'value' }, 51 | logger: TestUtils.createTestLogger(), 52 | }); 53 | const serviceId: string = 'jfrog@some.me'; 54 | const scope: nock.Scope = nock(SERVER_URL) 55 | .matchHeader('header1', 'value') 56 | .get('/api/v1/system/ping') 57 | .reply(200, serviceId); 58 | await client.system().ping(); 59 | expect(scope.isDone()).toBeTruthy(); 60 | }); 61 | -------------------------------------------------------------------------------- /test/tests/Platform/WebLoginClient.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import { AccessTokenResponse } from '../../../model'; 3 | import { HttpClient } from '../../../src/HttpClient'; 4 | import { WebLoginClient } from '../../../src/Platform/WebLoginClient'; 5 | 6 | describe('WebLoginClient', () => { 7 | const mockSessionId: string = 'mockSessionId'; 8 | const SERVER_URL: string = 'http://localhost:8000'; 9 | const mockAccessTokenResponse: AccessTokenResponse = { 10 | access_token: 'mockAccessToken', 11 | expires_in: 3600, 12 | refresh_token: 'refresh_token', 13 | scope: 'scope', 14 | token_id: 'token_id', 15 | token_type: 'Bearer', 16 | }; 17 | 18 | beforeEach(() => { 19 | nock.disableNetConnect(); 20 | }); 21 | 22 | afterEach(() => { 23 | nock.cleanAll(); 24 | nock.enableNetConnect(); 25 | }); 26 | 27 | it('Register session id', async () => { 28 | const httpClient: HttpClient = new HttpClient({ serverUrl: SERVER_URL }); 29 | const webLoginClient: WebLoginClient = new WebLoginClient(httpClient); 30 | 31 | nock(SERVER_URL).post('/access/api/v2/authentication/jfrog_client_login/request').reply(200); 32 | 33 | await webLoginClient.registerSessionId(mockSessionId); 34 | }); 35 | 36 | it('Register session id with error', async () => { 37 | const httpClient: HttpClient = new HttpClient({ serverUrl: SERVER_URL }); 38 | const webLoginClient: WebLoginClient = new WebLoginClient(httpClient); 39 | const sessionId: string = 'mockInvalidSessionId'; 40 | 41 | nock(SERVER_URL).post('/access/api/v2/authentication/jfrog_client_login/request').reply(400); 42 | 43 | await expect(webLoginClient.registerSessionId(sessionId)).rejects.toThrowError( 44 | 'Request failed with status code 400' 45 | ); 46 | }); 47 | 48 | it('Wait for token', async () => { 49 | const httpClient: HttpClient = new HttpClient({ serverUrl: SERVER_URL }); 50 | const webLoginClient: WebLoginClient = new WebLoginClient(httpClient); 51 | 52 | nock(SERVER_URL) 53 | .get(`/access/api/v2/authentication/jfrog_client_login/token/${mockSessionId}`) 54 | .reply(200, mockAccessTokenResponse); 55 | 56 | const accessToken: AccessTokenResponse = await webLoginClient.getToken(mockSessionId); 57 | 58 | expect(accessToken).toEqual(mockAccessTokenResponse); 59 | }); 60 | }); 61 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayDetailsClient.spec.ts: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import * as fs from 'fs'; 3 | import nock from 'nock'; 4 | import * as path from 'path'; 5 | import { IDetailsResponse } from '../../../model'; 6 | import { JfrogClient } from '../../../src'; 7 | import { TestUtils } from '../../TestUtils'; 8 | 9 | let jfrogClient: JfrogClient; 10 | const DETAILS_RESOURCE: string = './test/resources/xrayDetails/details.json'; 11 | 12 | beforeAll(() => { 13 | jfrogClient = new JfrogClient(TestUtils.getJfrogClientConfig()); 14 | }); 15 | 16 | describe('Xray details tests', () => { 17 | test('Build details', async () => { 18 | const PLATFORM_URL: string = faker.internet.url(); 19 | const buildName: string = 'build-example'; 20 | const buildNumber: string = '20201116.1'; 21 | const uri: string = `/xray/api/v1/details/build?build_name=${encodeURIComponent( 22 | buildName 23 | )}&build_number=${encodeURIComponent(buildNumber)}`; 24 | 25 | const expectedResource: string = fs.readFileSync(path.resolve(DETAILS_RESOURCE)).toString(); 26 | const scope: nock.Scope = nock(PLATFORM_URL).get(uri).reply(202, expectedResource); 27 | const client: JfrogClient = new JfrogClient({ 28 | platformUrl: PLATFORM_URL, 29 | logger: TestUtils.createTestLogger(), 30 | }); 31 | const res: IDetailsResponse = await client.xray().details().build(buildName, buildNumber); 32 | expect(res).toEqual(JSON.parse(expectedResource)); 33 | expect(scope.isDone()).toBeTruthy(); 34 | }); 35 | 36 | test('Build details for non existing build', async () => { 37 | const buildName: string = 'buildDoesNotExist'; 38 | const buildNumber: string = '123'; 39 | const projectKey: string = 'projectDoesNotExist'; 40 | const response: IDetailsResponse = await jfrogClient.xray().details().build(buildName, buildNumber, projectKey); 41 | expect(response).toBeTruthy(); 42 | 43 | // Check general build details. 44 | expect(response.build_name).toBe(buildName); 45 | expect(response.build_number).toBe(buildNumber); 46 | expect(response.project_key).toBe(projectKey); 47 | expect(response.is_scan_completed).toBe(false); 48 | expect(response.components).toBeFalsy(); 49 | 50 | // Check error. 51 | expect(response.error_details).toBeTruthy(); 52 | expect(response.error_details.error_code).toBeTruthy(); 53 | expect(response.error_details.error_message).toBeTruthy(); 54 | }); 55 | }); 56 | -------------------------------------------------------------------------------- /release/pipelines.release.yml: -------------------------------------------------------------------------------- 1 | pipelines: 2 | - name: release_jfrog_client_js 3 | configuration: 4 | runtime: 5 | type: image 6 | image: 7 | auto: 8 | language: node 9 | versions: 10 | - "16" 11 | environmentVariables: 12 | readOnly: 13 | NEXT_VERSION: 0.0.0 14 | 15 | steps: 16 | - name: Release 17 | type: Bash 18 | configuration: 19 | inputResources: 20 | - name: jfrogClientJsReleaseGit 21 | integrations: 22 | - name: il_automation 23 | - name: ecosys_entplus_deployer 24 | - name: npm 25 | execution: 26 | onExecute: 27 | - cd $res_jfrogClientJsReleaseGit_resourcePath 28 | 29 | # Set env 30 | - export CI=true 31 | - export JFROG_BUILD_STATUS=PASS 32 | - export JFROG_CLI_BUILD_NAME=ecosystem-jfrog-client-js-release 33 | - export JFROG_CLI_BUILD_NUMBER=$run_number 34 | - export JFROG_CLI_BUILD_PROJECT=ecosys 35 | 36 | # Configure git 37 | - git checkout master 38 | - git remote set-url origin https://$int_il_automation_token@github.com/jfrog/jfrog-client-js.git 39 | 40 | # Make sure version provided 41 | - echo "Checking variables" 42 | - test -n "$NEXT_VERSION" -a "$NEXT_VERSION" != "0.0.0" 43 | 44 | # Configure JFrog CLI 45 | - curl -fL https://install-cli.jfrog.io | sh 46 | - jf c rm --quiet 47 | - jf c add internal --url=$int_ecosys_entplus_deployer_url --user=$int_ecosys_entplus_deployer_user --password=$int_ecosys_entplus_deployer_apikey 48 | - jf npmc --repo-resolve ecosys-npm-remote --repo-deploy ecosys-npm-local 49 | 50 | # Install and audit 51 | - jf npm ci --ignore-scripts 52 | - jf audit 53 | 54 | # Publish 55 | - npm config set tag-version-prefix '' 56 | - npm version $NEXT_VERSION --allow-same-version 57 | - jf npm p 58 | - jf rt bag && jf rt bce 59 | - jf rt bp 60 | 61 | # Publish to npmjs 62 | - echo "//registry.npmjs.org/:_authToken=$int_npm_token" > .npmrc 63 | - npm publish --access public 64 | 65 | # Update version 66 | - git push 67 | - git push --tags 68 | onComplete: 69 | # Clean up 70 | - rm -f .npmrc 71 | - jf c rm --quiet 72 | -------------------------------------------------------------------------------- /test/tests/Artifactory/ArtifactoryClient.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import { ArtifactoryDownloadClient, ArtifactorySearchClient, ArtifactorySystemClient } from '../../../src'; 3 | import { ArtifactoryClient } from '../../../src/Artifactory/ArtifactoryClient'; 4 | import { TestUtils } from '../../TestUtils'; 5 | 6 | const SERVER_URL: string = 'http://localhost:8000'; 7 | 8 | describe('Artifactory clients tests', () => { 9 | beforeAll(() => { 10 | nock.enableNetConnect(SERVER_URL); 11 | }); 12 | 13 | afterAll(() => { 14 | nock.cleanAll(); 15 | nock.enableNetConnect(); 16 | }); 17 | 18 | test('Client initialization', () => { 19 | const client: ArtifactoryClient = new ArtifactoryClient({ 20 | serverUrl: SERVER_URL, 21 | logger: TestUtils.createTestLogger(), 22 | }); 23 | expect(client).toBeInstanceOf(ArtifactoryClient); 24 | }); 25 | test('Client w/o url', () => { 26 | expect(() => { 27 | new ArtifactoryClient({ serverUrl: '', logger: TestUtils.createTestLogger() }); 28 | }).toThrow('Artifactory client : must provide platformUrl or artifactoryUrl'); 29 | }); 30 | test('System client', () => { 31 | const client: ArtifactoryClient = new ArtifactoryClient({ 32 | serverUrl: SERVER_URL, 33 | logger: TestUtils.createTestLogger(), 34 | }); 35 | expect(client.system()).toBeInstanceOf(ArtifactorySystemClient); 36 | }); 37 | test('Search client', () => { 38 | const client: ArtifactoryClient = new ArtifactoryClient({ 39 | serverUrl: SERVER_URL, 40 | logger: TestUtils.createTestLogger(), 41 | }); 42 | expect(client.search()).toBeInstanceOf(ArtifactorySearchClient); 43 | }); 44 | test('Download client', () => { 45 | const client: ArtifactoryClient = new ArtifactoryClient({ 46 | serverUrl: SERVER_URL, 47 | logger: TestUtils.createTestLogger(), 48 | }); 49 | expect(client.download()).toBeInstanceOf(ArtifactoryDownloadClient); 50 | }); 51 | }); 52 | 53 | test('Artifactory client header tests', async () => { 54 | const client: ArtifactoryClient = new ArtifactoryClient({ 55 | serverUrl: SERVER_URL, 56 | headers: { header1: 'value' }, 57 | logger: TestUtils.createTestLogger(), 58 | }); 59 | const serviceId: string = 'jfrog@some.me'; 60 | const scope: nock.Scope = nock(SERVER_URL) 61 | .matchHeader('header1', 'value') 62 | .get('/api/system/ping') 63 | .reply(200, serviceId); 64 | await client.system().ping(); 65 | expect(scope.isDone()).toBeTruthy(); 66 | }); 67 | -------------------------------------------------------------------------------- /src/Xray/XrayClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '../HttpClient'; 2 | import { XraySystemClient } from './XraySystemClient'; 3 | import { XrayLogger } from './XrayLogger'; 4 | import { XraySummaryClient } from './XraySummaryClient'; 5 | import { XrayDetailsClient } from './XrayDetailsClient'; 6 | import { IClientSpecificConfig } from '../../model/ClientSpecificConfig'; 7 | import { ILogger } from '../../model/'; 8 | import { XrayGraphClient as XrayScanClient } from '..'; 9 | import { XrayEntitlementsClient } from './XrayEntitlementsClient'; 10 | import { XrayJasConfigClient } from './XrayJasConfigClient'; 11 | 12 | export class XrayClient { 13 | static readonly scanGraphEndpoint: string = 'api/v1/scan/graph'; 14 | 15 | private readonly httpClient: HttpClient; 16 | private logger: ILogger; 17 | 18 | public constructor(config: IClientSpecificConfig) { 19 | const { 20 | serverUrl, 21 | logger = console, 22 | username, 23 | password, 24 | accessToken, 25 | proxy, 26 | headers, 27 | retries, 28 | timeout, 29 | retryOnStatusCode, 30 | retryDelay, 31 | }: IClientSpecificConfig = config; 32 | if (!serverUrl) { 33 | throw new Error('Xray client : must provide platformUrl or xrayUrl'); 34 | } 35 | this.logger = new XrayLogger(logger); 36 | this.httpClient = new HttpClient( 37 | { 38 | serverUrl, 39 | username, 40 | password, 41 | accessToken, 42 | proxy, 43 | headers, 44 | retries, 45 | timeout, 46 | retryOnStatusCode, 47 | retryDelay, 48 | }, 49 | this.logger 50 | ); 51 | } 52 | 53 | public summary(): XraySummaryClient { 54 | return new XraySummaryClient(this.httpClient, this.logger); 55 | } 56 | 57 | public system(): XraySystemClient { 58 | return new XraySystemClient(this.httpClient, this.logger); 59 | } 60 | 61 | public details(): XrayDetailsClient { 62 | return new XrayDetailsClient(this.httpClient, this.logger); 63 | } 64 | 65 | public scan(): XrayScanClient { 66 | return new XrayScanClient(this.httpClient, XrayClient.scanGraphEndpoint, this.logger); 67 | } 68 | 69 | public entitlements(): XrayEntitlementsClient { 70 | return new XrayEntitlementsClient(this.httpClient, this.logger); 71 | } 72 | 73 | public jasconfig(): XrayJasConfigClient { 74 | return new XrayJasConfigClient(this.httpClient, this.logger); 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/Artifactory/ArtifactoryDownloadClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient, IRequestParams } from '../HttpClient'; 2 | import { IChecksumResult, ILogger } from '../../model/'; 3 | import { IClientResponse } from '../ClientResponse'; 4 | import * as fs from 'fs'; 5 | 6 | export class ArtifactoryDownloadClient { 7 | private static readonly MD5_HEADER: string = 'x-checksum-md5'; 8 | private static readonly SHA1_HEADER: string = 'x-checksum-sha1'; 9 | private static readonly SHA256_HEADER: string = 'x-checksum-sha256'; 10 | 11 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 12 | 13 | public async downloadArtifact(artifactPath: string): Promise { 14 | this.logger.debug('Sending download artifact request...'); 15 | const requestParams: IRequestParams = { 16 | url: encodeURI(artifactPath), 17 | method: 'GET', 18 | headers: { Connection: 'Keep-Alive' }, 19 | }; 20 | return (await this.httpClient.doAuthRequest(requestParams)).data; 21 | } 22 | 23 | public async downloadArtifactToFile(from: string, to: string): Promise { 24 | this.logger.debug('Sending download artifact request...'); 25 | const requestParams: IRequestParams = { 26 | url: encodeURI(from), 27 | method: 'GET', 28 | responseType: 'stream', 29 | }; 30 | 31 | let response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 32 | return new Promise((resolve, reject) => { 33 | const writer: fs.WriteStream = fs.createWriteStream(to, { flags: 'w' }); 34 | response.data.pipe(writer); 35 | writer.on('finish', () => { 36 | this.logger.debug('download from ' + from + ' to ' + to + ' was successful'); 37 | resolve(); 38 | }); 39 | writer.on('error', (err) => { 40 | this.logger.debug('download from ' + from + ' to ' + to + ' was unsuccessful, Error:' + err); 41 | writer.close(); 42 | reject(err); 43 | }); 44 | }); 45 | } 46 | 47 | public async getArtifactChecksum(artifactPath: string): Promise { 48 | this.logger.debug('Sending head request to ' + artifactPath + '...'); 49 | const requestParams: IRequestParams = { 50 | url: encodeURI(artifactPath), 51 | method: 'HEAD', 52 | }; 53 | const response: IClientResponse = await this.httpClient.doAuthRequest(requestParams); 54 | if (!response.headers) { 55 | throw new Error('JFrog client: Head request does not contain headers'); 56 | } 57 | return { 58 | md5: response.headers[ArtifactoryDownloadClient.MD5_HEADER], 59 | sha1: response.headers[ArtifactoryDownloadClient.SHA1_HEADER], 60 | sha256: response.headers[ArtifactoryDownloadClient.SHA256_HEADER], 61 | } as IChecksumResult; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /test/tests/Xsc/XscEventClient.spec.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock'; 2 | import * as os from 'os'; 3 | import { JfrogClient } from '../../../src/JfrogClient'; 4 | import { TestUtils } from '../../TestUtils'; 5 | import { 6 | IJfrogClientConfig, 7 | ScanEvent, 8 | ScanEventStatus, 9 | ScanEventType, 10 | StartScanRequest, 11 | ScanEventResponse, 12 | XscLog, 13 | } from '../../../model'; 14 | 15 | describe.only('Xsc Events tests', () => { 16 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 17 | const jfrogClient: JfrogClient = new JfrogClient(clientConfig); 18 | 19 | afterAll(() => { 20 | nock.cleanAll(); 21 | }); 22 | 23 | test('Log event', async () => { 24 | if (await shouldSkipTest()) { 25 | return; 26 | } 27 | const event: XscLog = { 28 | log_level: 'debug', 29 | source: 'test - client js', 30 | message: 'test message', 31 | }; 32 | const res: any = await jfrogClient.xsc().event().log(event); 33 | expect(res).toBeTruthy(); 34 | }); 35 | 36 | test('Scan event', async () => { 37 | if (await shouldSkipTest()) { 38 | return; 39 | } 40 | let testEvent: StartScanRequest = { 41 | product: 'jfrog-client-js tests', 42 | os_platform: os.platform(), 43 | os_architecture: os.arch(), 44 | event_type: ScanEventType.SourceCode, 45 | event_status: ScanEventStatus.Started, 46 | }; 47 | // Start scan 48 | const res: ScanEvent = await jfrogClient 49 | .xsc() 50 | .event() 51 | .startScan({ product: 'jfrog-client-js tests', os_platform: os.platform(), os_architecture: os.arch() }); 52 | expect(res).toBeTruthy(); 53 | expect(isValidUUID(res.multi_scan_id)).toBeTruthy(); 54 | 55 | // Get scan information 56 | let response: ScanEventResponse = await jfrogClient.xsc().event().getScanEvent(res.multi_scan_id); 57 | expect(response).toBeTruthy(); 58 | expect(response).toStrictEqual(testEvent); 59 | 60 | // End scan 61 | res.event_status = ScanEventStatus.Completed; 62 | expect(await jfrogClient.xsc().event().endScan(res)).toBeTruthy(); 63 | 64 | response = await jfrogClient.xsc().event().getScanEvent(res.multi_scan_id); 65 | expect(response).toBeTruthy(); 66 | expect(response).toStrictEqual({ ...testEvent, event_status: ScanEventStatus.Completed }); 67 | }); 68 | 69 | async function shouldSkipTest(): Promise { 70 | if (!(await jfrogClient.xsc().system().enabled())) { 71 | clientConfig.logger?.warn('Xsc is not enabled in the configuration platformUrl, skipping tests...'); 72 | return true; 73 | } 74 | return false; 75 | } 76 | 77 | function isValidUUID(str: string): boolean { 78 | const uuidRegex: RegExp = new RegExp(`^[0-9a-f]{8}-[0-9a-f]{4}-1[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$`); 79 | return uuidRegex.test(str); 80 | } 81 | }); 82 | -------------------------------------------------------------------------------- /test/resources/xrayDetails/details.json: -------------------------------------------------------------------------------- 1 | { 2 | "build_name": "build-example", 3 | "build_number": "20201116.1", 4 | "is_scan_completed": true, 5 | "components": [{ 6 | "general": { 7 | "name": "spring-core-2.5.6.jar", 8 | "component_id": "org.springframework:spring-core:1.0-rc1", 9 | "pkg_type": "maven", 10 | "sha256": "cf37656069488043c47f49a5520bb06d6879b63ef6044abb200c51a7ff2d6c49", 11 | "sha1": "c450bc49099430e13d21548d1e3d1a564b7e35e9", 12 | "parent_sha256": [ 13 | "091268f6acffaf8db36ad66610f2e7fda1a0b683daf65c239a6b000d35f590ba" 14 | ] 15 | }, 16 | "issues": [ 17 | { 18 | "issue_id": "XRAY-69351", 19 | "summary": "Spring Framework, versions 5.0 prior to 5.0.5 and versions 4.3 prior to 4.3.15 and older unsupported versions, provide client-side support for multipart requests. When Spring MVC or Spring WebFlux server application (server A) receives input from a remote client, and then uses that input to make a multipart request to another server (server B), it can be exposed to an attack, where an extra multipart is inserted in the content of the request from server A, causing server B to use the wrong value for a part it expects. This could to lead privilege escalation, for example, if the part content represents a username or user roles.", 20 | "description": "Spring Framework, versions 5.0 prior to 5.0.5 and versions 4.3 prior to 4.3.15 and older unsupported versions, provide client-side support for multipart requests. When Spring MVC or Spring WebFlux server application (server A) receives input from a remote client, and then uses that input to make a multipart request to another server (server B), it can be exposed to an attack, where an extra multipart is inserted in the content of the request from server A, causing server B to use the wrong value for a part it expects. This could to lead privilege escalation, for example, if the part content represents a username or user roles.", 21 | "issue_type": "security", 22 | "severity": "High", 23 | "provider": "JFrog", 24 | "cves": [ 25 | { 26 | "cve": "CVE-2018-1272", 27 | "cvss_v2": "6.0/CVSS:2.0/AV:N/AC:M/Au:S/C:P/I:P/A:P" 28 | } 29 | ], 30 | "created": "2018-07-12T00:00:00.700Z", 31 | "components": [ 32 | { 33 | "component_id": "org.springframework:spring-core", 34 | "fixed_versions": [ 35 | "[4.3.15.RELEASE]", 36 | "[5.0.5.RELEASE]" 37 | ] 38 | } 39 | ] 40 | } 41 | ], 42 | "licenses": [ 43 | { 44 | "name": "Apache-2.0", 45 | "full_name": "The Apache Software License, Version 2.0", 46 | "more_info_url": [ 47 | "http://raw.githubusercontent.com/aspnet/AspNetCore/2.0.0/LICENSE.txt", 48 | "https://raw.githubusercontent.com/aspnet/AspNetCore/2.0.0/LICENSE.txt", 49 | "http://licenses.nuget.org/Apache-2.0", 50 | "https://licenses.nuget.org/Apache-2.0", 51 | "http://www.apache.org/licenses/LICENSE-2.0", 52 | "https://spdx.org/licenses/Apache-2.0.html", 53 | "https://spdx.org/licenses/Apache-2.0", 54 | "http://www.opensource.org/licenses/apache2.0.php", 55 | "http://www.opensource.org/licenses/Apache-2.0" 56 | ], 57 | "components": [ 58 | "gav://org.springframework:spring-core:1.0-rc1" 59 | ] 60 | } 61 | ] 62 | }] 63 | } -------------------------------------------------------------------------------- /test/tests/HttpClient.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import { HttpsProxyAgent } from 'https-proxy-agent'; 3 | import nock from 'nock'; 4 | import { IClientResponse, IProxyConfig } from '../../model'; 5 | import { HttpClient, IRequestParams } from '../../src/HttpClient'; 6 | 7 | const subPath: string = '/subpath'; 8 | const serverUrl: string = faker.internet.url(); 9 | const username: string = faker.internet.userName(); 10 | const password: string = faker.internet.password(); 11 | 12 | beforeAll(() => { 13 | nock.disableNetConnect(); 14 | nock.enableNetConnect(serverUrl); 15 | }); 16 | 17 | afterAll(() => { 18 | nock.cleanAll(); 19 | nock.enableNetConnect(); 20 | }); 21 | 22 | describe('Http client tests', () => { 23 | test('Constructing client', () => { 24 | const client: HttpClient = new HttpClient({ serverUrl }); 25 | expect(client).toBeInstanceOf(HttpClient); 26 | }); 27 | 28 | [ 29 | { 30 | name: 'Http config', 31 | config: { host: 'host', port: 1, protocol: 'http' } as IProxyConfig, 32 | shouldExists: true, 33 | }, 34 | { 35 | name: 'Https config', 36 | config: { host: 'host', port: 1, protocol: 'https' } as IProxyConfig, 37 | shouldExists: false, 38 | }, 39 | { 40 | name: 'With empty config', 41 | config: {} as IProxyConfig, 42 | shouldExists: false, 43 | }, 44 | { 45 | name: 'With undefined', 46 | config: undefined, 47 | shouldExists: false, 48 | }, 49 | { 50 | name: 'With false', 51 | config: false, 52 | shouldExists: false, 53 | }, 54 | ].forEach((testCase) => { 55 | test('Constructing HttpToHttpsProxyConfig - ' + testCase.name, () => { 56 | let res: HttpsProxyAgent | undefined = HttpClient.getHttpToHttpsProxyConfig( 57 | testCase.config 58 | ); 59 | if (testCase.shouldExists) { 60 | expect(res).toBeDefined(); 61 | expect(res?.protocol).toBe('http:'); 62 | } else { 63 | expect(res).toBeUndefined(); 64 | } 65 | }); 66 | }); 67 | 68 | test('Do request', async () => { 69 | nock(serverUrl).post(subPath).matchHeader('User-Agent', 'http-client-test').reply(200, 'RESPONSE'); 70 | const client: HttpClient = new HttpClient({ serverUrl, headers: { 'User-Agent': 'http-client-test' } }); 71 | const requestParams: IRequestParams = { 72 | method: 'POST', 73 | url: subPath, 74 | } as IRequestParams; 75 | const res: IClientResponse = await client.doRequest(requestParams); 76 | expect(res.data).toBe('RESPONSE'); 77 | expect(res.status).toBe(200); 78 | }); 79 | 80 | test('Do auth request', async () => { 81 | nock(serverUrl) 82 | .post(subPath) 83 | .basicAuth({ user: username, pass: password }) 84 | .matchHeader('User-Agent', 'jfrog-client-js') 85 | .reply(200, 'RESPONSE'); 86 | const client: HttpClient = new HttpClient({ serverUrl, username, password }); 87 | const requestParams: IRequestParams = { 88 | method: 'POST', 89 | url: subPath, 90 | } as IRequestParams; 91 | const res: IClientResponse = await client.doAuthRequest(requestParams); 92 | expect(res.data).toBe('RESPONSE'); 93 | expect(res.status).toBe(200); 94 | }); 95 | }); 96 | -------------------------------------------------------------------------------- /src/JfrogClient.ts: -------------------------------------------------------------------------------- 1 | import { IJfrogClientConfig } from '../model/JfrogClientConfig'; 2 | import { XrayClient } from './Xray/XrayClient'; 3 | import { ArtifactoryClient } from './Artifactory/ArtifactoryClient'; 4 | import { XscClient } from './Xsc/XscClient'; 5 | import { IClientSpecificConfig } from '../model/ClientSpecificConfig'; 6 | 7 | import * as os from 'os'; 8 | import crypto from 'crypto'; // Important - Don't import '*'. It'll import deprecated encryption methods 9 | import { PlatformClient } from './Platform/PlatformClient'; 10 | import { ClientUtils } from './ClientUtils'; 11 | 12 | export class JfrogClient { 13 | private static readonly ARTIFACTORY_SUFFIX: string = 'artifactory'; 14 | private static readonly XRAY_SUFFIX: string = 'xray'; 15 | private static readonly XSC_SUFFIX: string = 'xsc'; 16 | 17 | public readonly clientId?: string; 18 | 19 | public constructor(private _jfrogConfig: IJfrogClientConfig) { 20 | if (!_jfrogConfig.platformUrl && !_jfrogConfig.xrayUrl && !_jfrogConfig.artifactoryUrl) { 21 | throw new Error('JFrog client: must provide platform or specific URLs'); 22 | } 23 | this.clientId = JfrogClient.getClientId(Object.values(os.networkInterfaces())); 24 | } 25 | 26 | public artifactory(): ArtifactoryClient { 27 | return new ArtifactoryClient( 28 | this.getSpecificClientConfig(JfrogClient.ARTIFACTORY_SUFFIX, this._jfrogConfig.artifactoryUrl), 29 | this.clientId 30 | ); 31 | } 32 | 33 | public xray(): XrayClient { 34 | return new XrayClient(this.getSpecificClientConfig(JfrogClient.XRAY_SUFFIX, this._jfrogConfig.xrayUrl)); 35 | } 36 | 37 | public platform(): PlatformClient { 38 | if (!this._jfrogConfig.platformUrl) { 39 | throw new Error('JFrog client: must provide platform URLs'); 40 | } 41 | return new PlatformClient({ serverUrl: this._jfrogConfig.platformUrl, ...this._jfrogConfig }); 42 | } 43 | 44 | public xsc(): XscClient { 45 | return new XscClient(this.getSpecificClientConfig(JfrogClient.XSC_SUFFIX)); 46 | } 47 | 48 | /** 49 | * Creates a server specific config from the provided JFrog config. 50 | * @param serverSuffix - server specific suffix. 51 | * @param providedCustomUrl - custom server URL, if provided. 52 | * @private 53 | */ 54 | private getSpecificClientConfig(serverSuffix: string, providedCustomUrl?: string): IClientSpecificConfig { 55 | return { serverUrl: this.getServerUrl(serverSuffix, providedCustomUrl), ...this._jfrogConfig }; 56 | } 57 | 58 | getServerUrl(serverSuffix: string, providedCustomUrl: string | undefined): string { 59 | let url: string = providedCustomUrl || ''; 60 | if (!url) { 61 | if (!this._jfrogConfig.platformUrl) { 62 | throw new Error(serverSuffix + ' client: must provide platform or specific URLs'); 63 | } 64 | url = ClientUtils.addTrailingSlashIfMissing(this._jfrogConfig.platformUrl) + serverSuffix + '/'; 65 | } 66 | return url; 67 | } 68 | 69 | public static getClientId(interfaces: (os.NetworkInterfaceBase[] | undefined)[]): string | undefined { 70 | for (const networkInterfaces of interfaces) { 71 | for (const networkInterface of networkInterfaces ?? []) { 72 | if (networkInterface.mac) { 73 | return this.hash('sha1', networkInterface.mac); 74 | } 75 | } 76 | } 77 | return undefined; 78 | } 79 | 80 | private static hash(algorithm: string, data: string): string { 81 | return crypto.createHash(algorithm).update(data).digest('hex'); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/Xsc/XscEventClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '..'; 2 | import { IRequestParams } from '../HttpClient'; 3 | 4 | import { 5 | IClientResponse, 6 | ILogger, 7 | ScanEventStatus, 8 | ScanEventType, 9 | XscLog, 10 | StartScanRequest, 11 | ScanEventResponse, 12 | ScanEvent, 13 | } from '../../model/'; 14 | 15 | export class XscEventClient { 16 | static readonly eventEndpoint: string = 'api/v1/event'; 17 | static readonly logEventEndpoint: string = XscEventClient.eventEndpoint + '/logMessage'; 18 | 19 | constructor(private readonly httpClient: HttpClient, private readonly logger: ILogger) {} 20 | 21 | /** 22 | * 23 | * Send 'POST /event/logMessage' request to Xsc. 24 | * 25 | * @param logEvent - The Log event to send 26 | * @returns true if the log was sent successfully, false otherwise. 27 | */ 28 | public async log(logEvent: XscLog): Promise { 29 | this.logger.debug('Sending POST event/logMessage request...'); 30 | const requestParams: IRequestParams = { 31 | url: XscEventClient.logEventEndpoint, 32 | method: 'POST', 33 | data: logEvent, 34 | }; 35 | try { 36 | let response: IClientResponse | undefined = await this.httpClient.doAuthRequest(requestParams); 37 | return response?.status === 201; 38 | } catch (error) { 39 | this.logger.debug(error); 40 | return false; 41 | } 42 | } 43 | 44 | /** 45 | * 46 | * Send 'POST /event' request to Xsc. 47 | * 48 | * @param eventInfo - The Scan request information that is requested to start 49 | * @returns the scan event information that started. 50 | * @throws an exception if an unexpected response received from Xsc. 51 | */ 52 | public async startScan(eventInfo: StartScanRequest): Promise { 53 | this.logger.debug('Sending POST event request...'); 54 | eventInfo.event_status = ScanEventStatus.Started; 55 | eventInfo.event_type = ScanEventType.SourceCode; 56 | const requestParams: IRequestParams = { 57 | url: XscEventClient.eventEndpoint, 58 | method: 'POST', 59 | data: eventInfo, 60 | validateStatus: (status: number) => status === 201, 61 | }; 62 | this.logger.debug('data: ' + JSON.stringify(eventInfo)); 63 | return await ( 64 | await this.httpClient.doAuthRequest(requestParams) 65 | ).data; 66 | } 67 | 68 | /** 69 | * 70 | * Send 'PUT /event' request to Xsc. 71 | * 72 | * @param eventInfo - The Scan event to end 73 | * @returns true if the scan ending information sent successfully, false otherwise. 74 | */ 75 | public async endScan(event: ScanEvent): Promise { 76 | this.logger.debug('Sending PUT event request...'); 77 | const requestParams: IRequestParams = { 78 | url: XscEventClient.eventEndpoint, 79 | method: 'PUT', 80 | data: event, 81 | }; 82 | try { 83 | let response: IClientResponse | undefined = await this.httpClient.doAuthRequest(requestParams); 84 | return response?.status === 200; 85 | } catch (error) { 86 | this.logger.debug(error); 87 | return false; 88 | } 89 | } 90 | 91 | public async getScanEvent(multiScanId: string): Promise { 92 | this.logger.debug(`Sending GET event/${multiScanId} request...`); 93 | const requestParams: IRequestParams = { 94 | url: XscEventClient.eventEndpoint + '/' + multiScanId, 95 | method: 'GET', 96 | validateStatus: (status: number) => status === 200, 97 | }; 98 | return await ( 99 | await this.httpClient.doAuthRequest(requestParams) 100 | ).data; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /test/tests/JfrogClient.spec.ts: -------------------------------------------------------------------------------- 1 | import * as os from 'os'; 2 | 3 | import { JfrogClient } from '../../src'; 4 | import { ArtifactoryClient } from '../../src/Artifactory/ArtifactoryClient'; 5 | import { XrayClient } from '../../src/Xray/XrayClient'; 6 | import { IJfrogClientConfig } from '../../model/JfrogClientConfig'; 7 | import { TestUtils } from '../TestUtils'; 8 | import { PlatformClient } from '../../src/Platform/PlatformClient'; 9 | 10 | const PLATFORM_URL: string = 'http://localhost:8000'; 11 | const ARTIFACTORY_URL: string = 'http://localhost:8765/artifactory'; 12 | const XRAY_URL: string = 'http://localhost:8765/xray'; 13 | 14 | describe('Jfrog client tests', () => { 15 | test('Client initialization with platform URL', () => { 16 | const config: IJfrogClientConfig = { platformUrl: PLATFORM_URL }; 17 | const jfrogClient: JfrogClient = new JfrogClient(config); 18 | expect(jfrogClient).toBeInstanceOf(JfrogClient); 19 | expect(jfrogClient.artifactory()).toBeInstanceOf(ArtifactoryClient); 20 | expect(jfrogClient.xray()).toBeInstanceOf(XrayClient); 21 | expect(jfrogClient.getServerUrl('artifactory', config.artifactoryUrl)).toBe(PLATFORM_URL + '/artifactory/'); 22 | expect(jfrogClient.getServerUrl('xray', config.xrayUrl)).toBe(PLATFORM_URL + '/xray/'); 23 | expect(jfrogClient.clientId).toBeDefined(); 24 | }); 25 | 26 | test('Client initialization with custom Artifactory URL', () => { 27 | const config: IJfrogClientConfig = { artifactoryUrl: ARTIFACTORY_URL, logger: TestUtils.createTestLogger() }; 28 | const jfrogClient: JfrogClient = new JfrogClient(config); 29 | expect(jfrogClient).toBeInstanceOf(JfrogClient); 30 | expect(jfrogClient.artifactory()).toBeInstanceOf(ArtifactoryClient); 31 | expect(() => { 32 | jfrogClient.xray(); 33 | }).toThrow('xray client: must provide platform or specific URLs'); 34 | expect(jfrogClient.getServerUrl('artifactory', config.artifactoryUrl)).toBe(ARTIFACTORY_URL); 35 | }); 36 | 37 | test('Client initialization with custom Xray URL', () => { 38 | const config: IJfrogClientConfig = { xrayUrl: XRAY_URL, logger: TestUtils.createTestLogger() }; 39 | const jfrogClient: JfrogClient = new JfrogClient(config); 40 | expect(jfrogClient).toBeInstanceOf(JfrogClient); 41 | expect(jfrogClient.xray()).toBeInstanceOf(XrayClient); 42 | expect(() => { 43 | jfrogClient.artifactory(); 44 | }).toThrow('artifactory client: must provide platform or specific URLs'); 45 | expect(jfrogClient.getServerUrl('xray', config.xrayUrl)).toBe(XRAY_URL); 46 | }); 47 | 48 | test('Client initialization with w/o URLs', () => { 49 | expect(() => { 50 | new JfrogClient({ logger: TestUtils.createTestLogger() }); 51 | }).toThrow('JFrog client: must provide platform or specific URLs'); 52 | }); 53 | 54 | test('Generate client unique id', () => { 55 | expect(JfrogClient.getClientId([undefined])).toBeUndefined(); 56 | let test: os.NetworkInterfaceBase = { 57 | mac: 'aa:aa:aa:aa:aa:aa', 58 | address: '', 59 | netmask: '', 60 | internal: false, 61 | cidr: null, 62 | }; 63 | expect(JfrogClient.getClientId([undefined, [], undefined, [test], undefined])).toBe( 64 | 'c7d2c26fea52066c5943777a3c2e1fc510350d55' 65 | ); 66 | }); 67 | 68 | describe('Platform client', () => { 69 | test('Generate platform client with provided platform URL', () => { 70 | const jfrogClient: JfrogClient = new JfrogClient({ platformUrl: PLATFORM_URL }); 71 | const result: PlatformClient = jfrogClient.platform(); 72 | expect(result).toBeInstanceOf(PlatformClient); 73 | }); 74 | 75 | test('Fail to Generate platform client with provided platform URL', () => { 76 | expect(() => new JfrogClient({ xrayUrl: PLATFORM_URL }).platform()).toThrowError( 77 | 'JFrog client: must provide platform URLs' 78 | ); 79 | }); 80 | }); 81 | }); 82 | -------------------------------------------------------------------------------- /test/tests/Artifactory/ArtifactoryDownloadClient.spec.ts: -------------------------------------------------------------------------------- 1 | import { IAqlSearchResult, IChecksumResult, IJfrogClientConfig } from '../../../model'; 2 | import { JfrogClient } from '../../../src'; 3 | import { TestUtils } from '../../TestUtils'; 4 | import * as path from 'path'; 5 | import * as tmp from 'tmp'; 6 | import * as fs from 'fs'; 7 | import nock from 'nock'; 8 | let jfrogClient: JfrogClient; 9 | const BUILD_INFO_REPO: string = '/artifactory-build-info/'; 10 | 11 | describe('Artifactory Download tests', () => { 12 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 13 | let downloadFilePath: string; 14 | let tmpDir: tmp.DirResult; 15 | 16 | beforeAll(() => { 17 | jfrogClient = new JfrogClient(clientConfig); 18 | }); 19 | 20 | beforeEach(() => { 21 | tmpDir = tmp.dirSync({ unsafeCleanup: true }); 22 | downloadFilePath = path.join(tmpDir.name, 'tmpFile'); 23 | }); 24 | 25 | afterEach(() => { 26 | tmpDir.removeCallback(); 27 | }); 28 | 29 | test('Build artifact download test', async () => { 30 | const result: IAqlSearchResult = await TestUtils.searchArtifactoryBuildRepo(jfrogClient); 31 | expect(result.results.length).toBeGreaterThan(0); 32 | const artifactPath: string = BUILD_INFO_REPO + result.results[0].path + '/' + result.results[0].name; 33 | const build: any = await jfrogClient.artifactory().download().downloadArtifact(artifactPath); 34 | expect(build).toBeTruthy(); 35 | expect(build.name).toBe(decodeURIComponent(result.results[0].path)); 36 | }); 37 | 38 | test('Build artifact download to file test', async () => { 39 | const result: IAqlSearchResult = await TestUtils.searchArtifactoryBuildRepo(jfrogClient); 40 | expect(result.results.length).toBeGreaterThan(0); 41 | const artifactPath: string = BUILD_INFO_REPO + result.results[0].path + '/' + result.results[0].name; 42 | await jfrogClient.artifactory().download().downloadArtifactToFile(artifactPath, downloadFilePath); 43 | expect(fs.existsSync(downloadFilePath)).toBeTruthy(); 44 | expect(fs.statSync(downloadFilePath).size).toEqual(result.results[0].size); 45 | }); 46 | 47 | test('Download non-existed artifact to file', async () => { 48 | await expect( 49 | async () => await jfrogClient.artifactory().download().downloadArtifactToFile('not-exist', downloadFilePath) 50 | ).rejects.toThrow('Request failed with status code 404'); 51 | expect(fs.existsSync(downloadFilePath)).toBeFalsy(); 52 | }); 53 | 54 | test('Download non-existed artifact to non-existed directory', async () => { 55 | tmpDir.removeCallback(); 56 | const result: IAqlSearchResult = await TestUtils.searchArtifactoryBuildRepo(jfrogClient); 57 | expect(result.results.length).toBeGreaterThan(0); 58 | const artifactPath: string = BUILD_INFO_REPO + result.results[0].path + '/' + result.results[0].name; 59 | await expect( 60 | async () => 61 | await jfrogClient.artifactory().download().downloadArtifactToFile(artifactPath, downloadFilePath) 62 | ).rejects.toThrow('no such file or directory'); 63 | }); 64 | 65 | test('Build artifact download checksum test', async () => { 66 | const result: IAqlSearchResult = await TestUtils.searchArtifactoryBuildRepo(jfrogClient); 67 | expect(result.results.length).toBeGreaterThan(0); 68 | const artifactPath: string = BUILD_INFO_REPO + result.results[0].path + '/' + result.results[0].name; 69 | const checksum: IChecksumResult = await jfrogClient.artifactory().download().getArtifactChecksum(artifactPath); 70 | expect(checksum.md5).toBeTruthy(); 71 | expect(checksum.sha1).toBeTruthy(); 72 | expect(checksum.sha256).toBeTruthy(); 73 | }); 74 | 75 | test('Build artifact download checksum timeout test', async () => { 76 | const dummyClient: JfrogClient = (jfrogClient = new JfrogClient({ 77 | artifactoryUrl: 'http://localhost:8080/artifactory', 78 | logger: TestUtils.createTestLogger(), 79 | timeout: 2000, 80 | } as IJfrogClientConfig)); 81 | nock('http://localhost:8080').head('/artifactory/a/b/file').delay(6000).reply(200, 'RESPONSE'); 82 | await expect( 83 | async () => await dummyClient.artifactory().download().getArtifactChecksum('a/b/file') 84 | ).rejects.toThrow('timeout of 2000ms exceeded'); 85 | }); 86 | }); 87 | -------------------------------------------------------------------------------- /test/tests/Xray/XraySummaryClient.spec.ts: -------------------------------------------------------------------------------- 1 | import { 2 | IArtifact, 3 | ComponentDetails, 4 | IGeneral, 5 | ICve, 6 | IIssue, 7 | IVulnerableComponent, 8 | ILicense, 9 | ISummaryRequestModel, 10 | ISummaryResponse, 11 | } from '../../../model'; 12 | import { TestUtils } from '../../TestUtils'; 13 | import { JfrogClient } from '../../../src'; 14 | 15 | const jsYaml: ISummaryRequestModel = { 16 | component_details: [new ComponentDetails('npm://js-yaml:3.10.0')], 17 | } as ISummaryRequestModel; 18 | const FIRST_ISSUE_ID: string = 'XRAY-79036'; 19 | const FIRST_ISSUE_SUMMARY: string = 'Denial of Service in js-yaml'; 20 | const SECOND_ISSUE_ID: string = 'XRAY-80240'; 21 | const SECOND_ISSUE_SUMMARY: string = 'Code Injection in js-yaml'; 22 | 23 | const express: ISummaryRequestModel = { 24 | component_details: [new ComponentDetails('npm://express:4.0.0')], 25 | } as ISummaryRequestModel; 26 | const EXPRESS_ISSUE_SUMMARY: string = 27 | 'The Express web framework before 3.11 and 4.x before 4.5 for Node.js does not provide a charset field in HTTP Content-Type headers in 400 level responses, which might allow remote attackers to conduct cross-site scripting (XSS) attacks via characters in a non-standard encoding.'; 28 | 29 | let jfrogClient: JfrogClient; 30 | 31 | beforeAll(() => { 32 | jfrogClient = new JfrogClient(TestUtils.getJfrogClientConfig()); 33 | }); 34 | describe('Xray summary tests', () => { 35 | test('Artifact summary component', async () => { 36 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(jsYaml); 37 | expect(response).toBeTruthy(); 38 | const artifacts: IArtifact[] = response.artifacts; 39 | expect(artifacts.length).toBe(1); 40 | }); 41 | 42 | test('Artifact summary component general', async () => { 43 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(jsYaml); 44 | expect(response).toBeTruthy(); 45 | 46 | const general: IGeneral = response.artifacts[0].general; 47 | expect(general).toBeTruthy(); 48 | expect(general.name).toBe('js-yaml'); 49 | expect(general.pkg_type).toBe('npm'); 50 | expect(general.component_id).toBe('js-yaml:3.10.0'); 51 | }); 52 | 53 | test('Artifact summary component issues', async () => { 54 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(jsYaml); 55 | expect(response).toBeTruthy(); 56 | 57 | const issues: IIssue[] = response.artifacts[0].issues; 58 | expect(issues.length).toBeGreaterThanOrEqual(2); 59 | 60 | const firstIssue: IIssue | undefined = issues.find((issue) => issue.issue_id === FIRST_ISSUE_ID); 61 | const secondIssue: IIssue | undefined = issues.find((issue) => issue.issue_id === SECOND_ISSUE_ID); 62 | expect(firstIssue).toBeTruthy(); 63 | expect(secondIssue).toBeTruthy(); 64 | if (!firstIssue || !secondIssue) { 65 | return; 66 | } 67 | expect(firstIssue.description).toBeTruthy(); 68 | expect(firstIssue.severity).toBe('Medium'); 69 | expect(firstIssue.summary).toBe(FIRST_ISSUE_SUMMARY); 70 | expect(secondIssue.description).toBeTruthy(); 71 | expect(secondIssue.severity).toBe('High'); 72 | expect(secondIssue.summary).toBe(SECOND_ISSUE_SUMMARY); 73 | }); 74 | 75 | test('Artifact Summary component CVE', async () => { 76 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(express); 77 | expect(response).toBeTruthy(); 78 | 79 | const issues: IIssue[] = response.artifacts[0].issues; 80 | expect(issues.length).toBeGreaterThanOrEqual(1); 81 | 82 | const testIssue: IIssue | undefined = issues.find((issue) => issue.summary === EXPRESS_ISSUE_SUMMARY); 83 | expect(testIssue).toBeTruthy(); 84 | 85 | const cves: ICve[] | undefined = testIssue?.cves; 86 | expect(cves).toBeTruthy(); 87 | if (!cves) { 88 | return; 89 | } 90 | expect(cves).toHaveLength(1); 91 | expect(cves[0].cve).toBe('CVE-2014-6393'); 92 | expect(cves[0].cvss_v2).toBe('4.3/CVSS:2.0/AV:N/AC:M/Au:N/C:N/I:P/A:N'); 93 | }); 94 | 95 | test('Artifact Summary component fixed versions', async () => { 96 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(express); 97 | expect(response).toBeTruthy(); 98 | 99 | const issues: IIssue[] = response.artifacts[0].issues; 100 | expect(issues.length).toBeGreaterThanOrEqual(1); 101 | 102 | const testIssue: IIssue | undefined = issues.find((issue) => issue.summary === EXPRESS_ISSUE_SUMMARY); 103 | expect(testIssue).toBeTruthy(); 104 | 105 | const components: IVulnerableComponent[] | undefined = testIssue?.components; 106 | expect(components).toBeTruthy(); 107 | 108 | const expressComponent: IVulnerableComponent | undefined = components?.find( 109 | (component) => component.component_id === 'express' 110 | ); 111 | expect(expressComponent).toBeTruthy(); 112 | const fixedVersions: string[] | undefined = expressComponent?.fixed_versions; 113 | expect(fixedVersions).toBeTruthy(); 114 | expect(fixedVersions?.length).toBeGreaterThanOrEqual(2); 115 | expect(fixedVersions).toContain('[3.11.0]'); 116 | expect(fixedVersions).toContain('[4.5.0]'); 117 | }); 118 | 119 | test('Artifact summary component licenses', async () => { 120 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(jsYaml); 121 | expect(response).toBeTruthy(); 122 | 123 | const licenses: ILicense[] = response.artifacts[0].licenses; 124 | expect(licenses.length).toBe(1); 125 | 126 | const license: ILicense = licenses[0]; 127 | expect(license.name).toBe('MIT'); 128 | expect(license.full_name).toBe('MIT License'); 129 | expect(license.more_info_url.length).toBeGreaterThanOrEqual(3); 130 | expect(license.components.length).toBe(1); 131 | expect(license.components[0]).toBe('npm://js-yaml:3.10.0'); 132 | }); 133 | 134 | test('Artifact not exist', async () => { 135 | const notFoundArtifactRequest: ISummaryRequestModel = { 136 | component_details: [new ComponentDetails('npm://non-existing-component:1.2.3')], 137 | } as ISummaryRequestModel; 138 | const response: ISummaryResponse = await jfrogClient.xray().summary().component(notFoundArtifactRequest); 139 | expect(response).toBeTruthy(); 140 | expect(response.artifacts.length).toBe(1); 141 | const artifact: IArtifact = response.artifacts[0]; 142 | expect(artifact.general.component_id).toBe('non-existing-component:1.2.3'); 143 | expect(artifact.issues.length).toBe(0); 144 | expect(artifact.licenses.length).toBe(1); 145 | 146 | const license: ILicense = artifact.licenses[0]; 147 | expect(license.name).toBe('Unknown'); 148 | expect(license.full_name).toBe('Unknown license'); 149 | expect(license.components.length).toBe(1); 150 | expect(license.components[0]).toBe('npm://non-existing-component:1.2.3'); 151 | }); 152 | }); 153 | -------------------------------------------------------------------------------- /test/tests/Artifactory/ArtifactorySystemClient.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import * as http from 'http'; 3 | import { createProxyServer, ServerOptions } from 'http-proxy'; 4 | import nock from 'nock'; 5 | import { IArtifactoryVersion, IProxyConfig, IUsageFeature } from '../../../model'; 6 | import { TestUtils } from '../../TestUtils'; 7 | import { IJfrogClientConfig } from '../../../model/JfrogClientConfig'; 8 | import { JfrogClient } from '../../../src'; 9 | 10 | let isPassedThroughProxy: boolean; 11 | let jfrogClient: JfrogClient; 12 | 13 | describe('Artifactory System tests', () => { 14 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 15 | beforeAll(() => { 16 | jfrogClient = new JfrogClient(clientConfig); 17 | }); 18 | afterAll(() => { 19 | nock.cleanAll(); 20 | }); 21 | 22 | test('Usage', async () => { 23 | const featureArray: IUsageFeature[] = [{ featureId: 'rt_test' }, { featureId: 'usage_test' }]; 24 | const res: string = await jfrogClient.artifactory().system().reportUsage('client-js-test/1.2.3', featureArray); 25 | // Empty string returned on successful requests. 26 | expect(res).toBeFalsy(); 27 | }); 28 | 29 | test('Version', async () => { 30 | const version: IArtifactoryVersion = await jfrogClient.artifactory().system().version(); 31 | expect(version.version).toBeTruthy(); 32 | expect(version.revision).toBeTruthy(); 33 | expect(isPassedThroughProxy).toBeFalsy(); 34 | }); 35 | 36 | describe('Ping tests', () => { 37 | const PING_RES: string = 'OK'; 38 | 39 | beforeEach(() => { 40 | process.env.HTTPS_PROXY = ''; 41 | process.env.NO_PROXY = ''; 42 | isPassedThroughProxy = false; 43 | }); 44 | 45 | test('Ping success', async () => { 46 | const response: any = await jfrogClient.artifactory().system().ping(); 47 | expect(response).toStrictEqual(PING_RES); 48 | expect(isPassedThroughProxy).toBeFalsy(); 49 | }); 50 | 51 | describe('Ping proxy', () => { 52 | let proxy: any; 53 | let proxyJfrogClient: JfrogClient; 54 | beforeAll(() => { 55 | clientConfig.proxy = { port: 9090 } as IProxyConfig; 56 | proxyJfrogClient = new JfrogClient(clientConfig); 57 | proxy = createProxyServer({ target: clientConfig.platformUrl } as ServerOptions).listen(9090); 58 | proxy.on('proxyReq', () => (isPassedThroughProxy = true)); 59 | }); 60 | afterAll(() => { 61 | proxy.close(); 62 | process.env.HTTPS_PROXY = ''; 63 | process.env.NO_PROXY = ''; 64 | }); 65 | 66 | test('Ping through proxy', async () => { 67 | const response: any = await proxyJfrogClient.artifactory().system().ping(); 68 | expect(response).toStrictEqual(PING_RES); 69 | expect(isPassedThroughProxy).toBeTruthy(); 70 | }); 71 | 72 | test('Ping through proxy env', async () => { 73 | process.env.HTTPS_PROXY = 'http://127.0.0.1:9090'; 74 | const response: any = await jfrogClient.artifactory().system().ping(); 75 | expect(response).toStrictEqual(PING_RES); 76 | expect(isPassedThroughProxy).toBeTruthy(); 77 | }); 78 | 79 | test('Ping skip proxy', async () => { 80 | process.env.HTTPS_PROXY = 'http://127.0.0.1:9090'; 81 | process.env.NO_PROXY = clientConfig.platformUrl; 82 | const response: any = await jfrogClient.artifactory().system().ping(); 83 | expect(response).toStrictEqual(PING_RES); 84 | expect(isPassedThroughProxy).toBeTruthy(); 85 | }); 86 | 87 | test('Ping empty proxy', async () => { 88 | const jfrogClientEmptyProxy: JfrogClient = new JfrogClient({ 89 | platformUrl: clientConfig.platformUrl, 90 | username: clientConfig.username, 91 | password: clientConfig.password, 92 | accessToken: clientConfig.accessToken, 93 | proxy: {} as IProxyConfig, 94 | logger: TestUtils.createTestLogger(), 95 | }); 96 | const response: any = await jfrogClientEmptyProxy.artifactory().system().ping(); 97 | expect(response).toStrictEqual(PING_RES); 98 | expect(isPassedThroughProxy).toBeFalsy(); 99 | }); 100 | 101 | describe('Ping auth proxy', () => { 102 | const PROXY_USER: string = faker.internet.userName(); 103 | const PROXY_PASS: string = faker.internet.password(); 104 | let proxyAuthJfrogClient: JfrogClient; 105 | let authProxy: any; 106 | beforeAll(() => { 107 | clientConfig.proxy = { port: 9091 } as IProxyConfig; 108 | clientConfig.headers = { 109 | 'proxy-authorization': 'Basic ' + Buffer.from(PROXY_USER + ':' + PROXY_PASS).toString('base64'), 110 | }; 111 | proxyAuthJfrogClient = new JfrogClient(clientConfig); 112 | authProxy = createProxyServer({ target: clientConfig.platformUrl } as ServerOptions).listen(9091); 113 | authProxy.on('proxyReq', (proxyReq: http.ClientRequest) => { 114 | isPassedThroughProxy = true; 115 | // Check proxy header 116 | const actualAuthHeader: number | string | string[] | undefined = 117 | proxyReq.getHeader('proxy-authorization'); 118 | const expectAuthHeader: string = 119 | 'Basic ' + Buffer.from(PROXY_USER + ':' + PROXY_PASS).toString('base64'); 120 | expect(actualAuthHeader).toBe(expectAuthHeader); 121 | }); 122 | }); 123 | afterAll(() => { 124 | authProxy.close(); 125 | }); 126 | 127 | test('Ping though auth proxy', async () => { 128 | const response: any = await proxyAuthJfrogClient.artifactory().system().ping(); 129 | expect(response).toStrictEqual(PING_RES); 130 | expect(isPassedThroughProxy).toBeTruthy(); 131 | }); 132 | }); 133 | }); 134 | 135 | test('Ping failure', async () => { 136 | const platformUrl: string = faker.internet.url(); 137 | const scope: nock.Scope = nock(platformUrl) 138 | .get(`/artifactory/api/system/ping`) 139 | .reply(402, { message: 'error' }); 140 | const client: JfrogClient = new JfrogClient({ platformUrl, logger: TestUtils.createTestLogger() }); 141 | const res: any = await client.artifactory().system().ping(); 142 | expect(res).toBeFalsy(); 143 | expect(scope.isDone()).toBeTruthy(); 144 | expect(isPassedThroughProxy).toBeFalsy(); 145 | }); 146 | }); 147 | }); 148 | -------------------------------------------------------------------------------- /test/tests/Xray/XraySystemClient.spec.ts: -------------------------------------------------------------------------------- 1 | import * as faker from 'faker'; 2 | import * as http from 'http'; 3 | import { createProxyServer, ServerOptions } from 'http-proxy'; 4 | import nock from 'nock'; 5 | import { IProxyConfig, IXrayVersion } from '../../../model'; 6 | import { IJfrogClientConfig } from '../../../model/JfrogClientConfig'; 7 | import { JfrogClient, XraySystemClient } from '../../../src'; 8 | import { TestUtils } from '../../TestUtils'; 9 | 10 | let isPassedThroughProxy: boolean; 11 | let jfrogClient: JfrogClient; 12 | 13 | describe('Xray System tests', () => { 14 | const clientConfig: IJfrogClientConfig = TestUtils.getJfrogClientConfig(); 15 | 16 | beforeEach(() => { 17 | process.env.HTTPS_PROXY = ''; 18 | process.env.NO_PROXY = ''; 19 | isPassedThroughProxy = false; 20 | }); 21 | beforeAll(() => { 22 | jfrogClient = new JfrogClient(clientConfig); 23 | }); 24 | afterAll(() => { 25 | nock.cleanAll(); 26 | }); 27 | 28 | describe('Version tests', () => { 29 | test('Version', async () => { 30 | const version: IXrayVersion = await jfrogClient.xray().system().version(); 31 | expect(version.xray_version).toBeTruthy(); 32 | expect(version.xray_revision).toBeTruthy(); 33 | expect(isPassedThroughProxy).toBeFalsy(); 34 | }); 35 | 36 | beforeEach(nock.cleanAll.bind(nock)); 37 | 38 | test('Version failure - server not active', async () => { 39 | const client: JfrogClient = new JfrogClient({ 40 | platformUrl: 'https://httpbin.org/redirect-to?url=reactivate-server', 41 | logger: TestUtils.createTestLogger(), 42 | }); 43 | let errFound: boolean = false; 44 | try { 45 | await client.xray().system().version(); 46 | } catch (err: any) { 47 | errFound = true; 48 | expect(err.activationUrl).toBeDefined(); 49 | // This result only expected for the test (using httpbin with the redirect-to flag cause this). 50 | // Actual activationUrl will be equal to the location without the added relative path to the version request. 51 | // The JFrog client concat to the location the relative path of the version request. 52 | expect(err.activationUrl).toBe('reactivate-server/xray' + XraySystemClient.versionEndpoint); 53 | } 54 | expect(errFound).toBeTruthy(); 55 | expect(isPassedThroughProxy).toBeFalsy(); 56 | }); 57 | }); 58 | 59 | describe('Ping tests', () => { 60 | const PING_RES: any = { status: 'pong' }; 61 | 62 | test('Ping success', async () => { 63 | const response: any = await jfrogClient.xray().system().ping(); 64 | expect(response).toStrictEqual(PING_RES); 65 | expect(isPassedThroughProxy).toBeFalsy(); 66 | }); 67 | 68 | describe('Ping proxy', () => { 69 | let proxy: any; 70 | let proxyJfrogClient: JfrogClient; 71 | beforeAll(() => { 72 | clientConfig.proxy = { port: 9090 } as IProxyConfig; 73 | proxyJfrogClient = new JfrogClient(clientConfig); 74 | proxy = createProxyServer({ target: clientConfig.platformUrl } as ServerOptions).listen(9090); 75 | proxy.on('proxyReq', () => (isPassedThroughProxy = true)); 76 | }); 77 | afterAll(() => { 78 | proxy.close(); 79 | }); 80 | 81 | test('Ping through proxy', async () => { 82 | const response: any = await proxyJfrogClient.xray().system().ping(); 83 | expect(response).toStrictEqual(PING_RES); 84 | expect(isPassedThroughProxy).toBeTruthy(); 85 | }); 86 | 87 | test('Ping through proxy env', async () => { 88 | process.env.HTTPS_PROXY = 'http://127.0.0.1:9090'; 89 | const response: any = await jfrogClient.xray().system().ping(); 90 | expect(response).toStrictEqual(PING_RES); 91 | expect(isPassedThroughProxy).toBeTruthy(); 92 | }); 93 | 94 | test('Ping skip proxy', async () => { 95 | process.env.HTTPS_PROXY = 'http://127.0.0.1:9090'; 96 | process.env.NO_PROXY = clientConfig.platformUrl; 97 | const response: any = await jfrogClient.xray().system().ping(); 98 | expect(response).toStrictEqual(PING_RES); 99 | expect(isPassedThroughProxy).toBeTruthy(); 100 | }); 101 | 102 | test('Ping empty proxy', async () => { 103 | const jfrogClientEmptyProxy: JfrogClient = new JfrogClient({ 104 | platformUrl: clientConfig.platformUrl, 105 | username: clientConfig.username, 106 | password: clientConfig.password, 107 | accessToken: clientConfig.accessToken, 108 | proxy: {} as IProxyConfig, 109 | logger: TestUtils.createTestLogger(), 110 | }); 111 | const response: any = await jfrogClientEmptyProxy.xray().system().ping(); 112 | expect(response).toStrictEqual(PING_RES); 113 | expect(isPassedThroughProxy).toBeFalsy(); 114 | }); 115 | 116 | describe('Ping auth proxy', () => { 117 | const PROXY_USER: string = faker.internet.userName(); 118 | const PROXY_PASS: string = faker.internet.password(); 119 | let proxyAuthJfrogClient: JfrogClient; 120 | let authProxy: any; 121 | beforeAll(() => { 122 | clientConfig.proxy = { port: 9091 } as IProxyConfig; 123 | clientConfig.headers = { 124 | 'proxy-authorization': 'Basic ' + Buffer.from(PROXY_USER + ':' + PROXY_PASS).toString('base64'), 125 | }; 126 | proxyAuthJfrogClient = new JfrogClient(clientConfig); 127 | authProxy = createProxyServer({ target: clientConfig.platformUrl } as ServerOptions).listen(9091); 128 | authProxy.on('proxyReq', (proxyReq: http.ClientRequest) => { 129 | isPassedThroughProxy = true; 130 | // Check proxy header 131 | const actualAuthHeader: string | number | string[] | undefined = 132 | proxyReq.getHeader('proxy-authorization'); 133 | const expectAuthHeader: string = 134 | 'Basic ' + Buffer.from(PROXY_USER + ':' + PROXY_PASS).toString('base64'); 135 | expect(actualAuthHeader).toBe(expectAuthHeader); 136 | }); 137 | }); 138 | afterAll(() => { 139 | authProxy.close(); 140 | }); 141 | 142 | test('Ping though auth proxy', async () => { 143 | const response: any = await proxyAuthJfrogClient.xray().system().ping(); 144 | expect(response).toStrictEqual(PING_RES); 145 | expect(isPassedThroughProxy).toBeTruthy(); 146 | }); 147 | }); 148 | }); 149 | 150 | test('Ping failure', async () => { 151 | const platformUrl: string = faker.internet.url(); 152 | const scope: nock.Scope = nock(platformUrl) 153 | .get(`/xray/api/v1/system/ping`) 154 | .reply(402, { message: 'error' }); 155 | const client: JfrogClient = new JfrogClient({ platformUrl, logger: TestUtils.createTestLogger() }); 156 | const res: any = await client.xray().system().ping(); 157 | expect(res).toBeFalsy(); 158 | expect(scope.isDone()).toBeTruthy(); 159 | expect(isPassedThroughProxy).toBeFalsy(); 160 | }); 161 | }); 162 | }); 163 | -------------------------------------------------------------------------------- /src/HttpClient.ts: -------------------------------------------------------------------------------- 1 | import axios, { AxiosError, AxiosInstance, AxiosProxyConfig, AxiosRequestConfig } from 'axios'; 2 | import { IClientResponse, ILogger, IProxyConfig, RetryOnStatusCode } from '../model'; 3 | import axiosRetry, { IAxiosRetryConfig } from 'axios-retry'; 4 | import { HttpsProxyAgent } from 'https-proxy-agent'; 5 | export class HttpClient { 6 | private static readonly AUTHORIZATION_HEADER: string = 'Authorization'; 7 | private static readonly USER_AGENT_HEADER: string = 'User-Agent'; 8 | private static readonly DEFAULT_RETRIES: number = 5; 9 | // Delay between retries, in milliseconds 10 | private static readonly DEFAULT_RETRY_DELAY_IN_MILLISECONDS: number = 1000; 11 | // Specifies the number of milliseconds before the request times out. 12 | // If the request takes longer than `DEFAULT_TIMEOUT_IN_MILLISECONDS`, the request will be aborted. 13 | public static readonly DEFAULT_TIMEOUT_IN_MILLISECONDS: number = 60000; 14 | private readonly _basicAuth: BasicAuth; 15 | private readonly _accessToken: string; 16 | private readonly _axiosInstance: AxiosInstance; 17 | 18 | constructor(config: IHttpConfig, private logger?: ILogger) { 19 | config.headers = config.headers || {}; 20 | this.addUserAgentHeader(config.headers); 21 | this._axiosInstance = axios.create({ 22 | baseURL: config.serverUrl, 23 | headers: config.headers, 24 | timeout: config.timeout, 25 | proxy: this.getAxiosProxyConfig(config.proxy), 26 | // Use instead of the default one since there is a bug in Axios if http -> https 27 | httpsAgent: HttpClient.getHttpToHttpsProxyConfig(config.proxy), 28 | } as AxiosRequestConfig); 29 | this._basicAuth = { 30 | username: config.username, 31 | password: config.password, 32 | } as BasicAuth; 33 | this._accessToken = config.accessToken || ''; 34 | this.addRetryInterceptor(config); 35 | } 36 | 37 | private addRetryInterceptor(config: IHttpConfig): void { 38 | const retryConfig: IAxiosRetryConfig = { 39 | retries: config.retries ?? HttpClient.DEFAULT_RETRIES, 40 | retryCondition: (error: AxiosError) => this.shouldRetry(config, error), 41 | retryDelay: (retryCount: number, err: AxiosError) => { 42 | this.logger?.debug(`Request ended with error: ${err}\nRetrying (attempt #${retryCount})...`); 43 | return config.retryDelay ?? HttpClient.DEFAULT_RETRY_DELAY_IN_MILLISECONDS; 44 | }, 45 | shouldResetTimeout: true, 46 | }; 47 | 48 | axiosRetry(this._axiosInstance, retryConfig); 49 | } 50 | 51 | private shouldRetry(config: IHttpConfig, error: AxiosError): boolean { 52 | if (config.retryOnStatusCode) { 53 | return !!error.response && config.retryOnStatusCode(error.response.status); 54 | } 55 | return axiosRetry.isNetworkOrIdempotentRequestError(error); 56 | } 57 | 58 | public async doRequest(requestParams: IRequestParams): Promise { 59 | return await this._axiosInstance(requestParams); 60 | } 61 | 62 | public async doAuthRequest(requestParams: IRequestParams): Promise { 63 | if (this._accessToken !== '') { 64 | this.addAuthHeader(requestParams); 65 | } else { 66 | requestParams.auth = this._basicAuth; 67 | } 68 | return this.doRequest(requestParams); 69 | } 70 | 71 | /** 72 | * Method to use for beforeRedirect attribute in IRequestParams. 73 | * Before redirecting checks if the target location for the redirect is for 'reactivate-server' and throws ServerNotActiveError if so. 74 | */ 75 | public static validateServerIsActive(_: Record, responseDetails: { headers: Record }) { 76 | let movedLocation: string | undefined = responseDetails?.headers['location']; 77 | if (movedLocation && movedLocation.includes('reactivate-server')) { 78 | throw new ServerNotActiveError(movedLocation); 79 | } 80 | } 81 | 82 | private addUserAgentHeader(headers: { [key: string]: string }) { 83 | if (!headers[HttpClient.USER_AGENT_HEADER]) { 84 | headers[HttpClient.USER_AGENT_HEADER] = 'jfrog-client-js'; 85 | } 86 | } 87 | 88 | private addAuthHeader(requestParams: IRequestParams) { 89 | if (!requestParams.headers) { 90 | requestParams.headers = {}; 91 | } 92 | if (!requestParams.headers[HttpClient.AUTHORIZATION_HEADER]) { 93 | requestParams.headers[HttpClient.AUTHORIZATION_HEADER] = 'Bearer ' + this._accessToken; 94 | } 95 | } 96 | 97 | /** 98 | * Use to create httpsAgent to handle Http proxy sending to a https server. 99 | * (Artifactory is https server, proxy protocol can be both) 100 | * @param proxyConfig - Receives on of the three: 101 | * 1. IProxyConfig to use specific proxy config. 102 | * 2. 'false' to disable proxy. 103 | * 3. 'undefined' to use environment variables if exist. 104 | * @returns if the proxy is http protocol return httpsAgent else return undefined 105 | */ 106 | public static getHttpToHttpsProxyConfig( 107 | proxyConfig: IProxyConfig | false | undefined 108 | ): HttpsProxyAgent | undefined { 109 | if ( 110 | !proxyConfig || 111 | !proxyConfig.host || 112 | !proxyConfig.port || 113 | (proxyConfig.protocol && proxyConfig.protocol.includes('https')) 114 | ) { 115 | return undefined; 116 | } 117 | return new HttpsProxyAgent(`http://${proxyConfig.host}:${proxyConfig.port}`); 118 | } 119 | 120 | /** 121 | * @param proxyConfig - Receives on of the three: 122 | * 1. IProxyConfig to use specific proxy config. 123 | * 2. 'false' to disable proxy. 124 | * 3. 'undefined' to use environment variables if exist. 125 | * 126 | * @returns AxiosProxyConfig to use specific proxy config, false to disable proxy or undefined to use environment. 127 | */ 128 | private getAxiosProxyConfig(proxyConfig: IProxyConfig | false | undefined): AxiosProxyConfig | false | undefined { 129 | // Return false to disable proxy or undefined to use default environment variables. 130 | if (!proxyConfig) { 131 | return proxyConfig; 132 | } 133 | if (proxyConfig.protocol && !proxyConfig.protocol.includes('https')) { 134 | // Disable default proxy handling 135 | return false; 136 | } 137 | // Return undefined to use default environment variables. 138 | const proxyHost: string = proxyConfig.host; 139 | const proxyPort: number = proxyConfig.port; 140 | if (!proxyHost && !proxyPort) { 141 | return undefined; 142 | } 143 | return { 144 | host: proxyConfig.host, 145 | port: proxyConfig.port, 146 | protocol: proxyConfig.protocol, 147 | } as AxiosProxyConfig; 148 | } 149 | } 150 | 151 | export class ServerNotActiveError extends Error { 152 | constructor(public readonly activationUrl: string) { 153 | super('Server is not active'); 154 | } 155 | } 156 | 157 | interface BasicAuth { 158 | username: string; 159 | password: string; 160 | } 161 | 162 | export interface IHttpConfig { 163 | serverUrl?: string; 164 | username?: string; 165 | password?: string; 166 | accessToken?: string; 167 | proxy?: IProxyConfig | false; 168 | headers?: { [key: string]: string }; 169 | retries?: number; 170 | retryDelay?: number; 171 | timeout?: number; 172 | retryOnStatusCode?: RetryOnStatusCode; 173 | } 174 | 175 | export type method = 'GET' | 'POST' | 'HEAD' | 'PUT'; 176 | export type responseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'; 177 | 178 | export interface IRequestParams { 179 | url: string; 180 | method: method; 181 | data?: any; 182 | auth?: BasicAuth; 183 | timeout?: number; 184 | headers?: any; 185 | responseType?: responseType; 186 | validateStatus?: ((status: number) => boolean) | null; 187 | beforeRedirect?: (options: Record, responseDetails: { headers: Record }) => void; 188 | } 189 | -------------------------------------------------------------------------------- /test/tests/Xray/XrayScanClient.spec.ts: -------------------------------------------------------------------------------- 1 | import faker from 'faker'; 2 | import nock from 'nock'; 3 | import { IGraphRequestModel } from '../../../model/Xray/Scan/GraphRequestModel'; 4 | import { IGraphResponse } from '../../../model/Xray/Scan/GraphResponse'; 5 | import { JfrogClient } from '../../../src'; 6 | import { XrayScanProgress } from '../../../src/Xray/XrayScanProgress'; 7 | import { TestUtils } from '../../TestUtils'; 8 | import { XrayClient } from '../../../src/Xray/XrayClient'; 9 | 10 | const PLATFORM_URL: string = faker.internet.url(); 11 | beforeAll(() => { 12 | nock.disableNetConnect(); 13 | }); 14 | 15 | afterAll(() => { 16 | nock.cleanAll(); 17 | nock.enableNetConnect(); 18 | }); 19 | 20 | describe('Scan graph tests', () => { 21 | const client: JfrogClient = new JfrogClient({ 22 | platformUrl: PLATFORM_URL, 23 | logger: TestUtils.createTestLogger(), 24 | }); 25 | test('Unexpected response', async () => { 26 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 27 | nock(PLATFORM_URL) 28 | .post(uri) 29 | .reply(200, { scan_id: '123' } as IGraphResponse); 30 | nock(PLATFORM_URL) 31 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=true') 32 | .reply(404, 'not found'); 33 | const progress: DummyProgress = new DummyProgress(); 34 | await expect(async () => { 35 | await client 36 | .xray() 37 | .scan() 38 | .graph({} as IGraphRequestModel, progress, () => undefined, '', []); 39 | }).rejects.toThrow(`Received unexpected response from Xray. AxiosError: Request failed with status code 404`); 40 | expect(progress.lastPercentage).toBe(100); 41 | }); 42 | 43 | test('Project test', async () => { 44 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 45 | nock(PLATFORM_URL) 46 | .post(uri + '?project=ecosys') 47 | .reply(200, { scan_id: '123' } as IGraphResponse); 48 | const scope: nock.Scope = nock(PLATFORM_URL) 49 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=false') 50 | .reply(200); 51 | const progress: DummyProgress = new DummyProgress(); 52 | await client 53 | .xray() 54 | .scan() 55 | .graph({ component_id: 'engine' } as IGraphRequestModel, progress, () => undefined, 'ecosys', []); 56 | expect(scope.isDone()).toBeTruthy(); 57 | expect(progress.lastPercentage).toBe(100); 58 | }); 59 | 60 | test('Watch test', async () => { 61 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 62 | nock(PLATFORM_URL) 63 | .post(uri + '?watch=watch-1') 64 | .reply(200, { scan_id: '123' } as IGraphResponse); 65 | const scope: nock.Scope = nock(PLATFORM_URL) 66 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=false') 67 | .reply(200); 68 | const progress: DummyProgress = new DummyProgress(); 69 | await client 70 | .xray() 71 | .scan() 72 | .graph({ component_id: 'engine' } as IGraphRequestModel, progress, () => undefined, '', ['watch-1']); 73 | expect(scope.isDone()).toBeTruthy(); 74 | expect(progress.lastPercentage).toBe(100); 75 | }); 76 | 77 | test('Watches test', async () => { 78 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 79 | nock(PLATFORM_URL) 80 | .post(uri + '?watch=watch-1&watch=watch-2') 81 | .reply(200, { scan_id: '123' } as IGraphResponse); 82 | const scope: nock.Scope = nock(PLATFORM_URL) 83 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=false') 84 | .reply(200); 85 | const progress: DummyProgress = new DummyProgress(); 86 | await client 87 | .xray() 88 | .scan() 89 | .graph({ component_id: 'engine' } as IGraphRequestModel, progress, () => undefined, '', [ 90 | 'watch-1', 91 | 'watch-2', 92 | ]); 93 | expect(scope.isDone()).toBeTruthy(); 94 | expect(progress.lastPercentage).toBe(100); 95 | }); 96 | 97 | test('Undefined request', async () => { 98 | const progress: DummyProgress = new DummyProgress(); 99 | expect( 100 | await client 101 | .xray() 102 | .scan() 103 | .graph(undefined as unknown as IGraphRequestModel, progress, () => undefined, '', []) 104 | ).toBeDefined(); 105 | expect(progress.lastPercentage).toBe(100); 106 | }); 107 | 108 | test('202 test', async () => { 109 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 110 | nock(PLATFORM_URL) 111 | .post(uri) 112 | .reply(200, { scan_id: '123' } as IGraphResponse); 113 | nock(PLATFORM_URL) 114 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=true') 115 | .reply(202); 116 | const scope: nock.Scope = nock(PLATFORM_URL) 117 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=true') 118 | .reply(200); 119 | const progress: DummyProgress = new DummyProgress(); 120 | await client 121 | .xray() 122 | .scan() 123 | .graph( 124 | { component_id: 'engine' } as IGraphRequestModel, 125 | progress, 126 | () => undefined, 127 | '', 128 | [], 129 | undefined, 130 | undefined, 131 | 10 132 | ); 133 | expect(scope.isDone()).toBeTruthy(); 134 | expect(progress.lastPercentage).toBe(100); 135 | }); 136 | 137 | test('Timeout', async () => { 138 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 139 | nock(PLATFORM_URL) 140 | .post(uri) 141 | .reply(200, { scan_id: '123' } as IGraphResponse); 142 | nock(PLATFORM_URL) 143 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=true') 144 | .reply(202) 145 | .persist(); 146 | const progress: DummyProgress = new DummyProgress(); 147 | await expect(async () => { 148 | await client 149 | .xray() 150 | .scan() 151 | .graph( 152 | { component_id: 'engine' } as IGraphRequestModel, 153 | progress, 154 | () => undefined, 155 | '', 156 | [], 157 | undefined, 158 | undefined, 159 | 10 160 | ); 161 | }).rejects.toThrow(`Xray get scan graph exceeded the timeout.`); 162 | expect(progress.lastPercentage).toBe(100); 163 | }); 164 | 165 | test('Check cancelled', async () => { 166 | const uri: string = '/xray/' + XrayClient.scanGraphEndpoint; 167 | nock(PLATFORM_URL) 168 | .post(uri) 169 | .reply(200, { scan_id: '123' } as IGraphResponse); 170 | nock(PLATFORM_URL) 171 | .get(uri + '/123?include_licenses=true&include_vulnerabilities=true') 172 | .reply(202) 173 | .persist(); 174 | const client: JfrogClient = new JfrogClient({ 175 | platformUrl: PLATFORM_URL, 176 | logger: TestUtils.createTestLogger(), 177 | }); 178 | const progress: DummyProgress = new DummyProgress(); 179 | await expect(async () => { 180 | await client 181 | .xray() 182 | .scan() 183 | .graph( 184 | { component_id: 'engine' } as IGraphRequestModel, 185 | progress, 186 | () => { 187 | throw Error('Scan aborted.'); 188 | }, 189 | '', 190 | [] 191 | ); 192 | }).rejects.toThrow(`Scan aborted.`); 193 | }); 194 | }); 195 | 196 | class DummyProgress implements XrayScanProgress { 197 | private _lastPercentage: number = 0; 198 | setPercentage(percentage: number): void { 199 | this._lastPercentage = percentage; 200 | } 201 | 202 | public get lastPercentage(): number { 203 | return this._lastPercentage; 204 | } 205 | } 206 | -------------------------------------------------------------------------------- /src/Xray/XrayScanClient.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '..'; 2 | import { IGraphRequestModel, IGraphResponse, ILogger } from '../../model/'; 3 | import { IClientResponse } from '../ClientResponse'; 4 | import { IRequestParams } from '../HttpClient'; 5 | import { XrayScanProgress } from './XrayScanProgress'; 6 | 7 | export class XrayScanClient { 8 | private static readonly SLEEP_INTERVAL_MILLISECONDS: number = 5000; 9 | private static readonly MAX_ATTEMPTS: number = 60; 10 | 11 | constructor( 12 | private readonly httpClient: HttpClient, 13 | private readonly endPoint: string, 14 | private readonly logger: ILogger 15 | ) {} 16 | 17 | public async graph( 18 | request: IGraphRequestModel, 19 | progress: XrayScanProgress, 20 | checkCanceled: () => void, 21 | projectKey: string | undefined, 22 | watches: string[] | undefined, 23 | multiScanId?: string, 24 | technologies?: string[], 25 | sleepIntervalMilliseconds: number = XrayScanClient.SLEEP_INTERVAL_MILLISECONDS 26 | ): Promise { 27 | try { 28 | if (!request) { 29 | return {} as IGraphResponse; 30 | } 31 | checkCanceled(); 32 | const response: IClientResponse = await this.postScanGraph( 33 | request, 34 | projectKey, 35 | watches, 36 | multiScanId, 37 | technologies 38 | ); 39 | return await this.getScanGraphResults( 40 | response.data.scan_id, 41 | progress, 42 | checkCanceled, 43 | (!projectKey || projectKey.length === 0) && (!watches || watches.length === 0), 44 | sleepIntervalMilliseconds 45 | ); 46 | } finally { 47 | progress.setPercentage(100); 48 | } 49 | } 50 | 51 | /** 52 | * 53 | * Send 'POST /scan/graph' request to Xray. 54 | * 55 | * @param request - The Graph to scan 56 | * @param projectKey - Project key or undefined 57 | * @param watches - List of Watches or undefined 58 | * @returns the graph response. 59 | * @throws an exception if an unexpected response received from Xray. 60 | */ 61 | private async postScanGraph( 62 | request: IGraphRequestModel, 63 | projectKey?: string, 64 | watches?: string[], 65 | multiScanId?: string, 66 | technologies?: string[] 67 | ): Promise { 68 | this.logger.debug('Sending POST scan/graph request...'); 69 | const requestParams: IRequestParams = { 70 | url: this.getUrl(projectKey, watches, multiScanId, technologies), 71 | method: 'POST', 72 | data: request, 73 | }; 74 | this.logger.debug('data: ' + JSON.stringify(request)); 75 | try { 76 | return await this.httpClient.doAuthRequest(requestParams); 77 | } catch (error) { 78 | let requestError: any = error; 79 | if (!requestError.message) { 80 | // Not an Axios error 81 | throw error; 82 | } 83 | let message: string = requestError.message; 84 | if (requestError.response?.data?.error) { 85 | message += ': ' + requestError?.response?.data?.error; 86 | } 87 | throw new Error(`${message}`); 88 | } 89 | } 90 | 91 | /** 92 | * Get URL for "POST scan/graph" (Xray: api/v1/scan/graph, XSC: api/v1/sca/scan/graph). 93 | * If no project key provided - /scan/graph 94 | * If project key was provided - /scan/graph?project= 95 | * If watches provided - /scan/graph?watch=&watch= 96 | * If multiScanId provided - /scan/graph?multi_scan_id= 97 | * If technologies provided - /scan/graph?tech=&tech= 98 | * @param projectKey - Project key or undefined 99 | * @param watches - List of Watches or undefined 100 | * @param multiScanId - Multi scan ID or undefined 101 | * @param technologies - List of technologies or undefined 102 | * @returns URL for "POST /scan/graph" 103 | */ 104 | private getUrl( 105 | projectKey: string | undefined, 106 | watches?: string[], 107 | multiScanId?: string, 108 | technologies?: string[] 109 | ): string { 110 | let url: string = this.endPoint; 111 | let params: string[] = []; 112 | 113 | if (projectKey && projectKey.length > 0) { 114 | params.push(`project=${projectKey}`); 115 | } else if (watches && watches.length > 0) { 116 | params.push(`watch=${watches.join('&watch=')}`); 117 | } 118 | if (multiScanId) { 119 | params.push(`multi_scan_id=${multiScanId}`); 120 | } 121 | if (technologies && technologies.length > 0) { 122 | params.push(`tech=${technologies.join('&tech=')}`); 123 | } 124 | 125 | return params.length > 0 ? url + '?' + params.join('&') : url; 126 | } 127 | 128 | /** 129 | * 130 | * Sends 'GET /scan/graph?...' requests to Xray and waits for 200 response. 131 | * If 202 response is received, it updates the progress and waits sleepIntervalMilliseconds. 132 | * If any other response received, it throws an error. 133 | * 134 | * @param scanId - The scan ID received from Xray, after running a 'POST scan/graph' request 135 | * @param progress - The progress that will be updated after every 202 response from Xray 136 | * @param checkCanceled - Function that may stop the scan if it throws an exception 137 | * @param includeVulnerabilities - True if no context (project or watches) is provided 138 | * @param sleepIntervalMilliseconds - Sleep interval in milliseconds between attepts 139 | * @returns the graph response 140 | * @throws an exception if an unexpected response received from Xray or if checkCanceled threw an exception 141 | */ 142 | private async getScanGraphResults( 143 | scanId: string, 144 | progress: XrayScanProgress, 145 | checkCanceled: () => void, 146 | includeVulnerabilities: boolean, 147 | sleepIntervalMilliseconds: number 148 | ): Promise { 149 | const scanGraphUrl: string = 150 | this.endPoint + 151 | '/' + 152 | scanId + 153 | '?include_licenses=true' + 154 | `&include_vulnerabilities=${includeVulnerabilities}`; 155 | for (let i: number = 0; i < XrayScanClient.MAX_ATTEMPTS; i++) { 156 | checkCanceled(); 157 | this.logger.debug(`Sending GET ${scanGraphUrl} request...`); 158 | let receivedStatus: number | undefined; 159 | const requestParams: IRequestParams = { 160 | url: scanGraphUrl, 161 | method: 'GET', 162 | validateStatus: (status: number): boolean => { 163 | receivedStatus = status; 164 | return status === 200 || status === 202; 165 | }, 166 | }; 167 | let message: string | undefined; 168 | let response: IClientResponse | undefined; 169 | try { 170 | response = await this.httpClient.doAuthRequest(requestParams); 171 | } catch (error) { 172 | throw new Error(`Received unexpected response from Xray. ${String(error)}`); 173 | } 174 | this.logger.debug(`Received status '${receivedStatus}' from Xray.`); 175 | if (receivedStatus === 200) { 176 | return response?.data; 177 | } 178 | 179 | if (receivedStatus === 202) { 180 | if (response?.data.progress_percentage) { 181 | progress.setPercentage(response.data.progress_percentage); 182 | } 183 | } else { 184 | if (receivedStatus) { 185 | throw new Error(`Received unexpected status '${receivedStatus}' from Xray: ${message}`); 186 | } 187 | throw new Error(`Received response from Xray: ${message}`); 188 | } 189 | 190 | await this.delay(sleepIntervalMilliseconds); 191 | } 192 | throw new Error('Xray get scan graph exceeded the timeout.'); 193 | } 194 | 195 | private async delay(sleepIntervalMilliseconds: number): Promise { 196 | return new Promise((resolve) => setTimeout(resolve, sleepIntervalMilliseconds)); 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # JFrog Javascript Client 2 | 3 | [![Scanned by Frogbot](https://raw.github.com/jfrog/frogbot/master/images/frogbot-badge.svg)](https://github.com/jfrog/frogbot#readme) 4 | [![Tests](https://github.com/jfrog/jfrog-client-js/actions/workflows/test.yml/badge.svg)](https://github.com/jfrog/jfrog-client-js/actions/workflows/test.yml) 5 | [![Code coverage](https://codecov.io/github/jfrog/jfrog-client-js/coverage.svg?branch=master)](https://codecov.io/github/jfrog/jfrog-client-js?branch=master) 6 | 7 | JFrog Javascript Client is a Javascript library, which wraps some REST APIs exposed by JFrog's different services. 8 | 9 | ## Contributions 10 | 11 | We welcome pull requests from the community. To help us improve this project, please read our [contribution](./CONTRIBUTING.md#guidelines) guide. 12 | 13 | ## Getting started 14 | 15 | Add jfrog-client-js as a dependency to your package.json file: 16 | 17 | ```json 18 | "dependencies": { 19 | "jfrog-client-js": "^2.0.0" 20 | } 21 | ``` 22 | 23 | ## APIs 24 | 25 | - [Setting up JFrog client](#setting-up-jfrog-client) 26 | - [Xray](#xray) 27 | - [Pinging Xray](#pinging-xray) 28 | - [Getting Xray Version](#getting-xray-version) 29 | - [Checking Xray Entitlement](#checking-xray-entitlement) 30 | - [Scanning Bulk of Dependencies](#scanning-bulk-of-dependencies) 31 | - [Scanning a Dependency Tree with Consideration to the JFrog Project](#scanning-a-dependency-tree-with-consideration-to-the-jfrog-project) 32 | - [Scanning a Dependency Tree with Consideration to the Xray Watches](#scanning-a-dependency-tree-with-consideration-to-the-xray-watches) 33 | - [Retrieving Xray Build Details](#retrieving-xray-build-details) 34 | - [Retrieving JAS configuration](#retrieving-jas-configuration) 35 | - [Artifactory](#artifactory) 36 | - [Pinging Artifactory](#pinging-artifactory) 37 | - [Getting Artifactory Version](#getting-artifactory-version) 38 | - [Downloading an Artifact](#downloading-an-artifact) 39 | - [Downloading an Artifact content](#downloading-an-artifact-content) 40 | - [Downloading an Artifact to file](#downloading-an-artifact-to-file) 41 | - [Downloading an Artifact checksum](#downloading-an-artifact-checksum) 42 | - [Searching by AQL](#searching-by-aql) 43 | - [Platform](#platform) 44 | - [Register For Web Login](#register-for-web-login) 45 | - [Get Access Token From Web Login](#get-access-token-from-web-login) 46 | - [Xray Source Control](#xray-source-control) 47 | - [Getting Xsc Version](#getting-xsc-version) 48 | - [Sending Log Message Event](#sending-log-mesage-event) 49 | - [Sending Start Scan Event](#sending-start-scan-event) 50 | - [Sending End Scan Event](#sending-end-scan-event) 51 | - [Getting Scan Event Details](#getting-scan-event-details) 52 | 53 | ### Setting up JFrog client 54 | 55 | ```javascript 56 | let jfrogClient = new JfrogClient({ 57 | platformUrl: 'https://my-platform-url.jfrog.io/', 58 | // artifactoryUrl - Set to use a custom Artifactory URL. 59 | // xrayUrl - Set to use a custom Xray URL. 60 | username: 'username', 61 | password: 'password', 62 | // OR 63 | accessToken: 'accessToken', 64 | 65 | // Optional parameters 66 | proxy: { host: '-xray.jfrog.io', port: 8081, protocol: 'https' }, 67 | headers: { key1: 'value1', key2: 'value2' }, 68 | // Connection retries. If not defined, the default value is 5. 69 | retries: 5, 70 | // Timeout before the connection is terminated in milliseconds, the default value is 60 seconds 71 | timeout: 60000, 72 | // Status codes that trigger retries. the default is network error or a 5xx status code. 73 | retryOnStatusCode: (statusCode: number) => statusCode >= 500;, 74 | // Delay between retries, in milliseconds. The default is 1000 milliseconds. 75 | retryDelay: 1000, 76 | }); 77 | ``` 78 | 79 | ### Xray 80 | 81 | #### Pinging Xray 82 | 83 | ```javascript 84 | jfrogClient 85 | .xray() 86 | .system() 87 | .ping() 88 | .then((result) => { 89 | console.log(result); 90 | }) 91 | .catch((error) => { 92 | console.error(error); 93 | }); 94 | ``` 95 | 96 | #### Getting Xray Version 97 | 98 | ```javascript 99 | jfrogClient 100 | .xray() 101 | .system() 102 | .version() 103 | .then((result) => { 104 | console.log(result); 105 | }) 106 | .catch((error) => { 107 | console.error(error); 108 | }); 109 | ``` 110 | 111 | #### Checking Xray Entitlement 112 | 113 | ```javascript 114 | let feature = 'contextual_analysis'; 115 | jfrogClient 116 | .xray() 117 | .entitlements() 118 | .feature(feature) 119 | .then((result) => { 120 | console.log(result); 121 | }) 122 | .catch((error) => { 123 | console.error(error); 124 | }); 125 | ``` 126 | 127 | #### Scanning Bulk of Dependencies 128 | 129 | ```javascript 130 | let express = new ComponentDetails('npm://express:4.0.0'); 131 | let request = new ComponentDetails('npm://request:2.0.0'); 132 | jfrogClient 133 | .xray() 134 | .summary() 135 | .component({ 136 | component_details: [express, request], 137 | }) 138 | .then((result) => { 139 | console.log(JSON.stringify(result)); 140 | }) 141 | .catch((error) => { 142 | console.error(error); 143 | }); 144 | ``` 145 | 146 | #### Scanning a Dependency Tree with Consideration to the JFrog Project 147 | 148 | ```javascript 149 | const progress: XrayScanProgress = { 150 | setPercentage(percentage: number): void { 151 | // Add progress 152 | }, 153 | } as XrayScanProgress; 154 | 155 | jfrogClient.xray().scan().graph({ 156 | component_id: 'root-node', 157 | nodes: [{component_id: 'npm://express:4.0.0'}, {component_id: 'npm://request:2.0.0'}] 158 | }, progress, () => { /* if (something) throw Error('Aborted')*/ }, 'projectKey', []) 159 | .then(result => { 160 | console.log(JSON.stringify(result)); 161 | }) 162 | .catch(error => { 163 | console.error(error); 164 | }); 165 | ``` 166 | 167 | #### Scanning a Dependency Tree with Consideration to the Xray Watches 168 | 169 | ```javascript 170 | const progress: XrayScanProgress = { 171 | setPercentage(percentage: number): void { 172 | // Add progress 173 | }, 174 | } as XrayScanProgress; 175 | 176 | jfrogClient.xray().scan().graph({ 177 | component_id: 'root-node', 178 | nodes: [{component_id: 'npm://express:4.0.0'}, {component_id: 'npm://request:2.0.0'}] 179 | }, progress, () => { /* if (something) throw Error('Aborted')*/ }, '', ['watch-1', 'watch-2']) 180 | .then(result => { 181 | console.log(JSON.stringify(result)); 182 | }) 183 | .catch(error => { 184 | console.error(error); 185 | }); 186 | ``` 187 | 188 | #### Retrieving Xray Build Details 189 | 190 | ```javascript 191 | jfrogClient 192 | .xray() 193 | .details() 194 | .build('Build Name', '1', 'Optional Project Key') 195 | .then((result) => { 196 | console.log(JSON.stringify(result)); 197 | }) 198 | .catch((error) => { 199 | console.error(error); 200 | }); 201 | ``` 202 | 203 | #### Retrieving JAS configuration 204 | ```javascript 205 | jfrogClient 206 | .xray() 207 | .jasconfig() 208 | .getJasConfig() 209 | .then((result) => { 210 | console.log(JSON.stringify(result)); 211 | }) 212 | .catch((error) => { 213 | console.error(error); 214 | }); 215 | ``` 216 | 217 | ### Artifactory 218 | 219 | #### Pinging Artifactory 220 | 221 | ```javascript 222 | jfrogClient 223 | .artifactory() 224 | .system() 225 | .ping() 226 | .then((result) => { 227 | console.log(result); 228 | }) 229 | .catch((error) => { 230 | console.error(error); 231 | }); 232 | ``` 233 | 234 | #### Getting Artifactory Version 235 | 236 | ```javascript 237 | jfrogClient 238 | .artifactory() 239 | .system() 240 | .version() 241 | .then((result) => { 242 | console.log(result); 243 | }) 244 | .catch((error) => { 245 | console.error(error); 246 | }); 247 | ``` 248 | 249 | #### Downloading an Artifact 250 | 251 | ```javascript 252 | jfrogClient 253 | .artifactory() 254 | .download() 255 | .downloadArtifact('path/to/artifact') 256 | .then((result) => { 257 | console.log(JSON.stringify(result)); 258 | }) 259 | .catch((error) => { 260 | console.error(error); 261 | }); 262 | ``` 263 | 264 | #### Downloading an Artifact content 265 | 266 | The content of the Artifact will be returned as a string. 267 | 268 | ```javascript 269 | jfrogClient 270 | .artifactory() 271 | .download() 272 | .downloadArtifact('path/to/artifact') 273 | .then((result) => { 274 | console.log(JSON.stringify(result)); 275 | }) 276 | .catch((error) => { 277 | console.error(error); 278 | }); 279 | ``` 280 | 281 | #### Downloading an Artifact to file 282 | 283 | ```javascript 284 | jfrogClient 285 | .artifactory() 286 | .download() 287 | .downloadArtifactToFile('path/to/artifact', 'local/path/to/download') 288 | .then((result) => { 289 | console.log(JSON.stringify(result)); 290 | }) 291 | .catch((error) => { 292 | console.error(error); 293 | }); 294 | ``` 295 | 296 | #### Downloading an Artifact checksum 297 | 298 | ```javascript 299 | jfrogClient 300 | .artifactory() 301 | .download() 302 | .getArtifactChecksum('path/to/artifact') 303 | .then((result) => { 304 | console.log('sha1:' + result.sha1 + 'sha256:' + result.sha256 + 'md5:' + result.md5); 305 | }) 306 | .catch((error) => { 307 | console.error(error); 308 | }); 309 | ``` 310 | 311 | #### Searching by AQL 312 | 313 | ```javascript 314 | jfrogClient.artifactory() 315 | .search() 316 | .aqlSearch( 317 | 'items.find({' + 318 | '"repo":"my-repo-name",' + 319 | '"path":{"$match":"*"}}' + 320 | ').include("name","repo","path","created").sort({"$desc":["created"]}).limit(10)' 321 | ); 322 | .then(result => { 323 | console.log(JSON.stringify(result)); 324 | }) 325 | .catch(error => { 326 | console.error(error); 327 | }); 328 | ``` 329 | 330 | ### Platform 331 | 332 | #### Web Login 333 | 334 | ##### Register For Web Login 335 | 336 | ```javascript 337 | const sessionId = XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX // UUID 338 | jfrogClient 339 | .platform() 340 | .webLogin() 341 | .registerSessionId(sessionId) 342 | .then((result) => { 343 | ... 344 | }) 345 | .catch((error) => { 346 | ... 347 | }); 348 | ``` 349 | 350 | ##### Get Access Token From Web Login 351 | 352 | ```javascript 353 | const sessionId = XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX // UUID 354 | jfrogClient 355 | .platform() 356 | .webLogin() 357 | .getToken(sessionId) 358 | .then((result) => { 359 | ... 360 | }) 361 | .catch((error) => { 362 | ... 363 | }); 364 | ``` 365 | 366 | Please note that you need to replace 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' with the actual session ID that you've generated for `registerSessionId`. 367 | 368 | ### Xray Source Control 369 | 370 | #### System 371 | 372 | ##### Getting Xsc Version 373 | 374 | ```javascript 375 | jfrogClient 376 | .xsc() 377 | .system() 378 | .version() 379 | .then((result) => { 380 | console.log(result); 381 | }) 382 | .catch((error) => { 383 | console.error(error); 384 | }); 385 | ``` 386 | 387 | #### Event 388 | 389 | ##### Sending Log Message Event 390 | 391 | ```javascript 392 | jfrogClient 393 | .xsc() 394 | .event() 395 | .log({log_level: 'error', source: 'js-client', message: 'error message to report as an event'}) 396 | .catch((error) => { 397 | console.error(error); 398 | }); 399 | ``` 400 | 401 | ##### Sending Start Scan Event 402 | 403 | ```javascript 404 | jfrogClient 405 | .xsc() 406 | .event() 407 | .startScan({product: 'product', os_platform: 'windows', jfrog_user: 'user-name'}) 408 | .then((result) => { 409 | console.log(result); 410 | }) 411 | .catch((error) => { 412 | console.error(error); 413 | }); 414 | ``` 415 | 416 | ##### Sending End Scan Event 417 | 418 | ```javascript 419 | const scanEvent = {multi_scan_id: 'some-scan-id', event_status: 'completed'} 420 | jfrogClient 421 | .xsc() 422 | .event() 423 | .endScan({product: 'product', os_platform: 'windows', jfrog_user: 'user-name'}) 424 | .then((result) => { 425 | console.log(result); 426 | }) 427 | .catch((error) => { 428 | console.error(error); 429 | }); 430 | ``` 431 | 432 | ##### Getting Scan Event Details 433 | 434 | ```javascript 435 | const multiScanId = XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX // UUID 436 | jfrogClient 437 | .xsc() 438 | .event() 439 | .getScanEvent(multiScanId) 440 | .then((result) => { 441 | ... 442 | }) 443 | .catch((error) => { 444 | ... 445 | }); 446 | ``` 447 | 448 | Please note that you need to replace 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' with the actual multi scan ID that you've generated with `startScan`. 449 | --------------------------------------------------------------------------------