@akasecurity/ai-tc-claude-code 0.9.3 → 0.9.4
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/.claude-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/commands/setup.md +123 -35
- package/hooks/hooks.json +11 -0
- package/package.json +4 -4
- package/scripts/apply-suppressions.js +581 -69
- package/scripts/backfill.js +1954 -147
- package/scripts/filescan.js +602 -76
- package/scripts/firstrun.js +517 -34
- package/scripts/intro.js +176 -20
- package/scripts/message-display.js +28945 -0
- package/scripts/onboard.js +542 -30
- package/scripts/post-tool-use.js +1943 -139
- package/scripts/pre-tool-use.js +2114 -163
- package/scripts/query.js +522 -35
- package/scripts/reconcile.js +2082 -242
- package/scripts/remediate.js +1872 -104
- package/scripts/session-start.js +680 -112
- package/scripts/start-light.js +174 -18
- package/scripts/statusline.js +517 -34
- package/scripts/stop.js +185 -29
- package/scripts/user-prompt-submit.js +1910 -152
package/scripts/post-tool-use.js
CHANGED
|
@@ -493,10 +493,10 @@ var require_ignore = __commonJS({
|
|
|
493
493
|
|
|
494
494
|
// ../../packages/plugin-sdk/src/config.ts
|
|
495
495
|
import { existsSync as existsSync4 } from "fs";
|
|
496
|
-
import { join as
|
|
496
|
+
import { join as join7 } from "path";
|
|
497
497
|
|
|
498
498
|
// ../../packages/persistence/src/database.ts
|
|
499
|
-
import { randomUUID as
|
|
499
|
+
import { randomUUID as randomUUID9 } from "crypto";
|
|
500
500
|
import { existsSync, renameSync as renameSync2, rmSync as rmSync2 } from "fs";
|
|
501
501
|
import { join, sep } from "path";
|
|
502
502
|
import { DatabaseSync } from "node:sqlite";
|
|
@@ -562,6 +562,22 @@ var SQLITE_MIGRATIONS = [
|
|
|
562
562
|
{
|
|
563
563
|
tag: "0014_drop_legacy_events_findings",
|
|
564
564
|
sql: "-- Custom migration: drops the frozen legacy `events`/`findings` tables\n-- (superseded by audit_events/inspection_definitions/inspection_findings) and\n-- replaces them with read-only views of the same name.\n--\n-- persistence's migrations.ts applies this migration ONLY once the batched\n-- history backfill (see runLegacyHistoryBackfill) has fully drained both\n-- tables, and only after copying the live file aside \u2014 see\n-- backupBeforeLegacyDrop in packages/persistence/src/migrations.ts. A store\n-- still mid-copy keeps its real tables and this migration stays pending.\n--\n-- The views exist for skew: the `aka` CLI and the Claude Code plugin update\n-- independently against one shared store, so an older, already-installed\n-- binary can open a store a newer binary already dropped these tables on.\n-- Every already-shipped repository constructor prepares its SQL eagerly at\n-- open time, so a bare \"table not found\" would fail the WHOLE open, not just\n-- a findings-specific read \u2014 these views keep `prepare()` succeeding so an\n-- old binary's unrelated features keep working; its own reads stay truthful,\n-- and its rare (already fail-open) writes fail at run time instead.\n--\n-- The 0009/0010 expression indexes existed only over the legacy `events`\n-- table; DROP TABLE below would remove them implicitly, but they are\n-- dropped explicitly first so the intent reads clearly. IF EXISTS so a store\n-- that reached here with an index missing out of band (an adopted-tag store\n-- whose physical index was never built) does not throw a deterministic \"no\n-- such index\" out of the fail-open drop path.\nDROP INDEX IF EXISTS `idx_events_code_change_path`;\n--> statement-breakpoint\nDROP INDEX IF EXISTS `idx_events_session_id`;\n--> statement-breakpoint\n-- `findings.event_id` references `events.id` \u2014 drop the child first.\nDROP TABLE `findings`;\n--> statement-breakpoint\nDROP TABLE `events`;\n--> statement-breakpoint\n-- Legacy `events` shape, projected from audit_events: `kind`/`occurred_at`/\n-- `source_tool` become real columns again (source_tool round-trips through\n-- the attributes bag, the only place a capture-typed audit row keeps it);\n-- `metadata` is reconstructed as the old camelCase JSON object from the new\n-- snake_case attributes bag, with `root_session_id` folded back in as\n-- `sessionId` (the one legacy metadata key that became a column, never an\n-- attribute, on the new table). Constrained to the four capture kinds so\n-- structural rows (session/run/tool_call/llm_call/source_lookup/config_scan)\n-- never leak into a legacy reader's result set \u2014 the old `events` table\n-- never held them either.\nCREATE VIEW `events` AS\nSELECT\n id,\n json_extract(attributes, '$.source_tool') AS source_tool,\n event_type AS kind,\n started_at AS occurred_at,\n content_hash,\n content,\n -- Plugin-local bookkeeping column that `ensureSyncedAtColumn` adds to the\n -- real `events` table at open time. A pre-cutover binary runs that probe on\n -- EVERY open; without this projection its `columnNames('events')` check\n -- misses `synced_at` and issues `ALTER TABLE events ADD COLUMN` against this\n -- view, which SQLite rejects (\"Cannot add a column to a view\") \u2014 a hard,\n -- non-fail-open crash of the whole open, the exact skew failure these views\n -- exist to prevent. Projecting it (always NULL; no reader consumes it)\n -- short-circuits that ALTER.\n NULL AS synced_at,\n json_object(\n 'sessionId', root_session_id,\n 'repo', json_extract(attributes, '$.repo'),\n 'filePath', json_extract(attributes, '$.file_path'),\n 'toolName', json_extract(attributes, '$.tool_name'),\n 'gitignored', json_extract(attributes, '$.gitignored'),\n 'wholeFile', json_extract(attributes, '$.whole_file'),\n 'model', json_extract(attributes, '$.model'),\n 'turnIndex', json_extract(attributes, '$.turn_index'),\n 'correlationId', json_extract(attributes, '$.correlation_id'),\n 'traceId', json_extract(attributes, '$.trace_id'),\n 'exceptionIds', json_extract(attributes, '$.exception_ids')\n ) AS metadata\nFROM audit_events\nWHERE event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- A plain single-row INSERT (the old writer's shape \u2014 no ON CONFLICT) is\n-- accepted by prepare() against a view once an INSTEAD OF INSERT trigger\n-- exists, so it fails at run time instead of at open \u2014 landing in the same\n-- fail-open path the caller already wraps its write in.\nCREATE TRIGGER `trg_events_ro`\nINSTEAD OF INSERT ON `events`\nBEGIN SELECT RAISE(ABORT, 'events is read-only; write to audit_events instead'); END;\n--> statement-breakpoint\n-- Legacy `findings` shape: rule_id/category/severity come from the joined\n-- inspection_definitions row (the legacy table inlined them per-row; the\n-- generalized schema normalizes them out into the shared definition). A view\n-- has no rowid of its own, so the underlying table's rowid is re-exposed\n-- explicitly under that name \u2014 a legacy reader ordering by `f.rowid` would\n-- otherwise fail to resolve the column at all. Joined to audit_events for the\n-- same four-capture-kind constraint as the events view above (a finding\n-- attached to a tool_call/config_scan row never existed in the legacy table\n-- either \u2014 see the persistence findings repository's identical predicate).\nCREATE VIEW `findings` AS\nSELECT\n f.id AS id,\n f.rowid AS rowid,\n f.audit_event_id AS event_id,\n d.rule_id AS rule_id,\n d.category AS category,\n d.severity AS severity,\n f.span_start AS span_start,\n f.span_end AS span_end,\n f.masked_match AS masked_match,\n f.action_taken AS action_taken,\n f.confidence AS confidence,\n f.finding_key AS finding_key,\n f.first_detected_at AS first_detected_at\nFROM inspection_findings f\nJOIN audit_events e ON e.id = f.audit_event_id\nJOIN inspection_definitions d ON d.id = f.inspection_definition_id\nWHERE e.event_type IN ('prompt', 'response', 'code_change', 'tool_use');\n--> statement-breakpoint\n-- Defense in depth only: SQLite refuses to plan ANY upsert against a view\n-- (\"cannot UPSERT a view\") no matter what trigger exists, so this can never\n-- rescue the real legacy writer, which always used\n-- `ON CONFLICT (finding_key) DO UPDATE` \u2014 that statement still fails at\n-- prepare() on an old binary, same as it would with no trigger at all. This\n-- only covers a plain-INSERT shape, should one ever exist.\nCREATE TRIGGER `trg_findings_ro`\nINSTEAD OF INSERT ON `findings`\nBEGIN SELECT RAISE(ABORT, 'findings is read-only; write to inspection_findings instead'); END;\n"
|
|
565
|
+
},
|
|
566
|
+
{
|
|
567
|
+
tag: "0015_busy_vengeance",
|
|
568
|
+
sql: "CREATE TABLE `secret_vault` (\n `pointer_id` text PRIMARY KEY NOT NULL,\n `value_fingerprint` text NOT NULL,\n `fingerprint_key_version` integer NOT NULL,\n `key_version` integer NOT NULL,\n `category` text NOT NULL,\n `rule_id` text NOT NULL,\n `masked_match` text NOT NULL,\n `provider` text,\n `ciphertext` text NOT NULL,\n `nonce` text NOT NULL,\n `auth_tag` text NOT NULL,\n `occurrence_count` integer DEFAULT 1 NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_value` ON `secret_vault` (`value_fingerprint`);--> statement-breakpoint\nCREATE TABLE `secret_vault_deref` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `at` integer NOT NULL,\n `target` text NOT NULL,\n `reason` text NOT NULL,\n `outcome` text NOT NULL,\n `grant_id` text,\n `pointer_count` integer DEFAULT 1 NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_pointer` ON `secret_vault_deref` (`pointer_id`);--> statement-breakpoint\nCREATE INDEX `idx_secret_vault_deref_reason_at` ON `secret_vault_deref` (`reason`,`at`);"
|
|
569
|
+
},
|
|
570
|
+
{
|
|
571
|
+
tag: "0016_breezy_zodiak",
|
|
572
|
+
sql: "ALTER TABLE `exceptions` ADD `capability` text DEFAULT 'suppress' NOT NULL;"
|
|
573
|
+
},
|
|
574
|
+
{
|
|
575
|
+
tag: "0017_rainy_kat_farrell",
|
|
576
|
+
sql: "CREATE TABLE `secret_vault_sighting` (\n `id` text PRIMARY KEY NOT NULL,\n `pointer_id` text NOT NULL,\n `location` text NOT NULL,\n `kind` text NOT NULL,\n `first_seen` integer NOT NULL,\n `last_seen` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE UNIQUE INDEX `uq_secret_vault_sighting` ON `secret_vault_sighting` (`pointer_id`,`location`);"
|
|
577
|
+
},
|
|
578
|
+
{
|
|
579
|
+
tag: "0018_serious_tana_nile",
|
|
580
|
+
sql: "ALTER TABLE `secret_vault` ADD `format_version` integer DEFAULT 2 NOT NULL;"
|
|
565
581
|
}
|
|
566
582
|
];
|
|
567
583
|
|
|
@@ -16218,6 +16234,7 @@ var ExceptionConditions = external_exports.object({
|
|
|
16218
16234
|
sourceTool: external_exports.string().optional(),
|
|
16219
16235
|
provider: external_exports.string().optional()
|
|
16220
16236
|
}).strict();
|
|
16237
|
+
var ExceptionCapability = external_exports.enum(["suppress", "reveal_to_model"]);
|
|
16221
16238
|
var DetectionException = external_exports.object({
|
|
16222
16239
|
id: external_exports.guid(),
|
|
16223
16240
|
ruleId: external_exports.string(),
|
|
@@ -16234,6 +16251,7 @@ var DetectionException = external_exports.object({
|
|
|
16234
16251
|
keyVersion: external_exports.number().int().positive(),
|
|
16235
16252
|
// maskMatch() preview of the approved value — never the raw value.
|
|
16236
16253
|
maskedValue: external_exports.string(),
|
|
16254
|
+
capability: ExceptionCapability.default("suppress"),
|
|
16237
16255
|
scope: ExceptionScope,
|
|
16238
16256
|
expiresAt: external_exports.iso.datetime().nullable(),
|
|
16239
16257
|
maxUses: external_exports.number().int().positive().nullable(),
|
|
@@ -16257,6 +16275,7 @@ var ExceptionBundleEntry = DetectionException.pick({
|
|
|
16257
16275
|
ruleId: true,
|
|
16258
16276
|
valueFingerprint: true,
|
|
16259
16277
|
keyVersion: true,
|
|
16278
|
+
capability: true,
|
|
16260
16279
|
expiresAt: true,
|
|
16261
16280
|
maxUses: true,
|
|
16262
16281
|
useCount: true,
|
|
@@ -17361,8 +17380,129 @@ var PatchInstalledPackRequest = external_exports.object({
|
|
|
17361
17380
|
message: "At least one field must be provided"
|
|
17362
17381
|
}).meta({ id: "PatchInstalledPackRequest" });
|
|
17363
17382
|
|
|
17383
|
+
// ../../packages/schema/src/zod/vault.ts
|
|
17384
|
+
var POINTER_FORMAT_VERSION = 2;
|
|
17385
|
+
var CATEGORY_ALTERNATION = DetectionCategory.options.join("|");
|
|
17386
|
+
var POINTER_TOKEN_PATTERN = new RegExp(
|
|
17387
|
+
`\\[\\[aka:(?:${CATEGORY_ALTERNATION}):[A-Z2-7]{2,7}\\.[A-Z2-7]{26}\\.[A-Z2-7]{16}\\]\\]`
|
|
17388
|
+
);
|
|
17389
|
+
var POINTER_TOKEN_ANCHORED = new RegExp(`^${POINTER_TOKEN_PATTERN.source}$`);
|
|
17390
|
+
function pointerTokenScanner() {
|
|
17391
|
+
return new RegExp(POINTER_TOKEN_PATTERN.source, "g");
|
|
17392
|
+
}
|
|
17393
|
+
var PointerToken = external_exports.string().regex(POINTER_TOKEN_ANCHORED);
|
|
17394
|
+
var ParsedPointer = external_exports.object({
|
|
17395
|
+
category: DetectionCategory,
|
|
17396
|
+
keyVersion: external_exports.number().int().positive(),
|
|
17397
|
+
pointerId: external_exports.string(),
|
|
17398
|
+
tag: external_exports.string()
|
|
17399
|
+
});
|
|
17400
|
+
var VaultEntry = external_exports.object({
|
|
17401
|
+
pointerId: external_exports.string(),
|
|
17402
|
+
// The keyed HMAC of the raw value under `exception.key`, and the epoch it was
|
|
17403
|
+
// derived under. This is what a reveal-to-model grant matches on, and it rotates
|
|
17404
|
+
// independently of the vault encryption key below.
|
|
17405
|
+
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
17406
|
+
fingerprintKeyVersion: external_exports.number().int().positive(),
|
|
17407
|
+
// The vault-key epoch this row's ciphertext was sealed under.
|
|
17408
|
+
keyVersion: external_exports.number().int().positive(),
|
|
17409
|
+
// Fixed at first mint and never updated: the same value detected later under a
|
|
17410
|
+
// different rule's category keeps the category it was minted with, so one
|
|
17411
|
+
// value always produces exactly one wire token.
|
|
17412
|
+
category: DetectionCategory,
|
|
17413
|
+
ruleId: external_exports.string(),
|
|
17414
|
+
// Partial-reveal preview for badges and listings. Never the raw value.
|
|
17415
|
+
maskedMatch: external_exports.string(),
|
|
17416
|
+
provider: external_exports.string().optional(),
|
|
17417
|
+
ciphertext: external_exports.string(),
|
|
17418
|
+
nonce: external_exports.string(),
|
|
17419
|
+
authTag: external_exports.string(),
|
|
17420
|
+
// How many times this value has been detected on this machine — the reuse
|
|
17421
|
+
// signal the vault dashboard reads. Distinct from VaultDeref.pointerCount.
|
|
17422
|
+
occurrenceCount: external_exports.number().int().nonnegative(),
|
|
17423
|
+
firstSeen: external_exports.string(),
|
|
17424
|
+
lastSeen: external_exports.string()
|
|
17425
|
+
});
|
|
17426
|
+
var PointerDescriptor = external_exports.object({
|
|
17427
|
+
category: DetectionCategory,
|
|
17428
|
+
provider: external_exports.string().optional(),
|
|
17429
|
+
maskedMatch: external_exports.string(),
|
|
17430
|
+
occurrences: external_exports.number().int().nonnegative(),
|
|
17431
|
+
firstSeen: external_exports.string(),
|
|
17432
|
+
lastSeen: external_exports.string()
|
|
17433
|
+
});
|
|
17434
|
+
var PointerIdentity = external_exports.object({
|
|
17435
|
+
ruleId: external_exports.string(),
|
|
17436
|
+
valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
|
|
17437
|
+
fingerprintKeyVersion: external_exports.number().int().positive()
|
|
17438
|
+
});
|
|
17439
|
+
var DetokenizeTarget = external_exports.enum(["human", "model"]);
|
|
17440
|
+
var VaultDerefReason = external_exports.enum([
|
|
17441
|
+
"display",
|
|
17442
|
+
"explicit-reveal",
|
|
17443
|
+
"view-render",
|
|
17444
|
+
"model-input",
|
|
17445
|
+
"remediation",
|
|
17446
|
+
"purge"
|
|
17447
|
+
]);
|
|
17448
|
+
var VaultDerefOutcome = external_exports.enum(["revealed", "refused", "unavailable"]);
|
|
17449
|
+
var BATCHED_DEREF_REASONS = ["display", "view-render"];
|
|
17450
|
+
function isBatchedDerefReason(reason) {
|
|
17451
|
+
return BATCHED_DEREF_REASONS.includes(reason);
|
|
17452
|
+
}
|
|
17453
|
+
var VaultDeref = external_exports.object({
|
|
17454
|
+
id: external_exports.guid(),
|
|
17455
|
+
pointerId: external_exports.string(),
|
|
17456
|
+
at: external_exports.string(),
|
|
17457
|
+
target: DetokenizeTarget,
|
|
17458
|
+
reason: VaultDerefReason,
|
|
17459
|
+
outcome: VaultDerefOutcome,
|
|
17460
|
+
// Present only on a model-target crossing that a reveal grant authorized.
|
|
17461
|
+
grantId: external_exports.string().optional(),
|
|
17462
|
+
// How many pointers ONE batched render resolved. 1 for unbatched rows. Named
|
|
17463
|
+
// apart from VaultEntry.occurrenceCount, which counts detections of a value.
|
|
17464
|
+
pointerCount: external_exports.number().int().positive().default(1)
|
|
17465
|
+
});
|
|
17466
|
+
var VaultSightingKind = external_exports.enum([
|
|
17467
|
+
"prompt",
|
|
17468
|
+
"tool-input",
|
|
17469
|
+
"tool-output",
|
|
17470
|
+
"file",
|
|
17471
|
+
"transcript"
|
|
17472
|
+
]);
|
|
17473
|
+
var VaultSighting = external_exports.object({
|
|
17474
|
+
location: external_exports.string(),
|
|
17475
|
+
kind: VaultSightingKind,
|
|
17476
|
+
firstSeen: external_exports.string(),
|
|
17477
|
+
lastSeen: external_exports.string()
|
|
17478
|
+
});
|
|
17479
|
+
var VaultInventoryEntry = external_exports.object({
|
|
17480
|
+
pointerId: external_exports.string(),
|
|
17481
|
+
category: DetectionCategory,
|
|
17482
|
+
provider: external_exports.string().optional(),
|
|
17483
|
+
maskedMatch: external_exports.string(),
|
|
17484
|
+
occurrences: external_exports.number().int().nonnegative(),
|
|
17485
|
+
firstSeen: external_exports.string(),
|
|
17486
|
+
lastSeen: external_exports.string(),
|
|
17487
|
+
// The active reveal-to-model grant covering this value, when one exists —
|
|
17488
|
+
// the inventory badges it, the row links to revocation.
|
|
17489
|
+
revealGrantId: external_exports.string().nullable(),
|
|
17490
|
+
sightings: external_exports.array(VaultSighting)
|
|
17491
|
+
});
|
|
17492
|
+
var VaultKeyCustody = external_exports.string();
|
|
17493
|
+
var VaultInlineReveal = external_exports.enum(["masked", "full", "off"]);
|
|
17494
|
+
var VAULT_EVENT_NOTE_MAX_POINTERS = 8;
|
|
17495
|
+
var VAULT_CONSENT_VERSION = 1;
|
|
17496
|
+
var VaultConsent = external_exports.object({
|
|
17497
|
+
acknowledgedAt: external_exports.iso.datetime(),
|
|
17498
|
+
version: external_exports.number().int().positive()
|
|
17499
|
+
});
|
|
17500
|
+
function isVaultConsentValid(consent) {
|
|
17501
|
+
return consent?.version === VAULT_CONSENT_VERSION;
|
|
17502
|
+
}
|
|
17503
|
+
|
|
17364
17504
|
// ../../packages/schema/src/zod/local.ts
|
|
17365
|
-
var WORKSPACE_SETTINGS_SPEC_VERSION =
|
|
17505
|
+
var WORKSPACE_SETTINGS_SPEC_VERSION = 5;
|
|
17366
17506
|
var RunMode = external_exports.enum(["standalone"]);
|
|
17367
17507
|
var SimpleDetectionPolicy = external_exports.enum(["redact", "warn"]);
|
|
17368
17508
|
var HistoricalAccess = external_exports.enum(["full", "session-only"]);
|
|
@@ -17384,6 +17524,16 @@ var WorkspaceSettings = external_exports.object({
|
|
|
17384
17524
|
// In-place egress extraction on the scan paths; disable to stop all Data
|
|
17385
17525
|
// Shares writes.
|
|
17386
17526
|
dataSharesInPlace: external_exports.boolean().default(true),
|
|
17527
|
+
// Consent to keep a RECOVERABLE encrypted copy of detected values in the local
|
|
17528
|
+
// vault, instead of destroying them. Absent by default: this is a custody
|
|
17529
|
+
// change from one-way redaction, so it is never an assumed grant on upgrade.
|
|
17530
|
+
// Revoking stops future vaulting; it does not erase what is already stored —
|
|
17531
|
+
// purging the vault is the eraser.
|
|
17532
|
+
vaultConsent: VaultConsent.optional(),
|
|
17533
|
+
// Where the vault master key lives.
|
|
17534
|
+
vaultKeyCustody: VaultKeyCustody.default("file"),
|
|
17535
|
+
// How a pointer renders in assistant prose on screen (see VaultInlineReveal).
|
|
17536
|
+
vaultInlineReveal: VaultInlineReveal.default("masked"),
|
|
17387
17537
|
// Absent until /aka:setup completes; its presence is what "onboarded" means.
|
|
17388
17538
|
onboardedAt: external_exports.iso.datetime().optional(),
|
|
17389
17539
|
// Records that the user consented to sending findings to the model API for
|
|
@@ -19798,6 +19948,9 @@ var AmbiguousExceptionIdError = class extends Error {
|
|
|
19798
19948
|
var ACTIVE_PREDICATE = `revoked_at IS NULL
|
|
19799
19949
|
AND (expires_at IS NULL OR expires_at > :now)
|
|
19800
19950
|
AND (max_uses IS NULL OR use_count < max_uses)`;
|
|
19951
|
+
var ACTIVE_REVEAL_GRANT_PREDICATE = `capability = 'reveal_to_model'
|
|
19952
|
+
AND conditions IS NULL
|
|
19953
|
+
AND ${ACTIVE_PREDICATE}`;
|
|
19801
19954
|
var SqliteExceptionsRepository = class {
|
|
19802
19955
|
constructor(db) {
|
|
19803
19956
|
this.db = db;
|
|
@@ -19889,11 +20042,11 @@ var SqliteExceptionsRepository = class {
|
|
|
19889
20042
|
this.db.prepare(
|
|
19890
20043
|
`INSERT INTO exceptions (
|
|
19891
20044
|
id, rule_id, category, value_fingerprint, key_version, masked_value,
|
|
19892
|
-
scope, expires_at, max_uses, use_count, last_used_at,
|
|
19893
|
-
conditions, created_by, created_via, created_at, updated_at
|
|
20045
|
+
capability, scope, expires_at, max_uses, use_count, last_used_at,
|
|
20046
|
+
justification, conditions, created_by, created_via, created_at, updated_at
|
|
19894
20047
|
) VALUES (
|
|
19895
20048
|
:id, :ruleId, :category, :valueFingerprint, :keyVersion, :maskedValue,
|
|
19896
|
-
:scope, :expiresAt, :maxUses, 0, NULL, :justification,
|
|
20049
|
+
:capability, :scope, :expiresAt, :maxUses, 0, NULL, :justification,
|
|
19897
20050
|
:conditions, :createdBy, :createdVia, :now, :now
|
|
19898
20051
|
)`
|
|
19899
20052
|
).run({
|
|
@@ -19903,6 +20056,7 @@ var SqliteExceptionsRepository = class {
|
|
|
19903
20056
|
valueFingerprint: input.valueFingerprint,
|
|
19904
20057
|
keyVersion: input.keyVersion,
|
|
19905
20058
|
maskedValue: input.maskedValue,
|
|
20059
|
+
capability: input.capability ?? "suppress",
|
|
19906
20060
|
scope: input.scope,
|
|
19907
20061
|
expiresAt: input.expiresAt === null ? null : isoToEpochMillis(input.expiresAt),
|
|
19908
20062
|
maxUses: input.maxUses,
|
|
@@ -19996,6 +20150,7 @@ var SqliteExceptionsRepository = class {
|
|
|
19996
20150
|
ruleId: row.rule_id,
|
|
19997
20151
|
valueFingerprint: row.value_fingerprint,
|
|
19998
20152
|
keyVersion: row.key_version,
|
|
20153
|
+
capability: row.capability,
|
|
19999
20154
|
expiresAt: row.expires_at === null ? null : epochMillisToIso(row.expires_at),
|
|
20000
20155
|
maxUses: row.max_uses,
|
|
20001
20156
|
useCount: row.use_count,
|
|
@@ -20050,6 +20205,35 @@ var SqliteExceptionsRepository = class {
|
|
|
20050
20205
|
}))
|
|
20051
20206
|
);
|
|
20052
20207
|
}
|
|
20208
|
+
/**
|
|
20209
|
+
* The active reveal-to-model grant for a vaulted value's identity, or null.
|
|
20210
|
+
* Matching is exact on (ruleId, valueFingerprint, keyVersion) — the same key
|
|
20211
|
+
* suppression uses — plus the capability: a suppression grant must never
|
|
20212
|
+
* authorize a reveal. Read-only: the caller does NOT consume here, because a
|
|
20213
|
+
* revealed value re-enters the detection scan immediately afterward and the
|
|
20214
|
+
* suppression match there claims the use — one crossing, one use.
|
|
20215
|
+
*
|
|
20216
|
+
* A grant with `conditions` NEVER matches here: the reveal path does not yet
|
|
20217
|
+
* evaluate conditions, and a narrowing clause that is ignored would WIDEN the
|
|
20218
|
+
* grant instead. Fail closed until reveal-side condition evaluation exists.
|
|
20219
|
+
*/
|
|
20220
|
+
activeRevealGrant(ruleId, valueFingerprint, keyVersion, now = Date.now()) {
|
|
20221
|
+
try {
|
|
20222
|
+
const row = getRow(
|
|
20223
|
+
this.db.prepare(
|
|
20224
|
+
`SELECT id FROM exceptions
|
|
20225
|
+
WHERE rule_id = :ruleId AND value_fingerprint = :valueFingerprint
|
|
20226
|
+
AND key_version = :keyVersion
|
|
20227
|
+
AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
|
|
20228
|
+
LIMIT 1`
|
|
20229
|
+
),
|
|
20230
|
+
{ ruleId, valueFingerprint, keyVersion, now }
|
|
20231
|
+
);
|
|
20232
|
+
return Promise.resolve(row ?? null);
|
|
20233
|
+
} catch (err) {
|
|
20234
|
+
return Promise.reject(err instanceof Error ? err : new Error(String(err)));
|
|
20235
|
+
}
|
|
20236
|
+
}
|
|
20053
20237
|
/**
|
|
20054
20238
|
* Retention sweep: delete TERMINAL rows (revoked, expired, or use-budget
|
|
20055
20239
|
* exhausted) whose last transition is older than the retention window.
|
|
@@ -20077,6 +20261,7 @@ function parseExceptionRow(row) {
|
|
|
20077
20261
|
valueFingerprint: row.value_fingerprint,
|
|
20078
20262
|
keyVersion: row.key_version,
|
|
20079
20263
|
maskedValue: row.masked_value,
|
|
20264
|
+
capability: row.capability,
|
|
20080
20265
|
scope: row.scope,
|
|
20081
20266
|
expiresAt: row.expires_at === null ? null : epochMillisToIso(row.expires_at),
|
|
20082
20267
|
maxUses: row.max_uses,
|
|
@@ -22242,6 +22427,287 @@ var SqliteScanLedgerRepository = class {
|
|
|
22242
22427
|
}
|
|
22243
22428
|
};
|
|
22244
22429
|
|
|
22430
|
+
// ../../packages/persistence/src/repositories/secret-vault.ts
|
|
22431
|
+
import { randomUUID as randomUUID7 } from "crypto";
|
|
22432
|
+
var SELECT_COLUMNS = `
|
|
22433
|
+
pointer_id AS pointerId,
|
|
22434
|
+
value_fingerprint AS valueFingerprint,
|
|
22435
|
+
fingerprint_key_version AS fingerprintKeyVersion,
|
|
22436
|
+
key_version AS keyVersion,
|
|
22437
|
+
format_version AS formatVersion,
|
|
22438
|
+
category,
|
|
22439
|
+
rule_id AS ruleId,
|
|
22440
|
+
masked_match AS maskedMatch,
|
|
22441
|
+
provider,
|
|
22442
|
+
ciphertext,
|
|
22443
|
+
nonce,
|
|
22444
|
+
auth_tag AS authTag,
|
|
22445
|
+
occurrence_count AS occurrenceCount,
|
|
22446
|
+
first_seen AS firstSeen,
|
|
22447
|
+
last_seen AS lastSeen`;
|
|
22448
|
+
function toRow(raw) {
|
|
22449
|
+
const { provider, ...rest } = raw;
|
|
22450
|
+
return provider === null ? rest : { ...rest, provider };
|
|
22451
|
+
}
|
|
22452
|
+
var SqliteSecretVaultRepository = class {
|
|
22453
|
+
constructor(db) {
|
|
22454
|
+
this.db = db;
|
|
22455
|
+
this.insertStmt = db.prepare(
|
|
22456
|
+
`INSERT INTO secret_vault (
|
|
22457
|
+
pointer_id, value_fingerprint, fingerprint_key_version, key_version,
|
|
22458
|
+
format_version, category, rule_id, masked_match, provider,
|
|
22459
|
+
ciphertext, nonce, auth_tag,
|
|
22460
|
+
occurrence_count, first_seen, last_seen
|
|
22461
|
+
) VALUES (
|
|
22462
|
+
:pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
|
|
22463
|
+
:formatVersion, :category, :ruleId, :maskedMatch, :provider,
|
|
22464
|
+
:ciphertext, :nonce, :authTag,
|
|
22465
|
+
1, :now, :now
|
|
22466
|
+
)`
|
|
22467
|
+
);
|
|
22468
|
+
this.bumpStmt = db.prepare(
|
|
22469
|
+
`UPDATE secret_vault
|
|
22470
|
+
SET occurrence_count = occurrence_count + 1, last_seen = :now
|
|
22471
|
+
WHERE value_fingerprint = :valueFingerprint`
|
|
22472
|
+
);
|
|
22473
|
+
this.byPointerStmt = db.prepare(
|
|
22474
|
+
`SELECT ${SELECT_COLUMNS} FROM secret_vault WHERE pointer_id = :pointerId`
|
|
22475
|
+
);
|
|
22476
|
+
this.byFingerprintStmt = db.prepare(
|
|
22477
|
+
`SELECT ${SELECT_COLUMNS} FROM secret_vault WHERE value_fingerprint = :valueFingerprint`
|
|
22478
|
+
);
|
|
22479
|
+
this.listStmt = db.prepare(`SELECT ${SELECT_COLUMNS} FROM secret_vault ORDER BY first_seen`);
|
|
22480
|
+
this.replaceCiphertextStmt = db.prepare(
|
|
22481
|
+
`UPDATE secret_vault
|
|
22482
|
+
SET key_version = :keyVersion, ciphertext = :ciphertext, nonce = :nonce, auth_tag = :authTag
|
|
22483
|
+
WHERE pointer_id = :pointerId`
|
|
22484
|
+
);
|
|
22485
|
+
this.refreshFingerprintStmt = db.prepare(
|
|
22486
|
+
`UPDATE secret_vault
|
|
22487
|
+
SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
|
|
22488
|
+
WHERE pointer_id = :pointerId`
|
|
22489
|
+
);
|
|
22490
|
+
this.derefStmt = db.prepare(
|
|
22491
|
+
`INSERT INTO secret_vault_deref (id, pointer_id, at, target, reason, outcome, grant_id, pointer_count)
|
|
22492
|
+
VALUES (:id, :pointerId, :at, :target, :reason, :outcome, :grantId, :pointerCount)`
|
|
22493
|
+
);
|
|
22494
|
+
}
|
|
22495
|
+
db;
|
|
22496
|
+
insertStmt;
|
|
22497
|
+
bumpStmt;
|
|
22498
|
+
byPointerStmt;
|
|
22499
|
+
byFingerprintStmt;
|
|
22500
|
+
listStmt;
|
|
22501
|
+
replaceCiphertextStmt;
|
|
22502
|
+
refreshFingerprintStmt;
|
|
22503
|
+
derefStmt;
|
|
22504
|
+
/**
|
|
22505
|
+
* Vault a value, or record another sighting of one already vaulted. Keyed on
|
|
22506
|
+
* `valueFingerprint`, never on the caller's pointer id: a value seen again
|
|
22507
|
+
* bumps `occurrence_count` and `last_seen` and comes back with its ORIGINAL
|
|
22508
|
+
* pointer, category and ciphertext, so the same secret always resolves to one
|
|
22509
|
+
* wire token. `minted` is true only when this call created the row.
|
|
22510
|
+
*
|
|
22511
|
+
* The read-then-write runs in one IMMEDIATE transaction so two concurrent
|
|
22512
|
+
* writers cannot both decide they are minting.
|
|
22513
|
+
*/
|
|
22514
|
+
upsert(input, now) {
|
|
22515
|
+
let minted = false;
|
|
22516
|
+
withTransaction(
|
|
22517
|
+
this.db,
|
|
22518
|
+
() => {
|
|
22519
|
+
const existing = getRow(this.byFingerprintStmt, {
|
|
22520
|
+
valueFingerprint: input.valueFingerprint
|
|
22521
|
+
});
|
|
22522
|
+
if (existing === void 0) {
|
|
22523
|
+
this.insertStmt.run(
|
|
22524
|
+
bindParams({
|
|
22525
|
+
pointerId: input.pointerId,
|
|
22526
|
+
valueFingerprint: input.valueFingerprint,
|
|
22527
|
+
fingerprintKeyVersion: input.fingerprintKeyVersion,
|
|
22528
|
+
keyVersion: input.keyVersion,
|
|
22529
|
+
formatVersion: input.formatVersion ?? POINTER_FORMAT_VERSION,
|
|
22530
|
+
category: input.category,
|
|
22531
|
+
ruleId: input.ruleId,
|
|
22532
|
+
maskedMatch: input.maskedMatch,
|
|
22533
|
+
provider: input.provider,
|
|
22534
|
+
ciphertext: input.ciphertext,
|
|
22535
|
+
nonce: input.nonce,
|
|
22536
|
+
authTag: input.authTag,
|
|
22537
|
+
now
|
|
22538
|
+
})
|
|
22539
|
+
);
|
|
22540
|
+
minted = true;
|
|
22541
|
+
return;
|
|
22542
|
+
}
|
|
22543
|
+
this.bumpStmt.run({ valueFingerprint: input.valueFingerprint, now });
|
|
22544
|
+
},
|
|
22545
|
+
"IMMEDIATE"
|
|
22546
|
+
);
|
|
22547
|
+
const row = getRow(this.byFingerprintStmt, {
|
|
22548
|
+
valueFingerprint: input.valueFingerprint
|
|
22549
|
+
});
|
|
22550
|
+
if (row === void 0) throw new Error("vault: row vanished immediately after write");
|
|
22551
|
+
return { row: toRow(row), minted };
|
|
22552
|
+
}
|
|
22553
|
+
byPointerId(pointerId) {
|
|
22554
|
+
const raw = getRow(this.byPointerStmt, { pointerId });
|
|
22555
|
+
return raw === void 0 ? null : toRow(raw);
|
|
22556
|
+
}
|
|
22557
|
+
byValueFingerprint(fingerprint) {
|
|
22558
|
+
const raw = getRow(this.byFingerprintStmt, { valueFingerprint: fingerprint });
|
|
22559
|
+
return raw === void 0 ? null : toRow(raw);
|
|
22560
|
+
}
|
|
22561
|
+
/** Append one audit row. Carries no raw value and no ciphertext, by shape. */
|
|
22562
|
+
recordDeref(entry) {
|
|
22563
|
+
this.derefStmt.run(
|
|
22564
|
+
bindParams({
|
|
22565
|
+
id: entry.id,
|
|
22566
|
+
pointerId: entry.pointerId,
|
|
22567
|
+
at: entry.at,
|
|
22568
|
+
target: entry.target,
|
|
22569
|
+
reason: entry.reason,
|
|
22570
|
+
outcome: entry.outcome,
|
|
22571
|
+
grantId: entry.grantId,
|
|
22572
|
+
pointerCount: entry.pointerCount ?? 1
|
|
22573
|
+
})
|
|
22574
|
+
);
|
|
22575
|
+
}
|
|
22576
|
+
listAll() {
|
|
22577
|
+
return allRows(this.listStmt).map(toRow);
|
|
22578
|
+
}
|
|
22579
|
+
/** Re-seal an entry under a new key epoch, leaving its identity untouched. */
|
|
22580
|
+
replaceCiphertext(pointerId, next) {
|
|
22581
|
+
this.replaceCiphertextStmt.run({ pointerId, ...next });
|
|
22582
|
+
}
|
|
22583
|
+
/** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
|
|
22584
|
+
refreshFingerprint(pointerId, next) {
|
|
22585
|
+
this.refreshFingerprintStmt.run({ pointerId, ...next });
|
|
22586
|
+
}
|
|
22587
|
+
/**
|
|
22588
|
+
* Destroy every vaulted value and report how many were destroyed. The deref
|
|
22589
|
+
* audit is left alone on purpose — see the table note above.
|
|
22590
|
+
*/
|
|
22591
|
+
purgeAll() {
|
|
22592
|
+
let destroyed = 0;
|
|
22593
|
+
withTransaction(
|
|
22594
|
+
this.db,
|
|
22595
|
+
() => {
|
|
22596
|
+
destroyed = this.countEntries();
|
|
22597
|
+
this.db.exec("DELETE FROM secret_vault");
|
|
22598
|
+
},
|
|
22599
|
+
"IMMEDIATE"
|
|
22600
|
+
);
|
|
22601
|
+
return destroyed;
|
|
22602
|
+
}
|
|
22603
|
+
/**
|
|
22604
|
+
* Record (or re-stamp) one place a pointer has been written. One row per
|
|
22605
|
+
* (pointer, location); a re-sighting bumps last_seen. Best-effort bookkeeping
|
|
22606
|
+
* on hook paths — a failure must never affect the rewrite that triggered it,
|
|
22607
|
+
* so callers wrap this, not the other way around.
|
|
22608
|
+
*/
|
|
22609
|
+
recordSighting(entry, now) {
|
|
22610
|
+
this.db.prepare(
|
|
22611
|
+
`INSERT INTO secret_vault_sighting (id, pointer_id, location, kind, first_seen, last_seen)
|
|
22612
|
+
VALUES (:id, :pointerId, :location, :kind, :now, :now)
|
|
22613
|
+
ON CONFLICT (pointer_id, location) DO UPDATE SET last_seen = :now`
|
|
22614
|
+
).run({
|
|
22615
|
+
id: randomUUID7(),
|
|
22616
|
+
pointerId: entry.pointerId,
|
|
22617
|
+
location: entry.location,
|
|
22618
|
+
kind: entry.kind,
|
|
22619
|
+
now
|
|
22620
|
+
});
|
|
22621
|
+
}
|
|
22622
|
+
listSightings(pointerId) {
|
|
22623
|
+
const rows = allRows(
|
|
22624
|
+
this.db.prepare(
|
|
22625
|
+
`SELECT location, kind, first_seen, last_seen FROM secret_vault_sighting
|
|
22626
|
+
WHERE pointer_id = :pointerId ORDER BY last_seen DESC`
|
|
22627
|
+
),
|
|
22628
|
+
{ pointerId }
|
|
22629
|
+
);
|
|
22630
|
+
return rows.map((r) => ({
|
|
22631
|
+
location: r.location,
|
|
22632
|
+
kind: r.kind,
|
|
22633
|
+
firstSeen: new Date(r.first_seen).toISOString(),
|
|
22634
|
+
lastSeen: new Date(r.last_seen).toISOString()
|
|
22635
|
+
}));
|
|
22636
|
+
}
|
|
22637
|
+
/**
|
|
22638
|
+
* The dashboard inventory: every vaulted value's descriptor data joined with
|
|
22639
|
+
* its sightings and the active reveal-to-model grant when one exists.
|
|
22640
|
+
* Raw-free by construction — neither the fingerprint nor the ciphertext
|
|
22641
|
+
* columns are selected.
|
|
22642
|
+
*/
|
|
22643
|
+
listInventory(now = Date.now()) {
|
|
22644
|
+
const rows = allRows(
|
|
22645
|
+
this.db.prepare(
|
|
22646
|
+
`SELECT v.pointer_id, v.category, v.rule_id, v.masked_match, v.provider,
|
|
22647
|
+
v.occurrence_count, v.first_seen, v.last_seen,
|
|
22648
|
+
(SELECT e.id FROM exceptions e
|
|
22649
|
+
WHERE e.rule_id = v.rule_id
|
|
22650
|
+
AND e.value_fingerprint = v.value_fingerprint
|
|
22651
|
+
AND e.key_version = v.fingerprint_key_version
|
|
22652
|
+
AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
|
|
22653
|
+
LIMIT 1) AS grant_id
|
|
22654
|
+
FROM secret_vault v
|
|
22655
|
+
ORDER BY v.last_seen DESC`
|
|
22656
|
+
),
|
|
22657
|
+
{ now }
|
|
22658
|
+
);
|
|
22659
|
+
return rows.map((r) => ({
|
|
22660
|
+
pointerId: r.pointer_id,
|
|
22661
|
+
category: r.category,
|
|
22662
|
+
...r.provider === null ? {} : { provider: r.provider },
|
|
22663
|
+
maskedMatch: r.masked_match,
|
|
22664
|
+
occurrences: r.occurrence_count,
|
|
22665
|
+
firstSeen: new Date(r.first_seen).toISOString(),
|
|
22666
|
+
lastSeen: new Date(r.last_seen).toISOString(),
|
|
22667
|
+
revealGrantId: r.grant_id,
|
|
22668
|
+
sightings: this.listSightings(r.pointer_id)
|
|
22669
|
+
}));
|
|
22670
|
+
}
|
|
22671
|
+
/**
|
|
22672
|
+
* The de-reference trail, newest first. By default the batched, high-volume
|
|
22673
|
+
* reasons (display, view-render) are hidden and counted instead — the rows
|
|
22674
|
+
* that matter as a signal are the model crossings, and burying them under
|
|
22675
|
+
* render noise would defeat the audit's purpose.
|
|
22676
|
+
*/
|
|
22677
|
+
listDerefs(opts) {
|
|
22678
|
+
const limit = opts?.limit ?? 200;
|
|
22679
|
+
const where = opts?.includeBatched === true ? "" : `WHERE reason NOT IN ('display', 'view-render')`;
|
|
22680
|
+
const rows = allRows(
|
|
22681
|
+
this.db.prepare(
|
|
22682
|
+
`SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
|
|
22683
|
+
FROM secret_vault_deref ${where}
|
|
22684
|
+
ORDER BY at DESC, rowid DESC LIMIT :limit`
|
|
22685
|
+
),
|
|
22686
|
+
{ limit }
|
|
22687
|
+
);
|
|
22688
|
+
const hiddenBatched = opts?.includeBatched === true ? 0 : countScalar(
|
|
22689
|
+
this.db,
|
|
22690
|
+
`SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')`
|
|
22691
|
+
);
|
|
22692
|
+
return {
|
|
22693
|
+
rows: rows.map((r) => ({
|
|
22694
|
+
id: r.id,
|
|
22695
|
+
pointerId: r.pointer_id,
|
|
22696
|
+
at: new Date(r.at).toISOString(),
|
|
22697
|
+
target: r.target,
|
|
22698
|
+
reason: r.reason,
|
|
22699
|
+
outcome: r.outcome,
|
|
22700
|
+
...r.grant_id === null ? {} : { grantId: r.grant_id },
|
|
22701
|
+
pointerCount: r.pointer_count
|
|
22702
|
+
})),
|
|
22703
|
+
hiddenBatched
|
|
22704
|
+
};
|
|
22705
|
+
}
|
|
22706
|
+
countEntries() {
|
|
22707
|
+
return countScalar(this.db, "SELECT COUNT(*) AS n FROM secret_vault");
|
|
22708
|
+
}
|
|
22709
|
+
};
|
|
22710
|
+
|
|
22245
22711
|
// ../../packages/persistence/src/repositories/security.ts
|
|
22246
22712
|
var DAY_MS4 = 864e5;
|
|
22247
22713
|
var SEVERITIES = ["critical", "high", "medium", "low"];
|
|
@@ -22587,7 +23053,7 @@ var SqliteSecurityRepository = class {
|
|
|
22587
23053
|
};
|
|
22588
23054
|
|
|
22589
23055
|
// ../../packages/persistence/src/repositories/shares.ts
|
|
22590
|
-
import { randomUUID as
|
|
23056
|
+
import { randomUUID as randomUUID8 } from "crypto";
|
|
22591
23057
|
var MAX_EGRESS_CALL_SITES_PER_PROJECT = 5e3;
|
|
22592
23058
|
var IN_CHUNK = 500;
|
|
22593
23059
|
var KIND_ORDER = ["provider", "internal", "external", "ip"];
|
|
@@ -22843,7 +23309,7 @@ var SqliteSharesRepository = class {
|
|
|
22843
23309
|
(id, destination_id, host, decision, created_at, updated_at)
|
|
22844
23310
|
VALUES (:id, :destinationId, :host, :decision, :now, :now)`
|
|
22845
23311
|
).run({
|
|
22846
|
-
id:
|
|
23312
|
+
id: randomUUID8(),
|
|
22847
23313
|
destinationId,
|
|
22848
23314
|
host: dest.host,
|
|
22849
23315
|
decision,
|
|
@@ -22992,7 +23458,7 @@ var SqliteSharesRepository = class {
|
|
|
22992
23458
|
let destinationId = destIds.get(hit.host);
|
|
22993
23459
|
if (destinationId === void 0) {
|
|
22994
23460
|
destStmt.run({
|
|
22995
|
-
id:
|
|
23461
|
+
id: randomUUID8(),
|
|
22996
23462
|
kind: hit.kind,
|
|
22997
23463
|
name: hit.name,
|
|
22998
23464
|
host: hit.host,
|
|
@@ -23008,7 +23474,7 @@ var SqliteSharesRepository = class {
|
|
|
23008
23474
|
let endpointId = endpointIds.get(endpointKey);
|
|
23009
23475
|
if (endpointId === void 0) {
|
|
23010
23476
|
endpointStmt.run({
|
|
23011
|
-
id:
|
|
23477
|
+
id: randomUUID8(),
|
|
23012
23478
|
destinationId,
|
|
23013
23479
|
method: hit.method,
|
|
23014
23480
|
transport: hit.transport,
|
|
@@ -23021,7 +23487,7 @@ var SqliteSharesRepository = class {
|
|
|
23021
23487
|
endpointIds.set(endpointKey, endpointId);
|
|
23022
23488
|
}
|
|
23023
23489
|
siteStmt.run({
|
|
23024
|
-
id:
|
|
23490
|
+
id: randomUUID8(),
|
|
23025
23491
|
endpointId,
|
|
23026
23492
|
project: input.project,
|
|
23027
23493
|
projectKey: input.projectKey,
|
|
@@ -23437,6 +23903,7 @@ function openAndInitialize(file2) {
|
|
|
23437
23903
|
policies,
|
|
23438
23904
|
installedPacks,
|
|
23439
23905
|
scanLedger: new SqliteScanLedgerRepository(db),
|
|
23906
|
+
secretVault: new SqliteSecretVaultRepository(db),
|
|
23440
23907
|
exceptions: new SqliteExceptionsRepository(db),
|
|
23441
23908
|
resolutions: new SqliteResolutionsRepository(db),
|
|
23442
23909
|
ruleProbeCache: new SqliteRuleProbeCacheRepository(db),
|
|
@@ -23472,6 +23939,7 @@ function openLocalDatabase(dir) {
|
|
|
23472
23939
|
policies,
|
|
23473
23940
|
installedPacks,
|
|
23474
23941
|
scanLedger,
|
|
23942
|
+
secretVault,
|
|
23475
23943
|
exceptions,
|
|
23476
23944
|
resolutions,
|
|
23477
23945
|
ruleProbeCache,
|
|
@@ -23580,7 +24048,7 @@ function openLocalDatabase(dir) {
|
|
|
23580
24048
|
const definitionId = definitionIds.get(`${finding.ruleId}@${finding.version}`);
|
|
23581
24049
|
if (!definitionId) continue;
|
|
23582
24050
|
inspectionFindings.insertFinding({
|
|
23583
|
-
id:
|
|
24051
|
+
id: randomUUID9(),
|
|
23584
24052
|
auditEventId: record2.scanEvent.id,
|
|
23585
24053
|
inspectionDefinitionId: definitionId,
|
|
23586
24054
|
span: finding.span,
|
|
@@ -23657,6 +24125,7 @@ function openLocalDatabase(dir) {
|
|
|
23657
24125
|
policies,
|
|
23658
24126
|
installedPacks,
|
|
23659
24127
|
scanLedger,
|
|
24128
|
+
secretVault,
|
|
23660
24129
|
exceptions,
|
|
23661
24130
|
resolutions,
|
|
23662
24131
|
ruleProbeCache,
|
|
@@ -23689,6 +24158,26 @@ function openLocalDatabase(dir) {
|
|
|
23689
24158
|
};
|
|
23690
24159
|
}
|
|
23691
24160
|
|
|
24161
|
+
// ../../packages/persistence/src/exception-policy.ts
|
|
24162
|
+
var UserGrantPolicyProvider = class {
|
|
24163
|
+
#exceptions;
|
|
24164
|
+
constructor(exceptions) {
|
|
24165
|
+
this.#exceptions = exceptions;
|
|
24166
|
+
}
|
|
24167
|
+
async decideReveal(identity) {
|
|
24168
|
+
try {
|
|
24169
|
+
const grant = await this.#exceptions.activeRevealGrant(
|
|
24170
|
+
identity.ruleId,
|
|
24171
|
+
identity.valueFingerprint,
|
|
24172
|
+
identity.fingerprintKeyVersion
|
|
24173
|
+
);
|
|
24174
|
+
return grant === null ? { allow: false } : { allow: true, grantId: grant.id };
|
|
24175
|
+
} catch {
|
|
24176
|
+
return { allow: false };
|
|
24177
|
+
}
|
|
24178
|
+
}
|
|
24179
|
+
};
|
|
24180
|
+
|
|
23692
24181
|
// ../../packages/persistence/src/finding-key.ts
|
|
23693
24182
|
import { createHash as createHash3 } from "crypto";
|
|
23694
24183
|
function normalizeFilePath(filePath) {
|
|
@@ -23727,7 +24216,11 @@ function parseKeyFile(raw) {
|
|
|
23727
24216
|
}
|
|
23728
24217
|
return { version: version2, material: bytes };
|
|
23729
24218
|
}
|
|
23730
|
-
var
|
|
24219
|
+
var KEY_VERSION_COLUMNS = {
|
|
24220
|
+
exceptions: "key_version",
|
|
24221
|
+
blocked_detections: "key_version",
|
|
24222
|
+
secret_vault: "fingerprint_key_version"
|
|
24223
|
+
};
|
|
23731
24224
|
var SQLITE_ERROR = 1;
|
|
23732
24225
|
var FLOOR_BUSY_TIMEOUT_MS = 250;
|
|
23733
24226
|
var FloorUnreadableError = class extends Error {
|
|
@@ -23748,10 +24241,10 @@ function storedKeyVersionFloor(dataDir2) {
|
|
|
23748
24241
|
db = new DatabaseSync2(file2, { readOnly: true });
|
|
23749
24242
|
db.exec(`PRAGMA busy_timeout = ${String(FLOOR_BUSY_TIMEOUT_MS)}`);
|
|
23750
24243
|
let floor = 0;
|
|
23751
|
-
for (const table of
|
|
24244
|
+
for (const [table, column] of Object.entries(KEY_VERSION_COLUMNS)) {
|
|
23752
24245
|
try {
|
|
23753
24246
|
const row = getRow(
|
|
23754
|
-
db.prepare(`SELECT MAX(
|
|
24247
|
+
db.prepare(`SELECT MAX(${column}) AS v FROM ${table}`)
|
|
23755
24248
|
);
|
|
23756
24249
|
floor = Math.max(floor, row?.v ?? 0);
|
|
23757
24250
|
} catch (err) {
|
|
@@ -23817,6 +24310,9 @@ function dataDir(base = defaultDataDir()) {
|
|
|
23817
24310
|
function dbPath(base = defaultDataDir()) {
|
|
23818
24311
|
return join3(dataDir(base), "aka.db");
|
|
23819
24312
|
}
|
|
24313
|
+
function keysDir(base = defaultDataDir()) {
|
|
24314
|
+
return join3(base, "keys");
|
|
24315
|
+
}
|
|
23820
24316
|
function ensureLayoutDirSync(dir = defaultDataDir()) {
|
|
23821
24317
|
ensureDataDirSync(dir);
|
|
23822
24318
|
}
|
|
@@ -23858,99 +24354,960 @@ function readJson(file2) {
|
|
|
23858
24354
|
return parseJsonObject(text) ?? null;
|
|
23859
24355
|
}
|
|
23860
24356
|
|
|
23861
|
-
// ../../packages/persistence/src/
|
|
23862
|
-
import {
|
|
23863
|
-
|
|
23864
|
-
|
|
23865
|
-
|
|
23866
|
-
|
|
23867
|
-
|
|
23868
|
-
|
|
23869
|
-
|
|
23870
|
-
|
|
23871
|
-
|
|
23872
|
-
|
|
24357
|
+
// ../../packages/persistence/src/vault/crypto.ts
|
|
24358
|
+
import {
|
|
24359
|
+
createCipheriv,
|
|
24360
|
+
createDecipheriv,
|
|
24361
|
+
createHmac as createHmac2,
|
|
24362
|
+
hkdfSync,
|
|
24363
|
+
timingSafeEqual
|
|
24364
|
+
} from "crypto";
|
|
24365
|
+
var POINTER_ID_BYTES = 16;
|
|
24366
|
+
var NONCE_BYTES = 12;
|
|
24367
|
+
var TAG_BYTES = 10;
|
|
24368
|
+
var SUBKEY_BYTES = 32;
|
|
24369
|
+
var HKDF_INFO_ENC = "aka:vault:enc:v1";
|
|
24370
|
+
var HKDF_INFO_SIGN = "aka:vault:sign:v1";
|
|
24371
|
+
var HKDF_SALT = "aka:vault:v1";
|
|
24372
|
+
var B32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
|
24373
|
+
function base32Encode(bytes) {
|
|
24374
|
+
let out = "";
|
|
24375
|
+
let buffer = 0;
|
|
24376
|
+
let bits = 0;
|
|
24377
|
+
for (const byte of bytes) {
|
|
24378
|
+
buffer = buffer << 8 | byte;
|
|
24379
|
+
bits += 8;
|
|
24380
|
+
while (bits >= 5) {
|
|
24381
|
+
out += B32_ALPHABET.charAt(buffer >>> bits - 5 & 31);
|
|
24382
|
+
bits -= 5;
|
|
24383
|
+
}
|
|
24384
|
+
}
|
|
24385
|
+
if (bits > 0) out += B32_ALPHABET.charAt(buffer << 5 - bits & 31);
|
|
24386
|
+
return out;
|
|
23873
24387
|
}
|
|
23874
|
-
|
|
23875
|
-
|
|
23876
|
-
|
|
23877
|
-
|
|
23878
|
-
|
|
23879
|
-
|
|
23880
|
-
|
|
23881
|
-
|
|
23882
|
-
|
|
23883
|
-
|
|
23884
|
-
|
|
23885
|
-
|
|
23886
|
-
}
|
|
23887
|
-
|
|
23888
|
-
|
|
23889
|
-
|
|
23890
|
-
|
|
23891
|
-
|
|
23892
|
-
|
|
23893
|
-
|
|
23894
|
-
|
|
23895
|
-
|
|
23896
|
-
|
|
23897
|
-
|
|
23898
|
-
|
|
23899
|
-
}
|
|
23900
|
-
|
|
24388
|
+
function base32Decode(text) {
|
|
24389
|
+
const out = [];
|
|
24390
|
+
let buffer = 0;
|
|
24391
|
+
let bits = 0;
|
|
24392
|
+
for (const char of text) {
|
|
24393
|
+
const value = B32_ALPHABET.indexOf(char);
|
|
24394
|
+
if (value < 0) throw new Error("base32: character outside the alphabet");
|
|
24395
|
+
buffer = buffer << 5 | value;
|
|
24396
|
+
bits += 5;
|
|
24397
|
+
if (bits >= 8) {
|
|
24398
|
+
out.push(buffer >>> bits - 8 & 255);
|
|
24399
|
+
bits -= 8;
|
|
24400
|
+
}
|
|
24401
|
+
}
|
|
24402
|
+
return Buffer.from(out);
|
|
24403
|
+
}
|
|
24404
|
+
function encodeKeyVersion(version2) {
|
|
24405
|
+
if (!Number.isInteger(version2) || version2 < 1 || version2 > 4294967295) {
|
|
24406
|
+
throw new Error("vault: key version out of range");
|
|
24407
|
+
}
|
|
24408
|
+
const bytes = [];
|
|
24409
|
+
let remaining = version2;
|
|
24410
|
+
while (remaining > 0) {
|
|
24411
|
+
bytes.unshift(remaining & 255);
|
|
24412
|
+
remaining = Math.floor(remaining / 256);
|
|
24413
|
+
}
|
|
24414
|
+
return base32Encode(Uint8Array.from(bytes));
|
|
24415
|
+
}
|
|
24416
|
+
function decodeKeyVersion(encoded) {
|
|
24417
|
+
const bytes = base32Decode(encoded);
|
|
24418
|
+
if (bytes.length === 0 || bytes.length > 4) throw new Error("vault: bad key version encoding");
|
|
24419
|
+
let version2 = 0;
|
|
24420
|
+
for (const byte of bytes) version2 = version2 * 256 + byte;
|
|
24421
|
+
if (version2 < 1) throw new Error("vault: bad key version");
|
|
24422
|
+
return version2;
|
|
24423
|
+
}
|
|
24424
|
+
function deriveSubkeys(master) {
|
|
24425
|
+
const derive = (info) => Buffer.from(hkdfSync("sha256", master, HKDF_SALT, info, SUBKEY_BYTES));
|
|
24426
|
+
return { enc: derive(HKDF_INFO_ENC), sign: derive(HKDF_INFO_SIGN) };
|
|
24427
|
+
}
|
|
24428
|
+
function bindingInput(keyVersion, pointerId, category, formatVersion = POINTER_FORMAT_VERSION) {
|
|
24429
|
+
if (pointerId.length !== POINTER_ID_BYTES) {
|
|
24430
|
+
throw new Error("vault: pointer id must be 16 bytes");
|
|
24431
|
+
}
|
|
24432
|
+
const head = Buffer.alloc(6);
|
|
24433
|
+
head.writeUInt16BE(formatVersion, 0);
|
|
24434
|
+
head.writeUInt32BE(keyVersion, 2);
|
|
24435
|
+
return Buffer.concat([head, Buffer.from(pointerId), Buffer.from(category, "utf8")]);
|
|
24436
|
+
}
|
|
24437
|
+
function seal(encKey, plaintext, aad, nonce) {
|
|
24438
|
+
const cipher = createCipheriv("aes-256-gcm", encKey, nonce);
|
|
24439
|
+
cipher.setAAD(aad);
|
|
24440
|
+
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
|
24441
|
+
return { ciphertext, nonce, authTag: cipher.getAuthTag() };
|
|
24442
|
+
}
|
|
24443
|
+
function open(encKey, sealed, aad) {
|
|
23901
24444
|
try {
|
|
23902
|
-
const
|
|
23903
|
-
|
|
24445
|
+
const decipher = createDecipheriv("aes-256-gcm", encKey, sealed.nonce);
|
|
24446
|
+
decipher.setAAD(aad);
|
|
24447
|
+
decipher.setAuthTag(sealed.authTag);
|
|
24448
|
+
return Buffer.concat([decipher.update(sealed.ciphertext), decipher.final()]).toString("utf8");
|
|
23904
24449
|
} catch {
|
|
23905
|
-
return
|
|
24450
|
+
return null;
|
|
23906
24451
|
}
|
|
23907
24452
|
}
|
|
23908
|
-
function
|
|
23909
|
-
|
|
23910
|
-
|
|
23911
|
-
|
|
23912
|
-
if (
|
|
23913
|
-
const
|
|
23914
|
-
|
|
23915
|
-
|
|
23916
|
-
|
|
23917
|
-
|
|
24453
|
+
function signPointer(signKey, keyVersion, pointerId, category) {
|
|
24454
|
+
return createHmac2("sha256", signKey).update(bindingInput(keyVersion, pointerId, category, POINTER_FORMAT_VERSION)).digest().subarray(0, TAG_BYTES);
|
|
24455
|
+
}
|
|
24456
|
+
function verifyPointerTag(signKey, keyVersion, pointerId, category, tag) {
|
|
24457
|
+
if (tag.length !== TAG_BYTES) return false;
|
|
24458
|
+
const expected = signPointer(signKey, keyVersion, pointerId, category);
|
|
24459
|
+
return timingSafeEqual(expected, Buffer.from(tag));
|
|
24460
|
+
}
|
|
24461
|
+
function formatPointer(category, keyVersion, pointerId, tag) {
|
|
24462
|
+
return `[[aka:${category}:${encodeKeyVersion(keyVersion)}.${base32Encode(pointerId)}.${base32Encode(tag)}]]`;
|
|
24463
|
+
}
|
|
24464
|
+
|
|
24465
|
+
// ../../packages/persistence/src/vault/key-provider.ts
|
|
24466
|
+
import { execFileSync } from "child_process";
|
|
24467
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
24468
|
+
import {
|
|
24469
|
+
chmodSync as chmodSync2,
|
|
24470
|
+
mkdirSync as mkdirSync2,
|
|
24471
|
+
readFileSync as readFileSync3,
|
|
24472
|
+
renameSync as renameSync4,
|
|
24473
|
+
rmSync as rmSync3,
|
|
24474
|
+
statSync,
|
|
24475
|
+
writeFileSync as writeFileSync2
|
|
24476
|
+
} from "fs";
|
|
24477
|
+
import { join as join5 } from "path";
|
|
24478
|
+
var VaultKeyEpochMissingError = class extends Error {
|
|
24479
|
+
version;
|
|
24480
|
+
constructor(version2) {
|
|
24481
|
+
super(`vault: key epoch ${String(version2)} is not present in the keyring`);
|
|
24482
|
+
this.name = "VaultKeyEpochMissingError";
|
|
24483
|
+
this.version = version2;
|
|
24484
|
+
}
|
|
24485
|
+
};
|
|
24486
|
+
var VAULT_KEY_FILENAME = "vault.key";
|
|
24487
|
+
var KEY_MATERIAL_BYTES2 = 32;
|
|
24488
|
+
var KEYCHAIN_SERVICE = "aka-vault";
|
|
24489
|
+
var KEYCHAIN_ACCOUNT = "keyring";
|
|
24490
|
+
function parseKeyring(raw) {
|
|
24491
|
+
const parsed = JSON.parse(raw);
|
|
24492
|
+
if (typeof parsed !== "object" || parsed === null) {
|
|
24493
|
+
throw new Error("vault key file is corrupt: not a JSON object");
|
|
24494
|
+
}
|
|
24495
|
+
const { current, keys } = parsed;
|
|
24496
|
+
if (typeof current !== "number" || !Number.isInteger(current) || current < 1) {
|
|
24497
|
+
throw new Error("vault key file is corrupt: bad current version");
|
|
24498
|
+
}
|
|
24499
|
+
if (typeof keys !== "object" || keys === null || Array.isArray(keys)) {
|
|
24500
|
+
throw new Error("vault key file is corrupt: bad keys map");
|
|
24501
|
+
}
|
|
24502
|
+
const map2 = /* @__PURE__ */ new Map();
|
|
24503
|
+
for (const [rawVersion, rawMaterial] of Object.entries(keys)) {
|
|
24504
|
+
const version2 = Number(rawVersion);
|
|
24505
|
+
if (!Number.isInteger(version2) || version2 < 1) {
|
|
24506
|
+
throw new Error("vault key file is corrupt: bad key version");
|
|
24507
|
+
}
|
|
24508
|
+
if (typeof rawMaterial !== "string") {
|
|
24509
|
+
throw new Error("vault key file is corrupt: bad key material");
|
|
24510
|
+
}
|
|
24511
|
+
const bytes = Buffer.from(rawMaterial, "base64");
|
|
24512
|
+
if (bytes.length !== KEY_MATERIAL_BYTES2) {
|
|
24513
|
+
throw new Error("vault key file is corrupt: bad key material length");
|
|
23918
24514
|
}
|
|
24515
|
+
map2.set(version2, bytes);
|
|
23919
24516
|
}
|
|
23920
|
-
|
|
24517
|
+
if (!map2.has(current)) {
|
|
24518
|
+
throw new Error("vault key file is corrupt: current version has no material");
|
|
24519
|
+
}
|
|
24520
|
+
return { current, keys: map2 };
|
|
23921
24521
|
}
|
|
23922
|
-
|
|
23923
|
-
|
|
23924
|
-
|
|
23925
|
-
|
|
23926
|
-
|
|
23927
|
-
const settingsFile = join6(settingsDir(base), "settings.json");
|
|
23928
|
-
if (existsSync4(settingsFile)) tightenFile(settingsFile);
|
|
23929
|
-
} catch {
|
|
24522
|
+
function serializeKeyring(keyring) {
|
|
24523
|
+
const keys = {};
|
|
24524
|
+
for (const version2 of [...keyring.keys.keys()].sort((a, b) => a - b)) {
|
|
24525
|
+
const material = keyring.keys.get(version2);
|
|
24526
|
+
if (material) keys[String(version2)] = material.toString("base64");
|
|
23930
24527
|
}
|
|
23931
|
-
|
|
23932
|
-
const settings = readWorkspaceSettings(base);
|
|
23933
|
-
return {
|
|
23934
|
-
settings,
|
|
23935
|
-
dataDir: dataDir(base),
|
|
23936
|
-
dbPath: dbPath(base),
|
|
23937
|
-
settingsDir: settingsDir(base),
|
|
23938
|
-
onboarded: settings.onboardedAt != null,
|
|
23939
|
-
provider: resolveProviderSafe()
|
|
23940
|
-
};
|
|
24528
|
+
return JSON.stringify({ current: keyring.current, keys });
|
|
23941
24529
|
}
|
|
23942
|
-
function
|
|
24530
|
+
function mintKeyring() {
|
|
24531
|
+
return { current: 1, keys: /* @__PURE__ */ new Map([[1, randomBytes2(KEY_MATERIAL_BYTES2)]]) };
|
|
24532
|
+
}
|
|
24533
|
+
function withNextEpoch(keyring) {
|
|
24534
|
+
const next = Math.max(...keyring.keys.keys()) + 1;
|
|
24535
|
+
const keys = new Map(keyring.keys);
|
|
24536
|
+
keys.set(next, randomBytes2(KEY_MATERIAL_BYTES2));
|
|
24537
|
+
return { current: next, keys };
|
|
24538
|
+
}
|
|
24539
|
+
function currentOf(keyring) {
|
|
24540
|
+
const material = keyring.keys.get(keyring.current);
|
|
24541
|
+
if (!material) throw new VaultKeyEpochMissingError(keyring.current);
|
|
24542
|
+
return { material, version: keyring.current };
|
|
24543
|
+
}
|
|
24544
|
+
function epochOf(keyring, version2) {
|
|
24545
|
+
const material = keyring.keys.get(version2);
|
|
24546
|
+
if (!material) throw new VaultKeyEpochMissingError(version2);
|
|
24547
|
+
return { material, version: version2 };
|
|
24548
|
+
}
|
|
24549
|
+
function asAsync(work) {
|
|
23943
24550
|
try {
|
|
23944
|
-
return
|
|
23945
|
-
} catch {
|
|
23946
|
-
return
|
|
24551
|
+
return Promise.resolve(work());
|
|
24552
|
+
} catch (err) {
|
|
24553
|
+
return Promise.reject(err instanceof Error ? err : new Error(String(err)));
|
|
24554
|
+
}
|
|
24555
|
+
}
|
|
24556
|
+
function asError(err) {
|
|
24557
|
+
return err instanceof Error ? err : new Error(String(err));
|
|
24558
|
+
}
|
|
24559
|
+
var ROTATION_LOCK_STALE_MS = 6e4;
|
|
24560
|
+
var LOCK_OWNER_FILE = "owner";
|
|
24561
|
+
var ROTATION_IN_PROGRESS = "vault: a key rotation is already in progress";
|
|
24562
|
+
function claimRotationLock(lock, owner) {
|
|
24563
|
+
try {
|
|
24564
|
+
mkdirSync2(lock);
|
|
24565
|
+
} catch (err) {
|
|
24566
|
+
if (err.code === "EEXIST") return false;
|
|
24567
|
+
throw asError(err);
|
|
24568
|
+
}
|
|
24569
|
+
try {
|
|
24570
|
+
writeFileSync2(join5(lock, LOCK_OWNER_FILE), `${owner}
|
|
24571
|
+
`, { mode: DATA_FILE_MODE });
|
|
24572
|
+
return true;
|
|
24573
|
+
} catch (err) {
|
|
24574
|
+
rmSync3(lock, { recursive: true, force: true });
|
|
24575
|
+
throw asError(err);
|
|
24576
|
+
}
|
|
24577
|
+
}
|
|
24578
|
+
function acquireRotationLock(keysDir2) {
|
|
24579
|
+
const lock = join5(keysDir2, `${VAULT_KEY_FILENAME}.lock`);
|
|
24580
|
+
const owner = randomBytes2(16).toString("hex");
|
|
24581
|
+
if (claimRotationLock(lock, owner)) return { lock, owner };
|
|
24582
|
+
let held;
|
|
24583
|
+
try {
|
|
24584
|
+
held = statSync(lock);
|
|
24585
|
+
} catch {
|
|
24586
|
+
throw new Error(ROTATION_IN_PROGRESS);
|
|
24587
|
+
}
|
|
24588
|
+
if (Date.now() - held.mtimeMs < ROTATION_LOCK_STALE_MS) throw new Error(ROTATION_IN_PROGRESS);
|
|
24589
|
+
const aside = `${lock}.stale.${owner}`;
|
|
24590
|
+
try {
|
|
24591
|
+
const now = statSync(lock);
|
|
24592
|
+
if (now.ino !== held.ino || now.mtimeMs !== held.mtimeMs) {
|
|
24593
|
+
throw new Error(ROTATION_IN_PROGRESS);
|
|
24594
|
+
}
|
|
24595
|
+
renameSync4(lock, aside);
|
|
24596
|
+
} catch (err) {
|
|
24597
|
+
if (err instanceof Error && err.message === ROTATION_IN_PROGRESS) throw err;
|
|
24598
|
+
throw new Error(ROTATION_IN_PROGRESS, { cause: err });
|
|
24599
|
+
}
|
|
24600
|
+
rmSync3(aside, { recursive: true, force: true });
|
|
24601
|
+
if (!claimRotationLock(lock, owner)) throw new Error(ROTATION_IN_PROGRESS);
|
|
24602
|
+
return { lock, owner };
|
|
24603
|
+
}
|
|
24604
|
+
function releaseRotationLock(lease) {
|
|
24605
|
+
try {
|
|
24606
|
+
if (readFileSync3(join5(lease.lock, LOCK_OWNER_FILE), "utf8").trim() !== lease.owner) return;
|
|
24607
|
+
} catch {
|
|
24608
|
+
return;
|
|
24609
|
+
}
|
|
24610
|
+
rmSync3(lease.lock, { recursive: true, force: true });
|
|
24611
|
+
}
|
|
24612
|
+
function withRotationLock(keysDir2, work) {
|
|
24613
|
+
ensureDataDirSync(keysDir2);
|
|
24614
|
+
const lease = acquireRotationLock(keysDir2);
|
|
24615
|
+
try {
|
|
24616
|
+
return work();
|
|
24617
|
+
} finally {
|
|
24618
|
+
releaseRotationLock(lease);
|
|
24619
|
+
}
|
|
24620
|
+
}
|
|
24621
|
+
var FileKeyProvider = class {
|
|
24622
|
+
#keysDir;
|
|
24623
|
+
constructor(keysDir2) {
|
|
24624
|
+
this.#keysDir = keysDir2;
|
|
24625
|
+
}
|
|
24626
|
+
get filePath() {
|
|
24627
|
+
return join5(this.#keysDir, VAULT_KEY_FILENAME);
|
|
24628
|
+
}
|
|
24629
|
+
loadOrCreate() {
|
|
24630
|
+
return asAsync(() => {
|
|
24631
|
+
const existing = this.#read();
|
|
24632
|
+
if (!existing) return currentOf(this.#createExclusive());
|
|
24633
|
+
tightenFileMode(this.filePath);
|
|
24634
|
+
return currentOf(existing);
|
|
24635
|
+
});
|
|
24636
|
+
}
|
|
24637
|
+
rotate() {
|
|
24638
|
+
return asAsync(
|
|
24639
|
+
() => withRotationLock(this.#keysDir, () => {
|
|
24640
|
+
const existing = this.#read();
|
|
24641
|
+
if (!existing) return currentOf(this.#createExclusive());
|
|
24642
|
+
return currentOf(this.#write(withNextEpoch(existing)));
|
|
24643
|
+
})
|
|
24644
|
+
);
|
|
24645
|
+
}
|
|
24646
|
+
materialFor(version2) {
|
|
24647
|
+
return asAsync(() => {
|
|
24648
|
+
const existing = this.#read();
|
|
24649
|
+
if (!existing) throw new VaultKeyEpochMissingError(version2);
|
|
24650
|
+
return epochOf(existing, version2);
|
|
24651
|
+
});
|
|
24652
|
+
}
|
|
24653
|
+
/** The keyring, or null when the file is ABSENT. A corrupt file throws. */
|
|
24654
|
+
#read() {
|
|
24655
|
+
let raw;
|
|
24656
|
+
try {
|
|
24657
|
+
raw = readFileSync3(this.filePath, "utf8");
|
|
24658
|
+
} catch (err) {
|
|
24659
|
+
if (err.code === "ENOENT") return null;
|
|
24660
|
+
throw err instanceof Error ? err : new Error(String(err));
|
|
24661
|
+
}
|
|
24662
|
+
return parseKeyring(raw);
|
|
24663
|
+
}
|
|
24664
|
+
/**
|
|
24665
|
+
* First mint: the keyring is created at its FINAL path with a
|
|
24666
|
+
* creation-exclusive write, so two processes racing a fresh machine cannot
|
|
24667
|
+
* each mint a different epoch 1 — with tmp + rename the loser's replace
|
|
24668
|
+
* would orphan everything the winner had already sealed. On EEXIST the
|
|
24669
|
+
* loser re-reads and adopts the winner's keyring; it minted nothing.
|
|
24670
|
+
* Atomic replace is unnecessary here: nothing can be mid-read of a file
|
|
24671
|
+
* that did not exist, and a torn exclusive write parses as corrupt on the
|
|
24672
|
+
* next read and fails secure rather than being re-minted over.
|
|
24673
|
+
*/
|
|
24674
|
+
#createExclusive() {
|
|
24675
|
+
ensureDataDirSync(this.#keysDir);
|
|
24676
|
+
const keyring = mintKeyring();
|
|
24677
|
+
try {
|
|
24678
|
+
writeFileSync2(this.filePath, `${serializeKeyring(keyring)}
|
|
24679
|
+
`, {
|
|
24680
|
+
flag: "wx",
|
|
24681
|
+
mode: DATA_FILE_MODE
|
|
24682
|
+
});
|
|
24683
|
+
} catch (err) {
|
|
24684
|
+
if (err.code !== "EEXIST") throw asError(err);
|
|
24685
|
+
const winner = this.#read();
|
|
24686
|
+
if (!winner) {
|
|
24687
|
+
throw new Error("vault: key file vanished during first mint", { cause: err });
|
|
24688
|
+
}
|
|
24689
|
+
return winner;
|
|
24690
|
+
}
|
|
24691
|
+
tightenFileMode(this.filePath);
|
|
24692
|
+
return keyring;
|
|
24693
|
+
}
|
|
24694
|
+
/**
|
|
24695
|
+
* Atomic tmp + rename so a crash mid-write cannot truncate the keyring.
|
|
24696
|
+
* Used only for rotation, under the rotation lock — first creation goes
|
|
24697
|
+
* through the creation-exclusive path instead.
|
|
24698
|
+
*/
|
|
24699
|
+
#write(keyring) {
|
|
24700
|
+
ensureDataDirSync(this.#keysDir);
|
|
24701
|
+
const file2 = this.filePath;
|
|
24702
|
+
const tmp = `${file2}.tmp`;
|
|
24703
|
+
writeFileSync2(tmp, `${serializeKeyring(keyring)}
|
|
24704
|
+
`, { mode: DATA_FILE_MODE });
|
|
24705
|
+
renameSync4(tmp, file2);
|
|
24706
|
+
tightenFileMode(file2);
|
|
24707
|
+
return keyring;
|
|
24708
|
+
}
|
|
24709
|
+
};
|
|
24710
|
+
function tightenFileMode(file2) {
|
|
24711
|
+
try {
|
|
24712
|
+
chmodSync2(file2, DATA_FILE_MODE);
|
|
24713
|
+
} catch {
|
|
24714
|
+
}
|
|
24715
|
+
}
|
|
24716
|
+
var runSecurity = (args) => execFileSync("/usr/bin/security", args, {
|
|
24717
|
+
encoding: "utf8",
|
|
24718
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
24719
|
+
});
|
|
24720
|
+
var SECURITY_ITEM_NOT_FOUND = 44;
|
|
24721
|
+
var KeychainKeyProvider = class {
|
|
24722
|
+
#keysDir;
|
|
24723
|
+
#exec;
|
|
24724
|
+
constructor(keysDir2, exec = runSecurity) {
|
|
24725
|
+
if (exec === runSecurity && process.platform !== "darwin") {
|
|
24726
|
+
throw new Error(
|
|
24727
|
+
`keychain custody is not available on this platform (${process.platform}); use file custody`
|
|
24728
|
+
);
|
|
24729
|
+
}
|
|
24730
|
+
this.#keysDir = keysDir2;
|
|
24731
|
+
this.#exec = exec;
|
|
24732
|
+
}
|
|
24733
|
+
/** Where a fallback file provider for the same vault would keep its keyring. */
|
|
24734
|
+
get keysDir() {
|
|
24735
|
+
return this.#keysDir;
|
|
24736
|
+
}
|
|
24737
|
+
loadOrCreate() {
|
|
24738
|
+
return asAsync(() => {
|
|
24739
|
+
const existing = this.#read();
|
|
24740
|
+
if (existing) return currentOf(existing);
|
|
24741
|
+
return currentOf(this.#create(mintKeyring()));
|
|
24742
|
+
});
|
|
24743
|
+
}
|
|
24744
|
+
rotate() {
|
|
24745
|
+
return asAsync(
|
|
24746
|
+
() => withRotationLock(this.#keysDir, () => {
|
|
24747
|
+
const existing = this.#read();
|
|
24748
|
+
if (!existing) return currentOf(this.#create(mintKeyring()));
|
|
24749
|
+
return currentOf(this.#replace(withNextEpoch(existing)));
|
|
24750
|
+
})
|
|
24751
|
+
);
|
|
24752
|
+
}
|
|
24753
|
+
materialFor(version2) {
|
|
24754
|
+
return asAsync(() => {
|
|
24755
|
+
const existing = this.#read();
|
|
24756
|
+
if (!existing) throw new VaultKeyEpochMissingError(version2);
|
|
24757
|
+
return epochOf(existing, version2);
|
|
24758
|
+
});
|
|
24759
|
+
}
|
|
24760
|
+
/** The keyring, or null when no item exists yet. A corrupt item throws. */
|
|
24761
|
+
#read() {
|
|
24762
|
+
let raw;
|
|
24763
|
+
try {
|
|
24764
|
+
raw = this.#exec([
|
|
24765
|
+
"find-generic-password",
|
|
24766
|
+
"-s",
|
|
24767
|
+
KEYCHAIN_SERVICE,
|
|
24768
|
+
"-a",
|
|
24769
|
+
KEYCHAIN_ACCOUNT,
|
|
24770
|
+
"-w"
|
|
24771
|
+
]);
|
|
24772
|
+
} catch (err) {
|
|
24773
|
+
if (err.status === SECURITY_ITEM_NOT_FOUND) return null;
|
|
24774
|
+
throw new Error(
|
|
24775
|
+
`vault: keychain read failed (${err instanceof Error ? err.message : String(err)}); refusing to treat the failure as an absent keyring`,
|
|
24776
|
+
{ cause: err }
|
|
24777
|
+
);
|
|
24778
|
+
}
|
|
24779
|
+
const body = raw.trim();
|
|
24780
|
+
if (body.length === 0) return null;
|
|
24781
|
+
return parseKeyring(body);
|
|
24782
|
+
}
|
|
24783
|
+
/**
|
|
24784
|
+
* First mint: a plain `add-generic-password` (no `-U`) fails when an item
|
|
24785
|
+
* already exists, so a concurrent first mint cannot overwrite the winner's
|
|
24786
|
+
* keyring — the loser re-reads and adopts it instead.
|
|
24787
|
+
*/
|
|
24788
|
+
#create(keyring) {
|
|
24789
|
+
const args = [
|
|
24790
|
+
"add-generic-password",
|
|
24791
|
+
"-s",
|
|
24792
|
+
KEYCHAIN_SERVICE,
|
|
24793
|
+
"-a",
|
|
24794
|
+
KEYCHAIN_ACCOUNT,
|
|
24795
|
+
"-w",
|
|
24796
|
+
serializeKeyring(keyring)
|
|
24797
|
+
];
|
|
24798
|
+
try {
|
|
24799
|
+
this.#exec(args);
|
|
24800
|
+
} catch (err) {
|
|
24801
|
+
const winner = this.#read();
|
|
24802
|
+
if (winner) return winner;
|
|
24803
|
+
throw asError(err);
|
|
24804
|
+
}
|
|
24805
|
+
return keyring;
|
|
24806
|
+
}
|
|
24807
|
+
// `-U` updates the item in place, deliberately replacing the stored map with
|
|
24808
|
+
// one that contains it — used only for rotation, under the rotation lock.
|
|
24809
|
+
#replace(keyring) {
|
|
24810
|
+
this.#exec([
|
|
24811
|
+
"add-generic-password",
|
|
24812
|
+
"-U",
|
|
24813
|
+
"-s",
|
|
24814
|
+
KEYCHAIN_SERVICE,
|
|
24815
|
+
"-a",
|
|
24816
|
+
KEYCHAIN_ACCOUNT,
|
|
24817
|
+
"-w",
|
|
24818
|
+
serializeKeyring(keyring)
|
|
24819
|
+
]);
|
|
24820
|
+
return keyring;
|
|
24821
|
+
}
|
|
24822
|
+
};
|
|
24823
|
+
function createKeyProvider(custody, keysDir2) {
|
|
24824
|
+
if (custody === "keychain") return new KeychainKeyProvider(keysDir2);
|
|
24825
|
+
return new FileKeyProvider(keysDir2);
|
|
24826
|
+
}
|
|
24827
|
+
|
|
24828
|
+
// ../../packages/persistence/src/vault/vault.ts
|
|
24829
|
+
import { randomBytes as randomBytes3, randomUUID as randomUUID10 } from "crypto";
|
|
24830
|
+
var CONSENT_ABSENT = /* @__PURE__ */ Symbol("aka.vault.consentAbsent");
|
|
24831
|
+
var UNAVAILABLE = /* @__PURE__ */ Symbol("aka.vault.unavailable");
|
|
24832
|
+
var VAULT_PURGE_POINTER_ID = "*";
|
|
24833
|
+
function parsePointer(token) {
|
|
24834
|
+
if (!POINTER_TOKEN_ANCHORED.test(token)) return null;
|
|
24835
|
+
const body = token.slice("[[aka:".length, -"]]".length);
|
|
24836
|
+
const colon = body.indexOf(":");
|
|
24837
|
+
if (colon < 0) return null;
|
|
24838
|
+
const category = body.slice(0, colon);
|
|
24839
|
+
const [kv, id, tag] = body.slice(colon + 1).split(".");
|
|
24840
|
+
if (kv === void 0 || id === void 0 || tag === void 0) return null;
|
|
24841
|
+
try {
|
|
24842
|
+
const keyVersion = decodeKeyVersion(kv);
|
|
24843
|
+
const pointerId = base32Decode(id);
|
|
24844
|
+
const tagBytes = base32Decode(tag);
|
|
24845
|
+
if (encodeKeyVersion(keyVersion) !== kv || base32Encode(pointerId) !== id || base32Encode(tagBytes) !== tag) {
|
|
24846
|
+
return null;
|
|
24847
|
+
}
|
|
24848
|
+
return { category, keyVersion, pointerId, tag: tagBytes };
|
|
24849
|
+
} catch {
|
|
24850
|
+
return null;
|
|
24851
|
+
}
|
|
24852
|
+
}
|
|
24853
|
+
var SecretVault = class {
|
|
24854
|
+
#repo;
|
|
24855
|
+
#keys;
|
|
24856
|
+
#fingerprintKey;
|
|
24857
|
+
#isConsented;
|
|
24858
|
+
#verifyGrant;
|
|
24859
|
+
#now;
|
|
24860
|
+
constructor(deps) {
|
|
24861
|
+
this.#repo = deps.repo;
|
|
24862
|
+
this.#keys = deps.keys;
|
|
24863
|
+
this.#fingerprintKey = deps.fingerprintKey;
|
|
24864
|
+
this.#isConsented = deps.isConsented;
|
|
24865
|
+
this.#verifyGrant = deps.verifyGrant;
|
|
24866
|
+
this.#now = deps.now ?? (() => Date.now());
|
|
24867
|
+
}
|
|
24868
|
+
/**
|
|
24869
|
+
* Store a value and return the pointer that stands for it. The same value
|
|
24870
|
+
* always yields the same pointer on this machine — one row, one pointer id,
|
|
24871
|
+
* one category — which is what makes dedup and reuse counting work.
|
|
24872
|
+
*/
|
|
24873
|
+
async tokenize(raw, meta3) {
|
|
24874
|
+
if (!this.#isConsented()) return CONSENT_ABSENT;
|
|
24875
|
+
const valueFingerprint = fingerprintValue(this.#fingerprintKey, raw);
|
|
24876
|
+
const existing = this.#repo.byValueFingerprint(valueFingerprint);
|
|
24877
|
+
const now = this.#now();
|
|
24878
|
+
if (existing) {
|
|
24879
|
+
this.#repo.upsert({ ...existing, provider: existing.provider ?? void 0 }, now);
|
|
24880
|
+
return await this.#emitToken(existing.keyVersion, existing.pointerId, existing.category);
|
|
24881
|
+
}
|
|
24882
|
+
const { material, version: version2 } = await this.#keys.loadOrCreate();
|
|
24883
|
+
const subkeys = deriveSubkeys(material);
|
|
24884
|
+
const pointerId = randomBytes3(POINTER_ID_BYTES);
|
|
24885
|
+
const aad = bindingInput(version2, pointerId, meta3.category, POINTER_FORMAT_VERSION);
|
|
24886
|
+
const sealed = seal(subkeys.enc, raw, aad, randomBytes3(NONCE_BYTES));
|
|
24887
|
+
const { row } = this.#repo.upsert(
|
|
24888
|
+
{
|
|
24889
|
+
pointerId: base32Encode(pointerId),
|
|
24890
|
+
valueFingerprint,
|
|
24891
|
+
fingerprintKeyVersion: this.#fingerprintKey.version,
|
|
24892
|
+
keyVersion: version2,
|
|
24893
|
+
// Recorded so the row stays OPENABLE if the wire-format constant ever
|
|
24894
|
+
// moves: it is part of this row's AEAD AAD. It is not a tag input —
|
|
24895
|
+
// tags are pinned to the constant on both sides.
|
|
24896
|
+
formatVersion: POINTER_FORMAT_VERSION,
|
|
24897
|
+
category: meta3.category,
|
|
24898
|
+
ruleId: meta3.ruleId,
|
|
24899
|
+
maskedMatch: meta3.maskedMatch,
|
|
24900
|
+
provider: meta3.provider,
|
|
24901
|
+
ciphertext: sealed.ciphertext.toString("base64"),
|
|
24902
|
+
nonce: sealed.nonce.toString("base64"),
|
|
24903
|
+
authTag: sealed.authTag.toString("base64")
|
|
24904
|
+
},
|
|
24905
|
+
now
|
|
24906
|
+
);
|
|
24907
|
+
return await this.#emitToken(row.keyVersion, row.pointerId, row.category);
|
|
24908
|
+
}
|
|
24909
|
+
/**
|
|
24910
|
+
* Resolve a pointer back to its value, for a human or (with a grant) for the
|
|
24911
|
+
* model. Every call that gets as far as an identified row writes an audit row.
|
|
24912
|
+
*/
|
|
24913
|
+
async detokenize(token, opts) {
|
|
24914
|
+
const parsed = parsePointer(token);
|
|
24915
|
+
if (!parsed) return UNAVAILABLE;
|
|
24916
|
+
let signKey;
|
|
24917
|
+
try {
|
|
24918
|
+
const epoch = await this.#keys.materialFor(parsed.keyVersion);
|
|
24919
|
+
signKey = deriveSubkeys(epoch.material).sign;
|
|
24920
|
+
} catch {
|
|
24921
|
+
return UNAVAILABLE;
|
|
24922
|
+
}
|
|
24923
|
+
if (!verifyPointerTag(signKey, parsed.keyVersion, parsed.pointerId, parsed.category, parsed.tag)) {
|
|
24924
|
+
return UNAVAILABLE;
|
|
24925
|
+
}
|
|
24926
|
+
const pointerId = base32Encode(parsed.pointerId);
|
|
24927
|
+
const row = this.#repo.byPointerId(pointerId);
|
|
24928
|
+
if (!row) {
|
|
24929
|
+
this.#audit(pointerId, opts, "unavailable");
|
|
24930
|
+
return UNAVAILABLE;
|
|
24931
|
+
}
|
|
24932
|
+
if (row.category !== parsed.category) return UNAVAILABLE;
|
|
24933
|
+
if (opts.target === "model") {
|
|
24934
|
+
const grantId = opts.grantId;
|
|
24935
|
+
const verify = this.#verifyGrant;
|
|
24936
|
+
if (verify === void 0 || grantId === void 0 || grantId === "") {
|
|
24937
|
+
this.#audit(pointerId, opts, "refused");
|
|
24938
|
+
return UNAVAILABLE;
|
|
24939
|
+
}
|
|
24940
|
+
let covered;
|
|
24941
|
+
try {
|
|
24942
|
+
covered = await verify(grantId, {
|
|
24943
|
+
ruleId: row.ruleId,
|
|
24944
|
+
valueFingerprint: row.valueFingerprint,
|
|
24945
|
+
fingerprintKeyVersion: row.fingerprintKeyVersion
|
|
24946
|
+
});
|
|
24947
|
+
} catch {
|
|
24948
|
+
covered = false;
|
|
24949
|
+
}
|
|
24950
|
+
if (!covered) {
|
|
24951
|
+
this.#audit(pointerId, opts, "refused");
|
|
24952
|
+
return UNAVAILABLE;
|
|
24953
|
+
}
|
|
24954
|
+
}
|
|
24955
|
+
let raw;
|
|
24956
|
+
try {
|
|
24957
|
+
const epoch = await this.#keys.materialFor(row.keyVersion);
|
|
24958
|
+
raw = open(
|
|
24959
|
+
deriveSubkeys(epoch.material).enc,
|
|
24960
|
+
{
|
|
24961
|
+
ciphertext: Buffer.from(row.ciphertext, "base64"),
|
|
24962
|
+
nonce: Buffer.from(row.nonce, "base64"),
|
|
24963
|
+
authTag: Buffer.from(row.authTag, "base64")
|
|
24964
|
+
},
|
|
24965
|
+
// Sealed under the ROW's epoch and format version. Rotation may have
|
|
24966
|
+
// moved the epoch past the one this token names, and a format bump may
|
|
24967
|
+
// have moved the constant past the generation this row was sealed
|
|
24968
|
+
// under — the AAD follows the row in both cases, never the token.
|
|
24969
|
+
bindingInput(row.keyVersion, parsed.pointerId, row.category, row.formatVersion)
|
|
24970
|
+
);
|
|
24971
|
+
} catch {
|
|
24972
|
+
raw = null;
|
|
24973
|
+
}
|
|
24974
|
+
if (raw === null) {
|
|
24975
|
+
this.#audit(pointerId, opts, "unavailable");
|
|
24976
|
+
return UNAVAILABLE;
|
|
24977
|
+
}
|
|
24978
|
+
this.#audit(pointerId, opts, "revealed");
|
|
24979
|
+
return raw;
|
|
24980
|
+
}
|
|
24981
|
+
/**
|
|
24982
|
+
* Owner-surface reveal by row id: the dashboard shows a row the owner can
|
|
24983
|
+
* already see and asks for its value. There is no wire token here to verify —
|
|
24984
|
+
* the tag exists to stop FORGED tokens arriving in untrusted text, and a row
|
|
24985
|
+
* id selected server-side from the owner's own store is not that — so this
|
|
24986
|
+
* loads the row directly, opens its ciphertext under the row's epoch, and
|
|
24987
|
+
* audits exactly like a human-target de-reference. Never callable with
|
|
24988
|
+
* target 'model': the wire-token path with its grant gate is the only road
|
|
24989
|
+
* raw travels toward the model.
|
|
24990
|
+
*/
|
|
24991
|
+
async revealEntry(pointerId, opts) {
|
|
24992
|
+
const row = this.#repo.byPointerId(pointerId);
|
|
24993
|
+
if (!row) {
|
|
24994
|
+
this.#audit(pointerId, { target: "human", reason: opts.reason }, "unavailable");
|
|
24995
|
+
return UNAVAILABLE;
|
|
24996
|
+
}
|
|
24997
|
+
const raw = await this.#openRow(row);
|
|
24998
|
+
if (raw === null) {
|
|
24999
|
+
this.#audit(pointerId, { target: "human", reason: opts.reason }, "unavailable");
|
|
25000
|
+
return UNAVAILABLE;
|
|
25001
|
+
}
|
|
25002
|
+
this.#audit(pointerId, { target: "human", reason: opts.reason }, "revealed");
|
|
25003
|
+
return raw;
|
|
25004
|
+
}
|
|
25005
|
+
/** Badge and listing data. No raw value, no fingerprint, and no audit row. */
|
|
25006
|
+
async describePointer(token) {
|
|
25007
|
+
const row = await this.#rowFor(token);
|
|
25008
|
+
if (!row) return null;
|
|
25009
|
+
return {
|
|
25010
|
+
category: row.category,
|
|
25011
|
+
...row.provider === void 0 ? {} : { provider: row.provider },
|
|
25012
|
+
maskedMatch: row.maskedMatch,
|
|
25013
|
+
occurrences: row.occurrenceCount,
|
|
25014
|
+
firstSeen: new Date(row.firstSeen).toISOString(),
|
|
25015
|
+
lastSeen: new Date(row.lastSeen).toISOString()
|
|
25016
|
+
};
|
|
25017
|
+
}
|
|
25018
|
+
/**
|
|
25019
|
+
* The raw-free row identity a reveal grant matches on. Deliberately not fed to
|
|
25020
|
+
* view surfaces: the keyed fingerprint is a correlation key and must not reach
|
|
25021
|
+
* a presentation layer.
|
|
25022
|
+
*/
|
|
25023
|
+
async resolvePointerIdentity(token) {
|
|
25024
|
+
const row = await this.#rowFor(token);
|
|
25025
|
+
if (!row) return null;
|
|
25026
|
+
return {
|
|
25027
|
+
ruleId: row.ruleId,
|
|
25028
|
+
valueFingerprint: row.valueFingerprint,
|
|
25029
|
+
fingerprintKeyVersion: row.fingerprintKeyVersion
|
|
25030
|
+
};
|
|
25031
|
+
}
|
|
25032
|
+
/**
|
|
25033
|
+
* Mint the next vault key epoch and re-encrypt every entry under it. Pointers
|
|
25034
|
+
* already emitted keep verifying: their tag is checked against the historical
|
|
25035
|
+
* epoch they name, which the key provider retains.
|
|
25036
|
+
*
|
|
25037
|
+
* Safe to interrupt — each row carries the epoch its ciphertext is sealed
|
|
25038
|
+
* under, so a half-finished pass leaves every row openable.
|
|
25039
|
+
*
|
|
25040
|
+
* The rotation lock covers only the keyring mint inside `rotate()`; the
|
|
25041
|
+
* re-seal pass below runs unlocked. Two concurrent rotations therefore
|
|
25042
|
+
* serialize on the keyring but interleave over the rows, so a slower pass can
|
|
25043
|
+
* re-seal a row back to an epoch a faster one already moved past, and
|
|
25044
|
+
* `reEncrypted` can double-count. No value is lost either way — every epoch is
|
|
25045
|
+
* retained and every row stays openable — but "after rotation every row sits
|
|
25046
|
+
* at the newest epoch" does not hold under concurrency. Holding the lock
|
|
25047
|
+
* across the whole pass requires an async-aware lock, since a callback that
|
|
25048
|
+
* awaits would release the lock at its first suspension.
|
|
25049
|
+
*/
|
|
25050
|
+
async rotateVaultKey() {
|
|
25051
|
+
const next = await this.#keys.rotate();
|
|
25052
|
+
const nextEnc = deriveSubkeys(next.material).enc;
|
|
25053
|
+
let reEncrypted = 0;
|
|
25054
|
+
for (const row of this.#repo.listAll()) {
|
|
25055
|
+
if (row.keyVersion === next.version) continue;
|
|
25056
|
+
const pointerId = base32Decode(row.pointerId);
|
|
25057
|
+
let raw;
|
|
25058
|
+
try {
|
|
25059
|
+
const epoch = await this.#keys.materialFor(row.keyVersion);
|
|
25060
|
+
raw = open(
|
|
25061
|
+
deriveSubkeys(epoch.material).enc,
|
|
25062
|
+
{
|
|
25063
|
+
ciphertext: Buffer.from(row.ciphertext, "base64"),
|
|
25064
|
+
nonce: Buffer.from(row.nonce, "base64"),
|
|
25065
|
+
authTag: Buffer.from(row.authTag, "base64")
|
|
25066
|
+
},
|
|
25067
|
+
bindingInput(row.keyVersion, pointerId, row.category, row.formatVersion)
|
|
25068
|
+
);
|
|
25069
|
+
} catch {
|
|
25070
|
+
raw = null;
|
|
25071
|
+
}
|
|
25072
|
+
if (raw === null) continue;
|
|
25073
|
+
const sealed = seal(
|
|
25074
|
+
nextEnc,
|
|
25075
|
+
raw,
|
|
25076
|
+
bindingInput(next.version, pointerId, row.category, row.formatVersion),
|
|
25077
|
+
randomBytes3(NONCE_BYTES)
|
|
25078
|
+
);
|
|
25079
|
+
this.#repo.replaceCiphertext(row.pointerId, {
|
|
25080
|
+
keyVersion: next.version,
|
|
25081
|
+
ciphertext: sealed.ciphertext.toString("base64"),
|
|
25082
|
+
nonce: sealed.nonce.toString("base64"),
|
|
25083
|
+
authTag: sealed.authTag.toString("base64")
|
|
25084
|
+
});
|
|
25085
|
+
reEncrypted += 1;
|
|
25086
|
+
}
|
|
25087
|
+
return { version: next.version, reEncrypted };
|
|
25088
|
+
}
|
|
25089
|
+
/**
|
|
25090
|
+
* Re-key every entry's value fingerprint after the exception key rotates,
|
|
25091
|
+
* PRESERVING each pointer id. Unlike grants — where rotation is invalidation,
|
|
25092
|
+
* because the raw values are gone — the vault still holds the values, so
|
|
25093
|
+
* determinism, dedup, and every outstanding pointer survive the rotation.
|
|
25094
|
+
*
|
|
25095
|
+
* Every fingerprint-key rotation must run this: a row left at the old epoch
|
|
25096
|
+
* still resolves, but the same value detected again fingerprints under the
|
|
25097
|
+
* NEW key, misses the dedup lookup, and mints a second row and a second
|
|
25098
|
+
* pointer — one value, two tokens in circulation.
|
|
25099
|
+
*
|
|
25100
|
+
* Per-row best-effort: a row that cannot open, or whose refreshed
|
|
25101
|
+
* fingerprint collides with a row already refreshed, is skipped rather than
|
|
25102
|
+
* aborting the pass — one damaged entry must not strand the re-key of every
|
|
25103
|
+
* other. A skipped row keeps resolving under its old fingerprint epoch.
|
|
25104
|
+
*/
|
|
25105
|
+
async refreshFingerprints(next) {
|
|
25106
|
+
let refreshed = 0;
|
|
25107
|
+
for (const row of this.#repo.listAll()) {
|
|
25108
|
+
try {
|
|
25109
|
+
const raw = await this.#openRow(row);
|
|
25110
|
+
if (raw === null) continue;
|
|
25111
|
+
this.#repo.refreshFingerprint(row.pointerId, {
|
|
25112
|
+
valueFingerprint: fingerprintValue(next, raw),
|
|
25113
|
+
fingerprintKeyVersion: next.version
|
|
25114
|
+
});
|
|
25115
|
+
refreshed += 1;
|
|
25116
|
+
} catch {
|
|
25117
|
+
continue;
|
|
25118
|
+
}
|
|
25119
|
+
}
|
|
25120
|
+
return refreshed;
|
|
25121
|
+
}
|
|
25122
|
+
/**
|
|
25123
|
+
* Destroy every entry, making all outstanding pointers permanently
|
|
25124
|
+
* unresolvable.
|
|
25125
|
+
*
|
|
25126
|
+
* The count comes from `purgeAll` rather than a separate `countEntries` —
|
|
25127
|
+
* `purgeAll` counts inside the same transaction that deletes, so the audit row
|
|
25128
|
+
* reports what was actually destroyed. Counting beforehand would let a
|
|
25129
|
+
* concurrent write land between the two statements and put a number in the
|
|
25130
|
+
* durable record that never matched reality.
|
|
25131
|
+
*/
|
|
25132
|
+
purgeVault() {
|
|
25133
|
+
const destroyed = this.#repo.purgeAll();
|
|
25134
|
+
this.#repo.recordDeref({
|
|
25135
|
+
id: randomUUID10(),
|
|
25136
|
+
pointerId: VAULT_PURGE_POINTER_ID,
|
|
25137
|
+
at: this.#now(),
|
|
25138
|
+
target: "human",
|
|
25139
|
+
reason: "purge",
|
|
25140
|
+
outcome: "unavailable",
|
|
25141
|
+
pointerCount: Math.max(destroyed, 1)
|
|
25142
|
+
});
|
|
25143
|
+
return destroyed;
|
|
25144
|
+
}
|
|
25145
|
+
// Sign under the epoch the token names — which for a re-detected value is the
|
|
25146
|
+
// epoch its row currently sits at rather than whatever is current.
|
|
25147
|
+
//
|
|
25148
|
+
// The row's format version is NOT a tag input. It binds the row's ciphertext
|
|
25149
|
+
// (it is part of the AEAD AAD, so an old row stays openable) but never the
|
|
25150
|
+
// wire tag, which verification checks against POINTER_FORMAT_VERSION without
|
|
25151
|
+
// knowing any row. Signing a token here under a row's own generation is what
|
|
25152
|
+
// would make the vault emit tokens it then refuses.
|
|
25153
|
+
async #emitToken(keyVersion, pointerIdB32, category) {
|
|
25154
|
+
const pointerId = base32Decode(pointerIdB32);
|
|
25155
|
+
const epoch = await this.#keys.materialFor(keyVersion);
|
|
25156
|
+
const signKey = deriveSubkeys(epoch.material).sign;
|
|
25157
|
+
return formatPointer(
|
|
25158
|
+
category,
|
|
25159
|
+
keyVersion,
|
|
25160
|
+
pointerId,
|
|
25161
|
+
signPointer(signKey, keyVersion, pointerId, category)
|
|
25162
|
+
);
|
|
25163
|
+
}
|
|
25164
|
+
async #openRow(row) {
|
|
25165
|
+
try {
|
|
25166
|
+
const epoch = await this.#keys.materialFor(row.keyVersion);
|
|
25167
|
+
return open(
|
|
25168
|
+
deriveSubkeys(epoch.material).enc,
|
|
25169
|
+
{
|
|
25170
|
+
ciphertext: Buffer.from(row.ciphertext, "base64"),
|
|
25171
|
+
nonce: Buffer.from(row.nonce, "base64"),
|
|
25172
|
+
authTag: Buffer.from(row.authTag, "base64")
|
|
25173
|
+
},
|
|
25174
|
+
bindingInput(row.keyVersion, base32Decode(row.pointerId), row.category, row.formatVersion)
|
|
25175
|
+
);
|
|
25176
|
+
} catch {
|
|
25177
|
+
return null;
|
|
25178
|
+
}
|
|
25179
|
+
}
|
|
25180
|
+
// Shared lookup for the read-only surfaces. It verifies the tag exactly as
|
|
25181
|
+
// detokenize does: a descriptor is not raw, but a token nobody can vouch for
|
|
25182
|
+
// should not resolve to anything at all — otherwise a fabricated pointer, or a
|
|
25183
|
+
// lookalike planted in a file, would still yield a category and a masked
|
|
25184
|
+
// preview. Verifying needs the historical epoch's key, which is why these
|
|
25185
|
+
// surfaces are async.
|
|
25186
|
+
async #rowFor(token) {
|
|
25187
|
+
const parsed = parsePointer(token);
|
|
25188
|
+
if (!parsed) return null;
|
|
25189
|
+
try {
|
|
25190
|
+
const epoch = await this.#keys.materialFor(parsed.keyVersion);
|
|
25191
|
+
const signKey = deriveSubkeys(epoch.material).sign;
|
|
25192
|
+
if (!verifyPointerTag(signKey, parsed.keyVersion, parsed.pointerId, parsed.category, parsed.tag)) {
|
|
25193
|
+
return null;
|
|
25194
|
+
}
|
|
25195
|
+
} catch {
|
|
25196
|
+
return null;
|
|
25197
|
+
}
|
|
25198
|
+
const row = this.#repo.byPointerId(base32Encode(parsed.pointerId));
|
|
25199
|
+
if (row?.category !== parsed.category) return null;
|
|
25200
|
+
return row;
|
|
25201
|
+
}
|
|
25202
|
+
#audit(pointerId, opts, outcome) {
|
|
25203
|
+
this.#repo.recordDeref({
|
|
25204
|
+
id: randomUUID10(),
|
|
25205
|
+
pointerId,
|
|
25206
|
+
at: this.#now(),
|
|
25207
|
+
target: opts.target,
|
|
25208
|
+
reason: opts.reason,
|
|
25209
|
+
outcome,
|
|
25210
|
+
...opts.grantId === void 0 ? {} : { grantId: opts.grantId },
|
|
25211
|
+
// Only the batched reasons carry a count above one; a model crossing is
|
|
25212
|
+
// always its own row.
|
|
25213
|
+
pointerCount: isBatchedDerefReason(opts.reason) ? opts.pointerCount ?? 1 : 1
|
|
25214
|
+
});
|
|
25215
|
+
}
|
|
25216
|
+
};
|
|
25217
|
+
|
|
25218
|
+
// ../../packages/persistence/src/warn-era-cap.ts
|
|
25219
|
+
import { existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
|
|
25220
|
+
import { join as join6 } from "path";
|
|
25221
|
+
var MARKER = "warn-era-capped";
|
|
25222
|
+
function capWarnEraEnforcementOnce(db, policyMode, dataDir2) {
|
|
25223
|
+
if (policyMode !== "warn") return { capped: 0, skipped: "not-warn" };
|
|
25224
|
+
const marker = join6(dataDir2, MARKER);
|
|
25225
|
+
if (existsSync3(marker)) return { capped: 0, skipped: "already-run" };
|
|
25226
|
+
const capped = db.policies.capCategoryActions();
|
|
25227
|
+
writeFileSync3(marker, `${new Date(Date.now()).toISOString()}
|
|
25228
|
+
`, { mode: DATA_FILE_MODE });
|
|
25229
|
+
return { capped };
|
|
25230
|
+
}
|
|
25231
|
+
|
|
25232
|
+
// ../../packages/plugin-sdk/src/provider-env.ts
|
|
25233
|
+
var DEFAULT_ANTHROPIC_HOST = "api.anthropic.com";
|
|
25234
|
+
var booleanish = external_exports.string().optional().transform((v) => {
|
|
25235
|
+
if (v === void 0) return void 0;
|
|
25236
|
+
const t = v.trim().toLowerCase();
|
|
25237
|
+
if (t === "" || t === "false" || t === "0") return false;
|
|
25238
|
+
return true;
|
|
25239
|
+
}).catch(void 0);
|
|
25240
|
+
var optionalBaseUrl = external_exports.preprocess((v) => {
|
|
25241
|
+
if (typeof v === "string" && v.trim() === "") return void 0;
|
|
25242
|
+
return v;
|
|
25243
|
+
}, external_exports.string().optional()).catch(void 0);
|
|
25244
|
+
var providerEnvShape = {
|
|
25245
|
+
CLAUDE_CODE_USE_BEDROCK: booleanish,
|
|
25246
|
+
CLAUDE_CODE_USE_VERTEX: booleanish,
|
|
25247
|
+
ANTHROPIC_BASE_URL: optionalBaseUrl
|
|
25248
|
+
};
|
|
25249
|
+
var ProviderEnvSchema = external_exports.object(providerEnvShape);
|
|
25250
|
+
|
|
25251
|
+
// ../../packages/plugin-sdk/src/provider.ts
|
|
25252
|
+
function hostOf(url2) {
|
|
25253
|
+
try {
|
|
25254
|
+
const host = new URL(url2).host;
|
|
25255
|
+
if (host !== "") return host;
|
|
25256
|
+
} catch {
|
|
25257
|
+
}
|
|
25258
|
+
try {
|
|
25259
|
+
const host = new URL(`https://${url2}`).host;
|
|
25260
|
+
return host !== "" ? host : void 0;
|
|
25261
|
+
} catch {
|
|
25262
|
+
return void 0;
|
|
25263
|
+
}
|
|
25264
|
+
}
|
|
25265
|
+
function resolveProvider() {
|
|
25266
|
+
const parsed = ProviderEnvSchema.safeParse(process.env);
|
|
25267
|
+
const env = parsed.success ? parsed.data : ProviderEnvSchema.parse({});
|
|
25268
|
+
if (env.CLAUDE_CODE_USE_BEDROCK === true) return { provider: "bedrock" };
|
|
25269
|
+
if (env.CLAUDE_CODE_USE_VERTEX === true) return { provider: "vertex" };
|
|
25270
|
+
const baseUrl = env.ANTHROPIC_BASE_URL;
|
|
25271
|
+
if (baseUrl !== void 0 && baseUrl !== "") {
|
|
25272
|
+
const host = hostOf(baseUrl);
|
|
25273
|
+
if (host !== void 0 && host !== DEFAULT_ANTHROPIC_HOST) {
|
|
25274
|
+
return { provider: "gateway", gatewayHost: host };
|
|
25275
|
+
}
|
|
25276
|
+
}
|
|
25277
|
+
return { provider: "anthropic" };
|
|
25278
|
+
}
|
|
25279
|
+
|
|
25280
|
+
// ../../packages/plugin-sdk/src/config.ts
|
|
25281
|
+
function loadConfig(base = defaultDataDir()) {
|
|
25282
|
+
try {
|
|
25283
|
+
ensureLayoutDirSync(base);
|
|
25284
|
+
const settingsFile = join7(settingsDir(base), "settings.json");
|
|
25285
|
+
if (existsSync4(settingsFile)) tightenFile(settingsFile);
|
|
25286
|
+
} catch {
|
|
25287
|
+
}
|
|
25288
|
+
migrateLegacyLayout(base);
|
|
25289
|
+
const settings = readWorkspaceSettings(base);
|
|
25290
|
+
return {
|
|
25291
|
+
settings,
|
|
25292
|
+
dataDir: dataDir(base),
|
|
25293
|
+
dbPath: dbPath(base),
|
|
25294
|
+
settingsDir: settingsDir(base),
|
|
25295
|
+
onboarded: settings.onboardedAt != null,
|
|
25296
|
+
provider: resolveProviderSafe()
|
|
25297
|
+
};
|
|
25298
|
+
}
|
|
25299
|
+
function resolveProviderSafe() {
|
|
25300
|
+
try {
|
|
25301
|
+
return resolveProvider();
|
|
25302
|
+
} catch {
|
|
25303
|
+
return { provider: "anthropic" };
|
|
23947
25304
|
}
|
|
23948
25305
|
}
|
|
23949
25306
|
|
|
23950
25307
|
// ../../packages/plugin-sdk/src/config-inventory.ts
|
|
23951
|
-
import { readdirSync, readFileSync as
|
|
25308
|
+
import { readdirSync, readFileSync as readFileSync5, realpathSync, statSync as statSync3 } from "fs";
|
|
23952
25309
|
import { homedir as homedir2 } from "os";
|
|
23953
|
-
import { basename as basename2, join as
|
|
25310
|
+
import { basename as basename2, join as join9 } from "path";
|
|
23954
25311
|
|
|
23955
25312
|
// ../../packages/detections/src/egress/registry.ts
|
|
23956
25313
|
var EXTRACTOR_VERSION = "1";
|
|
@@ -24738,12 +26095,12 @@ function redact(text, findings) {
|
|
|
24738
26095
|
const regions = [];
|
|
24739
26096
|
for (const f of sorted) {
|
|
24740
26097
|
const rank = SEVERITY_RANK2[f.severity];
|
|
24741
|
-
const
|
|
24742
|
-
if (
|
|
24743
|
-
|
|
24744
|
-
if (rank >
|
|
24745
|
-
|
|
24746
|
-
|
|
26098
|
+
const open2 = regions[regions.length - 1];
|
|
26099
|
+
if (open2 && f.span.start < open2.end) {
|
|
26100
|
+
open2.end = Math.max(open2.end, f.span.end);
|
|
26101
|
+
if (rank > open2.rank) {
|
|
26102
|
+
open2.rank = rank;
|
|
26103
|
+
open2.category = f.category;
|
|
24747
26104
|
}
|
|
24748
26105
|
} else {
|
|
24749
26106
|
regions.push({ start: f.span.start, end: f.span.end, category: f.category, rank });
|
|
@@ -24772,6 +26129,24 @@ function maskMatch(raw) {
|
|
|
24772
26129
|
return `${raw.charAt(0)}${"*".repeat(6)}${raw.charAt(raw.length - 1)}`;
|
|
24773
26130
|
}
|
|
24774
26131
|
|
|
26132
|
+
// ../../packages/detections/src/pointer-shield.ts
|
|
26133
|
+
function shieldPointers(text) {
|
|
26134
|
+
const spans = [];
|
|
26135
|
+
let out = null;
|
|
26136
|
+
for (const match of text.matchAll(pointerTokenScanner())) {
|
|
26137
|
+
spans.push({ start: match.index, end: match.index + match[0].length });
|
|
26138
|
+
out ??= text;
|
|
26139
|
+
out = out.slice(0, match.index) + " ".repeat(match[0].length) + out.slice(match.index + match[0].length);
|
|
26140
|
+
}
|
|
26141
|
+
return { text: out ?? text, spans };
|
|
26142
|
+
}
|
|
26143
|
+
function dropShieldedFindings(findings, spans) {
|
|
26144
|
+
if (spans.length === 0) return findings;
|
|
26145
|
+
return findings.filter(
|
|
26146
|
+
(finding) => !spans.some((s) => finding.span.start < s.end && finding.span.end > s.start)
|
|
26147
|
+
);
|
|
26148
|
+
}
|
|
26149
|
+
|
|
24775
26150
|
// ../../packages/detections/src/posture/config-posture.ts
|
|
24776
26151
|
var RULE_VERSION = "1";
|
|
24777
26152
|
var KNOWN_TOOLS = /* @__PURE__ */ new Set([
|
|
@@ -26971,8 +28346,8 @@ function uniqueRuleIds(findings) {
|
|
|
26971
28346
|
}
|
|
26972
28347
|
|
|
26973
28348
|
// ../../packages/plugin-sdk/src/repo.ts
|
|
26974
|
-
import { existsSync as existsSync5, readFileSync as
|
|
26975
|
-
import { basename, dirname, isAbsolute, join as
|
|
28349
|
+
import { existsSync as existsSync5, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
|
|
28350
|
+
import { basename, dirname, isAbsolute, join as join8, sep as sep2 } from "path";
|
|
26976
28351
|
function resolveRepo(cwd) {
|
|
26977
28352
|
try {
|
|
26978
28353
|
const root = findGitRoot(cwd);
|
|
@@ -26987,36 +28362,36 @@ function resolveRepo(cwd) {
|
|
|
26987
28362
|
function findGitRoot(start) {
|
|
26988
28363
|
let dir = start;
|
|
26989
28364
|
for (; ; ) {
|
|
26990
|
-
if (existsSync5(
|
|
28365
|
+
if (existsSync5(join8(dir, ".git"))) return dir;
|
|
26991
28366
|
const parent = dirname(dir);
|
|
26992
28367
|
if (parent === dir) return void 0;
|
|
26993
28368
|
dir = parent;
|
|
26994
28369
|
}
|
|
26995
28370
|
}
|
|
26996
28371
|
function resolveGitContext(root) {
|
|
26997
|
-
const dotGit =
|
|
28372
|
+
const dotGit = join8(root, ".git");
|
|
26998
28373
|
try {
|
|
26999
|
-
if (
|
|
27000
|
-
return { configPath:
|
|
28374
|
+
if (statSync2(dotGit).isDirectory()) {
|
|
28375
|
+
return { configPath: join8(dotGit, "config"), headRoot: root };
|
|
27001
28376
|
}
|
|
27002
28377
|
} catch {
|
|
27003
28378
|
return void 0;
|
|
27004
28379
|
}
|
|
27005
28380
|
const target = /^gitdir:\s*(.+?)\s*$/m.exec(safeRead(dotGit) ?? "")?.[1];
|
|
27006
28381
|
if (!target) return void 0;
|
|
27007
|
-
const gitdir = isAbsolute(target) ? target :
|
|
27008
|
-
if (existsSync5(
|
|
27009
|
-
return { configPath:
|
|
28382
|
+
const gitdir = isAbsolute(target) ? target : join8(root, target);
|
|
28383
|
+
if (existsSync5(join8(gitdir, "config"))) {
|
|
28384
|
+
return { configPath: join8(gitdir, "config"), headRoot: root };
|
|
27010
28385
|
}
|
|
27011
|
-
const commonRaw = safeRead(
|
|
28386
|
+
const commonRaw = safeRead(join8(gitdir, "commondir"))?.trim();
|
|
27012
28387
|
if (!commonRaw) return void 0;
|
|
27013
|
-
const commonGitDir = isAbsolute(commonRaw) ? commonRaw :
|
|
28388
|
+
const commonGitDir = isAbsolute(commonRaw) ? commonRaw : join8(gitdir, commonRaw);
|
|
27014
28389
|
const headRoot = basename(commonGitDir) === ".git" ? dirname(commonGitDir) : root;
|
|
27015
|
-
return { configPath:
|
|
28390
|
+
return { configPath: join8(commonGitDir, "config"), headRoot };
|
|
27016
28391
|
}
|
|
27017
28392
|
function safeRead(path) {
|
|
27018
28393
|
try {
|
|
27019
|
-
return
|
|
28394
|
+
return readFileSync4(path, "utf8");
|
|
27020
28395
|
} catch {
|
|
27021
28396
|
return void 0;
|
|
27022
28397
|
}
|
|
@@ -27054,13 +28429,13 @@ function slugFromUrl(url2) {
|
|
|
27054
28429
|
}
|
|
27055
28430
|
|
|
27056
28431
|
// ../../packages/plugin-sdk/src/events.ts
|
|
27057
|
-
import { createHash as createHash4, randomUUID as
|
|
28432
|
+
import { createHash as createHash4, randomUUID as randomUUID11 } from "crypto";
|
|
27058
28433
|
function contentHashOf(text) {
|
|
27059
28434
|
return createHash4("sha256").update(text).digest("hex");
|
|
27060
28435
|
}
|
|
27061
28436
|
function buildIngestEvent(input) {
|
|
27062
28437
|
return {
|
|
27063
|
-
id:
|
|
28438
|
+
id: randomUUID11(),
|
|
27064
28439
|
sourceTool: input.sourceTool,
|
|
27065
28440
|
kind: input.kind,
|
|
27066
28441
|
occurredAt: input.occurredAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -27071,7 +28446,7 @@ function buildIngestEvent(input) {
|
|
|
27071
28446
|
// SDK boot in the fail-open hook path). Preserve any id the caller already set.
|
|
27072
28447
|
metadata: {
|
|
27073
28448
|
...input.metadata,
|
|
27074
|
-
correlationId: input.metadata?.correlationId ??
|
|
28449
|
+
correlationId: input.metadata?.correlationId ?? randomUUID11()
|
|
27075
28450
|
}
|
|
27076
28451
|
};
|
|
27077
28452
|
}
|
|
@@ -27080,8 +28455,8 @@ function buildIngestEvent(input) {
|
|
|
27080
28455
|
import { arch, hostname as hostname3, platform, release } from "os";
|
|
27081
28456
|
|
|
27082
28457
|
// ../../packages/plugin-sdk/src/nudge.ts
|
|
27083
|
-
import { mkdirSync as
|
|
27084
|
-
import { join as
|
|
28458
|
+
import { mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
|
|
28459
|
+
import { join as join10 } from "path";
|
|
27085
28460
|
|
|
27086
28461
|
// ../../packages/plugin-sdk/src/paths.ts
|
|
27087
28462
|
import { readdirSync as readdirSync2, realpathSync as realpathSync2 } from "fs";
|
|
@@ -27089,8 +28464,8 @@ import { basename as basename3, dirname as dirname2, sep as sep3 } from "path";
|
|
|
27089
28464
|
|
|
27090
28465
|
// ../../packages/plugin-sdk/src/project-files.ts
|
|
27091
28466
|
var import_ignore = __toESM(require_ignore(), 1);
|
|
27092
|
-
import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as
|
|
27093
|
-
import { basename as basename4, join as
|
|
28467
|
+
import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync7 } from "fs";
|
|
28468
|
+
import { basename as basename4, join as join11, relative, sep as sep4 } from "path";
|
|
27094
28469
|
|
|
27095
28470
|
// ../../packages/plugin-sdk/src/rule-quarantine.ts
|
|
27096
28471
|
var PASS_BUDGET_MS = 2e3;
|
|
@@ -27146,7 +28521,7 @@ async function filterUnsafeRules(rules, gateway, opts) {
|
|
|
27146
28521
|
}
|
|
27147
28522
|
|
|
27148
28523
|
// ../../packages/plugin-sdk/src/runtime.ts
|
|
27149
|
-
import { randomUUID as
|
|
28524
|
+
import { randomUUID as randomUUID12 } from "crypto";
|
|
27150
28525
|
var ENFORCEMENT_CEILING_ENABLED = false;
|
|
27151
28526
|
var ACTION_PRIORITY = ["block", "redact", "warn", "log", "allow"];
|
|
27152
28527
|
function entryIsActive(entry, now) {
|
|
@@ -27249,7 +28624,12 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27249
28624
|
if (worst === "block") return { action: "block", text: null, findings };
|
|
27250
28625
|
if (worst === "redact") {
|
|
27251
28626
|
const redactFindings = findings.filter((f) => actionFor(f) === "redact");
|
|
27252
|
-
return {
|
|
28627
|
+
return {
|
|
28628
|
+
action: "redact",
|
|
28629
|
+
text: redact(text, redactFindings),
|
|
28630
|
+
findings,
|
|
28631
|
+
enforcedFindings: redactFindings
|
|
28632
|
+
};
|
|
27253
28633
|
}
|
|
27254
28634
|
return { action: worst, text, findings };
|
|
27255
28635
|
}
|
|
@@ -27290,9 +28670,17 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27290
28670
|
else groups.set(pair, [finding]);
|
|
27291
28671
|
}
|
|
27292
28672
|
const now = Date.now();
|
|
28673
|
+
const preAuthorized = new Set(ctx.preAuthorizedGrantIds ?? []);
|
|
27293
28674
|
for (const [pair, group] of groups) {
|
|
27294
28675
|
const entry = entries.get(pair);
|
|
27295
|
-
if (!entry
|
|
28676
|
+
if (!entry) continue;
|
|
28677
|
+
if (preAuthorized.has(entry.id)) {
|
|
28678
|
+
if (!conditionsMatch(entry.conditions, ctx)) continue;
|
|
28679
|
+
for (const finding of group) excepted.add(finding);
|
|
28680
|
+
exceptionIds.push(entry.id);
|
|
28681
|
+
continue;
|
|
28682
|
+
}
|
|
28683
|
+
if (!entryIsActive(entry, now) || !conditionsMatch(entry.conditions, ctx)) {
|
|
27296
28684
|
continue;
|
|
27297
28685
|
}
|
|
27298
28686
|
let consumed = false;
|
|
@@ -27324,7 +28712,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27324
28712
|
const pair = `${finding.ruleId}:${fp}`;
|
|
27325
28713
|
if (seen.has(pair)) continue;
|
|
27326
28714
|
seen.add(pair);
|
|
27327
|
-
const reference =
|
|
28715
|
+
const reference = randomUUID12().replaceAll("-", "").slice(0, 6);
|
|
27328
28716
|
const maskedValue = maskMatch(finding.rawMatch);
|
|
27329
28717
|
try {
|
|
27330
28718
|
await gateway.recordBlockedDetection({
|
|
@@ -27348,7 +28736,8 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27348
28736
|
async function evaluate(text, context, ctx) {
|
|
27349
28737
|
try {
|
|
27350
28738
|
await ensureInitialized();
|
|
27351
|
-
const
|
|
28739
|
+
const shielded = shieldPointers(text);
|
|
28740
|
+
const findings = dropShieldedFindings(scan(shielded.text, rules, context), shielded.spans);
|
|
27352
28741
|
const fpCache = /* @__PURE__ */ new Map();
|
|
27353
28742
|
const { excepted, exceptionIds } = await applyExceptions(findings, ctx, fpCache);
|
|
27354
28743
|
const decision = decide(findings, text, excepted);
|
|
@@ -27371,7 +28760,11 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27371
28760
|
const { decision, excepted, exceptionIds } = await evaluate(
|
|
27372
28761
|
input.text,
|
|
27373
28762
|
filePath ? { filePath } : void 0,
|
|
27374
|
-
{
|
|
28763
|
+
{
|
|
28764
|
+
sourceTool: input.sourceTool,
|
|
28765
|
+
metadata: input.metadata,
|
|
28766
|
+
preAuthorizedGrantIds: opts2.preAuthorizedGrantIds
|
|
28767
|
+
}
|
|
27375
28768
|
);
|
|
27376
28769
|
if (opts2.persist === "with-findings" && decision.findings.length === 0) return decision;
|
|
27377
28770
|
try {
|
|
@@ -27401,7 +28794,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27401
28794
|
valueFingerprint: findingKeyFingerprintKey ? fingerprintOf(findingKeyFingerprintKey, match, findingKeyFpCache) : maskedMatch
|
|
27402
28795
|
}) : void 0;
|
|
27403
28796
|
return {
|
|
27404
|
-
id:
|
|
28797
|
+
id: randomUUID12(),
|
|
27405
28798
|
eventId: event.id,
|
|
27406
28799
|
ruleId: match.ruleId,
|
|
27407
28800
|
category: match.category,
|
|
@@ -27427,7 +28820,7 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27427
28820
|
const sorted = [...rules].sort((a, b) => a.id.localeCompare(b.id));
|
|
27428
28821
|
return contentHashOf(JSON.stringify(sorted));
|
|
27429
28822
|
} catch {
|
|
27430
|
-
return `unresolved-${
|
|
28823
|
+
return `unresolved-${randomUUID12()}`;
|
|
27431
28824
|
}
|
|
27432
28825
|
}
|
|
27433
28826
|
async function close() {
|
|
@@ -27440,11 +28833,306 @@ function createPluginRuntime(gateway, settings, opts) {
|
|
|
27440
28833
|
var THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
27441
28834
|
|
|
27442
28835
|
// ../../packages/plugin-sdk/src/throttle.ts
|
|
27443
|
-
import { mkdirSync as
|
|
27444
|
-
import { join as
|
|
28836
|
+
import { mkdirSync as mkdirSync4, statSync as statSync4, writeFileSync as writeFileSync5 } from "fs";
|
|
28837
|
+
import { join as join12 } from "path";
|
|
28838
|
+
|
|
28839
|
+
// ../../packages/plugin-sdk/src/tokenize.ts
|
|
28840
|
+
function redactedPlaceholder(category) {
|
|
28841
|
+
return `[REDACTED:${category.toUpperCase()}]`;
|
|
28842
|
+
}
|
|
28843
|
+
var POINTER_UNAVAILABLE_TEXT = "[unavailable]";
|
|
28844
|
+
var SEVERITY_RANK3 = { critical: 3, high: 2, medium: 1, low: 0 };
|
|
28845
|
+
function groupSpans(text, findings) {
|
|
28846
|
+
const sorted = [...findings].filter((f) => f.span.start >= 0 && f.span.end <= text.length && f.span.start < f.span.end).sort((a, b) => a.span.start - b.span.start || b.span.end - a.span.end);
|
|
28847
|
+
const groups = [];
|
|
28848
|
+
for (const finding of sorted) {
|
|
28849
|
+
const last = groups[groups.length - 1];
|
|
28850
|
+
if (last && finding.span.start < last.end) {
|
|
28851
|
+
last.end = Math.max(last.end, finding.span.end);
|
|
28852
|
+
if ((SEVERITY_RANK3[finding.severity] ?? 0) > (SEVERITY_RANK3[last.severity] ?? 0)) {
|
|
28853
|
+
last.category = finding.category;
|
|
28854
|
+
last.severity = finding.severity;
|
|
28855
|
+
}
|
|
28856
|
+
delete last.finding;
|
|
28857
|
+
continue;
|
|
28858
|
+
}
|
|
28859
|
+
groups.push({
|
|
28860
|
+
start: finding.span.start,
|
|
28861
|
+
end: finding.span.end,
|
|
28862
|
+
finding,
|
|
28863
|
+
category: finding.category,
|
|
28864
|
+
severity: finding.severity
|
|
28865
|
+
});
|
|
28866
|
+
}
|
|
28867
|
+
return groups;
|
|
28868
|
+
}
|
|
28869
|
+
var NULL_RESOLVER = () => Promise.resolve(null);
|
|
28870
|
+
var SecretVaultGlue = class {
|
|
28871
|
+
#vault;
|
|
28872
|
+
revealGrantResolver;
|
|
28873
|
+
// Set only when THIS glue opened the store, so a glue over an injected vault
|
|
28874
|
+
// never closes a handle it does not own.
|
|
28875
|
+
#release;
|
|
28876
|
+
constructor(vault, revealGrantResolver = NULL_RESOLVER, release2) {
|
|
28877
|
+
this.#vault = vault;
|
|
28878
|
+
this.revealGrantResolver = revealGrantResolver;
|
|
28879
|
+
this.#release = release2;
|
|
28880
|
+
}
|
|
28881
|
+
close() {
|
|
28882
|
+
const release2 = this.#release;
|
|
28883
|
+
this.#release = void 0;
|
|
28884
|
+
try {
|
|
28885
|
+
release2?.();
|
|
28886
|
+
} catch {
|
|
28887
|
+
}
|
|
28888
|
+
}
|
|
28889
|
+
async tokenizeValue(raw, meta3) {
|
|
28890
|
+
try {
|
|
28891
|
+
const result = await this.#vault.tokenize(raw, meta3);
|
|
28892
|
+
return typeof result === "string" ? result : redactedPlaceholder(meta3.category);
|
|
28893
|
+
} catch {
|
|
28894
|
+
return redactedPlaceholder(meta3.category);
|
|
28895
|
+
}
|
|
28896
|
+
}
|
|
28897
|
+
async tokenizeText(text, opts) {
|
|
28898
|
+
try {
|
|
28899
|
+
const findings = opts?.findings ?? this.#selfScan(text);
|
|
28900
|
+
if (findings === null) return { text: "[REDACTED]", pointers: [], degraded: [] };
|
|
28901
|
+
if (findings.length === 0) return { text, pointers: [], degraded: [] };
|
|
28902
|
+
const groups = groupSpans(text, findings);
|
|
28903
|
+
const pointers = [];
|
|
28904
|
+
const degraded = [];
|
|
28905
|
+
let out = text;
|
|
28906
|
+
for (const group of [...groups].reverse()) {
|
|
28907
|
+
const original = text.slice(group.start, group.end);
|
|
28908
|
+
const finding = group.finding;
|
|
28909
|
+
let replacement;
|
|
28910
|
+
if (finding === void 0) {
|
|
28911
|
+
replacement = redactedPlaceholder(group.category);
|
|
28912
|
+
degraded.unshift({ category: group.category });
|
|
28913
|
+
} else if (original !== finding.rawMatch) {
|
|
28914
|
+
replacement = redactedPlaceholder(group.category);
|
|
28915
|
+
degraded.unshift({ category: group.category });
|
|
28916
|
+
} else {
|
|
28917
|
+
replacement = await this.tokenizeValue(finding.rawMatch, {
|
|
28918
|
+
ruleId: finding.ruleId,
|
|
28919
|
+
category: finding.category,
|
|
28920
|
+
maskedMatch: maskMatch(finding.rawMatch)
|
|
28921
|
+
});
|
|
28922
|
+
if (replacement.startsWith("[[aka:")) pointers.unshift(replacement);
|
|
28923
|
+
else degraded.unshift({ category: finding.category });
|
|
28924
|
+
}
|
|
28925
|
+
out = out.slice(0, group.start) + replacement + out.slice(group.end);
|
|
28926
|
+
}
|
|
28927
|
+
if (opts?.sighting && pointers.length > 0) {
|
|
28928
|
+
for (const pointer of pointers) {
|
|
28929
|
+
try {
|
|
28930
|
+
const id = pointer.split(".")[1];
|
|
28931
|
+
if (id !== void 0) this.#vault.recordSighting?.(id, opts.sighting);
|
|
28932
|
+
} catch {
|
|
28933
|
+
}
|
|
28934
|
+
}
|
|
28935
|
+
}
|
|
28936
|
+
return { text: out, pointers, degraded };
|
|
28937
|
+
} catch {
|
|
28938
|
+
return { text: "[REDACTED]", pointers: [], degraded: [] };
|
|
28939
|
+
}
|
|
28940
|
+
}
|
|
28941
|
+
async detokenizeText(text, opts) {
|
|
28942
|
+
try {
|
|
28943
|
+
const matches = [...text.matchAll(pointerTokenScanner())];
|
|
28944
|
+
if (matches.length === 0) return { text, revealed: 0 };
|
|
28945
|
+
const occurrences = /* @__PURE__ */ new Map();
|
|
28946
|
+
for (const match of matches) {
|
|
28947
|
+
occurrences.set(match[0], (occurrences.get(match[0]) ?? 0) + 1);
|
|
28948
|
+
}
|
|
28949
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
28950
|
+
for (const [pointer, count] of occurrences) {
|
|
28951
|
+
try {
|
|
28952
|
+
const value = await this.#vault.detokenize(pointer, {
|
|
28953
|
+
target: "human",
|
|
28954
|
+
reason: opts.reason,
|
|
28955
|
+
pointerCount: count
|
|
28956
|
+
});
|
|
28957
|
+
resolved.set(pointer, typeof value === "string" ? value : null);
|
|
28958
|
+
} catch {
|
|
28959
|
+
resolved.set(pointer, null);
|
|
28960
|
+
}
|
|
28961
|
+
}
|
|
28962
|
+
let out = text;
|
|
28963
|
+
let revealed = 0;
|
|
28964
|
+
for (const match of [...matches].reverse()) {
|
|
28965
|
+
const value = resolved.get(match[0]);
|
|
28966
|
+
const replacement = value ?? POINTER_UNAVAILABLE_TEXT;
|
|
28967
|
+
if (value !== null && value !== void 0) revealed += 1;
|
|
28968
|
+
out = out.slice(0, match.index) + replacement + out.slice(match.index + match[0].length);
|
|
28969
|
+
}
|
|
28970
|
+
return { text: out, revealed };
|
|
28971
|
+
} catch {
|
|
28972
|
+
return { text, revealed: 0 };
|
|
28973
|
+
}
|
|
28974
|
+
}
|
|
28975
|
+
// Scan with the bundled packs, as the mask path does. Pointers already in the
|
|
28976
|
+
// text are blanked first so a pointer is never re-tokenized. Returns null
|
|
28977
|
+
// when the registry or the scan itself failed — the caller must then treat
|
|
28978
|
+
// the whole text as unclassifiable.
|
|
28979
|
+
#selfScan(text) {
|
|
28980
|
+
try {
|
|
28981
|
+
registerBundledPacks();
|
|
28982
|
+
const shielded = shieldPointers(text);
|
|
28983
|
+
return dropShieldedFindings(scan(shielded.text, getLoadedRules()), shielded.spans);
|
|
28984
|
+
} catch {
|
|
28985
|
+
return null;
|
|
28986
|
+
}
|
|
28987
|
+
}
|
|
28988
|
+
async describePointerSafe(token) {
|
|
28989
|
+
try {
|
|
28990
|
+
return await this.#vault.describePointer(token);
|
|
28991
|
+
} catch {
|
|
28992
|
+
return null;
|
|
28993
|
+
}
|
|
28994
|
+
}
|
|
28995
|
+
async probeModelPointers(text, opts) {
|
|
28996
|
+
const granted = /* @__PURE__ */ new Map();
|
|
28997
|
+
const ungranted = [];
|
|
28998
|
+
try {
|
|
28999
|
+
for (const pointer of new Set([...text.matchAll(pointerTokenScanner())].map((m) => m[0]))) {
|
|
29000
|
+
try {
|
|
29001
|
+
const grantId = await opts.resolveGrant(pointer);
|
|
29002
|
+
if (grantId === null) ungranted.push(pointer);
|
|
29003
|
+
else granted.set(pointer, grantId);
|
|
29004
|
+
} catch {
|
|
29005
|
+
ungranted.push(pointer);
|
|
29006
|
+
}
|
|
29007
|
+
}
|
|
29008
|
+
return { granted, ungranted };
|
|
29009
|
+
} catch {
|
|
29010
|
+
return { granted: /* @__PURE__ */ new Map(), ungranted };
|
|
29011
|
+
}
|
|
29012
|
+
}
|
|
29013
|
+
async substituteModelPointers(text, opts) {
|
|
29014
|
+
try {
|
|
29015
|
+
const matches = [...text.matchAll(pointerTokenScanner())];
|
|
29016
|
+
if (matches.length === 0) return { text, revealed: [], unresolved: [], grantIds: [] };
|
|
29017
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
29018
|
+
for (const pointer of new Set(matches.map((m) => m[0]))) {
|
|
29019
|
+
try {
|
|
29020
|
+
const grantId = await opts.resolveGrant(pointer);
|
|
29021
|
+
if (grantId === null) {
|
|
29022
|
+
await this.#vault.detokenize(pointer, { target: "model", reason: "model-input" });
|
|
29023
|
+
resolved.set(pointer, null);
|
|
29024
|
+
continue;
|
|
29025
|
+
}
|
|
29026
|
+
const value = await this.#vault.detokenize(pointer, {
|
|
29027
|
+
target: "model",
|
|
29028
|
+
reason: "model-input",
|
|
29029
|
+
grantId
|
|
29030
|
+
});
|
|
29031
|
+
resolved.set(pointer, typeof value === "string" ? { value, grantId } : null);
|
|
29032
|
+
} catch {
|
|
29033
|
+
resolved.set(pointer, null);
|
|
29034
|
+
}
|
|
29035
|
+
}
|
|
29036
|
+
const spentGrants = /* @__PURE__ */ new Set();
|
|
29037
|
+
for (const entry of resolved.values()) {
|
|
29038
|
+
if (entry === null || spentGrants.has(entry.grantId)) continue;
|
|
29039
|
+
spentGrants.add(entry.grantId);
|
|
29040
|
+
try {
|
|
29041
|
+
await this.#vault.consumeGrant?.(entry.grantId);
|
|
29042
|
+
} catch {
|
|
29043
|
+
}
|
|
29044
|
+
}
|
|
29045
|
+
let out = text;
|
|
29046
|
+
const revealed = /* @__PURE__ */ new Set();
|
|
29047
|
+
const unresolved = /* @__PURE__ */ new Set();
|
|
29048
|
+
for (const match of [...matches].reverse()) {
|
|
29049
|
+
const entry = resolved.get(match[0]);
|
|
29050
|
+
if (entry === null || entry === void 0) {
|
|
29051
|
+
unresolved.add(match[0]);
|
|
29052
|
+
continue;
|
|
29053
|
+
}
|
|
29054
|
+
revealed.add(match[0]);
|
|
29055
|
+
out = out.slice(0, match.index) + entry.value + out.slice(match.index + match[0].length);
|
|
29056
|
+
}
|
|
29057
|
+
return {
|
|
29058
|
+
text: out,
|
|
29059
|
+
revealed: [...revealed],
|
|
29060
|
+
unresolved: [...unresolved],
|
|
29061
|
+
grantIds: [...spentGrants]
|
|
29062
|
+
};
|
|
29063
|
+
} catch {
|
|
29064
|
+
return { text, revealed: [], unresolved: [], grantIds: [] };
|
|
29065
|
+
}
|
|
29066
|
+
}
|
|
29067
|
+
};
|
|
29068
|
+
function createVaultGlue(options) {
|
|
29069
|
+
if (options?.vault) return new SecretVaultGlue(options.vault, options.revealResolver);
|
|
29070
|
+
const base = options?.base ?? defaultDataDir();
|
|
29071
|
+
try {
|
|
29072
|
+
const dir = dataDir(base);
|
|
29073
|
+
const db = openLocalDatabase(dir);
|
|
29074
|
+
const settings = readWorkspaceSettings(base);
|
|
29075
|
+
const provider = options?.policyProvider ?? new UserGrantPolicyProvider(db.exceptions);
|
|
29076
|
+
const vault = new SecretVault({
|
|
29077
|
+
repo: db.secretVault,
|
|
29078
|
+
keys: createKeyProvider(settings.vaultKeyCustody, keysDir(base)),
|
|
29079
|
+
fingerprintKey: loadOrCreateFingerprintKey(dir),
|
|
29080
|
+
// Read live so a revocation applies to the very next call, not the next
|
|
29081
|
+
// process.
|
|
29082
|
+
isConsented: () => isVaultConsentValid(readWorkspaceSettings(base).vaultConsent),
|
|
29083
|
+
// This is the one construction site that reveals to the model, so it is
|
|
29084
|
+
// the one that supplies the last gate. The decision is re-taken from the
|
|
29085
|
+
// ROW's identity at the moment of crossing, which closes the window
|
|
29086
|
+
// between resolving a grant and spending it: a grant revoked in between
|
|
29087
|
+
// refuses here.
|
|
29088
|
+
//
|
|
29089
|
+
// The re-decision is on the identity alone, never on the grant id
|
|
29090
|
+
// matching the one the resolver returned. ExceptionPolicyProvider
|
|
29091
|
+
// promises no id stability across calls — a provider deciding from
|
|
29092
|
+
// external policy may well mint a fresh id each time — so comparing ids
|
|
29093
|
+
// would silently refuse every crossing for such a provider while looking
|
|
29094
|
+
// like a security check. `allow` for this row is the whole question.
|
|
29095
|
+
verifyGrant: async (_grantId, identity) => {
|
|
29096
|
+
const decision = await provider.decideReveal(identity);
|
|
29097
|
+
return decision.allow;
|
|
29098
|
+
}
|
|
29099
|
+
});
|
|
29100
|
+
const vaultWithSightings = {
|
|
29101
|
+
tokenize: (raw, meta3) => vault.tokenize(raw, meta3),
|
|
29102
|
+
detokenize: (token, opts) => vault.detokenize(token, opts),
|
|
29103
|
+
describePointer: (token) => vault.describePointer(token),
|
|
29104
|
+
resolvePointerIdentity: (token) => vault.resolvePointerIdentity(token),
|
|
29105
|
+
recordSighting: (pointerId, sighting) => {
|
|
29106
|
+
db.secretVault.recordSighting({ pointerId, ...sighting }, Date.now());
|
|
29107
|
+
},
|
|
29108
|
+
consumeGrant: (grantId) => db.exceptions.consume(grantId)
|
|
29109
|
+
};
|
|
29110
|
+
const revealGrantResolver = async (pointer) => {
|
|
29111
|
+
try {
|
|
29112
|
+
const identity = await vault.resolvePointerIdentity(pointer);
|
|
29113
|
+
if (identity === null) return null;
|
|
29114
|
+
const decision = await provider.decideReveal(identity);
|
|
29115
|
+
return decision.allow ? decision.grantId : null;
|
|
29116
|
+
} catch {
|
|
29117
|
+
return null;
|
|
29118
|
+
}
|
|
29119
|
+
};
|
|
29120
|
+
return new SecretVaultGlue(vaultWithSightings, revealGrantResolver, () => {
|
|
29121
|
+
db.close();
|
|
29122
|
+
});
|
|
29123
|
+
} catch {
|
|
29124
|
+
return new SecretVaultGlue(UNOPENABLE_VAULT);
|
|
29125
|
+
}
|
|
29126
|
+
}
|
|
29127
|
+
var UNOPENABLE_VAULT = {
|
|
29128
|
+
tokenize: () => Promise.resolve(/* @__PURE__ */ Symbol("aka.vault.unopenable")),
|
|
29129
|
+
detokenize: () => Promise.resolve(/* @__PURE__ */ Symbol("aka.vault.unopenable")),
|
|
29130
|
+
describePointer: () => Promise.resolve(null),
|
|
29131
|
+
resolvePointerIdentity: () => Promise.resolve(null)
|
|
29132
|
+
};
|
|
27445
29133
|
|
|
27446
29134
|
// ../../packages/plugin-runtime/src/standalone-gateway.ts
|
|
27447
|
-
import { randomUUID as
|
|
29135
|
+
import { randomUUID as randomUUID13 } from "crypto";
|
|
27448
29136
|
|
|
27449
29137
|
// ../../packages/plugin-runtime/src/recorder.ts
|
|
27450
29138
|
var PLUGIN_RECORDER_BINARY = "plugin";
|
|
@@ -27606,7 +29294,7 @@ var StandaloneDataGateway = class {
|
|
|
27606
29294
|
const customKeywords = [...new Set(policies.flatMap((p) => p.customKeywords ?? []))];
|
|
27607
29295
|
const installed = this.installedScanRules();
|
|
27608
29296
|
const rulePolicies = installed ? [...installed.ruleActions].map(([ruleId, action]) => ({
|
|
27609
|
-
id:
|
|
29297
|
+
id: randomUUID13(),
|
|
27610
29298
|
scope: "global",
|
|
27611
29299
|
target: { ruleId },
|
|
27612
29300
|
action,
|
|
@@ -27759,9 +29447,83 @@ function resolveDataGateway(config2, meta3, gatewayFactory = standaloneGatewayFa
|
|
|
27759
29447
|
}
|
|
27760
29448
|
|
|
27761
29449
|
// ../../packages/plugin-runtime/src/handle-session-start.ts
|
|
27762
|
-
import { randomUUID as
|
|
29450
|
+
import { randomUUID as randomUUID14 } from "crypto";
|
|
27763
29451
|
var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
|
|
27764
29452
|
|
|
29453
|
+
// src/protocol/marker.ts
|
|
29454
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
29455
|
+
import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, renameSync as renameSync5, writeFileSync as writeFileSync6 } from "fs";
|
|
29456
|
+
import { join as join13 } from "path";
|
|
29457
|
+
var MARKER_FILE = "protocol-marker";
|
|
29458
|
+
function mintMarker() {
|
|
29459
|
+
return randomBytes4(8).toString("hex");
|
|
29460
|
+
}
|
|
29461
|
+
function sessionProtocolMarker(dataDir2, sessionId) {
|
|
29462
|
+
if (!sessionId) return mintMarker();
|
|
29463
|
+
const path = join13(dataDir2, MARKER_FILE);
|
|
29464
|
+
try {
|
|
29465
|
+
const stored = JSON.parse(readFileSync8(path, "utf8"));
|
|
29466
|
+
if (stored.sessionId === sessionId && typeof stored.marker === "string" && /^[0-9a-f]{16}$/.test(stored.marker)) {
|
|
29467
|
+
return stored.marker;
|
|
29468
|
+
}
|
|
29469
|
+
} catch {
|
|
29470
|
+
}
|
|
29471
|
+
const marker = mintMarker();
|
|
29472
|
+
try {
|
|
29473
|
+
mkdirSync5(dataDir2, { recursive: true, mode: DATA_DIR_MODE });
|
|
29474
|
+
const tmp = join13(dataDir2, `${MARKER_FILE}.tmp`);
|
|
29475
|
+
writeFileSync6(tmp, JSON.stringify({ sessionId, marker }), { mode: DATA_FILE_MODE });
|
|
29476
|
+
renameSync5(tmp, path);
|
|
29477
|
+
} catch {
|
|
29478
|
+
}
|
|
29479
|
+
return marker;
|
|
29480
|
+
}
|
|
29481
|
+
|
|
29482
|
+
// src/protocol/notes.ts
|
|
29483
|
+
function countOf(n, noun) {
|
|
29484
|
+
return `${String(n)} ${noun}${n === 1 ? "" : "s"}`;
|
|
29485
|
+
}
|
|
29486
|
+
function uniqueCategories(items) {
|
|
29487
|
+
return [...new Set(items.map((item) => item.category))].join(", ");
|
|
29488
|
+
}
|
|
29489
|
+
function eventNote(opts) {
|
|
29490
|
+
const { pointers, degraded } = opts.realized;
|
|
29491
|
+
if (pointers.length === 0 && degraded.length === 0) return null;
|
|
29492
|
+
const parts = [];
|
|
29493
|
+
if (pointers.length > 0) {
|
|
29494
|
+
const shown = pointers.slice(0, VAULT_EVENT_NOTE_MAX_POINTERS);
|
|
29495
|
+
const listed = shown.map((p) => `${p.token} (${p.category}${p.provider ? `/${p.provider}` : ""})`).join(", ");
|
|
29496
|
+
const hidden = pointers.length - shown.length;
|
|
29497
|
+
const overflow = hidden > 0 ? ` \u2026 and ${String(hidden)} more` : "";
|
|
29498
|
+
parts.push(
|
|
29499
|
+
`AKA replaced ${countOf(pointers.length, "value")} before this ran \u2014 ${listed}${overflow}. Use each pointer verbatim; the raw values are not available to you. Never fabricate or alter a pointer.`
|
|
29500
|
+
);
|
|
29501
|
+
}
|
|
29502
|
+
if (degraded.length > 0) {
|
|
29503
|
+
const many = degraded.length > 1;
|
|
29504
|
+
parts.push(
|
|
29505
|
+
`AKA removed ${countOf(degraded.length, "value")} (${uniqueCategories(degraded)}) before this ran. The vault was unavailable so ${many ? "they were" : "it was"} redacted irreversibly \u2014 no pointer exists for ${many ? "them" : "it"}. Do not invent one, and do not ask the user for the ${many ? "values" : "value"}.`
|
|
29506
|
+
);
|
|
29507
|
+
}
|
|
29508
|
+
return `[AKA ${opts.marker}] ${opts.surface}: ${parts.join(" ")}`;
|
|
29509
|
+
}
|
|
29510
|
+
function userDisclosure(opts) {
|
|
29511
|
+
const { pointers, degraded } = opts.realized;
|
|
29512
|
+
if (pointers.length === 0 && degraded.length === 0) return null;
|
|
29513
|
+
const sentences = [];
|
|
29514
|
+
if (pointers.length > 0) {
|
|
29515
|
+
sentences.push(
|
|
29516
|
+
`AKA replaced ${countOf(pointers.length, "value")} (${uniqueCategories(pointers)}) in this ${opts.surface} \u2014 kept recoverable in your local vault \u2014 see the AKA dashboard or \`aka vault show\`.`
|
|
29517
|
+
);
|
|
29518
|
+
}
|
|
29519
|
+
if (degraded.length > 0) {
|
|
29520
|
+
sentences.push(
|
|
29521
|
+
`AKA removed ${countOf(degraded.length, "value")} (${uniqueCategories(degraded)}) from this ${opts.surface} \u2014 redacted irreversibly \u2014 the vault was unavailable.`
|
|
29522
|
+
);
|
|
29523
|
+
}
|
|
29524
|
+
return sentences.join(" ");
|
|
29525
|
+
}
|
|
29526
|
+
|
|
27765
29527
|
// src/present.ts
|
|
27766
29528
|
var SHADE = {
|
|
27767
29529
|
light: "\u2591",
|
|
@@ -27805,6 +29567,7 @@ function withheldBanner(input) {
|
|
|
27805
29567
|
...input.redactedRuleIds ? [`${SHADE.full} Redacted: ${input.redactedRuleIds}`] : [],
|
|
27806
29568
|
...input.warnedRuleIds ? [`${SHADE.full} Also flagged (warn): ${input.warnedRuleIds}`] : [],
|
|
27807
29569
|
`${SHADE.full} ${subject} never reached the model.`,
|
|
29570
|
+
...input.vaultDisclosure ? [`${SHADE.full} ${input.vaultDisclosure}`] : [],
|
|
27808
29571
|
`${SHADE.full} ${approve}`,
|
|
27809
29572
|
`${SHADE.full} More: aka exception --help`
|
|
27810
29573
|
].join("\n");
|
|
@@ -27870,15 +29633,17 @@ function replaceResponseField(response, path, text) {
|
|
|
27870
29633
|
}
|
|
27871
29634
|
|
|
27872
29635
|
// src/hooks/scan-response.ts
|
|
27873
|
-
async function scanResponseFields(toolName, response, fields, capture) {
|
|
29636
|
+
async function scanResponseFields(toolName, response, fields, capture, tokenizeField) {
|
|
27874
29637
|
const outcome = {
|
|
27875
29638
|
updated: response,
|
|
27876
29639
|
withheldFindings: [],
|
|
27877
29640
|
redactedFindings: [],
|
|
27878
29641
|
warnedFindings: [],
|
|
27879
29642
|
blockedReferences: [],
|
|
27880
|
-
redactedReferences: []
|
|
29643
|
+
redactedReferences: [],
|
|
29644
|
+
realized: null
|
|
27881
29645
|
};
|
|
29646
|
+
const realized = { pointers: [], degraded: [] };
|
|
27882
29647
|
for (const field of fields) {
|
|
27883
29648
|
const result = await capture(field.text);
|
|
27884
29649
|
if (result.findings.length === 0) continue;
|
|
@@ -27891,23 +29656,43 @@ async function scanResponseFields(toolName, response, fields, capture) {
|
|
|
27891
29656
|
outcome.withheldFindings.push(...result.findings);
|
|
27892
29657
|
if (result.blockedReferences) outcome.blockedReferences.push(...result.blockedReferences);
|
|
27893
29658
|
} else if (result.action === "redact" && result.text !== null) {
|
|
27894
|
-
|
|
29659
|
+
let rewritten = result.text;
|
|
29660
|
+
const enforced = result.enforcedFindings ?? [];
|
|
29661
|
+
if (tokenizeField && enforced.length > 0) {
|
|
29662
|
+
try {
|
|
29663
|
+
const tokenized = await tokenizeField(field.text, enforced);
|
|
29664
|
+
rewritten = tokenized.text;
|
|
29665
|
+
for (const token of tokenized.pointers) {
|
|
29666
|
+
realized.pointers.push({ token, category: pointerCategoryOf(token) });
|
|
29667
|
+
}
|
|
29668
|
+
realized.degraded.push(...tokenized.degraded);
|
|
29669
|
+
} catch {
|
|
29670
|
+
}
|
|
29671
|
+
}
|
|
29672
|
+
outcome.updated = replaceResponseField(outcome.updated, field.path, rewritten);
|
|
27895
29673
|
outcome.redactedFindings.push(...result.findings);
|
|
27896
29674
|
if (result.blockedReferences) outcome.redactedReferences.push(...result.blockedReferences);
|
|
27897
29675
|
} else if (result.action === "warn") {
|
|
27898
29676
|
outcome.warnedFindings.push(...result.findings);
|
|
27899
29677
|
}
|
|
27900
29678
|
}
|
|
29679
|
+
if (realized.pointers.length > 0 || realized.degraded.length > 0) outcome.realized = realized;
|
|
27901
29680
|
return outcome;
|
|
27902
29681
|
}
|
|
27903
|
-
function
|
|
29682
|
+
function pointerCategoryOf(token) {
|
|
29683
|
+
const match = /^\[\[aka:([a-z_]+):/.exec(token);
|
|
29684
|
+
return match?.[1] ?? "secret";
|
|
29685
|
+
}
|
|
29686
|
+
function responseEmitPayload(toolName, outcome, notes) {
|
|
27904
29687
|
const { withheldFindings, redactedFindings, warnedFindings } = outcome;
|
|
27905
29688
|
if (withheldFindings.length > 0 || redactedFindings.length > 0) {
|
|
27906
29689
|
const action = withheldFindings.length > 0 ? "withheld" : "redacted";
|
|
29690
|
+
const note = notes?.note ?? null;
|
|
27907
29691
|
return {
|
|
27908
29692
|
hookSpecificOutput: {
|
|
27909
29693
|
hookEventName: "PostToolUse",
|
|
27910
|
-
updatedToolOutput: outcome.updated
|
|
29694
|
+
updatedToolOutput: outcome.updated,
|
|
29695
|
+
...note === null ? {} : { additionalContext: note }
|
|
27911
29696
|
},
|
|
27912
29697
|
// The approve pointer stays OUT of the model-visible replacement text:
|
|
27913
29698
|
// it is the user's audited escape hatch, not something to nudge an
|
|
@@ -27918,7 +29703,8 @@ function responseEmitPayload(toolName, outcome) {
|
|
|
27918
29703
|
withheldRuleIds: withheldFindings.length > 0 ? uniqueRuleIds(withheldFindings) : void 0,
|
|
27919
29704
|
redactedRuleIds: redactedFindings.length > 0 ? uniqueRuleIds(redactedFindings) : void 0,
|
|
27920
29705
|
warnedRuleIds: warnedFindings.length > 0 ? uniqueRuleIds(warnedFindings) : void 0,
|
|
27921
|
-
blockedRef: action === "withheld" ? outcome.blockedReferences[0] : outcome.redactedReferences[0]
|
|
29706
|
+
blockedRef: action === "withheld" ? outcome.blockedReferences[0] : outcome.redactedReferences[0],
|
|
29707
|
+
vaultDisclosure: notes?.disclosure ?? void 0
|
|
27922
29708
|
})
|
|
27923
29709
|
};
|
|
27924
29710
|
}
|
|
@@ -28007,6 +29793,7 @@ async function main() {
|
|
|
28007
29793
|
const config2 = loadConfig();
|
|
28008
29794
|
const gateway = resolveDataGateway(config2);
|
|
28009
29795
|
const runtime = createPluginRuntime(gateway, config2.settings, { dataDir: config2.dataDir });
|
|
29796
|
+
const vaultGlue = isVaultConsentValid(config2.settings.vaultConsent) ? createVaultGlue() : null;
|
|
28010
29797
|
let outcome;
|
|
28011
29798
|
try {
|
|
28012
29799
|
outcome = await scanResponseFields(
|
|
@@ -28016,12 +29803,29 @@ async function main() {
|
|
|
28016
29803
|
(text) => runtime.capture(
|
|
28017
29804
|
{ kind: "response", sourceTool: "claude-code", text, metadata },
|
|
28018
29805
|
{ persist: "with-findings" }
|
|
28019
|
-
)
|
|
29806
|
+
),
|
|
29807
|
+
vaultGlue ? (text, findings) => vaultGlue.tokenizeText(text, {
|
|
29808
|
+
findings,
|
|
29809
|
+
sighting: filePath ? { location: filePath, kind: "file" } : { location: `${toolName} output`, kind: "tool-output" }
|
|
29810
|
+
}) : void 0
|
|
28020
29811
|
);
|
|
28021
29812
|
} finally {
|
|
28022
29813
|
await runtime.close();
|
|
28023
29814
|
}
|
|
28024
|
-
|
|
29815
|
+
let notes;
|
|
29816
|
+
if (outcome.realized) {
|
|
29817
|
+
try {
|
|
29818
|
+
const surface = `${toolName} output`;
|
|
29819
|
+
const marker = sessionProtocolMarker(config2.dataDir, getString(input, "session_id"));
|
|
29820
|
+
notes = {
|
|
29821
|
+
note: eventNote({ marker, surface, realized: outcome.realized }),
|
|
29822
|
+
disclosure: userDisclosure({ surface, realized: outcome.realized })
|
|
29823
|
+
};
|
|
29824
|
+
} catch {
|
|
29825
|
+
notes = void 0;
|
|
29826
|
+
}
|
|
29827
|
+
}
|
|
29828
|
+
const payload = responseEmitPayload(toolName, outcome, notes);
|
|
28025
29829
|
if (payload !== void 0) await emit(payload);
|
|
28026
29830
|
}
|
|
28027
29831
|
try {
|