@agenticcli/shipguard 0.7.0 → 0.8.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 +2 -6
- package/dist/checksum-manifest.json +5 -5
- package/dist/{chunk-MPQ42F54.js → chunk-KGIK7XNK.js} +4 -18
- package/dist/{chunk-3NSULPWH.js → chunk-MVYY4QWT.js} +3 -3
- package/dist/{chunk-BVWCA2VJ.js → chunk-VJBU6FNW.js} +292 -119
- package/dist/cli-facts.json +5 -5
- package/dist/cli.js +303 -102
- package/dist/{config-generator-2BVUZGEU.js → config-generator-4MK6PGY5.js} +2 -2
- package/dist/{dist-3SW45O4F.js → dist-YSE6YNXH.js} +1 -3
- package/dist/{pro-scanner-SFOR7SGK.js → pro-scanner-5GYWJ7AS.js} +2 -2
- package/docs/llms.txt +2 -2
- package/package.json +5 -4
- package/rules/free-bundle.json +9 -9
package/dist/cli.js
CHANGED
|
@@ -7,8 +7,10 @@ import {
|
|
|
7
7
|
databaseCheck,
|
|
8
8
|
deploymentCheck,
|
|
9
9
|
deriveBlocking,
|
|
10
|
+
ensureSecureDir,
|
|
10
11
|
getAuthToken,
|
|
11
12
|
getFindingKey,
|
|
13
|
+
goLink,
|
|
12
14
|
isLineSuppressed,
|
|
13
15
|
isTokenExpired,
|
|
14
16
|
loadChecksumManifest,
|
|
@@ -20,21 +22,22 @@ import {
|
|
|
20
22
|
runProRulesWithDispatch,
|
|
21
23
|
saveCredentials,
|
|
22
24
|
secretsCheck,
|
|
23
|
-
validateBundleCompile
|
|
24
|
-
|
|
25
|
+
validateBundleCompile,
|
|
26
|
+
writeSecureFileSync
|
|
27
|
+
} from "./chunk-VJBU6FNW.js";
|
|
25
28
|
import {
|
|
26
29
|
DEFAULT_MAX_FILES,
|
|
27
30
|
DEFAULT_MAX_FILE_SIZE_BYTES,
|
|
28
31
|
DEFAULT_MAX_TOTAL_BYTES,
|
|
29
32
|
compareScanPaths,
|
|
30
33
|
readFiles
|
|
31
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-MVYY4QWT.js";
|
|
32
35
|
import {
|
|
33
36
|
decodeUtf8Strict,
|
|
34
37
|
detectBinary,
|
|
35
38
|
normalizeNewlines,
|
|
36
39
|
stripBom
|
|
37
|
-
} from "./chunk-
|
|
40
|
+
} from "./chunk-KGIK7XNK.js";
|
|
38
41
|
|
|
39
42
|
// src/cli.ts
|
|
40
43
|
import { Command as Command11, CommanderError } from "commander";
|
|
@@ -180,7 +183,7 @@ function initCommand() {
|
|
|
180
183
|
|
|
181
184
|
// src/commands/scan.ts
|
|
182
185
|
import { Command as Command2 } from "commander";
|
|
183
|
-
import { existsSync as
|
|
186
|
+
import { existsSync as existsSync7, statSync as statSync2 } from "fs";
|
|
184
187
|
import { join as join7, resolve as resolve4 } from "path";
|
|
185
188
|
|
|
186
189
|
// src/core/scanner.ts
|
|
@@ -484,10 +487,10 @@ function getChangedFiles(dir) {
|
|
|
484
487
|
var free_bundle_default = {
|
|
485
488
|
schemaVersion: 1,
|
|
486
489
|
description: "Offline free rule bundle compiled from rule-corpus/*/rule.yaml where bundleEligible=true and enabled=true. Governed by rules.md \xA74/\xA75/\xA79. Generated by scripts/build-free-bundle.ts \u2014 never hand-edited.",
|
|
487
|
-
corpusVersion:
|
|
488
|
-
corpusHash: "sha256:
|
|
490
|
+
corpusVersion: 19,
|
|
491
|
+
corpusHash: "sha256:4edcc0b1a6f89a2c34e796f022a693cf7b89dbc4e3bcf4afd5e7b54804150a97",
|
|
489
492
|
ruleCount: 30,
|
|
490
|
-
contentHash: "sha256:
|
|
493
|
+
contentHash: "sha256:1e274f5f8176c4ad8566703a67b110d038b528942c26c25c2b7299367bc8ffa8",
|
|
491
494
|
rules: [
|
|
492
495
|
{
|
|
493
496
|
id: "generic.auth.jwt-none-algorithm",
|
|
@@ -630,7 +633,7 @@ var free_bundle_default = {
|
|
|
630
633
|
severity: "high",
|
|
631
634
|
confidence: "MEDIUM",
|
|
632
635
|
action: "warn",
|
|
633
|
-
version:
|
|
636
|
+
version: 5,
|
|
634
637
|
status: "experimental",
|
|
635
638
|
cwe: [
|
|
636
639
|
"CWE-942",
|
|
@@ -656,7 +659,7 @@ var free_bundle_default = {
|
|
|
656
659
|
flags: "",
|
|
657
660
|
antiPatternScope: "block"
|
|
658
661
|
},
|
|
659
|
-
explanation:
|
|
662
|
+
explanation: "The server reflects the incoming Origin request header back into Access-Control-Allow-Origin without validating it against an allowlist. This is more dangerous than a static wildcard: any attacker-controlled origin can read authenticated API responses. CVE-2024-25124 (CVSS 9.8) in the Fiber Go framework exploited exactly this pattern, granting any origin full credentialed access to protected endpoints (CWE-942, CWE-346).",
|
|
660
663
|
recommendation: "Validate the incoming Origin header against a server-side allowlist before reflecting it. Store allowed origins in an environment variable (ALLOWED_ORIGINS) and check membership before setting Access-Control-Allow-Origin. Never reflect req.headers.origin directly.",
|
|
661
664
|
fix: "const allowed = (process.env.ALLOWED_ORIGINS || '').split(','); if (allowed.includes(req.headers.origin)) res.setHeader('Access-Control-Allow-Origin', req.headers.origin);",
|
|
662
665
|
findingType: "vulnerability",
|
|
@@ -677,7 +680,7 @@ var free_bundle_default = {
|
|
|
677
680
|
severity: "high",
|
|
678
681
|
confidence: "MEDIUM",
|
|
679
682
|
action: "warn",
|
|
680
|
-
version:
|
|
683
|
+
version: 6,
|
|
681
684
|
status: "experimental",
|
|
682
685
|
cwe: [
|
|
683
686
|
"CWE-942",
|
|
@@ -711,7 +714,7 @@ var free_bundle_default = {
|
|
|
711
714
|
],
|
|
712
715
|
flags: ""
|
|
713
716
|
},
|
|
714
|
-
explanation: "A wildcard CORS origin (Access-Control-Allow-Origin: *) was detected. For API endpoints returning user data, this allows any origin on the internet to read responses. Combined with credentials: 'include', wildcard origins are rejected by browsers \u2014 but without credentials, sensitive data is still exposed to cross-origin requests from attacker-controlled pages
|
|
717
|
+
explanation: "A wildcard CORS origin (Access-Control-Allow-Origin: *) was detected. For API endpoints returning user data, this allows any origin on the internet to read responses. Combined with credentials: 'include', wildcard origins are rejected by browsers \u2014 but without credentials, sensitive data is still exposed to cross-origin requests from attacker-controlled pages.",
|
|
715
718
|
recommendation: "Replace the wildcard with an explicit allowlist of trusted origins. Use environment variables for origin configuration (ALLOWED_ORIGINS) so production and development settings can differ. Audit whether this endpoint requires CORS at all.",
|
|
716
719
|
fix: "Replace `'*'` with `process.env.ALLOWED_ORIGIN` and validate against an allowlist.",
|
|
717
720
|
findingType: "vulnerability",
|
|
@@ -1644,7 +1647,7 @@ var free_bundle_default = {
|
|
|
1644
1647
|
severity: "critical",
|
|
1645
1648
|
confidence: "HIGH",
|
|
1646
1649
|
action: "block",
|
|
1647
|
-
version:
|
|
1650
|
+
version: 6,
|
|
1648
1651
|
status: "experimental",
|
|
1649
1652
|
cwe: [
|
|
1650
1653
|
"CWE-798"
|
|
@@ -1669,7 +1672,7 @@ var free_bundle_default = {
|
|
|
1669
1672
|
],
|
|
1670
1673
|
flags: ""
|
|
1671
1674
|
},
|
|
1672
|
-
explanation: "A hardcoded Stripe live secret key (sk_live_ prefix) was detected in source. This key grants full access to the Stripe account including charges, refunds, customer data, and payouts \u2014 immediate payment account compromise if exposed
|
|
1675
|
+
explanation: "A hardcoded Stripe live secret key (sk_live_ prefix) was detected in source. This key grants full access to the Stripe account including charges, refunds, customer data, and payouts \u2014 immediate payment account compromise if exposed.",
|
|
1673
1676
|
recommendation: "Remove the key immediately and roll it in the Stripe dashboard under Developers > API Keys. Store the key in an environment variable (STRIPE_SECRET_KEY) loaded at runtime. Never commit live API keys to version control.",
|
|
1674
1677
|
fix: "Replace with `process.env.STRIPE_SECRET_KEY` and add it to .env.local (gitignored). Rotate the exposed key immediately.",
|
|
1675
1678
|
findingType: "vulnerability",
|
|
@@ -2396,8 +2399,8 @@ async function scan(options, proRules, onProgress) {
|
|
|
2396
2399
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2397
2400
|
policyUsed: policy.project.name,
|
|
2398
2401
|
// Degraded when ANY of: coderef version-skip, collection truncation, a file
|
|
2399
|
-
// skipped for being too large, OR a symlink not followed (
|
|
2400
|
-
// The oversized-skip case
|
|
2402
|
+
// skipped for being too large, OR a symlink not followed (symlink reporting).
|
|
2403
|
+
// The oversized-skip case and the symlink-skip
|
|
2401
2404
|
// case both mean content was NOT scanned — the scan is incomplete, so it must
|
|
2402
2405
|
// NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL and
|
|
2403
2406
|
// intentionally EXCLUDED — a binary file legitimately has no source to scan.
|
|
@@ -2505,12 +2508,12 @@ function toSarif(result) {
|
|
|
2505
2508
|
|
|
2506
2509
|
// src/core/render.ts
|
|
2507
2510
|
import chalk from "chalk";
|
|
2508
|
-
import { existsSync as existsSync2
|
|
2511
|
+
import { existsSync as existsSync2 } from "fs";
|
|
2509
2512
|
import { join as join4, basename as basename2 } from "path";
|
|
2510
2513
|
import { homedir } from "os";
|
|
2511
|
-
var DOCS_URL = "
|
|
2512
|
-
var SITE_URL = "
|
|
2513
|
-
var PRICING_URL = "
|
|
2514
|
+
var DOCS_URL = goLink("docs");
|
|
2515
|
+
var SITE_URL = goLink("site");
|
|
2516
|
+
var PRICING_URL = goLink("pricing");
|
|
2514
2517
|
var ISSUES_URL = "https://github.com/agenticcli/shipguard/issues";
|
|
2515
2518
|
var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
|
|
2516
2519
|
var BOX_WIDTH = 78;
|
|
@@ -2852,8 +2855,8 @@ function welcomeBanner(configDir) {
|
|
|
2852
2855
|
return "";
|
|
2853
2856
|
}
|
|
2854
2857
|
try {
|
|
2855
|
-
|
|
2856
|
-
|
|
2858
|
+
ensureSecureDir(dir);
|
|
2859
|
+
writeSecureFileSync(marker, "1");
|
|
2857
2860
|
} catch {
|
|
2858
2861
|
}
|
|
2859
2862
|
const BANNER_INNER = BOX_WIDTH - 2;
|
|
@@ -2881,7 +2884,7 @@ function welcomeBanner(configDir) {
|
|
|
2881
2884
|
bannerLine(`Docs: ${chalk.underline(DOCS_URL)}`),
|
|
2882
2885
|
empty,
|
|
2883
2886
|
bannerLine(chalk.dim("Pseudonymous usage ping \u2014 opt out: shipguard telemetry disable")),
|
|
2884
|
-
bannerLine(chalk.dim(`or SHIPGUARD_TELEMETRY=0 \xB7 Details: ${chalk.underline("
|
|
2887
|
+
bannerLine(chalk.dim(`or SHIPGUARD_TELEMETRY=0 \xB7 Details: ${chalk.underline(goLink("telemetry"))}`)),
|
|
2885
2888
|
bottom,
|
|
2886
2889
|
""
|
|
2887
2890
|
].join("\n");
|
|
@@ -2967,8 +2970,61 @@ function displayWidth(str) {
|
|
|
2967
2970
|
return width;
|
|
2968
2971
|
}
|
|
2969
2972
|
|
|
2973
|
+
// src/core/history/finding-key.ts
|
|
2974
|
+
import { createHmac, randomBytes } from "crypto";
|
|
2975
|
+
import { chmodSync, existsSync as existsSync3, linkSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
|
|
2976
|
+
var SALT_BYTES = 32;
|
|
2977
|
+
var SALT_HEX = /^[0-9a-f]{64}$/;
|
|
2978
|
+
function saltPathFor(dbPath) {
|
|
2979
|
+
return `${dbPath}.salt`;
|
|
2980
|
+
}
|
|
2981
|
+
function keyFindingIdentity(salt, identityDigest) {
|
|
2982
|
+
return createHmac("sha256", salt).update(identityDigest).digest("hex").slice(0, 16);
|
|
2983
|
+
}
|
|
2984
|
+
function readSalt(path) {
|
|
2985
|
+
let text;
|
|
2986
|
+
try {
|
|
2987
|
+
text = readFileSync(path, "utf-8").trim();
|
|
2988
|
+
} catch (err) {
|
|
2989
|
+
return { ok: false, reason: `Could not read the history salt file ${path}: ${err instanceof Error ? err.message : err}` };
|
|
2990
|
+
}
|
|
2991
|
+
if (!SALT_HEX.test(text)) {
|
|
2992
|
+
return {
|
|
2993
|
+
ok: false,
|
|
2994
|
+
reason: `The history salt file ${path} is not a valid salt. Delete it (and the history file) to start fresh; finding identities recorded earlier will no longer match.`
|
|
2995
|
+
};
|
|
2996
|
+
}
|
|
2997
|
+
try {
|
|
2998
|
+
if ((statSync(path).mode & 63) !== 0) chmodSync(path, 384);
|
|
2999
|
+
} catch (err) {
|
|
3000
|
+
console.error(`shipguard: could not tighten permissions on ${path}: ${err instanceof Error ? err.message : err}`);
|
|
3001
|
+
}
|
|
3002
|
+
return { ok: true, salt: Buffer.from(text, "hex") };
|
|
3003
|
+
}
|
|
3004
|
+
function loadOrCreateSalt(dbPath) {
|
|
3005
|
+
const path = saltPathFor(dbPath);
|
|
3006
|
+
if (existsSync3(path)) return readSalt(path);
|
|
3007
|
+
const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
3008
|
+
try {
|
|
3009
|
+
writeFileSync(tmp, randomBytes(SALT_BYTES).toString("hex") + "\n", { mode: 384, flag: "wx" });
|
|
3010
|
+
try {
|
|
3011
|
+
linkSync(tmp, path);
|
|
3012
|
+
} catch (err) {
|
|
3013
|
+
if (err.code !== "EEXIST") throw err;
|
|
3014
|
+
}
|
|
3015
|
+
} catch (err) {
|
|
3016
|
+
return { ok: false, reason: `Could not create the history salt file ${path}: ${err instanceof Error ? err.message : err}` };
|
|
3017
|
+
} finally {
|
|
3018
|
+
try {
|
|
3019
|
+
unlinkSync(tmp);
|
|
3020
|
+
} catch {
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
return readSalt(path);
|
|
3024
|
+
}
|
|
3025
|
+
|
|
2970
3026
|
// src/core/history/schema.ts
|
|
2971
|
-
var CURRENT_SCHEMA_VERSION =
|
|
3027
|
+
var CURRENT_SCHEMA_VERSION = 3;
|
|
2972
3028
|
var MIGRATION_1_INIT = `
|
|
2973
3029
|
CREATE TABLE IF NOT EXISTS schema_meta (
|
|
2974
3030
|
schema_version INTEGER NOT NULL,
|
|
@@ -3040,9 +3096,19 @@ CREATE TABLE IF NOT EXISTS scan_id_reservations (
|
|
|
3040
3096
|
CREATE INDEX IF NOT EXISTS idx_scan_id_reservations_created
|
|
3041
3097
|
ON scan_id_reservations (created_at);
|
|
3042
3098
|
`;
|
|
3099
|
+
var MIGRATION_3_KEYED_FINDING_KEYS = `SELECT 1;`;
|
|
3043
3100
|
var MIGRATIONS = [
|
|
3044
3101
|
{ version: 1, sql: MIGRATION_1_INIT },
|
|
3045
|
-
{ version: 2, sql: MIGRATION_2_SCAN_ID_RESERVATIONS }
|
|
3102
|
+
{ version: 2, sql: MIGRATION_2_SCAN_ID_RESERVATIONS },
|
|
3103
|
+
{
|
|
3104
|
+
version: 3,
|
|
3105
|
+
sql: MIGRATION_3_KEYED_FINDING_KEYS,
|
|
3106
|
+
run: (db, salt) => {
|
|
3107
|
+
const rows = db.prepare("SELECT id, finding_key FROM findings").all();
|
|
3108
|
+
const update = db.prepare("UPDATE findings SET finding_key = ? WHERE id = ?");
|
|
3109
|
+
for (const row of rows) update.run(keyFindingIdentity(salt, row.finding_key), row.id);
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3046
3112
|
];
|
|
3047
3113
|
var UNVERSIONED = "unversioned";
|
|
3048
3114
|
|
|
@@ -3063,7 +3129,7 @@ function resolveHistoryPath(cwd, policy) {
|
|
|
3063
3129
|
// src/core/history/identity.ts
|
|
3064
3130
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
3065
3131
|
import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
|
|
3066
|
-
import { existsSync as
|
|
3132
|
+
import { existsSync as existsSync4, mkdirSync, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
3067
3133
|
import { dirname as dirname3, join as join5 } from "path";
|
|
3068
3134
|
function tryGit(cwd, args) {
|
|
3069
3135
|
try {
|
|
@@ -3075,7 +3141,7 @@ function tryGit(cwd, args) {
|
|
|
3075
3141
|
function ensureGitignored(cwd, entry) {
|
|
3076
3142
|
try {
|
|
3077
3143
|
const gitignorePath = join5(cwd, ".gitignore");
|
|
3078
|
-
const existing =
|
|
3144
|
+
const existing = existsSync4(gitignorePath) ? readFileSync2(gitignorePath, "utf-8") : "";
|
|
3079
3145
|
const alreadyPresent = existing.split("\n").map((l) => l.trim()).some((l) => l === entry || l === entry.replace(/\/$/, ""));
|
|
3080
3146
|
if (alreadyPresent) return;
|
|
3081
3147
|
const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
|
|
@@ -3096,14 +3162,14 @@ function resolveRepoIdentity(cwd) {
|
|
|
3096
3162
|
}
|
|
3097
3163
|
const fallbackPath = join5(cwd, DEFAULT_REPO_ID_FALLBACK_PATH);
|
|
3098
3164
|
try {
|
|
3099
|
-
if (
|
|
3100
|
-
const existing =
|
|
3165
|
+
if (existsSync4(fallbackPath)) {
|
|
3166
|
+
const existing = readFileSync2(fallbackPath, "utf-8").trim();
|
|
3101
3167
|
if (existing) {
|
|
3102
3168
|
return { repoId: existing, repoIdKind: "fallback-uuid", remoteLabel };
|
|
3103
3169
|
}
|
|
3104
3170
|
}
|
|
3105
3171
|
const id = randomUUID2();
|
|
3106
|
-
|
|
3172
|
+
mkdirSync(dirname3(fallbackPath), { recursive: true });
|
|
3107
3173
|
writeFileSync2(fallbackPath, `${id}
|
|
3108
3174
|
`, "utf-8");
|
|
3109
3175
|
ensureGitignored(cwd, ".shipguard/");
|
|
@@ -3143,7 +3209,7 @@ function computeScopeFingerprint(input) {
|
|
|
3143
3209
|
|
|
3144
3210
|
// src/core/history/store.ts
|
|
3145
3211
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
3146
|
-
import { existsSync as
|
|
3212
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync2 } from "fs";
|
|
3147
3213
|
import { dirname as dirname4 } from "path";
|
|
3148
3214
|
var sqliteModulePromise;
|
|
3149
3215
|
var warningFilterInstalled = false;
|
|
@@ -3162,6 +3228,9 @@ function installSqliteWarningFilter() {
|
|
|
3162
3228
|
});
|
|
3163
3229
|
}
|
|
3164
3230
|
var NODE_SQLITE_SPECIFIER = ["node", "sqlite"].join(":");
|
|
3231
|
+
function sqliteUnavailableReason(nodeVersion = process.versions.node) {
|
|
3232
|
+
return `node:sqlite is not available on Node.js ${nodeVersion} (scan history requires Node >=22.5). Upgrade Node to enable history; until then history is not recorded and regression checks are skipped. The scan's own findings/verdict are unaffected.`;
|
|
3233
|
+
}
|
|
3165
3234
|
async function loadSqliteModule() {
|
|
3166
3235
|
if (!sqliteModulePromise) {
|
|
3167
3236
|
installSqliteWarningFilter();
|
|
@@ -3174,12 +3243,14 @@ function isBusyOrLockedError(err) {
|
|
|
3174
3243
|
return /SQLITE_BUSY|database is locked|SQLITE_LOCKED/i.test(message);
|
|
3175
3244
|
}
|
|
3176
3245
|
var HistoryStore = class _HistoryStore {
|
|
3177
|
-
constructor(db, path) {
|
|
3246
|
+
constructor(db, path, salt) {
|
|
3178
3247
|
this.db = db;
|
|
3179
3248
|
this.path = path;
|
|
3249
|
+
this.salt = salt;
|
|
3180
3250
|
}
|
|
3181
3251
|
db;
|
|
3182
3252
|
path;
|
|
3253
|
+
salt;
|
|
3183
3254
|
/**
|
|
3184
3255
|
* Open (creating if absent) + forward-only-migrate + integrity-check the history store.
|
|
3185
3256
|
* NEVER throws — every failure mode returns a typed `{ ok: false, status, reason }` so
|
|
@@ -3191,12 +3262,12 @@ var HistoryStore = class _HistoryStore {
|
|
|
3191
3262
|
return {
|
|
3192
3263
|
ok: false,
|
|
3193
3264
|
status: "unavailable",
|
|
3194
|
-
reason:
|
|
3265
|
+
reason: sqliteUnavailableReason()
|
|
3195
3266
|
};
|
|
3196
3267
|
}
|
|
3197
|
-
const preExisted =
|
|
3268
|
+
const preExisted = existsSync5(dbPath);
|
|
3198
3269
|
try {
|
|
3199
|
-
|
|
3270
|
+
mkdirSync2(dirname4(dbPath), { recursive: true });
|
|
3200
3271
|
} catch (err) {
|
|
3201
3272
|
return {
|
|
3202
3273
|
ok: false,
|
|
@@ -3204,6 +3275,11 @@ var HistoryStore = class _HistoryStore {
|
|
|
3204
3275
|
reason: `Could not create the history directory: ${err instanceof Error ? err.message : err}`
|
|
3205
3276
|
};
|
|
3206
3277
|
}
|
|
3278
|
+
const saltResult = loadOrCreateSalt(dbPath);
|
|
3279
|
+
if (!saltResult.ok) {
|
|
3280
|
+
return { ok: false, status: "unavailable", reason: saltResult.reason };
|
|
3281
|
+
}
|
|
3282
|
+
const salt = saltResult.salt;
|
|
3207
3283
|
let db;
|
|
3208
3284
|
try {
|
|
3209
3285
|
db = new sqlite.DatabaseSync(dbPath);
|
|
@@ -3216,8 +3292,8 @@ var HistoryStore = class _HistoryStore {
|
|
|
3216
3292
|
};
|
|
3217
3293
|
}
|
|
3218
3294
|
try {
|
|
3219
|
-
db.exec("PRAGMA journal_mode = WAL");
|
|
3220
3295
|
db.exec("PRAGMA busy_timeout = 5000");
|
|
3296
|
+
db.exec("PRAGMA journal_mode = WAL");
|
|
3221
3297
|
db.exec("PRAGMA foreign_keys = ON");
|
|
3222
3298
|
} catch (err) {
|
|
3223
3299
|
const reason = err instanceof Error ? err.message : String(err);
|
|
@@ -3270,11 +3346,21 @@ var HistoryStore = class _HistoryStore {
|
|
|
3270
3346
|
const insertMeta = db.prepare(
|
|
3271
3347
|
"INSERT INTO schema_meta (schema_version, created_at, cli_version_created_with) VALUES (?, ?, ?)"
|
|
3272
3348
|
);
|
|
3349
|
+
const mayNeedScrub = existingVersion > 0 && existingVersion < 3;
|
|
3350
|
+
if (mayNeedScrub) db.exec("PRAGMA secure_delete = ON");
|
|
3351
|
+
let rekeyedHere = false;
|
|
3273
3352
|
for (const migration of MIGRATIONS) {
|
|
3274
3353
|
if (migration.version <= existingVersion) continue;
|
|
3275
3354
|
try {
|
|
3276
3355
|
db.exec("BEGIN IMMEDIATE");
|
|
3356
|
+
const lockedRow = db.prepare("SELECT MAX(schema_version) AS v FROM schema_meta").get();
|
|
3357
|
+
if (migration.version <= (lockedRow?.v ?? 0)) {
|
|
3358
|
+
db.exec("COMMIT");
|
|
3359
|
+
continue;
|
|
3360
|
+
}
|
|
3277
3361
|
db.exec(migration.sql);
|
|
3362
|
+
migration.run?.(db, salt);
|
|
3363
|
+
if (migration.version === 3 && mayNeedScrub) rekeyedHere = true;
|
|
3278
3364
|
insertMeta.run(migration.version, (/* @__PURE__ */ new Date()).toISOString(), cliVersion);
|
|
3279
3365
|
db.exec("COMMIT");
|
|
3280
3366
|
} catch (err) {
|
|
@@ -3291,6 +3377,17 @@ var HistoryStore = class _HistoryStore {
|
|
|
3291
3377
|
};
|
|
3292
3378
|
}
|
|
3293
3379
|
}
|
|
3380
|
+
if (rekeyedHere) {
|
|
3381
|
+
try {
|
|
3382
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
3383
|
+
db.exec("VACUUM");
|
|
3384
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
3385
|
+
} catch (err) {
|
|
3386
|
+
logger.warn(
|
|
3387
|
+
`ShipGuard history: the upgrade re-keyed your finding identities, but cleaning the old values out of ${dbPath} failed (${err instanceof Error ? err.message : err}). Delete the file if you need them gone.`
|
|
3388
|
+
);
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3294
3391
|
} catch (err) {
|
|
3295
3392
|
try {
|
|
3296
3393
|
db.close();
|
|
@@ -3299,7 +3396,7 @@ var HistoryStore = class _HistoryStore {
|
|
|
3299
3396
|
const reason = err instanceof Error ? err.message : String(err);
|
|
3300
3397
|
return { ok: false, status: "corrupt", reason: `History store migration bookkeeping failed: ${reason}` };
|
|
3301
3398
|
}
|
|
3302
|
-
return { ok: true, store: new _HistoryStore(db, dbPath) };
|
|
3399
|
+
return { ok: true, store: new _HistoryStore(db, dbPath, salt) };
|
|
3303
3400
|
}
|
|
3304
3401
|
/**
|
|
3305
3402
|
* One transaction per scan record (§1.4): begin → insert scan row + rule-outcome rows +
|
|
@@ -3351,7 +3448,7 @@ var HistoryStore = class _HistoryStore {
|
|
|
3351
3448
|
insertFinding.run(
|
|
3352
3449
|
input.scanId,
|
|
3353
3450
|
f.ruleId,
|
|
3354
|
-
f.findingKey,
|
|
3451
|
+
keyFindingIdentity(this.salt, f.findingKey),
|
|
3355
3452
|
f.filePath ?? null,
|
|
3356
3453
|
f.severity ?? null,
|
|
3357
3454
|
f.blocking ? 1 : 0,
|
|
@@ -3399,7 +3496,7 @@ var HistoryStore = class _HistoryStore {
|
|
|
3399
3496
|
};
|
|
3400
3497
|
}
|
|
3401
3498
|
/**
|
|
3402
|
-
*
|
|
3499
|
+
* ScanId reuse — look up or mint the scanId for a PRE-scan reuse key
|
|
3403
3500
|
* (repo_id + reuse_key, see history/scan-id.ts). Never throws — every failure (lock
|
|
3404
3501
|
* timeout, disk full, etc.) returns `{ ok: false, reason }` so the caller falls back to a
|
|
3405
3502
|
* fresh in-memory `randomUUID()` exactly like today (graceful degrade, §1.6's pattern).
|
|
@@ -3744,7 +3841,7 @@ import { randomUUID as randomUUID6 } from "crypto";
|
|
|
3744
3841
|
|
|
3745
3842
|
// src/core/telemetry-config.ts
|
|
3746
3843
|
import { randomUUID as randomUUID5 } from "crypto";
|
|
3747
|
-
import {
|
|
3844
|
+
import { existsSync as existsSync6, readFileSync as readFileSync3 } from "fs";
|
|
3748
3845
|
import { homedir as homedir2 } from "os";
|
|
3749
3846
|
import { join as join6 } from "path";
|
|
3750
3847
|
import YAML2 from "yaml";
|
|
@@ -3759,8 +3856,8 @@ function configFilePath(dir = getConfigDir()) {
|
|
|
3759
3856
|
function readUserConfig(dir = getConfigDir()) {
|
|
3760
3857
|
const file = configFilePath(dir);
|
|
3761
3858
|
try {
|
|
3762
|
-
if (!
|
|
3763
|
-
const parsed = JSON.parse(
|
|
3859
|
+
if (!existsSync6(file)) return {};
|
|
3860
|
+
const parsed = JSON.parse(readFileSync3(file, "utf-8"));
|
|
3764
3861
|
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
3765
3862
|
} catch (err) {
|
|
3766
3863
|
logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
@@ -3770,8 +3867,8 @@ function readUserConfig(dir = getConfigDir()) {
|
|
|
3770
3867
|
function userConfigUnreadable(dir = getConfigDir()) {
|
|
3771
3868
|
const file = configFilePath(dir);
|
|
3772
3869
|
try {
|
|
3773
|
-
if (!
|
|
3774
|
-
const parsed = JSON.parse(
|
|
3870
|
+
if (!existsSync6(file)) return false;
|
|
3871
|
+
const parsed = JSON.parse(readFileSync3(file, "utf-8"));
|
|
3775
3872
|
return !(parsed && typeof parsed === "object" && !Array.isArray(parsed));
|
|
3776
3873
|
} catch {
|
|
3777
3874
|
return true;
|
|
@@ -3780,9 +3877,8 @@ function userConfigUnreadable(dir = getConfigDir()) {
|
|
|
3780
3877
|
var UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
3781
3878
|
function writeConfig(dir, next) {
|
|
3782
3879
|
const file = configFilePath(dir);
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
chmodSync(file, 384);
|
|
3880
|
+
ensureSecureDir(dir);
|
|
3881
|
+
writeSecureFileSync(file, JSON.stringify(next, null, 2) + "\n");
|
|
3786
3882
|
return file;
|
|
3787
3883
|
}
|
|
3788
3884
|
function readInstallId(dir = getConfigDir()) {
|
|
@@ -3815,12 +3911,12 @@ function writeUserEnabled(dir, enabled) {
|
|
|
3815
3911
|
return writeConfig(dir, { ...readUserConfig(dir), enabled });
|
|
3816
3912
|
}
|
|
3817
3913
|
function noticeShown(dir = getConfigDir()) {
|
|
3818
|
-
return
|
|
3914
|
+
return existsSync6(join6(dir, NOTICE_MARKER));
|
|
3819
3915
|
}
|
|
3820
3916
|
function markNoticeShown(dir = getConfigDir()) {
|
|
3821
3917
|
try {
|
|
3822
|
-
|
|
3823
|
-
|
|
3918
|
+
ensureSecureDir(dir);
|
|
3919
|
+
writeSecureFileSync(join6(dir, NOTICE_MARKER), "1\n");
|
|
3824
3920
|
} catch (err) {
|
|
3825
3921
|
logger.debug(`telemetry: could not persist the notice marker: ${err instanceof Error ? err.message : String(err)}`);
|
|
3826
3922
|
}
|
|
@@ -3839,8 +3935,8 @@ function policyTelemetryEnabled(policy) {
|
|
|
3839
3935
|
}
|
|
3840
3936
|
function readYamlToggle(file) {
|
|
3841
3937
|
try {
|
|
3842
|
-
if (!
|
|
3843
|
-
return policyTelemetryEnabled(YAML2.parse(
|
|
3938
|
+
if (!existsSync6(file)) return void 0;
|
|
3939
|
+
return policyTelemetryEnabled(YAML2.parse(readFileSync3(file, "utf-8")));
|
|
3844
3940
|
} catch (err) {
|
|
3845
3941
|
logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
3846
3942
|
return void 0;
|
|
@@ -3965,7 +4061,7 @@ function decideTelemetry(input = {}) {
|
|
|
3965
4061
|
if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
|
|
3966
4062
|
return { enabled: true, source: "default" };
|
|
3967
4063
|
}
|
|
3968
|
-
var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`.
|
|
4064
|
+
var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`. " + goLink("telemetry");
|
|
3969
4065
|
var PING_WAIT_MS = 1500;
|
|
3970
4066
|
var FETCH_TIMEOUT_MS = 1e3;
|
|
3971
4067
|
function debugEnabled(env) {
|
|
@@ -4052,8 +4148,8 @@ function sendTelemetry(input, opts = {}) {
|
|
|
4052
4148
|
}
|
|
4053
4149
|
|
|
4054
4150
|
// src/commands/scan.ts
|
|
4055
|
-
var LEARN_MORE =
|
|
4056
|
-
var CLI_VERSION = true ? "0.
|
|
4151
|
+
var LEARN_MORE = `Docs ${goLink("docs")} \xB7 Site ${goLink("site")} \xB7 Pricing ${goLink("pricing")} \xB7 Issues https://github.com/agenticcli/shipguard/issues`;
|
|
4152
|
+
var CLI_VERSION = true ? "0.8.0" : process.env.npm_package_version ?? "0.0.0-dev";
|
|
4057
4153
|
function resolveExitCode(opts) {
|
|
4058
4154
|
if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
|
|
4059
4155
|
return EXIT_CODES.BLOCKED;
|
|
@@ -4065,21 +4161,30 @@ function proFetchActionHint(code, retryAfterSeconds) {
|
|
|
4065
4161
|
case "AUTH_FAILED":
|
|
4066
4162
|
return "Run `shipguard login` to re-authenticate, or pass --allow-degraded to run local rules only.";
|
|
4067
4163
|
case "INSUFFICIENT_CREDITS":
|
|
4068
|
-
return
|
|
4164
|
+
return `Buy more credits at ${goLink("billing")}, or pass --allow-degraded to run local rules only.`;
|
|
4069
4165
|
case "RATE_LIMITED":
|
|
4070
4166
|
return retryAfterSeconds !== void 0 ? `Rate limited \u2014 retry after ${retryAfterSeconds}s, or pass --allow-degraded to run local rules only.` : "Rate limited \u2014 wait and retry, or pass --allow-degraded to run local rules only.";
|
|
4071
4167
|
case "SERVER_ERROR":
|
|
4072
4168
|
return "This looks like a transient server/network issue \u2014 retry the scan, or pass --allow-degraded to run local rules only.";
|
|
4169
|
+
case "PLATFORM_UNAVAILABLE":
|
|
4170
|
+
return platformUnavailableMessage(retryAfterSeconds);
|
|
4073
4171
|
case "BUNDLE_INVALID":
|
|
4074
4172
|
return "The pro rule bundle failed validation (server-side issue) \u2014 retry, or pass --allow-degraded to run local rules only. If this persists, contact support.";
|
|
4075
4173
|
case "NO_ACTIVE_RELEASE":
|
|
4076
|
-
return "The Pro rule server has no active rule release yet \u2014 this is a server-side configuration gap, not something a retry or re-login will fix. Check
|
|
4174
|
+
return "The Pro rule server has no active rule release yet \u2014 this is a server-side configuration gap, not something a retry or re-login will fix. Check " + goLink("docs") + " or contact support, or pass --allow-degraded to run local rules only in the meantime.";
|
|
4077
4175
|
default:
|
|
4078
4176
|
return "Retry the scan, or pass --allow-degraded to run local rules only.";
|
|
4079
4177
|
}
|
|
4080
4178
|
}
|
|
4179
|
+
function formatSuggestedWait(seconds) {
|
|
4180
|
+
return seconds >= 60 && seconds % 60 === 0 ? `${seconds / 60} min` : `${seconds} s`;
|
|
4181
|
+
}
|
|
4182
|
+
function platformUnavailableMessage(retryAfterSeconds) {
|
|
4183
|
+
const wait = retryAfterSeconds !== void 0 ? ` (suggested wait: ${formatSuggestedWait(retryAfterSeconds)})` : "";
|
|
4184
|
+
return `ShipGuard's service is temporarily unavailable. This is on our side, not a problem with your project. Please try again in a few minutes${wait}, or pass --allow-degraded to run local rules only.`;
|
|
4185
|
+
}
|
|
4081
4186
|
function isProjectRoot(dir) {
|
|
4082
|
-
return
|
|
4187
|
+
return existsSync7(join7(dir, "package.json")) || existsSync7(join7(dir, ".git"));
|
|
4083
4188
|
}
|
|
4084
4189
|
function scanCommand() {
|
|
4085
4190
|
return new Command2("scan").description("Scan your project for high-risk issues (verbose by default; use --quiet for one-line verdict)").argument("[path]", "Path to project root to scan (defaults to current directory)").option("--changed", "Only scan changed files from git diff").option("--report", "Generate a detailed Markdown report").option("--strict", "Opt-in hard gate: exit 1 if blocking findings exist, the scan did not finish, OR the verdict is DO_NOT_SHIP (default exit is 0 \u2014 verdict is informational, read the JSON `recommendation`)").option("--json", "Output results as JSON (machine-readable; suppresses all decoration)").option("--sarif", "Output results as SARIF 2.1.0 (for GitHub Code Scanning)").option("-q, --quiet", "One-line verdict only (suppresses progress, panel, and tips)").option("--pro", "Include pro quality gate rules (requires authentication)").option("--api-url <url>", "API server URL", "https://agenticcli.dev").option("--category <categories>", "Comma-separated category filter for pro rules").option("--beta", "Include beta-stage rules").option("--all", "Scan any directory, even without package.json or .git").option("--allow-degraded", "With --pro: fall back to local-only rules if the pro rule fetch fails, instead of failing loud (opt-in; restores the pre-2026-07-14 fallback behavior \u2014 see exit code 3 below)").option("--check-regressions", "Opt-in hard gate: exit 1 if a previously-passing blocking rule now fails under the same scan scope + corpus release (informational-only in --json unless this flag is set)").addHelpText("after", `
|
|
@@ -4116,16 +4221,18 @@ Exit codes (verdict-neutral by default \u2014 ShipGuard informs, you choose the
|
|
|
4116
4221
|
agrees with the printed verdict). OR with --check-regressions AND at
|
|
4117
4222
|
least one regression (see \`regressions\` in --json output \u2014
|
|
4118
4223
|
informational-only unless this flag is set).
|
|
4119
|
-
2 Config error (bad policy file, bad flags, non-project directory
|
|
4224
|
+
2 Config error (bad policy file, bad flags, non-project directory, scan path
|
|
4225
|
+
that does not exist or is not a directory).
|
|
4120
4226
|
3 Runtime error \u2014 the scan could not meaningfully run at all. This
|
|
4121
4227
|
INCLUDES an explicit --pro request whose rule fetch failed (auth,
|
|
4122
|
-
credits, rate limit, server, an invalid bundle,
|
|
4123
|
-
release on the server
|
|
4228
|
+
credits, rate limit, server, an invalid bundle, no active rule
|
|
4229
|
+
release on the server, or the platform being temporarily unavailable \u2014
|
|
4230
|
+
--json code PLATFORM_UNAVAILABLE, with retryAfterSeconds when known) \u2014 the requested gate did not run, so
|
|
4124
4231
|
ShipGuard fails loud instead of silently falling back to a free
|
|
4125
4232
|
scan. Pass --allow-degraded to opt back into the free-scan
|
|
4126
4233
|
fallback (degraded:true, exit code unaffected).
|
|
4127
4234
|
|
|
4128
|
-
Local history
|
|
4235
|
+
Local history: every scan is recorded to a local SQLite store
|
|
4129
4236
|
(\`.shipguard/history.db\` by default; override via \`history.path\` in
|
|
4130
4237
|
shipguard.policy.yml or SHIPGUARD_HISTORY_PATH). \`stateStatus\` in --json
|
|
4131
4238
|
reports whether that recording succeeded (complete/unavailable/corrupt) \u2014
|
|
@@ -4138,6 +4245,16 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
|
|
|
4138
4245
|
const cwd = scanPath ? resolve4(scanPath) : process.cwd();
|
|
4139
4246
|
const machineOutput = Boolean(opts.json) || Boolean(opts.sarif);
|
|
4140
4247
|
const quiet = Boolean(opts.quiet);
|
|
4248
|
+
if (scanPath) {
|
|
4249
|
+
const pathProblem = checkScanPath(cwd);
|
|
4250
|
+
if (pathProblem) {
|
|
4251
|
+
logger.error(pathProblem.message);
|
|
4252
|
+
if (machineOutput) {
|
|
4253
|
+
console.log(JSON.stringify({ error: pathProblem.message, code: pathProblem.code }));
|
|
4254
|
+
}
|
|
4255
|
+
await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
|
|
4256
|
+
}
|
|
4257
|
+
}
|
|
4141
4258
|
if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
|
|
4142
4259
|
logger.error(
|
|
4143
4260
|
`Refusing to scan a non-project directory ${cwd}. Pass a path (\`shipguard scan ./my-app\`) or \`--all\` to override.`
|
|
@@ -4146,7 +4263,7 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
|
|
|
4146
4263
|
console.log(`
|
|
4147
4264
|
${LEARN_MORE}`);
|
|
4148
4265
|
}
|
|
4149
|
-
|
|
4266
|
+
await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
|
|
4150
4267
|
}
|
|
4151
4268
|
const originalCwd = process.cwd();
|
|
4152
4269
|
if (scanPath) {
|
|
@@ -4161,6 +4278,30 @@ ${LEARN_MORE}`);
|
|
|
4161
4278
|
}
|
|
4162
4279
|
});
|
|
4163
4280
|
}
|
|
4281
|
+
async function exitWithError(exitCode, startTime, projectDir, policy) {
|
|
4282
|
+
try {
|
|
4283
|
+
await sendTelemetry(
|
|
4284
|
+
{ cliVersion: CLI_VERSION, verdict: "error", durationMs: Date.now() - startTime },
|
|
4285
|
+
{ policy, projectDir }
|
|
4286
|
+
);
|
|
4287
|
+
} catch (err) {
|
|
4288
|
+
logger.debug(`telemetry: error ping skipped (ignored): ${err instanceof Error ? err.message : String(err)}`);
|
|
4289
|
+
}
|
|
4290
|
+
return process.exit(exitCode);
|
|
4291
|
+
}
|
|
4292
|
+
function checkScanPath(absPath) {
|
|
4293
|
+
let isDir;
|
|
4294
|
+
try {
|
|
4295
|
+
isDir = statSync2(absPath).isDirectory();
|
|
4296
|
+
} catch (err) {
|
|
4297
|
+
const code = err.code;
|
|
4298
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
4299
|
+
return { code: "PATH_NOT_FOUND", message: `Scan path does not exist: ${absPath}` };
|
|
4300
|
+
}
|
|
4301
|
+
return { code: "PATH_NOT_FOUND", message: `Scan path cannot be read (${code ?? "unknown error"}): ${absPath}` };
|
|
4302
|
+
}
|
|
4303
|
+
return isDir ? null : { code: "PATH_NOT_A_DIRECTORY", message: `Scan path is not a directory: ${absPath}` };
|
|
4304
|
+
}
|
|
4164
4305
|
async function runScan(ctx) {
|
|
4165
4306
|
const { cwd, opts, machineOutput, quiet, startTime } = ctx;
|
|
4166
4307
|
let policy;
|
|
@@ -4168,7 +4309,7 @@ async function runScan(ctx) {
|
|
|
4168
4309
|
policy = await loadPolicy(cwd);
|
|
4169
4310
|
} catch (error) {
|
|
4170
4311
|
logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
|
|
4171
|
-
|
|
4312
|
+
await exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, cwd);
|
|
4172
4313
|
return;
|
|
4173
4314
|
}
|
|
4174
4315
|
const changedOnly = Boolean(opts.changed);
|
|
@@ -4219,8 +4360,8 @@ async function runScan(ctx) {
|
|
|
4219
4360
|
logger.info("Detecting stack...");
|
|
4220
4361
|
}
|
|
4221
4362
|
try {
|
|
4222
|
-
const { fetchProRules } = await import("./pro-scanner-
|
|
4223
|
-
const { hasConfig, generateConfig } = await import("./config-generator-
|
|
4363
|
+
const { fetchProRules } = await import("./pro-scanner-5GYWJ7AS.js");
|
|
4364
|
+
const { hasConfig, generateConfig } = await import("./config-generator-4MK6PGY5.js");
|
|
4224
4365
|
const frameworks = detectedFrameworks;
|
|
4225
4366
|
if (!hasConfig(cwd)) {
|
|
4226
4367
|
const configPath = generateConfig(cwd, frameworks);
|
|
@@ -4262,7 +4403,7 @@ async function runScan(ctx) {
|
|
|
4262
4403
|
} else {
|
|
4263
4404
|
console.log(JSON.stringify({ error: errMsg, code: "NO_RULES_APPLIED" }));
|
|
4264
4405
|
}
|
|
4265
|
-
|
|
4406
|
+
await exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
|
|
4266
4407
|
}
|
|
4267
4408
|
const rawErrCode = err?.code;
|
|
4268
4409
|
const KNOWN_PRO_FETCH_ERROR_CODES = [
|
|
@@ -4271,7 +4412,8 @@ async function runScan(ctx) {
|
|
|
4271
4412
|
"RATE_LIMITED",
|
|
4272
4413
|
"SERVER_ERROR",
|
|
4273
4414
|
"BUNDLE_INVALID",
|
|
4274
|
-
"NO_ACTIVE_RELEASE"
|
|
4415
|
+
"NO_ACTIVE_RELEASE",
|
|
4416
|
+
"PLATFORM_UNAVAILABLE"
|
|
4275
4417
|
];
|
|
4276
4418
|
const proErrorCode = typeof rawErrCode === "string" && KNOWN_PRO_FETCH_ERROR_CODES.includes(rawErrCode) ? rawErrCode : "SERVER_ERROR";
|
|
4277
4419
|
const retryAfterSeconds = err?.retryAfterSeconds;
|
|
@@ -4284,9 +4426,13 @@ async function runScan(ctx) {
|
|
|
4284
4426
|
};
|
|
4285
4427
|
} else {
|
|
4286
4428
|
const action = proFetchActionHint(proErrorCode, retryAfterSeconds);
|
|
4287
|
-
|
|
4288
|
-
|
|
4289
|
-
|
|
4429
|
+
if (proErrorCode === "PLATFORM_UNAVAILABLE") {
|
|
4430
|
+
logger.error(action);
|
|
4431
|
+
} else {
|
|
4432
|
+
logger.error(`Pro rules request failed [${proErrorCode}]: ${errMsg}`);
|
|
4433
|
+
logger.error(action);
|
|
4434
|
+
logger.error("Pass --allow-degraded to fall back to a free (local-rules-only) scan instead.");
|
|
4435
|
+
}
|
|
4290
4436
|
if (machineOutput) {
|
|
4291
4437
|
console.log(JSON.stringify({
|
|
4292
4438
|
error: errMsg,
|
|
@@ -4296,7 +4442,7 @@ async function runScan(ctx) {
|
|
|
4296
4442
|
...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
|
|
4297
4443
|
}));
|
|
4298
4444
|
}
|
|
4299
|
-
|
|
4445
|
+
await exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
|
|
4300
4446
|
}
|
|
4301
4447
|
}
|
|
4302
4448
|
}
|
|
@@ -4328,7 +4474,7 @@ async function runScan(ctx) {
|
|
|
4328
4474
|
} else {
|
|
4329
4475
|
console.log(JSON.stringify({ error: String(error) }));
|
|
4330
4476
|
}
|
|
4331
|
-
|
|
4477
|
+
return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
|
|
4332
4478
|
}
|
|
4333
4479
|
if (showProgress) {
|
|
4334
4480
|
process.stderr.write("\r\x1B[K");
|
|
@@ -4457,7 +4603,7 @@ async function runScan(ctx) {
|
|
|
4457
4603
|
logger.warn(
|
|
4458
4604
|
`Scan was truncated: file count or total size limit was reached. Results are INCOMPLETE \u2014 add a \`.shipguardignore\` or edit \`shipguard.policy.yml\` limits.`
|
|
4459
4605
|
);
|
|
4460
|
-
logger.warn(`Docs:
|
|
4606
|
+
logger.warn(`Docs: ${goLink("docs")}`);
|
|
4461
4607
|
}
|
|
4462
4608
|
console.log(coverageLine());
|
|
4463
4609
|
console.log("");
|
|
@@ -4495,7 +4641,7 @@ async function runScan(ctx) {
|
|
|
4495
4641
|
let exitCode = resolveExitCode({
|
|
4496
4642
|
strict: scanOptions.strict,
|
|
4497
4643
|
blockingCount: result.riskScore.blockingCount,
|
|
4498
|
-
//
|
|
4644
|
+
// the hard stop must not inherit the false-safe on an
|
|
4499
4645
|
// unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
|
|
4500
4646
|
degraded: result.degraded === true,
|
|
4501
4647
|
// CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
|
|
@@ -4531,7 +4677,54 @@ async function runScan(ctx) {
|
|
|
4531
4677
|
|
|
4532
4678
|
// src/commands/login.ts
|
|
4533
4679
|
import { Command as Command3 } from "commander";
|
|
4534
|
-
|
|
4680
|
+
|
|
4681
|
+
// src/utils/open-url.ts
|
|
4682
|
+
import { spawn } from "child_process";
|
|
4683
|
+
var isLoopback = (host) => host === "localhost" || host === "127.0.0.1" || host === "[::1]";
|
|
4684
|
+
function parseOpenableUrl(raw2, apiUrl) {
|
|
4685
|
+
if (typeof raw2 !== "string") return null;
|
|
4686
|
+
if (/[\u0000-\u0020\u007f]/.test(raw2)) return null;
|
|
4687
|
+
let u;
|
|
4688
|
+
try {
|
|
4689
|
+
u = new URL(raw2);
|
|
4690
|
+
} catch {
|
|
4691
|
+
return null;
|
|
4692
|
+
}
|
|
4693
|
+
if (u.username || u.password) return null;
|
|
4694
|
+
const host = u.hostname.toLowerCase();
|
|
4695
|
+
const loopback = isLoopback(host);
|
|
4696
|
+
if (u.protocol === "http:" && loopback) return u;
|
|
4697
|
+
if (u.protocol !== "https:") return null;
|
|
4698
|
+
if (loopback) return u;
|
|
4699
|
+
let apiHost = null;
|
|
4700
|
+
try {
|
|
4701
|
+
apiHost = apiUrl ? new URL(apiUrl).hostname.toLowerCase() : null;
|
|
4702
|
+
} catch {
|
|
4703
|
+
apiHost = null;
|
|
4704
|
+
}
|
|
4705
|
+
return apiHost !== null && host === apiHost ? u : null;
|
|
4706
|
+
}
|
|
4707
|
+
function openerFor(platform, href) {
|
|
4708
|
+
if (platform === "darwin") return { cmd: "open", args: [href] };
|
|
4709
|
+
if (platform === "win32") return { cmd: "rundll32", args: ["url.dll,FileProtocolHandler", href] };
|
|
4710
|
+
return { cmd: "xdg-open", args: [href] };
|
|
4711
|
+
}
|
|
4712
|
+
function openUrl(raw2, apiUrl, onError = () => {
|
|
4713
|
+
}) {
|
|
4714
|
+
const url = parseOpenableUrl(raw2, apiUrl);
|
|
4715
|
+
if (!url) return false;
|
|
4716
|
+
const { cmd, args } = openerFor(process.platform, url.href);
|
|
4717
|
+
try {
|
|
4718
|
+
const child = spawn(cmd, args, { stdio: "ignore", detached: true, shell: false });
|
|
4719
|
+
child.on("error", onError);
|
|
4720
|
+
child.unref();
|
|
4721
|
+
} catch (err) {
|
|
4722
|
+
onError(err instanceof Error ? err : new Error(String(err)));
|
|
4723
|
+
}
|
|
4724
|
+
return true;
|
|
4725
|
+
}
|
|
4726
|
+
|
|
4727
|
+
// src/commands/login.ts
|
|
4535
4728
|
var DEFAULT_API_URL = "https://agenticcli.dev";
|
|
4536
4729
|
function loginCommand() {
|
|
4537
4730
|
return new Command3("login").description("Authenticate with ShipGuard for pro features").option("--api-url <url>", "API server URL", DEFAULT_API_URL).action(async (opts) => {
|
|
@@ -4543,13 +4736,19 @@ function loginCommand() {
|
|
|
4543
4736
|
process.exit(2);
|
|
4544
4737
|
}
|
|
4545
4738
|
const { device_code, user_code, verification_uri, expires_in, interval } = await res.json();
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
|
|
4739
|
+
const safeUrl = parseOpenableUrl(verification_uri, apiUrl);
|
|
4740
|
+
if (safeUrl) {
|
|
4741
|
+
logger.info(`
|
|
4742
|
+
Visit: ${safeUrl.href}`);
|
|
4743
|
+
} else {
|
|
4744
|
+
logger.warn("\nThe server sent a verification URL that is not a safe link to the ShipGuard server, so it was not opened or shown.");
|
|
4745
|
+
logger.info(`Open ${apiUrl}/activate in your browser yourself.`);
|
|
4746
|
+
}
|
|
4747
|
+
logger.info(`Enter code: ${String(user_code).replace(/[^\x20-\x7E]/g, "")}
|
|
4549
4748
|
`);
|
|
4550
|
-
|
|
4551
|
-
|
|
4552
|
-
}
|
|
4749
|
+
if (safeUrl) {
|
|
4750
|
+
openUrl(safeUrl.href, apiUrl, (err) => logger.warn(`Could not open a browser (${err.message}). Open the link above manually.`));
|
|
4751
|
+
}
|
|
4553
4752
|
const deadline = Date.now() + expires_in * 1e3;
|
|
4554
4753
|
const pollMs = (interval ?? 5) * 1e3;
|
|
4555
4754
|
while (Date.now() < deadline) {
|
|
@@ -4632,7 +4831,7 @@ function statusCommand() {
|
|
|
4632
4831
|
// src/commands/history.ts
|
|
4633
4832
|
import { Command as Command6 } from "commander";
|
|
4634
4833
|
import { resolve as resolve5 } from "path";
|
|
4635
|
-
var CLI_VERSION2 = true ? "0.
|
|
4834
|
+
var CLI_VERSION2 = true ? "0.8.0" : process.env.npm_package_version ?? "0.0.0-dev";
|
|
4636
4835
|
function historyCommand() {
|
|
4637
4836
|
return new Command6("history").description("Show recent local scan history for this repo (read-only; --json for machine output)").argument("[path]", "Path to project root (defaults to current directory)").option("--json", "Output as JSON").option("--limit <n>", "Number of recent scans to show", (v) => Number.parseInt(v, 10) || 10, 10).action(async (scanPath, opts) => {
|
|
4638
4837
|
const cwd = scanPath ? resolve5(scanPath) : process.cwd();
|
|
@@ -4653,7 +4852,9 @@ function historyCommand() {
|
|
|
4653
4852
|
console.log(JSON.stringify({ version: 1, available: false, status: openResult.status, reason: openResult.reason }));
|
|
4654
4853
|
} else {
|
|
4655
4854
|
logger.warn(`History unavailable (${openResult.status}): ${openResult.reason}`);
|
|
4656
|
-
logger.info(
|
|
4855
|
+
logger.info(
|
|
4856
|
+
openResult.reason.startsWith("node:sqlite is not available") ? "No history to show: history cannot be recorded on this Node.js runtime, so every scan here skips it." : "No history to show. History is recorded automatically on the next successful scan."
|
|
4857
|
+
);
|
|
4657
4858
|
}
|
|
4658
4859
|
return;
|
|
4659
4860
|
}
|
|
@@ -4696,7 +4897,7 @@ function historyCommand() {
|
|
|
4696
4897
|
// src/commands/hook.ts
|
|
4697
4898
|
import { Command as Command7 } from "commander";
|
|
4698
4899
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
4699
|
-
import { chmodSync as chmodSync2, existsSync as
|
|
4900
|
+
import { chmodSync as chmodSync2, existsSync as existsSync8, mkdirSync as mkdirSync3, readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
4700
4901
|
import { dirname as dirname5, isAbsolute, join as join8, relative as relative2, resolve as resolve6 } from "path";
|
|
4701
4902
|
|
|
4702
4903
|
// src/core/hook-templates.ts
|
|
@@ -4789,13 +4990,13 @@ function isManaged(content) {
|
|
|
4789
4990
|
|
|
4790
4991
|
// src/commands/hook.ts
|
|
4791
4992
|
function writeManaged(path, whole, block, executable) {
|
|
4792
|
-
if (!
|
|
4793
|
-
|
|
4794
|
-
|
|
4993
|
+
if (!existsSync8(path)) {
|
|
4994
|
+
mkdirSync3(dirname5(path), { recursive: true });
|
|
4995
|
+
writeFileSync3(path, whole, "utf-8");
|
|
4795
4996
|
if (executable) chmodSync2(path, 493);
|
|
4796
4997
|
return { path, status: "created" };
|
|
4797
4998
|
}
|
|
4798
|
-
const current =
|
|
4999
|
+
const current = readFileSync4(path, "utf-8");
|
|
4799
5000
|
if (!isManaged(current)) {
|
|
4800
5001
|
return {
|
|
4801
5002
|
path,
|
|
@@ -4805,7 +5006,7 @@ function writeManaged(path, whole, block, executable) {
|
|
|
4805
5006
|
}
|
|
4806
5007
|
const merged = replaceManagedBlock(current, block) ?? whole;
|
|
4807
5008
|
if (merged === current) return { path, status: "unchanged" };
|
|
4808
|
-
|
|
5009
|
+
writeFileSync3(path, merged, "utf-8");
|
|
4809
5010
|
if (executable) chmodSync2(path, 493);
|
|
4810
5011
|
return { path, status: "updated" };
|
|
4811
5012
|
}
|
|
@@ -4826,12 +5027,12 @@ function installGit(cwd) {
|
|
|
4826
5027
|
function installClaude(cwd) {
|
|
4827
5028
|
const path = join8(cwd, ".claude", "settings.json");
|
|
4828
5029
|
const entry = { matcher: "Bash", hooks: [{ type: "command", command: CLAUDE_HOOK_COMMAND }] };
|
|
4829
|
-
if (!
|
|
4830
|
-
|
|
4831
|
-
|
|
5030
|
+
if (!existsSync8(path)) {
|
|
5031
|
+
mkdirSync3(dirname5(path), { recursive: true });
|
|
5032
|
+
writeFileSync3(path, JSON.stringify({ hooks: { PreToolUse: [entry] } }, null, 2) + "\n", "utf-8");
|
|
4832
5033
|
return [{ path, status: "created" }];
|
|
4833
5034
|
}
|
|
4834
|
-
const raw2 =
|
|
5035
|
+
const raw2 = readFileSync4(path, "utf-8");
|
|
4835
5036
|
let settings;
|
|
4836
5037
|
try {
|
|
4837
5038
|
settings = JSON.parse(raw2);
|
|
@@ -4861,7 +5062,7 @@ function installClaude(cwd) {
|
|
|
4861
5062
|
...settings,
|
|
4862
5063
|
hooks: { ...settings.hooks ?? {}, PreToolUse: next }
|
|
4863
5064
|
};
|
|
4864
|
-
|
|
5065
|
+
writeFileSync3(path, JSON.stringify(merged, null, 2) + "\n", "utf-8");
|
|
4865
5066
|
}
|
|
4866
5067
|
return [{ path, status }];
|
|
4867
5068
|
}
|
|
@@ -4952,7 +5153,7 @@ Exit codes:
|
|
|
4952
5153
|
|
|
4953
5154
|
// src/commands/schema.ts
|
|
4954
5155
|
import { Command as Command8 } from "commander";
|
|
4955
|
-
var CLI_VERSION3 = true ? "0.
|
|
5156
|
+
var CLI_VERSION3 = true ? "0.8.0" : process.env.npm_package_version ?? "0.0.0-dev";
|
|
4956
5157
|
var CURRENT_SCHEMA_VERSION2 = "5";
|
|
4957
5158
|
function buildSchemaContract(limits) {
|
|
4958
5159
|
const src = (value, fallback) => value === fallback ? "default" : "policy";
|
|
@@ -5186,7 +5387,7 @@ function rateCommand() {
|
|
|
5186
5387
|
|
|
5187
5388
|
// src/commands/telemetry.ts
|
|
5188
5389
|
import { Command as Command10 } from "commander";
|
|
5189
|
-
var DOCS = "
|
|
5390
|
+
var DOCS = goLink("telemetry");
|
|
5190
5391
|
var SOURCE_TEXT = {
|
|
5191
5392
|
"env:SHIPGUARD_TELEMETRY": "SHIPGUARD_TELEMETRY=0 is set in the environment",
|
|
5192
5393
|
"env:DO_NOT_TRACK": "DO_NOT_TRACK=1 is set in the environment",
|
|
@@ -5268,7 +5469,7 @@ function telemetryCommand() {
|
|
|
5268
5469
|
|
|
5269
5470
|
// src/handlers.ts
|
|
5270
5471
|
var ISSUES_URL3 = "https://github.com/agenticcli/shipguard/issues";
|
|
5271
|
-
var DOCS_URL2 = "
|
|
5472
|
+
var DOCS_URL2 = goLink("docs");
|
|
5272
5473
|
var REPORT_LINE = `Report this: ${ISSUES_URL3} \xB7 Docs: ${DOCS_URL2}`;
|
|
5273
5474
|
function handleUncaughtException(error) {
|
|
5274
5475
|
const message = error instanceof Error ? error.message : String(error);
|
|
@@ -5305,12 +5506,12 @@ if (rawArgs[0] === "?") {
|
|
|
5305
5506
|
process.argv = [process.argv[0], process.argv[1], "help"];
|
|
5306
5507
|
}
|
|
5307
5508
|
program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
|
|
5308
|
-
true ? "0.
|
|
5509
|
+
true ? "0.8.0" : process.env.npm_package_version ?? "0.0.0-dev"
|
|
5309
5510
|
).helpCommand(false).addHelpText("after", `
|
|
5310
5511
|
Learn more:
|
|
5311
|
-
Docs
|
|
5312
|
-
Site
|
|
5313
|
-
Pricing
|
|
5512
|
+
Docs ${goLink("docs")}
|
|
5513
|
+
Site ${goLink("site")}
|
|
5514
|
+
Pricing ${goLink("pricing")}
|
|
5314
5515
|
Issues ${ISSUES_URL4}`);
|
|
5315
5516
|
program.exitOverride();
|
|
5316
5517
|
function addSubcommand(cmd) {
|