@agenticcli/shipguard 0.11.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 +29 -17
- package/dist/checksum-manifest.json +5 -5
- package/dist/{chunk-FQY6IANN.js → chunk-4J3V4FKA.js} +2080 -153
- 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 +20 -12
- package/dist/cli.js +10175 -2914
- 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-43JOEAJM.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 +25 -18
- package/rules/free-bundle.json +307 -21
- package/dist/chunk-7NXELBFO.js +0 -904
- package/dist/chunk-NC5RELTG.js +0 -40
- package/dist/config-generator-L7VDUKDY.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
|
}
|
|
@@ -1737,6 +3132,71 @@ function extractJwtRoleClaim(payloadSegment) {
|
|
|
1737
3132
|
return null;
|
|
1738
3133
|
}
|
|
1739
3134
|
}
|
|
3135
|
+
var PUBLISHABLE_PREFIX_RE = compileDetectorRegex(`^(?:pk_(?:live|test)_|sb_publishable_|phc_)[A-Za-z0-9_\\-]+$`);
|
|
3136
|
+
var PLACEHOLDER_VALUE_RE = compileDetectorRegex(
|
|
3137
|
+
// Every alternative is anchored to the WHOLE value (or, for a URL, to the whole password part).
|
|
3138
|
+
`^(?:[a-z]{1,6}[_-]){0,3}x{3,}(?:[_-]x{3,})*$|\\*{3,}|\\.{3}|\u2026|^(?:[a-z0-9]{1,8}[_\\-]){0,3}your[_\\- ].*$|^.*[_\\-]here$|^(?:[a-z0-9]{1,8}[_\\-]){0,3}(?:replace[_\\-]?me|change[_\\-]?me|placeholder|redacted|dummy|todo|tbd|fixme)(?:[_\\-](?:replace[_\\-]?me|change[_\\-]?me|placeholder|redacted|dummy|todo|tbd|fixme))*$|^(?:changeme|secret|password|passw0rd|test|example|none|null|undefined)$|^<[^>]{1,60}>$|^\\{\\{.*\\}\\}$|^\\$\\{.*\\}$|^\\[[a-z0-9_\\- ]+\\]$|^%[a-z0-9_]+%$|:\\/\\/[^\\s:\\/@]*:(?:<[^>@]{1,40}>|\\$\\{[^}@]+\\}|\\{\\{[^}@]+\\}\\}|%[A-Za-z0-9_]+%|your[_\\-]?password|change[_\\-]?me|\\*+|x{3,})@`,
|
|
3139
|
+
"i"
|
|
3140
|
+
);
|
|
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
|
+
}
|
|
3151
|
+
function isPublicKeyValue(value) {
|
|
3152
|
+
const v = value.trim();
|
|
3153
|
+
if (PUBLISHABLE_PREFIX_RE.test(v)) return true;
|
|
3154
|
+
const parts = v.split(".");
|
|
3155
|
+
if (parts.length === 3 && parts[0].startsWith("eyJ") && parts[1].startsWith("eyJ")) {
|
|
3156
|
+
return extractJwtRoleClaim(parts[1]) === "anon";
|
|
3157
|
+
}
|
|
3158
|
+
return false;
|
|
3159
|
+
}
|
|
3160
|
+
function isPlaceholderValue(value) {
|
|
3161
|
+
return PLACEHOLDER_VALUE_RE.test(value);
|
|
3162
|
+
}
|
|
3163
|
+
var FAKE_MARKER_RE = compileDetectorRegex(
|
|
3164
|
+
"example|sample|dummy|fake|not[_\\-]?real|placeholder|replace[_\\-]?me|change[_\\-]?me|your[_\\-]?(?:api|key|secret|token)|test[_\\-]?key|insert[_\\-]?(?:key|here)",
|
|
3165
|
+
"i"
|
|
3166
|
+
);
|
|
3167
|
+
var SEQUENCE_RUNS = [
|
|
3168
|
+
"01234567890123456789",
|
|
3169
|
+
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz",
|
|
3170
|
+
"0123456789abcdef0123456789abcdef",
|
|
3171
|
+
"qwertyuiopasdfghjklzxcvbnm"
|
|
3172
|
+
];
|
|
3173
|
+
function looksFakeKey(value) {
|
|
3174
|
+
const v = value.trim();
|
|
3175
|
+
if (v === "") return false;
|
|
3176
|
+
if (isPlaceholderValue(v) || FAKE_MARKER_RE.test(v)) return true;
|
|
3177
|
+
let body = v;
|
|
3178
|
+
for (; ; ) {
|
|
3179
|
+
const dash = body.indexOf("-");
|
|
3180
|
+
const under = body.indexOf("_");
|
|
3181
|
+
const sep = dash < 0 ? under : under < 0 ? dash : Math.min(dash, under);
|
|
3182
|
+
if (sep < 1 || sep > 10) break;
|
|
3183
|
+
body = body.slice(sep + 1);
|
|
3184
|
+
}
|
|
3185
|
+
if (body.length < 8) return false;
|
|
3186
|
+
if (isPlaceholderValue(body)) return true;
|
|
3187
|
+
if (new Set(body.toLowerCase()).size <= 2) return true;
|
|
3188
|
+
for (let unit = 1; unit <= 10 && unit * 2 <= body.length; unit++) {
|
|
3189
|
+
if (body.length % unit !== 0) continue;
|
|
3190
|
+
const chunk = body.slice(0, unit);
|
|
3191
|
+
if (chunk.repeat(body.length / unit) === body) return true;
|
|
3192
|
+
}
|
|
3193
|
+
const lower = body.toLowerCase();
|
|
3194
|
+
return lower.length >= 10 && SEQUENCE_RUNS.some((run) => run.includes(lower));
|
|
3195
|
+
}
|
|
3196
|
+
function assignedLiteral(rest) {
|
|
3197
|
+
const m = ASSIGNED_LITERAL_RE.exec(rest);
|
|
3198
|
+
return m ? m.groups[0] ?? "" : "";
|
|
3199
|
+
}
|
|
1740
3200
|
function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
|
|
1741
3201
|
const { content, relativePath } = file;
|
|
1742
3202
|
const lines = content.split("\n");
|
|
@@ -1756,22 +3216,88 @@ function checkSupabaseServiceRoleJwt(file, findings, policy, dedupe) {
|
|
|
1756
3216
|
category: "secrets",
|
|
1757
3217
|
file: relativePath,
|
|
1758
3218
|
line: i + 1,
|
|
1759
|
-
evidence:
|
|
3219
|
+
evidence: maskSecret("supabase_service_role_key", m.match),
|
|
1760
3220
|
confidence: "HIGH",
|
|
1761
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.',
|
|
1762
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.",
|
|
1763
3223
|
blocking: policy.block.includes(id)
|
|
1764
3224
|
};
|
|
3225
|
+
stampFindingIdentity(jwtFinding, m.match);
|
|
1765
3226
|
if (!dedupe.fold(findings, i, m.index, m.match, jwtFinding)) findings.push(jwtFinding);
|
|
1766
3227
|
}
|
|
1767
3228
|
}
|
|
1768
3229
|
}
|
|
3230
|
+
var SECRET_KEY_NAME_RE = compileDetectorRegex(
|
|
3231
|
+
`(?:SECRET|PASS|PWD|PRIVATE|TOKEN|API_?KEY|ACCESS_?KEY|SERVICE_?ROLE|CREDENTIAL|DATABASE_URL|DB_URL|CONNECTION_STRING|SALT|SESSION|JWT|COOKIE|SIGNING|WEBHOOK|DSN|AUTH|_KEY$|_PAT$|^KEY$)`,
|
|
3232
|
+
"i"
|
|
3233
|
+
);
|
|
3234
|
+
var STRONG_SECRET_NAME_RE = compileDetectorRegex(`(?:SECRET|PRIVATE|PASSWORD|PASSWD|SERVICE_?ROLE|SIGNING)`, "i");
|
|
3235
|
+
var PUBLIC_PREFIX_KEY_RE = compileDetectorRegex(`^(?:NEXT_PUBLIC|VITE|EXPO_PUBLIC|PUBLIC|REACT_APP|NUXT_PUBLIC|GATSBY)_`);
|
|
3236
|
+
var URL_USERINFO_RE = compileDetectorRegex(`^[a-z][a-z0-9+.\\-]*:\\/\\/([^\\/\\s@?#]*)@`, "i");
|
|
3237
|
+
var PUBLIC_CONFIG_VALUE_RE = compileDetectorRegex(
|
|
3238
|
+
`^(?:true|false|yes|no|on|off|0|1|[0-9]{1,5}|development|production|test|staging|preview|local|debug|info|warn|error|trace|silent|[a-z]{2}-[a-z]+-[0-9]|https?:\\/\\/[^\\s@]+|[a-z0-9][a-z0-9.\\-]*\\.[a-z]{2,}(?::[0-9]{1,5})?(?:\\/[^\\s@]*)?|localhost(?::[0-9]{1,5})?|127\\.0\\.0\\.1(?::[0-9]{1,5})?)$`,
|
|
3239
|
+
"i"
|
|
3240
|
+
);
|
|
3241
|
+
var EXPORT_PREFIX_RE = compileDetectorRegex(`^export\\s+`);
|
|
3242
|
+
var INLINE_COMMENT_RE = compileDetectorRegex(`\\s+#`);
|
|
3243
|
+
function urlHasRealPassword(value) {
|
|
3244
|
+
const m = URL_USERINFO_RE.exec(value);
|
|
3245
|
+
if (!m) return false;
|
|
3246
|
+
const info = m.groups[0] ?? "";
|
|
3247
|
+
const colon = info.indexOf(":");
|
|
3248
|
+
if (colon === -1) return false;
|
|
3249
|
+
const pw = info.slice(colon + 1);
|
|
3250
|
+
if (pw === "") return false;
|
|
3251
|
+
return !isPlaceholderValue(`://u:${pw}@`);
|
|
3252
|
+
}
|
|
3253
|
+
function envFileHasSecret(content) {
|
|
3254
|
+
for (const raw of content.split("\n")) {
|
|
3255
|
+
const line = raw.trim();
|
|
3256
|
+
if (line === "" || line.startsWith("#")) continue;
|
|
3257
|
+
const eq = line.indexOf("=");
|
|
3258
|
+
if (eq <= 0) continue;
|
|
3259
|
+
const key = EXPORT_PREFIX_RE.replace(line.slice(0, eq), "").trim();
|
|
3260
|
+
let value = line.slice(eq + 1).trim();
|
|
3261
|
+
const q = value.charAt(0);
|
|
3262
|
+
if ((q === '"' || q === "'") && value.indexOf(q, 1) > 0) value = value.slice(1, value.indexOf(q, 1));
|
|
3263
|
+
else {
|
|
3264
|
+
const c = INLINE_COMMENT_RE.exec(value);
|
|
3265
|
+
value = (c ? value.slice(0, c.index) : value).trim();
|
|
3266
|
+
}
|
|
3267
|
+
if (value === "") continue;
|
|
3268
|
+
if (URL_USERINFO_RE.test(value)) {
|
|
3269
|
+
if (urlHasRealPassword(value)) return true;
|
|
3270
|
+
continue;
|
|
3271
|
+
}
|
|
3272
|
+
if (isPublicKeyValue(value) || isPlaceholderValue(value)) continue;
|
|
3273
|
+
if (value.includes("hooks.slack.com/") || value.includes("/api/webhooks/")) return true;
|
|
3274
|
+
if (PUBLIC_PREFIX_KEY_RE.test(key) && !STRONG_SECRET_NAME_RE.test(key)) continue;
|
|
3275
|
+
if (!SECRET_KEY_NAME_RE.test(key) && PUBLIC_CONFIG_VALUE_RE.test(value)) continue;
|
|
3276
|
+
return true;
|
|
3277
|
+
}
|
|
3278
|
+
return false;
|
|
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_`);
|
|
1769
3288
|
function checkSecrets(files, policy) {
|
|
3289
|
+
return checkSecretsWithStats(files, policy).findings;
|
|
3290
|
+
}
|
|
3291
|
+
function checkSecretsWithStats(files, policy) {
|
|
1770
3292
|
const findings = [];
|
|
3293
|
+
let ignoredTestValues = 0;
|
|
3294
|
+
const publicIdentifiers = /* @__PURE__ */ new Set();
|
|
1771
3295
|
for (const file of files) {
|
|
1772
3296
|
const { content, relativePath } = file;
|
|
3297
|
+
let envFindingIdx = -1;
|
|
1773
3298
|
if (isDotEnvFile(relativePath)) {
|
|
1774
3299
|
const id = "exposed_env";
|
|
3300
|
+
envFindingIdx = findings.length;
|
|
1775
3301
|
findings.push({
|
|
1776
3302
|
id,
|
|
1777
3303
|
title: ".env file tracked in git",
|
|
@@ -1809,6 +3335,11 @@ function checkSecrets(files, policy) {
|
|
|
1809
3335
|
const line = lines2[i];
|
|
1810
3336
|
const match = NEXT_PUBLIC_SECRET_RE.exec(line);
|
|
1811
3337
|
if (match && match.groups[0]) {
|
|
3338
|
+
if (isPublicKeyValue(assignedLiteral(line.slice(match.index)))) continue;
|
|
3339
|
+
if (isTestValue(match.groups[0])) {
|
|
3340
|
+
ignoredTestValues++;
|
|
3341
|
+
continue;
|
|
3342
|
+
}
|
|
1812
3343
|
const id = "exposed_env";
|
|
1813
3344
|
findings.push({
|
|
1814
3345
|
id,
|
|
@@ -1817,7 +3348,7 @@ function checkSecrets(files, policy) {
|
|
|
1817
3348
|
category: "secrets",
|
|
1818
3349
|
file: relativePath,
|
|
1819
3350
|
line: i + 1,
|
|
1820
|
-
evidence: `${line.split("=")[0].trim()}=${
|
|
3351
|
+
evidence: `${line.split("=")[0].trim()}=${maskSecret("next_public_secret", match.groups[0])}`,
|
|
1821
3352
|
confidence: "HIGH",
|
|
1822
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."),
|
|
1823
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.",
|
|
@@ -1843,6 +3374,17 @@ function checkSecrets(files, policy) {
|
|
|
1843
3374
|
if (pattern.postExcludeFollowedBy(restAfterMatch)) continue;
|
|
1844
3375
|
}
|
|
1845
3376
|
const secretValue = lineMatch.groups[0] ?? lineMatch.match;
|
|
3377
|
+
if (isTestValue(secretValue)) {
|
|
3378
|
+
ignoredTestValues++;
|
|
3379
|
+
continue;
|
|
3380
|
+
}
|
|
3381
|
+
const isAssignMatch = lineMatch.match.includes("=") || lineMatch.match.includes(":");
|
|
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
|
+
}
|
|
1846
3388
|
const secretFinding = {
|
|
1847
3389
|
id: pattern.id,
|
|
1848
3390
|
title: pattern.name,
|
|
@@ -1850,20 +3392,24 @@ function checkSecrets(files, policy) {
|
|
|
1850
3392
|
category: "secrets",
|
|
1851
3393
|
file: relativePath,
|
|
1852
3394
|
line: i + 1,
|
|
1853
|
-
evidence:
|
|
1854
|
-
confidence: pattern.confidence,
|
|
3395
|
+
evidence: maskSecret(pattern.name, secretValue),
|
|
3396
|
+
confidence: looksFakeKey(secretValue) ? "LOW" : pattern.confidence,
|
|
1855
3397
|
explanation: pattern.explanation,
|
|
1856
3398
|
recommendation: pattern.recommendation,
|
|
1857
3399
|
blocking: policy.block.includes(pattern.id)
|
|
1858
3400
|
};
|
|
3401
|
+
stampFindingIdentity(secretFinding, secretValue);
|
|
1859
3402
|
if (!secretDedupe.fold(findings, i, secretStart(lineMatch, secretValue), secretValue, secretFinding)) {
|
|
1860
3403
|
findings.push(secretFinding);
|
|
1861
3404
|
}
|
|
1862
3405
|
}
|
|
1863
3406
|
}
|
|
1864
3407
|
}
|
|
3408
|
+
if (envFindingIdx >= 0 && !envFileHasSecret(content) && !findings.slice(envFindingIdx + 1).some((f) => f.file === relativePath)) {
|
|
3409
|
+
findings.splice(envFindingIdx, 1);
|
|
3410
|
+
}
|
|
1865
3411
|
}
|
|
1866
|
-
return findings;
|
|
3412
|
+
return { findings, ignoredTestValues, publicIdentifiers: publicIdentifiers.size };
|
|
1867
3413
|
}
|
|
1868
3414
|
var secretsCheck = {
|
|
1869
3415
|
id: "secrets",
|
|
@@ -1876,12 +3422,13 @@ var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|ac
|
|
|
1876
3422
|
var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management|debug|internal|env|_debug)(\/|$)/;
|
|
1877
3423
|
var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management|debug|internal|env|_debug|dev)(\/|$)/;
|
|
1878
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;
|
|
1879
3426
|
var RE2_EXPRESS_ROUTE_DEFINITION = compileDetectorRegex(
|
|
1880
3427
|
`(?:router|app)\\.(get|post|put|patch|delete|all)\\s*\\(\\s*['"\`]([^'"\`,)]+)['"\`]`,
|
|
1881
3428
|
"i"
|
|
1882
3429
|
);
|
|
1883
3430
|
var RE2_AUTH_CALL_PATTERN = compileDetectorRegex(
|
|
1884
|
-
`(?:auth|getServerSession|requireAuth|verifyToken|withAuth|clerkMiddleware|authMiddleware)\\s*\\(`
|
|
3431
|
+
`(?:auth|getAuth|getServerSession|getSession|getUser|getClaims|currentUser|requireAuth|requireUser|requireSession|requireAdmin|verifyToken|verifyAuth|withAuth|validateRequest|clerkMiddleware|authMiddleware)\\s*\\(`
|
|
1885
3432
|
);
|
|
1886
3433
|
var RE2_COMMENTED_AUTH_PATTERN = compileDetectorRegex(
|
|
1887
3434
|
`^\\s*(?:\\/\\/|\\/\\*|\\*)[^\\n]*(?:auth|getServerSession|requireAuth|verifyToken)\\s*\\(`,
|
|
@@ -1894,11 +3441,96 @@ var RE2_EXPRESS_AUTH_MIDDLEWARE_PATTERN = compileDetectorRegex(
|
|
|
1894
3441
|
var RE2_MIDDLEWARE_ADMIN_COVERAGE = compileDetectorRegex(
|
|
1895
3442
|
`(?:admin|dashboard|billing|account|management)`
|
|
1896
3443
|
);
|
|
3444
|
+
var RE2_SENSITIVE_PREFIX = compileDetectorRegex(
|
|
3445
|
+
`(?:admin|dashboard|billing|account|management|settings)`
|
|
3446
|
+
);
|
|
3447
|
+
function stripComments(src) {
|
|
3448
|
+
let out = "";
|
|
3449
|
+
let i = 0;
|
|
3450
|
+
while (i < src.length) {
|
|
3451
|
+
const c = src[i];
|
|
3452
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
3453
|
+
let j = i + 1;
|
|
3454
|
+
while (j < src.length && src[j] !== c) j += src[j] === "\\" ? 2 : 1;
|
|
3455
|
+
out += src.slice(i, j + 1);
|
|
3456
|
+
i = j + 1;
|
|
3457
|
+
} else if (c === "/" && src[i + 1] === "/") {
|
|
3458
|
+
while (i < src.length && src[i] !== "\n") i++;
|
|
3459
|
+
} else if (c === "/" && src[i + 1] === "*") {
|
|
3460
|
+
const end = src.indexOf("*/", i + 2);
|
|
3461
|
+
i = end === -1 ? src.length : end + 2;
|
|
3462
|
+
out += " ";
|
|
3463
|
+
} else {
|
|
3464
|
+
out += c;
|
|
3465
|
+
i++;
|
|
3466
|
+
}
|
|
3467
|
+
}
|
|
3468
|
+
return out;
|
|
3469
|
+
}
|
|
3470
|
+
function matcherLiterals(code) {
|
|
3471
|
+
const key = code.indexOf("matcher");
|
|
3472
|
+
if (key === -1) return [];
|
|
3473
|
+
let i = code.indexOf(":", key);
|
|
3474
|
+
if (i === -1) return [];
|
|
3475
|
+
i++;
|
|
3476
|
+
while (i < code.length && " \r\n".includes(code[i])) i++;
|
|
3477
|
+
const lits = [];
|
|
3478
|
+
let depth = 0;
|
|
3479
|
+
for (; i < code.length; i++) {
|
|
3480
|
+
const c = code[i];
|
|
3481
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
3482
|
+
let j = i + 1;
|
|
3483
|
+
while (j < code.length && code[j] !== c) j += code[j] === "\\" ? 2 : 1;
|
|
3484
|
+
lits.push(code.slice(i + 1, j));
|
|
3485
|
+
i = j;
|
|
3486
|
+
if (depth === 0) break;
|
|
3487
|
+
} else if (c === "[") depth++;
|
|
3488
|
+
else if (c === "]") {
|
|
3489
|
+
depth--;
|
|
3490
|
+
if (depth <= 0) break;
|
|
3491
|
+
} else if (depth === 0) break;
|
|
3492
|
+
}
|
|
3493
|
+
return lits;
|
|
3494
|
+
}
|
|
3495
|
+
function isSafeCatchAll(lit) {
|
|
3496
|
+
const start = lit.indexOf("(?!");
|
|
3497
|
+
if (start === -1 || !lit.startsWith("/(")) return false;
|
|
3498
|
+
let depth = 0;
|
|
3499
|
+
let end = -1;
|
|
3500
|
+
for (let i = start; i < lit.length; i++) {
|
|
3501
|
+
if (lit[i] === "\\") i++;
|
|
3502
|
+
else if (lit[i] === "(") depth++;
|
|
3503
|
+
else if (lit[i] === ")" && --depth === 0) {
|
|
3504
|
+
end = i;
|
|
3505
|
+
break;
|
|
3506
|
+
}
|
|
3507
|
+
}
|
|
3508
|
+
if (end === -1) return false;
|
|
3509
|
+
const rest = lit.slice(end + 1);
|
|
3510
|
+
if (rest !== ".*)" && rest !== ".*") return false;
|
|
3511
|
+
return !RE2_SENSITIVE_PREFIX.test(lit.slice(start, end + 1));
|
|
3512
|
+
}
|
|
3513
|
+
function middlewareCoversRoutes(content) {
|
|
3514
|
+
const code = stripComments(content);
|
|
3515
|
+
let words = "";
|
|
3516
|
+
for (let i = 0; i < code.length; i++) {
|
|
3517
|
+
if (code.startsWith("(?!", i)) {
|
|
3518
|
+
let depth = 0;
|
|
3519
|
+
for (; i < code.length; i++) {
|
|
3520
|
+
if (code[i] === "\\") i++;
|
|
3521
|
+
else if (code[i] === "(") depth++;
|
|
3522
|
+
else if (code[i] === ")" && --depth === 0) break;
|
|
3523
|
+
}
|
|
3524
|
+
} else words += code[i];
|
|
3525
|
+
}
|
|
3526
|
+
if (RE2_MIDDLEWARE_ADMIN_COVERAGE.test(words)) return true;
|
|
3527
|
+
return matcherLiterals(code).some(isSafeCatchAll);
|
|
3528
|
+
}
|
|
1897
3529
|
var RE2_INLINE_AUTH_CHECK = compileDetectorRegex(
|
|
1898
3530
|
`requireAuth|verifyToken|isAuth|isLogged|passport\\.authenticate`,
|
|
1899
3531
|
"i"
|
|
1900
3532
|
);
|
|
1901
|
-
var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?middleware\.[tj]s$/;
|
|
3533
|
+
var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?(?:middleware|proxy)\.[tj]s$/;
|
|
1902
3534
|
var NEXT_APP_ROUTER_PATH = /^(?:src\/)?(?:app\/|app$)/;
|
|
1903
3535
|
var NEXT_CONFIG_FILE = /^(?:src\/)?next\.config\.[cm]?[jt]s$/;
|
|
1904
3536
|
function isNextjsProject(files) {
|
|
@@ -2209,6 +3841,162 @@ function hasActiveAuthCall(content) {
|
|
|
2209
3841
|
const execText = extractExecutableText(content);
|
|
2210
3842
|
return RE2_AUTH_CALL_PATTERN.test(execText);
|
|
2211
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
|
+
}
|
|
3854
|
+
var PAGE_FILE_PATTERN = /(?:^|\/)page\.[tj]sx?$/;
|
|
3855
|
+
function isPageFile(rp) {
|
|
3856
|
+
return PAGE_FILE_PATTERN.test(rp);
|
|
3857
|
+
}
|
|
3858
|
+
function layoutChain(pagePath, byPath) {
|
|
3859
|
+
const segs = pagePath.split("/").slice(0, -1);
|
|
3860
|
+
const start = segs.findIndex((x) => RE2_SENSITIVE_SEGMENT.test(x));
|
|
3861
|
+
const out = [];
|
|
3862
|
+
if (start === -1) return out;
|
|
3863
|
+
for (let n = start + 1; n <= segs.length; n++) {
|
|
3864
|
+
const dir = segs.slice(0, n).join("/");
|
|
3865
|
+
for (const ext of ["tsx", "ts", "jsx", "js"]) {
|
|
3866
|
+
const f = byPath.get(`${dir}/layout.${ext}`);
|
|
3867
|
+
if (f) out.push(f);
|
|
3868
|
+
}
|
|
3869
|
+
}
|
|
3870
|
+
return out;
|
|
3871
|
+
}
|
|
3872
|
+
var RE2_SENSITIVE_SEGMENT = compileDetectorRegex(`^(?:admin|dashboard|billing|account|settings|management|debug|internal)$`);
|
|
3873
|
+
var RE2_ENFORCING_CALL = compileDetectorRegex(
|
|
3874
|
+
`\\b(?:require(?:Auth|User|Session|Admin|Login)\\w*|assertAuth\\w*|ensureAuth\\w*|withAuth\\w*|verifyToken|clerkMiddleware|authMiddleware)\\s*\\(|\\bauth\\.protect\\s*\\(`
|
|
3875
|
+
);
|
|
3876
|
+
var RE2_SESSION_FETCH = compileDetectorRegex(
|
|
3877
|
+
`\\b(?:auth|getAuth|getUser|getSession|getClaims|currentUser|validateRequest|getCurrentUser)\\s*\\(\\s*(?:supabase|client|sb|req|request|ctx|context)?\\s*\\)|\\bgetServerSession\\s*\\(|\\buse(?:Session|User|Auth)\\s*\\(`
|
|
3878
|
+
);
|
|
3879
|
+
var RE2_GUARD_ACTION = compileDetectorRegex(
|
|
3880
|
+
`^\\s*(?:\\{\\s*)?(?:return\\s+)?(?:(?:redirect|permanentRedirect|notFound|unauthorized|forbidden)\\s*\\(|throw\\b|null\\b|<|router\\.(?:push|replace)\\s*\\()`
|
|
3881
|
+
);
|
|
3882
|
+
var RE2_IF_OPEN = compileDetectorRegex(`\\bif\\s*\\(`);
|
|
3883
|
+
var RE2_INLINE_GUARD = compileDetectorRegex(`^[^\\n;]{0,60}(?:\\|\\||\\?\\?)\\s*(?:redirect|notFound|unauthorized|forbidden)\\s*\\(`);
|
|
3884
|
+
var RE2_ASSIGN_TARGET = compileDetectorRegex(`^(?:const|let|var)\\s+([^=;]{1,120}?)\\s*=`);
|
|
3885
|
+
var RE2_IDENT = compileDetectorRegex(`[A-Za-z_$][\\w$]*`);
|
|
3886
|
+
var RE2_DEFAULT_FN = compileDetectorRegex(`export\\s+default\\s+(?:async\\s+)?function\\s*(\\w*)\\s*\\(`);
|
|
3887
|
+
var RE2_DEFAULT_REF = compileDetectorRegex(`export\\s+default\\s+(\\w+)\\s*;?\\s*$`, "m");
|
|
3888
|
+
var RE2_CALL_NAME = compileDetectorRegex(`\\b([A-Za-z_]\\w*)\\s*\\(`);
|
|
3889
|
+
function braceBody(code, from) {
|
|
3890
|
+
const open = code.indexOf("{", from);
|
|
3891
|
+
if (open === -1) return "";
|
|
3892
|
+
let depth = 0;
|
|
3893
|
+
for (let i = open; i < code.length; i++) {
|
|
3894
|
+
if (code[i] === "{") depth++;
|
|
3895
|
+
else if (code[i] === "}" && --depth === 0) return code.slice(open, i + 1);
|
|
3896
|
+
}
|
|
3897
|
+
return "";
|
|
3898
|
+
}
|
|
3899
|
+
function afterParens(code, open) {
|
|
3900
|
+
let depth = 0;
|
|
3901
|
+
for (let i = open; i < code.length; i++) {
|
|
3902
|
+
if (code[i] === "(") depth++;
|
|
3903
|
+
else if (code[i] === ")" && --depth === 0) return i + 1;
|
|
3904
|
+
}
|
|
3905
|
+
return open;
|
|
3906
|
+
}
|
|
3907
|
+
function functionBody(code, name) {
|
|
3908
|
+
const fn = compileDetectorRegex(`(?:function\\s+${name}\\s*\\(|(?:const|let)\\s+${name}\\s*=\\s*(?:async\\s*)?(?:function\\s*)?\\()`).exec(code);
|
|
3909
|
+
if (!fn) return "";
|
|
3910
|
+
const paren = code.indexOf("(", fn.index + fn.match.length - 1);
|
|
3911
|
+
return braceBody(code, afterParens(code, paren));
|
|
3912
|
+
}
|
|
3913
|
+
function componentText(code) {
|
|
3914
|
+
let body = "";
|
|
3915
|
+
const decl = RE2_DEFAULT_FN.exec(code);
|
|
3916
|
+
if (decl) {
|
|
3917
|
+
body = braceBody(code, afterParens(code, decl.index + decl.match.length - 1));
|
|
3918
|
+
} else {
|
|
3919
|
+
const ref = RE2_DEFAULT_REF.exec(code);
|
|
3920
|
+
if (ref) body = functionBody(code, ref.groups[0] ?? "") || "";
|
|
3921
|
+
}
|
|
3922
|
+
if (body === "") return code;
|
|
3923
|
+
let extra = "";
|
|
3924
|
+
for (const m of RE2_CALL_NAME.matchAll(body)) {
|
|
3925
|
+
const name = m.groups[0] ?? "";
|
|
3926
|
+
if (name === "if" || name === "function" || name === "") continue;
|
|
3927
|
+
extra += functionBody(code, name);
|
|
3928
|
+
}
|
|
3929
|
+
return body + "\n" + extra;
|
|
3930
|
+
}
|
|
3931
|
+
function assignedNames(text, fetchIdx) {
|
|
3932
|
+
const before = text.slice(Math.max(0, fetchIdx - 300), fetchIdx);
|
|
3933
|
+
const kw = Math.max(before.lastIndexOf("const "), before.lastIndexOf("let "), before.lastIndexOf("var "));
|
|
3934
|
+
if (kw === -1 || before.slice(kw).includes(";")) return [];
|
|
3935
|
+
const m = RE2_ASSIGN_TARGET.exec(before.slice(kw));
|
|
3936
|
+
if (!m) return [];
|
|
3937
|
+
const names = [];
|
|
3938
|
+
const lhs = m.groups[0] ?? "";
|
|
3939
|
+
for (const id of RE2_IDENT.matchAll(lhs)) {
|
|
3940
|
+
let k = id.index + id.match.length;
|
|
3941
|
+
while (k < lhs.length && (lhs[k] === " " || lhs[k] === " " || lhs[k] === "\n" || lhs[k] === "\r")) k++;
|
|
3942
|
+
if (lhs[k] === ":") continue;
|
|
3943
|
+
names.push(id.match);
|
|
3944
|
+
}
|
|
3945
|
+
return names;
|
|
3946
|
+
}
|
|
3947
|
+
function trimLead(t) {
|
|
3948
|
+
let k = 0;
|
|
3949
|
+
while (k < t.length && (t[k] === " " || t[k] === " " || t[k] === "\n" || t[k] === "\r" || t[k] === ")")) k++;
|
|
3950
|
+
return t.slice(k);
|
|
3951
|
+
}
|
|
3952
|
+
function firstLines(text, n) {
|
|
3953
|
+
let end = 0;
|
|
3954
|
+
for (let k = 0; k < n; k++) {
|
|
3955
|
+
const nl = text.indexOf("\n", end);
|
|
3956
|
+
if (nl === -1) return text;
|
|
3957
|
+
end = nl + 1;
|
|
3958
|
+
}
|
|
3959
|
+
return text.slice(0, end);
|
|
3960
|
+
}
|
|
3961
|
+
function testsVariableThenTurnsAway(win, names) {
|
|
3962
|
+
for (const open of RE2_IF_OPEN.matchAll(win)) {
|
|
3963
|
+
let depth = 0;
|
|
3964
|
+
let close = -1;
|
|
3965
|
+
for (let k = open.index + open.match.length - 1; k < win.length && k < open.index + 200; k++) {
|
|
3966
|
+
if (win[k] === "(") depth++;
|
|
3967
|
+
else if (win[k] === ")" && --depth === 0) {
|
|
3968
|
+
close = k;
|
|
3969
|
+
break;
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
if (close === -1) continue;
|
|
3973
|
+
const cond = win.slice(open.index + open.match.length, close);
|
|
3974
|
+
const condIds = /* @__PURE__ */ new Set();
|
|
3975
|
+
for (const id of RE2_IDENT.matchAll(cond)) condIds.add(id.match);
|
|
3976
|
+
const namesIt = names.some((nm) => condIds.has(nm));
|
|
3977
|
+
const tests = cond.includes("!") || cond.includes("==");
|
|
3978
|
+
if (namesIt && tests && RE2_GUARD_ACTION.test(win.slice(close + 1))) return true;
|
|
3979
|
+
}
|
|
3980
|
+
for (const nm of names) {
|
|
3981
|
+
const tail = win.split(nm);
|
|
3982
|
+
for (let k = 1; k < tail.length; k++) if (RE2_INLINE_GUARD.test(tail[k])) return true;
|
|
3983
|
+
}
|
|
3984
|
+
return false;
|
|
3985
|
+
}
|
|
3986
|
+
function gatesAccess(src) {
|
|
3987
|
+
const text = componentText(extractExecutableText(src));
|
|
3988
|
+
if (RE2_ENFORCING_CALL.test(text)) return true;
|
|
3989
|
+
for (const m of RE2_SESSION_FETCH.matchAll(text)) {
|
|
3990
|
+
const end = m.index + m.match.length;
|
|
3991
|
+
const lineStart = text.lastIndexOf("\n", m.index) + 1;
|
|
3992
|
+
const prefix = text.slice(lineStart, m.index);
|
|
3993
|
+
if (RE2_IF_OPEN.test(prefix) && RE2_GUARD_ACTION.test(trimLead(text.slice(text.indexOf(")", end) + 1)))) return true;
|
|
3994
|
+
if (RE2_INLINE_GUARD.test(text.slice(end))) return true;
|
|
3995
|
+
const names = assignedNames(text, m.index);
|
|
3996
|
+
if (names.length > 0 && testsVariableThenTurnsAway(firstLines(text.slice(end), 7), names)) return true;
|
|
3997
|
+
}
|
|
3998
|
+
return false;
|
|
3999
|
+
}
|
|
2212
4000
|
function hasCommentedAuthCall(content) {
|
|
2213
4001
|
return RE2_COMMENTED_AUTH_PATTERN.test(content);
|
|
2214
4002
|
}
|
|
@@ -2236,19 +4024,7 @@ var authCheck = {
|
|
|
2236
4024
|
const findings = [];
|
|
2237
4025
|
const middlewareFile = files.find((f) => MIDDLEWARE_FILE_PATTERN.test(f.relativePath));
|
|
2238
4026
|
if (isNextjsProject(files)) {
|
|
2239
|
-
if (!middlewareFile) {
|
|
2240
|
-
findings.push({
|
|
2241
|
-
id: "public_admin_route",
|
|
2242
|
-
title: "No Next.js middleware.ts found",
|
|
2243
|
-
severity: "high",
|
|
2244
|
-
category: "auth",
|
|
2245
|
-
file: "middleware.ts",
|
|
2246
|
-
confidence: "MEDIUM",
|
|
2247
|
-
explanation: "No middleware.ts file was found. Next.js App Router relies on middleware to enforce route-level auth for admin, dashboard, and billing routes. Without it, protection depends entirely on individual Server Components and Route Handlers, which is error-prone.",
|
|
2248
|
-
recommendation: "Create middleware.ts at the project root (or src/middleware.ts) and add a matcher that covers /admin, /dashboard, and /billing. Use auth() from next-auth/auth.js or clerkMiddleware() to redirect unauthenticated requests.",
|
|
2249
|
-
blocking: policy.block.includes("public_admin_route")
|
|
2250
|
-
});
|
|
2251
|
-
} else if (!RE2_MIDDLEWARE_ADMIN_COVERAGE.test(middlewareFile.content)) {
|
|
4027
|
+
if (middlewareFile && !middlewareCoversRoutes(middlewareFile.content)) {
|
|
2252
4028
|
findings.push({
|
|
2253
4029
|
id: "public_admin_route",
|
|
2254
4030
|
title: "middleware.ts does not cover admin/dashboard routes",
|
|
@@ -2262,13 +4038,18 @@ var authCheck = {
|
|
|
2262
4038
|
});
|
|
2263
4039
|
}
|
|
2264
4040
|
}
|
|
4041
|
+
const filesByPath = new Map(files.map((f) => [f.relativePath, f]));
|
|
2265
4042
|
for (const file of files) {
|
|
2266
4043
|
const { relativePath: rp, content } = file;
|
|
2267
4044
|
if (WEBHOOK_PATH_PATTERN.test(rp)) {
|
|
2268
4045
|
continue;
|
|
2269
4046
|
}
|
|
4047
|
+
if (PUBLIC_AUTH_PATH_PATTERN.test(rp) && (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp) || SENSITIVE_API_ROUTE_PATTERN.test(rp))) {
|
|
4048
|
+
continue;
|
|
4049
|
+
}
|
|
2270
4050
|
if (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp)) {
|
|
2271
|
-
if (!
|
|
4051
|
+
if (!isPageFile(rp)) continue;
|
|
4052
|
+
if (!gatesAccess(content) && !layoutChain(rp, filesByPath).some((l) => gatesAccess(l.content))) {
|
|
2272
4053
|
const wasRemoved = hasCommentedAuthCall(content);
|
|
2273
4054
|
findings.push({
|
|
2274
4055
|
id: "public_admin_route",
|
|
@@ -2285,7 +4066,7 @@ var authCheck = {
|
|
|
2285
4066
|
continue;
|
|
2286
4067
|
}
|
|
2287
4068
|
if (SENSITIVE_API_ROUTE_PATTERN.test(rp)) {
|
|
2288
|
-
if (!hasActiveAuthCall(content)) {
|
|
4069
|
+
if (!hasActiveAuthCall(content) && !hasInlineCredentialGate(content)) {
|
|
2289
4070
|
const wasRemoved = hasCommentedAuthCall(content);
|
|
2290
4071
|
findings.push({
|
|
2291
4072
|
id: "auth_route_without_guard",
|
|
@@ -3038,15 +4819,17 @@ var deploymentCheck = {
|
|
|
3038
4819
|
};
|
|
3039
4820
|
|
|
3040
4821
|
// src/checks/payments.ts
|
|
3041
|
-
function isStripeWebhookRoute(relativePath) {
|
|
4822
|
+
function isStripeWebhookRoute(relativePath, content) {
|
|
3042
4823
|
const p = relativePath.toLowerCase();
|
|
3043
4824
|
if (!p.includes("api/") && !p.includes("api\\")) return false;
|
|
4825
|
+
if (p.includes("razorpay") && RE_RAZORPAY_WORD.test(content) && !RE_STRIPE_WORD.test(content)) return false;
|
|
3044
4826
|
return p.includes("webhook") || p.includes("stripe");
|
|
3045
4827
|
}
|
|
3046
|
-
function isRazorpayWebhookRoute(relativePath) {
|
|
4828
|
+
function isRazorpayWebhookRoute(relativePath, content) {
|
|
3047
4829
|
const p = relativePath.toLowerCase();
|
|
3048
4830
|
if (!p.includes("api/") && !p.includes("api\\")) return false;
|
|
3049
|
-
|
|
4831
|
+
if (!p.includes("razorpay")) return false;
|
|
4832
|
+
return RE_RAZORPAY_WORD.test(content) || !RE_STRIPE_WORD.test(content);
|
|
3050
4833
|
}
|
|
3051
4834
|
function isPaymentRoute(relativePath) {
|
|
3052
4835
|
const p = relativePath.toLowerCase();
|
|
@@ -3059,6 +4842,8 @@ function isClientSideFile(relativePath) {
|
|
|
3059
4842
|
return p.startsWith("app/") || p.startsWith("pages/") || p.startsWith("components/");
|
|
3060
4843
|
}
|
|
3061
4844
|
var RE_STRIPE_CONSTRUCT_EVENT = compileDetectorRegex("stripe\\.webhooks\\.constructEvent", "i");
|
|
4845
|
+
var RE_STRIPE_WORD = compileDetectorRegex("stripe", "i");
|
|
4846
|
+
var RE_RAZORPAY_WORD = compileDetectorRegex("razorpay", "i");
|
|
3062
4847
|
var RE_STRIPE_SIGNATURE = compileDetectorRegex("stripe-signature", "i");
|
|
3063
4848
|
var RE_RAZORPAY_VALIDATE = compileDetectorRegex("validateWebhookSignature", "i");
|
|
3064
4849
|
var RE_IDEMPOTENCY_WORD = compileDetectorRegex("idempoten(?:cy|t)", "i");
|
|
@@ -3094,39 +4879,26 @@ var payments = {
|
|
|
3094
4879
|
const findings = [];
|
|
3095
4880
|
for (const file of files) {
|
|
3096
4881
|
const { relativePath, content } = file;
|
|
3097
|
-
if (isStripeWebhookRoute(relativePath)) {
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
id,
|
|
3102
|
-
title: "Stripe webhook missing signature verification",
|
|
3103
|
-
severity: "critical",
|
|
3104
|
-
category: "payments",
|
|
3105
|
-
file: relativePath,
|
|
3106
|
-
evidence: "No call to stripe.webhooks.constructEvent() found",
|
|
3107
|
-
confidence: "MEDIUM",
|
|
3108
|
-
explanation: "Without calling stripe.webhooks.constructEvent(), the webhook endpoint cannot verify that requests originate from Stripe. Attackers can send forged events to trigger payment logic (e.g., fake payment_intent.succeeded) without making a real payment.",
|
|
3109
|
-
recommendation: "Verify every incoming webhook with stripe.webhooks.constructEvent(rawBody, sig, webhookSecret). Pass the raw request body \u2014 not a parsed JSON object \u2014 to prevent HMAC mismatch.",
|
|
3110
|
-
blocking: isBlocking(id, policy)
|
|
3111
|
-
});
|
|
3112
|
-
}
|
|
3113
|
-
if (!hasStripeSignatureHeader(content)) {
|
|
4882
|
+
if (isStripeWebhookRoute(relativePath, content)) {
|
|
4883
|
+
const noConstructEvent = !hasStripeConstructEvent(content);
|
|
4884
|
+
const noSignatureHeader = !hasStripeSignatureHeader(content);
|
|
4885
|
+
if (noConstructEvent || noSignatureHeader) {
|
|
3114
4886
|
const id = "payment_webhook_without_signature_check";
|
|
3115
4887
|
findings.push({
|
|
3116
4888
|
id,
|
|
3117
|
-
title: "Stripe webhook does not read stripe-signature header",
|
|
4889
|
+
title: noConstructEvent ? "Stripe webhook missing signature verification" : "Stripe webhook does not read stripe-signature header",
|
|
3118
4890
|
severity: "critical",
|
|
3119
4891
|
category: "payments",
|
|
3120
4892
|
file: relativePath,
|
|
3121
|
-
evidence: "No reference to stripe-signature header found",
|
|
4893
|
+
evidence: noConstructEvent && noSignatureHeader ? "No call to stripe.webhooks.constructEvent() and no reference to the stripe-signature header found" : noConstructEvent ? "No call to stripe.webhooks.constructEvent() found" : "No reference to stripe-signature header found",
|
|
3122
4894
|
confidence: "MEDIUM",
|
|
3123
|
-
explanation: "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
|
|
3124
|
-
recommendation: 'Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express)
|
|
4895
|
+
explanation: noConstructEvent ? "Without calling stripe.webhooks.constructEvent(), the webhook endpoint cannot verify that requests originate from Stripe. Attackers can send forged events to trigger payment logic (e.g., fake payment_intent.succeeded) without making a real payment." + (noSignatureHeader ? " The stripe-signature header, which carries the proof, is not read either." : "") : "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
|
|
4896
|
+
recommendation: 'Verify every incoming webhook with stripe.webhooks.constructEvent(rawBody, sig, webhookSecret). Pass the raw request body, not a parsed JSON object, to prevent HMAC mismatch. Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) first.',
|
|
3125
4897
|
blocking: isBlocking(id, policy)
|
|
3126
4898
|
});
|
|
3127
4899
|
}
|
|
3128
4900
|
}
|
|
3129
|
-
if (isRazorpayWebhookRoute(relativePath)) {
|
|
4901
|
+
if (isRazorpayWebhookRoute(relativePath, content)) {
|
|
3130
4902
|
if (!hasRazorpayValidateWebhook(content)) {
|
|
3131
4903
|
const id = "payment_webhook_without_signature_check";
|
|
3132
4904
|
findings.push({
|
|
@@ -3177,19 +4949,20 @@ var payments = {
|
|
|
3177
4949
|
});
|
|
3178
4950
|
}
|
|
3179
4951
|
}
|
|
3180
|
-
if (isStripeWebhookRoute(relativePath) || isRazorpayWebhookRoute(relativePath)) {
|
|
4952
|
+
if (isStripeWebhookRoute(relativePath, content) || isRazorpayWebhookRoute(relativePath, content)) {
|
|
3181
4953
|
if (!hasIdempotencyHandling(content)) {
|
|
3182
4954
|
const id = "missing_idempotency";
|
|
3183
4955
|
findings.push({
|
|
3184
4956
|
id,
|
|
3185
|
-
title: "
|
|
3186
|
-
|
|
4957
|
+
title: "No idempotency (duplicate-delivery) check found in webhook handler",
|
|
4958
|
+
// Robustness, not a security hole: a duplicate delivery repeats an action, it does not open access.
|
|
4959
|
+
severity: "low",
|
|
3187
4960
|
category: "payments",
|
|
3188
4961
|
file: relativePath,
|
|
3189
|
-
evidence: "No idempotency key, event.id check, or duplicate-detection logic found",
|
|
4962
|
+
evidence: "No idempotency key, event.id check, or duplicate-detection logic found in this file",
|
|
3190
4963
|
confidence: "LOW",
|
|
3191
|
-
explanation: "Payment providers
|
|
3192
|
-
recommendation: "
|
|
4964
|
+
explanation: "Payment providers can send the same webhook event more than once (for example after a timeout). This file has no sign of a check for events it has already handled, so a repeat could run the same action twice, such as a second order fulfilment or refund. If you handle repeats elsewhere (a shared helper or the database), this finding can be ignored.",
|
|
4965
|
+
recommendation: "Store each processed event.id before acting on the event. If the ID is already stored, return 200 right away without running the action again.",
|
|
3193
4966
|
blocking: isBlocking(id, policy)
|
|
3194
4967
|
});
|
|
3195
4968
|
}
|
|
@@ -3218,9 +4991,9 @@ var payments = {
|
|
|
3218
4991
|
|
|
3219
4992
|
// src/core/coderef-dispatch.ts
|
|
3220
4993
|
import { createRequire } from "module";
|
|
3221
|
-
import { readFileSync as
|
|
4994
|
+
import { readFileSync as readFileSync5, existsSync as existsSync4 } from "fs";
|
|
3222
4995
|
import { fileURLToPath } from "url";
|
|
3223
|
-
import { dirname as dirname3, join as
|
|
4996
|
+
import { dirname as dirname3, join as join6 } from "path";
|
|
3224
4997
|
var DEFAULT_DISPATCH_TABLE = {
|
|
3225
4998
|
"secrets:secretsCheck": secretsCheck,
|
|
3226
4999
|
"auth:authCheck": authCheck,
|
|
@@ -3239,7 +5012,7 @@ function semverLt(a, b) {
|
|
|
3239
5012
|
if (aMin !== bMin) return aMin < bMin;
|
|
3240
5013
|
return aPatch < bPatch;
|
|
3241
5014
|
}
|
|
3242
|
-
function runCoderefRules(rules, files, policy, cliVersion =
|
|
5015
|
+
function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION2, table = DEFAULT_DISPATCH_TABLE, manifest) {
|
|
3243
5016
|
const findings = [];
|
|
3244
5017
|
let degraded = false;
|
|
3245
5018
|
const warnings = [];
|
|
@@ -3292,21 +5065,21 @@ function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION, table =
|
|
|
3292
5065
|
return { findings, degraded, warnings };
|
|
3293
5066
|
}
|
|
3294
5067
|
var _require = createRequire(import.meta.url);
|
|
3295
|
-
var _pkgPath =
|
|
3296
|
-
var
|
|
5068
|
+
var _pkgPath = join6(dirname3(fileURLToPath(import.meta.url)), "../../package.json");
|
|
5069
|
+
var CLI_VERSION2;
|
|
3297
5070
|
try {
|
|
3298
5071
|
const pkg = _require(_pkgPath);
|
|
3299
|
-
|
|
5072
|
+
CLI_VERSION2 = typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
3300
5073
|
} catch {
|
|
3301
|
-
|
|
5074
|
+
CLI_VERSION2 = "0.0.0";
|
|
3302
5075
|
}
|
|
3303
|
-
var _manifestPath =
|
|
5076
|
+
var _manifestPath = join6(dirname3(fileURLToPath(import.meta.url)), "../../checksum-manifest.json");
|
|
3304
5077
|
function loadChecksumManifest() {
|
|
3305
|
-
if (!
|
|
5078
|
+
if (!existsSync4(_manifestPath)) {
|
|
3306
5079
|
return void 0;
|
|
3307
5080
|
}
|
|
3308
5081
|
try {
|
|
3309
|
-
const raw =
|
|
5082
|
+
const raw = readFileSync5(_manifestPath, "utf-8");
|
|
3310
5083
|
const parsed = JSON.parse(raw);
|
|
3311
5084
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
3312
5085
|
console.warn("[shipguard] checksum-manifest.json is not a valid object \u2014 skipping checksum verification");
|
|
@@ -3362,6 +5135,19 @@ function applySuppressions(findings, files) {
|
|
|
3362
5135
|
}
|
|
3363
5136
|
return findings;
|
|
3364
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
|
+
}
|
|
3365
5151
|
|
|
3366
5152
|
// src/core/re2js-compile-cache.ts
|
|
3367
5153
|
import { RE2JS as RE2JS2 } from "re2js";
|
|
@@ -3404,11 +5190,14 @@ var ProFetchError = class extends Error {
|
|
|
3404
5190
|
code;
|
|
3405
5191
|
/** Only populated for RATE_LIMITED and PLATFORM_UNAVAILABLE, when the server sends a usable `Retry-After` header. */
|
|
3406
5192
|
retryAfterSeconds;
|
|
5193
|
+
/** 0.13 plan data that came with the failure (the 402 refusals carry a signed account document). */
|
|
5194
|
+
context;
|
|
3407
5195
|
constructor(code, message, opts) {
|
|
3408
5196
|
super(message);
|
|
3409
5197
|
this.name = "ProFetchError";
|
|
3410
5198
|
this.code = code;
|
|
3411
5199
|
this.retryAfterSeconds = opts?.retryAfterSeconds;
|
|
5200
|
+
this.context = opts?.context;
|
|
3412
5201
|
}
|
|
3413
5202
|
};
|
|
3414
5203
|
function parseCreditsRemaining(headers) {
|
|
@@ -3417,6 +5206,7 @@ function parseCreditsRemaining(headers) {
|
|
|
3417
5206
|
const credits = Number(raw.trim());
|
|
3418
5207
|
return Number.isFinite(credits) ? credits : void 0;
|
|
3419
5208
|
}
|
|
5209
|
+
var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
3420
5210
|
async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath) {
|
|
3421
5211
|
assertTrustedApiUrl(apiUrl);
|
|
3422
5212
|
let token;
|
|
@@ -3432,6 +5222,8 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3432
5222
|
throw err;
|
|
3433
5223
|
}
|
|
3434
5224
|
if (!token) throw new ProFetchError("AUTH_FAILED", "Not authenticated. Run `shipguard login` first.");
|
|
5225
|
+
const acct = acctFromAccessToken(token);
|
|
5226
|
+
const nonce = newNonce();
|
|
3435
5227
|
let res;
|
|
3436
5228
|
try {
|
|
3437
5229
|
res = await fetch(`${apiUrl}/api/rules/fetch`, {
|
|
@@ -3439,6 +5231,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3439
5231
|
headers: {
|
|
3440
5232
|
"Authorization": `Bearer ${token}`,
|
|
3441
5233
|
"Content-Type": "application/json",
|
|
5234
|
+
...clientHelloHeaders(CLI_VERSION, nonce),
|
|
3442
5235
|
...scanId ? { "Idempotency-Key": scanId } : {}
|
|
3443
5236
|
},
|
|
3444
5237
|
body: JSON.stringify({ frameworks, categories, ...scanId ? { scanId } : {} })
|
|
@@ -3471,7 +5264,20 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3471
5264
|
);
|
|
3472
5265
|
}
|
|
3473
5266
|
if (res.status === 401) throw new ProFetchError("AUTH_FAILED", "Auth expired. Run `shipguard login` again.");
|
|
3474
|
-
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
|
+
}
|
|
3475
5281
|
if (res.status === 429) {
|
|
3476
5282
|
throw new ProFetchError(
|
|
3477
5283
|
"RATE_LIMITED",
|
|
@@ -3497,7 +5303,7 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3497
5303
|
const rawText = await res.text();
|
|
3498
5304
|
let responseJson;
|
|
3499
5305
|
try {
|
|
3500
|
-
const { parseStrictNoDup: parseStrict } = await import("./dist-
|
|
5306
|
+
const { parseStrictNoDup: parseStrict } = await import("./dist-3XUWQFMP.js");
|
|
3501
5307
|
responseJson = parseStrict(rawText);
|
|
3502
5308
|
} catch (parseErr) {
|
|
3503
5309
|
const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
|
|
@@ -3510,17 +5316,30 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3510
5316
|
const bundleResponse = responseJson;
|
|
3511
5317
|
const effectiveFloorPath = floorPath ?? DEFAULT_FLOOR_PATH;
|
|
3512
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;
|
|
3513
5323
|
const verifyResult = await verifyBundleResponse(
|
|
3514
5324
|
bundleResponse,
|
|
3515
5325
|
{
|
|
3516
5326
|
scanId: effectiveScanId,
|
|
3517
5327
|
frameworks,
|
|
3518
|
-
options: {},
|
|
3519
|
-
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
|
|
3520
5333
|
},
|
|
3521
5334
|
effectiveFloorPath
|
|
3522
5335
|
);
|
|
3523
5336
|
if (!verifyResult.ok) {
|
|
5337
|
+
if (verifyResult.freshnessExpired) {
|
|
5338
|
+
throw new ProFetchError(
|
|
5339
|
+
"FRESHNESS_EXPIRED",
|
|
5340
|
+
`${PRO_RULES_UNAVAILABLE_MESSAGE} (${verifyResult.reason})`
|
|
5341
|
+
);
|
|
5342
|
+
}
|
|
3524
5343
|
throw new ProFetchError(
|
|
3525
5344
|
"BUNDLE_INVALID",
|
|
3526
5345
|
`Attested bundle verification failed: ${verifyResult.reason}` + (verifyResult.nonSafe ? " [non-safe exit]" : "")
|
|
@@ -3574,7 +5393,21 @@ async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath)
|
|
|
3574
5393
|
framework: r.framework
|
|
3575
5394
|
};
|
|
3576
5395
|
});
|
|
3577
|
-
|
|
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
|
+
};
|
|
3578
5411
|
}
|
|
3579
5412
|
throw new ProFetchError(
|
|
3580
5413
|
"BUNDLE_INVALID",
|
|
@@ -3654,63 +5487,32 @@ function runProRules(rules, files, _policy) {
|
|
|
3654
5487
|
);
|
|
3655
5488
|
}
|
|
3656
5489
|
}
|
|
3657
|
-
const findings = [];
|
|
3658
5490
|
const allRelativePaths = files.map((f) => f.relativePath);
|
|
3659
5491
|
const ctx = {
|
|
3660
5492
|
allRelativePaths,
|
|
3661
5493
|
releaseId: "pre-attestation"
|
|
3662
5494
|
};
|
|
3663
|
-
|
|
3664
|
-
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
const
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
|
|
3673
|
-
|
|
3674
|
-
flags: rule.matcher.flags ?? "",
|
|
3675
|
-
// pass through delivered values; executor defaults to 'none'/'statement'.
|
|
3676
|
-
...boundary !== void 0 && { boundary },
|
|
3677
|
-
...antiPatternScope !== void 0 && { antiPatternScope }
|
|
3678
|
-
};
|
|
3679
|
-
} else if (rule.matcher.type === "file-presence") {
|
|
3680
|
-
const presenceRule = rule.matcher.presenceRule ?? "must-not-exist";
|
|
3681
|
-
matcherForExecutor = {
|
|
3682
|
-
type: "file-presence",
|
|
3683
|
-
fileGlob: rule.matcher.fileGlob,
|
|
3684
|
-
presenceRule
|
|
3685
|
-
};
|
|
3686
|
-
} else if (rule.matcher.type === "file-relationship") {
|
|
3687
|
-
const frAny = rule.matcher;
|
|
3688
|
-
const frFlags = frAny["flags"] ?? "";
|
|
3689
|
-
const frPatterns = rule.matcher.patterns ?? [];
|
|
3690
|
-
const frAntiPatterns = rule.matcher.antiPatterns ?? [];
|
|
3691
|
-
matcherForExecutor = {
|
|
3692
|
-
type: "file-relationship",
|
|
3693
|
-
fileGlob: rule.matcher.fileGlob,
|
|
3694
|
-
context: {
|
|
3695
|
-
requiresFile: rule.matcher.context?.requiresFile,
|
|
3696
|
-
requiresPattern: rule.matcher.context?.requiresPattern
|
|
3697
|
-
},
|
|
3698
|
-
// Extended fields for self-referential requiresPattern evaluation:
|
|
3699
|
-
patterns: frPatterns,
|
|
3700
|
-
antiPatterns: frAntiPatterns,
|
|
3701
|
-
flags: frFlags
|
|
3702
|
-
};
|
|
3703
|
-
} else {
|
|
3704
|
-
throw new RunProRulesFatalError(
|
|
3705
|
-
`Unreachable: unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}"`
|
|
3706
|
-
);
|
|
3707
|
-
}
|
|
3708
|
-
const matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
|
|
3709
|
-
for (const file of matched) {
|
|
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;
|
|
5504
|
+
}
|
|
5505
|
+
if (p.requiresRe !== void 0 && !p.requiresRe.matcher(file.content).find()) continue;
|
|
3710
5506
|
let canonicalFindings;
|
|
3711
5507
|
try {
|
|
3712
|
-
canonicalFindings =
|
|
3713
|
-
|
|
5508
|
+
canonicalFindings = p.requiresFailClosed !== void 0 ? [{
|
|
5509
|
+
line: 1,
|
|
5510
|
+
column: 1,
|
|
5511
|
+
evidence: `requiresPattern "${p.requiresFailClosed}" (compile error \u2014 fail closed)`,
|
|
5512
|
+
suppressionState: "active",
|
|
5513
|
+
matcherType: "pattern"
|
|
5514
|
+
}] : activeExecutor.evaluate(
|
|
5515
|
+
p.matcher,
|
|
3714
5516
|
{ relativePath: file.relativePath, content: file.content },
|
|
3715
5517
|
ctx
|
|
3716
5518
|
);
|
|
@@ -3724,11 +5526,11 @@ function runProRules(rules, files, _policy) {
|
|
|
3724
5526
|
);
|
|
3725
5527
|
}
|
|
3726
5528
|
for (const cf of canonicalFindings) {
|
|
3727
|
-
|
|
5529
|
+
lines ??= file.content.split("\n");
|
|
3728
5530
|
const lineIndex = cf.line - 1;
|
|
3729
5531
|
const commentSuppressed = lineIndex >= 0 ? isLineSuppressed(lines, lineIndex, rule.id) : false;
|
|
3730
5532
|
const isSuppressed = cf.suppressionState === "suppressed" || commentSuppressed;
|
|
3731
|
-
findings.push({
|
|
5533
|
+
p.findings.push({
|
|
3732
5534
|
id: rule.id,
|
|
3733
5535
|
title: rule.explanation.split(".")[0],
|
|
3734
5536
|
severity: rule.severity,
|
|
@@ -3755,7 +5557,70 @@ function runProRules(rules, files, _policy) {
|
|
|
3755
5557
|
}
|
|
3756
5558
|
}
|
|
3757
5559
|
}
|
|
3758
|
-
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: [] };
|
|
3759
5624
|
}
|
|
3760
5625
|
function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manifest) {
|
|
3761
5626
|
const augmented = rules;
|
|
@@ -3799,8 +5664,25 @@ function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manife
|
|
|
3799
5664
|
|
|
3800
5665
|
export {
|
|
3801
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,
|
|
5678
|
+
compileDetectorRegex,
|
|
5679
|
+
secretScreenLabel,
|
|
5680
|
+
parseMaskedSecret,
|
|
3802
5681
|
getFindingKey,
|
|
3803
5682
|
redactFindingsEvidence,
|
|
5683
|
+
looksFakeKey,
|
|
5684
|
+
isTestValue,
|
|
5685
|
+
checkSecretsWithStats,
|
|
3804
5686
|
secretsCheck,
|
|
3805
5687
|
authCheck,
|
|
3806
5688
|
databaseCheck,
|
|
@@ -3809,14 +5691,58 @@ export {
|
|
|
3809
5691
|
assertTrustedApiUrl,
|
|
3810
5692
|
ensureSecureDir,
|
|
3811
5693
|
writeSecureFileSync,
|
|
5694
|
+
PlatformUnavailableError,
|
|
5695
|
+
parseRetryAfterSeconds,
|
|
5696
|
+
isPlatformUnavailable,
|
|
5697
|
+
PRO_RULES_UNAVAILABLE_MESSAGE,
|
|
3812
5698
|
loadCredentials,
|
|
3813
5699
|
saveCredentials,
|
|
3814
5700
|
clearCredentials,
|
|
3815
5701
|
isTokenExpired,
|
|
5702
|
+
RefreshUnavailableError,
|
|
3816
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,
|
|
3817
5742
|
loadChecksumManifest,
|
|
3818
5743
|
isLineSuppressed,
|
|
3819
5744
|
applySuppressions,
|
|
5745
|
+
applyPolicyIgnores,
|
|
3820
5746
|
NoRulesAppliedError,
|
|
3821
5747
|
ProFetchError,
|
|
3822
5748
|
fetchProRules,
|
|
@@ -3826,3 +5752,4 @@ export {
|
|
|
3826
5752
|
runProRules,
|
|
3827
5753
|
runProRulesWithDispatch
|
|
3828
5754
|
};
|
|
5755
|
+
//# sourceMappingURL=chunk-4J3V4FKA.js.map
|