@akasecurity/ai-tc-codex 0.9.9 → 0.9.10
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 +3 -3
- package/scripts/apply-suppressions.js +1205 -676
- package/scripts/backfill.js +2054 -1250
- package/scripts/filescan.js +2053 -1249
- package/scripts/firstrun.js +1964 -1191
- package/scripts/history-sync.js +1882 -1029
- package/scripts/intro.js +365 -240
- package/scripts/onboard.js +1600 -1068
- package/scripts/post-tool-use.js +2054 -1248
- package/scripts/pre-tool-use.js +2054 -1250
- package/scripts/query.js +1963 -1190
- package/scripts/reconcile.js +1981 -1210
- package/scripts/remediate.js +2059 -1255
- package/scripts/scan-worker.js +278 -176
- package/scripts/session-start.js +2043 -1270
- package/scripts/start-light.js +368 -243
- package/scripts/stop.js +450 -317
- package/scripts/sync.js +17422 -2018
- package/scripts/user-prompt-submit.js +2064 -1257
package/scripts/post-tool-use.js
CHANGED
|
@@ -497,6 +497,7 @@ import { createHash as createHash4 } from "crypto";
|
|
|
497
497
|
// ../../packages/persistence/src/attached-derived.ts
|
|
498
498
|
import { rmSync } from "fs";
|
|
499
499
|
import { join } from "path";
|
|
500
|
+
var POLICY_CACHE_FILENAME = "policy-cache.json";
|
|
500
501
|
var ATTACHED_FORWARD_STATE_FILENAME = "attached-state.json";
|
|
501
502
|
var ATTACHED_FORWARD_DROPS_FILENAME = "attached-forward-drops.json";
|
|
502
503
|
|
|
@@ -597,6 +598,30 @@ var SQLITE_MIGRATIONS = [
|
|
|
597
598
|
{
|
|
598
599
|
tag: "0022_audit_inspection_ms",
|
|
599
600
|
sql: "ALTER TABLE `audit_events` ADD `inspection_ms` integer GENERATED ALWAYS AS (json_extract(attributes, '$.inspection_ms')) VIRTUAL;"
|
|
601
|
+
},
|
|
602
|
+
{
|
|
603
|
+
tag: "0023_secret_vault_user_authorized",
|
|
604
|
+
sql: "ALTER TABLE `secret_vault` ADD `user_authorized` integer DEFAULT 0 NOT NULL;"
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
tag: "0024_finding_resolution_key_created_index",
|
|
608
|
+
sql: "DROP INDEX IF EXISTS `idx_finding_resolution_key`;--> statement-breakpoint\nCREATE INDEX `idx_finding_resolution_key_created` ON `finding_resolution` (`finding_key`,`created_at`);"
|
|
609
|
+
},
|
|
610
|
+
{
|
|
611
|
+
tag: "0025_audit_capture_attribute_columns",
|
|
612
|
+
sql: "ALTER TABLE `audit_events` ADD `source_tool` text GENERATED ALWAYS AS (json_extract(attributes, '$.source_tool')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `repo` text GENERATED ALWAYS AS (json_extract(attributes, '$.repo')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `file_path` text GENERATED ALWAYS AS (json_extract(attributes, '$.file_path')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `tool_name` text GENERATED ALWAYS AS (json_extract(attributes, '$.tool_name')) VIRTUAL;"
|
|
613
|
+
},
|
|
614
|
+
{
|
|
615
|
+
tag: "0026_audit_llm_call_usage_columns",
|
|
616
|
+
sql: "ALTER TABLE `audit_events` ADD `service_tier` text GENERATED ALWAYS AS (json_extract(attributes, '$.service_tier')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_1h_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_1h_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `ephemeral_5m_input_tokens` integer GENERATED ALWAYS AS (json_extract(attributes, '$.ephemeral_5m_input_tokens')) VIRTUAL;--> statement-breakpoint\nALTER TABLE `audit_events` ADD `web_search_requests` integer GENERATED ALWAYS AS (json_extract(attributes, '$.web_search_requests')) VIRTUAL;"
|
|
617
|
+
},
|
|
618
|
+
{
|
|
619
|
+
tag: "0027_audit_llm_usage_index",
|
|
620
|
+
sql: "CREATE INDEX `idx_audit_llm_usage` ON `audit_events` (`started_at`,`root_session_id`,`provider`,`model`,`service_tier`,`input_tokens`,`output_tokens`,`cache_creation_input_tokens`,`cache_read_input_tokens`,`ephemeral_1h_input_tokens`,`ephemeral_5m_input_tokens`,`web_search_requests`) WHERE event_type = 'llm_call' AND attributes IS NOT NULL;"
|
|
621
|
+
},
|
|
622
|
+
{
|
|
623
|
+
tag: "0028_activity_session_probe_indexes",
|
|
624
|
+
sql: "CREATE INDEX `idx_audit_session_prompt` ON `audit_events` (`root_session_id`) WHERE event_type = 'prompt';--> statement-breakpoint\nCREATE INDEX `idx_audit_session_share` ON `audit_events` (`root_session_id`) WHERE event_type = 'share';--> statement-breakpoint\nCREATE INDEX `idx_audit_ended_at` ON `audit_events` (`ended_at`,`root_session_id`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\nCREATE INDEX `idx_audit_session_ended` ON `audit_events` (`root_session_id`,`ended_at`) WHERE ended_at IS NOT NULL;--> statement-breakpoint\n-- Expression index for the activity list's turns rollup: a live-captured\n-- session's turns are the DISTINCT `run_key` across its `llm_call` leaves, and\n-- carrying the extracted key in the index answers that count from the index\n-- alone instead of parsing every leaf's attribute bag. Written by hand, as\n-- 0013's `idx_audit_code_change_path` was: drizzle-kit cannot emit an\n-- expression containing a comma, so this index is not declared in sqlite.ts.\nCREATE INDEX `idx_audit_session_run_key` ON `audit_events` (`root_session_id`, json_extract(`attributes`, '$.run_key')) WHERE `event_type` = 'llm_call';\n"
|
|
600
625
|
}
|
|
601
626
|
];
|
|
602
627
|
|
|
@@ -22136,6 +22161,26 @@ var AttachTokenResponse = external_exports.union([
|
|
|
22136
22161
|
AttachTokenExpired,
|
|
22137
22162
|
external_exports.object({ status: printable(64) })
|
|
22138
22163
|
]);
|
|
22164
|
+
var DeviceCommandKind = external_exports.enum(["shares_rescan"]);
|
|
22165
|
+
var DeviceCommand = external_exports.object({
|
|
22166
|
+
id: printable(128).min(1),
|
|
22167
|
+
kind: DeviceCommandKind,
|
|
22168
|
+
issuedAt: printable(64).min(1),
|
|
22169
|
+
expiresAt: printable(64).min(1)
|
|
22170
|
+
}).strict();
|
|
22171
|
+
var DeviceCommandPollResponse = external_exports.object({ command: DeviceCommand.nullable() });
|
|
22172
|
+
var DeviceCommandFailureReason = external_exports.enum(["scan_failed", "no_projects", "expired"]);
|
|
22173
|
+
var DeviceCommandAckBody = external_exports.discriminatedUnion("outcome", [
|
|
22174
|
+
external_exports.object({
|
|
22175
|
+
outcome: external_exports.literal("reported"),
|
|
22176
|
+
projectsScanned: external_exports.number().int().nonnegative()
|
|
22177
|
+
}).strict(),
|
|
22178
|
+
external_exports.object({
|
|
22179
|
+
outcome: external_exports.literal("failed"),
|
|
22180
|
+
reason: DeviceCommandFailureReason,
|
|
22181
|
+
projectsScanned: external_exports.number().int().nonnegative()
|
|
22182
|
+
}).strict()
|
|
22183
|
+
]);
|
|
22139
22184
|
|
|
22140
22185
|
// ../../packages/schema/src/zod/registry.ts
|
|
22141
22186
|
var Namespace = external_exports.string().regex(/^[a-z][a-z0-9-]*$/);
|
|
@@ -22302,7 +22347,7 @@ var PackManifest = external_exports.object({
|
|
|
22302
22347
|
}).meta({ id: "PackManifest" });
|
|
22303
22348
|
|
|
22304
22349
|
// ../../packages/schema/src/zod/detection.ts
|
|
22305
|
-
var OriginEnum = external_exports.enum(["library"]).meta({ id: "OriginEnum" });
|
|
22350
|
+
var OriginEnum = external_exports.enum(["library", "custom"]).meta({ id: "OriginEnum" });
|
|
22306
22351
|
var DetectionFilterEnum = external_exports.enum(["all", "library", "custom", "customized", "updates"]);
|
|
22307
22352
|
var LibraryStateEnum = external_exports.enum(["new", "imported", "update"]).meta({ id: "LibraryStateEnum" });
|
|
22308
22353
|
var DetectionCounts = external_exports.object({
|
|
@@ -22439,14 +22484,17 @@ function optional2(key, parsed2, raw) {
|
|
|
22439
22484
|
function isStringArray(value) {
|
|
22440
22485
|
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
22441
22486
|
}
|
|
22487
|
+
var ORIGIN_VALUES = { library: true, custom: true };
|
|
22488
|
+
function resolveOrigin(origin) {
|
|
22489
|
+
return origin != null && Object.hasOwn(ORIGIN_VALUES, origin) ? origin : "library";
|
|
22490
|
+
}
|
|
22442
22491
|
function summaryToDetectionListItem(s) {
|
|
22443
22492
|
return {
|
|
22444
22493
|
id: `${s.namespace}/${s.packId}`,
|
|
22445
22494
|
name: s.name,
|
|
22446
22495
|
version: s.version,
|
|
22447
22496
|
enabled: s.enabled,
|
|
22448
|
-
origin:
|
|
22449
|
-
// v1: every installed pack is library origin
|
|
22497
|
+
origin: resolveOrigin(s.origin),
|
|
22450
22498
|
namespace: s.namespace,
|
|
22451
22499
|
packId: s.packId,
|
|
22452
22500
|
ruleCount: s.ruleCount,
|
|
@@ -22498,7 +22546,7 @@ function rowToDetectionDetail(row, findingsLast30d, update) {
|
|
|
22498
22546
|
name: row.name,
|
|
22499
22547
|
version: row.version,
|
|
22500
22548
|
enabled: row.enabled,
|
|
22501
|
-
origin:
|
|
22549
|
+
origin: resolveOrigin(row.origin),
|
|
22502
22550
|
namespace: row.namespace,
|
|
22503
22551
|
packId: row.packId,
|
|
22504
22552
|
ruleCount: row.rules.length,
|
|
@@ -22518,16 +22566,20 @@ function splitDetectionId(id) {
|
|
|
22518
22566
|
}
|
|
22519
22567
|
function buildDetectionsList(summaries, query) {
|
|
22520
22568
|
const withUpdate = summaries.filter((s) => s.latestVersion != null);
|
|
22569
|
+
const originOf = (s) => resolveOrigin(s.origin);
|
|
22521
22570
|
const counts = {
|
|
22522
22571
|
all: summaries.length,
|
|
22523
|
-
library: summaries.length,
|
|
22524
|
-
|
|
22525
|
-
|
|
22572
|
+
library: summaries.filter((s) => originOf(s) === "library").length,
|
|
22573
|
+
custom: summaries.filter((s) => originOf(s) === "custom").length,
|
|
22574
|
+
// No origin member produces this, so it is 0 BY CONSTRUCTION rather than by
|
|
22575
|
+
// omission: `customized` would mean a LIBRARY pack whose rules were edited in
|
|
22576
|
+
// place, and that state does not exist — editing a library pack forks it. See
|
|
22577
|
+
// OriginEnum.
|
|
22526
22578
|
customized: 0,
|
|
22527
22579
|
updates: withUpdate.length
|
|
22528
22580
|
};
|
|
22529
22581
|
const filter = query.filter;
|
|
22530
|
-
let filtered = filter === "custom"
|
|
22582
|
+
let filtered = filter === "customized" ? [] : filter === "custom" ? summaries.filter((s) => originOf(s) === "custom") : filter === "library" ? summaries.filter((s) => originOf(s) === "library") : filter === "updates" ? [...withUpdate] : [...summaries];
|
|
22531
22583
|
if (query.q) {
|
|
22532
22584
|
const q = query.q.toLowerCase();
|
|
22533
22585
|
filtered = filtered.filter(
|
|
@@ -22607,8 +22659,9 @@ var Event = external_exports.object({
|
|
|
22607
22659
|
metadata: EventMetadata.optional()
|
|
22608
22660
|
}).meta({ id: "Event" });
|
|
22609
22661
|
var IngestEvent = Event.meta({ id: "IngestEvent" });
|
|
22662
|
+
var INGEST_BATCH_MAX = 100;
|
|
22610
22663
|
var IngestBatch = external_exports.object({
|
|
22611
|
-
events: external_exports.array(IngestEvent).min(1).max(
|
|
22664
|
+
events: external_exports.array(IngestEvent).min(1).max(INGEST_BATCH_MAX),
|
|
22612
22665
|
// Dedup policy for this batch. Id-dedup ALWAYS applies. 'content-hash'
|
|
22613
22666
|
// additionally rejects any event whose contentHash the store has already
|
|
22614
22667
|
// recorded — for re-runnable bulk ingest (worktree scan, transcript
|
|
@@ -23164,375 +23217,11 @@ var PatchInstalledPackRequest = external_exports.object({
|
|
|
23164
23217
|
message: "At least one field must be provided"
|
|
23165
23218
|
}).meta({ id: "PatchInstalledPackRequest" });
|
|
23166
23219
|
|
|
23167
|
-
// ../../packages/schema/src/zod/vault.ts
|
|
23168
|
-
var POINTER_FORMAT_VERSION = 2;
|
|
23169
|
-
var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
|
|
23170
|
-
var POINTER_TOKEN_PATTERN = new RegExp(
|
|
23171
|
-
`\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
|
|
23172
|
-
);
|
|
23173
|
-
var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
|
|
23174
|
-
function pointerTokenScanner() {
|
|
23175
|
-
return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
|
|
23176
|
-
}
|
|
23177
|
-
var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
|
|
23178
|
-
var ParsedPointer = external_exports.object({
|
|
23179
|
-
category: DetectionCategory,
|
|
23180
|
-
keyVersion: external_exports.number().int().positive(),
|
|
23181
|
-
pointerId: external_exports.string(),
|
|
23182
|
-
tag: external_exports.string()
|
|
23183
|
-
});
|
|
23184
|
-
var VaultEntry = external_exports.object({
|
|
23185
|
-
pointerId: external_exports.string(),
|
|
23186
|
-
// The keyed HMAC of the raw value under `exception.key`, and the epoch it was
|
|
23187
|
-
// derived under. This is what a reveal-to-model grant matches on, and it rotates
|
|
23188
|
-
// independently of the vault encryption key below.
|
|
23189
|
-
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
23190
|
-
fingerprintKeyVersion: external_exports.number().int().positive(),
|
|
23191
|
-
// The vault-key epoch this row's ciphertext was sealed under.
|
|
23192
|
-
keyVersion: external_exports.number().int().positive(),
|
|
23193
|
-
// Fixed at first mint and never updated: the same value detected later under a
|
|
23194
|
-
// different rule's category keeps the category it was minted with, so one
|
|
23195
|
-
// value always produces exactly one wire token.
|
|
23196
|
-
category: DetectionCategory,
|
|
23197
|
-
ruleId: external_exports.string(),
|
|
23198
|
-
// Partial-reveal preview for badges and listings. Never the raw value.
|
|
23199
|
-
maskedMatch: external_exports.string(),
|
|
23200
|
-
provider: external_exports.string().optional(),
|
|
23201
|
-
ciphertext: external_exports.string(),
|
|
23202
|
-
nonce: external_exports.string(),
|
|
23203
|
-
authTag: external_exports.string(),
|
|
23204
|
-
// How many times this value has been detected on this machine — the reuse
|
|
23205
|
-
// signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
|
|
23206
|
-
occurrenceCount: external_exports.number().int().nonnegative(),
|
|
23207
|
-
firstSeen: external_exports.string(),
|
|
23208
|
-
lastSeen: external_exports.string()
|
|
23209
|
-
});
|
|
23210
|
-
var PointerDescriptor = external_exports.object({
|
|
23211
|
-
category: DetectionCategory,
|
|
23212
|
-
provider: external_exports.string().optional(),
|
|
23213
|
-
maskedMatch: external_exports.string(),
|
|
23214
|
-
occurrences: external_exports.number().int().nonnegative(),
|
|
23215
|
-
firstSeen: external_exports.string(),
|
|
23216
|
-
lastSeen: external_exports.string()
|
|
23217
|
-
});
|
|
23218
|
-
var PointerIdentity = external_exports.object({
|
|
23219
|
-
ruleId: external_exports.string(),
|
|
23220
|
-
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
23221
|
-
fingerprintKeyVersion: external_exports.number().int().positive()
|
|
23222
|
-
});
|
|
23223
|
-
var DetokenizeTarget = external_exports.enum(["human", "model"]);
|
|
23224
|
-
var VaultDerefReason = external_exports.enum([
|
|
23225
|
-
"display",
|
|
23226
|
-
"explicit-reveal",
|
|
23227
|
-
"view-render",
|
|
23228
|
-
"model-input",
|
|
23229
|
-
"remediation",
|
|
23230
|
-
"purge"
|
|
23231
|
-
]);
|
|
23232
|
-
var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
|
|
23233
|
-
var VaultDeref = external_exports.object({
|
|
23234
|
-
id: external_exports.guid(),
|
|
23235
|
-
pointerId: external_exports.string(),
|
|
23236
|
-
at: external_exports.string(),
|
|
23237
|
-
target: DetokenizeTarget,
|
|
23238
|
-
reason: VaultDerefReason,
|
|
23239
|
-
outcome: VaultDerefOutcome,
|
|
23240
|
-
// Present only on a model-target crossing that a reveal grant authorized.
|
|
23241
|
-
grantId: external_exports.string().optional(),
|
|
23242
|
-
// How many pointers ONE batched render resolved. 1 for unbatched rows. Named
|
|
23243
|
-
// apart from VaultEntry.occurrenceCount, which counts detections of a value.
|
|
23244
|
-
pointerCount: external_exports.number().int().positive().default(1)
|
|
23245
|
-
});
|
|
23246
|
-
var VaultSightingKind = external_exports.enum([
|
|
23247
|
-
"prompt",
|
|
23248
|
-
"tool-input",
|
|
23249
|
-
"tool-output",
|
|
23250
|
-
"file",
|
|
23251
|
-
"transcript"
|
|
23252
|
-
]);
|
|
23253
|
-
var VaultSighting = external_exports.object({
|
|
23254
|
-
location: external_exports.string(),
|
|
23255
|
-
kind: VaultSightingKind,
|
|
23256
|
-
firstSeen: external_exports.string(),
|
|
23257
|
-
lastSeen: external_exports.string()
|
|
23258
|
-
});
|
|
23259
|
-
var VaultInventoryEntry = external_exports.object({
|
|
23260
|
-
pointerId: external_exports.string(),
|
|
23261
|
-
category: DetectionCategory,
|
|
23262
|
-
provider: external_exports.string().optional(),
|
|
23263
|
-
maskedMatch: external_exports.string(),
|
|
23264
|
-
occurrences: external_exports.number().int().nonnegative(),
|
|
23265
|
-
firstSeen: external_exports.string(),
|
|
23266
|
-
lastSeen: external_exports.string(),
|
|
23267
|
-
// The active reveal-to-model grant covering this value, when one exists —
|
|
23268
|
-
// the inventory badges it, the row links to revocation.
|
|
23269
|
-
revealGrantId: external_exports.string().nullable(),
|
|
23270
|
-
sightings: external_exports.array(VaultSighting)
|
|
23271
|
-
});
|
|
23272
|
-
var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
|
|
23273
|
-
var DEFAULT_VAULT_DEREFS_LIMIT = 50;
|
|
23274
|
-
var MAX_VAULT_PAGE_LIMIT = 200;
|
|
23275
|
-
var ListVaultInventoryQuery = external_exports.object({
|
|
23276
|
-
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23277
|
-
// Opaque; names the last row of the page just served.
|
|
23278
|
-
cursor: external_exports.string().optional()
|
|
23279
|
-
});
|
|
23280
|
-
var ListVaultInventoryResponse = external_exports.object({
|
|
23281
|
-
// Vaulted values across the whole store, not just this page — cursor-
|
|
23282
|
-
// independent, so paging never changes what the count claims.
|
|
23283
|
-
totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
|
|
23284
|
-
items: external_exports.array(VaultInventoryEntry),
|
|
23285
|
-
// `null` once the last page is reached.
|
|
23286
|
-
nextCursor: external_exports.string().nullable()
|
|
23287
|
-
});
|
|
23288
|
-
var ListVaultReuseQuery = external_exports.object({
|
|
23289
|
-
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23290
|
-
cursor: external_exports.string().optional()
|
|
23291
|
-
});
|
|
23292
|
-
var ListVaultReuseResponse = external_exports.object({
|
|
23293
|
-
// Reused values across the whole store — the number the section's claim
|
|
23294
|
-
// ("values detected in more than one place") is about.
|
|
23295
|
-
totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
|
|
23296
|
-
items: external_exports.array(VaultInventoryEntry),
|
|
23297
|
-
nextCursor: external_exports.string().nullable()
|
|
23298
|
-
});
|
|
23299
|
-
var ListVaultDerefsQuery = external_exports.object({
|
|
23300
|
-
// Include the batched, high-volume reasons (display, view-render). Omitted
|
|
23301
|
-
// hides them and counts them into `hiddenBatched` instead, so the model
|
|
23302
|
-
// crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
|
|
23303
|
-
// over a Server Action, which preserves the type, never as a URL param.
|
|
23304
|
-
includeBatched: external_exports.boolean().optional(),
|
|
23305
|
-
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23306
|
-
cursor: external_exports.string().optional()
|
|
23307
|
-
});
|
|
23308
|
-
var ListVaultDerefsResponse = external_exports.object({
|
|
23309
|
-
items: external_exports.array(VaultDeref),
|
|
23310
|
-
nextCursor: external_exports.string().nullable(),
|
|
23311
|
-
// Display/view-render rows the query hid, over the WHOLE trail rather than
|
|
23312
|
-
// this page — it is the count the "N hidden" line and its toggle speak for.
|
|
23313
|
-
// Always 0 when `includeBatched` was set, since nothing was hidden.
|
|
23314
|
-
hiddenBatched: external_exports.number().int().nonnegative()
|
|
23315
|
-
});
|
|
23316
|
-
var VaultKeyCustody = external_exports.string();
|
|
23317
|
-
var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
|
|
23318
|
-
var VAULT_CONSENT_VERSION = 1;
|
|
23319
|
-
var VaultConsent = external_exports.object({
|
|
23320
|
-
acknowledgedAt: external_exports.iso.datetime(),
|
|
23321
|
-
version: external_exports.number().int().positive()
|
|
23322
|
-
});
|
|
23323
|
-
|
|
23324
|
-
// ../../packages/schema/src/zod/local.ts
|
|
23325
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION = 6;
|
|
23326
|
-
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23327
|
-
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23328
|
-
var ControlPlaneConnection = external_exports.object({
|
|
23329
|
-
endpoint: external_exports.string().min(1),
|
|
23330
|
-
// Display name for the deployment, shown instead of the raw endpoint.
|
|
23331
|
-
label: external_exports.string().min(1).optional(),
|
|
23332
|
-
attachedAt: external_exports.iso.datetime()
|
|
23333
|
-
}).meta({ id: "ControlPlaneConnection" });
|
|
23334
|
-
var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
|
|
23335
|
-
var HistoricalAccess = external_exports.enum(["full", "session-only"]);
|
|
23336
|
-
var ModelJudgeConsent = external_exports.object({
|
|
23337
|
-
acknowledgedAt: external_exports.iso.datetime(),
|
|
23338
|
-
payloadVersion: external_exports.number().int().positive()
|
|
23339
|
-
});
|
|
23340
|
-
var HistorySyncConsent = external_exports.object({
|
|
23341
|
-
acknowledgedAt: external_exports.iso.datetime(),
|
|
23342
|
-
payloadVersion: external_exports.number().int().positive(),
|
|
23343
|
-
endpoint: external_exports.string()
|
|
23344
|
-
});
|
|
23345
|
-
var WorkspaceSettings = external_exports.object({
|
|
23346
|
-
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23347
|
-
runMode: RunMode.default("standalone"),
|
|
23348
|
-
// Present only while attached; a detach clears it. Its presence is what makes
|
|
23349
|
-
// `runMode: 'attached'` mean anything — see isAttached.
|
|
23350
|
-
controlPlane: ControlPlaneConnection.optional(),
|
|
23351
|
-
policy: SimpleDetectionPolicy.default("redact"),
|
|
23352
|
-
// Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
|
|
23353
|
-
historicalAccess: HistoricalAccess.default("session-only"),
|
|
23354
|
-
// In-place egress extraction on the scan paths; disable to stop all Data
|
|
23355
|
-
// Shares writes.
|
|
23356
|
-
dataSharesInPlace: external_exports.boolean().default(true),
|
|
23357
|
-
// Consent to keep a RECOVERABLE encrypted copy of detected values in the local
|
|
23358
|
-
// vault, instead of destroying them. Absent by default: this is a custody
|
|
23359
|
-
// change from one-way redaction, so it is never an assumed grant on upgrade.
|
|
23360
|
-
// Revoking stops future vaulting; it does not erase what is already stored —
|
|
23361
|
-
// purging the vault is the eraser.
|
|
23362
|
-
vaultConsent: VaultConsent.optional(),
|
|
23363
|
-
// Where the vault master key lives.
|
|
23364
|
-
vaultKeyCustody: VaultKeyCustody.default("file"),
|
|
23365
|
-
// How a pointer renders in assistant prose on screen (see VaultInlineReveal).
|
|
23366
|
-
vaultInlineReveal: VaultInlineReveal.default("masked"),
|
|
23367
|
-
// Absent until /aka:setup completes; its presence is what "onboarded" means.
|
|
23368
|
-
onboardedAt: external_exports.iso.datetime().optional(),
|
|
23369
|
-
// Records that the user consented to sending findings to the model API for
|
|
23370
|
-
// the /aka:setup judge, along with the payload-shape version they agreed to.
|
|
23371
|
-
// Absent until granted; a stale payloadVersion means the consent no longer
|
|
23372
|
-
// covers the current payload and must be re-granted.
|
|
23373
|
-
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23374
|
-
// Records that the user consented to sending the activity already recorded on
|
|
23375
|
-
// this machine to the deployment it is attached to, along with the payload
|
|
23376
|
-
// shape and the endpoint they agreed to. Absent until granted, and a grant for
|
|
23377
|
-
// a different endpoint or an older payload no longer counts.
|
|
23378
|
-
historySyncConsent: HistorySyncConsent.optional()
|
|
23379
|
-
});
|
|
23380
|
-
function defaultWorkspaceSettings() {
|
|
23381
|
-
return WorkspaceSettings.parse({});
|
|
23382
|
-
}
|
|
23383
|
-
function isAttached(settings) {
|
|
23384
|
-
return settings.runMode === "attached" && settings.controlPlane !== void 0;
|
|
23385
|
-
}
|
|
23386
|
-
function toInventoryRow(input2, id, now) {
|
|
23387
|
-
return {
|
|
23388
|
-
id,
|
|
23389
|
-
objectType: input2.objectType,
|
|
23390
|
-
location: input2.location ?? null,
|
|
23391
|
-
title: input2.title ?? null,
|
|
23392
|
-
hostId: input2.hostId ?? null,
|
|
23393
|
-
attributes: JSON.stringify(input2.attributes),
|
|
23394
|
-
firstSeen: now,
|
|
23395
|
-
lastSeen: now
|
|
23396
|
-
};
|
|
23397
|
-
}
|
|
23398
|
-
function toSourceProjectRow(input2, id, now) {
|
|
23399
|
-
return {
|
|
23400
|
-
id,
|
|
23401
|
-
url: input2.url,
|
|
23402
|
-
name: input2.name ?? null,
|
|
23403
|
-
attributes: JSON.stringify(input2.attributes),
|
|
23404
|
-
firstSeen: now,
|
|
23405
|
-
lastSeen: now
|
|
23406
|
-
};
|
|
23407
|
-
}
|
|
23408
|
-
function toAuditEventRow(input2) {
|
|
23409
|
-
return {
|
|
23410
|
-
id: input2.id,
|
|
23411
|
-
parentId: input2.parentId ?? null,
|
|
23412
|
-
rootSessionId: input2.rootSessionId ?? null,
|
|
23413
|
-
eventType: input2.eventType,
|
|
23414
|
-
hostId: input2.hostId ?? null,
|
|
23415
|
-
harnessId: input2.harnessId ?? null,
|
|
23416
|
-
sourceProjectId: input2.sourceProjectId ?? null,
|
|
23417
|
-
startedAt: isoToEpochMillis(input2.startedAt),
|
|
23418
|
-
endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
|
|
23419
|
-
severity: input2.severity ?? null,
|
|
23420
|
-
priority: input2.priority ?? null,
|
|
23421
|
-
content: input2.content ?? null,
|
|
23422
|
-
contentHash: input2.contentHash ?? null,
|
|
23423
|
-
attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
|
|
23424
|
-
};
|
|
23425
|
-
}
|
|
23426
|
-
function toClassifiedDataRow(input2, id) {
|
|
23427
|
-
return {
|
|
23428
|
-
id,
|
|
23429
|
-
class: input2.class,
|
|
23430
|
-
label: input2.label ?? null,
|
|
23431
|
-
attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
|
|
23432
|
-
};
|
|
23433
|
-
}
|
|
23434
|
-
function toInspectionDefinitionRow(input2, id) {
|
|
23435
|
-
return {
|
|
23436
|
-
id,
|
|
23437
|
-
ruleId: input2.ruleId,
|
|
23438
|
-
name: input2.name,
|
|
23439
|
-
category: input2.category,
|
|
23440
|
-
severity: input2.severity,
|
|
23441
|
-
definition: input2.definition,
|
|
23442
|
-
version: input2.version
|
|
23443
|
-
};
|
|
23444
|
-
}
|
|
23445
|
-
function toInspectionFindingRow(input2) {
|
|
23446
|
-
return {
|
|
23447
|
-
id: input2.id,
|
|
23448
|
-
auditEventId: input2.auditEventId,
|
|
23449
|
-
inspectionDefinitionId: input2.inspectionDefinitionId,
|
|
23450
|
-
classifiedDataId: input2.classifiedDataId ?? null,
|
|
23451
|
-
spanStart: input2.span.start,
|
|
23452
|
-
spanEnd: input2.span.end,
|
|
23453
|
-
maskedMatch: input2.maskedMatch,
|
|
23454
|
-
actionTaken: input2.actionTaken,
|
|
23455
|
-
confidence: input2.confidence,
|
|
23456
|
-
findingKey: input2.findingKey ?? null,
|
|
23457
|
-
firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
|
|
23458
|
-
};
|
|
23459
|
-
}
|
|
23460
|
-
function toCaptureAttributes(event) {
|
|
23461
|
-
const metadata = event.metadata;
|
|
23462
|
-
return {
|
|
23463
|
-
source_tool: event.sourceTool,
|
|
23464
|
-
...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
|
|
23465
|
-
...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
|
|
23466
|
-
...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
|
|
23467
|
-
...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
|
|
23468
|
-
...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
|
|
23469
|
-
...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
|
|
23470
|
-
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23471
|
-
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23472
|
-
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
23473
|
-
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23474
|
-
// has ever populated either), but every legacy metadata key still rides
|
|
23475
|
-
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23476
|
-
// `.catchall(z.unknown())` carries the long tail.
|
|
23477
|
-
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23478
|
-
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
23479
|
-
};
|
|
23480
|
-
}
|
|
23481
|
-
function captureDefinitionVersion(finding) {
|
|
23482
|
-
return `capture/${finding.category}/${finding.severity}`;
|
|
23483
|
-
}
|
|
23484
|
-
function toCaptureDefinitionInput(finding) {
|
|
23485
|
-
return {
|
|
23486
|
-
ruleId: finding.ruleId,
|
|
23487
|
-
version: captureDefinitionVersion(finding),
|
|
23488
|
-
name: finding.ruleId,
|
|
23489
|
-
category: finding.category,
|
|
23490
|
-
severity: finding.severity,
|
|
23491
|
-
definition: JSON.stringify({ ruleId: finding.ruleId })
|
|
23492
|
-
};
|
|
23493
|
-
}
|
|
23494
|
-
|
|
23495
|
-
// ../../packages/schema/src/zod/managed.ts
|
|
23496
|
-
var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
|
|
23497
|
-
var MANAGED_SETTINGS_SPEC_VERSION = 1;
|
|
23498
|
-
var ManagedSettingKey = external_exports.enum([
|
|
23499
|
-
"runMode",
|
|
23500
|
-
"historicalAccess",
|
|
23501
|
-
"vaultConsent",
|
|
23502
|
-
"vaultKeyCustody",
|
|
23503
|
-
"vaultInlineReveal",
|
|
23504
|
-
"modelJudgeConsent",
|
|
23505
|
-
"dataSharesInPlace"
|
|
23506
|
-
]).meta({ id: "ManagedSettingKey" });
|
|
23507
|
-
var ManagedSettingsValues = external_exports.object({
|
|
23508
|
-
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
23509
|
-
controlPlane: external_exports.object({
|
|
23510
|
-
endpoint: external_exports.string().min(1),
|
|
23511
|
-
label: external_exports.string().min(1).optional()
|
|
23512
|
-
}).optional(),
|
|
23513
|
-
historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
|
|
23514
|
-
vaultConsent: external_exports.boolean().optional(),
|
|
23515
|
-
vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
|
|
23516
|
-
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23517
|
-
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23518
|
-
dataSharesInPlace: external_exports.boolean().optional()
|
|
23519
|
-
}).meta({ id: "ManagedSettingsValues" });
|
|
23520
|
-
var ManagedSettings = external_exports.object({
|
|
23521
|
-
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
23522
|
-
// Shown on every locked control, so the user can tell an administrative
|
|
23523
|
-
// decision from a bug. Absent renders as a generic "your organization".
|
|
23524
|
-
organization: external_exports.string().min(1).optional(),
|
|
23525
|
-
// What the administrator pinned.
|
|
23526
|
-
values: ManagedSettingsValues.default({}),
|
|
23527
|
-
// Which of those the user may not change. A key here with no matching value
|
|
23528
|
-
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23529
|
-
// the user may still override. The two are separable on purpose.
|
|
23530
|
-
lockedFields: external_exports.array(ManagedSettingKey).default([])
|
|
23531
|
-
}).meta({ id: "ManagedSettings" });
|
|
23532
|
-
|
|
23533
23220
|
// ../../packages/schema/src/zod/policy.ts
|
|
23534
23221
|
var PolicyScope = external_exports.enum(["global", "repo", "user"]).meta({ id: "PolicyScope" });
|
|
23535
23222
|
var PolicyTarget = external_exports.union([external_exports.object({ ruleId: external_exports.string() }), external_exports.object({ category: DetectionCategory })]).meta({ id: "PolicyTarget" });
|
|
23223
|
+
var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
|
|
23224
|
+
var PolicyProvenance = external_exports.enum(["builtin", "authored"]).meta({ id: "PolicyProvenance" });
|
|
23536
23225
|
var Policy = external_exports.object({
|
|
23537
23226
|
id: external_exports.guid(),
|
|
23538
23227
|
scope: PolicyScope,
|
|
@@ -23542,7 +23231,27 @@ var Policy = external_exports.object({
|
|
|
23542
23231
|
customKeywords: external_exports.array(external_exports.string()).optional(),
|
|
23543
23232
|
// Display name — optional so older policy rows without name still parse.
|
|
23544
23233
|
// Added for the findings API (policy.name column migration).
|
|
23545
|
-
name: external_exports.string().optional()
|
|
23234
|
+
name: external_exports.string().optional(),
|
|
23235
|
+
// Whether an AUTHORED policy governs this row's target — not a claim about
|
|
23236
|
+
// which row this is. A producer that collapses several rows onto one target
|
|
23237
|
+
// must carry the marker onto whichever row survives, or the collapse decides
|
|
23238
|
+
// the answer; a survivor may therefore be a built-in expansion still marked
|
|
23239
|
+
// 'authored' because an authored sibling targeted the same thing.
|
|
23240
|
+
// Optional so an older producer — and an older on-disk cache — still parses;
|
|
23241
|
+
// absent reads as 'builtin', which is the behaviour that predates the field.
|
|
23242
|
+
//
|
|
23243
|
+
// Deliberately NOT `kind`/PolicyKind: that name and that enum answer which
|
|
23244
|
+
// built-in archetype catalog entry a policy is, which every catalog surface
|
|
23245
|
+
// reads and which a caller may state. This one is a statement the PRODUCER
|
|
23246
|
+
// of a bundle makes about a row, and only the bundle builder ever stamps it
|
|
23247
|
+
// — the CRUD routes neither accept nor set it.
|
|
23248
|
+
//
|
|
23249
|
+
// A device consumes this in exactly one direction: an 'authored' policy
|
|
23250
|
+
// arriving from a control plane marks the rules it targets as not
|
|
23251
|
+
// locally re-assignable. That can only ever ADD a refusal, never relax one,
|
|
23252
|
+
// which is what makes it safe to honour from an unsigned cache — the same
|
|
23253
|
+
// test `prohibitedModels` passes and `reversibleRuleIds` fails.
|
|
23254
|
+
provenance: PolicyProvenance.optional()
|
|
23546
23255
|
}).meta({ id: "Policy" });
|
|
23547
23256
|
var PolicyBundle = external_exports.object({
|
|
23548
23257
|
version: external_exports.string(),
|
|
@@ -23594,6 +23303,12 @@ var PolicyBundle = external_exports.object({
|
|
|
23594
23303
|
customKeywords: external_exports.array(external_exports.string()),
|
|
23595
23304
|
fetchedAt: external_exports.iso.datetime()
|
|
23596
23305
|
}).meta({ id: "PolicyBundle" });
|
|
23306
|
+
var POLICY_BUNDLE_SHAPE_ID = [
|
|
23307
|
+
...Object.keys(PolicyBundle.shape),
|
|
23308
|
+
...Object.keys(Policy.shape).map((key) => `policies.${key}`),
|
|
23309
|
+
...PolicyTarget.options.flatMap((member) => "shape" in member ? Object.keys(member.shape) : []).map((key) => `policies.target.${key}`),
|
|
23310
|
+
...Object.keys(ExceptionBundleEntry.shape).map((key) => `exceptions.${key}`)
|
|
23311
|
+
].sort().join(",");
|
|
23597
23312
|
var OBSERVE_ONLY_CATEGORIES = ["config"];
|
|
23598
23313
|
var ENFORCEABLE_CATEGORIES = DetectionCategory.options.filter((c) => !OBSERVE_ONLY_CATEGORIES.includes(c));
|
|
23599
23314
|
var CATEGORY_PEAK_SEVERITY = {
|
|
@@ -23614,9 +23329,11 @@ function severityFloorPolicy(category) {
|
|
|
23614
23329
|
const peak = CATEGORY_PEAK_SEVERITY[category];
|
|
23615
23330
|
return peak === "critical" || peak === "high" ? "warn" : "monitor";
|
|
23616
23331
|
}
|
|
23617
|
-
var PolicyKind = external_exports.enum(["builtin", "custom"]).meta({ id: "PolicyKind" });
|
|
23618
23332
|
var KNOWN_BUILTIN_IDS = ["monitor", "warn", "redact", "vault", "block"];
|
|
23619
23333
|
var BuiltinPolicyId = external_exports.enum(KNOWN_BUILTIN_IDS).meta({ id: "BuiltinPolicyId" });
|
|
23334
|
+
var RedactFallback = BuiltinPolicyId.extract(["monitor", "warn", "block"]).meta({
|
|
23335
|
+
id: "RedactFallback"
|
|
23336
|
+
});
|
|
23620
23337
|
var BUILTIN_ORDER = KNOWN_BUILTIN_IDS;
|
|
23621
23338
|
var BUILTIN_POLICY_SPECS = {
|
|
23622
23339
|
monitor: {
|
|
@@ -23653,6 +23370,42 @@ var BUILTIN_POLICY_SPECS = {
|
|
|
23653
23370
|
function builtinPolicyToAction(id) {
|
|
23654
23371
|
return BUILTIN_POLICY_SPECS[id].action;
|
|
23655
23372
|
}
|
|
23373
|
+
var PALETTE_WEAKEST_FIRST = [
|
|
23374
|
+
...new Set(KNOWN_BUILTIN_IDS.map(builtinPolicyToAction))
|
|
23375
|
+
];
|
|
23376
|
+
var BELOW_PALETTE = ACTION_TAKEN_KEYS.filter(
|
|
23377
|
+
(action) => !PALETTE_WEAKEST_FIRST.includes(action)
|
|
23378
|
+
);
|
|
23379
|
+
var ACTION_STRENGTH_ORDER = [
|
|
23380
|
+
...BELOW_PALETTE,
|
|
23381
|
+
...PALETTE_WEAKEST_FIRST
|
|
23382
|
+
];
|
|
23383
|
+
function actionRank(action) {
|
|
23384
|
+
return ACTION_STRENGTH_ORDER.indexOf(action);
|
|
23385
|
+
}
|
|
23386
|
+
function isActionAtLeast(action, floor) {
|
|
23387
|
+
return actionRank(action) >= actionRank(floor);
|
|
23388
|
+
}
|
|
23389
|
+
function strongerAction(a, b) {
|
|
23390
|
+
return actionRank(a) >= actionRank(b) ? a : b;
|
|
23391
|
+
}
|
|
23392
|
+
function weakestBuiltinAtLeast(floor) {
|
|
23393
|
+
return KNOWN_BUILTIN_IDS.find((id) => isActionAtLeast(builtinPolicyToAction(id), floor)) ?? "block";
|
|
23394
|
+
}
|
|
23395
|
+
var PackPolicyFloor = external_exports.object({
|
|
23396
|
+
/**
|
|
23397
|
+
* The weakest archetype the device may assign. Stated as a BuiltinPolicyId
|
|
23398
|
+
* rather than a raw ActionTaken because that is the vocabulary the user
|
|
23399
|
+
* picks from — a floor a UI cannot name is one it cannot explain.
|
|
23400
|
+
*/
|
|
23401
|
+
floor: BuiltinPolicyId,
|
|
23402
|
+
/**
|
|
23403
|
+
* True when the organization AUTHORED a policy governing this pack rather
|
|
23404
|
+
* than stating a minimum: it gave the answer, so the pack is not
|
|
23405
|
+
* re-assignable locally in either direction.
|
|
23406
|
+
*/
|
|
23407
|
+
locked: external_exports.boolean()
|
|
23408
|
+
}).describe("PackPolicyFloor");
|
|
23656
23409
|
var CATEGORY_EXPRESSIBLE_IDS = KNOWN_BUILTIN_IDS.filter(
|
|
23657
23410
|
(id) => !BUILTIN_POLICY_SPECS[id].reversible
|
|
23658
23411
|
);
|
|
@@ -23710,6 +23463,397 @@ var PolicyStatsResponse = external_exports.object({
|
|
|
23710
23463
|
detectionsGoverned: external_exports.number().int().nonnegative()
|
|
23711
23464
|
}).meta({ id: "PolicyStatsResponse" });
|
|
23712
23465
|
|
|
23466
|
+
// ../../packages/schema/src/zod/vault.ts
|
|
23467
|
+
var POINTER_FORMAT_VERSION = 2;
|
|
23468
|
+
var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
|
|
23469
|
+
var POINTER_TOKEN_PATTERN = new RegExp(
|
|
23470
|
+
`\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
|
|
23471
|
+
);
|
|
23472
|
+
var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
|
|
23473
|
+
function pointerTokenScanner() {
|
|
23474
|
+
return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
|
|
23475
|
+
}
|
|
23476
|
+
var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
|
|
23477
|
+
var ParsedPointer = external_exports.object({
|
|
23478
|
+
category: DetectionCategory,
|
|
23479
|
+
keyVersion: external_exports.number().int().positive(),
|
|
23480
|
+
pointerId: external_exports.string(),
|
|
23481
|
+
tag: external_exports.string()
|
|
23482
|
+
});
|
|
23483
|
+
var VaultEntry = external_exports.object({
|
|
23484
|
+
pointerId: external_exports.string(),
|
|
23485
|
+
// The keyed HMAC of the raw value under `exception.key`, and the epoch it was
|
|
23486
|
+
// derived under. This is what a reveal-to-model grant matches on, and it rotates
|
|
23487
|
+
// independently of the vault encryption key below.
|
|
23488
|
+
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
23489
|
+
fingerprintKeyVersion: external_exports.number().int().positive(),
|
|
23490
|
+
// The vault-key epoch this row's ciphertext was sealed under.
|
|
23491
|
+
keyVersion: external_exports.number().int().positive(),
|
|
23492
|
+
// Fixed at first mint and never updated: the same value detected later under a
|
|
23493
|
+
// different rule's category keeps the category it was minted with, so one
|
|
23494
|
+
// value always produces exactly one wire token.
|
|
23495
|
+
category: DetectionCategory,
|
|
23496
|
+
ruleId: external_exports.string(),
|
|
23497
|
+
// Partial-reveal preview for badges and listings. Never the raw value.
|
|
23498
|
+
maskedMatch: external_exports.string(),
|
|
23499
|
+
provider: external_exports.string().optional(),
|
|
23500
|
+
ciphertext: external_exports.string(),
|
|
23501
|
+
nonce: external_exports.string(),
|
|
23502
|
+
authTag: external_exports.string(),
|
|
23503
|
+
// How many times this value has been detected on this machine — the reuse
|
|
23504
|
+
// signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
|
|
23505
|
+
occurrenceCount: external_exports.number().int().nonnegative(),
|
|
23506
|
+
// True when a PERSON asked for this value to be replaced — the surfaced-
|
|
23507
|
+
// secrets strike — rather than a pack enforcing its assignment. One value is
|
|
23508
|
+
// one row however many paths vault it, so this is what tells a policy sweep
|
|
23509
|
+
// that the row carries somebody's own instruction and not just an assignment
|
|
23510
|
+
// that has since been lowered. STICKY and MONOTONIC: a later automatic
|
|
23511
|
+
// vaulting of the same value must never clear it — what the user said about
|
|
23512
|
+
// the value does not expire.
|
|
23513
|
+
userAuthorized: external_exports.boolean(),
|
|
23514
|
+
firstSeen: external_exports.string(),
|
|
23515
|
+
lastSeen: external_exports.string()
|
|
23516
|
+
});
|
|
23517
|
+
var PointerDescriptor = external_exports.object({
|
|
23518
|
+
category: DetectionCategory,
|
|
23519
|
+
provider: external_exports.string().optional(),
|
|
23520
|
+
maskedMatch: external_exports.string(),
|
|
23521
|
+
occurrences: external_exports.number().int().nonnegative(),
|
|
23522
|
+
firstSeen: external_exports.string(),
|
|
23523
|
+
lastSeen: external_exports.string()
|
|
23524
|
+
});
|
|
23525
|
+
var PointerIdentity = external_exports.object({
|
|
23526
|
+
ruleId: external_exports.string(),
|
|
23527
|
+
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
23528
|
+
fingerprintKeyVersion: external_exports.number().int().positive()
|
|
23529
|
+
});
|
|
23530
|
+
var DetokenizeTarget = external_exports.enum(["human", "model"]);
|
|
23531
|
+
var VaultDerefReason = external_exports.enum([
|
|
23532
|
+
"display",
|
|
23533
|
+
"explicit-reveal",
|
|
23534
|
+
"view-render",
|
|
23535
|
+
"model-input",
|
|
23536
|
+
"remediation",
|
|
23537
|
+
"purge"
|
|
23538
|
+
]);
|
|
23539
|
+
var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
|
|
23540
|
+
var VaultDeref = external_exports.object({
|
|
23541
|
+
id: external_exports.guid(),
|
|
23542
|
+
pointerId: external_exports.string(),
|
|
23543
|
+
at: external_exports.string(),
|
|
23544
|
+
target: DetokenizeTarget,
|
|
23545
|
+
reason: VaultDerefReason,
|
|
23546
|
+
outcome: VaultDerefOutcome,
|
|
23547
|
+
// Present only on a model-target crossing that a reveal grant authorized.
|
|
23548
|
+
grantId: external_exports.string().optional(),
|
|
23549
|
+
// How many pointers ONE batched render resolved. 1 for unbatched rows. Named
|
|
23550
|
+
// apart from VaultEntry.occurrenceCount, which counts detections of a value.
|
|
23551
|
+
pointerCount: external_exports.number().int().positive().default(1)
|
|
23552
|
+
});
|
|
23553
|
+
var VaultSightingKind = external_exports.enum([
|
|
23554
|
+
"prompt",
|
|
23555
|
+
"tool-input",
|
|
23556
|
+
"tool-output",
|
|
23557
|
+
"file",
|
|
23558
|
+
"transcript"
|
|
23559
|
+
]);
|
|
23560
|
+
var VaultSighting = external_exports.object({
|
|
23561
|
+
location: external_exports.string(),
|
|
23562
|
+
kind: VaultSightingKind,
|
|
23563
|
+
firstSeen: external_exports.string(),
|
|
23564
|
+
lastSeen: external_exports.string()
|
|
23565
|
+
});
|
|
23566
|
+
var VaultInventoryEntry = external_exports.object({
|
|
23567
|
+
pointerId: external_exports.string(),
|
|
23568
|
+
category: DetectionCategory,
|
|
23569
|
+
provider: external_exports.string().optional(),
|
|
23570
|
+
maskedMatch: external_exports.string(),
|
|
23571
|
+
occurrences: external_exports.number().int().nonnegative(),
|
|
23572
|
+
firstSeen: external_exports.string(),
|
|
23573
|
+
lastSeen: external_exports.string(),
|
|
23574
|
+
// The active reveal-to-model grant covering this value, when one exists —
|
|
23575
|
+
// the inventory badges it, the row links to revocation.
|
|
23576
|
+
revealGrantId: external_exports.string().nullable(),
|
|
23577
|
+
sightings: external_exports.array(VaultSighting)
|
|
23578
|
+
});
|
|
23579
|
+
var DEFAULT_VAULT_INVENTORY_LIMIT = 50;
|
|
23580
|
+
var DEFAULT_VAULT_DEREFS_LIMIT = 50;
|
|
23581
|
+
var MAX_VAULT_PAGE_LIMIT = 200;
|
|
23582
|
+
var ListVaultInventoryQuery = external_exports.object({
|
|
23583
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23584
|
+
// Opaque; names the last row of the page just served.
|
|
23585
|
+
cursor: external_exports.string().optional()
|
|
23586
|
+
});
|
|
23587
|
+
var ListVaultInventoryResponse = external_exports.object({
|
|
23588
|
+
// Vaulted values across the whole store, not just this page — cursor-
|
|
23589
|
+
// independent, so paging never changes what the count claims.
|
|
23590
|
+
totals: external_exports.object({ values: external_exports.number().int().nonnegative() }),
|
|
23591
|
+
items: external_exports.array(VaultInventoryEntry),
|
|
23592
|
+
// `null` once the last page is reached.
|
|
23593
|
+
nextCursor: external_exports.string().nullable()
|
|
23594
|
+
});
|
|
23595
|
+
var ListVaultReuseQuery = external_exports.object({
|
|
23596
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23597
|
+
cursor: external_exports.string().optional()
|
|
23598
|
+
});
|
|
23599
|
+
var ListVaultReuseResponse = external_exports.object({
|
|
23600
|
+
// Reused values across the whole store — the number the section's claim
|
|
23601
|
+
// ("values detected in more than one place") is about.
|
|
23602
|
+
totals: external_exports.object({ reused: external_exports.number().int().nonnegative() }),
|
|
23603
|
+
items: external_exports.array(VaultInventoryEntry),
|
|
23604
|
+
nextCursor: external_exports.string().nullable()
|
|
23605
|
+
});
|
|
23606
|
+
var ListVaultDerefsQuery = external_exports.object({
|
|
23607
|
+
// Include the batched, high-volume reasons (display, view-render). Omitted
|
|
23608
|
+
// hides them and counts them into `hiddenBatched` instead, so the model
|
|
23609
|
+
// crossings stay visible. A real boolean, not `z.stringbool()`: this arrives
|
|
23610
|
+
// over a Server Action, which preserves the type, never as a URL param.
|
|
23611
|
+
includeBatched: external_exports.boolean().optional(),
|
|
23612
|
+
limit: external_exports.coerce.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
|
|
23613
|
+
cursor: external_exports.string().optional()
|
|
23614
|
+
});
|
|
23615
|
+
var ListVaultDerefsResponse = external_exports.object({
|
|
23616
|
+
items: external_exports.array(VaultDeref),
|
|
23617
|
+
nextCursor: external_exports.string().nullable(),
|
|
23618
|
+
// Display/view-render rows the query hid, over the WHOLE trail rather than
|
|
23619
|
+
// this page — it is the count the "N hidden" line and its toggle speak for.
|
|
23620
|
+
// Always 0 when `includeBatched` was set, since nothing was hidden.
|
|
23621
|
+
hiddenBatched: external_exports.number().int().nonnegative()
|
|
23622
|
+
});
|
|
23623
|
+
var VaultKeyCustody = external_exports.string();
|
|
23624
|
+
var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
|
|
23625
|
+
var VAULT_CONSENT_VERSION = 1;
|
|
23626
|
+
var VaultConsent = external_exports.object({
|
|
23627
|
+
acknowledgedAt: external_exports.iso.datetime(),
|
|
23628
|
+
version: external_exports.number().int().positive()
|
|
23629
|
+
});
|
|
23630
|
+
|
|
23631
|
+
// ../../packages/schema/src/zod/local.ts
|
|
23632
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 7;
|
|
23633
|
+
var MODEL_JUDGE_PAYLOAD_VERSION = 1;
|
|
23634
|
+
var RunMode = external_exports.enum(["standalone", "attached"]);
|
|
23635
|
+
var ControlPlaneConnection = external_exports.object({
|
|
23636
|
+
endpoint: external_exports.string().min(1),
|
|
23637
|
+
// Display name for the deployment, shown instead of the raw endpoint.
|
|
23638
|
+
label: external_exports.string().min(1).optional(),
|
|
23639
|
+
attachedAt: external_exports.iso.datetime()
|
|
23640
|
+
}).meta({ id: "ControlPlaneConnection" });
|
|
23641
|
+
var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
|
|
23642
|
+
var HistoricalAccess = external_exports.enum(["full", "session-only"]);
|
|
23643
|
+
var ModelJudgeConsent = external_exports.object({
|
|
23644
|
+
acknowledgedAt: external_exports.iso.datetime(),
|
|
23645
|
+
payloadVersion: external_exports.number().int().positive()
|
|
23646
|
+
});
|
|
23647
|
+
var HistorySyncConsent = external_exports.object({
|
|
23648
|
+
acknowledgedAt: external_exports.iso.datetime(),
|
|
23649
|
+
payloadVersion: external_exports.number().int().positive(),
|
|
23650
|
+
endpoint: external_exports.string()
|
|
23651
|
+
});
|
|
23652
|
+
var WorkspaceSettings = external_exports.object({
|
|
23653
|
+
specVersion: external_exports.number().int().positive().default(WORKSPACE_SETTINGS_SPEC_VERSION),
|
|
23654
|
+
runMode: RunMode.default("standalone"),
|
|
23655
|
+
// Present only while attached; a detach clears it. Its presence is what makes
|
|
23656
|
+
// `runMode: 'attached'` mean anything — see isAttached.
|
|
23657
|
+
controlPlane: ControlPlaneConnection.optional(),
|
|
23658
|
+
policy: SimpleDetectionPolicy.default("redact"),
|
|
23659
|
+
// Consent for scanning pre-install surfaces; opt-in (see HistoricalAccess).
|
|
23660
|
+
historicalAccess: HistoricalAccess.default("session-only"),
|
|
23661
|
+
// In-place egress extraction on the scan paths; disable to stop all Data
|
|
23662
|
+
// Shares writes.
|
|
23663
|
+
dataSharesInPlace: external_exports.boolean().default(true),
|
|
23664
|
+
// Consent to keep a RECOVERABLE encrypted copy of detected values in the local
|
|
23665
|
+
// vault, instead of destroying them. Absent by default: this is a custody
|
|
23666
|
+
// change from one-way redaction, so it is never an assumed grant on upgrade.
|
|
23667
|
+
// Revoking stops future vaulting; it does not erase what is already stored —
|
|
23668
|
+
// purging the vault is the eraser.
|
|
23669
|
+
vaultConsent: VaultConsent.optional(),
|
|
23670
|
+
// Where the vault master key lives.
|
|
23671
|
+
vaultKeyCustody: VaultKeyCustody.default("file"),
|
|
23672
|
+
// How a pointer renders in assistant prose on screen (see VaultInlineReveal).
|
|
23673
|
+
vaultInlineReveal: VaultInlineReveal.default("masked"),
|
|
23674
|
+
// What a `redact` policy degrades to on a FIELD the host cannot rewrite in
|
|
23675
|
+
// place. Not a handling policy: the policy has already resolved to redact,
|
|
23676
|
+
// and this only says what happens when the host offers no channel to carry it
|
|
23677
|
+
// out — Antigravity's PreToolUse has no updatedInput at all, and Codex and
|
|
23678
|
+
// Claude Code decline to mask a field that EXECUTES because masking would
|
|
23679
|
+
// change what runs. Per FIELD rather than per host, so a host that can
|
|
23680
|
+
// rewrite some inputs keeps true redaction on those.
|
|
23681
|
+
//
|
|
23682
|
+
// Spelled in the built-in policy vocabulary rather than as a fresh enum, so
|
|
23683
|
+
// an attached machine's merge is `strongerAction` over the one action ladder
|
|
23684
|
+
// and no second rank order exists to drift from it. 'deny' is a host wire
|
|
23685
|
+
// word and stays out of the stored value.
|
|
23686
|
+
redactFallback: RedactFallback.default("warn"),
|
|
23687
|
+
// Absent until /aka:setup completes; its presence is what "onboarded" means.
|
|
23688
|
+
onboardedAt: external_exports.iso.datetime().optional(),
|
|
23689
|
+
// Records that the user consented to sending findings to the model API for
|
|
23690
|
+
// the /aka:setup judge, along with the payload-shape version they agreed to.
|
|
23691
|
+
// Absent until granted; a stale payloadVersion means the consent no longer
|
|
23692
|
+
// covers the current payload and must be re-granted.
|
|
23693
|
+
modelJudgeConsent: ModelJudgeConsent.optional(),
|
|
23694
|
+
// Records that the user consented to the DEFERRED send — the outbox — along
|
|
23695
|
+
// with the payload shape and the endpoint they agreed to. Since payload v2
|
|
23696
|
+
// that covers both the pre-attach backlog and undelivered captures (which
|
|
23697
|
+
// carry prompt/reply text in `content`); the key name predates the widening.
|
|
23698
|
+
// Absent until granted, and a grant for a different endpoint or an older
|
|
23699
|
+
// payload no longer counts.
|
|
23700
|
+
historySyncConsent: HistorySyncConsent.optional()
|
|
23701
|
+
});
|
|
23702
|
+
function defaultWorkspaceSettings() {
|
|
23703
|
+
return WorkspaceSettings.parse({});
|
|
23704
|
+
}
|
|
23705
|
+
function isAttached(settings) {
|
|
23706
|
+
return settings.runMode === "attached" && settings.controlPlane !== void 0;
|
|
23707
|
+
}
|
|
23708
|
+
function toInventoryRow(input2, id, now) {
|
|
23709
|
+
return {
|
|
23710
|
+
id,
|
|
23711
|
+
objectType: input2.objectType,
|
|
23712
|
+
location: input2.location ?? null,
|
|
23713
|
+
title: input2.title ?? null,
|
|
23714
|
+
hostId: input2.hostId ?? null,
|
|
23715
|
+
attributes: JSON.stringify(input2.attributes),
|
|
23716
|
+
firstSeen: now,
|
|
23717
|
+
lastSeen: now
|
|
23718
|
+
};
|
|
23719
|
+
}
|
|
23720
|
+
function toSourceProjectRow(input2, id, now) {
|
|
23721
|
+
return {
|
|
23722
|
+
id,
|
|
23723
|
+
url: input2.url,
|
|
23724
|
+
name: input2.name ?? null,
|
|
23725
|
+
attributes: JSON.stringify(input2.attributes),
|
|
23726
|
+
firstSeen: now,
|
|
23727
|
+
lastSeen: now
|
|
23728
|
+
};
|
|
23729
|
+
}
|
|
23730
|
+
function toAuditEventRow(input2) {
|
|
23731
|
+
return {
|
|
23732
|
+
id: input2.id,
|
|
23733
|
+
parentId: input2.parentId ?? null,
|
|
23734
|
+
rootSessionId: input2.rootSessionId ?? null,
|
|
23735
|
+
eventType: input2.eventType,
|
|
23736
|
+
hostId: input2.hostId ?? null,
|
|
23737
|
+
harnessId: input2.harnessId ?? null,
|
|
23738
|
+
sourceProjectId: input2.sourceProjectId ?? null,
|
|
23739
|
+
startedAt: isoToEpochMillis(input2.startedAt),
|
|
23740
|
+
endedAt: input2.endedAt ? isoToEpochMillis(input2.endedAt) : null,
|
|
23741
|
+
severity: input2.severity ?? null,
|
|
23742
|
+
priority: input2.priority ?? null,
|
|
23743
|
+
content: input2.content ?? null,
|
|
23744
|
+
contentHash: input2.contentHash ?? null,
|
|
23745
|
+
attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
|
|
23746
|
+
};
|
|
23747
|
+
}
|
|
23748
|
+
function toClassifiedDataRow(input2, id) {
|
|
23749
|
+
return {
|
|
23750
|
+
id,
|
|
23751
|
+
class: input2.class,
|
|
23752
|
+
label: input2.label ?? null,
|
|
23753
|
+
attributes: input2.attributes ? JSON.stringify(input2.attributes) : null
|
|
23754
|
+
};
|
|
23755
|
+
}
|
|
23756
|
+
function toInspectionDefinitionRow(input2, id) {
|
|
23757
|
+
return {
|
|
23758
|
+
id,
|
|
23759
|
+
ruleId: input2.ruleId,
|
|
23760
|
+
name: input2.name,
|
|
23761
|
+
category: input2.category,
|
|
23762
|
+
severity: input2.severity,
|
|
23763
|
+
definition: input2.definition,
|
|
23764
|
+
version: input2.version
|
|
23765
|
+
};
|
|
23766
|
+
}
|
|
23767
|
+
function toInspectionFindingRow(input2) {
|
|
23768
|
+
return {
|
|
23769
|
+
id: input2.id,
|
|
23770
|
+
auditEventId: input2.auditEventId,
|
|
23771
|
+
inspectionDefinitionId: input2.inspectionDefinitionId,
|
|
23772
|
+
classifiedDataId: input2.classifiedDataId ?? null,
|
|
23773
|
+
spanStart: input2.span.start,
|
|
23774
|
+
spanEnd: input2.span.end,
|
|
23775
|
+
maskedMatch: input2.maskedMatch,
|
|
23776
|
+
actionTaken: input2.actionTaken,
|
|
23777
|
+
confidence: input2.confidence,
|
|
23778
|
+
findingKey: input2.findingKey ?? null,
|
|
23779
|
+
firstDetectedAt: input2.firstDetectedAt ? isoToEpochMillis(input2.firstDetectedAt) : null
|
|
23780
|
+
};
|
|
23781
|
+
}
|
|
23782
|
+
function toCaptureAttributes(event) {
|
|
23783
|
+
const metadata = event.metadata;
|
|
23784
|
+
return {
|
|
23785
|
+
source_tool: event.sourceTool,
|
|
23786
|
+
...metadata?.repo !== void 0 ? { repo: metadata.repo } : {},
|
|
23787
|
+
...metadata?.filePath !== void 0 ? { file_path: metadata.filePath } : {},
|
|
23788
|
+
...metadata?.toolName !== void 0 ? { tool_name: metadata.toolName } : {},
|
|
23789
|
+
...metadata?.gitignored !== void 0 ? { gitignored: metadata.gitignored } : {},
|
|
23790
|
+
...metadata?.wholeFile !== void 0 ? { whole_file: metadata.wholeFile } : {},
|
|
23791
|
+
...metadata?.correlationId !== void 0 ? { correlation_id: metadata.correlationId } : {},
|
|
23792
|
+
...metadata?.traceId !== void 0 ? { trace_id: metadata.traceId } : {},
|
|
23793
|
+
...metadata?.exceptionIds !== void 0 ? { exception_ids: metadata.exceptionIds } : {},
|
|
23794
|
+
...metadata?.inspectionMs !== void 0 ? { inspection_ms: metadata.inspectionMs } : {},
|
|
23795
|
+
// `model`/`turnIndex` have no dedicated CaptureAttributes field (no writer
|
|
23796
|
+
// has ever populated either), but every legacy metadata key still rides
|
|
23797
|
+
// the bag rather than being silently dropped — CaptureAttributes'
|
|
23798
|
+
// `.catchall(z.unknown())` carries the long tail.
|
|
23799
|
+
...metadata?.model !== void 0 ? { model: metadata.model } : {},
|
|
23800
|
+
...metadata?.turnIndex !== void 0 ? { turn_index: metadata.turnIndex } : {}
|
|
23801
|
+
};
|
|
23802
|
+
}
|
|
23803
|
+
function captureDefinitionVersion(finding) {
|
|
23804
|
+
return `capture/${finding.category}/${finding.severity}`;
|
|
23805
|
+
}
|
|
23806
|
+
function toCaptureDefinitionInput(finding) {
|
|
23807
|
+
return {
|
|
23808
|
+
ruleId: finding.ruleId,
|
|
23809
|
+
version: captureDefinitionVersion(finding),
|
|
23810
|
+
name: finding.ruleId,
|
|
23811
|
+
category: finding.category,
|
|
23812
|
+
severity: finding.severity,
|
|
23813
|
+
definition: JSON.stringify({ ruleId: finding.ruleId })
|
|
23814
|
+
};
|
|
23815
|
+
}
|
|
23816
|
+
|
|
23817
|
+
// ../../packages/schema/src/zod/managed.ts
|
|
23818
|
+
var MANAGED_SETTINGS_FILENAME = "managed-settings.json";
|
|
23819
|
+
var MANAGED_SETTINGS_SPEC_VERSION = 1;
|
|
23820
|
+
var ManagedSettingKey = external_exports.enum([
|
|
23821
|
+
"runMode",
|
|
23822
|
+
"historicalAccess",
|
|
23823
|
+
"vaultConsent",
|
|
23824
|
+
"vaultKeyCustody",
|
|
23825
|
+
"vaultInlineReveal",
|
|
23826
|
+
"modelJudgeConsent",
|
|
23827
|
+
"dataSharesInPlace",
|
|
23828
|
+
"redactFallback"
|
|
23829
|
+
]).meta({ id: "ManagedSettingKey" });
|
|
23830
|
+
var ManagedSettingsValues = external_exports.object({
|
|
23831
|
+
runMode: external_exports.enum(["standalone", "attached"]).optional(),
|
|
23832
|
+
controlPlane: external_exports.object({
|
|
23833
|
+
endpoint: external_exports.string().min(1),
|
|
23834
|
+
label: external_exports.string().min(1).optional()
|
|
23835
|
+
}).optional(),
|
|
23836
|
+
historicalAccess: external_exports.enum(["full", "session-only"]).optional(),
|
|
23837
|
+
vaultConsent: external_exports.boolean().optional(),
|
|
23838
|
+
vaultKeyCustody: external_exports.enum(["file", "keychain"]).optional(),
|
|
23839
|
+
vaultInlineReveal: external_exports.enum(["masked", "full", "off"]).optional(),
|
|
23840
|
+
modelJudgeConsent: external_exports.boolean().optional(),
|
|
23841
|
+
dataSharesInPlace: external_exports.boolean().optional(),
|
|
23842
|
+
redactFallback: RedactFallback.optional()
|
|
23843
|
+
}).meta({ id: "ManagedSettingsValues" });
|
|
23844
|
+
var ManagedSettings = external_exports.object({
|
|
23845
|
+
specVersion: external_exports.number().int().positive().default(MANAGED_SETTINGS_SPEC_VERSION),
|
|
23846
|
+
// Shown on every locked control, so the user can tell an administrative
|
|
23847
|
+
// decision from a bug. Absent renders as a generic "your organization".
|
|
23848
|
+
organization: external_exports.string().min(1).optional(),
|
|
23849
|
+
// What the administrator pinned.
|
|
23850
|
+
values: ManagedSettingsValues.default({}),
|
|
23851
|
+
// Which of those the user may not change. A key here with no matching value
|
|
23852
|
+
// freezes whatever the user last chose; a value with no lock is a DEFAULT
|
|
23853
|
+
// the user may still override. The two are separable on purpose.
|
|
23854
|
+
lockedFields: external_exports.array(ManagedSettingKey).default([])
|
|
23855
|
+
}).meta({ id: "ManagedSettings" });
|
|
23856
|
+
|
|
23713
23857
|
// ../../packages/schema/src/zod/project-files.ts
|
|
23714
23858
|
var ProjectFileInput = external_exports.object({
|
|
23715
23859
|
path: external_exports.string().min(1),
|
|
@@ -23955,10 +24099,12 @@ var DismissRecommendedActionResponse = external_exports.object({ id: external_ex
|
|
|
23955
24099
|
var RecommendedActionIdParam = external_exports.object({ id: external_exports.string() });
|
|
23956
24100
|
|
|
23957
24101
|
// ../../packages/schema/src/zod/settings-action.ts
|
|
24102
|
+
var HistorySyncConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "HistorySyncConsentChoice" });
|
|
24103
|
+
var ModelJudgeConsentChoice = external_exports.enum(["granted", "revoked", "unchanged"]).meta({ id: "ModelJudgeConsentChoice" });
|
|
23958
24104
|
var SaveSettingsInput = external_exports.object({
|
|
23959
24105
|
historicalAccess: external_exports.string(),
|
|
23960
|
-
modelJudgeConsent:
|
|
23961
|
-
historySyncConsent:
|
|
24106
|
+
modelJudgeConsent: ModelJudgeConsentChoice,
|
|
24107
|
+
historySyncConsent: HistorySyncConsentChoice,
|
|
23962
24108
|
vaultConsent: external_exports.string(),
|
|
23963
24109
|
vaultInlineReveal: external_exports.string()
|
|
23964
24110
|
});
|
|
@@ -24108,9 +24254,9 @@ function deriveReviewReasons(trust, transports) {
|
|
|
24108
24254
|
if (transports.includes("http") || transports.includes("ws")) reasons.push("plaintext_transport");
|
|
24109
24255
|
return reasons;
|
|
24110
24256
|
}
|
|
24111
|
-
function buildReviewInfo(trust, transports) {
|
|
24257
|
+
function buildReviewInfo(trust, transports, decided) {
|
|
24112
24258
|
const reasons = deriveReviewReasons(trust, transports);
|
|
24113
|
-
return { needsReview: reasons.length > 0, reasons };
|
|
24259
|
+
return { needsReview: reasons.length > 0 && !decided, reasons };
|
|
24114
24260
|
}
|
|
24115
24261
|
function distinctTransports(transports) {
|
|
24116
24262
|
return Array.from(new Set(transports));
|
|
@@ -24328,8 +24474,8 @@ function readControlPlaneCredential(settingsDir2, connection) {
|
|
|
24328
24474
|
}
|
|
24329
24475
|
|
|
24330
24476
|
// ../../packages/persistence/src/database.ts
|
|
24331
|
-
import { randomUUID as
|
|
24332
|
-
import { join as
|
|
24477
|
+
import { randomUUID as randomUUID11 } from "crypto";
|
|
24478
|
+
import { dirname as dirname2, join as join7, sep } from "path";
|
|
24333
24479
|
import { DatabaseSync } from "node:sqlite";
|
|
24334
24480
|
|
|
24335
24481
|
// ../../packages/persistence/src/ids.ts
|
|
@@ -24594,6 +24740,10 @@ function allRows(stmt, params) {
|
|
|
24594
24740
|
if (Array.isArray(params)) return stmt.all(...params);
|
|
24595
24741
|
return stmt.all(params);
|
|
24596
24742
|
}
|
|
24743
|
+
function* iterateRows(stmt, params) {
|
|
24744
|
+
const rows = params === void 0 ? stmt.iterate() : Array.isArray(params) ? stmt.iterate(...params) : stmt.iterate(params);
|
|
24745
|
+
for (const row of rows) yield row;
|
|
24746
|
+
}
|
|
24597
24747
|
function getRow(stmt, params) {
|
|
24598
24748
|
if (params === void 0) return stmt.get();
|
|
24599
24749
|
if (Array.isArray(params)) return stmt.get(...params);
|
|
@@ -25062,10 +25212,17 @@ function ensureSyncedAtColumn(db, table) {
|
|
|
25062
25212
|
if (!columns.includes("sync_claimed_at")) {
|
|
25063
25213
|
db.exec(`ALTER TABLE ${table} ADD COLUMN sync_claimed_at integer`);
|
|
25064
25214
|
}
|
|
25215
|
+
if (!columns.includes("outbox_owed")) {
|
|
25216
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN outbox_owed integer`);
|
|
25217
|
+
}
|
|
25065
25218
|
db.exec(
|
|
25066
25219
|
`CREATE INDEX IF NOT EXISTS idx_audit_events_sync
|
|
25067
25220
|
ON audit_events (event_type, synced_at, sync_claimed_at, started_at)`
|
|
25068
25221
|
);
|
|
25222
|
+
db.exec(
|
|
25223
|
+
`CREATE INDEX IF NOT EXISTS idx_audit_outbox_owed
|
|
25224
|
+
ON audit_events (event_type, synced_at, sync_claimed_at, started_at) WHERE outbox_owed = 1`
|
|
25225
|
+
);
|
|
25069
25226
|
db.exec(
|
|
25070
25227
|
`CREATE INDEX IF NOT EXISTS idx_audit_claimed
|
|
25071
25228
|
ON audit_events (sync_claimed_at) WHERE sync_claimed_at IS NOT NULL`
|
|
@@ -25170,7 +25327,6 @@ function decodeKeysetCursor(cursor) {
|
|
|
25170
25327
|
// ../../packages/persistence/src/repositories/activity.ts
|
|
25171
25328
|
var DAY_MS = 864e5;
|
|
25172
25329
|
var LIVE_ACTIVITY_WINDOW_MS = 30 * 6e4;
|
|
25173
|
-
var LAST_ACTIVITY_EXPR = `max(started_at, coalesce(ended_at, started_at))`;
|
|
25174
25330
|
function defaultTimeZone() {
|
|
25175
25331
|
try {
|
|
25176
25332
|
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
@@ -25225,6 +25381,7 @@ var DB_EVENT_TYPE_TO_KIND = {
|
|
|
25225
25381
|
error: "error",
|
|
25226
25382
|
active: "active"
|
|
25227
25383
|
};
|
|
25384
|
+
var TIMELINE_EVENT_TYPES = Object.keys(DB_EVENT_TYPE_TO_KIND).map((kind) => `'${kind}'`).join(", ");
|
|
25228
25385
|
function safeParseStringArray(raw) {
|
|
25229
25386
|
if (!raw) return [];
|
|
25230
25387
|
const parsed2 = safeJson(raw, null);
|
|
@@ -25298,6 +25455,37 @@ var TIMELINE_COLUMNS = `
|
|
|
25298
25455
|
json_extract(attributes, '$.targetId') AS target_id,
|
|
25299
25456
|
json_extract(attributes, '$.internal') AS internal,
|
|
25300
25457
|
json_extract(attributes, '$.flagged') AS flagged`;
|
|
25458
|
+
var LLM_USAGE_SELECT = `
|
|
25459
|
+
SELECT root_session_id AS sessionId,
|
|
25460
|
+
provider,
|
|
25461
|
+
model,
|
|
25462
|
+
service_tier AS serviceTier,
|
|
25463
|
+
coalesce(sum(input_tokens), 0) AS inputTokens,
|
|
25464
|
+
coalesce(sum(output_tokens), 0) AS outputTokens,
|
|
25465
|
+
coalesce(sum(cache_creation_input_tokens), 0) AS cacheCreationTokens,
|
|
25466
|
+
coalesce(sum(cache_read_input_tokens), 0) AS cacheReadTokens,
|
|
25467
|
+
coalesce(sum(ephemeral_1h_input_tokens), 0) AS ephemeral1hTokens,
|
|
25468
|
+
coalesce(sum(ephemeral_5m_input_tokens), 0) AS ephemeral5mTokens,
|
|
25469
|
+
coalesce(sum(web_search_requests), 0) AS webSearchRequests`;
|
|
25470
|
+
var LLM_USAGE_SCOPE = `event_type = 'llm_call' AND attributes IS NOT NULL AND root_session_id IS NOT NULL`;
|
|
25471
|
+
var LLM_USAGE_GROUP = `GROUP BY root_session_id, provider, model, service_tier`;
|
|
25472
|
+
function usageLeaves(rows) {
|
|
25473
|
+
return rows.map((row) => {
|
|
25474
|
+
const attributes = {
|
|
25475
|
+
input_tokens: row.inputTokens,
|
|
25476
|
+
output_tokens: row.outputTokens,
|
|
25477
|
+
cache_creation_input_tokens: row.cacheCreationTokens,
|
|
25478
|
+
cache_read_input_tokens: row.cacheReadTokens,
|
|
25479
|
+
ephemeral_1h_input_tokens: row.ephemeral1hTokens,
|
|
25480
|
+
ephemeral_5m_input_tokens: row.ephemeral5mTokens,
|
|
25481
|
+
web_search_requests: row.webSearchRequests
|
|
25482
|
+
};
|
|
25483
|
+
if (row.provider !== null) attributes.provider = row.provider;
|
|
25484
|
+
if (row.model !== null) attributes.model = row.model;
|
|
25485
|
+
if (row.serviceTier !== null) attributes.service_tier = row.serviceTier;
|
|
25486
|
+
return { sessionId: row.sessionId, attributes };
|
|
25487
|
+
});
|
|
25488
|
+
}
|
|
25301
25489
|
var SESSION_ROOT = `event_type = 'session'`;
|
|
25302
25490
|
var HAS_ACTIVITY = `EXISTS (
|
|
25303
25491
|
SELECT 1 FROM audit_events c
|
|
@@ -25323,16 +25511,17 @@ var SqliteActivityRepository = class {
|
|
|
25323
25511
|
const liveThreshold = this.now() - LIVE_ACTIVITY_WINDOW_MS;
|
|
25324
25512
|
const liveNow = countScalar(
|
|
25325
25513
|
this.db,
|
|
25326
|
-
`SELECT count(*) AS n FROM audit_events s
|
|
25514
|
+
`SELECT count(*) AS n FROM audit_events s INDEXED BY sqlite_autoindex_audit_events_1
|
|
25327
25515
|
WHERE s.event_type = 'session' AND s.ended_at IS NULL
|
|
25328
|
-
AND
|
|
25329
|
-
|
|
25330
|
-
|
|
25331
|
-
|
|
25332
|
-
|
|
25333
|
-
|
|
25334
|
-
|
|
25335
|
-
|
|
25516
|
+
AND s.id IN (
|
|
25517
|
+
SELECT id FROM audit_events WHERE event_type = 'session' AND started_at >= ?
|
|
25518
|
+
UNION
|
|
25519
|
+
SELECT root_session_id FROM audit_events INDEXED BY idx_audit_started_at
|
|
25520
|
+
WHERE started_at >= ?
|
|
25521
|
+
UNION
|
|
25522
|
+
SELECT root_session_id FROM audit_events INDEXED BY idx_audit_ended_at
|
|
25523
|
+
WHERE ended_at >= ?)`,
|
|
25524
|
+
[liveThreshold, liveThreshold, liveThreshold]
|
|
25336
25525
|
);
|
|
25337
25526
|
const toolCallsToday = countScalar(
|
|
25338
25527
|
this.db,
|
|
@@ -25462,7 +25651,7 @@ var SqliteActivityRepository = class {
|
|
|
25462
25651
|
this.db.prepare(
|
|
25463
25652
|
`SELECT ${TIMELINE_COLUMNS}
|
|
25464
25653
|
FROM audit_events
|
|
25465
|
-
WHERE id = ? OR root_session_id = ?
|
|
25654
|
+
WHERE (id = ? OR root_session_id = ?) AND event_type IN (${TIMELINE_EVENT_TYPES})
|
|
25466
25655
|
ORDER BY started_at ASC, id ASC`
|
|
25467
25656
|
),
|
|
25468
25657
|
[sessionId, sessionId]
|
|
@@ -25475,14 +25664,14 @@ var SqliteActivityRepository = class {
|
|
|
25475
25664
|
coalesce(sum(output_tokens), 0) AS output,
|
|
25476
25665
|
coalesce(sum(cache_creation_input_tokens), 0) AS cache_creation,
|
|
25477
25666
|
coalesce(sum(cache_read_input_tokens), 0) AS cache_read
|
|
25478
|
-
FROM audit_events
|
|
25667
|
+
FROM audit_events INDEXED BY idx_audit_session_type
|
|
25479
25668
|
WHERE root_session_id = ? AND event_type = 'llm_call'`
|
|
25480
25669
|
),
|
|
25481
25670
|
[sessionId]
|
|
25482
25671
|
) ?? { input: 0, output: 0, cache_creation: 0, cache_read: 0 };
|
|
25483
25672
|
const primaryModel = getRow(
|
|
25484
25673
|
this.db.prepare(
|
|
25485
|
-
`SELECT model, provider FROM audit_events
|
|
25674
|
+
`SELECT model, provider FROM audit_events INDEXED BY idx_audit_session_type
|
|
25486
25675
|
WHERE root_session_id = ? AND event_type = 'llm_call'
|
|
25487
25676
|
ORDER BY started_at ASC, id ASC
|
|
25488
25677
|
LIMIT 1`
|
|
@@ -25493,7 +25682,7 @@ var SqliteActivityRepository = class {
|
|
|
25493
25682
|
this.db.prepare(
|
|
25494
25683
|
`SELECT coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool')) AS tool,
|
|
25495
25684
|
count(*) AS n
|
|
25496
|
-
FROM audit_events
|
|
25685
|
+
FROM audit_events INDEXED BY idx_audit_session
|
|
25497
25686
|
WHERE root_session_id = ? AND event_type = 'tool_call'
|
|
25498
25687
|
GROUP BY coalesce(json_extract(attributes, '$.tool_name'), json_extract(attributes, '$.tool'))`
|
|
25499
25688
|
),
|
|
@@ -25501,7 +25690,7 @@ var SqliteActivityRepository = class {
|
|
|
25501
25690
|
);
|
|
25502
25691
|
const modelRows = allRows(
|
|
25503
25692
|
this.db.prepare(
|
|
25504
|
-
`SELECT DISTINCT model FROM audit_events
|
|
25693
|
+
`SELECT DISTINCT model FROM audit_events INDEXED BY idx_audit_session_type
|
|
25505
25694
|
WHERE root_session_id = ? AND event_type = 'llm_call' AND model IS NOT NULL AND model <> ''
|
|
25506
25695
|
ORDER BY model`
|
|
25507
25696
|
),
|
|
@@ -25510,7 +25699,7 @@ var SqliteActivityRepository = class {
|
|
|
25510
25699
|
const derivedModels = modelRows.map((r) => r.model);
|
|
25511
25700
|
const commits = countScalar(
|
|
25512
25701
|
this.db,
|
|
25513
|
-
`SELECT count(*) AS n FROM audit_events
|
|
25702
|
+
`SELECT count(*) AS n FROM audit_events INDEXED BY idx_audit_session
|
|
25514
25703
|
WHERE root_session_id = ? AND event_type = 'commit'`,
|
|
25515
25704
|
[sessionId]
|
|
25516
25705
|
);
|
|
@@ -25546,25 +25735,57 @@ var SqliteActivityRepository = class {
|
|
|
25546
25735
|
return Promise.resolve(session);
|
|
25547
25736
|
}
|
|
25548
25737
|
/**
|
|
25549
|
-
* Cross-session token report — every `llm_call`
|
|
25550
|
-
* `started_at >= fromMs`
|
|
25551
|
-
* USD cost DERIVED at read time via the shared
|
|
25552
|
-
*
|
|
25553
|
-
*
|
|
25554
|
-
*
|
|
25738
|
+
* Cross-session token report — every `llm_call` in the store (or in a
|
|
25739
|
+
* `started_at >= fromMs` window, the Activity page's range) grouped per
|
|
25740
|
+
* session, with USD cost DERIVED at read time via the shared
|
|
25741
|
+
* `defaultCostModel` (never stored). The caller collapses these onto
|
|
25742
|
+
* per-model rows with `aggregateTokenUsage`.
|
|
25743
|
+
*
|
|
25744
|
+
* Grouped in SQL over `idx_audit_llm_usage` — one entry per call carrying
|
|
25745
|
+
* the members the rollup sums — and priced once per group, which is exact
|
|
25746
|
+
* (see LlmUsageRow). Reading the bags and folding them in JS measured 31 ms
|
|
25747
|
+
* for a seven-day window at 50k calls, and naming the VIRTUAL columns
|
|
25748
|
+
* against the table 40 ms, since each is a json_extract recomputed per row;
|
|
25749
|
+
* the index stores the values once, at write, and answers the same window in
|
|
25750
|
+
* 8.5 ms. `INDEXED BY` is deliberate: with or without ANALYZE statistics the
|
|
25751
|
+
* planner prefers the general event-type index and fetches every row to
|
|
25752
|
+
* recompute the columns it could have read. The index is one every open
|
|
25753
|
+
* store carries, since opening runs the migrations, so the hard requirement
|
|
25754
|
+
* `INDEXED BY` introduces is already met; token-rollup-plans.test.ts pins
|
|
25755
|
+
* the plan. All-time is a scan of the whole index — still one narrow entry
|
|
25756
|
+
* per call, no bag parsed.
|
|
25555
25757
|
*/
|
|
25556
25758
|
tokenReports(fromMs) {
|
|
25557
|
-
const
|
|
25558
|
-
|
|
25759
|
+
const rows = allRows(
|
|
25760
|
+
this.db.prepare(
|
|
25761
|
+
`${LLM_USAGE_SELECT}
|
|
25762
|
+
FROM audit_events INDEXED BY idx_audit_llm_usage
|
|
25763
|
+
WHERE ${LLM_USAGE_SCOPE}${fromMs === void 0 ? "" : " AND started_at >= ?"}
|
|
25764
|
+
${LLM_USAGE_GROUP}`
|
|
25765
|
+
),
|
|
25766
|
+
fromMs === void 0 ? void 0 : [fromMs]
|
|
25767
|
+
);
|
|
25768
|
+
return Promise.resolve(buildTokenReports(usageLeaves(rows), defaultCostModel));
|
|
25559
25769
|
}
|
|
25560
25770
|
/**
|
|
25561
|
-
* One session's token report — its `llm_call`
|
|
25562
|
-
* model) with derived cost, or `null` when the session made no
|
|
25563
|
-
* (an empty/tool-only session). Feeds the session-detail pane's
|
|
25564
|
-
* breakdown + estimated cost.
|
|
25771
|
+
* One session's token report — its `llm_call`s grouped per (provider,
|
|
25772
|
+
* model, tier) with derived cost, or `null` when the session made no
|
|
25773
|
+
* `llm_call`s (an empty/tool-only session). Feeds the session-detail pane's
|
|
25774
|
+
* per-model breakdown + estimated cost. The same rollup as `tokenReports`,
|
|
25775
|
+
* seeking one root through a root-led `llm_call` index; the bag-reading fold
|
|
25776
|
+
* it replaces walked every `llm_call` in the store to find one session's.
|
|
25565
25777
|
*/
|
|
25566
25778
|
tokenReportForSession(sessionId) {
|
|
25567
|
-
const
|
|
25779
|
+
const rows = allRows(
|
|
25780
|
+
this.db.prepare(
|
|
25781
|
+
`${LLM_USAGE_SELECT}
|
|
25782
|
+
FROM audit_events
|
|
25783
|
+
WHERE ${LLM_USAGE_SCOPE} AND root_session_id = ?
|
|
25784
|
+
${LLM_USAGE_GROUP}`
|
|
25785
|
+
),
|
|
25786
|
+
[sessionId]
|
|
25787
|
+
);
|
|
25788
|
+
const reports = buildTokenReports(usageLeaves(rows), defaultCostModel);
|
|
25568
25789
|
return Promise.resolve(reports[0] ?? null);
|
|
25569
25790
|
}
|
|
25570
25791
|
/**
|
|
@@ -25588,42 +25809,6 @@ var SqliteActivityRepository = class {
|
|
|
25588
25809
|
for (const row of rows) seen.add(toHarness(row.harness));
|
|
25589
25810
|
return Promise.resolve([...seen]);
|
|
25590
25811
|
}
|
|
25591
|
-
/**
|
|
25592
|
-
* The raw `llm_call` leaves (session id + parsed attribute bag) for the token
|
|
25593
|
-
* rollups, optionally narrowed to one session and/or a `started_at >= fromMs`
|
|
25594
|
-
* window. A leaf whose attributes blob is NULL or unparseable is skipped
|
|
25595
|
-
* (best-effort read — a corrupt bag never breaks the report). `root_session_id`
|
|
25596
|
-
* is the leaf's session (the reconciler sets parent_id = root_session_id).
|
|
25597
|
-
*/
|
|
25598
|
-
readLlmCallLeaves(opts = {}) {
|
|
25599
|
-
const conditions = ["event_type = 'llm_call'", "attributes IS NOT NULL"];
|
|
25600
|
-
const params = [];
|
|
25601
|
-
if (opts.sessionId !== void 0) {
|
|
25602
|
-
conditions.push("root_session_id = ?");
|
|
25603
|
-
params.push(opts.sessionId);
|
|
25604
|
-
}
|
|
25605
|
-
if (opts.fromMs !== void 0) {
|
|
25606
|
-
conditions.push("started_at >= ?");
|
|
25607
|
-
params.push(opts.fromMs);
|
|
25608
|
-
}
|
|
25609
|
-
const rows = allRows(
|
|
25610
|
-
this.db.prepare(
|
|
25611
|
-
`SELECT root_session_id AS sessionId, attributes
|
|
25612
|
-
FROM audit_events
|
|
25613
|
-
WHERE ${conditions.join(" AND ")}`
|
|
25614
|
-
),
|
|
25615
|
-
params
|
|
25616
|
-
);
|
|
25617
|
-
return mapRowsTolerant(
|
|
25618
|
-
rows.filter(
|
|
25619
|
-
(row) => row.sessionId !== null
|
|
25620
|
-
),
|
|
25621
|
-
(row) => ({
|
|
25622
|
-
sessionId: row.sessionId,
|
|
25623
|
-
attributes: JSON.parse(row.attributes)
|
|
25624
|
-
})
|
|
25625
|
-
);
|
|
25626
|
-
}
|
|
25627
25812
|
/**
|
|
25628
25813
|
* Per-session turns/findings/shares + last-activity for a page of session ids,
|
|
25629
25814
|
* in grouped queries (not one per row). An id with no matching rows still
|
|
@@ -25638,20 +25823,23 @@ var SqliteActivityRepository = class {
|
|
|
25638
25823
|
const inClause = placeholders(sessionIds.length);
|
|
25639
25824
|
const lastActivityRows = allRows(
|
|
25640
25825
|
this.db.prepare(
|
|
25641
|
-
`SELECT
|
|
25642
|
-
|
|
25643
|
-
|
|
25826
|
+
`SELECT ids.value AS id,
|
|
25827
|
+
(SELECT max(started_at) FROM audit_events e WHERE e.root_session_id = ids.value) AS ms,
|
|
25828
|
+
(SELECT max(ended_at) FROM audit_events e
|
|
25829
|
+
WHERE e.root_session_id = ids.value AND e.ended_at IS NOT NULL) AS me
|
|
25830
|
+
FROM json_each(?) AS ids`
|
|
25644
25831
|
),
|
|
25645
|
-
sessionIds
|
|
25832
|
+
[JSON.stringify(sessionIds)]
|
|
25646
25833
|
);
|
|
25647
25834
|
for (const row of lastActivityRows) {
|
|
25648
|
-
if (row.id === null) continue;
|
|
25649
25835
|
const entry = result.get(row.id);
|
|
25650
|
-
|
|
25836
|
+
const last = Math.max(row.ms ?? 0, row.me ?? 0);
|
|
25837
|
+
if (entry && last > 0) entry.lastActivityMs = last;
|
|
25651
25838
|
}
|
|
25652
25839
|
const turnsRows = allRows(
|
|
25653
25840
|
this.db.prepare(
|
|
25654
|
-
`SELECT root_session_id AS id, count(*) AS n
|
|
25841
|
+
`SELECT root_session_id AS id, count(*) AS n
|
|
25842
|
+
FROM audit_events INDEXED BY idx_audit_session_prompt
|
|
25655
25843
|
WHERE root_session_id IN (${inClause}) AND event_type = 'prompt'
|
|
25656
25844
|
GROUP BY root_session_id`
|
|
25657
25845
|
),
|
|
@@ -25666,7 +25854,7 @@ var SqliteActivityRepository = class {
|
|
|
25666
25854
|
this.db.prepare(
|
|
25667
25855
|
`SELECT root_session_id AS id,
|
|
25668
25856
|
count(DISTINCT json_extract(attributes, '$.run_key')) AS n
|
|
25669
|
-
FROM audit_events
|
|
25857
|
+
FROM audit_events INDEXED BY idx_audit_session_run_key
|
|
25670
25858
|
WHERE root_session_id IN (${inClause}) AND event_type = 'llm_call'
|
|
25671
25859
|
AND json_extract(attributes, '$.run_key') IS NOT NULL
|
|
25672
25860
|
GROUP BY root_session_id`
|
|
@@ -25696,7 +25884,7 @@ var SqliteActivityRepository = class {
|
|
|
25696
25884
|
this.db.prepare(
|
|
25697
25885
|
`SELECT root_session_id AS id,
|
|
25698
25886
|
count(DISTINCT json_extract(attributes, '$.destination')) AS n
|
|
25699
|
-
FROM audit_events
|
|
25887
|
+
FROM audit_events INDEXED BY idx_audit_session_share
|
|
25700
25888
|
WHERE root_session_id IN (${inClause}) AND event_type = 'share'
|
|
25701
25889
|
GROUP BY root_session_id`
|
|
25702
25890
|
),
|
|
@@ -26725,7 +26913,6 @@ var LATEST_RESOLUTION_BY_KEY_SQL = `(
|
|
|
26725
26913
|
|
|
26726
26914
|
// ../../packages/persistence/src/repositories/findings.ts
|
|
26727
26915
|
var PREVIEW_INSTANCES_PER_GROUP = 200;
|
|
26728
|
-
var SCAN_BATCH_ROWS = 1e3;
|
|
26729
26916
|
var DEFAULT_LOCATIONS_LIMIT = 100;
|
|
26730
26917
|
var LOCATION_RULE_IDS_CAP = 20;
|
|
26731
26918
|
function compareLocationOrder(a, b) {
|
|
@@ -26754,6 +26941,25 @@ function deriveInstanceStatus(row) {
|
|
|
26754
26941
|
latestResolutionStatus: row.latest_status
|
|
26755
26942
|
});
|
|
26756
26943
|
}
|
|
26944
|
+
function toFlatFindingRow(r) {
|
|
26945
|
+
return {
|
|
26946
|
+
id: r.id,
|
|
26947
|
+
ruleId: r.rule_id,
|
|
26948
|
+
category: r.category,
|
|
26949
|
+
severity: r.severity,
|
|
26950
|
+
maskedMatch: r.masked_match,
|
|
26951
|
+
actionTaken: r.action_taken,
|
|
26952
|
+
confidence: r.confidence,
|
|
26953
|
+
occurredAt: epochMillisToIso(r.occurred_at),
|
|
26954
|
+
sourceTool: r.source_tool,
|
|
26955
|
+
repo: r.repo ?? "",
|
|
26956
|
+
file: r.file ?? "",
|
|
26957
|
+
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26958
|
+
eventId: r.event_id,
|
|
26959
|
+
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26960
|
+
status: deriveInstanceStatus(r)
|
|
26961
|
+
};
|
|
26962
|
+
}
|
|
26757
26963
|
function encodeGroupCursor(group) {
|
|
26758
26964
|
const payload = {
|
|
26759
26965
|
sev: group.severity,
|
|
@@ -26829,7 +27035,7 @@ var SqliteFindingsRepository = class {
|
|
|
26829
27035
|
this.db.prepare(
|
|
26830
27036
|
`SELECT f.id, f.audit_event_id AS event_id, d.rule_id, d.category, d.severity,
|
|
26831
27037
|
f.masked_match, f.action_taken, f.confidence, e.started_at AS occurred_at,
|
|
26832
|
-
|
|
27038
|
+
e.source_tool AS source_tool,
|
|
26833
27039
|
e.event_type AS kind
|
|
26834
27040
|
FROM audit_events e
|
|
26835
27041
|
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
@@ -26937,56 +27143,11 @@ var SqliteFindingsRepository = class {
|
|
|
26937
27143
|
predicate,
|
|
26938
27144
|
params: sessionParams
|
|
26939
27145
|
});
|
|
26940
|
-
const rows =
|
|
26941
|
-
|
|
26942
|
-
|
|
26943
|
-
|
|
26944
|
-
|
|
26945
|
-
FROM (
|
|
26946
|
-
SELECT f.id AS id, d.rule_id AS rule_id, d.category AS category,
|
|
26947
|
-
d.severity AS severity, f.masked_match AS masked_match,
|
|
26948
|
-
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
26949
|
-
e.started_at AS occurred_at,
|
|
26950
|
-
json_extract(e.attributes, '$.source_tool') AS source_tool,
|
|
26951
|
-
json_extract(e.attributes, '$.repo') AS repo,
|
|
26952
|
-
json_extract(e.attributes, '$.file_path') AS file,
|
|
26953
|
-
json_extract(e.attributes, '$.tool_name') AS tool_name,
|
|
26954
|
-
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
26955
|
-
e.event_type AS kind, f.finding_key AS finding_key,
|
|
26956
|
-
latest.status AS latest_status,
|
|
26957
|
-
ROW_NUMBER() OVER (
|
|
26958
|
-
PARTITION BY d.rule_id
|
|
26959
|
-
ORDER BY e.started_at DESC, f.id DESC
|
|
26960
|
-
) AS rn
|
|
26961
|
-
FROM inspection_findings f
|
|
26962
|
-
JOIN audit_events e ON e.id = f.audit_event_id
|
|
26963
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
26964
|
-
LEFT JOIN ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
26965
|
-
ON latest.finding_key = f.finding_key
|
|
26966
|
-
${predicate}
|
|
26967
|
-
)
|
|
26968
|
-
WHERE rn <= :cap
|
|
26969
|
-
ORDER BY occurred_at DESC, id DESC`
|
|
26970
|
-
),
|
|
26971
|
-
{ cap: PREVIEW_INSTANCES_PER_GROUP, ...sessionParams }
|
|
26972
|
-
);
|
|
26973
|
-
const groupable = rows.map((r) => ({
|
|
26974
|
-
id: r.id,
|
|
26975
|
-
ruleId: r.rule_id,
|
|
26976
|
-
category: r.category,
|
|
26977
|
-
severity: r.severity,
|
|
26978
|
-
maskedMatch: r.masked_match,
|
|
26979
|
-
actionTaken: r.action_taken,
|
|
26980
|
-
confidence: r.confidence,
|
|
26981
|
-
occurredAt: epochMillisToIso(r.occurred_at),
|
|
26982
|
-
sourceTool: r.source_tool,
|
|
26983
|
-
repo: r.repo ?? "",
|
|
26984
|
-
file: r.file ?? "",
|
|
26985
|
-
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
26986
|
-
eventId: r.event_id,
|
|
26987
|
-
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
26988
|
-
status: deriveInstanceStatus(r)
|
|
26989
|
-
}));
|
|
27146
|
+
const rows = this.previewRows(aggregates, {
|
|
27147
|
+
sessionId: query.sessionId,
|
|
27148
|
+
from: query.from
|
|
27149
|
+
});
|
|
27150
|
+
const groupable = rows.map(toFlatFindingRow);
|
|
26990
27151
|
const allGroups = buildFindingGroups(groupable, { aggregates });
|
|
26991
27152
|
const filterOpts = {
|
|
26992
27153
|
severity: query.severity,
|
|
@@ -27072,8 +27233,10 @@ var SqliteFindingsRepository = class {
|
|
|
27072
27233
|
*
|
|
27073
27234
|
* The scan runs from the top of the scope on every request, not from the
|
|
27074
27235
|
* cursor: `totals` and `facets` describe the whole filtered scope and must not
|
|
27075
|
-
* move as the caller pages. Rows
|
|
27076
|
-
*
|
|
27236
|
+
* move as the caller pages. Rows come off ONE statement, iterated rather
|
|
27237
|
+
* than materialized (`scanFindingRows`), so memory stays flat while the
|
|
27238
|
+
* counting runs — a generator streaming the index order, not a sequence of
|
|
27239
|
+
* fetched batches; only the page itself is retained.
|
|
27077
27240
|
*/
|
|
27078
27241
|
listFindingInstances(query) {
|
|
27079
27242
|
const opts = {
|
|
@@ -27089,6 +27252,10 @@ var SqliteFindingsRepository = class {
|
|
|
27089
27252
|
};
|
|
27090
27253
|
const limit = query.limit ?? DEFAULT_FLAT_FINDINGS_LIMIT;
|
|
27091
27254
|
const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
|
|
27255
|
+
const isPastCursor = cursor === null ? () => true : (row) => {
|
|
27256
|
+
const rowMs = isoToEpochMillis(row.occurredAt);
|
|
27257
|
+
return rowMs <= cursor.startedAtMs && (rowMs < cursor.startedAtMs || row.id < cursor.id);
|
|
27258
|
+
};
|
|
27092
27259
|
const accumulator = createInstanceFacetAccumulator(opts);
|
|
27093
27260
|
const items = [];
|
|
27094
27261
|
let total = 0;
|
|
@@ -27101,6 +27268,7 @@ var SqliteFindingsRepository = class {
|
|
|
27101
27268
|
accumulator.add(row);
|
|
27102
27269
|
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27103
27270
|
total += 1;
|
|
27271
|
+
if (!isPastCursor(row)) continue;
|
|
27104
27272
|
if (items.length < limit) {
|
|
27105
27273
|
items.push(toInstanceDetail(row));
|
|
27106
27274
|
last = row;
|
|
@@ -27109,15 +27277,6 @@ var SqliteFindingsRepository = class {
|
|
|
27109
27277
|
}
|
|
27110
27278
|
}
|
|
27111
27279
|
const nextCursor = hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null;
|
|
27112
|
-
if (cursor !== null) {
|
|
27113
|
-
const resumed = this.pageAfter(cursor, opts, limit, query);
|
|
27114
|
-
return Promise.resolve({
|
|
27115
|
-
totals: { findings: total },
|
|
27116
|
-
facets: accumulator.facets(),
|
|
27117
|
-
items: resumed.items,
|
|
27118
|
-
nextCursor: resumed.nextCursor
|
|
27119
|
-
});
|
|
27120
|
-
}
|
|
27121
27280
|
return Promise.resolve({
|
|
27122
27281
|
totals: { findings: total },
|
|
27123
27282
|
facets: accumulator.facets(),
|
|
@@ -27125,35 +27284,6 @@ var SqliteFindingsRepository = class {
|
|
|
27125
27284
|
nextCursor
|
|
27126
27285
|
});
|
|
27127
27286
|
}
|
|
27128
|
-
/**
|
|
27129
|
-
* The page of matching rows strictly after `cursor`. Separate from the
|
|
27130
|
-
* counting pass because that one starts at the top of the scope by design;
|
|
27131
|
-
* this one narrows the scan with the same keyset predicate the activity list
|
|
27132
|
-
* uses, so a later page costs less than the first rather than more.
|
|
27133
|
-
*/
|
|
27134
|
-
pageAfter(cursor, opts, limit, query) {
|
|
27135
|
-
const items = [];
|
|
27136
|
-
let last;
|
|
27137
|
-
let hasMore = false;
|
|
27138
|
-
for (const row of this.scanFindingRows({
|
|
27139
|
-
sessionId: query.sessionId,
|
|
27140
|
-
from: query.from,
|
|
27141
|
-
after: cursor
|
|
27142
|
-
})) {
|
|
27143
|
-
if (!matchesInstanceFilters(row, opts)) continue;
|
|
27144
|
-
if (items.length < limit) {
|
|
27145
|
-
items.push(toInstanceDetail(row));
|
|
27146
|
-
last = row;
|
|
27147
|
-
} else {
|
|
27148
|
-
hasMore = true;
|
|
27149
|
-
break;
|
|
27150
|
-
}
|
|
27151
|
-
}
|
|
27152
|
-
return {
|
|
27153
|
-
items,
|
|
27154
|
-
nextCursor: hasMore && last ? encodeKeysetCursor({ startedAtMs: isoToEpochMillis(last.occurredAt), id: last.id }) : null
|
|
27155
|
-
};
|
|
27156
|
-
}
|
|
27157
27287
|
/**
|
|
27158
27288
|
* The same findings folded by location: repository, then file within it.
|
|
27159
27289
|
*
|
|
@@ -27236,25 +27366,111 @@ var SqliteFindingsRepository = class {
|
|
|
27236
27366
|
});
|
|
27237
27367
|
}
|
|
27238
27368
|
/**
|
|
27239
|
-
*
|
|
27369
|
+
* Each group's newest instances, for the table's expanded rows.
|
|
27370
|
+
*
|
|
27371
|
+
* ONE index-ordered scan with early termination, and the shape is the point.
|
|
27372
|
+
* The natural spelling — `ROW_NUMBER() OVER (PARTITION BY rule_id ORDER BY
|
|
27373
|
+
* started_at DESC)` then `WHERE rn <= cap` — sorts EVERY finding in scope
|
|
27374
|
+
* through a temp B-tree to keep a bounded preview of each group, and then
|
|
27375
|
+
* sorts the survivors again for the page order. Both sorts grow with the
|
|
27376
|
+
* store while the answer does not.
|
|
27377
|
+
*
|
|
27378
|
+
* Instead the scan walks `audit_events` newest-first off `idx_audit_started_at`
|
|
27379
|
+
* (or the session or window index the scope names — see `findingScanSql`),
|
|
27380
|
+
* which is already the order the page wants, and keeps rows per rule until
|
|
27381
|
+
* each rule has as many as it can show. The aggregate the caller already holds
|
|
27382
|
+
* says how many that is: `min(instanceCount, PREVIEW_INSTANCES_PER_GROUP)`
|
|
27383
|
+
* per rule, summed, is the number of rows this scan has to find, and it stops
|
|
27384
|
+
* on the last one. That sum is bounded by `rules * PREVIEW_INSTANCES_PER_GROUP`
|
|
27385
|
+
* (8,000 at this repo's 40-rule bench corpus), not by a fixed row count — a
|
|
27386
|
+
* store with many firing rules widens it. The bound that DOES hold
|
|
27387
|
+
* unconditionally is the sorted form's floor: this scan visits at most as
|
|
27388
|
+
* many rows as `ROW_NUMBER() OVER (PARTITION BY rule_id …)` would have
|
|
27389
|
+
* sorted, and stops the moment every rule has its cap, where the sorted form
|
|
27390
|
+
* sorts the whole scope regardless. The true worst case — the rarest rule's
|
|
27391
|
+
* wanted instances sitting at the tail of the scope — is one pass over
|
|
27392
|
+
* everything in scope with a block sort of the id tie-break only, never a
|
|
27393
|
+
* sort of the scope, which is still that floor.
|
|
27394
|
+
*
|
|
27395
|
+
* A row whose rule the aggregate did not see is skipped: the two statements
|
|
27396
|
+
* run without a shared snapshot, so a capture landing between them can add a
|
|
27397
|
+
* rule here that has no counts there, and the counts are what the group is
|
|
27398
|
+
* built from.
|
|
27399
|
+
*/
|
|
27400
|
+
previewRows(aggregates, scope) {
|
|
27401
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
27402
|
+
let remaining = 0;
|
|
27403
|
+
for (const [ruleId, agg] of aggregates) {
|
|
27404
|
+
const n = Math.min(agg.instanceCount, PREVIEW_INSTANCES_PER_GROUP);
|
|
27405
|
+
wanted.set(ruleId, n);
|
|
27406
|
+
remaining += n;
|
|
27407
|
+
}
|
|
27408
|
+
const rows = [];
|
|
27409
|
+
if (remaining === 0) return rows;
|
|
27410
|
+
const { sql, params } = this.findingScanSql(scope);
|
|
27411
|
+
const taken = /* @__PURE__ */ new Map();
|
|
27412
|
+
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27413
|
+
const want = wanted.get(r.rule_id);
|
|
27414
|
+
if (want === void 0) continue;
|
|
27415
|
+
const have = taken.get(r.rule_id) ?? 0;
|
|
27416
|
+
if (have >= want) continue;
|
|
27417
|
+
taken.set(r.rule_id, have + 1);
|
|
27418
|
+
rows.push(r);
|
|
27419
|
+
remaining -= 1;
|
|
27420
|
+
if (remaining === 0) break;
|
|
27421
|
+
}
|
|
27422
|
+
return rows;
|
|
27423
|
+
}
|
|
27424
|
+
/**
|
|
27425
|
+
* Every finding in scope as a FlatFindingRow, newest first, streamed.
|
|
27240
27426
|
*
|
|
27241
27427
|
* A generator so a caller streams the scope without it ever being an array:
|
|
27242
27428
|
* the flat list counts and facets the whole filtered scope, which on a large
|
|
27243
|
-
* store is far more rows than any page.
|
|
27244
|
-
*
|
|
27245
|
-
*
|
|
27246
|
-
*
|
|
27247
|
-
*
|
|
27248
|
-
*
|
|
27249
|
-
* makes it a point lookup per row, and the derived table would re-materialize
|
|
27250
|
-
* a window over the whole resolution table once per batch.
|
|
27429
|
+
* store is far more rows than any page. The rows come off ONE statement,
|
|
27430
|
+
* iterated rather than materialized, in the index order `findingScanSql`
|
|
27431
|
+
* arranges — so the scan is a single pass with a block sort of the id
|
|
27432
|
+
* tie-break only, never a sort of the scope, where a sequence of
|
|
27433
|
+
* keyset-bounded batches re-sorted everything below the cursor on every
|
|
27434
|
+
* batch and cost the square of the scope.
|
|
27251
27435
|
*
|
|
27252
|
-
* `
|
|
27253
|
-
* would be missing from its own facet, which is
|
|
27254
|
-
* dimension
|
|
27436
|
+
* `sessionId` and `from` carry ONLY what no facet counts — a filter
|
|
27437
|
+
* dimension narrowed here would be missing from its own facet, which is
|
|
27438
|
+
* computed by excluding that dimension (see listFindingInstances). There is
|
|
27439
|
+
* no `after`/cursor parameter: a keyset page is collected inline from this
|
|
27440
|
+
* same pass (`listFindingInstances`' `isPastCursor`) rather than by a second,
|
|
27441
|
+
* narrower statement, since the counting pass already visits every row a
|
|
27442
|
+
* page-2+ request would otherwise re-seek for.
|
|
27255
27443
|
*/
|
|
27256
27444
|
*scanFindingRows(scope) {
|
|
27257
|
-
const
|
|
27445
|
+
const { sql, params } = this.findingScanSql(scope);
|
|
27446
|
+
for (const r of iterateRows(this.db.prepare(sql), params)) {
|
|
27447
|
+
yield toFlatFindingRow(r);
|
|
27448
|
+
}
|
|
27449
|
+
}
|
|
27450
|
+
/**
|
|
27451
|
+
* The one statement both instance-level scans run: every finding in scope,
|
|
27452
|
+
* joined to its event and definition, newest first.
|
|
27453
|
+
*
|
|
27454
|
+
* THE PLAN IS THE POINT, and two things in the SQL exist only to pin it —
|
|
27455
|
+
* the same two `recentFindings` documents at length, for the same reason:
|
|
27456
|
+
*
|
|
27457
|
+
* - **`+e.event_type`** makes the capture-kind predicate non-indexable, so
|
|
27458
|
+
* the planner cannot pick `idx_audit_type_t` and then sort. That index
|
|
27459
|
+
* yields `started_at` order per event type, not across the four, so
|
|
27460
|
+
* satisfying the ORDER BY from it would need a merge SQLite does not do.
|
|
27461
|
+
* Freed of it, the planner walks `idx_audit_started_at` backwards — or
|
|
27462
|
+
* `idx_audit_session` for a session scope, which is also `started_at`
|
|
27463
|
+
* ordered within the session — and the order falls out of the index.
|
|
27464
|
+
* - **`CROSS JOIN`** pins `audit_events` as the driving table. With plain
|
|
27465
|
+
* JOINs the planner drives from the findings and sorts everything.
|
|
27466
|
+
*
|
|
27467
|
+
* The latest-resolution lookup is the CORRELATED form: only `status` is
|
|
27468
|
+
* needed, `idx_finding_resolution_key_created` answers it with one backward
|
|
27469
|
+
* index probe per keyed row, and a derived table over the whole resolution
|
|
27470
|
+
* table would be materialized before the first row streamed.
|
|
27471
|
+
*/
|
|
27472
|
+
findingScanSql(scope) {
|
|
27473
|
+
const conditions = [`+e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})`];
|
|
27258
27474
|
const params = [];
|
|
27259
27475
|
if (scope.sessionId !== void 0 && scope.sessionId !== "") {
|
|
27260
27476
|
conditions.push("e.root_session_id = ?");
|
|
@@ -27268,58 +27484,24 @@ var SqliteFindingsRepository = class {
|
|
|
27268
27484
|
d.severity AS severity, f.masked_match AS masked_match,
|
|
27269
27485
|
f.action_taken AS action_taken, f.confidence AS confidence,
|
|
27270
27486
|
e.started_at AS occurred_at,
|
|
27271
|
-
|
|
27272
|
-
|
|
27273
|
-
|
|
27274
|
-
|
|
27487
|
+
e.source_tool AS source_tool,
|
|
27488
|
+
e.repo AS repo,
|
|
27489
|
+
e.file_path AS file,
|
|
27490
|
+
e.tool_name AS tool_name,
|
|
27275
27491
|
f.audit_event_id AS event_id, e.root_session_id AS session_id,
|
|
27276
27492
|
e.event_type AS kind, f.finding_key AS finding_key,
|
|
27277
27493
|
${latestResolutionStatusSql("f")} AS latest_status
|
|
27278
|
-
FROM
|
|
27279
|
-
JOIN
|
|
27280
|
-
JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27494
|
+
FROM audit_events e
|
|
27495
|
+
CROSS JOIN inspection_findings f ON f.audit_event_id = e.id
|
|
27496
|
+
CROSS JOIN inspection_definitions d ON d.id = f.inspection_definition_id
|
|
27281
27497
|
WHERE ${conditions.join(" AND ")}
|
|
27282
|
-
|
|
27283
|
-
|
|
27284
|
-
LIMIT ?`;
|
|
27285
|
-
let after = scope.after ?? { startedAtMs: Number.MAX_SAFE_INTEGER, id: "\uFFFF" };
|
|
27286
|
-
for (; ; ) {
|
|
27287
|
-
const rows = allRows(this.db.prepare(sql), [
|
|
27288
|
-
...params,
|
|
27289
|
-
after.startedAtMs,
|
|
27290
|
-
after.startedAtMs,
|
|
27291
|
-
after.id,
|
|
27292
|
-
SCAN_BATCH_ROWS
|
|
27293
|
-
]);
|
|
27294
|
-
for (const r of rows) {
|
|
27295
|
-
yield {
|
|
27296
|
-
id: r.id,
|
|
27297
|
-
ruleId: r.rule_id,
|
|
27298
|
-
category: r.category,
|
|
27299
|
-
severity: r.severity,
|
|
27300
|
-
maskedMatch: r.masked_match,
|
|
27301
|
-
actionTaken: r.action_taken,
|
|
27302
|
-
confidence: r.confidence,
|
|
27303
|
-
occurredAt: epochMillisToIso(r.occurred_at),
|
|
27304
|
-
sourceTool: r.source_tool,
|
|
27305
|
-
repo: r.repo ?? "",
|
|
27306
|
-
file: r.file ?? "",
|
|
27307
|
-
...r.tool_name === null ? {} : { toolName: r.tool_name },
|
|
27308
|
-
eventId: r.event_id,
|
|
27309
|
-
...r.session_id === null ? {} : { sessionId: r.session_id },
|
|
27310
|
-
status: deriveInstanceStatus(r)
|
|
27311
|
-
};
|
|
27312
|
-
}
|
|
27313
|
-
if (rows.length < SCAN_BATCH_ROWS) return;
|
|
27314
|
-
const lastRow = rows[rows.length - 1];
|
|
27315
|
-
if (lastRow === void 0) return;
|
|
27316
|
-
after = { startedAtMs: lastRow.occurred_at, id: lastRow.id };
|
|
27317
|
-
}
|
|
27498
|
+
ORDER BY e.started_at DESC, f.id DESC`;
|
|
27499
|
+
return { sql, params };
|
|
27318
27500
|
}
|
|
27319
27501
|
groupAggregates(withSearchText, scope) {
|
|
27320
|
-
const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT
|
|
27321
|
-
group_concat(DISTINCT
|
|
27322
|
-
group_concat(DISTINCT 'via ' ||
|
|
27502
|
+
const innerSearchColumns = withSearchText ? `, group_concat(DISTINCT e.repo) AS repos,
|
|
27503
|
+
group_concat(DISTINCT e.file_path) AS files,
|
|
27504
|
+
group_concat(DISTINCT 'via ' || e.tool_name) AS tool_names` : `, NULL AS repos, NULL AS files, NULL AS tool_names`;
|
|
27323
27505
|
const rows = this.db.prepare(
|
|
27324
27506
|
`SELECT rule_id,
|
|
27325
27507
|
sum(tuple_count) AS instance_count,
|
|
@@ -27337,7 +27519,7 @@ var SqliteFindingsRepository = class {
|
|
|
27337
27519
|
coalesce(latest.status, '') AS status_tuple,
|
|
27338
27520
|
count(*) AS tuple_count,
|
|
27339
27521
|
max(e.started_at) AS latest_at,
|
|
27340
|
-
group_concat(DISTINCT
|
|
27522
|
+
group_concat(DISTINCT e.source_tool) AS source_tools,
|
|
27341
27523
|
group_concat(DISTINCT f.action_taken) AS actions_taken
|
|
27342
27524
|
${innerSearchColumns}
|
|
27343
27525
|
FROM inspection_findings f
|
|
@@ -27468,6 +27650,8 @@ function isoDay(ms) {
|
|
|
27468
27650
|
// ../../packages/persistence/src/repositories/history-sync.ts
|
|
27469
27651
|
var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
|
|
27470
27652
|
var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27653
|
+
var OUTBOX_CAPTURE_EVENT_TYPES = ["prompt", "response", "tool_use"];
|
|
27654
|
+
var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
|
|
27471
27655
|
var SKIPPED = -1;
|
|
27472
27656
|
var ROW_COLUMNS = `id,
|
|
27473
27657
|
parent_id AS parentId,
|
|
@@ -27507,6 +27691,20 @@ var SqliteHistorySyncRepository = class {
|
|
|
27507
27691
|
ORDER BY (event_type = 'session') DESC, started_at
|
|
27508
27692
|
LIMIT :limit`
|
|
27509
27693
|
);
|
|
27694
|
+
this.captureRowsStmt = db.prepare(
|
|
27695
|
+
`SELECT ${ROW_COLUMNS}
|
|
27696
|
+
FROM audit_events
|
|
27697
|
+
WHERE synced_at IS NULL
|
|
27698
|
+
AND sync_claimed_at IS NULL
|
|
27699
|
+
AND outbox_owed = 1
|
|
27700
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})
|
|
27701
|
+
AND started_at < :before
|
|
27702
|
+
ORDER BY started_at
|
|
27703
|
+
LIMIT :limit`
|
|
27704
|
+
);
|
|
27705
|
+
this.markOwedStmt = db.prepare(
|
|
27706
|
+
`UPDATE audit_events SET outbox_owed = 1 WHERE id = :id AND synced_at IS NULL`
|
|
27707
|
+
);
|
|
27510
27708
|
this.stampStmt = db.prepare(
|
|
27511
27709
|
`UPDATE audit_events SET synced_at = :at, sync_claimed_at = NULL WHERE id = :id`
|
|
27512
27710
|
);
|
|
@@ -27538,6 +27736,12 @@ var SqliteHistorySyncRepository = class {
|
|
|
27538
27736
|
FROM audit_events
|
|
27539
27737
|
WHERE event_type IN (${TYPE_LIST})`
|
|
27540
27738
|
);
|
|
27739
|
+
this.captureSkipCountStmt = db.prepare(
|
|
27740
|
+
`SELECT COUNT(*) AS skipped
|
|
27741
|
+
FROM audit_events
|
|
27742
|
+
WHERE synced_at = ${String(SKIPPED)}
|
|
27743
|
+
AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27744
|
+
);
|
|
27541
27745
|
this.fingerprintStmt = db.prepare(
|
|
27542
27746
|
`SELECT endpoint_fingerprint AS fingerprint, backlog_before AS backlogBefore
|
|
27543
27747
|
FROM history_sync WHERE id = 1`
|
|
@@ -27547,6 +27751,10 @@ var SqliteHistorySyncRepository = class {
|
|
|
27547
27751
|
SET endpoint_fingerprint = :fingerprint, backlog_before = :backlogBefore
|
|
27548
27752
|
WHERE id = 1`
|
|
27549
27753
|
);
|
|
27754
|
+
this.disownCapturesStmt = db.prepare(
|
|
27755
|
+
`UPDATE audit_events SET outbox_owed = NULL
|
|
27756
|
+
WHERE outbox_owed IS NOT NULL AND event_type IN (${CAPTURE_TYPE_LIST})`
|
|
27757
|
+
);
|
|
27550
27758
|
this.rearmStmt = db.prepare(
|
|
27551
27759
|
`UPDATE audit_events SET synced_at = NULL
|
|
27552
27760
|
WHERE synced_at > 0 AND event_type IN (${TYPE_LIST})`
|
|
@@ -27619,6 +27827,10 @@ var SqliteHistorySyncRepository = class {
|
|
|
27619
27827
|
closeWindowStmt;
|
|
27620
27828
|
releaseBoundaryStmt;
|
|
27621
27829
|
freezeBoundaryStmt;
|
|
27830
|
+
captureRowsStmt;
|
|
27831
|
+
markOwedStmt;
|
|
27832
|
+
captureSkipCountStmt;
|
|
27833
|
+
disownCapturesStmt;
|
|
27622
27834
|
partitionStmt;
|
|
27623
27835
|
claimRowStmt;
|
|
27624
27836
|
releaseRowStmt;
|
|
@@ -27652,6 +27864,34 @@ var SqliteHistorySyncRepository = class {
|
|
|
27652
27864
|
pendingRows(sessionId, limit, before) {
|
|
27653
27865
|
return allRows(this.rowsStmt, { sessionId, limit, before });
|
|
27654
27866
|
}
|
|
27867
|
+
/**
|
|
27868
|
+
* Captures this machine still owes the deployment, oldest first.
|
|
27869
|
+
*
|
|
27870
|
+
* Selected by the `outbox_owed` marker the attached forward path writes, not
|
|
27871
|
+
* by a time window — see captureRowsStmt for why a window could not express
|
|
27872
|
+
* this. `before` is the grace window that leaves a just-recorded capture to
|
|
27873
|
+
* the live path.
|
|
27874
|
+
*/
|
|
27875
|
+
pendingCaptureRows(limit, before) {
|
|
27876
|
+
return allRows(this.captureRowsStmt, { limit, before });
|
|
27877
|
+
}
|
|
27878
|
+
/**
|
|
27879
|
+
* Record that a capture is OWED to the deployment.
|
|
27880
|
+
*
|
|
27881
|
+
* Written by the attached forward path when a live send did not confirm
|
|
27882
|
+
* delivery, and read by the drain as the whole of its eligibility test. It is
|
|
27883
|
+
* a fact rather than an inference: the machine was attached, the send did not
|
|
27884
|
+
* land, so the row is owed — which no time window can state, because the same
|
|
27885
|
+
* window that holds the rows a past attachment left owed also holds every
|
|
27886
|
+
* capture recorded while the machine was DETACHED, and those were never
|
|
27887
|
+
* offered to anyone.
|
|
27888
|
+
*
|
|
27889
|
+
* Idempotent, and never un-set: `markSynced` settling the row is what takes it
|
|
27890
|
+
* out of the drain's read.
|
|
27891
|
+
*/
|
|
27892
|
+
markCaptureOwed(id) {
|
|
27893
|
+
this.markOwedStmt.run({ id });
|
|
27894
|
+
}
|
|
27655
27895
|
/** Record delivery. Called only AFTER the far side has accepted the rows. */
|
|
27656
27896
|
markSynced(ids, atMs) {
|
|
27657
27897
|
this.stampAll(ids, atMs);
|
|
@@ -27735,10 +27975,12 @@ var SqliteHistorySyncRepository = class {
|
|
|
27735
27975
|
this.countsStmt,
|
|
27736
27976
|
{ before }
|
|
27737
27977
|
);
|
|
27978
|
+
const captures = getRow(this.captureSkipCountStmt);
|
|
27738
27979
|
return {
|
|
27739
27980
|
pending: row?.pending ?? 0,
|
|
27740
27981
|
sent: row?.sent ?? 0,
|
|
27741
|
-
skipped: row?.skipped ?? 0
|
|
27982
|
+
skipped: row?.skipped ?? 0,
|
|
27983
|
+
capturesSkipped: captures?.skipped ?? 0
|
|
27742
27984
|
};
|
|
27743
27985
|
}
|
|
27744
27986
|
/**
|
|
@@ -27779,7 +28021,11 @@ var SqliteHistorySyncRepository = class {
|
|
|
27779
28021
|
withTransaction(
|
|
27780
28022
|
this.db,
|
|
27781
28023
|
() => {
|
|
28024
|
+
const previous = getRow(this.fingerprintStmt)?.fingerprint;
|
|
27782
28025
|
this.rearmStmt.run();
|
|
28026
|
+
if (previous !== null && previous !== void 0 && previous !== fingerprint) {
|
|
28027
|
+
this.disownCapturesStmt.run();
|
|
28028
|
+
}
|
|
27783
28029
|
this.setFingerprintStmt.run({ fingerprint, backlogBefore });
|
|
27784
28030
|
},
|
|
27785
28031
|
"IMMEDIATE"
|
|
@@ -27976,7 +28222,259 @@ var SqliteInspectionFindingsRepository = class {
|
|
|
27976
28222
|
};
|
|
27977
28223
|
|
|
27978
28224
|
// ../../packages/persistence/src/repositories/installed-packs.ts
|
|
27979
|
-
import { createHash as createHash2, randomUUID as
|
|
28225
|
+
import { createHash as createHash2, randomUUID as randomUUID4 } from "crypto";
|
|
28226
|
+
|
|
28227
|
+
// ../../packages/persistence/src/policy-floor.ts
|
|
28228
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
28229
|
+
import { join as join6 } from "path";
|
|
28230
|
+
|
|
28231
|
+
// ../../packages/persistence/src/local-layout.ts
|
|
28232
|
+
import { renameSync as renameSync3 } from "fs";
|
|
28233
|
+
import { mkdir } from "fs/promises";
|
|
28234
|
+
import { homedir } from "os";
|
|
28235
|
+
import { join as join4 } from "path";
|
|
28236
|
+
function defaultDataDir() {
|
|
28237
|
+
return join4(homedir(), ".aka");
|
|
28238
|
+
}
|
|
28239
|
+
function settingsDir(base = defaultDataDir()) {
|
|
28240
|
+
return join4(base, "settings");
|
|
28241
|
+
}
|
|
28242
|
+
function dataDir(base = defaultDataDir()) {
|
|
28243
|
+
return join4(base, "data");
|
|
28244
|
+
}
|
|
28245
|
+
function dbPath(base = defaultDataDir()) {
|
|
28246
|
+
return join4(dataDir(base), "aka.db");
|
|
28247
|
+
}
|
|
28248
|
+
function keysDir(base = defaultDataDir()) {
|
|
28249
|
+
return join4(base, "keys");
|
|
28250
|
+
}
|
|
28251
|
+
async function ensureDataDir(dir = defaultDataDir()) {
|
|
28252
|
+
await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
28253
|
+
tightenDir(dir);
|
|
28254
|
+
}
|
|
28255
|
+
function ensureLayoutDirSync(dir = defaultDataDir()) {
|
|
28256
|
+
ensureDataDirSync(dir);
|
|
28257
|
+
}
|
|
28258
|
+
function migrateLegacyLayout(base = defaultDataDir()) {
|
|
28259
|
+
const moves = [
|
|
28260
|
+
{ name: "config.json", dest: settingsDir(base) },
|
|
28261
|
+
{ name: "policy-cache.json", dest: dataDir(base) }
|
|
28262
|
+
];
|
|
28263
|
+
for (const { name, dest } of moves) {
|
|
28264
|
+
try {
|
|
28265
|
+
ensureDataDirSync(dest);
|
|
28266
|
+
const moved = join4(dest, name);
|
|
28267
|
+
renameSync3(join4(base, name), moved);
|
|
28268
|
+
tightenFile(moved);
|
|
28269
|
+
} catch {
|
|
28270
|
+
}
|
|
28271
|
+
}
|
|
28272
|
+
}
|
|
28273
|
+
|
|
28274
|
+
// ../../packages/persistence/src/settings.ts
|
|
28275
|
+
import { readFileSync as readFileSync4 } from "fs";
|
|
28276
|
+
import { join as join5 } from "path";
|
|
28277
|
+
|
|
28278
|
+
// ../../packages/persistence/src/file-lock.ts
|
|
28279
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
28280
|
+
import {
|
|
28281
|
+
closeSync,
|
|
28282
|
+
existsSync as existsSync2,
|
|
28283
|
+
openSync,
|
|
28284
|
+
readFileSync as readFileSync2,
|
|
28285
|
+
rmSync as rmSync5,
|
|
28286
|
+
statSync as statSync3,
|
|
28287
|
+
writeFileSync as writeFileSync2
|
|
28288
|
+
} from "fs";
|
|
28289
|
+
import { hostname as hostname3 } from "os";
|
|
28290
|
+
var PARK = new Int32Array(new SharedArrayBuffer(4));
|
|
28291
|
+
|
|
28292
|
+
// ../../packages/persistence/src/managed-settings.ts
|
|
28293
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
28294
|
+
import { posix, win32 } from "path";
|
|
28295
|
+
function managedSettingsPaths(platform2 = process.platform) {
|
|
28296
|
+
if (platform2 === "darwin") {
|
|
28297
|
+
return [
|
|
28298
|
+
posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
|
|
28299
|
+
posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
|
|
28300
|
+
];
|
|
28301
|
+
}
|
|
28302
|
+
if (platform2 === "win32") {
|
|
28303
|
+
return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
|
|
28304
|
+
}
|
|
28305
|
+
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
28306
|
+
}
|
|
28307
|
+
function readManagedSettings(paths = managedSettingsPaths()) {
|
|
28308
|
+
for (const path of paths) {
|
|
28309
|
+
let text;
|
|
28310
|
+
try {
|
|
28311
|
+
text = readFileSync3(path, "utf8");
|
|
28312
|
+
} catch {
|
|
28313
|
+
continue;
|
|
28314
|
+
}
|
|
28315
|
+
const record2 = parseJsonObject(text);
|
|
28316
|
+
if (!record2) continue;
|
|
28317
|
+
const parsed2 = ManagedSettings.safeParse(record2);
|
|
28318
|
+
if (parsed2.success) return parsed2.data;
|
|
28319
|
+
}
|
|
28320
|
+
return null;
|
|
28321
|
+
}
|
|
28322
|
+
function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
|
|
28323
|
+
if (!managed) return settings;
|
|
28324
|
+
const { values } = managed;
|
|
28325
|
+
const merged = { ...settings };
|
|
28326
|
+
if (values.runMode !== void 0) merged.runMode = values.runMode;
|
|
28327
|
+
if (values.controlPlane !== void 0) {
|
|
28328
|
+
merged.controlPlane = {
|
|
28329
|
+
...values.controlPlane,
|
|
28330
|
+
// The administrator pinned WHICH deployment, not WHEN this machine
|
|
28331
|
+
// joined it. Keep the user's own attach time when the endpoint is
|
|
28332
|
+
// unchanged, so a managed machine does not appear to re-attach on every
|
|
28333
|
+
// read; stamp a fresh one when the administrator moved it.
|
|
28334
|
+
attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
|
|
28335
|
+
};
|
|
28336
|
+
}
|
|
28337
|
+
if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
|
|
28338
|
+
if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
|
|
28339
|
+
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
28340
|
+
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
28341
|
+
if (values.redactFallback !== void 0) merged.redactFallback = values.redactFallback;
|
|
28342
|
+
if (values.vaultConsent !== void 0) {
|
|
28343
|
+
merged.vaultConsent = values.vaultConsent ? (
|
|
28344
|
+
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
28345
|
+
// at the current version otherwise.
|
|
28346
|
+
settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
|
|
28347
|
+
) : void 0;
|
|
28348
|
+
}
|
|
28349
|
+
if (values.modelJudgeConsent !== void 0) {
|
|
28350
|
+
merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
|
|
28351
|
+
acknowledgedAt: now().toISOString(),
|
|
28352
|
+
payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
|
|
28353
|
+
} : void 0;
|
|
28354
|
+
}
|
|
28355
|
+
return merged;
|
|
28356
|
+
}
|
|
28357
|
+
|
|
28358
|
+
// ../../packages/persistence/src/settings.ts
|
|
28359
|
+
var SETTINGS_FILENAME = "settings.json";
|
|
28360
|
+
function readWorkspaceSettings(base = defaultDataDir()) {
|
|
28361
|
+
return overlayManagedSettings(readUserSettings(base), readManagedSettings());
|
|
28362
|
+
}
|
|
28363
|
+
function readUserSettings(base) {
|
|
28364
|
+
const record2 = readJson(join5(settingsDir(base), SETTINGS_FILENAME));
|
|
28365
|
+
if (!record2) return defaultWorkspaceSettings();
|
|
28366
|
+
try {
|
|
28367
|
+
return WorkspaceSettings.parse(record2);
|
|
28368
|
+
} catch {
|
|
28369
|
+
return defaultWorkspaceSettings();
|
|
28370
|
+
}
|
|
28371
|
+
}
|
|
28372
|
+
function readJson(file2) {
|
|
28373
|
+
let text;
|
|
28374
|
+
try {
|
|
28375
|
+
text = readFileSync4(file2, "utf8");
|
|
28376
|
+
} catch {
|
|
28377
|
+
return null;
|
|
28378
|
+
}
|
|
28379
|
+
return parseJsonObject(text) ?? null;
|
|
28380
|
+
}
|
|
28381
|
+
|
|
28382
|
+
// ../../packages/persistence/src/policy-floor.ts
|
|
28383
|
+
function refusalMessage(pack, attempted, floor, refusal) {
|
|
28384
|
+
switch (refusal) {
|
|
28385
|
+
case "lock":
|
|
28386
|
+
return `refusing to re-assign '${pack}': its policy is set by the connected control plane`;
|
|
28387
|
+
case "disable":
|
|
28388
|
+
return `refusing to disable '${pack}': it is governed by the connected control plane`;
|
|
28389
|
+
case "floor":
|
|
28390
|
+
return `refusing to set '${pack}' to '${attempted ?? "unassigned"}': the connected control plane requires at least '${floor}'`;
|
|
28391
|
+
}
|
|
28392
|
+
}
|
|
28393
|
+
var PolicyFloorError = class extends Error {
|
|
28394
|
+
/** `namespace/packId` of the detection whose write was refused. */
|
|
28395
|
+
pack;
|
|
28396
|
+
/**
|
|
28397
|
+
* The archetype the caller asked for, or null when the write named none —
|
|
28398
|
+
* clearing the assignment, or switching the detection off.
|
|
28399
|
+
*/
|
|
28400
|
+
attempted;
|
|
28401
|
+
/** The weakest archetype the control plane permits for this pack. */
|
|
28402
|
+
floor;
|
|
28403
|
+
refusal;
|
|
28404
|
+
constructor(pack, attempted, floor, refusal) {
|
|
28405
|
+
super(refusalMessage(pack, attempted, floor, refusal));
|
|
28406
|
+
this.name = "PolicyFloorError";
|
|
28407
|
+
this.pack = pack;
|
|
28408
|
+
this.attempted = attempted;
|
|
28409
|
+
this.floor = floor;
|
|
28410
|
+
this.refusal = refusal;
|
|
28411
|
+
}
|
|
28412
|
+
};
|
|
28413
|
+
function readCachedPolicyBundle(base = defaultDataDir()) {
|
|
28414
|
+
try {
|
|
28415
|
+
const raw = readFileSync5(join6(dataDir(base), POLICY_CACHE_FILENAME), "utf8");
|
|
28416
|
+
const parsed2 = JSON.parse(raw);
|
|
28417
|
+
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
28418
|
+
return PolicyBundle.parse(parsed2.bundle);
|
|
28419
|
+
} catch {
|
|
28420
|
+
return null;
|
|
28421
|
+
}
|
|
28422
|
+
}
|
|
28423
|
+
function indexEnabled(policies) {
|
|
28424
|
+
const byRuleId = /* @__PURE__ */ new Map();
|
|
28425
|
+
const byCategory = /* @__PURE__ */ new Map();
|
|
28426
|
+
for (const policy of policies) {
|
|
28427
|
+
if (!policy.enabled) continue;
|
|
28428
|
+
if ("ruleId" in policy.target) {
|
|
28429
|
+
if (!byRuleId.has(policy.target.ruleId)) byRuleId.set(policy.target.ruleId, policy.action);
|
|
28430
|
+
} else if (!byCategory.has(policy.target.category)) {
|
|
28431
|
+
byCategory.set(policy.target.category, policy.action);
|
|
28432
|
+
}
|
|
28433
|
+
}
|
|
28434
|
+
return { byRuleId, byCategory };
|
|
28435
|
+
}
|
|
28436
|
+
function hasAuthoredPolicy(policies, rules, byRuleId) {
|
|
28437
|
+
const ruleIds = new Set(rules.map((rule) => rule.id));
|
|
28438
|
+
const categories = new Set(rules.map((rule) => rule.category));
|
|
28439
|
+
const bundleNamesPack = rules.some((rule) => byRuleId.has(rule.id));
|
|
28440
|
+
return policies.some((policy) => {
|
|
28441
|
+
if (!policy.enabled || policy.provenance !== "authored") return false;
|
|
28442
|
+
return "ruleId" in policy.target ? ruleIds.has(policy.target.ruleId) : bundleNamesPack && categories.has(policy.target.category);
|
|
28443
|
+
});
|
|
28444
|
+
}
|
|
28445
|
+
function controlPlanePolicyFloor(rules, base = defaultDataDir()) {
|
|
28446
|
+
const floors = openControlPlaneFloors(base);
|
|
28447
|
+
return floors === null ? null : floors.floorFor(rules);
|
|
28448
|
+
}
|
|
28449
|
+
function openControlPlaneFloors(base = defaultDataDir()) {
|
|
28450
|
+
if (!isAttached(readWorkspaceSettings(base))) return null;
|
|
28451
|
+
const bundle = readCachedPolicyBundle(base);
|
|
28452
|
+
if (bundle === null) return null;
|
|
28453
|
+
const indexes = indexEnabled(bundle.policies);
|
|
28454
|
+
return { floorFor: (rules) => resolveFloor(rules, bundle.policies, indexes) };
|
|
28455
|
+
}
|
|
28456
|
+
function resolveFloor(rules, policies, { byRuleId, byCategory }) {
|
|
28457
|
+
let action = null;
|
|
28458
|
+
for (const rule of rules) {
|
|
28459
|
+
const resolved = byRuleId.get(rule.id) ?? byCategory.get(rule.category);
|
|
28460
|
+
if (resolved === void 0) continue;
|
|
28461
|
+
action = action === null ? resolved : strongerAction(action, resolved);
|
|
28462
|
+
}
|
|
28463
|
+
if (action === null) return null;
|
|
28464
|
+
return {
|
|
28465
|
+
floor: weakestBuiltinAtLeast(action),
|
|
28466
|
+
locked: hasAuthoredPolicy(policies, rules, byRuleId)
|
|
28467
|
+
};
|
|
28468
|
+
}
|
|
28469
|
+
function policyAssignmentRefusal(policyId, floor) {
|
|
28470
|
+
if (floor.locked) return "lock";
|
|
28471
|
+
const effective = policyId ?? DEFAULT_PACK_POLICY_ID;
|
|
28472
|
+
return isActionAtLeast(builtinPolicyToAction(effective), builtinPolicyToAction(floor.floor)) ? null : "floor";
|
|
28473
|
+
}
|
|
28474
|
+
function packEnablementRefusal(enabled, floor) {
|
|
28475
|
+
if (floor === null || enabled) return null;
|
|
28476
|
+
return "disable";
|
|
28477
|
+
}
|
|
27980
28478
|
|
|
27981
28479
|
// ../../packages/persistence/src/semver.ts
|
|
27982
28480
|
function parse3(version2) {
|
|
@@ -28070,8 +28568,19 @@ function ruleIdsOf(rulesJson) {
|
|
|
28070
28568
|
return ids;
|
|
28071
28569
|
}
|
|
28072
28570
|
var SqliteInstalledPacksRepository = class {
|
|
28073
|
-
|
|
28571
|
+
/**
|
|
28572
|
+
* `baseDir` is the `~/.aka` LAYOUT BASE, not the data dir — the control-plane
|
|
28573
|
+
* floor needs both halves of it (settings/ says whether this machine is
|
|
28574
|
+
* attached, data/ holds the cached bundle). It is optional because a caller
|
|
28575
|
+
* holding only a DatabaseSync — every test construction site, and any embedder
|
|
28576
|
+
* that opens the store itself — has no layout to point at, and such a caller
|
|
28577
|
+
* gets the pre-existing behaviour: no floor, no lock. Production threads it in
|
|
28578
|
+
* from `openLocalDatabase`, which is the single construction site that owns a
|
|
28579
|
+
* real `~/.aka`.
|
|
28580
|
+
*/
|
|
28581
|
+
constructor(db, baseDir) {
|
|
28074
28582
|
this.db = db;
|
|
28583
|
+
this.baseDir = baseDir;
|
|
28075
28584
|
this.insertMissingStmt = db.prepare(
|
|
28076
28585
|
`INSERT INTO installed_packs (id, namespace, pack_id, version, name, rules_json, enabled, created_at, updated_at)
|
|
28077
28586
|
VALUES (:id, :namespace, :packId, :version, :name, :rulesJson, 1, :now, :now)
|
|
@@ -28093,11 +28602,17 @@ var SqliteInstalledPacksRepository = class {
|
|
|
28093
28602
|
this.signatureStmt = db.prepare(
|
|
28094
28603
|
`SELECT namespace, pack_id AS packId, version, rules_json AS rulesJson FROM available_packs`
|
|
28095
28604
|
);
|
|
28605
|
+
this.packRulesStmt = db.prepare(
|
|
28606
|
+
`SELECT rules_json AS rulesJson FROM installed_packs
|
|
28607
|
+
WHERE namespace = ? AND pack_id = ?`
|
|
28608
|
+
);
|
|
28096
28609
|
}
|
|
28097
28610
|
db;
|
|
28611
|
+
baseDir;
|
|
28098
28612
|
insertMissingStmt;
|
|
28099
28613
|
upsertAvailableStmt;
|
|
28100
28614
|
signatureStmt;
|
|
28615
|
+
packRulesStmt;
|
|
28101
28616
|
/**
|
|
28102
28617
|
* Record the running binary's detection inventory. Refreshes the
|
|
28103
28618
|
* available_packs mirror (pruning packs the binary no longer ships) and
|
|
@@ -28139,7 +28654,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
28139
28654
|
let behind = false;
|
|
28140
28655
|
for (const row of rows) {
|
|
28141
28656
|
const params = {
|
|
28142
|
-
id:
|
|
28657
|
+
id: randomUUID4(),
|
|
28143
28658
|
namespace: row.namespace,
|
|
28144
28659
|
packId: row.packId,
|
|
28145
28660
|
version: row.version,
|
|
@@ -28151,7 +28666,7 @@ var SqliteInstalledPacksRepository = class {
|
|
|
28151
28666
|
if (stored === void 0 || !isMirrorDowngrade(row, stored)) {
|
|
28152
28667
|
this.upsertAvailableStmt.run({
|
|
28153
28668
|
...params,
|
|
28154
|
-
id:
|
|
28669
|
+
id: randomUUID4(),
|
|
28155
28670
|
recordedBy: meta4?.recordedBy ?? null
|
|
28156
28671
|
});
|
|
28157
28672
|
} else {
|
|
@@ -28397,9 +28912,65 @@ var SqliteInstalledPacksRepository = class {
|
|
|
28397
28912
|
// NOT on the hook path — so, unlike recordInventory, these surface errors to the
|
|
28398
28913
|
// caller rather than swallowing them. Each returns whether a row matched, so the
|
|
28399
28914
|
// caller can tell an edit from a no-such-detection.
|
|
28915
|
+
/**
|
|
28916
|
+
* The rules one installed pack owns, reduced to what a floor computation
|
|
28917
|
+
* reads. Display-tolerant parsing on purpose: a pack whose snapshot is
|
|
28918
|
+
* unreadable contributes no rules to a scan either, so it is not a detection
|
|
28919
|
+
* the control plane can be governing, and an empty list correctly imposes no
|
|
28920
|
+
* floor. Enabled state is deliberately not filtered — a disabled pack is one
|
|
28921
|
+
* the user can re-enable, and its assignment stays governed meanwhile.
|
|
28922
|
+
*/
|
|
28923
|
+
packFloorRules(namespace, packId) {
|
|
28924
|
+
const row = getRow(this.packRulesStmt, [namespace, packId]);
|
|
28925
|
+
if (!row) return [];
|
|
28926
|
+
return parseRules(row.rulesJson).map((rule) => ({ id: rule.id, category: rule.category }));
|
|
28927
|
+
}
|
|
28928
|
+
/**
|
|
28929
|
+
* What the connected control plane imposes on one installed pack, or null on a
|
|
28930
|
+
* machine that is its own authority (standalone, no cached bundle, or a
|
|
28931
|
+
* repository constructed without a layout base).
|
|
28932
|
+
*
|
|
28933
|
+
* Exposed as a READ so a surface can render the constraint — grey out the
|
|
28934
|
+
* choices below the floor, mark a locked detection as locked — rather than
|
|
28935
|
+
* offer the user a picker whose selections it will then be told it may not
|
|
28936
|
+
* make. The refusal in `setPolicy` does not depend on any surface calling this.
|
|
28937
|
+
*/
|
|
28938
|
+
policyFloor(namespace, packId) {
|
|
28939
|
+
if (this.baseDir === void 0) return null;
|
|
28940
|
+
return controlPlanePolicyFloor(this.packFloorRules(namespace, packId), this.baseDir);
|
|
28941
|
+
}
|
|
28942
|
+
/**
|
|
28943
|
+
* The same answer for several packs, keyed `namespace/packId` and carrying an
|
|
28944
|
+
* entry only for a pack the control plane actually governs.
|
|
28945
|
+
*
|
|
28946
|
+
* A surface listing every detection asks per pack, and asking through
|
|
28947
|
+
* `policyFloor` re-reads the settings, re-reads and re-parses the whole cached
|
|
28948
|
+
* bundle and rebuilds its indexes once per pack — the entire cost of one
|
|
28949
|
+
* answer, repeated for each row, on every render. This reads all of that once.
|
|
28950
|
+
* Packs whose rules the snapshot cannot produce simply contribute no entry,
|
|
28951
|
+
* exactly as the single-pack read returns null for them.
|
|
28952
|
+
*/
|
|
28953
|
+
policyFloors(packs2) {
|
|
28954
|
+
const floors = /* @__PURE__ */ new Map();
|
|
28955
|
+
if (this.baseDir === void 0) return floors;
|
|
28956
|
+
const source = openControlPlaneFloors(this.baseDir);
|
|
28957
|
+
if (source === null) return floors;
|
|
28958
|
+
for (const pack of packs2) {
|
|
28959
|
+
const floor = source.floorFor(this.packFloorRules(pack.namespace, pack.packId));
|
|
28960
|
+
if (floor !== null) floors.set(`${pack.namespace}/${pack.packId}`, floor);
|
|
28961
|
+
}
|
|
28962
|
+
return floors;
|
|
28963
|
+
}
|
|
28400
28964
|
/**
|
|
28401
28965
|
* Assign (or clear, with null) the enforcement policy for one installed pack.
|
|
28402
|
-
* `policyId` must be a known built-in id (monitor/warn/redact/block).
|
|
28966
|
+
* `policyId` must be a known built-in id (monitor/warn/redact/block/vault).
|
|
28967
|
+
*
|
|
28968
|
+
* On an ATTACHED machine the organization's bundle is a floor this refuses to
|
|
28969
|
+
* write below, and a detection the organization has authored a policy for is
|
|
28970
|
+
* refused outright — see policy-floor.ts for both, and for why the refusal is
|
|
28971
|
+
* a throw rather than a silently substituted value. This is the one device-local
|
|
28972
|
+
* write path for the assignment, so the check belongs here rather than on any
|
|
28973
|
+
* surface that offers the choice.
|
|
28403
28974
|
*/
|
|
28404
28975
|
setPolicy(namespace, packId, policyId) {
|
|
28405
28976
|
if (policyId !== null && !BuiltinPolicyId.safeParse(policyId).success) {
|
|
@@ -28407,14 +28978,38 @@ var SqliteInstalledPacksRepository = class {
|
|
|
28407
28978
|
`Unknown policy '${policyId}'. Must be one of: ${KNOWN_BUILTIN_IDS.join(", ")}.`
|
|
28408
28979
|
);
|
|
28409
28980
|
}
|
|
28981
|
+
const requested = policyId;
|
|
28982
|
+
const floor = this.policyFloor(namespace, packId);
|
|
28983
|
+
if (floor !== null) {
|
|
28984
|
+
const refusal = policyAssignmentRefusal(requested, floor);
|
|
28985
|
+
if (refusal !== null) {
|
|
28986
|
+
throw new PolicyFloorError(`${namespace}/${packId}`, requested, floor.floor, refusal);
|
|
28987
|
+
}
|
|
28988
|
+
}
|
|
28410
28989
|
const res = this.db.prepare(
|
|
28411
28990
|
`UPDATE installed_packs SET policy_id = :policyId, updated_at = :now
|
|
28412
28991
|
WHERE namespace = :namespace AND pack_id = :packId`
|
|
28413
28992
|
).run({ policyId, now: Date.now(), namespace, packId });
|
|
28414
28993
|
return Number(res.changes) > 0;
|
|
28415
28994
|
}
|
|
28416
|
-
/**
|
|
28995
|
+
/**
|
|
28996
|
+
* Enable or disable one installed pack.
|
|
28997
|
+
*
|
|
28998
|
+
* On an ATTACHED machine a detection the organization's bundle governs at all
|
|
28999
|
+
* may not be switched OFF here — see packEnablementRefusal for why that is not
|
|
29000
|
+
* merely another point below the floor, and why re-enabling stays open. Like
|
|
29001
|
+
* the assignment above, the check belongs at this write path rather than on a
|
|
29002
|
+
* surface: this is the one device-local writer of the column, and a refusal
|
|
29003
|
+
* that lived in a page would leave the CLI free.
|
|
29004
|
+
*/
|
|
28417
29005
|
setEnabled(namespace, packId, enabled) {
|
|
29006
|
+
const floor = this.policyFloor(namespace, packId);
|
|
29007
|
+
if (floor !== null) {
|
|
29008
|
+
const refusal = packEnablementRefusal(enabled, floor);
|
|
29009
|
+
if (refusal !== null) {
|
|
29010
|
+
throw new PolicyFloorError(`${namespace}/${packId}`, null, floor.floor, refusal);
|
|
29011
|
+
}
|
|
29012
|
+
}
|
|
28418
29013
|
const res = this.db.prepare(
|
|
28419
29014
|
`UPDATE installed_packs SET enabled = :enabled, updated_at = :now
|
|
28420
29015
|
WHERE namespace = :namespace AND pack_id = :packId`
|
|
@@ -28500,7 +29095,7 @@ var SqliteInventoryRepository = class {
|
|
|
28500
29095
|
};
|
|
28501
29096
|
|
|
28502
29097
|
// ../../packages/persistence/src/repositories/inventory-assets.ts
|
|
28503
|
-
import { randomUUID as
|
|
29098
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
28504
29099
|
var CATEGORY_ORDER = ["config", "skill", "mcp", "hook"];
|
|
28505
29100
|
var VALID_HARNESS_IDS = new Set(HarnessId.options);
|
|
28506
29101
|
var WORKTREE_CHECKOUT_FILTER = "(url IS NULL OR (url NOT LIKE '%/.claude/worktrees/%' AND url NOT LIKE '%\\.claude\\worktrees\\%'))";
|
|
@@ -28989,7 +29584,7 @@ var SqliteInventoryAssetsRepository = class {
|
|
|
28989
29584
|
`INSERT INTO file_access_override (id, project_id, path, access, created_at, updated_at)
|
|
28990
29585
|
VALUES (:id, :projectId, :path, :access, :now, :now)
|
|
28991
29586
|
ON CONFLICT (project_id, path) DO UPDATE SET access = excluded.access, updated_at = excluded.updated_at`
|
|
28992
|
-
).run({ id:
|
|
29587
|
+
).run({ id: randomUUID5(), projectId, path, access, now: Date.now() });
|
|
28993
29588
|
}
|
|
28994
29589
|
return true;
|
|
28995
29590
|
}
|
|
@@ -29010,7 +29605,7 @@ var SqliteInventoryAssetsRepository = class {
|
|
|
29010
29605
|
`INSERT INTO mcp_trust_override (id, asset_id, trust, created_at, updated_at)
|
|
29011
29606
|
VALUES (:id, :assetId, :trust, :now, :now)
|
|
29012
29607
|
ON CONFLICT (asset_id) DO UPDATE SET trust = excluded.trust, updated_at = excluded.updated_at`
|
|
29013
|
-
).run({ id:
|
|
29608
|
+
).run({ id: randomUUID5(), assetId, trust, now: Date.now() });
|
|
29014
29609
|
}
|
|
29015
29610
|
this.configRowsCache = void 0;
|
|
29016
29611
|
return "ok";
|
|
@@ -29307,7 +29902,7 @@ var SqliteInventoryAssetsRepository = class {
|
|
|
29307
29902
|
};
|
|
29308
29903
|
|
|
29309
29904
|
// ../../packages/persistence/src/repositories/policies.ts
|
|
29310
|
-
import { randomUUID as
|
|
29905
|
+
import { randomUUID as randomUUID6 } from "crypto";
|
|
29311
29906
|
var SqlitePoliciesRepository = class {
|
|
29312
29907
|
constructor(db) {
|
|
29313
29908
|
this.db = db;
|
|
@@ -29342,7 +29937,7 @@ var SqlitePoliciesRepository = class {
|
|
|
29342
29937
|
failOpenTransaction(this.db, () => {
|
|
29343
29938
|
for (const [category, action] of Object.entries(DEFAULT_ACTIONS)) {
|
|
29344
29939
|
stmt.run({
|
|
29345
|
-
id:
|
|
29940
|
+
id: randomUUID6(),
|
|
29346
29941
|
target: JSON.stringify({ category }),
|
|
29347
29942
|
action,
|
|
29348
29943
|
now: Date.now()
|
|
@@ -29362,7 +29957,7 @@ var SqlitePoliciesRepository = class {
|
|
|
29362
29957
|
`INSERT INTO policies (id, scope, target, action, enabled, created_at, updated_at)
|
|
29363
29958
|
VALUES (:id, 'global', :target, :action, 1, :now, :now)
|
|
29364
29959
|
ON CONFLICT(scope, target) DO UPDATE SET action = excluded.action, enabled = 1, updated_at = excluded.updated_at`
|
|
29365
|
-
).run({ id:
|
|
29960
|
+
).run({ id: randomUUID6(), target: JSON.stringify({ category }), action, now });
|
|
29366
29961
|
}
|
|
29367
29962
|
// Caps every global per-category policy currently set to block/redact down
|
|
29368
29963
|
// to warn (see warn-era-cap.ts). Rule-targeted policies are untouched.
|
|
@@ -29430,7 +30025,7 @@ var SqlitePolicyCatalogRepository = class {
|
|
|
29430
30025
|
};
|
|
29431
30026
|
|
|
29432
30027
|
// ../../packages/persistence/src/repositories/project-files.ts
|
|
29433
|
-
import { randomUUID as
|
|
30028
|
+
import { randomUUID as randomUUID7 } from "crypto";
|
|
29434
30029
|
var SqliteProjectFilesRepository = class {
|
|
29435
30030
|
constructor(db) {
|
|
29436
30031
|
this.db = db;
|
|
@@ -29462,7 +30057,7 @@ var SqliteProjectFilesRepository = class {
|
|
|
29462
30057
|
const stamp = Math.max(now, maxStamp + 1);
|
|
29463
30058
|
for (const file2 of scan2.files) {
|
|
29464
30059
|
this.upsertStmt.run({
|
|
29465
|
-
id:
|
|
30060
|
+
id: randomUUID7(),
|
|
29466
30061
|
projectId,
|
|
29467
30062
|
path: file2.path,
|
|
29468
30063
|
name: file2.name,
|
|
@@ -29476,9 +30071,9 @@ var SqliteProjectFilesRepository = class {
|
|
|
29476
30071
|
};
|
|
29477
30072
|
|
|
29478
30073
|
// ../../packages/persistence/src/repositories/resolutions.ts
|
|
29479
|
-
import { randomUUID as
|
|
30074
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
29480
30075
|
var SqliteResolutionsRepository = class {
|
|
29481
|
-
constructor(db, now = () => Date.now(), newId = () =>
|
|
30076
|
+
constructor(db, now = () => Date.now(), newId = () => randomUUID8()) {
|
|
29482
30077
|
this.db = db;
|
|
29483
30078
|
this.now = now;
|
|
29484
30079
|
this.newId = newId;
|
|
@@ -29691,7 +30286,7 @@ var SqliteScanLedgerRepository = class {
|
|
|
29691
30286
|
};
|
|
29692
30287
|
|
|
29693
30288
|
// ../../packages/persistence/src/repositories/secret-vault.ts
|
|
29694
|
-
import { randomUUID as
|
|
30289
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
29695
30290
|
function pageLimit(requested, fallback) {
|
|
29696
30291
|
if (requested === void 0) return fallback;
|
|
29697
30292
|
return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
|
|
@@ -29737,12 +30332,14 @@ var SELECT_COLUMNS = `
|
|
|
29737
30332
|
ciphertext,
|
|
29738
30333
|
nonce,
|
|
29739
30334
|
auth_tag AS authTag,
|
|
30335
|
+
user_authorized AS userAuthorized,
|
|
29740
30336
|
occurrence_count AS occurrenceCount,
|
|
29741
30337
|
first_seen AS firstSeen,
|
|
29742
30338
|
last_seen AS lastSeen`;
|
|
29743
30339
|
function toRow(raw) {
|
|
29744
|
-
const { provider, ...rest } = raw;
|
|
29745
|
-
|
|
30340
|
+
const { provider, userAuthorized, ...rest } = raw;
|
|
30341
|
+
const row = { ...rest, userAuthorized: userAuthorized !== 0 };
|
|
30342
|
+
return provider === null ? row : { ...row, provider };
|
|
29746
30343
|
}
|
|
29747
30344
|
var SqliteSecretVaultRepository = class {
|
|
29748
30345
|
constructor(db) {
|
|
@@ -29752,17 +30349,18 @@ var SqliteSecretVaultRepository = class {
|
|
|
29752
30349
|
pointer_id, value_fingerprint, fingerprint_key_version, key_version,
|
|
29753
30350
|
format_version, category, rule_id, masked_match, provider,
|
|
29754
30351
|
ciphertext, nonce, auth_tag,
|
|
29755
|
-
occurrence_count, first_seen, last_seen
|
|
30352
|
+
user_authorized, occurrence_count, first_seen, last_seen
|
|
29756
30353
|
) VALUES (
|
|
29757
30354
|
:pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
|
|
29758
30355
|
:formatVersion, :category, :ruleId, :maskedMatch, :provider,
|
|
29759
30356
|
:ciphertext, :nonce, :authTag,
|
|
29760
|
-
1, :now, :now
|
|
30357
|
+
:userAuthorized, 1, :now, :now
|
|
29761
30358
|
)`
|
|
29762
30359
|
);
|
|
29763
30360
|
this.bumpStmt = db.prepare(
|
|
29764
30361
|
`UPDATE secret_vault
|
|
29765
|
-
SET occurrence_count = occurrence_count + 1, last_seen = :now
|
|
30362
|
+
SET occurrence_count = occurrence_count + 1, last_seen = :now,
|
|
30363
|
+
user_authorized = max(user_authorized, :userAuthorized)
|
|
29766
30364
|
WHERE value_fingerprint = :valueFingerprint`
|
|
29767
30365
|
);
|
|
29768
30366
|
this.byPointerStmt = db.prepare(
|
|
@@ -29782,6 +30380,7 @@ var SqliteSecretVaultRepository = class {
|
|
|
29782
30380
|
SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
|
|
29783
30381
|
WHERE pointer_id = :pointerId`
|
|
29784
30382
|
);
|
|
30383
|
+
this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
|
|
29785
30384
|
this.derefStmt = db.prepare(
|
|
29786
30385
|
`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
|
|
29787
30386
|
VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
|
|
@@ -29795,6 +30394,7 @@ var SqliteSecretVaultRepository = class {
|
|
|
29795
30394
|
listStmt;
|
|
29796
30395
|
replaceCiphertextStmt;
|
|
29797
30396
|
refreshFingerprintStmt;
|
|
30397
|
+
deleteByPointerStmt;
|
|
29798
30398
|
derefStmt;
|
|
29799
30399
|
/**
|
|
29800
30400
|
* Vault a value, or record another sighting of one already vaulted. Keyed on
|
|
@@ -29803,6 +30403,11 @@ var SqliteSecretVaultRepository = class {
|
|
|
29803
30403
|
* pointer, category and ciphertext, so the same secret always resolves to one
|
|
29804
30404
|
* wire token. `minted` is true only when this call created the row.
|
|
29805
30405
|
*
|
|
30406
|
+
* `userAuthorized` is the one field a repeat call may still change, and only
|
|
30407
|
+
* upwards: it records that a PERSON asked for this value to be replaced, and
|
|
30408
|
+
* the row is shared with every automatic path that vaults the same value. See
|
|
30409
|
+
* `bumpStmt` for why clearing it is the defect this shape exists to refuse.
|
|
30410
|
+
*
|
|
29806
30411
|
* The read-then-write runs in one IMMEDIATE transaction so two concurrent
|
|
29807
30412
|
* writers cannot both decide they are minting.
|
|
29808
30413
|
*/
|
|
@@ -29829,13 +30434,18 @@ var SqliteSecretVaultRepository = class {
|
|
|
29829
30434
|
ciphertext: input2.ciphertext,
|
|
29830
30435
|
nonce: input2.nonce,
|
|
29831
30436
|
authTag: input2.authTag,
|
|
30437
|
+
userAuthorized: input2.userAuthorized === true ? 1 : 0,
|
|
29832
30438
|
now
|
|
29833
30439
|
})
|
|
29834
30440
|
);
|
|
29835
30441
|
minted = true;
|
|
29836
30442
|
return;
|
|
29837
30443
|
}
|
|
29838
|
-
this.bumpStmt.run({
|
|
30444
|
+
this.bumpStmt.run({
|
|
30445
|
+
valueFingerprint: input2.valueFingerprint,
|
|
30446
|
+
userAuthorized: input2.userAuthorized === true ? 1 : 0,
|
|
30447
|
+
now
|
|
30448
|
+
});
|
|
29839
30449
|
},
|
|
29840
30450
|
"IMMEDIATE"
|
|
29841
30451
|
);
|
|
@@ -29895,6 +30505,42 @@ var SqliteSecretVaultRepository = class {
|
|
|
29895
30505
|
);
|
|
29896
30506
|
return destroyed;
|
|
29897
30507
|
}
|
|
30508
|
+
/**
|
|
30509
|
+
* Destroy the named entries and report WHICH ones went — the scoped
|
|
30510
|
+
* counterpart to `purgeAll`, for a caller that has already put those specific
|
|
30511
|
+
* values back where they came from. Ids the store does not hold are absent
|
|
30512
|
+
* from the answer rather than an error, so a set assembled from a stale read
|
|
30513
|
+
* is not a fault. The deref audit is left alone, exactly as the purge leaves
|
|
30514
|
+
* it.
|
|
30515
|
+
*
|
|
30516
|
+
* The ids come back rather than a count because the caller's next act is to
|
|
30517
|
+
* write a purge row per destroyed entry, and a record of destruction has to
|
|
30518
|
+
* be a record of what was really destroyed: a selection is a claim about a
|
|
30519
|
+
* read that has since gone stale, and auditing from it invents a purge for an
|
|
30520
|
+
* entry still sitting in the vault.
|
|
30521
|
+
*
|
|
30522
|
+
* One transaction over the whole set rather than a statement per id: the
|
|
30523
|
+
* caller hands this the result of a restore pass it has completed, and a
|
|
30524
|
+
* fault partway through must leave the vault as it was found rather than
|
|
30525
|
+
* destroying a prefix of it. The vault holds the only copy of what a pointer
|
|
30526
|
+
* stands for, so half a delete is not a state anything can recover from.
|
|
30527
|
+
*/
|
|
30528
|
+
deleteByPointerIds(pointerIds) {
|
|
30529
|
+
if (pointerIds.length === 0) return [];
|
|
30530
|
+
const deleted = [];
|
|
30531
|
+
withTransaction(
|
|
30532
|
+
this.db,
|
|
30533
|
+
() => {
|
|
30534
|
+
for (const pointerId of pointerIds) {
|
|
30535
|
+
if (Number(this.deleteByPointerStmt.run({ pointerId }).changes) > 0) {
|
|
30536
|
+
deleted.push(pointerId);
|
|
30537
|
+
}
|
|
30538
|
+
}
|
|
30539
|
+
},
|
|
30540
|
+
"IMMEDIATE"
|
|
30541
|
+
);
|
|
30542
|
+
return deleted;
|
|
30543
|
+
}
|
|
29898
30544
|
/**
|
|
29899
30545
|
* Record (or re-stamp) one place a pointer has been written. One row per
|
|
29900
30546
|
* (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
|
|
@@ -29907,7 +30553,7 @@ var SqliteSecretVaultRepository = class {
|
|
|
29907
30553
|
VALUES (:id, :pointerId, :location, :kind, :now, :now)
|
|
29908
30554
|
ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
|
|
29909
30555
|
).run({
|
|
29910
|
-
id:
|
|
30556
|
+
id: randomUUID9(),
|
|
29911
30557
|
pointerId: entry.pointerId,
|
|
29912
30558
|
location: entry.location,
|
|
29913
30559
|
kind: entry.kind,
|
|
@@ -30420,15 +31066,15 @@ var SqliteSecurityRepository = class {
|
|
|
30420
31066
|
const from = now - RANGE_DAYS[range] * DAY_MS4;
|
|
30421
31067
|
const rows = allRows(
|
|
30422
31068
|
this.db.prepare(
|
|
30423
|
-
`SELECT
|
|
31069
|
+
`SELECT e.repo AS repo, count(*) AS c
|
|
30424
31070
|
FROM inspection_findings f
|
|
30425
31071
|
JOIN audit_events e ON e.id = f.audit_event_id
|
|
30426
31072
|
WHERE e.started_at >= :from AND e.started_at < :to
|
|
30427
31073
|
AND e.event_type IN (${CAPTURE_EVENT_TYPES_SQL})
|
|
30428
|
-
AND
|
|
30429
|
-
AND
|
|
30430
|
-
GROUP BY repo
|
|
30431
|
-
ORDER BY c DESC, repo
|
|
31074
|
+
AND e.repo IS NOT NULL
|
|
31075
|
+
AND e.repo != ''
|
|
31076
|
+
GROUP BY e.repo
|
|
31077
|
+
ORDER BY c DESC, e.repo
|
|
30432
31078
|
LIMIT :limit`
|
|
30433
31079
|
),
|
|
30434
31080
|
{ from, to: now, limit }
|
|
@@ -30490,7 +31136,7 @@ var SqliteSecurityRepository = class {
|
|
|
30490
31136
|
`SELECT f.finding_key AS finding_key,
|
|
30491
31137
|
d.rule_id AS rule_id,
|
|
30492
31138
|
d.severity AS severity,
|
|
30493
|
-
|
|
31139
|
+
e.file_path AS path,
|
|
30494
31140
|
COALESCE(f.first_detected_at, e.started_at) AS first_detected_at,
|
|
30495
31141
|
latest.resolved_at AS latest_resolved_at
|
|
30496
31142
|
FROM ${LATEST_RESOLUTION_BY_KEY_SQL} latest
|
|
@@ -30543,7 +31189,7 @@ var SqliteSecurityRepository = class {
|
|
|
30543
31189
|
};
|
|
30544
31190
|
|
|
30545
31191
|
// ../../packages/persistence/src/repositories/shares.ts
|
|
30546
|
-
import { randomUUID as
|
|
31192
|
+
import { randomUUID as randomUUID10 } from "crypto";
|
|
30547
31193
|
var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
|
|
30548
31194
|
var IN_CHUNK = 500;
|
|
30549
31195
|
var KIND_ORDER = ["provider", "internal", "external", "ip"];
|
|
@@ -30631,7 +31277,7 @@ function buildSummary(dest, endpoints) {
|
|
|
30631
31277
|
callSiteCount,
|
|
30632
31278
|
transports: distinctTransports(transports),
|
|
30633
31279
|
dataClasses: distinctDataClasses(dataClasses),
|
|
30634
|
-
review: buildReviewInfo(dest.trust, transports),
|
|
31280
|
+
review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
|
|
30635
31281
|
network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
|
|
30636
31282
|
endpoints: endpoints.map(toEndpointSummary)
|
|
30637
31283
|
};
|
|
@@ -30658,7 +31304,7 @@ function buildDetail(dest, endpoints, callSites) {
|
|
|
30658
31304
|
lastSeen: new Date(lastSeenMs).toISOString(),
|
|
30659
31305
|
transports: distinctTransports(transports),
|
|
30660
31306
|
dataClasses: distinctDataClasses(endpoints.map((e) => e.dataClass)),
|
|
30661
|
-
review: buildReviewInfo(dest.trust, transports),
|
|
31307
|
+
review: buildReviewInfo(dest.trust, transports, dest.overrideDecision !== null),
|
|
30662
31308
|
network: dest.kind === "provider" ? null : parseNetwork(dest.networkJson),
|
|
30663
31309
|
note: dest.note,
|
|
30664
31310
|
endpoints: endpoints.map((ep) => ({
|
|
@@ -30687,7 +31333,11 @@ var SqliteSharesRepository = class {
|
|
|
30687
31333
|
FROM share_destination d
|
|
30688
31334
|
LEFT JOIN share_endpoint e ON e.destination_id = d.id
|
|
30689
31335
|
AND e.transport IN ${PLAINTEXT_TRANSPORT_SQL}
|
|
30690
|
-
WHERE d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL
|
|
31336
|
+
WHERE (d.trust IN ('unverified', 'ip') OR e.id IS NOT NULL)
|
|
31337
|
+
AND NOT EXISTS (
|
|
31338
|
+
SELECT 1 FROM egress_decision_override o
|
|
31339
|
+
WHERE o.host = d.host OR (o.destination_id = d.id AND o.host IS NULL)
|
|
31340
|
+
)`
|
|
30691
31341
|
);
|
|
30692
31342
|
const kindCounts = countBy(
|
|
30693
31343
|
this.db,
|
|
@@ -30799,7 +31449,7 @@ var SqliteSharesRepository = class {
|
|
|
30799
31449
|
(id, destination_id, host, decision, created_at, updated_at)
|
|
30800
31450
|
VALUES (:id, :destinationId, :host, :decision, :now, :now)`
|
|
30801
31451
|
).run({
|
|
30802
|
-
id:
|
|
31452
|
+
id: randomUUID10(),
|
|
30803
31453
|
destinationId,
|
|
30804
31454
|
host: dest.host,
|
|
30805
31455
|
decision,
|
|
@@ -30948,7 +31598,7 @@ var SqliteSharesRepository = class {
|
|
|
30948
31598
|
let destinationId = destIds.get(hit.host);
|
|
30949
31599
|
if (destinationId === void 0) {
|
|
30950
31600
|
destStmt.run({
|
|
30951
|
-
id:
|
|
31601
|
+
id: randomUUID10(),
|
|
30952
31602
|
kind: hit.kind,
|
|
30953
31603
|
name: hit.name,
|
|
30954
31604
|
host: hit.host,
|
|
@@ -30964,7 +31614,7 @@ var SqliteSharesRepository = class {
|
|
|
30964
31614
|
let endpointId = endpointIds.get(endpointKey);
|
|
30965
31615
|
if (endpointId === void 0) {
|
|
30966
31616
|
endpointStmt.run({
|
|
30967
|
-
id:
|
|
31617
|
+
id: randomUUID10(),
|
|
30968
31618
|
destinationId,
|
|
30969
31619
|
method: hit.method,
|
|
30970
31620
|
transport: hit.transport,
|
|
@@ -30977,7 +31627,7 @@ var SqliteSharesRepository = class {
|
|
|
30977
31627
|
endpointIds.set(endpointKey, endpointId);
|
|
30978
31628
|
}
|
|
30979
31629
|
siteStmt.run({
|
|
30980
|
-
id:
|
|
31630
|
+
id: randomUUID10(),
|
|
30981
31631
|
endpointId,
|
|
30982
31632
|
project: input2.project,
|
|
30983
31633
|
projectKey: input2.projectKey,
|
|
@@ -31342,6 +31992,7 @@ function purgeSampleData(db) {
|
|
|
31342
31992
|
}
|
|
31343
31993
|
|
|
31344
31994
|
// ../../packages/persistence/src/database.ts
|
|
31995
|
+
var CAPTURE_GRAIN = new Set(EventKind.options);
|
|
31345
31996
|
var UNSAFE_TEST_ONLY_RAW_HANDLE = /* @__PURE__ */ Symbol(
|
|
31346
31997
|
"aka.persistence.unsafeTestOnlyRawHandle"
|
|
31347
31998
|
);
|
|
@@ -31389,7 +32040,7 @@ function backupLegacyStore(db, file2) {
|
|
|
31389
32040
|
discardStore(file2, backup);
|
|
31390
32041
|
return backup;
|
|
31391
32042
|
}
|
|
31392
|
-
function openAndInitialize(file2) {
|
|
32043
|
+
function openAndInitialize(file2, base) {
|
|
31393
32044
|
let db = openWithPragmas(file2);
|
|
31394
32045
|
try {
|
|
31395
32046
|
if (isForeignSqliteLineage(db)) {
|
|
@@ -31402,7 +32053,7 @@ function openAndInitialize(file2) {
|
|
|
31402
32053
|
applyMigrations(db, file2);
|
|
31403
32054
|
tightenPerms(file2);
|
|
31404
32055
|
const policies = new SqlitePoliciesRepository(db);
|
|
31405
|
-
const installedPacks = new SqliteInstalledPacksRepository(db);
|
|
32056
|
+
const installedPacks = new SqliteInstalledPacksRepository(db, base);
|
|
31406
32057
|
const repositories = {
|
|
31407
32058
|
events: new SqliteEventsRepository(db),
|
|
31408
32059
|
findings: new SqliteFindingsRepository(db),
|
|
@@ -31438,7 +32089,7 @@ function openAndInitialize(file2) {
|
|
|
31438
32089
|
}
|
|
31439
32090
|
function openLocalDatabase(dir) {
|
|
31440
32091
|
ensureDataDirSync(dir);
|
|
31441
|
-
const file2 =
|
|
32092
|
+
const file2 = join7(dir, DB_FILENAME);
|
|
31442
32093
|
reapStalePartials(file2);
|
|
31443
32094
|
const {
|
|
31444
32095
|
db,
|
|
@@ -31466,7 +32117,13 @@ function openLocalDatabase(dir) {
|
|
|
31466
32117
|
inspectionDefinitions,
|
|
31467
32118
|
inspectionFindings,
|
|
31468
32119
|
configInventory
|
|
31469
|
-
} = openAndInitialize(
|
|
32120
|
+
} = openAndInitialize(
|
|
32121
|
+
file2,
|
|
32122
|
+
// `dir` is always `<base>/data` — every caller resolves it through
|
|
32123
|
+
// `dataDir()` — so its parent is the `~/.aka` base the layout splits into
|
|
32124
|
+
// settings/ and data/, and the pack-policy floor needs both halves.
|
|
32125
|
+
dirname2(dir)
|
|
32126
|
+
);
|
|
31470
32127
|
function captureRowId(event) {
|
|
31471
32128
|
return captureId(
|
|
31472
32129
|
event.metadata?.sessionId ?? null,
|
|
@@ -31479,6 +32136,21 @@ function openLocalDatabase(dir) {
|
|
|
31479
32136
|
historySync.markSynced([captureRowId(event)], atMs);
|
|
31480
32137
|
});
|
|
31481
32138
|
}
|
|
32139
|
+
function markCaptureOwed(event) {
|
|
32140
|
+
failOpenTransaction(db, () => {
|
|
32141
|
+
historySync.markCaptureOwed(captureRowId(event));
|
|
32142
|
+
});
|
|
32143
|
+
}
|
|
32144
|
+
function markAuditEventsDelivered(events2, atMs) {
|
|
32145
|
+
const stampable = events2.filter((event) => !CAPTURE_GRAIN.has(event.eventType));
|
|
32146
|
+
if (stampable.length === 0) return;
|
|
32147
|
+
failOpenTransaction(db, () => {
|
|
32148
|
+
historySync.markSynced(
|
|
32149
|
+
stampable.map((event) => event.id),
|
|
32150
|
+
atMs
|
|
32151
|
+
);
|
|
32152
|
+
});
|
|
32153
|
+
}
|
|
31482
32154
|
function recordCapture(event, detected) {
|
|
31483
32155
|
failOpenTransaction(db, () => {
|
|
31484
32156
|
const sessionId = event.metadata?.sessionId;
|
|
@@ -31565,7 +32237,7 @@ function openLocalDatabase(dir) {
|
|
|
31565
32237
|
const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
|
|
31566
32238
|
if (!definitionId) continue;
|
|
31567
32239
|
inspectionFindings.insertFinding({
|
|
31568
|
-
id:
|
|
32240
|
+
id: randomUUID11(),
|
|
31569
32241
|
auditEventId: record2.scanEvent.id,
|
|
31570
32242
|
inspectionDefinitionId: definitionId,
|
|
31571
32243
|
span: finding.span,
|
|
@@ -31661,6 +32333,8 @@ function openLocalDatabase(dir) {
|
|
|
31661
32333
|
inspectionFindings,
|
|
31662
32334
|
recordCapture,
|
|
31663
32335
|
markCaptureDelivered,
|
|
32336
|
+
markCaptureOwed,
|
|
32337
|
+
markAuditEventsDelivered,
|
|
31664
32338
|
ensureInventory,
|
|
31665
32339
|
recordConfigScan,
|
|
31666
32340
|
recordProjectFiles,
|
|
@@ -31679,20 +32353,6 @@ function openLocalDatabase(dir) {
|
|
|
31679
32353
|
};
|
|
31680
32354
|
}
|
|
31681
32355
|
|
|
31682
|
-
// ../../packages/persistence/src/file-lock.ts
|
|
31683
|
-
import { randomUUID as randomUUID11 } from "crypto";
|
|
31684
|
-
import {
|
|
31685
|
-
closeSync,
|
|
31686
|
-
existsSync as existsSync2,
|
|
31687
|
-
openSync,
|
|
31688
|
-
readFileSync as readFileSync2,
|
|
31689
|
-
rmSync as rmSync5,
|
|
31690
|
-
statSync as statSync3,
|
|
31691
|
-
writeFileSync as writeFileSync2
|
|
31692
|
-
} from "fs";
|
|
31693
|
-
import { hostname as hostname3 } from "os";
|
|
31694
|
-
var PARK = new Int32Array(new SharedArrayBuffer(4));
|
|
31695
|
-
|
|
31696
32356
|
// ../../packages/persistence/src/finding-key.ts
|
|
31697
32357
|
import { createHash as createHash3 } from "crypto";
|
|
31698
32358
|
function normalizeFilePath(filePath) {
|
|
@@ -31705,13 +32365,13 @@ function computeFindingKey(input2) {
|
|
|
31705
32365
|
|
|
31706
32366
|
// ../../packages/persistence/src/fingerprint.ts
|
|
31707
32367
|
import { createHmac, randomBytes } from "crypto";
|
|
31708
|
-
import { existsSync as existsSync3, readFileSync as
|
|
31709
|
-
import { join as
|
|
32368
|
+
import { existsSync as existsSync3, readFileSync as readFileSync6 } from "fs";
|
|
32369
|
+
import { join as join8 } from "path";
|
|
31710
32370
|
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
31711
32371
|
var EXCEPTION_KEY_FILENAME = "exception.key";
|
|
31712
32372
|
var KEY_MATERIAL_BYTES = 32;
|
|
31713
32373
|
function keyFilePath(dataDir2) {
|
|
31714
|
-
return
|
|
32374
|
+
return join8(dataDir2, EXCEPTION_KEY_FILENAME);
|
|
31715
32375
|
}
|
|
31716
32376
|
function parseKeyFile(raw) {
|
|
31717
32377
|
const parsed2 = JSON.parse(raw);
|
|
@@ -31749,7 +32409,7 @@ var FloorUnreadableError = class extends Error {
|
|
|
31749
32409
|
}
|
|
31750
32410
|
};
|
|
31751
32411
|
function storedKeyVersionFloor(dataDir2) {
|
|
31752
|
-
const file2 =
|
|
32412
|
+
const file2 = join8(dataDir2, DB_FILENAME);
|
|
31753
32413
|
if (!existsSync3(file2)) return 0;
|
|
31754
32414
|
let db;
|
|
31755
32415
|
try {
|
|
@@ -31804,7 +32464,7 @@ function occupantMessage(file2, kind) {
|
|
|
31804
32464
|
function readFingerprintKey(dataDir2) {
|
|
31805
32465
|
let raw;
|
|
31806
32466
|
try {
|
|
31807
|
-
raw =
|
|
32467
|
+
raw = readFileSync6(keyFilePath(dataDir2), "utf8");
|
|
31808
32468
|
} catch (err) {
|
|
31809
32469
|
if (err.code === "ENOENT") return null;
|
|
31810
32470
|
throw err instanceof Error ? err : new Error(String(err));
|
|
@@ -31828,146 +32488,12 @@ function fingerprintValue(key, raw) {
|
|
|
31828
32488
|
|
|
31829
32489
|
// ../../packages/persistence/src/history-preview.ts
|
|
31830
32490
|
import { existsSync as existsSync4 } from "fs";
|
|
31831
|
-
import { join as
|
|
32491
|
+
import { join as join9 } from "path";
|
|
31832
32492
|
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
31833
32493
|
|
|
31834
|
-
// ../../packages/persistence/src/local-layout.ts
|
|
31835
|
-
import { renameSync as renameSync3 } from "fs";
|
|
31836
|
-
import { mkdir } from "fs/promises";
|
|
31837
|
-
import { homedir } from "os";
|
|
31838
|
-
import { join as join7 } from "path";
|
|
31839
|
-
function defaultDataDir() {
|
|
31840
|
-
return join7(homedir(), ".aka");
|
|
31841
|
-
}
|
|
31842
|
-
function settingsDir(base = defaultDataDir()) {
|
|
31843
|
-
return join7(base, "settings");
|
|
31844
|
-
}
|
|
31845
|
-
function dataDir(base = defaultDataDir()) {
|
|
31846
|
-
return join7(base, "data");
|
|
31847
|
-
}
|
|
31848
|
-
function dbPath(base = defaultDataDir()) {
|
|
31849
|
-
return join7(dataDir(base), "aka.db");
|
|
31850
|
-
}
|
|
31851
|
-
function keysDir(base = defaultDataDir()) {
|
|
31852
|
-
return join7(base, "keys");
|
|
31853
|
-
}
|
|
31854
|
-
async function ensureDataDir(dir = defaultDataDir()) {
|
|
31855
|
-
await mkdir(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
31856
|
-
tightenDir(dir);
|
|
31857
|
-
}
|
|
31858
|
-
function ensureLayoutDirSync(dir = defaultDataDir()) {
|
|
31859
|
-
ensureDataDirSync(dir);
|
|
31860
|
-
}
|
|
31861
|
-
function migrateLegacyLayout(base = defaultDataDir()) {
|
|
31862
|
-
const moves = [
|
|
31863
|
-
{ name: "config.json", dest: settingsDir(base) },
|
|
31864
|
-
{ name: "policy-cache.json", dest: dataDir(base) }
|
|
31865
|
-
];
|
|
31866
|
-
for (const { name, dest } of moves) {
|
|
31867
|
-
try {
|
|
31868
|
-
ensureDataDirSync(dest);
|
|
31869
|
-
const moved = join7(dest, name);
|
|
31870
|
-
renameSync3(join7(base, name), moved);
|
|
31871
|
-
tightenFile(moved);
|
|
31872
|
-
} catch {
|
|
31873
|
-
}
|
|
31874
|
-
}
|
|
31875
|
-
}
|
|
31876
|
-
|
|
31877
|
-
// ../../packages/persistence/src/managed-settings.ts
|
|
31878
|
-
import { readFileSync as readFileSync4 } from "fs";
|
|
31879
|
-
import { posix, win32 } from "path";
|
|
31880
|
-
function managedSettingsPaths(platform2 = process.platform) {
|
|
31881
|
-
if (platform2 === "darwin") {
|
|
31882
|
-
return [
|
|
31883
|
-
posix.join("/Library", "Application Support", "AKASecurity", MANAGED_SETTINGS_FILENAME),
|
|
31884
|
-
posix.join("/Library", "Managed Preferences", MANAGED_SETTINGS_FILENAME)
|
|
31885
|
-
];
|
|
31886
|
-
}
|
|
31887
|
-
if (platform2 === "win32") {
|
|
31888
|
-
return [win32.join("C:\\", "ProgramData", "AKASecurity", MANAGED_SETTINGS_FILENAME)];
|
|
31889
|
-
}
|
|
31890
|
-
return [posix.join("/etc", "aka", MANAGED_SETTINGS_FILENAME)];
|
|
31891
|
-
}
|
|
31892
|
-
function readManagedSettings(paths = managedSettingsPaths()) {
|
|
31893
|
-
for (const path of paths) {
|
|
31894
|
-
let text;
|
|
31895
|
-
try {
|
|
31896
|
-
text = readFileSync4(path, "utf8");
|
|
31897
|
-
} catch {
|
|
31898
|
-
continue;
|
|
31899
|
-
}
|
|
31900
|
-
const record2 = parseJsonObject(text);
|
|
31901
|
-
if (!record2) continue;
|
|
31902
|
-
const parsed2 = ManagedSettings.safeParse(record2);
|
|
31903
|
-
if (parsed2.success) return parsed2.data;
|
|
31904
|
-
}
|
|
31905
|
-
return null;
|
|
31906
|
-
}
|
|
31907
|
-
function overlayManagedSettings(settings, managed, now = () => /* @__PURE__ */ new Date()) {
|
|
31908
|
-
if (!managed) return settings;
|
|
31909
|
-
const { values } = managed;
|
|
31910
|
-
const merged = { ...settings };
|
|
31911
|
-
if (values.runMode !== void 0) merged.runMode = values.runMode;
|
|
31912
|
-
if (values.controlPlane !== void 0) {
|
|
31913
|
-
merged.controlPlane = {
|
|
31914
|
-
...values.controlPlane,
|
|
31915
|
-
// The administrator pinned WHICH deployment, not WHEN this machine
|
|
31916
|
-
// joined it. Keep the user's own attach time when the endpoint is
|
|
31917
|
-
// unchanged, so a managed machine does not appear to re-attach on every
|
|
31918
|
-
// read; stamp a fresh one when the administrator moved it.
|
|
31919
|
-
attachedAt: settings.controlPlane?.endpoint === values.controlPlane.endpoint ? settings.controlPlane.attachedAt : now().toISOString()
|
|
31920
|
-
};
|
|
31921
|
-
}
|
|
31922
|
-
if (values.historicalAccess !== void 0) merged.historicalAccess = values.historicalAccess;
|
|
31923
|
-
if (values.vaultKeyCustody !== void 0) merged.vaultKeyCustody = values.vaultKeyCustody;
|
|
31924
|
-
if (values.vaultInlineReveal !== void 0) merged.vaultInlineReveal = values.vaultInlineReveal;
|
|
31925
|
-
if (values.dataSharesInPlace !== void 0) merged.dataSharesInPlace = values.dataSharesInPlace;
|
|
31926
|
-
if (values.vaultConsent !== void 0) {
|
|
31927
|
-
merged.vaultConsent = values.vaultConsent ? (
|
|
31928
|
-
// Keep an existing valid grant so its acknowledgedAt survives; mint one
|
|
31929
|
-
// at the current version otherwise.
|
|
31930
|
-
settings.vaultConsent?.version === VAULT_CONSENT_VERSION ? settings.vaultConsent : { acknowledgedAt: now().toISOString(), version: VAULT_CONSENT_VERSION }
|
|
31931
|
-
) : void 0;
|
|
31932
|
-
}
|
|
31933
|
-
if (values.modelJudgeConsent !== void 0) {
|
|
31934
|
-
merged.modelJudgeConsent = values.modelJudgeConsent ? settings.modelJudgeConsent?.payloadVersion === MODEL_JUDGE_PAYLOAD_VERSION ? settings.modelJudgeConsent : {
|
|
31935
|
-
acknowledgedAt: now().toISOString(),
|
|
31936
|
-
payloadVersion: MODEL_JUDGE_PAYLOAD_VERSION
|
|
31937
|
-
} : void 0;
|
|
31938
|
-
}
|
|
31939
|
-
return merged;
|
|
31940
|
-
}
|
|
31941
|
-
|
|
31942
|
-
// ../../packages/persistence/src/settings.ts
|
|
31943
|
-
import { readFileSync as readFileSync5 } from "fs";
|
|
31944
|
-
import { join as join8 } from "path";
|
|
31945
|
-
var SETTINGS_FILENAME = "settings.json";
|
|
31946
|
-
function readWorkspaceSettings(base = defaultDataDir()) {
|
|
31947
|
-
return overlayManagedSettings(readUserSettings(base), readManagedSettings());
|
|
31948
|
-
}
|
|
31949
|
-
function readUserSettings(base) {
|
|
31950
|
-
const record2 = readJson(join8(settingsDir(base), SETTINGS_FILENAME));
|
|
31951
|
-
if (!record2) return defaultWorkspaceSettings();
|
|
31952
|
-
try {
|
|
31953
|
-
return WorkspaceSettings.parse(record2);
|
|
31954
|
-
} catch {
|
|
31955
|
-
return defaultWorkspaceSettings();
|
|
31956
|
-
}
|
|
31957
|
-
}
|
|
31958
|
-
function readJson(file2) {
|
|
31959
|
-
let text;
|
|
31960
|
-
try {
|
|
31961
|
-
text = readFileSync5(file2, "utf8");
|
|
31962
|
-
} catch {
|
|
31963
|
-
return null;
|
|
31964
|
-
}
|
|
31965
|
-
return parseJsonObject(text) ?? null;
|
|
31966
|
-
}
|
|
31967
|
-
|
|
31968
32494
|
// ../../packages/persistence/src/store-symlinks.ts
|
|
31969
32495
|
import { existsSync as existsSync5, lstatSync as lstatSync3, readlinkSync, realpathSync, statSync as statSync4 } from "fs";
|
|
31970
|
-
import { dirname as
|
|
32496
|
+
import { dirname as dirname3, join as join10, resolve } from "path";
|
|
31971
32497
|
var STORE_DB = "the store database (including the prompt corpus)";
|
|
31972
32498
|
var STORE_SETTINGS = "your settings file";
|
|
31973
32499
|
function storeContents(home) {
|
|
@@ -31976,7 +32502,7 @@ function storeContents(home) {
|
|
|
31976
32502
|
[settingsDir(home), STORE_SETTINGS],
|
|
31977
32503
|
[dataDir(home), STORE_DB],
|
|
31978
32504
|
[keysDir(home), "the vault key"],
|
|
31979
|
-
[
|
|
32505
|
+
[join10(settingsDir(home), "settings.json"), STORE_SETTINGS],
|
|
31980
32506
|
[dbPath(home), STORE_DB]
|
|
31981
32507
|
]);
|
|
31982
32508
|
}
|
|
@@ -32004,7 +32530,7 @@ function linkTarget(path) {
|
|
|
32004
32530
|
try {
|
|
32005
32531
|
return realpathSync(path);
|
|
32006
32532
|
} catch {
|
|
32007
|
-
return resolve(
|
|
32533
|
+
return resolve(dirname3(path), readlinkSync(path));
|
|
32008
32534
|
}
|
|
32009
32535
|
}
|
|
32010
32536
|
function targetMode(path, platform2) {
|
|
@@ -32028,19 +32554,19 @@ import {
|
|
|
32028
32554
|
// ../../packages/persistence/src/vault/key-provider.ts
|
|
32029
32555
|
import { execFileSync } from "child_process";
|
|
32030
32556
|
import { randomBytes as randomBytes2 } from "crypto";
|
|
32031
|
-
import { chmodSync as chmodSync3, readFileSync as
|
|
32032
|
-
import { join as
|
|
32557
|
+
import { chmodSync as chmodSync3, readFileSync as readFileSync7, renameSync as renameSync4, rmSync as rmSync6, statSync as statSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
32558
|
+
import { join as join11 } from "path";
|
|
32033
32559
|
|
|
32034
32560
|
// ../../packages/persistence/src/vault/vault.ts
|
|
32035
32561
|
import { randomBytes as randomBytes3, randomUUID as randomUUID12 } from "crypto";
|
|
32036
32562
|
|
|
32037
32563
|
// ../../packages/persistence/src/warn-era-cap.ts
|
|
32038
32564
|
import { existsSync as existsSync6, writeFileSync as writeFileSync4 } from "fs";
|
|
32039
|
-
import { join as
|
|
32565
|
+
import { join as join12 } from "path";
|
|
32040
32566
|
var MARKER = "warn-era-capped";
|
|
32041
32567
|
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
32042
32568
|
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
32043
|
-
const marker =
|
|
32569
|
+
const marker = join12(dataDir2, MARKER);
|
|
32044
32570
|
if (existsSync6(marker)) return { capped: 0, skipped: "already-run" };
|
|
32045
32571
|
const capped = db.policies.capCategoryActions();
|
|
32046
32572
|
writeFileSync4(marker, `${new Date(Date.now()).toISOString()}
|
|
@@ -32084,6 +32610,307 @@ function toEgressIngestRequest(input2) {
|
|
|
32084
32610
|
};
|
|
32085
32611
|
}
|
|
32086
32612
|
|
|
32613
|
+
// ../../packages/remote/src/http.ts
|
|
32614
|
+
import { request as httpRequest } from "http";
|
|
32615
|
+
import { request as httpsRequest } from "https";
|
|
32616
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
32617
|
+
var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
32618
|
+
var RemoteRequestError = class extends Error {
|
|
32619
|
+
constructor(status) {
|
|
32620
|
+
super(`control-plane request failed with status ${String(status)}`);
|
|
32621
|
+
this.status = status;
|
|
32622
|
+
this.name = "RemoteRequestError";
|
|
32623
|
+
}
|
|
32624
|
+
status;
|
|
32625
|
+
};
|
|
32626
|
+
var RemoteRouteAbsent = class extends Error {
|
|
32627
|
+
constructor(route) {
|
|
32628
|
+
super(`control plane does not serve ${route}`);
|
|
32629
|
+
this.route = route;
|
|
32630
|
+
this.name = "RemoteRouteAbsent";
|
|
32631
|
+
}
|
|
32632
|
+
route;
|
|
32633
|
+
};
|
|
32634
|
+
var RemoteRequestInvalid = class extends Error {
|
|
32635
|
+
constructor(route, cause) {
|
|
32636
|
+
super(`refusing to send a malformed body to ${route}`);
|
|
32637
|
+
this.cause = cause;
|
|
32638
|
+
this.name = "RemoteRequestInvalid";
|
|
32639
|
+
}
|
|
32640
|
+
cause;
|
|
32641
|
+
};
|
|
32642
|
+
var RemoteResponseInvalid = class extends Error {
|
|
32643
|
+
constructor(route, detail) {
|
|
32644
|
+
super(`control plane answered ${route} with ${detail}`);
|
|
32645
|
+
this.name = "RemoteResponseInvalid";
|
|
32646
|
+
}
|
|
32647
|
+
};
|
|
32648
|
+
var RemoteTransportError = class extends Error {
|
|
32649
|
+
/**
|
|
32650
|
+
* The status the peer sent, when headers arrived and only the BODY was
|
|
32651
|
+
* refused.
|
|
32652
|
+
*
|
|
32653
|
+
* Undefined for the ordinary case this class was written for — no answer at
|
|
32654
|
+
* all. It exists because two paths reject after a status has already been
|
|
32655
|
+
* delivered: an oversized body and an aborted response. Discarding it there
|
|
32656
|
+
* reported a deployment answering 401 with a verbose body as a network
|
|
32657
|
+
* outage, which sends the reader to look at their network instead of their
|
|
32658
|
+
* credential.
|
|
32659
|
+
*/
|
|
32660
|
+
constructor(reason, status) {
|
|
32661
|
+
super(`control-plane request did not complete: ${reason}`);
|
|
32662
|
+
this.status = status;
|
|
32663
|
+
this.name = "RemoteTransportError";
|
|
32664
|
+
}
|
|
32665
|
+
status;
|
|
32666
|
+
};
|
|
32667
|
+
async function send(options) {
|
|
32668
|
+
const url2 = new URL(options.url);
|
|
32669
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
32670
|
+
const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
|
|
32671
|
+
const requestOptions = {
|
|
32672
|
+
method: options.method,
|
|
32673
|
+
headers: {
|
|
32674
|
+
// CALLER HEADERS FIRST, so this module's own are not overridable. Spread
|
|
32675
|
+
// last they win, and two of the values below are ones no caller may
|
|
32676
|
+
// replace: `x-api-key` is the credential, and `content-length` is the
|
|
32677
|
+
// byte count that stops a multi-byte body being truncated by the
|
|
32678
|
+
// receiver. `SendOptions.headers` is a free-form record on an exported
|
|
32679
|
+
// function, so "no caller does that today" is not the guarantee to rely
|
|
32680
|
+
// on. The one header any caller actually passes — `if-none-match` on the
|
|
32681
|
+
// conditional GET — is untouched by this order.
|
|
32682
|
+
...options.headers,
|
|
32683
|
+
// The credential. One header, matching what the deployment authenticates
|
|
32684
|
+
// on; a second copy in an `Authorization` header would be one more place
|
|
32685
|
+
// it can be logged by an intermediary for no gain.
|
|
32686
|
+
//
|
|
32687
|
+
// Spread conditionally rather than assigned as `undefined`: Node's header
|
|
32688
|
+
// handling and `content-length` bookkeeping treat a present-but-undefined
|
|
32689
|
+
// key differently from an absent one, and "the header is not there" is
|
|
32690
|
+
// the property the attach flow needs.
|
|
32691
|
+
...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
|
|
32692
|
+
accept: "application/json",
|
|
32693
|
+
...options.body === void 0 ? {} : {
|
|
32694
|
+
"content-type": "application/json",
|
|
32695
|
+
// Byte length, not string length: a multi-byte body sent with a
|
|
32696
|
+
// character count is truncated by the receiver.
|
|
32697
|
+
"content-length": String(Buffer.byteLength(options.body))
|
|
32698
|
+
}
|
|
32699
|
+
}
|
|
32700
|
+
};
|
|
32701
|
+
return new Promise((resolve2, reject) => {
|
|
32702
|
+
let settled = false;
|
|
32703
|
+
const fail = (reason, status) => {
|
|
32704
|
+
if (settled) return;
|
|
32705
|
+
settled = true;
|
|
32706
|
+
reject(new RemoteTransportError(reason, status));
|
|
32707
|
+
};
|
|
32708
|
+
const req = send_(url2, requestOptions, (res) => {
|
|
32709
|
+
const chunks = [];
|
|
32710
|
+
let size = 0;
|
|
32711
|
+
res.on("data", (chunk) => {
|
|
32712
|
+
size += chunk.length;
|
|
32713
|
+
if (size > MAX_RESPONSE_BYTES) {
|
|
32714
|
+
fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
|
|
32715
|
+
res.destroy();
|
|
32716
|
+
req.destroy();
|
|
32717
|
+
return;
|
|
32718
|
+
}
|
|
32719
|
+
chunks.push(chunk);
|
|
32720
|
+
});
|
|
32721
|
+
res.on("aborted", () => {
|
|
32722
|
+
fail("the response was aborted", res.statusCode);
|
|
32723
|
+
});
|
|
32724
|
+
res.on("end", () => {
|
|
32725
|
+
if (settled) return;
|
|
32726
|
+
settled = true;
|
|
32727
|
+
resolve2({
|
|
32728
|
+
status: res.statusCode ?? 0,
|
|
32729
|
+
headers: res.headers,
|
|
32730
|
+
body: Buffer.concat(chunks).toString("utf8")
|
|
32731
|
+
});
|
|
32732
|
+
});
|
|
32733
|
+
});
|
|
32734
|
+
const deadline = setTimeout(() => {
|
|
32735
|
+
fail(`no response within ${String(timeoutMs)}ms`);
|
|
32736
|
+
req.destroy();
|
|
32737
|
+
}, timeoutMs);
|
|
32738
|
+
deadline.unref();
|
|
32739
|
+
req.on("upgrade", (_res, socket) => {
|
|
32740
|
+
fail("the deployment answered with a protocol upgrade");
|
|
32741
|
+
socket.destroy();
|
|
32742
|
+
});
|
|
32743
|
+
req.on("close", () => {
|
|
32744
|
+
fail("the connection closed before a response was read");
|
|
32745
|
+
clearTimeout(deadline);
|
|
32746
|
+
});
|
|
32747
|
+
req.on("error", (err) => {
|
|
32748
|
+
fail(err.message);
|
|
32749
|
+
});
|
|
32750
|
+
if (options.body !== void 0) req.write(options.body);
|
|
32751
|
+
req.end();
|
|
32752
|
+
});
|
|
32753
|
+
}
|
|
32754
|
+
|
|
32755
|
+
// ../../packages/remote/src/client.ts
|
|
32756
|
+
var ROUTES = {
|
|
32757
|
+
events: "/v1/events",
|
|
32758
|
+
auditEvents: "/v1/audit-events",
|
|
32759
|
+
auditEventsBatch: "/v1/audit-events/batch",
|
|
32760
|
+
inventory: "/v1/inventory",
|
|
32761
|
+
storePosture: "/v1/store-posture",
|
|
32762
|
+
policyBundle: "/v1/policy-bundle",
|
|
32763
|
+
whoami: "/v1/plugin/whoami",
|
|
32764
|
+
shares: "/v1/shares",
|
|
32765
|
+
commands: "/v1/plugin/commands"
|
|
32766
|
+
};
|
|
32767
|
+
function ackRoute(id) {
|
|
32768
|
+
return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
|
|
32769
|
+
}
|
|
32770
|
+
function headerValue(response, name) {
|
|
32771
|
+
const raw = response.headers[name];
|
|
32772
|
+
if (raw === void 0) return void 0;
|
|
32773
|
+
return Array.isArray(raw) ? raw[0] : raw;
|
|
32774
|
+
}
|
|
32775
|
+
function okBody(response) {
|
|
32776
|
+
if (response.status < 200 || response.status >= 300) {
|
|
32777
|
+
throw new RemoteRequestError(response.status);
|
|
32778
|
+
}
|
|
32779
|
+
return response.body;
|
|
32780
|
+
}
|
|
32781
|
+
function parsed(schema, body, route) {
|
|
32782
|
+
let json2;
|
|
32783
|
+
try {
|
|
32784
|
+
json2 = JSON.parse(body);
|
|
32785
|
+
} catch {
|
|
32786
|
+
throw new RemoteResponseInvalid(route, "a body that is not JSON");
|
|
32787
|
+
}
|
|
32788
|
+
const result = schema.safeParse(json2);
|
|
32789
|
+
if (!result.success) {
|
|
32790
|
+
throw new RemoteResponseInvalid(route, "a body this client cannot read");
|
|
32791
|
+
}
|
|
32792
|
+
return result.data;
|
|
32793
|
+
}
|
|
32794
|
+
function withoutTrailingSlashes(endpoint) {
|
|
32795
|
+
let end = endpoint.length;
|
|
32796
|
+
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
|
|
32797
|
+
return endpoint.slice(0, end);
|
|
32798
|
+
}
|
|
32799
|
+
var SLASH = "/".charCodeAt(0);
|
|
32800
|
+
function createRemoteClient(options) {
|
|
32801
|
+
const base = withoutTrailingSlashes(options.endpoint);
|
|
32802
|
+
const url2 = (route) => `${base}${route}`;
|
|
32803
|
+
const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
|
|
32804
|
+
const sendOne = async (event) => {
|
|
32805
|
+
const validated = RecordAuditEventRequest.safeParse(event);
|
|
32806
|
+
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
|
|
32807
|
+
const response = await send({
|
|
32808
|
+
...common,
|
|
32809
|
+
method: "POST",
|
|
32810
|
+
url: url2(ROUTES.auditEvents),
|
|
32811
|
+
body: JSON.stringify(validated.data)
|
|
32812
|
+
});
|
|
32813
|
+
okBody(response);
|
|
32814
|
+
};
|
|
32815
|
+
return {
|
|
32816
|
+
async ingestEvents(batch) {
|
|
32817
|
+
const response = await send({
|
|
32818
|
+
...common,
|
|
32819
|
+
method: "POST",
|
|
32820
|
+
url: url2(ROUTES.events),
|
|
32821
|
+
body: JSON.stringify(batch)
|
|
32822
|
+
});
|
|
32823
|
+
return parsed(IngestAck, okBody(response), ROUTES.events);
|
|
32824
|
+
},
|
|
32825
|
+
async ingestInventory(context) {
|
|
32826
|
+
const response = await send({
|
|
32827
|
+
...common,
|
|
32828
|
+
method: "POST",
|
|
32829
|
+
url: url2(ROUTES.inventory),
|
|
32830
|
+
body: JSON.stringify(context)
|
|
32831
|
+
});
|
|
32832
|
+
return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
|
|
32833
|
+
},
|
|
32834
|
+
async recordAuditEvent(event) {
|
|
32835
|
+
await sendOne(event);
|
|
32836
|
+
},
|
|
32837
|
+
async recordAuditEvents(events, opts) {
|
|
32838
|
+
const validated = RecordAuditEventBatch.safeParse({ events });
|
|
32839
|
+
if (!validated.success) {
|
|
32840
|
+
throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
|
|
32841
|
+
}
|
|
32842
|
+
const response = await send({
|
|
32843
|
+
...common,
|
|
32844
|
+
method: "POST",
|
|
32845
|
+
url: url2(ROUTES.auditEventsBatch),
|
|
32846
|
+
body: JSON.stringify(validated.data)
|
|
32847
|
+
});
|
|
32848
|
+
if (response.status === 404) {
|
|
32849
|
+
if (opts?.fallbackToSingleEvents !== true) {
|
|
32850
|
+
throw new RemoteRouteAbsent(ROUTES.auditEventsBatch);
|
|
32851
|
+
}
|
|
32852
|
+
for (const event of validated.data.events) await sendOne(event);
|
|
32853
|
+
return { accepted: validated.data.events.length };
|
|
32854
|
+
}
|
|
32855
|
+
return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
|
|
32856
|
+
},
|
|
32857
|
+
async reportStorePosture(snapshot) {
|
|
32858
|
+
const response = await send({
|
|
32859
|
+
...common,
|
|
32860
|
+
method: "POST",
|
|
32861
|
+
url: url2(ROUTES.storePosture),
|
|
32862
|
+
body: JSON.stringify(snapshot)
|
|
32863
|
+
});
|
|
32864
|
+
okBody(response);
|
|
32865
|
+
},
|
|
32866
|
+
async getPolicyBundle(etag) {
|
|
32867
|
+
const response = await send({
|
|
32868
|
+
...common,
|
|
32869
|
+
method: "GET",
|
|
32870
|
+
url: url2(ROUTES.policyBundle),
|
|
32871
|
+
...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
|
|
32872
|
+
});
|
|
32873
|
+
if (response.status === 304) {
|
|
32874
|
+
return { changed: false, etag: headerValue(response, "etag") ?? etag };
|
|
32875
|
+
}
|
|
32876
|
+
const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
|
|
32877
|
+
return { changed: true, bundle, etag: headerValue(response, "etag") };
|
|
32878
|
+
},
|
|
32879
|
+
async whoami() {
|
|
32880
|
+
const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
|
|
32881
|
+
return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
|
|
32882
|
+
},
|
|
32883
|
+
async recordProjectEgress(request) {
|
|
32884
|
+
const validated = EgressIngestRequest.safeParse(request);
|
|
32885
|
+
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
|
|
32886
|
+
const response = await send({
|
|
32887
|
+
...common,
|
|
32888
|
+
method: "POST",
|
|
32889
|
+
url: url2(ROUTES.shares),
|
|
32890
|
+
body: JSON.stringify(validated.data)
|
|
32891
|
+
});
|
|
32892
|
+
okBody(response);
|
|
32893
|
+
},
|
|
32894
|
+
async pollCommand() {
|
|
32895
|
+
const response = await send({ ...common, method: "GET", url: url2(ROUTES.commands) });
|
|
32896
|
+
if (response.status === 404) return null;
|
|
32897
|
+
return parsed(DeviceCommandPollResponse, okBody(response), ROUTES.commands).command;
|
|
32898
|
+
},
|
|
32899
|
+
async ackCommand(id, body) {
|
|
32900
|
+
const validated = DeviceCommandAckBody.safeParse(body);
|
|
32901
|
+
const route = ackRoute(id);
|
|
32902
|
+
if (!validated.success) throw new RemoteRequestInvalid(route, validated.error);
|
|
32903
|
+
const response = await send({
|
|
32904
|
+
...common,
|
|
32905
|
+
method: "POST",
|
|
32906
|
+
url: url2(route),
|
|
32907
|
+
body: JSON.stringify(validated.data)
|
|
32908
|
+
});
|
|
32909
|
+
okBody(response);
|
|
32910
|
+
}
|
|
32911
|
+
};
|
|
32912
|
+
}
|
|
32913
|
+
|
|
32087
32914
|
// ../../packages/plugin-runtime/src/attached/failure.ts
|
|
32088
32915
|
function statusOf(err) {
|
|
32089
32916
|
if (typeof err !== "object" || err === null || !("status" in err)) return null;
|
|
@@ -32102,12 +32929,27 @@ function classifyFailure(err) {
|
|
|
32102
32929
|
}
|
|
32103
32930
|
}
|
|
32104
32931
|
|
|
32932
|
+
// ../../packages/plugin-runtime/src/attached/with-timeout.ts
|
|
32933
|
+
var REQUEST_TIMEOUT_MS = 2e3;
|
|
32934
|
+
function withTimeout(promise2, ms) {
|
|
32935
|
+
let timer;
|
|
32936
|
+
const timeout = new Promise((_, reject) => {
|
|
32937
|
+
timer = setTimeout(() => {
|
|
32938
|
+
reject(new Error("attached gateway request timed out"));
|
|
32939
|
+
}, ms);
|
|
32940
|
+
});
|
|
32941
|
+
promise2.catch(() => void 0);
|
|
32942
|
+
return Promise.race([promise2, timeout]).finally(() => {
|
|
32943
|
+
clearTimeout(timer);
|
|
32944
|
+
});
|
|
32945
|
+
}
|
|
32946
|
+
|
|
32105
32947
|
// ../../packages/plugin-runtime/src/attached/forward-drops.ts
|
|
32106
|
-
import { readFileSync as
|
|
32107
|
-
import { join as
|
|
32948
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
32949
|
+
import { join as join13 } from "path";
|
|
32108
32950
|
var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
|
|
32109
32951
|
function forwardDropsPath(dataDir2) {
|
|
32110
|
-
return
|
|
32952
|
+
return join13(dataDir2, FORWARD_DROPS_FILENAME);
|
|
32111
32953
|
}
|
|
32112
32954
|
function recordForwardDrops(dataDir2, count, nowMs) {
|
|
32113
32955
|
if (count <= 0) return;
|
|
@@ -32125,7 +32967,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
|
|
|
32125
32967
|
}
|
|
32126
32968
|
function readForwardDrops(dataDir2) {
|
|
32127
32969
|
try {
|
|
32128
|
-
const parsed2 = JSON.parse(
|
|
32970
|
+
const parsed2 = JSON.parse(readFileSync8(forwardDropsPath(dataDir2), "utf8"));
|
|
32129
32971
|
if (typeof parsed2 !== "object" || parsed2 === null) return null;
|
|
32130
32972
|
const record2 = parsed2;
|
|
32131
32973
|
if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
|
|
@@ -32143,13 +32985,13 @@ function readForwardDrops(dataDir2) {
|
|
|
32143
32985
|
|
|
32144
32986
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
32145
32987
|
import { randomUUID as randomUUID15 } from "crypto";
|
|
32146
|
-
import { readFileSync as
|
|
32988
|
+
import { readFileSync as readFileSync14 } from "fs";
|
|
32147
32989
|
import { readFile, rename, writeFile } from "fs/promises";
|
|
32148
|
-
import { join as
|
|
32990
|
+
import { join as join22 } from "path";
|
|
32149
32991
|
|
|
32150
32992
|
// ../../packages/plugin-sdk/src/config.ts
|
|
32151
32993
|
import { existsSync as existsSync7 } from "fs";
|
|
32152
|
-
import { join as
|
|
32994
|
+
import { join as join14 } from "path";
|
|
32153
32995
|
|
|
32154
32996
|
// ../../packages/plugin-sdk/src/provider-env.ts
|
|
32155
32997
|
var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
|
|
@@ -32203,7 +33045,7 @@ function resolveProvider() {
|
|
|
32203
33045
|
function loadConfig(base = defaultDataDir(), resolveProviderFn = resolveProvider) {
|
|
32204
33046
|
try {
|
|
32205
33047
|
ensureLayoutDirSync(base);
|
|
32206
|
-
const settingsFile =
|
|
33048
|
+
const settingsFile = join14(settingsDir(base), "settings.json");
|
|
32207
33049
|
if (existsSync7(settingsFile)) tightenFile(settingsFile);
|
|
32208
33050
|
} catch {
|
|
32209
33051
|
}
|
|
@@ -32227,9 +33069,9 @@ function resolveProviderSafe(resolveProviderFn) {
|
|
|
32227
33069
|
}
|
|
32228
33070
|
|
|
32229
33071
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
32230
|
-
import { readdirSync as readdirSync2, readFileSync as
|
|
33072
|
+
import { readdirSync as readdirSync2, readFileSync as readFileSync10, realpathSync as realpathSync2, statSync as statSync7 } from "fs";
|
|
32231
33073
|
import { homedir as homedir2 } from "os";
|
|
32232
|
-
import { basename as basename3, join as
|
|
33074
|
+
import { basename as basename3, join as join16 } from "path";
|
|
32233
33075
|
|
|
32234
33076
|
// ../../packages/detections/src/egress/registry.ts
|
|
32235
33077
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -35321,8 +36163,8 @@ function uniqueRuleIds(findings) {
|
|
|
35321
36163
|
}
|
|
35322
36164
|
|
|
35323
36165
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
35324
|
-
import { existsSync as existsSync8, readFileSync as
|
|
35325
|
-
import { basename as basename2, dirname as
|
|
36166
|
+
import { existsSync as existsSync8, readFileSync as readFileSync9, statSync as statSync6 } from "fs";
|
|
36167
|
+
import { basename as basename2, dirname as dirname4, isAbsolute, join as join15, sep as sep2 } from "path";
|
|
35326
36168
|
function resolveRepo(cwd) {
|
|
35327
36169
|
try {
|
|
35328
36170
|
const root = findGitRoot(cwd);
|
|
@@ -35337,36 +36179,36 @@ function resolveRepo(cwd) {
|
|
|
35337
36179
|
function findGitRoot(start) {
|
|
35338
36180
|
let dir = start;
|
|
35339
36181
|
for (; ; ) {
|
|
35340
|
-
if (existsSync8(
|
|
35341
|
-
const parent =
|
|
36182
|
+
if (existsSync8(join15(dir, ".git"))) return dir;
|
|
36183
|
+
const parent = dirname4(dir);
|
|
35342
36184
|
if (parent === dir) return void 0;
|
|
35343
36185
|
dir = parent;
|
|
35344
36186
|
}
|
|
35345
36187
|
}
|
|
35346
36188
|
function resolveGitContext(root) {
|
|
35347
|
-
const dotGit =
|
|
36189
|
+
const dotGit = join15(root, ".git");
|
|
35348
36190
|
try {
|
|
35349
36191
|
if (statSync6(dotGit).isDirectory()) {
|
|
35350
|
-
return { configPath:
|
|
36192
|
+
return { configPath: join15(dotGit, "config"), headRoot: root };
|
|
35351
36193
|
}
|
|
35352
36194
|
} catch {
|
|
35353
36195
|
return void 0;
|
|
35354
36196
|
}
|
|
35355
36197
|
const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
|
|
35356
36198
|
if (!target) return void 0;
|
|
35357
|
-
const gitdir = isAbsolute(target) ? target :
|
|
35358
|
-
if (existsSync8(
|
|
35359
|
-
return { configPath:
|
|
36199
|
+
const gitdir = isAbsolute(target) ? target : join15(root, target);
|
|
36200
|
+
if (existsSync8(join15(gitdir, "config"))) {
|
|
36201
|
+
return { configPath: join15(gitdir, "config"), headRoot: root };
|
|
35360
36202
|
}
|
|
35361
|
-
const commonRaw = safeRead(
|
|
36203
|
+
const commonRaw = safeRead(join15(gitdir, "commondir"))?.trim();
|
|
35362
36204
|
if (!commonRaw) return void 0;
|
|
35363
|
-
const commonGitDir = isAbsolute(commonRaw) ? commonRaw :
|
|
35364
|
-
const headRoot = basename2(commonGitDir) === ".git" ?
|
|
35365
|
-
return { configPath:
|
|
36205
|
+
const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join15(gitdir, commonRaw);
|
|
36206
|
+
const headRoot = basename2(commonGitDir) === ".git" ? dirname4(commonGitDir) : root;
|
|
36207
|
+
return { configPath: join15(commonGitDir, "config"), headRoot };
|
|
35366
36208
|
}
|
|
35367
36209
|
function safeRead(path) {
|
|
35368
36210
|
try {
|
|
35369
|
-
return
|
|
36211
|
+
return readFileSync9(path, "utf8");
|
|
35370
36212
|
} catch {
|
|
35371
36213
|
return void 0;
|
|
35372
36214
|
}
|
|
@@ -35911,8 +36753,8 @@ function createGuardedScanner(partition, gateway, opts) {
|
|
|
35911
36753
|
|
|
35912
36754
|
// ../../packages/plugin-sdk/src/ignore-layers.ts
|
|
35913
36755
|
var import_ignore = __toESM(require_ignore(), 1);
|
|
35914
|
-
import { readFileSync as
|
|
35915
|
-
import { join as
|
|
36756
|
+
import { readFileSync as readFileSync11 } from "fs";
|
|
36757
|
+
import { join as join17 } from "path";
|
|
35916
36758
|
|
|
35917
36759
|
// ../../packages/plugin-sdk/src/inventory-resolver.ts
|
|
35918
36760
|
import { arch, hostname as hostname4, platform, release } from "os";
|
|
@@ -35923,24 +36765,59 @@ import {
|
|
|
35923
36765
|
fstatSync,
|
|
35924
36766
|
mkdirSync as mkdirSync2,
|
|
35925
36767
|
openSync as openSync2,
|
|
35926
|
-
readFileSync as
|
|
36768
|
+
readFileSync as readFileSync12,
|
|
35927
36769
|
readSync,
|
|
35928
36770
|
writeFileSync as writeFileSync5
|
|
35929
36771
|
} from "fs";
|
|
35930
|
-
import { join as
|
|
36772
|
+
import { join as join18 } from "path";
|
|
35931
36773
|
var TAIL_BYTES = 256 * 1024;
|
|
35932
36774
|
|
|
35933
36775
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
35934
|
-
import { mkdirSync as mkdirSync3, readFileSync as
|
|
35935
|
-
import { join as
|
|
36776
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync13, writeFileSync as writeFileSync6 } from "fs";
|
|
36777
|
+
import { join as join19 } from "path";
|
|
35936
36778
|
|
|
35937
36779
|
// ../../packages/plugin-sdk/src/paths.ts
|
|
35938
36780
|
import { readdirSync as readdirSync3, realpathSync as realpathSync3 } from "fs";
|
|
35939
|
-
import { basename as basename4, dirname as
|
|
36781
|
+
import { basename as basename4, dirname as dirname5, sep as sep3 } from "path";
|
|
36782
|
+
|
|
36783
|
+
// ../../packages/plugin-sdk/src/policy-resolver.ts
|
|
36784
|
+
function createPolicyResolver(bundle) {
|
|
36785
|
+
const byRule = /* @__PURE__ */ new Map();
|
|
36786
|
+
const byCategory = /* @__PURE__ */ new Map();
|
|
36787
|
+
let reversible = /* @__PURE__ */ new Set();
|
|
36788
|
+
try {
|
|
36789
|
+
for (const policy of bundle.policies) {
|
|
36790
|
+
if (!policy.enabled) continue;
|
|
36791
|
+
if ("ruleId" in policy.target) {
|
|
36792
|
+
if (!byRule.has(policy.target.ruleId)) byRule.set(policy.target.ruleId, policy.action);
|
|
36793
|
+
} else if (!byCategory.has(policy.target.category)) {
|
|
36794
|
+
byCategory.set(policy.target.category, policy.action);
|
|
36795
|
+
}
|
|
36796
|
+
}
|
|
36797
|
+
reversible = new Set(bundle.reversibleRuleIds ?? []);
|
|
36798
|
+
} catch {
|
|
36799
|
+
byRule.clear();
|
|
36800
|
+
byCategory.clear();
|
|
36801
|
+
reversible = /* @__PURE__ */ new Set();
|
|
36802
|
+
}
|
|
36803
|
+
return {
|
|
36804
|
+
actionFor(ruleId, category) {
|
|
36805
|
+
const byRuleAction = byRule.get(ruleId);
|
|
36806
|
+
if (byRuleAction !== void 0) return byRuleAction;
|
|
36807
|
+
const byCategoryAction = byCategory.get(category);
|
|
36808
|
+
if (byCategoryAction !== void 0) return byCategoryAction;
|
|
36809
|
+
const fallback = DEFAULT_ACTIONS[category];
|
|
36810
|
+
return fallback ?? "log";
|
|
36811
|
+
},
|
|
36812
|
+
isReversible(ruleId) {
|
|
36813
|
+
return reversible.has(ruleId);
|
|
36814
|
+
}
|
|
36815
|
+
};
|
|
36816
|
+
}
|
|
35940
36817
|
|
|
35941
36818
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
35942
36819
|
import { existsSync as existsSync10, readdirSync as readdirSync4 } from "fs";
|
|
35943
|
-
import { basename as basename5, join as
|
|
36820
|
+
import { basename as basename5, join as join20 } from "path";
|
|
35944
36821
|
|
|
35945
36822
|
// ../../packages/plugin-sdk/src/provider-env-antigravity.ts
|
|
35946
36823
|
var optionalBaseUrl2 = external_exports.preprocess((v) => {
|
|
@@ -35971,7 +36848,6 @@ var CodexProviderEnvSchema = external_exports.object(codexProviderEnvShape);
|
|
|
35971
36848
|
// ../../packages/plugin-sdk/src/runtime.ts
|
|
35972
36849
|
import { randomUUID as randomUUID14 } from "crypto";
|
|
35973
36850
|
var ENFORCEMENT_CEILING_ENABLED = false;
|
|
35974
|
-
var ACTION_PRIORITY = ["block", "redact", "warn", "log", "allow"];
|
|
35975
36851
|
function startTiming() {
|
|
35976
36852
|
try {
|
|
35977
36853
|
return performance.now();
|
|
@@ -36008,28 +36884,22 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36008
36884
|
bundlesPacked = true;
|
|
36009
36885
|
}
|
|
36010
36886
|
const policyMode = settings.policy;
|
|
36887
|
+
const redactFallback = settings.redactFallback;
|
|
36011
36888
|
const dataDir2 = opts?.dataDir;
|
|
36012
|
-
let policies = [];
|
|
36013
36889
|
let rules = [];
|
|
36014
36890
|
let scanner;
|
|
36015
36891
|
let bundleExceptions = [];
|
|
36016
36892
|
let initialized = false;
|
|
36017
|
-
|
|
36018
|
-
|
|
36019
|
-
|
|
36893
|
+
let resolver = createPolicyResolver({
|
|
36894
|
+
version: "",
|
|
36895
|
+
policies: [],
|
|
36896
|
+
customKeywords: [],
|
|
36897
|
+
fetchedAt: ""
|
|
36898
|
+
});
|
|
36020
36899
|
async function ensureInitialized() {
|
|
36021
36900
|
if (initialized) return;
|
|
36022
36901
|
const bundle = await gateway.getPolicyBundle();
|
|
36023
|
-
|
|
36024
|
-
for (const p of policies) {
|
|
36025
|
-
if (!p.enabled) continue;
|
|
36026
|
-
if ("ruleId" in p.target) {
|
|
36027
|
-
if (!ruleActionIndex.has(p.target.ruleId)) ruleActionIndex.set(p.target.ruleId, p.action);
|
|
36028
|
-
} else if (!categoryActionIndex.has(p.target.category)) {
|
|
36029
|
-
categoryActionIndex.set(p.target.category, p.action);
|
|
36030
|
-
}
|
|
36031
|
-
}
|
|
36032
|
-
reversibleRuleIndex = new Set(bundle.reversibleRuleIds ?? []);
|
|
36902
|
+
resolver = createPolicyResolver(bundle);
|
|
36033
36903
|
const bundledProbeKeys = new Set(
|
|
36034
36904
|
getLoadedRules().map(ruleProbeKey).filter((key) => key !== void 0)
|
|
36035
36905
|
);
|
|
@@ -36082,33 +36952,28 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36082
36952
|
return cachedKey;
|
|
36083
36953
|
}
|
|
36084
36954
|
function resolveAction(ruleId, category) {
|
|
36085
|
-
|
|
36086
|
-
|
|
36087
|
-
|
|
36088
|
-
if (byCategory !== void 0) return byCategory;
|
|
36089
|
-
const fallback = DEFAULT_ACTIONS[category];
|
|
36090
|
-
return fallback ?? "log";
|
|
36091
|
-
}
|
|
36092
|
-
function actionForFinding(finding, excepted) {
|
|
36955
|
+
return resolver.actionFor(ruleId, category);
|
|
36956
|
+
}
|
|
36957
|
+
function actionForFinding(finding, excepted, rewritable = true) {
|
|
36093
36958
|
if (excepted?.has(finding)) return "allow";
|
|
36094
36959
|
const action = resolveAction(finding.ruleId, finding.category);
|
|
36960
|
+
if (!rewritable && action === "redact") return builtinPolicyToAction(redactFallback);
|
|
36095
36961
|
if (ENFORCEMENT_CEILING_ENABLED && policyMode === "warn" && (action === "block" || action === "redact")) {
|
|
36096
36962
|
return "warn";
|
|
36097
36963
|
}
|
|
36098
36964
|
return action;
|
|
36099
36965
|
}
|
|
36100
|
-
function decide(findings, text, excepted) {
|
|
36966
|
+
function decide(findings, text, excepted, rewritable = true) {
|
|
36101
36967
|
if (findings.length === 0) return { action: "log", text, findings: [] };
|
|
36102
|
-
const actionFor = (finding) => actionForFinding(finding, excepted);
|
|
36968
|
+
const actionFor = (finding) => actionForFinding(finding, excepted, rewritable);
|
|
36103
36969
|
let worst = "log";
|
|
36104
36970
|
for (const finding of findings) {
|
|
36105
|
-
|
|
36106
|
-
if (ACTION_PRIORITY.indexOf(action) < ACTION_PRIORITY.indexOf(worst)) worst = action;
|
|
36971
|
+
worst = strongerAction(worst, actionFor(finding));
|
|
36107
36972
|
}
|
|
36108
36973
|
if (worst === "block") return { action: "block", text: null, findings };
|
|
36109
36974
|
if (worst === "redact") {
|
|
36110
36975
|
const redactFindings = findings.filter((f) => actionFor(f) === "redact");
|
|
36111
|
-
const reversibleFindings = redactFindings.filter((f) =>
|
|
36976
|
+
const reversibleFindings = redactFindings.filter((f) => resolver.isReversible(f.ruleId));
|
|
36112
36977
|
return {
|
|
36113
36978
|
action: "redact",
|
|
36114
36979
|
text: redact(text, redactFindings),
|
|
@@ -36184,7 +37049,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36184
37049
|
return { excepted: /* @__PURE__ */ new Set(), exceptionIds: [] };
|
|
36185
37050
|
}
|
|
36186
37051
|
}
|
|
36187
|
-
async function recordBlockedDetections(decision, excepted, ctx, fpCache) {
|
|
37052
|
+
async function recordBlockedDetections(decision, excepted, ctx, fpCache, rewritable = true) {
|
|
36188
37053
|
const references = [];
|
|
36189
37054
|
try {
|
|
36190
37055
|
if (decision.action !== "block" && decision.action !== "redact") return references;
|
|
@@ -36192,7 +37057,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36192
37057
|
if (!key) return references;
|
|
36193
37058
|
const seen = /* @__PURE__ */ new Set();
|
|
36194
37059
|
for (const finding of decision.findings) {
|
|
36195
|
-
const action = actionForFinding(finding, excepted);
|
|
37060
|
+
const action = actionForFinding(finding, excepted, rewritable);
|
|
36196
37061
|
if (action !== "block" && action !== "redact") continue;
|
|
36197
37062
|
const fp = fingerprintOf(key, finding, fpCache);
|
|
36198
37063
|
const pair = `${finding.ruleId}:${fp}`;
|
|
@@ -36219,7 +37084,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36219
37084
|
}
|
|
36220
37085
|
return references;
|
|
36221
37086
|
}
|
|
36222
|
-
async function evaluate(text, context, ctx) {
|
|
37087
|
+
async function evaluate(text, context, ctx, rewritable = true) {
|
|
36223
37088
|
try {
|
|
36224
37089
|
await ensureInitialized();
|
|
36225
37090
|
if (!scanner) throw new Error("the runtime initialized without a scanner");
|
|
@@ -36228,8 +37093,14 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36228
37093
|
const findings = dropShieldedFindings(matched, shielded.spans);
|
|
36229
37094
|
const fpCache = /* @__PURE__ */ new Map();
|
|
36230
37095
|
const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
|
|
36231
|
-
const decision = decide(findings, text, excepted);
|
|
36232
|
-
const blockedReferences = await recordBlockedDetections(
|
|
37096
|
+
const decision = decide(findings, text, excepted, rewritable);
|
|
37097
|
+
const blockedReferences = await recordBlockedDetections(
|
|
37098
|
+
decision,
|
|
37099
|
+
excepted,
|
|
37100
|
+
ctx,
|
|
37101
|
+
fpCache,
|
|
37102
|
+
rewritable
|
|
37103
|
+
);
|
|
36233
37104
|
if (blockedReferences.length > 0) decision.blockedReferences = blockedReferences;
|
|
36234
37105
|
return { decision, excepted, exceptionIds };
|
|
36235
37106
|
} catch {
|
|
@@ -36253,12 +37124,16 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36253
37124
|
sourceTool: input2.sourceTool,
|
|
36254
37125
|
metadata: input2.metadata,
|
|
36255
37126
|
preAuthorizedGrantIds: opts2.preAuthorizedGrantIds
|
|
36256
|
-
}
|
|
37127
|
+
},
|
|
37128
|
+
opts2.rewritable
|
|
36257
37129
|
);
|
|
36258
37130
|
if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
|
|
36259
37131
|
try {
|
|
36260
37132
|
const contentHash = contentHashOf(input2.text);
|
|
36261
|
-
const
|
|
37133
|
+
const maskedFindings = decision.findings.filter(
|
|
37134
|
+
(match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
|
|
37135
|
+
);
|
|
37136
|
+
const storedContent = maskedFindings.length > 0 ? redact(input2.text, maskedFindings) : input2.text;
|
|
36262
37137
|
const inspectionMs = elapsedMs(timingStartedAt);
|
|
36263
37138
|
const metadata = exceptionIds.length > 0 || inspectionMs !== void 0 ? {
|
|
36264
37139
|
...input2.metadata,
|
|
@@ -36295,7 +37170,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
36295
37170
|
severity: match.severity,
|
|
36296
37171
|
span: match.span,
|
|
36297
37172
|
maskedMatch,
|
|
36298
|
-
actionTaken: actionForFinding(match, excepted),
|
|
37173
|
+
actionTaken: actionForFinding(match, excepted, opts2.rewritable),
|
|
36299
37174
|
confidence: match.confidence,
|
|
36300
37175
|
...findingKey ? { findingKey } : {}
|
|
36301
37176
|
};
|
|
@@ -36335,27 +37210,19 @@ var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
|
36335
37210
|
|
|
36336
37211
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
36337
37212
|
import { mkdirSync as mkdirSync4, statSync as statSync8, writeFileSync as writeFileSync7 } from "fs";
|
|
36338
|
-
import { join as
|
|
36339
|
-
|
|
36340
|
-
// ../../packages/plugin-runtime/src/attached/with-timeout.ts
|
|
36341
|
-
var REQUEST_TIMEOUT_MS = 2e3;
|
|
36342
|
-
function withTimeout(promise2, ms) {
|
|
36343
|
-
let timer;
|
|
36344
|
-
const timeout = new Promise((_, reject) => {
|
|
36345
|
-
timer = setTimeout(() => {
|
|
36346
|
-
reject(new Error("attached gateway request timed out"));
|
|
36347
|
-
}, ms);
|
|
36348
|
-
});
|
|
36349
|
-
promise2.catch(() => void 0);
|
|
36350
|
-
return Promise.race([promise2, timeout]).finally(() => {
|
|
36351
|
-
clearTimeout(timer);
|
|
36352
|
-
});
|
|
36353
|
-
}
|
|
37213
|
+
import { join as join21 } from "path";
|
|
36354
37214
|
|
|
36355
37215
|
// ../../packages/plugin-runtime/src/attached/forward-policy.ts
|
|
36356
37216
|
function isInvalidRequest(err) {
|
|
36357
37217
|
return typeof err === "object" && err !== null && err.name === "RemoteRequestInvalid";
|
|
36358
37218
|
}
|
|
37219
|
+
function isRouteAbsent(err) {
|
|
37220
|
+
return typeof err === "object" && err !== null && err.name === "RemoteRouteAbsent";
|
|
37221
|
+
}
|
|
37222
|
+
function isServerRejection(err) {
|
|
37223
|
+
const status = statusOf(err);
|
|
37224
|
+
return status !== null && status >= 400 && status <= 499 && status !== 401 && status !== 403 && status !== 404 && status !== 429;
|
|
37225
|
+
}
|
|
36359
37226
|
var FORWARD_BUDGET_MS = 1500;
|
|
36360
37227
|
var DECISION_PATH_BUDGET_MS = 800;
|
|
36361
37228
|
var BREAKER_FAILURE_THRESHOLD = 3;
|
|
@@ -36383,7 +37250,7 @@ function parseBreakerState(raw, nowMs) {
|
|
|
36383
37250
|
}
|
|
36384
37251
|
function createForwardPolicy(deps) {
|
|
36385
37252
|
const now = deps.now ?? (() => Date.now());
|
|
36386
|
-
const file2 =
|
|
37253
|
+
const file2 = join22(deps.dir, STATE_FILENAME);
|
|
36387
37254
|
let state = null;
|
|
36388
37255
|
let loading = null;
|
|
36389
37256
|
async function readState() {
|
|
@@ -36423,6 +37290,20 @@ function createForwardPolicy(deps) {
|
|
|
36423
37290
|
} catch {
|
|
36424
37291
|
current = { ...CLOSED };
|
|
36425
37292
|
}
|
|
37293
|
+
const restoreOpenedAtMs = (openedAtMs) => persist({
|
|
37294
|
+
consecutiveFailures: current.consecutiveFailures,
|
|
37295
|
+
openedAtMs,
|
|
37296
|
+
lastFailure: current.lastFailure
|
|
37297
|
+
});
|
|
37298
|
+
const recordFailure = (cause) => {
|
|
37299
|
+
const failures = current.consecutiveFailures + 1;
|
|
37300
|
+
const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
|
|
37301
|
+
return persist({
|
|
37302
|
+
consecutiveFailures: failures,
|
|
37303
|
+
openedAtMs: shouldOpen ? now() : null,
|
|
37304
|
+
lastFailure: cause
|
|
37305
|
+
});
|
|
37306
|
+
};
|
|
36426
37307
|
const at = now();
|
|
36427
37308
|
if (current.openedAtMs !== null) {
|
|
36428
37309
|
if (at - current.openedAtMs < BREAKER_COOLDOWN_MS) {
|
|
@@ -36441,15 +37322,20 @@ function createForwardPolicy(deps) {
|
|
|
36441
37322
|
}
|
|
36442
37323
|
return { ok: true, value };
|
|
36443
37324
|
} catch (err) {
|
|
36444
|
-
if (isInvalidRequest(err))
|
|
37325
|
+
if (isInvalidRequest(err)) {
|
|
37326
|
+
if (current.openedAtMs !== null) await restoreOpenedAtMs(current.openedAtMs);
|
|
37327
|
+
return { ok: false, reason: "invalid-request" };
|
|
37328
|
+
}
|
|
37329
|
+
if (isRouteAbsent(err)) {
|
|
37330
|
+
if (current.openedAtMs !== null) await restoreOpenedAtMs(null);
|
|
37331
|
+
return { ok: false, reason: "route-absent" };
|
|
37332
|
+
}
|
|
37333
|
+
if (isServerRejection(err)) {
|
|
37334
|
+
await recordFailure("unreachable");
|
|
37335
|
+
return { ok: false, reason: "rejected" };
|
|
37336
|
+
}
|
|
36445
37337
|
const reason = classifyFailure(err);
|
|
36446
|
-
|
|
36447
|
-
const shouldOpen = current.openedAtMs !== null || failures >= BREAKER_FAILURE_THRESHOLD;
|
|
36448
|
-
await persist({
|
|
36449
|
-
consecutiveFailures: failures,
|
|
36450
|
-
openedAtMs: shouldOpen ? now() : null,
|
|
36451
|
-
lastFailure: reason
|
|
36452
|
-
});
|
|
37338
|
+
await recordFailure(reason);
|
|
36453
37339
|
return { ok: false, reason };
|
|
36454
37340
|
}
|
|
36455
37341
|
}
|
|
@@ -36457,13 +37343,11 @@ function createForwardPolicy(deps) {
|
|
|
36457
37343
|
}
|
|
36458
37344
|
|
|
36459
37345
|
// ../../packages/plugin-runtime/src/attached/gateway.ts
|
|
36460
|
-
|
|
36461
|
-
|
|
36462
|
-
|
|
36463
|
-
|
|
36464
|
-
|
|
36465
|
-
block: 4
|
|
36466
|
-
};
|
|
37346
|
+
function strongerOf(a, b) {
|
|
37347
|
+
if (a === null) return b;
|
|
37348
|
+
if (b === null) return a;
|
|
37349
|
+
return strongerAction(a, b);
|
|
37350
|
+
}
|
|
36467
37351
|
function ruleCategoryMap(wireRules, localRules) {
|
|
36468
37352
|
const map2 = /* @__PURE__ */ new Map();
|
|
36469
37353
|
for (const rule of wireRules ?? []) map2.set(rule.id, rule.category);
|
|
@@ -36473,11 +37357,6 @@ function ruleCategoryMap(wireRules, localRules) {
|
|
|
36473
37357
|
}
|
|
36474
37358
|
return map2;
|
|
36475
37359
|
}
|
|
36476
|
-
function strongerOf(a, b) {
|
|
36477
|
-
if (a === null) return b;
|
|
36478
|
-
if (b === null) return a;
|
|
36479
|
-
return ACTION_STRENGTH[a] >= ACTION_STRENGTH[b] ? a : b;
|
|
36480
|
-
}
|
|
36481
37360
|
function policyKey(policy) {
|
|
36482
37361
|
return "ruleId" in policy.target ? `rule:${policy.target.ruleId}` : `category:${policy.target.category}`;
|
|
36483
37362
|
}
|
|
@@ -36496,7 +37375,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
|
|
|
36496
37375
|
const floor = floorFor(policy, categoryByRuleId);
|
|
36497
37376
|
remoteCategoryAction.set(
|
|
36498
37377
|
policy.target.category,
|
|
36499
|
-
floor !== null &&
|
|
37378
|
+
floor !== null && !isActionAtLeast(policy.action, floor) ? floor : policy.action
|
|
36500
37379
|
);
|
|
36501
37380
|
}
|
|
36502
37381
|
for (const policy of localPolicies) {
|
|
@@ -36513,7 +37392,7 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
|
|
|
36513
37392
|
}
|
|
36514
37393
|
merged.set(
|
|
36515
37394
|
key,
|
|
36516
|
-
remoteFloor !== null &&
|
|
37395
|
+
remoteFloor !== null && !isActionAtLeast(policy.action, remoteFloor) ? { ...policy, action: remoteFloor } : policy
|
|
36517
37396
|
);
|
|
36518
37397
|
}
|
|
36519
37398
|
const localCategoryAction = /* @__PURE__ */ new Map();
|
|
@@ -36533,13 +37412,13 @@ function mergeRaiseOnly(localPolicies, remotePolicies, categoryByRuleId) {
|
|
|
36533
37412
|
if (category !== void 0) localFloor = localCategoryAction.get(category) ?? null;
|
|
36534
37413
|
}
|
|
36535
37414
|
const effectiveFloor = strongerOf(floor, localFloor);
|
|
36536
|
-
const clamped = effectiveFloor !== null &&
|
|
37415
|
+
const clamped = effectiveFloor !== null && !isActionAtLeast(policy.action, effectiveFloor) ? { ...policy, action: effectiveFloor } : policy;
|
|
36537
37416
|
const existing = merged.get(key);
|
|
36538
37417
|
if (existing === void 0) {
|
|
36539
37418
|
merged.set(key, clamped);
|
|
36540
37419
|
continue;
|
|
36541
37420
|
}
|
|
36542
|
-
if (
|
|
37421
|
+
if (actionRank(clamped.action) > actionRank(existing.action)) {
|
|
36543
37422
|
merged.set(key, clamped);
|
|
36544
37423
|
}
|
|
36545
37424
|
}
|
|
@@ -36572,6 +37451,8 @@ var AttachedDataGateway = class {
|
|
|
36572
37451
|
);
|
|
36573
37452
|
if (forwarded.ok && forwarded.value.accepted + forwarded.value.duplicates > 0) {
|
|
36574
37453
|
this.deps.local.markCaptureDelivered(record2.event, Date.now());
|
|
37454
|
+
} else {
|
|
37455
|
+
this.deps.local.markCaptureOwed(record2.event);
|
|
36575
37456
|
}
|
|
36576
37457
|
}
|
|
36577
37458
|
async ensureInventory(ctx) {
|
|
@@ -36608,9 +37489,10 @@ var AttachedDataGateway = class {
|
|
|
36608
37489
|
// a retried tool_call, exactly this path — can never stomp a populated row.
|
|
36609
37490
|
async recordAuditEvent(event) {
|
|
36610
37491
|
await this.deps.local.recordAuditEvent(event);
|
|
36611
|
-
await this.deps.forward.run(
|
|
37492
|
+
const forwarded = await this.deps.forward.run(
|
|
36612
37493
|
() => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
|
|
36613
37494
|
);
|
|
37495
|
+
if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
|
|
36614
37496
|
}
|
|
36615
37497
|
// Attached `llm_call` is written locally by the inner gateway, then routed to
|
|
36616
37498
|
// the control plane through the existing `recordAuditEvent` ingest (no dedicated
|
|
@@ -36619,44 +37501,170 @@ var AttachedDataGateway = class {
|
|
|
36619
37501
|
// which would write the event to the local store a second time.
|
|
36620
37502
|
async recordLlmCall(input2) {
|
|
36621
37503
|
await this.deps.local.recordLlmCall(input2);
|
|
36622
|
-
|
|
36623
|
-
|
|
36624
|
-
|
|
36625
|
-
)
|
|
37504
|
+
const event = llmAuditEvent(input2);
|
|
37505
|
+
const forwarded = await this.deps.forward.run(
|
|
37506
|
+
() => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
|
|
36626
37507
|
);
|
|
37508
|
+
if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
|
|
36627
37509
|
}
|
|
36628
37510
|
/**
|
|
36629
|
-
* Forward one batch
|
|
37511
|
+
* Forward one batch in CHUNKS of AUDIT_EVENT_BATCH_MAX, under ONE aggregate deadline.
|
|
37512
|
+
*
|
|
37513
|
+
* This used to send one HTTP request per event, which is what made the batch
|
|
37514
|
+
* budget bite: at 200ms round-trip a 3s budget admitted ~15 events and threw
|
|
37515
|
+
* away everything after them. The same rows now cross 50 at a time over
|
|
37516
|
+
* `POST /v1/audit-events/batch` — the route the attach-time drain has always
|
|
37517
|
+
* used — so the same budget admits ~750. The wire cap is the server's own
|
|
37518
|
+
* constant, sized against server cost, and the client REFUSES a longer array
|
|
37519
|
+
* client-side, so the chunking here is not a convention.
|
|
37520
|
+
*
|
|
37521
|
+
* Still serial, and still for the original reason: firing N requests at once
|
|
37522
|
+
* would trade a latency problem for a burst the plane's per-key rate limiting
|
|
37523
|
+
* answers with the refusals the breaker then counts. Fewer, fuller requests is
|
|
37524
|
+
* the fix; more concurrent ones is not.
|
|
37525
|
+
*
|
|
37526
|
+
* When the deadline passes the remainder is dropped rather than sent: the
|
|
37527
|
+
* local write has already succeeded, so every caller has a correct result to
|
|
37528
|
+
* return. What is dropped is COUNTED, everywhere it can happen — this path
|
|
37529
|
+
* returns BEFORE `ForwardPolicy.run` is reached, so without the tally in
|
|
37530
|
+
* `forward-drops.ts` a slow-but-answering plane produces no failures, keeps
|
|
37531
|
+
* the breaker closed, renders a healthy block, and discards the tail of every
|
|
37532
|
+
* batch indefinitely. The SAME tally also covers a single that fails inside
|
|
37533
|
+
* the per-item retry below — the breaker opening mid-retry is a failure the
|
|
37534
|
+
* breaker's own state DOES capture, but the events still in this chunk once
|
|
37535
|
+
* that happens are neither delivered nor otherwise counted anywhere, which is
|
|
37536
|
+
* the same invisibility with a different cause.
|
|
37537
|
+
*
|
|
37538
|
+
* `ok` ALONE IS NOT DELIVERY, the same rule `recordCapture` states for the
|
|
37539
|
+
* single-event ack and at fifty times the blast radius here:
|
|
37540
|
+
* `AuditEventBatchAck.accepted` is an aggregate count the wire contract does
|
|
37541
|
+
* not tie to the chunk's own length, so a 2xx answering `{accepted: 30}` for
|
|
37542
|
+
* fifty events is well-formed. Trusting `ok` alone would stamp all fifty as
|
|
37543
|
+
* delivered and never re-offer the twenty the plane did not take. So success
|
|
37544
|
+
* is checked against `chunk.length`; anything short of it falls into the same
|
|
37545
|
+
* per-item pass as a refused chunk, which is the only way to recover the
|
|
37546
|
+
* rows that did not land, since the ack carries no per-row verdict to
|
|
37547
|
+
* resend by.
|
|
37548
|
+
*
|
|
37549
|
+
* That fallback ASSUMES a re-send of an already-landed row is a harmless
|
|
37550
|
+
* no-op rather than a second cost — an assumption this file cannot verify.
|
|
37551
|
+
* `AuditEventBatchAck` carries only `accepted`, unlike its sibling
|
|
37552
|
+
* `IngestAck` (`accepted` + `duplicates`, with `accepted + duplicates ==`
|
|
37553
|
+
* the batch size as the invariant `recordCapture` reads), so whether a
|
|
37554
|
+
* duplicate counts toward THIS route's `accepted` is not expressed
|
|
37555
|
+
* anywhere in this repo. If it follows its sibling's convention and does
|
|
37556
|
+
* NOT, a chunk containing even one already-delivered row — the ordinary
|
|
37557
|
+
* consequence of a lost stamp, which this file already treats as cheap —
|
|
37558
|
+
* answers short forever and enters the per-item pass on every pass it is
|
|
37559
|
+
* offered again. The cost of that is bounded rather than silent: the
|
|
37560
|
+
* pass converges (every row lands and stamps), so it is one wasted round
|
|
37561
|
+
* of singles rather than a stall, and it errs toward an extra resend
|
|
37562
|
+
* rather than toward the lost row the alternative risks.
|
|
36630
37563
|
*
|
|
36631
|
-
*
|
|
36632
|
-
*
|
|
36633
|
-
*
|
|
36634
|
-
*
|
|
36635
|
-
*
|
|
37564
|
+
* BATCH-ATOMIC SETTLEMENT is otherwise the rule: the receiver wraps a chunk in
|
|
37565
|
+
* one transaction, so a full 2xx settles every event in it and a non-2xx
|
|
37566
|
+
* settles none — which is why the whole chunk is stamped together on a FULL
|
|
37567
|
+
* accept and none of it otherwise. THREE reasons do not deserve whole-chunk
|
|
37568
|
+
* treatment, alongside a short accept, and all are re-sent one event at a
|
|
37569
|
+
* time:
|
|
36636
37570
|
*
|
|
36637
|
-
*
|
|
36638
|
-
*
|
|
36639
|
-
*
|
|
37571
|
+
* `invalid-request` a chunk the client refused to send at all. One malformed
|
|
37572
|
+
* event would otherwise cost the 49 good ones beside it —
|
|
37573
|
+
* a new way to lose data introduced by the very change
|
|
37574
|
+
* meant to stop losing it.
|
|
37575
|
+
* `route-absent` a deployment that predates the batch route. The
|
|
37576
|
+
* single-event route is the one it serves, and re-sending
|
|
37577
|
+
* here rather than inside the client is what gives each
|
|
37578
|
+
* request its own budget instead of 50 inside one.
|
|
37579
|
+
* `rejected` the deployment's SERVER-side twin of `invalid-request` —
|
|
37580
|
+
* a 4xx body refusal from schema drift on the other side
|
|
37581
|
+
* of the wire. Settlement is batch-atomic on this reason
|
|
37582
|
+
* exactly as on the others, so leaving it out would cost
|
|
37583
|
+
* the whole chunk for one event the DEPLOYMENT considers
|
|
37584
|
+
* malformed, where the per-item form cost only that one.
|
|
36640
37585
|
*
|
|
36641
|
-
*
|
|
36642
|
-
*
|
|
36643
|
-
*
|
|
36644
|
-
*
|
|
36645
|
-
* plane produces no failures, keeps the breaker closed, renders a healthy
|
|
36646
|
-
* block, and discards the tail of every batch indefinitely.
|
|
37586
|
+
* Every other reason (breaker-open, a refusal, a timeout) applies to the whole
|
|
37587
|
+
* chunk, and re-sending it item by item would just spend the budget failing 50
|
|
37588
|
+
* more times — for those, the blast radius stays exactly what it was before
|
|
37589
|
+
* batching.
|
|
36647
37590
|
*/
|
|
36648
37591
|
async forwardBatch(inputs, toEvent) {
|
|
36649
37592
|
const deadline = Date.now() + BATCH_FORWARD_BUDGET_MS;
|
|
36650
|
-
|
|
36651
|
-
|
|
36652
|
-
|
|
36653
|
-
|
|
36654
|
-
|
|
37593
|
+
const delivered = [];
|
|
37594
|
+
try {
|
|
37595
|
+
for (let i = 0; i < inputs.length; i += AUDIT_EVENT_BATCH_MAX) {
|
|
37596
|
+
const now = Date.now();
|
|
37597
|
+
if (now >= deadline) {
|
|
37598
|
+
recordForwardDrops(this.deps.dataDir, inputs.length - i, now);
|
|
37599
|
+
return;
|
|
37600
|
+
}
|
|
37601
|
+
const chunk = inputs.slice(i, i + AUDIT_EVENT_BATCH_MAX).map((input2) => toEvent(input2));
|
|
37602
|
+
const forwarded = await this.deps.forward.run(
|
|
37603
|
+
() => this.deps.client.recordAuditEvents(
|
|
37604
|
+
chunk.map((event) => reKeyForForward(event, this.remoteInventory))
|
|
37605
|
+
)
|
|
37606
|
+
);
|
|
37607
|
+
if (forwarded.ok) {
|
|
37608
|
+
if (forwarded.value.accepted === chunk.length) {
|
|
37609
|
+
delivered.push(...chunk);
|
|
37610
|
+
continue;
|
|
37611
|
+
}
|
|
37612
|
+
} else if (
|
|
37613
|
+
// THREE reasons are worth a second pass, one at a time, and they are
|
|
37614
|
+
// the three settled BEFORE the control plane refused anything, or
|
|
37615
|
+
// (for `rejected`) refused the BODY rather than the connection.
|
|
37616
|
+
//
|
|
37617
|
+
// `invalid-request` — the CLIENT refused the body before any request
|
|
37618
|
+
// went out: a defect in one event, not an outage. Re-sending singly
|
|
37619
|
+
// isolates the bad one instead of charging its 49 neighbours for it.
|
|
37620
|
+
//
|
|
37621
|
+
// `route-absent` — the deployment predates the batch route and serves
|
|
37622
|
+
// only the single-event one. The retry IS the compatibility path, and
|
|
37623
|
+
// it has to live HERE rather than inside the client: each single gets
|
|
37624
|
+
// its own FORWARD_BUDGET_MS through `run`, whereas the client's own
|
|
37625
|
+
// fallback would spend 50 sequential round trips inside the ONE
|
|
37626
|
+
// budget wrapping this call — turning a working older deployment into
|
|
37627
|
+
// a timeout, three of those into an open breaker, and every row into
|
|
37628
|
+
// a silent drop while the status surface called an answering
|
|
37629
|
+
// deployment down.
|
|
37630
|
+
//
|
|
37631
|
+
// `rejected` — the deployment's own 4xx refusal of the body, the
|
|
37632
|
+
// server-side twin of `invalid-request`: isolating it the same way
|
|
37633
|
+
// costs one event instead of the whole chunk for a defect the
|
|
37634
|
+
// deployment considers local to one row.
|
|
37635
|
+
//
|
|
37636
|
+
// Every other reason (breaker-open, a refusal, a timeout) applies to
|
|
37637
|
+
// the whole chunk; re-sending it item by item would just spend the
|
|
37638
|
+
// budget failing 50 more times.
|
|
37639
|
+
forwarded.reason !== "invalid-request" && forwarded.reason !== "route-absent" && forwarded.reason !== "rejected"
|
|
37640
|
+
) {
|
|
37641
|
+
continue;
|
|
37642
|
+
}
|
|
37643
|
+
for (const [j, event] of chunk.entries()) {
|
|
37644
|
+
const at = Date.now();
|
|
37645
|
+
if (at >= deadline) {
|
|
37646
|
+
recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
|
|
37647
|
+
return;
|
|
37648
|
+
}
|
|
37649
|
+
const single = await this.deps.forward.run(
|
|
37650
|
+
() => this.deps.client.recordAuditEvent(reKeyForForward(event, this.remoteInventory))
|
|
37651
|
+
);
|
|
37652
|
+
if (single.ok) {
|
|
37653
|
+
delivered.push(event);
|
|
37654
|
+
continue;
|
|
37655
|
+
}
|
|
37656
|
+
if (single.reason === "breaker-open") {
|
|
37657
|
+
recordForwardDrops(this.deps.dataDir, inputs.length - i - j, at);
|
|
37658
|
+
return;
|
|
37659
|
+
}
|
|
37660
|
+
recordForwardDrops(this.deps.dataDir, 1, at);
|
|
37661
|
+
}
|
|
37662
|
+
}
|
|
37663
|
+
} finally {
|
|
37664
|
+
try {
|
|
37665
|
+
this.deps.local.markAuditEventsDelivered(delivered, Date.now());
|
|
37666
|
+
} catch {
|
|
36655
37667
|
}
|
|
36656
|
-
const input2 = inputs[i];
|
|
36657
|
-
await this.deps.forward.run(
|
|
36658
|
-
() => this.deps.client.recordAuditEvent(reKeyForForward(toEvent(input2), this.remoteInventory))
|
|
36659
|
-
);
|
|
36660
37668
|
}
|
|
36661
37669
|
}
|
|
36662
37670
|
// Delegated as a BATCH rather than looped over recordLlmCall: the inner
|
|
@@ -36699,9 +37707,10 @@ var AttachedDataGateway = class {
|
|
|
36699
37707
|
// local store.
|
|
36700
37708
|
async recordConfigScan(record2) {
|
|
36701
37709
|
await this.deps.local.recordConfigScan(record2);
|
|
36702
|
-
await this.deps.forward.run(
|
|
37710
|
+
const forwarded = await this.deps.forward.run(
|
|
36703
37711
|
() => this.deps.client.recordAuditEvent(reKeyForForward(record2.scanEvent, this.remoteInventory))
|
|
36704
37712
|
);
|
|
37713
|
+
if (forwarded.ok) this.deps.local.markAuditEventsDelivered([record2.scanEvent], Date.now());
|
|
36705
37714
|
}
|
|
36706
37715
|
async recordBlockedDetection(entry) {
|
|
36707
37716
|
return this.deps.local.recordBlockedDetection(entry);
|
|
@@ -36835,6 +37844,18 @@ var AttachedDataGateway = class {
|
|
|
36835
37844
|
// exactly what it did, leaving the whole control inert on every device
|
|
36836
37845
|
// while every test around it stayed green.
|
|
36837
37846
|
prohibitedModels: cached2.prohibitedModels
|
|
37847
|
+
// ALSO HONOURED FROM THE CACHE, and not a bundle field at all: each
|
|
37848
|
+
// merged policy's own `provenance`. `mergeRaiseOnly` spreads the policies
|
|
37849
|
+
// it emits, so an 'authored' policy arriving from the control plane
|
|
37850
|
+
// keeps that marker even where the clamp rebuilds it with a stronger
|
|
37851
|
+
// action. The device reads it in exactly one direction — the rules such a
|
|
37852
|
+
// policy targets are not locally re-assignable — so it sits on the
|
|
37853
|
+
// `prohibitedModels` side of the line for the same reason that field
|
|
37854
|
+
// does: it can only ever ADD a refusal, never relax one, and an unsigned
|
|
37855
|
+
// cache therefore has no relaxation to grant by carrying it. Dropping it
|
|
37856
|
+
// would be the silent failure rather than the safe one — the action would
|
|
37857
|
+
// still be enforced while the local override the organization authored
|
|
37858
|
+
// away quietly came back.
|
|
36838
37859
|
// `rulesComplete` is a STANDALONE-ONLY signal (the user's local installed
|
|
36839
37860
|
// snapshot) and is taken from the LOCAL bundle only — never from the wire
|
|
36840
37861
|
// or the on-disk cache. Honoring a cached one would hand the control plane, or
|
|
@@ -36874,10 +37895,10 @@ var AttachedDataGateway = class {
|
|
|
36874
37895
|
//
|
|
36875
37896
|
// Implementing these is what actually closes the skipped-local-maintenance
|
|
36876
37897
|
// gap: the OSS structural guard `hasLocalStoreMaintenance()` is satisfied by
|
|
36877
|
-
// any object carrying all
|
|
37898
|
+
// any object carrying them all, so the composite qualifies and SessionStart
|
|
36878
37899
|
// runs maintenance on the device's real store.
|
|
36879
37900
|
//
|
|
36880
|
-
// ⚠
|
|
37901
|
+
// ⚠ Several of them are SYNCHRONOUS and must stay that way. `handle-session-start`
|
|
36881
37902
|
// calls `capWarnEraEnforcement` without `await` and uses `staleBinaryNotice`'s
|
|
36882
37903
|
// return value directly; declaring them `async` here would hand those call
|
|
36883
37904
|
// sites a Promise and silently break both.
|
|
@@ -36900,9 +37921,15 @@ var AttachedDataGateway = class {
|
|
|
36900
37921
|
// Delegated like the rest, and SYNCHRONOUS for the reason the note above
|
|
36901
37922
|
// gives: `recordCapture` calls it after the forward has already settled, on a
|
|
36902
37923
|
// path that has nothing left to await.
|
|
37924
|
+
markCaptureOwed(event) {
|
|
37925
|
+
this.deps.local.markCaptureOwed(event);
|
|
37926
|
+
}
|
|
36903
37927
|
markCaptureDelivered(event, atMs) {
|
|
36904
37928
|
this.deps.local.markCaptureDelivered(event, atMs);
|
|
36905
37929
|
}
|
|
37930
|
+
markAuditEventsDelivered(events, atMs) {
|
|
37931
|
+
this.deps.local.markAuditEventsDelivered(events, atMs);
|
|
37932
|
+
}
|
|
36906
37933
|
};
|
|
36907
37934
|
function reKeyForForward(event, remote) {
|
|
36908
37935
|
if (remote === null) {
|
|
@@ -36945,281 +37972,17 @@ function toolAuditEvent(input2) {
|
|
|
36945
37972
|
}
|
|
36946
37973
|
|
|
36947
37974
|
// ../../packages/plugin-runtime/src/attached/history-state.ts
|
|
36948
|
-
import { readFileSync as
|
|
36949
|
-
import { join as
|
|
37975
|
+
import { readFileSync as readFileSync15 } from "fs";
|
|
37976
|
+
import { join as join23 } from "path";
|
|
36950
37977
|
|
|
36951
37978
|
// ../../packages/plugin-runtime/src/attached/history-sync.ts
|
|
36952
37979
|
import { createHash as createHash6 } from "crypto";
|
|
36953
37980
|
import { hostname as hostname5 } from "os";
|
|
36954
37981
|
|
|
36955
|
-
// ../../packages/
|
|
36956
|
-
|
|
36957
|
-
|
|
36958
|
-
var
|
|
36959
|
-
var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
36960
|
-
var RemoteRequestError = class extends Error {
|
|
36961
|
-
constructor(status) {
|
|
36962
|
-
super(`control-plane request failed with status ${String(status)}`);
|
|
36963
|
-
this.status = status;
|
|
36964
|
-
this.name = "RemoteRequestError";
|
|
36965
|
-
}
|
|
36966
|
-
status;
|
|
36967
|
-
};
|
|
36968
|
-
var RemoteRequestInvalid = class extends Error {
|
|
36969
|
-
constructor(route, cause) {
|
|
36970
|
-
super(`refusing to send a malformed body to ${route}`);
|
|
36971
|
-
this.cause = cause;
|
|
36972
|
-
this.name = "RemoteRequestInvalid";
|
|
36973
|
-
}
|
|
36974
|
-
cause;
|
|
36975
|
-
};
|
|
36976
|
-
var RemoteResponseInvalid = class extends Error {
|
|
36977
|
-
constructor(route, detail) {
|
|
36978
|
-
super(`control plane answered ${route} with ${detail}`);
|
|
36979
|
-
this.name = "RemoteResponseInvalid";
|
|
36980
|
-
}
|
|
36981
|
-
};
|
|
36982
|
-
var RemoteTransportError = class extends Error {
|
|
36983
|
-
/**
|
|
36984
|
-
* The status the peer sent, when headers arrived and only the BODY was
|
|
36985
|
-
* refused.
|
|
36986
|
-
*
|
|
36987
|
-
* Undefined for the ordinary case this class was written for — no answer at
|
|
36988
|
-
* all. It exists because two paths reject after a status has already been
|
|
36989
|
-
* delivered: an oversized body and an aborted response. Discarding it there
|
|
36990
|
-
* reported a deployment answering 401 with a verbose body as a network
|
|
36991
|
-
* outage, which sends the reader to look at their network instead of their
|
|
36992
|
-
* credential.
|
|
36993
|
-
*/
|
|
36994
|
-
constructor(reason, status) {
|
|
36995
|
-
super(`control-plane request did not complete: ${reason}`);
|
|
36996
|
-
this.status = status;
|
|
36997
|
-
this.name = "RemoteTransportError";
|
|
36998
|
-
}
|
|
36999
|
-
status;
|
|
37000
|
-
};
|
|
37001
|
-
async function send(options) {
|
|
37002
|
-
const url2 = new URL(options.url);
|
|
37003
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
37004
|
-
const send_ = url2.protocol === "http:" ? httpRequest : httpsRequest;
|
|
37005
|
-
const requestOptions = {
|
|
37006
|
-
method: options.method,
|
|
37007
|
-
headers: {
|
|
37008
|
-
// CALLER HEADERS FIRST, so this module's own are not overridable. Spread
|
|
37009
|
-
// last they win, and two of the values below are ones no caller may
|
|
37010
|
-
// replace: `x-api-key` is the credential, and `content-length` is the
|
|
37011
|
-
// byte count that stops a multi-byte body being truncated by the
|
|
37012
|
-
// receiver. `SendOptions.headers` is a free-form record on an exported
|
|
37013
|
-
// function, so "no caller does that today" is not the guarantee to rely
|
|
37014
|
-
// on. The one header any caller actually passes — `if-none-match` on the
|
|
37015
|
-
// conditional GET — is untouched by this order.
|
|
37016
|
-
...options.headers,
|
|
37017
|
-
// The credential. One header, matching what the deployment authenticates
|
|
37018
|
-
// on; a second copy in an `Authorization` header would be one more place
|
|
37019
|
-
// it can be logged by an intermediary for no gain.
|
|
37020
|
-
//
|
|
37021
|
-
// Spread conditionally rather than assigned as `undefined`: Node's header
|
|
37022
|
-
// handling and `content-length` bookkeeping treat a present-but-undefined
|
|
37023
|
-
// key differently from an absent one, and "the header is not there" is
|
|
37024
|
-
// the property the attach flow needs.
|
|
37025
|
-
...options.apiKey === void 0 ? {} : { "x-api-key": options.apiKey },
|
|
37026
|
-
accept: "application/json",
|
|
37027
|
-
...options.body === void 0 ? {} : {
|
|
37028
|
-
"content-type": "application/json",
|
|
37029
|
-
// Byte length, not string length: a multi-byte body sent with a
|
|
37030
|
-
// character count is truncated by the receiver.
|
|
37031
|
-
"content-length": String(Buffer.byteLength(options.body))
|
|
37032
|
-
}
|
|
37033
|
-
}
|
|
37034
|
-
};
|
|
37035
|
-
return new Promise((resolve2, reject) => {
|
|
37036
|
-
let settled = false;
|
|
37037
|
-
const fail = (reason, status) => {
|
|
37038
|
-
if (settled) return;
|
|
37039
|
-
settled = true;
|
|
37040
|
-
reject(new RemoteTransportError(reason, status));
|
|
37041
|
-
};
|
|
37042
|
-
const req = send_(url2, requestOptions, (res) => {
|
|
37043
|
-
const chunks = [];
|
|
37044
|
-
let size = 0;
|
|
37045
|
-
res.on("data", (chunk) => {
|
|
37046
|
-
size += chunk.length;
|
|
37047
|
-
if (size > MAX_RESPONSE_BYTES) {
|
|
37048
|
-
fail(`response exceeded ${String(MAX_RESPONSE_BYTES)} bytes`, res.statusCode);
|
|
37049
|
-
res.destroy();
|
|
37050
|
-
req.destroy();
|
|
37051
|
-
return;
|
|
37052
|
-
}
|
|
37053
|
-
chunks.push(chunk);
|
|
37054
|
-
});
|
|
37055
|
-
res.on("aborted", () => {
|
|
37056
|
-
fail("the response was aborted", res.statusCode);
|
|
37057
|
-
});
|
|
37058
|
-
res.on("end", () => {
|
|
37059
|
-
if (settled) return;
|
|
37060
|
-
settled = true;
|
|
37061
|
-
resolve2({
|
|
37062
|
-
status: res.statusCode ?? 0,
|
|
37063
|
-
headers: res.headers,
|
|
37064
|
-
body: Buffer.concat(chunks).toString("utf8")
|
|
37065
|
-
});
|
|
37066
|
-
});
|
|
37067
|
-
});
|
|
37068
|
-
const deadline = setTimeout(() => {
|
|
37069
|
-
fail(`no response within ${String(timeoutMs)}ms`);
|
|
37070
|
-
req.destroy();
|
|
37071
|
-
}, timeoutMs);
|
|
37072
|
-
deadline.unref();
|
|
37073
|
-
req.on("upgrade", (_res, socket) => {
|
|
37074
|
-
fail("the deployment answered with a protocol upgrade");
|
|
37075
|
-
socket.destroy();
|
|
37076
|
-
});
|
|
37077
|
-
req.on("close", () => {
|
|
37078
|
-
fail("the connection closed before a response was read");
|
|
37079
|
-
clearTimeout(deadline);
|
|
37080
|
-
});
|
|
37081
|
-
req.on("error", (err) => {
|
|
37082
|
-
fail(err.message);
|
|
37083
|
-
});
|
|
37084
|
-
if (options.body !== void 0) req.write(options.body);
|
|
37085
|
-
req.end();
|
|
37086
|
-
});
|
|
37087
|
-
}
|
|
37088
|
-
|
|
37089
|
-
// ../../packages/remote/src/client.ts
|
|
37090
|
-
var ROUTES = {
|
|
37091
|
-
events: "/v1/events",
|
|
37092
|
-
auditEvents: "/v1/audit-events",
|
|
37093
|
-
auditEventsBatch: "/v1/audit-events/batch",
|
|
37094
|
-
inventory: "/v1/inventory",
|
|
37095
|
-
storePosture: "/v1/store-posture",
|
|
37096
|
-
policyBundle: "/v1/policy-bundle",
|
|
37097
|
-
whoami: "/v1/plugin/whoami",
|
|
37098
|
-
shares: "/v1/shares"
|
|
37099
|
-
};
|
|
37100
|
-
function headerValue(response, name) {
|
|
37101
|
-
const raw = response.headers[name];
|
|
37102
|
-
if (raw === void 0) return void 0;
|
|
37103
|
-
return Array.isArray(raw) ? raw[0] : raw;
|
|
37104
|
-
}
|
|
37105
|
-
function okBody(response) {
|
|
37106
|
-
if (response.status < 200 || response.status >= 300) {
|
|
37107
|
-
throw new RemoteRequestError(response.status);
|
|
37108
|
-
}
|
|
37109
|
-
return response.body;
|
|
37110
|
-
}
|
|
37111
|
-
function parsed(schema, body, route) {
|
|
37112
|
-
let json2;
|
|
37113
|
-
try {
|
|
37114
|
-
json2 = JSON.parse(body);
|
|
37115
|
-
} catch {
|
|
37116
|
-
throw new RemoteResponseInvalid(route, "a body that is not JSON");
|
|
37117
|
-
}
|
|
37118
|
-
const result = schema.safeParse(json2);
|
|
37119
|
-
if (!result.success) {
|
|
37120
|
-
throw new RemoteResponseInvalid(route, "a body this client cannot read");
|
|
37121
|
-
}
|
|
37122
|
-
return result.data;
|
|
37123
|
-
}
|
|
37124
|
-
function withoutTrailingSlashes(endpoint) {
|
|
37125
|
-
let end = endpoint.length;
|
|
37126
|
-
while (end > 0 && endpoint.charCodeAt(end - 1) === SLASH) end -= 1;
|
|
37127
|
-
return endpoint.slice(0, end);
|
|
37128
|
-
}
|
|
37129
|
-
var SLASH = "/".charCodeAt(0);
|
|
37130
|
-
function createRemoteClient(options) {
|
|
37131
|
-
const base = withoutTrailingSlashes(options.endpoint);
|
|
37132
|
-
const url2 = (route) => `${base}${route}`;
|
|
37133
|
-
const common = { apiKey: options.apiKey, timeoutMs: options.timeoutMs };
|
|
37134
|
-
const sendOne = async (event) => {
|
|
37135
|
-
const validated = RecordAuditEventRequest.safeParse(event);
|
|
37136
|
-
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.auditEvents, validated.error);
|
|
37137
|
-
const response = await send({
|
|
37138
|
-
...common,
|
|
37139
|
-
method: "POST",
|
|
37140
|
-
url: url2(ROUTES.auditEvents),
|
|
37141
|
-
body: JSON.stringify(validated.data)
|
|
37142
|
-
});
|
|
37143
|
-
okBody(response);
|
|
37144
|
-
};
|
|
37145
|
-
return {
|
|
37146
|
-
async ingestEvents(batch) {
|
|
37147
|
-
const response = await send({
|
|
37148
|
-
...common,
|
|
37149
|
-
method: "POST",
|
|
37150
|
-
url: url2(ROUTES.events),
|
|
37151
|
-
body: JSON.stringify(batch)
|
|
37152
|
-
});
|
|
37153
|
-
return parsed(IngestAck, okBody(response), ROUTES.events);
|
|
37154
|
-
},
|
|
37155
|
-
async ingestInventory(context) {
|
|
37156
|
-
const response = await send({
|
|
37157
|
-
...common,
|
|
37158
|
-
method: "POST",
|
|
37159
|
-
url: url2(ROUTES.inventory),
|
|
37160
|
-
body: JSON.stringify(context)
|
|
37161
|
-
});
|
|
37162
|
-
return parsed(ResolvedInventory, okBody(response), ROUTES.inventory);
|
|
37163
|
-
},
|
|
37164
|
-
async recordAuditEvent(event) {
|
|
37165
|
-
await sendOne(event);
|
|
37166
|
-
},
|
|
37167
|
-
async recordAuditEvents(events) {
|
|
37168
|
-
const validated = RecordAuditEventBatch.safeParse({ events });
|
|
37169
|
-
if (!validated.success) {
|
|
37170
|
-
throw new RemoteRequestInvalid(ROUTES.auditEventsBatch, validated.error);
|
|
37171
|
-
}
|
|
37172
|
-
const response = await send({
|
|
37173
|
-
...common,
|
|
37174
|
-
method: "POST",
|
|
37175
|
-
url: url2(ROUTES.auditEventsBatch),
|
|
37176
|
-
body: JSON.stringify(validated.data)
|
|
37177
|
-
});
|
|
37178
|
-
if (response.status === 404) {
|
|
37179
|
-
for (const event of validated.data.events) await sendOne(event);
|
|
37180
|
-
return { accepted: validated.data.events.length };
|
|
37181
|
-
}
|
|
37182
|
-
return parsed(AuditEventBatchAck, okBody(response), ROUTES.auditEventsBatch);
|
|
37183
|
-
},
|
|
37184
|
-
async reportStorePosture(snapshot) {
|
|
37185
|
-
const response = await send({
|
|
37186
|
-
...common,
|
|
37187
|
-
method: "POST",
|
|
37188
|
-
url: url2(ROUTES.storePosture),
|
|
37189
|
-
body: JSON.stringify(snapshot)
|
|
37190
|
-
});
|
|
37191
|
-
okBody(response);
|
|
37192
|
-
},
|
|
37193
|
-
async getPolicyBundle(etag) {
|
|
37194
|
-
const response = await send({
|
|
37195
|
-
...common,
|
|
37196
|
-
method: "GET",
|
|
37197
|
-
url: url2(ROUTES.policyBundle),
|
|
37198
|
-
...etag === void 0 ? {} : { headers: { "if-none-match": etag } }
|
|
37199
|
-
});
|
|
37200
|
-
if (response.status === 304) {
|
|
37201
|
-
return { changed: false, etag: headerValue(response, "etag") ?? etag };
|
|
37202
|
-
}
|
|
37203
|
-
const bundle = parsed(PolicyBundle, okBody(response), ROUTES.policyBundle);
|
|
37204
|
-
return { changed: true, bundle, etag: headerValue(response, "etag") };
|
|
37205
|
-
},
|
|
37206
|
-
async whoami() {
|
|
37207
|
-
const response = await send({ ...common, method: "GET", url: url2(ROUTES.whoami) });
|
|
37208
|
-
return parsed(PluginWhoami, okBody(response), ROUTES.whoami);
|
|
37209
|
-
},
|
|
37210
|
-
async recordProjectEgress(request) {
|
|
37211
|
-
const validated = EgressIngestRequest.safeParse(request);
|
|
37212
|
-
if (!validated.success) throw new RemoteRequestInvalid(ROUTES.shares, validated.error);
|
|
37213
|
-
const response = await send({
|
|
37214
|
-
...common,
|
|
37215
|
-
method: "POST",
|
|
37216
|
-
url: url2(ROUTES.shares),
|
|
37217
|
-
body: JSON.stringify(validated.data)
|
|
37218
|
-
});
|
|
37219
|
-
okBody(response);
|
|
37220
|
-
}
|
|
37221
|
-
};
|
|
37222
|
-
}
|
|
37982
|
+
// ../../packages/plugin-runtime/src/attached/capture-rebuild.ts
|
|
37983
|
+
var CORRELATION_ID = EventMetadata.shape.correlationId;
|
|
37984
|
+
var TRACE_ID = EventMetadata.shape.traceId;
|
|
37985
|
+
var EXCEPTION_ID = EventMetadata.shape.exceptionIds.unwrap().element;
|
|
37223
37986
|
|
|
37224
37987
|
// ../../packages/plugin-runtime/src/attached/history-sync-trigger.ts
|
|
37225
37988
|
import { spawn } from "child_process";
|
|
@@ -37227,7 +37990,7 @@ import { fileURLToPath as fileURLToPath2 } from "url";
|
|
|
37227
37990
|
var HISTORY_SYNC_THROTTLE_MS = 5 * 60 * 1e3;
|
|
37228
37991
|
|
|
37229
37992
|
// ../../packages/plugin-runtime/src/attached/plugin-block.ts
|
|
37230
|
-
import { readFileSync as
|
|
37993
|
+
import { readFileSync as readFileSync16 } from "fs";
|
|
37231
37994
|
function createPluginBlock(build, policyStore) {
|
|
37232
37995
|
return async () => {
|
|
37233
37996
|
const cached2 = await policyStore.read();
|
|
@@ -37246,7 +38009,7 @@ function createPluginBlock(build, policyStore) {
|
|
|
37246
38009
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
37247
38010
|
import { randomUUID as randomUUID16 } from "crypto";
|
|
37248
38011
|
import { readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
|
|
37249
|
-
import { join as
|
|
38012
|
+
import { join as join24 } from "path";
|
|
37250
38013
|
|
|
37251
38014
|
// ../../packages/plugin-runtime/src/attached/atomic-publish.ts
|
|
37252
38015
|
import { rename as rename2 } from "fs/promises";
|
|
@@ -37270,7 +38033,7 @@ async function publishByRename(tmp, file2, move = rename2) {
|
|
|
37270
38033
|
|
|
37271
38034
|
// ../../packages/plugin-runtime/src/attached/policy-store.ts
|
|
37272
38035
|
function createPolicyStore(dir = dataDir()) {
|
|
37273
|
-
const file2 =
|
|
38036
|
+
const file2 = join24(dir, "policy-cache.json");
|
|
37274
38037
|
async function read() {
|
|
37275
38038
|
try {
|
|
37276
38039
|
const raw = await readFile2(file2, "utf8");
|
|
@@ -37279,22 +38042,32 @@ function createPolicyStore(dir = dataDir()) {
|
|
|
37279
38042
|
const record2 = parsed2;
|
|
37280
38043
|
const bundle = PolicyBundle.parse(record2.bundle);
|
|
37281
38044
|
const fetchedAtMs = typeof record2.fetchedAtMs === "number" ? record2.fetchedAtMs : 0;
|
|
37282
|
-
const
|
|
38045
|
+
const stored = typeof record2.etag === "string" ? record2.etag : void 0;
|
|
38046
|
+
const replayable = record2.shapeId === POLICY_BUNDLE_SHAPE_ID || knowsMoreThanThisBuild(record2.shapeId);
|
|
38047
|
+
const etag = replayable ? stored : void 0;
|
|
37283
38048
|
return { bundle, fetchedAtMs, ...etag === void 0 ? {} : { etag } };
|
|
37284
38049
|
} catch {
|
|
37285
38050
|
return null;
|
|
37286
38051
|
}
|
|
37287
38052
|
}
|
|
37288
|
-
|
|
37289
|
-
|
|
37290
|
-
const
|
|
37291
|
-
|
|
37292
|
-
|
|
37293
|
-
|
|
37294
|
-
|
|
38053
|
+
function knowsMoreThanThisBuild(shapeId) {
|
|
38054
|
+
if (typeof shapeId !== "string" || shapeId === "") return false;
|
|
38055
|
+
const theirs = new Set(shapeId.split(","));
|
|
38056
|
+
const ours = new Set(POLICY_BUNDLE_SHAPE_ID.split(","));
|
|
38057
|
+
return theirs.size > ours.size && [...ours].every((key) => theirs.has(key));
|
|
38058
|
+
}
|
|
38059
|
+
async function priorRecord() {
|
|
38060
|
+
try {
|
|
38061
|
+
const parsed2 = JSON.parse(await readFile2(file2, "utf8"));
|
|
38062
|
+
return typeof parsed2 === "object" && parsed2 !== null ? parsed2 : null;
|
|
38063
|
+
} catch {
|
|
38064
|
+
return null;
|
|
38065
|
+
}
|
|
38066
|
+
}
|
|
38067
|
+
async function publishRecord(record2) {
|
|
37295
38068
|
const tmp = `${file2}.${randomUUID16()}.tmp`;
|
|
37296
38069
|
try {
|
|
37297
|
-
await writeFile2(tmp, JSON.stringify(
|
|
38070
|
+
await writeFile2(tmp, JSON.stringify(record2), {
|
|
37298
38071
|
encoding: "utf8",
|
|
37299
38072
|
mode: DATA_FILE_MODE,
|
|
37300
38073
|
flag: "wx"
|
|
@@ -37305,6 +38078,27 @@ function createPolicyStore(dir = dataDir()) {
|
|
|
37305
38078
|
throw err;
|
|
37306
38079
|
}
|
|
37307
38080
|
}
|
|
38081
|
+
async function write(bundle, etag) {
|
|
38082
|
+
await ensureDataDir(dir);
|
|
38083
|
+
const prior = await priorRecord();
|
|
38084
|
+
const priorVersion = prior?.bundle?.version;
|
|
38085
|
+
if (prior !== null && knowsMoreThanThisBuild(prior.shapeId) && priorVersion === bundle.version) {
|
|
38086
|
+
await publishRecord({
|
|
38087
|
+
...prior,
|
|
38088
|
+
fetchedAtMs: Date.now()
|
|
38089
|
+
});
|
|
38090
|
+
return;
|
|
38091
|
+
}
|
|
38092
|
+
await publishRecord({
|
|
38093
|
+
bundle,
|
|
38094
|
+
fetchedAtMs: Date.now(),
|
|
38095
|
+
// Stamped on EVERY write, the 304 arm's included: that arm hands back the
|
|
38096
|
+
// bundle it already holds, and the point of the stamp is to describe the
|
|
38097
|
+
// build that last narrowed those bytes, which is this one.
|
|
38098
|
+
shapeId: POLICY_BUNDLE_SHAPE_ID,
|
|
38099
|
+
...etag === void 0 ? {} : { etag }
|
|
38100
|
+
});
|
|
38101
|
+
}
|
|
37308
38102
|
return { read, write, file: file2 };
|
|
37309
38103
|
}
|
|
37310
38104
|
|
|
@@ -37470,11 +38264,11 @@ function readStorePosture(dbPath2) {
|
|
|
37470
38264
|
// ../../packages/plugin-runtime/src/attached/posture-store.ts
|
|
37471
38265
|
import { randomUUID as randomUUID17 } from "crypto";
|
|
37472
38266
|
import { readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "fs/promises";
|
|
37473
|
-
import { join as
|
|
38267
|
+
import { join as join25 } from "path";
|
|
37474
38268
|
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
37475
38269
|
function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
37476
|
-
const file2 =
|
|
37477
|
-
const legacyFile = legacyDir === void 0 ? null :
|
|
38270
|
+
const file2 = join25(dir, "posture-state.json");
|
|
38271
|
+
const legacyFile = legacyDir === void 0 ? null : join25(legacyDir, "posture-state.json");
|
|
37478
38272
|
async function persist(state) {
|
|
37479
38273
|
await ensureDataDir(dir);
|
|
37480
38274
|
const tmp = `${file2}.${randomUUID17()}.tmp`;
|
|
@@ -37542,8 +38336,8 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
|
|
|
37542
38336
|
}
|
|
37543
38337
|
|
|
37544
38338
|
// ../../packages/plugin-runtime/src/attached/sync-state.ts
|
|
37545
|
-
import { readFileSync as
|
|
37546
|
-
import { join as
|
|
38339
|
+
import { readFileSync as readFileSync17 } from "fs";
|
|
38340
|
+
import { join as join26 } from "path";
|
|
37547
38341
|
|
|
37548
38342
|
// ../../packages/plugin-runtime/src/attached/status.ts
|
|
37549
38343
|
var REFUSAL_LINES = {
|
|
@@ -37861,9 +38655,21 @@ var StandaloneDataGateway = class {
|
|
|
37861
38655
|
// for the whole of it, so a member that threw would make that answer a lie
|
|
37862
38656
|
// the moment a composite delegated to it. A store-level no-op is the honest
|
|
37863
38657
|
// shape — a standalone machine has nothing delivered to record.
|
|
38658
|
+
markCaptureOwed(event) {
|
|
38659
|
+
this.db.markCaptureOwed(event);
|
|
38660
|
+
}
|
|
37864
38661
|
markCaptureDelivered(event, atMs) {
|
|
37865
38662
|
this.db.markCaptureDelivered(event, atMs);
|
|
37866
38663
|
}
|
|
38664
|
+
// Implemented, not stubbed, for the same reason its sibling above is: the
|
|
38665
|
+
// attached gateway is a DECORATOR over an instance of this class
|
|
38666
|
+
// (`attached/factory.ts` builds one and passes it as `deps.local`), so every
|
|
38667
|
+
// stamp the live forward makes lands here with a non-empty array. This is the
|
|
38668
|
+
// production write path for that feature, not a shape-satisfying no-op — a
|
|
38669
|
+
// machine that is merely standalone simply never calls it.
|
|
38670
|
+
markAuditEventsDelivered(events, atMs) {
|
|
38671
|
+
this.db.markAuditEventsDelivered(events, atMs);
|
|
38672
|
+
}
|
|
37867
38673
|
staleBinaryNotice(currentVersion) {
|
|
37868
38674
|
try {
|
|
37869
38675
|
const newest = this.db.installedPacks.newestRecordedBinary();
|
|
@@ -38163,16 +38969,16 @@ function baseMetadata(input2) {
|
|
|
38163
38969
|
}
|
|
38164
38970
|
|
|
38165
38971
|
// src/hooks/store-health.ts
|
|
38166
|
-
import { mkdirSync as mkdirSync5, readFileSync as
|
|
38167
|
-
import { dirname as
|
|
38972
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync18, writeFileSync as writeFileSync8 } from "fs";
|
|
38973
|
+
import { dirname as dirname6, join as join27 } from "path";
|
|
38168
38974
|
var STORE_REDIRECT_MARKER = "store-redirect-last-session";
|
|
38169
38975
|
function markerDirs(dataDir2) {
|
|
38170
|
-
return [dataDir2,
|
|
38976
|
+
return [dataDir2, dirname6(dataDir2)];
|
|
38171
38977
|
}
|
|
38172
38978
|
function alreadyClaimed(dirs, marker, sessionId) {
|
|
38173
38979
|
return dirs.some((dir) => {
|
|
38174
38980
|
try {
|
|
38175
|
-
return
|
|
38981
|
+
return readFileSync18(join27(dir, marker), "utf8") === sessionId;
|
|
38176
38982
|
} catch {
|
|
38177
38983
|
return false;
|
|
38178
38984
|
}
|
|
@@ -38182,7 +38988,7 @@ function recordClaim(dirs, marker, sessionId) {
|
|
|
38182
38988
|
for (const dir of dirs) {
|
|
38183
38989
|
try {
|
|
38184
38990
|
mkdirSync5(dir, { recursive: true, mode: DATA_DIR_MODE });
|
|
38185
|
-
writeFileSync8(
|
|
38991
|
+
writeFileSync8(join27(dir, marker), sessionId, { mode: DATA_FILE_MODE });
|
|
38186
38992
|
return;
|
|
38187
38993
|
} catch {
|
|
38188
38994
|
}
|
|
@@ -38207,7 +39013,7 @@ function formatMode(mode) {
|
|
|
38207
39013
|
}
|
|
38208
39014
|
function warnIfStoreRedirected(config2, sessionId, write = (message) => void process.stderr.write(message)) {
|
|
38209
39015
|
try {
|
|
38210
|
-
const paths = symlinkedStorePaths(
|
|
39016
|
+
const paths = symlinkedStorePaths(dirname6(config2.dataDir));
|
|
38211
39017
|
if (paths.length === 0) return;
|
|
38212
39018
|
if (!sessionId) {
|
|
38213
39019
|
write(storeRedirectedMessage(paths));
|