@akasecurity/ai-tc-codex 0.9.14 → 0.9.15

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.
@@ -32,9 +32,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
  mod
33
33
  ));
34
34
 
35
- // ../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js
35
+ // ../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js
36
36
  var require_ignore = __commonJS({
37
- "../../node_modules/.pnpm/ignore@7.0.9/node_modules/ignore/index.js"(exports, module) {
37
+ "../../node_modules/.pnpm/ignore@7.0.10/node_modules/ignore/index.js"(exports, module) {
38
38
  "use strict";
39
39
  function makeArray(subject) {
40
40
  return Array.isArray(subject) ? subject : [subject];
@@ -429,6 +429,13 @@ var require_ignore = __commonJS({
429
429
  }
430
430
  };
431
431
  var WILDCARD = "[^\\/]*";
432
+ var separatorAfter = (run, at) => {
433
+ let separator = EMPTY;
434
+ for (let index = at + 1; index < run.length && !run[index].wildcard; index++) {
435
+ separator += run[index].single;
436
+ }
437
+ return separator;
438
+ };
432
439
  var pinWildcards = (source) => {
433
440
  if (source.indexOf(WILDCARD) < 0) {
434
441
  return source;
@@ -498,7 +505,7 @@ var require_ignore = __commonJS({
498
505
  out += token.single;
499
506
  return;
500
507
  }
501
- out += at === lastWildcard ? WILDCARD : `(?:(?!${run[at + 1].single})[^\\/])*`;
508
+ out += at === lastWildcard ? WILDCARD : `(?:(?!${separatorAfter(run, at)})[^\\/])*`;
502
509
  });
503
510
  run = [];
504
511
  };
@@ -1001,6 +1008,10 @@ var SQLITE_MIGRATIONS = [
1001
1008
  {
1002
1009
  tag: "0035_share_destination_provider_id",
1003
1010
  sql: "ALTER TABLE `share_destination` ADD `provider_id` text;"
1011
+ },
1012
+ {
1013
+ tag: "0036_secret_vault_identity_fingerprint",
1014
+ sql: "ALTER TABLE `secret_vault` ADD `value_identity_fingerprint` text DEFAULT '' NOT NULL;--> statement-breakpoint\nUPDATE `secret_vault` SET `value_identity_fingerprint` = `value_fingerprint`;\n"
1004
1015
  }
1005
1016
  ];
1006
1017
 
@@ -23377,7 +23388,29 @@ var StorePosturePlugin = external_exports.object({
23377
23388
  */
23378
23389
  policyBundleVersion: external_exports.string().max(200).nullable(),
23379
23390
  /** Epoch millis, on the CLIENT clock, of that fetch. */
23380
- policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable()
23391
+ policyFetchedAt: external_exports.number().int().min(0).max(MAX_DATE_MS).nullable(),
23392
+ /**
23393
+ * The newest version the host's own install record holds for this plugin —
23394
+ * what is on disk. After an update it leads `version` (the running copy) by
23395
+ * one launch. Null when no usable version can be read: no install record
23396
+ * (a plugin run from a checkout), no entry with a valid version, or every
23397
+ * such entry names an `installPath` that no longer exists; OPTIONAL, not
23398
+ * required, so a build that predates the member keeps getting its 200.
23399
+ * Bounded like `version`.
23400
+ */
23401
+ installedVersion: external_exports.string().max(64).nullable().optional(),
23402
+ /**
23403
+ * The local-store schema version this running build migrates a store to:
23404
+ * the number of store migrations it carries, the count it stamps into
23405
+ * `PRAGMA user_version`. A snapshot whose `schemaVersion` is above it
23406
+ * usually describes a store a newer build migrated. It is a hint, not a
23407
+ * verdict: the stamp is write-only, so a store whose count ran past this
23408
+ * build's while this build knows every migration in its ledger reads above
23409
+ * it too, which is why describeStoreSkew decides skew on ledger tags and
23410
+ * never on the count. OPTIONAL for the same reason as `installedVersion`;
23411
+ * bounded like `schemaVersion`.
23412
+ */
23413
+ buildSchemaVersion: external_exports.number().int().min(0).max(MAX_INT4).optional()
23381
23414
  }).meta({ id: "StorePosturePlugin" });
23382
23415
  var StorePostureSnapshot = external_exports.object({
23383
23416
  deviceId: external_exports.guid(),
@@ -24941,10 +24974,15 @@ var ParsedPointer = external_exports.object({
24941
24974
  });
24942
24975
  var VaultEntry = external_exports.object({
24943
24976
  pointerId: external_exports.string(),
24944
- // The keyed HMAC of the raw value under `exception.key`, and the epoch it was
24945
- // derived under. This is what a reveal-to-model grant matches on, and it rotates
24946
- // independently of the vault encryption key below.
24977
+ // The keyed HMAC of the EXACT raw bytes under `exception.key`, and the epoch it
24978
+ // was derived under. The vault's own dedupe key: a value and its invisibly
24979
+ // padded twin are two rows. It rotates independently of the vault encryption
24980
+ // key below. Never matched against an exception or grant.
24947
24981
  valueFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
24982
+ // The same HMAC over the raw with invisible padding removed: the identity a
24983
+ // reveal-to-model grant and every exception match on. Shared by a value and
24984
+ // its padded twin.
24985
+ valueIdentityFingerprint: external_exports.string().regex(/^[0-9a-f]{64}$/),
24948
24986
  fingerprintKeyVersion: external_exports.number().int().positive(),
24949
24987
  // The vault-key epoch this row's ciphertext was sealed under.
24950
24988
  keyVersion: external_exports.number().int().positive(),
@@ -25520,10 +25558,18 @@ var SeveritySummaryItem = external_exports.object({
25520
25558
  count: external_exports.number().int().nonnegative(),
25521
25559
  // Resolution-aware breakdown (optional, additive). Populated once findings
25522
25560
  // carry lifecycle state: `caught` = handled in-flight (enforced); `openAtRest`
25523
- // = still open with no in-flight enforcement (needs remediation). Absent on the
25524
- // legacy count-only response until the resolution feature lands.
25561
+ // = still open with no in-flight enforcement (needs remediation); `dismissed`
25562
+ // = closed by a human judgement rather than a fix — visible, but not counted as
25563
+ // needing remediation. The three are disjoint. Absent on the legacy count-only
25564
+ // response until the resolution feature lands.
25525
25565
  caught: external_exports.number().int().nonnegative().optional(),
25526
- openAtRest: external_exports.number().int().nonnegative().optional()
25566
+ openAtRest: external_exports.number().int().nonnegative().optional(),
25567
+ dismissed: external_exports.number().int().nonnegative().optional(),
25568
+ // The two halves of `caught`, for a reader that wants them apart: `handled` =
25569
+ // in-flight findings an enforcement action already contained; `resolved` =
25570
+ // at-rest findings closed out by fixing them. `handled + resolved === caught`.
25571
+ handled: external_exports.number().int().nonnegative().optional(),
25572
+ resolved: external_exports.number().int().nonnegative().optional()
25527
25573
  }).meta({ id: "SeveritySummaryItem" });
25528
25574
  var SeveritySummaryResponse = external_exports.object({
25529
25575
  // Sum of bySeverity[].count.
@@ -25531,6 +25577,9 @@ var SeveritySummaryResponse = external_exports.object({
25531
25577
  // Findings still open at rest (sum of bySeverity[].openAtRest). Optional and
25532
25578
  // additive — absent on the legacy response until the resolution feature lands.
25533
25579
  needsRemediation: external_exports.number().int().nonnegative().optional(),
25580
+ // Findings a user dismissed (sum of bySeverity[].dismissed). Excluded from
25581
+ // needsRemediation, and kept visible here so an accepted risk is not erased.
25582
+ dismissed: external_exports.number().int().nonnegative().optional(),
25534
25583
  // All four severity levels are always present (count may be 0).
25535
25584
  bySeverity: external_exports.array(SeveritySummaryItem)
25536
25585
  }).meta({ id: "SeveritySummaryResponse" });
@@ -32150,7 +32199,10 @@ var SqliteResolutionsRepository = class {
32150
32199
  * Insert many dispositions as ONE transaction — all of them or none.
32151
32200
  *
32152
32201
  * A dashboard dismissal closes every open finding of a rule, which is one
32153
- * write per key; run loose, a fault partway leaves half a rule closed with
32202
+ * write per key. It reaches this through
32203
+ * `LocalDatabase.dismissOpenFindingsForRule`, which calls it inside the
32204
+ * transaction that selected the keys, so there it runs as a SAVEPOINT of
32205
+ * that transaction. Run loose, a fault partway leaves half a rule closed with
32154
32206
  * nothing recording that the other half was meant to be. The caller then has
32155
32207
  * no way to tell a partial run from a complete one, because the card it
32156
32208
  * refreshes into just shows a smaller number either way.
@@ -32370,6 +32422,7 @@ function toSighting(row) {
32370
32422
  var SELECT_COLUMNS = `
32371
32423
  pointer_id AS pointerId,
32372
32424
  value_fingerprint AS valueFingerprint,
32425
+ value_identity_fingerprint AS valueIdentityFingerprint,
32373
32426
  fingerprint_key_version AS fingerprintKeyVersion,
32374
32427
  key_version AS keyVersion,
32375
32428
  format_version AS formatVersion,
@@ -32394,13 +32447,13 @@ var SqliteSecretVaultRepository = class {
32394
32447
  this.db = db;
32395
32448
  this.insertStmt = db.prepare(
32396
32449
  `INSERT INTO secret_vault (
32397
- pointer_id, value_fingerprint, fingerprint_key_version, key_version,
32398
- format_version, category, rule_id, masked_match, provider,
32450
+ pointer_id, value_fingerprint, value_identity_fingerprint,
32451
+ fingerprint_key_version, key_version, format_version, category, rule_id, masked_match, provider,
32399
32452
  ciphertext, nonce, auth_tag,
32400
32453
  user_authorized, occurrence_count, first_seen, last_seen
32401
32454
  ) VALUES (
32402
- :pointerId, :valueFingerprint, :fingerprintKeyVersion, :keyVersion,
32403
- :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32455
+ :pointerId, :valueFingerprint, :valueIdentityFingerprint,
32456
+ :fingerprintKeyVersion, :keyVersion, :formatVersion, :category, :ruleId, :maskedMatch, :provider,
32404
32457
  :ciphertext, :nonce, :authTag,
32405
32458
  :userAuthorized, 1, :now, :now
32406
32459
  )`
@@ -32425,7 +32478,13 @@ var SqliteSecretVaultRepository = class {
32425
32478
  );
32426
32479
  this.refreshFingerprintStmt = db.prepare(
32427
32480
  `UPDATE secret_vault
32428
- SET value_fingerprint = :valueFingerprint, fingerprint_key_version = :fingerprintKeyVersion
32481
+ SET value_fingerprint = :valueFingerprint,
32482
+ value_identity_fingerprint = :valueIdentityFingerprint,
32483
+ fingerprint_key_version = :fingerprintKeyVersion
32484
+ WHERE pointer_id = :pointerId`
32485
+ );
32486
+ this.setIdentityStmt = db.prepare(
32487
+ `UPDATE secret_vault SET value_identity_fingerprint = :valueIdentityFingerprint
32429
32488
  WHERE pointer_id = :pointerId`
32430
32489
  );
32431
32490
  this.deleteByPointerStmt = db.prepare(`DELETE FROM secret_vault WHERE pointer_id = :pointerId`);
@@ -32442,6 +32501,7 @@ var SqliteSecretVaultRepository = class {
32442
32501
  listStmt;
32443
32502
  replaceCiphertextStmt;
32444
32503
  refreshFingerprintStmt;
32504
+ setIdentityStmt;
32445
32505
  deleteByPointerStmt;
32446
32506
  derefStmt;
32447
32507
  /**
@@ -32472,6 +32532,7 @@ var SqliteSecretVaultRepository = class {
32472
32532
  bindParams({
32473
32533
  pointerId: input2.pointerId,
32474
32534
  valueFingerprint: input2.valueFingerprint,
32535
+ valueIdentityFingerprint: input2.valueIdentityFingerprint,
32475
32536
  fingerprintKeyVersion: input2.fingerprintKeyVersion,
32476
32537
  keyVersion: input2.keyVersion,
32477
32538
  formatVersion: input2.formatVersion ?? POINTER_FORMAT_VERSION,
@@ -32533,7 +32594,15 @@ var SqliteSecretVaultRepository = class {
32533
32594
  replaceCiphertext(pointerId, next) {
32534
32595
  this.replaceCiphertextStmt.run({ pointerId, ...next });
32535
32596
  }
32536
- /** Re-derive an entry's fingerprint under a new fingerprint-key epoch. */
32597
+ /**
32598
+ * Correct an entry's identity fingerprint in place, leaving its exact
32599
+ * fingerprint and key epoch alone. For a row whose identity column still holds
32600
+ * the exact value copied in by the migration that added it.
32601
+ */
32602
+ setIdentityFingerprint(pointerId, valueIdentityFingerprint) {
32603
+ this.setIdentityStmt.run({ pointerId, valueIdentityFingerprint });
32604
+ }
32605
+ /** Re-derive an entry's fingerprints under a new fingerprint-key epoch. */
32537
32606
  refreshFingerprint(pointerId, next) {
32538
32607
  this.refreshFingerprintStmt.run({ pointerId, ...next });
32539
32608
  }
@@ -32664,7 +32733,7 @@ var SqliteSecretVaultRepository = class {
32664
32733
  `SELECT ${INVENTORY_COLUMNS},
32665
32734
  (SELECT e.id FROM exceptions e
32666
32735
  WHERE e.rule_id = v.rule_id
32667
- AND e.value_fingerprint = v.value_fingerprint
32736
+ AND e.value_fingerprint = v.value_identity_fingerprint
32668
32737
  AND e.key_version = v.fingerprint_key_version
32669
32738
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32670
32739
  LIMIT 1) AS grant_id
@@ -32707,7 +32776,7 @@ var SqliteSecretVaultRepository = class {
32707
32776
  `SELECT ${INVENTORY_COLUMNS},
32708
32777
  (SELECT e.id FROM exceptions e
32709
32778
  WHERE e.rule_id = v.rule_id
32710
- AND e.value_fingerprint = v.value_fingerprint
32779
+ AND e.value_fingerprint = v.value_identity_fingerprint
32711
32780
  AND e.key_version = v.fingerprint_key_version
32712
32781
  AND ${ACTIVE_REVEAL_GRANT_PREDICATE}
32713
32782
  LIMIT 1) AS grant_id
@@ -32811,6 +32880,18 @@ var OPEN_AT_REST_FINDINGS_SQL = `FROM inspection_findings f
32811
32880
  OR latest.status IS NULL
32812
32881
  OR latest.status NOT IN ('resolved', 'dismissed')
32813
32882
  )`;
32883
+ function selectOpenFindingKeysForRule(db, ruleId) {
32884
+ const rows = allRows(
32885
+ db.prepare(
32886
+ `SELECT DISTINCT f.finding_key AS finding_key
32887
+ ${OPEN_AT_REST_FINDINGS_SQL}
32888
+ AND d.rule_id = :ruleId
32889
+ AND f.finding_key IS NOT NULL`
32890
+ ),
32891
+ { ruleId }
32892
+ );
32893
+ return rows.map((r) => r.finding_key);
32894
+ }
32814
32895
  var SEVERITIES = ["critical", "high", "medium", "low"];
32815
32896
  var ACTION_TO_KIND = {
32816
32897
  block: "blocked",
@@ -32867,16 +32948,16 @@ var SqliteSecurityRepository = class {
32867
32948
  // findings are caught only once their latest disposition is resolved,
32868
32949
  // otherwise they are open-at-rest.
32869
32950
  //
32870
- // NOTE for future manual-resolution writers: only latest status
32871
- // 'resolved' counts as caught above. When acknowledged/dismissed/
32872
- // false-positive manual dispositions land, this must keep filtering by
32873
- // status/method — 'acknowledged' is accepted risk, not a fix, and must NOT
32874
- // be bucketed as caught alongside 'resolved'.
32951
+ // Only latest status 'resolved' counts as caught above. 'dismissed' is its
32952
+ // own bucket: a judgement rather than a fix, so it is neither caught nor
32953
+ // needing remediation, and stays countable. A further manual disposition
32954
+ // (acknowledged, false-positive) must be placed deliberately — 'acknowledged'
32955
+ // is accepted risk, not a fix, and must NOT be bucketed as caught.
32875
32956
  //
32876
32957
  // Legacy at-rest findings from pre-branch scans carry finding_key = NULL —
32877
32958
  // the resolution lifecycle is keyed by finding_key, so it can never attach a
32878
32959
  // disposition to (or clear) one of these on re-scan. They are excluded from
32879
- // both caught and openAtRest (untracked, not "needs remediation forever"),
32960
+ // all three buckets (untracked, not "needs remediation forever"),
32880
32961
  // but still counted in total/count below — this keeps this predicate
32881
32962
  // consistent with SqliteResolutionsRepository.openAtRestKeysForPath, which
32882
32963
  // already filters `finding_key IS NOT NULL`.
@@ -32899,12 +32980,25 @@ var SqliteSecurityRepository = class {
32899
32980
  WHEN latest.status = 'resolved' THEN 1
32900
32981
  ELSE 0
32901
32982
  END) AS caught,
32983
+ SUM(CASE WHEN e.event_type != 'code_change' THEN 1 ELSE 0 END) AS handled,
32984
+ SUM(CASE
32985
+ WHEN e.event_type = 'code_change'
32986
+ AND f.finding_key IS NOT NULL
32987
+ AND latest.status = 'resolved' THEN 1
32988
+ ELSE 0
32989
+ END) AS resolved,
32902
32990
  SUM(CASE
32903
32991
  WHEN e.event_type = 'code_change'
32904
32992
  AND f.finding_key IS NOT NULL
32905
- AND (latest.status IS NULL OR latest.status != 'resolved') THEN 1
32993
+ AND (latest.status IS NULL
32994
+ OR latest.status NOT IN ('resolved', 'dismissed')) THEN 1
32995
+ ELSE 0
32996
+ END) AS open_at_rest,
32997
+ SUM(CASE
32998
+ WHEN e.event_type = 'code_change'
32999
+ AND latest.status = 'dismissed' THEN 1
32906
33000
  ELSE 0
32907
- END) AS open_at_rest
33001
+ END) AS dismissed
32908
33002
  FROM inspection_findings f
32909
33003
  JOIN audit_events e INDEXED BY idx_audit_capture_rollup ON e.id = f.audit_event_id
32910
33004
  JOIN inspection_definitions d ON d.id = f.inspection_definition_id
@@ -32919,11 +33013,15 @@ var SqliteSecurityRepository = class {
32919
33013
  severity,
32920
33014
  count: byRow.get(severity)?.count ?? 0,
32921
33015
  caught: byRow.get(severity)?.caught ?? 0,
32922
- openAtRest: byRow.get(severity)?.open_at_rest ?? 0
33016
+ handled: byRow.get(severity)?.handled ?? 0,
33017
+ resolved: byRow.get(severity)?.resolved ?? 0,
33018
+ openAtRest: byRow.get(severity)?.open_at_rest ?? 0,
33019
+ dismissed: byRow.get(severity)?.dismissed ?? 0
32923
33020
  }));
32924
33021
  const total = bySeverity.reduce((sum, s) => sum + s.count, 0);
32925
33022
  const needsRemediation = bySeverity.reduce((sum, s) => sum + s.openAtRest, 0);
32926
- return Promise.resolve({ total, needsRemediation, bySeverity });
33023
+ const dismissed = bySeverity.reduce((sum, s) => sum + s.dismissed, 0);
33024
+ return Promise.resolve({ total, needsRemediation, dismissed, bySeverity });
32927
33025
  }
32928
33026
  // Range is echoed but does not change the result today — coverage is a constant
32929
33027
  // business fact (see SCAN_COVERAGE), not a measured per-window metric. Order
@@ -33240,10 +33338,10 @@ var SqliteSecurityRepository = class {
33240
33338
  * machine, and the second reported "no recommendations" over live exposure.
33241
33339
  *
33242
33340
  * `open` mirrors `deriveFindingStatus` — at-rest, minus resolved and dismissed —
33243
- * so a row's count is exactly what `?status=open&type=<rule>` returns. Note that
33244
- * is NOT `severitySummary`'s `openAtRest`, which keeps dismissed findings (a
33245
- * dismissal is a judgement, not a remediation) and drops untracked legacy rows.
33246
- * The two answer different questions and only this one has to match a link.
33341
+ * so a row's count is exactly what `?status=open&type=<rule>` returns. It
33342
+ * differs from `severitySummary`'s `openAtRest` only in including untracked
33343
+ * legacy rows, which that bucket leaves out; dismissed is excluded from both.
33344
+ * Only this one has to match a link.
33247
33345
  *
33248
33346
  * Aggregated in SQL: the result is O(distinct rule × category × severity), so a
33249
33347
  * whole-store scope costs a grouped scan rather than a row per finding.
@@ -33271,6 +33369,8 @@ var SqliteSecurityRepository = class {
33271
33369
  /**
33272
33370
  * The distinct `finding_key`s behind ONE rule's {@link recommendationInputs}
33273
33371
  * tally — what a dashboard dismissal of that row writes a disposition for.
33372
+ * The dismissal itself does not call this: it reads the same set through
33373
+ * {@link selectOpenFindingKeysForRule}, inside its own write transaction.
33274
33374
  *
33275
33375
  * It shares {@link OPEN_AT_REST_FINDINGS_SQL} with the count rather than
33276
33376
  * restating the predicate, because a dismissal has to act on exactly the set
@@ -33287,16 +33387,7 @@ var SqliteSecurityRepository = class {
33287
33387
  * this set SMALLER than the tally, never larger.
33288
33388
  */
33289
33389
  openFindingKeysForRule(ruleId) {
33290
- const rows = allRows(
33291
- this.db.prepare(
33292
- `SELECT DISTINCT f.finding_key AS finding_key
33293
- ${OPEN_AT_REST_FINDINGS_SQL}
33294
- AND d.rule_id = :ruleId
33295
- AND f.finding_key IS NOT NULL`
33296
- ),
33297
- { ruleId }
33298
- );
33299
- return Promise.resolve(rows.map((r) => r.finding_key));
33390
+ return Promise.resolve(selectOpenFindingKeysForRule(this.db, ruleId));
33300
33391
  }
33301
33392
  // Findings whose parent event occurred in [fromMs, toMs), with the parent's
33302
33393
  // epoch-millis timestamp. started_at is an INTEGER column, so the bounds stay
@@ -34342,6 +34433,31 @@ function openLocalDatabase(dir, options = {}) {
34342
34433
  );
34343
34434
  });
34344
34435
  }
34436
+ function dismissOpenFindingsForRule(ruleId, disposition) {
34437
+ let dismissed = 0;
34438
+ withTransaction(
34439
+ db,
34440
+ () => {
34441
+ const keys = selectOpenFindingKeysForRule(db, ruleId);
34442
+ resolutions.insertResolutions(
34443
+ keys.map((findingKey) => ({
34444
+ findingKey,
34445
+ status: "dismissed",
34446
+ method: disposition.method,
34447
+ resolvedAt: disposition.resolvedAt,
34448
+ evidence: disposition.evidence
34449
+ }))
34450
+ );
34451
+ dismissed = keys.length;
34452
+ },
34453
+ // IMMEDIATE takes the write lock at BEGIN, before the select, which is
34454
+ // what keeps a concurrent resolve out of the gap. It also makes waiting
34455
+ // on a busy writer an ordinary busy_timeout wait rather than a
34456
+ // read-to-write upgrade SQLite refuses to retry.
34457
+ "IMMEDIATE"
34458
+ );
34459
+ return dismissed;
34460
+ }
34345
34461
  function recordCapture(event, detected) {
34346
34462
  failOpenTransaction(db, () => {
34347
34463
  const sessionId = event.metadata?.sessionId;
@@ -34525,6 +34641,7 @@ function openLocalDatabase(dir, options = {}) {
34525
34641
  inspectionDefinitions,
34526
34642
  inspectionFindings,
34527
34643
  recordCapture,
34644
+ dismissOpenFindingsForRule,
34528
34645
  markCaptureDelivered,
34529
34646
  markCaptureOwed,
34530
34647
  markAuditEventsDelivered,
@@ -35282,6 +35399,82 @@ function escapeRegExp2(value) {
35282
35399
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
35283
35400
  }
35284
35401
 
35402
+ // ../../packages/detections/src/format-chars.ts
35403
+ var HAS_FORMAT_CHAR = new RegExp("\\p{Cf}", "u");
35404
+ var FORMAT_CHAR_GLOBAL = new RegExp("\\p{Cf}", "gu");
35405
+ function normalizeFormatChars(text) {
35406
+ if (!HAS_FORMAT_CHAR.test(text)) return void 0;
35407
+ const normalizedParts = [];
35408
+ const segments = [];
35409
+ let cursor = 0;
35410
+ let normLength = 0;
35411
+ for (const match of text.matchAll(FORMAT_CHAR_GLOBAL)) {
35412
+ const matchStart = match.index;
35413
+ if (matchStart > cursor) {
35414
+ const length = matchStart - cursor;
35415
+ normalizedParts.push(text.slice(cursor, matchStart));
35416
+ segments.push({ normStart: normLength, origStart: cursor, length });
35417
+ normLength += length;
35418
+ }
35419
+ cursor = matchStart + match[0].length;
35420
+ }
35421
+ if (cursor < text.length) {
35422
+ const length = text.length - cursor;
35423
+ normalizedParts.push(text.slice(cursor));
35424
+ segments.push({ normStart: normLength, origStart: cursor, length });
35425
+ }
35426
+ return { normalized: normalizedParts.join(""), segments };
35427
+ }
35428
+ function segmentAt(segments, normPos) {
35429
+ let lo = 0;
35430
+ let hi = segments.length - 1;
35431
+ while (lo < hi) {
35432
+ const mid = lo + hi >> 1;
35433
+ const segment = segments[mid];
35434
+ if (segment !== void 0 && normPos >= segment.normStart + segment.length) {
35435
+ lo = mid + 1;
35436
+ } else {
35437
+ hi = mid;
35438
+ }
35439
+ }
35440
+ const found = segments[lo];
35441
+ if (found === void 0) {
35442
+ throw new Error(`normPos ${String(normPos)} has no covering segment`);
35443
+ }
35444
+ return found;
35445
+ }
35446
+ function mapSpanToOriginal(span, normalization) {
35447
+ const { segments } = normalization;
35448
+ const startSegment = segmentAt(segments, span.start);
35449
+ const start = startSegment.origStart + (span.start - startSegment.normStart);
35450
+ const endSegment = segmentAt(segments, span.end - 1);
35451
+ const end = endSegment.origStart + (span.end - 1 - endSegment.normStart) + 1;
35452
+ return { start, end };
35453
+ }
35454
+ function normalizedOffset(origPos, segments) {
35455
+ let lo = 0;
35456
+ let hi = segments.length;
35457
+ while (lo < hi) {
35458
+ const mid = lo + hi >> 1;
35459
+ const segment = segments[mid];
35460
+ if (segment !== void 0 && segment.origStart + segment.length <= origPos) {
35461
+ lo = mid + 1;
35462
+ } else {
35463
+ hi = mid;
35464
+ }
35465
+ }
35466
+ const found = segments[Math.min(lo, segments.length - 1)];
35467
+ if (found === void 0) return 0;
35468
+ return found.normStart + Math.min(Math.max(0, origPos - found.origStart), found.length);
35469
+ }
35470
+ function mapSpanToNormalized(span, normalization) {
35471
+ const { segments } = normalization;
35472
+ return {
35473
+ start: normalizedOffset(span.start, segments),
35474
+ end: normalizedOffset(span.end, segments)
35475
+ };
35476
+ }
35477
+
35285
35478
  // ../../packages/detections/src/regex-cache.ts
35286
35479
  var singles = /* @__PURE__ */ new WeakMap();
35287
35480
  var keywordLists = /* @__PURE__ */ new WeakMap();
@@ -35443,29 +35636,35 @@ function registerPack(pack) {
35443
35636
  function getLoadedRules() {
35444
35637
  return [...packs.values()].flatMap((p) => p.rules);
35445
35638
  }
35446
- function isCorroborated(candidate, candidates, text) {
35639
+ function spansOverlap(a, b) {
35640
+ return a.start < b.end && a.end > b.start;
35641
+ }
35642
+ function isCorroborated(candidate, candidates, text, normalization) {
35447
35643
  const req = candidate.rule.requiresNearby;
35448
35644
  if (!req) return true;
35449
35645
  const halfWindow = req.windowChars;
35450
- const { start, end } = candidate.match.span;
35451
- const winStart = start - halfWindow;
35452
- const winEnd = end + halfWindow;
35646
+ const ns = candidate.normSpan;
35647
+ const winStart = ns.start - halfWindow;
35648
+ const winEnd = ns.end + halfWindow;
35453
35649
  const categories = req.categories;
35454
35650
  const ruleIds = req.ruleIds;
35455
35651
  if (categories?.length || ruleIds?.length) {
35456
35652
  for (const other of candidates) {
35457
35653
  if (other === candidate) continue;
35458
- const os = other.match.span;
35459
- if (os.end < winStart || os.start > winEnd) continue;
35460
- if (other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category)) {
35461
- return true;
35654
+ if (other.normSpan.end < winStart || other.normSpan.start > winEnd) continue;
35655
+ const relevant = other.match.ruleId !== candidate.match.ruleId && categories?.includes(other.match.category) === true || ruleIds?.includes(other.match.ruleId) === true;
35656
+ if (!relevant) continue;
35657
+ if (other.match.ruleId === candidate.match.ruleId && spansOverlap(other.match.span, candidate.match.span)) {
35658
+ continue;
35462
35659
  }
35463
- if (ruleIds?.includes(other.match.ruleId)) return true;
35660
+ return true;
35464
35661
  }
35465
35662
  }
35466
35663
  const labels = req.labels;
35467
35664
  if (labels && labels.length > 0) {
35468
- const haystack = text.slice(Math.max(0, winStart), winEnd);
35665
+ const { start, end } = candidate.match.span;
35666
+ const haystack = text.slice(Math.max(0, start - halfWindow), end + halfWindow);
35667
+ const normalizedHaystack = normalization === void 0 ? void 0 : normalization.normalized.slice(Math.max(0, winStart), winEnd);
35469
35668
  for (const re of memoizedRegExpList(
35470
35669
  "label",
35471
35670
  req,
@@ -35474,29 +35673,20 @@ function isCorroborated(candidate, candidates, text) {
35474
35673
  return trimmed.length === 0 ? void 0 : new RegExp(`(?<![A-Za-z0-9])${escapeRegExp2(trimmed)}(?![A-Za-z0-9])`, "i");
35475
35674
  })
35476
35675
  )) {
35477
- if (re?.test(haystack)) return true;
35676
+ if (!re) continue;
35677
+ if (re.test(haystack)) return true;
35678
+ if (normalizedHaystack !== void 0 && re.test(normalizedHaystack)) return true;
35478
35679
  }
35479
35680
  }
35480
35681
  return false;
35481
35682
  }
35482
- function extensionOf(filePath) {
35483
- const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
35484
- const dot = base.lastIndexOf(".");
35485
- return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
35486
- }
35487
- function ruleApplies(rule, extension) {
35488
- if (!rule.appliesTo || extension === void 0) return true;
35489
- return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
35490
- }
35491
- function scan(text, rules, context) {
35492
- const ruleset = rules ?? getLoadedRules();
35493
- const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
35683
+ function buildCandidates(matchText, ruleset, extension) {
35494
35684
  const candidates = [];
35495
35685
  for (const rule of ruleset) {
35496
35686
  if (!ruleApplies(rule, extension)) continue;
35497
- const spans = MATCHERS[rule.matcher.type](text, rule);
35687
+ const spans = MATCHERS[rule.matcher.type](matchText, rule);
35498
35688
  for (const span of spans) {
35499
- const rawMatch = text.slice(span.start, span.end);
35689
+ const rawMatch = matchText.slice(span.start, span.end);
35500
35690
  if (!passesPostValidators(rule, rawMatch)) continue;
35501
35691
  candidates.push({
35502
35692
  rule,
@@ -35507,10 +35697,31 @@ function scan(text, rules, context) {
35507
35697
  span,
35508
35698
  rawMatch,
35509
35699
  confidence: 0.9
35510
- }
35700
+ },
35701
+ // In `matchText`'s own coordinates, which is the normalized text for
35702
+ // a normalized-pass candidate and so already right; an original-pass
35703
+ // candidate on the slow path is re-derived by withNormalizedSpan.
35704
+ normSpan: span
35511
35705
  });
35512
35706
  }
35513
35707
  }
35708
+ return candidates;
35709
+ }
35710
+ function mapCandidateToOriginal(candidate, normalization, text) {
35711
+ const span = mapSpanToOriginal(candidate.match.span, normalization);
35712
+ return {
35713
+ rule: candidate.rule,
35714
+ match: { ...candidate.match, span, rawMatch: text.slice(span.start, span.end) },
35715
+ // Deliberately NOT remapped: `normSpan` is the span the primitive match
35716
+ // was found at in the normalized text, which is exactly the coordinate
35717
+ // space windows are measured in. See the `Candidate` comment.
35718
+ normSpan: candidate.normSpan
35719
+ };
35720
+ }
35721
+ function withNormalizedSpan(candidate, normalization) {
35722
+ return { ...candidate, normSpan: mapSpanToNormalized(candidate.match.span, normalization) };
35723
+ }
35724
+ function gate(candidates, text, normalization) {
35514
35725
  const findings = [];
35515
35726
  for (const candidate of candidates) {
35516
35727
  const req = candidate.rule.requiresNearby;
@@ -35518,7 +35729,7 @@ function scan(text, rules, context) {
35518
35729
  findings.push(candidate.match);
35519
35730
  continue;
35520
35731
  }
35521
- if (!isCorroborated(candidate, candidates, text)) continue;
35732
+ if (!isCorroborated(candidate, candidates, text, normalization)) continue;
35522
35733
  const boost = req.confidenceBoost;
35523
35734
  findings.push(
35524
35735
  boost ? { ...candidate.match, confidence: Math.min(0.99, candidate.match.confidence + boost) } : candidate.match
@@ -35526,6 +35737,81 @@ function scan(text, rules, context) {
35526
35737
  }
35527
35738
  return findings;
35528
35739
  }
35740
+ function closeRegion(open3, text) {
35741
+ const span = { start: open3.start, end: open3.end };
35742
+ return {
35743
+ ruleId: open3.ruleId,
35744
+ category: open3.category,
35745
+ severity: open3.severity,
35746
+ span,
35747
+ rawMatch: text.slice(span.start, span.end),
35748
+ confidence: open3.confidence
35749
+ };
35750
+ }
35751
+ function mergeOverlappingSameRule(findings, text) {
35752
+ if (findings.length === 0) return findings;
35753
+ const groups = /* @__PURE__ */ new Map();
35754
+ const ruleOrder = [];
35755
+ for (const finding of findings) {
35756
+ const group = groups.get(finding.ruleId);
35757
+ if (group) {
35758
+ group.push(finding);
35759
+ } else {
35760
+ groups.set(finding.ruleId, [finding]);
35761
+ ruleOrder.push(finding.ruleId);
35762
+ }
35763
+ }
35764
+ const merged = [];
35765
+ for (const ruleId of ruleOrder) {
35766
+ const group = groups.get(ruleId) ?? [];
35767
+ const sorted = [...group].sort(
35768
+ (a, b) => a.span.start - b.span.start || a.span.end - b.span.end
35769
+ );
35770
+ let open3;
35771
+ for (const finding of sorted) {
35772
+ if (open3 && finding.span.start < open3.end) {
35773
+ open3.end = Math.max(open3.end, finding.span.end);
35774
+ open3.confidence = Math.max(open3.confidence, finding.confidence);
35775
+ continue;
35776
+ }
35777
+ if (open3) merged.push(closeRegion(open3, text));
35778
+ open3 = {
35779
+ start: finding.span.start,
35780
+ end: finding.span.end,
35781
+ confidence: finding.confidence,
35782
+ ruleId: finding.ruleId,
35783
+ category: finding.category,
35784
+ severity: finding.severity
35785
+ };
35786
+ }
35787
+ if (open3) merged.push(closeRegion(open3, text));
35788
+ }
35789
+ return merged;
35790
+ }
35791
+ function extensionOf(filePath) {
35792
+ const base = filePath.slice(Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) + 1);
35793
+ const dot = base.lastIndexOf(".");
35794
+ return dot > 0 ? base.slice(dot).toLowerCase() : void 0;
35795
+ }
35796
+ function ruleApplies(rule, extension) {
35797
+ if (!rule.appliesTo || extension === void 0) return true;
35798
+ return rule.appliesTo.extensions.some((e) => e.toLowerCase() === extension);
35799
+ }
35800
+ function scan(text, rules, context) {
35801
+ const ruleset = rules ?? getLoadedRules();
35802
+ const extension = context?.filePath ? extensionOf(context.filePath) : void 0;
35803
+ const normalization = normalizeFormatChars(text);
35804
+ const originalCandidates = buildCandidates(text, ruleset, extension);
35805
+ if (!normalization) return gate(originalCandidates, text, void 0);
35806
+ const pooledOriginal = originalCandidates.map(
35807
+ (candidate) => withNormalizedSpan(candidate, normalization)
35808
+ );
35809
+ const normalizedCandidates = buildCandidates(normalization.normalized, ruleset, extension).map(
35810
+ (candidate) => mapCandidateToOriginal(candidate, normalization, text)
35811
+ );
35812
+ const findings = gate([...pooledOriginal, ...normalizedCandidates], text, normalization);
35813
+ return mergeOverlappingSameRule(findings, text);
35814
+ }
35529
35815
  var SEVERITY_RANK2 = {
35530
35816
  critical: 3,
35531
35817
  high: 2,
@@ -38683,19 +38969,19 @@ function runPreview(deps, planIO) {
38683
38969
  } catch {
38684
38970
  storeUnavailable = true;
38685
38971
  }
38686
- const gate = [];
38972
+ const gate2 = [];
38687
38973
  if (storeUnavailable) {
38688
- gate.push(present.storeUnavailableNote);
38974
+ gate2.push(present.storeUnavailableNote);
38689
38975
  }
38690
- gate.push(renderPosturePlan(plan.posture, storeUnavailable ? {} : current));
38691
- gate.push(renderShowcase(plan.showcase));
38692
- gate.push(renderSuppressionGate(plan.entries, plan.join));
38976
+ gate2.push(renderPosturePlan(plan.posture, storeUnavailable ? {} : current));
38977
+ gate2.push(renderShowcase(plan.showcase));
38978
+ gate2.push(renderSuppressionGate(plan.entries, plan.join));
38693
38979
  if (plan.skipped.length > 0) {
38694
- gate.push(
38980
+ gate2.push(
38695
38981
  `Skipped (fail-secure): ${plan.skipped.map((s) => `${s.category} \u2014 ${s.reason}`).join("; ")}`
38696
38982
  );
38697
38983
  }
38698
- gate.push(`Notes: ${plan.notes}`);
38984
+ gate2.push(`Notes: ${plan.notes}`);
38699
38985
  const preview = {
38700
38986
  categories: plan.showcase.map((c) => ({
38701
38987
  category: c.category,
@@ -38708,9 +38994,9 @@ function runPreview(deps, planIO) {
38708
38994
  const maskedFindings = deriveSurfacedSecretFindings(hits, rec, plan);
38709
38995
  const falsePositivePatterns = deriveFalsePositivePatterns(reps, rec, plan);
38710
38996
  const calibration = present.frameCalibration(preview, maskedFindings, falsePositivePatterns);
38711
- gate.push(calibration.copy);
38712
- gate.push(present.renderRecommendedPosture(preview.posture));
38713
- deps.stdout(present.show(present.fenced(gate.join("\n\n"))));
38997
+ gate2.push(calibration.copy);
38998
+ gate2.push(present.renderRecommendedPosture(preview.posture));
38999
+ deps.stdout(present.show(present.fenced(gate2.join("\n\n"))));
38714
39000
  deps.stdout(present.frameJsonBlock(calibration.frame));
38715
39001
  const planPath = planIO.write(plan, storeUnavailable ? {} : current, rawValues);
38716
39002
  deps.stdout(`