@akasecurity/ai-tc-codex 0.9.16 → 0.9.17
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/.codex-plugin/plugin.json +1 -1
- package/package.json +6 -6
- package/scripts/apply-suppressions.js +739 -1263
- package/scripts/backfill.js +1040 -1291
- package/scripts/content-retention.js +781 -2074
- package/scripts/filescan.js +1266 -497
- package/scripts/firstrun.js +1277 -1701
- package/scripts/history-sync.js +777 -2107
- package/scripts/intro.js +141 -2190
- package/scripts/onboard.js +2806 -1186
- package/scripts/post-tool-use.js +1512 -1728
- package/scripts/pre-tool-use.js +1094 -1319
- package/scripts/query.js +1277 -1701
- package/scripts/reconcile.js +897 -1288
- package/scripts/remediate.js +1081 -1341
- package/scripts/scan-worker.js +147 -14
- package/scripts/session-start.js +1895 -827
- package/scripts/start-light.js +176 -1360
- package/scripts/stop.js +322 -1113
- package/scripts/sync.js +1818 -1029
- package/scripts/user-prompt-submit.js +1295 -1489
package/scripts/session-start.js
CHANGED
|
@@ -52,7 +52,7 @@ var require_ignore = __commonJS({
|
|
|
52
52
|
var DOUBLE_SLASH = "//";
|
|
53
53
|
var SLASH_CODE = 47;
|
|
54
54
|
var DOT_CODE = 46;
|
|
55
|
-
var
|
|
55
|
+
var SLASH4 = "/";
|
|
56
56
|
var TMP_KEY_IGNORE = "node-ignore";
|
|
57
57
|
if (typeof Symbol !== "undefined") {
|
|
58
58
|
TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
|
|
@@ -289,13 +289,13 @@ var require_ignore = __commonJS({
|
|
|
289
289
|
// A leading slash matches the beginning of the pathname
|
|
290
290
|
/^\//,
|
|
291
291
|
() => "^",
|
|
292
|
-
|
|
292
|
+
SLASH4
|
|
293
293
|
],
|
|
294
294
|
// replace special metacharacter slash after the leading slash
|
|
295
295
|
[
|
|
296
296
|
/\//g,
|
|
297
297
|
() => "\\/",
|
|
298
|
-
|
|
298
|
+
SLASH4
|
|
299
299
|
],
|
|
300
300
|
[
|
|
301
301
|
// > A leading "**" followed by a slash means match in all directories.
|
|
@@ -411,7 +411,7 @@ var require_ignore = __commonJS({
|
|
|
411
411
|
if (!last || last === TRAILING_WILDCARD || last === TRAILING_DOUBLESTAR) {
|
|
412
412
|
return source;
|
|
413
413
|
}
|
|
414
|
-
return last ===
|
|
414
|
+
return last === SLASH4 ? `${source}$` : `${source}(?=$|\\/$)`;
|
|
415
415
|
}
|
|
416
416
|
]
|
|
417
417
|
];
|
|
@@ -541,7 +541,7 @@ var require_ignore = __commonJS({
|
|
|
541
541
|
) : replaced;
|
|
542
542
|
};
|
|
543
543
|
var checkSourceOf = (body, prefix) => {
|
|
544
|
-
if (body[body.length - 1] ===
|
|
544
|
+
if (body[body.length - 1] === SLASH4) {
|
|
545
545
|
prefix = makeRegexPrefix(body.slice(0, -1));
|
|
546
546
|
}
|
|
547
547
|
const head = prefix.slice(0, -1);
|
|
@@ -549,26 +549,26 @@ var require_ignore = __commonJS({
|
|
|
549
549
|
return last === TRAILING_WILDCARD ? `${head}$` : last === TRAILING_DOUBLESTAR ? `${head}.*$` : NEVER_MATCH;
|
|
550
550
|
};
|
|
551
551
|
var matchesBasename = (body) => {
|
|
552
|
-
const index = body.indexOf(
|
|
552
|
+
const index = body.indexOf(SLASH4);
|
|
553
553
|
return index < 0 || index === body.length - 1;
|
|
554
554
|
};
|
|
555
555
|
var basenameOf = (path) => {
|
|
556
556
|
const end = path.length - 1;
|
|
557
557
|
const index = path.lastIndexOf(
|
|
558
|
-
|
|
559
|
-
path[end] ===
|
|
558
|
+
SLASH4,
|
|
559
|
+
path[end] === SLASH4 ? end - 1 : end
|
|
560
560
|
);
|
|
561
561
|
return index < 0 ? path : path.slice(index + 1);
|
|
562
562
|
};
|
|
563
563
|
var parentOf = (path) => {
|
|
564
564
|
if (path.charCodeAt(0) === SLASH_CODE || path.indexOf(DOUBLE_SLASH) >= 0) {
|
|
565
|
-
const slices = path.split(
|
|
565
|
+
const slices = path.split(SLASH4).filter(Boolean);
|
|
566
566
|
slices.pop();
|
|
567
|
-
return slices.length ? slices.join(
|
|
567
|
+
return slices.length ? slices.join(SLASH4) + SLASH4 : EMPTY;
|
|
568
568
|
}
|
|
569
569
|
const end = path.length - 1;
|
|
570
570
|
const cut = path.lastIndexOf(
|
|
571
|
-
|
|
571
|
+
SLASH4,
|
|
572
572
|
path.charCodeAt(end) === SLASH_CODE ? end - 1 : end
|
|
573
573
|
);
|
|
574
574
|
return cut < 0 ? EMPTY : path.slice(0, cut + 1);
|
|
@@ -679,7 +679,7 @@ var require_ignore = __commonJS({
|
|
|
679
679
|
// are left out once, rather than tested or compiled for every path.
|
|
680
680
|
testLiteral(path) {
|
|
681
681
|
const rules = this._literalRules || (this._literalRules = this._rules.filter(
|
|
682
|
-
({ body }) => body[body.length - (body[body.length - 1] ===
|
|
682
|
+
({ body }) => body[body.length - (body[body.length - 1] === SLASH4 ? 2 : 1)] === "*"
|
|
683
683
|
));
|
|
684
684
|
let ignored = false;
|
|
685
685
|
let unignored = false;
|
|
@@ -716,13 +716,13 @@ var require_ignore = __commonJS({
|
|
|
716
716
|
const rules = this._rules;
|
|
717
717
|
const { length } = rules;
|
|
718
718
|
const shortcut = this._basenameCount * 2 >= length;
|
|
719
|
-
const
|
|
719
|
+
const basename7 = shortcut ? basenameOf(path) : path;
|
|
720
720
|
for (let index = 0; index < length; index++) {
|
|
721
721
|
const rule = rules[index];
|
|
722
722
|
const { negative } = rule;
|
|
723
723
|
const skip = unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored;
|
|
724
724
|
if (!skip && rule[mode].test(
|
|
725
|
-
shortcut && rule._basenameOnly ?
|
|
725
|
+
shortcut && rule._basenameOnly ? basename7 : path
|
|
726
726
|
)) {
|
|
727
727
|
ignored = !negative;
|
|
728
728
|
unignored = negative;
|
|
@@ -873,19 +873,7 @@ var require_ignore = __commonJS({
|
|
|
873
873
|
});
|
|
874
874
|
|
|
875
875
|
// src/hooks/session-start.ts
|
|
876
|
-
import { readFileSync as
|
|
877
|
-
|
|
878
|
-
// ../../packages/persistence/src/attached-derived.ts
|
|
879
|
-
import { rmSync } from "fs";
|
|
880
|
-
import { join } from "path";
|
|
881
|
-
var POLICY_CACHE_FILENAME = "policy-cache.json";
|
|
882
|
-
var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
|
|
883
|
-
var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
|
|
884
|
-
var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
|
|
885
|
-
|
|
886
|
-
// ../../packages/persistence/src/control-plane-credential.ts
|
|
887
|
-
import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
|
|
888
|
-
import { join as join2 } from "path";
|
|
876
|
+
import { readFileSync as readFileSync24 } from "fs";
|
|
889
877
|
|
|
890
878
|
// ../../packages/schema/src/drizzle/deferred-migrations.ts
|
|
891
879
|
var DEFERRED_MIGRATION_TAGS = [
|
|
@@ -1057,6 +1045,12 @@ var HOUR_MS = 60 * MINUTE_MS;
|
|
|
1057
1045
|
var MAX_TEMPORARY_MS = 24 * HOUR_MS;
|
|
1058
1046
|
var ONCE_BACKSTOP_MS = 30 * MINUTE_MS;
|
|
1059
1047
|
|
|
1048
|
+
// ../../packages/schema/src/invisible-padding.ts
|
|
1049
|
+
var INVISIBLE_PADDING = /[\u00AD\u061C\u180E\u200B\u200E\u200F\u2060-\u2064\u202A-\u202E\u2066-\u2069\uFEFF\uFFF9-\uFFFB\u{E0001}\u{E0020}-\u{E007F}]/gu;
|
|
1050
|
+
function stripInvisiblePadding(text) {
|
|
1051
|
+
return text.replace(INVISIBLE_PADDING, "");
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1060
1054
|
// ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
|
|
1061
1055
|
var external_exports = {};
|
|
1062
1056
|
__export(external_exports, {
|
|
@@ -20792,13 +20786,16 @@ function serviceTierMultiplier(tier) {
|
|
|
20792
20786
|
if (tier === void 0) return 1;
|
|
20793
20787
|
return SERVICE_TIER_MULTIPLIERS.get(tier) ?? 1;
|
|
20794
20788
|
}
|
|
20789
|
+
function promptTokensOf(usage) {
|
|
20790
|
+
return usage.promptTokens ?? (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0) + (usage.cacheWrite1hTokens ?? 0) + (usage.cacheWrite5mTokens ?? 0);
|
|
20791
|
+
}
|
|
20795
20792
|
function costOf(price, usage) {
|
|
20796
20793
|
const metered = [
|
|
20797
20794
|
[usage.cacheWrite1hTokens ?? 0, price.cacheWrite1h],
|
|
20798
20795
|
[usage.cacheWrite5mTokens ?? 0, price.cacheWrite5m],
|
|
20799
20796
|
[usage.cacheReadTokens ?? 0, price.cacheRead]
|
|
20800
20797
|
];
|
|
20801
|
-
const band = price.longContext !== null && (usage
|
|
20798
|
+
const band = price.longContext !== null && promptTokensOf(usage) > price.longContext.thresholdInputTokens ? price.longContext : null;
|
|
20802
20799
|
if (band !== null && (band.input === null || band.output === null)) return null;
|
|
20803
20800
|
const inputRate = band?.input ?? price.input;
|
|
20804
20801
|
const outputRate = band?.output ?? price.output;
|
|
@@ -21008,7 +21005,7 @@ var GATEWAY_VENDOR_SLASH_RE = /^[a-z0-9][\w.-]*\//iu;
|
|
|
21008
21005
|
var BEDROCK_VERSION_RE = /-v\d+:\d+$/u;
|
|
21009
21006
|
var BEDROCK_REVISION_RE = /:\d+$/u;
|
|
21010
21007
|
var VERTEX_VERSION_RE = /@[\w-]+$/u;
|
|
21011
|
-
var DATED_SUFFIX_RE =
|
|
21008
|
+
var DATED_SUFFIX_RE = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/u;
|
|
21012
21009
|
function stripPlatformDecorations(model) {
|
|
21013
21010
|
let id = model.trim();
|
|
21014
21011
|
let platform2 = null;
|
|
@@ -21158,7 +21155,7 @@ anthropic.model("claude-haiku-4-5", {
|
|
|
21158
21155
|
name: "Claude Haiku 4.5",
|
|
21159
21156
|
ctx: 2e5,
|
|
21160
21157
|
maxOut: 64e3,
|
|
21161
|
-
// Reviewed: fast/cheap tier,
|
|
21158
|
+
// Reviewed: fast/cheap general-purpose tier, not a reasoning or code model.
|
|
21162
21159
|
capability: null,
|
|
21163
21160
|
price: anthropicPrice(1, 5, 0.1),
|
|
21164
21161
|
// The vendor documents `claude-haiku-4-5-20251001` as the versioned id and
|
|
@@ -21289,6 +21286,11 @@ openai.model("gpt-4o", {
|
|
|
21289
21286
|
price: tokenPrice(2.5, 10, { cacheRead: 1.25 }),
|
|
21290
21287
|
on: [...OPENAI_RESELLERS]
|
|
21291
21288
|
});
|
|
21289
|
+
openai.model("gpt-4o-2024-05-13", {
|
|
21290
|
+
name: "GPT-4o (2024-05-13)",
|
|
21291
|
+
price: tokenPrice(5, 15),
|
|
21292
|
+
on: [...OPENAI_RESELLERS]
|
|
21293
|
+
});
|
|
21292
21294
|
openai.model("gpt-4o-mini", {
|
|
21293
21295
|
name: "GPT-4o mini",
|
|
21294
21296
|
price: tokenPrice(0.15, 0.6, { cacheRead: 0.075 }),
|
|
@@ -21308,6 +21310,24 @@ openai.model("o3", {
|
|
|
21308
21310
|
price: tokenPrice(2, 8, { cacheRead: 0.5 }),
|
|
21309
21311
|
on: [...OPENAI_RESELLERS]
|
|
21310
21312
|
});
|
|
21313
|
+
openai.model("text-embedding-3-small", {
|
|
21314
|
+
name: "text-embedding-3-small",
|
|
21315
|
+
capability: "embedding",
|
|
21316
|
+
price: tokenPrice(0.02, 0),
|
|
21317
|
+
on: [...OPENAI_RESELLERS]
|
|
21318
|
+
});
|
|
21319
|
+
openai.model("text-embedding-3-large", {
|
|
21320
|
+
name: "text-embedding-3-large",
|
|
21321
|
+
capability: "embedding",
|
|
21322
|
+
price: tokenPrice(0.13, 0),
|
|
21323
|
+
on: [...OPENAI_RESELLERS]
|
|
21324
|
+
});
|
|
21325
|
+
openai.model("text-embedding-ada-002", {
|
|
21326
|
+
name: "text-embedding-ada-002",
|
|
21327
|
+
capability: "embedding",
|
|
21328
|
+
price: tokenPrice(0.1, 0),
|
|
21329
|
+
on: [...OPENAI_RESELLERS]
|
|
21330
|
+
});
|
|
21311
21331
|
openai.model("gpt-oss-120b", {
|
|
21312
21332
|
name: "GPT-OSS 120B",
|
|
21313
21333
|
openWeights: true,
|
|
@@ -21594,10 +21614,21 @@ var MODEL_ENTRIES = Object.freeze([
|
|
|
21594
21614
|
...alibaba.models(),
|
|
21595
21615
|
...amazon.models()
|
|
21596
21616
|
]);
|
|
21617
|
+
var LONG_CONTEXT_THRESHOLDS = Object.freeze(
|
|
21618
|
+
[
|
|
21619
|
+
...new Set(
|
|
21620
|
+
MODEL_ENTRIES.flatMap(
|
|
21621
|
+
(entry) => [...entry.platforms.values()].flatMap(
|
|
21622
|
+
(offering) => offering.price?.longContext ? [offering.price.longContext.thresholdInputTokens] : []
|
|
21623
|
+
)
|
|
21624
|
+
)
|
|
21625
|
+
)
|
|
21626
|
+
].sort((a, b) => a - b)
|
|
21627
|
+
);
|
|
21597
21628
|
var MODEL_INDEX = buildModelIndex(MODEL_ENTRIES);
|
|
21598
21629
|
|
|
21599
21630
|
// ../../packages/schema/src/model/governance.ts
|
|
21600
|
-
var ModelCapability = external_exports.enum(["reasoning", "code"]);
|
|
21631
|
+
var ModelCapability = external_exports.enum(["reasoning", "code", "embedding"]);
|
|
21601
21632
|
var DataRetention = external_exports.enum([
|
|
21602
21633
|
"zero_retention",
|
|
21603
21634
|
"no_storage",
|
|
@@ -21728,7 +21759,7 @@ var COMPACT = new Intl.NumberFormat("en-US", {
|
|
|
21728
21759
|
|
|
21729
21760
|
// ../../packages/schema/src/token/token-report.ts
|
|
21730
21761
|
var num = (value) => value ?? 0;
|
|
21731
|
-
function costUsageOf(a) {
|
|
21762
|
+
function costUsageOf(a, promptTokens) {
|
|
21732
21763
|
const usage = {
|
|
21733
21764
|
inputTokens: num(a.input_tokens),
|
|
21734
21765
|
outputTokens: num(a.output_tokens),
|
|
@@ -21738,11 +21769,12 @@ function costUsageOf(a) {
|
|
|
21738
21769
|
webSearchRequests: num(a.web_search_requests)
|
|
21739
21770
|
};
|
|
21740
21771
|
if (a.service_tier !== void 0) usage.serviceTier = a.service_tier;
|
|
21772
|
+
if (promptTokens !== void 0) usage.promptTokens = promptTokens;
|
|
21741
21773
|
return usage;
|
|
21742
21774
|
}
|
|
21743
21775
|
function buildTokenReports(leaves, costModel) {
|
|
21744
21776
|
const bySession = /* @__PURE__ */ new Map();
|
|
21745
|
-
for (const { sessionId, attributes } of leaves) {
|
|
21777
|
+
for (const { sessionId, attributes, promptTokens } of leaves) {
|
|
21746
21778
|
const provider = attributes.provider ?? "unknown";
|
|
21747
21779
|
const model = attributes.model ?? "unknown";
|
|
21748
21780
|
const key = `${provider} ${model}`;
|
|
@@ -21761,7 +21793,8 @@ function buildTokenReports(leaves, costModel) {
|
|
|
21761
21793
|
cacheCreation: 0,
|
|
21762
21794
|
cacheRead: 0,
|
|
21763
21795
|
costUsd: 0,
|
|
21764
|
-
priced: false
|
|
21796
|
+
priced: false,
|
|
21797
|
+
partial: false
|
|
21765
21798
|
};
|
|
21766
21799
|
rollups.set(key, acc);
|
|
21767
21800
|
}
|
|
@@ -21769,8 +21802,14 @@ function buildTokenReports(leaves, costModel) {
|
|
|
21769
21802
|
acc.output += num(attributes.output_tokens);
|
|
21770
21803
|
acc.cacheCreation += num(attributes.cache_creation_input_tokens);
|
|
21771
21804
|
acc.cacheRead += num(attributes.cache_read_input_tokens);
|
|
21772
|
-
const leafCost = costModel.costFor({
|
|
21773
|
-
|
|
21805
|
+
const leafCost = costModel.costFor({
|
|
21806
|
+
provider,
|
|
21807
|
+
model,
|
|
21808
|
+
usage: costUsageOf(attributes, promptTokens)
|
|
21809
|
+
});
|
|
21810
|
+
if (leafCost === null) {
|
|
21811
|
+
acc.partial = true;
|
|
21812
|
+
} else {
|
|
21774
21813
|
acc.costUsd += leafCost;
|
|
21775
21814
|
acc.priced = true;
|
|
21776
21815
|
}
|
|
@@ -21786,9 +21825,8 @@ function buildTokenReports(leaves, costModel) {
|
|
|
21786
21825
|
const rollupTotal = acc.input + acc.output + acc.cacheCreation + acc.cacheRead;
|
|
21787
21826
|
totalTokens += rollupTotal;
|
|
21788
21827
|
const estimatedCostUsd = acc.priced ? acc.costUsd : null;
|
|
21789
|
-
if (
|
|
21790
|
-
|
|
21791
|
-
} else {
|
|
21828
|
+
if (acc.partial) anyUnpriced = true;
|
|
21829
|
+
if (estimatedCostUsd !== null) {
|
|
21792
21830
|
anyPriced = true;
|
|
21793
21831
|
costUsd += estimatedCostUsd;
|
|
21794
21832
|
}
|
|
@@ -21811,7 +21849,7 @@ function buildTokenReports(leaves, costModel) {
|
|
|
21811
21849
|
totalTokens,
|
|
21812
21850
|
// Σ of the PRICED rollups; null when none had a known price.
|
|
21813
21851
|
estimatedCostUsd: anyPriced ? costUsd : null,
|
|
21814
|
-
// Any
|
|
21852
|
+
// Any call priced to null means the total understates real spend.
|
|
21815
21853
|
costIsPartial: anyUnpriced
|
|
21816
21854
|
});
|
|
21817
21855
|
}
|
|
@@ -22516,6 +22554,11 @@ var CaptureAttributes = external_exports.object({
|
|
|
22516
22554
|
// here too. The full statement is on EventMetadata.redactDegradedTo; it is
|
|
22517
22555
|
// repeated rather than referenced because a store reader opens this file.
|
|
22518
22556
|
redact_degraded_to: ActionTaken.optional(),
|
|
22557
|
+
// Why a capture has no content and no findings: its field was refused
|
|
22558
|
+
// because its bounded scan did not finish (see EventMetadata.scanIncomplete,
|
|
22559
|
+
// whose value this is). Absent on every capture that was scanned, so a
|
|
22560
|
+
// reader can tell a refused row from an empty clean one.
|
|
22561
|
+
scan_incomplete: external_exports.enum(["timeout", "unavailable"]).optional(),
|
|
22519
22562
|
// The scope key this capture was stamped with: the canonical repository
|
|
22520
22563
|
// (`host/owner/repo`) of the path the capture names (a relative path is read
|
|
22521
22564
|
// against its working directory), else of its own working directory, or a
|
|
@@ -22693,8 +22736,9 @@ var SessionTokenReport = external_exports.object({
|
|
|
22693
22736
|
totalTokens: external_exports.number().int().nonnegative(),
|
|
22694
22737
|
// Σ of the PRICED rollups only; null when no rollup had a known price.
|
|
22695
22738
|
estimatedCostUsd: external_exports.number().nullable(),
|
|
22696
|
-
// True whenever any
|
|
22697
|
-
//
|
|
22739
|
+
// True whenever any call priced to null (an unknown provider/model, or a call
|
|
22740
|
+
// over a long-context threshold whose rate is unpublished), so the total
|
|
22741
|
+
// understates real spend — the UI renders `≥ $X` instead of a falsely
|
|
22698
22742
|
// precise figure rather than silently dropping the unpriced calls.
|
|
22699
22743
|
costIsPartial: external_exports.boolean()
|
|
22700
22744
|
});
|
|
@@ -23685,7 +23729,15 @@ var StorePostureSnapshot = external_exports.object({
|
|
|
23685
23729
|
policyCounts: StorePosturePolicyCounts,
|
|
23686
23730
|
// OPTIONAL, not nullable: a reporter that predates this member keeps
|
|
23687
23731
|
// getting its 200 without a payload change.
|
|
23688
|
-
plugin: StorePosturePlugin.optional()
|
|
23732
|
+
plugin: StorePosturePlugin.optional(),
|
|
23733
|
+
// OPTIONAL, and sent only by a scoped attachment, always as `scoped`. A
|
|
23734
|
+
// machine attachment omits it, so its body is byte for byte the one it
|
|
23735
|
+
// sent before this member existed. Absent therefore means machine-wide OR
|
|
23736
|
+
// a reporter older than this member, never "scoped". Both values parse, so
|
|
23737
|
+
// a sender that one day spells `machine` breaks no receiver; any other
|
|
23738
|
+
// value fails the whole snapshot, which is why the reporter sends a
|
|
23739
|
+
// constant and never the raw mode.
|
|
23740
|
+
attachmentMode: AttachmentMode.optional()
|
|
23689
23741
|
}).meta({ id: "StorePostureSnapshot" });
|
|
23690
23742
|
var CAPTURE_VERSION_PREFIX = "capture/";
|
|
23691
23743
|
var RecordAuditEventRequest = AuditEventInput.extend({
|
|
@@ -23962,7 +24014,19 @@ var EventMetadata = external_exports.object({
|
|
|
23962
24014
|
// Both are pinned as behaviour in @akasecurity/plugin-sdk's runtime suite.
|
|
23963
24015
|
// Closing either means moving the reason onto the finding row, which
|
|
23964
24016
|
// already carries its own action.
|
|
23965
|
-
redactDegradedTo: ActionTaken.optional()
|
|
24017
|
+
redactDegradedTo: ActionTaken.optional(),
|
|
24018
|
+
// Set when this capture's field was REFUSED rather than scanned: a hook
|
|
24019
|
+
// bounds the scan of a large field (see `LargeInputScanOptions` in
|
|
24020
|
+
// @akasecurity/plugin-sdk), and a scan that did not finish blocks the
|
|
24021
|
+
// field instead of letting it through unscanned.
|
|
24022
|
+
//
|
|
24023
|
+
// - 'timeout': the bounded scan ran out of time.
|
|
24024
|
+
// - 'unavailable': no worker could run it.
|
|
24025
|
+
//
|
|
24026
|
+
// A refused row stores '' as its content and has no findings, which is
|
|
24027
|
+
// exactly what a clean, empty capture looks like — this marker is the only
|
|
24028
|
+
// thing that tells the two apart. Absent on every capture that was scanned.
|
|
24029
|
+
scanIncomplete: external_exports.enum(["timeout", "unavailable"]).optional()
|
|
23966
24030
|
}).meta({ id: "EventMetadata" });
|
|
23967
24031
|
var Event = external_exports.object({
|
|
23968
24032
|
id: external_exports.guid(),
|
|
@@ -24132,7 +24196,7 @@ var Rule = external_exports.strictObject({
|
|
|
24132
24196
|
postValidators: external_exports.array(PostValidatorRef).optional(),
|
|
24133
24197
|
requiresNearby: RequiresNearby.optional(),
|
|
24134
24198
|
examples: external_exports.array(external_exports.string()).optional(),
|
|
24135
|
-
// Whether the matched text is itself sensitive
|
|
24199
|
+
// Whether the matched text is itself sensitive (see RuleEvidence).
|
|
24136
24200
|
evidence: RuleEvidence.optional()
|
|
24137
24201
|
}).meta({ id: "Rule" });
|
|
24138
24202
|
var Author = external_exports.object({
|
|
@@ -24224,7 +24288,13 @@ var DetectionRule = external_exports.object({
|
|
|
24224
24288
|
// Representative matching strings the rule author shipped with the rule. The
|
|
24225
24289
|
// cheapest honest answer to "show me what this rule catches" — every bundled
|
|
24226
24290
|
// rule has them, and they are already in the stored snapshot.
|
|
24227
|
-
examples: external_exports.array(external_exports.string()).optional()
|
|
24291
|
+
examples: external_exports.array(external_exports.string()).optional(),
|
|
24292
|
+
// The rule's DECLARED evidence, as stored. Absent defers to the engine's
|
|
24293
|
+
// classification (ruleEvidence in @akasecurity/detections): a bundled
|
|
24294
|
+
// code-flaw rule reads as 'code' and anything else as 'value', and a rule
|
|
24295
|
+
// in a value category (secret/pii/financial/phi) is always 'value',
|
|
24296
|
+
// whatever it declares.
|
|
24297
|
+
evidence: RuleEvidence.optional()
|
|
24228
24298
|
}).meta({ id: "DetectionRule" });
|
|
24229
24299
|
var DetectionUpdate = external_exports.object({
|
|
24230
24300
|
available: external_exports.boolean(),
|
|
@@ -24292,8 +24362,10 @@ var ImportDetectionRequest = external_exports.object({
|
|
|
24292
24362
|
}).meta({ id: "ImportDetectionRequest" });
|
|
24293
24363
|
|
|
24294
24364
|
// ../../packages/schema/src/zod/detection-build.ts
|
|
24295
|
-
function optional2(key,
|
|
24296
|
-
if (raw === void 0
|
|
24365
|
+
function optional2(key, raw, parse4) {
|
|
24366
|
+
if (raw === void 0) return {};
|
|
24367
|
+
const parsed2 = parse4(raw);
|
|
24368
|
+
if (!parsed2.success || parsed2.data === void 0) return {};
|
|
24297
24369
|
return { [key]: parsed2.data };
|
|
24298
24370
|
}
|
|
24299
24371
|
function isStringArray(value) {
|
|
@@ -24328,10 +24400,12 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
|
|
|
24328
24400
|
category: r.category,
|
|
24329
24401
|
severity: r.severity,
|
|
24330
24402
|
matcher: parsed2.data,
|
|
24331
|
-
//
|
|
24332
|
-
//
|
|
24333
|
-
//
|
|
24334
|
-
//
|
|
24403
|
+
// `appliesTo`, `postValidators` and `requiresNearby` are the rest of what
|
|
24404
|
+
// decides whether this rule fires. Carried so a consumer re-running the
|
|
24405
|
+
// rule (a preview, a tester) evaluates what the engine evaluates rather
|
|
24406
|
+
// than a matcher stripped of its guards — half the bundled catalog
|
|
24407
|
+
// carries at least one of these. `examples` and `evidence` describe the
|
|
24408
|
+
// rule and never gate a match.
|
|
24335
24409
|
//
|
|
24336
24410
|
// Enrichment is deliberately per-field and best-effort, NOT a whole-rule
|
|
24337
24411
|
// `Rule.safeParse`. Two reasons: `Rule` is a strict object pinned to
|
|
@@ -24341,18 +24415,19 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
|
|
|
24341
24415
|
// test should stay exactly what it was, namely a renderable matcher. A
|
|
24342
24416
|
// field that fails validation is omitted, which reads as "not set" and is
|
|
24343
24417
|
// the same thing the consumer saw before this change.
|
|
24344
|
-
...optional2("appliesTo",
|
|
24418
|
+
...optional2("appliesTo", r.appliesTo, (v) => AppliesTo.safeParse(v)),
|
|
24345
24419
|
...optional2(
|
|
24346
24420
|
"postValidators",
|
|
24347
|
-
|
|
24348
|
-
|
|
24421
|
+
r.postValidators,
|
|
24422
|
+
(v) => PostValidatorRef.array().safeParse(v)
|
|
24349
24423
|
),
|
|
24350
|
-
...optional2("requiresNearby",
|
|
24424
|
+
...optional2("requiresNearby", r.requiresNearby, (v) => RequiresNearby.safeParse(v)),
|
|
24351
24425
|
...optional2(
|
|
24352
24426
|
"examples",
|
|
24353
|
-
|
|
24354
|
-
|
|
24355
|
-
)
|
|
24427
|
+
r.examples,
|
|
24428
|
+
(v) => isStringArray(v) ? { success: true, data: v } : { success: false }
|
|
24429
|
+
),
|
|
24430
|
+
...optional2("evidence", r.evidence, (v) => RuleEvidence.safeParse(v))
|
|
24356
24431
|
}
|
|
24357
24432
|
];
|
|
24358
24433
|
});
|
|
@@ -25045,11 +25120,14 @@ var PolicyBundle = external_exports.object({
|
|
|
25045
25120
|
ruleVersions: external_exports.record(external_exports.string(), external_exports.string()).optional(),
|
|
25046
25121
|
// Model ids (the raw `model` string a harness reports, e.g.
|
|
25047
25122
|
// `claude-opus-4-1`) the tenant has PROHIBITED. The plugin refuses to switch
|
|
25048
|
-
// a session onto one (PreModelSwitch)
|
|
25049
|
-
//
|
|
25050
|
-
//
|
|
25051
|
-
//
|
|
25052
|
-
//
|
|
25123
|
+
// a session onto one (PreModelSwitch), refuses a turn that would run on one
|
|
25124
|
+
// (UserPromptSubmit) and refuses a subagent spawn onto one (PreToolUse),
|
|
25125
|
+
// wherever the organization governs the event: everywhere on a
|
|
25126
|
+
// machine-wide attachment, and only in enrolled repositories on a scoped
|
|
25127
|
+
// one (the plugin runtime's `governanceApplies`).
|
|
25128
|
+
// Optional so an older backend — and an older on-disk cache — still
|
|
25129
|
+
// parses; consumers read `?? []`, which is the unenforced behaviour that
|
|
25130
|
+
// predates this field and the safe direction to default.
|
|
25053
25131
|
//
|
|
25054
25132
|
// Ids, not display names: the governance decision is keyed on the exact
|
|
25055
25133
|
// string the harness reports (`model_status_override.versionId` in the
|
|
@@ -25511,6 +25589,8 @@ var AttachmentScopeEntry = external_exports.object({
|
|
|
25511
25589
|
});
|
|
25512
25590
|
var AttachmentScope = external_exports.object({
|
|
25513
25591
|
endpoint: external_exports.string().min(1),
|
|
25592
|
+
tenantName: PluginWhoami.shape.tenantName.optional(),
|
|
25593
|
+
userEmail: PluginWhoami.shape.userEmail.optional(),
|
|
25514
25594
|
entries: external_exports.array(AttachmentScopeEntry)
|
|
25515
25595
|
});
|
|
25516
25596
|
var AttachmentScopeEnvelope = AttachmentScope.extend({ entries: external_exports.array(external_exports.unknown()) });
|
|
@@ -25523,7 +25603,13 @@ function parseAttachmentScope(raw) {
|
|
|
25523
25603
|
const entry = AttachmentScopeEntry.safeParse(candidate);
|
|
25524
25604
|
if (entry.success) entries.push(entry.data);
|
|
25525
25605
|
}
|
|
25526
|
-
|
|
25606
|
+
const { endpoint, tenantName, userEmail } = envelope.data;
|
|
25607
|
+
return {
|
|
25608
|
+
endpoint,
|
|
25609
|
+
...tenantName === void 0 ? {} : { tenantName },
|
|
25610
|
+
...userEmail === void 0 ? {} : { userEmail },
|
|
25611
|
+
entries
|
|
25612
|
+
};
|
|
25527
25613
|
} catch {
|
|
25528
25614
|
return void 0;
|
|
25529
25615
|
}
|
|
@@ -25760,6 +25846,7 @@ function toCaptureAttributes(event) {
|
|
|
25760
25846
|
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
25761
25847
|
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
25762
25848
|
...metadata?.redactDegradedTo !== void 0 ? { redact_degraded_to: metadata.redactDegradedTo } : {},
|
|
25849
|
+
...metadata?.scanIncomplete !== void 0 ? { scan_incomplete: metadata.scanIncomplete } : {},
|
|
25763
25850
|
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
25764
25851
|
// has ever populated either), but every legacy metadata key still rides
|
|
25765
25852
|
// the bag rather than being silently dropped — CaptureAttributes'
|
|
@@ -25888,6 +25975,27 @@ var ManagedSettings = external_exports.object({
|
|
|
25888
25975
|
};
|
|
25889
25976
|
}).meta({ id: "ManagedSettings" });
|
|
25890
25977
|
|
|
25978
|
+
// ../../packages/schema/src/zod/mod-policy-snapshot.ts
|
|
25979
|
+
var MOD_POLICY_SNAPSHOT_VERSION = 1;
|
|
25980
|
+
var MOD_POLICY_SNAPSHOT_MAX_BYTES = 4 * 1024 * 1024;
|
|
25981
|
+
var ModPolicySnapshot = external_exports.object({
|
|
25982
|
+
version: external_exports.literal(MOD_POLICY_SNAPSHOT_VERSION),
|
|
25983
|
+
generatedAt: external_exports.iso.datetime(),
|
|
25984
|
+
// The complete effective ruleset, as the hook's runtime scans with it: the
|
|
25985
|
+
// user's enabled installed packs (user-modified and custom packs included).
|
|
25986
|
+
// Absent means the store holds no authoritative snapshot, and the reader
|
|
25987
|
+
// scans with the packs it ships — the hook's own fallback.
|
|
25988
|
+
rules: external_exports.array(Rule).optional(),
|
|
25989
|
+
// Rule-targeted actions (first enabled policy per rule wins).
|
|
25990
|
+
ruleActions: external_exports.record(external_exports.string(), ActionTaken),
|
|
25991
|
+
// The resolved action per detection category.
|
|
25992
|
+
categoryActions: external_exports.record(external_exports.string(), ActionTaken),
|
|
25993
|
+
// Rules with an active exception grant. Honouring a grant means matching a
|
|
25994
|
+
// keyed fingerprint of the value and consuming a use, which only the hook can
|
|
25995
|
+
// do, so the mod leaves a finding of one of these rules for the hook to decide.
|
|
25996
|
+
exceptionRuleIds: external_exports.array(external_exports.string())
|
|
25997
|
+
}).meta({ id: "ModPolicySnapshot" });
|
|
25998
|
+
|
|
25891
25999
|
// ../../packages/schema/src/zod/project-files.ts
|
|
25892
26000
|
var ProjectFileInput = external_exports.object({
|
|
25893
26001
|
path: external_exports.string().min(1),
|
|
@@ -26208,7 +26316,16 @@ var AttachInput = external_exports.object({
|
|
|
26208
26316
|
// 200 matches the tenantName bound beside it in control-plane.ts; nothing
|
|
26209
26317
|
// renders a longer one usefully.
|
|
26210
26318
|
label: printable(200).optional(),
|
|
26211
|
-
accessKey: external_exports.string()
|
|
26319
|
+
accessKey: external_exports.string(),
|
|
26320
|
+
// How much of this machine the attachment is for: everything, or only the
|
|
26321
|
+
// repositories its user enrolls. Optional, so an input without it still
|
|
26322
|
+
// parses; what an absent mode means is for whatever reads it to decide, not
|
|
26323
|
+
// this shape. This member validates the VALUE rather than leaving that to the
|
|
26324
|
+
// call site, a deliberate exception to this module's shape-only rule: a shape
|
|
26325
|
+
// rejection names the field, so a value that is not a mode is refused as a bad
|
|
26326
|
+
// `mode` rather than stripped or passed on. The dashboard's attach action reads
|
|
26327
|
+
// it as the mode to attach in.
|
|
26328
|
+
mode: AttachmentMode.optional()
|
|
26212
26329
|
});
|
|
26213
26330
|
|
|
26214
26331
|
// ../../packages/schema/src/zod/triage.ts
|
|
@@ -26494,6 +26611,18 @@ function fromCaptureStatusAttributes(bag) {
|
|
|
26494
26611
|
return parsedStatus.success ? parsedStatus.data : null;
|
|
26495
26612
|
}
|
|
26496
26613
|
|
|
26614
|
+
// ../../packages/persistence/src/attached-derived.ts
|
|
26615
|
+
import { rmSync } from "fs";
|
|
26616
|
+
import { join } from "path";
|
|
26617
|
+
var POLICY_CACHE_FILENAME = "policy-cache.json";
|
|
26618
|
+
var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
|
|
26619
|
+
var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
|
|
26620
|
+
var ATTACHED_POSTURE_REPORT_FILENAME = "attached-posture-report.json";
|
|
26621
|
+
|
|
26622
|
+
// ../../packages/persistence/src/control-plane-credential.ts
|
|
26623
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync2, readFileSync, rmSync as rmSync3, statSync } from "fs";
|
|
26624
|
+
import { join as join2 } from "path";
|
|
26625
|
+
|
|
26497
26626
|
// ../../packages/persistence/src/paths.ts
|
|
26498
26627
|
import {
|
|
26499
26628
|
chmodSync,
|
|
@@ -26624,6 +26753,14 @@ function readControlPlaneCredentialState(settingsDir2, connection) {
|
|
|
26624
26753
|
const read = readControlPlaneCredentialFile(settingsDir2, connection);
|
|
26625
26754
|
return read.usable ? { usable: true } : read;
|
|
26626
26755
|
}
|
|
26756
|
+
function asReadableCredential(value) {
|
|
26757
|
+
const result = AttachedCredentialAny.safeParse(value);
|
|
26758
|
+
if (!result.success) return null;
|
|
26759
|
+
if (attachmentModeOf(result.data) === "machine" && typeof value === "object" && value !== null && Object.hasOwn(value, "mode")) {
|
|
26760
|
+
return null;
|
|
26761
|
+
}
|
|
26762
|
+
return result.data;
|
|
26763
|
+
}
|
|
26627
26764
|
function readControlPlaneCredentialFile(settingsDir2, connection) {
|
|
26628
26765
|
const file2 = controlPlaneCredentialPath(settingsDir2);
|
|
26629
26766
|
let raw;
|
|
@@ -26642,20 +26779,20 @@ function readControlPlaneCredentialFile(settingsDir2, connection) {
|
|
|
26642
26779
|
} catch {
|
|
26643
26780
|
return { usable: false, reason: "malformed" };
|
|
26644
26781
|
}
|
|
26645
|
-
const
|
|
26646
|
-
if (
|
|
26647
|
-
if (!isSafeEndpoint(
|
|
26782
|
+
const credential = asReadableCredential(parsed2);
|
|
26783
|
+
if (credential === null) return { usable: false, reason: "malformed" };
|
|
26784
|
+
if (!isSafeEndpoint(credential.endpoint)) {
|
|
26648
26785
|
return { usable: false, reason: "unsafe-endpoint" };
|
|
26649
26786
|
}
|
|
26650
|
-
if (connection !== void 0 && connection.endpoint !==
|
|
26787
|
+
if (connection !== void 0 && connection.endpoint !== credential.endpoint) {
|
|
26651
26788
|
return {
|
|
26652
26789
|
usable: false,
|
|
26653
26790
|
reason: "endpoint-mismatch",
|
|
26654
|
-
credentialEndpoint:
|
|
26791
|
+
credentialEndpoint: credential.endpoint,
|
|
26655
26792
|
settingsEndpoint: connection.endpoint
|
|
26656
26793
|
};
|
|
26657
26794
|
}
|
|
26658
|
-
return { usable: true, credential
|
|
26795
|
+
return { usable: true, credential };
|
|
26659
26796
|
}
|
|
26660
26797
|
function readControlPlaneCredential(settingsDir2, connection) {
|
|
26661
26798
|
const read = readControlPlaneCredentialFile(settingsDir2, connection);
|
|
@@ -26664,7 +26801,7 @@ function readControlPlaneCredential(settingsDir2, connection) {
|
|
|
26664
26801
|
|
|
26665
26802
|
// ../../packages/persistence/src/database.ts
|
|
26666
26803
|
import { randomUUID as randomUUID11 } from "crypto";
|
|
26667
|
-
import { dirname as dirname2, join as
|
|
26804
|
+
import { dirname as dirname2, join as join8, sep } from "path";
|
|
26668
26805
|
import { DatabaseSync } from "node:sqlite";
|
|
26669
26806
|
|
|
26670
26807
|
// ../../packages/persistence/src/ids.ts
|
|
@@ -26708,6 +26845,7 @@ function captureId(sessionId, contentHash, filePath = null) {
|
|
|
26708
26845
|
canonicalIdentity(["capture", sessionId ?? NO_SESSION, contentHash, filePath ?? NO_PATH])
|
|
26709
26846
|
);
|
|
26710
26847
|
}
|
|
26848
|
+
var DOT = ".".charCodeAt(0);
|
|
26711
26849
|
|
|
26712
26850
|
// ../../packages/persistence/src/internal/snapshot.ts
|
|
26713
26851
|
import { randomUUID } from "crypto";
|
|
@@ -27035,6 +27173,25 @@ function scopeKeysParam(scopeKeys) {
|
|
|
27035
27173
|
var ROOT_SCOPE_KEY = `(SELECT session_root.scope_key
|
|
27036
27174
|
FROM audit_events AS session_root
|
|
27037
27175
|
WHERE session_root.id = COALESCE(audit_events.root_session_id, audit_events.id))`;
|
|
27176
|
+
var COUNTED_IN_SCOPE = `
|
|
27177
|
+
AND ${inScope("scope_key")}
|
|
27178
|
+
AND (event_type IN (${CAPTURE_TYPE_LIST}) OR ${inScope(ROOT_SCOPE_KEY)})`;
|
|
27179
|
+
var DRAIN_TOTALS = `SELECT
|
|
27180
|
+
SUM(CASE WHEN synced_at IS NULL AND started_at < :before THEN 1 ELSE 0 END) AS pending,
|
|
27181
|
+
SUM(CASE WHEN synced_at > 0 THEN 1 ELSE 0 END) AS sent,
|
|
27182
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27183
|
+
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
27184
|
+
THEN 1 ELSE 0 END) AS skipped,
|
|
27185
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27186
|
+
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
27187
|
+
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27188
|
+
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
27189
|
+
FROM audit_events
|
|
27190
|
+
WHERE event_type IN (${TYPE_LIST})`;
|
|
27191
|
+
var CAPTURE_SKIPS = `SELECT COUNT(*) AS skipped
|
|
27192
|
+
FROM audit_events
|
|
27193
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
27194
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`;
|
|
27038
27195
|
var ROW_COLUMNS = `id,
|
|
27039
27196
|
parent_id AS parentId,
|
|
27040
27197
|
root_session_id AS rootSessionId,
|
|
@@ -27110,7 +27267,7 @@ var SqliteHistorySyncRepository = class {
|
|
|
27110
27267
|
);
|
|
27111
27268
|
this.scopedCaptureRowsStmt = db.prepare(
|
|
27112
27269
|
`SELECT ${ROW_COLUMNS}
|
|
27113
|
-
FROM audit_events
|
|
27270
|
+
FROM audit_events INDEXED BY idx_audit_scope_owed
|
|
27114
27271
|
WHERE synced_at IS NULL
|
|
27115
27272
|
AND sync_claimed_at IS NULL
|
|
27116
27273
|
AND outbox_owed = 1
|
|
@@ -27163,40 +27320,28 @@ var SqliteHistorySyncRepository = class {
|
|
|
27163
27320
|
);
|
|
27164
27321
|
this.partitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
27165
27322
|
FROM audit_events${COUNTED_SCOPE}`);
|
|
27323
|
+
this.scopedPartitionStmt = db.prepare(`SELECT${PARTITION_BUCKETS}
|
|
27324
|
+
FROM audit_events${COUNTED_SCOPE}${COUNTED_IN_SCOPE}`);
|
|
27166
27325
|
this.partitionByKindStmt = db.prepare(
|
|
27167
27326
|
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
27168
27327
|
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}
|
|
27169
27328
|
GROUP BY event_type`
|
|
27170
27329
|
);
|
|
27171
|
-
this.
|
|
27172
|
-
`SELECT
|
|
27173
|
-
|
|
27174
|
-
|
|
27175
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27176
|
-
AND (sync_failure IS NULL OR sync_failure = 'payload_invalid')
|
|
27177
|
-
THEN 1 ELSE 0 END) AS skipped,
|
|
27178
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27179
|
-
AND sync_failure = 'deployment_refused' THEN 1 ELSE 0 END) AS refused,
|
|
27180
|
-
SUM(CASE WHEN synced_at = ${String(SKIPPED)}
|
|
27181
|
-
AND sync_failure = 'detached_undelivered' THEN 1 ELSE 0 END) AS detached
|
|
27182
|
-
FROM audit_events
|
|
27183
|
-
WHERE event_type IN (${TYPE_LIST})`
|
|
27330
|
+
this.scopedPartitionByKindStmt = db.prepare(
|
|
27331
|
+
`SELECT event_type AS kind,${PARTITION_BUCKETS}
|
|
27332
|
+
FROM audit_events INDEXED BY idx_audit_events_sync${COUNTED_SCOPE}${COUNTED_IN_SCOPE}
|
|
27333
|
+
GROUP BY event_type`
|
|
27184
27334
|
);
|
|
27185
|
-
this.
|
|
27186
|
-
|
|
27187
|
-
|
|
27188
|
-
|
|
27189
|
-
|
|
27190
|
-
|
|
27191
|
-
|
|
27192
|
-
|
|
27193
|
-
|
|
27194
|
-
|
|
27195
|
-
// frees.
|
|
27196
|
-
`SELECT COUNT(*) AS skipped
|
|
27197
|
-
FROM audit_events
|
|
27198
|
-
WHERE synced_at = ${String(SKIPPED)}
|
|
27199
|
-
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27335
|
+
this.countsStmt = db.prepare(DRAIN_TOTALS);
|
|
27336
|
+
this.scopedCountsStmt = db.prepare(
|
|
27337
|
+
`${DRAIN_TOTALS}
|
|
27338
|
+
AND ${inScope("scope_key")}
|
|
27339
|
+
AND ${inScope(ROOT_SCOPE_KEY)}`
|
|
27340
|
+
);
|
|
27341
|
+
this.captureSkipCountStmt = db.prepare(CAPTURE_SKIPS);
|
|
27342
|
+
this.scopedCaptureSkipCountStmt = db.prepare(
|
|
27343
|
+
`${CAPTURE_SKIPS}
|
|
27344
|
+
AND ${inScope("scope_key")}`
|
|
27200
27345
|
);
|
|
27201
27346
|
this.fingerprintStmt = db.prepare(
|
|
27202
27347
|
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
@@ -27310,6 +27455,10 @@ var SqliteHistorySyncRepository = class {
|
|
|
27310
27455
|
scopedCaptureRowsStmt;
|
|
27311
27456
|
scopedCaptureBacklogOwedStmt;
|
|
27312
27457
|
markScopeCapturesOwedStmt;
|
|
27458
|
+
scopedPartitionStmt;
|
|
27459
|
+
scopedPartitionByKindStmt;
|
|
27460
|
+
scopedCountsStmt;
|
|
27461
|
+
scopedCaptureSkipCountStmt;
|
|
27313
27462
|
/**
|
|
27314
27463
|
* The masked detections recorded against one tool call.
|
|
27315
27464
|
*
|
|
@@ -27531,7 +27680,29 @@ var SqliteHistorySyncRepository = class {
|
|
|
27531
27680
|
* in" — and a machine that has never attached has no boundary to pass, so
|
|
27532
27681
|
* requiring one would force a caller to invent one and report the whole store
|
|
27533
27682
|
* as queued.
|
|
27683
|
+
*
|
|
27684
|
+
* `scopeKeys` is a scoped attachment's filter: every bucket then counts only
|
|
27685
|
+
* the rows that pass the drain's reachability rule for that scope
|
|
27686
|
+
* (COUNTED_IN_SCOPE, which also names the one kind of row it counts that the
|
|
27687
|
+
* drain never offers), so a personal repository's rows are in none of them.
|
|
27688
|
+
* Omitted, this runs the machine statement, unchanged; an empty list counts
|
|
27689
|
+
* nothing.
|
|
27534
27690
|
*/
|
|
27691
|
+
partition(scopeKeys) {
|
|
27692
|
+
const row = getRow(
|
|
27693
|
+
scopeKeys === void 0 ? this.partitionStmt : this.scopedPartitionStmt,
|
|
27694
|
+
scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
|
|
27695
|
+
);
|
|
27696
|
+
return {
|
|
27697
|
+
queued: row?.queued ?? 0,
|
|
27698
|
+
inProgress: row?.inProgress ?? 0,
|
|
27699
|
+
synced: row?.synced ?? 0,
|
|
27700
|
+
failed: row?.failed ?? 0,
|
|
27701
|
+
refused: row?.refused ?? 0,
|
|
27702
|
+
detached: row?.detached ?? 0,
|
|
27703
|
+
total: row?.total ?? 0
|
|
27704
|
+
};
|
|
27705
|
+
}
|
|
27535
27706
|
/**
|
|
27536
27707
|
* The same partition, one row per kind that a lane carries.
|
|
27537
27708
|
*
|
|
@@ -27541,11 +27712,14 @@ var SqliteHistorySyncRepository = class {
|
|
|
27541
27712
|
* rendering a fixed list of kinds must therefore treat a missing one as "no
|
|
27542
27713
|
* rows", never as "zero sent"; the two look identical in a bar and mean
|
|
27543
27714
|
* different things.
|
|
27715
|
+
*
|
|
27716
|
+
* `scopeKeys` scopes it with the clause `partition` uses, so the per-kind rows
|
|
27717
|
+
* still sum to the scoped aggregate. An empty list returns no rows.
|
|
27544
27718
|
*/
|
|
27545
|
-
partitionByKind() {
|
|
27719
|
+
partitionByKind(scopeKeys) {
|
|
27546
27720
|
return allRows(
|
|
27547
|
-
this.partitionByKindStmt,
|
|
27548
|
-
{}
|
|
27721
|
+
scopeKeys === void 0 ? this.partitionByKindStmt : this.scopedPartitionByKindStmt,
|
|
27722
|
+
scopeKeys === void 0 ? {} : { scopeKeys: scopeKeysParam(scopeKeys) }
|
|
27549
27723
|
).map((row) => ({
|
|
27550
27724
|
kind: row.kind,
|
|
27551
27725
|
queued: row.queued ?? 0,
|
|
@@ -27557,22 +27731,25 @@ var SqliteHistorySyncRepository = class {
|
|
|
27557
27731
|
total: row.total ?? 0
|
|
27558
27732
|
}));
|
|
27559
27733
|
}
|
|
27560
|
-
|
|
27561
|
-
|
|
27562
|
-
|
|
27563
|
-
|
|
27564
|
-
|
|
27565
|
-
|
|
27566
|
-
|
|
27567
|
-
|
|
27568
|
-
|
|
27569
|
-
|
|
27570
|
-
|
|
27571
|
-
|
|
27572
|
-
|
|
27573
|
-
|
|
27574
|
-
|
|
27575
|
-
|
|
27734
|
+
/**
|
|
27735
|
+
* The drain's totals. `pending` counts only what is inside the backlog; sent
|
|
27736
|
+
* and skipped are totals.
|
|
27737
|
+
*
|
|
27738
|
+
* `scopeKeys` is a scoped attachment's filter, and it scopes every figure,
|
|
27739
|
+
* `capturesSkipped` included: a structural row is counted only when its own
|
|
27740
|
+
* key and its session root's key are among them, a capture when its own key
|
|
27741
|
+
* is. So `pending` is exactly what pendingSessions and pendingRows page out
|
|
27742
|
+
* under the same keys and boundary. Omitted, this runs the machine
|
|
27743
|
+
* statements, unchanged; an empty list counts nothing.
|
|
27744
|
+
*/
|
|
27745
|
+
counts(before, scopeKeys) {
|
|
27746
|
+
const row = getRow(
|
|
27747
|
+
scopeKeys === void 0 ? this.countsStmt : this.scopedCountsStmt,
|
|
27748
|
+
scopeKeys === void 0 ? { before } : { before, scopeKeys: scopeKeysParam(scopeKeys) }
|
|
27749
|
+
);
|
|
27750
|
+
const captures = scopeKeys === void 0 ? getRow(this.captureSkipCountStmt) : getRow(this.scopedCaptureSkipCountStmt, {
|
|
27751
|
+
scopeKeys: scopeKeysParam(scopeKeys)
|
|
27752
|
+
});
|
|
27576
27753
|
return {
|
|
27577
27754
|
pending: row?.pending ?? 0,
|
|
27578
27755
|
sent: row?.sent ?? 0,
|
|
@@ -27824,6 +28001,7 @@ function applyMigrations(db, file2, options = {}) {
|
|
|
27824
28001
|
}
|
|
27825
28002
|
ensureSyncedAtColumn(db, "audit_events");
|
|
27826
28003
|
ensureScopeKeyColumn(db);
|
|
28004
|
+
ensureScopeOwedIndex(db);
|
|
27827
28005
|
ensureScanLedgerTable(db);
|
|
27828
28006
|
ensureHistorySyncTable(db);
|
|
27829
28007
|
ensureBlockedDetectionsTable(db);
|
|
@@ -28264,14 +28442,48 @@ function ensureScopeKeyColumn(db) {
|
|
|
28264
28442
|
function hasScopeKeyColumn(db) {
|
|
28265
28443
|
return columnNames(db, "audit_events", { includeGenerated: true }).includes("scope_key");
|
|
28266
28444
|
}
|
|
28445
|
+
var SCOPE_OWED_INDEX_DDL = "CREATE INDEX IF NOT EXISTS idx_audit_scope_owed ON audit_events (scope_key, event_type, started_at) WHERE outbox_owed = 1 AND synced_at IS NULL";
|
|
28446
|
+
function ensureScopeOwedIndex(db) {
|
|
28447
|
+
if (!schemaObjectExists(db, "table", "audit_events")) return;
|
|
28448
|
+
const columns = columnNames(db, "audit_events", { includeGenerated: true });
|
|
28449
|
+
const complete = ["scope_key", "outbox_owed", "synced_at"].every((c) => columns.includes(c));
|
|
28450
|
+
if (!complete) return;
|
|
28451
|
+
db.exec(SCOPE_OWED_INDEX_DDL);
|
|
28452
|
+
}
|
|
28267
28453
|
function ensureScanLedgerTable(db) {
|
|
28268
28454
|
db.exec(`CREATE TABLE IF NOT EXISTS scan_ledger (
|
|
28269
28455
|
path TEXT PRIMARY KEY,
|
|
28270
28456
|
mtime TEXT NOT NULL,
|
|
28271
28457
|
content_hash TEXT NOT NULL,
|
|
28272
28458
|
ruleset_hash TEXT NOT NULL,
|
|
28273
|
-
scanned_at INTEGER NOT NULL
|
|
28459
|
+
scanned_at INTEGER NOT NULL,
|
|
28460
|
+
scope_key TEXT,
|
|
28461
|
+
scope_root TEXT
|
|
28274
28462
|
)`);
|
|
28463
|
+
ensureScanLedgerScopeKeyColumn(db);
|
|
28464
|
+
ensureScanLedgerScopeRootColumn(db);
|
|
28465
|
+
}
|
|
28466
|
+
var SCAN_LEDGER_SCOPE_KEY_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_key TEXT";
|
|
28467
|
+
var SCAN_LEDGER_SCOPE_ROOT_DDL = "ALTER TABLE scan_ledger ADD COLUMN scope_root TEXT";
|
|
28468
|
+
function ensureScanLedgerScopeKeyColumn(db) {
|
|
28469
|
+
ensureScanLedgerColumn(db, "scope_key", SCAN_LEDGER_SCOPE_KEY_DDL);
|
|
28470
|
+
}
|
|
28471
|
+
function ensureScanLedgerScopeRootColumn(db) {
|
|
28472
|
+
ensureScanLedgerColumn(db, "scope_root", SCAN_LEDGER_SCOPE_ROOT_DDL);
|
|
28473
|
+
}
|
|
28474
|
+
function ensureScanLedgerColumn(db, column, ddl) {
|
|
28475
|
+
if (!schemaObjectExists(db, "table", "scan_ledger")) return;
|
|
28476
|
+
if (hasScanLedgerColumn(db, column)) return;
|
|
28477
|
+
withTransaction(
|
|
28478
|
+
db,
|
|
28479
|
+
() => {
|
|
28480
|
+
if (!hasScanLedgerColumn(db, column)) db.exec(ddl);
|
|
28481
|
+
},
|
|
28482
|
+
"IMMEDIATE"
|
|
28483
|
+
);
|
|
28484
|
+
}
|
|
28485
|
+
function hasScanLedgerColumn(db, column) {
|
|
28486
|
+
return columnNames(db, "scan_ledger").includes(column);
|
|
28275
28487
|
}
|
|
28276
28488
|
function ensureHistorySyncTable(db) {
|
|
28277
28489
|
db.exec(`CREATE TABLE IF NOT EXISTS history_sync (
|
|
@@ -28322,6 +28534,106 @@ function ensureRuleProbeCacheTable(db) {
|
|
|
28322
28534
|
)`);
|
|
28323
28535
|
}
|
|
28324
28536
|
|
|
28537
|
+
// ../../packages/persistence/src/mod-policy-snapshot.ts
|
|
28538
|
+
import { createHash as createHash2 } from "crypto";
|
|
28539
|
+
import { readFileSync as readFileSync2 } from "fs";
|
|
28540
|
+
import { join as join4 } from "path";
|
|
28541
|
+
var MOD_POLICY_SNAPSHOT_FILENAME = "mod-policy.json";
|
|
28542
|
+
function modPolicySnapshotPath(dataDir2) {
|
|
28543
|
+
return join4(dataDir2, MOD_POLICY_SNAPSHOT_FILENAME);
|
|
28544
|
+
}
|
|
28545
|
+
function buildModPolicySnapshot(input2, generatedAt = /* @__PURE__ */ new Date()) {
|
|
28546
|
+
const byRule = /* @__PURE__ */ new Map();
|
|
28547
|
+
const byCategory = /* @__PURE__ */ new Map();
|
|
28548
|
+
for (const policy of input2.policies) {
|
|
28549
|
+
if (!policy.enabled) continue;
|
|
28550
|
+
if ("ruleId" in policy.target) {
|
|
28551
|
+
if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
|
|
28552
|
+
} else if (!byCategory.has(policy.target.category)) {
|
|
28553
|
+
byCategory.set(policy.target.category, policy.action);
|
|
28554
|
+
}
|
|
28555
|
+
}
|
|
28556
|
+
const categoryActions = {};
|
|
28557
|
+
for (const category of DetectionCategory.options) {
|
|
28558
|
+
categoryActions[category] = byCategory.get(category) ?? DEFAULT_ACTIONS[category];
|
|
28559
|
+
}
|
|
28560
|
+
return {
|
|
28561
|
+
version: MOD_POLICY_SNAPSHOT_VERSION,
|
|
28562
|
+
generatedAt: generatedAt.toISOString(),
|
|
28563
|
+
// `examples` is documentation the mod never reads, and a custom pack's are
|
|
28564
|
+
// whatever its author pasted in, so they stay behind.
|
|
28565
|
+
...input2.rules !== void 0 ? { rules: input2.rules.map(withoutExamples) } : {},
|
|
28566
|
+
ruleActions: Object.fromEntries(byRule),
|
|
28567
|
+
categoryActions,
|
|
28568
|
+
exceptionRuleIds: [...new Set(input2.exceptionRuleIds)].sort()
|
|
28569
|
+
};
|
|
28570
|
+
}
|
|
28571
|
+
function assignedRuleActionPolicies(installed) {
|
|
28572
|
+
const out = [];
|
|
28573
|
+
for (const [ruleId, action] of installed.ruleActions) {
|
|
28574
|
+
if (installed.assignedRules.has(ruleId))
|
|
28575
|
+
out.push({ target: { ruleId }, action, enabled: true });
|
|
28576
|
+
}
|
|
28577
|
+
return out;
|
|
28578
|
+
}
|
|
28579
|
+
function withoutExamples(rule) {
|
|
28580
|
+
const copy = { ...rule };
|
|
28581
|
+
delete copy.examples;
|
|
28582
|
+
return copy;
|
|
28583
|
+
}
|
|
28584
|
+
function sameContent(a, b) {
|
|
28585
|
+
return JSON.stringify({ ...a, generatedAt: "" }) === JSON.stringify({ ...b, generatedAt: "" });
|
|
28586
|
+
}
|
|
28587
|
+
function readModPolicySnapshot(dataDir2) {
|
|
28588
|
+
try {
|
|
28589
|
+
const text = readFileSync2(modPolicySnapshotPath(dataDir2), "utf8");
|
|
28590
|
+
if (text.length > MOD_POLICY_SNAPSHOT_MAX_BYTES) return null;
|
|
28591
|
+
const parsed2 = ModPolicySnapshot.safeParse(JSON.parse(text));
|
|
28592
|
+
return parsed2.success ? parsed2.data : null;
|
|
28593
|
+
} catch {
|
|
28594
|
+
return null;
|
|
28595
|
+
}
|
|
28596
|
+
}
|
|
28597
|
+
function writeModPolicySnapshot(dataDir2, snapshot) {
|
|
28598
|
+
const text = JSON.stringify(snapshot);
|
|
28599
|
+
if (Buffer.byteLength(text) > MOD_POLICY_SNAPSHOT_MAX_BYTES) return false;
|
|
28600
|
+
const existing = readModPolicySnapshot(dataDir2);
|
|
28601
|
+
if (existing !== null && sameContent(existing, snapshot)) return false;
|
|
28602
|
+
ensureDataDirSync(dataDir2);
|
|
28603
|
+
writeOwnerOnlyFileSync(modPolicySnapshotPath(dataDir2), text);
|
|
28604
|
+
return true;
|
|
28605
|
+
}
|
|
28606
|
+
function regexProbeKey(matcher) {
|
|
28607
|
+
return createHash2("sha256").update(`${matcher.pattern} ${matcher.flags}`).digest("hex");
|
|
28608
|
+
}
|
|
28609
|
+
function vetRulesForMod(rules, sources, previouslyVetted = /* @__PURE__ */ new Set()) {
|
|
28610
|
+
const bundled = new Set(sources.bundledRegexMatchers().map(regexProbeKey));
|
|
28611
|
+
return rules.filter((rule) => {
|
|
28612
|
+
if (rule.matcher.type !== "regex") return true;
|
|
28613
|
+
const key = regexProbeKey(rule.matcher);
|
|
28614
|
+
const verdict = sources.probeVerdict(key);
|
|
28615
|
+
if (verdict === "quarantined") return false;
|
|
28616
|
+
return verdict === "safe" || bundled.has(key) || previouslyVetted.has(key);
|
|
28617
|
+
});
|
|
28618
|
+
}
|
|
28619
|
+
function modPolicyInputFromStore(sources, previouslyVetted = /* @__PURE__ */ new Set()) {
|
|
28620
|
+
const policies = sources.readPolicies();
|
|
28621
|
+
const snapshot = sources.installedRuleset();
|
|
28622
|
+
const usable = snapshot.installedPacks > 0 && (snapshot.enabledPacks === 0 || snapshot.invalidRules === 0 && snapshot.rules.length > 0);
|
|
28623
|
+
const empty = snapshot.installedPacks > 0 && snapshot.enabledPacks === 0;
|
|
28624
|
+
return {
|
|
28625
|
+
...usable ? { rules: empty ? [] : vetRulesForMod(snapshot.rules, sources, previouslyVetted) } : {},
|
|
28626
|
+
policies: [...policies, ...usable && !empty ? assignedRuleActionPolicies(snapshot) : []],
|
|
28627
|
+
exceptionRuleIds: sources.activeExceptionRuleIds()
|
|
28628
|
+
};
|
|
28629
|
+
}
|
|
28630
|
+
function refreshModPolicySnapshot(dataDir2, sources) {
|
|
28631
|
+
try {
|
|
28632
|
+
writeModPolicySnapshot(dataDir2, buildModPolicySnapshot(modPolicyInputFromStore(sources)));
|
|
28633
|
+
} catch {
|
|
28634
|
+
}
|
|
28635
|
+
}
|
|
28636
|
+
|
|
28325
28637
|
// ../../packages/persistence/src/internal/json.ts
|
|
28326
28638
|
function safeJson(s, fallback) {
|
|
28327
28639
|
if (s == null) return fallback;
|
|
@@ -28496,6 +28808,11 @@ var TIMELINE_COLUMNS = `
|
|
|
28496
28808
|
json_extract(attributes, '$.targetId') AS target_id,
|
|
28497
28809
|
json_extract(attributes, '$.internal') AS internal,
|
|
28498
28810
|
json_extract(attributes, '$.flagged') AS flagged`;
|
|
28811
|
+
var CALL_PROMPT_TOKENS = `(coalesce(input_tokens, 0) + coalesce(cache_read_input_tokens, 0)
|
|
28812
|
+
+ coalesce(ephemeral_1h_input_tokens, 0) + coalesce(ephemeral_5m_input_tokens, 0))`;
|
|
28813
|
+
var CALL_BAND = LONG_CONTEXT_THRESHOLDS.length === 0 ? "0" : LONG_CONTEXT_THRESHOLDS.map((t) => `(${CALL_PROMPT_TOKENS} > ${String(Math.trunc(t))})`).join(
|
|
28814
|
+
" + "
|
|
28815
|
+
);
|
|
28499
28816
|
var LLM_USAGE_SELECT = `
|
|
28500
28817
|
SELECT root_session_id AS sessionId,
|
|
28501
28818
|
provider,
|
|
@@ -28507,9 +28824,10 @@ var LLM_USAGE_SELECT = `
|
|
|
28507
28824
|
coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
|
|
28508
28825
|
coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
|
|
28509
28826
|
coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
|
|
28510
|
-
coalesce(sum(web_search_requests), 0) AS webSearchRequests
|
|
28827
|
+
coalesce(sum(web_search_requests), 0) AS webSearchRequests,
|
|
28828
|
+
coalesce(max(${CALL_PROMPT_TOKENS}), 0) AS promptTokens`;
|
|
28511
28829
|
var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
|
|
28512
|
-
var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
|
|
28830
|
+
var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier, ${CALL_BAND}`;
|
|
28513
28831
|
function usageLeaves(rows) {
|
|
28514
28832
|
return rows.map((row) => {
|
|
28515
28833
|
const attributes = {
|
|
@@ -28524,7 +28842,7 @@ function usageLeaves(rows) {
|
|
|
28524
28842
|
if (row.provider !== null) attributes.provider = row.provider;
|
|
28525
28843
|
if (row.model !== null) attributes.model = row.model;
|
|
28526
28844
|
if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
|
|
28527
|
-
return { sessionId: row.sessionId, attributes };
|
|
28845
|
+
return { sessionId: row.sessionId, attributes, promptTokens: row.promptTokens };
|
|
28528
28846
|
});
|
|
28529
28847
|
}
|
|
28530
28848
|
var SESSION_ROOT = `event_type = 'session'`;
|
|
@@ -29858,9 +30176,10 @@ var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
|
|
|
29858
30176
|
AND conditions IS NULL
|
|
29859
30177
|
AND ${ACTIVE_PREDICATE}`;
|
|
29860
30178
|
var SqliteExceptionsRepository = class {
|
|
29861
|
-
constructor(db, now = () => Date.now()) {
|
|
30179
|
+
constructor(db, now = () => Date.now(), onChange = () => void 0) {
|
|
29862
30180
|
this.db = db;
|
|
29863
30181
|
this.now = now;
|
|
30182
|
+
this.onChange = onChange;
|
|
29864
30183
|
this.consumeStmt = db.prepare(
|
|
29865
30184
|
`UPDATE exceptions
|
|
29866
30185
|
SET use_count = use_count + 1, last_used_at = :now, updated_at = :now
|
|
@@ -29879,6 +30198,7 @@ var SqliteExceptionsRepository = class {
|
|
|
29879
30198
|
}
|
|
29880
30199
|
db;
|
|
29881
30200
|
now;
|
|
30201
|
+
onChange;
|
|
29882
30202
|
consumeStmt;
|
|
29883
30203
|
insertBlockedStmt;
|
|
29884
30204
|
sweepBlockedStmt;
|
|
@@ -29894,7 +30214,9 @@ var SqliteExceptionsRepository = class {
|
|
|
29894
30214
|
*/
|
|
29895
30215
|
create(input2) {
|
|
29896
30216
|
try {
|
|
29897
|
-
|
|
30217
|
+
const created = this.createSync(input2);
|
|
30218
|
+
this.onChange();
|
|
30219
|
+
return Promise.resolve(created);
|
|
29898
30220
|
} catch (err) {
|
|
29899
30221
|
return Promise.reject(err instanceof Error ? err : new Error(String(err)));
|
|
29900
30222
|
}
|
|
@@ -30025,6 +30347,7 @@ var SqliteExceptionsRepository = class {
|
|
|
30025
30347
|
SET revoked_at = :now, revoked_by = :revokedBy, revoke_reason = :reason, updated_at = :now
|
|
30026
30348
|
WHERE id = :id AND revoked_at IS NULL`
|
|
30027
30349
|
).run({ id, revokedBy, reason: reason ?? null, now });
|
|
30350
|
+
if (Number(result.changes) === 1) this.onChange();
|
|
30028
30351
|
return Promise.resolve(Number(result.changes) === 1);
|
|
30029
30352
|
}
|
|
30030
30353
|
/**
|
|
@@ -30037,6 +30360,15 @@ var SqliteExceptionsRepository = class {
|
|
|
30037
30360
|
const result = this.consumeStmt.run({ id, now });
|
|
30038
30361
|
return Promise.resolve(Number(result.changes) === 1);
|
|
30039
30362
|
}
|
|
30363
|
+
/** The rule ids with at least one active grant, under any key version. */
|
|
30364
|
+
activeRuleIds(now = this.now()) {
|
|
30365
|
+
return allRows(
|
|
30366
|
+
this.db.prepare(
|
|
30367
|
+
`SELECT DISTINCT rule_id AS ruleId FROM exceptions WHERE ${ACTIVE_PREDICATE}`
|
|
30368
|
+
),
|
|
30369
|
+
{ now }
|
|
30370
|
+
).map((row) => row.ruleId);
|
|
30371
|
+
}
|
|
30040
30372
|
/**
|
|
30041
30373
|
* The evaluation subset of every active grant under one fingerprint key
|
|
30042
30374
|
* version — what rides the policy bundle to the hook. Grants written under
|
|
@@ -31160,31 +31492,31 @@ var SqliteInspectionFindingsRepository = class {
|
|
|
31160
31492
|
};
|
|
31161
31493
|
|
|
31162
31494
|
// ../../packages/persistence/src/repositories/installed-packs.ts
|
|
31163
|
-
import { createHash as
|
|
31495
|
+
import { createHash as createHash3, randomUUID as randomUUID4 } from "crypto";
|
|
31164
31496
|
|
|
31165
31497
|
// ../../packages/persistence/src/policy-floor.ts
|
|
31166
|
-
import { readFileSync as
|
|
31167
|
-
import { join as
|
|
31498
|
+
import { readFileSync as readFileSync6 } from "fs";
|
|
31499
|
+
import { join as join7 } from "path";
|
|
31168
31500
|
|
|
31169
31501
|
// ../../packages/persistence/src/local-layout.ts
|
|
31170
31502
|
import { renameSync as renameSync3 } from "fs";
|
|
31171
31503
|
import { mkdir } from "fs/promises";
|
|
31172
31504
|
import { homedir } from "os";
|
|
31173
|
-
import { join as
|
|
31505
|
+
import { join as join5 } from "path";
|
|
31174
31506
|
function defaultDataDir() {
|
|
31175
|
-
return
|
|
31507
|
+
return join5(homedir(), ".aka");
|
|
31176
31508
|
}
|
|
31177
31509
|
function settingsDir(base = defaultDataDir()) {
|
|
31178
|
-
return
|
|
31510
|
+
return join5(base, "settings");
|
|
31179
31511
|
}
|
|
31180
31512
|
function dataDir(base = defaultDataDir()) {
|
|
31181
|
-
return
|
|
31513
|
+
return join5(base, "data");
|
|
31182
31514
|
}
|
|
31183
31515
|
function dbPath(base = defaultDataDir()) {
|
|
31184
|
-
return
|
|
31516
|
+
return join5(dataDir(base), "aka.db");
|
|
31185
31517
|
}
|
|
31186
31518
|
function keysDir(base = defaultDataDir()) {
|
|
31187
|
-
return
|
|
31519
|
+
return join5(base, "keys");
|
|
31188
31520
|
}
|
|
31189
31521
|
async function ensureDataDir(dir = defaultDataDir()) {
|
|
31190
31522
|
await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
@@ -31201,8 +31533,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
|
|
|
31201
31533
|
for (const { name, dest } of moves) {
|
|
31202
31534
|
try {
|
|
31203
31535
|
ensureDataDirSync(dest);
|
|
31204
|
-
const moved =
|
|
31205
|
-
renameSync3(
|
|
31536
|
+
const moved = join5(dest, name);
|
|
31537
|
+
renameSync3(join5(base, name), moved);
|
|
31206
31538
|
tightenFile(moved);
|
|
31207
31539
|
} catch {
|
|
31208
31540
|
}
|
|
@@ -31210,8 +31542,8 @@ function migrateLegacyLayout(base = defaultDataDir()) {
|
|
|
31210
31542
|
}
|
|
31211
31543
|
|
|
31212
31544
|
// ../../packages/persistence/src/settings.ts
|
|
31213
|
-
import { readFileSync as
|
|
31214
|
-
import { join as
|
|
31545
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
31546
|
+
import { join as join6 } from "path";
|
|
31215
31547
|
|
|
31216
31548
|
// ../../packages/persistence/src/file-lock.ts
|
|
31217
31549
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
@@ -31219,7 +31551,7 @@ import {
|
|
|
31219
31551
|
closeSync,
|
|
31220
31552
|
existsSync as existsSync2,
|
|
31221
31553
|
openSync,
|
|
31222
|
-
readFileSync as
|
|
31554
|
+
readFileSync as readFileSync3,
|
|
31223
31555
|
rmSync as rmSync5,
|
|
31224
31556
|
statSync as statSync3,
|
|
31225
31557
|
writeFileSync as writeFileSync2
|
|
@@ -31228,7 +31560,7 @@ import { hostname as hostname3 } from "os";
|
|
|
31228
31560
|
var PARK = new Int32Array(new SharedArrayBuffer(4));
|
|
31229
31561
|
|
|
31230
31562
|
// ../../packages/persistence/src/managed-settings.ts
|
|
31231
|
-
import { readFileSync as
|
|
31563
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
31232
31564
|
import { posix, win32 } from "path";
|
|
31233
31565
|
function managedSettingsPaths(platform2 = process.platform) {
|
|
31234
31566
|
if (platform2 === "darwin") {
|
|
@@ -31247,7 +31579,7 @@ function readManagedSettings(paths = testOnlyManagedPaths ?? managedSettingsPath
|
|
|
31247
31579
|
for (const path of paths) {
|
|
31248
31580
|
let text;
|
|
31249
31581
|
try {
|
|
31250
|
-
text =
|
|
31582
|
+
text = readFileSync4(path, "utf8");
|
|
31251
31583
|
} catch {
|
|
31252
31584
|
continue;
|
|
31253
31585
|
}
|
|
@@ -31301,7 +31633,7 @@ function readWorkspaceSettings(base = defaultDataDir()) {
|
|
|
31301
31633
|
return overlayManagedSettings(readUserSettings(base), readManagedSettings());
|
|
31302
31634
|
}
|
|
31303
31635
|
function readUserSettings(base) {
|
|
31304
|
-
const record2 = readJson(
|
|
31636
|
+
const record2 = readJson(join6(settingsDir(base), SETTINGS_FILENAME));
|
|
31305
31637
|
if (!record2) return defaultWorkspaceSettings();
|
|
31306
31638
|
try {
|
|
31307
31639
|
return WorkspaceSettings.parse(record2);
|
|
@@ -31312,7 +31644,7 @@ function readUserSettings(base) {
|
|
|
31312
31644
|
function readJson(file2) {
|
|
31313
31645
|
let text;
|
|
31314
31646
|
try {
|
|
31315
|
-
text =
|
|
31647
|
+
text = readFileSync5(file2, "utf8");
|
|
31316
31648
|
} catch {
|
|
31317
31649
|
return null;
|
|
31318
31650
|
}
|
|
@@ -31352,7 +31684,7 @@ var PolicyFloorError = class extends Error {
|
|
|
31352
31684
|
};
|
|
31353
31685
|
function readCachedPolicyBundle(base = defaultDataDir()) {
|
|
31354
31686
|
try {
|
|
31355
|
-
const raw =
|
|
31687
|
+
const raw = readFileSync6(join7(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
|
|
31356
31688
|
const parsed2 = JSON.parse(raw);
|
|
31357
31689
|
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
31358
31690
|
return PolicyBundle.parse(parsed2.bundle);
|
|
@@ -31476,7 +31808,7 @@ function inventorySignature(packs2) {
|
|
|
31476
31808
|
return packs2.map((p) => `${p.namespace}/${p.packId}@${p.version}#${hashRules(p.rulesJson)}`).sort().join(",");
|
|
31477
31809
|
}
|
|
31478
31810
|
function hashRules(rulesJson) {
|
|
31479
|
-
return
|
|
31811
|
+
return createHash3("sha256").update(rulesJson).digest("hex");
|
|
31480
31812
|
}
|
|
31481
31813
|
function parseVersion(v) {
|
|
31482
31814
|
const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
|
|
@@ -31518,9 +31850,10 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31518
31850
|
* from `openLocalDatabase`, which is the single construction site that owns a
|
|
31519
31851
|
* real `~/.aka`.
|
|
31520
31852
|
*/
|
|
31521
|
-
constructor(db, baseDir) {
|
|
31853
|
+
constructor(db, baseDir, onChange = () => void 0) {
|
|
31522
31854
|
this.db = db;
|
|
31523
31855
|
this.baseDir = baseDir;
|
|
31856
|
+
this.onChange = onChange;
|
|
31524
31857
|
this.insertMissingStmt = db.prepare(
|
|
31525
31858
|
`INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, policy_id, created_at, updated_at)
|
|
31526
31859
|
VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :policyId, :now, :now)
|
|
@@ -31549,6 +31882,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31549
31882
|
}
|
|
31550
31883
|
db;
|
|
31551
31884
|
baseDir;
|
|
31885
|
+
onChange;
|
|
31552
31886
|
insertMissingStmt;
|
|
31553
31887
|
upsertAvailableStmt;
|
|
31554
31888
|
signatureStmt;
|
|
@@ -31621,6 +31955,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31621
31955
|
},
|
|
31622
31956
|
"IMMEDIATE"
|
|
31623
31957
|
);
|
|
31958
|
+
this.onChange();
|
|
31624
31959
|
} catch {
|
|
31625
31960
|
}
|
|
31626
31961
|
}
|
|
@@ -31695,6 +32030,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31695
32030
|
},
|
|
31696
32031
|
"IMMEDIATE"
|
|
31697
32032
|
);
|
|
32033
|
+
if (changed) this.onChange();
|
|
31698
32034
|
return changed;
|
|
31699
32035
|
}
|
|
31700
32036
|
/**
|
|
@@ -31936,6 +32272,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31936
32272
|
`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
|
|
31937
32273
|
WHERE namespace = :namespace AND pack_id = :packId`
|
|
31938
32274
|
).run({ policyId, now: Date.now(), namespace, packId });
|
|
32275
|
+
if (Number(res.changes) > 0) this.onChange();
|
|
31939
32276
|
return Number(res.changes) > 0;
|
|
31940
32277
|
}
|
|
31941
32278
|
/**
|
|
@@ -31960,6 +32297,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
31960
32297
|
`UPDATE installed_packs SET enabled = :enabled, updated_at = :now
|
|
31961
32298
|
WHERE namespace = :namespace AND pack_id = :packId`
|
|
31962
32299
|
).run({ enabled: boolToInt(enabled), now: Date.now(), namespace, packId });
|
|
32300
|
+
if (Number(res.changes) > 0) this.onChange();
|
|
31963
32301
|
return Number(res.changes) > 0;
|
|
31964
32302
|
}
|
|
31965
32303
|
// Fingerprint of the recorded available mirror — compared against the
|
|
@@ -32857,13 +33195,19 @@ var SqliteInventoryAssetsRepository = class {
|
|
|
32857
33195
|
import { randomUUID as randomUUID6 } from "crypto";
|
|
32858
33196
|
var SEED_BATCH_WINDOW_MS = 6e4;
|
|
32859
33197
|
var SqlitePoliciesRepository = class {
|
|
32860
|
-
constructor(db) {
|
|
33198
|
+
constructor(db, onChange = () => void 0) {
|
|
32861
33199
|
this.db = db;
|
|
33200
|
+
this.onChange = onChange;
|
|
32862
33201
|
}
|
|
32863
33202
|
db;
|
|
33203
|
+
onChange;
|
|
32864
33204
|
readPolicies() {
|
|
33205
|
+
return Promise.resolve(this.listPolicies());
|
|
33206
|
+
}
|
|
33207
|
+
/** The synchronous read behind {@link readPolicies}. */
|
|
33208
|
+
listPolicies() {
|
|
32865
33209
|
const rows = allRows(this.db.prepare("SELECT * FROM policies"));
|
|
32866
|
-
|
|
33210
|
+
return mapRowsTolerant(rows, (row) => {
|
|
32867
33211
|
const target = JSON.parse(row.target);
|
|
32868
33212
|
const customKeywords = row.custom_keywords ? JSON.parse(row.custom_keywords) : void 0;
|
|
32869
33213
|
return Policy.parse({
|
|
@@ -32875,7 +33219,6 @@ var SqlitePoliciesRepository = class {
|
|
|
32875
33219
|
customKeywords
|
|
32876
33220
|
});
|
|
32877
33221
|
});
|
|
32878
|
-
return Promise.resolve(policies);
|
|
32879
33222
|
}
|
|
32880
33223
|
// Seed one policy per bundled category at Monitor so the detection-type config
|
|
32881
33224
|
// exists from first run. An unassigned pack's rules follow these rows, so
|
|
@@ -32886,7 +33229,7 @@ var SqlitePoliciesRepository = class {
|
|
|
32886
33229
|
const count = countScalar(this.db, "SELECT count(*) AS n FROM policies");
|
|
32887
33230
|
if (count > 0) {
|
|
32888
33231
|
this.markEarlierChoices();
|
|
32889
|
-
this.monitorUntouchedSeeds();
|
|
33232
|
+
if (this.monitorUntouchedSeeds()) this.onChange();
|
|
32890
33233
|
return;
|
|
32891
33234
|
}
|
|
32892
33235
|
const stmt = this.db.prepare(
|
|
@@ -32903,6 +33246,7 @@ var SqlitePoliciesRepository = class {
|
|
|
32903
33246
|
});
|
|
32904
33247
|
}
|
|
32905
33248
|
});
|
|
33249
|
+
this.onChange();
|
|
32906
33250
|
}
|
|
32907
33251
|
// Before this build, upsertCategoryAction INSERTed a new row with updated_at
|
|
32908
33252
|
// equal to created_at, so a choice made for a category that had no row yet
|
|
@@ -32968,7 +33312,7 @@ var SqlitePoliciesRepository = class {
|
|
|
32968
33312
|
).filter(
|
|
32969
33313
|
(row) => DEFAULT_ACTIONS[row.category] === row.action
|
|
32970
33314
|
);
|
|
32971
|
-
if (untouched.length === 0) return;
|
|
33315
|
+
if (untouched.length === 0) return false;
|
|
32972
33316
|
const stmt = this.db.prepare(
|
|
32973
33317
|
`UPDATE policies SET action = 'log'
|
|
32974
33318
|
WHERE scope = 'global' AND json_extract(target, '$.category') = :category
|
|
@@ -32979,6 +33323,7 @@ var SqlitePoliciesRepository = class {
|
|
|
32979
33323
|
stmt.run({ category: row.category, seeded: row.action });
|
|
32980
33324
|
}
|
|
32981
33325
|
});
|
|
33326
|
+
return true;
|
|
32982
33327
|
}
|
|
32983
33328
|
// Insert-or-update the single global per-category policy row, keyed on the
|
|
32984
33329
|
// existing uq_policies_scope_target unique index (scope, target). `action`
|
|
@@ -32995,6 +33340,7 @@ var SqlitePoliciesRepository = class {
|
|
|
32995
33340
|
ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1,
|
|
32996
33341
|
updated_at = MAX(excluded.updated_at, policies.created_at + 1)`
|
|
32997
33342
|
).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
|
|
33343
|
+
this.onChange();
|
|
32998
33344
|
}
|
|
32999
33345
|
// Caps every global per-category policy currently set to block/redact down
|
|
33000
33346
|
// to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
|
|
@@ -33005,6 +33351,7 @@ var SqlitePoliciesRepository = class {
|
|
|
33005
33351
|
WHERE scope='global' AND action IN ('block','redact')
|
|
33006
33352
|
AND json_extract(target,'$.category') IS NOT NULL`
|
|
33007
33353
|
).run({ now: Date.now() });
|
|
33354
|
+
if (Number(info.changes) > 0) this.onChange();
|
|
33008
33355
|
return Number(info.changes);
|
|
33009
33356
|
}
|
|
33010
33357
|
// Whether the category's row was ever written after it was created — by the
|
|
@@ -33312,9 +33659,9 @@ var SqliteRuleProbeCacheRepository = class {
|
|
|
33312
33659
|
});
|
|
33313
33660
|
return { refused: !committed, cleared: before - this.countQuarantined() };
|
|
33314
33661
|
}
|
|
33315
|
-
setVerdict(ruleKey, verdict,
|
|
33662
|
+
setVerdict(ruleKey, verdict, worstProbeMs2) {
|
|
33316
33663
|
failOpenTransaction(this.db, () => {
|
|
33317
|
-
this.upsertStmt.run({ ruleKey, verdict, worstProbeMs, checkedAt: Date.now() });
|
|
33664
|
+
this.upsertStmt.run({ ruleKey, verdict, worstProbeMs: worstProbeMs2, checkedAt: Date.now() });
|
|
33318
33665
|
});
|
|
33319
33666
|
}
|
|
33320
33667
|
};
|
|
@@ -33324,31 +33671,45 @@ var SqliteScanLedgerRepository = class {
|
|
|
33324
33671
|
constructor(db) {
|
|
33325
33672
|
this.db = db;
|
|
33326
33673
|
this.upsertStmt = db.prepare(
|
|
33327
|
-
`INSERT INTO scan_ledger
|
|
33328
|
-
|
|
33674
|
+
`INSERT INTO scan_ledger
|
|
33675
|
+
(path, mtime, content_hash, ruleset_hash, scope_key, scope_root, scanned_at)
|
|
33676
|
+
VALUES (:path, :mtime, :contentHash, :rulesetHash, :scopeKey, :scopeRoot, :scannedAt)
|
|
33329
33677
|
ON CONFLICT (path) DO UPDATE SET
|
|
33330
33678
|
mtime = excluded.mtime,
|
|
33331
33679
|
content_hash = excluded.content_hash,
|
|
33332
33680
|
ruleset_hash = excluded.ruleset_hash,
|
|
33681
|
+
scope_key = excluded.scope_key,
|
|
33682
|
+
scope_root = excluded.scope_root,
|
|
33333
33683
|
scanned_at = excluded.scanned_at`
|
|
33334
33684
|
);
|
|
33335
33685
|
this.readStmt = db.prepare(
|
|
33336
|
-
`SELECT path, mtime, content_hash AS contentHash
|
|
33686
|
+
`SELECT path, mtime, content_hash AS contentHash, scope_key AS scopeKey,
|
|
33687
|
+
scope_root AS scopeRoot
|
|
33337
33688
|
FROM scan_ledger WHERE ruleset_hash = :rulesetHash`
|
|
33338
33689
|
);
|
|
33339
33690
|
this.pathsStmt = db.prepare(`SELECT path FROM scan_ledger`);
|
|
33691
|
+
this.pathKeysStmt = db.prepare(`SELECT path, scope_key AS scopeKey FROM scan_ledger`);
|
|
33340
33692
|
}
|
|
33341
33693
|
db;
|
|
33342
33694
|
upsertStmt;
|
|
33343
33695
|
readStmt;
|
|
33344
33696
|
pathsStmt;
|
|
33697
|
+
pathKeysStmt;
|
|
33345
33698
|
// Previously scanned files under THIS ruleset, keyed by path. Rows from an
|
|
33346
33699
|
// older ruleset are simply absent, which reads as "never scanned".
|
|
33347
33700
|
entriesForRuleset(rulesetHash) {
|
|
33348
|
-
const rows = allRows(this.readStmt, {
|
|
33349
|
-
|
|
33350
|
-
|
|
33351
|
-
|
|
33701
|
+
const rows = allRows(this.readStmt, { rulesetHash });
|
|
33702
|
+
return new Map(
|
|
33703
|
+
rows.map((r) => [
|
|
33704
|
+
r.path,
|
|
33705
|
+
{
|
|
33706
|
+
mtime: r.mtime,
|
|
33707
|
+
contentHash: r.contentHash,
|
|
33708
|
+
...r.scopeKey !== null ? { scopeKey: r.scopeKey } : {},
|
|
33709
|
+
...r.scopeRoot !== null ? { scopeRoot: r.scopeRoot } : {}
|
|
33710
|
+
}
|
|
33711
|
+
])
|
|
33712
|
+
);
|
|
33352
33713
|
}
|
|
33353
33714
|
// Every ledgered path, whatever ruleset it was scanned under — the set a
|
|
33354
33715
|
// deletion sweep checks against disk. A file deleted before a ruleset change
|
|
@@ -33357,6 +33718,14 @@ var SqliteScanLedgerRepository = class {
|
|
|
33357
33718
|
allPaths() {
|
|
33358
33719
|
return allRows(this.pathsStmt).map((r) => r.path);
|
|
33359
33720
|
}
|
|
33721
|
+
// Every ledgered path with the repository it was in when it was last read,
|
|
33722
|
+
// whatever ruleset it was scanned under: what a deletion sweep needs to say
|
|
33723
|
+
// which repository a vanished file belonged to. `undefined` for a row with no
|
|
33724
|
+
// key, which is every row written before the column existed.
|
|
33725
|
+
pathKeys() {
|
|
33726
|
+
const rows = allRows(this.pathKeysStmt);
|
|
33727
|
+
return new Map(rows.map((r) => [r.path, r.scopeKey ?? void 0]));
|
|
33728
|
+
}
|
|
33360
33729
|
upsertEntries(entries) {
|
|
33361
33730
|
if (entries.length === 0) return;
|
|
33362
33731
|
const scannedAt = Date.now();
|
|
@@ -33367,6 +33736,8 @@ var SqliteScanLedgerRepository = class {
|
|
|
33367
33736
|
mtime: entry.mtime,
|
|
33368
33737
|
contentHash: entry.contentHash,
|
|
33369
33738
|
rulesetHash: entry.rulesetHash,
|
|
33739
|
+
scopeKey: entry.scopeKey ?? null,
|
|
33740
|
+
scopeRoot: entry.scopeRoot ?? null,
|
|
33370
33741
|
scannedAt
|
|
33371
33742
|
});
|
|
33372
33743
|
}
|
|
@@ -34454,6 +34825,11 @@ function withoutDroppedFiles(reconcile, droppedFiles) {
|
|
|
34454
34825
|
deletedFiles: reconcile.deletedFiles.filter((file2) => !dropped.has(file2))
|
|
34455
34826
|
};
|
|
34456
34827
|
}
|
|
34828
|
+
function withoutTrailingSlashes(path) {
|
|
34829
|
+
let end = path.length;
|
|
34830
|
+
while (end > 0 && path.charCodeAt(end - 1) === 47) end--;
|
|
34831
|
+
return path.slice(0, end);
|
|
34832
|
+
}
|
|
34457
34833
|
function toEndpointSummary(row) {
|
|
34458
34834
|
return {
|
|
34459
34835
|
id: row.id,
|
|
@@ -34741,7 +35117,7 @@ var SqliteSharesRepository = class {
|
|
|
34741
35117
|
*/
|
|
34742
35118
|
reconcileCallSites(projectKey, reconcile) {
|
|
34743
35119
|
if (reconcile.mode === "walk") {
|
|
34744
|
-
const prefix = reconcile.walkedPrefix
|
|
35120
|
+
const prefix = withoutTrailingSlashes(reconcile.walkedPrefix);
|
|
34745
35121
|
this.db.prepare(
|
|
34746
35122
|
`DELETE FROM share_call_site
|
|
34747
35123
|
WHERE project_key = :key
|
|
@@ -35309,7 +35685,7 @@ function backupLegacyStore(db, file2) {
|
|
|
35309
35685
|
discardStore(file2, backup);
|
|
35310
35686
|
return backup;
|
|
35311
35687
|
}
|
|
35312
|
-
function openAndInitialize(file2, base, skipTags) {
|
|
35688
|
+
function openAndInitialize(file2, base, skipTags, shippedRegexMatchers2) {
|
|
35313
35689
|
let db = openWithPragmas(file2);
|
|
35314
35690
|
try {
|
|
35315
35691
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -35321,8 +35697,15 @@ function openAndInitialize(file2, base, skipTags) {
|
|
|
35321
35697
|
}
|
|
35322
35698
|
applyMigrations(db, file2, { skipTags });
|
|
35323
35699
|
tightenPerms(file2);
|
|
35324
|
-
const
|
|
35325
|
-
const
|
|
35700
|
+
const modPolicy = {};
|
|
35701
|
+
const onPolicyStateChange = () => {
|
|
35702
|
+
if (modPolicy.current !== void 0)
|
|
35703
|
+
refreshModPolicySnapshot(dirname2(file2), modPolicy.current);
|
|
35704
|
+
};
|
|
35705
|
+
const policies = new SqlitePoliciesRepository(db, onPolicyStateChange);
|
|
35706
|
+
const installedPacks = new SqliteInstalledPacksRepository(db, base, onPolicyStateChange);
|
|
35707
|
+
const ruleProbeCache = new SqliteRuleProbeCacheRepository(db);
|
|
35708
|
+
const exceptions = new SqliteExceptionsRepository(db, void 0, onPolicyStateChange);
|
|
35326
35709
|
const repositories = {
|
|
35327
35710
|
events: new SqliteEventsRepository(db),
|
|
35328
35711
|
findings: new SqliteFindingsRepository(db),
|
|
@@ -35331,9 +35714,9 @@ function openAndInitialize(file2, base, skipTags) {
|
|
|
35331
35714
|
scanLedger: new SqliteScanLedgerRepository(db),
|
|
35332
35715
|
historySync: new SqliteHistorySyncRepository(db),
|
|
35333
35716
|
secretVault: new SqliteSecretVaultRepository(db),
|
|
35334
|
-
exceptions
|
|
35717
|
+
exceptions,
|
|
35335
35718
|
resolutions: new SqliteResolutionsRepository(db),
|
|
35336
|
-
ruleProbeCache
|
|
35719
|
+
ruleProbeCache,
|
|
35337
35720
|
bodyRetention: new SqliteBodyRetentionRepository(db),
|
|
35338
35721
|
security: new SqliteSecurityRepository(db),
|
|
35339
35722
|
detections: new SqliteDetectionsRepository(db),
|
|
@@ -35351,6 +35734,13 @@ function openAndInitialize(file2, base, skipTags) {
|
|
|
35351
35734
|
inspectionFindings: new SqliteInspectionFindingsRepository(db),
|
|
35352
35735
|
configInventory: new SqliteConfigInventoryRepository(db)
|
|
35353
35736
|
};
|
|
35737
|
+
modPolicy.current = {
|
|
35738
|
+
installedRuleset: () => installedPacks.installedRuleset(),
|
|
35739
|
+
readPolicies: () => policies.listPolicies(),
|
|
35740
|
+
activeExceptionRuleIds: () => exceptions.activeRuleIds(),
|
|
35741
|
+
probeVerdict: (key) => ruleProbeCache.getVerdict(key)?.verdict,
|
|
35742
|
+
bundledRegexMatchers: () => shippedRegexMatchers2
|
|
35743
|
+
};
|
|
35354
35744
|
policies.seedDefaults();
|
|
35355
35745
|
return { db, ...repositories };
|
|
35356
35746
|
} catch (err) {
|
|
@@ -35362,7 +35752,7 @@ function openAndInitialize(file2, base, skipTags) {
|
|
|
35362
35752
|
var DEFERRED_TAGS = new Set(DEFERRED_MIGRATION_TAGS);
|
|
35363
35753
|
function openLocalDatabase(dir, options = {}) {
|
|
35364
35754
|
ensureDataDirSync(dir);
|
|
35365
|
-
const file2 =
|
|
35755
|
+
const file2 = join8(dir, DB_FILENAME);
|
|
35366
35756
|
reapStalePartials(file2);
|
|
35367
35757
|
const {
|
|
35368
35758
|
db,
|
|
@@ -35398,7 +35788,8 @@ function openLocalDatabase(dir, options = {}) {
|
|
|
35398
35788
|
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
35399
35789
|
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
35400
35790
|
dirname2(dir),
|
|
35401
|
-
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS
|
|
35791
|
+
options.applyDeferredMigrations === true ? void 0 : DEFERRED_TAGS,
|
|
35792
|
+
options.shippedRegexMatchers ?? []
|
|
35402
35793
|
);
|
|
35403
35794
|
function captureRowId(event) {
|
|
35404
35795
|
return captureId(
|
|
@@ -35663,7 +36054,7 @@ function openLocalDatabase(dir, options = {}) {
|
|
|
35663
36054
|
}
|
|
35664
36055
|
|
|
35665
36056
|
// ../../packages/persistence/src/egress-wire.ts
|
|
35666
|
-
import { createHash as
|
|
36057
|
+
import { createHash as createHash4 } from "crypto";
|
|
35667
36058
|
var PROJECT_KEY_DIGEST_VERSION = "v2";
|
|
35668
36059
|
var SCP_FORM = /^(?:[^@/]+@)?([^/:]+):(.+)$/;
|
|
35669
36060
|
var DOS_DRIVE = /^[A-Za-z]:[\\/]/;
|
|
@@ -35695,7 +36086,7 @@ function canonicalGitUrl(url2) {
|
|
|
35695
36086
|
}
|
|
35696
36087
|
function hashProjectKey(projectKey) {
|
|
35697
36088
|
const canonical = projectKey.startsWith("git:") ? `git:${canonicalGitUrl(projectKey.slice("git:".length))}` : projectKey;
|
|
35698
|
-
return
|
|
36089
|
+
return createHash4("sha256").update(`${PROJECT_KEY_DIGEST_VERSION}:${canonical}`, "utf8").digest("hex");
|
|
35699
36090
|
}
|
|
35700
36091
|
var SCOPE_KEY = printable(ATTACHMENT_SCOPE_IDENTITY_MAX_LENGTH);
|
|
35701
36092
|
var URL_SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
|
|
@@ -35760,17 +36151,16 @@ function toEgressIngestRequest(input2) {
|
|
|
35760
36151
|
}
|
|
35761
36152
|
|
|
35762
36153
|
// ../../packages/persistence/src/finding-key.ts
|
|
35763
|
-
import { createHash as
|
|
36154
|
+
import { createHash as createHash5 } from "crypto";
|
|
35764
36155
|
|
|
35765
36156
|
// ../../packages/persistence/src/fingerprint.ts
|
|
35766
36157
|
import { createHmac, randomBytes } from "crypto";
|
|
35767
|
-
import { existsSync as existsSync3, readFileSync as
|
|
35768
|
-
import { join as
|
|
35769
|
-
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
36158
|
+
import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
|
|
36159
|
+
import { join as join9 } from "path";
|
|
35770
36160
|
var EXCEPTION_KEY_FILENAME = "exception.key";
|
|
35771
36161
|
var KEY_MATERIAL_BYTES = 32;
|
|
35772
36162
|
function keyFilePath(dataDir2) {
|
|
35773
|
-
return
|
|
36163
|
+
return join9(dataDir2, EXCEPTION_KEY_FILENAME);
|
|
35774
36164
|
}
|
|
35775
36165
|
function parseKeyFile(raw) {
|
|
35776
36166
|
const parsed2 = JSON.parse(raw);
|
|
@@ -35793,7 +36183,7 @@ function parseKeyFile(raw) {
|
|
|
35793
36183
|
function readFingerprintKey(dataDir2) {
|
|
35794
36184
|
let raw;
|
|
35795
36185
|
try {
|
|
35796
|
-
raw =
|
|
36186
|
+
raw = readFileSync7(keyFilePath(dataDir2), "utf8");
|
|
35797
36187
|
} catch (err) {
|
|
35798
36188
|
if (err.code === "ENOENT") return null;
|
|
35799
36189
|
throw err instanceof Error ? err : new Error(String(err));
|
|
@@ -35802,8 +36192,8 @@ function readFingerprintKey(dataDir2) {
|
|
|
35802
36192
|
}
|
|
35803
36193
|
|
|
35804
36194
|
// ../../packages/persistence/src/forward-health.ts
|
|
35805
|
-
import { readFileSync as
|
|
35806
|
-
import { join as
|
|
36195
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
36196
|
+
import { join as join10 } from "path";
|
|
35807
36197
|
var BREAKER_COOLDOWN_MS = 3e4;
|
|
35808
36198
|
function parseForwardHealth(raw, nowMs) {
|
|
35809
36199
|
try {
|
|
@@ -35827,20 +36217,21 @@ function isForwardPaused(health, nowMs) {
|
|
|
35827
36217
|
|
|
35828
36218
|
// ../../packages/persistence/src/history-backfill.ts
|
|
35829
36219
|
import { existsSync as existsSync4 } from "fs";
|
|
35830
|
-
import { join as
|
|
36220
|
+
import { join as join11 } from "path";
|
|
35831
36221
|
|
|
35832
36222
|
// ../../packages/persistence/src/history-preview.ts
|
|
35833
36223
|
import { existsSync as existsSync5 } from "fs";
|
|
35834
|
-
import { join as
|
|
35835
|
-
import { DatabaseSync as
|
|
36224
|
+
import { join as join12 } from "path";
|
|
36225
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
35836
36226
|
|
|
35837
36227
|
// ../../packages/persistence/src/history-sync-state.ts
|
|
35838
|
-
import { readFileSync as
|
|
35839
|
-
import { join as
|
|
36228
|
+
import { readFileSync as readFileSync9 } from "fs";
|
|
36229
|
+
import { join as join13 } from "path";
|
|
36230
|
+
var COUNTS_SCOPES = new Set(AttachmentMode.options);
|
|
35840
36231
|
|
|
35841
36232
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
35842
36233
|
import { existsSync as existsSync6, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
35843
|
-
import { dirname as dirname3, join as
|
|
36234
|
+
import { dirname as dirname3, join as join14, resolve } from "path";
|
|
35844
36235
|
var STORE_DB = "the store database (including the prompt corpus)";
|
|
35845
36236
|
var STORE_SETTINGS = "your settings file";
|
|
35846
36237
|
function storeContents(home) {
|
|
@@ -35849,7 +36240,7 @@ function storeContents(home) {
|
|
|
35849
36240
|
[settingsDir(home), STORE_SETTINGS],
|
|
35850
36241
|
[dataDir(home), STORE_DB],
|
|
35851
36242
|
[keysDir(home), "the vault key"],
|
|
35852
|
-
[
|
|
36243
|
+
[join14(settingsDir(home), "settings.json"), STORE_SETTINGS],
|
|
35853
36244
|
[dbPath(home), STORE_DB]
|
|
35854
36245
|
]);
|
|
35855
36246
|
}
|
|
@@ -35901,19 +36292,19 @@ import {
|
|
|
35901
36292
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
35902
36293
|
import { execFileSync } from "child_process";
|
|
35903
36294
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
35904
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
35905
|
-
import { join as
|
|
36295
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync10, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
36296
|
+
import { join as join15 } from "path";
|
|
35906
36297
|
|
|
35907
36298
|
// ../../packages/persistence/src/vault/vault.ts
|
|
35908
36299
|
import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
|
|
35909
36300
|
|
|
35910
36301
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
35911
36302
|
import { existsSync as existsSync7, writeFileSync as writeFileSync4 } from "fs";
|
|
35912
|
-
import { join as
|
|
36303
|
+
import { join as join16 } from "path";
|
|
35913
36304
|
var MARKER = "warn-era-capped";
|
|
35914
36305
|
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
35915
36306
|
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
35916
|
-
const marker =
|
|
36307
|
+
const marker = join16(dataDir2, MARKER);
|
|
35917
36308
|
if (existsSync7(marker)) return { capped: 0, skipped: "already-run" };
|
|
35918
36309
|
const capped = db.policies.capCategoryActions();
|
|
35919
36310
|
writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
|
|
@@ -35921,425 +36312,6 @@ function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
|
35921
36312
|
return { capped };
|
|
35922
36313
|
}
|
|
35923
36314
|
|
|
35924
|
-
// ../../packages/remote/src/http.ts
|
|
35925
|
-
import { request as httpRequest } from "http";
|
|
35926
|
-
import { request as httpsRequest } from "https";
|
|
35927
|
-
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
35928
|
-
var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
35929
|
-
var RemoteRequestError = class extends Error {
|
|
35930
|
-
constructor(status) {
|
|
35931
|
-
super(`control-plane request failed with status ${String(status)}`);
|
|
35932
|
-
this.status = status;
|
|
35933
|
-
this.name = "RemoteRequestError";
|
|
35934
|
-
}
|
|
35935
|
-
status;
|
|
35936
|
-
};
|
|
35937
|
-
var RemoteRouteAbsent = class extends Error {
|
|
35938
|
-
constructor(route) {
|
|
35939
|
-
super(`control plane does not serve ${route}`);
|
|
35940
|
-
this.route = route;
|
|
35941
|
-
this.name = "RemoteRouteAbsent";
|
|
35942
|
-
}
|
|
35943
|
-
route;
|
|
35944
|
-
};
|
|
35945
|
-
var RemoteRequestInvalid = class extends Error {
|
|
35946
|
-
constructor(route, cause) {
|
|
35947
|
-
super(`refusing to send a malformed body to ${route}`);
|
|
35948
|
-
this.cause = cause;
|
|
35949
|
-
this.name = "RemoteRequestInvalid";
|
|
35950
|
-
}
|
|
35951
|
-
cause;
|
|
35952
|
-
};
|
|
35953
|
-
var RemoteEndpointRefused = class extends Error {
|
|
35954
|
-
constructor(endpoint) {
|
|
35955
|
-
super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
|
|
35956
|
-
this.name = "RemoteEndpointRefused";
|
|
35957
|
-
}
|
|
35958
|
-
};
|
|
35959
|
-
var RemoteResponseInvalid = class extends Error {
|
|
35960
|
-
constructor(route, detail) {
|
|
35961
|
-
super(`control plane answered ${route} with ${detail}`);
|
|
35962
|
-
this.name = "RemoteResponseInvalid";
|
|
35963
|
-
}
|
|
35964
|
-
};
|
|
35965
|
-
var RemoteTransportError = class extends Error {
|
|
35966
|
-
/**
|
|
35967
|
-
* The status the peer sent, when headers arrived and only the BODY was
|
|
35968
|
-
* refused.
|
|
35969
|
-
*
|
|
35970
|
-
* Undefined for the ordinary case this class was written for — no answer at
|
|
35971
|
-
* all. It exists because two paths reject after a status has already been
|
|
35972
|
-
* delivered: an oversized body and an aborted response. Discarding it there
|
|
35973
|
-
* reported a deployment answering 401 with a verbose body as a network
|
|
35974
|
-
* outage, which sends the reader to look at their network instead of their
|
|
35975
|
-
* credential.
|
|
35976
|
-
*/
|
|
35977
|
-
constructor(reason, status) {
|
|
35978
|
-
super(`control-plane request did not complete: ${reason}`);
|
|
35979
|
-
this.status = status;
|
|
35980
|
-
this.name = "RemoteTransportError";
|
|
35981
|
-
}
|
|
35982
|
-
status;
|
|
35983
|
-
};
|
|
35984
|
-
async function send(options) {
|
|
35985
|
-
const url2 = new URL(options.url);
|
|
35986
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
35987
|
-
const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
|
|
35988
|
-
const requestOptions = {
|
|
35989
|
-
method: options.method,
|
|
35990
|
-
headers: {
|
|
35991
|
-
// CALLER HEADERS FIRST, so this module's own are not overridable. Spread
|
|
35992
|
-
// last they win, and two of the values below are ones no caller may
|
|
35993
|
-
// replace: `x-api-key` is the credential, and `content-length` is the
|
|
35994
|
-
// byte count that stops a multi-byte body being truncated by the
|
|
35995
|
-
// receiver. `SendOptions.headers` is a free-form record on an exported
|
|
35996
|
-
// function, so "no caller does that today" is not the guarantee to rely
|
|
35997
|
-
// on. The one header any caller actually passes — `if-none-match` on the
|
|
35998
|
-
// conditional GET — is untouched by this order.
|
|
35999
|
-
...options.headers,
|
|
36000
|
-
// The credential. One header, matching what the deployment authenticates
|
|
36001
|
-
// on; a second copy in an `Authorization` header would be one more place
|
|
36002
|
-
// it can be logged by an intermediary for no gain.
|
|
36003
|
-
//
|
|
36004
|
-
// Spread conditionally rather than assigned as `undefined`: Node's header
|
|
36005
|
-
// handling and `content-length` bookkeeping treat a present-but-undefined
|
|
36006
|
-
// key differently from an absent one, and "the header is not there" is
|
|
36007
|
-
// the property the attach flow needs.
|
|
36008
|
-
...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
|
|
36009
|
-
accept: "application/json",
|
|
36010
|
-
...options.body === void 0 ? {} : {
|
|
36011
|
-
"content-type": "application/json",
|
|
36012
|
-
// Byte length, not string length: a multi-byte body sent with a
|
|
36013
|
-
// character count is truncated by the receiver.
|
|
36014
|
-
"content-length": String(Buffer.byteLength(options.body))
|
|
36015
|
-
}
|
|
36016
|
-
}
|
|
36017
|
-
};
|
|
36018
|
-
return new Promise((resolve3, reject) => {
|
|
36019
|
-
let settled = false;
|
|
36020
|
-
const fail = (reason, status) => {
|
|
36021
|
-
if (settled) return;
|
|
36022
|
-
settled = true;
|
|
36023
|
-
reject(new RemoteTransportError(reason, status));
|
|
36024
|
-
};
|
|
36025
|
-
const req = send_(url2, requestOptions, (res) => {
|
|
36026
|
-
const chunks = [];
|
|
36027
|
-
let size = 0;
|
|
36028
|
-
res.on("data", (chunk) => {
|
|
36029
|
-
size += chunk.length;
|
|
36030
|
-
if (size > MAX_RESPONSE_BYTES) {
|
|
36031
|
-
fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
|
|
36032
|
-
res.destroy();
|
|
36033
|
-
req.destroy();
|
|
36034
|
-
return;
|
|
36035
|
-
}
|
|
36036
|
-
chunks.push(chunk);
|
|
36037
|
-
});
|
|
36038
|
-
res.on("aborted", () => {
|
|
36039
|
-
fail("the response was aborted", res.statusCode);
|
|
36040
|
-
});
|
|
36041
|
-
res.on("end", () => {
|
|
36042
|
-
if (settled) return;
|
|
36043
|
-
settled = true;
|
|
36044
|
-
resolve3({
|
|
36045
|
-
status: res.statusCode ?? 0,
|
|
36046
|
-
headers: res.headers,
|
|
36047
|
-
body: Buffer.concat(chunks).toString("utf8")
|
|
36048
|
-
});
|
|
36049
|
-
});
|
|
36050
|
-
});
|
|
36051
|
-
const deadline = setTimeout(() => {
|
|
36052
|
-
fail(`no response within ${String(timeoutMs)}ms`);
|
|
36053
|
-
req.destroy();
|
|
36054
|
-
}, timeoutMs);
|
|
36055
|
-
deadline.unref();
|
|
36056
|
-
req.on("upgrade", (_res, socket) => {
|
|
36057
|
-
fail("the deployment answered with a protocol upgrade");
|
|
36058
|
-
socket.destroy();
|
|
36059
|
-
});
|
|
36060
|
-
req.on("close", () => {
|
|
36061
|
-
fail("the connection closed before a response was read");
|
|
36062
|
-
clearTimeout(deadline);
|
|
36063
|
-
});
|
|
36064
|
-
req.on("error", (err) => {
|
|
36065
|
-
fail(err.message);
|
|
36066
|
-
});
|
|
36067
|
-
if (options.body !== void 0) req.write(options.body);
|
|
36068
|
-
req.end();
|
|
36069
|
-
});
|
|
36070
|
-
}
|
|
36071
|
-
|
|
36072
|
-
// ../../packages/remote/src/client.ts
|
|
36073
|
-
var ROUTES = {
|
|
36074
|
-
events: "/v1/events",
|
|
36075
|
-
auditEvents: "/v1/audit-events",
|
|
36076
|
-
auditEventsBatch: "/v1/audit-events/batch",
|
|
36077
|
-
inventory: "/v1/inventory",
|
|
36078
|
-
storePosture: "/v1/store-posture",
|
|
36079
|
-
policyBundle: "/v1/policy-bundle",
|
|
36080
|
-
whoami: "/v1/plugin/whoami",
|
|
36081
|
-
shares: "/v1/shares",
|
|
36082
|
-
commands: "/v1/plugin/commands"
|
|
36083
|
-
};
|
|
36084
|
-
function ackRoute(id) {
|
|
36085
|
-
return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
|
|
36086
|
-
}
|
|
36087
|
-
function headerValue(response, name) {
|
|
36088
|
-
const raw = response.headers[name];
|
|
36089
|
-
if (raw === void 0) return void 0;
|
|
36090
|
-
return Array.isArray(raw) ? raw[0] : raw;
|
|
36091
|
-
}
|
|
36092
|
-
function okBody(response) {
|
|
36093
|
-
if (response.status < 200 || response.status >= 300) {
|
|
36094
|
-
throw new RemoteRequestError(response.status);
|
|
36095
|
-
}
|
|
36096
|
-
return response.body;
|
|
36097
|
-
}
|
|
36098
|
-
function parsed(schema, body, route) {
|
|
36099
|
-
let json2;
|
|
36100
|
-
try {
|
|
36101
|
-
json2 = JSON.parse(body);
|
|
36102
|
-
} catch {
|
|
36103
|
-
throw new RemoteResponseInvalid(route, "a body that is not JSON");
|
|
36104
|
-
}
|
|
36105
|
-
const result = schema.safeParse(json2);
|
|
36106
|
-
if (!result.success) {
|
|
36107
|
-
throw new RemoteResponseInvalid(route, "a body this client cannot read");
|
|
36108
|
-
}
|
|
36109
|
-
return result.data;
|
|
36110
|
-
}
|
|
36111
|
-
function resolveBaseUrl(endpoint) {
|
|
36112
|
-
if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
|
|
36113
|
-
let end = endpoint.length;
|
|
36114
|
-
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH2) end -= 1;
|
|
36115
|
-
return endpoint.slice(0, end);
|
|
36116
|
-
}
|
|
36117
|
-
var SLASH2 = "/".charCodeAt(0);
|
|
36118
|
-
function createRemoteClient(options) {
|
|
36119
|
-
const base = resolveBaseUrl(options.endpoint);
|
|
36120
|
-
const url2 = (route) => `${base}${route}`;
|
|
36121
|
-
const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
|
|
36122
|
-
const sendOne = async (event) => {
|
|
36123
|
-
const validated = RecordAuditEventRequest.safeParse(event);
|
|
36124
|
-
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
|
|
36125
|
-
const response = await send({
|
|
36126
|
-
...common,
|
|
36127
|
-
method: "POST",
|
|
36128
|
-
url: url2(ROUTES.auditEvents),
|
|
36129
|
-
body: JSON.stringify(validated.data)
|
|
36130
|
-
});
|
|
36131
|
-
okBody(response);
|
|
36132
|
-
};
|
|
36133
|
-
return {
|
|
36134
|
-
async ingestEvents(batch) {
|
|
36135
|
-
const response = await send({
|
|
36136
|
-
...common,
|
|
36137
|
-
method: "POST",
|
|
36138
|
-
url: url2(ROUTES.events),
|
|
36139
|
-
body: JSON.stringify(batch)
|
|
36140
|
-
});
|
|
36141
|
-
return parsed(IngestAck, okBody(response), ROUTES.events);
|
|
36142
|
-
},
|
|
36143
|
-
async ingestInventory(context) {
|
|
36144
|
-
const response = await send({
|
|
36145
|
-
...common,
|
|
36146
|
-
method: "POST",
|
|
36147
|
-
url: url2(ROUTES.inventory),
|
|
36148
|
-
body: JSON.stringify(context)
|
|
36149
|
-
});
|
|
36150
|
-
return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
|
|
36151
|
-
},
|
|
36152
|
-
async recordAuditEvent(event) {
|
|
36153
|
-
await sendOne(event);
|
|
36154
|
-
},
|
|
36155
|
-
async recordAuditEvents(events, opts) {
|
|
36156
|
-
const validated = RecordAuditEventBatch.safeParse({ events });
|
|
36157
|
-
if (!validated.success) {
|
|
36158
|
-
throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
|
|
36159
|
-
}
|
|
36160
|
-
const response = await send({
|
|
36161
|
-
...common,
|
|
36162
|
-
method: "POST",
|
|
36163
|
-
url: url2(ROUTES.auditEventsBatch),
|
|
36164
|
-
body: JSON.stringify(validated.data)
|
|
36165
|
-
});
|
|
36166
|
-
if (response.status === 404) {
|
|
36167
|
-
if (opts?.fallbackToSingleEvents !== true) {
|
|
36168
|
-
throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
|
|
36169
|
-
}
|
|
36170
|
-
for (const event of validated.data.events) await sendOne(event);
|
|
36171
|
-
return { accepted: validated.data.events.length };
|
|
36172
|
-
}
|
|
36173
|
-
return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
|
|
36174
|
-
},
|
|
36175
|
-
async reportStorePosture(snapshot) {
|
|
36176
|
-
const response = await send({
|
|
36177
|
-
...common,
|
|
36178
|
-
method: "POST",
|
|
36179
|
-
url: url2(ROUTES.storePosture),
|
|
36180
|
-
body: JSON.stringify(snapshot)
|
|
36181
|
-
});
|
|
36182
|
-
okBody(response);
|
|
36183
|
-
},
|
|
36184
|
-
async getPolicyBundle(etag) {
|
|
36185
|
-
const response = await send({
|
|
36186
|
-
...common,
|
|
36187
|
-
method: "GET",
|
|
36188
|
-
url: url2(ROUTES.policyBundle),
|
|
36189
|
-
...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
|
|
36190
|
-
});
|
|
36191
|
-
if (response.status === 304) {
|
|
36192
|
-
return { changed: false, etag: headerValue(response, "etag") ?? etag };
|
|
36193
|
-
}
|
|
36194
|
-
const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
|
|
36195
|
-
return { changed: true, bundle, etag: headerValue(response, "etag") };
|
|
36196
|
-
},
|
|
36197
|
-
async whoami() {
|
|
36198
|
-
const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
|
|
36199
|
-
return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
|
|
36200
|
-
},
|
|
36201
|
-
async recordProjectEgress(request) {
|
|
36202
|
-
const validated = EgressIngestRequest.safeParse(request);
|
|
36203
|
-
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
|
|
36204
|
-
const response = await send({
|
|
36205
|
-
...common,
|
|
36206
|
-
method: "POST",
|
|
36207
|
-
url: url2(ROUTES.shares),
|
|
36208
|
-
body: JSON.stringify(validated.data)
|
|
36209
|
-
});
|
|
36210
|
-
if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
|
|
36211
|
-
okBody(response);
|
|
36212
|
-
},
|
|
36213
|
-
async pollCommand() {
|
|
36214
|
-
const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
|
|
36215
|
-
if (response.status === 404) return null;
|
|
36216
|
-
return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
|
|
36217
|
-
},
|
|
36218
|
-
async ackCommand(id, body) {
|
|
36219
|
-
const validated = DeviceCommandAckBody.safeParse(body);
|
|
36220
|
-
const route = ackRoute(id);
|
|
36221
|
-
if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
|
|
36222
|
-
const response = await send({
|
|
36223
|
-
...common,
|
|
36224
|
-
method: "POST",
|
|
36225
|
-
url: url2(route),
|
|
36226
|
-
body: JSON.stringify(validated.data)
|
|
36227
|
-
});
|
|
36228
|
-
okBody(response);
|
|
36229
|
-
}
|
|
36230
|
-
};
|
|
36231
|
-
}
|
|
36232
|
-
|
|
36233
|
-
// ../../packages/remote/src/failure-kind.ts
|
|
36234
|
-
function statusOf(err) {
|
|
36235
|
-
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
36236
|
-
const { status } = err;
|
|
36237
|
-
if (typeof status !== "number" || !Number.isInteger(status)) return null;
|
|
36238
|
-
return status >= 100 && status <= 599 ? status : null;
|
|
36239
|
-
}
|
|
36240
|
-
function nameOf(err) {
|
|
36241
|
-
if (typeof err !== "object" || err === null || !("name" in err)) return null;
|
|
36242
|
-
return typeof err.name === "string" ? err.name : null;
|
|
36243
|
-
}
|
|
36244
|
-
function classifyRemoteFailure(err) {
|
|
36245
|
-
switch (nameOf(err)) {
|
|
36246
|
-
case "RemoteRouteAbsent":
|
|
36247
|
-
return "route-absent";
|
|
36248
|
-
case "RemoteRequestInvalid":
|
|
36249
|
-
case "RemoteEndpointRefused":
|
|
36250
|
-
return "invalid-request";
|
|
36251
|
-
case "RemoteResponseInvalid":
|
|
36252
|
-
return "rejected";
|
|
36253
|
-
default:
|
|
36254
|
-
break;
|
|
36255
|
-
}
|
|
36256
|
-
const status = statusOf(err);
|
|
36257
|
-
if (status === null) return "unreachable";
|
|
36258
|
-
switch (status) {
|
|
36259
|
-
case 401:
|
|
36260
|
-
return "unauthorized";
|
|
36261
|
-
case 403:
|
|
36262
|
-
return "forbidden";
|
|
36263
|
-
case 429:
|
|
36264
|
-
return "unreachable";
|
|
36265
|
-
case 404:
|
|
36266
|
-
return "unreachable";
|
|
36267
|
-
default:
|
|
36268
|
-
return status >= 400 && status <= 499 ? "rejected" : "unreachable";
|
|
36269
|
-
}
|
|
36270
|
-
}
|
|
36271
|
-
|
|
36272
|
-
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
36273
|
-
function classifyFailure(err) {
|
|
36274
|
-
switch (classifyRemoteFailure(err)) {
|
|
36275
|
-
case "unauthorized":
|
|
36276
|
-
return "unauthorized";
|
|
36277
|
-
case "forbidden":
|
|
36278
|
-
return "forbidden";
|
|
36279
|
-
default:
|
|
36280
|
-
return "unreachable";
|
|
36281
|
-
}
|
|
36282
|
-
}
|
|
36283
|
-
|
|
36284
|
-
// ../../packages/plugin-runtime/src/attached/with-timeout.ts
|
|
36285
|
-
var REQUEST_TIMEOUT_MS = 2e3;
|
|
36286
|
-
function withTimeout(promise2, ms) {
|
|
36287
|
-
let timer;
|
|
36288
|
-
const timeout = new Promise((_, reject) => {
|
|
36289
|
-
timer = setTimeout(() => {
|
|
36290
|
-
reject(new Error("attached gateway request timed out"));
|
|
36291
|
-
}, ms);
|
|
36292
|
-
});
|
|
36293
|
-
promise2.catch(() => void 0);
|
|
36294
|
-
return Promise.race([promise2, timeout]).finally(() => {
|
|
36295
|
-
clearTimeout(timer);
|
|
36296
|
-
});
|
|
36297
|
-
}
|
|
36298
|
-
|
|
36299
|
-
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
36300
|
-
import { readFileSync as readFileSync10 } from "fs";
|
|
36301
|
-
import { join as join16 } from "path";
|
|
36302
|
-
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
36303
|
-
function forwardDropsPath(dataDir2) {
|
|
36304
|
-
return join16(dataDir2, FORWARD_DROPS_FILENAME);
|
|
36305
|
-
}
|
|
36306
|
-
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
36307
|
-
if (count <= 0) return;
|
|
36308
|
-
try {
|
|
36309
|
-
ensureDataDirSync(dataDir2);
|
|
36310
|
-
const previous = readForwardDrops(dataDir2);
|
|
36311
|
-
const next = {
|
|
36312
|
-
droppedForwards: (previous?.droppedForwards ?? 0) + count,
|
|
36313
|
-
lastDropAtMs: nowMs
|
|
36314
|
-
};
|
|
36315
|
-
writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
|
|
36316
|
-
`);
|
|
36317
|
-
} catch {
|
|
36318
|
-
}
|
|
36319
|
-
}
|
|
36320
|
-
function readForwardDrops(dataDir2) {
|
|
36321
|
-
try {
|
|
36322
|
-
const parsed2 = JSON.parse(readFileSync10(forwardDropsPath(dataDir2), "utf8"));
|
|
36323
|
-
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
36324
|
-
const record2 = parsed2;
|
|
36325
|
-
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
36326
|
-
return null;
|
|
36327
|
-
}
|
|
36328
|
-
if (record2.droppedForwards <= 0) return null;
|
|
36329
|
-
if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
|
|
36330
|
-
return null;
|
|
36331
|
-
}
|
|
36332
|
-
return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
|
|
36333
|
-
} catch {
|
|
36334
|
-
return null;
|
|
36335
|
-
}
|
|
36336
|
-
}
|
|
36337
|
-
|
|
36338
|
-
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
36339
|
-
import { randomUUID as randomUUID16 } from "crypto";
|
|
36340
|
-
import { readFile, rename, writeFile } from "fs/promises";
|
|
36341
|
-
import { join as join28 } from "path";
|
|
36342
|
-
|
|
36343
36315
|
// ../../packages/plugin-sdk/src/config.ts
|
|
36344
36316
|
import { existsSync as existsSync8 } from "fs";
|
|
36345
36317
|
import { join as join17 } from "path";
|
|
@@ -37534,17 +37506,18 @@ function ruleEvidence(rule) {
|
|
|
37534
37506
|
|
|
37535
37507
|
// ../../packages/detections/src/mask.ts
|
|
37536
37508
|
function maskMatch(raw) {
|
|
37537
|
-
|
|
37538
|
-
|
|
37539
|
-
|
|
37540
|
-
|
|
37509
|
+
const visible = stripInvisiblePadding(raw);
|
|
37510
|
+
if (visible.length <= 5) return "***";
|
|
37511
|
+
const atIndex = visible.indexOf("@");
|
|
37512
|
+
if (atIndex > 0 && atIndex < visible.length - 1) {
|
|
37513
|
+
const domain2 = visible.slice(atIndex + 1);
|
|
37541
37514
|
if (domain2.includes(".")) {
|
|
37542
|
-
const local =
|
|
37515
|
+
const local = visible.slice(0, atIndex);
|
|
37543
37516
|
const maskedLocal = local.length <= 1 ? local : local.charAt(0) + "*".repeat(local.length - 1);
|
|
37544
37517
|
return `${maskedLocal}@${domain2}`;
|
|
37545
37518
|
}
|
|
37546
37519
|
}
|
|
37547
|
-
return `${
|
|
37520
|
+
return `${visible.charAt(0)}${"*".repeat(6)}${visible.charAt(visible.length - 1)}`;
|
|
37548
37521
|
}
|
|
37549
37522
|
|
|
37550
37523
|
// ../../packages/detections/src/pointer-shield.ts
|
|
@@ -37779,8 +37752,127 @@ var EXPONENTIAL_PROBES = EXPONENTIAL_UNITS.flatMap(
|
|
|
37779
37752
|
var POLYNOMIAL_PROBES = ["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map(
|
|
37780
37753
|
(unit) => unit.repeat(1e4).slice(0, 4e4) + "!"
|
|
37781
37754
|
);
|
|
37755
|
+
function literalPrefix(pattern) {
|
|
37756
|
+
let prefix = "";
|
|
37757
|
+
let i = 0;
|
|
37758
|
+
if (pattern[i] === "^") i++;
|
|
37759
|
+
while (i < pattern.length) {
|
|
37760
|
+
const c = pattern[i];
|
|
37761
|
+
if (c === void 0) break;
|
|
37762
|
+
if (c === "\\") {
|
|
37763
|
+
const next = pattern[i + 1];
|
|
37764
|
+
if (next === "b" || next === "B") {
|
|
37765
|
+
i += 2;
|
|
37766
|
+
continue;
|
|
37767
|
+
}
|
|
37768
|
+
if (next === void 0 || /[dDwWsSnrtfv.]/.test(next)) break;
|
|
37769
|
+
prefix += next;
|
|
37770
|
+
i += 2;
|
|
37771
|
+
continue;
|
|
37772
|
+
}
|
|
37773
|
+
if ("([{.*+?|)]}^$".includes(c)) break;
|
|
37774
|
+
prefix += c;
|
|
37775
|
+
i++;
|
|
37776
|
+
}
|
|
37777
|
+
return prefix;
|
|
37778
|
+
}
|
|
37779
|
+
function fuelChars(pattern) {
|
|
37780
|
+
const fuel = /* @__PURE__ */ new Set();
|
|
37781
|
+
for (const m of pattern.matchAll(/\[\^?([^\]]+)\]/g)) {
|
|
37782
|
+
const body = m[1];
|
|
37783
|
+
if (body === void 0) continue;
|
|
37784
|
+
const range = /([A-Za-z0-9])-[A-Za-z0-9]/.exec(body);
|
|
37785
|
+
const rangeStart = range?.[1];
|
|
37786
|
+
if (rangeStart !== void 0) fuel.add(rangeStart);
|
|
37787
|
+
else {
|
|
37788
|
+
const literal2 = body.replace(/\\/g, "")[0];
|
|
37789
|
+
if (literal2 !== void 0 && literal2 !== "^") fuel.add(literal2);
|
|
37790
|
+
}
|
|
37791
|
+
}
|
|
37792
|
+
if (pattern.includes("\\w")) fuel.add("a");
|
|
37793
|
+
if (pattern.includes("\\d")) fuel.add("0");
|
|
37794
|
+
if (pattern.includes("\\s")) fuel.add(" ");
|
|
37795
|
+
if (/(?<!\\)\./.test(pattern)) fuel.add("a");
|
|
37796
|
+
if (fuel.size === 0) fuel.add("a");
|
|
37797
|
+
return [...fuel];
|
|
37798
|
+
}
|
|
37799
|
+
function derivedProbes(pattern) {
|
|
37800
|
+
const prefix = literalPrefix(pattern);
|
|
37801
|
+
const fuel = fuelChars(pattern);
|
|
37802
|
+
const terminators = ["!", "#", "~", "\n"];
|
|
37803
|
+
const probes = [];
|
|
37804
|
+
for (const f of fuel) {
|
|
37805
|
+
for (const term of terminators) {
|
|
37806
|
+
if (term === f) continue;
|
|
37807
|
+
for (const len of [23, 25]) probes.push(prefix + f.repeat(len) + term);
|
|
37808
|
+
}
|
|
37809
|
+
}
|
|
37810
|
+
return probes;
|
|
37811
|
+
}
|
|
37812
|
+
function probesFor(rule) {
|
|
37813
|
+
const derived2 = rule.matcher.type === "regex" ? derivedProbes(rule.matcher.pattern) : [];
|
|
37814
|
+
return [...derived2, ...EXPONENTIAL_PROBES, ...POLYNOMIAL_PROBES];
|
|
37815
|
+
}
|
|
37816
|
+
var wallClock = () => performance.now();
|
|
37817
|
+
function worstProbeMs(rule, now = wallClock, corroborate) {
|
|
37818
|
+
let ms = 0;
|
|
37819
|
+
let probe = "";
|
|
37820
|
+
let corroboratedMs;
|
|
37821
|
+
for (const text of probesFor(rule)) {
|
|
37822
|
+
const start = now();
|
|
37823
|
+
const corroborateStart = corroborate?.();
|
|
37824
|
+
scan(text, [rule]);
|
|
37825
|
+
const elapsed = now() - start;
|
|
37826
|
+
const corroborateEnd = corroborate?.();
|
|
37827
|
+
if (elapsed > ms) {
|
|
37828
|
+
ms = elapsed;
|
|
37829
|
+
probe = text;
|
|
37830
|
+
corroboratedMs = corroborateStart === void 0 || corroborateEnd === void 0 ? void 0 : corroborateEnd - corroborateStart;
|
|
37831
|
+
}
|
|
37832
|
+
if (ms >= BUDGET_MS) break;
|
|
37833
|
+
}
|
|
37834
|
+
return { ms, probe, corroboratedMs };
|
|
37835
|
+
}
|
|
37782
37836
|
var CPU_CORROBORATION_SHARE = 0.2;
|
|
37783
37837
|
var CORROBORATION_FLOOR_MS = BUDGET_MS * CPU_CORROBORATION_SHARE;
|
|
37838
|
+
function repeatTo(unit, length) {
|
|
37839
|
+
return unit.repeat(Math.ceil(length / unit.length)).slice(0, length);
|
|
37840
|
+
}
|
|
37841
|
+
function joinTo(length, open3, close, item) {
|
|
37842
|
+
const parts = [];
|
|
37843
|
+
let size = open3.length;
|
|
37844
|
+
for (let i = 0; size < length; i++) {
|
|
37845
|
+
const next = (i === 0 ? "" : ",") + item(i);
|
|
37846
|
+
parts.push(next);
|
|
37847
|
+
size += next.length;
|
|
37848
|
+
}
|
|
37849
|
+
return (open3 + parts.join("") + close).slice(0, length);
|
|
37850
|
+
}
|
|
37851
|
+
var SQL_WORDS = ["select", "insert", "update", "delete", "drop", "where"];
|
|
37852
|
+
var GROWTH_CORPORA = [
|
|
37853
|
+
{
|
|
37854
|
+
name: "one-line JSON dictionary",
|
|
37855
|
+
build: (length) => joinTo(length, "{", "}", (i) => `"id-${String(i)}":"label ${String(i)}"`)
|
|
37856
|
+
},
|
|
37857
|
+
{
|
|
37858
|
+
name: "JSON array of quoted SQL keywords",
|
|
37859
|
+
build: (length) => joinTo(length, "[", "]", (i) => `"${SQL_WORDS[i % SQL_WORDS.length] ?? ""} ${String(i)}"`)
|
|
37860
|
+
},
|
|
37861
|
+
{ name: "single-quoted keyword run ('where)", build: (length) => repeatTo("'where", length) },
|
|
37862
|
+
{ name: "double-quote run", build: (length) => repeatTo('"', length) },
|
|
37863
|
+
{ name: "space run", build: (length) => repeatTo(" ", length) },
|
|
37864
|
+
{ name: "newline run", build: (length) => repeatTo("\n", length) },
|
|
37865
|
+
...["abc-", "a.", "a ", "a=", "x", "0", "a@", "a/", "ab"].map((unit) => ({
|
|
37866
|
+
name: `unit run ${JSON.stringify(unit)}`,
|
|
37867
|
+
build: (length) => repeatTo(unit, length)
|
|
37868
|
+
}))
|
|
37869
|
+
];
|
|
37870
|
+
function checkRuleTiming(rule, corroborate) {
|
|
37871
|
+
const { ms, probe, corroboratedMs } = worstProbeMs(rule, wallClock, corroborate);
|
|
37872
|
+
const work = corroboratedMs ?? 0;
|
|
37873
|
+
const verdict = ms < BUDGET_MS ? "safe" : work >= CORROBORATION_FLOOR_MS ? "over-budget" : "uncorroborated";
|
|
37874
|
+
return { verdict, worstMs: ms, corroboratedMs: work, probe };
|
|
37875
|
+
}
|
|
37784
37876
|
|
|
37785
37877
|
// ../../packages/plugin-sdk/src/raw-egress.ts
|
|
37786
37878
|
var RawEgressError = class extends Error {
|
|
@@ -37801,7 +37893,12 @@ var MIN_RAW_LEN = 4;
|
|
|
37801
37893
|
var RAW_RUN_LEN = 8;
|
|
37802
37894
|
function carriesRawRun(text, rawValues) {
|
|
37803
37895
|
let windows = null;
|
|
37804
|
-
|
|
37896
|
+
const values = /* @__PURE__ */ new Set();
|
|
37897
|
+
for (const raw of rawValues) {
|
|
37898
|
+
values.add(raw);
|
|
37899
|
+
values.add(stripInvisiblePadding(raw));
|
|
37900
|
+
}
|
|
37901
|
+
for (const raw of values) {
|
|
37805
37902
|
if (raw.length < MIN_RAW_LEN) continue;
|
|
37806
37903
|
if (raw.length < RAW_RUN_LEN) {
|
|
37807
37904
|
if (text.includes(raw)) return true;
|
|
@@ -37825,11 +37922,16 @@ function carriesRawRun(text, rawValues) {
|
|
|
37825
37922
|
return false;
|
|
37826
37923
|
}
|
|
37827
37924
|
function safeMaskedMatch(rawMatch) {
|
|
37828
|
-
const
|
|
37829
|
-
|
|
37830
|
-
|
|
37925
|
+
const visible = stripInvisiblePadding(rawMatch);
|
|
37926
|
+
const masked = maskMatch(visible);
|
|
37927
|
+
const reveals = (preview) => preview === visible || visible.length >= MIN_RAW_LEN && preview.includes(visible);
|
|
37928
|
+
if (!reveals(masked)) return masked;
|
|
37929
|
+
const atIndex = masked.indexOf("@");
|
|
37930
|
+
if (atIndex > 0 && atIndex < masked.length - 1) {
|
|
37931
|
+
const emailFallback = `*${masked.slice(atIndex)}`;
|
|
37932
|
+
if (!reveals(emailFallback)) return emailFallback;
|
|
37831
37933
|
}
|
|
37832
|
-
return
|
|
37934
|
+
return "***";
|
|
37833
37935
|
}
|
|
37834
37936
|
function assertRawFree(text, rawValues) {
|
|
37835
37937
|
if (carriesRawRun(text, rawValues)) {
|
|
@@ -38066,7 +38168,7 @@ var auth_jwt_no_verify_default = {
|
|
|
38066
38168
|
severity: "critical",
|
|
38067
38169
|
matcher: {
|
|
38068
38170
|
type: "regex",
|
|
38069
|
-
pattern: "(verify\\s*=\\s*false|verify_signature
|
|
38171
|
+
pattern: "(verify\\s*=\\s*false|verify_signature(?:(?!verify_signature).)*false|algorithms\\s*=\\s*\\[\\])",
|
|
38070
38172
|
flags: "gi"
|
|
38071
38173
|
},
|
|
38072
38174
|
requiresNearby: {
|
|
@@ -38154,7 +38256,7 @@ var cmd_inject_shell_default = {
|
|
|
38154
38256
|
severity: "critical",
|
|
38155
38257
|
matcher: {
|
|
38156
38258
|
type: "regex",
|
|
38157
|
-
pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\([^)]*shell\\s*=\\s*True",
|
|
38259
|
+
pattern: "subprocess\\.(run|Popen|call|check_output)\\s*\\((?:(?!subprocess\\.(?:run|Popen|call|check_output)\\s*\\()[^)])*shell\\s*=\\s*True",
|
|
38158
38260
|
flags: "gi"
|
|
38159
38261
|
},
|
|
38160
38262
|
requiresNearby: {
|
|
@@ -38283,7 +38385,7 @@ var deser_yaml_unsafe_default = {
|
|
|
38283
38385
|
severity: "high",
|
|
38284
38386
|
matcher: {
|
|
38285
38387
|
type: "regex",
|
|
38286
|
-
pattern: "\\byaml\\.load\\s*\\((?![^)]
|
|
38388
|
+
pattern: "\\byaml\\.load\\s*\\((?!(?:(?!yaml\\.load\\s*\\()[^)])*?(?:SafeLoader|safe_load))",
|
|
38287
38389
|
flags: "gi"
|
|
38288
38390
|
},
|
|
38289
38391
|
examples: ["data = yaml.load(user_input)", "config = yaml.load(f)"],
|
|
@@ -38500,7 +38602,7 @@ var sql_inject_concat_dot_default = {
|
|
|
38500
38602
|
severity: "high",
|
|
38501
38603
|
matcher: {
|
|
38502
38604
|
type: "regex",
|
|
38503
|
-
pattern: `["'][
|
|
38605
|
+
pattern: `["'](?=([^"'\\n]*?(?:select|insert|update|delete|drop|where)))\\1(?:(?!["'][^"'\\n]*?(?:select|insert|update|delete|drop|where))[^\\n])*?["']\\s*\\.`,
|
|
38504
38606
|
flags: "gi"
|
|
38505
38607
|
},
|
|
38506
38608
|
appliesTo: {
|
|
@@ -38518,7 +38620,7 @@ var sql_inject_concat_default = {
|
|
|
38518
38620
|
severity: "high",
|
|
38519
38621
|
matcher: {
|
|
38520
38622
|
type: "regex",
|
|
38521
|
-
pattern: `["']\\s*(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?["']\\s*\\+`,
|
|
38623
|
+
pattern: `(["'])\\s*(?=(select\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?=))\\2(?:(?!\\1\\s*(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b))[^\\n])*?["']\\s*\\+`,
|
|
38522
38624
|
flags: "gi"
|
|
38523
38625
|
},
|
|
38524
38626
|
examples: ['"SELECT * FROM users WHERE id = " + userId']
|
|
@@ -38533,7 +38635,7 @@ var sql_inject_format_default = {
|
|
|
38533
38635
|
severity: "high",
|
|
38534
38636
|
matcher: {
|
|
38535
38637
|
type: "regex",
|
|
38536
|
-
pattern: "\\b(?:select\\b[^\\n]*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b|where\\b[^\\n]*?=)[^\\n]*?(?:[%][sd]|\\{[^}]+\\})",
|
|
38638
|
+
pattern: "\\b(?=(select\\b(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?\\bfrom\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))\\1(?:(?!\\b(?:select\\b|insert\\s+into\\b|update\\s+\\S+\\s+set\\b|delete\\s+from\\b|drop\\s+(?:table|database)\\b))[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})|\\b(?=(where\\b(?:(?!\\bwhere\\b)[^\\n])*?=))\\2(?:(?!\\bwhere\\b)[^\\n])*?(?:[%][sd]|\\{[^{}\\n]+\\})",
|
|
38537
38639
|
flags: "gi"
|
|
38538
38640
|
},
|
|
38539
38641
|
examples: [
|
|
@@ -38551,7 +38653,7 @@ var sql_inject_interp_default = {
|
|
|
38551
38653
|
severity: "high",
|
|
38552
38654
|
matcher: {
|
|
38553
38655
|
type: "regex",
|
|
38554
|
-
pattern: "(select|insert|update|delete|where)[^\\n]*?(#\\{|\\$[a-z_])",
|
|
38656
|
+
pattern: "(select|insert|update|delete|where)(?:(?!(?:select|insert|update|delete|where))[^\\n])*?(#\\{|\\$[a-z_])",
|
|
38555
38657
|
flags: "gi"
|
|
38556
38658
|
},
|
|
38557
38659
|
examples: [
|
|
@@ -38926,7 +39028,7 @@ var stack_trace_default = {
|
|
|
38926
39028
|
severity: "low",
|
|
38927
39029
|
matcher: {
|
|
38928
39030
|
type: "regex",
|
|
38929
|
-
pattern: "(
|
|
39031
|
+
pattern: "(?:^|(?<!\\s)\\s+)at\\s+[A-Za-z0-9._$<>]+\\.[A-Za-z0-9_$]+\\s*\\([A-Za-z0-9._\\-/:]+:\\d+:\\d+\\)",
|
|
38930
39032
|
flags: "g"
|
|
38931
39033
|
},
|
|
38932
39034
|
examples: ["at com.example.service.UserService.findUser(UserService.java:42:13)"]
|
|
@@ -40084,7 +40186,7 @@ var BUNDLED_PACKS = [
|
|
|
40084
40186
|
{
|
|
40085
40187
|
packId: "code-flaws",
|
|
40086
40188
|
name: "Code Security Flaws",
|
|
40087
|
-
version: "0.1.
|
|
40189
|
+
version: "0.1.1",
|
|
40088
40190
|
rawRules: [
|
|
40089
40191
|
sql_inject_concat_default,
|
|
40090
40192
|
sql_inject_concat_dot_default,
|
|
@@ -40134,7 +40236,7 @@ var BUNDLED_PACKS = [
|
|
|
40134
40236
|
{
|
|
40135
40237
|
packId: "core-code-context",
|
|
40136
40238
|
name: "Code Context",
|
|
40137
|
-
version: "0.2.
|
|
40239
|
+
version: "0.2.2",
|
|
40138
40240
|
rawRules: [
|
|
40139
40241
|
internal_ip_default,
|
|
40140
40242
|
localhost_ref_default,
|
|
@@ -40271,6 +40373,11 @@ function bundledDetections() {
|
|
|
40271
40373
|
}));
|
|
40272
40374
|
return cachedDetections;
|
|
40273
40375
|
}
|
|
40376
|
+
function shippedRegexMatchers() {
|
|
40377
|
+
return bundledDetections().flatMap((pack) => pack.rules).flatMap(
|
|
40378
|
+
(rule) => rule.matcher.type === "regex" ? [{ pattern: rule.matcher.pattern, flags: rule.matcher.flags }] : []
|
|
40379
|
+
);
|
|
40380
|
+
}
|
|
40274
40381
|
|
|
40275
40382
|
// ../../packages/plugin-sdk/src/mask.ts
|
|
40276
40383
|
var packsReady = false;
|
|
@@ -40346,8 +40453,9 @@ function resolveRepoIdentity(cwd) {
|
|
|
40346
40453
|
var ATTRIBUTION_MEMO_LIMIT = 64;
|
|
40347
40454
|
var attributionMemo = /* @__PURE__ */ new Map();
|
|
40348
40455
|
var NO_ATTRIBUTION = Object.freeze({});
|
|
40349
|
-
function resolveRepoAttribution(cwd) {
|
|
40456
|
+
function resolveRepoAttribution(cwd, options) {
|
|
40350
40457
|
try {
|
|
40458
|
+
if (options?.cache === false) return attributeRepo(cwd);
|
|
40351
40459
|
const remembered = attributionMemo.get(cwd);
|
|
40352
40460
|
if (remembered !== void 0) return remembered;
|
|
40353
40461
|
const attribution = attributeRepo(cwd);
|
|
@@ -40662,7 +40770,7 @@ function collectUserClaudeJson(scan2, path, cwd, repoIdentity) {
|
|
|
40662
40770
|
}
|
|
40663
40771
|
function projectEntryFor(projects, cwd) {
|
|
40664
40772
|
const candidates = /* @__PURE__ */ new Set([cwd]);
|
|
40665
|
-
const trimmed = cwd
|
|
40773
|
+
const trimmed = withoutTrailingSlashes2(cwd);
|
|
40666
40774
|
if (trimmed.length > 0) candidates.add(trimmed);
|
|
40667
40775
|
try {
|
|
40668
40776
|
candidates.add(realpathSync2(cwd));
|
|
@@ -40674,6 +40782,12 @@ function projectEntryFor(projects, cwd) {
|
|
|
40674
40782
|
}
|
|
40675
40783
|
return void 0;
|
|
40676
40784
|
}
|
|
40785
|
+
var SLASH2 = "/".charCodeAt(0);
|
|
40786
|
+
function withoutTrailingSlashes2(path) {
|
|
40787
|
+
let end = path.length;
|
|
40788
|
+
while (end > 0 && path.charCodeAt(end - 1) === SLASH2) end -= 1;
|
|
40789
|
+
return path.slice(0, end);
|
|
40790
|
+
}
|
|
40677
40791
|
function collectPluginManifestMcp(scan2, installPath, origin) {
|
|
40678
40792
|
const manifestPath = join19(installPath, ".claude-plugin", "plugin.json");
|
|
40679
40793
|
const raw = readOptional(manifestPath);
|
|
@@ -40823,10 +40937,10 @@ function parseFrontmatter(raw) {
|
|
|
40823
40937
|
if (lines[0]?.trim() !== "---") return out;
|
|
40824
40938
|
for (const line of lines.slice(1)) {
|
|
40825
40939
|
if (line.trim() === "---") break;
|
|
40826
|
-
const
|
|
40827
|
-
if (
|
|
40828
|
-
const key = line.slice(0,
|
|
40829
|
-
const value = line.slice(
|
|
40940
|
+
const sep3 = line.indexOf(":");
|
|
40941
|
+
if (sep3 === -1) continue;
|
|
40942
|
+
const key = line.slice(0, sep3).trim();
|
|
40943
|
+
const value = line.slice(sep3 + 1).trim().replace(/^['"]|['"]$/g, "");
|
|
40830
40944
|
if (value === "") continue;
|
|
40831
40945
|
if (key === "name") out.name = value;
|
|
40832
40946
|
else if (key === "description") out.description = value;
|
|
@@ -40985,12 +41099,416 @@ function offersMaintenance(gateway, member) {
|
|
|
40985
41099
|
}
|
|
40986
41100
|
|
|
40987
41101
|
// ../../packages/plugin-sdk/src/events.ts
|
|
40988
|
-
import { createHash as
|
|
41102
|
+
import { createHash as createHash6, randomUUID as randomUUID13 } from "crypto";
|
|
41103
|
+
function contentHashOf(text) {
|
|
41104
|
+
return createHash6("sha256").update(text).digest("hex");
|
|
41105
|
+
}
|
|
40989
41106
|
|
|
40990
41107
|
// ../../packages/plugin-sdk/src/isolated-scan.ts
|
|
40991
41108
|
import { existsSync as existsSync10 } from "fs";
|
|
40992
41109
|
import { fileURLToPath } from "url";
|
|
40993
41110
|
import { Worker } from "worker_threads";
|
|
41111
|
+
var ISOLATED_SCAN_BUDGET_MS = 2e3;
|
|
41112
|
+
var ISOLATED_PROBE_BUDGET_MS = 1e3;
|
|
41113
|
+
var ISOLATED_START_BUDGET_MS = 5e3;
|
|
41114
|
+
var ATTRIBUTION_MIN_RULE_MS = 500;
|
|
41115
|
+
var ATTRIBUTION_MIN_SHARE = 0.5;
|
|
41116
|
+
var resolvedWorkerUrl;
|
|
41117
|
+
function resolveWorkerUrl() {
|
|
41118
|
+
if (resolvedWorkerUrl !== void 0) return resolvedWorkerUrl ?? void 0;
|
|
41119
|
+
resolvedWorkerUrl = null;
|
|
41120
|
+
try {
|
|
41121
|
+
const built = new URL(
|
|
41122
|
+
/* webpackIgnore: true */
|
|
41123
|
+
"./scan-worker.js",
|
|
41124
|
+
import.meta.url
|
|
41125
|
+
);
|
|
41126
|
+
for (const candidate of [built, sourceTwin(built)]) {
|
|
41127
|
+
if (existsSync10(fileURLToPath(candidate))) {
|
|
41128
|
+
resolvedWorkerUrl = candidate;
|
|
41129
|
+
break;
|
|
41130
|
+
}
|
|
41131
|
+
}
|
|
41132
|
+
} catch {
|
|
41133
|
+
}
|
|
41134
|
+
return resolvedWorkerUrl ?? void 0;
|
|
41135
|
+
}
|
|
41136
|
+
function sourceTwin(url2) {
|
|
41137
|
+
const twin = new URL(url2);
|
|
41138
|
+
twin.pathname = twin.pathname.replace(/\.js$/, ".ts");
|
|
41139
|
+
return twin;
|
|
41140
|
+
}
|
|
41141
|
+
function messageOf(error62) {
|
|
41142
|
+
return error62 instanceof Error ? error62.message : String(error62);
|
|
41143
|
+
}
|
|
41144
|
+
function createIsolatedScanner(data, opts = {}) {
|
|
41145
|
+
const budgetMs = opts.budgetMs ?? ISOLATED_SCAN_BUDGET_MS;
|
|
41146
|
+
const probeBudgetMs = opts.probeBudgetMs ?? ISOLATED_PROBE_BUDGET_MS;
|
|
41147
|
+
const startBudgetMs = opts.startBudgetMs ?? ISOLATED_START_BUDGET_MS;
|
|
41148
|
+
const minAttributionMs = opts.minAttributionMs ?? ATTRIBUTION_MIN_RULE_MS;
|
|
41149
|
+
let worker;
|
|
41150
|
+
let readyWorker;
|
|
41151
|
+
let broken;
|
|
41152
|
+
let closed = false;
|
|
41153
|
+
let nextJobId = 1;
|
|
41154
|
+
let pending;
|
|
41155
|
+
const terminating = /* @__PURE__ */ new Set();
|
|
41156
|
+
let chain = Promise.resolve();
|
|
41157
|
+
function clearTimers(job) {
|
|
41158
|
+
if (job.startupTimer !== void 0) clearTimeout(job.startupTimer);
|
|
41159
|
+
if (job.timer !== void 0) clearTimeout(job.timer);
|
|
41160
|
+
}
|
|
41161
|
+
function take() {
|
|
41162
|
+
const job = pending;
|
|
41163
|
+
if (!job) return void 0;
|
|
41164
|
+
pending = void 0;
|
|
41165
|
+
clearTimers(job);
|
|
41166
|
+
worker?.unref();
|
|
41167
|
+
return job;
|
|
41168
|
+
}
|
|
41169
|
+
function failPending(outcome) {
|
|
41170
|
+
take()?.fail(outcome);
|
|
41171
|
+
}
|
|
41172
|
+
function kill(dead) {
|
|
41173
|
+
if (worker === dead) worker = void 0;
|
|
41174
|
+
if (readyWorker === dead) readyWorker = void 0;
|
|
41175
|
+
const done = dead.terminate().catch(() => void 0);
|
|
41176
|
+
terminating.add(done);
|
|
41177
|
+
void done.finally(() => terminating.delete(done));
|
|
41178
|
+
}
|
|
41179
|
+
function onDeadline(job) {
|
|
41180
|
+
if (pending !== job) return;
|
|
41181
|
+
const now = performance.now();
|
|
41182
|
+
const runningMs = now - job.progressAt;
|
|
41183
|
+
const elapsedMs = now - job.startedAt;
|
|
41184
|
+
const blamed = job.progressIndex >= 0 && runningMs >= minAttributionMs && runningMs >= elapsedMs * ATTRIBUTION_MIN_SHARE;
|
|
41185
|
+
const culpritIndex = blamed ? job.progressIndex : void 0;
|
|
41186
|
+
kill(job.worker);
|
|
41187
|
+
failPending({ status: "timeout", culpritIndex, elapsedMs });
|
|
41188
|
+
}
|
|
41189
|
+
function ensureWorker() {
|
|
41190
|
+
if (worker) return worker;
|
|
41191
|
+
const url2 = opts.workerUrl ?? resolveWorkerUrl();
|
|
41192
|
+
if (!url2) {
|
|
41193
|
+
return {
|
|
41194
|
+
error: "the scan worker script was not found next to this bundle"
|
|
41195
|
+
};
|
|
41196
|
+
}
|
|
41197
|
+
let started;
|
|
41198
|
+
try {
|
|
41199
|
+
started = new Worker(url2, { workerData: data });
|
|
41200
|
+
} catch (error62) {
|
|
41201
|
+
return { error: `could not start the scan worker: ${messageOf(error62)}` };
|
|
41202
|
+
}
|
|
41203
|
+
opts.onWorkerStart?.(started.threadId);
|
|
41204
|
+
started.on("message", (message2) => {
|
|
41205
|
+
if (worker !== started) return;
|
|
41206
|
+
if (message2.kind === "ready") {
|
|
41207
|
+
readyWorker = started;
|
|
41208
|
+
if (pending?.worker === started) beginDeadline(pending);
|
|
41209
|
+
return;
|
|
41210
|
+
}
|
|
41211
|
+
if (message2.kind === "progress") {
|
|
41212
|
+
if (pending?.worker === started) {
|
|
41213
|
+
pending.progressIndex = message2.index;
|
|
41214
|
+
pending.progressAt = performance.now();
|
|
41215
|
+
}
|
|
41216
|
+
return;
|
|
41217
|
+
}
|
|
41218
|
+
if (pending?.id !== message2.id) return;
|
|
41219
|
+
if (message2.kind === "failed") {
|
|
41220
|
+
failPending({
|
|
41221
|
+
status: "unavailable",
|
|
41222
|
+
reason: `the scan worker failed: ${message2.message}`
|
|
41223
|
+
});
|
|
41224
|
+
return;
|
|
41225
|
+
}
|
|
41226
|
+
const job = take();
|
|
41227
|
+
if (job && !job.reply(message2)) {
|
|
41228
|
+
job.fail({ status: "unavailable", reason: "the scan worker answered the wrong job" });
|
|
41229
|
+
}
|
|
41230
|
+
});
|
|
41231
|
+
started.on("error", (error62) => {
|
|
41232
|
+
if (worker !== started) return;
|
|
41233
|
+
broken = messageOf(error62);
|
|
41234
|
+
worker = void 0;
|
|
41235
|
+
if (readyWorker === started) readyWorker = void 0;
|
|
41236
|
+
failPending({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
|
|
41237
|
+
});
|
|
41238
|
+
started.on("exit", () => {
|
|
41239
|
+
if (worker !== started) return;
|
|
41240
|
+
broken ??= "the scan worker exited before answering";
|
|
41241
|
+
worker = void 0;
|
|
41242
|
+
if (readyWorker === started) readyWorker = void 0;
|
|
41243
|
+
failPending({ status: "unavailable", reason: "the scan worker exited before answering" });
|
|
41244
|
+
});
|
|
41245
|
+
started.unref();
|
|
41246
|
+
worker = started;
|
|
41247
|
+
return started;
|
|
41248
|
+
}
|
|
41249
|
+
function beginDeadline(job) {
|
|
41250
|
+
if (job.startupTimer !== void 0) {
|
|
41251
|
+
clearTimeout(job.startupTimer);
|
|
41252
|
+
job.startupTimer = void 0;
|
|
41253
|
+
}
|
|
41254
|
+
if (job.timer !== void 0) return;
|
|
41255
|
+
job.startedAt = performance.now();
|
|
41256
|
+
job.progressAt = job.startedAt;
|
|
41257
|
+
const budget = job.deadlineAt === void 0 ? job.budgetMs : Math.max(0, Math.min(job.budgetMs, job.deadlineAt - job.startedAt));
|
|
41258
|
+
job.timer = setTimeout(() => {
|
|
41259
|
+
onDeadline(job);
|
|
41260
|
+
}, budget);
|
|
41261
|
+
}
|
|
41262
|
+
function runOne(spec, fail) {
|
|
41263
|
+
if (closed) {
|
|
41264
|
+
fail({ status: "unavailable", reason: "the scan worker is closed" });
|
|
41265
|
+
return;
|
|
41266
|
+
}
|
|
41267
|
+
if (broken !== void 0) {
|
|
41268
|
+
fail({ status: "unavailable", reason: `the scan worker crashed: ${broken}` });
|
|
41269
|
+
return;
|
|
41270
|
+
}
|
|
41271
|
+
const now = performance.now();
|
|
41272
|
+
const deadlineAt = spec.deadlineAt;
|
|
41273
|
+
if (deadlineAt !== void 0 && deadlineAt <= now) {
|
|
41274
|
+
fail({ status: "timeout", culpritIndex: void 0, elapsedMs: 0 });
|
|
41275
|
+
return;
|
|
41276
|
+
}
|
|
41277
|
+
const started = ensureWorker();
|
|
41278
|
+
if (!(started instanceof Worker)) {
|
|
41279
|
+
broken = started.error;
|
|
41280
|
+
fail({ status: "unavailable", reason: started.error });
|
|
41281
|
+
return;
|
|
41282
|
+
}
|
|
41283
|
+
const id = nextJobId++;
|
|
41284
|
+
const job = {
|
|
41285
|
+
id,
|
|
41286
|
+
worker: started,
|
|
41287
|
+
budgetMs: spec.budgetMs,
|
|
41288
|
+
deadlineAt,
|
|
41289
|
+
startedAt: now,
|
|
41290
|
+
progressIndex: -1,
|
|
41291
|
+
progressAt: now,
|
|
41292
|
+
startupTimer: void 0,
|
|
41293
|
+
timer: void 0,
|
|
41294
|
+
reply: spec.reply,
|
|
41295
|
+
fail
|
|
41296
|
+
};
|
|
41297
|
+
pending = job;
|
|
41298
|
+
started.ref();
|
|
41299
|
+
if (readyWorker === started) {
|
|
41300
|
+
beginDeadline(job);
|
|
41301
|
+
} else {
|
|
41302
|
+
const startBudget = spec.startBudgetMs ?? startBudgetMs;
|
|
41303
|
+
const callerLimited = deadlineAt !== void 0 && deadlineAt - now < startBudget;
|
|
41304
|
+
const startWaitMs = callerLimited ? deadlineAt - now : startBudget;
|
|
41305
|
+
job.startupTimer = setTimeout(() => {
|
|
41306
|
+
if (pending !== job) return;
|
|
41307
|
+
kill(job.worker);
|
|
41308
|
+
failPending(
|
|
41309
|
+
callerLimited ? { status: "timeout", culpritIndex: void 0, elapsedMs: performance.now() - now } : {
|
|
41310
|
+
status: "unavailable",
|
|
41311
|
+
reason: `the scan worker did not start within ${String(startBudget)}ms`
|
|
41312
|
+
}
|
|
41313
|
+
);
|
|
41314
|
+
}, startWaitMs);
|
|
41315
|
+
}
|
|
41316
|
+
try {
|
|
41317
|
+
started.postMessage(spec.build(id));
|
|
41318
|
+
} catch (error62) {
|
|
41319
|
+
failPending({
|
|
41320
|
+
// The thread went away between the ref and the post.
|
|
41321
|
+
status: "unavailable",
|
|
41322
|
+
reason: `could not reach the scan worker: ${messageOf(error62)}`
|
|
41323
|
+
});
|
|
41324
|
+
}
|
|
41325
|
+
}
|
|
41326
|
+
function enqueue(spec) {
|
|
41327
|
+
const next = chain.then(
|
|
41328
|
+
() => new Promise((resolve3) => {
|
|
41329
|
+
spec(resolve3);
|
|
41330
|
+
})
|
|
41331
|
+
);
|
|
41332
|
+
chain = next.then(
|
|
41333
|
+
() => void 0,
|
|
41334
|
+
() => void 0
|
|
41335
|
+
);
|
|
41336
|
+
return next;
|
|
41337
|
+
}
|
|
41338
|
+
return {
|
|
41339
|
+
scan(text, context, scanOpts) {
|
|
41340
|
+
return enqueue((resolve3) => {
|
|
41341
|
+
runOne(
|
|
41342
|
+
{
|
|
41343
|
+
budgetMs: scanOpts?.budgetMs ?? budgetMs,
|
|
41344
|
+
startBudgetMs: scanOpts?.startBudgetMs,
|
|
41345
|
+
deadlineAt: scanOpts?.deadlineAt,
|
|
41346
|
+
build: (id) => ({
|
|
41347
|
+
kind: "scan",
|
|
41348
|
+
id,
|
|
41349
|
+
text,
|
|
41350
|
+
filePath: context?.filePath,
|
|
41351
|
+
eventKind: context?.eventKind,
|
|
41352
|
+
attribute: scanOpts?.attribute === true
|
|
41353
|
+
}),
|
|
41354
|
+
reply: (message2) => {
|
|
41355
|
+
if (message2.kind !== "result") return false;
|
|
41356
|
+
resolve3({ status: "ok", findings: message2.findings });
|
|
41357
|
+
return true;
|
|
41358
|
+
}
|
|
41359
|
+
},
|
|
41360
|
+
resolve3
|
|
41361
|
+
);
|
|
41362
|
+
});
|
|
41363
|
+
},
|
|
41364
|
+
probe(rule) {
|
|
41365
|
+
return enqueue((resolve3) => {
|
|
41366
|
+
runOne(
|
|
41367
|
+
{
|
|
41368
|
+
budgetMs: probeBudgetMs,
|
|
41369
|
+
build: (id) => ({ kind: "probe", id, rule }),
|
|
41370
|
+
reply: (message2) => {
|
|
41371
|
+
if (message2.kind !== "probed") return false;
|
|
41372
|
+
resolve3({
|
|
41373
|
+
status: "ok",
|
|
41374
|
+
verdict: message2.verdict,
|
|
41375
|
+
worstMs: message2.worstMs,
|
|
41376
|
+
corroboratedMs: message2.corroboratedMs
|
|
41377
|
+
});
|
|
41378
|
+
return true;
|
|
41379
|
+
}
|
|
41380
|
+
},
|
|
41381
|
+
resolve3
|
|
41382
|
+
);
|
|
41383
|
+
});
|
|
41384
|
+
},
|
|
41385
|
+
async close() {
|
|
41386
|
+
closed = true;
|
|
41387
|
+
const live = worker;
|
|
41388
|
+
worker = void 0;
|
|
41389
|
+
readyWorker = void 0;
|
|
41390
|
+
failPending({ status: "unavailable", reason: "the scan worker is closed" });
|
|
41391
|
+
if (live) kill(live);
|
|
41392
|
+
await Promise.all([...terminating]);
|
|
41393
|
+
}
|
|
41394
|
+
};
|
|
41395
|
+
}
|
|
41396
|
+
|
|
41397
|
+
// ../../packages/plugin-sdk/src/work-clock.ts
|
|
41398
|
+
function workClockMs() {
|
|
41399
|
+
const usage = typeof process.threadCpuUsage === "function" ? process.threadCpuUsage() : process.cpuUsage();
|
|
41400
|
+
return (usage.user + usage.system) / 1e3;
|
|
41401
|
+
}
|
|
41402
|
+
|
|
41403
|
+
// ../../packages/plugin-sdk/src/rule-quarantine.ts
|
|
41404
|
+
var PASS_BUDGET_MS = 2e3;
|
|
41405
|
+
var UNQUARANTINE_HINT = "clear it with `aka detections unquarantine`";
|
|
41406
|
+
function ruleProbeKey(rule) {
|
|
41407
|
+
if (rule.matcher.type !== "regex") return void 0;
|
|
41408
|
+
return contentHashOf(`${rule.matcher.pattern} ${rule.matcher.flags}`);
|
|
41409
|
+
}
|
|
41410
|
+
function warn(rule, verb, detail, recoverable) {
|
|
41411
|
+
const hint = recoverable ? ` (${UNQUARANTINE_HINT})` : "";
|
|
41412
|
+
process.stderr.write(`[aka] ${verb} rule "${rule.id}": ${detail}${hint}
|
|
41413
|
+
`);
|
|
41414
|
+
}
|
|
41415
|
+
function warnQuarantined(rule, worstMs, cached2) {
|
|
41416
|
+
warn(
|
|
41417
|
+
rule,
|
|
41418
|
+
"quarantined",
|
|
41419
|
+
Number.isFinite(worstMs) ? `regex matcher exceeded the ReDoS timing budget (${worstMs.toFixed(1)}ms); excluded from this scan.` : "the timing battery failed while measuring its regex matcher; excluded from this scan.",
|
|
41420
|
+
cached2
|
|
41421
|
+
);
|
|
41422
|
+
}
|
|
41423
|
+
function warnUnmeasured(rule) {
|
|
41424
|
+
warn(
|
|
41425
|
+
rule,
|
|
41426
|
+
"skipped",
|
|
41427
|
+
"the timing pre-flight ran out of time before this rule could be measured; excluded for the rest of this run, and measured again next time.",
|
|
41428
|
+
false
|
|
41429
|
+
);
|
|
41430
|
+
}
|
|
41431
|
+
function warnUncorroborated(rule, worstMs, corroboratedMs) {
|
|
41432
|
+
warn(
|
|
41433
|
+
rule,
|
|
41434
|
+
"deferred",
|
|
41435
|
+
`its regex matcher ran past the ReDoS timing budget (${worstMs.toFixed(1)}ms) but spent only ${corroboratedMs.toFixed(1)}ms of CPU doing it, which is a busy machine rather than a slow pattern; excluded from this run and measured again next time, with nothing recorded against it.`,
|
|
41436
|
+
false
|
|
41437
|
+
);
|
|
41438
|
+
}
|
|
41439
|
+
function warnUnmeasurable(reason, count) {
|
|
41440
|
+
process.stderr.write(
|
|
41441
|
+
`[aka] ${String(count)} pulled/custom-pack rule(s) could not be time-checked: ${reason}. That is a problem with this install, not with the rules \u2014 until it is fixed they are excluded from every scan on this machine. Nothing was quarantined, so reinstalling AKA brings them straight back.
|
|
41442
|
+
`
|
|
41443
|
+
);
|
|
41444
|
+
}
|
|
41445
|
+
async function filterUnsafeRules(rules, gateway, opts) {
|
|
41446
|
+
const passBudgetMs = opts?.passBudgetMs ?? PASS_BUDGET_MS;
|
|
41447
|
+
const prober = opts?.prober;
|
|
41448
|
+
const passStart = performance.now();
|
|
41449
|
+
const safe = [];
|
|
41450
|
+
const unmeasurable = /* @__PURE__ */ new Map();
|
|
41451
|
+
try {
|
|
41452
|
+
for (const rule of rules) {
|
|
41453
|
+
const key = ruleProbeKey(rule);
|
|
41454
|
+
if (key === void 0) {
|
|
41455
|
+
safe.push(rule);
|
|
41456
|
+
continue;
|
|
41457
|
+
}
|
|
41458
|
+
let cached2;
|
|
41459
|
+
try {
|
|
41460
|
+
cached2 = await gateway.getRuleProbeVerdict(key);
|
|
41461
|
+
} catch {
|
|
41462
|
+
cached2 = void 0;
|
|
41463
|
+
}
|
|
41464
|
+
if (cached2) {
|
|
41465
|
+
if (cached2.verdict === "safe") safe.push(rule);
|
|
41466
|
+
else warnQuarantined(rule, cached2.worstProbeMs, true);
|
|
41467
|
+
continue;
|
|
41468
|
+
}
|
|
41469
|
+
if (performance.now() - passStart >= passBudgetMs) {
|
|
41470
|
+
warnUnmeasured(rule);
|
|
41471
|
+
continue;
|
|
41472
|
+
}
|
|
41473
|
+
let verdict;
|
|
41474
|
+
let worstMs;
|
|
41475
|
+
let corroboratedMs = 0;
|
|
41476
|
+
if (prober) {
|
|
41477
|
+
const outcome = await prober.probe(rule);
|
|
41478
|
+
if (outcome.status === "unavailable") {
|
|
41479
|
+
unmeasurable.set(outcome.reason, (unmeasurable.get(outcome.reason) ?? 0) + 1);
|
|
41480
|
+
continue;
|
|
41481
|
+
}
|
|
41482
|
+
verdict = outcome.status === "ok" ? outcome.verdict : "over-budget";
|
|
41483
|
+
worstMs = outcome.status === "ok" ? outcome.worstMs : outcome.elapsedMs;
|
|
41484
|
+
if (outcome.status === "ok") corroboratedMs = outcome.corroboratedMs;
|
|
41485
|
+
} else {
|
|
41486
|
+
try {
|
|
41487
|
+
({ verdict, worstMs, corroboratedMs } = checkRuleTiming(rule, workClockMs));
|
|
41488
|
+
} catch {
|
|
41489
|
+
verdict = "over-budget";
|
|
41490
|
+
worstMs = Number.POSITIVE_INFINITY;
|
|
41491
|
+
}
|
|
41492
|
+
}
|
|
41493
|
+
if (verdict === "uncorroborated") {
|
|
41494
|
+
warnUncorroborated(rule, worstMs, corroboratedMs);
|
|
41495
|
+
continue;
|
|
41496
|
+
}
|
|
41497
|
+
const isSafe = verdict === "safe";
|
|
41498
|
+
let persisted = false;
|
|
41499
|
+
try {
|
|
41500
|
+
await gateway.setRuleProbeVerdict(key, isSafe ? "safe" : "quarantined", worstMs);
|
|
41501
|
+
persisted = true;
|
|
41502
|
+
} catch {
|
|
41503
|
+
}
|
|
41504
|
+
if (isSafe) safe.push(rule);
|
|
41505
|
+
else warnQuarantined(rule, worstMs, persisted);
|
|
41506
|
+
}
|
|
41507
|
+
} finally {
|
|
41508
|
+
for (const [reason, count] of unmeasurable) warnUnmeasurable(reason, count);
|
|
41509
|
+
}
|
|
41510
|
+
return safe;
|
|
41511
|
+
}
|
|
40994
41512
|
|
|
40995
41513
|
// ../../packages/plugin-sdk/src/hook-fail-opens.ts
|
|
40996
41514
|
import { readFileSync as readFileSync13 } from "fs";
|
|
@@ -41030,58 +41548,13 @@ function isPositiveSafeInteger(value) {
|
|
|
41030
41548
|
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
41031
41549
|
}
|
|
41032
41550
|
|
|
41033
|
-
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
41034
|
-
import { readFileSync as readFileSync15 } from "fs";
|
|
41035
|
-
import { join as join22 } from "path";
|
|
41036
|
-
|
|
41037
|
-
// ../../packages/plugin-sdk/src/model-governance.ts
|
|
41038
|
-
import {
|
|
41039
|
-
closeSync as closeSync2,
|
|
41040
|
-
fstatSync,
|
|
41041
|
-
mkdirSync as mkdirSync2,
|
|
41042
|
-
openSync as openSync2,
|
|
41043
|
-
readFileSync as readFileSync14,
|
|
41044
|
-
readSync,
|
|
41045
|
-
writeFileSync as writeFileSync5
|
|
41046
|
-
} from "fs";
|
|
41047
|
-
import { join as join21 } from "path";
|
|
41048
|
-
var TAIL_BYTES = 256 * 1024;
|
|
41049
|
-
|
|
41050
|
-
// ../../packages/plugin-sdk/src/host-floor.ts
|
|
41051
|
-
var HOST_FEATURE = {
|
|
41052
|
-
ModelSwitch: "model-switch",
|
|
41053
|
-
VaultPointerDisplay: "vault-pointer-display"
|
|
41054
|
-
};
|
|
41055
|
-
var HOST_FLOORS = {
|
|
41056
|
-
[HOST_FEATURE.ModelSwitch]: {
|
|
41057
|
-
label: "model-switch protection",
|
|
41058
|
-
hookEvents: ["PreModelSwitch", "PostModelSwitch"],
|
|
41059
|
-
since: "2.1.251"
|
|
41060
|
-
},
|
|
41061
|
-
[HOST_FEATURE.VaultPointerDisplay]: {
|
|
41062
|
-
label: "vault pointer display",
|
|
41063
|
-
hookEvents: ["MessageDisplay"],
|
|
41064
|
-
since: "2.1.152"
|
|
41065
|
-
}
|
|
41066
|
-
};
|
|
41067
|
-
var ANTIGRAVITY_HOST_FEATURE = {
|
|
41068
|
-
EndOfTurnCapture: "end-of-turn-capture"
|
|
41069
|
-
};
|
|
41070
|
-
var ANTIGRAVITY_HOST_FLOORS = {
|
|
41071
|
-
[ANTIGRAVITY_HOST_FEATURE.EndOfTurnCapture]: {
|
|
41072
|
-
label: "end-of-turn history capture",
|
|
41073
|
-
hookEvents: ["Stop"],
|
|
41074
|
-
since: "1.1.10"
|
|
41075
|
-
}
|
|
41076
|
-
};
|
|
41077
|
-
|
|
41078
41551
|
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
41079
41552
|
var import_ignore = __toESM(require_ignore(), 1);
|
|
41080
|
-
import { readFileSync as
|
|
41081
|
-
import { join as
|
|
41553
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
41554
|
+
import { join as join21 } from "path";
|
|
41082
41555
|
function readIgnoreLayer(dir, filename, anchorLen) {
|
|
41083
41556
|
try {
|
|
41084
|
-
return { matcher: (0, import_ignore.default)().add(
|
|
41557
|
+
return { matcher: (0, import_ignore.default)().add(readFileSync14(join21(dir, filename), "utf8")), anchorLen };
|
|
41085
41558
|
} catch {
|
|
41086
41559
|
return void 0;
|
|
41087
41560
|
}
|
|
@@ -41138,31 +41611,27 @@ function resolveInventoryContext(input2) {
|
|
|
41138
41611
|
}
|
|
41139
41612
|
|
|
41140
41613
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
41141
|
-
import { mkdirSync as
|
|
41142
|
-
import { join as
|
|
41614
|
+
import { mkdirSync as mkdirSync2, readFileSync as readFileSync15, writeFileSync as writeFileSync5 } from "fs";
|
|
41615
|
+
import { join as join22 } from "path";
|
|
41143
41616
|
var SESSION_START_MARKER = "session-start-last";
|
|
41144
41617
|
function claimSessionStart(dataDir2, sessionId) {
|
|
41145
41618
|
return claimOncePerSession(dataDir2, SESSION_START_MARKER, sessionId);
|
|
41146
41619
|
}
|
|
41147
41620
|
function claimOncePerSession(dataDir2, marker, sessionId) {
|
|
41148
41621
|
if (!sessionId) return true;
|
|
41149
|
-
const path =
|
|
41622
|
+
const path = join22(dataDir2, marker);
|
|
41150
41623
|
try {
|
|
41151
|
-
if (
|
|
41624
|
+
if (readFileSync15(path, "utf8") === sessionId) return false;
|
|
41152
41625
|
} catch {
|
|
41153
41626
|
}
|
|
41154
41627
|
try {
|
|
41155
|
-
|
|
41156
|
-
|
|
41628
|
+
mkdirSync2(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
|
|
41629
|
+
writeFileSync5(path, sessionId, { mode: DATA_FILE_MODE });
|
|
41157
41630
|
} catch {
|
|
41158
41631
|
}
|
|
41159
41632
|
return true;
|
|
41160
41633
|
}
|
|
41161
41634
|
|
|
41162
|
-
// ../../packages/plugin-sdk/src/paths.ts
|
|
41163
|
-
import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
|
|
41164
|
-
import { basename as basename5, dirname as dirname5, sep as sep3 } from "path";
|
|
41165
|
-
|
|
41166
41635
|
// ../../packages/plugin-sdk/src/policy-resolver.ts
|
|
41167
41636
|
import { randomUUID as randomUUID14 } from "crypto";
|
|
41168
41637
|
function assignedRulePolicies(installed) {
|
|
@@ -41175,8 +41644,8 @@ function assignedRulePolicies(installed) {
|
|
|
41175
41644
|
}
|
|
41176
41645
|
|
|
41177
41646
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
41178
|
-
import { existsSync as existsSync11, readdirSync as
|
|
41179
|
-
import { basename as
|
|
41647
|
+
import { existsSync as existsSync11, readdirSync as readdirSync3 } from "fs";
|
|
41648
|
+
import { basename as basename5, join as join23 } from "path";
|
|
41180
41649
|
var SKIP_DIRS = /* @__PURE__ */ new Set([
|
|
41181
41650
|
".git",
|
|
41182
41651
|
"node_modules",
|
|
@@ -41255,7 +41724,7 @@ function resolveProjectFiles(cwd, opts = {}) {
|
|
|
41255
41724
|
let visit3 = function(dir, dirRel, layers, depth) {
|
|
41256
41725
|
let dirents;
|
|
41257
41726
|
try {
|
|
41258
|
-
dirents =
|
|
41727
|
+
dirents = readdirSync3(dir, { withFileTypes: true, encoding: "utf8" });
|
|
41259
41728
|
} catch {
|
|
41260
41729
|
walk.lostSubtree = true;
|
|
41261
41730
|
return false;
|
|
@@ -41273,8 +41742,8 @@ function resolveProjectFiles(cwd, opts = {}) {
|
|
|
41273
41742
|
}
|
|
41274
41743
|
if (entry.isDirectory()) {
|
|
41275
41744
|
if (SKIP_DIRS.has(entry.name) || isIgnored(dirLayers, dirRel, entry.name, true)) continue;
|
|
41276
|
-
const fullPath =
|
|
41277
|
-
if (existsSync11(
|
|
41745
|
+
const fullPath = join23(dir, entry.name);
|
|
41746
|
+
if (existsSync11(join23(fullPath, ".git"))) continue;
|
|
41278
41747
|
if (depth >= bounds.maxDepth) {
|
|
41279
41748
|
walk.omitted = true;
|
|
41280
41749
|
continue;
|
|
@@ -41289,7 +41758,7 @@ function resolveProjectFiles(cwd, opts = {}) {
|
|
|
41289
41758
|
const relPath = childRel(dirRel, entry.name);
|
|
41290
41759
|
files.push({
|
|
41291
41760
|
path: relPath,
|
|
41292
|
-
name:
|
|
41761
|
+
name: basename5(entry.name),
|
|
41293
41762
|
origin: classifyOrigin(relPath, entry.name),
|
|
41294
41763
|
defaultAccess: "approved"
|
|
41295
41764
|
});
|
|
@@ -41313,30 +41782,14 @@ function resolveProjectFiles(cwd, opts = {}) {
|
|
|
41313
41782
|
}
|
|
41314
41783
|
}
|
|
41315
41784
|
|
|
41316
|
-
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
41317
|
-
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
41318
|
-
if (typeof v === "string" && v.trim() === "") return void 0;
|
|
41319
|
-
return v;
|
|
41320
|
-
}, external_exports.string().optional()).catch(void 0);
|
|
41321
|
-
var optionalFlag = external_exports.preprocess((v) => {
|
|
41322
|
-
if (typeof v !== "string") return false;
|
|
41323
|
-
const normalized = v.trim().toLowerCase();
|
|
41324
|
-
return normalized !== "" && normalized !== "0" && normalized !== "false";
|
|
41325
|
-
}, external_exports.boolean()).catch(false);
|
|
41326
|
-
var antigravityProviderEnvShape = {
|
|
41327
|
-
GOOGLE_GENAI_USE_VERTEXAI: optionalFlag,
|
|
41328
|
-
GOOGLE_GEMINI_BASE_URL: optionalBaseUrl2
|
|
41329
|
-
};
|
|
41330
|
-
var AntigravityProviderEnvSchema = external_exports.object(antigravityProviderEnvShape);
|
|
41331
|
-
|
|
41332
41785
|
// ../../packages/plugin-sdk/src/provider-env-codex.ts
|
|
41333
41786
|
var DEFAULT_OPENAI_HOST = "api.openai.com";
|
|
41334
|
-
var
|
|
41787
|
+
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
41335
41788
|
if (typeof v === "string" && v.trim() === "") return void 0;
|
|
41336
41789
|
return v;
|
|
41337
41790
|
}, external_exports.string().optional()).catch(void 0);
|
|
41338
41791
|
var codexProviderEnvShape = {
|
|
41339
|
-
OPENAI_BASE_URL:
|
|
41792
|
+
OPENAI_BASE_URL: optionalBaseUrl2
|
|
41340
41793
|
};
|
|
41341
41794
|
var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
|
|
41342
41795
|
|
|
@@ -41367,37 +41820,448 @@ function resolveCodexProvider() {
|
|
|
41367
41820
|
return { provider: "openai" };
|
|
41368
41821
|
}
|
|
41369
41822
|
|
|
41370
|
-
// ../../packages/plugin-sdk/src/runtime.ts
|
|
41371
|
-
import { randomUUID as randomUUID15 } from "crypto";
|
|
41372
|
-
|
|
41373
41823
|
// ../../packages/plugin-sdk/src/scope-key.ts
|
|
41374
41824
|
import { existsSync as existsSync12 } from "fs";
|
|
41375
|
-
import { dirname as
|
|
41825
|
+
import { dirname as dirname5, isAbsolute as isAbsolute2, join as join24, normalize } from "path";
|
|
41376
41826
|
function sessionRootScopeKey(cwd) {
|
|
41377
41827
|
return cwd === void 0 ? void 0 : resolveRepoAttribution(cwd).scopeKey;
|
|
41378
41828
|
}
|
|
41379
41829
|
|
|
41380
|
-
// ../../packages/plugin-sdk/src/suppressions.ts
|
|
41381
|
-
var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
41382
|
-
|
|
41383
41830
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
41384
|
-
import { mkdirSync as
|
|
41385
|
-
import { join as
|
|
41831
|
+
import { mkdirSync as mkdirSync3, statSync as statSync8, writeFileSync as writeFileSync6 } from "fs";
|
|
41832
|
+
import { join as join25 } from "path";
|
|
41386
41833
|
function throttled(dataDir2, markerName, windowMs) {
|
|
41387
|
-
const marker =
|
|
41834
|
+
const marker = join25(dataDir2, markerName);
|
|
41388
41835
|
try {
|
|
41389
41836
|
if (Date.now() - statSync8(marker).mtimeMs < windowMs) return true;
|
|
41390
41837
|
} catch {
|
|
41391
41838
|
}
|
|
41392
41839
|
try {
|
|
41393
|
-
|
|
41394
|
-
|
|
41840
|
+
mkdirSync3(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
|
|
41841
|
+
writeFileSync6(marker, String(Date.now()), { mode: DATA_FILE_MODE });
|
|
41395
41842
|
} catch {
|
|
41396
41843
|
}
|
|
41397
41844
|
return false;
|
|
41398
41845
|
}
|
|
41399
41846
|
|
|
41847
|
+
// ../../packages/remote/src/http.ts
|
|
41848
|
+
import { request as httpRequest } from "http";
|
|
41849
|
+
import { request as httpsRequest } from "https";
|
|
41850
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
41851
|
+
var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
41852
|
+
var RemoteRequestError = class extends Error {
|
|
41853
|
+
constructor(status) {
|
|
41854
|
+
super(`control-plane request failed with status ${String(status)}`);
|
|
41855
|
+
this.status = status;
|
|
41856
|
+
this.name = "RemoteRequestError";
|
|
41857
|
+
}
|
|
41858
|
+
status;
|
|
41859
|
+
};
|
|
41860
|
+
var RemoteRouteAbsent = class extends Error {
|
|
41861
|
+
constructor(route) {
|
|
41862
|
+
super(`control plane does not serve ${route}`);
|
|
41863
|
+
this.route = route;
|
|
41864
|
+
this.name = "RemoteRouteAbsent";
|
|
41865
|
+
}
|
|
41866
|
+
route;
|
|
41867
|
+
};
|
|
41868
|
+
var RemoteRequestInvalid = class extends Error {
|
|
41869
|
+
constructor(route, cause) {
|
|
41870
|
+
super(`refusing to send a malformed body to ${route}`);
|
|
41871
|
+
this.cause = cause;
|
|
41872
|
+
this.name = "RemoteRequestInvalid";
|
|
41873
|
+
}
|
|
41874
|
+
cause;
|
|
41875
|
+
};
|
|
41876
|
+
var RemoteEndpointRefused = class extends Error {
|
|
41877
|
+
constructor(endpoint) {
|
|
41878
|
+
super(`refusing to talk to an unsafe control-plane endpoint: ${originOnly(endpoint)}`);
|
|
41879
|
+
this.name = "RemoteEndpointRefused";
|
|
41880
|
+
}
|
|
41881
|
+
};
|
|
41882
|
+
var RemoteResponseInvalid = class extends Error {
|
|
41883
|
+
constructor(route, detail) {
|
|
41884
|
+
super(`control plane answered ${route} with ${detail}`);
|
|
41885
|
+
this.name = "RemoteResponseInvalid";
|
|
41886
|
+
}
|
|
41887
|
+
};
|
|
41888
|
+
var RemoteTransportError = class extends Error {
|
|
41889
|
+
/**
|
|
41890
|
+
* The status the peer sent, when headers arrived and only the BODY was
|
|
41891
|
+
* refused.
|
|
41892
|
+
*
|
|
41893
|
+
* Undefined for the ordinary case this class was written for — no answer at
|
|
41894
|
+
* all. It exists because two paths reject after a status has already been
|
|
41895
|
+
* delivered: an oversized body and an aborted response. Discarding it there
|
|
41896
|
+
* reported a deployment answering 401 with a verbose body as a network
|
|
41897
|
+
* outage, which sends the reader to look at their network instead of their
|
|
41898
|
+
* credential.
|
|
41899
|
+
*/
|
|
41900
|
+
constructor(reason, status) {
|
|
41901
|
+
super(`control-plane request did not complete: ${reason}`);
|
|
41902
|
+
this.status = status;
|
|
41903
|
+
this.name = "RemoteTransportError";
|
|
41904
|
+
}
|
|
41905
|
+
status;
|
|
41906
|
+
};
|
|
41907
|
+
async function send(options) {
|
|
41908
|
+
const url2 = new URL(options.url);
|
|
41909
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
41910
|
+
const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
|
|
41911
|
+
const requestOptions = {
|
|
41912
|
+
method: options.method,
|
|
41913
|
+
headers: {
|
|
41914
|
+
// CALLER HEADERS FIRST, so this module's own are not overridable. Spread
|
|
41915
|
+
// last they win, and two of the values below are ones no caller may
|
|
41916
|
+
// replace: `x-api-key` is the credential, and `content-length` is the
|
|
41917
|
+
// byte count that stops a multi-byte body being truncated by the
|
|
41918
|
+
// receiver. `SendOptions.headers` is a free-form record on an exported
|
|
41919
|
+
// function, so "no caller does that today" is not the guarantee to rely
|
|
41920
|
+
// on. The one header any caller actually passes — `if-none-match` on the
|
|
41921
|
+
// conditional GET — is untouched by this order.
|
|
41922
|
+
...options.headers,
|
|
41923
|
+
// The credential. One header, matching what the deployment authenticates
|
|
41924
|
+
// on; a second copy in an `Authorization` header would be one more place
|
|
41925
|
+
// it can be logged by an intermediary for no gain.
|
|
41926
|
+
//
|
|
41927
|
+
// Spread conditionally rather than assigned as `undefined`: Node's header
|
|
41928
|
+
// handling and `content-length` bookkeeping treat a present-but-undefined
|
|
41929
|
+
// key differently from an absent one, and "the header is not there" is
|
|
41930
|
+
// the property the attach flow needs.
|
|
41931
|
+
...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
|
|
41932
|
+
accept: "application/json",
|
|
41933
|
+
...options.body === void 0 ? {} : {
|
|
41934
|
+
"content-type": "application/json",
|
|
41935
|
+
// Byte length, not string length: a multi-byte body sent with a
|
|
41936
|
+
// character count is truncated by the receiver.
|
|
41937
|
+
"content-length": String(Buffer.byteLength(options.body))
|
|
41938
|
+
}
|
|
41939
|
+
}
|
|
41940
|
+
};
|
|
41941
|
+
return new Promise((resolve3, reject) => {
|
|
41942
|
+
let settled = false;
|
|
41943
|
+
const fail = (reason, status) => {
|
|
41944
|
+
if (settled) return;
|
|
41945
|
+
settled = true;
|
|
41946
|
+
reject(new RemoteTransportError(reason, status));
|
|
41947
|
+
};
|
|
41948
|
+
const req = send_(url2, requestOptions, (res) => {
|
|
41949
|
+
const chunks = [];
|
|
41950
|
+
let size = 0;
|
|
41951
|
+
res.on("data", (chunk) => {
|
|
41952
|
+
size += chunk.length;
|
|
41953
|
+
if (size > MAX_RESPONSE_BYTES) {
|
|
41954
|
+
fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
|
|
41955
|
+
res.destroy();
|
|
41956
|
+
req.destroy();
|
|
41957
|
+
return;
|
|
41958
|
+
}
|
|
41959
|
+
chunks.push(chunk);
|
|
41960
|
+
});
|
|
41961
|
+
res.on("aborted", () => {
|
|
41962
|
+
fail("the response was aborted", res.statusCode);
|
|
41963
|
+
});
|
|
41964
|
+
res.on("end", () => {
|
|
41965
|
+
if (settled) return;
|
|
41966
|
+
settled = true;
|
|
41967
|
+
resolve3({
|
|
41968
|
+
status: res.statusCode ?? 0,
|
|
41969
|
+
headers: res.headers,
|
|
41970
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
41971
|
+
});
|
|
41972
|
+
});
|
|
41973
|
+
});
|
|
41974
|
+
const deadline = setTimeout(() => {
|
|
41975
|
+
fail(`no response within ${String(timeoutMs)}ms`);
|
|
41976
|
+
req.destroy();
|
|
41977
|
+
}, timeoutMs);
|
|
41978
|
+
deadline.unref();
|
|
41979
|
+
req.on("upgrade", (_res, socket) => {
|
|
41980
|
+
fail("the deployment answered with a protocol upgrade");
|
|
41981
|
+
socket.destroy();
|
|
41982
|
+
});
|
|
41983
|
+
req.on("close", () => {
|
|
41984
|
+
fail("the connection closed before a response was read");
|
|
41985
|
+
clearTimeout(deadline);
|
|
41986
|
+
});
|
|
41987
|
+
req.on("error", (err) => {
|
|
41988
|
+
fail(err.message);
|
|
41989
|
+
});
|
|
41990
|
+
if (options.body !== void 0) req.write(options.body);
|
|
41991
|
+
req.end();
|
|
41992
|
+
});
|
|
41993
|
+
}
|
|
41994
|
+
|
|
41995
|
+
// ../../packages/remote/src/client.ts
|
|
41996
|
+
var ROUTES = {
|
|
41997
|
+
events: "/v1/events",
|
|
41998
|
+
auditEvents: "/v1/audit-events",
|
|
41999
|
+
auditEventsBatch: "/v1/audit-events/batch",
|
|
42000
|
+
inventory: "/v1/inventory",
|
|
42001
|
+
storePosture: "/v1/store-posture",
|
|
42002
|
+
policyBundle: "/v1/policy-bundle",
|
|
42003
|
+
whoami: "/v1/plugin/whoami",
|
|
42004
|
+
shares: "/v1/shares",
|
|
42005
|
+
commands: "/v1/plugin/commands"
|
|
42006
|
+
};
|
|
42007
|
+
function ackRoute(id) {
|
|
42008
|
+
return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
|
|
42009
|
+
}
|
|
42010
|
+
function headerValue(response, name) {
|
|
42011
|
+
const raw = response.headers[name];
|
|
42012
|
+
if (raw === void 0) return void 0;
|
|
42013
|
+
return Array.isArray(raw) ? raw[0] : raw;
|
|
42014
|
+
}
|
|
42015
|
+
function okBody(response) {
|
|
42016
|
+
if (response.status < 200 || response.status >= 300) {
|
|
42017
|
+
throw new RemoteRequestError(response.status);
|
|
42018
|
+
}
|
|
42019
|
+
return response.body;
|
|
42020
|
+
}
|
|
42021
|
+
function parsed(schema, body, route) {
|
|
42022
|
+
let json2;
|
|
42023
|
+
try {
|
|
42024
|
+
json2 = JSON.parse(body);
|
|
42025
|
+
} catch {
|
|
42026
|
+
throw new RemoteResponseInvalid(route, "a body that is not JSON");
|
|
42027
|
+
}
|
|
42028
|
+
const result = schema.safeParse(json2);
|
|
42029
|
+
if (!result.success) {
|
|
42030
|
+
throw new RemoteResponseInvalid(route, "a body this client cannot read");
|
|
42031
|
+
}
|
|
42032
|
+
return result.data;
|
|
42033
|
+
}
|
|
42034
|
+
function resolveBaseUrl(endpoint) {
|
|
42035
|
+
if (!isSafeEndpoint(endpoint)) throw new RemoteEndpointRefused(endpoint);
|
|
42036
|
+
let end = endpoint.length;
|
|
42037
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH3) end -= 1;
|
|
42038
|
+
return endpoint.slice(0, end);
|
|
42039
|
+
}
|
|
42040
|
+
var SLASH3 = "/".charCodeAt(0);
|
|
42041
|
+
function createRemoteClient(options) {
|
|
42042
|
+
const base = resolveBaseUrl(options.endpoint);
|
|
42043
|
+
const url2 = (route) => `${base}${route}`;
|
|
42044
|
+
const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
|
|
42045
|
+
const sendOne = async (event) => {
|
|
42046
|
+
const validated = RecordAuditEventRequest.safeParse(event);
|
|
42047
|
+
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
|
|
42048
|
+
const response = await send({
|
|
42049
|
+
...common,
|
|
42050
|
+
method: "POST",
|
|
42051
|
+
url: url2(ROUTES.auditEvents),
|
|
42052
|
+
body: JSON.stringify(validated.data)
|
|
42053
|
+
});
|
|
42054
|
+
okBody(response);
|
|
42055
|
+
};
|
|
42056
|
+
return {
|
|
42057
|
+
async ingestEvents(batch) {
|
|
42058
|
+
const response = await send({
|
|
42059
|
+
...common,
|
|
42060
|
+
method: "POST",
|
|
42061
|
+
url: url2(ROUTES.events),
|
|
42062
|
+
body: JSON.stringify(batch)
|
|
42063
|
+
});
|
|
42064
|
+
return parsed(IngestAck, okBody(response), ROUTES.events);
|
|
42065
|
+
},
|
|
42066
|
+
async ingestInventory(context) {
|
|
42067
|
+
const response = await send({
|
|
42068
|
+
...common,
|
|
42069
|
+
method: "POST",
|
|
42070
|
+
url: url2(ROUTES.inventory),
|
|
42071
|
+
body: JSON.stringify(context)
|
|
42072
|
+
});
|
|
42073
|
+
return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
|
|
42074
|
+
},
|
|
42075
|
+
async recordAuditEvent(event) {
|
|
42076
|
+
await sendOne(event);
|
|
42077
|
+
},
|
|
42078
|
+
async recordAuditEvents(events, opts) {
|
|
42079
|
+
const validated = RecordAuditEventBatch.safeParse({ events });
|
|
42080
|
+
if (!validated.success) {
|
|
42081
|
+
throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
|
|
42082
|
+
}
|
|
42083
|
+
const response = await send({
|
|
42084
|
+
...common,
|
|
42085
|
+
method: "POST",
|
|
42086
|
+
url: url2(ROUTES.auditEventsBatch),
|
|
42087
|
+
body: JSON.stringify(validated.data)
|
|
42088
|
+
});
|
|
42089
|
+
if (response.status === 404) {
|
|
42090
|
+
if (opts?.fallbackToSingleEvents !== true) {
|
|
42091
|
+
throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
|
|
42092
|
+
}
|
|
42093
|
+
for (const event of validated.data.events) await sendOne(event);
|
|
42094
|
+
return { accepted: validated.data.events.length };
|
|
42095
|
+
}
|
|
42096
|
+
return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
|
|
42097
|
+
},
|
|
42098
|
+
async reportStorePosture(snapshot) {
|
|
42099
|
+
const response = await send({
|
|
42100
|
+
...common,
|
|
42101
|
+
method: "POST",
|
|
42102
|
+
url: url2(ROUTES.storePosture),
|
|
42103
|
+
body: JSON.stringify(snapshot)
|
|
42104
|
+
});
|
|
42105
|
+
okBody(response);
|
|
42106
|
+
},
|
|
42107
|
+
async getPolicyBundle(etag) {
|
|
42108
|
+
const response = await send({
|
|
42109
|
+
...common,
|
|
42110
|
+
method: "GET",
|
|
42111
|
+
url: url2(ROUTES.policyBundle),
|
|
42112
|
+
...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
|
|
42113
|
+
});
|
|
42114
|
+
if (response.status === 304) {
|
|
42115
|
+
return { changed: false, etag: headerValue(response, "etag") ?? etag };
|
|
42116
|
+
}
|
|
42117
|
+
const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
|
|
42118
|
+
return { changed: true, bundle, etag: headerValue(response, "etag") };
|
|
42119
|
+
},
|
|
42120
|
+
async whoami() {
|
|
42121
|
+
const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
|
|
42122
|
+
return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
|
|
42123
|
+
},
|
|
42124
|
+
async recordProjectEgress(request) {
|
|
42125
|
+
const validated = EgressIngestRequest.safeParse(request);
|
|
42126
|
+
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
|
|
42127
|
+
const response = await send({
|
|
42128
|
+
...common,
|
|
42129
|
+
method: "POST",
|
|
42130
|
+
url: url2(ROUTES.shares),
|
|
42131
|
+
body: JSON.stringify(validated.data)
|
|
42132
|
+
});
|
|
42133
|
+
if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.shares);
|
|
42134
|
+
okBody(response);
|
|
42135
|
+
},
|
|
42136
|
+
async pollCommand() {
|
|
42137
|
+
const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
|
|
42138
|
+
if (response.status === 404) return null;
|
|
42139
|
+
return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
|
|
42140
|
+
},
|
|
42141
|
+
async ackCommand(id, body) {
|
|
42142
|
+
const validated = DeviceCommandAckBody.safeParse(body);
|
|
42143
|
+
const route = ackRoute(id);
|
|
42144
|
+
if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
|
|
42145
|
+
const response = await send({
|
|
42146
|
+
...common,
|
|
42147
|
+
method: "POST",
|
|
42148
|
+
url: url2(route),
|
|
42149
|
+
body: JSON.stringify(validated.data)
|
|
42150
|
+
});
|
|
42151
|
+
okBody(response);
|
|
42152
|
+
}
|
|
42153
|
+
};
|
|
42154
|
+
}
|
|
42155
|
+
|
|
42156
|
+
// ../../packages/remote/src/failure-kind.ts
|
|
42157
|
+
function statusOf(err) {
|
|
42158
|
+
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
42159
|
+
const { status } = err;
|
|
42160
|
+
if (typeof status !== "number" || !Number.isInteger(status)) return null;
|
|
42161
|
+
return status >= 100 && status <= 599 ? status : null;
|
|
42162
|
+
}
|
|
42163
|
+
function nameOf(err) {
|
|
42164
|
+
if (typeof err !== "object" || err === null || !("name" in err)) return null;
|
|
42165
|
+
return typeof err.name === "string" ? err.name : null;
|
|
42166
|
+
}
|
|
42167
|
+
function classifyRemoteFailure(err) {
|
|
42168
|
+
switch (nameOf(err)) {
|
|
42169
|
+
case "RemoteRouteAbsent":
|
|
42170
|
+
return "route-absent";
|
|
42171
|
+
case "RemoteRequestInvalid":
|
|
42172
|
+
case "RemoteEndpointRefused":
|
|
42173
|
+
return "invalid-request";
|
|
42174
|
+
case "RemoteResponseInvalid":
|
|
42175
|
+
return "rejected";
|
|
42176
|
+
default:
|
|
42177
|
+
break;
|
|
42178
|
+
}
|
|
42179
|
+
const status = statusOf(err);
|
|
42180
|
+
if (status === null) return "unreachable";
|
|
42181
|
+
switch (status) {
|
|
42182
|
+
case 401:
|
|
42183
|
+
return "unauthorized";
|
|
42184
|
+
case 403:
|
|
42185
|
+
return "forbidden";
|
|
42186
|
+
case 429:
|
|
42187
|
+
return "unreachable";
|
|
42188
|
+
case 404:
|
|
42189
|
+
return "unreachable";
|
|
42190
|
+
default:
|
|
42191
|
+
return status >= 400 && status <= 499 ? "rejected" : "unreachable";
|
|
42192
|
+
}
|
|
42193
|
+
}
|
|
42194
|
+
|
|
42195
|
+
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
42196
|
+
function classifyFailure(err) {
|
|
42197
|
+
switch (classifyRemoteFailure(err)) {
|
|
42198
|
+
case "unauthorized":
|
|
42199
|
+
return "unauthorized";
|
|
42200
|
+
case "forbidden":
|
|
42201
|
+
return "forbidden";
|
|
42202
|
+
default:
|
|
42203
|
+
return "unreachable";
|
|
42204
|
+
}
|
|
42205
|
+
}
|
|
42206
|
+
|
|
42207
|
+
// ../../packages/plugin-runtime/src/attached/with-timeout.ts
|
|
42208
|
+
var REQUEST_TIMEOUT_MS = 2e3;
|
|
42209
|
+
function withTimeout(promise2, ms) {
|
|
42210
|
+
let timer;
|
|
42211
|
+
const timeout = new Promise((_, reject) => {
|
|
42212
|
+
timer = setTimeout(() => {
|
|
42213
|
+
reject(new Error("attached gateway request timed out"));
|
|
42214
|
+
}, ms);
|
|
42215
|
+
});
|
|
42216
|
+
promise2.catch(() => void 0);
|
|
42217
|
+
return Promise.race([promise2, timeout]).finally(() => {
|
|
42218
|
+
clearTimeout(timer);
|
|
42219
|
+
});
|
|
42220
|
+
}
|
|
42221
|
+
|
|
42222
|
+
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
42223
|
+
import { readFileSync as readFileSync16 } from "fs";
|
|
42224
|
+
import { join as join26 } from "path";
|
|
42225
|
+
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
42226
|
+
function forwardDropsPath(dataDir2) {
|
|
42227
|
+
return join26(dataDir2, FORWARD_DROPS_FILENAME);
|
|
42228
|
+
}
|
|
42229
|
+
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
42230
|
+
if (count <= 0) return;
|
|
42231
|
+
try {
|
|
42232
|
+
ensureDataDirSync(dataDir2);
|
|
42233
|
+
const previous = readForwardDrops(dataDir2);
|
|
42234
|
+
const next = {
|
|
42235
|
+
droppedForwards: (previous?.droppedForwards ?? 0) + count,
|
|
42236
|
+
lastDropAtMs: nowMs
|
|
42237
|
+
};
|
|
42238
|
+
writeOwnerOnlyFileSync(forwardDropsPath(dataDir2), `${JSON.stringify(next)}
|
|
42239
|
+
`);
|
|
42240
|
+
} catch {
|
|
42241
|
+
}
|
|
42242
|
+
}
|
|
42243
|
+
function readForwardDrops(dataDir2) {
|
|
42244
|
+
try {
|
|
42245
|
+
const parsed2 = JSON.parse(readFileSync16(forwardDropsPath(dataDir2), "utf8"));
|
|
42246
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
42247
|
+
const record2 = parsed2;
|
|
42248
|
+
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
42249
|
+
return null;
|
|
42250
|
+
}
|
|
42251
|
+
if (record2.droppedForwards <= 0) return null;
|
|
42252
|
+
if (typeof record2.lastDropAtMs !== "number" || !Number.isFinite(record2.lastDropAtMs)) {
|
|
42253
|
+
return null;
|
|
42254
|
+
}
|
|
42255
|
+
return { droppedForwards: record2.droppedForwards, lastDropAtMs: record2.lastDropAtMs };
|
|
42256
|
+
} catch {
|
|
42257
|
+
return null;
|
|
42258
|
+
}
|
|
42259
|
+
}
|
|
42260
|
+
|
|
41400
42261
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
42262
|
+
import { randomUUID as randomUUID15 } from "crypto";
|
|
42263
|
+
import { readFile, rename, writeFile } from "fs/promises";
|
|
42264
|
+
import { join as join27 } from "path";
|
|
41401
42265
|
function isInvalidRequest(err) {
|
|
41402
42266
|
return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
|
|
41403
42267
|
}
|
|
@@ -41416,7 +42280,7 @@ var FORWARD_STATE_FILENAME = ATTACHED_FORWARD_STATE_FILENAME;
|
|
|
41416
42280
|
var STATE_FILENAME = FORWARD_STATE_FILENAME;
|
|
41417
42281
|
function createForwardPolicy(deps) {
|
|
41418
42282
|
const now = deps.now ?? (() => Date.now());
|
|
41419
|
-
const file2 =
|
|
42283
|
+
const file2 = join27(deps.dir, STATE_FILENAME);
|
|
41420
42284
|
let state = null;
|
|
41421
42285
|
let loading = null;
|
|
41422
42286
|
async function readState() {
|
|
@@ -41441,7 +42305,7 @@ function createForwardPolicy(deps) {
|
|
|
41441
42305
|
state = next;
|
|
41442
42306
|
try {
|
|
41443
42307
|
await ensureDataDir(deps.dir);
|
|
41444
|
-
const tmp = `${file2}.${
|
|
42308
|
+
const tmp = `${file2}.${randomUUID15()}.tmp`;
|
|
41445
42309
|
await writeFile(tmp, JSON.stringify(next), { encoding: "utf8", mode: DATA_FILE_MODE });
|
|
41446
42310
|
await rename(tmp, file2);
|
|
41447
42311
|
} catch {
|
|
@@ -41582,6 +42446,9 @@ var AttachedDataGateway = class {
|
|
|
41582
42446
|
*
|
|
41583
42447
|
* Machine mode answers before any key is read, so a machine attachment pays
|
|
41584
42448
|
* nothing for scoping and forwards exactly what it always has.
|
|
42449
|
+
*
|
|
42450
|
+
* `governanceAppliesTo` answers from this same verdict, so it agrees with
|
|
42451
|
+
* forwarding key for key.
|
|
41585
42452
|
*/
|
|
41586
42453
|
verdictFor(keyOf) {
|
|
41587
42454
|
try {
|
|
@@ -41598,24 +42465,27 @@ var AttachedDataGateway = class {
|
|
|
41598
42465
|
* the key its row holds in the local store, recorded per root (see
|
|
41599
42466
|
* `rootVerdict`), not the key on the root event just handed in: roots are
|
|
41600
42467
|
* first-write-wins in the store, so when two producers record a root for one
|
|
41601
|
-
* session (the session-start hook, then a reconcile pass) the second leaves
|
|
41602
|
-
*
|
|
41603
|
-
*
|
|
41604
|
-
*
|
|
41605
|
-
*
|
|
41606
|
-
*
|
|
41607
|
-
*
|
|
41608
|
-
*
|
|
41609
|
-
*
|
|
41610
|
-
*
|
|
41611
|
-
*
|
|
41612
|
-
*
|
|
41613
|
-
*
|
|
41614
|
-
*
|
|
41615
|
-
*
|
|
41616
|
-
*
|
|
41617
|
-
*
|
|
41618
|
-
*
|
|
42468
|
+
* session (the session-start hook, then a reconcile pass) the second leaves the
|
|
42469
|
+
* stored row as it was. That stored row, not this event, is what a history
|
|
42470
|
+
* drain pass would decide, if the root started before the attach; the drain
|
|
42471
|
+
* never offers one that started after it (`started_at < backlogBefore`).
|
|
42472
|
+
* Whether this root EVENT is itself sent takes both keys: the stored one AND
|
|
42473
|
+
* its own. The event's attributes (cwd, project, repo) describe where it was
|
|
42474
|
+
* recorded from, so a root event keyed to a personal directory is never sent
|
|
42475
|
+
* under an enrolled stored root, though the enrolled leaves still forward under
|
|
42476
|
+
* it: the instance that wrote the stored root is expected to have forwarded it.
|
|
42477
|
+
* If it did not (the root was written while standalone or under another
|
|
42478
|
+
* attachment, or its forward failed), the plane refuses those leaves. A root
|
|
42479
|
+
* that started before the attach is shipped, ahead of its leaves, by the
|
|
42480
|
+
* history drain; one that started after it is never offered by the drain. Any
|
|
42481
|
+
* other row with a root reference (`rootSessionId`, else `parentId`) forwards
|
|
42482
|
+
* only when its own key is in scope AND this instance recorded an in-scope
|
|
42483
|
+
* verdict for that root. The audit-event route has real foreign keys on both
|
|
42484
|
+
* columns and stubs no missing root, so a leaf sent after its root was kept
|
|
42485
|
+
* local is refused there, and a refused forward counts toward the breaker that
|
|
42486
|
+
* guards every other one. A root this instance never recorded is therefore
|
|
42487
|
+
* `'local'`: the only answer that cannot orphan a row. A row with no root
|
|
42488
|
+
* reference at all has nothing to orphan, and is decided by its own key.
|
|
41619
42489
|
*
|
|
41620
42490
|
* What this costs is stated rather than discovered. A session whose stored
|
|
41621
42491
|
* root is not keyed to an enrolled repository keeps its token and tool
|
|
@@ -41686,6 +42556,87 @@ var AttachedDataGateway = class {
|
|
|
41686
42556
|
return [];
|
|
41687
42557
|
}
|
|
41688
42558
|
}
|
|
42559
|
+
/**
|
|
42560
|
+
* The verdict for the repositories nested in a scanned project, answered
|
|
42561
|
+
* TOTALLY: `'forward'` or `'local'`, never a throw.
|
|
42562
|
+
*
|
|
42563
|
+
* A walk descends into a nested clone or submodule and folds its files into
|
|
42564
|
+
* the project it is walking, so one register can carry several
|
|
42565
|
+
* repositories' call sites under one project key. Each of them must be in
|
|
42566
|
+
* scope for it to forward. One key out of scope, or a nested repository with
|
|
42567
|
+
* no remote (an `undefined` key), keeps the whole register local.
|
|
42568
|
+
*
|
|
42569
|
+
* An ABSENT list is `'local'` too. Only the code that walked the tree can say
|
|
42570
|
+
* what is nested in it, and every scan passes the list, empty when nothing
|
|
42571
|
+
* is nested. A register nobody vouched for is not one a scoped attachment
|
|
42572
|
+
* may send.
|
|
42573
|
+
*
|
|
42574
|
+
* Machine mode answers before reading the context, so a machine attachment
|
|
42575
|
+
* forwards exactly what it always has.
|
|
42576
|
+
*/
|
|
42577
|
+
nestedVerdict(context) {
|
|
42578
|
+
try {
|
|
42579
|
+
if (this.deps.attachment.mode === "machine") return "forward";
|
|
42580
|
+
const keys = context?.nestedScopeKeys;
|
|
42581
|
+
if (keys === void 0) return "local";
|
|
42582
|
+
for (const key of keys) {
|
|
42583
|
+
if (this.verdictFor(() => key) === "local") return "local";
|
|
42584
|
+
}
|
|
42585
|
+
return "forward";
|
|
42586
|
+
} catch {
|
|
42587
|
+
return "local";
|
|
42588
|
+
}
|
|
42589
|
+
}
|
|
42590
|
+
/**
|
|
42591
|
+
* The register a scoped attachment sends, once the project and the repositories
|
|
42592
|
+
* nested in it are in scope: the register itself, with `reconcile.deletedFiles`
|
|
42593
|
+
* cut to the deleted paths whose own repository is in scope. `undefined` sends
|
|
42594
|
+
* nothing. TOTAL, like `verdictFor`, and for its reasons.
|
|
42595
|
+
*
|
|
42596
|
+
* The deletion sweep takes its paths from the scan ledger, not from the walk,
|
|
42597
|
+
* and the ledger holds every file the scanner ever read under the root, nested
|
|
42598
|
+
* clones' included. So a clone that was removed, or one an ignore file now
|
|
42599
|
+
* hides, is in no walk and never reaches `nestedVerdict`, yet its ledgered
|
|
42600
|
+
* paths come back as deleted. The scan names the repository of each deleted
|
|
42601
|
+
* path (`context.deletedFileKeys`, one entry per path in the register's order)
|
|
42602
|
+
* and each is held to the same verdict as any other key. A path whose key is
|
|
42603
|
+
* absent, or out of scope, is not sent.
|
|
42604
|
+
*
|
|
42605
|
+
* The list is asked for here, and only here: it is an async read of the scan
|
|
42606
|
+
* ledger that the scan makes on being called, so a machine attachment, which
|
|
42607
|
+
* returns before this, and a register already kept local never cause it.
|
|
42608
|
+
*
|
|
42609
|
+
* Anything the scan did not vouch for sends no deleted path, and the register
|
|
42610
|
+
* itself still goes: no list, a list that throws or whose read is rejected, or a
|
|
42611
|
+
* list whose length is not the register's. Deleting is the only thing a dropped
|
|
42612
|
+
* path could have done on the server, so the cost of a refusal is a stored row
|
|
42613
|
+
* that stays, never a path that leaves.
|
|
42614
|
+
*
|
|
42615
|
+
* Machine mode returns `input` itself, the same object and unread, so a machine
|
|
42616
|
+
* attachment's request is exactly what it was. A register that lists no deleted
|
|
42617
|
+
* path, or that is not a ledger register, has nothing to cut and is returned
|
|
42618
|
+
* as it came, with the list unread.
|
|
42619
|
+
*/
|
|
42620
|
+
async registerForWire(input2, context) {
|
|
42621
|
+
try {
|
|
42622
|
+
if (this.deps.attachment.mode === "machine") return input2;
|
|
42623
|
+
const { reconcile } = input2;
|
|
42624
|
+
if (reconcile.mode !== "ledger" || reconcile.deletedFiles.length === 0) return input2;
|
|
42625
|
+
const deleted = reconcile.deletedFiles;
|
|
42626
|
+
let kept = [];
|
|
42627
|
+
try {
|
|
42628
|
+
const keys = await context?.deletedFileKeys?.();
|
|
42629
|
+
if (keys?.length === deleted.length) {
|
|
42630
|
+
kept = deleted.filter((_path, at) => this.verdictFor(() => keys[at]) === "forward");
|
|
42631
|
+
}
|
|
42632
|
+
} catch {
|
|
42633
|
+
kept = [];
|
|
42634
|
+
}
|
|
42635
|
+
return { ...input2, reconcile: { ...reconcile, deletedFiles: kept } };
|
|
42636
|
+
} catch {
|
|
42637
|
+
return void 0;
|
|
42638
|
+
}
|
|
42639
|
+
}
|
|
41689
42640
|
/**
|
|
41690
42641
|
* The event `recordCapture` sends for a capture the verdict let through, or
|
|
41691
42642
|
* `undefined` to send nothing. TOTAL, like `verdictFor`, and for its reasons.
|
|
@@ -42011,12 +42962,24 @@ var AttachedDataGateway = class {
|
|
|
42011
42962
|
* payload onto the wire-boundary-safe shape (no snippet, hashed
|
|
42012
42963
|
* projectKey), and its result is discarded: `forward.run` never throws or
|
|
42013
42964
|
* rejects, so there is nothing here to act on.
|
|
42965
|
+
*
|
|
42966
|
+
* `context.nestedScopeKeys` is what the scanner knows and the register does
|
|
42967
|
+
* not say: the key of every repository nested below the scan root, whose
|
|
42968
|
+
* files the walk folded into this register. On a scoped attachment the
|
|
42969
|
+
* register is forwarded only when the project's own key AND every one of
|
|
42970
|
+
* those is in scope (see `nestedVerdict`), and its deleted paths are cut to the
|
|
42971
|
+
* ones whose own repository is in scope (`context.deletedFileKeys`, see
|
|
42972
|
+
* `registerForWire`). Machine mode never reads either, and the local write
|
|
42973
|
+
* never receives the context and gets the register whole.
|
|
42014
42974
|
*/
|
|
42015
|
-
async recordProjectEgress(input2) {
|
|
42975
|
+
async recordProjectEgress(input2, context) {
|
|
42016
42976
|
const summary = await this.deps.local.recordProjectEgress(input2);
|
|
42017
42977
|
if (this.verdictFor(() => scopeKeyOfProjectKey(input2.projectKey)) === "local") return summary;
|
|
42978
|
+
if (this.nestedVerdict(context) === "local") return summary;
|
|
42979
|
+
const register = await this.registerForWire(input2, context);
|
|
42980
|
+
if (register === void 0) return summary;
|
|
42018
42981
|
await this.deps.forward.run(
|
|
42019
|
-
() => this.deps.client.recordProjectEgress(toEgressIngestRequest(
|
|
42982
|
+
() => this.deps.client.recordProjectEgress(toEgressIngestRequest(register))
|
|
42020
42983
|
);
|
|
42021
42984
|
return summary;
|
|
42022
42985
|
}
|
|
@@ -42070,14 +43033,19 @@ var AttachedDataGateway = class {
|
|
|
42070
43033
|
async scanLedgerPaths() {
|
|
42071
43034
|
return this.deps.local.scanLedgerPaths();
|
|
42072
43035
|
}
|
|
43036
|
+
// Delegated, like the path list. An inner gateway that cannot say answers an
|
|
43037
|
+
// empty map, which gives every deleted path no key.
|
|
43038
|
+
async scanLedgerPathKeys() {
|
|
43039
|
+
return await this.deps.local.scanLedgerPathKeys?.() ?? /* @__PURE__ */ new Map();
|
|
43040
|
+
}
|
|
42073
43041
|
async recordScanned(entries) {
|
|
42074
43042
|
return this.deps.local.recordScanned(entries);
|
|
42075
43043
|
}
|
|
42076
43044
|
async getRuleProbeVerdict(ruleKey) {
|
|
42077
43045
|
return this.deps.local.getRuleProbeVerdict(ruleKey);
|
|
42078
43046
|
}
|
|
42079
|
-
async setRuleProbeVerdict(ruleKey, verdict,
|
|
42080
|
-
return this.deps.local.setRuleProbeVerdict(ruleKey, verdict,
|
|
43047
|
+
async setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
|
|
43048
|
+
return this.deps.local.setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2);
|
|
42081
43049
|
}
|
|
42082
43050
|
async openAtRestKeysForPath(path) {
|
|
42083
43051
|
return this.deps.local.openAtRestKeysForPath(path);
|
|
@@ -42136,6 +43104,12 @@ var AttachedDataGateway = class {
|
|
|
42136
43104
|
// and the spread above would otherwise drop the field silently — which is
|
|
42137
43105
|
// exactly what it did, leaving the whole control inert on every device
|
|
42138
43106
|
// while every test around it stayed green.
|
|
43107
|
+
//
|
|
43108
|
+
// WHOLE ON EVERY ATTACHMENT. A scoped attachment does not narrow the list
|
|
43109
|
+
// here: the port's `getPolicyBundle()` takes no event, and the runtime
|
|
43110
|
+
// reads this bundle once to build detection, so the detections it carries
|
|
43111
|
+
// apply to every event on the machine. Where a prohibition applies is
|
|
43112
|
+
// answered per event by `governanceAppliesTo` below.
|
|
42139
43113
|
prohibitedModels: cached2.prohibitedModels,
|
|
42140
43114
|
// NAMED for the same reason as the line above, and it is the same defect
|
|
42141
43115
|
// if it is not: `...local` above spreads the DEVICE's bundle, so a field
|
|
@@ -42195,6 +43169,30 @@ var AttachedDataGateway = class {
|
|
|
42195
43169
|
};
|
|
42196
43170
|
}
|
|
42197
43171
|
// ---------------------------------------------------------------------
|
|
43172
|
+
// GovernanceScope — where the organization's model policy applies
|
|
43173
|
+
// ---------------------------------------------------------------------
|
|
43174
|
+
/**
|
|
43175
|
+
* Whether the organization's governance applies to an event keyed `scopeKey`:
|
|
43176
|
+
* the question a model-guard site asks once it has decided to refuse.
|
|
43177
|
+
*
|
|
43178
|
+
* THE FORWARD VERDICT, through `verdictFor`: the answer is whether a capture
|
|
43179
|
+
* with the same key would be forwarded. A machine-wide attachment governs
|
|
43180
|
+
* every event, keyless included, exactly as before. A scoped one governs an
|
|
43181
|
+
* event only when its key names an enrolled repository. An event in a
|
|
43182
|
+
* personal repository, in no repository, with an empty key, or met by a fault
|
|
43183
|
+
* is not governed.
|
|
43184
|
+
*
|
|
43185
|
+
* The event's OWN key, never its session root's. The root rule in
|
|
43186
|
+
* `auditVerdict` decides whether a row can be forwarded without orphaning it;
|
|
43187
|
+
* this decides whether a refusal applies, which is a question about where the
|
|
43188
|
+
* event happened.
|
|
43189
|
+
*
|
|
43190
|
+
* Answered from memory: no store read, no bundle read, nothing sent.
|
|
43191
|
+
*/
|
|
43192
|
+
governanceAppliesTo(scopeKey) {
|
|
43193
|
+
return this.verdictFor(() => scopeKey) === "forward";
|
|
43194
|
+
}
|
|
43195
|
+
// ---------------------------------------------------------------------
|
|
42198
43196
|
// LocalStoreMaintenance — by delegation (D3).
|
|
42199
43197
|
//
|
|
42200
43198
|
// Implementing these is what actually closes the skipped-local-maintenance
|
|
@@ -42303,7 +43301,7 @@ function toWireInspection(insp) {
|
|
|
42303
43301
|
}
|
|
42304
43302
|
|
|
42305
43303
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
42306
|
-
import { createHash as
|
|
43304
|
+
import { createHash as createHash7 } from "crypto";
|
|
42307
43305
|
import { hostname as hostname5 } from "os";
|
|
42308
43306
|
|
|
42309
43307
|
// ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
|
|
@@ -42311,6 +43309,7 @@ var CORRELATION_ID = EventMetadata.shape.correlationId;
|
|
|
42311
43309
|
var TRACE_ID = EventMetadata.shape.traceId;
|
|
42312
43310
|
var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
|
|
42313
43311
|
var REDACT_DEGRADED_TO = EventMetadata.shape.redactDegradedTo.unwrap();
|
|
43312
|
+
var SCAN_INCOMPLETE = EventMetadata.shape.scanIncomplete.unwrap();
|
|
42314
43313
|
|
|
42315
43314
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
42316
43315
|
var CAPTURE_BATCH_BYTES = 1024 * 1024;
|
|
@@ -42346,17 +43345,17 @@ function spawnDetached(scriptPath) {
|
|
|
42346
43345
|
|
|
42347
43346
|
// ../../packages/plugin-runtime/src/attached/install-record.ts
|
|
42348
43347
|
import { readFile as readFile2, stat } from "fs/promises";
|
|
42349
|
-
import { basename as
|
|
43348
|
+
import { basename as basename6, dirname as dirname6, join as join28, resolve as resolve2 } from "path";
|
|
42350
43349
|
async function readInstalledVersion(installRoot) {
|
|
42351
43350
|
try {
|
|
42352
43351
|
const versionDir = resolve2(installRoot);
|
|
42353
|
-
const pluginDir =
|
|
42354
|
-
const marketplaceDir =
|
|
42355
|
-
const cacheDir =
|
|
42356
|
-
if (
|
|
42357
|
-
const key = `${
|
|
43352
|
+
const pluginDir = dirname6(versionDir);
|
|
43353
|
+
const marketplaceDir = dirname6(pluginDir);
|
|
43354
|
+
const cacheDir = dirname6(marketplaceDir);
|
|
43355
|
+
if (basename6(cacheDir) !== "cache") return null;
|
|
43356
|
+
const key = `${basename6(pluginDir)}@${basename6(marketplaceDir)}`;
|
|
42358
43357
|
const record2 = JSON.parse(
|
|
42359
|
-
await readFile2(
|
|
43358
|
+
await readFile2(join28(dirname6(cacheDir), "installed_plugins.json"), "utf8")
|
|
42360
43359
|
);
|
|
42361
43360
|
const plugins = record2?.plugins;
|
|
42362
43361
|
if (typeof plugins !== "object" || plugins === null || !Object.hasOwn(plugins, key)) {
|
|
@@ -42388,7 +43387,7 @@ async function exists(path) {
|
|
|
42388
43387
|
}
|
|
42389
43388
|
|
|
42390
43389
|
// ../../packages/plugin-runtime/src/attached/plugin-block.ts
|
|
42391
|
-
import { readFileSync as
|
|
43390
|
+
import { readFileSync as readFileSync17 } from "fs";
|
|
42392
43391
|
var INSTALL_RECORD_READ_TIMEOUT_MS = REQUEST_TIMEOUT_MS / 2;
|
|
42393
43392
|
var manifestBuildCache = /* @__PURE__ */ new Map();
|
|
42394
43393
|
function readManifestBuild(manifestUrl, packageName) {
|
|
@@ -42396,7 +43395,7 @@ function readManifestBuild(manifestUrl, packageName) {
|
|
|
42396
43395
|
if (!manifestBuildCache.has(key)) {
|
|
42397
43396
|
let build;
|
|
42398
43397
|
try {
|
|
42399
|
-
const manifest = JSON.parse(
|
|
43398
|
+
const manifest = JSON.parse(readFileSync17(manifestUrl, "utf8"));
|
|
42400
43399
|
build = typeof manifest.version === "string" && manifest.version.length > 0 ? { package: packageName, version: manifest.version } : void 0;
|
|
42401
43400
|
} catch {
|
|
42402
43401
|
build = void 0;
|
|
@@ -42431,9 +43430,9 @@ async function readInstalledVersionBounded(installRoot) {
|
|
|
42431
43430
|
}
|
|
42432
43431
|
|
|
42433
43432
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
42434
|
-
import { randomUUID as
|
|
43433
|
+
import { randomUUID as randomUUID16 } from "crypto";
|
|
42435
43434
|
import { readFile as readFile3, rm, writeFile as writeFile2 } from "fs/promises";
|
|
42436
|
-
import { join as
|
|
43435
|
+
import { join as join29 } from "path";
|
|
42437
43436
|
|
|
42438
43437
|
// ../../packages/plugin-runtime/src/attached/atomic-publish.ts
|
|
42439
43438
|
import { rename as rename2 } from "fs/promises";
|
|
@@ -42462,7 +43461,7 @@ async function publishByRename(tmp, file2, move = rename2) {
|
|
|
42462
43461
|
|
|
42463
43462
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
42464
43463
|
function createPolicyStore(dir = dataDir()) {
|
|
42465
|
-
const file2 =
|
|
43464
|
+
const file2 = join29(dir, "policy-cache.json");
|
|
42466
43465
|
async function read() {
|
|
42467
43466
|
try {
|
|
42468
43467
|
const raw = await readFile3(file2, "utf8");
|
|
@@ -42494,7 +43493,7 @@ function createPolicyStore(dir = dataDir()) {
|
|
|
42494
43493
|
}
|
|
42495
43494
|
}
|
|
42496
43495
|
async function publishRecord(record2) {
|
|
42497
|
-
const tmp = `${file2}.${
|
|
43496
|
+
const tmp = `${file2}.${randomUUID16()}.tmp`;
|
|
42498
43497
|
try {
|
|
42499
43498
|
await writeFile2(tmp, JSON.stringify(record2), {
|
|
42500
43499
|
encoding: "utf8",
|
|
@@ -42532,8 +43531,8 @@ function createPolicyStore(dir = dataDir()) {
|
|
|
42532
43531
|
}
|
|
42533
43532
|
|
|
42534
43533
|
// ../../packages/plugin-runtime/src/attached/posture-report-state.ts
|
|
42535
|
-
import { readFileSync as
|
|
42536
|
-
import { join as
|
|
43534
|
+
import { readFileSync as readFileSync18 } from "fs";
|
|
43535
|
+
import { join as join30 } from "path";
|
|
42537
43536
|
var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
|
|
42538
43537
|
var OUTCOME_KEYS = {
|
|
42539
43538
|
ok: true,
|
|
@@ -42547,7 +43546,7 @@ var OUTCOME_KEYS = {
|
|
|
42547
43546
|
};
|
|
42548
43547
|
var OUTCOMES = new Set(Object.keys(OUTCOME_KEYS));
|
|
42549
43548
|
function postureReportStatePath(dataDir2) {
|
|
42550
|
-
return
|
|
43549
|
+
return join30(dataDir2, POSTURE_REPORT_STATE_FILENAME);
|
|
42551
43550
|
}
|
|
42552
43551
|
function writePostureReportState(dataDir2, state) {
|
|
42553
43552
|
try {
|
|
@@ -42588,10 +43587,19 @@ function createPostureReporter(deps) {
|
|
|
42588
43587
|
hostname: deps.hostname(),
|
|
42589
43588
|
capturedAt: nowMs,
|
|
42590
43589
|
...measurement,
|
|
42591
|
-
// Omit the key rather than spread an explicit `undefined
|
|
42592
|
-
//
|
|
42593
|
-
//
|
|
42594
|
-
|
|
43590
|
+
// Omit the key rather than spread an explicit `undefined`. The type
|
|
43591
|
+
// admits `undefined` here (the schema's optional member), and
|
|
43592
|
+
// JSON.stringify sends the same bytes either way. Omitting keeps the
|
|
43593
|
+
// in-memory object free of an explicit `undefined` member, which the
|
|
43594
|
+
// tests pin by key presence.
|
|
43595
|
+
...plugin === void 0 ? {} : { plugin },
|
|
43596
|
+
// LAST, and only for a scoped attachment. A machine attachment omits
|
|
43597
|
+
// the key the same way, so its body is byte for byte the one it sent
|
|
43598
|
+
// before the member existed. Anything but exactly `machine` reports the
|
|
43599
|
+
// constant `scoped`, never the raw value: that is resolveScope's own
|
|
43600
|
+
// fail direction, and a value outside the wire's vocabulary would fail
|
|
43601
|
+
// the whole snapshot at the receiver, the wipe signal with it.
|
|
43602
|
+
...deps.attachmentMode === "machine" ? {} : { attachmentMode: "scoped" }
|
|
42595
43603
|
};
|
|
42596
43604
|
} catch {
|
|
42597
43605
|
return null;
|
|
@@ -42615,7 +43623,7 @@ function createPostureReporter(deps) {
|
|
|
42615
43623
|
|
|
42616
43624
|
// ../../packages/plugin-runtime/src/attached/posture-snapshot.ts
|
|
42617
43625
|
import { statSync as statSync9 } from "fs";
|
|
42618
|
-
import { DatabaseSync as
|
|
43626
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
42619
43627
|
|
|
42620
43628
|
// ../../packages/plugin-runtime/src/attached/action-counts.ts
|
|
42621
43629
|
function emptyActionCounts() {
|
|
@@ -42673,7 +43681,7 @@ function readStorePosture(dbPath2) {
|
|
|
42673
43681
|
readError: false
|
|
42674
43682
|
});
|
|
42675
43683
|
try {
|
|
42676
|
-
db = new
|
|
43684
|
+
db = new DatabaseSync3(dbPath2, { readOnly: true });
|
|
42677
43685
|
db.exec("PRAGMA busy_timeout = 2000");
|
|
42678
43686
|
version2 = db.prepare("PRAGMA user_version").get().user_version;
|
|
42679
43687
|
try {
|
|
@@ -42725,16 +43733,16 @@ function readStorePosture(dbPath2) {
|
|
|
42725
43733
|
}
|
|
42726
43734
|
|
|
42727
43735
|
// ../../packages/plugin-runtime/src/attached/posture-store.ts
|
|
42728
|
-
import { randomUUID as
|
|
43736
|
+
import { randomUUID as randomUUID17 } from "crypto";
|
|
42729
43737
|
import { readFile as readFile4, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
42730
|
-
import { join as
|
|
43738
|
+
import { join as join31 } from "path";
|
|
42731
43739
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
42732
43740
|
function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
42733
|
-
const file2 =
|
|
42734
|
-
const legacyFile = legacyDir === void 0 ? null :
|
|
43741
|
+
const file2 = join31(dir, "posture-state.json");
|
|
43742
|
+
const legacyFile = legacyDir === void 0 ? null : join31(legacyDir, "posture-state.json");
|
|
42735
43743
|
async function persist(state) {
|
|
42736
43744
|
await ensureDataDir(dir);
|
|
42737
|
-
const tmp = `${file2}.${
|
|
43745
|
+
const tmp = `${file2}.${randomUUID17()}.tmp`;
|
|
42738
43746
|
try {
|
|
42739
43747
|
await writeFile3(tmp, JSON.stringify(state), { encoding: "utf8", mode: DATA_FILE_MODE });
|
|
42740
43748
|
await publishByRename(tmp, file2);
|
|
@@ -42776,7 +43784,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
42776
43784
|
}
|
|
42777
43785
|
return legacy;
|
|
42778
43786
|
}
|
|
42779
|
-
const fresh = { deviceId:
|
|
43787
|
+
const fresh = { deviceId: randomUUID17(), lastAttemptedAtMs: 0 };
|
|
42780
43788
|
try {
|
|
42781
43789
|
await ensureDataDir(dir);
|
|
42782
43790
|
if (createOwnerOnlyFileSync(file2, JSON.stringify(fresh))) return fresh;
|
|
@@ -42799,8 +43807,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
42799
43807
|
}
|
|
42800
43808
|
|
|
42801
43809
|
// ../../packages/plugin-runtime/src/attached/sync-state.ts
|
|
42802
|
-
import { readFileSync as
|
|
42803
|
-
import { join as
|
|
43810
|
+
import { readFileSync as readFileSync19 } from "fs";
|
|
43811
|
+
import { join as join32 } from "path";
|
|
42804
43812
|
|
|
42805
43813
|
// ../../packages/plugin-runtime/src/attached/status.ts
|
|
42806
43814
|
var REFUSAL_LINES = {
|
|
@@ -42887,7 +43895,7 @@ var StandaloneDataGateway = class {
|
|
|
42887
43895
|
// One notice per gateway — see warnRulesetDiscarded.
|
|
42888
43896
|
warnedRulesetDiscarded = false;
|
|
42889
43897
|
constructor(dataDir2, detections = [], meta4) {
|
|
42890
|
-
this.db = openLocalDatabase(dataDir2);
|
|
43898
|
+
this.db = openLocalDatabase(dataDir2, { shippedRegexMatchers: shippedRegexMatchers() });
|
|
42891
43899
|
this.dataDir = dataDir2;
|
|
42892
43900
|
this.db.installedPacks.recordInventory(detections, meta4);
|
|
42893
43901
|
}
|
|
@@ -43236,6 +44244,9 @@ var StandaloneDataGateway = class {
|
|
|
43236
44244
|
scanLedgerPaths() {
|
|
43237
44245
|
return Promise.resolve(this.db.scanLedger.allPaths());
|
|
43238
44246
|
}
|
|
44247
|
+
scanLedgerPathKeys() {
|
|
44248
|
+
return Promise.resolve(this.db.scanLedger.pathKeys());
|
|
44249
|
+
}
|
|
43239
44250
|
recordScanned(entries) {
|
|
43240
44251
|
this.db.scanLedger.upsertEntries(entries);
|
|
43241
44252
|
return Promise.resolve();
|
|
@@ -43243,8 +44254,8 @@ var StandaloneDataGateway = class {
|
|
|
43243
44254
|
getRuleProbeVerdict(ruleKey) {
|
|
43244
44255
|
return Promise.resolve(this.db.ruleProbeCache.getVerdict(ruleKey));
|
|
43245
44256
|
}
|
|
43246
|
-
setRuleProbeVerdict(ruleKey, verdict,
|
|
43247
|
-
this.db.ruleProbeCache.setVerdict(ruleKey, verdict,
|
|
44257
|
+
setRuleProbeVerdict(ruleKey, verdict, worstProbeMs2) {
|
|
44258
|
+
this.db.ruleProbeCache.setVerdict(ruleKey, verdict, worstProbeMs2);
|
|
43248
44259
|
return Promise.resolve();
|
|
43249
44260
|
}
|
|
43250
44261
|
openAtRestKeysForPath(path) {
|
|
@@ -43323,11 +44334,15 @@ function resolveGatewayForConfig(config2, meta4) {
|
|
|
43323
44334
|
readStore: () => readStorePosture(config2.dbPath),
|
|
43324
44335
|
hostname: () => hostname6(),
|
|
43325
44336
|
now: () => Date.now(),
|
|
44337
|
+
// The mode THIS gateway enforces, from the attachment resolved above,
|
|
44338
|
+
// so the report cannot name a mode the forward paths are not using.
|
|
44339
|
+
attachmentMode: attachment.mode,
|
|
43326
44340
|
// The reporting build's identity, when the caller knows it (the plugin
|
|
43327
44341
|
// adapters do; an embedder or a test may not). Composed with the SAME
|
|
43328
44342
|
// policy store the sync child writes, so the block names the bundle
|
|
43329
|
-
// actually in force.
|
|
43330
|
-
// reporter
|
|
44343
|
+
// actually in force. The dependency key is omitted when no build is
|
|
44344
|
+
// known, and the reporter's optional call (`deps.pluginBlock?.()`)
|
|
44345
|
+
// then adds no block.
|
|
43331
44346
|
...meta4?.pluginBuild === void 0 ? {} : { pluginBlock: createPluginBlock(meta4.pluginBuild, store) }
|
|
43332
44347
|
})
|
|
43333
44348
|
});
|
|
@@ -43344,7 +44359,57 @@ function resolveDataGateway(config2, meta4, gatewayFactory = defaultGatewayFacto
|
|
|
43344
44359
|
}
|
|
43345
44360
|
|
|
43346
44361
|
// ../../packages/plugin-runtime/src/handle-session-start.ts
|
|
43347
|
-
import { randomUUID as
|
|
44362
|
+
import { randomUUID as randomUUID18 } from "crypto";
|
|
44363
|
+
|
|
44364
|
+
// ../../packages/plugin-runtime/src/mod-policy-sync.ts
|
|
44365
|
+
function modPolicyInputFromBundle(bundle) {
|
|
44366
|
+
const extra = bundle.rules ?? [];
|
|
44367
|
+
const rules = bundle.rulesComplete ? extra : extra.length > 0 ? [...bundledDetections().flatMap((pack) => pack.rules), ...extra] : void 0;
|
|
44368
|
+
return {
|
|
44369
|
+
rules,
|
|
44370
|
+
policies: bundle.policies,
|
|
44371
|
+
exceptionRuleIds: (bundle.exceptions ?? []).map((entry) => entry.ruleId)
|
|
44372
|
+
};
|
|
44373
|
+
}
|
|
44374
|
+
async function vetRulesForModFromGateway(rules, gateway, prober) {
|
|
44375
|
+
const bundledKeys = new Set(
|
|
44376
|
+
bundledDetections().flatMap((pack) => pack.rules).map(ruleProbeKey)
|
|
44377
|
+
);
|
|
44378
|
+
const shipped = [];
|
|
44379
|
+
const unproven = [];
|
|
44380
|
+
for (const rule of rules) {
|
|
44381
|
+
const key = ruleProbeKey(rule);
|
|
44382
|
+
if (key === void 0) shipped.push(rule);
|
|
44383
|
+
else if (bundledKeys.has(key)) {
|
|
44384
|
+
const verdict = await gateway.getRuleProbeVerdict(key).catch(() => void 0);
|
|
44385
|
+
if (verdict?.verdict !== "quarantined") shipped.push(rule);
|
|
44386
|
+
} else unproven.push(rule);
|
|
44387
|
+
}
|
|
44388
|
+
let isolated;
|
|
44389
|
+
const passed = new Set(
|
|
44390
|
+
await filterUnsafeRules(unproven, gateway, {
|
|
44391
|
+
prober: prober ?? {
|
|
44392
|
+
probe: (rule) => {
|
|
44393
|
+
isolated ??= createIsolatedScanner({ verified: [], unverified: [] });
|
|
44394
|
+
return isolated.probe(rule);
|
|
44395
|
+
}
|
|
44396
|
+
}
|
|
44397
|
+
})
|
|
44398
|
+
);
|
|
44399
|
+
await isolated?.close();
|
|
44400
|
+
const keep = /* @__PURE__ */ new Set([...shipped, ...passed]);
|
|
44401
|
+
return rules.filter((rule) => keep.has(rule));
|
|
44402
|
+
}
|
|
44403
|
+
async function syncModPolicySnapshot(gateway, dataDir2, prober) {
|
|
44404
|
+
try {
|
|
44405
|
+
const input2 = modPolicyInputFromBundle(await gateway.getPolicyBundle());
|
|
44406
|
+
const rules = input2.rules === void 0 ? void 0 : await vetRulesForModFromGateway(input2.rules, gateway, prober);
|
|
44407
|
+
writeModPolicySnapshot(dataDir2, buildModPolicySnapshot({ ...input2, rules }));
|
|
44408
|
+
} catch {
|
|
44409
|
+
}
|
|
44410
|
+
}
|
|
44411
|
+
|
|
44412
|
+
// ../../packages/plugin-runtime/src/handle-session-start.ts
|
|
43348
44413
|
var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
|
|
43349
44414
|
async function handleSessionStart(input2, config2 = loadConfig()) {
|
|
43350
44415
|
const silent = { staleBinaryNotice: null };
|
|
@@ -43386,6 +44451,9 @@ async function handleSessionStart(input2, config2 = loadConfig()) {
|
|
|
43386
44451
|
} catch {
|
|
43387
44452
|
}
|
|
43388
44453
|
}
|
|
44454
|
+
if (input2.tool === SOURCE_TOOL.ClaudeCode) {
|
|
44455
|
+
await syncModPolicySnapshot(gateway, config2.dataDir);
|
|
44456
|
+
}
|
|
43389
44457
|
if (offersMaintenance(gateway, "recordProjectFiles")) {
|
|
43390
44458
|
try {
|
|
43391
44459
|
if (resolved.sourceProjectId) {
|
|
@@ -43437,7 +44505,7 @@ async function recordConfigInventory(gateway, sessionId, cwd, homeDir) {
|
|
|
43437
44505
|
}
|
|
43438
44506
|
function buildConfigScanEvent(sessionId, scan2) {
|
|
43439
44507
|
return {
|
|
43440
|
-
id:
|
|
44508
|
+
id: randomUUID18(),
|
|
43441
44509
|
eventType: "config_scan",
|
|
43442
44510
|
startedAt: scan2.scannedAt,
|
|
43443
44511
|
parentId: sessionId,
|
|
@@ -43496,27 +44564,27 @@ function pluginBuild() {
|
|
|
43496
44564
|
|
|
43497
44565
|
// src/history/reconcile-trigger.ts
|
|
43498
44566
|
import { spawn as spawn4 } from "child_process";
|
|
43499
|
-
import { dirname as
|
|
44567
|
+
import { dirname as dirname7, join as join34 } from "path";
|
|
43500
44568
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
43501
44569
|
|
|
43502
44570
|
// src/history/tail.ts
|
|
43503
|
-
import { createHash as
|
|
44571
|
+
import { createHash as createHash8 } from "crypto";
|
|
43504
44572
|
import {
|
|
43505
|
-
closeSync as
|
|
43506
|
-
fstatSync
|
|
43507
|
-
mkdirSync as
|
|
43508
|
-
openSync as
|
|
43509
|
-
readFileSync as
|
|
43510
|
-
readSync
|
|
43511
|
-
writeFileSync as
|
|
44573
|
+
closeSync as closeSync2,
|
|
44574
|
+
fstatSync,
|
|
44575
|
+
mkdirSync as mkdirSync4,
|
|
44576
|
+
openSync as openSync2,
|
|
44577
|
+
readFileSync as readFileSync20,
|
|
44578
|
+
readSync,
|
|
44579
|
+
writeFileSync as writeFileSync7
|
|
43512
44580
|
} from "fs";
|
|
43513
|
-
import { join as
|
|
44581
|
+
import { join as join33 } from "path";
|
|
43514
44582
|
var SAFE_SESSION_ID = /^[A-Za-z0-9._-]+$/;
|
|
43515
44583
|
function safeSessionId(sessionId) {
|
|
43516
44584
|
if (SAFE_SESSION_ID.test(sessionId) && sessionId !== "." && sessionId !== "..") {
|
|
43517
44585
|
return sessionId;
|
|
43518
44586
|
}
|
|
43519
|
-
return
|
|
44587
|
+
return createHash8("sha256").update(sessionId).digest("hex");
|
|
43520
44588
|
}
|
|
43521
44589
|
|
|
43522
44590
|
// src/history/reconcile-trigger.ts
|
|
@@ -43526,8 +44594,8 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
|
|
|
43526
44594
|
try {
|
|
43527
44595
|
const marker = `${RECONCILE_MARKER_PREFIX}-${safeSessionId(sessionId)}`;
|
|
43528
44596
|
if (throttled(dataDir2, marker, RECONCILE_THROTTLE_MS)) return;
|
|
43529
|
-
const here =
|
|
43530
|
-
const child = spawn4(process.execPath, [
|
|
44597
|
+
const here = dirname7(fileURLToPath5(import.meta.url));
|
|
44598
|
+
const child = spawn4(process.execPath, [join34(here, "reconcile.js"), sessionId, transcriptPath], {
|
|
43531
44599
|
detached: true,
|
|
43532
44600
|
stdio: "ignore"
|
|
43533
44601
|
});
|
|
@@ -43537,9 +44605,9 @@ function triggerReconcile(dataDir2, sessionId, transcriptPath) {
|
|
|
43537
44605
|
}
|
|
43538
44606
|
|
|
43539
44607
|
// src/history/transcripts.ts
|
|
43540
|
-
import { closeSync as
|
|
44608
|
+
import { closeSync as closeSync3, openSync as openSync3, readdirSync as readdirSync4, readFileSync as readFileSync21, readSync as readSync2, statSync as statSync10 } from "fs";
|
|
43541
44609
|
import { homedir as homedir3 } from "os";
|
|
43542
|
-
import { join as
|
|
44610
|
+
import { join as join35 } from "path";
|
|
43543
44611
|
function isRecord(value) {
|
|
43544
44612
|
return typeof value === "object" && value !== null;
|
|
43545
44613
|
}
|
|
@@ -43550,13 +44618,13 @@ var SESSION_META_PEEK_BYTES = 4096;
|
|
|
43550
44618
|
function peekSessionOriginator(transcriptPath) {
|
|
43551
44619
|
let head;
|
|
43552
44620
|
try {
|
|
43553
|
-
const fd =
|
|
44621
|
+
const fd = openSync3(transcriptPath, "r");
|
|
43554
44622
|
try {
|
|
43555
44623
|
const buf = Buffer.allocUnsafe(SESSION_META_PEEK_BYTES);
|
|
43556
|
-
const bytesRead =
|
|
44624
|
+
const bytesRead = readSync2(fd, buf, 0, SESSION_META_PEEK_BYTES, 0);
|
|
43557
44625
|
head = buf.subarray(0, bytesRead).toString("utf8");
|
|
43558
44626
|
} finally {
|
|
43559
|
-
|
|
44627
|
+
closeSync3(fd);
|
|
43560
44628
|
}
|
|
43561
44629
|
} catch {
|
|
43562
44630
|
return void 0;
|
|
@@ -43578,17 +44646,17 @@ var DAY_MS5 = 24 * 60 * 60 * 1e3;
|
|
|
43578
44646
|
|
|
43579
44647
|
// src/protocol/marker.ts
|
|
43580
44648
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
43581
|
-
import { mkdirSync as
|
|
43582
|
-
import { join as
|
|
44649
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync22, renameSync as renameSync5, writeFileSync as writeFileSync8 } from "fs";
|
|
44650
|
+
import { join as join36 } from "path";
|
|
43583
44651
|
var MARKER_FILE = "protocol-marker";
|
|
43584
44652
|
function mintMarker() {
|
|
43585
44653
|
return randomBytes4(8).toString("hex");
|
|
43586
44654
|
}
|
|
43587
44655
|
function sessionProtocolMarker(dataDir2, sessionId) {
|
|
43588
44656
|
if (!sessionId) return mintMarker();
|
|
43589
|
-
const path =
|
|
44657
|
+
const path = join36(dataDir2, MARKER_FILE);
|
|
43590
44658
|
try {
|
|
43591
|
-
const stored = JSON.parse(
|
|
44659
|
+
const stored = JSON.parse(readFileSync22(path, "utf8"));
|
|
43592
44660
|
if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
|
|
43593
44661
|
return stored.marker;
|
|
43594
44662
|
}
|
|
@@ -43596,9 +44664,9 @@ function sessionProtocolMarker(dataDir2, sessionId) {
|
|
|
43596
44664
|
}
|
|
43597
44665
|
const marker = mintMarker();
|
|
43598
44666
|
try {
|
|
43599
|
-
|
|
43600
|
-
const tmp =
|
|
43601
|
-
|
|
44667
|
+
mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
|
|
44668
|
+
const tmp = join36(dataDir2, `${MARKER_FILE}.tmp`);
|
|
44669
|
+
writeFileSync8(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
|
|
43602
44670
|
renameSync5(tmp, path);
|
|
43603
44671
|
} catch {
|
|
43604
44672
|
}
|
|
@@ -43667,16 +44735,16 @@ function countFailOpen(base) {
|
|
|
43667
44735
|
}
|
|
43668
44736
|
|
|
43669
44737
|
// src/hooks/store-health.ts
|
|
43670
|
-
import { mkdirSync as
|
|
43671
|
-
import { dirname as
|
|
44738
|
+
import { mkdirSync as mkdirSync6, readFileSync as readFileSync23, writeFileSync as writeFileSync9 } from "fs";
|
|
44739
|
+
import { dirname as dirname8, join as join37 } from "path";
|
|
43672
44740
|
var STORE_REDIRECT_MARKER = "store-redirect-last-session";
|
|
43673
44741
|
function markerDirs(dataDir2) {
|
|
43674
|
-
return [dataDir2,
|
|
44742
|
+
return [dataDir2, dirname8(dataDir2)];
|
|
43675
44743
|
}
|
|
43676
44744
|
function alreadyClaimed(dirs, marker, sessionId) {
|
|
43677
44745
|
return dirs.some((dir) => {
|
|
43678
44746
|
try {
|
|
43679
|
-
return
|
|
44747
|
+
return readFileSync23(join37(dir, marker), "utf8") === sessionId;
|
|
43680
44748
|
} catch {
|
|
43681
44749
|
return false;
|
|
43682
44750
|
}
|
|
@@ -43685,8 +44753,8 @@ function alreadyClaimed(dirs, marker, sessionId) {
|
|
|
43685
44753
|
function recordClaim(dirs, marker, sessionId) {
|
|
43686
44754
|
for (const dir of dirs) {
|
|
43687
44755
|
try {
|
|
43688
|
-
|
|
43689
|
-
|
|
44756
|
+
mkdirSync6(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
44757
|
+
writeFileSync9(join37(dir, marker), sessionId, { mode: DATA_FILE_MODE });
|
|
43690
44758
|
return;
|
|
43691
44759
|
} catch {
|
|
43692
44760
|
}
|
|
@@ -43711,7 +44779,7 @@ function formatMode(mode) {
|
|
|
43711
44779
|
}
|
|
43712
44780
|
function warnIfStoreRedirected(config2, sessionId, write = (message2) => void process.stderr.write(message2)) {
|
|
43713
44781
|
try {
|
|
43714
|
-
const paths = symlinkedStorePaths(
|
|
44782
|
+
const paths = symlinkedStorePaths(dirname8(config2.dataDir));
|
|
43715
44783
|
if (paths.length === 0) return;
|
|
43716
44784
|
if (!sessionId) {
|
|
43717
44785
|
write(storeRedirectedMessage(paths));
|
|
@@ -43730,7 +44798,7 @@ function harnessVersion() {
|
|
|
43730
44798
|
const manifestPath = process.argv[2];
|
|
43731
44799
|
if (!manifestPath) return void 0;
|
|
43732
44800
|
try {
|
|
43733
|
-
const manifest = JSON.parse(
|
|
44801
|
+
const manifest = JSON.parse(readFileSync24(manifestPath, "utf8"));
|
|
43734
44802
|
return typeof manifest.version === "string" ? manifest.version : void 0;
|
|
43735
44803
|
} catch {
|
|
43736
44804
|
return void 0;
|