@agenticcli/shipguard 0.12.0 → 0.13.1
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/LICENSE +201 -90
- package/NOTICE +4 -0
- package/README.md +22 -14
- package/dist/checksum-manifest.json +5 -5
- package/dist/{chunk-WMGOTWCL.js → chunk-4J3V4FKA.js} +1698 -122
- package/dist/chunk-4J3V4FKA.js.map +1 -0
- package/dist/chunk-IZOXM3IM.js +32 -0
- package/dist/chunk-IZOXM3IM.js.map +1 -0
- package/dist/{chunk-RVDTQ2FR.js → chunk-MPBX5W3L.js} +1 -0
- package/dist/chunk-MPBX5W3L.js.map +1 -0
- package/dist/cli-facts.json +7 -7
- package/dist/cli.js +10800 -3958
- package/dist/cli.js.map +1 -0
- package/dist/{dist-5SSCBJRC.js → dist-3XUWQFMP.js} +2 -1
- package/dist/dist-3XUWQFMP.js.map +1 -0
- package/dist/framework-EUF7YNNW.js +9 -0
- package/dist/framework-EUF7YNNW.js.map +1 -0
- package/dist/{pro-scanner-NSDJLVII.js → pro-scanner-5UJZYBZF.js} +3 -3
- package/dist/pro-scanner-5UJZYBZF.js.map +1 -0
- package/docs/llms.txt +15 -7
- package/docs/placement-kit.md +9 -6
- package/package.json +27 -20
- package/rules/free-bundle.json +15 -15
- package/dist/chunk-IPNOC7JF.js +0 -918
- package/dist/chunk-NC5RELTG.js +0 -40
- package/dist/config-generator-BNFR3LZR.js +0 -74
- package/dist/framework-PA6RVE7G.js +0 -27
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
logger
|
|
3
|
-
} from "./chunk-NC5RELTG.js";
|
|
4
1
|
import {
|
|
5
2
|
EXEC_RULE_FIELDS,
|
|
6
3
|
RE2JS_V1_RUNTIME_ID,
|
|
@@ -11,7 +8,7 @@ import {
|
|
|
11
8
|
re2jsV1Executor,
|
|
12
9
|
selectExpected,
|
|
13
10
|
verifyExactSet
|
|
14
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-MPBX5W3L.js";
|
|
15
12
|
|
|
16
13
|
// src/core/pro-scanner.ts
|
|
17
14
|
import * as path2 from "path";
|
|
@@ -60,10 +57,18 @@ function assertTrustedApiUrl(url) {
|
|
|
60
57
|
}
|
|
61
58
|
|
|
62
59
|
// src/core/links.ts
|
|
60
|
+
var GO_SLOTS = ["docs", "site", "pricing", "billing", "dashboard", "telemetry", "checkout", "pricing-md"];
|
|
63
61
|
var GO_BASE = "https://agenticcli.dev/go/";
|
|
64
62
|
function goLink(slot) {
|
|
65
63
|
return `${GO_BASE}${slot}`;
|
|
66
64
|
}
|
|
65
|
+
function goLinkFromServerSlot(slot) {
|
|
66
|
+
const known = typeof slot === "string" ? GO_SLOTS.find((s) => s === slot) : void 0;
|
|
67
|
+
return goLink(known ?? "pricing");
|
|
68
|
+
}
|
|
69
|
+
function resolveServerSlot(slot) {
|
|
70
|
+
return (typeof slot === "string" ? GO_SLOTS.find((s) => s === slot) : void 0) ?? "pricing";
|
|
71
|
+
}
|
|
67
72
|
|
|
68
73
|
// src/utils/secure-fs.ts
|
|
69
74
|
import { chmodSync, mkdirSync, statSync, writeFileSync } from "fs";
|
|
@@ -101,6 +106,7 @@ function isPlatformUnavailable(res, body) {
|
|
|
101
106
|
return body?.code === PLATFORM_UNAVAILABLE_CODE || res.status === 503 && header === "unavailable";
|
|
102
107
|
}
|
|
103
108
|
var PLATFORM_UNAVAILABLE_DEFAULT_MESSAGE = "Service temporarily unavailable. Please try again later.";
|
|
109
|
+
var PRO_RULES_UNAVAILABLE_MESSAGE = "Pro rules are temporarily unavailable. Retry later, or run with --allow-degraded to scan with local rules only.";
|
|
104
110
|
|
|
105
111
|
// src/core/auth.ts
|
|
106
112
|
var FILE_MODE = 384;
|
|
@@ -173,9 +179,9 @@ async function exchangeApiKeyForToken(apiKey, apiUrl) {
|
|
|
173
179
|
);
|
|
174
180
|
}
|
|
175
181
|
if (res.status === 402) {
|
|
176
|
-
console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 monthly
|
|
182
|
+
console.error("[shipguard] SHIPGUARD_API_KEY exchange rejected \u2014 monthly usage limit reached");
|
|
177
183
|
throw new Error(
|
|
178
|
-
`SHIPGUARD_API_KEY has
|
|
184
|
+
`SHIPGUARD_API_KEY has reached its monthly usage limit. See your plan at ${goLink("billing")}`
|
|
179
185
|
);
|
|
180
186
|
}
|
|
181
187
|
if (!res.ok) {
|
|
@@ -314,10 +320,9 @@ async function getAuthToken(apiUrl) {
|
|
|
314
320
|
return null;
|
|
315
321
|
}
|
|
316
322
|
|
|
317
|
-
// src/core/
|
|
318
|
-
import
|
|
319
|
-
import
|
|
320
|
-
import { sha256 } from "@noble/hashes/sha2.js";
|
|
323
|
+
// src/core/plan.ts
|
|
324
|
+
import { createHash as createHash2, randomBytes as randomBytes2 } from "crypto";
|
|
325
|
+
import { join as join4 } from "path";
|
|
321
326
|
|
|
322
327
|
// src/core/crypto.ts
|
|
323
328
|
import { createHash } from "crypto";
|
|
@@ -509,9 +514,976 @@ async function verifyBundleEnvelopeSignature(preimageBytes, signatureB64url, kid
|
|
|
509
514
|
throw new Error("bundle-envelope signature verification failed \u2014 possible tampering or replay");
|
|
510
515
|
}
|
|
511
516
|
}
|
|
517
|
+
async function verifyPlanDocumentSignature(signingInput, signatureB64url, kid) {
|
|
518
|
+
const cryptoKey = await resolveAndImportKey(kid, "bundle");
|
|
519
|
+
const signatureBytes = Buffer.from(signatureB64url, "base64url");
|
|
520
|
+
return globalThis.crypto.subtle.verify(
|
|
521
|
+
"Ed25519",
|
|
522
|
+
cryptoKey,
|
|
523
|
+
signatureBytes,
|
|
524
|
+
signingInput
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/core/safe-text.ts
|
|
529
|
+
var TEXT_CAPS = {
|
|
530
|
+
offer: 300,
|
|
531
|
+
usage: 120,
|
|
532
|
+
label: 32,
|
|
533
|
+
limit: 200,
|
|
534
|
+
account: 200,
|
|
535
|
+
updateNotice: 200,
|
|
536
|
+
item: 40,
|
|
537
|
+
items: 8
|
|
538
|
+
};
|
|
539
|
+
var ESCAPE_SEQUENCES = new RegExp(
|
|
540
|
+
[
|
|
541
|
+
"\\u001b\\[[0-?]*[ -/]*[@-~]",
|
|
542
|
+
// CSI
|
|
543
|
+
"\\u009b[0-?]*[ -/]*[@-~]",
|
|
544
|
+
// 8-bit CSI
|
|
545
|
+
"\\u001b\\][^\\u0007\\u001b]*(?:\\u0007|\\u001b\\\\)?",
|
|
546
|
+
// OSC
|
|
547
|
+
"\\u009d[^\\u0007\\u009c]*(?:\\u0007|\\u009c)?",
|
|
548
|
+
// 8-bit OSC
|
|
549
|
+
"\\u001b[PX^_][^\\u001b]*(?:\\u001b\\\\)?",
|
|
550
|
+
// DCS, SOS, PM, APC
|
|
551
|
+
"\\u001b[\\s\\S]?"
|
|
552
|
+
// any other ESC pair
|
|
553
|
+
].join("|"),
|
|
554
|
+
"g"
|
|
555
|
+
);
|
|
556
|
+
var TLDS = "com|net|org|io|dev|app|co|xyz|info|biz|ru|cn|tk|top|ly|me|sh|ai|gg|us|uk|de|fr|cc|link|click|site|online|store|shop|page|pw|ws|to|ink|club|live|tech|work|zip|mov";
|
|
557
|
+
var URLS = new RegExp(
|
|
558
|
+
[
|
|
559
|
+
"\\b[a-z][a-z0-9+.-]{1,15}:\\/\\/\\S*",
|
|
560
|
+
"\\b(?:mailto|javascript|vbscript|data|file|tel|sms|blob|about):\\S*",
|
|
561
|
+
"[^\\s@]+@[^\\s@]+\\.[a-z]{2,}\\S*",
|
|
562
|
+
"\\bwww\\.\\S+",
|
|
563
|
+
`\\b(?:[a-z0-9-]+\\.)+(?:${TLDS})\\b(?:[/:?#]\\S*)?`
|
|
564
|
+
].join("|"),
|
|
565
|
+
"gi"
|
|
566
|
+
);
|
|
567
|
+
var UNSAFE_CHARS = new RegExp(
|
|
568
|
+
"[\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u200b-\\u200f\\u202a-\\u202e\\u2060\\u2066-\\u2069\\ufeff\\u{e0000}-\\u{e007f}]",
|
|
569
|
+
"gu"
|
|
570
|
+
);
|
|
571
|
+
function safeServerText(value, maxLen) {
|
|
572
|
+
if (typeof value !== "string" || !Number.isInteger(maxLen) || maxLen < 4) return null;
|
|
573
|
+
const bounded = value.length > 8192 ? value.slice(0, 8192) : value;
|
|
574
|
+
const cleaned = bounded.normalize("NFC").replace(ESCAPE_SEQUENCES, " ").replace(URLS, " ").replace(UNSAFE_CHARS, " ").replace(/\s+/g, " ").trim();
|
|
575
|
+
if (cleaned === "") return null;
|
|
576
|
+
const chars = Array.from(cleaned);
|
|
577
|
+
if (chars.length <= maxLen) return cleaned;
|
|
578
|
+
return chars.slice(0, maxLen - 3).join("").trimEnd() + "...";
|
|
579
|
+
}
|
|
580
|
+
function safeServerList(value) {
|
|
581
|
+
if (!Array.isArray(value)) return [];
|
|
582
|
+
const out = [];
|
|
583
|
+
for (const item of value) {
|
|
584
|
+
const text = safeServerText(item, TEXT_CAPS.item);
|
|
585
|
+
if (text !== null) out.push(text);
|
|
586
|
+
if (out.length >= TEXT_CAPS.items) break;
|
|
587
|
+
}
|
|
588
|
+
return out;
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
// src/core/config-store.ts
|
|
592
|
+
import { lstatSync, readFileSync as readFileSync3, readdirSync, renameSync, rmSync as rmSync2 } from "fs";
|
|
593
|
+
import { join as join3 } from "path";
|
|
594
|
+
import { randomBytes } from "crypto";
|
|
595
|
+
|
|
596
|
+
// src/utils/logger.ts
|
|
597
|
+
import chalk from "chalk";
|
|
598
|
+
var logger = {
|
|
599
|
+
info: (msg) => console.error(chalk.blue("\u2139"), msg),
|
|
600
|
+
success: (msg) => console.error(chalk.green("\u2713"), msg),
|
|
601
|
+
warn: (msg) => console.error(chalk.yellow("\u26A0"), msg),
|
|
602
|
+
error: (msg) => console.error(chalk.red("\u2717"), msg),
|
|
603
|
+
// Diagnostics that are true and worth being able to inspect, but too detailed for a
|
|
604
|
+
// normal run — e.g. "this legacy finding was superseded by a governed corpus rule on
|
|
605
|
+
// the same line". Deliberately NOT a silent drop: the information is always produced
|
|
606
|
+
// and one env var makes it visible. Stderr only, like every other logger method.
|
|
607
|
+
debug: (msg) => {
|
|
608
|
+
if (process.env.SHIPGUARD_DEBUG) console.error(chalk.gray("\xB7"), msg);
|
|
609
|
+
},
|
|
610
|
+
finding: (severity, msg) => {
|
|
611
|
+
const colors = {
|
|
612
|
+
critical: chalk.bgRed.white,
|
|
613
|
+
high: chalk.red,
|
|
614
|
+
medium: chalk.yellow,
|
|
615
|
+
low: chalk.blue,
|
|
616
|
+
info: chalk.gray
|
|
617
|
+
};
|
|
618
|
+
const colorFn = colors[severity] || chalk.white;
|
|
619
|
+
const label = severity.toUpperCase().padEnd(8);
|
|
620
|
+
console.error(` ${colorFn(label)} ${msg}`);
|
|
621
|
+
},
|
|
622
|
+
score: (score, recommendation) => {
|
|
623
|
+
const color = score <= 20 ? chalk.green : score <= 50 ? chalk.yellow : chalk.red;
|
|
624
|
+
const icon = score <= 20 ? "\u2713" : score <= 50 ? "\u26A0" : "\u2717";
|
|
625
|
+
console.error("");
|
|
626
|
+
console.error(chalk.bold("ShipGuard Scan Result"));
|
|
627
|
+
console.error(`Risk Score: ${color(`${score}/100`)}`);
|
|
628
|
+
console.error(`Status: ${color(`${icon} ${recommendation.replace(/_/g, " ")}`)}`);
|
|
629
|
+
},
|
|
630
|
+
divider: () => console.error(chalk.gray("\u2500".repeat(50)))
|
|
631
|
+
};
|
|
632
|
+
|
|
633
|
+
// src/core/telemetry-config.ts
|
|
634
|
+
import { randomUUID } from "crypto";
|
|
635
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
636
|
+
import { homedir as homedir2 } from "os";
|
|
637
|
+
import { join as join2 } from "path";
|
|
638
|
+
import YAML from "yaml";
|
|
639
|
+
|
|
640
|
+
// ../shared/dist/constants.js
|
|
641
|
+
var SEVERITY_WEIGHTS = {
|
|
642
|
+
info: 1,
|
|
643
|
+
low: 5,
|
|
644
|
+
medium: 15,
|
|
645
|
+
high: 30,
|
|
646
|
+
critical: 50
|
|
647
|
+
};
|
|
648
|
+
var EXIT_CODES = {
|
|
649
|
+
SAFE: 0,
|
|
650
|
+
BLOCKED: 1,
|
|
651
|
+
CONFIG_ERROR: 2,
|
|
652
|
+
RUNTIME_ERROR: 3
|
|
653
|
+
};
|
|
654
|
+
var DEFAULT_POLICY_PATH = "shipguard.policy.yml";
|
|
655
|
+
var DEFAULT_REPORT_DIR = ".shipguard/reports";
|
|
656
|
+
var DEFAULT_REPORT_FILE = ".shipguard/reports/latest.md";
|
|
657
|
+
var DEFAULT_HISTORY_PATH = ".shipguard/history.db";
|
|
658
|
+
var HISTORY_PATH_ENV_VAR = "SHIPGUARD_HISTORY_PATH";
|
|
659
|
+
var DEFAULT_REPO_ID_FALLBACK_PATH = ".shipguard/repo-id";
|
|
660
|
+
var DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES = 30;
|
|
661
|
+
var SCAN_ID_REUSE_WINDOW_ENV_VAR = "SHIPGUARD_SCAN_ID_REUSE_WINDOW_MINUTES";
|
|
662
|
+
|
|
663
|
+
// src/core/telemetry-config.ts
|
|
664
|
+
var SAFE_MODE_LINE = "Safe mode: no usage pings, no writes outside the project except the sign-in token.";
|
|
665
|
+
function isSafeMode(env = process.env, argv = process.argv) {
|
|
666
|
+
const v = env.SHIPGUARD_SAFE_MODE;
|
|
667
|
+
if (v !== void 0 && ["1", "true"].includes(v.trim().toLowerCase())) return true;
|
|
668
|
+
const end = argv.indexOf("--");
|
|
669
|
+
return (end === -1 ? argv : argv.slice(0, end)).includes("--safe-mode");
|
|
670
|
+
}
|
|
671
|
+
var safeModeAnnounced = false;
|
|
672
|
+
function announceSafeMode(env = process.env, argv = process.argv) {
|
|
673
|
+
if (!isSafeMode(env, argv)) return false;
|
|
674
|
+
if (!safeModeAnnounced) {
|
|
675
|
+
safeModeAnnounced = true;
|
|
676
|
+
process.stderr.write(SAFE_MODE_LINE + "\n");
|
|
677
|
+
}
|
|
678
|
+
return true;
|
|
679
|
+
}
|
|
680
|
+
var CONFIG_FILE = "telemetry.json";
|
|
681
|
+
var NOTICE_MARKER = "telemetry-notice-shown";
|
|
682
|
+
var FIRST_RUN_MARKER = "telemetry-first-run-sent";
|
|
683
|
+
function getConfigDir() {
|
|
684
|
+
return join2(homedir2(), ".config", "shipguard");
|
|
685
|
+
}
|
|
686
|
+
function configFilePath(dir = getConfigDir()) {
|
|
687
|
+
return join2(dir, CONFIG_FILE);
|
|
688
|
+
}
|
|
689
|
+
function readUserConfig(dir = getConfigDir()) {
|
|
690
|
+
const file = configFilePath(dir);
|
|
691
|
+
try {
|
|
692
|
+
if (!existsSync2(file)) return {};
|
|
693
|
+
const parsed = JSON.parse(readFileSync2(file, "utf-8"));
|
|
694
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
695
|
+
} catch (err) {
|
|
696
|
+
logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
697
|
+
return {};
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
function userConfigUnreadable(dir = getConfigDir()) {
|
|
701
|
+
const file = configFilePath(dir);
|
|
702
|
+
try {
|
|
703
|
+
if (!existsSync2(file)) return false;
|
|
704
|
+
const parsed = JSON.parse(readFileSync2(file, "utf-8"));
|
|
705
|
+
return !(parsed && typeof parsed === "object" && !Array.isArray(parsed));
|
|
706
|
+
} catch {
|
|
707
|
+
return true;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
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}$/;
|
|
711
|
+
function writeConfig(dir, next) {
|
|
712
|
+
const file = configFilePath(dir);
|
|
713
|
+
ensureSecureDir(dir);
|
|
714
|
+
writeSecureFileSync(file, JSON.stringify(next, null, 2) + "\n");
|
|
715
|
+
return file;
|
|
716
|
+
}
|
|
717
|
+
function readInstallId(dir = getConfigDir()) {
|
|
718
|
+
const id = readUserConfig(dir).installId;
|
|
719
|
+
return typeof id === "string" && UUID_V4.test(id) ? id : void 0;
|
|
720
|
+
}
|
|
721
|
+
function getOrCreateInstallId(dir = getConfigDir()) {
|
|
722
|
+
const existing = readInstallId(dir);
|
|
723
|
+
if (existing) return existing;
|
|
724
|
+
if (isSafeMode()) return void 0;
|
|
725
|
+
try {
|
|
726
|
+
const installId = randomUUID();
|
|
727
|
+
writeConfig(dir, { ...readUserConfig(dir), installId });
|
|
728
|
+
return installId;
|
|
729
|
+
} catch (err) {
|
|
730
|
+
logger.debug(`telemetry: could not persist the install id: ${err instanceof Error ? err.message : String(err)}`);
|
|
731
|
+
return void 0;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
function resetInstallId(dir = getConfigDir()) {
|
|
735
|
+
const cfg = readUserConfig(dir);
|
|
736
|
+
const hadId = "installId" in cfg;
|
|
737
|
+
const oldId = readInstallId(dir);
|
|
738
|
+
if (hadId) {
|
|
739
|
+
delete cfg.installId;
|
|
740
|
+
writeConfig(dir, cfg);
|
|
741
|
+
}
|
|
742
|
+
return { hadId, oldId };
|
|
743
|
+
}
|
|
744
|
+
function writeUserEnabled(dir, enabled) {
|
|
745
|
+
return writeConfig(dir, { ...readUserConfig(dir), enabled });
|
|
746
|
+
}
|
|
747
|
+
var noticePrinted = /* @__PURE__ */ new Set();
|
|
748
|
+
function noticeShown(dir = getConfigDir()) {
|
|
749
|
+
return noticePrinted.has(dir) || existsSync2(join2(dir, NOTICE_MARKER));
|
|
750
|
+
}
|
|
751
|
+
function markNoticeShown(dir = getConfigDir()) {
|
|
752
|
+
noticePrinted.add(dir);
|
|
753
|
+
if (isSafeMode()) return;
|
|
754
|
+
try {
|
|
755
|
+
ensureSecureDir(dir);
|
|
756
|
+
writeSecureFileSync(join2(dir, NOTICE_MARKER), "1\n");
|
|
757
|
+
} catch (err) {
|
|
758
|
+
logger.debug(`telemetry: could not persist the notice marker: ${err instanceof Error ? err.message : String(err)}`);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
function firstRunHandled(dir = getConfigDir()) {
|
|
762
|
+
return existsSync2(join2(dir, FIRST_RUN_MARKER));
|
|
763
|
+
}
|
|
764
|
+
function markFirstRunHandled(dir = getConfigDir()) {
|
|
765
|
+
if (isSafeMode()) return false;
|
|
766
|
+
try {
|
|
767
|
+
ensureSecureDir(dir);
|
|
768
|
+
writeSecureFileSync(join2(dir, FIRST_RUN_MARKER), "1\n");
|
|
769
|
+
return true;
|
|
770
|
+
} catch (err) {
|
|
771
|
+
logger.debug(`telemetry: could not persist the first-run marker: ${err instanceof Error ? err.message : String(err)}`);
|
|
772
|
+
return false;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
var FALSE_LIKE = /* @__PURE__ */ new Set(["false", "off", "no", "0"]);
|
|
776
|
+
var GENERATED_CONFIG_FILE = ".shipguard.yml";
|
|
777
|
+
function policyTelemetryEnabled(policy) {
|
|
778
|
+
if (!policy || typeof policy !== "object") return void 0;
|
|
779
|
+
const t = policy.telemetry;
|
|
780
|
+
if (!t || typeof t !== "object") return void 0;
|
|
781
|
+
const v = t.enabled;
|
|
782
|
+
if (v === false || v === 0) return false;
|
|
783
|
+
if (typeof v === "string" && FALSE_LIKE.has(v.trim().toLowerCase())) return false;
|
|
784
|
+
if (v === true) return true;
|
|
785
|
+
return void 0;
|
|
786
|
+
}
|
|
787
|
+
function readYamlToggle(file) {
|
|
788
|
+
try {
|
|
789
|
+
if (!existsSync2(file)) return void 0;
|
|
790
|
+
return policyTelemetryEnabled(YAML.parse(readFileSync2(file, "utf-8")));
|
|
791
|
+
} catch (err) {
|
|
792
|
+
logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
793
|
+
return void 0;
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
function projectTelemetryEnabled(input) {
|
|
797
|
+
const values = [policyTelemetryEnabled(input.policy)];
|
|
798
|
+
if (input.projectDir) {
|
|
799
|
+
if (input.policy === void 0) values.push(readYamlToggle(join2(input.projectDir, DEFAULT_POLICY_PATH)));
|
|
800
|
+
values.push(readYamlToggle(join2(input.projectDir, GENERATED_CONFIG_FILE)));
|
|
801
|
+
}
|
|
802
|
+
if (values.includes(false)) return false;
|
|
803
|
+
if (values.includes(true)) return true;
|
|
804
|
+
return void 0;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
// src/core/config-store.ts
|
|
808
|
+
var isPosix3 = process.platform !== "win32";
|
|
809
|
+
function readConfigText(file, maxBytes) {
|
|
810
|
+
let st;
|
|
811
|
+
try {
|
|
812
|
+
st = lstatSync(file);
|
|
813
|
+
} catch (err) {
|
|
814
|
+
if (err.code === "ENOENT") return { state: "missing" };
|
|
815
|
+
logger.debug(`config-store: cannot stat ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
816
|
+
return { state: "unsafe", why: "unreadable" };
|
|
817
|
+
}
|
|
818
|
+
if (!st.isFile()) return { state: "unsafe", why: "not a regular file" };
|
|
819
|
+
if (isPosix3 && (st.mode & 63) !== 0) return { state: "unsafe", why: "group/other-accessible" };
|
|
820
|
+
if (st.size > maxBytes) return { state: "unsafe", why: "too large" };
|
|
821
|
+
try {
|
|
822
|
+
return { state: "ok", text: readFileSync3(file, "utf8") };
|
|
823
|
+
} catch (err) {
|
|
824
|
+
logger.debug(`config-store: cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
825
|
+
return { state: "unsafe", why: "unreadable" };
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
function writeConfigText(dir, name, data) {
|
|
829
|
+
if (isSafeMode()) {
|
|
830
|
+
logger.debug(`config-store: safe mode, not writing ${join3(dir, name)}`);
|
|
831
|
+
return false;
|
|
832
|
+
}
|
|
833
|
+
const tmp = join3(dir, `.${name}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
|
|
834
|
+
try {
|
|
835
|
+
ensureSecureDir(dir);
|
|
836
|
+
writeSecureFileSync(tmp, data);
|
|
837
|
+
renameSync(tmp, join3(dir, name));
|
|
838
|
+
return true;
|
|
839
|
+
} catch (err) {
|
|
840
|
+
logger.debug(`config-store: cannot write ${join3(dir, name)}: ${err instanceof Error ? err.message : String(err)}`);
|
|
841
|
+
try {
|
|
842
|
+
rmSync2(tmp, { force: true });
|
|
843
|
+
} catch (cleanupErr) {
|
|
844
|
+
logger.debug(`config-store: cannot remove ${tmp}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}`);
|
|
845
|
+
}
|
|
846
|
+
return false;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
function removeConfigFile(file) {
|
|
850
|
+
try {
|
|
851
|
+
rmSync2(file, { force: true });
|
|
852
|
+
return true;
|
|
853
|
+
} catch (err) {
|
|
854
|
+
logger.debug(`config-store: cannot remove ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
855
|
+
return false;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
function listConfigDir(dir) {
|
|
859
|
+
try {
|
|
860
|
+
return readdirSync(dir);
|
|
861
|
+
} catch (err) {
|
|
862
|
+
if (err.code !== "ENOENT") {
|
|
863
|
+
logger.debug(`config-store: cannot list ${dir}: ${err instanceof Error ? err.message : String(err)}`);
|
|
864
|
+
}
|
|
865
|
+
return [];
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// src/core/plan.ts
|
|
870
|
+
var PLAN_DV = 1;
|
|
871
|
+
var ISSUER = "agenticcli.dev";
|
|
872
|
+
var SKEW_FUTURE_SECONDS = 300;
|
|
873
|
+
var KNOWN_ACCOUNT_STATUSES = ["active", "trialing", "pending", "past_due", "ending", "lapsed", "none"];
|
|
874
|
+
var PAID_STATUSES = ["active", "trialing", "past_due", "ending"];
|
|
875
|
+
var DOC_RULES = {
|
|
876
|
+
account: {
|
|
877
|
+
typ: "shipguard-account+jws",
|
|
878
|
+
aud: "shipguard-cli",
|
|
879
|
+
maxBytes: 16384,
|
|
880
|
+
maxLifeSeconds: 72 * 3600,
|
|
881
|
+
required: ["dv", "iss", "aud", "acct", "iat", "exp"]
|
|
882
|
+
},
|
|
883
|
+
offer: {
|
|
884
|
+
typ: "shipguard-offer+jws",
|
|
885
|
+
aud: "shipguard-cli-offer",
|
|
886
|
+
maxBytes: 65536,
|
|
887
|
+
maxLifeSeconds: 7 * 86400,
|
|
888
|
+
required: ["dv", "iss", "aud", "iat", "exp"]
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
var REFRESH_MIN_SECONDS = 60;
|
|
892
|
+
var REFRESH_MAX_SECONDS = 6 * 3600;
|
|
893
|
+
var ACCOUNT_CACHE_FILE = "account.jws";
|
|
894
|
+
function acctHash(sub) {
|
|
895
|
+
return createHash2("sha256").update("shipguard-acct-v1" + sub).digest("base64url");
|
|
896
|
+
}
|
|
897
|
+
function acctFromAccessToken(accessToken) {
|
|
898
|
+
if (typeof accessToken !== "string") return null;
|
|
899
|
+
const parts = accessToken.split(".");
|
|
900
|
+
if (parts.length !== 3) return null;
|
|
901
|
+
try {
|
|
902
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
903
|
+
const sub = payload?.sub;
|
|
904
|
+
return typeof sub === "string" && sub !== "" ? acctHash(sub) : null;
|
|
905
|
+
} catch (err) {
|
|
906
|
+
logger.debug(`plan: access token payload not readable: ${err instanceof Error ? err.message : String(err)}`);
|
|
907
|
+
return null;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
function newNonce() {
|
|
911
|
+
return randomBytes2(16).toString("base64url");
|
|
912
|
+
}
|
|
913
|
+
var NONCE_PATTERN = /^[A-Za-z0-9_-]{22}$/;
|
|
914
|
+
function clientHelloHeaders(cliVersion, nonce) {
|
|
915
|
+
const headers = {
|
|
916
|
+
"X-ShipGuard-Client": `shipguard/${cliVersion}; bundle-protocol=2`
|
|
917
|
+
};
|
|
918
|
+
if (nonce !== void 0) headers["X-ShipGuard-Nonce"] = nonce;
|
|
919
|
+
return headers;
|
|
920
|
+
}
|
|
921
|
+
var fail = (step, expired) => expired ? { ok: false, step, expired } : { ok: false, step };
|
|
922
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
923
|
+
async function verifyPlanDocument(kind, token, ctx) {
|
|
924
|
+
const rules = DOC_RULES[kind];
|
|
925
|
+
try {
|
|
926
|
+
if (typeof token !== "string") return fail("not a string");
|
|
927
|
+
if (token.length > rules.maxBytes) return fail("size cap");
|
|
928
|
+
const parts = token.split(".");
|
|
929
|
+
if (parts.length !== 3 || parts.some((p) => !/^[A-Za-z0-9_-]+$/.test(p))) return fail("not three base64url parts");
|
|
930
|
+
const header = parseStrictNoDup(Buffer.from(parts[0], "base64url").toString("utf8"));
|
|
931
|
+
if (!isRecord(header)) return fail("header not an object");
|
|
932
|
+
if (Object.keys(header).some((k) => k !== "alg" && k !== "kid" && k !== "typ")) return fail("header key not allowed");
|
|
933
|
+
if (header["alg"] !== "EdDSA") return fail("alg");
|
|
934
|
+
if (header["typ"] !== rules.typ) return fail("typ");
|
|
935
|
+
const kid = header["kid"];
|
|
936
|
+
if (typeof kid !== "string" || !/^[A-Za-z0-9._-]{1,64}$/.test(kid)) return fail("kid");
|
|
937
|
+
const signingInput = new TextEncoder().encode(`${parts[0]}.${parts[1]}`);
|
|
938
|
+
if (!await verifyPlanDocumentSignature(signingInput, parts[2], kid)) return fail("signature");
|
|
939
|
+
const payload = parseStrictNoDup(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
940
|
+
if (!isRecord(payload)) return fail("payload not an object");
|
|
941
|
+
if (payload["iss"] !== ISSUER || payload["aud"] !== rules.aud) return fail("iss or aud");
|
|
942
|
+
if (payload["dv"] !== PLAN_DV) return fail("unsupported dv");
|
|
943
|
+
for (const key of rules.required) if (!(key in payload)) return fail(`missing ${key}`);
|
|
944
|
+
const iat = payload["iat"];
|
|
945
|
+
const exp = payload["exp"];
|
|
946
|
+
if (!Number.isSafeInteger(iat) || !Number.isSafeInteger(exp)) return fail("iat or exp");
|
|
947
|
+
if (kind === "account") {
|
|
948
|
+
if (typeof ctx.acct !== "string" || ctx.acct === "") return fail("no account to bind to");
|
|
949
|
+
if (payload["acct"] !== ctx.acct) return fail("wrong account");
|
|
950
|
+
}
|
|
951
|
+
const live = kind === "account" && typeof ctx.nonce === "string";
|
|
952
|
+
if (live) {
|
|
953
|
+
if (!NONCE_PATTERN.test(ctx.nonce) || payload["nonce"] !== ctx.nonce) return fail("nonce mismatch");
|
|
954
|
+
if (typeof ctx.scanId === "string") {
|
|
955
|
+
const binding = payload["binding"];
|
|
956
|
+
if (!isRecord(binding) || binding["scanId"] !== ctx.scanId) return fail("scanId mismatch");
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
const nowSeconds = Math.floor(ctx.now / 1e3);
|
|
960
|
+
if (iat > nowSeconds + SKEW_FUTURE_SECONDS) return fail("issued in the future");
|
|
961
|
+
if (nowSeconds >= exp) return fail("expired", true);
|
|
962
|
+
if (exp - iat > rules.maxLifeSeconds) return fail("lifetime too long");
|
|
963
|
+
return { ok: true, payload, live };
|
|
964
|
+
} catch (err) {
|
|
965
|
+
logger.debug(`plan: ${kind} document rejected: ${err instanceof Error ? err.message : String(err)}`);
|
|
966
|
+
return fail("exception");
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
var iso = (seconds) => new Date(seconds * 1e3).toISOString();
|
|
970
|
+
var ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
971
|
+
function normalizeAccountStatus(value) {
|
|
972
|
+
return typeof value === "string" && KNOWN_ACCOUNT_STATUSES.includes(value) ? value : "unsupported";
|
|
973
|
+
}
|
|
974
|
+
function mapOffer(value) {
|
|
975
|
+
if (!isRecord(value)) return null;
|
|
976
|
+
const text = safeServerText(value["text"], TEXT_CAPS.offer);
|
|
977
|
+
if (text === null) return null;
|
|
978
|
+
return { text, slot: resolveServerSlot(value["slot"]) };
|
|
979
|
+
}
|
|
980
|
+
function mapUsage(value) {
|
|
981
|
+
if (!isRecord(value)) return null;
|
|
982
|
+
const percent = value["percent"];
|
|
983
|
+
if (typeof percent !== "number" || !Number.isInteger(percent) || percent < 0 || percent > 100) return null;
|
|
984
|
+
const state = value["state"] === "warn" || value["state"] === "used" ? value["state"] : "ok";
|
|
985
|
+
const resetsAt = typeof value["resetsAt"] === "string" && ISO_TIME.test(value["resetsAt"]) && !Number.isNaN(Date.parse(value["resetsAt"])) ? value["resetsAt"] : null;
|
|
986
|
+
return {
|
|
987
|
+
percent,
|
|
988
|
+
state,
|
|
989
|
+
resetsAt,
|
|
990
|
+
text: safeServerText(value["text"], TEXT_CAPS.usage),
|
|
991
|
+
counted: typeof value["counted"] === "boolean" ? value["counted"] : null
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
function mapProAdds(value) {
|
|
995
|
+
if (!isRecord(value)) return null;
|
|
996
|
+
const rules = value["rules"];
|
|
997
|
+
return {
|
|
998
|
+
planName: safeServerText(value["planName"], TEXT_CAPS.label),
|
|
999
|
+
rules: typeof rules === "number" && Number.isSafeInteger(rules) && rules >= 0 ? rules : null,
|
|
1000
|
+
stacks: safeServerList(value["stacks"]),
|
|
1001
|
+
areas: safeServerList(value["areas"])
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
function mapCapabilities(value) {
|
|
1005
|
+
if (!isRecord(value) || typeof value["rulebookDefault"] !== "boolean") return null;
|
|
1006
|
+
const tiers = Array.isArray(value["rulebookTiers"]) ? value["rulebookTiers"].filter((t) => typeof t === "string" && /^[a-z0-9-]{1,32}$/.test(t)).slice(0, 16) : [];
|
|
1007
|
+
return { rulebookDefault: value["rulebookDefault"], rulebookTiers: tiers };
|
|
1008
|
+
}
|
|
1009
|
+
function mapAccountPayload(p) {
|
|
1010
|
+
const account = p["account"];
|
|
1011
|
+
const limit = p["limit"];
|
|
1012
|
+
const refresh = p["refreshAfter"];
|
|
1013
|
+
const limitText = isRecord(limit) ? safeServerText(limit["text"], TEXT_CAPS.limit) : null;
|
|
1014
|
+
return {
|
|
1015
|
+
fetchedAt: iso(p["iat"]),
|
|
1016
|
+
validUntil: iso(p["exp"]),
|
|
1017
|
+
label: safeServerText(p["label"], TEXT_CAPS.label),
|
|
1018
|
+
account: isRecord(account) ? { status: normalizeAccountStatus(account["status"]), text: safeServerText(account["text"], TEXT_CAPS.account) } : null,
|
|
1019
|
+
usage: mapUsage(p["usage"]),
|
|
1020
|
+
limit: limitText === null ? null : { text: limitText },
|
|
1021
|
+
capabilities: mapCapabilities(p["capabilities"]),
|
|
1022
|
+
refreshAfter: typeof refresh === "number" && Number.isFinite(refresh) ? Math.min(REFRESH_MAX_SECONDS, Math.max(REFRESH_MIN_SECONDS, Math.floor(refresh))) : null,
|
|
1023
|
+
updateNotice: safeServerText(p["updateNotice"], TEXT_CAPS.updateNotice),
|
|
1024
|
+
proAdds: mapProAdds(p["proAdds"]),
|
|
1025
|
+
offer: mapOffer(p["offer"])
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
function mapOfferPayload(p, stacks) {
|
|
1029
|
+
const counts = isRecord(p["counts"]) ? p["counts"] : {};
|
|
1030
|
+
const combined = isRecord(p["combined"]) ? p["combined"] : {};
|
|
1031
|
+
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
1032
|
+
const isCount = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
1033
|
+
let rules = null;
|
|
1034
|
+
const areas = [];
|
|
1035
|
+
for (const stack of stacks) {
|
|
1036
|
+
const entry = has(counts, stack) ? counts[stack] : void 0;
|
|
1037
|
+
if (isRecord(entry)) {
|
|
1038
|
+
for (const a of safeServerList(entry["areas"])) if (!areas.includes(a)) areas.push(a);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
if (stacks.length === 1) {
|
|
1042
|
+
const entry = has(counts, stacks[0]) ? counts[stacks[0]] : void 0;
|
|
1043
|
+
if (isRecord(entry) && isCount(entry["rules"])) rules = entry["rules"];
|
|
1044
|
+
} else if (stacks.length > 1) {
|
|
1045
|
+
const key = [...stacks].sort().join("+");
|
|
1046
|
+
if (has(combined, key) && isCount(combined[key])) rules = combined[key];
|
|
1047
|
+
}
|
|
1048
|
+
return {
|
|
1049
|
+
fetchedAt: iso(p["iat"]),
|
|
1050
|
+
validUntil: iso(p["exp"]),
|
|
1051
|
+
label: null,
|
|
1052
|
+
account: null,
|
|
1053
|
+
usage: null,
|
|
1054
|
+
limit: null,
|
|
1055
|
+
capabilities: null,
|
|
1056
|
+
refreshAfter: null,
|
|
1057
|
+
updateNotice: null,
|
|
1058
|
+
proAdds: { planName: null, rules, stacks: [...stacks], areas: areas.slice(0, TEXT_CAPS.items) },
|
|
1059
|
+
offer: mapOffer(p["offer"])
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
function hasPaidPlan(status) {
|
|
1063
|
+
return status !== null && status !== void 0 && PAID_STATUSES.includes(status);
|
|
1064
|
+
}
|
|
1065
|
+
function unavailableBlock(reason) {
|
|
1066
|
+
return { status: "unavailable", reason, command: "shipguard upgrade", link: null, server: null };
|
|
1067
|
+
}
|
|
1068
|
+
function planBlockFrom(server, status, reason = null) {
|
|
1069
|
+
return {
|
|
1070
|
+
status,
|
|
1071
|
+
reason: status === "cached" ? reason : null,
|
|
1072
|
+
command: hasPaidPlan(server.account?.status) ? "shipguard status" : "shipguard upgrade",
|
|
1073
|
+
link: server.offer ? goLinkFromServerSlot(server.offer.slot) : null,
|
|
1074
|
+
server
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
function cachedWithReason(block, reason) {
|
|
1078
|
+
return block.status === "unavailable" || block.server === null ? block : { ...block, status: "cached", reason };
|
|
1079
|
+
}
|
|
1080
|
+
var NOT_VERIFIED = (reason) => ({ block: unavailableBlock(reason), token: null, live: false });
|
|
1081
|
+
async function readAccountReply(token, req) {
|
|
1082
|
+
if (token === void 0 || token === null) return NOT_VERIFIED("SERVER_NO_PLAN");
|
|
1083
|
+
const result = await verifyPlanDocument("account", token, { now: req.now, acct: req.acct, nonce: req.nonce, scanId: req.scanId ?? null });
|
|
1084
|
+
if (!result.ok) {
|
|
1085
|
+
logger.debug(`plan: account document not trusted (${result.step})`);
|
|
1086
|
+
return NOT_VERIFIED("PLAN_UNVERIFIED");
|
|
1087
|
+
}
|
|
1088
|
+
return { block: planBlockFrom(mapAccountPayload(result.payload), "live"), token, live: true };
|
|
1089
|
+
}
|
|
1090
|
+
function writeAccountCache(configDir, token, opts = {}) {
|
|
1091
|
+
if (opts.noWrite) return false;
|
|
1092
|
+
return writeConfigText(configDir, ACCOUNT_CACHE_FILE, token);
|
|
1093
|
+
}
|
|
1094
|
+
function clearAccountCache(configDir) {
|
|
1095
|
+
removeConfigFile(join4(configDir, ACCOUNT_CACHE_FILE));
|
|
1096
|
+
}
|
|
1097
|
+
async function readAccountCache(configDir, req) {
|
|
1098
|
+
const file = readConfigText(join4(configDir, ACCOUNT_CACHE_FILE), DOC_RULES.account.maxBytes);
|
|
1099
|
+
if (file.state === "missing") return NOT_VERIFIED("NOT_FETCHED");
|
|
1100
|
+
if (file.state === "unsafe") {
|
|
1101
|
+
logger.debug(`plan: ignoring account cache (${file.why})`);
|
|
1102
|
+
return NOT_VERIFIED("PLAN_UNVERIFIED");
|
|
1103
|
+
}
|
|
1104
|
+
const token = file.text.trim();
|
|
1105
|
+
const result = await verifyPlanDocument("account", token, { now: req.now, acct: req.acct, nonce: null, scanId: null });
|
|
1106
|
+
if (!result.ok) {
|
|
1107
|
+
if (result.expired) return NOT_VERIFIED("NOT_FETCHED");
|
|
1108
|
+
logger.debug(`plan: cached account document not trusted (${result.step})`);
|
|
1109
|
+
return NOT_VERIFIED("PLAN_UNVERIFIED");
|
|
1110
|
+
}
|
|
1111
|
+
return { block: planBlockFrom(mapAccountPayload(result.payload), "cached"), token, live: false };
|
|
1112
|
+
}
|
|
1113
|
+
function cacheMaySkipRulebookCall(block, now, opts) {
|
|
1114
|
+
if (opts.explicitPro || block.status !== "cached" || block.server === null) return false;
|
|
1115
|
+
const s = block.server;
|
|
1116
|
+
if (s.capabilities === null || s.capabilities.rulebookDefault !== false) return false;
|
|
1117
|
+
if (s.refreshAfter === null) return false;
|
|
1118
|
+
const status = s.account?.status;
|
|
1119
|
+
if (status === void 0 || status === "none" || status === "pending" || status === "lapsed" || status === "unsupported") return false;
|
|
1120
|
+
const fetched = Date.parse(s.fetchedAt);
|
|
1121
|
+
if (Number.isNaN(fetched) || now < fetched || now - fetched > s.refreshAfter * 1e3) return false;
|
|
1122
|
+
if (s.usage?.resetsAt && now >= Date.parse(s.usage.resetsAt)) return false;
|
|
1123
|
+
return true;
|
|
1124
|
+
}
|
|
1125
|
+
function isSignedLimitUsed(plan, serverCode) {
|
|
1126
|
+
return plan.status === "live" && plan.server?.usage?.state === "used" && serverCode === "ALLOWANCE_USED";
|
|
1127
|
+
}
|
|
1128
|
+
function decideRulebookUse(input) {
|
|
1129
|
+
const { signedIn, explicitPro, allowDegraded, plan, cause } = input;
|
|
1130
|
+
if (!signedIn) {
|
|
1131
|
+
if (!explicitPro) return { action: "plain-free" };
|
|
1132
|
+
return allowDegraded ? { action: "run-general", code: "LOGIN_REQUIRED", reason: null } : { action: "exit-3", code: "LOGIN_REQUIRED" };
|
|
1133
|
+
}
|
|
1134
|
+
if (cause === null) return { action: "run-rulebook" };
|
|
1135
|
+
if (isSignedLimitUsed(plan, cause.serverCode)) {
|
|
1136
|
+
return { action: "run-general", code: "RULEBOOK_WITHHELD", reason: "ALLOWANCE_USED" };
|
|
1137
|
+
}
|
|
1138
|
+
if (explicitPro && !allowDegraded) return { action: "exit-3", code: cause.code };
|
|
1139
|
+
return { action: "run-general", code: cause.code, reason: null };
|
|
1140
|
+
}
|
|
1141
|
+
function fallbackApplies(code, status) {
|
|
1142
|
+
if (code === "PLAN_INACTIVE") return status === "lapsed" || status === "past_due";
|
|
1143
|
+
return hasPaidPlan(status);
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
// src/core/telemetry.ts
|
|
1147
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
1148
|
+
var IS_PUBLISHED_BUILD = true;
|
|
1149
|
+
function getProvenance(published = IS_PUBLISHED_BUILD) {
|
|
1150
|
+
return published ? "published" : "dev";
|
|
1151
|
+
}
|
|
1152
|
+
var PROD_TELEMETRY_ENDPOINT = "https://agenticcli.dev/api/cli-telemetry";
|
|
1153
|
+
function isLoopbackUrl(raw) {
|
|
1154
|
+
if (!raw) return false;
|
|
1155
|
+
try {
|
|
1156
|
+
const host = new URL(raw).hostname;
|
|
1157
|
+
return host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
|
|
1158
|
+
} catch {
|
|
1159
|
+
return false;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
function resolveEndpoint(published = IS_PUBLISHED_BUILD, env = process.env) {
|
|
1163
|
+
const override = env.SHIPGUARD_TELEMETRY_URL;
|
|
1164
|
+
if (published) return override || PROD_TELEMETRY_ENDPOINT;
|
|
1165
|
+
return isLoopbackUrl(override) ? override : null;
|
|
1166
|
+
}
|
|
1167
|
+
function resolveTraffic(env, published) {
|
|
1168
|
+
const v = env.SHIPGUARD_TRAFFIC;
|
|
1169
|
+
if (v === "test" || v === "internal") return v;
|
|
1170
|
+
return published ? void 0 : "test";
|
|
1171
|
+
}
|
|
1172
|
+
var TELEMETRY_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "copilot", "opencode", "other_agent", "none"];
|
|
1173
|
+
var TELEMETRY_OUTPUTS = ["json", "human", "sarif"];
|
|
1174
|
+
var AGENT_MARKERS = [
|
|
1175
|
+
["claude_code", ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"]],
|
|
1176
|
+
["codex", ["CODEX_SANDBOX", "CODEX_SANDBOX_NETWORK_DISABLED"]],
|
|
1177
|
+
["cursor", ["CURSOR_AGENT"]],
|
|
1178
|
+
["gemini_cli", ["GEMINI_CLI"]],
|
|
1179
|
+
["copilot", ["COPILOT_CLI", "COPILOT_AGENT_RUNNER_TYPE"]],
|
|
1180
|
+
["opencode", ["OPENCODE"]]
|
|
1181
|
+
];
|
|
1182
|
+
var OTHER_AGENT_MARKERS = ["AI_AGENT", "AGENT", "GOOSE_TERMINAL"];
|
|
1183
|
+
function detectAgent(env = process.env) {
|
|
1184
|
+
for (const [agent, vars] of AGENT_MARKERS) if (vars.some((k) => env[k] !== void 0 && env[k] !== "")) return agent;
|
|
1185
|
+
return OTHER_AGENT_MARKERS.some((k) => env[k] !== void 0 && env[k] !== "") ? "other_agent" : "none";
|
|
1186
|
+
}
|
|
1187
|
+
var TELEMETRY_GATE_KINDS = ["claude", "git", "ci", "none"];
|
|
1188
|
+
var currentGateKind = "none";
|
|
1189
|
+
function setGateKind(kind) {
|
|
1190
|
+
if (TELEMETRY_GATE_KINDS.includes(kind)) currentGateKind = kind;
|
|
1191
|
+
else logger.debug(`telemetry: ignoring unknown gate kind (not in the allowlist)`);
|
|
1192
|
+
}
|
|
1193
|
+
var ALLOWED_KEYS = [
|
|
1194
|
+
"schema",
|
|
1195
|
+
"eventId",
|
|
1196
|
+
"installId",
|
|
1197
|
+
"cliVersion",
|
|
1198
|
+
"provenance",
|
|
1199
|
+
"verdict",
|
|
1200
|
+
"durationBucket",
|
|
1201
|
+
"ci",
|
|
1202
|
+
"agent",
|
|
1203
|
+
"interactive",
|
|
1204
|
+
"output",
|
|
1205
|
+
"gateKind"
|
|
1206
|
+
];
|
|
1207
|
+
var VERSION_RE = /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})(-[0-9A-Za-z.-]{1,24})?$/;
|
|
1208
|
+
var DURATION_BUCKETS = ["lt1s", "1to5s", "5to30s", "gt30s"];
|
|
1209
|
+
function durationBucket(ms) {
|
|
1210
|
+
if (!(ms >= 1e3)) return "lt1s";
|
|
1211
|
+
if (ms < 5e3) return "1to5s";
|
|
1212
|
+
if (ms < 3e4) return "5to30s";
|
|
1213
|
+
return "gt30s";
|
|
1214
|
+
}
|
|
1215
|
+
var CI_PROVIDER_VARS = [
|
|
1216
|
+
"GITHUB_ACTIONS",
|
|
1217
|
+
"GITLAB_CI",
|
|
1218
|
+
"CIRCLECI",
|
|
1219
|
+
"TRAVIS",
|
|
1220
|
+
"BUILDKITE",
|
|
1221
|
+
"JENKINS_URL",
|
|
1222
|
+
"TF_BUILD",
|
|
1223
|
+
"TEAMCITY_VERSION",
|
|
1224
|
+
"BITBUCKET_BUILD_NUMBER",
|
|
1225
|
+
"APPVEYOR",
|
|
1226
|
+
"DRONE",
|
|
1227
|
+
"CODEBUILD_BUILD_ID",
|
|
1228
|
+
"SEMAPHORE",
|
|
1229
|
+
"BUILD_BUILDID",
|
|
1230
|
+
"CF_BUILD_ID",
|
|
1231
|
+
"NETLIFY",
|
|
1232
|
+
"VERCEL",
|
|
1233
|
+
"WOODPECKER",
|
|
1234
|
+
"BUDDY",
|
|
1235
|
+
"HUDSON_URL"
|
|
1236
|
+
];
|
|
1237
|
+
function detectCi(env = process.env) {
|
|
1238
|
+
const ci = env.CI;
|
|
1239
|
+
if (ci !== void 0 && !["", "0", "false"].includes(ci.trim().toLowerCase())) return true;
|
|
1240
|
+
return CI_PROVIDER_VARS.some((k) => env[k] !== void 0);
|
|
1241
|
+
}
|
|
1242
|
+
function isTruthyOff(v, offValues) {
|
|
1243
|
+
return v !== void 0 && offValues.includes(v.trim().toLowerCase());
|
|
1244
|
+
}
|
|
1245
|
+
function envOptOut(env) {
|
|
1246
|
+
if (isTruthyOff(env.SHIPGUARD_TELEMETRY, ["0", "false"])) return "env:SHIPGUARD_TELEMETRY";
|
|
1247
|
+
if (isTruthyOff(env.DO_NOT_TRACK, ["1", "true"])) return "env:DO_NOT_TRACK";
|
|
1248
|
+
return null;
|
|
1249
|
+
}
|
|
1250
|
+
function buildPayload(input) {
|
|
1251
|
+
const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, agent, interactive, output, gateKind, traffic } = input;
|
|
1252
|
+
const out = { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, agent, interactive, output, gateKind };
|
|
1253
|
+
if (traffic === "test" || traffic === "internal") out.traffic = traffic;
|
|
1254
|
+
return out;
|
|
1255
|
+
}
|
|
1256
|
+
function isTrafficOk(obj, count, expected) {
|
|
1257
|
+
if ("traffic" in obj) return count === expected + 1 && (obj.traffic === "test" || obj.traffic === "internal");
|
|
1258
|
+
return count === expected;
|
|
1259
|
+
}
|
|
1260
|
+
function validatePayload(payload) {
|
|
1261
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
|
|
1262
|
+
const obj = payload;
|
|
1263
|
+
const keys = Object.keys(obj);
|
|
1264
|
+
if (!isTrafficOk(obj, keys.length, ALLOWED_KEYS.length)) return false;
|
|
1265
|
+
for (const k of ALLOWED_KEYS) if (!(k in obj)) return false;
|
|
1266
|
+
if (obj.schema !== 5) return false;
|
|
1267
|
+
if (typeof obj.eventId !== "string" || !UUID_V4.test(obj.eventId)) return false;
|
|
1268
|
+
if (typeof obj.ci !== "boolean") return false;
|
|
1269
|
+
if (obj.ci) {
|
|
1270
|
+
if (obj.installId !== null) return false;
|
|
1271
|
+
} else if (typeof obj.installId !== "string" || !UUID_V4.test(obj.installId)) {
|
|
1272
|
+
return false;
|
|
1273
|
+
}
|
|
1274
|
+
if (typeof obj.cliVersion !== "string" || obj.cliVersion.length > 40 || !VERSION_RE.test(obj.cliVersion)) return false;
|
|
1275
|
+
if (obj.provenance !== "published" && obj.provenance !== "dev") return false;
|
|
1276
|
+
if (!["safe", "review", "blocked", "error"].includes(obj.verdict)) return false;
|
|
1277
|
+
if (!DURATION_BUCKETS.includes(obj.durationBucket)) return false;
|
|
1278
|
+
if (!TELEMETRY_AGENTS.includes(obj.agent)) return false;
|
|
1279
|
+
if (typeof obj.interactive !== "boolean") return false;
|
|
1280
|
+
if (!TELEMETRY_OUTPUTS.includes(obj.output)) return false;
|
|
1281
|
+
if (!TELEMETRY_GATE_KINDS.includes(obj.gateKind)) return false;
|
|
1282
|
+
return true;
|
|
1283
|
+
}
|
|
1284
|
+
function decideTelemetry(input = {}) {
|
|
1285
|
+
const env = input.env ?? process.env;
|
|
1286
|
+
if (isSafeMode(env)) return { enabled: false, source: "safe-mode" };
|
|
1287
|
+
const envOff = envOptOut(env);
|
|
1288
|
+
if (envOff) return { enabled: false, source: envOff };
|
|
1289
|
+
const dir = input.configDir ?? getConfigDir();
|
|
1290
|
+
if (userConfigUnreadable(dir) || readUserConfig(dir).enabled === false) {
|
|
1291
|
+
return { enabled: false, source: "user-config" };
|
|
1292
|
+
}
|
|
1293
|
+
if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
|
|
1294
|
+
return { enabled: true, source: "default" };
|
|
1295
|
+
}
|
|
1296
|
+
var NOTICE_TEXT = "usage pings on: version, verdict, timing, run context (CI, terminal, which agent or gate ran it), a random id; never code, paths or your account. Details: shipguard telemetry status. Off: shipguard telemetry disable";
|
|
1297
|
+
function telemetryState(opts = {}) {
|
|
1298
|
+
try {
|
|
1299
|
+
return decideTelemetry(opts).enabled ? "on" : "off";
|
|
1300
|
+
} catch (err) {
|
|
1301
|
+
logger.debug(`telemetry: state check failed, reporting off: ${err instanceof Error ? err.message : String(err)}`);
|
|
1302
|
+
return "off";
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
var PING_WAIT_MS = 1500;
|
|
1306
|
+
var FETCH_TIMEOUT_MS = 1e3;
|
|
1307
|
+
function debugEnabled(env) {
|
|
1308
|
+
const v = env.SHIPGUARD_TELEMETRY_DEBUG;
|
|
1309
|
+
return Boolean(v) && v !== "0";
|
|
1310
|
+
}
|
|
1311
|
+
function sendTelemetry(input, opts = {}) {
|
|
1312
|
+
try {
|
|
1313
|
+
const env = opts.env ?? process.env;
|
|
1314
|
+
const configDir = opts.configDir ?? getConfigDir();
|
|
1315
|
+
const published = opts.published ?? IS_PUBLISHED_BUILD;
|
|
1316
|
+
const debug = debugEnabled(env);
|
|
1317
|
+
const decision = decideTelemetry({ env, configDir, policy: opts.policy, projectDir: opts.projectDir });
|
|
1318
|
+
if (!decision.enabled) {
|
|
1319
|
+
if (debug) process.stderr.write(`[shipguard:telemetry] disabled (${decision.source}); nothing would be sent
|
|
1320
|
+
`);
|
|
1321
|
+
return Promise.resolve();
|
|
1322
|
+
}
|
|
1323
|
+
const endpoint = resolveEndpoint(published, env);
|
|
1324
|
+
const ci = detectCi(env);
|
|
1325
|
+
const base = {
|
|
1326
|
+
schema: 5,
|
|
1327
|
+
eventId: randomUUID2(),
|
|
1328
|
+
cliVersion: input.cliVersion,
|
|
1329
|
+
provenance: getProvenance(published),
|
|
1330
|
+
verdict: input.verdict,
|
|
1331
|
+
durationBucket: durationBucket(input.durationMs),
|
|
1332
|
+
ci,
|
|
1333
|
+
agent: detectAgent(env),
|
|
1334
|
+
interactive: opts.interactive ?? Boolean(process.stdout.isTTY),
|
|
1335
|
+
output: input.output,
|
|
1336
|
+
gateKind: input.gateKind ?? currentGateKind,
|
|
1337
|
+
traffic: resolveTraffic(env, published)
|
|
1338
|
+
};
|
|
1339
|
+
if (debug) {
|
|
1340
|
+
const stored = ci ? null : readInstallId(configDir);
|
|
1341
|
+
const installId2 = ci ? null : stored ?? randomUUID2();
|
|
1342
|
+
const note = !ci && !stored ? " (installId is a preview: none saved yet, one is created on the first real ping)" : "";
|
|
1343
|
+
process.stderr.write(
|
|
1344
|
+
`[shipguard:telemetry] SHIPGUARD_TELEMETRY_DEBUG=1: not sending. provenance=${base.provenance} endpoint=${endpoint ?? "(none: dev build without a loopback SHIPGUARD_TELEMETRY_URL)"} payload=${JSON.stringify(buildPayload({ ...base, installId: installId2 }))}${note}
|
|
1345
|
+
`
|
|
1346
|
+
);
|
|
1347
|
+
return Promise.resolve();
|
|
1348
|
+
}
|
|
1349
|
+
if (endpoint === null) {
|
|
1350
|
+
logger.debug("telemetry: dev build, not sending (set a loopback SHIPGUARD_TELEMETRY_URL to capture)");
|
|
1351
|
+
return Promise.resolve();
|
|
1352
|
+
}
|
|
1353
|
+
if (!noticeShown(configDir)) {
|
|
1354
|
+
process.stderr.write(NOTICE_TEXT + "\n");
|
|
1355
|
+
markNoticeShown(configDir);
|
|
1356
|
+
}
|
|
1357
|
+
const installId = ci ? null : getOrCreateInstallId(configDir) ?? void 0;
|
|
1358
|
+
if (installId === void 0) {
|
|
1359
|
+
logger.debug("telemetry: no install id could be saved; not sending");
|
|
1360
|
+
return Promise.resolve();
|
|
1361
|
+
}
|
|
1362
|
+
const payload = buildPayload({ ...base, installId });
|
|
1363
|
+
if (!validatePayload(payload)) {
|
|
1364
|
+
logger.debug("telemetry: payload failed validation; not sending");
|
|
1365
|
+
return Promise.resolve();
|
|
1366
|
+
}
|
|
1367
|
+
const body = JSON.stringify(payload);
|
|
1368
|
+
return postBounded(endpoint, body);
|
|
1369
|
+
} catch (err) {
|
|
1370
|
+
logger.debug(`telemetry: skipped after error (ignored): ${err instanceof Error ? err.message : String(err)}`);
|
|
1371
|
+
return Promise.resolve();
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
function postBounded(endpoint, body) {
|
|
1375
|
+
const controller = new AbortController();
|
|
1376
|
+
const abortTimer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
1377
|
+
const request = fetch(endpoint, {
|
|
1378
|
+
method: "POST",
|
|
1379
|
+
headers: { "Content-Type": "application/json" },
|
|
1380
|
+
body,
|
|
1381
|
+
signal: controller.signal
|
|
1382
|
+
}).then(
|
|
1383
|
+
() => void 0,
|
|
1384
|
+
(err) => {
|
|
1385
|
+
logger.debug(`telemetry: ping failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
|
|
1386
|
+
}
|
|
1387
|
+
).finally(() => clearTimeout(abortTimer));
|
|
1388
|
+
return new Promise((resolve) => {
|
|
1389
|
+
const cap = setTimeout(resolve, PING_WAIT_MS);
|
|
1390
|
+
cap.unref();
|
|
1391
|
+
void request.then(() => {
|
|
1392
|
+
clearTimeout(cap);
|
|
1393
|
+
resolve();
|
|
1394
|
+
});
|
|
1395
|
+
});
|
|
1396
|
+
}
|
|
1397
|
+
var CLI_VERSION = true ? "0.13.1" : process.env.npm_package_version ?? "0.0.0-dev";
|
|
1398
|
+
var LIFECYCLE_KEYS = ["schema", "event", "eventId", "installId", "cliVersion", "provenance", "ci"];
|
|
1399
|
+
function validateLifecyclePayload(payload) {
|
|
1400
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
|
|
1401
|
+
const o = payload;
|
|
1402
|
+
const keys = Object.keys(o);
|
|
1403
|
+
if (!isTrafficOk(o, keys.length, LIFECYCLE_KEYS.length) || !LIFECYCLE_KEYS.every((k) => k in o)) return false;
|
|
1404
|
+
if (o.schema !== 3) return false;
|
|
1405
|
+
if (o.event !== "cli_first_run" && o.event !== "cli_login") return false;
|
|
1406
|
+
if (typeof o.eventId !== "string" || !UUID_V4.test(o.eventId)) return false;
|
|
1407
|
+
if (typeof o.ci !== "boolean") return false;
|
|
1408
|
+
if (o.ci) {
|
|
1409
|
+
if (o.installId !== null || o.event === "cli_first_run") return false;
|
|
1410
|
+
} else if (typeof o.installId !== "string" || !UUID_V4.test(o.installId)) {
|
|
1411
|
+
return false;
|
|
1412
|
+
}
|
|
1413
|
+
if (typeof o.cliVersion !== "string" || o.cliVersion.length > 40 || !VERSION_RE.test(o.cliVersion)) return false;
|
|
1414
|
+
return o.provenance === "published" || o.provenance === "dev";
|
|
1415
|
+
}
|
|
1416
|
+
function sendLifecycleEvent(event, input, opts = {}) {
|
|
1417
|
+
try {
|
|
1418
|
+
const env = opts.env ?? process.env;
|
|
1419
|
+
const configDir = opts.configDir ?? getConfigDir();
|
|
1420
|
+
const published = opts.published ?? IS_PUBLISHED_BUILD;
|
|
1421
|
+
const debug = debugEnabled(env);
|
|
1422
|
+
const ci = detectCi(env);
|
|
1423
|
+
if (event === "cli_first_run" && ci) return Promise.resolve();
|
|
1424
|
+
const decision = decideTelemetry({ env, configDir, policy: opts.policy, projectDir: opts.projectDir });
|
|
1425
|
+
if (!decision.enabled) {
|
|
1426
|
+
if (debug) process.stderr.write(`[shipguard:telemetry] disabled (${decision.source}); nothing would be sent
|
|
1427
|
+
`);
|
|
1428
|
+
return Promise.resolve();
|
|
1429
|
+
}
|
|
1430
|
+
const endpoint = resolveEndpoint(published, env);
|
|
1431
|
+
const base = {
|
|
1432
|
+
schema: 3,
|
|
1433
|
+
event,
|
|
1434
|
+
eventId: randomUUID2(),
|
|
1435
|
+
cliVersion: input.cliVersion,
|
|
1436
|
+
provenance: getProvenance(published),
|
|
1437
|
+
ci
|
|
1438
|
+
};
|
|
1439
|
+
const traffic = resolveTraffic(env, published);
|
|
1440
|
+
if (debug) {
|
|
1441
|
+
const installId2 = ci ? null : readInstallId(configDir) ?? randomUUID2();
|
|
1442
|
+
process.stderr.write(
|
|
1443
|
+
`[shipguard:telemetry] SHIPGUARD_TELEMETRY_DEBUG=1: not sending. endpoint=${endpoint ?? "(none)"} payload=${JSON.stringify({ ...base, installId: installId2, ...traffic ? { traffic } : {} })}
|
|
1444
|
+
`
|
|
1445
|
+
);
|
|
1446
|
+
return Promise.resolve();
|
|
1447
|
+
}
|
|
1448
|
+
if (endpoint === null) {
|
|
1449
|
+
logger.debug("telemetry: dev build, not sending (set a loopback SHIPGUARD_TELEMETRY_URL to capture)");
|
|
1450
|
+
return Promise.resolve();
|
|
1451
|
+
}
|
|
1452
|
+
if (event === "cli_first_run") {
|
|
1453
|
+
if (firstRunHandled(configDir)) return Promise.resolve();
|
|
1454
|
+
if (readInstallId(configDir)) {
|
|
1455
|
+
markFirstRunHandled(configDir);
|
|
1456
|
+
return Promise.resolve();
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
if (!noticeShown(configDir)) {
|
|
1460
|
+
process.stderr.write(NOTICE_TEXT + "\n");
|
|
1461
|
+
markNoticeShown(configDir);
|
|
1462
|
+
}
|
|
1463
|
+
const installId = ci ? null : getOrCreateInstallId(configDir) ?? void 0;
|
|
1464
|
+
if (installId === void 0) {
|
|
1465
|
+
logger.debug("telemetry: no install id could be saved; not sending");
|
|
1466
|
+
return Promise.resolve();
|
|
1467
|
+
}
|
|
1468
|
+
if (event === "cli_first_run" && !markFirstRunHandled(configDir)) return Promise.resolve();
|
|
1469
|
+
const payload = { ...base, installId, ...traffic ? { traffic } : {} };
|
|
1470
|
+
if (!validateLifecyclePayload(payload)) {
|
|
1471
|
+
logger.debug("telemetry: lifecycle payload failed validation; not sending");
|
|
1472
|
+
return Promise.resolve();
|
|
1473
|
+
}
|
|
1474
|
+
return postBounded(endpoint, JSON.stringify(payload));
|
|
1475
|
+
} catch (err) {
|
|
1476
|
+
logger.debug(`telemetry: skipped after error (ignored): ${err instanceof Error ? err.message : String(err)}`);
|
|
1477
|
+
return Promise.resolve();
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
512
1480
|
|
|
513
1481
|
// src/core/release-verify.ts
|
|
1482
|
+
import * as fs from "fs";
|
|
1483
|
+
import * as path from "path";
|
|
1484
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
514
1485
|
var MIN_ACCEPTABLE_SEQUENCE = 1;
|
|
1486
|
+
var FRESHNESS_MAX_TTL_SECONDS = 73 * 3600;
|
|
515
1487
|
function sha256hex(input) {
|
|
516
1488
|
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
517
1489
|
return Buffer.from(sha256(bytes)).toString("hex");
|
|
@@ -632,6 +1604,32 @@ function atomicAcceptFloor(floorPath, incoming) {
|
|
|
632
1604
|
releaseLock();
|
|
633
1605
|
}
|
|
634
1606
|
}
|
|
1607
|
+
var TIER_TOKEN = /^[a-z0-9-]{1,32}$/;
|
|
1608
|
+
var CATEGORY_TOKEN = /^[A-Za-z0-9_.-]{1,64}$/;
|
|
1609
|
+
function parseSelection(raw) {
|
|
1610
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return "bundleEnvelope.selection must be an object";
|
|
1611
|
+
const sel = raw;
|
|
1612
|
+
for (const k of Object.keys(sel)) {
|
|
1613
|
+
if (k !== "tiers" && k !== "categories") return `bundleEnvelope.selection has an unknown field "${k}"`;
|
|
1614
|
+
}
|
|
1615
|
+
const tiers = sel["tiers"];
|
|
1616
|
+
if (!Array.isArray(tiers) || tiers.length === 0 || tiers.length > 16 || !tiers.every((t) => typeof t === "string" && TIER_TOKEN.test(t))) {
|
|
1617
|
+
return "bundleEnvelope.selection.tiers must be 1 to 16 lower-case tier tokens";
|
|
1618
|
+
}
|
|
1619
|
+
if (new Set(tiers).size !== tiers.length) return "bundleEnvelope.selection.tiers has duplicates";
|
|
1620
|
+
const categories = sel["categories"];
|
|
1621
|
+
if (categories === null || categories === void 0) return { tiers: [...tiers], categories: null };
|
|
1622
|
+
if (!Array.isArray(categories) || categories.length > 64 || !categories.every((c) => typeof c === "string" && CATEGORY_TOKEN.test(c))) {
|
|
1623
|
+
return "bundleEnvelope.selection.categories must be null or a list of category tokens";
|
|
1624
|
+
}
|
|
1625
|
+
return { tiers: [...tiers], categories: [...categories] };
|
|
1626
|
+
}
|
|
1627
|
+
function sameCategories(a, b) {
|
|
1628
|
+
const norm = (v) => v === null ? [] : [...new Set(v)].sort();
|
|
1629
|
+
const x = norm(a);
|
|
1630
|
+
const y = norm(b);
|
|
1631
|
+
return x.length === y.length && x.every((v, i) => v === y[i]);
|
|
1632
|
+
}
|
|
635
1633
|
async function verifyBundleResponse(response, request, floorPath) {
|
|
636
1634
|
let manifest;
|
|
637
1635
|
let attestation;
|
|
@@ -760,8 +1758,9 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
760
1758
|
return { ok: false, reason: "freshnessTok.signature must be a non-empty string", nonSafe: true };
|
|
761
1759
|
}
|
|
762
1760
|
}
|
|
1761
|
+
let selection;
|
|
763
1762
|
{
|
|
764
|
-
const
|
|
1763
|
+
const ENV_REQUIRED_V1 = [
|
|
765
1764
|
"exp",
|
|
766
1765
|
"expectedRuleSet",
|
|
767
1766
|
"frameworks",
|
|
@@ -776,12 +1775,19 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
776
1775
|
"sequence",
|
|
777
1776
|
"signature"
|
|
778
1777
|
];
|
|
1778
|
+
const isV2 = envelope["protocolVersion"] === "2";
|
|
1779
|
+
const ENV_REQUIRED = isV2 ? [...ENV_REQUIRED_V1, "selection"] : ENV_REQUIRED_V1;
|
|
779
1780
|
const f = requireFields(envelope, ENV_REQUIRED, "bundleEnvelope");
|
|
780
1781
|
if (f) return f;
|
|
781
1782
|
const x = rejectExtraFields(envelope, ENV_REQUIRED, "bundleEnvelope");
|
|
782
1783
|
if (x) return x;
|
|
783
|
-
if (envelope["protocolVersion"] !== "1") {
|
|
784
|
-
return { ok: false, reason: `bundleEnvelope.protocolVersion must be "1", got "${envelope["protocolVersion"]}"`, nonSafe: true };
|
|
1784
|
+
if (envelope["protocolVersion"] !== "1" && !isV2) {
|
|
1785
|
+
return { ok: false, reason: `bundleEnvelope.protocolVersion must be "1" or "2", got "${envelope["protocolVersion"]}"`, nonSafe: true };
|
|
1786
|
+
}
|
|
1787
|
+
if (isV2) {
|
|
1788
|
+
const parsed = parseSelection(envelope["selection"]);
|
|
1789
|
+
if (typeof parsed === "string") return { ok: false, reason: parsed, nonSafe: true };
|
|
1790
|
+
selection = parsed;
|
|
785
1791
|
}
|
|
786
1792
|
if (!isSafeInteger(envelope["exp"])) {
|
|
787
1793
|
return { ok: false, reason: "bundleEnvelope.exp must be a safe integer", nonSafe: true };
|
|
@@ -949,8 +1955,8 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
949
1955
|
if (typeof rObj["severity"] !== "string" || !VALID_SEVERITY_5.has(rObj["severity"])) {
|
|
950
1956
|
return { ok: false, reason: `selectedRules[${i}].severity must be critical|high|medium|low|info, got "${rObj["severity"]}"`, nonSafe: true };
|
|
951
1957
|
}
|
|
952
|
-
if (typeof rObj["tier"] !== "string" || rObj["tier"]
|
|
953
|
-
return { ok: false, reason: `selectedRules[${i}].tier must be
|
|
1958
|
+
if (typeof rObj["tier"] !== "string" || !TIER_TOKEN.test(rObj["tier"])) {
|
|
1959
|
+
return { ok: false, reason: `selectedRules[${i}].tier must be a lower-case tier token`, nonSafe: true };
|
|
954
1960
|
}
|
|
955
1961
|
if (typeof rObj["title"] !== "string") {
|
|
956
1962
|
return { ok: false, reason: `selectedRules[${i}].title must be a string`, nonSafe: true };
|
|
@@ -1094,7 +2100,8 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
1094
2100
|
return {
|
|
1095
2101
|
ok: false,
|
|
1096
2102
|
reason: `freshness token expired (expiresAt=${expiresAt}, now=${nowFresh})`,
|
|
1097
|
-
nonSafe: true
|
|
2103
|
+
nonSafe: true,
|
|
2104
|
+
freshnessExpired: true
|
|
1098
2105
|
};
|
|
1099
2106
|
}
|
|
1100
2107
|
if (nowFresh < issuedAt - CLOCK_SKEW) {
|
|
@@ -1104,10 +2111,10 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
1104
2111
|
nonSafe: true
|
|
1105
2112
|
};
|
|
1106
2113
|
}
|
|
1107
|
-
if (expiresAt - issuedAt >
|
|
2114
|
+
if (expiresAt - issuedAt > FRESHNESS_MAX_TTL_SECONDS) {
|
|
1108
2115
|
return {
|
|
1109
2116
|
ok: false,
|
|
1110
|
-
reason: `freshness token TTL exceeds maximum
|
|
2117
|
+
reason: `freshness token TTL exceeds maximum 73 hours (${expiresAt - issuedAt}s)`,
|
|
1111
2118
|
nonSafe: true
|
|
1112
2119
|
};
|
|
1113
2120
|
}
|
|
@@ -1173,11 +2180,34 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
1173
2180
|
}
|
|
1174
2181
|
const manifestForSelector = manifest;
|
|
1175
2182
|
let expectedSet;
|
|
2183
|
+
let partial = false;
|
|
1176
2184
|
try {
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
2185
|
+
if (selection === void 0) {
|
|
2186
|
+
expectedSet = selectExpected(manifestForSelector, {
|
|
2187
|
+
frameworks: request.frameworks,
|
|
2188
|
+
isPro: request.isPro ?? false
|
|
2189
|
+
});
|
|
2190
|
+
} else {
|
|
2191
|
+
if (!sameCategories(selection.categories, request.categories ?? null)) {
|
|
2192
|
+
return { ok: false, reason: "selection.categories does not equal the categories this CLI requested", nonSafe: true };
|
|
2193
|
+
}
|
|
2194
|
+
const full = selectExpected(manifestForSelector, { frameworks: request.frameworks, isPro: true });
|
|
2195
|
+
const tierOf = /* @__PURE__ */ new Map();
|
|
2196
|
+
for (const r of manifestForSelector.rules) tierOf.set(`${r.id}\0${r.executableHash}`, r.tier);
|
|
2197
|
+
const manifestTiers = /* @__PURE__ */ new Set();
|
|
2198
|
+
for (const r of manifestForSelector.rules) manifestTiers.add(r.tier);
|
|
2199
|
+
const served = new Set(selection.tiers);
|
|
2200
|
+
if (!served.has("free")) return { ok: false, reason: "selection.tiers does not include the free tier", nonSafe: true };
|
|
2201
|
+
for (const t of served) {
|
|
2202
|
+
if (!manifestTiers.has(t)) return { ok: false, reason: `selection.tiers names a tier the attested manifest does not have ("${t}")`, nonSafe: true };
|
|
2203
|
+
}
|
|
2204
|
+
expectedSet = full.filter((e) => served.has(tierOf.get(`${e.id}\0${e.executableHash}`) ?? ""));
|
|
2205
|
+
if (request.isPro) {
|
|
2206
|
+
const manifestReference = [...new Set(full.map((e) => tierOf.get(`${e.id}\0${e.executableHash}`) ?? ""))];
|
|
2207
|
+
const reference = /* @__PURE__ */ new Set([...manifestReference, ...request.verifiedRulebookTiers ?? []]);
|
|
2208
|
+
partial = [...reference].some((t) => !served.has(t));
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
1181
2211
|
} catch (err) {
|
|
1182
2212
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1183
2213
|
return { ok: false, reason: `select-expected-failed: ${msg}`, nonSafe: true };
|
|
@@ -1262,6 +2292,7 @@ async function verifyBundleResponse(response, request, floorPath) {
|
|
|
1262
2292
|
};
|
|
1263
2293
|
}
|
|
1264
2294
|
const selectedRules = deliveredWithHashes.map((d) => d.rule);
|
|
2295
|
+
if (selection !== void 0) return { ok: true, selectedRules, selection, partial };
|
|
1265
2296
|
return { ok: true, selectedRules };
|
|
1266
2297
|
}
|
|
1267
2298
|
|
|
@@ -1270,6 +2301,339 @@ import { minimatch } from "minimatch";
|
|
|
1270
2301
|
|
|
1271
2302
|
// src/core/re2-detector-engine.ts
|
|
1272
2303
|
import { RE2JS } from "re2js";
|
|
2304
|
+
|
|
2305
|
+
// src/core/rule-prefilter.ts
|
|
2306
|
+
var Unsure = class extends Error {
|
|
2307
|
+
};
|
|
2308
|
+
var MAX_RUNS_PER_BRANCH = 2;
|
|
2309
|
+
var MAX_ORS_PER_BRANCH = 3;
|
|
2310
|
+
var MAX_OR_MEMBERS = 12;
|
|
2311
|
+
var longest = (runs) => runs.reduce((a, b) => a === void 0 || b.length > a.length ? b : a, void 0);
|
|
2312
|
+
function parseQuant(src, pos) {
|
|
2313
|
+
const c = src[pos];
|
|
2314
|
+
let q = { min: 1, present: false };
|
|
2315
|
+
if (c === "*" || c === "?") {
|
|
2316
|
+
q = { min: 0, present: true };
|
|
2317
|
+
pos++;
|
|
2318
|
+
} else if (c === "+") {
|
|
2319
|
+
q = { min: 1, present: true };
|
|
2320
|
+
pos++;
|
|
2321
|
+
} else if (c === "{") {
|
|
2322
|
+
let j = pos + 1;
|
|
2323
|
+
let digits = "";
|
|
2324
|
+
while (j < src.length && src[j] >= "0" && src[j] <= "9") digits += src[j++];
|
|
2325
|
+
if (digits === "") throw new Unsure();
|
|
2326
|
+
if (src[j] === ",") {
|
|
2327
|
+
j++;
|
|
2328
|
+
while (j < src.length && src[j] >= "0" && src[j] <= "9") j++;
|
|
2329
|
+
}
|
|
2330
|
+
if (src[j] !== "}") throw new Unsure();
|
|
2331
|
+
q = { min: Number(digits), present: true };
|
|
2332
|
+
pos = j + 1;
|
|
2333
|
+
} else {
|
|
2334
|
+
return { q, pos };
|
|
2335
|
+
}
|
|
2336
|
+
if (src[pos] === "?") pos++;
|
|
2337
|
+
const n = src[pos];
|
|
2338
|
+
if (n === "*" || n === "+" || n === "?" || n === "{") throw new Unsure();
|
|
2339
|
+
return { q, pos };
|
|
2340
|
+
}
|
|
2341
|
+
function skipClass(src, start) {
|
|
2342
|
+
let i = start + 1;
|
|
2343
|
+
if (src[i] === "^") i++;
|
|
2344
|
+
if (src[i] === "]") i++;
|
|
2345
|
+
while (i < src.length) {
|
|
2346
|
+
const c = src[i];
|
|
2347
|
+
if (c === "\\") {
|
|
2348
|
+
const n = src[i + 1];
|
|
2349
|
+
if (n === void 0 || n === "Q" || n === "E") throw new Unsure();
|
|
2350
|
+
i += 2;
|
|
2351
|
+
if ((n === "p" || n === "P" || n === "x") && src[i] === "{") {
|
|
2352
|
+
const close = src.indexOf("}", i);
|
|
2353
|
+
if (close < 0) throw new Unsure();
|
|
2354
|
+
i = close + 1;
|
|
2355
|
+
}
|
|
2356
|
+
} else if (c === "[" && src[i + 1] === ":") {
|
|
2357
|
+
const close = src.indexOf(":]", i + 2);
|
|
2358
|
+
if (close < 0) throw new Unsure();
|
|
2359
|
+
i = close + 2;
|
|
2360
|
+
} else if (c === "]") {
|
|
2361
|
+
return i + 1;
|
|
2362
|
+
} else {
|
|
2363
|
+
i++;
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
throw new Unsure();
|
|
2367
|
+
}
|
|
2368
|
+
var ESCAPE_LITERAL = { n: "\n", t: " ", r: "\r", f: "\f", v: "\v" };
|
|
2369
|
+
function parseBranches(src, start, inGroup) {
|
|
2370
|
+
const branches = [];
|
|
2371
|
+
let runs = [];
|
|
2372
|
+
let ors = [];
|
|
2373
|
+
let cur = "";
|
|
2374
|
+
const flush = () => {
|
|
2375
|
+
if (cur !== "") runs.push(cur);
|
|
2376
|
+
cur = "";
|
|
2377
|
+
};
|
|
2378
|
+
let pos = start;
|
|
2379
|
+
while (pos < src.length) {
|
|
2380
|
+
const ch = src[pos];
|
|
2381
|
+
if (ch === "|") {
|
|
2382
|
+
flush();
|
|
2383
|
+
branches.push({ runs, ors });
|
|
2384
|
+
runs = [];
|
|
2385
|
+
ors = [];
|
|
2386
|
+
pos++;
|
|
2387
|
+
continue;
|
|
2388
|
+
}
|
|
2389
|
+
if (ch === ")") {
|
|
2390
|
+
if (!inGroup) throw new Unsure();
|
|
2391
|
+
break;
|
|
2392
|
+
}
|
|
2393
|
+
if (ch === "(") {
|
|
2394
|
+
let p = pos + 1;
|
|
2395
|
+
if (src[p] === "?") {
|
|
2396
|
+
if (src[p + 1] === ":") p += 2;
|
|
2397
|
+
else if (src[p + 1] === "P" && src[p + 2] === "<") p = nameEnd(src, p + 3);
|
|
2398
|
+
else if (src[p + 1] === "<" && src[p + 2] !== "=" && src[p + 2] !== "!") p = nameEnd(src, p + 2);
|
|
2399
|
+
else throw new Unsure();
|
|
2400
|
+
}
|
|
2401
|
+
const inner = parseBranches(src, p, true);
|
|
2402
|
+
if (src[inner.pos] !== ")") throw new Unsure();
|
|
2403
|
+
const after2 = parseQuant(src, inner.pos + 1);
|
|
2404
|
+
flush();
|
|
2405
|
+
if (after2.q.min >= 1) {
|
|
2406
|
+
if (inner.branches.length === 1) {
|
|
2407
|
+
runs.push(...inner.branches[0].runs);
|
|
2408
|
+
ors.push(...inner.branches[0].ors);
|
|
2409
|
+
} else {
|
|
2410
|
+
const members = inner.branches.map((b) => longest(b.runs));
|
|
2411
|
+
if (members.every((m) => m !== void 0) && members.length <= MAX_OR_MEMBERS) {
|
|
2412
|
+
ors.push([...new Set(members)]);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
pos = after2.pos;
|
|
2417
|
+
continue;
|
|
2418
|
+
}
|
|
2419
|
+
if (ch === "*" || ch === "+" || ch === "?" || ch === "{" || ch === "}" || ch === "]") throw new Unsure();
|
|
2420
|
+
if (ch === "^" || ch === "$") {
|
|
2421
|
+
flush();
|
|
2422
|
+
pos++;
|
|
2423
|
+
continue;
|
|
2424
|
+
}
|
|
2425
|
+
if (ch === ".") {
|
|
2426
|
+
pos = parseQuant(src, pos + 1).pos;
|
|
2427
|
+
flush();
|
|
2428
|
+
continue;
|
|
2429
|
+
}
|
|
2430
|
+
if (ch === "[") {
|
|
2431
|
+
pos = parseQuant(src, skipClass(src, pos)).pos;
|
|
2432
|
+
flush();
|
|
2433
|
+
continue;
|
|
2434
|
+
}
|
|
2435
|
+
let literal;
|
|
2436
|
+
let next;
|
|
2437
|
+
if (ch === "\\") {
|
|
2438
|
+
const e = src[pos + 1];
|
|
2439
|
+
if (e === void 0) throw new Unsure();
|
|
2440
|
+
next = pos + 2;
|
|
2441
|
+
if ("dDwWsS".includes(e)) {
|
|
2442
|
+
pos = parseQuant(src, next).pos;
|
|
2443
|
+
flush();
|
|
2444
|
+
continue;
|
|
2445
|
+
}
|
|
2446
|
+
if ("bBAz".includes(e)) {
|
|
2447
|
+
flush();
|
|
2448
|
+
pos = next;
|
|
2449
|
+
continue;
|
|
2450
|
+
}
|
|
2451
|
+
if (e in ESCAPE_LITERAL) literal = ESCAPE_LITERAL[e];
|
|
2452
|
+
else if (e.charCodeAt(0) < 128 && !/[A-Za-z0-9]/.test(e)) literal = e;
|
|
2453
|
+
else throw new Unsure();
|
|
2454
|
+
} else {
|
|
2455
|
+
const cp = src.codePointAt(pos);
|
|
2456
|
+
literal = String.fromCodePoint(cp);
|
|
2457
|
+
next = pos + literal.length;
|
|
2458
|
+
}
|
|
2459
|
+
const after = parseQuant(src, next);
|
|
2460
|
+
if (after.q.min >= 1) cur += literal;
|
|
2461
|
+
if (after.q.present || after.q.min < 1) flush();
|
|
2462
|
+
pos = after.pos;
|
|
2463
|
+
}
|
|
2464
|
+
flush();
|
|
2465
|
+
branches.push({ runs, ors });
|
|
2466
|
+
return { branches, pos };
|
|
2467
|
+
}
|
|
2468
|
+
function nameEnd(src, from) {
|
|
2469
|
+
const close = src.indexOf(">", from);
|
|
2470
|
+
if (close < 0) throw new Unsure();
|
|
2471
|
+
return close + 1;
|
|
2472
|
+
}
|
|
2473
|
+
function unwrapWholeGroup(pattern) {
|
|
2474
|
+
if (!pattern.startsWith("(?:") || !pattern.endsWith(")")) return pattern;
|
|
2475
|
+
let depth = 1;
|
|
2476
|
+
let i = 3;
|
|
2477
|
+
try {
|
|
2478
|
+
while (i < pattern.length) {
|
|
2479
|
+
const c = pattern[i];
|
|
2480
|
+
if (c === "\\") {
|
|
2481
|
+
const n = pattern[i + 1];
|
|
2482
|
+
if (n === void 0 || n === "Q" || n === "E" || n === "p" || n === "P" || n === "x") return pattern;
|
|
2483
|
+
i += 2;
|
|
2484
|
+
} else if (c === "[") {
|
|
2485
|
+
i = skipClass(pattern, i);
|
|
2486
|
+
} else if (c === "(") {
|
|
2487
|
+
depth++;
|
|
2488
|
+
i++;
|
|
2489
|
+
} else if (c === ")") {
|
|
2490
|
+
depth--;
|
|
2491
|
+
if (depth === 0) return i === pattern.length - 1 ? pattern.slice(3, -1) : pattern;
|
|
2492
|
+
i++;
|
|
2493
|
+
} else {
|
|
2494
|
+
i++;
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
} catch (err) {
|
|
2498
|
+
if (err instanceof Unsure) return pattern;
|
|
2499
|
+
throw err;
|
|
2500
|
+
}
|
|
2501
|
+
return pattern;
|
|
2502
|
+
}
|
|
2503
|
+
function patternAlts(rawPattern, caseInsensitive) {
|
|
2504
|
+
const pattern = unwrapWholeGroup(rawPattern);
|
|
2505
|
+
let parsed;
|
|
2506
|
+
try {
|
|
2507
|
+
parsed = parseBranches(pattern, 0, false);
|
|
2508
|
+
} catch (err) {
|
|
2509
|
+
if (err instanceof Unsure) return void 0;
|
|
2510
|
+
throw err;
|
|
2511
|
+
}
|
|
2512
|
+
if (parsed.pos !== pattern.length) return void 0;
|
|
2513
|
+
const isAscii = (r) => [...r].every((c) => c.charCodeAt(0) < 128);
|
|
2514
|
+
const out = [];
|
|
2515
|
+
for (const b of parsed.branches) {
|
|
2516
|
+
let runs = b.runs;
|
|
2517
|
+
let ors = b.ors;
|
|
2518
|
+
if (caseInsensitive) {
|
|
2519
|
+
runs = runs.filter(isAscii).map((r) => r.toLowerCase());
|
|
2520
|
+
ors = ors.filter((set) => set.every(isAscii)).map((set) => set.map((r) => r.toLowerCase()));
|
|
2521
|
+
}
|
|
2522
|
+
if (runs.length === 0 && ors.length === 0) return void 0;
|
|
2523
|
+
out.push({
|
|
2524
|
+
runs: [...new Set(runs)].sort((x, y) => y.length - x.length).slice(0, MAX_RUNS_PER_BRANCH),
|
|
2525
|
+
ors: ors.slice(0, MAX_ORS_PER_BRANCH)
|
|
2526
|
+
});
|
|
2527
|
+
}
|
|
2528
|
+
return out;
|
|
2529
|
+
}
|
|
2530
|
+
function buildPrefilter(patterns, flags) {
|
|
2531
|
+
if (!Array.isArray(patterns) || patterns.length === 0) return void 0;
|
|
2532
|
+
if (!patterns.every((p) => typeof p === "string")) return void 0;
|
|
2533
|
+
if (!/^[ims]*$/.test(flags)) return void 0;
|
|
2534
|
+
const ci = flags.includes("i");
|
|
2535
|
+
const alts = [];
|
|
2536
|
+
for (const p of patterns) {
|
|
2537
|
+
const a = patternAlts(p, ci);
|
|
2538
|
+
if (a === void 0) return void 0;
|
|
2539
|
+
alts.push(...a);
|
|
2540
|
+
}
|
|
2541
|
+
return { alts, folded: ci };
|
|
2542
|
+
}
|
|
2543
|
+
function foldContent(content) {
|
|
2544
|
+
return content.toLowerCase().replaceAll("\u017F", "s");
|
|
2545
|
+
}
|
|
2546
|
+
var FileProbe = class {
|
|
2547
|
+
constructor(content) {
|
|
2548
|
+
this.content = content;
|
|
2549
|
+
}
|
|
2550
|
+
content;
|
|
2551
|
+
raw = /* @__PURE__ */ new Map();
|
|
2552
|
+
fold = /* @__PURE__ */ new Map();
|
|
2553
|
+
foldedText;
|
|
2554
|
+
has(needle, folded) {
|
|
2555
|
+
const memo = folded ? this.fold : this.raw;
|
|
2556
|
+
let found = memo.get(needle);
|
|
2557
|
+
if (found === void 0) {
|
|
2558
|
+
const hay = folded ? this.foldedText ??= foldContent(this.content) : this.content;
|
|
2559
|
+
found = hay.includes(needle);
|
|
2560
|
+
memo.set(needle, found);
|
|
2561
|
+
}
|
|
2562
|
+
return found;
|
|
2563
|
+
}
|
|
2564
|
+
};
|
|
2565
|
+
function mayMatch(pf, probe) {
|
|
2566
|
+
const folded = pf.folded;
|
|
2567
|
+
for (const b of pf.alts) {
|
|
2568
|
+
let ok = true;
|
|
2569
|
+
for (const r of b.runs) {
|
|
2570
|
+
if (!probe.has(r, folded)) {
|
|
2571
|
+
ok = false;
|
|
2572
|
+
break;
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
if (ok) {
|
|
2576
|
+
for (const set of b.ors) {
|
|
2577
|
+
let any = false;
|
|
2578
|
+
for (const r of set) {
|
|
2579
|
+
if (probe.has(r, folded)) {
|
|
2580
|
+
any = true;
|
|
2581
|
+
break;
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
2584
|
+
if (!any) {
|
|
2585
|
+
ok = false;
|
|
2586
|
+
break;
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
if (ok) return true;
|
|
2591
|
+
}
|
|
2592
|
+
return false;
|
|
2593
|
+
}
|
|
2594
|
+
var MIN_FOLD_LENGTH = 256;
|
|
2595
|
+
var lastFoldInput;
|
|
2596
|
+
var lastFolded = "";
|
|
2597
|
+
function mayMatchText(pf, text) {
|
|
2598
|
+
let hay = text;
|
|
2599
|
+
if (pf.folded) {
|
|
2600
|
+
if (text.length < MIN_FOLD_LENGTH) return true;
|
|
2601
|
+
if (lastFoldInput !== text) {
|
|
2602
|
+
lastFolded = foldContent(text);
|
|
2603
|
+
lastFoldInput = text;
|
|
2604
|
+
}
|
|
2605
|
+
hay = lastFolded;
|
|
2606
|
+
}
|
|
2607
|
+
for (const b of pf.alts) {
|
|
2608
|
+
let ok = true;
|
|
2609
|
+
for (const r of b.runs) {
|
|
2610
|
+
if (!hay.includes(r)) {
|
|
2611
|
+
ok = false;
|
|
2612
|
+
break;
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
if (ok) {
|
|
2616
|
+
for (const set of b.ors) {
|
|
2617
|
+
let any = false;
|
|
2618
|
+
for (const r of set) {
|
|
2619
|
+
if (hay.includes(r)) {
|
|
2620
|
+
any = true;
|
|
2621
|
+
break;
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
if (!any) {
|
|
2625
|
+
ok = false;
|
|
2626
|
+
break;
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
if (ok) return true;
|
|
2631
|
+
}
|
|
2632
|
+
return false;
|
|
2633
|
+
}
|
|
2634
|
+
var prefilterControl = { enabled: true };
|
|
2635
|
+
|
|
2636
|
+
// src/core/re2-detector-engine.ts
|
|
1273
2637
|
function toRe2jsFlags(flags) {
|
|
1274
2638
|
let bits = 0;
|
|
1275
2639
|
if (flags.has("i")) bits |= RE2JS.CASE_INSENSITIVE;
|
|
@@ -1298,11 +2662,15 @@ function compileDetectorRegex(source, flags = "") {
|
|
|
1298
2662
|
`[re2-detector-engine] re2js compilation failed for pattern ${JSON.stringify(source)} (flags: ${JSON.stringify(flags)}). Lookaheads, lookbehinds, and backreferences are not supported by re2js \u2014 rewrite the pattern to a RE2-compatible equivalent. Original error: ${err instanceof Error ? err.message : String(err)}`
|
|
1299
2663
|
);
|
|
1300
2664
|
}
|
|
2665
|
+
const prefilter = buildPrefilter([source], flags);
|
|
2666
|
+
const cannotMatch = (input) => prefilter !== void 0 && prefilterControl.enabled && !mayMatchText(prefilter, input);
|
|
1301
2667
|
return {
|
|
1302
2668
|
test(input) {
|
|
2669
|
+
if (cannotMatch(input)) return false;
|
|
1303
2670
|
return compiled.matcher(input).find();
|
|
1304
2671
|
},
|
|
1305
2672
|
exec(input) {
|
|
2673
|
+
if (cannotMatch(input)) return null;
|
|
1306
2674
|
const m = compiled.matcher(input);
|
|
1307
2675
|
if (!m.find()) return null;
|
|
1308
2676
|
const groupCount = compiled.groupCount();
|
|
@@ -1318,6 +2686,7 @@ function compileDetectorRegex(source, flags = "") {
|
|
|
1318
2686
|
};
|
|
1319
2687
|
},
|
|
1320
2688
|
matchAll(input) {
|
|
2689
|
+
if (cannotMatch(input)) return [];
|
|
1321
2690
|
const results = [];
|
|
1322
2691
|
const m = compiled.matcher(input);
|
|
1323
2692
|
const groupCount = compiled.groupCount();
|
|
@@ -1347,6 +2716,7 @@ function compileDetectorRegex(source, flags = "") {
|
|
|
1347
2716
|
return results;
|
|
1348
2717
|
},
|
|
1349
2718
|
replaceFirst(input, replacement) {
|
|
2719
|
+
if (cannotMatch(input)) return input;
|
|
1350
2720
|
const m = compiled.matcher(input);
|
|
1351
2721
|
if (!m.find()) return input;
|
|
1352
2722
|
const start = m.start();
|
|
@@ -1354,16 +2724,32 @@ function compileDetectorRegex(source, flags = "") {
|
|
|
1354
2724
|
return input.slice(0, start) + replacement + input.slice(end);
|
|
1355
2725
|
},
|
|
1356
2726
|
replace(input, replacement) {
|
|
2727
|
+
if (cannotMatch(input)) return input;
|
|
1357
2728
|
return compiled.matcher(input).replaceAll(replacement);
|
|
1358
2729
|
}
|
|
1359
2730
|
};
|
|
1360
2731
|
}
|
|
1361
2732
|
|
|
1362
2733
|
// src/core/redact.ts
|
|
1363
|
-
import { createHash as
|
|
1364
|
-
function redactSecretValue(
|
|
1365
|
-
|
|
1366
|
-
|
|
2734
|
+
import { createHash as createHash3 } from "crypto";
|
|
2735
|
+
function redactSecretValue(_value) {
|
|
2736
|
+
return "***";
|
|
2737
|
+
}
|
|
2738
|
+
function secretTypeName(nameOrRuleId) {
|
|
2739
|
+
const last = nameOrRuleId.includes(".") ? nameOrRuleId.slice(nameOrRuleId.lastIndexOf(".") + 1) : nameOrRuleId;
|
|
2740
|
+
const slug = last.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
2741
|
+
return slug === "" ? "secret" : slug;
|
|
2742
|
+
}
|
|
2743
|
+
function maskSecret(secretType, value) {
|
|
2744
|
+
return `${secretTypeName(secretType)}, ${[...value].length} characters, value hidden`;
|
|
2745
|
+
}
|
|
2746
|
+
function secretScreenLabel(length) {
|
|
2747
|
+
return length === null ? "value hidden" : `${length} chars, value hidden`;
|
|
2748
|
+
}
|
|
2749
|
+
var MASKED_SECRET_RE = /^([a-z0-9_]+), (\d+) characters, value hidden$/;
|
|
2750
|
+
function parseMaskedSecret(evidence) {
|
|
2751
|
+
const m = MASKED_SECRET_RE.exec(evidence.trim());
|
|
2752
|
+
return m ? { kind: "secret", secretType: m[1], length: Number(m[2]), valueHidden: true } : void 0;
|
|
1367
2753
|
}
|
|
1368
2754
|
var NON_SECRET_EVIDENCE_RE = compileDetectorRegex(
|
|
1369
2755
|
`^(?:-----BEGIN [A-Z ]{0,30}PRIVATE KEY-----|"type"\\s*:\\s*"service_account")$`
|
|
@@ -1427,26 +2813,35 @@ function scrubSecretShapes(text) {
|
|
|
1427
2813
|
out = replaceGroup(out, SECRET_ASSIGNMENT_RE, 1, maskAssignedValue);
|
|
1428
2814
|
return replaceGroup(out, AUTH_ASSIGNMENT_RE, 1, maskAssignedValue);
|
|
1429
2815
|
}
|
|
1430
|
-
function redactEvidence(evidence, category) {
|
|
2816
|
+
function redactEvidence(evidence, category, ruleId = "secret") {
|
|
1431
2817
|
if (category === "secrets") {
|
|
1432
2818
|
const trimmed = evidence.trim();
|
|
1433
|
-
if (NON_SECRET_EVIDENCE_RE.test(trimmed)) return evidence;
|
|
1434
|
-
return
|
|
2819
|
+
if (NON_SECRET_EVIDENCE_RE.test(trimmed) || parseMaskedSecret(trimmed)) return evidence;
|
|
2820
|
+
return maskSecret(ruleId, trimmed);
|
|
1435
2821
|
}
|
|
1436
2822
|
return scrubSecretShapes(evidence);
|
|
1437
2823
|
}
|
|
1438
2824
|
function computeFindingKey(finding) {
|
|
1439
2825
|
const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
|
|
1440
|
-
return
|
|
2826
|
+
return createHash3("sha256").update(basis).digest("hex").slice(0, 16);
|
|
1441
2827
|
}
|
|
1442
2828
|
var FINDING_KEY_PROP = "_findingKey";
|
|
2829
|
+
function stampFindingIdentity(finding, rawValue) {
|
|
2830
|
+
Object.defineProperty(finding, FINDING_KEY_PROP, {
|
|
2831
|
+
value: createHash3("sha256").update(rawValue).digest("hex").slice(0, 16),
|
|
2832
|
+
enumerable: false,
|
|
2833
|
+
writable: true,
|
|
2834
|
+
configurable: true
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
1443
2837
|
function getFindingKey(finding) {
|
|
1444
2838
|
const stamped = finding[FINDING_KEY_PROP];
|
|
1445
2839
|
return typeof stamped === "string" ? stamped : computeFindingKey(finding);
|
|
1446
2840
|
}
|
|
1447
2841
|
function redactFindingsEvidence(findings, alreadyRedacted = /* @__PURE__ */ new Set()) {
|
|
1448
2842
|
for (const f of findings) {
|
|
1449
|
-
Object.
|
|
2843
|
+
if (Object.prototype.hasOwnProperty.call(f, FINDING_KEY_PROP)) {
|
|
2844
|
+
} else Object.defineProperty(f, FINDING_KEY_PROP, {
|
|
1450
2845
|
value: computeFindingKey(f),
|
|
1451
2846
|
enumerable: false,
|
|
1452
2847
|
writable: true,
|
|
@@ -1454,7 +2849,7 @@ function redactFindingsEvidence(findings, alreadyRedacted = /* @__PURE__ */ new
|
|
|
1454
2849
|
});
|
|
1455
2850
|
if (typeof f.evidence !== "string" || f.evidence.length === 0) continue;
|
|
1456
2851
|
if (alreadyRedacted.has(f)) continue;
|
|
1457
|
-
f.evidence = redactEvidence(f.evidence, f.category);
|
|
2852
|
+
f.evidence = redactEvidence(f.evidence, f.category, f.id);
|
|
1458
2853
|
}
|
|
1459
2854
|
return findings;
|
|
1460
2855
|
}
|
|
@@ -1744,6 +3139,15 @@ var PLACEHOLDER_VALUE_RE = compileDetectorRegex(
|
|
|
1744
3139
|
"i"
|
|
1745
3140
|
);
|
|
1746
3141
|
var ASSIGNED_LITERAL_RE = compileDetectorRegex(`[=:]\\s*['"\`]?([^\\s'"\`;,]+)`);
|
|
3142
|
+
var FIREBASE_CONFIG_CONTEXT_RE = compileDetectorRegex(`firebaseConfig|initializeApp|authDomain|messagingSenderId|storageBucket|measurementId`);
|
|
3143
|
+
var API_KEY_ASSIGN_RE = compileDetectorRegex(`\\bapiKey['"]?\\s*[:=]`);
|
|
3144
|
+
var FIREBASE_ADMIN_RE = compileDetectorRegex(`firebase-admin|firebase_admin`);
|
|
3145
|
+
function isFirebaseWebConfigKey(lines, i, content) {
|
|
3146
|
+
if (!API_KEY_ASSIGN_RE.test(lines[i])) return false;
|
|
3147
|
+
if (FIREBASE_ADMIN_RE.test(content)) return false;
|
|
3148
|
+
const window = lines.slice(Math.max(0, i - 12), i + 13).join("\n");
|
|
3149
|
+
return FIREBASE_CONFIG_CONTEXT_RE.test(window);
|
|
3150
|
+
}
|
|
1747
3151
|
function isPublicKeyValue(value) {
|
|
1748
3152
|
const v = value.trim();
|
|
1749
3153
|
if (PUBLISHABLE_PREFIX_RE.test(v)) return true;
|
|
@@ -1812,12 +3216,13 @@ function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
|
|
|
1812
3216
|
category: "secrets",
|
|
1813
3217
|
file: relativePath,
|
|
1814
3218
|
line: i + 1,
|
|
1815
|
-
evidence:
|
|
3219
|
+
evidence: maskSecret("supabase_service_role_key", m.match),
|
|
1816
3220
|
confidence: "HIGH",
|
|
1817
3221
|
explanation: 'A legacy-format Supabase service-role key was found \u2014 a JWT whose decoded payload contains "role":"service_role". This key bypasses Row Level Security entirely and grants full read/write access to every table, regardless of any RLS policy.',
|
|
1818
3222
|
recommendation: "Remove immediately, including from any .env file. Never reference it from a NEXT_PUBLIC_/VITE_/EXPO_PUBLIC_-prefixed variable or client-side code. Use it only in server-only code via process.env.SUPABASE_SERVICE_ROLE_KEY, and rotate it in the Supabase dashboard (Project Settings \u2192 API) since any repo exposure must be treated as compromised.",
|
|
1819
3223
|
blocking: policy.block.includes(id)
|
|
1820
3224
|
};
|
|
3225
|
+
stampFindingIdentity(jwtFinding, m.match);
|
|
1821
3226
|
if (!dedupe.fold(findings, i, m.index, m.match, jwtFinding)) findings.push(jwtFinding);
|
|
1822
3227
|
}
|
|
1823
3228
|
}
|
|
@@ -1872,8 +3277,21 @@ function envFileHasSecret(content) {
|
|
|
1872
3277
|
}
|
|
1873
3278
|
return false;
|
|
1874
3279
|
}
|
|
3280
|
+
function isTestValue(value) {
|
|
3281
|
+
const v = value.trim();
|
|
3282
|
+
const urlPassword = URL_PASSWORD_RE.exec(v);
|
|
3283
|
+
if (v.includes("://")) return isPlaceholderValue(v) || urlPassword?.groups[0] !== void 0 && isPlaceholderValue(urlPassword.groups[0]);
|
|
3284
|
+
return TEST_MODE_KEY_RE.test(v) || isPlaceholderValue(v);
|
|
3285
|
+
}
|
|
3286
|
+
var URL_PASSWORD_RE = compileDetectorRegex(`://[^\\s:/@]*:([^\\s@]+)@`);
|
|
3287
|
+
var TEST_MODE_KEY_RE = compileDetectorRegex(`^[rs]k_test_`);
|
|
1875
3288
|
function checkSecrets(files, policy) {
|
|
3289
|
+
return checkSecretsWithStats(files, policy).findings;
|
|
3290
|
+
}
|
|
3291
|
+
function checkSecretsWithStats(files, policy) {
|
|
1876
3292
|
const findings = [];
|
|
3293
|
+
let ignoredTestValues = 0;
|
|
3294
|
+
const publicIdentifiers = /* @__PURE__ */ new Set();
|
|
1877
3295
|
for (const file of files) {
|
|
1878
3296
|
const { content, relativePath } = file;
|
|
1879
3297
|
let envFindingIdx = -1;
|
|
@@ -1917,7 +3335,11 @@ function checkSecrets(files, policy) {
|
|
|
1917
3335
|
const line = lines2[i];
|
|
1918
3336
|
const match = NEXT_PUBLIC_SECRET_RE.exec(line);
|
|
1919
3337
|
if (match && match.groups[0]) {
|
|
1920
|
-
if (isPublicKeyValue(assignedLiteral(line.slice(match.index)))
|
|
3338
|
+
if (isPublicKeyValue(assignedLiteral(line.slice(match.index)))) continue;
|
|
3339
|
+
if (isTestValue(match.groups[0])) {
|
|
3340
|
+
ignoredTestValues++;
|
|
3341
|
+
continue;
|
|
3342
|
+
}
|
|
1921
3343
|
const id = "exposed_env";
|
|
1922
3344
|
findings.push({
|
|
1923
3345
|
id,
|
|
@@ -1926,7 +3348,7 @@ function checkSecrets(files, policy) {
|
|
|
1926
3348
|
category: "secrets",
|
|
1927
3349
|
file: relativePath,
|
|
1928
3350
|
line: i + 1,
|
|
1929
|
-
evidence: `${line.split("=")[0].trim()}=${
|
|
3351
|
+
evidence: `${line.split("=")[0].trim()}=${maskSecret("next_public_secret", match.groups[0])}`,
|
|
1930
3352
|
confidence: "HIGH",
|
|
1931
3353
|
explanation: "An environment variable with NEXT_PUBLIC_ prefix containing a secret-sounding name is declared " + (isEnvFileForNextPublicCheck ? "in a .env file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users regardless of which file declares them." : "in a frontend file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users."),
|
|
1932
3354
|
recommendation: "Move secret API calls to a server-side route (e.g., Next.js API route or Server Action). Never use NEXT_PUBLIC_ for keys, tokens, or secrets.",
|
|
@@ -1952,9 +3374,17 @@ function checkSecrets(files, policy) {
|
|
|
1952
3374
|
if (pattern.postExcludeFollowedBy(restAfterMatch)) continue;
|
|
1953
3375
|
}
|
|
1954
3376
|
const secretValue = lineMatch.groups[0] ?? lineMatch.match;
|
|
1955
|
-
if (
|
|
3377
|
+
if (isTestValue(secretValue)) {
|
|
3378
|
+
ignoredTestValues++;
|
|
3379
|
+
continue;
|
|
3380
|
+
}
|
|
1956
3381
|
const isAssignMatch = lineMatch.match.includes("=") || lineMatch.match.includes(":");
|
|
1957
3382
|
if (isPublicKeyValue((isAssignMatch ? assignedLiteral(line.slice(lineMatch.index)) : "") || secretValue)) continue;
|
|
3383
|
+
const firebasePublic = secretValue.startsWith("AIza") && isFirebaseWebConfigKey(lines, i, content);
|
|
3384
|
+
if (firebasePublic) {
|
|
3385
|
+
publicIdentifiers.add(`${relativePath}:${i}`);
|
|
3386
|
+
continue;
|
|
3387
|
+
}
|
|
1958
3388
|
const secretFinding = {
|
|
1959
3389
|
id: pattern.id,
|
|
1960
3390
|
title: pattern.name,
|
|
@@ -1962,12 +3392,13 @@ function checkSecrets(files, policy) {
|
|
|
1962
3392
|
category: "secrets",
|
|
1963
3393
|
file: relativePath,
|
|
1964
3394
|
line: i + 1,
|
|
1965
|
-
evidence:
|
|
3395
|
+
evidence: maskSecret(pattern.name, secretValue),
|
|
1966
3396
|
confidence: looksFakeKey(secretValue) ? "LOW" : pattern.confidence,
|
|
1967
3397
|
explanation: pattern.explanation,
|
|
1968
3398
|
recommendation: pattern.recommendation,
|
|
1969
3399
|
blocking: policy.block.includes(pattern.id)
|
|
1970
3400
|
};
|
|
3401
|
+
stampFindingIdentity(secretFinding, secretValue);
|
|
1971
3402
|
if (!secretDedupe.fold(findings, i, secretStart(lineMatch, secretValue), secretValue, secretFinding)) {
|
|
1972
3403
|
findings.push(secretFinding);
|
|
1973
3404
|
}
|
|
@@ -1978,7 +3409,7 @@ function checkSecrets(files, policy) {
|
|
|
1978
3409
|
findings.splice(envFindingIdx, 1);
|
|
1979
3410
|
}
|
|
1980
3411
|
}
|
|
1981
|
-
return findings;
|
|
3412
|
+
return { findings, ignoredTestValues, publicIdentifiers: publicIdentifiers.size };
|
|
1982
3413
|
}
|
|
1983
3414
|
var secretsCheck = {
|
|
1984
3415
|
id: "secrets",
|
|
@@ -1991,6 +3422,7 @@ var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|ac
|
|
|
1991
3422
|
var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management|debug|internal|env|_debug)(\/|$)/;
|
|
1992
3423
|
var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management|debug|internal|env|_debug|dev)(\/|$)/;
|
|
1993
3424
|
var WEBHOOK_PATH_PATTERN = /\/webhooks?\//;
|
|
3425
|
+
var PUBLIC_AUTH_PATH_PATTERN = /(?:^|\/)(?:\(auth\)|sign-?in|sign-?up|sign-?out|log-?in|log-?out|register|forgot-password|reset-password|verify-email|callback)(?:\/|\.|$)/i;
|
|
1994
3426
|
var RE2_EXPRESS_ROUTE_DEFINITION = compileDetectorRegex(
|
|
1995
3427
|
`(?:router|app)\\.(get|post|put|patch|delete|all)\\s*\\(\\s*['"\`]([^'"\`,)]+)['"\`]`,
|
|
1996
3428
|
"i"
|
|
@@ -2409,6 +3841,16 @@ function hasActiveAuthCall(content) {
|
|
|
2409
3841
|
const execText = extractExecutableText(content);
|
|
2410
3842
|
return RE2_AUTH_CALL_PATTERN.test(execText);
|
|
2411
3843
|
}
|
|
3844
|
+
var RE2_INLINE_DENY = compileDetectorRegex(
|
|
3845
|
+
`status\\s*:\\s*40[13]\\b|\\.status\\s*\\(\\s*40[13]\\s*\\)|\\b(?:unauthorized|forbidden)\\s*\\(`
|
|
3846
|
+
);
|
|
3847
|
+
var RE2_CREDENTIAL_READ = compileDetectorRegex(
|
|
3848
|
+
`authorization|cookies\\s*\\(|\\.cookies\\b|bearer|x-api-key|\\bsession\\b|\\btoken\\b`,
|
|
3849
|
+
"i"
|
|
3850
|
+
);
|
|
3851
|
+
function hasInlineCredentialGate(content) {
|
|
3852
|
+
return RE2_INLINE_DENY.test(extractExecutableText(content)) && RE2_CREDENTIAL_READ.test(stripComments(content));
|
|
3853
|
+
}
|
|
2412
3854
|
var PAGE_FILE_PATTERN = /(?:^|\/)page\.[tj]sx?$/;
|
|
2413
3855
|
function isPageFile(rp) {
|
|
2414
3856
|
return PAGE_FILE_PATTERN.test(rp);
|
|
@@ -2602,6 +4044,9 @@ var authCheck = {
|
|
|
2602
4044
|
if (WEBHOOK_PATH_PATTERN.test(rp)) {
|
|
2603
4045
|
continue;
|
|
2604
4046
|
}
|
|
4047
|
+
if (PUBLIC_AUTH_PATH_PATTERN.test(rp) && (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp) || SENSITIVE_API_ROUTE_PATTERN.test(rp))) {
|
|
4048
|
+
continue;
|
|
4049
|
+
}
|
|
2605
4050
|
if (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp)) {
|
|
2606
4051
|
if (!isPageFile(rp)) continue;
|
|
2607
4052
|
if (!gatesAccess(content) && !layoutChain(rp, filesByPath).some((l) => gatesAccess(l.content))) {
|
|
@@ -2621,7 +4066,7 @@ var authCheck = {
|
|
|
2621
4066
|
continue;
|
|
2622
4067
|
}
|
|
2623
4068
|
if (SENSITIVE_API_ROUTE_PATTERN.test(rp)) {
|
|
2624
|
-
if (!hasActiveAuthCall(content)) {
|
|
4069
|
+
if (!hasActiveAuthCall(content) && !hasInlineCredentialGate(content)) {
|
|
2625
4070
|
const wasRemoved = hasCommentedAuthCall(content);
|
|
2626
4071
|
findings.push({
|
|
2627
4072
|
id: "auth_route_without_guard",
|
|
@@ -3546,9 +4991,9 @@ var payments = {
|
|
|
3546
4991
|
|
|
3547
4992
|
// src/core/coderef-dispatch.ts
|
|
3548
4993
|
import { createRequire } from "module";
|
|
3549
|
-
import { readFileSync as
|
|
4994
|
+
import { readFileSync as readFileSync5, existsSync as existsSync4 } from "fs";
|
|
3550
4995
|
import { fileURLToPath } from "url";
|
|
3551
|
-
import { dirname as dirname3, join as
|
|
4996
|
+
import { dirname as dirname3, join as join6 } from "path";
|
|
3552
4997
|
var DEFAULT_DISPATCH_TABLE = {
|
|
3553
4998
|
"secrets:secretsCheck": secretsCheck,
|
|
3554
4999
|
"auth:authCheck": authCheck,
|
|
@@ -3567,7 +5012,7 @@ function semverLt(a, b) {
|
|
|
3567
5012
|
if (aMin !== bMin) return aMin < bMin;
|
|
3568
5013
|
return aPatch < bPatch;
|
|
3569
5014
|
}
|
|
3570
|
-
function runCoderefRules(rules, files, policy, cliVersion =
|
|
5015
|
+
function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION2, table = DEFAULT_DISPATCH_TABLE, manifest) {
|
|
3571
5016
|
const findings = [];
|
|
3572
5017
|
let degraded = false;
|
|
3573
5018
|
const warnings = [];
|
|
@@ -3620,21 +5065,21 @@ function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION, table =
|
|
|
3620
5065
|
return { findings, degraded, warnings };
|
|
3621
5066
|
}
|
|
3622
5067
|
var _require = createRequire(import.meta.url);
|
|
3623
|
-
var _pkgPath =
|
|
3624
|
-
var
|
|
5068
|
+
var _pkgPath = join6(dirname3(fileURLToPath(import.meta.url)), "../../package.json");
|
|
5069
|
+
var CLI_VERSION2;
|
|
3625
5070
|
try {
|
|
3626
5071
|
const pkg = _require(_pkgPath);
|
|
3627
|
-
|
|
5072
|
+
CLI_VERSION2 = typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
3628
5073
|
} catch {
|
|
3629
|
-
|
|
5074
|
+
CLI_VERSION2 = "0.0.0";
|
|
3630
5075
|
}
|
|
3631
|
-
var _manifestPath =
|
|
5076
|
+
var _manifestPath = join6(dirname3(fileURLToPath(import.meta.url)), "../../checksum-manifest.json");
|
|
3632
5077
|
function loadChecksumManifest() {
|
|
3633
|
-
if (!
|
|
5078
|
+
if (!existsSync4(_manifestPath)) {
|
|
3634
5079
|
return void 0;
|
|
3635
5080
|
}
|
|
3636
5081
|
try {
|
|
3637
|
-
const raw =
|
|
5082
|
+
const raw = readFileSync5(_manifestPath, "utf-8");
|
|
3638
5083
|
const parsed = JSON.parse(raw);
|
|
3639
5084
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
3640
5085
|
console.warn("[shipguard] checksum-manifest.json is not a valid object \u2014 skipping checksum verification");
|
|
@@ -3690,6 +5135,19 @@ function applySuppressions(findings, files) {
|
|
|
3690
5135
|
}
|
|
3691
5136
|
return findings;
|
|
3692
5137
|
}
|
|
5138
|
+
function applyPolicyIgnores(findings, entries) {
|
|
5139
|
+
const byFinding = entries.filter((e) => e.finding !== void 0);
|
|
5140
|
+
if (byFinding.length === 0) return findings;
|
|
5141
|
+
for (const f of findings) {
|
|
5142
|
+
const hit = byFinding.find((e) => e.finding === f.id && (e.file === void 0 || e.file === f.file));
|
|
5143
|
+
if (hit) {
|
|
5144
|
+
f.suppressed = true;
|
|
5145
|
+
f.suppressionReason = hit.reason;
|
|
5146
|
+
f.blocking = false;
|
|
5147
|
+
}
|
|
5148
|
+
}
|
|
5149
|
+
return findings;
|
|
5150
|
+
}
|
|
3693
5151
|
|
|
3694
5152
|
// src/core/re2js-compile-cache.ts
|
|
3695
5153
|
import { RE2JS as RE2JS2 } from "re2js";
|
|
@@ -3732,11 +5190,14 @@ var ProFetchError = class extends Error {
|
|
|
3732
5190
|
code;
|
|
3733
5191
|
/** Only populated for RATE_LIMITED and PLATFORM_UNAVAILABLE, when the server sends a usable `Retry-After` header. */
|
|
3734
5192
|
retryAfterSeconds;
|
|
5193
|
+
/** 0.13 plan data that came with the failure (the 402 refusals carry a signed account document). */
|
|
5194
|
+
context;
|
|
3735
5195
|
constructor(code, message, opts) {
|
|
3736
5196
|
super(message);
|
|
3737
5197
|
this.name = "ProFetchError";
|
|
3738
5198
|
this.code = code;
|
|
3739
5199
|
this.retryAfterSeconds = opts?.retryAfterSeconds;
|
|
5200
|
+
this.context = opts?.context;
|
|
3740
5201
|
}
|
|
3741
5202
|
};
|
|
3742
5203
|
function parseCreditsRemaining(headers) {
|
|
@@ -3745,6 +5206,7 @@ function parseCreditsRemaining(headers) {
|
|
|
3745
5206
|
const credits = Number(raw.trim());
|
|
3746
5207
|
return Number.isFinite(credits) ? credits : void 0;
|
|
3747
5208
|
}
|
|
5209
|
+
var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3748
5210
|
async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath) {
|
|
3749
5211
|
assertTrustedApiUrl(apiUrl);
|
|
3750
5212
|
let token;
|
|
@@ -3760,6 +5222,8 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3760
5222
|
throw err;
|
|
3761
5223
|
}
|
|
3762
5224
|
if (!token) throw new ProFetchError("AUTH_FAILED", "Not authenticated. Run `shipguard login` first.");
|
|
5225
|
+
const acct = acctFromAccessToken(token);
|
|
5226
|
+
const nonce = newNonce();
|
|
3763
5227
|
let res;
|
|
3764
5228
|
try {
|
|
3765
5229
|
res = await fetch(`${apiUrl}/api/rules/fetch`, {
|
|
@@ -3767,6 +5231,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3767
5231
|
headers: {
|
|
3768
5232
|
"Authorization": `Bearer ${token}`,
|
|
3769
5233
|
"Content-Type": "application/json",
|
|
5234
|
+
...clientHelloHeaders(CLI_VERSION, nonce),
|
|
3770
5235
|
...scanId ? { "Idempotency-Key": scanId } : {}
|
|
3771
5236
|
},
|
|
3772
5237
|
body: JSON.stringify({ frameworks, categories, ...scanId ? { scanId } : {} })
|
|
@@ -3799,7 +5264,20 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3799
5264
|
);
|
|
3800
5265
|
}
|
|
3801
5266
|
if (res.status === 401) throw new ProFetchError("AUTH_FAILED", "Auth expired. Run `shipguard login` again.");
|
|
3802
|
-
if (res.status ===
|
|
5267
|
+
if (res.status === 503 && errorBody?.code === "TOKEN_CHECK_UNAVAILABLE") {
|
|
5268
|
+
throw new ProFetchError("SERVER_ERROR", "The rulebook service could not check your sign-in right now. Retry in a minute.", {
|
|
5269
|
+
retryAfterSeconds: parseRetryAfterSeconds(res.headers)
|
|
5270
|
+
});
|
|
5271
|
+
}
|
|
5272
|
+
if (res.status === 402) {
|
|
5273
|
+
const plan = errorBody?.account === void 0 ? null : await readAccountReply(errorBody.account, { acct, nonce, scanId: scanId ?? null, now: Date.now() });
|
|
5274
|
+
const serverCode = typeof errorBody?.code === "string" && /^[A-Z_]{1,40}$/.test(errorBody.code) ? errorBody.code : null;
|
|
5275
|
+
const serverText = safeServerText(errorBody?.error, TEXT_CAPS.limit);
|
|
5276
|
+
const code = serverCode === "ALLOWANCE_USED" ? "ALLOWANCE_USED" : serverCode === "PLAN_INACTIVE" ? "PLAN_INACTIVE" : "INSUFFICIENT_CREDITS";
|
|
5277
|
+
throw new ProFetchError(code, serverText ?? "The server did not provide the rulebook for this scan.", {
|
|
5278
|
+
context: { plan, acct, serverCode, serverText }
|
|
5279
|
+
});
|
|
5280
|
+
}
|
|
3803
5281
|
if (res.status === 429) {
|
|
3804
5282
|
throw new ProFetchError(
|
|
3805
5283
|
"RATE_LIMITED",
|
|
@@ -3825,7 +5303,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3825
5303
|
const rawText = await res.text();
|
|
3826
5304
|
let responseJson;
|
|
3827
5305
|
try {
|
|
3828
|
-
const { parseStrictNoDup: parseStrict } = await import("./dist-
|
|
5306
|
+
const { parseStrictNoDup: parseStrict } = await import("./dist-3XUWQFMP.js");
|
|
3829
5307
|
responseJson = parseStrict(rawText);
|
|
3830
5308
|
} catch (parseErr) {
|
|
3831
5309
|
const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
|
|
@@ -3838,17 +5316,30 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3838
5316
|
const bundleResponse = responseJson;
|
|
3839
5317
|
const effectiveFloorPath = floorPath ?? DEFAULT_FLOOR_PATH;
|
|
3840
5318
|
const effectiveScanId = scanId ?? "";
|
|
5319
|
+
const planRead = await readAccountReply(bundleResponse.account, { acct, nonce, scanId: effectiveScanId === "" ? null : effectiveScanId, now: Date.now() });
|
|
5320
|
+
const rawEnvelope = bundleResponse.bundleEnvelope;
|
|
5321
|
+
const isV2 = isRecord2(rawEnvelope) && rawEnvelope["protocolVersion"] === "2";
|
|
5322
|
+
const sentCategories = categories !== void 0 && categories.length > 0 ? categories : null;
|
|
3841
5323
|
const verifyResult = await verifyBundleResponse(
|
|
3842
5324
|
bundleResponse,
|
|
3843
5325
|
{
|
|
3844
5326
|
scanId: effectiveScanId,
|
|
3845
5327
|
frameworks,
|
|
3846
|
-
options: {},
|
|
3847
|
-
isPro: true
|
|
5328
|
+
options: isV2 && sentCategories !== null ? { categories: sentCategories } : {},
|
|
5329
|
+
isPro: true,
|
|
5330
|
+
categories: sentCategories,
|
|
5331
|
+
// A verified LIVE plan document's tiers: a served selection narrower than these is RULEBOOK_PARTIAL.
|
|
5332
|
+
verifiedRulebookTiers: planRead.live ? planRead.block.server?.capabilities?.rulebookTiers ?? null : null
|
|
3848
5333
|
},
|
|
3849
5334
|
effectiveFloorPath
|
|
3850
5335
|
);
|
|
3851
5336
|
if (!verifyResult.ok) {
|
|
5337
|
+
if (verifyResult.freshnessExpired) {
|
|
5338
|
+
throw new ProFetchError(
|
|
5339
|
+
"FRESHNESS_EXPIRED",
|
|
5340
|
+
`${PRO_RULES_UNAVAILABLE_MESSAGE} (${verifyResult.reason})`
|
|
5341
|
+
);
|
|
5342
|
+
}
|
|
3852
5343
|
throw new ProFetchError(
|
|
3853
5344
|
"BUNDLE_INVALID",
|
|
3854
5345
|
`Attested bundle verification failed: ${verifyResult.reason}` + (verifyResult.nonSafe ? " [non-safe exit]" : "")
|
|
@@ -3902,7 +5393,21 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3902
5393
|
framework: r.framework
|
|
3903
5394
|
};
|
|
3904
5395
|
});
|
|
3905
|
-
|
|
5396
|
+
const areaByRuleId = {};
|
|
5397
|
+
for (const r of verifyResult.selectedRules) {
|
|
5398
|
+
const area = safeServerText(r["area"], TEXT_CAPS.item);
|
|
5399
|
+
if (area !== null) areaByRuleId[r.id] = area;
|
|
5400
|
+
}
|
|
5401
|
+
return {
|
|
5402
|
+
rules,
|
|
5403
|
+
creditsRemaining: credits,
|
|
5404
|
+
rulesVersion,
|
|
5405
|
+
plan: planRead,
|
|
5406
|
+
acct,
|
|
5407
|
+
partial: verifyResult.partial === true,
|
|
5408
|
+
tiersApplied: verifyResult.selection ? verifyResult.selection.tiers : null,
|
|
5409
|
+
areaByRuleId
|
|
5410
|
+
};
|
|
3906
5411
|
}
|
|
3907
5412
|
throw new ProFetchError(
|
|
3908
5413
|
"BUNDLE_INVALID",
|
|
@@ -3982,84 +5487,32 @@ function runProRules(rules, files, _policy) {
|
|
|
3982
5487
|
);
|
|
3983
5488
|
}
|
|
3984
5489
|
}
|
|
3985
|
-
const findings = [];
|
|
3986
5490
|
const allRelativePaths = files.map((f) => f.relativePath);
|
|
3987
5491
|
const ctx = {
|
|
3988
5492
|
allRelativePaths,
|
|
3989
5493
|
releaseId: "pre-attestation"
|
|
3990
5494
|
};
|
|
3991
|
-
|
|
3992
|
-
|
|
3993
|
-
|
|
3994
|
-
|
|
3995
|
-
|
|
3996
|
-
const
|
|
3997
|
-
|
|
3998
|
-
|
|
3999
|
-
|
|
4000
|
-
patterns: rule.matcher.patterns,
|
|
4001
|
-
antiPatterns: rule.matcher.antiPatterns,
|
|
4002
|
-
flags: rule.matcher.flags ?? "",
|
|
4003
|
-
// pass through delivered values; executor defaults to 'none'/'statement'.
|
|
4004
|
-
...boundary !== void 0 && { boundary },
|
|
4005
|
-
...antiPatternScope !== void 0 && { antiPatternScope }
|
|
4006
|
-
};
|
|
4007
|
-
} else if (rule.matcher.type === "file-presence") {
|
|
4008
|
-
const presenceRule = rule.matcher.presenceRule ?? "must-not-exist";
|
|
4009
|
-
matcherForExecutor = {
|
|
4010
|
-
type: "file-presence",
|
|
4011
|
-
fileGlob: rule.matcher.fileGlob,
|
|
4012
|
-
presenceRule
|
|
4013
|
-
};
|
|
4014
|
-
} else if (rule.matcher.type === "file-relationship") {
|
|
4015
|
-
const frAny = rule.matcher;
|
|
4016
|
-
const frFlags = frAny["flags"] ?? "";
|
|
4017
|
-
const frPatterns = rule.matcher.patterns ?? [];
|
|
4018
|
-
const frAntiPatterns = rule.matcher.antiPatterns ?? [];
|
|
4019
|
-
matcherForExecutor = {
|
|
4020
|
-
type: "file-relationship",
|
|
4021
|
-
fileGlob: rule.matcher.fileGlob,
|
|
4022
|
-
context: {
|
|
4023
|
-
requiresFile: rule.matcher.context?.requiresFile,
|
|
4024
|
-
requiresPattern: rule.matcher.context?.requiresPattern
|
|
4025
|
-
},
|
|
4026
|
-
// Extended fields for self-referential requiresPattern evaluation:
|
|
4027
|
-
patterns: frPatterns,
|
|
4028
|
-
antiPatterns: frAntiPatterns,
|
|
4029
|
-
flags: frFlags
|
|
4030
|
-
};
|
|
4031
|
-
} else {
|
|
4032
|
-
throw new RunProRulesFatalError(
|
|
4033
|
-
`Unreachable: unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}"`
|
|
4034
|
-
);
|
|
4035
|
-
}
|
|
4036
|
-
let matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
|
|
4037
|
-
let requiresFailClosed;
|
|
4038
|
-
if (rule.matcher.type === "pattern") {
|
|
4039
|
-
const reqPattern = rule.matcher.context?.requiresPattern;
|
|
4040
|
-
if (reqPattern !== void 0) {
|
|
4041
|
-
try {
|
|
4042
|
-
const reqRe = compileCached(reqPattern, 0);
|
|
4043
|
-
matched = matched.filter((f) => reqRe.matcher(f.content).find());
|
|
4044
|
-
} catch (reqErr) {
|
|
4045
|
-
console.error(
|
|
4046
|
-
`[shipguard] requiresPattern compile error for rule ${rule.id}: ${reqErr instanceof Error ? reqErr.message : String(reqErr)} \u2014 fail closed`
|
|
4047
|
-
);
|
|
4048
|
-
requiresFailClosed = reqPattern;
|
|
4049
|
-
}
|
|
5495
|
+
const prepared = rules.map((rule) => prepareRule(rule));
|
|
5496
|
+
for (const file of files) {
|
|
5497
|
+
const probe = new FileProbe(file.content);
|
|
5498
|
+
let lines;
|
|
5499
|
+
for (const p of prepared) {
|
|
5500
|
+
const { rule } = p;
|
|
5501
|
+
if (!minimatch(file.relativePath, rule.matcher.fileGlob)) continue;
|
|
5502
|
+
if (p.prefilter !== void 0 && p.requiresFailClosed === void 0 && prefilterControl.enabled) {
|
|
5503
|
+
if (!mayMatch(p.prefilter, probe)) continue;
|
|
4050
5504
|
}
|
|
4051
|
-
|
|
4052
|
-
for (const file of matched) {
|
|
5505
|
+
if (p.requiresRe !== void 0 && !p.requiresRe.matcher(file.content).find()) continue;
|
|
4053
5506
|
let canonicalFindings;
|
|
4054
5507
|
try {
|
|
4055
|
-
canonicalFindings = requiresFailClosed !== void 0 ? [{
|
|
5508
|
+
canonicalFindings = p.requiresFailClosed !== void 0 ? [{
|
|
4056
5509
|
line: 1,
|
|
4057
5510
|
column: 1,
|
|
4058
|
-
evidence: `requiresPattern "${requiresFailClosed}" (compile error \u2014 fail closed)`,
|
|
5511
|
+
evidence: `requiresPattern "${p.requiresFailClosed}" (compile error \u2014 fail closed)`,
|
|
4059
5512
|
suppressionState: "active",
|
|
4060
5513
|
matcherType: "pattern"
|
|
4061
5514
|
}] : activeExecutor.evaluate(
|
|
4062
|
-
|
|
5515
|
+
p.matcher,
|
|
4063
5516
|
{ relativePath: file.relativePath, content: file.content },
|
|
4064
5517
|
ctx
|
|
4065
5518
|
);
|
|
@@ -4073,11 +5526,11 @@ function runProRules(rules, files, _policy) {
|
|
|
4073
5526
|
);
|
|
4074
5527
|
}
|
|
4075
5528
|
for (const cf of canonicalFindings) {
|
|
4076
|
-
|
|
5529
|
+
lines ??= file.content.split("\n");
|
|
4077
5530
|
const lineIndex = cf.line - 1;
|
|
4078
5531
|
const commentSuppressed = lineIndex >= 0 ? isLineSuppressed(lines, lineIndex, rule.id) : false;
|
|
4079
5532
|
const isSuppressed = cf.suppressionState === "suppressed" || commentSuppressed;
|
|
4080
|
-
findings.push({
|
|
5533
|
+
p.findings.push({
|
|
4081
5534
|
id: rule.id,
|
|
4082
5535
|
title: rule.explanation.split(".")[0],
|
|
4083
5536
|
severity: rule.severity,
|
|
@@ -4104,7 +5557,70 @@ function runProRules(rules, files, _policy) {
|
|
|
4104
5557
|
}
|
|
4105
5558
|
}
|
|
4106
5559
|
}
|
|
4107
|
-
return findings;
|
|
5560
|
+
return prepared.flatMap((p) => p.findings);
|
|
5561
|
+
}
|
|
5562
|
+
function prepareRule(rule) {
|
|
5563
|
+
let matcherForExecutor;
|
|
5564
|
+
if (rule.matcher.type === "pattern") {
|
|
5565
|
+
const ruleAny = rule.matcher;
|
|
5566
|
+
const antiPatternScope = ruleAny["antiPatternScope"];
|
|
5567
|
+
const boundary = ruleAny["boundary"];
|
|
5568
|
+
matcherForExecutor = {
|
|
5569
|
+
type: "pattern",
|
|
5570
|
+
fileGlob: rule.matcher.fileGlob,
|
|
5571
|
+
patterns: rule.matcher.patterns,
|
|
5572
|
+
antiPatterns: rule.matcher.antiPatterns,
|
|
5573
|
+
flags: rule.matcher.flags ?? "",
|
|
5574
|
+
// pass through delivered values; executor defaults to 'none'/'statement'.
|
|
5575
|
+
...boundary !== void 0 && { boundary },
|
|
5576
|
+
...antiPatternScope !== void 0 && { antiPatternScope }
|
|
5577
|
+
};
|
|
5578
|
+
} else if (rule.matcher.type === "file-presence") {
|
|
5579
|
+
const presenceRule = rule.matcher.presenceRule ?? "must-not-exist";
|
|
5580
|
+
matcherForExecutor = {
|
|
5581
|
+
type: "file-presence",
|
|
5582
|
+
fileGlob: rule.matcher.fileGlob,
|
|
5583
|
+
presenceRule
|
|
5584
|
+
};
|
|
5585
|
+
} else if (rule.matcher.type === "file-relationship") {
|
|
5586
|
+
const frAny = rule.matcher;
|
|
5587
|
+
const frFlags = frAny["flags"] ?? "";
|
|
5588
|
+
const frPatterns = rule.matcher.patterns ?? [];
|
|
5589
|
+
const frAntiPatterns = rule.matcher.antiPatterns ?? [];
|
|
5590
|
+
matcherForExecutor = {
|
|
5591
|
+
type: "file-relationship",
|
|
5592
|
+
fileGlob: rule.matcher.fileGlob,
|
|
5593
|
+
context: {
|
|
5594
|
+
requiresFile: rule.matcher.context?.requiresFile,
|
|
5595
|
+
requiresPattern: rule.matcher.context?.requiresPattern
|
|
5596
|
+
},
|
|
5597
|
+
// Extended fields for self-referential requiresPattern evaluation:
|
|
5598
|
+
patterns: frPatterns,
|
|
5599
|
+
antiPatterns: frAntiPatterns,
|
|
5600
|
+
flags: frFlags
|
|
5601
|
+
};
|
|
5602
|
+
} else {
|
|
5603
|
+
throw new RunProRulesFatalError(
|
|
5604
|
+
`Unreachable: unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}"`
|
|
5605
|
+
);
|
|
5606
|
+
}
|
|
5607
|
+
let requiresRe;
|
|
5608
|
+
let requiresFailClosed;
|
|
5609
|
+
if (rule.matcher.type === "pattern") {
|
|
5610
|
+
const reqPattern = rule.matcher.context?.requiresPattern;
|
|
5611
|
+
if (reqPattern !== void 0) {
|
|
5612
|
+
try {
|
|
5613
|
+
requiresRe = compileCached(reqPattern, 0);
|
|
5614
|
+
} catch (reqErr) {
|
|
5615
|
+
console.error(
|
|
5616
|
+
`[shipguard] requiresPattern compile error for rule ${rule.id}: ${reqErr instanceof Error ? reqErr.message : String(reqErr)} \u2014 fail closed`
|
|
5617
|
+
);
|
|
5618
|
+
requiresFailClosed = reqPattern;
|
|
5619
|
+
}
|
|
5620
|
+
}
|
|
5621
|
+
}
|
|
5622
|
+
const prefilter = rule.matcher.type === "pattern" ? buildPrefilter(rule.matcher.patterns, rule.matcher.flags ?? "") : void 0;
|
|
5623
|
+
return { rule, matcher: matcherForExecutor, requiresRe, requiresFailClosed, prefilter, findings: [] };
|
|
4108
5624
|
}
|
|
4109
5625
|
function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manifest) {
|
|
4110
5626
|
const augmented = rules;
|
|
@@ -4148,10 +5664,25 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
|
|
|
4148
5664
|
|
|
4149
5665
|
export {
|
|
4150
5666
|
goLink,
|
|
5667
|
+
SEVERITY_WEIGHTS,
|
|
5668
|
+
EXIT_CODES,
|
|
5669
|
+
DEFAULT_POLICY_PATH,
|
|
5670
|
+
DEFAULT_REPORT_DIR,
|
|
5671
|
+
DEFAULT_REPORT_FILE,
|
|
5672
|
+
DEFAULT_HISTORY_PATH,
|
|
5673
|
+
HISTORY_PATH_ENV_VAR,
|
|
5674
|
+
DEFAULT_REPO_ID_FALLBACK_PATH,
|
|
5675
|
+
DEFAULT_SCAN_ID_REUSE_WINDOW_MINUTES,
|
|
5676
|
+
SCAN_ID_REUSE_WINDOW_ENV_VAR,
|
|
5677
|
+
logger,
|
|
4151
5678
|
compileDetectorRegex,
|
|
5679
|
+
secretScreenLabel,
|
|
5680
|
+
parseMaskedSecret,
|
|
4152
5681
|
getFindingKey,
|
|
4153
5682
|
redactFindingsEvidence,
|
|
4154
5683
|
looksFakeKey,
|
|
5684
|
+
isTestValue,
|
|
5685
|
+
checkSecretsWithStats,
|
|
4155
5686
|
secretsCheck,
|
|
4156
5687
|
authCheck,
|
|
4157
5688
|
databaseCheck,
|
|
@@ -4160,14 +5691,58 @@ export {
|
|
|
4160
5691
|
assertTrustedApiUrl,
|
|
4161
5692
|
ensureSecureDir,
|
|
4162
5693
|
writeSecureFileSync,
|
|
5694
|
+
PlatformUnavailableError,
|
|
5695
|
+
parseRetryAfterSeconds,
|
|
5696
|
+
isPlatformUnavailable,
|
|
5697
|
+
PRO_RULES_UNAVAILABLE_MESSAGE,
|
|
4163
5698
|
loadCredentials,
|
|
4164
5699
|
saveCredentials,
|
|
4165
5700
|
clearCredentials,
|
|
4166
5701
|
isTokenExpired,
|
|
5702
|
+
RefreshUnavailableError,
|
|
4167
5703
|
getAuthToken,
|
|
5704
|
+
isSafeMode,
|
|
5705
|
+
announceSafeMode,
|
|
5706
|
+
getConfigDir,
|
|
5707
|
+
configFilePath,
|
|
5708
|
+
readInstallId,
|
|
5709
|
+
resetInstallId,
|
|
5710
|
+
writeUserEnabled,
|
|
5711
|
+
noticeShown,
|
|
5712
|
+
readConfigText,
|
|
5713
|
+
writeConfigText,
|
|
5714
|
+
removeConfigFile,
|
|
5715
|
+
listConfigDir,
|
|
5716
|
+
acctFromAccessToken,
|
|
5717
|
+
newNonce,
|
|
5718
|
+
clientHelloHeaders,
|
|
5719
|
+
verifyPlanDocument,
|
|
5720
|
+
mapOfferPayload,
|
|
5721
|
+
hasPaidPlan,
|
|
5722
|
+
unavailableBlock,
|
|
5723
|
+
planBlockFrom,
|
|
5724
|
+
cachedWithReason,
|
|
5725
|
+
readAccountReply,
|
|
5726
|
+
writeAccountCache,
|
|
5727
|
+
clearAccountCache,
|
|
5728
|
+
readAccountCache,
|
|
5729
|
+
cacheMaySkipRulebookCall,
|
|
5730
|
+
decideRulebookUse,
|
|
5731
|
+
fallbackApplies,
|
|
5732
|
+
getProvenance,
|
|
5733
|
+
resolveEndpoint,
|
|
5734
|
+
detectAgent,
|
|
5735
|
+
setGateKind,
|
|
5736
|
+
detectCi,
|
|
5737
|
+
decideTelemetry,
|
|
5738
|
+
telemetryState,
|
|
5739
|
+
sendTelemetry,
|
|
5740
|
+
CLI_VERSION,
|
|
5741
|
+
sendLifecycleEvent,
|
|
4168
5742
|
loadChecksumManifest,
|
|
4169
5743
|
isLineSuppressed,
|
|
4170
5744
|
applySuppressions,
|
|
5745
|
+
applyPolicyIgnores,
|
|
4171
5746
|
NoRulesAppliedError,
|
|
4172
5747
|
ProFetchError,
|
|
4173
5748
|
fetchProRules,
|
|
@@ -4177,3 +5752,4 @@ export {
|
|
|
4177
5752
|
runProRules,
|
|
4178
5753
|
runProRulesWithDispatch
|
|
4179
5754
|
};
|
|
5755
|
+
//# sourceMappingURL=chunk-4J3V4FKA.js.map
|