@agenticcli/shipguard 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +91 -0
- package/README.md +4 -0
- package/dist/checksum-manifest.json +7 -0
- package/dist/{chunk-BZWSFLBO.js → chunk-ALFVS2BH.js} +30 -13
- package/dist/chunk-ANTCYKRO.js +2024 -0
- package/dist/chunk-XOWMKGOE.js +3166 -0
- package/dist/cli-facts.json +101 -0
- package/dist/cli.js +98 -25
- package/dist/{config-generator-Q2YTMBZ5.js → config-generator-RMWNQQHW.js} +2 -1
- package/dist/dist-PCVBV5S6.js +74 -0
- package/dist/pro-scanner-ENFCTA4R.js +17 -0
- package/package.json +20 -6
- package/dist/chunk-2N3P2DUE.js +0 -1574
- package/dist/pro-scanner-ER2RYPI5.js +0 -10
|
@@ -0,0 +1,3166 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EXEC_RULE_FIELDS,
|
|
3
|
+
RE2JS_V1_RUNTIME_ID,
|
|
4
|
+
canonicalJson,
|
|
5
|
+
computeExecutableHash,
|
|
6
|
+
parseFlags,
|
|
7
|
+
parseStrictNoDup,
|
|
8
|
+
re2jsV1Executor,
|
|
9
|
+
selectExpected,
|
|
10
|
+
verifyExactSet
|
|
11
|
+
} from "./chunk-ANTCYKRO.js";
|
|
12
|
+
|
|
13
|
+
// src/core/pro-scanner.ts
|
|
14
|
+
import * as path2 from "path";
|
|
15
|
+
import * as os from "os";
|
|
16
|
+
|
|
17
|
+
// src/core/auth.ts
|
|
18
|
+
import {
|
|
19
|
+
readFileSync,
|
|
20
|
+
writeFileSync,
|
|
21
|
+
mkdirSync,
|
|
22
|
+
rmSync,
|
|
23
|
+
existsSync,
|
|
24
|
+
statSync,
|
|
25
|
+
chmodSync
|
|
26
|
+
} from "fs";
|
|
27
|
+
import { join, dirname } from "path";
|
|
28
|
+
import { homedir } from "os";
|
|
29
|
+
|
|
30
|
+
// src/utils/trust.ts
|
|
31
|
+
var BUILT_IN_TRUSTED = /* @__PURE__ */ new Set([
|
|
32
|
+
"agenticcli.dev",
|
|
33
|
+
"localhost",
|
|
34
|
+
"127.0.0.1"
|
|
35
|
+
]);
|
|
36
|
+
function assertTrustedApiUrl(url) {
|
|
37
|
+
let parsed;
|
|
38
|
+
try {
|
|
39
|
+
parsed = new URL(url);
|
|
40
|
+
} catch {
|
|
41
|
+
throw new Error(
|
|
42
|
+
`[shipguard] Untrusted API URL "${url}" \u2014 URL is invalid. Only agenticcli.dev, localhost, and 127.0.0.1 are permitted. Set SHIPGUARD_EXTRA_HOSTS to add trusted hosts.`
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
const hostname = parsed.hostname.toLowerCase();
|
|
46
|
+
if (BUILT_IN_TRUSTED.has(hostname)) return;
|
|
47
|
+
const extra = (process.env.SHIPGUARD_EXTRA_HOSTS ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
48
|
+
if (extra.includes(hostname)) return;
|
|
49
|
+
throw new Error(
|
|
50
|
+
`[shipguard] Untrusted API URL "${url}" (hostname: "${hostname}"). Only agenticcli.dev, localhost, and 127.0.0.1 are permitted by default. To allow additional hosts, set SHIPGUARD_EXTRA_HOSTS=<comma-separated-hostnames>.`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/core/auth.ts
|
|
55
|
+
var DIR_MODE = 448;
|
|
56
|
+
var FILE_MODE = 384;
|
|
57
|
+
var UNSAFE_PERM_MASK = 63;
|
|
58
|
+
var isPosix = process.platform !== "win32";
|
|
59
|
+
function getCredentialsPath() {
|
|
60
|
+
return join(homedir(), ".config", "shipguard", "credentials.json");
|
|
61
|
+
}
|
|
62
|
+
function hasUnsafePermissions(path3) {
|
|
63
|
+
if (!isPosix) return false;
|
|
64
|
+
const mode = statSync(path3).mode & 511;
|
|
65
|
+
return (mode & UNSAFE_PERM_MASK) !== 0;
|
|
66
|
+
}
|
|
67
|
+
function loadCredentials() {
|
|
68
|
+
const p = getCredentialsPath();
|
|
69
|
+
if (!existsSync(p)) return null;
|
|
70
|
+
if (hasUnsafePermissions(p)) {
|
|
71
|
+
console.warn(
|
|
72
|
+
"[shipguard] credentials file has unsafe permissions (group/other-readable or writable) \u2014 refusing to use it. Run `shipguard login` again to re-create it with 0600 perms."
|
|
73
|
+
);
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(readFileSync(p, "utf-8"));
|
|
78
|
+
} catch {
|
|
79
|
+
console.warn("[shipguard] credentials file is corrupt \u2014 run `shipguard login` again");
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
async function saveCredentials(creds) {
|
|
84
|
+
const p = getCredentialsPath();
|
|
85
|
+
const dir = dirname(p);
|
|
86
|
+
mkdirSync(dir, { recursive: true, mode: DIR_MODE });
|
|
87
|
+
if (isPosix) chmodSync(dir, DIR_MODE);
|
|
88
|
+
writeFileSync(p, JSON.stringify(creds, null, 2), { mode: FILE_MODE });
|
|
89
|
+
if (isPosix) chmodSync(p, FILE_MODE);
|
|
90
|
+
}
|
|
91
|
+
function clearCredentials() {
|
|
92
|
+
const p = getCredentialsPath();
|
|
93
|
+
if (!existsSync(p)) return;
|
|
94
|
+
try {
|
|
95
|
+
const size = statSync(p).size;
|
|
96
|
+
if (size > 0) writeFileSync(p, Buffer.alloc(size, 0), { mode: FILE_MODE });
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
rmSync(p, { force: true });
|
|
100
|
+
}
|
|
101
|
+
function isTokenExpired(creds) {
|
|
102
|
+
return creds.expiresAt < Date.now();
|
|
103
|
+
}
|
|
104
|
+
async function getAuthToken() {
|
|
105
|
+
if (process.env.SHIPGUARD_API_KEY) return process.env.SHIPGUARD_API_KEY;
|
|
106
|
+
const creds = loadCredentials();
|
|
107
|
+
if (!creds) return null;
|
|
108
|
+
if (!isTokenExpired(creds)) return creds.accessToken;
|
|
109
|
+
if (creds.refreshToken && creds.apiUrl) {
|
|
110
|
+
try {
|
|
111
|
+
assertTrustedApiUrl(creds.apiUrl);
|
|
112
|
+
const res = await fetch(`${creds.apiUrl}/api/auth/device/refresh`, {
|
|
113
|
+
method: "POST",
|
|
114
|
+
headers: { "Content-Type": "application/json" },
|
|
115
|
+
body: JSON.stringify({ refresh_token: creds.refreshToken })
|
|
116
|
+
});
|
|
117
|
+
if (res.ok) {
|
|
118
|
+
const { access_token, refresh_token, expires_in } = await res.json();
|
|
119
|
+
await saveCredentials({
|
|
120
|
+
accessToken: access_token,
|
|
121
|
+
refreshToken: refresh_token ?? creds.refreshToken,
|
|
122
|
+
expiresAt: Date.now() + (expires_in ?? 900) * 1e3,
|
|
123
|
+
apiUrl: creds.apiUrl
|
|
124
|
+
});
|
|
125
|
+
return access_token;
|
|
126
|
+
}
|
|
127
|
+
} catch {
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// src/core/release-verify.ts
|
|
134
|
+
import * as fs from "fs";
|
|
135
|
+
import * as path from "path";
|
|
136
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
137
|
+
|
|
138
|
+
// src/core/crypto.ts
|
|
139
|
+
var MIN_ACCEPTABLE_EPOCH = 1;
|
|
140
|
+
var KEYRING = [
|
|
141
|
+
// ----- RELEASE-ATTESTATION (TEST keypair ra-k1-2026) -----
|
|
142
|
+
// Signs corpus manifest + release attestation objects. CI only.
|
|
143
|
+
// Private half lives ONLY in protected CI secrets — never shipped.
|
|
144
|
+
{
|
|
145
|
+
kid: "ra-k1-2026",
|
|
146
|
+
role: "release-attestation",
|
|
147
|
+
epoch: 1,
|
|
148
|
+
expiry: 1798761600,
|
|
149
|
+
// 2027-01-01 00:00:00 UTC — test/dev expiry; real keys use deploy-time values
|
|
150
|
+
fingerprint: "5a173b63249cd3032dd3aeb44c15f70170cc8373ec376bd32bf6e93633c31592",
|
|
151
|
+
publicKey: `-----BEGIN PUBLIC KEY-----
|
|
152
|
+
MCowBQYDK2VwAyEA0GawD+n2tLAG3iq/xQuUUUM2Zhesjx3zmvOzs6FcapY=
|
|
153
|
+
-----END PUBLIC KEY-----`
|
|
154
|
+
},
|
|
155
|
+
// ----- CI-FRESHNESS (TEST keypair cf-k1-2026) -----
|
|
156
|
+
// Signs short-TTL freshness tokens. CI only.
|
|
157
|
+
// Private half lives ONLY in protected CI secrets — never shipped.
|
|
158
|
+
{
|
|
159
|
+
kid: "cf-k1-2026",
|
|
160
|
+
role: "ci-freshness",
|
|
161
|
+
epoch: 1,
|
|
162
|
+
expiry: 1798761600,
|
|
163
|
+
// 2027-01-01 00:00:00 UTC — test/dev expiry; real keys use deploy-time values
|
|
164
|
+
fingerprint: "079c4eb3984816650860939dce0c18d86b923786701610bfc2e7da5a9e4b94d7",
|
|
165
|
+
publicKey: `-----BEGIN PUBLIC KEY-----
|
|
166
|
+
MCowBQYDK2VwAyEA5BGUcYyU9AeLVjNeyEPS0z693KL68WqilSG+APXjqg0=
|
|
167
|
+
-----END PUBLIC KEY-----`
|
|
168
|
+
},
|
|
169
|
+
// ----- BUNDLE keys (existing k1-2026 and k2-2026) -----
|
|
170
|
+
// Convex-held; signs per-request bundle envelopes. PINNED_KEYS stays in sync.
|
|
171
|
+
{
|
|
172
|
+
kid: "k1-2026",
|
|
173
|
+
role: "bundle",
|
|
174
|
+
epoch: 1,
|
|
175
|
+
expiry: 1798761600,
|
|
176
|
+
fingerprint: "855e81b870c16d377efd8354e9761fadca2d22d16536f291fb77e690f9d65abc",
|
|
177
|
+
publicKey: `-----BEGIN PUBLIC KEY-----
|
|
178
|
+
MCowBQYDK2VwAyEAkpeX0A3zIOttGn8t+jagJHLRTv5Q809vqIZU37lE6xQ=
|
|
179
|
+
-----END PUBLIC KEY-----`
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
kid: "k2-2026",
|
|
183
|
+
role: "bundle",
|
|
184
|
+
epoch: 2,
|
|
185
|
+
expiry: 1798761600,
|
|
186
|
+
fingerprint: "57873aac03421fa0740fdd9520729536223010067ea3012135db2b255a2b263c",
|
|
187
|
+
publicKey: `-----BEGIN PUBLIC KEY-----
|
|
188
|
+
MCowBQYDK2VwAyEA1DXW6sA9dllAbfXMa/G+50Sw00svQF2X5bcU+YcP6M8=
|
|
189
|
+
-----END PUBLIC KEY-----`
|
|
190
|
+
}
|
|
191
|
+
// AUTH key: managed separately via JWKS endpoint; the CLI does NOT pin auth keys for
|
|
192
|
+
// release trust — only for reference/documentation completeness. Wired separately.
|
|
193
|
+
// If you need to add auth-k1-2026 here, obtain the public PEM from the auth service JWKS.
|
|
194
|
+
];
|
|
195
|
+
function validateKeyringEntry(entry) {
|
|
196
|
+
if (entry.epoch < MIN_ACCEPTABLE_EPOCH) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
`Key "${entry.kid}" epoch ${entry.epoch} is below the minimum acceptable epoch ${MIN_ACCEPTABLE_EPOCH} \u2014 epoch rollback rejected`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
if (entry.expiry < Date.now() / 1e3) {
|
|
202
|
+
throw new Error(
|
|
203
|
+
`Key "${entry.kid}" has expired (expiry=${entry.expiry}, now=${Math.floor(Date.now() / 1e3)})`
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
function pemToArrayBuffer(pem) {
|
|
208
|
+
const b64 = pem.replace(/-----BEGIN PUBLIC KEY-----/, "").replace(/-----END PUBLIC KEY-----/, "").replace(/\s/g, "");
|
|
209
|
+
const binary = Buffer.from(b64, "base64");
|
|
210
|
+
return binary.buffer.slice(binary.byteOffset, binary.byteOffset + binary.byteLength);
|
|
211
|
+
}
|
|
212
|
+
async function resolveAndImportKey(kid, expectedRole) {
|
|
213
|
+
const entry = KEYRING.find((e) => e.kid === kid);
|
|
214
|
+
if (!entry) {
|
|
215
|
+
throw new Error(
|
|
216
|
+
`Unknown key "${kid}" \u2014 not found in KEYRING. Upgrade shipguard to a version that supports this key id.`
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
validateKeyringEntry(entry);
|
|
220
|
+
if (entry.role !== expectedRole) {
|
|
221
|
+
throw new Error(
|
|
222
|
+
`key role mismatch: expected ${expectedRole}, got ${entry.role} \u2014 cross-role replay rejected`
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return globalThis.crypto.subtle.importKey(
|
|
226
|
+
"spki",
|
|
227
|
+
pemToArrayBuffer(entry.publicKey),
|
|
228
|
+
{ name: "Ed25519" },
|
|
229
|
+
false,
|
|
230
|
+
["verify"]
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
async function verifyAttestation(preimageBytesOrManifestBytes, signatureB64url, kid) {
|
|
234
|
+
const cryptoKey = await resolveAndImportKey(kid, "release-attestation");
|
|
235
|
+
const signatureBytes = Buffer.from(signatureB64url.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
236
|
+
const valid = await globalThis.crypto.subtle.verify(
|
|
237
|
+
"Ed25519",
|
|
238
|
+
cryptoKey,
|
|
239
|
+
signatureBytes,
|
|
240
|
+
// WHY: Buffer.from(...,'base64') is always ArrayBuffer-backed (never SharedArrayBuffer)
|
|
241
|
+
// but TS lib.dom types Buffer as Uint8Array<ArrayBufferLike>. SubtleCrypto.verify
|
|
242
|
+
// requires Uint8Array<ArrayBuffer>. The cast is safe: Node Buffer never uses SAB.
|
|
243
|
+
preimageBytesOrManifestBytes
|
|
244
|
+
);
|
|
245
|
+
if (!valid) {
|
|
246
|
+
throw new Error("release-attestation signature verification failed \u2014 possible tampering");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
async function verifyFreshness(preimageBytesOrFreshnessBytes, signatureB64url, kid) {
|
|
250
|
+
const cryptoKey = await resolveAndImportKey(kid, "ci-freshness");
|
|
251
|
+
const signatureBytes = Buffer.from(signatureB64url.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
252
|
+
const valid = await globalThis.crypto.subtle.verify(
|
|
253
|
+
"Ed25519",
|
|
254
|
+
cryptoKey,
|
|
255
|
+
signatureBytes,
|
|
256
|
+
// WHY: Buffer.from(...,'base64') is always ArrayBuffer-backed (never SharedArrayBuffer)
|
|
257
|
+
// but TS lib.dom types Buffer as Uint8Array<ArrayBufferLike>. SubtleCrypto.verify
|
|
258
|
+
// requires Uint8Array<ArrayBuffer>. The cast is safe: Node Buffer never uses SAB.
|
|
259
|
+
preimageBytesOrFreshnessBytes
|
|
260
|
+
);
|
|
261
|
+
if (!valid) {
|
|
262
|
+
throw new Error("ci-freshness signature verification failed \u2014 possible tampering");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async function verifyBundleEnvelopeSignature(preimageBytes, signatureB64url, kid) {
|
|
266
|
+
const cryptoKey = await resolveAndImportKey(kid, "bundle");
|
|
267
|
+
const signatureBytes = Buffer.from(signatureB64url.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
|
268
|
+
const valid = await globalThis.crypto.subtle.verify(
|
|
269
|
+
"Ed25519",
|
|
270
|
+
cryptoKey,
|
|
271
|
+
signatureBytes,
|
|
272
|
+
// WHY: Buffer.from(...,'base64') is always ArrayBuffer-backed (never SharedArrayBuffer)
|
|
273
|
+
// but TS lib.dom types Buffer as Uint8Array<ArrayBufferLike>. SubtleCrypto.verify
|
|
274
|
+
// requires Uint8Array<ArrayBuffer>. The cast is safe: Node Buffer never uses SAB.
|
|
275
|
+
preimageBytes
|
|
276
|
+
);
|
|
277
|
+
if (!valid) {
|
|
278
|
+
throw new Error("bundle-envelope signature verification failed \u2014 possible tampering or replay");
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// src/core/release-verify.ts
|
|
283
|
+
var MIN_ACCEPTABLE_SEQUENCE = 1;
|
|
284
|
+
function sha256hex(input) {
|
|
285
|
+
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
286
|
+
return Buffer.from(sha256(bytes)).toString("hex");
|
|
287
|
+
}
|
|
288
|
+
function acquireFloorLock(lockPath, timeoutMs = 5e3) {
|
|
289
|
+
const deadline = Date.now() + timeoutMs;
|
|
290
|
+
while (Date.now() < deadline) {
|
|
291
|
+
try {
|
|
292
|
+
const fd = fs.openSync(lockPath, "wx");
|
|
293
|
+
fs.closeSync(fd);
|
|
294
|
+
return () => {
|
|
295
|
+
try {
|
|
296
|
+
fs.unlinkSync(lockPath);
|
|
297
|
+
} catch {
|
|
298
|
+
}
|
|
299
|
+
};
|
|
300
|
+
} catch (err) {
|
|
301
|
+
const code = err.code;
|
|
302
|
+
if (code !== "EEXIST") throw err;
|
|
303
|
+
const waitUntil = Date.now() + 10;
|
|
304
|
+
while (Date.now() < waitUntil) {
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
throw new Error(`floor lock timeout after ${timeoutMs}ms \u2014 concurrent CLI writer?`);
|
|
309
|
+
}
|
|
310
|
+
function atomicAcceptFloor(floorPath, incoming) {
|
|
311
|
+
const lockPath = `${floorPath}.lock`;
|
|
312
|
+
const dir = path.dirname(floorPath);
|
|
313
|
+
const tmpPath = path.join(dir, `.floor-tmp-${process.pid}-${Date.now()}.json`);
|
|
314
|
+
const releaseLock = acquireFloorLock(lockPath);
|
|
315
|
+
try {
|
|
316
|
+
let lockedFloor = null;
|
|
317
|
+
let rawFloor = null;
|
|
318
|
+
try {
|
|
319
|
+
rawFloor = fs.readFileSync(floorPath, "utf-8");
|
|
320
|
+
} catch (readErr) {
|
|
321
|
+
const code = readErr.code;
|
|
322
|
+
if (code === "ENOENT") {
|
|
323
|
+
rawFloor = null;
|
|
324
|
+
} else {
|
|
325
|
+
const msg = readErr instanceof Error ? readErr.message : String(readErr);
|
|
326
|
+
return { corrupt: true, reason: `floor read I/O error (${code ?? "unknown"}): ${msg}` };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (rawFloor !== null) {
|
|
330
|
+
try {
|
|
331
|
+
lockedFloor = parseStrictNoDup(rawFloor);
|
|
332
|
+
if (typeof lockedFloor.sequence !== "number" || !Number.isSafeInteger(lockedFloor.sequence) || typeof lockedFloor.releaseId !== "string" || typeof lockedFloor.manifestDigest !== "string" || typeof lockedFloor.keyringEpoch !== "number" || !Number.isSafeInteger(lockedFloor.keyringEpoch)) {
|
|
333
|
+
return {
|
|
334
|
+
corrupt: true,
|
|
335
|
+
reason: "floor file present but missing required fields or non-safe-integer values \u2014 treating as corruption (Finding 2)"
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
} catch (parseErr) {
|
|
339
|
+
const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
|
|
340
|
+
return {
|
|
341
|
+
corrupt: true,
|
|
342
|
+
reason: `floor file present but not valid JSON (duplicate key or malformed): ${msg} \u2014 treating as corruption (Finding 2)`
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (lockedFloor !== null) {
|
|
347
|
+
if (incoming.sequence < lockedFloor.sequence) {
|
|
348
|
+
return {
|
|
349
|
+
accepted: false,
|
|
350
|
+
reason: `sequence rollback rejected (under-lock): incoming=${incoming.sequence}, locked-floor=${lockedFloor.sequence}`
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (incoming.sequence === lockedFloor.sequence) {
|
|
354
|
+
const sameReleaseId = incoming.releaseId === lockedFloor.releaseId;
|
|
355
|
+
const sameManifest = incoming.manifestDigest === lockedFloor.manifestDigest;
|
|
356
|
+
const sameEpoch = incoming.keyringEpoch === lockedFloor.keyringEpoch;
|
|
357
|
+
if (!sameReleaseId || !sameManifest || !sameEpoch) {
|
|
358
|
+
return {
|
|
359
|
+
accepted: false,
|
|
360
|
+
reason: `same-sequence/different-tuple rejected (under-lock): sequence=${incoming.sequence}`
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
return { accepted: true, wrote: false };
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
fs.writeFileSync(tmpPath, JSON.stringify(incoming), "utf-8");
|
|
367
|
+
const tmpFd = fs.openSync(tmpPath, "r+");
|
|
368
|
+
try {
|
|
369
|
+
fs.fsyncSync(tmpFd);
|
|
370
|
+
} finally {
|
|
371
|
+
fs.closeSync(tmpFd);
|
|
372
|
+
}
|
|
373
|
+
fs.renameSync(tmpPath, floorPath);
|
|
374
|
+
const dirFd = fs.openSync(dir, "r");
|
|
375
|
+
try {
|
|
376
|
+
fs.fsyncSync(dirFd);
|
|
377
|
+
} finally {
|
|
378
|
+
fs.closeSync(dirFd);
|
|
379
|
+
}
|
|
380
|
+
return { accepted: true, wrote: true };
|
|
381
|
+
} finally {
|
|
382
|
+
try {
|
|
383
|
+
if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath);
|
|
384
|
+
} catch {
|
|
385
|
+
}
|
|
386
|
+
releaseLock();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
async function verifyBundleResponse(response, request, floorPath) {
|
|
390
|
+
let manifest;
|
|
391
|
+
let attestation;
|
|
392
|
+
let freshnessTok;
|
|
393
|
+
let deliveredRulesRaw;
|
|
394
|
+
let envelope;
|
|
395
|
+
try {
|
|
396
|
+
const toStrictParsed = (v) => {
|
|
397
|
+
const json = typeof v === "string" ? v : JSON.stringify(v);
|
|
398
|
+
return parseStrictNoDup(json);
|
|
399
|
+
};
|
|
400
|
+
manifest = toStrictParsed(response.fullManifest);
|
|
401
|
+
attestation = toStrictParsed(response.corpusAttestation);
|
|
402
|
+
freshnessTok = toStrictParsed(response.freshnessTok);
|
|
403
|
+
envelope = toStrictParsed(response.bundleEnvelope);
|
|
404
|
+
const rulesJson = typeof response.selectedRules === "string" ? response.selectedRules : JSON.stringify(response.selectedRules);
|
|
405
|
+
const parsedRules = parseStrictNoDup(rulesJson);
|
|
406
|
+
if (!Array.isArray(parsedRules)) {
|
|
407
|
+
return { ok: false, reason: "selectedRules is not an array", nonSafe: true };
|
|
408
|
+
}
|
|
409
|
+
deliveredRulesRaw = parsedRules;
|
|
410
|
+
} catch (err) {
|
|
411
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
412
|
+
return { ok: false, reason: `parse-failure: ${msg}`, nonSafe: true };
|
|
413
|
+
}
|
|
414
|
+
function requireFields(obj, fields, label) {
|
|
415
|
+
for (const f of fields) {
|
|
416
|
+
if (!(f in obj) || obj[f] === void 0) {
|
|
417
|
+
return { ok: false, reason: `${label}: missing required field "${f}"`, nonSafe: true };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
function rejectExtraFields(obj, allowed, label) {
|
|
423
|
+
const allowedSet = new Set(allowed);
|
|
424
|
+
for (const key of Object.keys(obj)) {
|
|
425
|
+
if (!allowedSet.has(key)) {
|
|
426
|
+
return { ok: false, reason: `${label}: unexpected field "${key}"`, nonSafe: true };
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
function isSafeInteger(v) {
|
|
432
|
+
return typeof v === "number" && Number.isSafeInteger(v);
|
|
433
|
+
}
|
|
434
|
+
{
|
|
435
|
+
const MANIFEST_REQUIRED = [
|
|
436
|
+
"protocolVersion",
|
|
437
|
+
"releaseId",
|
|
438
|
+
"releaseSequence",
|
|
439
|
+
"corpusRuleCount",
|
|
440
|
+
"rules",
|
|
441
|
+
"capProfile",
|
|
442
|
+
"matcherEngineVersion",
|
|
443
|
+
"matcherEngineOptions",
|
|
444
|
+
"matcherRuntimeId",
|
|
445
|
+
"contractVersion",
|
|
446
|
+
"gateBVersion",
|
|
447
|
+
"gateCVersion"
|
|
448
|
+
];
|
|
449
|
+
const MANIFEST_ALLOWED = [...MANIFEST_REQUIRED, "sourceYamlDigest"];
|
|
450
|
+
const f = requireFields(manifest, MANIFEST_REQUIRED, "manifest");
|
|
451
|
+
if (f) return f;
|
|
452
|
+
const x = rejectExtraFields(manifest, MANIFEST_ALLOWED, "manifest");
|
|
453
|
+
if (x) return x;
|
|
454
|
+
if (manifest["protocolVersion"] !== "1") {
|
|
455
|
+
return { ok: false, reason: `manifest.protocolVersion must be "1", got "${manifest["protocolVersion"]}"`, nonSafe: true };
|
|
456
|
+
}
|
|
457
|
+
if (!isSafeInteger(manifest["releaseSequence"])) {
|
|
458
|
+
return { ok: false, reason: "manifest.releaseSequence must be a safe integer", nonSafe: true };
|
|
459
|
+
}
|
|
460
|
+
if (!isSafeInteger(manifest["corpusRuleCount"]) || manifest["corpusRuleCount"] < 0) {
|
|
461
|
+
return { ok: false, reason: "manifest.corpusRuleCount must be a non-negative safe integer", nonSafe: true };
|
|
462
|
+
}
|
|
463
|
+
if (typeof manifest["releaseId"] !== "string" || manifest["releaseId"] === "") {
|
|
464
|
+
return { ok: false, reason: "manifest.releaseId must be a non-empty string", nonSafe: true };
|
|
465
|
+
}
|
|
466
|
+
if (!Array.isArray(manifest["rules"])) {
|
|
467
|
+
return { ok: false, reason: "manifest.rules must be an array", nonSafe: true };
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
{
|
|
471
|
+
const ATT_REQUIRED = ["issuedAt", "kid", "manifestDigest", "protocolVersion", "releaseId", "releaseSequence", "signature"];
|
|
472
|
+
const f = requireFields(attestation, ATT_REQUIRED, "attestation");
|
|
473
|
+
if (f) return f;
|
|
474
|
+
const x = rejectExtraFields(attestation, ATT_REQUIRED, "attestation");
|
|
475
|
+
if (x) return x;
|
|
476
|
+
if (attestation["protocolVersion"] !== "1") {
|
|
477
|
+
return { ok: false, reason: `attestation.protocolVersion must be "1", got "${attestation["protocolVersion"]}"`, nonSafe: true };
|
|
478
|
+
}
|
|
479
|
+
if (!isSafeInteger(attestation["issuedAt"])) {
|
|
480
|
+
return { ok: false, reason: "attestation.issuedAt must be a safe integer", nonSafe: true };
|
|
481
|
+
}
|
|
482
|
+
if (!isSafeInteger(attestation["releaseSequence"])) {
|
|
483
|
+
return { ok: false, reason: "attestation.releaseSequence must be a safe integer", nonSafe: true };
|
|
484
|
+
}
|
|
485
|
+
if (typeof attestation["kid"] !== "string" || attestation["kid"] === "") {
|
|
486
|
+
return { ok: false, reason: "attestation.kid must be a non-empty string", nonSafe: true };
|
|
487
|
+
}
|
|
488
|
+
if (typeof attestation["signature"] !== "string" || attestation["signature"] === "") {
|
|
489
|
+
return { ok: false, reason: "attestation.signature must be a non-empty string", nonSafe: true };
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
{
|
|
493
|
+
const FRESH_REQUIRED = ["expiresAt", "issuedAt", "kid", "manifestDigest", "protocolVersion", "releaseId", "sequence", "signature"];
|
|
494
|
+
const f = requireFields(freshnessTok, FRESH_REQUIRED, "freshnessTok");
|
|
495
|
+
if (f) return f;
|
|
496
|
+
const x = rejectExtraFields(freshnessTok, FRESH_REQUIRED, "freshnessTok");
|
|
497
|
+
if (x) return x;
|
|
498
|
+
if (freshnessTok["protocolVersion"] !== "1") {
|
|
499
|
+
return { ok: false, reason: `freshnessTok.protocolVersion must be "1", got "${freshnessTok["protocolVersion"]}"`, nonSafe: true };
|
|
500
|
+
}
|
|
501
|
+
if (!isSafeInteger(freshnessTok["issuedAt"])) {
|
|
502
|
+
return { ok: false, reason: "freshnessTok.issuedAt must be a safe integer", nonSafe: true };
|
|
503
|
+
}
|
|
504
|
+
if (!isSafeInteger(freshnessTok["expiresAt"])) {
|
|
505
|
+
return { ok: false, reason: "freshnessTok.expiresAt must be a safe integer", nonSafe: true };
|
|
506
|
+
}
|
|
507
|
+
if (!isSafeInteger(freshnessTok["sequence"])) {
|
|
508
|
+
return { ok: false, reason: "freshnessTok.sequence must be a safe integer", nonSafe: true };
|
|
509
|
+
}
|
|
510
|
+
if (typeof freshnessTok["kid"] !== "string" || freshnessTok["kid"] === "") {
|
|
511
|
+
return { ok: false, reason: "freshnessTok.kid must be a non-empty string", nonSafe: true };
|
|
512
|
+
}
|
|
513
|
+
if (typeof freshnessTok["signature"] !== "string" || freshnessTok["signature"] === "") {
|
|
514
|
+
return { ok: false, reason: "freshnessTok.signature must be a non-empty string", nonSafe: true };
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
{
|
|
518
|
+
const ENV_REQUIRED = [
|
|
519
|
+
"exp",
|
|
520
|
+
"expectedRuleSet",
|
|
521
|
+
"frameworks",
|
|
522
|
+
"iat",
|
|
523
|
+
"kid",
|
|
524
|
+
"manifestDigest",
|
|
525
|
+
"options",
|
|
526
|
+
"protocolVersion",
|
|
527
|
+
"releaseId",
|
|
528
|
+
"requestDigest",
|
|
529
|
+
"scanId",
|
|
530
|
+
"sequence",
|
|
531
|
+
"signature"
|
|
532
|
+
];
|
|
533
|
+
const f = requireFields(envelope, ENV_REQUIRED, "bundleEnvelope");
|
|
534
|
+
if (f) return f;
|
|
535
|
+
const x = rejectExtraFields(envelope, ENV_REQUIRED, "bundleEnvelope");
|
|
536
|
+
if (x) return x;
|
|
537
|
+
if (envelope["protocolVersion"] !== "1") {
|
|
538
|
+
return { ok: false, reason: `bundleEnvelope.protocolVersion must be "1", got "${envelope["protocolVersion"]}"`, nonSafe: true };
|
|
539
|
+
}
|
|
540
|
+
if (!isSafeInteger(envelope["exp"])) {
|
|
541
|
+
return { ok: false, reason: "bundleEnvelope.exp must be a safe integer", nonSafe: true };
|
|
542
|
+
}
|
|
543
|
+
if (!isSafeInteger(envelope["iat"])) {
|
|
544
|
+
return { ok: false, reason: "bundleEnvelope.iat must be a safe integer", nonSafe: true };
|
|
545
|
+
}
|
|
546
|
+
if (!isSafeInteger(envelope["sequence"])) {
|
|
547
|
+
return { ok: false, reason: "bundleEnvelope.sequence must be a safe integer", nonSafe: true };
|
|
548
|
+
}
|
|
549
|
+
if (!Array.isArray(envelope["expectedRuleSet"])) {
|
|
550
|
+
return { ok: false, reason: "bundleEnvelope.expectedRuleSet must be an array", nonSafe: true };
|
|
551
|
+
}
|
|
552
|
+
if (typeof envelope["kid"] !== "string" || envelope["kid"] === "") {
|
|
553
|
+
return { ok: false, reason: "bundleEnvelope.kid must be a non-empty string", nonSafe: true };
|
|
554
|
+
}
|
|
555
|
+
if (typeof envelope["signature"] !== "string" || envelope["signature"] === "") {
|
|
556
|
+
return { ok: false, reason: "bundleEnvelope.signature must be a non-empty string", nonSafe: true };
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
{
|
|
560
|
+
const manifestRulesArr = manifest["rules"];
|
|
561
|
+
const MANIFEST_RULE_REQUIRED = ["id", "executableHash", "enabled", "framework", "tier", "severity", "matcherType", "title", "flags", "sourceYamlDigest"];
|
|
562
|
+
const VALID_MANIFEST_SEVERITY = /* @__PURE__ */ new Set(["error", "warning", "info", "critical", "high", "medium", "low"]);
|
|
563
|
+
const VALID_MANIFEST_MATCHER_TYPES = /* @__PURE__ */ new Set(["pattern", "file-presence", "file-relationship"]);
|
|
564
|
+
for (let i = 0; i < manifestRulesArr.length; i++) {
|
|
565
|
+
const r = manifestRulesArr[i];
|
|
566
|
+
if (r === null || typeof r !== "object" || Array.isArray(r)) {
|
|
567
|
+
return { ok: false, reason: `manifest.rules[${i}] is not an object`, nonSafe: true };
|
|
568
|
+
}
|
|
569
|
+
const rEntry = r;
|
|
570
|
+
for (const field of MANIFEST_RULE_REQUIRED) {
|
|
571
|
+
if (!(field in rEntry) || rEntry[field] === void 0) {
|
|
572
|
+
return { ok: false, reason: `manifest.rules[${i}]: missing required field "${field}"`, nonSafe: true };
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (typeof rEntry["id"] !== "string" || rEntry["id"] === "") {
|
|
576
|
+
return { ok: false, reason: `manifest.rules[${i}].id must be a non-empty string`, nonSafe: true };
|
|
577
|
+
}
|
|
578
|
+
if (typeof rEntry["executableHash"] !== "string" || rEntry["executableHash"].length !== 64) {
|
|
579
|
+
return { ok: false, reason: `manifest.rules[${i}].executableHash must be a 64-char hex string`, nonSafe: true };
|
|
580
|
+
}
|
|
581
|
+
if (typeof rEntry["enabled"] !== "boolean") {
|
|
582
|
+
return { ok: false, reason: `manifest.rules[${i}].enabled must be a boolean`, nonSafe: true };
|
|
583
|
+
}
|
|
584
|
+
if (typeof rEntry["severity"] !== "string" || !VALID_MANIFEST_SEVERITY.has(rEntry["severity"])) {
|
|
585
|
+
return { ok: false, reason: `manifest.rules[${i}].severity must be a valid severity enum value, got "${rEntry["severity"]}"`, nonSafe: true };
|
|
586
|
+
}
|
|
587
|
+
if (typeof rEntry["matcherType"] !== "string" || !VALID_MANIFEST_MATCHER_TYPES.has(rEntry["matcherType"])) {
|
|
588
|
+
return { ok: false, reason: `manifest.rules[${i}].matcherType must be pattern|file-presence|file-relationship`, nonSafe: true };
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
{
|
|
593
|
+
const cap = manifest["capProfile"];
|
|
594
|
+
if (cap === null || typeof cap !== "object" || Array.isArray(cap)) {
|
|
595
|
+
return { ok: false, reason: "manifest.capProfile must be an object", nonSafe: true };
|
|
596
|
+
}
|
|
597
|
+
const capObj = cap;
|
|
598
|
+
const CAP_FIELDS = ["maxFileBytes", "maxFiles", "maxFindings", "maxPatternBytes", "maxPatternsPerRule", "maxRules"];
|
|
599
|
+
for (const field of CAP_FIELDS) {
|
|
600
|
+
if (!(field in capObj) || !Number.isSafeInteger(capObj[field]) || capObj[field] < 0) {
|
|
601
|
+
return { ok: false, reason: `manifest.capProfile.${field} must be a non-negative safe integer`, nonSafe: true };
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
for (const key of Object.keys(capObj)) {
|
|
605
|
+
if (!CAP_FIELDS.includes(key)) {
|
|
606
|
+
return { ok: false, reason: `manifest.capProfile: unexpected field "${key}"`, nonSafe: true };
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
{
|
|
611
|
+
const opts = manifest["matcherEngineOptions"];
|
|
612
|
+
if (opts === null || typeof opts !== "object" || Array.isArray(opts)) {
|
|
613
|
+
return { ok: false, reason: "manifest.matcherEngineOptions must be an object", nonSafe: true };
|
|
614
|
+
}
|
|
615
|
+
const optsObj = opts;
|
|
616
|
+
if (typeof optsObj["LOOKBEHINDS"] !== "boolean") {
|
|
617
|
+
return { ok: false, reason: "manifest.matcherEngineOptions.LOOKBEHINDS must be a boolean", nonSafe: true };
|
|
618
|
+
}
|
|
619
|
+
for (const key of Object.keys(optsObj)) {
|
|
620
|
+
if (key !== "LOOKBEHINDS") {
|
|
621
|
+
return { ok: false, reason: `manifest.matcherEngineOptions: unexpected field "${key}"`, nonSafe: true };
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
{
|
|
626
|
+
const expectedSet2 = envelope["expectedRuleSet"];
|
|
627
|
+
for (let i = 0; i < expectedSet2.length; i++) {
|
|
628
|
+
const e = expectedSet2[i];
|
|
629
|
+
if (e === null || typeof e !== "object" || Array.isArray(e)) {
|
|
630
|
+
return { ok: false, reason: `bundleEnvelope.expectedRuleSet[${i}] is not an object`, nonSafe: true };
|
|
631
|
+
}
|
|
632
|
+
const eObj = e;
|
|
633
|
+
if (typeof eObj["id"] !== "string" || eObj["id"] === "") {
|
|
634
|
+
return { ok: false, reason: `bundleEnvelope.expectedRuleSet[${i}].id must be a non-empty string`, nonSafe: true };
|
|
635
|
+
}
|
|
636
|
+
if (typeof eObj["executableHash"] !== "string" || eObj["executableHash"].length !== 64) {
|
|
637
|
+
return { ok: false, reason: `bundleEnvelope.expectedRuleSet[${i}].executableHash must be a 64-char hex string`, nonSafe: true };
|
|
638
|
+
}
|
|
639
|
+
for (const key of Object.keys(eObj)) {
|
|
640
|
+
if (key !== "id" && key !== "executableHash") {
|
|
641
|
+
return { ok: false, reason: `bundleEnvelope.expectedRuleSet[${i}]: unexpected field "${key}"`, nonSafe: true };
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
{
|
|
647
|
+
const frameworks = envelope["frameworks"];
|
|
648
|
+
if (!Array.isArray(frameworks)) {
|
|
649
|
+
return { ok: false, reason: "bundleEnvelope.frameworks must be an array", nonSafe: true };
|
|
650
|
+
}
|
|
651
|
+
for (let i = 0; i < frameworks.length; i++) {
|
|
652
|
+
if (typeof frameworks[i] !== "string") {
|
|
653
|
+
return { ok: false, reason: `bundleEnvelope.frameworks[${i}] must be a string`, nonSafe: true };
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
{
|
|
658
|
+
const VALID_FLAGS = /* @__PURE__ */ new Set(["", "i", "m", "s", "im", "is", "ms", "ims"]);
|
|
659
|
+
const VALID_SEVERITY_5 = /* @__PURE__ */ new Set(["critical", "high", "medium", "low", "info"]);
|
|
660
|
+
const VALID_MATCHER_TYPES = /* @__PURE__ */ new Set(["pattern", "file-presence", "file-relationship"]);
|
|
661
|
+
const VALID_BOUNDARY = /* @__PURE__ */ new Set(["none", "word", "token"]);
|
|
662
|
+
const EXEC_RULE_ALLOWED = /* @__PURE__ */ new Set([...EXEC_RULE_FIELDS]);
|
|
663
|
+
const EXEC_RULE_REQUIRED = ["enabled", "flags", "framework", "id", "matcherType", "severity", "tier", "title"];
|
|
664
|
+
for (let i = 0; i < deliveredRulesRaw.length; i++) {
|
|
665
|
+
const r = deliveredRulesRaw[i];
|
|
666
|
+
if (r === null || typeof r !== "object" || Array.isArray(r)) {
|
|
667
|
+
return { ok: false, reason: `selectedRules[${i}] is not an object`, nonSafe: true };
|
|
668
|
+
}
|
|
669
|
+
const rObj = r;
|
|
670
|
+
for (const field of EXEC_RULE_REQUIRED) {
|
|
671
|
+
if (!(field in rObj) || rObj[field] === void 0) {
|
|
672
|
+
return { ok: false, reason: `selectedRules[${i}]: missing required field "${field}"`, nonSafe: true };
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
for (const key of Object.keys(rObj)) {
|
|
676
|
+
if (!EXEC_RULE_ALLOWED.has(key)) {
|
|
677
|
+
return { ok: false, reason: `selectedRules[${i}]: unexpected field "${key}"`, nonSafe: true };
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (typeof rObj["enabled"] !== "boolean") {
|
|
681
|
+
return { ok: false, reason: `selectedRules[${i}].enabled must be a boolean`, nonSafe: true };
|
|
682
|
+
}
|
|
683
|
+
if (typeof rObj["flags"] !== "string" || !VALID_FLAGS.has(rObj["flags"])) {
|
|
684
|
+
return { ok: false, reason: `selectedRules[${i}].flags must be a valid flags enum (""|"i"|"m"|"s"|"im"|"is"|"ms"|"ims"), got "${rObj["flags"]}"`, nonSafe: true };
|
|
685
|
+
}
|
|
686
|
+
if (typeof rObj["id"] !== "string" || rObj["id"] === "") {
|
|
687
|
+
return { ok: false, reason: `selectedRules[${i}].id must be a non-empty string`, nonSafe: true };
|
|
688
|
+
}
|
|
689
|
+
if (typeof rObj["matcherType"] !== "string" || !VALID_MATCHER_TYPES.has(rObj["matcherType"])) {
|
|
690
|
+
return { ok: false, reason: `selectedRules[${i}].matcherType must be pattern|file-presence|file-relationship`, nonSafe: true };
|
|
691
|
+
}
|
|
692
|
+
if (typeof rObj["severity"] !== "string" || !VALID_SEVERITY_5.has(rObj["severity"])) {
|
|
693
|
+
return { ok: false, reason: `selectedRules[${i}].severity must be critical|high|medium|low|info, got "${rObj["severity"]}"`, nonSafe: true };
|
|
694
|
+
}
|
|
695
|
+
if (typeof rObj["tier"] !== "string" || rObj["tier"] !== "free" && rObj["tier"] !== "pro") {
|
|
696
|
+
return { ok: false, reason: `selectedRules[${i}].tier must be "free"|"pro"`, nonSafe: true };
|
|
697
|
+
}
|
|
698
|
+
if (typeof rObj["title"] !== "string") {
|
|
699
|
+
return { ok: false, reason: `selectedRules[${i}].title must be a string`, nonSafe: true };
|
|
700
|
+
}
|
|
701
|
+
if (typeof rObj["framework"] !== "string") {
|
|
702
|
+
return { ok: false, reason: `selectedRules[${i}].framework must be a string`, nonSafe: true };
|
|
703
|
+
}
|
|
704
|
+
if ("action" in rObj && rObj["action"] !== void 0) {
|
|
705
|
+
if (typeof rObj["action"] !== "string" || !["block", "warn", "monitor"].includes(rObj["action"])) {
|
|
706
|
+
return { ok: false, reason: `selectedRules[${i}].action must be "block"|"warn"|"monitor"`, nonSafe: true };
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
if ("antiBoundary" in rObj && rObj["antiBoundary"] !== void 0) {
|
|
710
|
+
if (typeof rObj["antiBoundary"] !== "string" || !VALID_BOUNDARY.has(rObj["antiBoundary"])) {
|
|
711
|
+
return { ok: false, reason: `selectedRules[${i}].antiBoundary must be none|word|token`, nonSafe: true };
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
if ("antiPatternScope" in rObj && rObj["antiPatternScope"] !== void 0) {
|
|
715
|
+
const scope = rObj["antiPatternScope"];
|
|
716
|
+
const VALID_SCOPE_STRINGS = /* @__PURE__ */ new Set(["statement", "block", "function", "file"]);
|
|
717
|
+
const isValidScopeString = typeof scope === "string" && VALID_SCOPE_STRINGS.has(scope);
|
|
718
|
+
const isValidScopeObject = scope !== null && typeof scope === "object" && !Array.isArray(scope) && "lines" in scope && Number.isSafeInteger(scope["lines"]) && scope["lines"] >= 0 && Object.keys(scope).length === 1;
|
|
719
|
+
if (!isValidScopeString && !isValidScopeObject) {
|
|
720
|
+
return { ok: false, reason: `selectedRules[${i}].antiPatternScope must be "statement"|"block"|"function"|"file" or {lines:N}`, nonSafe: true };
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
if ("blocking" in rObj && rObj["blocking"] !== void 0) {
|
|
724
|
+
if (typeof rObj["blocking"] !== "boolean") {
|
|
725
|
+
return { ok: false, reason: `selectedRules[${i}].blocking must be a boolean`, nonSafe: true };
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if ("boundary" in rObj && rObj["boundary"] !== void 0) {
|
|
729
|
+
if (typeof rObj["boundary"] !== "string" || !VALID_BOUNDARY.has(rObj["boundary"])) {
|
|
730
|
+
return { ok: false, reason: `selectedRules[${i}].boundary must be "none"|"word"|"token"`, nonSafe: true };
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if ("categories" in rObj && rObj["categories"] !== void 0) {
|
|
734
|
+
if (!Array.isArray(rObj["categories"])) {
|
|
735
|
+
return { ok: false, reason: `selectedRules[${i}].categories must be an array`, nonSafe: true };
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if ("fileGlob" in rObj && rObj["fileGlob"] !== void 0) {
|
|
739
|
+
if (typeof rObj["fileGlob"] !== "string") {
|
|
740
|
+
return { ok: false, reason: `selectedRules[${i}].fileGlob must be a string`, nonSafe: true };
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
if ("presenceRule" in rObj && rObj["presenceRule"] !== void 0) {
|
|
744
|
+
if (typeof rObj["presenceRule"] !== "string" || !["must-exist", "must-not-exist"].includes(rObj["presenceRule"])) {
|
|
745
|
+
return { ok: false, reason: `selectedRules[${i}].presenceRule must be "must-exist"|"must-not-exist"`, nonSafe: true };
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
const manifestDigest = sha256hex("shipguard-manifest-v1\0" + canonicalJson(manifest));
|
|
751
|
+
if (manifest["protocolVersion"] !== "1") {
|
|
752
|
+
return { ok: false, reason: `unknown protocolVersion "${manifest["protocolVersion"]}"`, nonSafe: true };
|
|
753
|
+
}
|
|
754
|
+
const manifestRules = manifest["rules"];
|
|
755
|
+
if (!Array.isArray(manifestRules)) {
|
|
756
|
+
return { ok: false, reason: "manifest.rules is not an array", nonSafe: true };
|
|
757
|
+
}
|
|
758
|
+
if (manifest["corpusRuleCount"] !== manifestRules.length) {
|
|
759
|
+
return {
|
|
760
|
+
ok: false,
|
|
761
|
+
reason: `manifest.corpusRuleCount (${manifest["corpusRuleCount"]}) !== manifest.rules.length (${manifestRules.length})`,
|
|
762
|
+
nonSafe: true
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
if (attestation["releaseId"] !== manifest["releaseId"]) {
|
|
766
|
+
return {
|
|
767
|
+
ok: false,
|
|
768
|
+
reason: `attestation.releaseId mismatch: "${attestation["releaseId"]}" !== "${manifest["releaseId"]}"`,
|
|
769
|
+
nonSafe: true
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
if (attestation["releaseSequence"] !== manifest["releaseSequence"]) {
|
|
773
|
+
return {
|
|
774
|
+
ok: false,
|
|
775
|
+
reason: `attestation.releaseSequence mismatch`,
|
|
776
|
+
nonSafe: true
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
if (attestation["manifestDigest"] !== manifestDigest) {
|
|
780
|
+
return {
|
|
781
|
+
ok: false,
|
|
782
|
+
reason: `attestation.manifestDigest does not match recomputed manifest digest`,
|
|
783
|
+
nonSafe: true
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
const { signature: _sig, ...attestationWithoutSig } = attestation;
|
|
788
|
+
const attPreimage = new TextEncoder().encode(
|
|
789
|
+
"shipguard-attestation-v1\0" + canonicalJson(attestationWithoutSig)
|
|
790
|
+
);
|
|
791
|
+
await verifyAttestation(attPreimage, attestation["signature"], attestation["kid"]);
|
|
792
|
+
} catch (err) {
|
|
793
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
794
|
+
return { ok: false, reason: `attestation-verify-failed: ${msg}`, nonSafe: true };
|
|
795
|
+
}
|
|
796
|
+
const requestObj = {
|
|
797
|
+
frameworks: request.frameworks,
|
|
798
|
+
options: request.options,
|
|
799
|
+
scanId: request.scanId
|
|
800
|
+
};
|
|
801
|
+
const requestDigest = sha256hex(canonicalJson(requestObj));
|
|
802
|
+
if (envelope["releaseId"] !== manifest["releaseId"]) {
|
|
803
|
+
return { ok: false, reason: `envelope.releaseId mismatch`, nonSafe: true };
|
|
804
|
+
}
|
|
805
|
+
if (envelope["sequence"] !== manifest["releaseSequence"]) {
|
|
806
|
+
return { ok: false, reason: `envelope.sequence mismatch`, nonSafe: true };
|
|
807
|
+
}
|
|
808
|
+
if (envelope["manifestDigest"] !== manifestDigest) {
|
|
809
|
+
return { ok: false, reason: `envelope.manifestDigest does not match manifest digest`, nonSafe: true };
|
|
810
|
+
}
|
|
811
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
812
|
+
if (typeof envelope["exp"] !== "number" || envelope["exp"] <= now) {
|
|
813
|
+
return { ok: false, reason: `bundle envelope expired (exp=${envelope["exp"]}, now=${now})`, nonSafe: true };
|
|
814
|
+
}
|
|
815
|
+
if (envelope["requestDigest"] !== requestDigest) {
|
|
816
|
+
return {
|
|
817
|
+
ok: false,
|
|
818
|
+
reason: `envelope.requestDigest mismatch \u2014 possible replay for a different scanId/request`,
|
|
819
|
+
nonSafe: true
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
try {
|
|
823
|
+
const { signature: _eSig, ...envelopeWithoutSig } = envelope;
|
|
824
|
+
const envPreimage = new TextEncoder().encode(
|
|
825
|
+
"shipguard-bundle-v1\0" + canonicalJson(envelopeWithoutSig)
|
|
826
|
+
);
|
|
827
|
+
await verifyBundleEnvelopeSignature(envPreimage, envelope["signature"], envelope["kid"]);
|
|
828
|
+
} catch (err) {
|
|
829
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
830
|
+
return { ok: false, reason: `envelope-verify-failed: ${msg}`, nonSafe: true };
|
|
831
|
+
}
|
|
832
|
+
const nowFresh = Math.floor(Date.now() / 1e3);
|
|
833
|
+
const issuedAt = freshnessTok["issuedAt"];
|
|
834
|
+
const expiresAt = freshnessTok["expiresAt"];
|
|
835
|
+
const CLOCK_SKEW = 300;
|
|
836
|
+
if (nowFresh > expiresAt + CLOCK_SKEW) {
|
|
837
|
+
return {
|
|
838
|
+
ok: false,
|
|
839
|
+
reason: `freshness token expired (expiresAt=${expiresAt}, now=${nowFresh})`,
|
|
840
|
+
nonSafe: true
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
if (nowFresh < issuedAt - CLOCK_SKEW) {
|
|
844
|
+
return {
|
|
845
|
+
ok: false,
|
|
846
|
+
reason: `freshness token issued in the future (issuedAt=${issuedAt}, now=${nowFresh})`,
|
|
847
|
+
nonSafe: true
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
if (expiresAt - issuedAt > 9e4) {
|
|
851
|
+
return {
|
|
852
|
+
ok: false,
|
|
853
|
+
reason: `freshness token TTL exceeds maximum 25 hours (${expiresAt - issuedAt}s)`,
|
|
854
|
+
nonSafe: true
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
if (freshnessTok["releaseId"] !== manifest["releaseId"]) {
|
|
858
|
+
return { ok: false, reason: `freshnessTok.releaseId mismatch`, nonSafe: true };
|
|
859
|
+
}
|
|
860
|
+
if (freshnessTok["sequence"] !== manifest["releaseSequence"]) {
|
|
861
|
+
return { ok: false, reason: `freshnessTok.sequence mismatch`, nonSafe: true };
|
|
862
|
+
}
|
|
863
|
+
if (freshnessTok["manifestDigest"] !== manifestDigest) {
|
|
864
|
+
return {
|
|
865
|
+
ok: false,
|
|
866
|
+
reason: `freshnessTok.manifestDigest mismatch \u2014 token bound to a different manifest (GC.4d)`,
|
|
867
|
+
nonSafe: true
|
|
868
|
+
};
|
|
869
|
+
}
|
|
870
|
+
try {
|
|
871
|
+
const { signature: _fSig, ...freshnessWithoutSig } = freshnessTok;
|
|
872
|
+
const freshPreimage = new TextEncoder().encode(
|
|
873
|
+
"shipguard-freshness-v1\0" + canonicalJson(freshnessWithoutSig)
|
|
874
|
+
);
|
|
875
|
+
await verifyFreshness(freshPreimage, freshnessTok["signature"], freshnessTok["kid"]);
|
|
876
|
+
} catch (err) {
|
|
877
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
878
|
+
return { ok: false, reason: `freshness-verify-failed: ${msg}`, nonSafe: true };
|
|
879
|
+
}
|
|
880
|
+
const manifestRuleMap = /* @__PURE__ */ new Map();
|
|
881
|
+
for (const r of manifestRules) {
|
|
882
|
+
const rEntry = r;
|
|
883
|
+
manifestRuleMap.set(rEntry["id"], rEntry);
|
|
884
|
+
}
|
|
885
|
+
const deliveredWithHashes = [];
|
|
886
|
+
for (const rawRule of deliveredRulesRaw) {
|
|
887
|
+
const ruleObj = rawRule;
|
|
888
|
+
const ruleId = ruleObj["id"];
|
|
889
|
+
let recomputedHash;
|
|
890
|
+
try {
|
|
891
|
+
recomputedHash = computeExecutableHash(ruleObj);
|
|
892
|
+
} catch (err) {
|
|
893
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
894
|
+
return { ok: false, reason: `rule-hash-compute-failed for "${ruleId}": ${msg}`, nonSafe: true };
|
|
895
|
+
}
|
|
896
|
+
const manifestEntry = manifestRuleMap.get(ruleId);
|
|
897
|
+
if (!manifestEntry) {
|
|
898
|
+
return {
|
|
899
|
+
ok: false,
|
|
900
|
+
reason: `delivered rule "${ruleId}" not found in manifest`,
|
|
901
|
+
nonSafe: true
|
|
902
|
+
};
|
|
903
|
+
}
|
|
904
|
+
if (manifestEntry["executableHash"] !== recomputedHash) {
|
|
905
|
+
return {
|
|
906
|
+
ok: false,
|
|
907
|
+
reason: `rule "${ruleId}" hash mismatch: manifest="${manifestEntry["executableHash"]}", recomputed="${recomputedHash}"`,
|
|
908
|
+
nonSafe: true
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
deliveredWithHashes.push({
|
|
912
|
+
id: ruleId,
|
|
913
|
+
executableHash: recomputedHash,
|
|
914
|
+
rule: ruleObj
|
|
915
|
+
});
|
|
916
|
+
}
|
|
917
|
+
const manifestForSelector = manifest;
|
|
918
|
+
let expectedSet;
|
|
919
|
+
try {
|
|
920
|
+
expectedSet = selectExpected(manifestForSelector, {
|
|
921
|
+
frameworks: request.frameworks,
|
|
922
|
+
isPro: request.isPro ?? false
|
|
923
|
+
});
|
|
924
|
+
} catch (err) {
|
|
925
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
926
|
+
return { ok: false, reason: `select-expected-failed: ${msg}`, nonSafe: true };
|
|
927
|
+
}
|
|
928
|
+
const deliveredPairs = deliveredWithHashes.map((d) => ({ id: d.id, executableHash: d.executableHash }));
|
|
929
|
+
const exactSetResult = verifyExactSet(deliveredPairs, expectedSet);
|
|
930
|
+
if (!exactSetResult.ok) {
|
|
931
|
+
const violations = exactSetResult.violations.map((v) => `${v.type}:${v.ruleId}`).join(", ");
|
|
932
|
+
return {
|
|
933
|
+
ok: false,
|
|
934
|
+
reason: `completeness-mismatch: ${violations}`,
|
|
935
|
+
nonSafe: true
|
|
936
|
+
};
|
|
937
|
+
}
|
|
938
|
+
const envelopeExpected = envelope["expectedRuleSet"];
|
|
939
|
+
if (!Array.isArray(envelopeExpected)) {
|
|
940
|
+
return { ok: false, reason: "bundleEnvelope.expectedRuleSet is not an array", nonSafe: true };
|
|
941
|
+
}
|
|
942
|
+
const envelopeSetResult = verifyExactSet(envelopeExpected, expectedSet);
|
|
943
|
+
if (!envelopeSetResult.ok) {
|
|
944
|
+
const violations = envelopeSetResult.violations.map((v) => `${v.type}:${v.ruleId}`).join(", ");
|
|
945
|
+
return {
|
|
946
|
+
ok: false,
|
|
947
|
+
reason: `envelope.expectedRuleSet mismatch: ${violations}`,
|
|
948
|
+
nonSafe: true
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
if (manifest["matcherRuntimeId"] !== RE2JS_V1_RUNTIME_ID) {
|
|
952
|
+
return {
|
|
953
|
+
ok: false,
|
|
954
|
+
reason: `matcherRuntimeId mismatch: manifest="${manifest["matcherRuntimeId"]}", CLI="${RE2JS_V1_RUNTIME_ID}"`,
|
|
955
|
+
nonSafe: true
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
const incomingSequence = manifest["releaseSequence"];
|
|
959
|
+
const incomingReleaseId = manifest["releaseId"];
|
|
960
|
+
if (incomingSequence < MIN_ACCEPTABLE_SEQUENCE) {
|
|
961
|
+
return {
|
|
962
|
+
ok: false,
|
|
963
|
+
reason: `sequence ${incomingSequence} is below MIN_ACCEPTABLE_SEQUENCE ${MIN_ACCEPTABLE_SEQUENCE}`,
|
|
964
|
+
nonSafe: true
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
const attestationEntry = KEYRING.find((e) => e.kid === attestation["kid"]);
|
|
968
|
+
const incomingKeyringEpoch = attestationEntry?.epoch ?? 1;
|
|
969
|
+
const incomingTuple = {
|
|
970
|
+
sequence: incomingSequence,
|
|
971
|
+
releaseId: incomingReleaseId,
|
|
972
|
+
manifestDigest,
|
|
973
|
+
keyringEpoch: incomingKeyringEpoch
|
|
974
|
+
};
|
|
975
|
+
let floorResult;
|
|
976
|
+
try {
|
|
977
|
+
floorResult = atomicAcceptFloor(floorPath, incomingTuple);
|
|
978
|
+
} catch (err) {
|
|
979
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
980
|
+
return {
|
|
981
|
+
ok: false,
|
|
982
|
+
reason: `floor-write-failure: ${msg}`,
|
|
983
|
+
nonSafe: true
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
if ("corrupt" in floorResult) {
|
|
987
|
+
return {
|
|
988
|
+
ok: false,
|
|
989
|
+
reason: `floor-corruption: ${floorResult.reason}`,
|
|
990
|
+
nonSafe: true
|
|
991
|
+
};
|
|
992
|
+
}
|
|
993
|
+
if (!floorResult.accepted) {
|
|
994
|
+
return {
|
|
995
|
+
ok: false,
|
|
996
|
+
reason: floorResult.reason,
|
|
997
|
+
nonSafe: true
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
const selectedRules = deliveredWithHashes.map((d) => d.rule);
|
|
1001
|
+
return { ok: true, selectedRules };
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
// src/core/pro-scanner.ts
|
|
1005
|
+
import { minimatch } from "minimatch";
|
|
1006
|
+
|
|
1007
|
+
// src/core/re2-detector-engine.ts
|
|
1008
|
+
import { RE2JS } from "re2js";
|
|
1009
|
+
function toRe2jsFlags(flags) {
|
|
1010
|
+
let bits = 0;
|
|
1011
|
+
if (flags.has("i")) bits |= RE2JS.CASE_INSENSITIVE;
|
|
1012
|
+
if (flags.has("m")) bits |= RE2JS.MULTILINE;
|
|
1013
|
+
if (flags.has("s")) bits |= RE2JS.DOTALL;
|
|
1014
|
+
return bits;
|
|
1015
|
+
}
|
|
1016
|
+
function compileDetectorRegex(source, flags = "") {
|
|
1017
|
+
if (flags.includes("g")) {
|
|
1018
|
+
throw new Error(
|
|
1019
|
+
`[re2-detector-engine] 'g' flag is not allowed \u2014 use matchAll() for all-matches iteration. Pattern: ${JSON.stringify(source)}`
|
|
1020
|
+
);
|
|
1021
|
+
}
|
|
1022
|
+
const parsed = parseFlags(flags);
|
|
1023
|
+
if (!parsed.ok) {
|
|
1024
|
+
throw new Error(
|
|
1025
|
+
`[re2-detector-engine] Invalid flags ${JSON.stringify(flags)}: ${parsed.reason}. Pattern: ${JSON.stringify(source)}`
|
|
1026
|
+
);
|
|
1027
|
+
}
|
|
1028
|
+
const re2jsFlags = toRe2jsFlags(parsed.flags);
|
|
1029
|
+
let compiled;
|
|
1030
|
+
try {
|
|
1031
|
+
compiled = RE2JS.compile(source, re2jsFlags);
|
|
1032
|
+
} catch (err) {
|
|
1033
|
+
throw new Error(
|
|
1034
|
+
`[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)}`
|
|
1035
|
+
);
|
|
1036
|
+
}
|
|
1037
|
+
return {
|
|
1038
|
+
test(input) {
|
|
1039
|
+
return compiled.matcher(input).find();
|
|
1040
|
+
},
|
|
1041
|
+
exec(input) {
|
|
1042
|
+
const m = compiled.matcher(input);
|
|
1043
|
+
if (!m.find()) return null;
|
|
1044
|
+
const groupCount = compiled.groupCount();
|
|
1045
|
+
const groups = [];
|
|
1046
|
+
for (let g = 1; g <= groupCount; g++) {
|
|
1047
|
+
const gv = m.group(g);
|
|
1048
|
+
groups.push(gv === null ? void 0 : gv);
|
|
1049
|
+
}
|
|
1050
|
+
return {
|
|
1051
|
+
match: m.group() ?? "",
|
|
1052
|
+
index: m.start(),
|
|
1053
|
+
groups
|
|
1054
|
+
};
|
|
1055
|
+
},
|
|
1056
|
+
matchAll(input) {
|
|
1057
|
+
const results = [];
|
|
1058
|
+
const m = compiled.matcher(input);
|
|
1059
|
+
const groupCount = compiled.groupCount();
|
|
1060
|
+
let searchFrom = void 0;
|
|
1061
|
+
while (true) {
|
|
1062
|
+
const found = searchFrom !== void 0 ? m.find(searchFrom) : m.find();
|
|
1063
|
+
if (!found) break;
|
|
1064
|
+
const start = m.start();
|
|
1065
|
+
const end = m.end();
|
|
1066
|
+
const groups = [];
|
|
1067
|
+
for (let g = 1; g <= groupCount; g++) {
|
|
1068
|
+
const gv = m.group(g);
|
|
1069
|
+
groups.push(gv === null ? void 0 : gv);
|
|
1070
|
+
}
|
|
1071
|
+
results.push({
|
|
1072
|
+
match: m.group() ?? "",
|
|
1073
|
+
index: start,
|
|
1074
|
+
groups
|
|
1075
|
+
});
|
|
1076
|
+
if (start === end) {
|
|
1077
|
+
searchFrom = start + 1;
|
|
1078
|
+
if (start >= input.length) break;
|
|
1079
|
+
} else {
|
|
1080
|
+
searchFrom = void 0;
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
return results;
|
|
1084
|
+
},
|
|
1085
|
+
replaceFirst(input, replacement) {
|
|
1086
|
+
const m = compiled.matcher(input);
|
|
1087
|
+
if (!m.find()) return input;
|
|
1088
|
+
const start = m.start();
|
|
1089
|
+
const end = m.end();
|
|
1090
|
+
return input.slice(0, start) + replacement + input.slice(end);
|
|
1091
|
+
},
|
|
1092
|
+
replace(input, replacement) {
|
|
1093
|
+
return compiled.matcher(input).replaceAll(replacement);
|
|
1094
|
+
}
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
// src/checks/secrets.ts
|
|
1099
|
+
function redact(value) {
|
|
1100
|
+
if (value.length <= 8) return "***";
|
|
1101
|
+
return value.slice(0, 8) + "***";
|
|
1102
|
+
}
|
|
1103
|
+
var SAFE_EXCLUSIONS_RE = compileDetectorRegex(`\\.(example|sample|template|dist|tmpl|test)$`, "i");
|
|
1104
|
+
var FRONTEND_PATH_RE = compileDetectorRegex(`^(app|pages|components|src\\/(app|pages|components))\\/`);
|
|
1105
|
+
function isDotEnvFile(relativePath) {
|
|
1106
|
+
const basename2 = relativePath.split("/").pop() ?? relativePath;
|
|
1107
|
+
if (!basename2.startsWith(".env")) return false;
|
|
1108
|
+
return !SAFE_EXCLUSIONS_RE.test(basename2);
|
|
1109
|
+
}
|
|
1110
|
+
function isFrontendFile(relativePath) {
|
|
1111
|
+
return FRONTEND_PATH_RE.test(relativePath);
|
|
1112
|
+
}
|
|
1113
|
+
var SECRET_PATTERNS = [
|
|
1114
|
+
// OpenAI — sk-proj-... (new format)
|
|
1115
|
+
{
|
|
1116
|
+
id: "hardcoded_secret",
|
|
1117
|
+
name: "OpenAI API Key",
|
|
1118
|
+
compiled: compileDetectorRegex(`['"]?(sk-proj-[a-zA-Z0-9_\\-]{20,})['"]?`, "m"),
|
|
1119
|
+
severity: "high",
|
|
1120
|
+
confidence: "HIGH",
|
|
1121
|
+
explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
|
|
1122
|
+
recommendation: "Remove the key from source code. Use process.env.OPENAI_API_KEY and store the value in a .env file that is gitignored."
|
|
1123
|
+
},
|
|
1124
|
+
// OpenAI — sk-... (legacy format) via variable name context
|
|
1125
|
+
{
|
|
1126
|
+
id: "hardcoded_secret",
|
|
1127
|
+
name: "OpenAI Legacy API Key",
|
|
1128
|
+
compiled: compileDetectorRegex(
|
|
1129
|
+
`(?:openai[_\\-]?(?:api[_\\-]?)?key|OPENAI[_\\-]?(?:API[_\\-]?)?KEY)\\s*[=:]\\s*['"]?(sk-[a-zA-Z0-9]{20,})['"]?`,
|
|
1130
|
+
"im"
|
|
1131
|
+
),
|
|
1132
|
+
severity: "high",
|
|
1133
|
+
confidence: "HIGH",
|
|
1134
|
+
explanation: "Hardcoded OpenAI API key detected. Leaking this key allows unauthorized use of your OpenAI account, incurring charges.",
|
|
1135
|
+
recommendation: "Remove the key from source code. Use process.env.OPENAI_API_KEY and store the value in a .env file that is gitignored."
|
|
1136
|
+
},
|
|
1137
|
+
// Anthropic — sk-ant-api03-...
|
|
1138
|
+
{
|
|
1139
|
+
id: "hardcoded_secret",
|
|
1140
|
+
name: "Anthropic API Key",
|
|
1141
|
+
compiled: compileDetectorRegex(`['"]?(sk-ant-(?:api\\d+-)?[a-zA-Z0-9_\\-]{20,})['"]?`, "im"),
|
|
1142
|
+
severity: "high",
|
|
1143
|
+
confidence: "HIGH",
|
|
1144
|
+
explanation: "Hardcoded Anthropic API key detected. Leaking this key allows unauthorized use of Anthropic Claude, incurring charges.",
|
|
1145
|
+
recommendation: "Remove the key from source code. Use process.env.ANTHROPIC_API_KEY and store the value in a .env file that is gitignored."
|
|
1146
|
+
},
|
|
1147
|
+
// Stripe live secret key
|
|
1148
|
+
{
|
|
1149
|
+
id: "hardcoded_secret",
|
|
1150
|
+
name: "Stripe Live Secret Key",
|
|
1151
|
+
compiled: compileDetectorRegex(`['"]?(sk_live_[a-zA-Z0-9]{24,})['"]?`, "im"),
|
|
1152
|
+
severity: "critical",
|
|
1153
|
+
confidence: "HIGH",
|
|
1154
|
+
explanation: "Hardcoded Stripe live secret key detected. This key can be used to make charges, refunds, and access customer data in your live Stripe account.",
|
|
1155
|
+
recommendation: "Remove immediately. Use process.env.STRIPE_SECRET_KEY. Rotate the key in the Stripe Dashboard."
|
|
1156
|
+
},
|
|
1157
|
+
// Stripe test secret key
|
|
1158
|
+
{
|
|
1159
|
+
id: "hardcoded_secret",
|
|
1160
|
+
name: "Stripe Test Secret Key",
|
|
1161
|
+
compiled: compileDetectorRegex(`['"]?(sk_test_[a-zA-Z0-9]{24,})['"]?`, "im"),
|
|
1162
|
+
severity: "medium",
|
|
1163
|
+
confidence: "HIGH",
|
|
1164
|
+
explanation: "Hardcoded Stripe test secret key detected. While test keys cannot process real payments, committing them is a bad practice that often leads to live key exposure.",
|
|
1165
|
+
recommendation: "Remove from source code. Use process.env.STRIPE_SECRET_KEY with a .env file that is gitignored."
|
|
1166
|
+
},
|
|
1167
|
+
// AWS access key ID
|
|
1168
|
+
{
|
|
1169
|
+
id: "hardcoded_secret",
|
|
1170
|
+
name: "AWS Access Key ID",
|
|
1171
|
+
compiled: compileDetectorRegex(`['"]?(AKIA[0-9A-Z]{16})['"]?`, "m"),
|
|
1172
|
+
severity: "high",
|
|
1173
|
+
confidence: "HIGH",
|
|
1174
|
+
explanation: "Hardcoded AWS Access Key ID detected. Combined with the secret key, this allows full AWS API access under your account.",
|
|
1175
|
+
recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
|
|
1176
|
+
},
|
|
1177
|
+
// AWS secret access key
|
|
1178
|
+
{
|
|
1179
|
+
id: "hardcoded_secret",
|
|
1180
|
+
name: "AWS Secret Access Key",
|
|
1181
|
+
compiled: compileDetectorRegex(
|
|
1182
|
+
`(?:aws[_\\-]?secret[_\\-]?(?:access[_\\-]?)?key|AWS_SECRET_ACCESS_KEY)\\s*[=:]\\s*['"]?([a-zA-Z0-9\\/+]{40})['"]?`,
|
|
1183
|
+
"im"
|
|
1184
|
+
),
|
|
1185
|
+
severity: "high",
|
|
1186
|
+
confidence: "HIGH",
|
|
1187
|
+
explanation: "Hardcoded AWS Secret Access Key detected. This credential enables full programmatic access to AWS services.",
|
|
1188
|
+
recommendation: "Remove and rotate immediately via IAM. Use environment variables or AWS credential profiles instead."
|
|
1189
|
+
},
|
|
1190
|
+
// Google API key
|
|
1191
|
+
{
|
|
1192
|
+
id: "hardcoded_secret",
|
|
1193
|
+
name: "Google API Key",
|
|
1194
|
+
compiled: compileDetectorRegex(`['"]?(AIza[0-9A-Za-z\\-_]{35})['"]?`, "m"),
|
|
1195
|
+
severity: "high",
|
|
1196
|
+
confidence: "HIGH",
|
|
1197
|
+
explanation: "Hardcoded Google API key detected. This key can be used to access Google Cloud services or Google Maps, incurring charges.",
|
|
1198
|
+
recommendation: "Remove from source code. Restrict key usage in the Google Cloud Console and use environment variables."
|
|
1199
|
+
},
|
|
1200
|
+
// GitHub personal access token (classic ghp_ and fine-grained github_pat_)
|
|
1201
|
+
{
|
|
1202
|
+
id: "hardcoded_secret",
|
|
1203
|
+
name: "GitHub Personal Access Token",
|
|
1204
|
+
compiled: compileDetectorRegex(`['"]?(ghp_[a-zA-Z0-9]{36}|github_pat_[a-zA-Z0-9_]{82})['"]?`, "m"),
|
|
1205
|
+
severity: "high",
|
|
1206
|
+
confidence: "HIGH",
|
|
1207
|
+
explanation: "Hardcoded GitHub Personal Access Token detected. This token grants access to GitHub repositories and actions under your account.",
|
|
1208
|
+
recommendation: "Remove and revoke the token at github.com/settings/tokens. Use environment variables."
|
|
1209
|
+
},
|
|
1210
|
+
// Razorpay live secret key
|
|
1211
|
+
{
|
|
1212
|
+
id: "hardcoded_secret",
|
|
1213
|
+
name: "Razorpay Secret Key",
|
|
1214
|
+
compiled: compileDetectorRegex(
|
|
1215
|
+
`(?:razorpay[_\\-]?(?:key[_\\-]?)?secret|RAZORPAY_KEY_SECRET)\\s*[=:]\\s*['"]?([a-zA-Z0-9]{20,})['"]?`,
|
|
1216
|
+
"im"
|
|
1217
|
+
),
|
|
1218
|
+
severity: "high",
|
|
1219
|
+
confidence: "HIGH",
|
|
1220
|
+
explanation: "Hardcoded Razorpay secret key detected. This allows unauthorized access to your Razorpay payment account.",
|
|
1221
|
+
recommendation: "Remove from source code. Use process.env.RAZORPAY_KEY_SECRET and store in a gitignored .env file."
|
|
1222
|
+
},
|
|
1223
|
+
// JWT secret
|
|
1224
|
+
{
|
|
1225
|
+
id: "hardcoded_secret",
|
|
1226
|
+
name: "JWT Secret",
|
|
1227
|
+
compiled: compileDetectorRegex(
|
|
1228
|
+
`(?:jwt[_\\-]?secret|JWT_SECRET)\\s*[=:]\\s*['"]([^'"]{16,})['"]?`,
|
|
1229
|
+
"im"
|
|
1230
|
+
),
|
|
1231
|
+
severity: "high",
|
|
1232
|
+
confidence: "HIGH",
|
|
1233
|
+
explanation: "Hardcoded JWT secret detected. Exposing this allows attackers to forge valid JWT tokens and bypass authentication.",
|
|
1234
|
+
recommendation: "Remove from source code. Generate a strong random secret, store it in environment variables."
|
|
1235
|
+
},
|
|
1236
|
+
// Database URL with embedded credentials
|
|
1237
|
+
{
|
|
1238
|
+
id: "hardcoded_secret",
|
|
1239
|
+
name: "Database URL with Credentials",
|
|
1240
|
+
compiled: compileDetectorRegex(
|
|
1241
|
+
`(?:(?:database[_\\-]?url|DATABASE_URL|db[_\\-]?url|DB_URL|connection[_\\-]?string|CONNECTION_STRING)\\s*[=:]\\s*)?['"]?((?:postgres|postgresql|mysql|mongodb|mongodb\\+srv|redis|amqp|rabbitmq):\\/\\/[^:'"]+:[^@'"]+@[^'"]+)['"]?`,
|
|
1242
|
+
"im"
|
|
1243
|
+
),
|
|
1244
|
+
severity: "critical",
|
|
1245
|
+
confidence: "HIGH",
|
|
1246
|
+
explanation: "Database URL with embedded credentials detected. This exposes the database host, username, and password directly.",
|
|
1247
|
+
recommendation: "Remove credentials from the URL. Use environment variables and ensure the .env file is gitignored."
|
|
1248
|
+
},
|
|
1249
|
+
// Generic assignment: VAR = "long-base64/alphanumeric string"
|
|
1250
|
+
// D.4 REWRITE: Removed native negative-lookahead (?!\s*\+|\.) — not supported by re2js.
|
|
1251
|
+
// Equivalent behavior is achieved via postExcludeFollowedBy() which checks the
|
|
1252
|
+
// character immediately after the closing quote. See DIFFERENTIAL NOTE above.
|
|
1253
|
+
{
|
|
1254
|
+
id: "hardcoded_secret",
|
|
1255
|
+
name: "High-Entropy Secret String",
|
|
1256
|
+
compiled: compileDetectorRegex(
|
|
1257
|
+
`(?:api[_\\-]?key|secret|token|password|passwd|auth[_\\-]?key|access[_\\-]?key)\\s*[=:]\\s*['"]([a-zA-Z0-9\\/+_\\-]{32,64})['"]`,
|
|
1258
|
+
"im"
|
|
1259
|
+
),
|
|
1260
|
+
severity: "medium",
|
|
1261
|
+
confidence: "MEDIUM",
|
|
1262
|
+
explanation: "A variable with a secret-sounding name is assigned a long literal string that resembles an API key or token.",
|
|
1263
|
+
recommendation: "Move this value to a .env file and reference it via process.env. Never hardcode credentials.",
|
|
1264
|
+
// Exact equivalent of native negative-lookahead (?!\s*\+|\.) — suppress the
|
|
1265
|
+
// match iff the text immediately following it matches EITHER:
|
|
1266
|
+
// (a) \s*\+ — zero or more JS-whitespace chars then a literal '+'
|
|
1267
|
+
// (b) \. — an IMMEDIATE dot (no leading whitespace; the alternation has no \s*)
|
|
1268
|
+
// Algorithm uses plain string operations only (no native RegExp, no ReDoS risk):
|
|
1269
|
+
// 1. Immediate dot -> suppress.
|
|
1270
|
+
// 2. Skip JS \s chars (code points: 0x09 0x0a 0x0b 0x0c 0x0d 0x20 0xa0
|
|
1271
|
+
// 0x1680 0x2000-0x200a 0x2028 0x2029 0x202f 0x205f 0x3000 0xfeff);
|
|
1272
|
+
// if the first non-ws char is '+' -> suppress.
|
|
1273
|
+
// 3. Otherwise -> KEEP (flag the secret).
|
|
1274
|
+
postExcludeFollowedBy: (restAfterMatch) => {
|
|
1275
|
+
if (restAfterMatch.length === 0) return false;
|
|
1276
|
+
if (restAfterMatch[0] === ".") return true;
|
|
1277
|
+
let i = 0;
|
|
1278
|
+
while (i < restAfterMatch.length) {
|
|
1279
|
+
const cp = restAfterMatch.codePointAt(i) ?? 0;
|
|
1280
|
+
if (cp === 9 || cp === 10 || cp === 11 || cp === 12 || cp === 13 || cp === 32 || cp === 160 || cp === 5760 || cp >= 8192 && cp <= 8202 || cp === 8232 || cp === 8233 || cp === 8239 || cp === 8287 || cp === 12288 || cp === 65279) {
|
|
1281
|
+
i++;
|
|
1282
|
+
} else {
|
|
1283
|
+
break;
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
return restAfterMatch[i] === "+";
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
];
|
|
1290
|
+
var PRIVATE_KEY_RE = compileDetectorRegex(
|
|
1291
|
+
`-----BEGIN\\s(?:RSA\\s|EC\\s|DSA\\s|OPENSSH\\s|ENCRYPTED\\s)?PRIVATE KEY-----`,
|
|
1292
|
+
"m"
|
|
1293
|
+
);
|
|
1294
|
+
var NEXT_PUBLIC_SECRET_RE = compileDetectorRegex(
|
|
1295
|
+
`NEXT_PUBLIC_(?:[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD|AUTH)[A-Z_]*)=['"']?([a-zA-Z0-9\\/+_\\-]{16,})['"']?`,
|
|
1296
|
+
"m"
|
|
1297
|
+
);
|
|
1298
|
+
var ENV_REFERENCE_ONLY_RE = compileDetectorRegex(`process\\.env\\.[A-Z_]+`);
|
|
1299
|
+
var LITERAL_ASSIGN_RE = compileDetectorRegex(`=\\s*['"]`);
|
|
1300
|
+
var LINE_COMMENT_RE = compileDetectorRegex(`^\\s*(\\/\\/|#)`, "m");
|
|
1301
|
+
function checkSecrets(files, policy) {
|
|
1302
|
+
const findings = [];
|
|
1303
|
+
for (const file of files) {
|
|
1304
|
+
const { content, relativePath } = file;
|
|
1305
|
+
if (isDotEnvFile(relativePath)) {
|
|
1306
|
+
const id = "exposed_env";
|
|
1307
|
+
findings.push({
|
|
1308
|
+
id,
|
|
1309
|
+
title: ".env file tracked in git",
|
|
1310
|
+
severity: "high",
|
|
1311
|
+
category: "secrets",
|
|
1312
|
+
file: relativePath,
|
|
1313
|
+
confidence: "HIGH",
|
|
1314
|
+
explanation: "A .env file is tracked in the repository. These files often contain secrets such as API keys, database credentials, and tokens that should never be committed.",
|
|
1315
|
+
recommendation: "Add .env (and its variants like .env.local, .env.production) to .gitignore. Remove the file from git history using `git rm --cached .env`.",
|
|
1316
|
+
blocking: policy.block.includes(id)
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
const pkExec = PRIVATE_KEY_RE.exec(content);
|
|
1320
|
+
if (pkExec) {
|
|
1321
|
+
const lineNum = content.slice(0, pkExec.index).split("\n").length;
|
|
1322
|
+
const id = "hardcoded_secret";
|
|
1323
|
+
findings.push({
|
|
1324
|
+
id,
|
|
1325
|
+
title: "Private key block in source",
|
|
1326
|
+
severity: "critical",
|
|
1327
|
+
category: "secrets",
|
|
1328
|
+
file: relativePath,
|
|
1329
|
+
line: lineNum,
|
|
1330
|
+
evidence: pkExec.match.trim(),
|
|
1331
|
+
confidence: "HIGH",
|
|
1332
|
+
explanation: "A PEM private key block is embedded in the source file. This exposes cryptographic material that can be used to impersonate services, decrypt data, or forge signatures.",
|
|
1333
|
+
recommendation: "Remove the private key from the codebase immediately. Store keys in a secrets manager (e.g., AWS Secrets Manager, Vault) or as environment variables.",
|
|
1334
|
+
blocking: policy.block.includes(id)
|
|
1335
|
+
});
|
|
1336
|
+
}
|
|
1337
|
+
if (isFrontendFile(relativePath)) {
|
|
1338
|
+
const lines2 = content.split("\n");
|
|
1339
|
+
for (let i = 0; i < lines2.length; i++) {
|
|
1340
|
+
const line = lines2[i];
|
|
1341
|
+
const match = NEXT_PUBLIC_SECRET_RE.exec(line);
|
|
1342
|
+
if (match && match.groups[0]) {
|
|
1343
|
+
const id = "exposed_env";
|
|
1344
|
+
findings.push({
|
|
1345
|
+
id,
|
|
1346
|
+
title: "Secret exposed via NEXT_PUBLIC_ prefix",
|
|
1347
|
+
severity: "critical",
|
|
1348
|
+
category: "secrets",
|
|
1349
|
+
file: relativePath,
|
|
1350
|
+
line: i + 1,
|
|
1351
|
+
evidence: `${line.split("=")[0].trim()}=${redact(match.groups[0])}`,
|
|
1352
|
+
confidence: "HIGH",
|
|
1353
|
+
explanation: "An environment variable with NEXT_PUBLIC_ prefix containing a secret-sounding name is used in a frontend file. NEXT_PUBLIC_ variables are bundled into client-side JavaScript and exposed to all users.",
|
|
1354
|
+
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.",
|
|
1355
|
+
blocking: policy.block.includes(id)
|
|
1356
|
+
});
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
const lines = content.split("\n");
|
|
1361
|
+
for (const pattern of SECRET_PATTERNS) {
|
|
1362
|
+
if (!pattern.compiled.test(content)) continue;
|
|
1363
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1364
|
+
const line = lines[i];
|
|
1365
|
+
if (ENV_REFERENCE_ONLY_RE.test(line) && !line.includes("'") && !line.includes('"') && !line.includes("`")) continue;
|
|
1366
|
+
if (LINE_COMMENT_RE.test(line)) continue;
|
|
1367
|
+
const lineMatches = pattern.compiled.matchAll(line);
|
|
1368
|
+
for (const lineMatch of lineMatches) {
|
|
1369
|
+
if (pattern.postExcludeFollowedBy !== void 0) {
|
|
1370
|
+
const charAfterIndex = lineMatch.index + lineMatch.match.length;
|
|
1371
|
+
const restAfterMatch = line.slice(charAfterIndex);
|
|
1372
|
+
if (pattern.postExcludeFollowedBy(restAfterMatch)) continue;
|
|
1373
|
+
}
|
|
1374
|
+
const secretValue = lineMatch.groups[0] ?? lineMatch.match;
|
|
1375
|
+
findings.push({
|
|
1376
|
+
id: pattern.id,
|
|
1377
|
+
title: pattern.name,
|
|
1378
|
+
severity: pattern.severity,
|
|
1379
|
+
category: "secrets",
|
|
1380
|
+
file: relativePath,
|
|
1381
|
+
line: i + 1,
|
|
1382
|
+
evidence: `...${redact(secretValue)}...`,
|
|
1383
|
+
confidence: pattern.confidence,
|
|
1384
|
+
explanation: pattern.explanation,
|
|
1385
|
+
recommendation: pattern.recommendation,
|
|
1386
|
+
blocking: policy.block.includes(pattern.id)
|
|
1387
|
+
});
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
return findings;
|
|
1393
|
+
}
|
|
1394
|
+
var secretsCheck = {
|
|
1395
|
+
id: "secrets",
|
|
1396
|
+
name: "Secrets & Environment Leaks",
|
|
1397
|
+
run: checkSecrets
|
|
1398
|
+
};
|
|
1399
|
+
|
|
1400
|
+
// src/checks/auth.ts
|
|
1401
|
+
var SENSITIVE_NEXTJS_PAGE_PATTERN = /^(?:src\/)?app\/(admin|dashboard|billing|account|settings|management)(\/|$)/;
|
|
1402
|
+
var SENSITIVE_API_ROUTE_PATTERN = /^(?:src\/)?app\/api\/(admin|users|billing|account|management)(\/|$)/;
|
|
1403
|
+
var SENSITIVE_EXPRESS_PATHS = /\/(admin|users|billing|account|management)(\/|$)/;
|
|
1404
|
+
var WEBHOOK_PATH_PATTERN = /\/webhooks?\//;
|
|
1405
|
+
var RE2_EXPRESS_ROUTE_DEFINITION = compileDetectorRegex(
|
|
1406
|
+
`(?:router|app)\\.(get|post|put|patch|delete|all)\\s*\\(\\s*['"\`]([^'"\`,)]+)['"\`]`,
|
|
1407
|
+
"i"
|
|
1408
|
+
);
|
|
1409
|
+
var RE2_AUTH_CALL_PATTERN = compileDetectorRegex(
|
|
1410
|
+
`(?:auth|getServerSession|requireAuth|verifyToken|withAuth|clerkMiddleware|authMiddleware)\\s*\\(`
|
|
1411
|
+
);
|
|
1412
|
+
var RE2_COMMENTED_AUTH_PATTERN = compileDetectorRegex(
|
|
1413
|
+
`^\\s*(?:\\/\\/|\\/\\*|\\*)[^\\n]*(?:auth|getServerSession|requireAuth|verifyToken)\\s*\\(`,
|
|
1414
|
+
"m"
|
|
1415
|
+
);
|
|
1416
|
+
var RE2_EXPRESS_AUTH_MIDDLEWARE_PATTERN = compileDetectorRegex(
|
|
1417
|
+
`(?:router|app)\\.use\\s*\\([^)]*(?:auth|requireAuth|verifyToken|isAuth|isLogged|passport)\\w*`,
|
|
1418
|
+
"i"
|
|
1419
|
+
);
|
|
1420
|
+
var RE2_MIDDLEWARE_ADMIN_COVERAGE = compileDetectorRegex(
|
|
1421
|
+
`(?:admin|dashboard|billing|account|management)`
|
|
1422
|
+
);
|
|
1423
|
+
var RE2_INLINE_AUTH_CHECK = compileDetectorRegex(
|
|
1424
|
+
`requireAuth|verifyToken|isAuth|isLogged|passport\\.authenticate`,
|
|
1425
|
+
"i"
|
|
1426
|
+
);
|
|
1427
|
+
var MIDDLEWARE_FILE_PATTERN = /^(?:src\/)?middleware\.[tj]s$/;
|
|
1428
|
+
var NEXT_APP_ROUTER_PATH = /^(?:src\/)?(?:app\/|app$)/;
|
|
1429
|
+
var NEXT_CONFIG_FILE = /^(?:src\/)?next\.config\.[cm]?[jt]s$/;
|
|
1430
|
+
function isNextjsProject(files) {
|
|
1431
|
+
for (const f of files) {
|
|
1432
|
+
if (NEXT_APP_ROUTER_PATH.test(f.relativePath)) return true;
|
|
1433
|
+
if (NEXT_CONFIG_FILE.test(f.relativePath)) return true;
|
|
1434
|
+
if (f.relativePath === "package.json" || f.relativePath.endsWith("/package.json")) {
|
|
1435
|
+
try {
|
|
1436
|
+
const pkg = JSON.parse(f.content);
|
|
1437
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
1438
|
+
if ("next" in deps) return true;
|
|
1439
|
+
} catch {
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
return false;
|
|
1444
|
+
}
|
|
1445
|
+
function lexInterpolationBody(src, start) {
|
|
1446
|
+
const len = src.length;
|
|
1447
|
+
let i = start;
|
|
1448
|
+
let depth = 1;
|
|
1449
|
+
const execParts = [];
|
|
1450
|
+
while (i < len && depth > 0) {
|
|
1451
|
+
const ch = src[i];
|
|
1452
|
+
if (ch === "{") {
|
|
1453
|
+
execParts.push(ch);
|
|
1454
|
+
depth++;
|
|
1455
|
+
i++;
|
|
1456
|
+
continue;
|
|
1457
|
+
}
|
|
1458
|
+
if (ch === "}") {
|
|
1459
|
+
depth--;
|
|
1460
|
+
if (depth > 0) {
|
|
1461
|
+
execParts.push(ch);
|
|
1462
|
+
i++;
|
|
1463
|
+
}
|
|
1464
|
+
break;
|
|
1465
|
+
}
|
|
1466
|
+
if (ch === "/" && i + 1 < len && src[i + 1] === "/") {
|
|
1467
|
+
i += 2;
|
|
1468
|
+
while (i < len && src[i] !== "\n") i++;
|
|
1469
|
+
continue;
|
|
1470
|
+
}
|
|
1471
|
+
if (ch === "/" && i + 1 < len && src[i + 1] === "*") {
|
|
1472
|
+
i += 2;
|
|
1473
|
+
while (i < len - 1) {
|
|
1474
|
+
if (src[i] === "*" && src[i + 1] === "/") {
|
|
1475
|
+
i += 2;
|
|
1476
|
+
break;
|
|
1477
|
+
}
|
|
1478
|
+
i++;
|
|
1479
|
+
}
|
|
1480
|
+
if (i >= len - 1) i = len;
|
|
1481
|
+
continue;
|
|
1482
|
+
}
|
|
1483
|
+
if (ch === "'") {
|
|
1484
|
+
i++;
|
|
1485
|
+
while (i < len) {
|
|
1486
|
+
const sc = src[i];
|
|
1487
|
+
if (sc === "\\" && i + 1 < len) {
|
|
1488
|
+
i += 2;
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
if (sc === "'") {
|
|
1492
|
+
i++;
|
|
1493
|
+
break;
|
|
1494
|
+
}
|
|
1495
|
+
if (sc === "\n") break;
|
|
1496
|
+
i++;
|
|
1497
|
+
}
|
|
1498
|
+
continue;
|
|
1499
|
+
}
|
|
1500
|
+
if (ch === '"') {
|
|
1501
|
+
i++;
|
|
1502
|
+
while (i < len) {
|
|
1503
|
+
const sc = src[i];
|
|
1504
|
+
if (sc === "\\" && i + 1 < len) {
|
|
1505
|
+
i += 2;
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
if (sc === '"') {
|
|
1509
|
+
i++;
|
|
1510
|
+
break;
|
|
1511
|
+
}
|
|
1512
|
+
if (sc === "\n") break;
|
|
1513
|
+
i++;
|
|
1514
|
+
}
|
|
1515
|
+
continue;
|
|
1516
|
+
}
|
|
1517
|
+
if (ch === "`") {
|
|
1518
|
+
i++;
|
|
1519
|
+
while (i < len) {
|
|
1520
|
+
const tc = src[i];
|
|
1521
|
+
if (tc === "\\" && i + 1 < len) {
|
|
1522
|
+
i += 2;
|
|
1523
|
+
continue;
|
|
1524
|
+
}
|
|
1525
|
+
if (tc === "`") {
|
|
1526
|
+
i++;
|
|
1527
|
+
break;
|
|
1528
|
+
}
|
|
1529
|
+
if (tc === "$" && i + 1 < len && src[i + 1] === "{") {
|
|
1530
|
+
i += 2;
|
|
1531
|
+
const inner = lexInterpolationBody(src, i);
|
|
1532
|
+
if (inner.execText.length > 0) {
|
|
1533
|
+
execParts.push(inner.execText);
|
|
1534
|
+
}
|
|
1535
|
+
i = inner.end < len ? inner.end + 1 : len;
|
|
1536
|
+
continue;
|
|
1537
|
+
}
|
|
1538
|
+
i++;
|
|
1539
|
+
}
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
execParts.push(ch);
|
|
1543
|
+
i++;
|
|
1544
|
+
}
|
|
1545
|
+
return { execText: execParts.join(""), end: i };
|
|
1546
|
+
}
|
|
1547
|
+
function extractExecutableText(src) {
|
|
1548
|
+
const buf = [];
|
|
1549
|
+
const len = src.length;
|
|
1550
|
+
let i = 0;
|
|
1551
|
+
let lastMeaningfulChar = "";
|
|
1552
|
+
function canStartRegex() {
|
|
1553
|
+
const c = lastMeaningfulChar;
|
|
1554
|
+
if (c === "") return true;
|
|
1555
|
+
if (c === ")" || c === "]" || c === "}") return false;
|
|
1556
|
+
if (c >= "a" && c <= "z" || c >= "A" && c <= "Z") return false;
|
|
1557
|
+
if (c >= "0" && c <= "9") return false;
|
|
1558
|
+
if (c === "_" || c === "$" || c === ".") return false;
|
|
1559
|
+
return true;
|
|
1560
|
+
}
|
|
1561
|
+
function appendExec(text) {
|
|
1562
|
+
buf.push(text);
|
|
1563
|
+
for (let k = text.length - 1; k >= 0; k--) {
|
|
1564
|
+
const c = text[k];
|
|
1565
|
+
if (c !== " " && c !== " " && c !== "\r" && c !== "\n") {
|
|
1566
|
+
lastMeaningfulChar = c;
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
function appendNonExecGap() {
|
|
1572
|
+
buf.push(" ");
|
|
1573
|
+
lastMeaningfulChar = '"';
|
|
1574
|
+
}
|
|
1575
|
+
while (i < len) {
|
|
1576
|
+
const ch = src[i];
|
|
1577
|
+
if (ch === "/") {
|
|
1578
|
+
const next = i + 1 < len ? src[i + 1] : "";
|
|
1579
|
+
if (next === "/") {
|
|
1580
|
+
const start = i;
|
|
1581
|
+
i += 2;
|
|
1582
|
+
while (i < len && src[i] !== "\n") i++;
|
|
1583
|
+
appendNonExecGap();
|
|
1584
|
+
void start;
|
|
1585
|
+
continue;
|
|
1586
|
+
}
|
|
1587
|
+
if (next === "*") {
|
|
1588
|
+
i += 2;
|
|
1589
|
+
let closed = false;
|
|
1590
|
+
while (i < len - 1) {
|
|
1591
|
+
if (src[i] === "*" && src[i + 1] === "/") {
|
|
1592
|
+
i += 2;
|
|
1593
|
+
closed = true;
|
|
1594
|
+
break;
|
|
1595
|
+
}
|
|
1596
|
+
i++;
|
|
1597
|
+
}
|
|
1598
|
+
if (!closed) i = len;
|
|
1599
|
+
appendNonExecGap();
|
|
1600
|
+
continue;
|
|
1601
|
+
}
|
|
1602
|
+
if (canStartRegex()) {
|
|
1603
|
+
const start = i;
|
|
1604
|
+
i++;
|
|
1605
|
+
let inClass = false;
|
|
1606
|
+
let closedRegex = false;
|
|
1607
|
+
let hitNewline = false;
|
|
1608
|
+
while (i < len) {
|
|
1609
|
+
const rc = src[i];
|
|
1610
|
+
if (rc === "\\" && i + 1 < len) {
|
|
1611
|
+
i += 2;
|
|
1612
|
+
continue;
|
|
1613
|
+
}
|
|
1614
|
+
if (rc === "[") {
|
|
1615
|
+
inClass = true;
|
|
1616
|
+
i++;
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
if (rc === "]" && inClass) {
|
|
1620
|
+
inClass = false;
|
|
1621
|
+
i++;
|
|
1622
|
+
continue;
|
|
1623
|
+
}
|
|
1624
|
+
if (rc === "/" && !inClass) {
|
|
1625
|
+
i++;
|
|
1626
|
+
while (i < len && /[a-z]/i.test(src[i])) i++;
|
|
1627
|
+
closedRegex = true;
|
|
1628
|
+
break;
|
|
1629
|
+
}
|
|
1630
|
+
if (rc === "\n") {
|
|
1631
|
+
hitNewline = true;
|
|
1632
|
+
break;
|
|
1633
|
+
}
|
|
1634
|
+
i++;
|
|
1635
|
+
}
|
|
1636
|
+
if (hitNewline) {
|
|
1637
|
+
appendExec("/");
|
|
1638
|
+
i = start + 1;
|
|
1639
|
+
} else {
|
|
1640
|
+
appendNonExecGap();
|
|
1641
|
+
}
|
|
1642
|
+
continue;
|
|
1643
|
+
}
|
|
1644
|
+
appendExec(ch);
|
|
1645
|
+
i++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
if (ch === "'") {
|
|
1649
|
+
let j = i + 1;
|
|
1650
|
+
let terminated = false;
|
|
1651
|
+
while (j < len) {
|
|
1652
|
+
const sc = src[j];
|
|
1653
|
+
if (sc === "\\" && j + 1 < len) {
|
|
1654
|
+
j += 2;
|
|
1655
|
+
continue;
|
|
1656
|
+
}
|
|
1657
|
+
if (sc === "'") {
|
|
1658
|
+
j++;
|
|
1659
|
+
terminated = true;
|
|
1660
|
+
break;
|
|
1661
|
+
}
|
|
1662
|
+
if (sc === "\n") break;
|
|
1663
|
+
j++;
|
|
1664
|
+
}
|
|
1665
|
+
if (terminated) {
|
|
1666
|
+
appendNonExecGap();
|
|
1667
|
+
i = j;
|
|
1668
|
+
} else {
|
|
1669
|
+
appendExec("'");
|
|
1670
|
+
i++;
|
|
1671
|
+
}
|
|
1672
|
+
continue;
|
|
1673
|
+
}
|
|
1674
|
+
if (ch === '"') {
|
|
1675
|
+
let j = i + 1;
|
|
1676
|
+
let terminated = false;
|
|
1677
|
+
while (j < len) {
|
|
1678
|
+
const sc = src[j];
|
|
1679
|
+
if (sc === "\\" && j + 1 < len) {
|
|
1680
|
+
j += 2;
|
|
1681
|
+
continue;
|
|
1682
|
+
}
|
|
1683
|
+
if (sc === '"') {
|
|
1684
|
+
j++;
|
|
1685
|
+
terminated = true;
|
|
1686
|
+
break;
|
|
1687
|
+
}
|
|
1688
|
+
if (sc === "\n") break;
|
|
1689
|
+
j++;
|
|
1690
|
+
}
|
|
1691
|
+
if (terminated) {
|
|
1692
|
+
appendNonExecGap();
|
|
1693
|
+
i = j;
|
|
1694
|
+
} else {
|
|
1695
|
+
appendExec('"');
|
|
1696
|
+
i++;
|
|
1697
|
+
}
|
|
1698
|
+
continue;
|
|
1699
|
+
}
|
|
1700
|
+
if (ch === "`") {
|
|
1701
|
+
i++;
|
|
1702
|
+
while (i < len) {
|
|
1703
|
+
const tc = src[i];
|
|
1704
|
+
if (tc === "\\" && i + 1 < len) {
|
|
1705
|
+
i += 2;
|
|
1706
|
+
continue;
|
|
1707
|
+
}
|
|
1708
|
+
if (tc === "`") {
|
|
1709
|
+
i++;
|
|
1710
|
+
appendNonExecGap();
|
|
1711
|
+
break;
|
|
1712
|
+
}
|
|
1713
|
+
if (tc === "$" && i + 1 < len && src[i + 1] === "{") {
|
|
1714
|
+
appendNonExecGap();
|
|
1715
|
+
i += 2;
|
|
1716
|
+
const interp = lexInterpolationBody(src, i);
|
|
1717
|
+
if (interp.execText.length > 0) {
|
|
1718
|
+
appendExec(interp.execText);
|
|
1719
|
+
}
|
|
1720
|
+
i = interp.end < len ? interp.end + 1 : len;
|
|
1721
|
+
continue;
|
|
1722
|
+
}
|
|
1723
|
+
i++;
|
|
1724
|
+
}
|
|
1725
|
+
continue;
|
|
1726
|
+
}
|
|
1727
|
+
appendExec(ch);
|
|
1728
|
+
i++;
|
|
1729
|
+
}
|
|
1730
|
+
return buf.join("");
|
|
1731
|
+
}
|
|
1732
|
+
function hasActiveAuthCall(content) {
|
|
1733
|
+
const execText = extractExecutableText(content);
|
|
1734
|
+
return RE2_AUTH_CALL_PATTERN.test(execText);
|
|
1735
|
+
}
|
|
1736
|
+
function hasCommentedAuthCall(content) {
|
|
1737
|
+
return RE2_COMMENTED_AUTH_PATTERN.test(content);
|
|
1738
|
+
}
|
|
1739
|
+
function hasUnsecuredExpressRoute(content) {
|
|
1740
|
+
if (RE2_EXPRESS_AUTH_MIDDLEWARE_PATTERN.test(content)) {
|
|
1741
|
+
return false;
|
|
1742
|
+
}
|
|
1743
|
+
const matches = RE2_EXPRESS_ROUTE_DEFINITION.matchAll(content);
|
|
1744
|
+
for (const match of matches) {
|
|
1745
|
+
const routePath = match.groups[1];
|
|
1746
|
+
if (routePath !== void 0 && SENSITIVE_EXPRESS_PATHS.test(routePath) && !WEBHOOK_PATH_PATTERN.test(routePath)) {
|
|
1747
|
+
const routeCallStart = match.index;
|
|
1748
|
+
const routeCall = content.slice(routeCallStart, routeCallStart + 300);
|
|
1749
|
+
if (!RE2_INLINE_AUTH_CHECK.test(routeCall)) {
|
|
1750
|
+
return true;
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
return false;
|
|
1755
|
+
}
|
|
1756
|
+
var authCheck = {
|
|
1757
|
+
id: "auth",
|
|
1758
|
+
name: "Auth & Session Protection",
|
|
1759
|
+
run(files, policy) {
|
|
1760
|
+
const findings = [];
|
|
1761
|
+
const middlewareFile = files.find((f) => MIDDLEWARE_FILE_PATTERN.test(f.relativePath));
|
|
1762
|
+
if (isNextjsProject(files)) {
|
|
1763
|
+
if (!middlewareFile) {
|
|
1764
|
+
findings.push({
|
|
1765
|
+
id: "public_admin_route",
|
|
1766
|
+
title: "No Next.js middleware.ts found",
|
|
1767
|
+
severity: "high",
|
|
1768
|
+
category: "auth",
|
|
1769
|
+
file: "middleware.ts",
|
|
1770
|
+
confidence: "MEDIUM",
|
|
1771
|
+
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.",
|
|
1772
|
+
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.",
|
|
1773
|
+
blocking: policy.block.includes("public_admin_route")
|
|
1774
|
+
});
|
|
1775
|
+
} else if (!RE2_MIDDLEWARE_ADMIN_COVERAGE.test(middlewareFile.content)) {
|
|
1776
|
+
findings.push({
|
|
1777
|
+
id: "public_admin_route",
|
|
1778
|
+
title: "middleware.ts does not cover admin/dashboard routes",
|
|
1779
|
+
severity: "high",
|
|
1780
|
+
category: "auth",
|
|
1781
|
+
file: middlewareFile.relativePath,
|
|
1782
|
+
confidence: "MEDIUM",
|
|
1783
|
+
explanation: "A middleware.ts file exists but its content does not reference admin, dashboard, billing, account, or management routes. Sensitive routes may not be protected at the edge/middleware layer.",
|
|
1784
|
+
recommendation: 'Add a matcher config to middleware.ts that covers protected route prefixes:\n export const config = { matcher: ["/admin/:path*", "/dashboard/:path*"] }',
|
|
1785
|
+
blocking: policy.block.includes("public_admin_route")
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
for (const file of files) {
|
|
1790
|
+
const { relativePath: rp, content } = file;
|
|
1791
|
+
if (WEBHOOK_PATH_PATTERN.test(rp)) {
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
if (SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp)) {
|
|
1795
|
+
if (!hasActiveAuthCall(content)) {
|
|
1796
|
+
const wasRemoved = hasCommentedAuthCall(content);
|
|
1797
|
+
findings.push({
|
|
1798
|
+
id: "public_admin_route",
|
|
1799
|
+
title: `Unprotected admin/dashboard page: ${rp}`,
|
|
1800
|
+
severity: "high",
|
|
1801
|
+
category: "auth",
|
|
1802
|
+
file: rp,
|
|
1803
|
+
confidence: "MEDIUM",
|
|
1804
|
+
explanation: wasRemoved ? `${rp} previously had an auth call that appears to have been commented out. This page is now accessible without authentication.` : `${rp} is in a sensitive route segment (admin/dashboard/billing) but contains no active auth call (auth(), getServerSession(), requireAuth(), etc.). Server Components must verify the session even when middleware is in place \u2014 middleware is not a security boundary (see CVE-2025-29927).`,
|
|
1805
|
+
recommendation: 'Add `const session = await auth()` at the top of the Server Component and redirect unauthenticated users with `if (!session) redirect("/login")`.',
|
|
1806
|
+
blocking: policy.block.includes("public_admin_route")
|
|
1807
|
+
});
|
|
1808
|
+
}
|
|
1809
|
+
continue;
|
|
1810
|
+
}
|
|
1811
|
+
if (SENSITIVE_API_ROUTE_PATTERN.test(rp)) {
|
|
1812
|
+
if (!hasActiveAuthCall(content)) {
|
|
1813
|
+
const wasRemoved = hasCommentedAuthCall(content);
|
|
1814
|
+
findings.push({
|
|
1815
|
+
id: "auth_route_without_guard",
|
|
1816
|
+
title: `Unprotected API route handler: ${rp}`,
|
|
1817
|
+
severity: "high",
|
|
1818
|
+
category: "auth",
|
|
1819
|
+
file: rp,
|
|
1820
|
+
confidence: "MEDIUM",
|
|
1821
|
+
explanation: wasRemoved ? `${rp} previously had an auth call that appears to have been commented out. This API route now responds to requests without verifying the caller.` : `${rp} is an API Route Handler under a sensitive path (admin/users/billing) but contains no auth guard. Any caller \u2014 including unauthenticated requests \u2014 can invoke it.`,
|
|
1822
|
+
recommendation: "Add `const session = await auth()` (next-auth) or `const { userId } = await currentUser()` (Clerk) at the start of each exported HTTP handler. Return a 401 if no session.",
|
|
1823
|
+
blocking: policy.block.includes("auth_route_without_guard")
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
continue;
|
|
1827
|
+
}
|
|
1828
|
+
if (
|
|
1829
|
+
// eslint-disable-next-line no-restricted-syntax
|
|
1830
|
+
/\.(ts|js)$/.test(rp) && // path classifier — matches file extension only
|
|
1831
|
+
!SENSITIVE_NEXTJS_PAGE_PATTERN.test(rp) && !SENSITIVE_API_ROUTE_PATTERN.test(rp)
|
|
1832
|
+
) {
|
|
1833
|
+
if (hasUnsecuredExpressRoute(content)) {
|
|
1834
|
+
findings.push({
|
|
1835
|
+
id: "auth_route_without_guard",
|
|
1836
|
+
title: `Express route exposes sensitive path without auth middleware: ${rp}`,
|
|
1837
|
+
severity: "medium",
|
|
1838
|
+
category: "auth",
|
|
1839
|
+
file: rp,
|
|
1840
|
+
confidence: "LOW",
|
|
1841
|
+
explanation: `${rp} registers a route on a sensitive URL segment (admin/users/billing) without an apparent auth middleware guard. In Express, protect routes by passing auth middleware before the handler or by calling router.use(authMiddleware) above the sensitive routes.`,
|
|
1842
|
+
recommendation: 'Use `router.use(requireAuth)` before sensitive routes, or pass it inline:\n router.get("/admin/users", requireAuth, handler)\nFor Fastify, use a `preHandler` hook or `onRequest` hook.',
|
|
1843
|
+
blocking: policy.block.includes("auth_route_without_guard")
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
}
|
|
1848
|
+
return findings;
|
|
1849
|
+
}
|
|
1850
|
+
};
|
|
1851
|
+
|
|
1852
|
+
// src/checks/database.ts
|
|
1853
|
+
var MIGRATION_PATTERNS = [
|
|
1854
|
+
/^prisma\/migrations\/.+\.sql$/i,
|
|
1855
|
+
/^drizzle\/.+\.sql$/i,
|
|
1856
|
+
/^migrations\/.+\.sql$/i,
|
|
1857
|
+
/^db\/.+\.sql$/i,
|
|
1858
|
+
/^[^/]+\.sql$/i
|
|
1859
|
+
// root-level .sql files
|
|
1860
|
+
];
|
|
1861
|
+
function isMigrationFile(relativePath) {
|
|
1862
|
+
return MIGRATION_PATTERNS.some((p) => p.test(relativePath));
|
|
1863
|
+
}
|
|
1864
|
+
var BLOCK_COMMENT_RE = compileDetectorRegex("\\/\\*.*?\\*\\/", "s");
|
|
1865
|
+
var LINE_COMMENT_RE2 = compileDetectorRegex("--[^\n]*");
|
|
1866
|
+
var NEWLINE_RE = compileDetectorRegex("\n");
|
|
1867
|
+
var WHERE_RE = compileDetectorRegex("\\bWHERE\\b", "i");
|
|
1868
|
+
var PRISMA_TOOL_RE = compileDetectorRegex("prisma", "i");
|
|
1869
|
+
function stripSqlComments(sql) {
|
|
1870
|
+
return LINE_COMMENT_RE2.replace(BLOCK_COMMENT_RE.replace(sql, " "), "");
|
|
1871
|
+
}
|
|
1872
|
+
function splitStatements(sql) {
|
|
1873
|
+
const statements = [];
|
|
1874
|
+
const parts = sql.split(";");
|
|
1875
|
+
let currentLine = 1;
|
|
1876
|
+
for (const part of parts) {
|
|
1877
|
+
const trimmed = part.trim();
|
|
1878
|
+
if (trimmed.length > 0) {
|
|
1879
|
+
statements.push({ text: trimmed, startLine: currentLine });
|
|
1880
|
+
}
|
|
1881
|
+
currentLine += NEWLINE_RE.matchAll(part).length;
|
|
1882
|
+
}
|
|
1883
|
+
return statements;
|
|
1884
|
+
}
|
|
1885
|
+
function findLineNumber(content, matchIndex) {
|
|
1886
|
+
const before = content.slice(0, matchIndex);
|
|
1887
|
+
return NEWLINE_RE.matchAll(before).length + 1;
|
|
1888
|
+
}
|
|
1889
|
+
var SQL_PATTERNS = [
|
|
1890
|
+
{
|
|
1891
|
+
id: "db-drop-table",
|
|
1892
|
+
title: "Destructive migration: DROP TABLE",
|
|
1893
|
+
severity: "critical",
|
|
1894
|
+
confidence: "HIGH",
|
|
1895
|
+
explanation: "DROP TABLE permanently deletes a table and all its data. In production this causes irreversible data loss and immediate application failure for any query targeting that table.",
|
|
1896
|
+
recommendation: "Never drop a table in the same migration that removes code references. Use an expand-contract strategy: deprecate code first, then drop in a later release after confirming no traffic.",
|
|
1897
|
+
pattern: compileDetectorRegex("\\bDROP\\s+TABLE\\b", "i")
|
|
1898
|
+
},
|
|
1899
|
+
{
|
|
1900
|
+
id: "db-drop-column",
|
|
1901
|
+
title: "Destructive migration: DROP COLUMN",
|
|
1902
|
+
severity: "high",
|
|
1903
|
+
confidence: "HIGH",
|
|
1904
|
+
explanation: "DROP COLUMN removes a column and its data permanently. Running this while old application code still reads the column causes immediate query failures.",
|
|
1905
|
+
recommendation: "Deprecate the column in code first, deploy, confirm no usage, then run the drop in a separate migration.",
|
|
1906
|
+
pattern: compileDetectorRegex("\\bDROP\\s+COLUMN\\b", "i")
|
|
1907
|
+
},
|
|
1908
|
+
{
|
|
1909
|
+
id: "db-truncate",
|
|
1910
|
+
title: "Destructive migration: TRUNCATE",
|
|
1911
|
+
severity: "high",
|
|
1912
|
+
confidence: "HIGH",
|
|
1913
|
+
explanation: "TRUNCATE deletes all rows in a table instantly without logging individual row deletions, making it very fast but also unrecoverable without a full backup restore.",
|
|
1914
|
+
recommendation: "Remove TRUNCATE from migration files. Data wipes should be explicit operational procedures, not automatic schema changes.",
|
|
1915
|
+
pattern: compileDetectorRegex("\\bTRUNCATE\\b", "i")
|
|
1916
|
+
},
|
|
1917
|
+
{
|
|
1918
|
+
id: "db-delete-without-where",
|
|
1919
|
+
title: "Unsafe migration: DELETE FROM without WHERE clause",
|
|
1920
|
+
severity: "high",
|
|
1921
|
+
confidence: "HIGH",
|
|
1922
|
+
explanation: "DELETE FROM without a WHERE clause deletes every row in the table. In a migration file this almost always indicates a copy-paste error or oversight.",
|
|
1923
|
+
recommendation: "Add a WHERE clause, or replace with TRUNCATE (and add a review gate) if a full wipe is truly intended.",
|
|
1924
|
+
pattern: compileDetectorRegex("\\bDELETE\\s+FROM\\b", "i"),
|
|
1925
|
+
requiresNoWhere: true
|
|
1926
|
+
},
|
|
1927
|
+
{
|
|
1928
|
+
id: "db-alter-drop",
|
|
1929
|
+
title: "Potentially destructive migration: ALTER TABLE DROP",
|
|
1930
|
+
severity: "medium",
|
|
1931
|
+
confidence: "MEDIUM",
|
|
1932
|
+
explanation: "ALTER TABLE \u2026 DROP (other than DROP COLUMN, which is flagged separately) can drop constraints, indexes, or partitions. Dropping a NOT NULL constraint or unique index affects data integrity and query plans.",
|
|
1933
|
+
recommendation: "Review what exactly is being dropped. Ensure application code is already compatible with the removed constraint before deploying.",
|
|
1934
|
+
// Avoid double-flagging lines that already match DROP COLUMN (handled above)
|
|
1935
|
+
// Note: /\bALTER\s+TABLE\b[^;]*\bDROP\b/i — [^;]* is RE2-compatible (no lookaround needed)
|
|
1936
|
+
pattern: compileDetectorRegex("\\bALTER\\s+TABLE\\b[^;]*\\bDROP\\b", "i"),
|
|
1937
|
+
skipIfSiblingMatched: "db-drop-column"
|
|
1938
|
+
}
|
|
1939
|
+
];
|
|
1940
|
+
var PUSH_PATTERNS = [
|
|
1941
|
+
compileDetectorRegex("prisma\\s+db\\s+push", "i"),
|
|
1942
|
+
compileDetectorRegex("drizzle-kit\\s+push", "i")
|
|
1943
|
+
];
|
|
1944
|
+
function checkSqlFile(file, findings) {
|
|
1945
|
+
const raw = file.content;
|
|
1946
|
+
const stripped = stripSqlComments(raw);
|
|
1947
|
+
const statements = splitStatements(stripped);
|
|
1948
|
+
const matchedLinesById = /* @__PURE__ */ new Map();
|
|
1949
|
+
for (const pattern of SQL_PATTERNS) {
|
|
1950
|
+
for (const stmt of statements) {
|
|
1951
|
+
if (!pattern.pattern.test(stmt.text)) continue;
|
|
1952
|
+
if (pattern.requiresNoWhere) {
|
|
1953
|
+
const hasWhere = WHERE_RE.test(stmt.text);
|
|
1954
|
+
if (hasWhere) continue;
|
|
1955
|
+
}
|
|
1956
|
+
if (pattern.skipIfSiblingMatched) {
|
|
1957
|
+
const siblingId = pattern.skipIfSiblingMatched;
|
|
1958
|
+
const siblingPattern = SQL_PATTERNS.find((p) => p.id === siblingId);
|
|
1959
|
+
if (siblingPattern && siblingPattern.pattern.test(stmt.text)) continue;
|
|
1960
|
+
}
|
|
1961
|
+
const matchInStripped = pattern.pattern.exec(stmt.text);
|
|
1962
|
+
const matchIndex = matchInStripped ? raw.indexOf(stmt.text.slice(0, 40)) : 0;
|
|
1963
|
+
const lineNumber = matchIndex >= 0 ? findLineNumber(raw, matchIndex) : stmt.startLine;
|
|
1964
|
+
if (!matchedLinesById.has(pattern.id)) {
|
|
1965
|
+
matchedLinesById.set(pattern.id, /* @__PURE__ */ new Set());
|
|
1966
|
+
}
|
|
1967
|
+
const lines = matchedLinesById.get(pattern.id);
|
|
1968
|
+
if (lines.has(lineNumber)) continue;
|
|
1969
|
+
lines.add(lineNumber);
|
|
1970
|
+
const rawLines = raw.split("\n");
|
|
1971
|
+
const evidenceLine = rawLines[lineNumber - 1]?.trim().slice(0, 120) ?? stmt.text.slice(0, 120);
|
|
1972
|
+
findings.push({
|
|
1973
|
+
id: pattern.id,
|
|
1974
|
+
title: pattern.title,
|
|
1975
|
+
severity: pattern.severity,
|
|
1976
|
+
category: "database",
|
|
1977
|
+
file: file.relativePath,
|
|
1978
|
+
line: lineNumber,
|
|
1979
|
+
evidence: evidenceLine,
|
|
1980
|
+
confidence: pattern.confidence,
|
|
1981
|
+
explanation: pattern.explanation,
|
|
1982
|
+
recommendation: pattern.recommendation,
|
|
1983
|
+
blocking: pattern.severity === "critical" || pattern.severity === "high"
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
function checkPackageJson(file, findings) {
|
|
1989
|
+
if (!file.relativePath.endsWith("package.json")) return;
|
|
1990
|
+
let parsed;
|
|
1991
|
+
try {
|
|
1992
|
+
parsed = JSON.parse(file.content);
|
|
1993
|
+
} catch {
|
|
1994
|
+
return;
|
|
1995
|
+
}
|
|
1996
|
+
const scripts = parsed["scripts"];
|
|
1997
|
+
if (!scripts || typeof scripts !== "object") return;
|
|
1998
|
+
for (const [scriptName, scriptValue] of Object.entries(scripts)) {
|
|
1999
|
+
if (typeof scriptValue !== "string") continue;
|
|
2000
|
+
for (const pushPattern of PUSH_PATTERNS) {
|
|
2001
|
+
if (!pushPattern.test(scriptValue)) continue;
|
|
2002
|
+
const tool = PRISMA_TOOL_RE.test(scriptValue) ? "prisma db push" : "drizzle-kit push";
|
|
2003
|
+
findings.push({
|
|
2004
|
+
id: "db-push-in-scripts",
|
|
2005
|
+
title: `Dangerous command in package.json scripts: ${tool}`,
|
|
2006
|
+
severity: "medium",
|
|
2007
|
+
category: "database",
|
|
2008
|
+
file: file.relativePath,
|
|
2009
|
+
evidence: `"${scriptName}": "${scriptValue.slice(0, 120)}"`,
|
|
2010
|
+
confidence: "HIGH",
|
|
2011
|
+
explanation: `The "${tool}" command bypasses migration files and applies schema changes directly to the database without an audit trail. In production or CI this can silently drop columns, tables, or constraints with no rollback path.`,
|
|
2012
|
+
recommendation: 'Replace with "prisma migrate deploy" (Prisma) or "drizzle-kit migrate" (Drizzle) in all non-local scripts. Reserve db push for local prototype databases only.',
|
|
2013
|
+
blocking: false
|
|
2014
|
+
});
|
|
2015
|
+
break;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
function checkPrismaSchemaWithoutMigration(files, findings) {
|
|
2020
|
+
const hasSchemaChange = files.some((f) => f.relativePath === "prisma/schema.prisma");
|
|
2021
|
+
if (!hasSchemaChange) return;
|
|
2022
|
+
const hasMigration = files.some((f) => /^prisma\/migrations\/.+\.sql$/i.test(f.relativePath));
|
|
2023
|
+
if (hasMigration) return;
|
|
2024
|
+
const schemaFile = files.find((f) => f.relativePath === "prisma/schema.prisma");
|
|
2025
|
+
findings.push({
|
|
2026
|
+
id: "db-schema-without-migration",
|
|
2027
|
+
title: "Prisma schema changed without a migration file",
|
|
2028
|
+
severity: "medium",
|
|
2029
|
+
category: "database",
|
|
2030
|
+
file: schemaFile.relativePath,
|
|
2031
|
+
confidence: "MEDIUM",
|
|
2032
|
+
explanation: 'The Prisma schema was modified but no migration file appears in the changed file set. In production you must run "prisma migrate dev" to generate a migration, then commit it before deploying.',
|
|
2033
|
+
recommendation: 'Run "npx prisma migrate dev --name <description>" locally, commit the generated migration file in prisma/migrations/, and re-scan.',
|
|
2034
|
+
blocking: false
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
var databaseCheck = {
|
|
2038
|
+
id: "database",
|
|
2039
|
+
name: "Database & Migration Safety",
|
|
2040
|
+
run(files, _policy) {
|
|
2041
|
+
const findings = [];
|
|
2042
|
+
for (const file of files) {
|
|
2043
|
+
if (isMigrationFile(file.relativePath)) {
|
|
2044
|
+
checkSqlFile(file, findings);
|
|
2045
|
+
} else if (file.relativePath.endsWith("package.json")) {
|
|
2046
|
+
checkPackageJson(file, findings);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
checkPrismaSchemaWithoutMigration(files, findings);
|
|
2050
|
+
return findings;
|
|
2051
|
+
}
|
|
2052
|
+
};
|
|
2053
|
+
|
|
2054
|
+
// src/checks/deployment.ts
|
|
2055
|
+
import { basename } from "path";
|
|
2056
|
+
var RE_CORS_NEXT_VALUE = compileDetectorRegex(
|
|
2057
|
+
`Access-Control-Allow-Origin['"]\\s*,\\s*value\\s*:\\s*['"]?\\s*\\*\\s*['"]?`,
|
|
2058
|
+
"i"
|
|
2059
|
+
);
|
|
2060
|
+
var RE_CORS_NEXT_HEADER = compileDetectorRegex(
|
|
2061
|
+
`Access-Control-Allow-Origin['"]?\\s*:\\s*['"]\\s*\\*\\s*['"]`,
|
|
2062
|
+
"i"
|
|
2063
|
+
);
|
|
2064
|
+
var RE_SOURCE_MAPS = compileDetectorRegex(
|
|
2065
|
+
"productionBrowserSourceMaps\\s*:\\s*true"
|
|
2066
|
+
);
|
|
2067
|
+
var RE_HEADERS_FN_PARENS = compileDetectorRegex("headers\\s*\\(\\s*\\)");
|
|
2068
|
+
var RE_HEADERS_FN_ASYNC = compileDetectorRegex("async\\s+headers");
|
|
2069
|
+
var RE_X_FRAME_OPTIONS = compileDetectorRegex("X-Frame-Options", "i");
|
|
2070
|
+
var RE_X_CONTENT_TYPE = compileDetectorRegex("X-Content-Type-Options", "i");
|
|
2071
|
+
var RE_DOCKER_USER_LINE = compileDetectorRegex("^\\s*USER\\s+", "i");
|
|
2072
|
+
var RE_DOCKER_ROOT_USER = compileDetectorRegex("^USER\\s+(root|0)\\s*$", "i");
|
|
2073
|
+
var RE_DOCKER_FROM_LINE = compileDetectorRegex("^\\s*FROM\\s+", "i");
|
|
2074
|
+
var RE_DOCKER_AS_ALIAS = compileDetectorRegex("\\s+AS\\s+\\w+", "i");
|
|
2075
|
+
var RE_DOCKER_FROM_IMAGE = compileDetectorRegex(
|
|
2076
|
+
"^FROM\\s+(?:--platform=\\S+\\s+)?(\\S+)",
|
|
2077
|
+
"i"
|
|
2078
|
+
);
|
|
2079
|
+
var RE_COMPOSE_IMAGE_LINE = compileDetectorRegex("^\\s+image:\\s+\\S+");
|
|
2080
|
+
var RE_COMPOSE_IMAGE_NAME = compileDetectorRegex("image:\\s+(\\S+)");
|
|
2081
|
+
var RE_VERCEL_BROAD_REWRITE = compileDetectorRegex(
|
|
2082
|
+
`["']source["']\\s*:\\s*["']/?\\*\\*?/?["']`
|
|
2083
|
+
);
|
|
2084
|
+
var RE_VERCEL_HEADERS = compileDetectorRegex('"headers"\\s*:');
|
|
2085
|
+
var RE_NETLIFY_HEADERS = compileDetectorRegex("\\[headers\\]");
|
|
2086
|
+
var RE_PKG_NODE_ENV_DEV = compileDetectorRegex("NODE_ENV=development", "i");
|
|
2087
|
+
var RE_PKG_DEBUG_TRUE = compileDetectorRegex("DEBUG\\s*=\\s*true", "i");
|
|
2088
|
+
var RE_PKG_DEBUG_STAR = compileDetectorRegex("DEBUG\\s*=\\s*\\*", "i");
|
|
2089
|
+
var RE_CONFIG_CORS_WILDCARD = compileDetectorRegex(
|
|
2090
|
+
`["']?origin["']?\\s*:\\s*["']?\\*["']?`,
|
|
2091
|
+
"i"
|
|
2092
|
+
);
|
|
2093
|
+
var RE_CONFIG_DEBUG_MODE = compileDetectorRegex(
|
|
2094
|
+
`["']?debug["']?\\s*:\\s*true`,
|
|
2095
|
+
"i"
|
|
2096
|
+
);
|
|
2097
|
+
function makeId(suffix) {
|
|
2098
|
+
return `deployment_${suffix}`;
|
|
2099
|
+
}
|
|
2100
|
+
function findLine(content, pattern) {
|
|
2101
|
+
const lines = content.split("\n");
|
|
2102
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2103
|
+
if (pattern.test(lines[i])) return i + 1;
|
|
2104
|
+
}
|
|
2105
|
+
return void 0;
|
|
2106
|
+
}
|
|
2107
|
+
function findLineStr(content, literal) {
|
|
2108
|
+
const lines = content.split("\n");
|
|
2109
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2110
|
+
if (lines[i].includes(literal)) return i + 1;
|
|
2111
|
+
}
|
|
2112
|
+
return void 0;
|
|
2113
|
+
}
|
|
2114
|
+
function checkNextConfig(file) {
|
|
2115
|
+
const findings = [];
|
|
2116
|
+
const { content, relativePath } = file;
|
|
2117
|
+
if (RE_CORS_NEXT_VALUE.test(content) || RE_CORS_NEXT_HEADER.test(content)) {
|
|
2118
|
+
const matchedPattern = RE_CORS_NEXT_VALUE.test(content) ? RE_CORS_NEXT_VALUE : RE_CORS_NEXT_HEADER;
|
|
2119
|
+
const line = findLine(content, matchedPattern);
|
|
2120
|
+
findings.push({
|
|
2121
|
+
id: makeId("cors_wildcard"),
|
|
2122
|
+
title: "Permissive CORS: Access-Control-Allow-Origin set to wildcard (*)",
|
|
2123
|
+
severity: "high",
|
|
2124
|
+
category: "deployment",
|
|
2125
|
+
file: relativePath,
|
|
2126
|
+
line,
|
|
2127
|
+
evidence: "Access-Control-Allow-Origin: *",
|
|
2128
|
+
confidence: "HIGH",
|
|
2129
|
+
explanation: "A wildcard CORS policy allows any origin to read responses from your API. Combined with credentials, this can expose user data to malicious sites.",
|
|
2130
|
+
recommendation: "Replace the wildcard with an explicit list of trusted origins in the headers() configuration.",
|
|
2131
|
+
blocking: true
|
|
2132
|
+
});
|
|
2133
|
+
}
|
|
2134
|
+
if (RE_SOURCE_MAPS.test(content)) {
|
|
2135
|
+
const line = findLine(content, RE_SOURCE_MAPS);
|
|
2136
|
+
findings.push({
|
|
2137
|
+
id: makeId("source_maps_exposed"),
|
|
2138
|
+
title: "Production source maps are enabled (productionBrowserSourceMaps: true)",
|
|
2139
|
+
severity: "medium",
|
|
2140
|
+
category: "deployment",
|
|
2141
|
+
file: relativePath,
|
|
2142
|
+
line,
|
|
2143
|
+
evidence: "productionBrowserSourceMaps: true",
|
|
2144
|
+
confidence: "HIGH",
|
|
2145
|
+
explanation: "Enabling production source maps exposes your original application source code to anyone inspecting browser devtools, aiding reverse engineering and vulnerability discovery.",
|
|
2146
|
+
recommendation: "Remove productionBrowserSourceMaps: true or set it to false for production builds.",
|
|
2147
|
+
blocking: false
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
const hasHeadersFunction = RE_HEADERS_FN_PARENS.test(content) || RE_HEADERS_FN_ASYNC.test(content);
|
|
2151
|
+
const hasXFrameOptions = RE_X_FRAME_OPTIONS.test(content);
|
|
2152
|
+
const hasXContentType = RE_X_CONTENT_TYPE.test(content);
|
|
2153
|
+
if (hasHeadersFunction && !hasXFrameOptions) {
|
|
2154
|
+
findings.push({
|
|
2155
|
+
id: makeId("missing_x_frame_options"),
|
|
2156
|
+
title: "Missing security header: X-Frame-Options not configured",
|
|
2157
|
+
severity: "medium",
|
|
2158
|
+
category: "deployment",
|
|
2159
|
+
file: relativePath,
|
|
2160
|
+
confidence: "MEDIUM",
|
|
2161
|
+
explanation: "X-Frame-Options prevents your site from being embedded in an iframe, protecting users against clickjacking attacks.",
|
|
2162
|
+
recommendation: "Add { key: 'X-Frame-Options', value: 'DENY' } to your headers() configuration in next.config.js.",
|
|
2163
|
+
blocking: false
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
if (hasHeadersFunction && !hasXContentType) {
|
|
2167
|
+
findings.push({
|
|
2168
|
+
id: makeId("missing_x_content_type"),
|
|
2169
|
+
title: "Missing security header: X-Content-Type-Options not configured",
|
|
2170
|
+
severity: "medium",
|
|
2171
|
+
category: "deployment",
|
|
2172
|
+
file: relativePath,
|
|
2173
|
+
confidence: "MEDIUM",
|
|
2174
|
+
explanation: "X-Content-Type-Options: nosniff prevents MIME-type sniffing attacks where browsers execute content as a different type than declared.",
|
|
2175
|
+
recommendation: "Add { key: 'X-Content-Type-Options', value: 'nosniff' } to your headers() configuration.",
|
|
2176
|
+
blocking: false
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
return findings;
|
|
2180
|
+
}
|
|
2181
|
+
function checkDockerfile(file) {
|
|
2182
|
+
const findings = [];
|
|
2183
|
+
const { content, relativePath } = file;
|
|
2184
|
+
const userDirectives = content.split("\n").filter((line) => RE_DOCKER_USER_LINE.test(line)).map((line) => line.trim());
|
|
2185
|
+
const hasNonRootUser = userDirectives.some(
|
|
2186
|
+
(line) => !RE_DOCKER_ROOT_USER.test(line)
|
|
2187
|
+
);
|
|
2188
|
+
if (!hasNonRootUser) {
|
|
2189
|
+
findings.push({
|
|
2190
|
+
id: makeId("docker_root_user"),
|
|
2191
|
+
title: "Dockerfile runs container as root (no non-root USER directive)",
|
|
2192
|
+
severity: "medium",
|
|
2193
|
+
category: "deployment",
|
|
2194
|
+
file: relativePath,
|
|
2195
|
+
confidence: "MEDIUM",
|
|
2196
|
+
explanation: "Running containers as root amplifies the blast radius of a container escape. A non-root user limits what an attacker can do if they gain code execution inside the container.",
|
|
2197
|
+
recommendation: "Add a USER directive with a non-root user (e.g., USER node or create a dedicated user with addgroup/adduser).",
|
|
2198
|
+
blocking: false
|
|
2199
|
+
});
|
|
2200
|
+
}
|
|
2201
|
+
const fromLines = content.split("\n").filter((line) => RE_DOCKER_FROM_LINE.test(line));
|
|
2202
|
+
for (const line of fromLines) {
|
|
2203
|
+
const stripped = RE_DOCKER_AS_ALIAS.replaceFirst(line, "").trim();
|
|
2204
|
+
const match = RE_DOCKER_FROM_IMAGE.exec(stripped);
|
|
2205
|
+
if (!match) continue;
|
|
2206
|
+
const image = match.groups[0] ?? "";
|
|
2207
|
+
if (image.toLowerCase() === "scratch") continue;
|
|
2208
|
+
const hasTag = image.includes(":");
|
|
2209
|
+
const isLatest = image.toLowerCase().endsWith(":latest");
|
|
2210
|
+
if (!hasTag || isLatest) {
|
|
2211
|
+
const lineNum = findLineStr(content, line.trim());
|
|
2212
|
+
findings.push({
|
|
2213
|
+
id: makeId("docker_unpinned_image"),
|
|
2214
|
+
title: `Dockerfile uses unpinned base image: ${image}`,
|
|
2215
|
+
severity: "medium",
|
|
2216
|
+
category: "deployment",
|
|
2217
|
+
file: relativePath,
|
|
2218
|
+
line: lineNum,
|
|
2219
|
+
evidence: line.trim(),
|
|
2220
|
+
confidence: "HIGH",
|
|
2221
|
+
explanation: "Using :latest or no tag means the base image can change silently between builds, introducing unreviewed dependency updates or security regressions.",
|
|
2222
|
+
recommendation: `Pin the image to a specific digest or version tag (e.g., ${image.split(":")[0]}:20-alpine or with a SHA digest).`,
|
|
2223
|
+
blocking: false
|
|
2224
|
+
});
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
return findings;
|
|
2228
|
+
}
|
|
2229
|
+
function checkDockerCompose(file) {
|
|
2230
|
+
const findings = [];
|
|
2231
|
+
const { content, relativePath } = file;
|
|
2232
|
+
const imageLines = content.split("\n").filter((line) => RE_COMPOSE_IMAGE_LINE.test(line));
|
|
2233
|
+
for (const line of imageLines) {
|
|
2234
|
+
const match = RE_COMPOSE_IMAGE_NAME.exec(line);
|
|
2235
|
+
if (!match) continue;
|
|
2236
|
+
const image = match.groups[0] ?? "";
|
|
2237
|
+
const hasTag = image.includes(":");
|
|
2238
|
+
const isLatest = image.toLowerCase().endsWith(":latest");
|
|
2239
|
+
if (!hasTag || isLatest) {
|
|
2240
|
+
findings.push({
|
|
2241
|
+
id: makeId("compose_unpinned_image"),
|
|
2242
|
+
title: `docker-compose uses unpinned image: ${image}`,
|
|
2243
|
+
severity: "medium",
|
|
2244
|
+
category: "deployment",
|
|
2245
|
+
file: relativePath,
|
|
2246
|
+
evidence: line.trim(),
|
|
2247
|
+
confidence: "HIGH",
|
|
2248
|
+
explanation: "Unpinned images in docker-compose can silently pull breaking or vulnerable upstream changes.",
|
|
2249
|
+
recommendation: `Pin to a specific version tag or SHA digest for ${image.split(":")[0]}.`,
|
|
2250
|
+
blocking: false
|
|
2251
|
+
});
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
return findings;
|
|
2255
|
+
}
|
|
2256
|
+
function checkVercelConfig(file) {
|
|
2257
|
+
const findings = [];
|
|
2258
|
+
const { content, relativePath } = file;
|
|
2259
|
+
if (RE_VERCEL_BROAD_REWRITE.test(content)) {
|
|
2260
|
+
const line = findLine(content, RE_VERCEL_BROAD_REWRITE);
|
|
2261
|
+
findings.push({
|
|
2262
|
+
id: makeId("vercel_broad_rewrite"),
|
|
2263
|
+
title: "vercel.json has overly broad rewrite/redirect rule (wildcard source)",
|
|
2264
|
+
severity: "medium",
|
|
2265
|
+
category: "deployment",
|
|
2266
|
+
file: relativePath,
|
|
2267
|
+
line,
|
|
2268
|
+
confidence: "MEDIUM",
|
|
2269
|
+
explanation: "Catch-all rewrite rules can accidentally expose internal routes or proxy unintended paths, creating an open redirect or SSRF surface.",
|
|
2270
|
+
recommendation: "Narrow the source pattern to only the specific paths that need rewriting.",
|
|
2271
|
+
blocking: false
|
|
2272
|
+
});
|
|
2273
|
+
}
|
|
2274
|
+
const hasHeaders = RE_VERCEL_HEADERS.test(content);
|
|
2275
|
+
if (!hasHeaders) {
|
|
2276
|
+
findings.push({
|
|
2277
|
+
id: makeId("vercel_missing_headers"),
|
|
2278
|
+
title: "vercel.json has no security headers configuration",
|
|
2279
|
+
severity: "medium",
|
|
2280
|
+
category: "deployment",
|
|
2281
|
+
file: relativePath,
|
|
2282
|
+
confidence: "MEDIUM",
|
|
2283
|
+
explanation: "Without explicit headers in vercel.json, responses lack security headers like X-Frame-Options, X-Content-Type-Options, and CSP, leaving users exposed to clickjacking and XSS.",
|
|
2284
|
+
recommendation: 'Add a "headers" block to vercel.json or configure security headers in next.config.js instead.',
|
|
2285
|
+
blocking: false
|
|
2286
|
+
});
|
|
2287
|
+
}
|
|
2288
|
+
return findings;
|
|
2289
|
+
}
|
|
2290
|
+
function checkNetlifyConfig(file) {
|
|
2291
|
+
const findings = [];
|
|
2292
|
+
const { content, relativePath } = file;
|
|
2293
|
+
const hasHeaders = RE_NETLIFY_HEADERS.test(content);
|
|
2294
|
+
if (!hasHeaders) {
|
|
2295
|
+
findings.push({
|
|
2296
|
+
id: makeId("netlify_missing_headers"),
|
|
2297
|
+
title: "netlify.toml has no [[headers]] security configuration",
|
|
2298
|
+
severity: "medium",
|
|
2299
|
+
category: "deployment",
|
|
2300
|
+
file: relativePath,
|
|
2301
|
+
confidence: "MEDIUM",
|
|
2302
|
+
explanation: "Without a [[headers]] block, Netlify deployments lack security headers, exposing the app to clickjacking and content-type sniffing attacks.",
|
|
2303
|
+
recommendation: "Add a [[headers]] section to netlify.toml with X-Frame-Options, X-Content-Type-Options, and other security headers.",
|
|
2304
|
+
blocking: false
|
|
2305
|
+
});
|
|
2306
|
+
}
|
|
2307
|
+
return findings;
|
|
2308
|
+
}
|
|
2309
|
+
function checkEnvFiles(files) {
|
|
2310
|
+
const findings = [];
|
|
2311
|
+
const envFile = files.find((f) => basename(f.relativePath) === ".env");
|
|
2312
|
+
const envExampleFile = files.find(
|
|
2313
|
+
(f) => basename(f.relativePath) === ".env.example" || basename(f.relativePath) === ".env.sample"
|
|
2314
|
+
);
|
|
2315
|
+
if (envFile && !envExampleFile) {
|
|
2316
|
+
findings.push({
|
|
2317
|
+
id: makeId("missing_env_example"),
|
|
2318
|
+
title: ".env file exists but .env.example is missing",
|
|
2319
|
+
severity: "low",
|
|
2320
|
+
category: "deployment",
|
|
2321
|
+
file: envFile.relativePath,
|
|
2322
|
+
confidence: "HIGH",
|
|
2323
|
+
explanation: "Without a .env.example, new contributors have no template for required environment variables, increasing the risk of misconfigured deployments.",
|
|
2324
|
+
recommendation: "Create a .env.example file with all required variable keys (and safe placeholder values) so the team can onboard without guessing configuration.",
|
|
2325
|
+
blocking: false
|
|
2326
|
+
});
|
|
2327
|
+
return findings;
|
|
2328
|
+
}
|
|
2329
|
+
if (envFile && envExampleFile) {
|
|
2330
|
+
const parseKeys = (content) => {
|
|
2331
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2332
|
+
for (const line of content.split("\n")) {
|
|
2333
|
+
const trimmed = line.trim();
|
|
2334
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
2335
|
+
const eqIdx = trimmed.indexOf("=");
|
|
2336
|
+
if (eqIdx > 0) {
|
|
2337
|
+
keys.add(trimmed.slice(0, eqIdx).trim());
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
return keys;
|
|
2341
|
+
};
|
|
2342
|
+
const envKeys = parseKeys(envFile.content);
|
|
2343
|
+
const exampleKeys = parseKeys(envExampleFile.content);
|
|
2344
|
+
const undocumentedKeys = [...envKeys].filter((k) => !exampleKeys.has(k));
|
|
2345
|
+
if (undocumentedKeys.length > 0) {
|
|
2346
|
+
findings.push({
|
|
2347
|
+
id: makeId("env_undocumented_keys"),
|
|
2348
|
+
title: `.env has keys not present in .env.example: ${undocumentedKeys.join(", ")}`,
|
|
2349
|
+
severity: "low",
|
|
2350
|
+
category: "deployment",
|
|
2351
|
+
file: envFile.relativePath,
|
|
2352
|
+
evidence: undocumentedKeys.join(", "),
|
|
2353
|
+
confidence: "HIGH",
|
|
2354
|
+
explanation: "Keys present in .env but missing from .env.example leave teammates and deployment pipelines without the full required configuration, causing runtime failures.",
|
|
2355
|
+
recommendation: `Add the following keys to .env.example: ${undocumentedKeys.join(", ")}`,
|
|
2356
|
+
blocking: false
|
|
2357
|
+
});
|
|
2358
|
+
}
|
|
2359
|
+
}
|
|
2360
|
+
return findings;
|
|
2361
|
+
}
|
|
2362
|
+
function checkPackageJson2(file) {
|
|
2363
|
+
const findings = [];
|
|
2364
|
+
const { content, relativePath } = file;
|
|
2365
|
+
let parsed;
|
|
2366
|
+
try {
|
|
2367
|
+
parsed = JSON.parse(content);
|
|
2368
|
+
} catch {
|
|
2369
|
+
return findings;
|
|
2370
|
+
}
|
|
2371
|
+
const scripts = parsed["scripts"];
|
|
2372
|
+
if (!scripts || typeof scripts !== "object") return findings;
|
|
2373
|
+
const scriptEntries = Object.entries(scripts);
|
|
2374
|
+
for (const [name, value] of scriptEntries) {
|
|
2375
|
+
if (typeof value !== "string") continue;
|
|
2376
|
+
if (RE_PKG_NODE_ENV_DEV.test(value)) {
|
|
2377
|
+
findings.push({
|
|
2378
|
+
id: makeId(`pkg_node_env_dev_${name}`),
|
|
2379
|
+
title: `package.json script "${name}" sets NODE_ENV=development`,
|
|
2380
|
+
severity: "high",
|
|
2381
|
+
category: "deployment",
|
|
2382
|
+
file: relativePath,
|
|
2383
|
+
evidence: `"${name}": "${value}"`,
|
|
2384
|
+
confidence: "HIGH",
|
|
2385
|
+
explanation: "Running with NODE_ENV=development in production disables performance optimisations and may enable verbose error output, leaking stack traces to end users.",
|
|
2386
|
+
recommendation: `Remove NODE_ENV=development from the "${name}" script or set NODE_ENV=production explicitly.`,
|
|
2387
|
+
blocking: true
|
|
2388
|
+
});
|
|
2389
|
+
}
|
|
2390
|
+
if (RE_PKG_DEBUG_TRUE.test(value) || RE_PKG_DEBUG_STAR.test(value)) {
|
|
2391
|
+
findings.push({
|
|
2392
|
+
id: makeId(`pkg_debug_true_${name}`),
|
|
2393
|
+
title: `package.json script "${name}" enables DEBUG mode`,
|
|
2394
|
+
severity: "high",
|
|
2395
|
+
category: "deployment",
|
|
2396
|
+
file: relativePath,
|
|
2397
|
+
evidence: `"${name}": "${value}"`,
|
|
2398
|
+
confidence: "HIGH",
|
|
2399
|
+
explanation: "DEBUG=true or DEBUG=* enables verbose logging in many Node.js libraries, which can leak internal paths, secrets, and request details in production logs.",
|
|
2400
|
+
recommendation: `Remove the DEBUG flag from the "${name}" script.`,
|
|
2401
|
+
blocking: true
|
|
2402
|
+
});
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
return findings;
|
|
2406
|
+
}
|
|
2407
|
+
function checkGeneralConfigs(file) {
|
|
2408
|
+
const findings = [];
|
|
2409
|
+
const { content, relativePath } = file;
|
|
2410
|
+
if (RE_CONFIG_CORS_WILDCARD.test(content)) {
|
|
2411
|
+
const line = findLine(content, RE_CONFIG_CORS_WILDCARD);
|
|
2412
|
+
findings.push({
|
|
2413
|
+
id: makeId("config_cors_wildcard_origin"),
|
|
2414
|
+
title: `CORS origin wildcard (*) detected in ${relativePath}`,
|
|
2415
|
+
severity: "high",
|
|
2416
|
+
category: "deployment",
|
|
2417
|
+
file: relativePath,
|
|
2418
|
+
line,
|
|
2419
|
+
evidence: "origin: *",
|
|
2420
|
+
confidence: "MEDIUM",
|
|
2421
|
+
explanation: "Setting CORS origin to * allows any website to make credentialed requests to your API, bypassing Same-Origin Policy protections.",
|
|
2422
|
+
recommendation: "Replace the wildcard origin with an explicit allowlist of trusted domains.",
|
|
2423
|
+
blocking: true
|
|
2424
|
+
});
|
|
2425
|
+
}
|
|
2426
|
+
if (RE_CONFIG_DEBUG_MODE.test(content)) {
|
|
2427
|
+
const line = findLine(content, RE_CONFIG_DEBUG_MODE);
|
|
2428
|
+
findings.push({
|
|
2429
|
+
id: makeId("config_debug_mode"),
|
|
2430
|
+
title: `Debug mode enabled in ${relativePath}`,
|
|
2431
|
+
severity: "high",
|
|
2432
|
+
category: "deployment",
|
|
2433
|
+
file: relativePath,
|
|
2434
|
+
line,
|
|
2435
|
+
evidence: "debug: true",
|
|
2436
|
+
confidence: "MEDIUM",
|
|
2437
|
+
explanation: "Debug mode in production configs exposes verbose logs, internal stack traces, and configuration details that aid attackers.",
|
|
2438
|
+
recommendation: "Set debug: false or remove the debug flag from production configuration.",
|
|
2439
|
+
blocking: true
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
return findings;
|
|
2443
|
+
}
|
|
2444
|
+
var deploymentCheck = {
|
|
2445
|
+
id: "deployment",
|
|
2446
|
+
name: "Deployment & Configuration",
|
|
2447
|
+
run(files, _policy) {
|
|
2448
|
+
const findings = [];
|
|
2449
|
+
for (const file of files) {
|
|
2450
|
+
const base = basename(file.relativePath);
|
|
2451
|
+
if (["next.config.js", "next.config.mjs", "next.config.ts"].includes(base)) {
|
|
2452
|
+
findings.push(...checkNextConfig(file));
|
|
2453
|
+
continue;
|
|
2454
|
+
}
|
|
2455
|
+
if (base === "Dockerfile" || base.startsWith("Dockerfile.")) {
|
|
2456
|
+
findings.push(...checkDockerfile(file));
|
|
2457
|
+
continue;
|
|
2458
|
+
}
|
|
2459
|
+
if (base === "docker-compose.yml" || base === "docker-compose.yaml") {
|
|
2460
|
+
findings.push(...checkDockerCompose(file));
|
|
2461
|
+
continue;
|
|
2462
|
+
}
|
|
2463
|
+
if (base === "vercel.json") {
|
|
2464
|
+
findings.push(...checkVercelConfig(file));
|
|
2465
|
+
continue;
|
|
2466
|
+
}
|
|
2467
|
+
if (base === "netlify.toml") {
|
|
2468
|
+
findings.push(...checkNetlifyConfig(file));
|
|
2469
|
+
continue;
|
|
2470
|
+
}
|
|
2471
|
+
if (base === "package.json") {
|
|
2472
|
+
findings.push(...checkPackageJson2(file));
|
|
2473
|
+
continue;
|
|
2474
|
+
}
|
|
2475
|
+
findings.push(...checkGeneralConfigs(file));
|
|
2476
|
+
}
|
|
2477
|
+
findings.push(...checkEnvFiles(files));
|
|
2478
|
+
return findings;
|
|
2479
|
+
}
|
|
2480
|
+
};
|
|
2481
|
+
|
|
2482
|
+
// src/checks/payments.ts
|
|
2483
|
+
function isStripeWebhookRoute(relativePath) {
|
|
2484
|
+
const p = relativePath.toLowerCase();
|
|
2485
|
+
if (!p.includes("api/") && !p.includes("api\\")) return false;
|
|
2486
|
+
return p.includes("webhook") || p.includes("stripe");
|
|
2487
|
+
}
|
|
2488
|
+
function isRazorpayWebhookRoute(relativePath) {
|
|
2489
|
+
const p = relativePath.toLowerCase();
|
|
2490
|
+
if (!p.includes("api/") && !p.includes("api\\")) return false;
|
|
2491
|
+
return p.includes("razorpay") || p.includes("webhook") && p.includes("razorpay");
|
|
2492
|
+
}
|
|
2493
|
+
function isPaymentRoute(relativePath) {
|
|
2494
|
+
const p = relativePath.toLowerCase();
|
|
2495
|
+
if (!p.includes("api/") && !p.includes("api\\")) return false;
|
|
2496
|
+
return p.includes("checkout") || p.includes("billing") || p.includes("subscription") || p.includes("payment");
|
|
2497
|
+
}
|
|
2498
|
+
function isClientSideFile(relativePath) {
|
|
2499
|
+
const p = relativePath.toLowerCase().replace(/\\/g, "/");
|
|
2500
|
+
if (p.startsWith("app/api/") || p.startsWith("pages/api/")) return false;
|
|
2501
|
+
return p.startsWith("app/") || p.startsWith("pages/") || p.startsWith("components/");
|
|
2502
|
+
}
|
|
2503
|
+
var RE_STRIPE_CONSTRUCT_EVENT = compileDetectorRegex("stripe\\.webhooks\\.constructEvent", "i");
|
|
2504
|
+
var RE_STRIPE_SIGNATURE = compileDetectorRegex("stripe-signature", "i");
|
|
2505
|
+
var RE_RAZORPAY_VALIDATE = compileDetectorRegex("validateWebhookSignature", "i");
|
|
2506
|
+
var RE_IDEMPOTENCY_WORD = compileDetectorRegex("idempoten(?:cy|t)", "i");
|
|
2507
|
+
var RE_EVENT_ID = compileDetectorRegex("event\\.id", "i");
|
|
2508
|
+
var RE_PROCESSED_EVENTS = compileDetectorRegex("processedEvents", "i");
|
|
2509
|
+
var RE_ALREADY_PROCESSED = compileDetectorRegex("alreadyProcessed", "i");
|
|
2510
|
+
var RE_TRY = compileDetectorRegex("\\btry\\b");
|
|
2511
|
+
var RE_CATCH = compileDetectorRegex("\\bcatch\\b");
|
|
2512
|
+
var RE_STRIPE_SECRET_KEY = compileDetectorRegex("STRIPE_SECRET_KEY", "i");
|
|
2513
|
+
var RE_RAZORPAY_KEY_SECRET = compileDetectorRegex("RAZORPAY_KEY_SECRET", "i");
|
|
2514
|
+
function hasStripeConstructEvent(content) {
|
|
2515
|
+
return RE_STRIPE_CONSTRUCT_EVENT.test(content);
|
|
2516
|
+
}
|
|
2517
|
+
function hasStripeSignatureHeader(content) {
|
|
2518
|
+
return RE_STRIPE_SIGNATURE.test(content);
|
|
2519
|
+
}
|
|
2520
|
+
function hasRazorpayValidateWebhook(content) {
|
|
2521
|
+
return RE_RAZORPAY_VALIDATE.test(content);
|
|
2522
|
+
}
|
|
2523
|
+
function hasIdempotencyHandling(content) {
|
|
2524
|
+
return RE_IDEMPOTENCY_WORD.test(content) || RE_EVENT_ID.test(content) || RE_PROCESSED_EVENTS.test(content) || RE_ALREADY_PROCESSED.test(content);
|
|
2525
|
+
}
|
|
2526
|
+
function hasErrorHandling(content) {
|
|
2527
|
+
return RE_TRY.test(content) && RE_CATCH.test(content);
|
|
2528
|
+
}
|
|
2529
|
+
function isBlocking(id, policy) {
|
|
2530
|
+
return policy.block.includes(id);
|
|
2531
|
+
}
|
|
2532
|
+
var payments = {
|
|
2533
|
+
id: "payments",
|
|
2534
|
+
name: "Payment & Webhook Security",
|
|
2535
|
+
run(files, policy) {
|
|
2536
|
+
const findings = [];
|
|
2537
|
+
for (const file of files) {
|
|
2538
|
+
const { relativePath, content } = file;
|
|
2539
|
+
if (isStripeWebhookRoute(relativePath)) {
|
|
2540
|
+
if (!hasStripeConstructEvent(content)) {
|
|
2541
|
+
const id = "payment_webhook_without_signature_check";
|
|
2542
|
+
findings.push({
|
|
2543
|
+
id,
|
|
2544
|
+
title: "Stripe webhook missing signature verification",
|
|
2545
|
+
severity: "critical",
|
|
2546
|
+
category: "payments",
|
|
2547
|
+
file: relativePath,
|
|
2548
|
+
evidence: "No call to stripe.webhooks.constructEvent() found",
|
|
2549
|
+
confidence: "MEDIUM",
|
|
2550
|
+
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.",
|
|
2551
|
+
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.",
|
|
2552
|
+
blocking: isBlocking(id, policy)
|
|
2553
|
+
});
|
|
2554
|
+
}
|
|
2555
|
+
if (!hasStripeSignatureHeader(content)) {
|
|
2556
|
+
const id = "payment_webhook_without_signature_check";
|
|
2557
|
+
findings.push({
|
|
2558
|
+
id,
|
|
2559
|
+
title: "Stripe webhook does not read stripe-signature header",
|
|
2560
|
+
severity: "critical",
|
|
2561
|
+
category: "payments",
|
|
2562
|
+
file: relativePath,
|
|
2563
|
+
evidence: "No reference to stripe-signature header found",
|
|
2564
|
+
confidence: "MEDIUM",
|
|
2565
|
+
explanation: "The Stripe-Signature header carries the HMAC timestamp+hash that proves the request originated from Stripe. Without reading it, signature verification is impossible.",
|
|
2566
|
+
recommendation: 'Read the header with request.headers.get("stripe-signature") (Next.js) or req.headers["stripe-signature"] (Express) before calling constructEvent().',
|
|
2567
|
+
blocking: isBlocking(id, policy)
|
|
2568
|
+
});
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
if (isRazorpayWebhookRoute(relativePath)) {
|
|
2572
|
+
if (!hasRazorpayValidateWebhook(content)) {
|
|
2573
|
+
const id = "payment_webhook_without_signature_check";
|
|
2574
|
+
findings.push({
|
|
2575
|
+
id,
|
|
2576
|
+
title: "Razorpay webhook missing signature verification",
|
|
2577
|
+
severity: "critical",
|
|
2578
|
+
category: "payments",
|
|
2579
|
+
file: relativePath,
|
|
2580
|
+
evidence: "No call to validateWebhookSignature() found",
|
|
2581
|
+
confidence: "MEDIUM",
|
|
2582
|
+
explanation: "Without validateWebhookSignature(), the webhook endpoint cannot verify that requests originate from Razorpay. An attacker can send forged payment confirmation events without completing an actual payment.",
|
|
2583
|
+
recommendation: "Use Razorpay.validateWebhookSignature(rawBody, signature, webhookSecret) where signature is taken from the x-razorpay-signature header. Always pass the raw (unparsed) body.",
|
|
2584
|
+
blocking: isBlocking(id, policy)
|
|
2585
|
+
});
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
if (isClientSideFile(relativePath)) {
|
|
2589
|
+
const stripeSecretInFile = RE_STRIPE_SECRET_KEY.test(content);
|
|
2590
|
+
const razorpaySecretInFile = RE_RAZORPAY_KEY_SECRET.test(content);
|
|
2591
|
+
if (stripeSecretInFile) {
|
|
2592
|
+
const id = "exposed_env";
|
|
2593
|
+
findings.push({
|
|
2594
|
+
id,
|
|
2595
|
+
title: "STRIPE_SECRET_KEY referenced in client-side file",
|
|
2596
|
+
severity: "critical",
|
|
2597
|
+
category: "payments",
|
|
2598
|
+
file: relativePath,
|
|
2599
|
+
evidence: "Reference to STRIPE_SECRET_KEY found in a client-bundle file",
|
|
2600
|
+
confidence: "MEDIUM",
|
|
2601
|
+
explanation: "STRIPE_SECRET_KEY is a server-only secret. If it is bundled into client-side code it will be exposed in the browser, allowing anyone to make API calls on your behalf \u2014 creating charges, accessing customer data, or issuing refunds.",
|
|
2602
|
+
recommendation: "Move Stripe secret key usage exclusively to API routes (app/api/ or pages/api/). Use NEXT_PUBLIC_ prefix only for the Stripe publishable key.",
|
|
2603
|
+
blocking: isBlocking(id, policy)
|
|
2604
|
+
});
|
|
2605
|
+
}
|
|
2606
|
+
if (razorpaySecretInFile) {
|
|
2607
|
+
const id = "exposed_env";
|
|
2608
|
+
findings.push({
|
|
2609
|
+
id,
|
|
2610
|
+
title: "RAZORPAY_KEY_SECRET referenced in client-side file",
|
|
2611
|
+
severity: "critical",
|
|
2612
|
+
category: "payments",
|
|
2613
|
+
file: relativePath,
|
|
2614
|
+
evidence: "Reference to RAZORPAY_KEY_SECRET found in a client-bundle file",
|
|
2615
|
+
confidence: "MEDIUM",
|
|
2616
|
+
explanation: "RAZORPAY_KEY_SECRET is a server-only secret. Exposure in client-side code allows attackers to forge payment signatures and verify payments without completing them.",
|
|
2617
|
+
recommendation: "Use RAZORPAY_KEY_SECRET only in server-side API routes. For the client, only use the Razorpay key_id (public).",
|
|
2618
|
+
blocking: isBlocking(id, policy)
|
|
2619
|
+
});
|
|
2620
|
+
}
|
|
2621
|
+
}
|
|
2622
|
+
if (isStripeWebhookRoute(relativePath) || isRazorpayWebhookRoute(relativePath)) {
|
|
2623
|
+
if (!hasIdempotencyHandling(content)) {
|
|
2624
|
+
const id = "missing_idempotency";
|
|
2625
|
+
findings.push({
|
|
2626
|
+
id,
|
|
2627
|
+
title: "Webhook handler lacks idempotency protection",
|
|
2628
|
+
severity: "medium",
|
|
2629
|
+
category: "payments",
|
|
2630
|
+
file: relativePath,
|
|
2631
|
+
evidence: "No idempotency key, event.id check, or duplicate-detection logic found",
|
|
2632
|
+
confidence: "LOW",
|
|
2633
|
+
explanation: "Payment providers may deliver the same webhook event more than once (retries after network failure, provider-side bugs). Without idempotency guards, duplicate deliveries can cause double-charges, double-fulfillments, or double-refunds.",
|
|
2634
|
+
recommendation: "Record processed event IDs (e.g., store event.id in a database) before acting on the event. If the ID already exists, return 200 immediately without reprocessing.",
|
|
2635
|
+
blocking: isBlocking(id, policy)
|
|
2636
|
+
});
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
if (isPaymentRoute(relativePath)) {
|
|
2640
|
+
if (!hasErrorHandling(content)) {
|
|
2641
|
+
const id = "missing_error_handling";
|
|
2642
|
+
findings.push({
|
|
2643
|
+
id,
|
|
2644
|
+
title: "Payment route lacks error handling",
|
|
2645
|
+
severity: "low",
|
|
2646
|
+
category: "payments",
|
|
2647
|
+
file: relativePath,
|
|
2648
|
+
evidence: "No try/catch block found in payment-related route",
|
|
2649
|
+
confidence: "LOW",
|
|
2650
|
+
explanation: "Unhandled exceptions in payment routes can leak stack traces to the client, cause silent failures in payment processing, and make debugging production incidents harder.",
|
|
2651
|
+
recommendation: "Wrap payment logic in try/catch. Return a structured error response (e.g., 500 with a generic message) and log the full error server-side.",
|
|
2652
|
+
blocking: isBlocking(id, policy)
|
|
2653
|
+
});
|
|
2654
|
+
}
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
return findings;
|
|
2658
|
+
}
|
|
2659
|
+
};
|
|
2660
|
+
|
|
2661
|
+
// src/core/coderef-dispatch.ts
|
|
2662
|
+
import { createRequire } from "module";
|
|
2663
|
+
import { readFileSync as readFileSync3, existsSync as existsSync3 } from "fs";
|
|
2664
|
+
import { fileURLToPath } from "url";
|
|
2665
|
+
import { dirname as dirname3, join as join3 } from "path";
|
|
2666
|
+
var DEFAULT_DISPATCH_TABLE = {
|
|
2667
|
+
"secrets:secretsCheck": secretsCheck,
|
|
2668
|
+
"auth:authCheck": authCheck,
|
|
2669
|
+
"database:databaseCheck": databaseCheck,
|
|
2670
|
+
"deployment:deploymentCheck": deploymentCheck,
|
|
2671
|
+
"payments:payments": payments
|
|
2672
|
+
};
|
|
2673
|
+
function parseSemver(v) {
|
|
2674
|
+
const [major = 0, minor = 0, patch = 0] = v.split(".").map(Number);
|
|
2675
|
+
return [major, minor, patch];
|
|
2676
|
+
}
|
|
2677
|
+
function semverLt(a, b) {
|
|
2678
|
+
const [aMaj, aMin, aPatch] = parseSemver(a);
|
|
2679
|
+
const [bMaj, bMin, bPatch] = parseSemver(b);
|
|
2680
|
+
if (aMaj !== bMaj) return aMaj < bMaj;
|
|
2681
|
+
if (aMin !== bMin) return aMin < bMin;
|
|
2682
|
+
return aPatch < bPatch;
|
|
2683
|
+
}
|
|
2684
|
+
function runCoderefRules(rules, files, policy, cliVersion = CLI_VERSION, table = DEFAULT_DISPATCH_TABLE, manifest) {
|
|
2685
|
+
const findings = [];
|
|
2686
|
+
let degraded = false;
|
|
2687
|
+
const warnings = [];
|
|
2688
|
+
const augmented = rules;
|
|
2689
|
+
const coderefs = augmented.filter((r) => r.implType === "coderef");
|
|
2690
|
+
for (const rule of coderefs) {
|
|
2691
|
+
const ref = rule.codeRef;
|
|
2692
|
+
if (!ref) {
|
|
2693
|
+
warnings.push(
|
|
2694
|
+
`[shipguard] coderef rule ${rule.id} has implType:"coderef" but no codeRef pointer \u2014 skipping`
|
|
2695
|
+
);
|
|
2696
|
+
continue;
|
|
2697
|
+
}
|
|
2698
|
+
if (semverLt(cliVersion, ref.minCliVersion)) {
|
|
2699
|
+
warnings.push(
|
|
2700
|
+
`[shipguard] Skipping coderef rule ${rule.id}: requires CLI \u2265${ref.minCliVersion}, installed ${cliVersion}`
|
|
2701
|
+
);
|
|
2702
|
+
degraded = true;
|
|
2703
|
+
continue;
|
|
2704
|
+
}
|
|
2705
|
+
if (manifest) {
|
|
2706
|
+
const expected = manifest[ref.moduleId];
|
|
2707
|
+
if (expected === void 0) {
|
|
2708
|
+
warnings.push(
|
|
2709
|
+
`[shipguard] CODEREF_CHECKSUM_MISMATCH: rule ${rule.id}: module "${ref.moduleId}" is absent from the checksum manifest \u2014 refusing to run (non-safe)`
|
|
2710
|
+
);
|
|
2711
|
+
degraded = true;
|
|
2712
|
+
continue;
|
|
2713
|
+
}
|
|
2714
|
+
if (expected !== ref.checksum) {
|
|
2715
|
+
warnings.push(
|
|
2716
|
+
`[shipguard] CODEREF_CHECKSUM_MISMATCH: rule ${rule.id}: checksum mismatch for module "${ref.moduleId}" (expected ${expected}, got ${ref.checksum ?? "undefined"}) \u2014 refusing to run (non-safe)`
|
|
2717
|
+
);
|
|
2718
|
+
degraded = true;
|
|
2719
|
+
continue;
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
const dispatchKey = `${ref.moduleId}:${ref.exportName}`;
|
|
2723
|
+
const mod = table[dispatchKey];
|
|
2724
|
+
if (!mod) {
|
|
2725
|
+
warnings.push(
|
|
2726
|
+
`[shipguard] Unknown coderef "${dispatchKey}" for rule ${rule.id} \u2014 skipping (not a crash)`
|
|
2727
|
+
);
|
|
2728
|
+
degraded = true;
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
const moduleFindings = mod.run(files, policy);
|
|
2732
|
+
findings.push(...moduleFindings);
|
|
2733
|
+
}
|
|
2734
|
+
return { findings, degraded, warnings };
|
|
2735
|
+
}
|
|
2736
|
+
var _require = createRequire(import.meta.url);
|
|
2737
|
+
var _pkgPath = join3(dirname3(fileURLToPath(import.meta.url)), "../../package.json");
|
|
2738
|
+
var CLI_VERSION;
|
|
2739
|
+
try {
|
|
2740
|
+
const pkg = _require(_pkgPath);
|
|
2741
|
+
CLI_VERSION = typeof pkg.version === "string" ? pkg.version : "0.0.0";
|
|
2742
|
+
} catch {
|
|
2743
|
+
CLI_VERSION = "0.0.0";
|
|
2744
|
+
}
|
|
2745
|
+
var _manifestPath = join3(dirname3(fileURLToPath(import.meta.url)), "../../checksum-manifest.json");
|
|
2746
|
+
function loadChecksumManifest() {
|
|
2747
|
+
if (!existsSync3(_manifestPath)) {
|
|
2748
|
+
return void 0;
|
|
2749
|
+
}
|
|
2750
|
+
try {
|
|
2751
|
+
const raw = readFileSync3(_manifestPath, "utf-8");
|
|
2752
|
+
const parsed = JSON.parse(raw);
|
|
2753
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
2754
|
+
console.warn("[shipguard] checksum-manifest.json is not a valid object \u2014 skipping checksum verification");
|
|
2755
|
+
return void 0;
|
|
2756
|
+
}
|
|
2757
|
+
return parsed;
|
|
2758
|
+
} catch (err) {
|
|
2759
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2760
|
+
console.warn(`[shipguard] Failed to load checksum-manifest.json: ${msg} \u2014 skipping checksum verification`);
|
|
2761
|
+
return void 0;
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
// src/core/suppression.ts
|
|
2766
|
+
var SUPPRESS_RE = /\/\/\s*shipguard-ignore:\s*([\w.-]+)\s*--\s*(.+)/;
|
|
2767
|
+
function isLineSuppressed(lines, lineIndex, ruleId) {
|
|
2768
|
+
const sameLine = lines[lineIndex];
|
|
2769
|
+
if (sameLine !== void 0) {
|
|
2770
|
+
const sameMatch = SUPPRESS_RE.exec(sameLine);
|
|
2771
|
+
if (sameMatch && sameMatch[1] === ruleId) return true;
|
|
2772
|
+
}
|
|
2773
|
+
if (lineIndex > 0) {
|
|
2774
|
+
const aboveLine = lines[lineIndex - 1];
|
|
2775
|
+
if (aboveLine !== void 0) {
|
|
2776
|
+
const aboveMatch = SUPPRESS_RE.exec(aboveLine);
|
|
2777
|
+
if (aboveMatch && aboveMatch[1] === ruleId) return true;
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
return false;
|
|
2781
|
+
}
|
|
2782
|
+
function applySuppressions(findings, files) {
|
|
2783
|
+
if (findings.length === 0) return findings;
|
|
2784
|
+
const linesByPath = /* @__PURE__ */ new Map();
|
|
2785
|
+
const linesFor = (relativePath) => {
|
|
2786
|
+
if (linesByPath.has(relativePath)) return linesByPath.get(relativePath);
|
|
2787
|
+
const file = files.find((f) => f.relativePath === relativePath);
|
|
2788
|
+
if (!file) {
|
|
2789
|
+
linesByPath.set(relativePath, []);
|
|
2790
|
+
return void 0;
|
|
2791
|
+
}
|
|
2792
|
+
const split = file.content.split("\n");
|
|
2793
|
+
linesByPath.set(relativePath, split);
|
|
2794
|
+
return split;
|
|
2795
|
+
};
|
|
2796
|
+
for (const finding of findings) {
|
|
2797
|
+
if (finding.line === void 0) continue;
|
|
2798
|
+
const lines = linesFor(finding.file);
|
|
2799
|
+
if (!lines || lines.length === 0) continue;
|
|
2800
|
+
if (isLineSuppressed(lines, finding.line - 1, finding.id)) {
|
|
2801
|
+
finding.suppressed = true;
|
|
2802
|
+
finding.blocking = false;
|
|
2803
|
+
}
|
|
2804
|
+
}
|
|
2805
|
+
return findings;
|
|
2806
|
+
}
|
|
2807
|
+
|
|
2808
|
+
// src/core/pro-scanner.ts
|
|
2809
|
+
import { RE2JS as RE2JS2 } from "re2js";
|
|
2810
|
+
var activeExecutor = re2jsV1Executor;
|
|
2811
|
+
var DEFAULT_FLOOR_PATH = path2.join(os.homedir(), ".shipguard", "release-floor.json");
|
|
2812
|
+
var NoRulesAppliedError = class extends Error {
|
|
2813
|
+
code = "NO_RULES_APPLIED";
|
|
2814
|
+
constructor(message) {
|
|
2815
|
+
super(message);
|
|
2816
|
+
this.name = "NoRulesAppliedError";
|
|
2817
|
+
}
|
|
2818
|
+
};
|
|
2819
|
+
async function fetchProRules(frameworks, categories, apiUrl, scanId, floorPath) {
|
|
2820
|
+
assertTrustedApiUrl(apiUrl);
|
|
2821
|
+
const token = await getAuthToken();
|
|
2822
|
+
if (!token) throw new Error("Not authenticated. Run `shipguard login` first.");
|
|
2823
|
+
const res = await fetch(`${apiUrl}/api/rules/fetch`, {
|
|
2824
|
+
method: "POST",
|
|
2825
|
+
headers: {
|
|
2826
|
+
"Authorization": `Bearer ${token}`,
|
|
2827
|
+
"Content-Type": "application/json"
|
|
2828
|
+
},
|
|
2829
|
+
body: JSON.stringify({ frameworks, categories, ...scanId ? { scanId } : {} })
|
|
2830
|
+
});
|
|
2831
|
+
if (res.status === 401) throw new Error("Auth expired. Run `shipguard login` again.");
|
|
2832
|
+
if (res.status === 402) throw new Error("No credits. Buy at https://agenticcli.dev/dashboard/billing");
|
|
2833
|
+
if (res.status === 422) {
|
|
2834
|
+
let detail = res.statusText;
|
|
2835
|
+
try {
|
|
2836
|
+
const body = await res.json();
|
|
2837
|
+
if (body?.code === "NO_RULES_APPLIED") {
|
|
2838
|
+
throw new NoRulesAppliedError(
|
|
2839
|
+
body.error ?? "Pro rule fetch resolved zero rules \u2014 the scan checked nothing (fail-closed). This is NOT a clean pass."
|
|
2840
|
+
);
|
|
2841
|
+
}
|
|
2842
|
+
detail = body?.error ?? detail;
|
|
2843
|
+
} catch (err) {
|
|
2844
|
+
if (err instanceof NoRulesAppliedError) throw err;
|
|
2845
|
+
}
|
|
2846
|
+
throw new Error(`Rule fetch failed (422): ${detail}`);
|
|
2847
|
+
}
|
|
2848
|
+
if (!res.ok) throw new Error(`Rule fetch failed: ${res.statusText}`);
|
|
2849
|
+
const credits = parseInt(res.headers.get("X-Credits-Remaining") ?? "0", 10);
|
|
2850
|
+
const rulesVersion = res.headers.get("X-Rules-Version") ?? void 0;
|
|
2851
|
+
const rawText = await res.text();
|
|
2852
|
+
let responseJson;
|
|
2853
|
+
try {
|
|
2854
|
+
const { parseStrictNoDup: parseStrict } = await import("./dist-PCVBV5S6.js");
|
|
2855
|
+
responseJson = parseStrict(rawText);
|
|
2856
|
+
} catch (parseErr) {
|
|
2857
|
+
const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
|
|
2858
|
+
throw new Error(
|
|
2859
|
+
`Rule fetch response rejected \u2014 duplicate-key or malformed JSON detected: ${msg}`
|
|
2860
|
+
);
|
|
2861
|
+
}
|
|
2862
|
+
if (responseJson && typeof responseJson === "object" && "fullManifest" in responseJson) {
|
|
2863
|
+
const bundleResponse = responseJson;
|
|
2864
|
+
const effectiveFloorPath = floorPath ?? DEFAULT_FLOOR_PATH;
|
|
2865
|
+
const effectiveScanId = scanId ?? "";
|
|
2866
|
+
const verifyResult = await verifyBundleResponse(
|
|
2867
|
+
bundleResponse,
|
|
2868
|
+
{
|
|
2869
|
+
scanId: effectiveScanId,
|
|
2870
|
+
frameworks,
|
|
2871
|
+
options: {},
|
|
2872
|
+
isPro: true
|
|
2873
|
+
},
|
|
2874
|
+
effectiveFloorPath
|
|
2875
|
+
);
|
|
2876
|
+
if (!verifyResult.ok) {
|
|
2877
|
+
throw new Error(
|
|
2878
|
+
`Attested bundle verification failed: ${verifyResult.reason}` + (verifyResult.nonSafe ? " [non-safe exit]" : "")
|
|
2879
|
+
);
|
|
2880
|
+
}
|
|
2881
|
+
const rules = verifyResult.selectedRules.map((r) => {
|
|
2882
|
+
const rAny = r;
|
|
2883
|
+
const action = rAny["action"] ?? (r.blocking ? "block" : "warn");
|
|
2884
|
+
return {
|
|
2885
|
+
id: r.id,
|
|
2886
|
+
title: r.title,
|
|
2887
|
+
severity: r.severity,
|
|
2888
|
+
category: r.categories?.[0] ?? "security",
|
|
2889
|
+
explanation: r.title,
|
|
2890
|
+
recommendation: "",
|
|
2891
|
+
action,
|
|
2892
|
+
confidence: "HIGH",
|
|
2893
|
+
matcher: {
|
|
2894
|
+
type: r.matcherType === "pattern" ? "pattern" : r.matcherType,
|
|
2895
|
+
// fileGlob: all 20 fields are hashed in 0.5.0 and delivered on the wire.
|
|
2896
|
+
fileGlob: rAny["fileGlob"] ?? "**/*",
|
|
2897
|
+
patterns: r.pattern ? [r.pattern] : [],
|
|
2898
|
+
antiPatterns: r.antiPattern ? [r.antiPattern] : [],
|
|
2899
|
+
flags: r.flags,
|
|
2900
|
+
// FIX 1 (CRITICAL): antiPatternScope and boundary are now part of the 20-field
|
|
2901
|
+
// hash preimage (contract 0.5.0) and ARE delivered on the wire ExecutableRule.
|
|
2902
|
+
// They were missing from this mapping, causing runProRules to always default to
|
|
2903
|
+
// antiPatternScope:'statement' / boundary:'none' — ignoring the corpus values.
|
|
2904
|
+
// 55 corpus rules set non-default scope/boundary; this was a gate-C ≠ production
|
|
2905
|
+
// divergence. Copy them into matcher so runProRules picks them up correctly.
|
|
2906
|
+
...rAny["antiPatternScope"] !== void 0 && { antiPatternScope: rAny["antiPatternScope"] },
|
|
2907
|
+
...rAny["boundary"] !== void 0 && { boundary: rAny["boundary"] },
|
|
2908
|
+
// Preserve presenceRule for file-presence matchers.
|
|
2909
|
+
...r.matcherType === "file-presence" && {
|
|
2910
|
+
presenceRule: rAny["presenceRule"] ?? "must-not-exist"
|
|
2911
|
+
},
|
|
2912
|
+
// Preserve context for file-relationship matchers.
|
|
2913
|
+
...r.matcherType === "file-relationship" && {
|
|
2914
|
+
context: {
|
|
2915
|
+
requiresFile: r.requiresFile,
|
|
2916
|
+
requiresPattern: r.requiresPattern
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
},
|
|
2920
|
+
// Propagate the framework for routing
|
|
2921
|
+
framework: r.framework
|
|
2922
|
+
};
|
|
2923
|
+
});
|
|
2924
|
+
return { rules, creditsRemaining: credits, rulesVersion };
|
|
2925
|
+
}
|
|
2926
|
+
throw new Error(
|
|
2927
|
+
"legacy-bundle-rejected: attestation required \u2014 server response lacks fullManifest. The server must deliver a BundleResponse with fullManifest + corpusAttestation (attested-release protocol, GC.14). Exit non-safe."
|
|
2928
|
+
);
|
|
2929
|
+
}
|
|
2930
|
+
function toRe2jsFlags2(flags) {
|
|
2931
|
+
let bits = 0;
|
|
2932
|
+
if (flags.has("i")) bits |= RE2JS2.CASE_INSENSITIVE;
|
|
2933
|
+
if (flags.has("m")) bits |= RE2JS2.MULTILINE;
|
|
2934
|
+
if (flags.has("s")) bits |= RE2JS2.DOTALL;
|
|
2935
|
+
return bits;
|
|
2936
|
+
}
|
|
2937
|
+
function validateBundleCompile(rules) {
|
|
2938
|
+
for (const rule of rules) {
|
|
2939
|
+
const rawFlags = rule.matcher.flags ?? "";
|
|
2940
|
+
const flagsResult = parseFlags(rawFlags);
|
|
2941
|
+
if (!flagsResult.ok) {
|
|
2942
|
+
return {
|
|
2943
|
+
ok: false,
|
|
2944
|
+
reason: `Rule ${rule.id}: invalid flags "${rawFlags}" \u2014 ${flagsResult.reason}`
|
|
2945
|
+
};
|
|
2946
|
+
}
|
|
2947
|
+
const re2jsFlags = toRe2jsFlags2(flagsResult.flags);
|
|
2948
|
+
for (const p of rule.matcher.patterns) {
|
|
2949
|
+
try {
|
|
2950
|
+
RE2JS2.compile(p, re2jsFlags);
|
|
2951
|
+
} catch (err) {
|
|
2952
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2953
|
+
return {
|
|
2954
|
+
ok: false,
|
|
2955
|
+
reason: `Rule ${rule.id}: primary pattern "${p}" fails re2js compilation \u2014 ${msg}`
|
|
2956
|
+
};
|
|
2957
|
+
}
|
|
2958
|
+
}
|
|
2959
|
+
for (const ap of rule.matcher.antiPatterns) {
|
|
2960
|
+
try {
|
|
2961
|
+
RE2JS2.compile(ap, re2jsFlags);
|
|
2962
|
+
} catch (err) {
|
|
2963
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
2964
|
+
return {
|
|
2965
|
+
ok: false,
|
|
2966
|
+
reason: `Rule ${rule.id}: anti-pattern "${ap}" fails re2js compilation \u2014 ${msg}. The entire bundle is degraded rather than running the rule without its anti-pattern guard (atomic compile, FIX 5 fail-closed).`
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
}
|
|
2970
|
+
}
|
|
2971
|
+
return { ok: true };
|
|
2972
|
+
}
|
|
2973
|
+
function deriveBlocking(rule) {
|
|
2974
|
+
if (rule.action === "block") return true;
|
|
2975
|
+
if (rule.action === "warn" || rule.action === "monitor") return false;
|
|
2976
|
+
if (rule.confidence === "HIGH") return true;
|
|
2977
|
+
return rule.severity === "critical" || rule.severity === "high";
|
|
2978
|
+
}
|
|
2979
|
+
var RunProRulesFatalError = class extends Error {
|
|
2980
|
+
constructor(message) {
|
|
2981
|
+
super(message);
|
|
2982
|
+
this.name = "RunProRulesFatalError";
|
|
2983
|
+
}
|
|
2984
|
+
};
|
|
2985
|
+
function runProRules(rules, files, _policy) {
|
|
2986
|
+
const compileCheck = validateBundleCompile(rules);
|
|
2987
|
+
if (!compileCheck.ok) {
|
|
2988
|
+
console.error(
|
|
2989
|
+
`[shipguard] Pro rule bundle failed atomic compile \u2014 refusing to run degraded bundle.
|
|
2990
|
+
Reason: ${compileCheck.reason}
|
|
2991
|
+
Action: The caller must mark the scan result DEGRADED + non-safe.`
|
|
2992
|
+
);
|
|
2993
|
+
return [];
|
|
2994
|
+
}
|
|
2995
|
+
const SUPPORTED_TYPES = /* @__PURE__ */ new Set(["pattern", "file-presence", "file-relationship"]);
|
|
2996
|
+
for (const rule of rules) {
|
|
2997
|
+
if (!SUPPORTED_TYPES.has(rule.matcher.type)) {
|
|
2998
|
+
throw new RunProRulesFatalError(
|
|
2999
|
+
`Bundle contains unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}" \u2014 whole bundle rejected (non-safe). Only pattern/file-presence/file-relationship are supported by re2js-v1.`
|
|
3000
|
+
);
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
const findings = [];
|
|
3004
|
+
const allRelativePaths = files.map((f) => f.relativePath);
|
|
3005
|
+
const ctx = {
|
|
3006
|
+
allRelativePaths,
|
|
3007
|
+
releaseId: "pre-attestation"
|
|
3008
|
+
};
|
|
3009
|
+
for (const rule of rules) {
|
|
3010
|
+
let matcherForExecutor;
|
|
3011
|
+
if (rule.matcher.type === "pattern") {
|
|
3012
|
+
const ruleAny = rule.matcher;
|
|
3013
|
+
const antiPatternScope = ruleAny["antiPatternScope"];
|
|
3014
|
+
const boundary = ruleAny["boundary"];
|
|
3015
|
+
matcherForExecutor = {
|
|
3016
|
+
type: "pattern",
|
|
3017
|
+
fileGlob: rule.matcher.fileGlob,
|
|
3018
|
+
patterns: rule.matcher.patterns,
|
|
3019
|
+
antiPatterns: rule.matcher.antiPatterns,
|
|
3020
|
+
flags: rule.matcher.flags ?? "",
|
|
3021
|
+
// FIX 1+2: pass through delivered values; executor defaults to 'none'/'statement'.
|
|
3022
|
+
...boundary !== void 0 && { boundary },
|
|
3023
|
+
...antiPatternScope !== void 0 && { antiPatternScope }
|
|
3024
|
+
};
|
|
3025
|
+
} else if (rule.matcher.type === "file-presence") {
|
|
3026
|
+
const presenceRule = rule.matcher.presenceRule ?? "must-not-exist";
|
|
3027
|
+
matcherForExecutor = {
|
|
3028
|
+
type: "file-presence",
|
|
3029
|
+
fileGlob: rule.matcher.fileGlob,
|
|
3030
|
+
presenceRule
|
|
3031
|
+
};
|
|
3032
|
+
} else if (rule.matcher.type === "file-relationship") {
|
|
3033
|
+
const frAny = rule.matcher;
|
|
3034
|
+
const frFlags = frAny["flags"] ?? "";
|
|
3035
|
+
const frPatterns = rule.matcher.patterns ?? [];
|
|
3036
|
+
const frAntiPatterns = rule.matcher.antiPatterns ?? [];
|
|
3037
|
+
matcherForExecutor = {
|
|
3038
|
+
type: "file-relationship",
|
|
3039
|
+
fileGlob: rule.matcher.fileGlob,
|
|
3040
|
+
context: {
|
|
3041
|
+
requiresFile: rule.matcher.context?.requiresFile,
|
|
3042
|
+
requiresPattern: rule.matcher.context?.requiresPattern
|
|
3043
|
+
},
|
|
3044
|
+
// Extended fields for self-referential requiresPattern evaluation:
|
|
3045
|
+
patterns: frPatterns,
|
|
3046
|
+
antiPatterns: frAntiPatterns,
|
|
3047
|
+
flags: frFlags
|
|
3048
|
+
};
|
|
3049
|
+
} else {
|
|
3050
|
+
throw new RunProRulesFatalError(
|
|
3051
|
+
`Unreachable: unsupported matcher type "${rule.matcher.type}" on rule "${rule.id}"`
|
|
3052
|
+
);
|
|
3053
|
+
}
|
|
3054
|
+
const matched = files.filter((f) => minimatch(f.relativePath, rule.matcher.fileGlob));
|
|
3055
|
+
for (const file of matched) {
|
|
3056
|
+
let canonicalFindings;
|
|
3057
|
+
try {
|
|
3058
|
+
canonicalFindings = activeExecutor.evaluate(
|
|
3059
|
+
matcherForExecutor,
|
|
3060
|
+
{ relativePath: file.relativePath, content: file.content },
|
|
3061
|
+
ctx
|
|
3062
|
+
);
|
|
3063
|
+
} catch (execErr) {
|
|
3064
|
+
const msg = execErr instanceof Error ? execErr.message : String(execErr);
|
|
3065
|
+
console.error(
|
|
3066
|
+
`[shipguard] Engine exception evaluating rule ${rule.id} against ${file.relativePath}: ${msg} \u2014 scan non-safe (Finding 4 fail-closed)`
|
|
3067
|
+
);
|
|
3068
|
+
throw new RunProRulesFatalError(
|
|
3069
|
+
`Engine exception evaluating rule "${rule.id}" against "${file.relativePath}": ${msg}`
|
|
3070
|
+
);
|
|
3071
|
+
}
|
|
3072
|
+
for (const cf of canonicalFindings) {
|
|
3073
|
+
const lines = file.content.split("\n");
|
|
3074
|
+
const lineIndex = cf.line - 1;
|
|
3075
|
+
const commentSuppressed = lineIndex >= 0 ? isLineSuppressed(lines, lineIndex, rule.id) : false;
|
|
3076
|
+
const isSuppressed = cf.suppressionState === "suppressed" || commentSuppressed;
|
|
3077
|
+
findings.push({
|
|
3078
|
+
id: rule.id,
|
|
3079
|
+
title: rule.explanation.split(".")[0],
|
|
3080
|
+
severity: rule.severity,
|
|
3081
|
+
category: rule.category,
|
|
3082
|
+
file: file.relativePath,
|
|
3083
|
+
line: cf.line,
|
|
3084
|
+
column: cf.column,
|
|
3085
|
+
evidence: cf.evidence ?? void 0,
|
|
3086
|
+
explanation: rule.explanation,
|
|
3087
|
+
recommendation: rule.recommendation,
|
|
3088
|
+
blocking: isSuppressed ? false : deriveBlocking(rule),
|
|
3089
|
+
suppressed: isSuppressed,
|
|
3090
|
+
// New fields from contract integration (Task A-CLI-INT.2)
|
|
3091
|
+
suppressionState: isSuppressed ? "suppressed" : "active",
|
|
3092
|
+
matcherType: cf.matcherType,
|
|
3093
|
+
// releaseId: 'pre-attestation' — not set on Finding until Phase C wires
|
|
3094
|
+
// the real attested releaseId into the bundle response.
|
|
3095
|
+
// New fields from QualityGateRule
|
|
3096
|
+
fix: rule.fix,
|
|
3097
|
+
confidence: rule.confidence,
|
|
3098
|
+
aiCodeTarget: rule.aiCodeTarget,
|
|
3099
|
+
cwe: rule.cwe
|
|
3100
|
+
});
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
return findings;
|
|
3105
|
+
}
|
|
3106
|
+
function runProRulesWithDispatch(rules, files, policy, cliVersion, table, manifest) {
|
|
3107
|
+
const augmented = rules;
|
|
3108
|
+
const coderefs = augmented.filter((r) => r.implType === "coderef");
|
|
3109
|
+
const declaratives = augmented.filter((r) => r.implType !== "coderef");
|
|
3110
|
+
let declarativeFindings = [];
|
|
3111
|
+
let fatalErrorReason;
|
|
3112
|
+
if (declaratives.length > 0) {
|
|
3113
|
+
try {
|
|
3114
|
+
declarativeFindings = runProRules(declaratives, files, policy);
|
|
3115
|
+
} catch (err) {
|
|
3116
|
+
if (err instanceof RunProRulesFatalError) {
|
|
3117
|
+
fatalErrorReason = err.message;
|
|
3118
|
+
console.error(
|
|
3119
|
+
`[shipguard] runProRules fatal error \u2014 scan non-safe: ${err.message}`
|
|
3120
|
+
);
|
|
3121
|
+
} else {
|
|
3122
|
+
throw err;
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
const compileResult = fatalErrorReason === void 0 && declaratives.length > 0 ? validateBundleCompile(declaratives) : { ok: true };
|
|
3127
|
+
const compileDegraded = !compileResult.ok;
|
|
3128
|
+
const fatalDegraded = fatalErrorReason !== void 0;
|
|
3129
|
+
const compileWarnings = compileDegraded ? [`Pro rule bundle compile failure: ${compileResult.reason}`] : fatalDegraded ? [`Pro rule bundle fatal execution error: ${fatalErrorReason}`] : [];
|
|
3130
|
+
const dispatchArgs = [
|
|
3131
|
+
coderefs,
|
|
3132
|
+
files,
|
|
3133
|
+
policy
|
|
3134
|
+
];
|
|
3135
|
+
if (cliVersion !== void 0) dispatchArgs.push(cliVersion);
|
|
3136
|
+
if (table !== void 0) dispatchArgs.push(table);
|
|
3137
|
+
if (manifest !== void 0) dispatchArgs.push(manifest);
|
|
3138
|
+
const { findings: coderefFindings, degraded: coderefDegraded, warnings: coderefWarnings } = runCoderefRules(...dispatchArgs);
|
|
3139
|
+
return {
|
|
3140
|
+
findings: [...declarativeFindings, ...coderefFindings],
|
|
3141
|
+
degraded: compileDegraded || fatalDegraded || coderefDegraded,
|
|
3142
|
+
warnings: [...compileWarnings, ...coderefWarnings]
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
|
|
3146
|
+
export {
|
|
3147
|
+
secretsCheck,
|
|
3148
|
+
authCheck,
|
|
3149
|
+
databaseCheck,
|
|
3150
|
+
payments,
|
|
3151
|
+
deploymentCheck,
|
|
3152
|
+
assertTrustedApiUrl,
|
|
3153
|
+
loadCredentials,
|
|
3154
|
+
saveCredentials,
|
|
3155
|
+
clearCredentials,
|
|
3156
|
+
isTokenExpired,
|
|
3157
|
+
getAuthToken,
|
|
3158
|
+
loadChecksumManifest,
|
|
3159
|
+
applySuppressions,
|
|
3160
|
+
NoRulesAppliedError,
|
|
3161
|
+
fetchProRules,
|
|
3162
|
+
validateBundleCompile,
|
|
3163
|
+
RunProRulesFatalError,
|
|
3164
|
+
runProRules,
|
|
3165
|
+
runProRulesWithDispatch
|
|
3166
|
+
};
|