snyk 1.940.0 → 1.941.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -12
- package/dist/cli/519.index.js +5 -9
- package/dist/cli/519.index.js.map +1 -1
- package/dist/cli/663.index.js +1 -1
- package/dist/cli/663.index.js.map +1 -1
- package/dist/cli/895.index.js +11 -11
- package/dist/cli/895.index.js.map +1 -1
- package/dist/cli/935.index.js +5 -5
- package/dist/cli/935.index.js.map +1 -1
- package/dist/cli/commands/test/iac/local-execution/{oci-pull.d.ts → rules/oci-pull.d.ts} +2 -2
- package/dist/cli/commands/test/iac/local-execution/{rules.d.ts → rules/rules.d.ts} +2 -2
- package/dist/lib/iac/drift/driftctl.d.ts +1 -1
- package/help/cli-commands/apps.md +2 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -160,18 +160,7 @@ scoop install snyk
|
|
|
160
160
|
|
|
161
161
|
### Snyk CLI in a Docker image
|
|
162
162
|
|
|
163
|
-
Snyk CLI can also be run from a Docker image. Snyk offers multiple Docker
|
|
164
|
-
|
|
165
|
-
These images wrap the Snyk CLI and depending on the Tag come with a relevant tooling for different projects. For example scanning a Gradle project with snyk/snyk-cli:
|
|
166
|
-
|
|
167
|
-
```bash
|
|
168
|
-
docker run -it
|
|
169
|
-
-e "SNYK_TOKEN=<TOKEN>"
|
|
170
|
-
-e "USER_ID=1234"
|
|
171
|
-
-v "<PROJECT_DIRECTORY>:/project"
|
|
172
|
-
-v "/home/user/.gradle:/home/node/.gradle"
|
|
173
|
-
snyk/snyk-cli:gradle-5.4 test --org=my-org-name
|
|
174
|
-
```
|
|
163
|
+
Snyk CLI can also be run from a Docker image. Snyk offers multiple Docker tags under [`snyk/snyk`](https://hub.docker.com/r/snyk/snyk). These images wrap the Snyk CLI and depending on the Tag come with a relevant tooling for different projects. [See the snyk/images on GitHub for more details and examples](https://github.com/snyk/snyk-images).
|
|
175
164
|
|
|
176
165
|
</details>
|
|
177
166
|
|
package/dist/cli/519.index.js
CHANGED
|
@@ -104,7 +104,7 @@ const tar = __webpack_require__(97998);
|
|
|
104
104
|
const path = __webpack_require__(85622);
|
|
105
105
|
const crypto = __webpack_require__(76417);
|
|
106
106
|
const local_cache_1 = __webpack_require__(50089);
|
|
107
|
-
const oci_pull_1 = __webpack_require__(
|
|
107
|
+
const oci_pull_1 = __webpack_require__(166);
|
|
108
108
|
const fs_1 = __webpack_require__(35747);
|
|
109
109
|
const path_1 = __webpack_require__(85622);
|
|
110
110
|
function hashData(s) {
|
|
@@ -401,7 +401,7 @@ exports.calculatePercentage = (relativeValue, totalValue) => +(totalValue ? (rel
|
|
|
401
401
|
|
|
402
402
|
/***/ }),
|
|
403
403
|
|
|
404
|
-
/***/
|
|
404
|
+
/***/ 166:
|
|
405
405
|
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
|
|
406
406
|
|
|
407
407
|
|
|
@@ -424,23 +424,19 @@ function extractOCIRegistryURLComponents(OCIRegistryURL) {
|
|
|
424
424
|
? OCIRegistryURL.split('://')[1]
|
|
425
425
|
: OCIRegistryURL;
|
|
426
426
|
const firstSlashIdx = urlWithoutProtocol.indexOf('/');
|
|
427
|
-
if (firstSlashIdx === -1) {
|
|
428
|
-
throw new InvalidRemoteRegistryURLError(OCIRegistryURL);
|
|
429
|
-
}
|
|
430
427
|
const [registryHost, repoWithTag] = [
|
|
431
428
|
urlWithoutProtocol.substring(0, firstSlashIdx),
|
|
432
429
|
urlWithoutProtocol.substring(firstSlashIdx + 1),
|
|
433
430
|
];
|
|
434
|
-
if (!registryHost || !repoWithTag) {
|
|
435
|
-
throw new InvalidRemoteRegistryURLError(OCIRegistryURL);
|
|
436
|
-
}
|
|
437
431
|
const [repo, tag = 'latest'] = repoWithTag.split(':');
|
|
438
|
-
if (!repo) {
|
|
432
|
+
if (firstSlashIdx === -1 || !registryHost || !repoWithTag || !repo) {
|
|
439
433
|
throw new InvalidRemoteRegistryURLError(OCIRegistryURL);
|
|
440
434
|
}
|
|
441
435
|
return { registryBase: registryHost, repo, tag };
|
|
442
436
|
}
|
|
443
437
|
catch {
|
|
438
|
+
// if one of the String functions in the try throws,
|
|
439
|
+
// we wrap it in our own error
|
|
444
440
|
throw new InvalidRemoteRegistryURLError(OCIRegistryURL);
|
|
445
441
|
}
|
|
446
442
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"519.index.js","mappings":";;;;;;;;;;;AAAA,2CAAgF;AAChF,6CAA0D;AAC1D,gDAAmD;AACnD,gDAAgE;AAEhE,6CAAwE;AAExE,SAAgB,eAAe,CAC7B,gBAAmC,EACnC,IAGC;IAED,IAAI,gBAAgB,GAAG,CAAC,CAAC;IACzB,MAAM,2BAA2B,GAAqC,EAAE,CAAC;IACzE,IAAI,0BAA0B,GAAG,CAAC,CAAC;IACnC,MAAM,oBAAoB,GAA2B,EAAE,CAAC;IACxD,MAAM,eAAe,GAAG,KAAK,EAAU,CAAC;IAExC,gBAAgB,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;;QAC/B,gBAAgB;YACd,CAAC,gBAAgB,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC;QAEjE,MAAM,WAAW,GAAG,GAAG,CAAC,cAAc,CAAC;QACvC,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAClC,oBAAoB,CAAC,WAAW,CAAC,SAAG,oBAAoB,CAAC,WAAW,CAAC,mCAAI;YACvE,KAAK,EAAE,CAAC;SACT,CAAC;QACF,oBAAoB,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;QAE7C,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC/C,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;gBAChD,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,C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AAC;CACF;AARD,sEAQC;AAED,MAAa,iCAAkC,SAAQ,oBAAW;IAChE,YAAY,OAAgB;QAC1B,KAAK,CAAC,OAAO,IAAI,iCAAiC,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,qBAAa,CAAC,6BAA6B,CAAC;QACxD,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,oCAAoC,OAAO,2DAA2D,CAAC;IAC5H,CAAC;CACF;AAPD,8EAOC;AAED,MAAa,6BAA8B,SAAQ,oBAAW;IAC5D,YAAY,GAAY;QACtB,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,GAAG,qBAAa,CAAC,6BAA6B,CAAC;QACxD,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,mCACjB,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,EACvB,qCAAqC,CAAC;IACxC,CAAC;CACF;AATD,sEASC;AAED,MAAa,+BAAgC,SAAQ,oBAAW;IAC9D,YAAY,WAAmB;QAC7B,KAAK,CAAC,wCAAwC,WAAW,cAAc,CAAC,CAAC;QACzE,IAAI,CAAC,IAAI,GAAG,qBAAa,CAAC,+BAA+B,CAAC;QAC1D,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,8GAA8G,CAAC;IACpI,CAAC;CACF;AAPD,0EAOC","sources":["webpack://snyk/./src/cli/commands/test/iac/local-execution/analytics.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/file-utils.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/local-cache.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/math-utils.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/oci-pull.ts"],"sourcesContent":["import { FormattedResult, PerformanceAnalyticsKey, RulesOrigin } from './types';\nimport * as analytics from '../../../../../lib/analytics';\nimport { calculatePercentage } from './math-utils';\nimport { computeCustomRulesBundleChecksum } from './file-utils';\nimport { DescribeOptions, DriftAnalysis } from '../../../../../lib/iac/types';\nimport { driftctlVersion } from '../../../../../lib/iac/drift/driftctl';\n\nexport function addIacAnalytics(\n formattedResults: FormattedResult[],\n opts: {\n ignoredIssuesCount: number;\n rulesOrigin: RulesOrigin;\n },\n): void {\n let totalIssuesCount = 0;\n const customRulesIdsFoundInIssues: { [customRuleId: string]: true } = {};\n let issuesFromCustomRulesCount = 0;\n const projectTypeAnalytics: Record<string, object> = {};\n const packageManagers = Array<string>();\n\n formattedResults.forEach((res) => {\n totalIssuesCount =\n (totalIssuesCount || 0) + res.result.cloudConfigResults.length;\n\n const projectType = res.packageManager;\n packageManagers.push(projectType);\n projectTypeAnalytics[projectType] = projectTypeAnalytics[projectType] ?? {\n count: 0,\n };\n projectTypeAnalytics[projectType]['count']++;\n\n res.result.cloudConfigResults.forEach((policy) => {\n projectTypeAnalytics[projectType][policy.severity] =\n (projectTypeAnalytics[projectType][policy.severity] || 0) + 1;\n\n if (policy.isGeneratedByCustomRule) {\n issuesFromCustomRulesCount++;\n customRulesIdsFoundInIssues[policy.publicId] = true;\n }\n });\n });\n\n const uniqueCustomRulesCount: number = Object.keys(\n customRulesIdsFoundInIssues,\n ).length;\n\n analytics.add('packageManager', Array.from(new Set(packageManagers)));\n analytics.add('iac-issues-count', totalIssuesCount);\n analytics.add('iac-ignored-issues-count', opts.ignoredIssuesCount);\n analytics.add('iac-type', projectTypeAnalytics);\n analytics.add('iac-metrics', performanceAnalyticsObject);\n analytics.add('iac-test-count', formattedResults.length); // TODO: remove this once we all analytics use iac-files-count\n analytics.add('iac-files-count', formattedResults.length);\n analytics.add(\n 'iac-local-custom-rules',\n opts.rulesOrigin === RulesOrigin.Local,\n );\n analytics.add(\n 'iac-remote-custom-rules',\n opts.rulesOrigin === RulesOrigin.Remote,\n );\n analytics.add('iac-custom-rules-issues-count', issuesFromCustomRulesCount);\n analytics.add(\n 'iac-custom-rules-issues-percentage',\n calculatePercentage(issuesFromCustomRulesCount, totalIssuesCount),\n );\n analytics.add(\n 'iac-custom-rules-checksum',\n computeCustomRulesBundleChecksum(),\n );\n analytics.add('iac-custom-rules-coverage-count', uniqueCustomRulesCount);\n}\n\nexport const performanceAnalyticsObject: Record<\n PerformanceAnalyticsKey,\n number | null\n> = {\n [PerformanceAnalyticsKey.InitLocalCache]: null,\n [PerformanceAnalyticsKey.FileLoading]: null,\n [PerformanceAnalyticsKey.FileParsing]: null,\n [PerformanceAnalyticsKey.FileScanning]: null,\n [PerformanceAnalyticsKey.OrgSettings]: null,\n [PerformanceAnalyticsKey.CustomSeverities]: null,\n [PerformanceAnalyticsKey.ResultFormatting]: null,\n [PerformanceAnalyticsKey.UsageTracking]: null,\n [PerformanceAnalyticsKey.CacheCleanup]: null,\n [PerformanceAnalyticsKey.Total]: null,\n};\n\nexport function addIacDriftAnalytics(\n analysis: DriftAnalysis,\n options: DescribeOptions,\n): void {\n analytics.add('iac-drift-coverage', analysis.coverage);\n analytics.add('iac-drift-total-resources', analysis.summary.total_resources);\n analytics.add('iac-drift-total-unmanaged', analysis.summary.total_unmanaged);\n analytics.add('iac-drift-total-managed', analysis.summary.total_managed);\n analytics.add('iac-drift-total-missing', analysis.summary.total_missing);\n analytics.add('iac-drift-total-changed', analysis.summary.total_changed);\n analytics.add(\n 'iac-drift-iac-source-count',\n analysis.summary.total_iac_source_count,\n );\n analytics.add('iac-drift-provider-name', analysis.provider_name);\n analytics.add('iac-drift-provider-version', analysis.provider_version);\n analytics.add('iac-drift-version', driftctlVersion);\n analytics.add('iac-drift-scan-duration', analysis.scan_duration);\n\n let scope = 'all';\n if (options['only-managed']) {\n scope = 'managed';\n } else if (options['only-unmanaged']) {\n scope = 'unmanaged';\n }\n analytics.add('iac-drift-scan-scope', scope);\n}\n","import * as fs from 'fs';\nimport * as tar from 'tar';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport {\n FailedToInitLocalCacheError,\n LOCAL_POLICY_ENGINE_DIR,\n} from './local-cache';\nimport { CUSTOM_RULES_TARBALL } from './oci-pull';\nimport { readdirSync } from 'fs';\nimport { join } from 'path';\n\nfunction hashData(s: string): string {\n const hashedData = crypto\n .createHash('sha1')\n .update(s)\n .digest('hex');\n return hashedData;\n}\n\nexport function createIacDir(): void {\n // this path will be able to be customised by the user in the future\n const iacPath: fs.PathLike = path.join(LOCAL_POLICY_ENGINE_DIR);\n try {\n if (!fs.existsSync(iacPath)) {\n fs.mkdirSync(iacPath, '700');\n }\n fs.accessSync(iacPath, fs.constants.W_OK);\n } catch {\n throw new FailedToInitLocalCacheError();\n }\n}\n\nexport function extractBundle(response: NodeJS.ReadableStream): Promise<void> {\n return new Promise((resolve, reject) => {\n response\n .on('error', reject)\n .pipe(\n tar.x({\n C: path.join(LOCAL_POLICY_ENGINE_DIR),\n }),\n )\n .on('finish', resolve)\n .on('error', reject);\n });\n}\n\nexport function isValidBundle(wasmPath: string, dataPath: string): boolean {\n try {\n // verify that the correct files were generated, since this is user input\n return !(!fs.existsSync(wasmPath) || !fs.existsSync(dataPath));\n } catch {\n return false;\n }\n}\n\nexport function computeCustomRulesBundleChecksum(): string | undefined {\n try {\n const customRulesPolicyWasmPath = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n CUSTOM_RULES_TARBALL,\n );\n // if bundle is not configured we don't want to include the checksum\n if (!fs.existsSync(customRulesPolicyWasmPath)) {\n return;\n }\n const policyWasm = fs.readFileSync(customRulesPolicyWasmPath, 'utf8');\n return hashData(policyWasm);\n } catch (err) {\n return;\n }\n}\n\n/**\n * makeFileAndDirectoryGenerator is a generator function that helps walking the directory and file structure of this pathToScan\n * @param root\n * @param maxDepth? - An optional `maxDepth` argument can be provided to limit how deep in the file tree the search will go.\n * @returns {Generator<object>} - a generator which yields an object with directories or paths for the path to scan\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function* makeFileAndDirectoryGenerator(root = '.', maxDepth?: number) {\n function* generatorHelper(pathToScan, currentDepth) {\n {\n yield { directory: pathToScan };\n }\n if (maxDepth !== currentDepth) {\n for (const dirent of readdirSync(pathToScan, { withFileTypes: true })) {\n if (\n dirent.isDirectory() &&\n fs.readdirSync(join(pathToScan, dirent.name)).length !== 0\n ) {\n yield* generatorHelper(\n join(pathToScan, dirent.name),\n currentDepth + 1,\n );\n } else if (dirent.isFile()) {\n yield {\n file: {\n dir: pathToScan,\n fileName: join(pathToScan, dirent.name),\n },\n };\n }\n }\n }\n }\n yield* generatorHelper(root, 0);\n}\n","import * as path from 'path';\nimport * as fs from 'fs';\nimport { EngineType, IaCErrorCodes } from './types';\nimport * as needle from 'needle';\nimport * as rimraf from 'rimraf';\nimport { createIacDir, extractBundle, isValidBundle } from './file-utils';\nimport * as Debug from 'debug';\nimport { CustomError } from '../../../../../lib/errors';\nimport * as analytics from '../../../../../lib/analytics';\nimport ReadableStream = NodeJS.ReadableStream;\nimport { getErrorStringCode } from './error-utils';\nimport config from '../../../../../lib/config';\n\nconst debug = Debug('iac-local-cache');\n\nexport const LOCAL_POLICY_ENGINE_DIR = '.iac-data';\n\nconst KUBERNETES_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'k8s_policy.wasm',\n);\nconst KUBERNETES_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'k8s_data.json',\n);\nconst TERRAFORM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'tf_policy.wasm',\n);\nconst TERRAFORM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'tf_data.json',\n);\nconst CLOUDFORMATION_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'cloudformation_policy.wasm',\n);\nconst CLOUDFORMATION_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'cloudformation_data.json',\n);\nconst ARM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'arm_policy.wasm',\n);\nconst ARM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'arm_data.json',\n);\n\n// NOTE: The filenames used for the custom policy bundles match those output\n// by the `opa` CLI tool, which is why they are very generic.\nexport const CUSTOM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'policy.wasm',\n);\nconst CUSTOM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'data.json',\n);\n\nexport function assertNever(value: never): never {\n throw new Error(\n `Unhandled discriminated union member: ${JSON.stringify(value)}`,\n );\n}\n\nexport function getLocalCachePath(engineType: EngineType): string[] {\n switch (engineType) {\n case EngineType.Kubernetes:\n return [\n `${process.cwd()}/${KUBERNETES_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${KUBERNETES_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.Terraform:\n return [\n `${process.cwd()}/${TERRAFORM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${TERRAFORM_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.CloudFormation:\n return [\n `${process.cwd()}/${CLOUDFORMATION_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${CLOUDFORMATION_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.ARM:\n return [\n `${process.cwd()}/${ARM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${ARM_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.Custom:\n return [\n `${process.cwd()}/${CUSTOM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${CUSTOM_POLICY_ENGINE_DATA_PATH}`,\n ];\n default:\n assertNever(engineType);\n }\n}\n\nexport async function initLocalCache({\n customRulesPath,\n}: { customRulesPath?: string } = {}): Promise<void> {\n try {\n createIacDir();\n } catch (e) {\n throw new FailedToInitLocalCacheError();\n }\n\n // Attempt to extract the custom rules from the path provided.\n if (customRulesPath) {\n if (!fs.existsSync(customRulesPath)) {\n throw new InvalidCustomRulesPath(customRulesPath);\n }\n\n try {\n const response = fs.createReadStream(customRulesPath);\n await extractBundle(response);\n } catch (e) {\n throw new FailedToExtractCustomRulesError(customRulesPath);\n }\n\n if (\n !isValidBundle(\n CUSTOM_POLICY_ENGINE_WASM_PATH,\n CUSTOM_POLICY_ENGINE_DATA_PATH,\n )\n ) {\n throw new InvalidCustomRules(customRulesPath);\n }\n }\n\n // IAC_BUNDLE_PATH is a developer setting that is not useful to most users. It\n // is not a replacement for custom rules.\n if (config.IAC_BUNDLE_PATH) {\n const stream = fs.createReadStream(config.IAC_BUNDLE_PATH);\n await extractBundle(stream);\n return;\n }\n\n // We extract the Snyk rules after the custom rules to ensure our files\n // always overwrite whatever might be there.\n try {\n const BUNDLE_URL = 'https://static.snyk.io/cli/wasm/bundle.tar.gz';\n const response: ReadableStream = needle.get(BUNDLE_URL);\n await extractBundle(response);\n } catch (e) {\n throw new FailedToDownloadRulesError();\n }\n}\n\nexport function cleanLocalCache() {\n // path to delete is hardcoded for now\n const iacPath: fs.PathLike = path.join(\n `${process.cwd()}`,\n LOCAL_POLICY_ENGINE_DIR,\n );\n try {\n // when we support Node version >= 12.10.0 , we can replace rimraf\n // with the native fs.rmdirSync(path, {recursive: true})\n rimraf.sync(iacPath);\n } catch (e) {\n const err = new FailedToCleanLocalCacheError();\n analytics.add('error-code', err.code);\n debug('The local cache directory could not be deleted');\n }\n}\n\nexport class FailedToInitLocalCacheError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to initialize local cache');\n this.code = IaCErrorCodes.FailedToInitLocalCacheError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to create a local directory to store the test assets, please ensure that the current working directory is writable';\n }\n}\n\nexport class FailedToDownloadRulesError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to download policies');\n this.code = IaCErrorCodes.FailedToDownloadRulesError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to download the security rules, please ensure the network can access https://static.snyk.io';\n }\n}\n\nexport class FailedToExtractCustomRulesError extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Failed to download policies');\n this.code = IaCErrorCodes.FailedToExtractCustomRulesError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The provided bundle may be corrupted or invalid. Please ensure it was generated using the 'snyk-iac-rules' SDK`;\n }\n}\n\nexport class InvalidCustomRules extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Invalid custom rules bundle');\n this.code = IaCErrorCodes.InvalidCustomRules;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The provided bundle does not match the required structure. Please ensure it was generated using the 'snyk-iac-rules' SDK`;\n }\n}\n\nexport class InvalidCustomRulesPath extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Invalid path to custom rules bundle');\n this.code = IaCErrorCodes.InvalidCustomRulesPath;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The bundle at the provided path does not exist`;\n }\n}\n\nclass FailedToCleanLocalCacheError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to clean local cache');\n this.code = IaCErrorCodes.FailedToCleanLocalCacheError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = ''; // Not a user facing error.\n }\n}\n","/**\n * Calculate percentage from relative and total amounts.\n * @param relativeValue The relative amount.\n * @param totalValue The total amount.\n * @returns The calculated precentage.\n */\nexport const calculatePercentage = (\n relativeValue: number,\n totalValue: number,\n): number => +(totalValue ? (relativeValue / totalValue) * 100 : 0).toFixed(2);\n","import * as registryClient from '@snyk/docker-registry-v2-client';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport {\n IaCErrorCodes,\n ImageManifest,\n ManifestConfig,\n OCIPullOptions,\n OCIRegistryURLComponents,\n} from './types';\nimport { CustomError } from '../../../../../lib/errors';\nimport { getErrorStringCode } from './error-utils';\nimport { LOCAL_POLICY_ENGINE_DIR } from './local-cache';\nimport * as Debug from 'debug';\nimport { createIacDir } from './file-utils';\nconst debug = Debug('iac-oci-pull');\n\nexport const CUSTOM_RULES_TARBALL = 'custom-bundle.tar.gz';\n\nexport function extractOCIRegistryURLComponents(\n OCIRegistryURL: string,\n): OCIRegistryURLComponents {\n try {\n const urlWithoutProtocol = OCIRegistryURL.includes('://')\n ? OCIRegistryURL.split('://')[1]\n : OCIRegistryURL;\n\n const firstSlashIdx = urlWithoutProtocol.indexOf('/');\n if (firstSlashIdx === -1) {\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n\n const [registryHost, repoWithTag] = [\n urlWithoutProtocol.substring(0, firstSlashIdx),\n urlWithoutProtocol.substring(firstSlashIdx + 1),\n ];\n if (!registryHost || !repoWithTag) {\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n\n const [repo, tag = 'latest'] = repoWithTag.split(':');\n if (!repo) {\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n\n return { registryBase: registryHost, repo, tag };\n } catch {\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n}\n\n/**\n * Downloads an OCI Artifact from a remote OCI Registry and writes it to the disk.\n * The artifact here is a custom rules bundle stored in a remote registry.\n * In order to do that, it calls an external docker registry v2 client to get the manifests, the layers and then builds the artifact.\n * Example: https://github.com/opencontainers/image-spec/blob/main/manifest.md#example-image-manifest\n * @param OCIRegistryURL - the URL where the custom rules bundle is stored\n * @param opt????? (optional) - object that holds the credentials and other metadata required for the registry-v2-client\n **/\nexport async function pull(\n { registryBase, repo, tag }: OCIRegistryURLComponents,\n opt?: OCIPullOptions,\n): Promise<string> {\n const manifest: ImageManifest = await registryClient.getManifest(\n registryBase,\n repo,\n tag,\n opt?.username,\n opt?.password,\n opt?.reqOptions,\n );\n if (manifest.schemaVersion !== 2) {\n throw new InvalidManifestSchemaVersionError(\n manifest.schemaVersion.toString(),\n );\n }\n const manifestLayers: ManifestConfig[] = manifest.layers;\n // We assume that we will always have an artifact of a single layer\n if (manifestLayers.length > 1) {\n debug('There were more than one layers found in the OCI Artifact.');\n }\n const blob = await registryClient.getLayer(\n registryBase,\n repo,\n manifestLayers[0].digest,\n opt?.username,\n opt?.password,\n opt?.reqOptions,\n );\n\n try {\n const downloadPath: string = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n CUSTOM_RULES_TARBALL,\n );\n createIacDir();\n await fs.writeFile(downloadPath, blob);\n return downloadPath;\n } catch (err) {\n throw new FailedToBuildOCIArtifactError();\n }\n}\n\nexport class FailedToBuildOCIArtifactError extends CustomError {\n constructor(message?: string) {\n super(message || 'Could not build OCI Artifact');\n this.code = IaCErrorCodes.FailedToBuildOCIArtifactError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to build the remote OCI Artifact locally, please ensure that the local directory is writeable.';\n }\n}\n\nexport class InvalidManifestSchemaVersionError extends CustomError {\n constructor(message?: string) {\n super(message || 'Invalid manifest schema version');\n this.code = IaCErrorCodes.InvalidRemoteRegistryURLError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `Invalid manifest schema version: ${message}. We currently support Image Manifest Version 2, Schema 2`;\n }\n}\n\nexport class InvalidRemoteRegistryURLError extends CustomError {\n constructor(url?: string) {\n super('Invalid URL for Remote Registry');\n this.code = IaCErrorCodes.InvalidRemoteRegistryURLError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `The provided remote registry URL${\n url ? `: \"${url}\"` : ''\n } is invalid. Please check it again.`;\n }\n}\n\nexport class UnsupportedEntitlementPullError extends CustomError {\n constructor(entitlement: string) {\n super(`OCI Pull not supported - Missing the ${entitlement} entitlement`);\n this.code = IaCErrorCodes.UnsupportedEntitlementPullError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `The custom rules feature is currently not supported for this org. To enable it, please contact snyk support.`;\n }\n}\n"],"names":[],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"519.index.js","mappings":";;;;;;;;;;;AAAA,2CAAgF;AAChF,6CAA0D;AAC1D,gDAAmD;AACnD,gDAAgE;AAEhE,6CAAwE;AAExE,SAAgB,eAAe,CAC7B,gBAAmC,EACnC,IAGC;IAED,IAAI,gBAAgB,GAAG,CAAC,CAAC;IACzB,MAAM,2BAA2B,GAAqC,EAAE,CAAC;IACzE,IAAI,0BAA0B,GAAG,CAAC,CAAC;IACnC,MAAM,oBAAoB,GAA2B,EAAE,CAAC;IACxD,MAAM,eAAe,GAAG,KAAK,EAAU,CAAC;IAExC,gBAAgB,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;;QAC/B,gBAAgB;YACd,CAAC,gBAAgB,IAAI,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,MAAM,CAAC;QAEjE,MAAM,WAAW,GAAG,GAAG,CAAC,cAAc,CAAC;QACvC,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAClC,oBAAoB,CAAC,WAAW,CAAC,SAAG,oBAAoB,CAAC,WAAW,CAAC,mCAAI;YACvE,KAAK,EAAE,CAAC;SACT,CAAC;QACF,oBAAoB,CAAC,WAAW,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;QAE7C,GAAG,CAAC,MAAM,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC/C,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC;gBAChD,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;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qBAAa,CAAC,6BAA6B,CAAC;QACxD,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,oCAAoC,OAAO,2DAA2D,CAAC;IAC5H,CAAC;CACF;AAPD,8EAOC;AAED,MAAa,6BAA8B,SAAQ,oBAAW;IAC5D,YAAY,GAAY;QACtB,KAAK,CAAC,iCAAiC,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,GAAG,qBAAa,CAAC,6BAA6B,CAAC;QACxD,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,mCACjB,GAAG,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,EACvB,qCAAqC,CAAC;IACxC,CAAC;CACF;AATD,sEASC;AAED,MAAa,+BAAgC,SAAQ,oBAAW;IAC9D,YAAY,WAAmB;QAC7B,KAAK,CAAC,wCAAwC,WAAW,cAAc,CAAC,CAAC;QACzE,IAAI,CAAC,IAAI,GAAG,qBAAa,CAAC,+BAA+B,CAAC;QAC1D,IAAI,CAAC,OAAO,GAAG,gCAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,GAAG,8GAA8G,CAAC;IACpI,CAAC;CACF;AAPD,0EAOC","sources":["webpack://snyk/./src/cli/commands/test/iac/local-execution/analytics.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/file-utils.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/local-cache.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/math-utils.ts","webpack://snyk/./src/cli/commands/test/iac/local-execution/rules/oci-pull.ts"],"sourcesContent":["import { FormattedResult, PerformanceAnalyticsKey, RulesOrigin } from './types';\nimport * as analytics from '../../../../../lib/analytics';\nimport { calculatePercentage } from './math-utils';\nimport { computeCustomRulesBundleChecksum } from './file-utils';\nimport { DescribeOptions, DriftAnalysis } from '../../../../../lib/iac/types';\nimport { driftctlVersion } from '../../../../../lib/iac/drift/driftctl';\n\nexport function addIacAnalytics(\n formattedResults: FormattedResult[],\n opts: {\n ignoredIssuesCount: number;\n rulesOrigin: RulesOrigin;\n },\n): void {\n let totalIssuesCount = 0;\n const customRulesIdsFoundInIssues: { [customRuleId: string]: true } = {};\n let issuesFromCustomRulesCount = 0;\n const projectTypeAnalytics: Record<string, object> = {};\n const packageManagers = Array<string>();\n\n formattedResults.forEach((res) => {\n totalIssuesCount =\n (totalIssuesCount || 0) + res.result.cloudConfigResults.length;\n\n const projectType = res.packageManager;\n packageManagers.push(projectType);\n projectTypeAnalytics[projectType] = projectTypeAnalytics[projectType] ?? {\n count: 0,\n };\n projectTypeAnalytics[projectType]['count']++;\n\n res.result.cloudConfigResults.forEach((policy) => {\n projectTypeAnalytics[projectType][policy.severity] =\n (projectTypeAnalytics[projectType][policy.severity] || 0) + 1;\n\n if (policy.isGeneratedByCustomRule) {\n issuesFromCustomRulesCount++;\n customRulesIdsFoundInIssues[policy.publicId] = true;\n }\n });\n });\n\n const uniqueCustomRulesCount: number = Object.keys(\n customRulesIdsFoundInIssues,\n ).length;\n\n analytics.add('packageManager', Array.from(new Set(packageManagers)));\n analytics.add('iac-issues-count', totalIssuesCount);\n analytics.add('iac-ignored-issues-count', opts.ignoredIssuesCount);\n analytics.add('iac-type', projectTypeAnalytics);\n analytics.add('iac-metrics', performanceAnalyticsObject);\n analytics.add('iac-test-count', formattedResults.length); // TODO: remove this once we all analytics use iac-files-count\n analytics.add('iac-files-count', formattedResults.length);\n analytics.add(\n 'iac-local-custom-rules',\n opts.rulesOrigin === RulesOrigin.Local,\n );\n analytics.add(\n 'iac-remote-custom-rules',\n opts.rulesOrigin === RulesOrigin.Remote,\n );\n analytics.add('iac-custom-rules-issues-count', issuesFromCustomRulesCount);\n analytics.add(\n 'iac-custom-rules-issues-percentage',\n calculatePercentage(issuesFromCustomRulesCount, totalIssuesCount),\n );\n analytics.add(\n 'iac-custom-rules-checksum',\n computeCustomRulesBundleChecksum(),\n );\n analytics.add('iac-custom-rules-coverage-count', uniqueCustomRulesCount);\n}\n\nexport const performanceAnalyticsObject: Record<\n PerformanceAnalyticsKey,\n number | null\n> = {\n [PerformanceAnalyticsKey.InitLocalCache]: null,\n [PerformanceAnalyticsKey.FileLoading]: null,\n [PerformanceAnalyticsKey.FileParsing]: null,\n [PerformanceAnalyticsKey.FileScanning]: null,\n [PerformanceAnalyticsKey.OrgSettings]: null,\n [PerformanceAnalyticsKey.CustomSeverities]: null,\n [PerformanceAnalyticsKey.ResultFormatting]: null,\n [PerformanceAnalyticsKey.UsageTracking]: null,\n [PerformanceAnalyticsKey.CacheCleanup]: null,\n [PerformanceAnalyticsKey.Total]: null,\n};\n\nexport function addIacDriftAnalytics(\n analysis: DriftAnalysis,\n options: DescribeOptions,\n): void {\n analytics.add('iac-drift-coverage', analysis.coverage);\n analytics.add('iac-drift-total-resources', analysis.summary.total_resources);\n analytics.add('iac-drift-total-unmanaged', analysis.summary.total_unmanaged);\n analytics.add('iac-drift-total-managed', analysis.summary.total_managed);\n analytics.add('iac-drift-total-missing', analysis.summary.total_missing);\n analytics.add('iac-drift-total-changed', analysis.summary.total_changed);\n analytics.add(\n 'iac-drift-iac-source-count',\n analysis.summary.total_iac_source_count,\n );\n analytics.add('iac-drift-provider-name', analysis.provider_name);\n analytics.add('iac-drift-provider-version', analysis.provider_version);\n analytics.add('iac-drift-version', driftctlVersion);\n analytics.add('iac-drift-scan-duration', analysis.scan_duration);\n\n let scope = 'all';\n if (options['only-managed']) {\n scope = 'managed';\n } else if (options['only-unmanaged']) {\n scope = 'unmanaged';\n }\n analytics.add('iac-drift-scan-scope', scope);\n}\n","import * as fs from 'fs';\nimport * as tar from 'tar';\nimport * as path from 'path';\nimport * as crypto from 'crypto';\nimport {\n FailedToInitLocalCacheError,\n LOCAL_POLICY_ENGINE_DIR,\n} from './local-cache';\nimport { CUSTOM_RULES_TARBALL } from './rules/oci-pull';\nimport { readdirSync } from 'fs';\nimport { join } from 'path';\n\nfunction hashData(s: string): string {\n const hashedData = crypto\n .createHash('sha1')\n .update(s)\n .digest('hex');\n return hashedData;\n}\n\nexport function createIacDir(): void {\n // this path will be able to be customised by the user in the future\n const iacPath: fs.PathLike = path.join(LOCAL_POLICY_ENGINE_DIR);\n try {\n if (!fs.existsSync(iacPath)) {\n fs.mkdirSync(iacPath, '700');\n }\n fs.accessSync(iacPath, fs.constants.W_OK);\n } catch {\n throw new FailedToInitLocalCacheError();\n }\n}\n\nexport function extractBundle(response: NodeJS.ReadableStream): Promise<void> {\n return new Promise((resolve, reject) => {\n response\n .on('error', reject)\n .pipe(\n tar.x({\n C: path.join(LOCAL_POLICY_ENGINE_DIR),\n }),\n )\n .on('finish', resolve)\n .on('error', reject);\n });\n}\n\nexport function isValidBundle(wasmPath: string, dataPath: string): boolean {\n try {\n // verify that the correct files were generated, since this is user input\n return !(!fs.existsSync(wasmPath) || !fs.existsSync(dataPath));\n } catch {\n return false;\n }\n}\n\nexport function computeCustomRulesBundleChecksum(): string | undefined {\n try {\n const customRulesPolicyWasmPath = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n CUSTOM_RULES_TARBALL,\n );\n // if bundle is not configured we don't want to include the checksum\n if (!fs.existsSync(customRulesPolicyWasmPath)) {\n return;\n }\n const policyWasm = fs.readFileSync(customRulesPolicyWasmPath, 'utf8');\n return hashData(policyWasm);\n } catch (err) {\n return;\n }\n}\n\n/**\n * makeFileAndDirectoryGenerator is a generator function that helps walking the directory and file structure of this pathToScan\n * @param root\n * @param maxDepth? - An optional `maxDepth` argument can be provided to limit how deep in the file tree the search will go.\n * @returns {Generator<object>} - a generator which yields an object with directories or paths for the path to scan\n */\n// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types\nexport function* makeFileAndDirectoryGenerator(root = '.', maxDepth?: number) {\n function* generatorHelper(pathToScan, currentDepth) {\n {\n yield { directory: pathToScan };\n }\n if (maxDepth !== currentDepth) {\n for (const dirent of readdirSync(pathToScan, { withFileTypes: true })) {\n if (\n dirent.isDirectory() &&\n fs.readdirSync(join(pathToScan, dirent.name)).length !== 0\n ) {\n yield* generatorHelper(\n join(pathToScan, dirent.name),\n currentDepth + 1,\n );\n } else if (dirent.isFile()) {\n yield {\n file: {\n dir: pathToScan,\n fileName: join(pathToScan, dirent.name),\n },\n };\n }\n }\n }\n }\n yield* generatorHelper(root, 0);\n}\n","import * as path from 'path';\nimport * as fs from 'fs';\nimport { EngineType, IaCErrorCodes } from './types';\nimport * as needle from 'needle';\nimport * as rimraf from 'rimraf';\nimport { createIacDir, extractBundle, isValidBundle } from './file-utils';\nimport * as Debug from 'debug';\nimport { CustomError } from '../../../../../lib/errors';\nimport * as analytics from '../../../../../lib/analytics';\nimport ReadableStream = NodeJS.ReadableStream;\nimport { getErrorStringCode } from './error-utils';\nimport config from '../../../../../lib/config';\n\nconst debug = Debug('iac-local-cache');\n\nexport const LOCAL_POLICY_ENGINE_DIR = '.iac-data';\n\nconst KUBERNETES_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'k8s_policy.wasm',\n);\nconst KUBERNETES_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'k8s_data.json',\n);\nconst TERRAFORM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'tf_policy.wasm',\n);\nconst TERRAFORM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'tf_data.json',\n);\nconst CLOUDFORMATION_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'cloudformation_policy.wasm',\n);\nconst CLOUDFORMATION_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'cloudformation_data.json',\n);\nconst ARM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'arm_policy.wasm',\n);\nconst ARM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'arm_data.json',\n);\n\n// NOTE: The filenames used for the custom policy bundles match those output\n// by the `opa` CLI tool, which is why they are very generic.\nexport const CUSTOM_POLICY_ENGINE_WASM_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'policy.wasm',\n);\nconst CUSTOM_POLICY_ENGINE_DATA_PATH = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n 'data.json',\n);\n\nexport function assertNever(value: never): never {\n throw new Error(\n `Unhandled discriminated union member: ${JSON.stringify(value)}`,\n );\n}\n\nexport function getLocalCachePath(engineType: EngineType): string[] {\n switch (engineType) {\n case EngineType.Kubernetes:\n return [\n `${process.cwd()}/${KUBERNETES_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${KUBERNETES_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.Terraform:\n return [\n `${process.cwd()}/${TERRAFORM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${TERRAFORM_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.CloudFormation:\n return [\n `${process.cwd()}/${CLOUDFORMATION_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${CLOUDFORMATION_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.ARM:\n return [\n `${process.cwd()}/${ARM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${ARM_POLICY_ENGINE_DATA_PATH}`,\n ];\n case EngineType.Custom:\n return [\n `${process.cwd()}/${CUSTOM_POLICY_ENGINE_WASM_PATH}`,\n `${process.cwd()}/${CUSTOM_POLICY_ENGINE_DATA_PATH}`,\n ];\n default:\n assertNever(engineType);\n }\n}\n\nexport async function initLocalCache({\n customRulesPath,\n}: { customRulesPath?: string } = {}): Promise<void> {\n try {\n createIacDir();\n } catch (e) {\n throw new FailedToInitLocalCacheError();\n }\n\n // Attempt to extract the custom rules from the path provided.\n if (customRulesPath) {\n if (!fs.existsSync(customRulesPath)) {\n throw new InvalidCustomRulesPath(customRulesPath);\n }\n\n try {\n const response = fs.createReadStream(customRulesPath);\n await extractBundle(response);\n } catch (e) {\n throw new FailedToExtractCustomRulesError(customRulesPath);\n }\n\n if (\n !isValidBundle(\n CUSTOM_POLICY_ENGINE_WASM_PATH,\n CUSTOM_POLICY_ENGINE_DATA_PATH,\n )\n ) {\n throw new InvalidCustomRules(customRulesPath);\n }\n }\n\n // IAC_BUNDLE_PATH is a developer setting that is not useful to most users. It\n // is not a replacement for custom rules.\n if (config.IAC_BUNDLE_PATH) {\n const stream = fs.createReadStream(config.IAC_BUNDLE_PATH);\n await extractBundle(stream);\n return;\n }\n\n // We extract the Snyk rules after the custom rules to ensure our files\n // always overwrite whatever might be there.\n try {\n const BUNDLE_URL = 'https://static.snyk.io/cli/wasm/bundle.tar.gz';\n const response: ReadableStream = needle.get(BUNDLE_URL);\n await extractBundle(response);\n } catch (e) {\n throw new FailedToDownloadRulesError();\n }\n}\n\nexport function cleanLocalCache() {\n // path to delete is hardcoded for now\n const iacPath: fs.PathLike = path.join(\n `${process.cwd()}`,\n LOCAL_POLICY_ENGINE_DIR,\n );\n try {\n // when we support Node version >= 12.10.0 , we can replace rimraf\n // with the native fs.rmdirSync(path, {recursive: true})\n rimraf.sync(iacPath);\n } catch (e) {\n const err = new FailedToCleanLocalCacheError();\n analytics.add('error-code', err.code);\n debug('The local cache directory could not be deleted');\n }\n}\n\nexport class FailedToInitLocalCacheError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to initialize local cache');\n this.code = IaCErrorCodes.FailedToInitLocalCacheError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to create a local directory to store the test assets, please ensure that the current working directory is writable';\n }\n}\n\nexport class FailedToDownloadRulesError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to download policies');\n this.code = IaCErrorCodes.FailedToDownloadRulesError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to download the security rules, please ensure the network can access https://static.snyk.io';\n }\n}\n\nexport class FailedToExtractCustomRulesError extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Failed to download policies');\n this.code = IaCErrorCodes.FailedToExtractCustomRulesError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The provided bundle may be corrupted or invalid. Please ensure it was generated using the 'snyk-iac-rules' SDK`;\n }\n}\n\nexport class InvalidCustomRules extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Invalid custom rules bundle');\n this.code = IaCErrorCodes.InvalidCustomRules;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The provided bundle does not match the required structure. Please ensure it was generated using the 'snyk-iac-rules' SDK`;\n }\n}\n\nexport class InvalidCustomRulesPath extends CustomError {\n constructor(path: string, message?: string) {\n super(message || 'Invalid path to custom rules bundle');\n this.code = IaCErrorCodes.InvalidCustomRulesPath;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `We were unable to extract the rules provided at: ${path}. The bundle at the provided path does not exist`;\n }\n}\n\nclass FailedToCleanLocalCacheError extends CustomError {\n constructor(message?: string) {\n super(message || 'Failed to clean local cache');\n this.code = IaCErrorCodes.FailedToCleanLocalCacheError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = ''; // Not a user facing error.\n }\n}\n","/**\n * Calculate percentage from relative and total amounts.\n * @param relativeValue The relative amount.\n * @param totalValue The total amount.\n * @returns The calculated precentage.\n */\nexport const calculatePercentage = (\n relativeValue: number,\n totalValue: number,\n): number => +(totalValue ? (relativeValue / totalValue) * 100 : 0).toFixed(2);\n","import * as registryClient from '@snyk/docker-registry-v2-client';\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport {\n IaCErrorCodes,\n ImageManifest,\n ManifestConfig,\n OCIPullOptions,\n OCIRegistryURLComponents,\n} from '../types';\nimport { CustomError } from '../../../../../../lib/errors';\nimport { getErrorStringCode } from '../error-utils';\nimport { LOCAL_POLICY_ENGINE_DIR } from '../local-cache';\nimport * as Debug from 'debug';\nimport { createIacDir } from '../file-utils';\nconst debug = Debug('iac-oci-pull');\n\nexport const CUSTOM_RULES_TARBALL = 'custom-bundle.tar.gz';\n\nexport function extractOCIRegistryURLComponents(\n OCIRegistryURL: string,\n): OCIRegistryURLComponents {\n try {\n const urlWithoutProtocol = OCIRegistryURL.includes('://')\n ? OCIRegistryURL.split('://')[1]\n : OCIRegistryURL;\n\n const firstSlashIdx = urlWithoutProtocol.indexOf('/');\n const [registryHost, repoWithTag] = [\n urlWithoutProtocol.substring(0, firstSlashIdx),\n urlWithoutProtocol.substring(firstSlashIdx + 1),\n ];\n const [repo, tag = 'latest'] = repoWithTag.split(':');\n if (firstSlashIdx === -1 || !registryHost || !repoWithTag || !repo) {\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n return { registryBase: registryHost, repo, tag };\n } catch {\n // if one of the String functions in the try throws,\n // we wrap it in our own error\n throw new InvalidRemoteRegistryURLError(OCIRegistryURL);\n }\n}\n\n/**\n * Downloads an OCI Artifact from a remote OCI Registry and writes it to the disk.\n * The artifact here is a custom rules bundle stored in a remote registry.\n * In order to do that, it calls an external docker registry v2 client to get the manifests, the layers and then builds the artifact.\n * Example: https://github.com/opencontainers/image-spec/blob/main/manifest.md#example-image-manifest\n * @param OCIRegistryURL - the URL where the custom rules bundle is stored\n * @param opt????? (optional) - object that holds the credentials and other metadata required for the registry-v2-client\n **/\nexport async function pull(\n { registryBase, repo, tag }: OCIRegistryURLComponents,\n opt?: OCIPullOptions,\n): Promise<string> {\n const manifest: ImageManifest = await registryClient.getManifest(\n registryBase,\n repo,\n tag,\n opt?.username,\n opt?.password,\n opt?.reqOptions,\n );\n if (manifest.schemaVersion !== 2) {\n throw new InvalidManifestSchemaVersionError(\n manifest.schemaVersion.toString(),\n );\n }\n const manifestLayers: ManifestConfig[] = manifest.layers;\n // We assume that we will always have an artifact of a single layer\n if (manifestLayers.length > 1) {\n debug('There were more than one layers found in the OCI Artifact.');\n }\n const blob = await registryClient.getLayer(\n registryBase,\n repo,\n manifestLayers[0].digest,\n opt?.username,\n opt?.password,\n opt?.reqOptions,\n );\n\n try {\n const downloadPath: string = path.join(\n LOCAL_POLICY_ENGINE_DIR,\n CUSTOM_RULES_TARBALL,\n );\n createIacDir();\n await fs.writeFile(downloadPath, blob);\n return downloadPath;\n } catch (err) {\n throw new FailedToBuildOCIArtifactError();\n }\n}\n\nexport class FailedToBuildOCIArtifactError extends CustomError {\n constructor(message?: string) {\n super(message || 'Could not build OCI Artifact');\n this.code = IaCErrorCodes.FailedToBuildOCIArtifactError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage =\n 'We were unable to build the remote OCI Artifact locally, please ensure that the local directory is writeable.';\n }\n}\n\nexport class InvalidManifestSchemaVersionError extends CustomError {\n constructor(message?: string) {\n super(message || 'Invalid manifest schema version');\n this.code = IaCErrorCodes.InvalidRemoteRegistryURLError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `Invalid manifest schema version: ${message}. We currently support Image Manifest Version 2, Schema 2`;\n }\n}\n\nexport class InvalidRemoteRegistryURLError extends CustomError {\n constructor(url?: string) {\n super('Invalid URL for Remote Registry');\n this.code = IaCErrorCodes.InvalidRemoteRegistryURLError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `The provided remote registry URL${\n url ? `: \"${url}\"` : ''\n } is invalid. Please check it again.`;\n }\n}\n\nexport class UnsupportedEntitlementPullError extends CustomError {\n constructor(entitlement: string) {\n super(`OCI Pull not supported - Missing the ${entitlement} entitlement`);\n this.code = IaCErrorCodes.UnsupportedEntitlementPullError;\n this.strCode = getErrorStringCode(this.code);\n this.userMessage = `The custom rules feature is currently not supported for this org. To enable it, please contact snyk support.`;\n }\n}\n"],"names":[],"sourceRoot":""}
|
package/dist/cli/663.index.js
CHANGED
|
@@ -468,7 +468,7 @@ exports.CreateAppPromptData = {
|
|
|
468
468
|
},
|
|
469
469
|
SNYK_APP_SCOPES: {
|
|
470
470
|
name: exports.SNYK_APP_SCOPES,
|
|
471
|
-
message: `Your Snyk App's permission scopes (comma separated list. ${chalk_1.default.yellowBright(' Ex:
|
|
471
|
+
message: `Your Snyk App's permission scopes (comma separated list. ${chalk_1.default.yellowBright(' Ex: org.read,org.report.read')})?: `,
|
|
472
472
|
},
|
|
473
473
|
SNYK_APP_ORG_ID: {
|
|
474
474
|
name: exports.SNYK_APP_ORG_ID,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"663.index.js","mappings":";;;;;;;;;;;AAAA,yCAA+B;AAC/B,0CAQ2B;AAC3B,6CAA+D;AAC/D,6CAA+C;AAE/C,MAAM,KAAK,GAAG,KAAK,CAAC,qBAAc,CAAC,CAAC;AAEpC;;;;;;;GAOG;AACI,KAAK,UAAU,SAAS,CAC7B,IAAuB;IAEvB,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACxB,MAAM,EACJ,KAAK,EACL,WAAW,EAAE,IAAI,EACjB,mBAAmB,EAAE,YAAY,EACjC,aAAa,EAAE,MAAM,GACtB,GAAG,IAAI,CAAC;IACT,MAAM,OAAO,GAAG;QACd,MAAM,EAAE,MAAM;QACd,GAAG,EAAE,iBAAU,CAAC,eAAQ,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC;QAC/C,IAAI,EAAE;YACJ,IAAI;YACJ,YAAY;YACZ,MAAM;SACP;QACD,EAAE,EAAE;YACF,OAAO,EAAE,yBAAyB;SACnC;KACF,CAAC;IAEF,IAAI;QACF,MAAM,iBAAO,CAAC,wBAAwB,CAAC,CAAC;QACxC,MAAM,QAAQ,GAAG,MAAM,yBAAe,CAAqB,OAAO,CAAC,CAAC;QACpE,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChB,iBAAO,CAAC,QAAQ,EAAE,CAAC;QACnB,OAAO,yBAAkB,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AK,CAAC,IAAW,CAAM,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AApBD,0CAoBC","sources":["webpack://snyk/./src/cli/commands/apps/create-app.ts","webpack://snyk/./src/cli/commands/apps/index.ts","webpack://snyk/./src/cli/commands/help/index.ts","webpack://snyk/./src/cli/commands/help/markdown-renderer.ts","webpack://snyk/./src/cli/commands/help/reflow-text.ts","webpack://snyk/./src/cli/commands/process-command-args.ts","webpack://snyk/./src/lib/apps/constants.ts","webpack://snyk/./src/lib/apps/create-app/index.ts","webpack://snyk/./src/lib/apps/index.ts","webpack://snyk/./src/lib/apps/input-validator.ts","webpack://snyk/./src/lib/apps/prompts.ts","webpack://snyk/./src/lib/apps/rest-utils.ts","webpack://snyk/./src/lib/apps/types.ts","webpack://snyk/./src/lib/apps/utils.ts","webpack://snyk/./src/lib/request/promise.ts"],"sourcesContent":["import * as Debug from 'debug';\nimport {\n EAppsURL,\n getAppsURL,\n handleCreateAppRes,\n handleRestError,\n ICreateAppRequest,\n ICreateAppResponse,\n SNYK_APP_DEBUG,\n} from '../../../lib/apps';\nimport { makeRequestRest } from '../../../lib/request/promise';\nimport { spinner } from '../../../lib/spinner';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\n/**\n * Function to process the app creation request and\n * handle any errors that are request error and print\n * in a formatted string. It throws is error is unknown\n * or cannot be handled.\n * @param {ICreateAppRequest} data to create the app\n * @returns {String} response formatted string\n */\nexport async function createApp(\n data: ICreateAppRequest,\n): Promise<string | void> {\n debug('App data', data);\n const {\n orgId,\n snykAppName: name,\n snykAppRedirectUris: redirectUris,\n snykAppScopes: scopes,\n } = data;\n const payload = {\n method: 'POST',\n url: getAppsURL(EAppsURL.CREATE_APP, { orgId }),\n body: {\n name,\n redirectUris,\n scopes,\n },\n qs: {\n version: '2021-08-11~experimental',\n },\n };\n\n try {\n await spinner('Creating your Snyk App');\n const response = await makeRequestRest<ICreateAppResponse>(payload);\n debug(response);\n spinner.clearAll();\n return handleCreateAppRes(response);\n } catch (error) {\n spinner.clearAll();\n handleRestError(error);\n }\n}\n","import * as Debug from 'debug';\nimport { MethodArgs } from '../../args';\nimport { processCommandArgs } from '../process-command-args';\nimport {\n EValidSubCommands,\n validAppsSubCommands,\n SNYK_APP_DEBUG,\n ICreateAppOptions,\n AppsErrorMessages,\n} from '../../../lib/apps';\n\nimport { createApp } from './create-app';\n// import * as path from 'path';\nimport {\n createAppDataInteractive,\n createAppDataScriptable,\n} from '../../../lib/apps/create-app';\nimport help from '../help';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\nexport default async function apps(\n ...args0: MethodArgs\n): Promise<string | undefined | any> {\n debug('Snyk apps CLI called');\n\n const { options, paths } = processCommandArgs<ICreateAppOptions>(...args0);\n debug(options, paths);\n\n const commandVerb1 = paths[0];\n const validCommandVerb =\n commandVerb1 && validAppsSubCommands.includes(commandVerb1);\n if (!validCommandVerb) {\n // Display help md for apps\n debug(`Unknown subcommand: ${commandVerb1}`);\n return help('apps');\n }\n // Check if experimental flag is being used\n if (!options.experimental) throw new Error(AppsErrorMessages.useExperimental);\n\n if (commandVerb1 === EValidSubCommands.CREATE) {\n const createAppData = options.interactive\n ? await createAppDataInteractive()\n : createAppDataScriptable(options);\n return await createApp(createAppData);\n }\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { MethodArgs } from '../../args';\nimport { renderMarkdown } from './markdown-renderer';\n\nexport function findHelpFile(\n helpArgs: string[],\n helpFolderPath = '../../help/cli-commands', // this is a relative path from the webpack dist directory,\n): string {\n while (helpArgs.length > 0) {\n // cleanse the filename to only contain letters\n // aka: /\\W/g but figured this was easier to read\n const file = `${helpArgs.join('-').replace(/[^a-z0-9-]/gi, '')}.md`;\n const testHelpAbsolutePath = path.resolve(__dirname, helpFolderPath, file);\n if (fs.existsSync(testHelpAbsolutePath)) {\n return testHelpAbsolutePath;\n }\n helpArgs = helpArgs.slice(0, -1);\n }\n return path.resolve(__dirname, helpFolderPath, `README.md`); // Default help file\n}\n\nexport default async function help(...args: MethodArgs): Promise<string> {\n const helpArgs = args.filter((arg): arg is string => typeof arg === 'string');\n const helpFileAbsolutePath = findHelpFile(helpArgs);\n return renderMarkdown(fs.readFileSync(helpFileAbsolutePath, 'utf8'));\n}\n","import { marked } from 'marked';\nimport chalk from 'chalk';\nimport { reflowText } from './reflow-text';\n\n// stateful variable to control left-padding by header level\nlet currentHeader = 1;\nconst listItemSeparator = 'LISTITEMSEPARATOR'; // Helper string for rendering ListItems\n\n/**\n * @description get padding spaces depending on the last header level used\n * @returns string\n */\nfunction getLeftTextPadding(): string {\n return ' '.repeat(\n currentHeader === 1 || currentHeader === 2 ? 1 : currentHeader - 1,\n );\n}\n\n/**\n * @description Reads current terminal width if available to limit column width for text-reflowing\n * @returns {number}\n */\nconst defaultMaximumLineWidth = 100;\nfunction getIdealTextWidth(maximumLineWidth = defaultMaximumLineWidth): number {\n if (typeof process.stdout.columns === 'number') {\n if (process.stdout.columns < maximumLineWidth) {\n return process.stdout.columns - getLeftTextPadding().length - 5;\n }\n }\n return maximumLineWidth - getLeftTextPadding().length;\n}\n\n// Marked custom renderer class\nconst renderer = {\n em(text) {\n return chalk.italic(text);\n },\n strong(text) {\n return chalk.bold(text);\n },\n link(href, title, text) {\n // Don't render links to relative paths (like local files)\n if (href.startsWith('./') || !href.includes('://')) {\n return text;\n }\n const renderedLink = chalk.bold.blueBright(href);\n if (text && text !== href) {\n return `${text} ${renderedLink}`;\n }\n return renderedLink;\n },\n blockquote(quote) {\n return quote;\n },\n list(body, ordered, start) {\n return (\n body\n .split(listItemSeparator)\n .map((listItem, listItemIndex) => {\n const bulletPoint = ordered ? `${listItemIndex + start}. ` : '- ';\n return reflowText(listItem, getIdealTextWidth())\n .split('\\n')\n .map((listItemLine, listItemLineIndex) => {\n if (!listItemLine) {\n return '';\n }\n return `${getLeftTextPadding()}${\n listItemLineIndex === 0 ? bulletPoint : ' '\n }${listItemLine}`;\n })\n .join('\\n');\n })\n .join('\\n') + '\\n'\n );\n },\n listitem(text) {\n return text + listItemSeparator;\n },\n paragraph(text) {\n return (\n reflowText(text, getIdealTextWidth())\n .split('\\n')\n .map((s) => getLeftTextPadding() + chalk.reset() + s)\n .join('\\n') + '\\n\\n'\n );\n },\n codespan(text) {\n return chalk.italic.blueBright(`${text}`);\n },\n code(code) {\n return (\n code\n .split('\\n')\n .map((s) => getLeftTextPadding() + chalk.reset() + s)\n .join('\\n') + '\\n\\n'\n );\n },\n heading(text, level) {\n currentHeader = level;\n let coloring;\n switch (level) {\n case 1:\n coloring = chalk.bold.underline;\n break;\n case 3:\n case 4:\n coloring = chalk;\n break;\n default:\n coloring = chalk.bold;\n break;\n }\n return `${' '.repeat(level === 1 ? 0 : currentHeader - 2)}${coloring(\n text,\n )}\\n`;\n },\n};\n\nmarked.use({ renderer });\nmarked.setOptions({\n mangle: false,\n});\n\nconst htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\",\n '`': '`',\n ' ': '',\n};\n\n/**\n * @description Replace HTML entities with their non-encoded variant\n * @param {string} text\n * @returns {string}\n */\nfunction unescape(text: string): string {\n Object.entries(htmlUnescapes).forEach(([escapedChar, unescapedChar]) => {\n const escapedCharRegExp = new RegExp(escapedChar, 'g');\n text = text.replace(escapedCharRegExp, unescapedChar);\n });\n return text;\n}\n\nexport function renderMarkdown(markdown: string): string {\n return unescape(marked.parse(markdown));\n}\n","/**\nCode in this file is adapted from mikaelbr/marked-terminal\nhttps://github.com/mikaelbr/marked-terminal/blob/7501b8bb24a5ed52ec7d9114d4aeefa14f1bf5e6/index.js#L234-L330\n\n\nMIT License\n\nCopyright (c) 2017 Mikael Brevik\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n// Compute length of str not including ANSI escape codes.\n// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\nfunction textLength(str: string): number {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\u001b\\[(?:\\d{1,3})(?:;\\d{1,3})*m/g, '').length;\n}\n\n// Munge \\n's and spaces in \"text\" so that the number of\n// characters between \\n's is less than or equal to \"width\".\nexport function reflowText(text: string, width: number): string {\n const HARD_RETURN = '\\r|\\n';\n const HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br ?/?>');\n\n const splitRe = HARD_RETURN_GFM_RE;\n const sections = text.split(splitRe);\n const reflowed = [] as string[];\n\n sections.forEach((section) => {\n // Split the section by escape codes so that we can\n // deal with them separately.\n // eslint-disable-next-line no-control-regex\n const fragments = section.split(/(\\u001b\\[(?:\\d{1,3})(?:;\\d{1,3})*m)/g);\n let column = 0;\n let currentLine = '';\n let lastWasEscapeChar = false;\n\n while (fragments.length) {\n const fragment = fragments[0];\n\n if (fragment === '') {\n fragments.splice(0, 1);\n lastWasEscapeChar = false;\n continue;\n }\n\n // This is an escape code - leave it whole and\n // move to the next fragment.\n if (!textLength(fragment)) {\n currentLine += fragment;\n fragments.splice(0, 1);\n lastWasEscapeChar = true;\n continue;\n }\n\n const words = fragment.split(/[ \\t\\n]+/);\n\n for (let i = 0; i < words.length; i++) {\n let word = words[i];\n let addSpace = column != 0;\n if (lastWasEscapeChar) addSpace = false;\n\n // If adding the new word overflows the required width\n if (column + word.length > width) {\n if (word.length <= width) {\n // If the new word is smaller than the required width\n // just add it at the beginning of a new line\n reflowed.push(currentLine);\n currentLine = word;\n column = word.length;\n } else {\n // If the new word is longer than the required width\n // split this word into smaller parts.\n const w = word.substr(0, width - column);\n if (addSpace) currentLine += ' ';\n currentLine += w;\n reflowed.push(currentLine);\n currentLine = '';\n column = 0;\n\n word = word.substr(w.length);\n while (word.length) {\n const w = word.substr(0, width);\n\n if (!w.length) break;\n\n if (w.length < width) {\n currentLine = w;\n column = w.length;\n break;\n } else {\n reflowed.push(w);\n word = word.substr(width);\n }\n }\n }\n } else {\n if (addSpace) {\n currentLine += ' ';\n column++;\n }\n\n currentLine += word;\n column += word.length;\n }\n\n lastWasEscapeChar = false;\n }\n\n fragments.splice(0, 1);\n }\n\n if (textLength(currentLine)) reflowed.push(currentLine);\n });\n\n return reflowed.join('\\n');\n}\n","import { Options } from '../../lib/types';\n\nexport function processCommandArgs<CommandOptions>(\n ...args\n): { paths: string[]; options: Options & CommandOptions } {\n let options = ({} as any) as Options & CommandOptions;\n\n if (typeof args[args.length - 1] === 'object') {\n options = (args.pop() as any) as Options & CommandOptions;\n }\n args = args.filter(Boolean);\n\n // For repository scanning, populate with default path (cwd) if no path given\n if (args.length === 0 && !options.docker) {\n args.unshift(process.cwd());\n }\n\n return { options, paths: args };\n}\n","import chalk from 'chalk';\n\nexport const SNYK_APP_NAME = 'snykAppName';\nexport const SNYK_APP_REDIRECT_URIS = 'snykAppRedirectUris';\nexport const SNYK_APP_SCOPES = 'snykAppScopes';\nexport const SNYK_APP_CLIENT_ID = 'snykAppClientId';\nexport const SNYK_APP_ORG_ID = 'snykAppOrgId';\nexport const SNYK_APP_DEBUG = 'snyk:apps';\n\nexport enum EValidSubCommands {\n CREATE = 'create',\n}\n\nexport enum EAppsURL {\n CREATE_APP,\n}\n\nexport const validAppsSubCommands = Object.values<string>(EValidSubCommands);\n\nexport const AppsErrorMessages = {\n orgRequired: `Option '--org' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n nameRequired: `Option '--name' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n redirectUrisRequired: `Option '--redirect-uris' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n scopesRequired: `Option '--scopes' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n useExperimental: `\\n${chalk.redBright(\n \"All 'apps' commands are only accessible behind the '--experimental' flag.\",\n )}\\n \nThe behaviour can change at any time, without prior notice. \nYou are kindly advised to use all the commands with caution.\n \n${chalk.bold('Usage')}\n ${chalk.italic('snyk apps <COMMAND> --experimental')}\\n`,\n};\n\nexport const CreateAppPromptData = {\n SNYK_APP_NAME: {\n name: SNYK_APP_NAME,\n message: `Name of the Snyk App (visible to users when they install the Snyk App)?`,\n },\n SNYK_APP_REDIRECT_URIS: {\n name: SNYK_APP_REDIRECT_URIS,\n message: `Your Snyk App's redirect URIs (comma seprated list. ${chalk.yellowBright(\n ' Ex: https://example1.com,https://example2.com',\n )})?: `,\n },\n SNYK_APP_SCOPES: {\n name: SNYK_APP_SCOPES,\n message: `Your Snyk App's permission scopes (comma separated list. ${chalk.yellowBright(\n ' Ex: apps:beta',\n )})?: `,\n },\n SNYK_APP_ORG_ID: {\n name: SNYK_APP_ORG_ID,\n message:\n 'Please provide the org id under which you want to create your Snyk App: ',\n },\n};\n","import {\n AppsErrorMessages,\n createAppPrompts,\n ICreateAppRequest,\n ICreateAppOptions,\n SNYK_APP_NAME,\n SNYK_APP_REDIRECT_URIS,\n SNYK_APP_SCOPES,\n SNYK_APP_ORG_ID,\n validateUUID,\n validateAllURL,\n} from '..';\nimport * as enquirer from 'enquirer';\nimport { ValidationError } from '../../errors';\n\n/**\n * Validates and parsed the data required to create app.\n * Throws error if option is not provided or is invalid\n * @param {ICreateAppOptions} options required to create an app\n * @returns {ICreateAppRequest} data that is used to make the request\n */\nexport function createAppDataScriptable(\n options: ICreateAppOptions,\n): ICreateAppRequest {\n if (!options.org) {\n throw new ValidationError(AppsErrorMessages.orgRequired);\n } else if (typeof validateUUID(options.org) === 'string') {\n // Combines to form \"Invalid UUID provided for org id\"\n throw new ValidationError(`${validateUUID(options.org)} for org id`);\n } else if (!options.name) {\n throw new ValidationError(AppsErrorMessages.nameRequired);\n } else if (!options['redirect-uris']) {\n throw new ValidationError(AppsErrorMessages.redirectUrisRequired);\n } else if (typeof validateAllURL(options['redirect-uris']) === 'string') {\n throw new ValidationError(\n validateAllURL(options['redirect-uris']) as string,\n );\n } else if (!options.scopes) {\n throw new ValidationError(AppsErrorMessages.scopesRequired);\n } else {\n return {\n orgId: options.org,\n snykAppName: options.name,\n snykAppRedirectUris: options['redirect-uris']\n .replace(/\\s+/g, '')\n .split(','),\n snykAppScopes: options.scopes.replace(/\\s+/g, '').split(','),\n };\n }\n}\n\n// Interactive format\nexport async function createAppDataInteractive(): Promise<ICreateAppRequest> {\n // Proceed with interactive\n const answers = await enquirer.prompt(createAppPrompts);\n // Process answers\n const snykAppName = answers[SNYK_APP_NAME].trim() as string;\n const snykAppRedirectUris = answers[SNYK_APP_REDIRECT_URIS].replace(\n /\\s+/g,\n '',\n ).split(',') as string[];\n const snykAppScopes = answers[SNYK_APP_SCOPES].replace(/\\s+/g, '').split(\n ',',\n ) as string[];\n const orgId = answers[SNYK_APP_ORG_ID].trim() as string;\n // POST: to create an app\n return {\n orgId,\n snykAppName,\n snykAppRedirectUris,\n snykAppScopes,\n };\n}\n","export * from './constants';\nexport * from './prompts';\nexport * from './types';\nexport * from './rest-utils';\nexport * from './utils';\nexport * from './input-validator';\n","import * as uuid from 'uuid';\n\n/**\n *\n * @param {String} input of space separated URL/URI passed by\n * user for redirect URIs\n * @returns { String | Boolean } complying with enquirer return values, the function\n * separates the string on space and validates each to see\n * if a valid URL/URI. Return a string if invalid and\n * boolean true if valid\n */\nexport function validateAllURL(input: string): string | boolean {\n const trimmedInput = input.trim();\n let errMessage = '';\n for (const i of trimmedInput.split(',')) {\n if (typeof validURL(i) == 'string')\n errMessage = errMessage + `\\n${validURL(i)}`;\n }\n\n if (errMessage) return errMessage;\n return true;\n}\n\n/**\n * Custom validation logic which takes in consideration\n * creation of Snyk Apps and thus allows localhost.com\n * as a valid URL.\n * @param {String} input of URI/URL value to validate using\n * regex\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validURL(input: string): boolean | string {\n try {\n new URL(input);\n return true;\n } catch (error) {\n return `${input} is not a valid URL`;\n }\n}\n\n/**\n * Function validates if a valid UUID (version of UUID not tacken into account)\n * @param {String} input UUID to be validated\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validateUUID(input: string): boolean | string {\n return uuid.validate(input) ? true : 'Invalid UUID provided';\n}\n\n/**\n * @param {String} input\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validInput(input: string): string | boolean {\n if (!input) return 'Please enter something';\n return true;\n}\n","import { CreateAppPromptData } from './constants';\nimport { validInput, validateAllURL, validateUUID } from './input-validator';\n\n/**\n * Prompts for $snyk apps create command\n */\nexport const createAppPrompts = [\n {\n name: CreateAppPromptData.SNYK_APP_NAME.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_NAME.message,\n validate: validInput,\n },\n {\n name: CreateAppPromptData.SNYK_APP_REDIRECT_URIS.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_REDIRECT_URIS.message,\n validate: validateAllURL,\n },\n {\n name: CreateAppPromptData.SNYK_APP_SCOPES.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_SCOPES.message,\n validate: validInput,\n },\n {\n name: CreateAppPromptData.SNYK_APP_ORG_ID.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_ORG_ID.message,\n validate: validateUUID,\n },\n];\n","/**\n * Collection of utility function for the\n * $snyk apps commands\n */\nimport {\n EAppsURL,\n ICreateAppResponse,\n IGetAppsURLOpts,\n IRestErrorResponse,\n SNYK_APP_DEBUG,\n} from '.';\nimport chalk from 'chalk';\nimport { AuthFailedError, InternalServerError } from '../errors';\nimport * as Debug from 'debug';\nimport config from '../config';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\nexport function getAppsURL(\n selection: EAppsURL,\n opts: IGetAppsURLOpts = {},\n): string {\n // Get the rest URL from user config\n // Environment variable takes precendence over config\n const baseURL = config.API_REST_URL;\n debug(`API rest base URL => ${baseURL}`);\n\n switch (selection) {\n case EAppsURL.CREATE_APP:\n return `${baseURL}/orgs/${opts.orgId}/apps`;\n default:\n throw new Error('Invalid selection for URL');\n }\n}\n\nexport function handleRestError(error: any): void {\n if (error.code) {\n if (error.code === 400) {\n // Bad request\n const responseJSON: IRestErrorResponse = error.body;\n const errString = errorsToDisplayString(responseJSON);\n throw new Error(errString);\n } else if (error.code === 401) {\n // Unauthorized\n throw AuthFailedError();\n } else if (error.code === 403) {\n throw new Error(\n 'Forbidden! the authentication token does not have access to the resource.',\n );\n } else if (error.code === 404) {\n const responseJSON: IRestErrorResponse = error.body;\n const errString = errorsToDisplayString(responseJSON);\n throw new Error(errString);\n } else if (error.code === 500) {\n throw new InternalServerError('Internal server error');\n } else {\n throw new Error(error.message);\n }\n } else {\n throw error;\n }\n}\n\n/**\n * @param errRes RestError response\n * @returns {String} Iterates over error and\n * converts them into a readible string\n */\nfunction errorsToDisplayString(errRes: IRestErrorResponse): string {\n const resString = `Uh oh! an error occurred while trying to create the Snyk App.\nPlease run the command with '--debug' or '-d' to get more information`;\n if (!errRes.errors) return resString;\n errRes.errors.forEach((e) => {\n let metaString = '',\n sourceString = '';\n if (e.meta) {\n for (const [key, value] of Object.entries(e.meta)) {\n metaString += `${key}: ${value}\\n`;\n }\n }\n if (e.source) {\n for (const [key, value] of Object.entries(e.source)) {\n sourceString += `${key}: ${value}\\n`;\n }\n }\n\n const meta = metaString || '-';\n const source = sourceString || '-';\n\n return `Uh oh! an error occured while trying to create the Snyk App.\n\nError Description:\\t${e.detail}\nRequest Status:\\t${e.status}\nSource:\\t${source}\nMeta:\\t${meta}`;\n });\n return resString;\n}\n\nexport function handleCreateAppRes(res: ICreateAppResponse): string {\n const {\n name,\n clientId,\n redirectUris,\n scopes,\n isPublic,\n clientSecret,\n } = res.data.attributes;\n\n return `Snyk App created successfully!\nPlease ensure you save the following details:\n\nApp Name:\\t${name}\nClient ID:\\t${clientId}\nRedirect URIs:\\t${redirectUris}\nScopes:\\t${scopes}\nIs App Public:\\t${isPublic}\nClient Secret (${chalk.redBright(\n 'keep it safe and protected',\n )}):\\t${clientSecret}`;\n}\n","export interface IGetAppsURLOpts {\n orgId?: string;\n clientId?: string;\n}\n\ninterface IJSONApi {\n version: string;\n}\n\nexport interface ICreateAppResponse {\n jsonapi: IJSONApi;\n data: {\n type: string;\n id: string;\n attributes: {\n name: string;\n clientId: string;\n redirectUris: string[];\n scopes: string[];\n isPublic: boolean;\n clientSecret: string;\n };\n links: {\n self: string;\n };\n };\n}\n\nexport interface IRestErrorResponse {\n jsonapi: IJSONApi;\n errors: [\n {\n status: string;\n detail: string;\n source?: any;\n meta?: any;\n },\n ];\n}\n\nexport interface IGenerateAppsOptions {\n interactive?: boolean;\n}\n\nexport interface ICreateAppOptions extends IGenerateAppsOptions {\n org?: string;\n name?: string;\n redirectUris?: string;\n scopes?: string;\n}\n\nexport interface ICreateAppRequest {\n orgId: string;\n snykAppName: string;\n snykAppRedirectUris: string[];\n snykAppScopes: string[];\n}\n","import * as fs from 'fs';\nimport { renderMarkdown } from '../../cli/commands/help/markdown-renderer';\n\nexport function readAppsHelpMarkdown(filename: string): string {\n const file = fs.readFileSync(filename, 'utf8');\n return renderMarkdown(file);\n}\n","import { getAuthHeader } from '../api-token';\nimport * as request from './index';\n\nexport async function makeRequest<T>(payload: any): Promise<T> {\n return new Promise((resolve, reject) => {\n request.makeRequest(payload, (error, res, body) => {\n if (error) {\n return reject(error);\n }\n if (res.statusCode !== 200) {\n return reject({\n code: res.statusCode,\n message: body?.message,\n });\n }\n resolve(body);\n });\n });\n}\n\n/**\n * All rest request will essentially be the same and are JSON by default\n * Thus if no headers provided default headers are used\n * @param {any} payload for the request\n * @returns\n */\nexport async function makeRequestRest<T>(payload: any): Promise<T> {\n return new Promise((resolve, reject) => {\n payload.headers = payload.headers ?? {\n 'Content-Type': 'application/vnd.api+json',\n authorization: getAuthHeader(),\n };\n payload.json = true;\n request.makeRequest(payload, (error, res, body) => {\n if (error) {\n return reject(error);\n }\n if (res.statusCode >= 400) {\n return reject({\n code: res.statusCode,\n body: JSON.parse(body as any),\n });\n }\n resolve(JSON.parse(body as any) as T);\n });\n });\n}\n"],"names":[],"sourceRoot":""}
|
|
1
|
+
{"version":3,"file":"663.index.js","mappings":";;;;;;;;;;;AAAA,yCAA+B;AAC/B,0CAQ2B;AAC3B,6CAA+D;AAC/D,6CAA+C;AAE/C,MAAM,KAAK,GAAG,KAAK,CAAC,qBAAc,CAAC,CAAC;AAEpC;;;;;;;GAOG;AACI,KAAK,UAAU,SAAS,CAC7B,IAAuB;IAEvB,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;IACxB,MAAM,EACJ,KAAK,EACL,WAAW,EAAE,IAAI,EACjB,mBAAmB,EAAE,YAAY,EACjC,aAAa,EAAE,MAAM,GACtB,GAAG,IAAI,CAAC;IACT,MAAM,OAAO,GAAG;QACd,MAAM,EAAE,MAAM;QACd,GAAG,EAAE,iBAAU,CAAC,eAAQ,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,CAAC;QAC/C,IAAI,EAAE;YACJ,IAAI;YACJ,YAAY;YACZ,MAAM;SACP;QACD,EAAE,EAAE;YACF,OAAO,EAAE,yBAAyB;SACnC;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ACtB;YACD,IAAI,GAAG,CAAC,UAAU,IAAI,GAAG,EAAE;gBACzB,OAAO,MAAM,CAAC;oBACZ,IAAI,EAAE,GAAG,CAAC,UAAU;oBACpB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,IAAW,CAAC;iBAC9B,CAAC,CAAC;aACJ;YACD,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,IAAW,CAAM,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC;AApBD,0CAoBC","sources":["webpack://snyk/./src/cli/commands/apps/create-app.ts","webpack://snyk/./src/cli/commands/apps/index.ts","webpack://snyk/./src/cli/commands/help/index.ts","webpack://snyk/./src/cli/commands/help/markdown-renderer.ts","webpack://snyk/./src/cli/commands/help/reflow-text.ts","webpack://snyk/./src/cli/commands/process-command-args.ts","webpack://snyk/./src/lib/apps/constants.ts","webpack://snyk/./src/lib/apps/create-app/index.ts","webpack://snyk/./src/lib/apps/index.ts","webpack://snyk/./src/lib/apps/input-validator.ts","webpack://snyk/./src/lib/apps/prompts.ts","webpack://snyk/./src/lib/apps/rest-utils.ts","webpack://snyk/./src/lib/apps/types.ts","webpack://snyk/./src/lib/apps/utils.ts","webpack://snyk/./src/lib/request/promise.ts"],"sourcesContent":["import * as Debug from 'debug';\nimport {\n EAppsURL,\n getAppsURL,\n handleCreateAppRes,\n handleRestError,\n ICreateAppRequest,\n ICreateAppResponse,\n SNYK_APP_DEBUG,\n} from '../../../lib/apps';\nimport { makeRequestRest } from '../../../lib/request/promise';\nimport { spinner } from '../../../lib/spinner';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\n/**\n * Function to process the app creation request and\n * handle any errors that are request error and print\n * in a formatted string. It throws is error is unknown\n * or cannot be handled.\n * @param {ICreateAppRequest} data to create the app\n * @returns {String} response formatted string\n */\nexport async function createApp(\n data: ICreateAppRequest,\n): Promise<string | void> {\n debug('App data', data);\n const {\n orgId,\n snykAppName: name,\n snykAppRedirectUris: redirectUris,\n snykAppScopes: scopes,\n } = data;\n const payload = {\n method: 'POST',\n url: getAppsURL(EAppsURL.CREATE_APP, { orgId }),\n body: {\n name,\n redirectUris,\n scopes,\n },\n qs: {\n version: '2021-08-11~experimental',\n },\n };\n\n try {\n await spinner('Creating your Snyk App');\n const response = await makeRequestRest<ICreateAppResponse>(payload);\n debug(response);\n spinner.clearAll();\n return handleCreateAppRes(response);\n } catch (error) {\n spinner.clearAll();\n handleRestError(error);\n }\n}\n","import * as Debug from 'debug';\nimport { MethodArgs } from '../../args';\nimport { processCommandArgs } from '../process-command-args';\nimport {\n EValidSubCommands,\n validAppsSubCommands,\n SNYK_APP_DEBUG,\n ICreateAppOptions,\n AppsErrorMessages,\n} from '../../../lib/apps';\n\nimport { createApp } from './create-app';\n// import * as path from 'path';\nimport {\n createAppDataInteractive,\n createAppDataScriptable,\n} from '../../../lib/apps/create-app';\nimport help from '../help';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\nexport default async function apps(\n ...args0: MethodArgs\n): Promise<string | undefined | any> {\n debug('Snyk apps CLI called');\n\n const { options, paths } = processCommandArgs<ICreateAppOptions>(...args0);\n debug(options, paths);\n\n const commandVerb1 = paths[0];\n const validCommandVerb =\n commandVerb1 && validAppsSubCommands.includes(commandVerb1);\n if (!validCommandVerb) {\n // Display help md for apps\n debug(`Unknown subcommand: ${commandVerb1}`);\n return help('apps');\n }\n // Check if experimental flag is being used\n if (!options.experimental) throw new Error(AppsErrorMessages.useExperimental);\n\n if (commandVerb1 === EValidSubCommands.CREATE) {\n const createAppData = options.interactive\n ? await createAppDataInteractive()\n : createAppDataScriptable(options);\n return await createApp(createAppData);\n }\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport { MethodArgs } from '../../args';\nimport { renderMarkdown } from './markdown-renderer';\n\nexport function findHelpFile(\n helpArgs: string[],\n helpFolderPath = '../../help/cli-commands', // this is a relative path from the webpack dist directory,\n): string {\n while (helpArgs.length > 0) {\n // cleanse the filename to only contain letters\n // aka: /\\W/g but figured this was easier to read\n const file = `${helpArgs.join('-').replace(/[^a-z0-9-]/gi, '')}.md`;\n const testHelpAbsolutePath = path.resolve(__dirname, helpFolderPath, file);\n if (fs.existsSync(testHelpAbsolutePath)) {\n return testHelpAbsolutePath;\n }\n helpArgs = helpArgs.slice(0, -1);\n }\n return path.resolve(__dirname, helpFolderPath, `README.md`); // Default help file\n}\n\nexport default async function help(...args: MethodArgs): Promise<string> {\n const helpArgs = args.filter((arg): arg is string => typeof arg === 'string');\n const helpFileAbsolutePath = findHelpFile(helpArgs);\n return renderMarkdown(fs.readFileSync(helpFileAbsolutePath, 'utf8'));\n}\n","import { marked } from 'marked';\nimport chalk from 'chalk';\nimport { reflowText } from './reflow-text';\n\n// stateful variable to control left-padding by header level\nlet currentHeader = 1;\nconst listItemSeparator = 'LISTITEMSEPARATOR'; // Helper string for rendering ListItems\n\n/**\n * @description get padding spaces depending on the last header level used\n * @returns string\n */\nfunction getLeftTextPadding(): string {\n return ' '.repeat(\n currentHeader === 1 || currentHeader === 2 ? 1 : currentHeader - 1,\n );\n}\n\n/**\n * @description Reads current terminal width if available to limit column width for text-reflowing\n * @returns {number}\n */\nconst defaultMaximumLineWidth = 100;\nfunction getIdealTextWidth(maximumLineWidth = defaultMaximumLineWidth): number {\n if (typeof process.stdout.columns === 'number') {\n if (process.stdout.columns < maximumLineWidth) {\n return process.stdout.columns - getLeftTextPadding().length - 5;\n }\n }\n return maximumLineWidth - getLeftTextPadding().length;\n}\n\n// Marked custom renderer class\nconst renderer = {\n em(text) {\n return chalk.italic(text);\n },\n strong(text) {\n return chalk.bold(text);\n },\n link(href, title, text) {\n // Don't render links to relative paths (like local files)\n if (href.startsWith('./') || !href.includes('://')) {\n return text;\n }\n const renderedLink = chalk.bold.blueBright(href);\n if (text && text !== href) {\n return `${text} ${renderedLink}`;\n }\n return renderedLink;\n },\n blockquote(quote) {\n return quote;\n },\n list(body, ordered, start) {\n return (\n body\n .split(listItemSeparator)\n .map((listItem, listItemIndex) => {\n const bulletPoint = ordered ? `${listItemIndex + start}. ` : '- ';\n return reflowText(listItem, getIdealTextWidth())\n .split('\\n')\n .map((listItemLine, listItemLineIndex) => {\n if (!listItemLine) {\n return '';\n }\n return `${getLeftTextPadding()}${\n listItemLineIndex === 0 ? bulletPoint : ' '\n }${listItemLine}`;\n })\n .join('\\n');\n })\n .join('\\n') + '\\n'\n );\n },\n listitem(text) {\n return text + listItemSeparator;\n },\n paragraph(text) {\n return (\n reflowText(text, getIdealTextWidth())\n .split('\\n')\n .map((s) => getLeftTextPadding() + chalk.reset() + s)\n .join('\\n') + '\\n\\n'\n );\n },\n codespan(text) {\n return chalk.italic.blueBright(`${text}`);\n },\n code(code) {\n return (\n code\n .split('\\n')\n .map((s) => getLeftTextPadding() + chalk.reset() + s)\n .join('\\n') + '\\n\\n'\n );\n },\n heading(text, level) {\n currentHeader = level;\n let coloring;\n switch (level) {\n case 1:\n coloring = chalk.bold.underline;\n break;\n case 3:\n case 4:\n coloring = chalk;\n break;\n default:\n coloring = chalk.bold;\n break;\n }\n return `${' '.repeat(level === 1 ? 0 : currentHeader - 2)}${coloring(\n text,\n )}\\n`;\n },\n};\n\nmarked.use({ renderer });\nmarked.setOptions({\n mangle: false,\n});\n\nconst htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\",\n '`': '`',\n ' ': '',\n};\n\n/**\n * @description Replace HTML entities with their non-encoded variant\n * @param {string} text\n * @returns {string}\n */\nfunction unescape(text: string): string {\n Object.entries(htmlUnescapes).forEach(([escapedChar, unescapedChar]) => {\n const escapedCharRegExp = new RegExp(escapedChar, 'g');\n text = text.replace(escapedCharRegExp, unescapedChar);\n });\n return text;\n}\n\nexport function renderMarkdown(markdown: string): string {\n return unescape(marked.parse(markdown));\n}\n","/**\nCode in this file is adapted from mikaelbr/marked-terminal\nhttps://github.com/mikaelbr/marked-terminal/blob/7501b8bb24a5ed52ec7d9114d4aeefa14f1bf5e6/index.js#L234-L330\n\n\nMIT License\n\nCopyright (c) 2017 Mikael Brevik\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n */\n\n// Compute length of str not including ANSI escape codes.\n// See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\nfunction textLength(str: string): number {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\u001b\\[(?:\\d{1,3})(?:;\\d{1,3})*m/g, '').length;\n}\n\n// Munge \\n's and spaces in \"text\" so that the number of\n// characters between \\n's is less than or equal to \"width\".\nexport function reflowText(text: string, width: number): string {\n const HARD_RETURN = '\\r|\\n';\n const HARD_RETURN_GFM_RE = new RegExp(HARD_RETURN + '|<br ?/?>');\n\n const splitRe = HARD_RETURN_GFM_RE;\n const sections = text.split(splitRe);\n const reflowed = [] as string[];\n\n sections.forEach((section) => {\n // Split the section by escape codes so that we can\n // deal with them separately.\n // eslint-disable-next-line no-control-regex\n const fragments = section.split(/(\\u001b\\[(?:\\d{1,3})(?:;\\d{1,3})*m)/g);\n let column = 0;\n let currentLine = '';\n let lastWasEscapeChar = false;\n\n while (fragments.length) {\n const fragment = fragments[0];\n\n if (fragment === '') {\n fragments.splice(0, 1);\n lastWasEscapeChar = false;\n continue;\n }\n\n // This is an escape code - leave it whole and\n // move to the next fragment.\n if (!textLength(fragment)) {\n currentLine += fragment;\n fragments.splice(0, 1);\n lastWasEscapeChar = true;\n continue;\n }\n\n const words = fragment.split(/[ \\t\\n]+/);\n\n for (let i = 0; i < words.length; i++) {\n let word = words[i];\n let addSpace = column != 0;\n if (lastWasEscapeChar) addSpace = false;\n\n // If adding the new word overflows the required width\n if (column + word.length > width) {\n if (word.length <= width) {\n // If the new word is smaller than the required width\n // just add it at the beginning of a new line\n reflowed.push(currentLine);\n currentLine = word;\n column = word.length;\n } else {\n // If the new word is longer than the required width\n // split this word into smaller parts.\n const w = word.substr(0, width - column);\n if (addSpace) currentLine += ' ';\n currentLine += w;\n reflowed.push(currentLine);\n currentLine = '';\n column = 0;\n\n word = word.substr(w.length);\n while (word.length) {\n const w = word.substr(0, width);\n\n if (!w.length) break;\n\n if (w.length < width) {\n currentLine = w;\n column = w.length;\n break;\n } else {\n reflowed.push(w);\n word = word.substr(width);\n }\n }\n }\n } else {\n if (addSpace) {\n currentLine += ' ';\n column++;\n }\n\n currentLine += word;\n column += word.length;\n }\n\n lastWasEscapeChar = false;\n }\n\n fragments.splice(0, 1);\n }\n\n if (textLength(currentLine)) reflowed.push(currentLine);\n });\n\n return reflowed.join('\\n');\n}\n","import { Options } from '../../lib/types';\n\nexport function processCommandArgs<CommandOptions>(\n ...args\n): { paths: string[]; options: Options & CommandOptions } {\n let options = ({} as any) as Options & CommandOptions;\n\n if (typeof args[args.length - 1] === 'object') {\n options = (args.pop() as any) as Options & CommandOptions;\n }\n args = args.filter(Boolean);\n\n // For repository scanning, populate with default path (cwd) if no path given\n if (args.length === 0 && !options.docker) {\n args.unshift(process.cwd());\n }\n\n return { options, paths: args };\n}\n","import chalk from 'chalk';\n\nexport const SNYK_APP_NAME = 'snykAppName';\nexport const SNYK_APP_REDIRECT_URIS = 'snykAppRedirectUris';\nexport const SNYK_APP_SCOPES = 'snykAppScopes';\nexport const SNYK_APP_CLIENT_ID = 'snykAppClientId';\nexport const SNYK_APP_ORG_ID = 'snykAppOrgId';\nexport const SNYK_APP_DEBUG = 'snyk:apps';\n\nexport enum EValidSubCommands {\n CREATE = 'create',\n}\n\nexport enum EAppsURL {\n CREATE_APP,\n}\n\nexport const validAppsSubCommands = Object.values<string>(EValidSubCommands);\n\nexport const AppsErrorMessages = {\n orgRequired: `Option '--org' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n nameRequired: `Option '--name' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n redirectUrisRequired: `Option '--redirect-uris' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n scopesRequired: `Option '--scopes' is required! For interactive mode, please use '--interactive' or '-i' flag. For more information please run the help command 'snyk apps --help' or 'snyk apps -h'.`,\n useExperimental: `\\n${chalk.redBright(\n \"All 'apps' commands are only accessible behind the '--experimental' flag.\",\n )}\\n \nThe behaviour can change at any time, without prior notice. \nYou are kindly advised to use all the commands with caution.\n \n${chalk.bold('Usage')}\n ${chalk.italic('snyk apps <COMMAND> --experimental')}\\n`,\n};\n\nexport const CreateAppPromptData = {\n SNYK_APP_NAME: {\n name: SNYK_APP_NAME,\n message: `Name of the Snyk App (visible to users when they install the Snyk App)?`,\n },\n SNYK_APP_REDIRECT_URIS: {\n name: SNYK_APP_REDIRECT_URIS,\n message: `Your Snyk App's redirect URIs (comma seprated list. ${chalk.yellowBright(\n ' Ex: https://example1.com,https://example2.com',\n )})?: `,\n },\n SNYK_APP_SCOPES: {\n name: SNYK_APP_SCOPES,\n message: `Your Snyk App's permission scopes (comma separated list. ${chalk.yellowBright(\n ' Ex: org.read,org.report.read',\n )})?: `,\n },\n SNYK_APP_ORG_ID: {\n name: SNYK_APP_ORG_ID,\n message:\n 'Please provide the org id under which you want to create your Snyk App: ',\n },\n};\n","import {\n AppsErrorMessages,\n createAppPrompts,\n ICreateAppRequest,\n ICreateAppOptions,\n SNYK_APP_NAME,\n SNYK_APP_REDIRECT_URIS,\n SNYK_APP_SCOPES,\n SNYK_APP_ORG_ID,\n validateUUID,\n validateAllURL,\n} from '..';\nimport * as enquirer from 'enquirer';\nimport { ValidationError } from '../../errors';\n\n/**\n * Validates and parsed the data required to create app.\n * Throws error if option is not provided or is invalid\n * @param {ICreateAppOptions} options required to create an app\n * @returns {ICreateAppRequest} data that is used to make the request\n */\nexport function createAppDataScriptable(\n options: ICreateAppOptions,\n): ICreateAppRequest {\n if (!options.org) {\n throw new ValidationError(AppsErrorMessages.orgRequired);\n } else if (typeof validateUUID(options.org) === 'string') {\n // Combines to form \"Invalid UUID provided for org id\"\n throw new ValidationError(`${validateUUID(options.org)} for org id`);\n } else if (!options.name) {\n throw new ValidationError(AppsErrorMessages.nameRequired);\n } else if (!options['redirect-uris']) {\n throw new ValidationError(AppsErrorMessages.redirectUrisRequired);\n } else if (typeof validateAllURL(options['redirect-uris']) === 'string') {\n throw new ValidationError(\n validateAllURL(options['redirect-uris']) as string,\n );\n } else if (!options.scopes) {\n throw new ValidationError(AppsErrorMessages.scopesRequired);\n } else {\n return {\n orgId: options.org,\n snykAppName: options.name,\n snykAppRedirectUris: options['redirect-uris']\n .replace(/\\s+/g, '')\n .split(','),\n snykAppScopes: options.scopes.replace(/\\s+/g, '').split(','),\n };\n }\n}\n\n// Interactive format\nexport async function createAppDataInteractive(): Promise<ICreateAppRequest> {\n // Proceed with interactive\n const answers = await enquirer.prompt(createAppPrompts);\n // Process answers\n const snykAppName = answers[SNYK_APP_NAME].trim() as string;\n const snykAppRedirectUris = answers[SNYK_APP_REDIRECT_URIS].replace(\n /\\s+/g,\n '',\n ).split(',') as string[];\n const snykAppScopes = answers[SNYK_APP_SCOPES].replace(/\\s+/g, '').split(\n ',',\n ) as string[];\n const orgId = answers[SNYK_APP_ORG_ID].trim() as string;\n // POST: to create an app\n return {\n orgId,\n snykAppName,\n snykAppRedirectUris,\n snykAppScopes,\n };\n}\n","export * from './constants';\nexport * from './prompts';\nexport * from './types';\nexport * from './rest-utils';\nexport * from './utils';\nexport * from './input-validator';\n","import * as uuid from 'uuid';\n\n/**\n *\n * @param {String} input of space separated URL/URI passed by\n * user for redirect URIs\n * @returns { String | Boolean } complying with enquirer return values, the function\n * separates the string on space and validates each to see\n * if a valid URL/URI. Return a string if invalid and\n * boolean true if valid\n */\nexport function validateAllURL(input: string): string | boolean {\n const trimmedInput = input.trim();\n let errMessage = '';\n for (const i of trimmedInput.split(',')) {\n if (typeof validURL(i) == 'string')\n errMessage = errMessage + `\\n${validURL(i)}`;\n }\n\n if (errMessage) return errMessage;\n return true;\n}\n\n/**\n * Custom validation logic which takes in consideration\n * creation of Snyk Apps and thus allows localhost.com\n * as a valid URL.\n * @param {String} input of URI/URL value to validate using\n * regex\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validURL(input: string): boolean | string {\n try {\n new URL(input);\n return true;\n } catch (error) {\n return `${input} is not a valid URL`;\n }\n}\n\n/**\n * Function validates if a valid UUID (version of UUID not tacken into account)\n * @param {String} input UUID to be validated\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validateUUID(input: string): boolean | string {\n return uuid.validate(input) ? true : 'Invalid UUID provided';\n}\n\n/**\n * @param {String} input\n * @returns {String | Boolean } string message is not valid\n * and boolean true if valid\n */\nexport function validInput(input: string): string | boolean {\n if (!input) return 'Please enter something';\n return true;\n}\n","import { CreateAppPromptData } from './constants';\nimport { validInput, validateAllURL, validateUUID } from './input-validator';\n\n/**\n * Prompts for $snyk apps create command\n */\nexport const createAppPrompts = [\n {\n name: CreateAppPromptData.SNYK_APP_NAME.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_NAME.message,\n validate: validInput,\n },\n {\n name: CreateAppPromptData.SNYK_APP_REDIRECT_URIS.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_REDIRECT_URIS.message,\n validate: validateAllURL,\n },\n {\n name: CreateAppPromptData.SNYK_APP_SCOPES.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_SCOPES.message,\n validate: validInput,\n },\n {\n name: CreateAppPromptData.SNYK_APP_ORG_ID.name,\n type: 'input',\n message: CreateAppPromptData.SNYK_APP_ORG_ID.message,\n validate: validateUUID,\n },\n];\n","/**\n * Collection of utility function for the\n * $snyk apps commands\n */\nimport {\n EAppsURL,\n ICreateAppResponse,\n IGetAppsURLOpts,\n IRestErrorResponse,\n SNYK_APP_DEBUG,\n} from '.';\nimport chalk from 'chalk';\nimport { AuthFailedError, InternalServerError } from '../errors';\nimport * as Debug from 'debug';\nimport config from '../config';\n\nconst debug = Debug(SNYK_APP_DEBUG);\n\nexport function getAppsURL(\n selection: EAppsURL,\n opts: IGetAppsURLOpts = {},\n): string {\n // Get the rest URL from user config\n // Environment variable takes precendence over config\n const baseURL = config.API_REST_URL;\n debug(`API rest base URL => ${baseURL}`);\n\n switch (selection) {\n case EAppsURL.CREATE_APP:\n return `${baseURL}/orgs/${opts.orgId}/apps`;\n default:\n throw new Error('Invalid selection for URL');\n }\n}\n\nexport function handleRestError(error: any): void {\n if (error.code) {\n if (error.code === 400) {\n // Bad request\n const responseJSON: IRestErrorResponse = error.body;\n const errString = errorsToDisplayString(responseJSON);\n throw new Error(errString);\n } else if (error.code === 401) {\n // Unauthorized\n throw AuthFailedError();\n } else if (error.code === 403) {\n throw new Error(\n 'Forbidden! the authentication token does not have access to the resource.',\n );\n } else if (error.code === 404) {\n const responseJSON: IRestErrorResponse = error.body;\n const errString = errorsToDisplayString(responseJSON);\n throw new Error(errString);\n } else if (error.code === 500) {\n throw new InternalServerError('Internal server error');\n } else {\n throw new Error(error.message);\n }\n } else {\n throw error;\n }\n}\n\n/**\n * @param errRes RestError response\n * @returns {String} Iterates over error and\n * converts them into a readible string\n */\nfunction errorsToDisplayString(errRes: IRestErrorResponse): string {\n const resString = `Uh oh! an error occurred while trying to create the Snyk App.\nPlease run the command with '--debug' or '-d' to get more information`;\n if (!errRes.errors) return resString;\n errRes.errors.forEach((e) => {\n let metaString = '',\n sourceString = '';\n if (e.meta) {\n for (const [key, value] of Object.entries(e.meta)) {\n metaString += `${key}: ${value}\\n`;\n }\n }\n if (e.source) {\n for (const [key, value] of Object.entries(e.source)) {\n sourceString += `${key}: ${value}\\n`;\n }\n }\n\n const meta = metaString || '-';\n const source = sourceString || '-';\n\n return `Uh oh! an error occured while trying to create the Snyk App.\n\nError Description:\\t${e.detail}\nRequest Status:\\t${e.status}\nSource:\\t${source}\nMeta:\\t${meta}`;\n });\n return resString;\n}\n\nexport function handleCreateAppRes(res: ICreateAppResponse): string {\n const {\n name,\n clientId,\n redirectUris,\n scopes,\n isPublic,\n clientSecret,\n } = res.data.attributes;\n\n return `Snyk App created successfully!\nPlease ensure you save the following details:\n\nApp Name:\\t${name}\nClient ID:\\t${clientId}\nRedirect URIs:\\t${redirectUris}\nScopes:\\t${scopes}\nIs App Public:\\t${isPublic}\nClient Secret (${chalk.redBright(\n 'keep it safe and protected',\n )}):\\t${clientSecret}`;\n}\n","export interface IGetAppsURLOpts {\n orgId?: string;\n clientId?: string;\n}\n\ninterface IJSONApi {\n version: string;\n}\n\nexport interface ICreateAppResponse {\n jsonapi: IJSONApi;\n data: {\n type: string;\n id: string;\n attributes: {\n name: string;\n clientId: string;\n redirectUris: string[];\n scopes: string[];\n isPublic: boolean;\n clientSecret: string;\n };\n links: {\n self: string;\n };\n };\n}\n\nexport interface IRestErrorResponse {\n jsonapi: IJSONApi;\n errors: [\n {\n status: string;\n detail: string;\n source?: any;\n meta?: any;\n },\n ];\n}\n\nexport interface IGenerateAppsOptions {\n interactive?: boolean;\n}\n\nexport interface ICreateAppOptions extends IGenerateAppsOptions {\n org?: string;\n name?: string;\n redirectUris?: string;\n scopes?: string;\n}\n\nexport interface ICreateAppRequest {\n orgId: string;\n snykAppName: string;\n snykAppRedirectUris: string[];\n snykAppScopes: string[];\n}\n","import * as fs from 'fs';\nimport { renderMarkdown } from '../../cli/commands/help/markdown-renderer';\n\nexport function readAppsHelpMarkdown(filename: string): string {\n const file = fs.readFileSync(filename, 'utf8');\n return renderMarkdown(file);\n}\n","import { getAuthHeader } from '../api-token';\nimport * as request from './index';\n\nexport async function makeRequest<T>(payload: any): Promise<T> {\n return new Promise((resolve, reject) => {\n request.makeRequest(payload, (error, res, body) => {\n if (error) {\n return reject(error);\n }\n if (res.statusCode !== 200) {\n return reject({\n code: res.statusCode,\n message: body?.message,\n });\n }\n resolve(body);\n });\n });\n}\n\n/**\n * All rest request will essentially be the same and are JSON by default\n * Thus if no headers provided default headers are used\n * @param {any} payload for the request\n * @returns\n */\nexport async function makeRequestRest<T>(payload: any): Promise<T> {\n return new Promise((resolve, reject) => {\n payload.headers = payload.headers ?? {\n 'Content-Type': 'application/vnd.api+json',\n authorization: getAuthHeader(),\n };\n payload.json = true;\n request.makeRequest(payload, (error, res, body) => {\n if (error) {\n return reject(error);\n }\n if (res.statusCode >= 400) {\n return reject({\n code: res.statusCode,\n body: JSON.parse(body as any),\n });\n }\n resolve(JSON.parse(body as any) as T);\n });\n });\n}\n"],"names":[],"sourceRoot":""}
|
package/dist/cli/895.index.js
CHANGED
|
@@ -449,18 +449,18 @@ exports.DCTL_EXIT_CODES = {
|
|
|
449
449
|
EXIT_NOT_IN_SYNC: 1,
|
|
450
450
|
EXIT_ERROR: 2,
|
|
451
451
|
};
|
|
452
|
-
exports.driftctlVersion = 'v0.
|
|
452
|
+
exports.driftctlVersion = 'v0.31.0';
|
|
453
453
|
const driftctlChecksums = {
|
|
454
|
-
'driftctl_windows_386.exe': '
|
|
455
|
-
driftctl_darwin_amd64: '
|
|
456
|
-
driftctl_linux_386: '
|
|
457
|
-
driftctl_linux_amd64: '
|
|
458
|
-
driftctl_linux_arm64: '
|
|
459
|
-
'driftctl_windows_arm64.exe': '
|
|
460
|
-
driftctl_darwin_arm64: '
|
|
461
|
-
'driftctl_windows_arm.exe': '
|
|
462
|
-
driftctl_linux_arm: '
|
|
463
|
-
'driftctl_windows_amd64.exe': '
|
|
454
|
+
'driftctl_windows_386.exe': '9cf6d1548ac30adda85b0a59597f2b1dcfd61509762b8fa6ceaebc1ab96fc21a',
|
|
455
|
+
driftctl_darwin_amd64: 'bc89d09e65fa1a774dca35ae93003ef1f0b7b112a68e2a005f1311f4f41388e4',
|
|
456
|
+
driftctl_linux_386: '9cf6d1548ac30adda85b0a59597f2b1dcfd61509762b8fa6ceaebc1ab96fc21a',
|
|
457
|
+
driftctl_linux_amd64: '28a88686be407f394487722d27666c1758b7112e56cd528055bb8dd336466fd5',
|
|
458
|
+
driftctl_linux_arm64: 'b4efae6681041a6a34ee4e3212cd7034e4df63c92ba64c576a9f4cfa34ee204f',
|
|
459
|
+
'driftctl_windows_arm64.exe': '8e02f91936da43693904084f4c2df530549a105a4b660a55736cc23fb8259f47',
|
|
460
|
+
driftctl_darwin_arm64: '5fbe33daddc61276fb211d626966c226b3401eb2d3c5da7bc362c2f109a1a195',
|
|
461
|
+
'driftctl_windows_arm.exe': '0e4d5a8cdb312b1174eef9c53e5db27e81e3092fc86849606409dd25608bebc2',
|
|
462
|
+
driftctl_linux_arm: 'b4efae6681041a6a34ee4e3212cd7034e4df63c92ba64c576a9f4cfa34ee204f',
|
|
463
|
+
'driftctl_windows_amd64.exe': 'ff42d0ed2e7f9f4e4323b88e64c676afe1eff31b1592e6f1d56e11add8e72a96',
|
|
464
464
|
};
|
|
465
465
|
const dctlBaseUrl = 'https://static.snyk.io/cli/driftctl/';
|
|
466
466
|
const driftctlPath = path.join(cachePath, 'driftctl_' + exports.driftctlVersion);
|