conbridge-agent 0.8.1 → 0.9.1

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.
@@ -29,7 +29,7 @@ __export(cli_exports, {
29
29
  module.exports = __toCommonJS(cli_exports);
30
30
 
31
31
  // <define:__CONBRIDGE_BUILD__>
32
- var define_CONBRIDGE_BUILD_default = { version: "0.8.1", commit: "18da9064eede", built_at: "2026-11-12T23:54:03.139Z", keychain_helper_sha256: "0a2d65388c0acc75305386ce0d6b7ee2e522ed939f291eb5a50055197674c023", distribution: "npm" };
32
+ var define_CONBRIDGE_BUILD_default = { version: "0.9.1", commit: "8d2be2cfc4ba", built_at: "2026-11-23T15:05:57.439Z", keychain_helper_sha256: "0a2d65388c0acc75305386ce0d6b7ee2e522ed939f291eb5a50055197674c023", distribution: "npm" };
33
33
 
34
34
  // dist/cli.js
35
35
  var import_promises22 = require("node:readline/promises");
@@ -21323,6 +21323,7 @@ var WPDB_QUERY_PATTERN = /\bfor query\s.*?(?=\smade by\s|$)/gi;
21323
21323
  var SECRET_PAIR_PATTERN = /(["']?)\b(password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|auth|authorization|session|cookie)\1(\s*[=:]\s*)(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|(?!<secret>)[^\s&,;)"']+)/gi;
21324
21324
  var BEARER_PATTERN = /\b(Bearer|Basic)\s+(?!<secret>)[A-Za-z0-9._~+/=-]+/g;
21325
21325
  var SSH_FINGERPRINT_PATTERN = /\bSHA256:[A-Za-z0-9+/]{43}(?![A-Za-z0-9+/=])/g;
21326
+ var WINDOWS_ACCOUNT_PATTERN = /\b(log ?on as|to the user|account)(:?\s+)(?!(?:HKEY_\w{1,32}|HK(?:LM|CU|CR|CC|U))\\)(?:[\w.-]{1,63}|\.)\\(?:[^\\"'<>]{1,104}?(?= with the currently configured password\b)|[^\s\\"'<>]{1,104})/gi;
21326
21327
  var AUTH_LINE = /(authenticat|password|invalid user|illegal user|session|pam_|\bpam\b|access denied for user|accepted \w+ for|not allowed because|sudo|COMMAND=|\buser\b.{1,122}? (?:was )?not found\b)/i;
21327
21328
  var AUTH_USER_PATTERN = /\b((?:for )?(?:invalid |illegal )?user) (?:(.{1,120})(?= from \S+(?: port (?:\d|<n>)|$))|(.{1,120})(?= \S+ port (?:\d|<n>))|(.{1,120})(?<! was)(?= (?:was )?not found\b)|(.{1,120})(?= by PAM account configuration\b)|(.{1,120})(?=: password mismatch\b)|(.{1,120}?)(?= from | port |$))/gi;
21328
21329
  var AUTH_NOT_ALLOWED_PATTERN = /\b(User) (.{1,120})(?= from \S+ not allowed because\b)/g;
@@ -21399,6 +21400,7 @@ function redactLogMessage(message, options = {}) {
21399
21400
  result2 = result2.replace(URL_PATTERN, "<url>");
21400
21401
  result2 = result2.replace(EMAIL_PATTERN, "<email>");
21401
21402
  result2 = result2.replace(SSH_FINGERPRINT_PATTERN, "SHA256:<fingerprint>");
21403
+ result2 = result2.replace(WINDOWS_ACCOUNT_PATTERN, "$1$2<account>");
21402
21404
  if (AUTH_LINE.test(result2)) {
21403
21405
  result2 = result2.replace(AUTH_NOT_ALLOWED_PATTERN, "$1 <user>");
21404
21406
  result2 = result2.replace(AUTH_USER_PATTERN, "$1 <user>");
@@ -21667,7 +21669,7 @@ function ratingOfCvss(score) {
21667
21669
  var WINDOWS_ECOSYSTEM = "windows";
21668
21670
 
21669
21671
  // ../../packages/protocol/dist/security/components.js
21670
- var COMPONENT_RULES_VERSION = "2026-11-13.3";
21672
+ var COMPONENT_RULES_VERSION = "2026-11-19.1";
21671
21673
  var DAEMON_PACKAGES = Object.freeze([
21672
21674
  "openssh-server",
21673
21675
  "postfix",
@@ -22162,9 +22164,9 @@ function riskInputsOf(args) {
22162
22164
  }
22163
22165
 
22164
22166
  // ../../packages/protocol/dist/security/matching.js
22165
- var MATCHING_RULES_VERSION = "2026-11-13.4";
22167
+ var MATCHING_RULES_VERSION = "2026-11-19.1";
22166
22168
  var EVALUATION_RULES_VERSION = [COMPONENT_RULES_VERSION, MATCHING_RULES_VERSION, RISK_RULES_VERSION, BUCKET_RULES_VERSION].join("+");
22167
- var MATCHING_RULES_VERSION_V2 = "2026-11-13.4.v2";
22169
+ var MATCHING_RULES_VERSION_V2 = "2026-11-19.1.v2";
22168
22170
  var EVALUATION_RULES_VERSION_V2 = [COMPONENT_RULES_VERSION, MATCHING_RULES_VERSION_V2, RISK_RULES_VERSION_V2, BUCKET_RULES_VERSION_V2].join("+");
22169
22171
  var OPEN_CLASSES = ["confirmed", "potential", "unknown"];
22170
22172
  var isOpenClass = (value) => OPEN_CLASSES.includes(value);
@@ -22340,6 +22342,8 @@ function evaluateAsset(input2) {
22340
22342
  const v2 = input2.rules === "v2";
22341
22343
  const facts = input2.facts ?? null;
22342
22344
  const incomplete = input2.incomplete ?? { os: false, npm: false };
22345
+ const unreadImages = input2.unreadImages ?? /* @__PURE__ */ new Set();
22346
+ const imageRowUnseen = (row) => incomplete.image_list === true || (Array.isArray(row.image_refs) && row.image_refs.length > 0 ? row.image_refs.some((ref) => unreadImages.has(ref)) : incomplete.image === true);
22343
22347
  const previousBy = new Map(previous.map((row) => [`${row.finding_id}\0${row.component_key}`, row]));
22344
22348
  const events = [];
22345
22349
  if (lookup2 === null || context.receivedAtMs === null) {
@@ -22364,6 +22368,7 @@ function evaluateAsset(input2) {
22364
22368
  }
22365
22369
  const stale = context.nowMs > context.receivedAtMs + context.staleAfterMs;
22366
22370
  const hostHasEsm = input2.components.some((component) => component.origin === "esm" || component.ecosystem.startsWith("Ubuntu:Pro:"));
22371
+ const proChannelFor = (component) => hostHasEsm && component.source === "dpkg";
22367
22372
  const pendingKeys = /* @__PURE__ */ new Set();
22368
22373
  const pendingComponents = [];
22369
22374
  const pendingBefore = new Map((input2.previousPending ?? []).map((entry) => [entry.component_key, entry.since_ms]));
@@ -22487,21 +22492,42 @@ function evaluateAsset(input2) {
22487
22492
  for (const group3 of v2 ? groups : []) {
22488
22493
  if (group3.component.role !== "running_kernel")
22489
22494
  continue;
22490
- const target = stagedTarget(stagedStatusOf(group3, hostHasEsm), group3.component, nextKernelVersion, candidateKernelVersion);
22495
+ const target = stagedTarget(stagedStatusOf(group3, proChannelFor(group3.component)), group3.component, nextKernelVersion, candidateKernelVersion);
22491
22496
  if (target && !target.installed)
22492
22497
  stagedKernel.set(group3.canonical, target);
22493
22498
  }
22494
22499
  const closes = kernelCloses(next, candidate, runningAdvisories, stagedKernel);
22495
22500
  const kernelTarget = kernelTargetFrom(closes, next, candidate);
22501
+ const presentPackages = new Set(visible.map((component) => packageKey(component.ecosystem, component.name)));
22502
+ const presentSources = /* @__PURE__ */ new Map();
22503
+ for (const component of visible) {
22504
+ const key = packageKey(component.ecosystem, component.name);
22505
+ presentSources.set(key, (presentSources.get(key) ?? /* @__PURE__ */ new Set()).add(component.source));
22506
+ }
22507
+ const ownSourceUnseen = (row) => {
22508
+ const [ecosystem = "", name3 = ""] = row.component_key.split("|");
22509
+ if (ecosystem === "cpe")
22510
+ return incomplete.banner === true;
22511
+ const sources = presentSources.get(packageKey(ecosystem, name3));
22512
+ if (ecosystem === "npm")
22513
+ return incomplete.npm && !(typeof row.source === "string" && sources?.has(row.source) === true);
22514
+ return incomplete.os && ![...sources ?? []].some((source) => source !== "image");
22515
+ };
22496
22516
  const carry = /* @__PURE__ */ new Map();
22497
22517
  for (const row of previous) {
22498
22518
  if (!isOpenClass(row.class) || present.has(row.component_key) || leftOut.has(row.component_key) || isImageKernelRow(row))
22499
22519
  continue;
22520
+ if (row.source !== "image" && ownSourceUnseen(row))
22521
+ continue;
22500
22522
  const key = `${row.finding_id}\0${packageOf2(row.component_key)}`;
22501
22523
  const held = carry.get(key);
22502
22524
  if (!held || row.component_key < held.component_key)
22503
22525
  carry.set(key, row);
22504
22526
  }
22527
+ const rowKey = (row) => `${row.finding_id}\0${row.component_key}`;
22528
+ const groupRowKeys = new Set(groups.map((group3) => `${group3.canonical}\0${group3.component.key}`));
22529
+ const formerIdsOf = (group3) => [...new Set(group3.views.flatMap((view) => [view.id, ...view.aliases]))].filter((id) => id !== group3.canonical).sort();
22530
+ const movedRows = /* @__PURE__ */ new Map();
22505
22531
  const findingViews = /* @__PURE__ */ new Map();
22506
22532
  const rows = [];
22507
22533
  const settledRows = [];
@@ -22522,11 +22548,14 @@ function evaluateAsset(input2) {
22522
22548
  let fixState = states.includes("fix") || group3.noticeFixes.length > 0 ? "fix" : states.includes("no_fix") ? "no_fix" : "unknown";
22523
22549
  const deciding = group3.matches.find((match) => matchFixState2(match) === fixState) ?? group3.matches[0];
22524
22550
  const proFixed = fixState === "no_fix" ? [...new Set(group3.matches.flatMap((match) => match.pro_fixed ?? []))].slice(0, 20) : [];
22525
- const channel = proFixed.length > 0 && hostHasEsm ? "pro" : null;
22551
+ const channel = proFixed.length > 0 && proChannelFor(component) ? "pro" : null;
22526
22552
  if (channel)
22527
22553
  fixState = "fix";
22528
22554
  const exposure = component.exposure_unresolved ? "unknown" : component.exposure;
22529
- const before = previousBy.get(`${group3.canonical}\0${component.key}`);
22555
+ const formerIds = formerIdsOf(group3);
22556
+ const direct = previousBy.get(`${group3.canonical}\0${component.key}`);
22557
+ const former = formerIds.map((id) => previousBy.get(`${id}\0${component.key}`)).filter((row2) => row2 !== void 0 && !groupRowKeys.has(rowKey(row2)) && !movedRows.has(rowKey(row2)));
22558
+ const before = direct && isOpenClass(direct.class) ? direct : former.find((row2) => isOpenClass(row2.class)) ?? direct ?? former[0];
22530
22559
  let risk;
22531
22560
  let bucket;
22532
22561
  let rowClass = cls;
@@ -22534,6 +22563,10 @@ function evaluateAsset(input2) {
22534
22563
  let staged = null;
22535
22564
  const local = localRangeCheckOf({ ecosystem: component.ecosystem, installed: component.version, matches: group3.matches, notice_fixes: group3.noticeFixes });
22536
22565
  const clientOnly = component.role === "client_only";
22566
+ if (before?.class === "not_affected" && before.closed_reason === "local_range_check" && local?.value !== "not_affected" && group3.matches.some((match) => match.local_check_skipped === "stale_record") && group3.matches.every((match) => match.local_check_skipped === "stale_record" || match.local_check?.value === "not_affected"))
22567
+ continue;
22568
+ for (const row2 of former)
22569
+ movedRows.set(rowKey(row2), row2);
22537
22570
  if (!v2) {
22538
22571
  if (local?.value === "not_affected")
22539
22572
  rowClass = "not_affected";
@@ -22584,7 +22617,7 @@ function evaluateAsset(input2) {
22584
22617
  const byLocal = applicability.basis === "local_range_check" ? local : null;
22585
22618
  const mitigation = applicability.value === "affected" && applicability.reason !== "vendor_status_unknown" ? mitigationOf({ view: decidingOsv?.view ?? null, component, facts }) : null;
22586
22619
  const settles = applicability.value === "not_affected";
22587
- staged = settles ? null : stagedTarget(stagedStatusOf(group3, hostHasEsm), component, nextKernelVersion, candidateKernelVersion);
22620
+ staged = settles ? null : stagedTarget(stagedStatusOf(group3, proChannelFor(component)), component, nextKernelVersion, candidateKernelVersion);
22588
22621
  const stagedInstalled = staged?.installed === true;
22589
22622
  if (staged)
22590
22623
  fixState = "fix";
@@ -22622,10 +22655,12 @@ function evaluateAsset(input2) {
22622
22655
  const role = component.role ?? null;
22623
22656
  const nextVersion = (role === "running_kernel" && next?.advisories && !next.advisories.has(group3.canonical) ? next.component.version : null) ?? staged?.next_kernel ?? null;
22624
22657
  const candidateVersion = (role === "running_kernel" && candidate?.advisories && !candidate.advisories.has(group3.canonical) ? candidate.component.version : null) ?? staged?.candidate_kernel ?? null;
22625
- const carried = before || settled ? void 0 : carry.get(`${group3.canonical}\0${packageKey(component.ecosystem, component.name)}`);
22658
+ const carryKey = (id) => `${id}\0${packageKey(component.ecosystem, component.name)}`;
22659
+ const carried = before || settled ? void 0 : carry.get(carryKey(group3.canonical)) ?? formerIds.map((id) => carry.get(carryKey(id))).find((row2) => row2 !== void 0);
22660
+ const moved = before !== void 0 && before !== direct ? before : carried !== void 0 && carried.finding_id !== group3.canonical ? carried : null;
22626
22661
  const summary = before || carried || settled ? void 0 : previousWaitingOf(component);
22627
22662
  const fromSummary = summary !== void 0 && previousListed(component).has(group3.canonical);
22628
- const firstSeenHint = !fromSummary ? null : isTime(summary.first_seen?.[group3.canonical]) ? summary.first_seen[group3.canonical] : isTime(summary.since_ms) ? summary.since_ms : null;
22663
+ const firstSeenHint = moved ? isTime(moved.first_seen_at_ms) ? moved.first_seen_at_ms : null : !fromSummary ? null : isTime(summary.first_seen?.[group3.canonical]) ? summary.first_seen[group3.canonical] : isTime(summary.since_ms) ? summary.since_ms : null;
22629
22664
  const why = {
22630
22665
  rule: bucket.rule,
22631
22666
  severity: { rating: severity.rating, source: severity.source },
@@ -22663,6 +22698,7 @@ function evaluateAsset(input2) {
22663
22698
  candidate_kernel: candidateVersion,
22664
22699
  kernel_target: role === "running_kernel" ? kernelTarget : null,
22665
22700
  previous_component_key: carried?.component_key ?? null,
22701
+ ...moved ? { previous_finding_id: moved.finding_id } : {},
22666
22702
  first_seen_hint_ms: firstSeenHint,
22667
22703
  evidence: {
22668
22704
  advisory_ids: [...new Set(group3.views.map((view) => view.id))].sort(),
@@ -22744,7 +22780,6 @@ function evaluateAsset(input2) {
22744
22780
  modified: views.map((view) => view.modified).filter((value) => Boolean(value)).sort().at(-1) ?? null
22745
22781
  });
22746
22782
  }
22747
- const presentPackages = new Set(visible.map((component) => packageKey(component.ecosystem, component.name)));
22748
22783
  const pendingPackages = /* @__PURE__ */ new Map();
22749
22784
  for (const component of visible) {
22750
22785
  if (!pendingKeys.has(component.key))
@@ -22752,12 +22787,24 @@ function evaluateAsset(input2) {
22752
22787
  const key = packageKey(component.ecosystem, component.name);
22753
22788
  pendingPackages.set(key, [...pendingPackages.get(key) ?? [], component]);
22754
22789
  }
22790
+ const unsupportedPackages = /* @__PURE__ */ new Map();
22791
+ for (const component of visible) {
22792
+ if (!unsupportedKeys.has(component.key))
22793
+ continue;
22794
+ const key = packageKey(component.ecosystem, component.name);
22795
+ unsupportedPackages.set(key, [...unsupportedPackages.get(key) ?? [], component]);
22796
+ }
22755
22797
  const lowestPending = (components) => [...components].sort((a, b) => a.key < b.key ? -1 : 1).reduce((low, component) => DPKG_ECOSYSTEM.test(component.ecosystem) && compareDpkgVersions(component.version, low.version) === -1 ? component : low);
22756
22798
  const produced = new Set([...rows, ...settledRows].map((row) => `${row.finding_id}\0${row.component_key}`));
22757
- const carriedOn = new Set(rows.filter((row) => row.previous_component_key !== null).map((row) => `${row.finding_id}\0${row.previous_component_key}`));
22799
+ const carriedOn = new Set(rows.filter((row) => row.previous_component_key !== null).map((row) => `${row.previous_finding_id ?? row.finding_id}\0${row.previous_component_key}`));
22758
22800
  const closed = [];
22759
22801
  const marked = [];
22802
+ for (const row of movedRows.values()) {
22803
+ closed.push({ finding_id: row.finding_id, component_key: row.component_key, class: "fixed", reason: "superseded", score: 0, band: "none" });
22804
+ }
22760
22805
  for (const row of previous) {
22806
+ if (movedRows.has(rowKey(row)))
22807
+ continue;
22761
22808
  if (!isOpenClass(row.class) || produced.has(`${row.finding_id}\0${row.component_key}`))
22762
22809
  continue;
22763
22810
  if (pendingKeys.has(row.component_key))
@@ -22770,12 +22817,18 @@ function evaluateAsset(input2) {
22770
22817
  closing = closedRow(row, "not_affected", leftOutReason);
22771
22818
  } else if (!present.has(row.component_key) && isImageKernelRow(row)) {
22772
22819
  closing = closedRow(row, "not_affected", "kernel_in_image");
22820
+ } else if (!present.has(row.component_key) && row.source === "image" && imageRowUnseen(row)) {
22821
+ continue;
22822
+ } else if (!present.has(row.component_key) && row.source !== "image" && ownSourceUnseen(row)) {
22823
+ continue;
22773
22824
  } else if (!present.has(row.component_key)) {
22774
22825
  const [ecosystem = "", name3 = "", version3 = ""] = row.component_key.split("|");
22775
22826
  if (presentPackages.has(packageKey(ecosystem, name3))) {
22776
22827
  const newVersions = pendingPackages.get(packageKey(ecosystem, name3));
22828
+ const unanswered = unsupportedPackages.get(packageKey(ecosystem, name3)) ?? [];
22829
+ const carriesFix = (component) => carriesEveryFix(component.ecosystem, row.fixed, component.version);
22777
22830
  if (newVersions) {
22778
- const fixedNow = !carriedOn.has(`${row.finding_id}\0${row.component_key}`) && newVersions.every((component) => carriesEveryFix(component.ecosystem, row.fixed, component.version));
22831
+ const fixedNow = !carriedOn.has(`${row.finding_id}\0${row.component_key}`) && [...newVersions, ...unanswered].every(carriesFix);
22779
22832
  if (!fixedNow) {
22780
22833
  marked.push({
22781
22834
  finding_id: row.finding_id,
@@ -22790,8 +22843,14 @@ function evaluateAsset(input2) {
22790
22843
  } else if (carriedOn.has(`${row.finding_id}\0${row.component_key}`)) {
22791
22844
  closed.push({ finding_id: row.finding_id, component_key: row.component_key, class: "fixed", reason: "superseded", score: 0, band: "none" });
22792
22845
  continue;
22846
+ } else if (!unanswered.every(carriesFix)) {
22847
+ const ended = unanswered.map((component) => coverageEnded.get(component.key)).filter((date5) => date5 !== void 0).sort()[0];
22848
+ if (ended !== void 0) {
22849
+ marked.push({ finding_id: row.finding_id, component_key: row.component_key, mark: "intel_coverage_ended", date: ended });
22850
+ continue;
22851
+ }
22793
22852
  }
22794
- closing = closedRow(row, "fixed", "component_changed");
22853
+ closing = unanswered.every(carriesFix) ? closedRow(row, "fixed", "component_changed") : closedRow(row, "unknown", "not_comparable");
22795
22854
  } else if (ecosystem === "cpe") {
22796
22855
  if (incomplete.banner)
22797
22856
  continue;
@@ -23157,6 +23216,32 @@ function safeParseCapabilityPayload(capability2, payload) {
23157
23216
  return { success: true, data };
23158
23217
  }
23159
23218
 
23219
+ // ../../packages/protocol/dist/paths.js
23220
+ var DEFAULT_DENY_GLOBS = Object.freeze([
23221
+ ".git/**",
23222
+ "**/.git/**",
23223
+ "**/.env*",
23224
+ "**/*.pem",
23225
+ "**/*.key",
23226
+ "**/.ssh/**",
23227
+ "**/id_rsa*",
23228
+ "**/id_ed25519*",
23229
+ "**/.aws/**",
23230
+ "**/.netrc",
23231
+ "**/.npmrc",
23232
+ "**/.git-credentials",
23233
+ "**/.gnupg/**",
23234
+ "**/.config/gh/**",
23235
+ "**/.kube/**",
23236
+ "**/.docker/config.json",
23237
+ "**/.conbridge/**",
23238
+ "**/Library/Keychains/**"
23239
+ ]);
23240
+ var UNSAFE_PATH_CHARS = /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/u;
23241
+ function isSafePathText(value) {
23242
+ return !UNSAFE_PATH_CHARS.test(value);
23243
+ }
23244
+
23160
23245
  // ../../packages/protocol/dist/connectors/desktop.js
23161
23246
  var DESKTOP_CAPABILITIES = Object.freeze([
23162
23247
  "files.list",
@@ -23177,7 +23262,7 @@ var MAX_READ_BYTES = 256 * 1024;
23177
23262
  var MAX_EDIT_FILE_BYTES = 8 * 1024 * 1024;
23178
23263
  var MAX_EDIT_TEXT_BYTES = 48 * 1024;
23179
23264
  var MAX_EDIT_REPLACEMENTS = 1e3;
23180
- var relativePath = external_exports.string().max(1024).refine((value) => !value.startsWith("/") && !value.includes("\0") && !/^[A-Za-z]:/.test(value), "Path must be relative to the selected root");
23265
+ var relativePath = external_exports.string().max(1024).refine((value) => !value.startsWith("/") && !value.includes("\0") && !/^[A-Za-z]:/.test(value), "Path must be relative to the selected root").refine(isSafePathText, "Path must not contain control, bidi or invisible characters");
23181
23266
  var sha256 = external_exports.string().regex(/^[a-f0-9]{64}$/);
23182
23267
  var filePayloadSchemas = {
23183
23268
  "files.list": external_exports.strictObject({ path: relativePath }),
@@ -24254,7 +24339,7 @@ async function verifyEd25519(publicKeyB64u2, message, signatureB64u) {
24254
24339
  }
24255
24340
  }
24256
24341
 
24257
- // ../../packages/protocol/dist/security/dispositions.js
24342
+ // ../../packages/protocol/dist/security/disposition-constants.js
24258
24343
  var JUSTIFICATIONS = Object.freeze({
24259
24344
  not_affected: [
24260
24345
  "component_not_present",
@@ -24265,9 +24350,13 @@ var JUSTIFICATIONS = Object.freeze({
24265
24350
  ],
24266
24351
  false_positive: ["wrong_component_identity", "version_outside_range", "vendor_states_not_affected"],
24267
24352
  mitigated: ["configuration_changed", "network_restricted", "feature_disabled", "compensating_control"],
24268
- risk_accepted: ["no_fix_available", "business_requirement", "low_exposure", "replacement_planned"]
24353
+ // CB-449: `fix_not_in_channel` (a fix exists upstream but not in the release channel this asset uses) and
24354
+ // `fix_breaks_service` (installing the fix would break a service the owner needs).
24355
+ risk_accepted: ["no_fix_available", "business_requirement", "low_exposure", "replacement_planned", "fix_not_in_channel", "fix_breaks_service"]
24269
24356
  });
24270
24357
  var MAX_EXPIRY_DAYS = Object.freeze({ not_affected: 365, false_positive: 365, mitigated: 180, risk_accepted: 90 });
24358
+
24359
+ // ../../packages/protocol/dist/security/dispositions.js
24271
24360
  var CHECK_SECTIONS = Object.freeze({
24272
24361
  "os.release": null,
24273
24362
  "kernel.release": "kernel",
@@ -24375,7 +24464,8 @@ var INDEPENDENT_REASON_TEXT = Object.freeze({
24375
24464
  official_provisional: "The official score is provisional.",
24376
24465
  hardening_unknown: "The advanced security checks have not run on this asset; they deduct nothing until they do.",
24377
24466
  checks_not_read: "Some advanced security checks could not be read; they deduct nothing until they are.",
24378
- vendor_unknown: "The vulnerabilities waiting for a vendor fix are not known yet; they deduct nothing until they are."
24467
+ vendor_unknown: "The vulnerabilities waiting for a vendor fix are not known yet; they deduct nothing until they are.",
24468
+ deferred_unknown: "Deferred findings were not scored yet; the next evaluation adds them."
24379
24469
  });
24380
24470
 
24381
24471
  // ../../packages/protocol/dist/http.js
@@ -24459,28 +24549,6 @@ var unservedVerifiedOverviewSchema = external_exports.strictObject({
24459
24549
  ctx.addIssue({ code: "custom", message: "DUPLICATE_SCOPED_DEVICE" });
24460
24550
  });
24461
24551
 
24462
- // ../../packages/protocol/dist/paths.js
24463
- var DEFAULT_DENY_GLOBS = Object.freeze([
24464
- ".git/**",
24465
- "**/.git/**",
24466
- "**/.env*",
24467
- "**/*.pem",
24468
- "**/*.key",
24469
- "**/.ssh/**",
24470
- "**/id_rsa*",
24471
- "**/id_ed25519*",
24472
- "**/.aws/**",
24473
- "**/.netrc",
24474
- "**/.npmrc",
24475
- "**/.git-credentials",
24476
- "**/.gnupg/**",
24477
- "**/.config/gh/**",
24478
- "**/.kube/**",
24479
- "**/.docker/config.json",
24480
- "**/.conbridge/**",
24481
- "**/Library/Keychains/**"
24482
- ]);
24483
-
24484
24552
  // ../../packages/protocol/dist/index.js
24485
24553
  var moduleInfo = Object.freeze({ name: "@conbridge/protocol", runtime: "shared", status: "scaffold-only" });
24486
24554
 
@@ -24516,7 +24584,7 @@ var import_node_fs = require("node:fs");
24516
24584
  var import_node_path = require("node:path");
24517
24585
  var import_node_sea = require("node:sea");
24518
24586
  var import_node_url = require("node:url");
24519
- var SOURCE_VERSION = "0.8.1";
24587
+ var SOURCE_VERSION = "0.9.1";
24520
24588
  var BUILD_INFO = typeof define_CONBRIDGE_BUILD_default === "object" && define_CONBRIDGE_BUILD_default !== null ? define_CONBRIDGE_BUILD_default : null;
24521
24589
  var AGENT_VERSION = BUILD_INFO?.version ?? SOURCE_VERSION;
24522
24590
  function runningAsSea() {
@@ -24678,6 +24746,19 @@ function buildLaunchAgentPlist(options) {
24678
24746
  function launchAgentPath(home = (0, import_node_os.homedir)()) {
24679
24747
  return (0, import_node_path3.join)(home, "Library", "LaunchAgents", `${LAUNCH_AGENT_LABEL}.plist`);
24680
24748
  }
24749
+ function defaultStateDirIn(home) {
24750
+ return (0, import_node_path3.join)(home, ".conbridge", "agent");
24751
+ }
24752
+ function xmlUnescape(value) {
24753
+ const entities = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
24754
+ return value.replace(/&(amp|lt|gt|quot|apos);/g, (_, name3) => entities[name3]);
24755
+ }
24756
+ function launchAgentStateDir(plist, home) {
24757
+ if (!/<key>Label<\/key>\s*<string>com\.conbridge\.agent<\/string>/.test(plist))
24758
+ return null;
24759
+ const custom2 = /<key>CONBRIDGE_AGENT_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(plist);
24760
+ return custom2 ? xmlUnescape(custom2[1]) : defaultStateDirIn(home);
24761
+ }
24681
24762
  function defaultLogPath(home = (0, import_node_os.homedir)()) {
24682
24763
  return (0, import_node_path3.join)(home, "Library", "Logs", "conbridge-agent.log");
24683
24764
  }
@@ -24767,6 +24848,18 @@ function buildSystemdUnit(options) {
24767
24848
  ""
24768
24849
  ].join("\n");
24769
24850
  }
24851
+ function systemdUnword(quoted2) {
24852
+ return quoted2.replace(/\\(.)|%%|\$\$/g, (match, escaped) => escaped ?? match[0]);
24853
+ }
24854
+ function systemdUnitStateDir(unit2, home) {
24855
+ if (!/^Description=ConBridge Desktop Agent$/m.test(unit2))
24856
+ return null;
24857
+ const variable = (name3) => {
24858
+ const match = new RegExp(`^Environment="${name3}=((?:[^"\\\\]|\\\\.)*)"$`, "m").exec(unit2);
24859
+ return match ? systemdUnword(match[1]) : null;
24860
+ };
24861
+ return variable("CONBRIDGE_AGENT_HOME") ?? defaultStateDirIn(variable("HOME") ?? home);
24862
+ }
24770
24863
  async function systemdRunning() {
24771
24864
  return (0, import_promises2.stat)("/run/systemd/system").then((info) => info.isDirectory(), () => false);
24772
24865
  }
@@ -24832,6 +24925,13 @@ function buildCronLine(options) {
24832
24925
  const env = options.stateDir ? `CONBRIDGE_AGENT_HOME=${shWord(options.stateDir)} ` : "";
24833
24926
  return `@reboot ${env}${args} supervise >> ${shWord(options.logPath)} 2>&1 ${CRON_MARKER}`;
24834
24927
  }
24928
+ function cronStateDir(crontab, home) {
24929
+ const line = crontab.split("\n").find((entry) => entry.includes(CRON_MARKER));
24930
+ if (line === void 0)
24931
+ return null;
24932
+ const custom2 = /^@reboot CONBRIDGE_AGENT_HOME='((?:[^']|'\\'')*)' /.exec(line);
24933
+ return custom2 ? custom2[1].replace(/'\\''/g, "'") : defaultStateDirIn(home);
24934
+ }
24835
24935
  function withCronLine(current, line) {
24836
24936
  const kept = current.split("\n").filter((entry) => entry.trim() !== "" && !entry.includes(CRON_MARKER));
24837
24937
  return [...kept, ...line ? [line] : []].join("\n") + "\n";
@@ -24873,8 +24973,8 @@ function windowsPath(value) {
24873
24973
  }
24874
24974
  var vbsString = (value) => '"' + value.replace(/"/g, '""') + '"';
24875
24975
  function buildWindowsLauncher(options) {
24876
- const quoted = programArguments(options).map((arg2, index, all) => index === all.length - 1 ? arg2 : `"${windowsPath(arg2)}"`).join(" ");
24877
- const command2 = `cmd.exe /d /s /c "${quoted} >> "${windowsPath(options.logPath)}" 2>&1"`;
24976
+ const quoted2 = programArguments(options).map((arg2, index, all) => index === all.length - 1 ? arg2 : `"${windowsPath(arg2)}"`).join(" ");
24977
+ const command2 = `cmd.exe /d /s /c "${quoted2} >> "${windowsPath(options.logPath)}" 2>&1"`;
24878
24978
  return [
24879
24979
  "' ConBridge Desktop Agent launcher (Task Scheduler). Generated by conbridge-agent service install.",
24880
24980
  "Option Explicit",
@@ -25065,6 +25165,17 @@ var identitySchema = external_exports.strictObject({
25065
25165
  destroy_deadline_ms: external_exports.number().int().nonnegative().nullable().optional(),
25066
25166
  key_store: keyStoreDescriptorSchema.optional()
25067
25167
  });
25168
+ var grantOwnerSchema = external_exports.strictObject({ gateway_url: external_exports.url(), tenant_id: opaque2, user_id: opaque2 });
25169
+ function grantOwnerOf(identity) {
25170
+ return { gateway_url: identity.gateway_url, tenant_id: identity.tenant_id, user_id: identity.user_id };
25171
+ }
25172
+ function sameGrantOwner(a, b) {
25173
+ return a !== void 0 && b !== void 0 && a.gateway_url === b.gateway_url && a.tenant_id === b.tenant_id && a.user_id === b.user_id;
25174
+ }
25175
+ async function currentGrantOwner(paths) {
25176
+ const identity = await loadIdentity(paths).catch(() => null);
25177
+ return identity ? grantOwnerOf(identity) : void 0;
25178
+ }
25068
25179
  var rootSchema = external_exports.strictObject({
25069
25180
  root_id: external_exports.uuid(),
25070
25181
  path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute"),
@@ -25084,7 +25195,14 @@ var configSchema = external_exports.strictObject({
25084
25195
  */
25085
25196
  full_access: external_exports.boolean().optional(),
25086
25197
  /** Software inventory (ADR DEVICE_INVENTORY): the computer's own switch; the owner turns it on in the Console. Absent = allowed. */
25087
- inventory: external_exports.boolean().optional()
25198
+ inventory: external_exports.boolean().optional(),
25199
+ /** Whose grants `roots` and `full_access` are (see grantOwnerSchema). Absent: made while unpaired, or by an older agent. */
25200
+ granted_for: grantOwnerSchema.optional(),
25201
+ /** The home folder root `access full` added, so `access files` can take exactly that share back. */
25202
+ home_root_added: external_exports.strictObject({
25203
+ root_id: external_exports.uuid(),
25204
+ path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute")
25205
+ }).optional()
25088
25206
  });
25089
25207
  function defaultConfig() {
25090
25208
  return { version: 1, roots: [], deny_globs: [...DEFAULT_DENY_GLOBS], confirm_writes: false };
@@ -25145,7 +25263,8 @@ async function addRoot(paths, input2) {
25145
25263
  if (label.length < 1 || label.length > 128)
25146
25264
  throw new Error("Label must be 1 to 128 characters");
25147
25265
  const root = { root_id: (0, import_node_crypto2.randomUUID)(), path: real, label, writable: input2.writable };
25148
- await saveConfig(paths, { ...config2, roots: [...config2.roots, root] });
25266
+ const owner = await currentGrantOwner(paths);
25267
+ await saveConfig(paths, { ...config2, roots: [...config2.roots, root], ...owner ? { granted_for: owner } : {} });
25149
25268
  return root;
25150
25269
  }
25151
25270
  async function removeRoot(paths, rootId) {
@@ -25153,9 +25272,14 @@ async function removeRoot(paths, rootId) {
25153
25272
  const roots = config2.roots.filter((root) => root.root_id !== rootId);
25154
25273
  if (roots.length === config2.roots.length)
25155
25274
  return false;
25156
- await saveConfig(paths, { ...config2, roots });
25275
+ const { home_root_added: home, ...rest } = config2;
25276
+ await saveConfig(paths, { ...rest, roots, ...home && home.root_id !== rootId ? { home_root_added: home } : {} });
25157
25277
  return true;
25158
25278
  }
25279
+ function addedHomeRoot(config2) {
25280
+ const added = config2.home_root_added;
25281
+ return added ? config2.roots.find((root) => root.root_id === added.root_id && root.path === added.path) : void 0;
25282
+ }
25159
25283
 
25160
25284
  // dist/keystore.js
25161
25285
  var import_node_path5 = require("node:path");
@@ -25765,8 +25889,21 @@ function purgePowerShell(signal) {
25765
25889
  });
25766
25890
  });
25767
25891
  }
25892
+ async function sameDirectory(a, b) {
25893
+ return (0, import_node_path8.resolve)(a) === (0, import_node_path8.resolve)(b) || await realpathLenient(a) === await realpathLenient(b);
25894
+ }
25895
+ async function ownerOf(text6, parse3, stateDir, home) {
25896
+ if (text6 === null)
25897
+ return "unknown";
25898
+ const startsStateDir = parse3(text6, home);
25899
+ return startsStateDir !== null && await sameDirectory(startsStateDir, stateDir) ? "ours" : "other";
25900
+ }
25901
+ async function definitionOwner(path, parse3, stateDir, home) {
25902
+ return ownerOf(await (0, import_promises7.readFile)(path, "utf8").catch(() => null), parse3, stateDir, home);
25903
+ }
25768
25904
  async function removeAgentAutostart(stateDir = resolveStateDir(), deps = {}, signal) {
25769
25905
  const platform2 = deps.platform ?? process.platform;
25906
+ const home = deps.home ?? (0, import_node_os4.homedir)();
25770
25907
  const run2 = deps.run ?? boundedCommand(signal);
25771
25908
  const serviceDeps = { stopRunning: false, ...deps, platform: platform2, run: run2, launchctl: deps.launchctl ?? ((args) => run2("/bin/launchctl", args)) };
25772
25909
  const failures = [];
@@ -25779,14 +25916,20 @@ async function removeAgentAutostart(stateDir = resolveStateDir(), deps = {}, sig
25779
25916
  failures.push(error63);
25780
25917
  }
25781
25918
  };
25782
- if (platform2 === "darwin")
25919
+ const ours = async (path, parse3) => await definitionOwner(path, parse3, stateDir, home) === "ours";
25920
+ if (platform2 === "darwin" && await ours(launchAgentPath(home), launchAgentStateDir))
25783
25921
  await attempt(() => uninstallLaunchAgent(serviceDeps));
25784
25922
  if (platform2 === "linux") {
25785
- await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 1 }));
25786
- await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 0 }));
25787
- await attempt(() => uninstallCronService({ ...serviceDeps, writeCrontab: deps.writeCrontab ?? boundedCronWriter(signal) }));
25923
+ if (await ours(systemdUnitPath(home), systemdUnitStateDir))
25924
+ await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 1 }));
25925
+ if (await ours(deps.systemUnitPath ?? SYSTEMD_SYSTEM_UNIT_PATH, systemdUnitStateDir))
25926
+ await attempt(() => uninstallSystemdService({ ...serviceDeps, uid: 0 }));
25927
+ const crontab = signal?.aborted ? { ok: false, output: "" } : await run2("crontab", ["-l"]);
25928
+ if (crontab.ok && await ownerOf(crontab.output, cronStateDir, stateDir, home) === "ours") {
25929
+ await attempt(() => uninstallCronService({ ...serviceDeps, writeCrontab: deps.writeCrontab ?? boundedCronWriter(signal) }));
25930
+ }
25788
25931
  }
25789
- if (platform2 === "win32")
25932
+ if (platform2 === "win32" && await (deps.exists ?? exists)(windowsLauncherPath(stateDir)))
25790
25933
  await attempt(() => uninstallWindowsTask(stateDir, serviceDeps));
25791
25934
  if (failures.length)
25792
25935
  throw new AggregateError(failures, "Some autostart files could not be removed");
@@ -25967,18 +26110,20 @@ async function purgeAgent(options, deps = {}) {
25967
26110
  throw new AggregateError(failures, "Some ConBridge files could not be removed");
25968
26111
  });
25969
26112
  await step2("leftovers", async (signal) => {
25970
- if (platform2 === "darwin" && await has("/usr/local/lib/conbridge-agent/uninstall.sh")) {
26113
+ if (platform2 === "darwin" && await has("/usr/local/lib/conbridge-agent/uninstall.sh") && await definitionOwner(launchAgentPath(home), launchAgentStateDir, stateDir, home) !== "other") {
25971
26114
  leftovers.push("sudo /usr/local/lib/conbridge-agent/uninstall.sh");
25972
26115
  }
25973
26116
  const quote = (path) => `'${path.replace(/'/g, "'\\''")}'`;
26117
+ const remains = async (path, parse3) => await has(path) && await definitionOwner(path, parse3, stateDir, home) === "ours";
25974
26118
  if (platform2 === "linux") {
25975
- if (await has(systemdUnitPath(home)))
26119
+ if (await remains(systemdUnitPath(home), systemdUnitStateDir)) {
25976
26120
  leftovers.push(`systemctl --user disable --now conbridge-agent.service; rm -f -- ${quote(systemdUnitPath(home))}; systemctl --user daemon-reload`);
26121
+ }
25977
26122
  const systemUnit = deps.systemUnitPath ?? SYSTEMD_SYSTEM_UNIT_PATH;
25978
- if (await has(systemUnit))
26123
+ if (await remains(systemUnit, systemdUnitStateDir))
25979
26124
  leftovers.push(`sudo systemctl disable --now conbridge-agent.service; sudo rm -f -- ${quote(systemUnit)}; sudo systemctl daemon-reload`);
25980
26125
  }
25981
- if (platform2 === "darwin" && await has(launchAgentPath(home)))
26126
+ if (platform2 === "darwin" && await remains(launchAgentPath(home), launchAgentStateDir))
25982
26127
  leftovers.push(`rm -f -- ${quote(launchAgentPath(home))}`);
25983
26128
  if (!deferred) {
25984
26129
  const owned = dedicated ? [stateDir] : await stateEntries(stateDir, false, options.keepRuntime ?? false, pathApi).catch(() => []);
@@ -26018,21 +26163,45 @@ var import_node_util2 = require("node:util");
26018
26163
  var import_node_child_process5 = require("node:child_process");
26019
26164
  var import_node_path9 = require("node:path");
26020
26165
  var CONFIRM_TIMEOUT_MS = 13e4;
26021
- function confirmText(request) {
26022
- const verb = request.created ? "create" : "overwrite";
26023
- return `ConBridge wants to ${verb} "${request.path}" in root "${request.rootLabel}" (${request.bytes} bytes). This write was approved in the Console.`.replace(/[\r\n]+/g, " ");
26166
+ var UNSAFE_TEXT = new RegExp(UNSAFE_PATH_CHARS.source, "gu");
26167
+ function quoted(value) {
26168
+ return `"${value.replace(UNSAFE_TEXT, " ")}"`;
26024
26169
  }
26025
- function appleScriptString(value) {
26026
- return '"' + value.replace(/[\\"]/g, "\\$&").replace(/[\r\n]+/g, " ") + '"';
26170
+ function confirmText(request) {
26171
+ const where = `in root ${quoted(request.rootLabel)}`;
26172
+ let what;
26173
+ switch (request.action) {
26174
+ case "write":
26175
+ what = `${request.created ? "create" : "overwrite"} ${quoted(request.path)} ${where}${request.bytes === void 0 ? "" : ` (${request.bytes} bytes)`}`;
26176
+ break;
26177
+ case "edit":
26178
+ what = `edit ${quoted(request.path)} ${where}${request.replacements === void 0 ? "" : ` (${request.replacements} replacement${request.replacements === 1 ? "" : "s"})`}`;
26179
+ break;
26180
+ case "delete":
26181
+ what = `delete ${quoted(request.path)} ${where}`;
26182
+ break;
26183
+ case "move":
26184
+ what = `move ${quoted(request.path)} to ${quoted(request.to ?? "")} ${where}`;
26185
+ break;
26186
+ case "mkdir":
26187
+ what = `create the folder ${quoted(request.path)} ${where}`;
26188
+ break;
26189
+ }
26190
+ return `ConBridge wants to ${what}. This change was approved in the Console.`;
26027
26191
  }
26028
- function buildConfirmScript(request) {
26029
- return `display dialog ${appleScriptString(confirmText(request))} with title "ConBridge" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" with icon caution giving up after 120`;
26192
+ var MAC_CONFIRM_SCRIPT = [
26193
+ "on run argv",
26194
+ 'display dialog (item 1 of argv) with title "ConBridge" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" with icon caution giving up after 120',
26195
+ "end run"
26196
+ ];
26197
+ function buildConfirmArgs(request) {
26198
+ return [...MAC_CONFIRM_SCRIPT.flatMap((line) => ["-e", line]), confirmText(request)];
26030
26199
  }
26031
26200
  var macDialogConfirm = (request) => {
26032
26201
  if (process.platform !== "darwin")
26033
26202
  return Promise.resolve(false);
26034
26203
  return new Promise((resolve10) => {
26035
- (0, import_node_child_process5.execFile)("/usr/bin/osascript", ["-e", buildConfirmScript(request)], { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
26204
+ (0, import_node_child_process5.execFile)("/usr/bin/osascript", buildConfirmArgs(request), { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
26036
26205
  if (error63)
26037
26206
  return resolve10(false);
26038
26207
  resolve10(/button returned:Allow/.test(stdout) && !/gave up:true/.test(stdout));
@@ -26048,16 +26217,23 @@ var windowsConfirm = (request) => new Promise((resolve10) => {
26048
26217
  const powershell = import_node_path9.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
26049
26218
  (0, import_node_child_process5.execFile)(powershell, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_CONFIRM_SCRIPT], { timeout: CONFIRM_TIMEOUT_MS, windowsHide: false, env: { ...process.env, CONBRIDGE_CONFIRM_TEXT: confirmText(request) } }, (error63) => resolve10(!error63));
26050
26219
  });
26220
+ function linuxZenityArgs(text6) {
26221
+ return ["--question", "--no-markup", "--title=ConBridge", `--text=${text6}`, "--ok-label=Allow", "--cancel-label=Deny", "--default-cancel", "--timeout=120"];
26222
+ }
26223
+ function linuxKdialogArgs(text6) {
26224
+ const escaped = text6.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
26225
+ return ["--title", "ConBridge", "--warningyesno", `<qt>${escaped}</qt>`, "--yes-label", "Allow", "--no-label", "Deny"];
26226
+ }
26051
26227
  var linuxConfirm = (request) => new Promise((resolve10) => {
26052
26228
  if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
26053
26229
  return resolve10(false);
26054
26230
  const text6 = confirmText(request);
26055
- (0, import_node_child_process5.execFile)("zenity", ["--question", "--title=ConBridge", `--text=${text6}`, "--ok-label=Allow", "--cancel-label=Deny", "--default-cancel", "--timeout=120"], { timeout: CONFIRM_TIMEOUT_MS }, (error63) => {
26231
+ (0, import_node_child_process5.execFile)("zenity", linuxZenityArgs(text6), { timeout: CONFIRM_TIMEOUT_MS }, (error63) => {
26056
26232
  if (!error63)
26057
26233
  return resolve10(true);
26058
26234
  if (error63.code !== "ENOENT")
26059
26235
  return resolve10(false);
26060
- (0, import_node_child_process5.execFile)("kdialog", ["--title", "ConBridge", "--warningyesno", text6, "--yes-label", "Allow", "--no-label", "Deny"], { timeout: CONFIRM_TIMEOUT_MS }, (fallback) => resolve10(!fallback));
26236
+ (0, import_node_child_process5.execFile)("kdialog", linuxKdialogArgs(text6), { timeout: CONFIRM_TIMEOUT_MS }, (fallback) => resolve10(!fallback));
26061
26237
  });
26062
26238
  });
26063
26239
  var localConfirm = (request) => {
@@ -26072,7 +26248,220 @@ var localConfirm = (request) => {
26072
26248
 
26073
26249
  // dist/connect.js
26074
26250
  var import_node_child_process6 = require("node:child_process");
26251
+ var import_node_path11 = require("node:path");
26252
+
26253
+ // dist/ssh/hosts.js
26254
+ var import_node_crypto6 = require("node:crypto");
26255
+ var import_promises8 = require("node:fs/promises");
26075
26256
  var import_node_path10 = require("node:path");
26257
+ var MAX_SSH_HOSTS = 64;
26258
+ var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
26259
+ var DNS_HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
26260
+ var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
26261
+ var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
26262
+ function isValidSshHost(value) {
26263
+ return DNS_HOST.test(value) || IPV6_HOST.test(value);
26264
+ }
26265
+ function isValidIdentityPath(value) {
26266
+ return (0, import_node_path10.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
26267
+ }
26268
+ var PINNABLE_KEY_TYPES = Object.freeze([
26269
+ "ssh-ed25519",
26270
+ "ecdsa-sha2-nistp256",
26271
+ "ecdsa-sha2-nistp384",
26272
+ "ecdsa-sha2-nistp521",
26273
+ "ssh-rsa"
26274
+ ]);
26275
+ var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
26276
+ var sshHostSchema = external_exports.strictObject({
26277
+ resource_id: external_exports.uuid(),
26278
+ alias: external_exports.string().regex(SSH_ALIAS),
26279
+ host: external_exports.string().refine(isValidSshHost, "Invalid host"),
26280
+ port: external_exports.number().int().min(1).max(65535),
26281
+ user: external_exports.string().regex(SSH_USER).optional(),
26282
+ identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
26283
+ production: external_exports.boolean(),
26284
+ key_type: external_exports.enum(PINNABLE_KEY_TYPES),
26285
+ public_key: external_exports.string().min(16).max(8192).regex(base643),
26286
+ fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
26287
+ pinned_at: external_exports.iso.datetime({ offset: true })
26288
+ });
26289
+ var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS), granted_for: grantOwnerSchema.optional() });
26290
+ function sshPaths(stateDir) {
26291
+ const dir = (0, import_node_path10.join)(stateDir, "ssh");
26292
+ return { dir, hosts: (0, import_node_path10.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path10.join)(dir, "known_hosts") };
26293
+ }
26294
+ function knownHostsPath(paths, resourceId) {
26295
+ return (0, import_node_path10.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
26296
+ }
26297
+ function hostKeyAlias(host) {
26298
+ return "conbridge-" + host.resource_id;
26299
+ }
26300
+ function fingerprintOf(publicKey) {
26301
+ return "SHA256:" + (0, import_node_crypto6.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
26302
+ }
26303
+ function normalizeFingerprint(value) {
26304
+ const trimmed = value.trim();
26305
+ return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
26306
+ }
26307
+ function parseKeyscan(output2) {
26308
+ const keys = [];
26309
+ for (const line of output2.split("\n")) {
26310
+ const trimmed = line.trim();
26311
+ if (trimmed === "" || trimmed.startsWith("#"))
26312
+ continue;
26313
+ const [, type, key] = trimmed.split(/\s+/);
26314
+ if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
26315
+ continue;
26316
+ keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
26317
+ }
26318
+ return keys;
26319
+ }
26320
+ function preferredKey(keys) {
26321
+ for (const type of PINNABLE_KEY_TYPES) {
26322
+ const key = keys.find((candidate) => candidate.key_type === type);
26323
+ if (key)
26324
+ return key;
26325
+ }
26326
+ return null;
26327
+ }
26328
+ async function loadHostsFile(paths) {
26329
+ let text6;
26330
+ try {
26331
+ text6 = await (0, import_promises8.readFile)(paths.hosts, "utf8");
26332
+ } catch (error63) {
26333
+ if (errorCode2(error63) === "ENOENT")
26334
+ return null;
26335
+ throw error63;
26336
+ }
26337
+ return hostsFileSchema.parse(JSON.parse(text6));
26338
+ }
26339
+ async function loadSshHosts(paths) {
26340
+ return (await loadHostsFile(paths))?.hosts ?? [];
26341
+ }
26342
+ async function sshHostsOwner(paths) {
26343
+ return (await loadHostsFile(paths))?.granted_for;
26344
+ }
26345
+ async function setSshHostsOwner(paths, owner) {
26346
+ const file2 = await loadHostsFile(paths);
26347
+ if (file2)
26348
+ await saveSshHosts(paths, file2.hosts, owner);
26349
+ }
26350
+ async function clearSshHosts(paths) {
26351
+ const hosts = await loadSshHosts(paths).catch(() => []);
26352
+ await (0, import_promises8.rm)(paths.hosts, { force: true });
26353
+ const pins = await (0, import_promises8.readdir)(paths.knownHostsDir).catch((error63) => {
26354
+ if (errorCode2(error63) === "ENOENT")
26355
+ return [];
26356
+ throw error63;
26357
+ });
26358
+ for (const name3 of pins)
26359
+ if (external_exports.uuid().safeParse(name3).success)
26360
+ await (0, import_promises8.rm)((0, import_node_path10.join)(paths.knownHostsDir, name3), { force: true });
26361
+ return hosts;
26362
+ }
26363
+ async function ensureSshDirs(paths) {
26364
+ for (const dir of [paths.dir, paths.knownHostsDir]) {
26365
+ await (0, import_promises8.mkdir)(dir, { recursive: true, mode: 448 });
26366
+ await (0, import_promises8.chmod)(dir, 448);
26367
+ }
26368
+ }
26369
+ async function saveSshHosts(paths, hosts, owner) {
26370
+ await ensureSshDirs(paths);
26371
+ const file2 = hostsFileSchema.parse({ version: 1, hosts, ...owner ? { granted_for: owner } : {} });
26372
+ await writeFileAtomic(paths.hosts, JSON.stringify(file2, null, 2) + "\n", 384);
26373
+ }
26374
+ async function ownerForNewHost(paths, recorded) {
26375
+ return await currentGrantOwner(statePaths((0, import_node_path10.dirname)(paths.dir))) ?? recorded;
26376
+ }
26377
+ async function writeKnownHosts(paths, host) {
26378
+ await ensureSshDirs(paths);
26379
+ await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
26380
+ `, 384);
26381
+ }
26382
+ async function validateNewHost(input2) {
26383
+ if (!SSH_ALIAS.test(input2.alias))
26384
+ throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
26385
+ if (!isValidSshHost(input2.host))
26386
+ throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
26387
+ if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
26388
+ throw new Error("Port must be 1-65535");
26389
+ if (input2.user !== void 0 && !SSH_USER.test(input2.user))
26390
+ throw new Error("User must be a plain login name");
26391
+ if (input2.identity !== void 0) {
26392
+ if (!isValidIdentityPath(input2.identity))
26393
+ throw new Error("Identity must be an absolute path without quotes, % or control characters");
26394
+ const info = await (0, import_promises8.stat)(input2.identity).catch(() => null);
26395
+ if (!info?.isFile())
26396
+ throw new Error("Identity file not found");
26397
+ }
26398
+ }
26399
+ async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
26400
+ await validateNewHost(input2);
26401
+ const file2 = await loadHostsFile(paths);
26402
+ const hosts = file2?.hosts ?? [];
26403
+ if (hosts.some((host2) => host2.alias === input2.alias))
26404
+ throw new Error(`An SSH host named ${input2.alias} already exists`);
26405
+ if (hosts.length >= MAX_SSH_HOSTS)
26406
+ throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
26407
+ const host = sshHostSchema.parse({
26408
+ resource_id: (0, import_node_crypto6.randomUUID)(),
26409
+ alias: input2.alias,
26410
+ host: input2.host,
26411
+ port: input2.port ?? 22,
26412
+ ...input2.user !== void 0 ? { user: input2.user } : {},
26413
+ ...input2.identity !== void 0 ? { identity: input2.identity } : {},
26414
+ production: input2.production === true,
26415
+ key_type: key.key_type,
26416
+ public_key: key.public_key,
26417
+ fingerprint: key.fingerprint,
26418
+ pinned_at: now.toISOString()
26419
+ });
26420
+ await writeKnownHosts(paths, host);
26421
+ await saveSshHosts(paths, [...hosts, host], await ownerForNewHost(paths, file2?.granted_for));
26422
+ return host;
26423
+ }
26424
+ async function findSshHost(paths, alias) {
26425
+ return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
26426
+ }
26427
+ async function updateHost(paths, alias, change) {
26428
+ const file2 = await loadHostsFile(paths);
26429
+ const hosts = file2?.hosts ?? [];
26430
+ const index = hosts.findIndex((host) => host.alias === alias);
26431
+ if (index < 0)
26432
+ throw new Error(`No SSH host named ${alias}`);
26433
+ const updated = sshHostSchema.parse(change(hosts[index]));
26434
+ const next = [...hosts];
26435
+ next[index] = updated;
26436
+ if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
26437
+ await writeKnownHosts(paths, updated);
26438
+ await saveSshHosts(paths, next, file2?.granted_for);
26439
+ return updated;
26440
+ }
26441
+ async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
26442
+ return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
26443
+ }
26444
+ async function setSshHostProduction(paths, alias, production) {
26445
+ return await updateHost(paths, alias, (host) => ({ ...host, production }));
26446
+ }
26447
+ async function removeSshHost(paths, alias) {
26448
+ const file2 = await loadHostsFile(paths);
26449
+ const hosts = file2?.hosts ?? [];
26450
+ const host = hosts.find((entry) => entry.alias === alias);
26451
+ if (!host)
26452
+ return false;
26453
+ await saveSshHosts(paths, hosts.filter((entry) => entry !== host), file2?.granted_for);
26454
+ await (0, import_promises8.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
26455
+ return true;
26456
+ }
26457
+ function hostAddress(host) {
26458
+ if (host.port === 22)
26459
+ return host.host;
26460
+ return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
26461
+ }
26462
+ function inventoryResource2(host) {
26463
+ return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
26464
+ }
26076
26465
 
26077
26466
  // dist/pairing.js
26078
26467
  var PAIRING_CODE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}-?[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/;
@@ -26106,7 +26495,12 @@ function normalizePairingCode(input2) {
26106
26495
  return code.includes("-") ? code : `${code.slice(0, 4)}-${code.slice(4)}`;
26107
26496
  }
26108
26497
  var POLL_TOKEN_HEADER = "X-ConBridge-Poll-Token";
26109
- var offerResponseSchema = external_exports.object({ pairing_id: external_exports.string().min(1).max(128), poll_token: external_exports.string().min(16).max(512) });
26498
+ var offerResponseSchema = external_exports.object({
26499
+ pairing_id: external_exports.string().min(1).max(128),
26500
+ poll_token: external_exports.string().min(16).max(512),
26501
+ organization_name: external_exports.string().max(1024).optional().catch(void 0),
26502
+ inviter: external_exports.string().max(1024).optional().catch(void 0)
26503
+ });
26110
26504
  var statusResponseSchema = external_exports.discriminatedUnion("state", [
26111
26505
  external_exports.object({
26112
26506
  state: external_exports.literal("approved"),
@@ -26121,6 +26515,83 @@ var statusResponseSchema = external_exports.discriminatedUnion("state", [
26121
26515
  external_exports.object({ state: external_exports.enum(["open", "offered", "pending"]) }),
26122
26516
  external_exports.object({ state: external_exports.enum(["denied", "expired"]) })
26123
26517
  ]);
26518
+ var UNSAFE_TEXT2 = new RegExp(UNSAFE_PATH_CHARS.source, "gu");
26519
+ function displayText(value, max = 80) {
26520
+ const text6 = (value ?? "").replace(UNSAFE_TEXT2, " ").replace(/\s+/g, " ").trim();
26521
+ if (text6 === "")
26522
+ return null;
26523
+ return text6.length > max ? text6.slice(0, max - 3) + "..." : text6;
26524
+ }
26525
+ function hasLocalGrants(grants) {
26526
+ return grants.roots.length > 0 || grants.full_access || grants.ssh_hosts.length > 0;
26527
+ }
26528
+ function grantsOf(config2, hosts) {
26529
+ return {
26530
+ roots: config2.roots.map(({ label, path, writable }) => ({ label, path, writable })),
26531
+ full_access: config2.full_access === true,
26532
+ ssh_hosts: hosts.map(({ alias, production }) => ({ alias, production }))
26533
+ };
26534
+ }
26535
+ async function readLocalGrants(paths) {
26536
+ return grantsOf(await loadConfig(paths), await loadSshHosts(sshPaths(paths.dir)).catch(() => []));
26537
+ }
26538
+ function describeLocalGrants(grants) {
26539
+ const lines5 = [];
26540
+ if (grants.roots.length > 0) {
26541
+ lines5.push("Shared folders: " + grants.roots.map((root) => `${displayText(root.label, 64) ?? "folder"} (${root.writable ? "read-write" : "read-only"})`).join(", "));
26542
+ }
26543
+ if (grants.full_access)
26544
+ lines5.push("Full access (terminal): on");
26545
+ if (grants.ssh_hosts.length > 0)
26546
+ lines5.push("SSH hosts: " + grants.ssh_hosts.map((host) => host.production ? `${host.alias} (production)` : host.alias).join(", "));
26547
+ return lines5;
26548
+ }
26549
+ function describeClearedGrants(grants) {
26550
+ const lines5 = [];
26551
+ if (grants.roots.length > 0)
26552
+ lines5.push("Stopped sharing folders: " + grants.roots.map((root) => `${displayText(root.label, 64) ?? "folder"} (${displayText(root.path, 256) ?? ""})`).join(", "));
26553
+ if (grants.full_access)
26554
+ lines5.push("Turned full access (terminal) off");
26555
+ if (grants.ssh_hosts.length > 0)
26556
+ lines5.push("Removed SSH hosts and their pinned keys: " + grants.ssh_hosts.map((host) => host.alias).join(", "));
26557
+ return lines5;
26558
+ }
26559
+ async function adoptUnownedGrants(paths, owner) {
26560
+ const config2 = await loadConfig(paths);
26561
+ if (config2.granted_for === void 0 && hasLocalGrants(grantsOf(config2, [])))
26562
+ await saveConfig(paths, { ...config2, granted_for: owner });
26563
+ const ssh = sshPaths(paths.dir);
26564
+ const hosts = await loadSshHosts(ssh).then((list) => list, () => []);
26565
+ if (hosts.length > 0 && await sshHostsOwner(ssh) === void 0)
26566
+ await setSshHostsOwner(ssh, owner);
26567
+ }
26568
+ function withoutGrants(config2) {
26569
+ const next = { ...config2, roots: [] };
26570
+ delete next.full_access;
26571
+ delete next.home_root_added;
26572
+ delete next.granted_for;
26573
+ return next;
26574
+ }
26575
+ async function clearLocalGrants(paths) {
26576
+ const config2 = await loadConfig(paths);
26577
+ await saveConfig(paths, withoutGrants(config2));
26578
+ const hosts = await clearSshHosts(sshPaths(paths.dir));
26579
+ return grantsOf(config2, hosts);
26580
+ }
26581
+ async function bindLocalGrants(paths, owner, previous) {
26582
+ const replaced = previous ? grantOwnerOf(previous) : void 0;
26583
+ const config2 = await loadConfig(paths);
26584
+ const keepConfig = sameGrantOwner(config2.granted_for ?? replaced, owner);
26585
+ await saveConfig(paths, { ...keepConfig ? config2 : withoutGrants(config2), granted_for: owner });
26586
+ const ssh = sshPaths(paths.dir);
26587
+ const hostsOwner = await sshHostsOwner(ssh).then((recorded) => ({ readable: true, recorded }), () => ({ readable: false, recorded: void 0 }));
26588
+ let clearedHosts = [];
26589
+ if (hostsOwner.readable && sameGrantOwner(hostsOwner.recorded ?? replaced, owner))
26590
+ await setSshHostsOwner(ssh, owner);
26591
+ else
26592
+ clearedHosts = await clearSshHosts(ssh);
26593
+ return keepConfig ? grantsOf({ ...config2, roots: [], full_access: false }, clearedHosts) : grantsOf(config2, clearedHosts);
26594
+ }
26124
26595
  var PairingError = class extends Error {
26125
26596
  state;
26126
26597
  constructor(state2, message) {
@@ -26160,7 +26631,15 @@ async function pairDevice(options) {
26160
26631
  headers: { "content-type": "application/json" },
26161
26632
  body: JSON.stringify({ code, public_key: publicKeyB64u(key), display_name: name3, platform: platform2, capabilities: [LIFECYCLE_CAPABILITY] })
26162
26633
  }), "Pairing offer"));
26163
- options.onOffered?.({ fingerprint, pairing_id: offer.pairing_id });
26634
+ const offered = {
26635
+ pairing_id: offer.pairing_id,
26636
+ fingerprint,
26637
+ organization_name: displayText(offer.organization_name),
26638
+ inviter: displayText(offer.inviter, 120)
26639
+ };
26640
+ options.onOffered?.(offered);
26641
+ if (options.confirmOffer && !await options.confirmOffer(offered))
26642
+ throw new PairingError("cancelled", "Pairing was cancelled on this computer");
26164
26643
  const deadline = Date.now() + (options.timeoutMs ?? 11 * 6e4);
26165
26644
  const query = new URLSearchParams({ pairing_id: offer.pairing_id }).toString();
26166
26645
  const pollInit = { method: "GET", headers: { [POLL_TOKEN_HEADER]: offer.poll_token } };
@@ -26185,6 +26664,10 @@ async function pairDevice(options) {
26185
26664
  paired_at: (/* @__PURE__ */ new Date()).toISOString(),
26186
26665
  key_store: options.keyStore.descriptor
26187
26666
  };
26667
+ const previous = await loadIdentity(options.paths).catch(() => null);
26668
+ const cleared = await bindLocalGrants(options.paths, grantOwnerOf(identity), previous);
26669
+ if (hasLocalGrants(cleared))
26670
+ options.onLocalGrantsCleared?.(cleared);
26188
26671
  await options.onApproved?.();
26189
26672
  await saveIdentity(options.paths, identity);
26190
26673
  succeeded = true;
@@ -26246,79 +26729,134 @@ async function runConnect(link, deps, extraHosts = []) {
26246
26729
  dialogs.fail(friendly(error63));
26247
26730
  return 2;
26248
26731
  }
26732
+ let cancelled = false;
26249
26733
  try {
26250
26734
  const replacing = await deps.isPaired();
26251
- if (!await dialogs.confirmConnect(new URL(request.gateway).host, request.name, replacing)) {
26735
+ const host = new URL(request.gateway).host;
26736
+ if (!await dialogs.confirmConnect(host, request.name, replacing)) {
26252
26737
  deps.log("Connect cancelled.");
26253
26738
  return 0;
26254
26739
  }
26255
- const folders = await dialogs.chooseFolders();
26256
- const writable = folders.length > 0 ? await dialogs.askAllowChanges() : false;
26740
+ let folders = [];
26741
+ let writable = false;
26742
+ await deps.pair(request, replacing, async (offer) => {
26743
+ const view = {
26744
+ host,
26745
+ requestedName: request.name,
26746
+ replacing,
26747
+ organization: offer.organization_name,
26748
+ inviter: offer.inviter,
26749
+ fingerprint: offer.fingerprint,
26750
+ shared: await deps.localAccess()
26751
+ };
26752
+ if (!await dialogs.confirmOffer(view)) {
26753
+ cancelled = true;
26754
+ return false;
26755
+ }
26756
+ folders = await dialogs.chooseFolders();
26757
+ writable = folders.length > 0 ? await dialogs.askAllowChanges() : false;
26758
+ dialogs.notify("ConBridge", `Almost done. Go back to ConBridge in your browser and approve this Mac if it shows the fingerprint ${offer.fingerprint}.`);
26759
+ return true;
26760
+ });
26257
26761
  const skipped = [];
26258
26762
  for (const folder of folders) {
26259
26763
  try {
26260
- await deps.addFolder(folder, (0, import_node_path10.basename)(folder) || folder, writable);
26764
+ await deps.addFolder(folder, (0, import_node_path11.basename)(folder) || folder, writable);
26261
26765
  } catch (error63) {
26262
- skipped.push(`${(0, import_node_path10.basename)(folder) || folder}: ${friendly(error63)}`);
26766
+ skipped.push(`${(0, import_node_path11.basename)(folder) || folder}: ${friendly(error63)}`);
26263
26767
  }
26264
26768
  }
26265
26769
  if (skipped.length > 0)
26266
26770
  dialogs.fail("Some folders were not added:\n" + skipped.join("\n"));
26267
- dialogs.notify("ConBridge", "Almost done. Go back to ConBridge in your browser and approve this Mac.");
26268
- await deps.pair(request, replacing);
26269
26771
  await deps.installService();
26270
26772
  dialogs.notify("ConBridge", "This Mac is connected. ConBridge keeps running in the background.");
26271
26773
  return 0;
26272
26774
  } catch (error63) {
26775
+ if (cancelled) {
26776
+ deps.log("Connect cancelled after the offer; this Mac was not connected.");
26777
+ return 0;
26778
+ }
26273
26779
  deps.log(`Connect failed: ${friendly(error63)}`);
26274
26780
  dialogs.fail("This Mac could not be connected.\n\n" + friendly(error63));
26275
26781
  return 1;
26276
26782
  }
26277
26783
  }
26278
- function appleScriptString2(value) {
26279
- return '"' + value.replace(/[\\"]/g, "\\$&").replace(/\r?\n/g, '" & linefeed & "') + '"';
26280
- }
26281
- function osascript(script, timeoutMs) {
26282
- return new Promise((resolve10) => {
26283
- (0, import_node_child_process6.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
26284
- resolve10({ ok: !error63, stdout: stdout ?? "" });
26285
- });
26286
- });
26287
- }
26288
- var macConnectDialogs = {
26289
- async confirmConnect(host, name3, replacing) {
26290
- const text6 = (replacing ? "This Mac is already connected. Connecting again replaces that connection.\n\n" : "") + `Connect this Mac to ConBridge?
26784
+ function connectStartText(host, requestedName, replacing) {
26785
+ return (replacing ? "This Mac is already connected. Connecting again replaces that connection.\n\n" : "") + `Connect this Mac to ConBridge?
26291
26786
 
26292
- Your AI apps can use only the folders you choose, with the permissions you set in ConBridge.
26787
+ Before anything is shared, the next window shows which organization invited this Mac and its device fingerprint.
26293
26788
 
26294
26789
  Address: ${host}
26295
- Name: ${name3}`;
26296
- const result2 = await osascript(`display dialog ${appleScriptString2(text6)} with title "ConBridge" buttons {"Cancel", "Connect"} default button "Connect" cancel button "Cancel" giving up after 300`, 31e4);
26297
- return result2.ok && /button returned:Connect/.test(result2.stdout) && !/gave up:true/.test(result2.stdout);
26298
- },
26299
- async chooseFolders() {
26300
- const script = 'set theFolders to choose folder with prompt "Choose the folders your AI apps may use. You can add more later." with multiple selections allowed\nset out to ""\nrepeat with f in theFolders\nset out to out & POSIX path of f & linefeed\nend repeat\nreturn out';
26301
- const result2 = await osascript(script, 6e5);
26302
- if (!result2.ok)
26303
- return [];
26304
- return result2.stdout.split("\n").map((line) => line.trim().replace(/\/$/, "")).filter(Boolean);
26305
- },
26306
- async askAllowChanges() {
26307
- const text6 = "Should your AI apps be able to propose changes to these folders?\n\nYou still approve every change in ConBridge before anything is written.";
26308
- const result2 = await osascript(`display dialog ${appleScriptString2(text6)} with title "ConBridge" buttons {"Read only", "Allow changes"} default button "Read only" giving up after 300`, 31e4);
26309
- return result2.ok && /button returned:Allow changes/.test(result2.stdout) && !/gave up:true/.test(result2.stdout);
26310
- },
26311
- notify(title, message) {
26312
- void osascript(`display notification ${appleScriptString2(message)} with title ${appleScriptString2(title)}`, 1e4);
26313
- },
26314
- fail(message) {
26315
- void osascript(`display dialog ${appleScriptString2(message)} with title "ConBridge" buttons {"OK"} default button "OK" with icon caution`, 12e4);
26790
+ Requested name: ${requestedName}`;
26791
+ }
26792
+ function connectOfferText(view) {
26793
+ const lines5 = [];
26794
+ if (view.replacing)
26795
+ lines5.push("This Mac is already connected. Connecting again replaces that connection.", "");
26796
+ lines5.push("Connect this Mac to this ConBridge organization?", "");
26797
+ lines5.push(`Organization: ${view.organization !== null ? `"${view.organization}"` : "organization not shown by this server"}`);
26798
+ lines5.push(`Invited by: ${view.inviter ?? "not shown by this server"}`);
26799
+ lines5.push(`Device fingerprint: ${view.fingerprint}`);
26800
+ lines5.push(`Requested name: ${view.requestedName}`);
26801
+ lines5.push(`Address: ${view.host}`, "");
26802
+ lines5.push("Continue only if you know this organization and ConBridge in your browser shows the same fingerprint.", "");
26803
+ const shared = describeLocalGrants(view.shared);
26804
+ if (shared.length === 0) {
26805
+ lines5.push("Nothing is shared from this Mac yet. You choose folders next.");
26806
+ } else {
26807
+ lines5.push("Already shared from this Mac:", ...shared.map((line) => `- ${line}`));
26808
+ lines5.push("They stay shared only if this Mac is approved for the ConBridge account and organization they were set up for; otherwise, or if they were set up while this Mac was not connected, they are removed before it connects. You can choose more folders next.");
26316
26809
  }
26317
- };
26810
+ return lines5.join("\n");
26811
+ }
26812
+ function appleScriptString(value) {
26813
+ return '"' + value.replace(/[\\"]/g, "\\$&").replace(/\r?\n/g, '" & linefeed & "') + '"';
26814
+ }
26815
+ var osascript = (script, timeoutMs) => new Promise((resolve10) => {
26816
+ (0, import_node_child_process6.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
26817
+ resolve10({ ok: !error63, stdout: stdout ?? "" });
26818
+ });
26819
+ });
26820
+ function pressed(result2, button) {
26821
+ return result2.ok && result2.stdout.includes(`button returned:${button}`) && !/gave up:true/.test(result2.stdout);
26822
+ }
26823
+ function createMacConnectDialogs(run2 = osascript) {
26824
+ return {
26825
+ async confirmConnect(host, requestedName, replacing) {
26826
+ const text6 = connectStartText(host, requestedName, replacing);
26827
+ const result2 = await run2(`display dialog ${appleScriptString(text6)} with title "ConBridge" buttons {"Cancel", "Continue"} default button "Continue" cancel button "Cancel" giving up after 300`, 31e4);
26828
+ return pressed(result2, "Continue");
26829
+ },
26830
+ async confirmOffer(view) {
26831
+ const text6 = connectOfferText(view);
26832
+ const result2 = await run2(`display dialog ${appleScriptString(text6)} with title "ConBridge" buttons {"Cancel", "Connect"} default button "Cancel" cancel button "Cancel" giving up after 300`, 31e4);
26833
+ return pressed(result2, "Connect");
26834
+ },
26835
+ async chooseFolders() {
26836
+ const script = 'set theFolders to choose folder with prompt "Choose the folders your AI apps may use. You can add more later." with multiple selections allowed\nset out to ""\nrepeat with f in theFolders\nset out to out & POSIX path of f & linefeed\nend repeat\nreturn out';
26837
+ const result2 = await run2(script, 6e5);
26838
+ if (!result2.ok)
26839
+ return [];
26840
+ return result2.stdout.split("\n").map((line) => line.trim().replace(/\/$/, "")).filter(Boolean);
26841
+ },
26842
+ async askAllowChanges() {
26843
+ const text6 = "Should your AI apps be able to propose changes to these folders?\n\nWhether a change waits for your approval follows your settings in ConBridge.";
26844
+ const result2 = await run2(`display dialog ${appleScriptString(text6)} with title "ConBridge" buttons {"Read only", "Allow changes"} default button "Read only" giving up after 300`, 31e4);
26845
+ return pressed(result2, "Allow changes");
26846
+ },
26847
+ notify(title, message) {
26848
+ void run2(`display notification ${appleScriptString(message)} with title ${appleScriptString(title)}`, 1e4);
26849
+ },
26850
+ fail(message) {
26851
+ void run2(`display dialog ${appleScriptString(message)} with title "ConBridge" buttons {"OK"} default button "OK" with icon caution`, 12e4);
26852
+ }
26853
+ };
26854
+ }
26855
+ var macConnectDialogs = createMacConnectDialogs();
26318
26856
 
26319
26857
  // dist/journal.js
26320
- var import_promises8 = require("node:fs/promises");
26321
- var import_node_path11 = require("node:path");
26858
+ var import_promises9 = require("node:fs/promises");
26859
+ var import_node_path12 = require("node:path");
26322
26860
  var storedResultSchema = external_exports.strictObject({
26323
26861
  state: external_exports.enum(["SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED"]),
26324
26862
  executed: external_exports.boolean(),
@@ -26393,7 +26931,7 @@ var Journal = class _Journal {
26393
26931
  const journal = new _Journal(path);
26394
26932
  let text6 = "";
26395
26933
  try {
26396
- text6 = await (0, import_promises8.readFile)(path, "utf8");
26934
+ text6 = await (0, import_promises9.readFile)(path, "utf8");
26397
26935
  } catch (error63) {
26398
26936
  if (errorCode2(error63) !== "ENOENT")
26399
26937
  throw error63;
@@ -26451,7 +26989,7 @@ var Journal = class _Journal {
26451
26989
  async #append(entry) {
26452
26990
  const line = JSON.stringify(entrySchema.parse(entry)) + "\n";
26453
26991
  await this.#serialize(async () => {
26454
- const handle = await (0, import_promises8.open)(this.#path, "a", 384);
26992
+ const handle = await (0, import_promises9.open)(this.#path, "a", 384);
26455
26993
  try {
26456
26994
  await handle.appendFile(line, "utf8");
26457
26995
  await handle.sync();
@@ -26501,7 +27039,7 @@ var Journal = class _Journal {
26501
27039
  return this.#serialize(async () => {
26502
27040
  let text6 = "";
26503
27041
  try {
26504
- text6 = await (0, import_promises8.readFile)(this.#path, "utf8");
27042
+ text6 = await (0, import_promises9.readFile)(this.#path, "utf8");
26505
27043
  } catch (error63) {
26506
27044
  if (errorCode2(error63) === "ENOENT")
26507
27045
  return;
@@ -26536,24 +27074,24 @@ var Journal = class _Journal {
26536
27074
  const lines5 = kept.map((entry) => JSON.stringify(entry) + "\n");
26537
27075
  if (watermark !== null)
26538
27076
  lines5.unshift(JSON.stringify(watermarkSchema.parse({ type: "WATERMARK", at_ms: now, watermark_ms: watermark })) + "\n");
26539
- const temp = (0, import_node_path11.join)((0, import_node_path11.dirname)(this.#path), `.${(0, import_node_path11.basename)(this.#path)}.${randomToken(6)}.tmp`);
26540
- const handle = await (0, import_promises8.open)(temp, "wx", 384);
27077
+ const temp = (0, import_node_path12.join)((0, import_node_path12.dirname)(this.#path), `.${(0, import_node_path12.basename)(this.#path)}.${randomToken(6)}.tmp`);
27078
+ const handle = await (0, import_promises9.open)(temp, "wx", 384);
26541
27079
  try {
26542
27080
  await handle.writeFile(lines5.join(""), "utf8");
26543
27081
  await handle.sync();
26544
27082
  } catch (error63) {
26545
27083
  await handle.close().catch(() => void 0);
26546
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27084
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26547
27085
  throw error63;
26548
27086
  }
26549
27087
  await handle.close();
26550
27088
  try {
26551
- await (0, import_promises8.rename)(temp, this.#path);
27089
+ await (0, import_promises9.rename)(temp, this.#path);
26552
27090
  } catch (error63) {
26553
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27091
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26554
27092
  throw error63;
26555
27093
  }
26556
- await fsyncDirectory((0, import_node_path11.dirname)(this.#path));
27094
+ await fsyncDirectory((0, import_node_path12.dirname)(this.#path));
26557
27095
  this.#records.clear();
26558
27096
  this.#nonces.clear();
26559
27097
  for (const entry of kept)
@@ -26565,22 +27103,22 @@ var Journal = class _Journal {
26565
27103
  };
26566
27104
 
26567
27105
  // dist/install.js
26568
- var import_promises9 = require("node:fs/promises");
26569
- var import_node_path12 = require("node:path");
27106
+ var import_promises10 = require("node:fs/promises");
27107
+ var import_node_path13 = require("node:path");
26570
27108
  var import_node_url2 = require("node:url");
26571
27109
  var RUNTIME_ENTRY = "conbridge-agent.cjs";
26572
27110
  function runtimeDir(stateDir) {
26573
- return (0, import_node_path12.join)(stateDir, "runtime");
27111
+ return (0, import_node_path13.join)(stateDir, "runtime");
26574
27112
  }
26575
27113
  function runtimeEntry(stateDir) {
26576
- return (0, import_node_path12.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
27114
+ return (0, import_node_path13.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
26577
27115
  }
26578
27116
  function currentEntry() {
26579
27117
  return (0, import_node_url2.fileURLToPath)(__conbridge_import_meta_url);
26580
27118
  }
26581
27119
  async function sameBytes(a, b) {
26582
27120
  try {
26583
- const [left, right] = await Promise.all([(0, import_promises9.readFile)(a), (0, import_promises9.readFile)(b)]);
27121
+ const [left, right] = await Promise.all([(0, import_promises10.readFile)(a), (0, import_promises10.readFile)(b)]);
26584
27122
  return left.equals(right);
26585
27123
  } catch {
26586
27124
  return false;
@@ -26589,11 +27127,11 @@ async function sameBytes(a, b) {
26589
27127
  async function copyAtomic(from, to, mode) {
26590
27128
  const temp = `${to}.${randomToken(6)}.tmp`;
26591
27129
  try {
26592
- await (0, import_promises9.copyFile)(from, temp);
26593
- await (0, import_promises9.chmod)(temp, mode);
26594
- await (0, import_promises9.rename)(temp, to);
27130
+ await (0, import_promises10.copyFile)(from, temp);
27131
+ await (0, import_promises10.chmod)(temp, mode);
27132
+ await (0, import_promises10.rename)(temp, to);
26595
27133
  } catch (error63) {
26596
- await (0, import_promises9.unlink)(temp).catch(() => void 0);
27134
+ await (0, import_promises10.unlink)(temp).catch(() => void 0);
26597
27135
  throw error63;
26598
27136
  }
26599
27137
  }
@@ -26602,21 +27140,21 @@ async function installRuntime(stateDir, from = {}) {
26602
27140
  const sourceDir = from.codeDir ?? codeDirectory();
26603
27141
  const dir = runtimeDir(stateDir);
26604
27142
  const entry = runtimeEntry(stateDir);
26605
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
26606
- await (0, import_promises9.chmod)(dir, 448);
27143
+ await (0, import_promises10.mkdir)(dir, { recursive: true, mode: 448 });
27144
+ await (0, import_promises10.chmod)(dir, 448);
26607
27145
  let changed = false;
26608
27146
  if (!await sameBytes(source, entry)) {
26609
27147
  await copyAtomic(source, entry, 384);
26610
27148
  changed = true;
26611
27149
  }
26612
- const helper = (0, import_node_path12.join)(sourceDir, KEYCHAIN_HELPER_NAME);
26613
- const helperTarget = (0, import_node_path12.join)(dir, KEYCHAIN_HELPER_NAME);
26614
- const hasHelper = await (0, import_promises9.stat)(helper).then((info) => info.isFile(), () => false);
27150
+ const helper = (0, import_node_path13.join)(sourceDir, KEYCHAIN_HELPER_NAME);
27151
+ const helperTarget = (0, import_node_path13.join)(dir, KEYCHAIN_HELPER_NAME);
27152
+ const hasHelper = await (0, import_promises10.stat)(helper).then((info) => info.isFile(), () => false);
26615
27153
  if (hasHelper && !await sameBytes(helper, helperTarget)) {
26616
27154
  await copyAtomic(helper, helperTarget, 493);
26617
27155
  changed = true;
26618
27156
  } else if (!hasHelper) {
26619
- await (0, import_promises9.unlink)(helperTarget).catch((error63) => {
27157
+ await (0, import_promises10.unlink)(helperTarget).catch((error63) => {
26620
27158
  if (errorCode2(error63) !== "ENOENT")
26621
27159
  throw error63;
26622
27160
  });
@@ -26626,26 +27164,26 @@ async function installRuntime(stateDir, from = {}) {
26626
27164
  async function snapshotRuntime(stateDir) {
26627
27165
  const dir = runtimeDir(stateDir);
26628
27166
  const backup = `${dir}.previous`;
26629
- await (0, import_promises9.rm)(backup, { recursive: true, force: true });
26630
- await (0, import_promises9.mkdir)(backup, { recursive: true, mode: 448 });
27167
+ await (0, import_promises10.rm)(backup, { recursive: true, force: true });
27168
+ await (0, import_promises10.mkdir)(backup, { recursive: true, mode: 448 });
26631
27169
  const saved = /* @__PURE__ */ new Map();
26632
27170
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
26633
- const info = await (0, import_promises9.stat)((0, import_node_path12.join)(dir, name3)).catch(() => null);
27171
+ const info = await (0, import_promises10.stat)((0, import_node_path13.join)(dir, name3)).catch(() => null);
26634
27172
  if (!info?.isFile())
26635
27173
  continue;
26636
- await (0, import_promises9.copyFile)((0, import_node_path12.join)(dir, name3), (0, import_node_path12.join)(backup, name3));
27174
+ await (0, import_promises10.copyFile)((0, import_node_path13.join)(dir, name3), (0, import_node_path13.join)(backup, name3));
26637
27175
  saved.set(name3, info.mode & 511);
26638
27176
  }
26639
- const discard = () => (0, import_promises9.rm)(backup, { recursive: true, force: true });
27177
+ const discard = () => (0, import_promises10.rm)(backup, { recursive: true, force: true });
26640
27178
  return {
26641
27179
  async restore() {
26642
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
27180
+ await (0, import_promises10.mkdir)(dir, { recursive: true, mode: 448 });
26643
27181
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
26644
27182
  const mode = saved.get(name3);
26645
27183
  if (mode !== void 0)
26646
- await copyAtomic((0, import_node_path12.join)(backup, name3), (0, import_node_path12.join)(dir, name3), mode);
27184
+ await copyAtomic((0, import_node_path13.join)(backup, name3), (0, import_node_path13.join)(dir, name3), mode);
26647
27185
  else
26648
- await (0, import_promises9.unlink)((0, import_node_path12.join)(dir, name3)).catch((error63) => {
27186
+ await (0, import_promises10.unlink)((0, import_node_path13.join)(dir, name3)).catch((error63) => {
26649
27187
  if (errorCode2(error63) !== "ENOENT")
26650
27188
  throw error63;
26651
27189
  });
@@ -26663,7 +27201,7 @@ async function runningFromRuntime(stateDir, entry = currentEntry()) {
26663
27201
  // dist/keepawake.js
26664
27202
  var import_node_child_process7 = require("node:child_process");
26665
27203
  var import_node_fs2 = require("node:fs");
26666
- var import_node_path13 = require("node:path");
27204
+ var import_node_path14 = require("node:path");
26667
27205
  var POWER_SUPPLY_DIR = "/sys/class/power_supply";
26668
27206
  var DISPLAY_SOCKET_DIRS = { x11: "/tmp/.X11-unix", runUser: "/run/user" };
26669
27207
  function entries(dir) {
@@ -26676,7 +27214,7 @@ function entries(dir) {
26676
27214
  function linuxDisplaySocket(env = process.env, dirs = DISPLAY_SOCKET_DIRS) {
26677
27215
  if (entries(dirs.x11).some((name3) => /^X\d+$/.test(name3)))
26678
27216
  return true;
26679
- const runtimeDirs = [...env.XDG_RUNTIME_DIR ? [env.XDG_RUNTIME_DIR] : [], ...entries(dirs.runUser).map((uid) => (0, import_node_path13.join)(dirs.runUser, uid))];
27217
+ const runtimeDirs = [...env.XDG_RUNTIME_DIR ? [env.XDG_RUNTIME_DIR] : [], ...entries(dirs.runUser).map((uid) => (0, import_node_path14.join)(dirs.runUser, uid))];
26680
27218
  return runtimeDirs.some((dir) => entries(dir).some((name3) => /^wayland-\d+$/.test(name3)));
26681
27219
  }
26682
27220
  function powerSupplies(dir) {
@@ -26693,7 +27231,7 @@ function powerSupplies(dir) {
26693
27231
  return null;
26694
27232
  }
26695
27233
  };
26696
- return names2.map((name3) => ({ type: read2((0, import_node_path13.join)(dir, name3, "type")) ?? "", online: read2((0, import_node_path13.join)(dir, name3, "online")) }));
27234
+ return names2.map((name3) => ({ type: read2((0, import_node_path14.join)(dir, name3, "type")) ?? "", online: read2((0, import_node_path14.join)(dir, name3, "online")) }));
26697
27235
  }
26698
27236
  var defaultProbe = {
26699
27237
  hasBattery: () => powerSupplies(POWER_SUPPLY_DIR).some((supply) => supply.type === "Battery"),
@@ -26858,7 +27396,7 @@ function startKeepAwake(options = {}) {
26858
27396
  }
26859
27397
 
26860
27398
  // dist/lock.js
26861
- var import_promises10 = require("node:fs/promises");
27399
+ var import_promises11 = require("node:fs/promises");
26862
27400
  function alive(pid) {
26863
27401
  try {
26864
27402
  process.kill(pid, 0);
@@ -26869,7 +27407,7 @@ function alive(pid) {
26869
27407
  }
26870
27408
  async function readLockPid(path) {
26871
27409
  try {
26872
- const pid = Number.parseInt((await (0, import_promises10.readFile)(path, "utf8")).trim(), 10);
27410
+ const pid = Number.parseInt((await (0, import_promises11.readFile)(path, "utf8")).trim(), 10);
26873
27411
  return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
26874
27412
  } catch {
26875
27413
  return null;
@@ -26878,12 +27416,12 @@ async function readLockPid(path) {
26878
27416
  async function acquireLock(path) {
26879
27417
  for (let attempt = 0; attempt < 2; attempt += 1) {
26880
27418
  try {
26881
- const handle = await (0, import_promises10.open)(path, "wx", 384);
27419
+ const handle = await (0, import_promises11.open)(path, "wx", 384);
26882
27420
  await handle.writeFile(`${process.pid}
26883
27421
  `);
26884
27422
  await handle.close();
26885
27423
  return async () => {
26886
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27424
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26887
27425
  };
26888
27426
  } catch (error63) {
26889
27427
  if (errorCode2(error63) !== "EEXIST")
@@ -26891,19 +27429,19 @@ async function acquireLock(path) {
26891
27429
  const pid = await readLockPid(path);
26892
27430
  if (pid !== null)
26893
27431
  throw new Error(`Another agent is already running (pid ${pid})`);
26894
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27432
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26895
27433
  }
26896
27434
  }
26897
27435
  throw new Error("Could not acquire the agent lock");
26898
27436
  }
26899
27437
 
26900
27438
  // dist/envelope.js
26901
- var import_node_crypto6 = require("node:crypto");
26902
- function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto6.randomUUID)()) {
27439
+ var import_node_crypto7 = require("node:crypto");
27440
+ function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto7.randomUUID)()) {
26903
27441
  return {
26904
27442
  version: 1,
26905
27443
  kind,
26906
- message_id: (0, import_node_crypto6.randomUUID)(),
27444
+ message_id: (0, import_node_crypto7.randomUUID)(),
26907
27445
  correlation_id: correlationId,
26908
27446
  tenant_id: identity.tenant_id,
26909
27447
  user_id: identity.user_id,
@@ -26947,13 +27485,13 @@ function excerpt(value) {
26947
27485
  var import_node_os14 = require("node:os");
26948
27486
 
26949
27487
  // dist/dispatcher.js
26950
- var import_node_crypto8 = require("node:crypto");
27488
+ var import_node_crypto9 = require("node:crypto");
26951
27489
 
26952
27490
  // dist/fileops.js
26953
27491
  var import_node_fs3 = require("node:fs");
26954
- var import_promises11 = require("node:fs/promises");
26955
- var import_node_crypto7 = require("node:crypto");
26956
- var import_node_path14 = require("node:path");
27492
+ var import_promises12 = require("node:fs/promises");
27493
+ var import_node_crypto8 = require("node:crypto");
27494
+ var import_node_path15 = require("node:path");
26957
27495
 
26958
27496
  // dist/glob.js
26959
27497
  function globToRegExp(glob) {
@@ -26981,18 +27519,29 @@ function globToRegExp(glob) {
26981
27519
  index += 1;
26982
27520
  }
26983
27521
  }
26984
- return new RegExp("^" + source + "$", "i");
27522
+ return new RegExp("^" + source + "$", "ius");
27523
+ }
27524
+ function foldPathText(text6) {
27525
+ return text6.normalize("NFKC").toUpperCase().toLowerCase().replace(/\u00df/gu, "ss");
26985
27526
  }
26986
27527
  var DenyMatcher = class {
26987
27528
  #patterns;
26988
27529
  constructor(globs) {
26989
- this.#patterns = globs.map(globToRegExp);
27530
+ this.#patterns = [...new Set(globs.flatMap((glob) => [glob, foldPathText(glob)]))].map(globToRegExp);
26990
27531
  }
26991
- /** True when the path or any of its ancestor directories matches a deny glob. */
27532
+ /**
27533
+ * True when the path or any of its ancestor directories matches a deny glob,
27534
+ * as written or folded (see {@link foldPathText}).
27535
+ */
26992
27536
  denies(relativePath3) {
26993
27537
  if (relativePath3 === "")
26994
27538
  return false;
26995
- const segments = relativePath3.split("/");
27539
+ const folded = foldPathText(relativePath3);
27540
+ const asciiLower2 = relativePath3.replace(/[A-Z]/gu, (letter) => letter.toLowerCase());
27541
+ return this.#matches(relativePath3) || folded !== asciiLower2 && this.#matches(folded);
27542
+ }
27543
+ #matches(path) {
27544
+ const segments = path.split("/");
26996
27545
  for (let length = 1; length <= segments.length; length += 1) {
26997
27546
  const prefix = segments.slice(0, length).join("/");
26998
27547
  if (this.#patterns.some((pattern) => pattern.test(prefix)))
@@ -27008,6 +27557,7 @@ var MAX_SEARCH_RESULTS = 100;
27008
27557
  var MAX_SEARCH_BYTES_PER_FILE = 2 * 1024 * 1024;
27009
27558
  var MAX_SEARCH_FILES = 1e4;
27010
27559
  var MAX_SEARCH_TOTAL_BYTES = 64 * 1024 * 1024;
27560
+ var MAX_MOVE_TREE_ENTRIES = 1e4;
27011
27561
  var PREVIEW_CHARS = 200;
27012
27562
  var READ_BLOCK = 64 * 1024;
27013
27563
  var OPEN_READ_FLAGS = import_node_fs3.constants.O_RDONLY | import_node_fs3.constants.O_NOFOLLOW | import_node_fs3.constants.O_NONBLOCK;
@@ -27025,7 +27575,8 @@ var WIRE_CODE = {
27025
27575
  EDIT_MISMATCH: "INVALID_MESSAGE",
27026
27576
  ALREADY_EXISTS: "INVALID_MESSAGE",
27027
27577
  NOT_EMPTY: "INVALID_MESSAGE",
27028
- TOO_LARGE: "SIZE_LIMIT"
27578
+ TOO_LARGE: "SIZE_LIMIT",
27579
+ OWNERSHIP_WOULD_CHANGE: "POLICY_DENIED"
27029
27580
  };
27030
27581
  var FileOpError = class extends Error {
27031
27582
  reason;
@@ -27044,6 +27595,8 @@ function normalizeRelativePath(input2) {
27044
27595
  throw new FileOpError("PATH_INVALID", "Path is invalid");
27045
27596
  if (input2.includes("\0"))
27046
27597
  throw new FileOpError("PATH_INVALID", "Path contains NUL");
27598
+ if (!isSafePathText(input2))
27599
+ throw new FileOpError("PATH_INVALID", "Path contains control, bidi or invisible characters");
27047
27600
  if (input2.startsWith("/") || input2.startsWith("\\") || /^[A-Za-z]:/.test(input2) || input2.startsWith("~")) {
27048
27601
  throw new FileOpError("PATH_INVALID", "Path must be relative to the root");
27049
27602
  }
@@ -27097,7 +27650,7 @@ function decodeText(bytes3) {
27097
27650
  }
27098
27651
  }
27099
27652
  async function hashHandle(handle) {
27100
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27653
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
27101
27654
  const buffer = Buffer.allocUnsafe(READ_BLOCK);
27102
27655
  let position2 = 0;
27103
27656
  for (; ; ) {
@@ -27110,7 +27663,7 @@ async function hashHandle(handle) {
27110
27663
  return hash2.digest("hex");
27111
27664
  }
27112
27665
  function sha256OfBytes(bytes3) {
27113
- return (0, import_node_crypto7.createHash)("sha256").update(bytes3).digest("hex");
27666
+ return (0, import_node_crypto8.createHash)("sha256").update(bytes3).digest("hex");
27114
27667
  }
27115
27668
  var RootedFs = class {
27116
27669
  #root;
@@ -27130,7 +27683,7 @@ var RootedFs = class {
27130
27683
  return;
27131
27684
  const forms = /* @__PURE__ */ new Set();
27132
27685
  for (const path of this.#protectedInput) {
27133
- forms.add((0, import_node_path14.resolve)(path));
27686
+ forms.add((0, import_node_path15.resolve)(path));
27134
27687
  forms.add(await realpathLenient(path));
27135
27688
  }
27136
27689
  this.#protected = [...forms];
@@ -27140,7 +27693,7 @@ var RootedFs = class {
27140
27693
  #blockedReal(real) {
27141
27694
  if (this.#protected.some((dir) => isSameOrInside(dir, real)))
27142
27695
  return true;
27143
- return this.#hardDeny.denies(real.split(import_node_path14.sep).filter((segment) => segment !== "").join("/"));
27696
+ return this.#hardDeny.denies(real.split(import_node_path15.sep).filter((segment) => segment !== "").join("/"));
27144
27697
  }
27145
27698
  #checkReal(real) {
27146
27699
  if (this.#blockedReal(real))
@@ -27149,8 +27702,8 @@ var RootedFs = class {
27149
27702
  async #rootReal() {
27150
27703
  await this.#loadProtected();
27151
27704
  try {
27152
- const real = await (0, import_promises11.realpath)(this.#root.path);
27153
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
27705
+ const real = await (0, import_promises12.realpath)(this.#root.path);
27706
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27154
27707
  throw new FileOpError("NOT_FOUND", "Root is unavailable");
27155
27708
  return real;
27156
27709
  } catch (error63) {
@@ -27160,11 +27713,11 @@ var RootedFs = class {
27160
27713
  }
27161
27714
  }
27162
27715
  #inside(rootReal, real) {
27163
- const prefix = rootReal.endsWith(import_node_path14.sep) ? rootReal : rootReal + import_node_path14.sep;
27716
+ const prefix = rootReal.endsWith(import_node_path15.sep) ? rootReal : rootReal + import_node_path15.sep;
27164
27717
  return real === rootReal || real.startsWith(prefix);
27165
27718
  }
27166
27719
  #relativeOf(rootReal, real) {
27167
- return (0, import_node_path14.relative)(rootReal, real).split(import_node_path14.sep).join("/");
27720
+ return (0, import_node_path15.relative)(rootReal, real).split(import_node_path15.sep).join("/");
27168
27721
  }
27169
27722
  #checkDeny(rel) {
27170
27723
  if (this.#deny.denies(rel))
@@ -27177,7 +27730,7 @@ var RootedFs = class {
27177
27730
  const rootReal = await this.#rootReal();
27178
27731
  let real;
27179
27732
  try {
27180
- real = await (0, import_promises11.realpath)((0, import_node_path14.join)(rootReal, rel));
27733
+ real = await (0, import_promises12.realpath)((0, import_node_path15.join)(rootReal, rel));
27181
27734
  } catch (error63) {
27182
27735
  throw mapFsError(error63, rel);
27183
27736
  }
@@ -27196,10 +27749,10 @@ var RootedFs = class {
27196
27749
  async #openVerified(rootReal, real) {
27197
27750
  let handle;
27198
27751
  try {
27199
- const before = await (0, import_promises11.lstat)(real);
27752
+ const before = await (0, import_promises12.lstat)(real);
27200
27753
  if (!before.isFile())
27201
27754
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
27202
- handle = await (0, import_promises11.open)(real, OPEN_READ_FLAGS);
27755
+ handle = await (0, import_promises12.open)(real, OPEN_READ_FLAGS);
27203
27756
  } catch (error63) {
27204
27757
  throw mapFsError(error63, "");
27205
27758
  }
@@ -27207,8 +27760,8 @@ var RootedFs = class {
27207
27760
  const info = await handle.stat();
27208
27761
  if (!info.isFile())
27209
27762
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
27210
- const again = await (0, import_promises11.realpath)(real);
27211
- const pathInfo = await (0, import_promises11.stat)(again);
27763
+ const again = await (0, import_promises12.realpath)(real);
27764
+ const pathInfo = await (0, import_promises12.stat)(again);
27212
27765
  if (again !== real || !this.#inside(rootReal, again) || pathInfo.ino !== info.ino || pathInfo.dev !== info.dev) {
27213
27766
  throw new FileOpError("PATH_ESCAPE", "Path changed while it was being opened");
27214
27767
  }
@@ -27227,7 +27780,7 @@ var RootedFs = class {
27227
27780
  try {
27228
27781
  if (!info.isFile())
27229
27782
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file", { path: rel });
27230
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27783
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
27231
27784
  const kept = [];
27232
27785
  let keptBytes = 0;
27233
27786
  let size = 0;
@@ -27260,18 +27813,18 @@ var RootedFs = class {
27260
27813
  async list(input2) {
27261
27814
  const { rel, real } = await this.resolveExisting(input2);
27262
27815
  try {
27263
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
27816
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27264
27817
  throw new FileOpError("NOT_A_DIRECTORY", "Path is not a directory", { path: rel });
27265
- const dir = await (0, import_promises11.opendir)(real);
27818
+ const dir = await (0, import_promises12.opendir)(real);
27266
27819
  const names2 = [];
27267
27820
  for await (const entry of dir) {
27268
27821
  const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
27269
27822
  if (this.#deny.denies(childRel))
27270
27823
  continue;
27271
- const childReal = (0, import_node_path14.join)(real, entry.name);
27824
+ const childReal = (0, import_node_path15.join)(real, entry.name);
27272
27825
  if (this.#blockedReal(childReal))
27273
27826
  continue;
27274
- if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises11.realpath)(childReal).catch(() => childReal)))
27827
+ if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises12.realpath)(childReal).catch(() => childReal)))
27275
27828
  continue;
27276
27829
  const type = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "other";
27277
27830
  names2.push({ name: entry.name, type });
@@ -27280,7 +27833,7 @@ var RootedFs = class {
27280
27833
  const entries2 = [];
27281
27834
  for (const item of names2.slice(0, MAX_LIST_ENTRIES)) {
27282
27835
  if (item.type === "file") {
27283
- const size = await (0, import_promises11.lstat)((0, import_node_path14.join)(real, item.name)).then((s) => s.size, () => void 0);
27836
+ const size = await (0, import_promises12.lstat)((0, import_node_path15.join)(real, item.name)).then((s) => s.size, () => void 0);
27284
27837
  entries2.push(size === void 0 ? item : { ...item, size });
27285
27838
  } else
27286
27839
  entries2.push(item);
@@ -27303,7 +27856,7 @@ var RootedFs = class {
27303
27856
  return;
27304
27857
  let resolved;
27305
27858
  try {
27306
- resolved = await (0, import_promises11.realpath)(fileReal);
27859
+ resolved = await (0, import_promises12.realpath)(fileReal);
27307
27860
  } catch {
27308
27861
  return;
27309
27862
  }
@@ -27311,9 +27864,9 @@ var RootedFs = class {
27311
27864
  return;
27312
27865
  let handle;
27313
27866
  try {
27314
- if (!(await (0, import_promises11.lstat)(resolved)).isFile())
27867
+ if (!(await (0, import_promises12.lstat)(resolved)).isFile())
27315
27868
  return;
27316
- handle = await (0, import_promises11.open)(resolved, OPEN_READ_FLAGS);
27869
+ handle = await (0, import_promises12.open)(resolved, OPEN_READ_FLAGS);
27317
27870
  } catch {
27318
27871
  return;
27319
27872
  }
@@ -27355,7 +27908,7 @@ var RootedFs = class {
27355
27908
  await handle.close().catch(() => void 0);
27356
27909
  }
27357
27910
  };
27358
- const start = await (0, import_promises11.stat)(real).catch((error63) => {
27911
+ const start = await (0, import_promises12.stat)(real).catch((error63) => {
27359
27912
  throw mapFsError(error63, rel);
27360
27913
  });
27361
27914
  if (start.isFile()) {
@@ -27366,7 +27919,7 @@ var RootedFs = class {
27366
27919
  const current = queue.shift();
27367
27920
  let entries2;
27368
27921
  try {
27369
- const dir = await (0, import_promises11.opendir)(current.real);
27922
+ const dir = await (0, import_promises12.opendir)(current.real);
27370
27923
  entries2 = [];
27371
27924
  for await (const entry of dir) {
27372
27925
  entries2.push({ name: entry.name, file: entry.isFile(), dir: entry.isDirectory() });
@@ -27381,7 +27934,7 @@ var RootedFs = class {
27381
27934
  const childRel = current.rel === "" ? entry.name : `${current.rel}/${entry.name}`;
27382
27935
  if (this.#deny.denies(childRel))
27383
27936
  continue;
27384
- const childReal = (0, import_node_path14.join)(current.real, entry.name);
27937
+ const childReal = (0, import_node_path15.join)(current.real, entry.name);
27385
27938
  if (this.#blockedReal(childReal))
27386
27939
  continue;
27387
27940
  if (entry.dir)
@@ -27403,10 +27956,10 @@ var RootedFs = class {
27403
27956
  async #currentHash(rootReal, target) {
27404
27957
  let info;
27405
27958
  try {
27406
- info = await (0, import_promises11.lstat)(target);
27959
+ info = await (0, import_promises12.lstat)(target);
27407
27960
  } catch (error63) {
27408
27961
  if (errorCode2(error63) === "ENOENT")
27409
- return { sha256: null, mode: null };
27962
+ return { sha256: null, mode: null, uid: null, gid: null };
27410
27963
  throw mapFsError(error63, "");
27411
27964
  }
27412
27965
  if (info.isSymbolicLink())
@@ -27415,7 +27968,7 @@ var RootedFs = class {
27415
27968
  throw new FileOpError("NOT_A_FILE", "Target is not a regular file");
27416
27969
  const { handle } = await this.#openVerified(rootReal, target);
27417
27970
  try {
27418
- return { sha256: await hashHandle(handle), mode: info.mode & 4095 };
27971
+ return { sha256: await hashHandle(handle), mode: info.mode & 4095, uid: info.uid, gid: info.gid };
27419
27972
  } finally {
27420
27973
  await handle.close().catch(() => void 0);
27421
27974
  }
@@ -27435,8 +27988,8 @@ var RootedFs = class {
27435
27988
  const name3 = slash < 0 ? rel : rel.slice(slash + 1);
27436
27989
  let parentReal;
27437
27990
  try {
27438
- parentReal = await (0, import_promises11.realpath)((0, import_node_path14.join)(rootReal, parentRel));
27439
- if (!(await (0, import_promises11.stat)(parentReal)).isDirectory())
27991
+ parentReal = await (0, import_promises12.realpath)((0, import_node_path15.join)(rootReal, parentRel));
27992
+ if (!(await (0, import_promises12.stat)(parentReal)).isDirectory())
27440
27993
  throw new FileOpError("NOT_A_DIRECTORY", "Parent is not a directory");
27441
27994
  } catch (error63) {
27442
27995
  if (errorCode2(error63) === "ENOENT")
@@ -27447,44 +28000,76 @@ var RootedFs = class {
27447
28000
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27448
28001
  const parentRealRel = this.#relativeOf(rootReal, parentReal);
27449
28002
  this.#checkDeny(parentRealRel === "" ? name3 : `${parentRealRel}/${name3}`);
27450
- const target = (0, import_node_path14.join)(parentReal, name3);
28003
+ const target = (0, import_node_path15.join)(parentReal, name3);
27451
28004
  this.#checkReal(target);
27452
28005
  return { rel, rootReal, parentReal, name: name3, target };
27453
28006
  }
27454
- /** Temp file in the same directory, fsync, re-check the version, rename over the target. */
28007
+ /**
28008
+ * Give the temp file that replaces an existing file the file's owner and group, so a fix keeps a
28009
+ * www-data:www-data file readable by the web server. Ownership of a new inode can only be changed with chown: a
28010
+ * root agent can always set both; another agent user can set a group it belongs to but cannot give a file away.
28011
+ * When the owner would change (the agent does not own the file, or the file system ignored the chown) the write is
28012
+ * refused with OWNERSHIP_WOULD_CHANGE before anything is renamed. When only the group cannot be kept, the write
28013
+ * goes ahead and returns true (reported as `ownership_changed`). Runs before chmod: chown clears setuid/setgid.
28014
+ */
28015
+ async #keepOwnership(handle, before, rel) {
28016
+ if (before.uid === null || before.gid === null)
28017
+ return false;
28018
+ let temp = await handle.stat();
28019
+ if (temp.uid !== before.uid) {
28020
+ await handle.chown(before.uid, before.gid).catch(() => void 0);
28021
+ temp = await handle.stat();
28022
+ if (temp.uid !== before.uid) {
28023
+ throw new FileOpError("OWNERSHIP_WOULD_CHANGE", "The file belongs to another user and replacing it would make the agent its owner; nothing was changed", { path: rel });
28024
+ }
28025
+ }
28026
+ if (temp.gid !== before.gid) {
28027
+ await handle.chown(-1, before.gid).catch(() => void 0);
28028
+ temp = await handle.stat();
28029
+ }
28030
+ return temp.gid !== before.gid;
28031
+ }
28032
+ /**
28033
+ * Temp file in the same directory with the replaced file's owner, group and mode; fsync, re-check the version,
28034
+ * rename over the target. Returns true when the file's group could not be kept.
28035
+ */
27455
28036
  async #replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3) {
27456
- const temp = (0, import_node_path14.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
28037
+ const temp = (0, import_node_path15.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
27457
28038
  let handle;
27458
28039
  try {
27459
- handle = await (0, import_promises11.open)(temp, import_node_fs3.constants.O_WRONLY | import_node_fs3.constants.O_CREAT | import_node_fs3.constants.O_EXCL | import_node_fs3.constants.O_NOFOLLOW, before.mode ?? 438);
28040
+ handle = await (0, import_promises12.open)(temp, import_node_fs3.constants.O_WRONLY | import_node_fs3.constants.O_CREAT | import_node_fs3.constants.O_EXCL | import_node_fs3.constants.O_NOFOLLOW, before.mode ?? 438);
27460
28041
  } catch (error63) {
27461
28042
  throw mapFsError(error63, rel);
27462
28043
  }
27463
28044
  let renamed = false;
28045
+ let groupLost = false;
27464
28046
  try {
27465
28047
  try {
28048
+ if (before.sha256 !== null)
28049
+ groupLost = await this.#keepOwnership(handle, before, rel);
28050
+ await handle.writeFile(bytes3);
27466
28051
  if (before.mode !== null)
27467
28052
  await handle.chmod(before.mode);
27468
- await handle.writeFile(bytes3);
27469
28053
  await handle.sync();
27470
28054
  } finally {
27471
28055
  await handle.close();
27472
28056
  }
27473
- if (await (0, import_promises11.realpath)(parentReal) !== parentReal)
28057
+ if (await (0, import_promises12.realpath)(parentReal) !== parentReal)
27474
28058
  throw new FileOpError("PATH_ESCAPE", "Directory changed during write");
27475
28059
  const again = await this.#currentHash(rootReal, target);
27476
28060
  if (again.sha256 !== before.sha256) {
27477
28061
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed during write", { path: rel, current_sha256: again.sha256 });
27478
28062
  }
27479
- await (0, import_promises11.rename)(temp, target);
28063
+ await (0, import_promises12.rename)(temp, target);
27480
28064
  renamed = true;
27481
28065
  await fsyncDirectory(parentReal);
27482
28066
  } catch (error63) {
27483
28067
  throw mapFsError(error63, rel);
27484
28068
  } finally {
27485
28069
  if (!renamed)
27486
- await (0, import_promises11.unlink)(temp).catch(() => void 0);
28070
+ await (0, import_promises12.unlink)(temp).catch(() => void 0);
27487
28071
  }
28072
+ return groupLost;
27488
28073
  }
27489
28074
  #requireWritable() {
27490
28075
  if (!this.#root.writable)
@@ -27492,8 +28077,9 @@ var RootedFs = class {
27492
28077
  }
27493
28078
  /**
27494
28079
  * Version-checked atomic write: `expectedSha256` must equal the current hash,
27495
- * or be null with the file absent. Writes a temp file in the same directory,
27496
- * fsyncs it, re-checks the version and renames over the target.
28080
+ * or be null with the file absent. Writes a temp file in the same directory
28081
+ * (with the replaced file's owner, group and mode), fsyncs it, re-checks the
28082
+ * version and renames over the target.
27497
28083
  */
27498
28084
  async write(input2, expectedSha256, content) {
27499
28085
  this.#requireWritable();
@@ -27503,15 +28089,16 @@ var RootedFs = class {
27503
28089
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: before.sha256 });
27504
28090
  }
27505
28091
  const bytes3 = Buffer.from(content, "utf8");
27506
- await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
27507
- return { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, created: before.sha256 === null };
28092
+ const groupLost = await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
28093
+ const result2 = { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, created: before.sha256 === null };
28094
+ return groupLost ? { ...result2, ownership_changed: true } : result2;
27508
28095
  }
27509
28096
  /** Size, dates and type of a file or directory; files up to 8 MiB also get their sha256 (for edit and delete). */
27510
28097
  async info(input2) {
27511
28098
  const { rel, real, rootReal } = await this.resolveExisting(input2);
27512
28099
  let info;
27513
28100
  try {
27514
- info = await (0, import_promises11.lstat)(real);
28101
+ info = await (0, import_promises12.lstat)(real);
27515
28102
  } catch (error63) {
27516
28103
  throw mapFsError(error63, rel);
27517
28104
  }
@@ -27533,7 +28120,7 @@ var RootedFs = class {
27533
28120
  }
27534
28121
  }
27535
28122
  if (type === "directory") {
27536
- const entries2 = await (0, import_promises11.readdir)(real).then((names2) => names2.length, () => void 0);
28123
+ const entries2 = await (0, import_promises12.readdir)(real).then((names2) => names2.length, () => void 0);
27537
28124
  return entries2 === void 0 ? base2 : { ...base2, entries: entries2 };
27538
28125
  }
27539
28126
  return base2;
@@ -27570,8 +28157,9 @@ var RootedFs = class {
27570
28157
  throw new FileOpError("EDIT_MISMATCH", `old_text was found ${found} times, expected ${expectedReplacements}`, { path: rel, found });
27571
28158
  }
27572
28159
  const bytes3 = Buffer.from(parts.join(newText), "utf8");
27573
- await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
27574
- return { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, replacements: found };
28160
+ const groupLost = await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
28161
+ const result2 = { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, replacements: found };
28162
+ return groupLost ? { ...result2, ownership_changed: true } : result2;
27575
28163
  }
27576
28164
  /** Create a directory and its missing parents, each checked against the root and the deny rules. */
27577
28165
  async mkdir(input2) {
@@ -27583,14 +28171,14 @@ var RootedFs = class {
27583
28171
  let created = false;
27584
28172
  for (let index = 1; index <= segments.length; index += 1) {
27585
28173
  const { rootReal, target } = await this.#resolveNew(segments.slice(0, index).join("/"));
27586
- const existing = await (0, import_promises11.lstat)(target).catch(() => null);
28174
+ const existing = await (0, import_promises12.lstat)(target).catch(() => null);
27587
28175
  if (existing) {
27588
28176
  const segment = segments.slice(0, index).join("/");
27589
28177
  if (existing.isSymbolicLink()) {
27590
- const real = await (0, import_promises11.realpath)(target).catch(() => null);
28178
+ const real = await (0, import_promises12.realpath)(target).catch(() => null);
27591
28179
  if (real === null || !this.#inside(rootReal, real))
27592
28180
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: segment });
27593
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
28181
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27594
28182
  throw new FileOpError("ALREADY_EXISTS", "A file with that name exists", { path: segment });
27595
28183
  continue;
27596
28184
  }
@@ -27599,35 +28187,143 @@ var RootedFs = class {
27599
28187
  continue;
27600
28188
  }
27601
28189
  try {
27602
- await (0, import_promises11.mkdir)(target, { mode: 511 });
28190
+ await (0, import_promises12.mkdir)(target, { mode: 511 });
27603
28191
  } catch (error63) {
27604
28192
  if (errorCode2(error63) !== "EEXIST")
27605
28193
  throw mapFsError(error63, rel);
27606
28194
  }
27607
- if (!this.#inside(rootReal, await (0, import_promises11.realpath)(target)))
28195
+ if (!this.#inside(rootReal, await (0, import_promises12.realpath)(target)))
27608
28196
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27609
28197
  created = true;
27610
28198
  }
27611
28199
  return { path: rel, created };
27612
28200
  }
28201
+ /**
28202
+ * Walk a folder about to be moved, without following symlinks, and refuse (PATH_DENIED) when any entry, file or
28203
+ * folder, is denied at its current path or at the path it would get after the move: by the root-relative deny
28204
+ * globs (requested and real form) or by the absolute hard-deny/protected check `read` uses. More than
28205
+ * MAX_MOVE_TREE_ENTRIES entries, or a folder that cannot be read, refuses the move: unchecked content never moves.
28206
+ * `from.real` is the folder's real path (see #moveSource), so its real name is what the globs see.
28207
+ */
28208
+ async #checkMovedTree(from, dest) {
28209
+ const bases = [
28210
+ { rel: from.rel, realRel: this.#relativeOf(from.rootReal, from.real), real: from.real },
28211
+ { rel: dest.rel, realRel: this.#relativeOf(dest.rootReal, dest.target), real: dest.target }
28212
+ ];
28213
+ const denied = (suffix) => bases.some((base2) => this.#deny.denies(`${base2.rel}/${suffix}`) || this.#deny.denies(`${base2.realRel}/${suffix}`) || this.#blockedReal((0, import_node_path15.join)(base2.real, ...suffix.split("/"))));
28214
+ const queue = [""];
28215
+ let seen = 0;
28216
+ while (queue.length > 0) {
28217
+ const dirSuffix = queue.shift();
28218
+ const dirReal = dirSuffix === "" ? from.real : (0, import_node_path15.join)(from.real, ...dirSuffix.split("/"));
28219
+ try {
28220
+ for await (const entry of await (0, import_promises12.opendir)(dirReal)) {
28221
+ seen += 1;
28222
+ if (seen > MAX_MOVE_TREE_ENTRIES) {
28223
+ throw new FileOpError("TOO_LARGE", `Folder has more than ${MAX_MOVE_TREE_ENTRIES} entries; move it on the computer itself`, { path: from.rel });
28224
+ }
28225
+ const suffix = dirSuffix === "" ? entry.name : `${dirSuffix}/${entry.name}`;
28226
+ if (denied(suffix)) {
28227
+ throw new FileOpError("PATH_DENIED", "Folder contains files blocked by a local deny rule", { path: from.rel });
28228
+ }
28229
+ let isDir = entry.isDirectory();
28230
+ if (!isDir && !entry.isFile() && !entry.isSymbolicLink() && !entry.isFIFO() && !entry.isSocket() && !entry.isBlockDevice() && !entry.isCharacterDevice()) {
28231
+ isDir = (await (0, import_promises12.lstat)((0, import_node_path15.join)(dirReal, entry.name))).isDirectory();
28232
+ }
28233
+ if (isDir)
28234
+ queue.push(suffix);
28235
+ }
28236
+ } catch (error63) {
28237
+ if (error63 instanceof FileOpError)
28238
+ throw error63;
28239
+ throw new FileOpError("IO_ERROR", "Folder contents could not be checked; nothing was moved", { path: from.rel });
28240
+ }
28241
+ }
28242
+ }
28243
+ /**
28244
+ * The entry a move would rename, judged under its real name. A case-insensitive file system (APFS by default,
28245
+ * NTFS, casefold ext4) resolves a typed alias to another entry: with a long s (U+017F), Kelvin sign (U+212A),
28246
+ * fi ligature (U+FB01) or sharp s (U+00DF) a typed name reaches `.aws`, `.kube`, `.config` or `.ssh`. The deny
28247
+ * rules must judge that entry, so they run on its real path: for a file or folder the native realpath
28248
+ * (case-correcting on macOS), for a symlink the parent's entry with the same inode (the link is not followed).
28249
+ * The typed name must then be that entry's own name (canonically equal Unicode is accepted), otherwise
28250
+ * PATH_INVALID: an alias never moves and never reaches an approval preview as a look-alike name.
28251
+ */
28252
+ async #moveSource(from, source) {
28253
+ let names2;
28254
+ try {
28255
+ names2 = await (0, import_promises12.readdir)(from.parentReal);
28256
+ } catch (error63) {
28257
+ throw mapFsError(error63, from.rel);
28258
+ }
28259
+ const typed = from.name.normalize("NFC");
28260
+ const sameName = (name3) => name3 === from.name || name3.normalize("NFC") === typed;
28261
+ let entry;
28262
+ let real;
28263
+ if (source.isSymbolicLink()) {
28264
+ const sameEntry = async (name3) => {
28265
+ const info = await (0, import_promises12.lstat)((0, import_node_path15.join)(from.parentReal, name3)).catch(() => null);
28266
+ return info !== null && info.isSymbolicLink() && info.ino === source.ino && info.dev === source.dev;
28267
+ };
28268
+ for (const name3 of names2.filter(sameName)) {
28269
+ if (await sameEntry(name3)) {
28270
+ entry = name3;
28271
+ break;
28272
+ }
28273
+ }
28274
+ if (entry === void 0) {
28275
+ for (const name3 of names2) {
28276
+ if (await sameEntry(name3)) {
28277
+ entry = name3;
28278
+ break;
28279
+ }
28280
+ }
28281
+ }
28282
+ if (entry === void 0)
28283
+ throw new FileOpError("PATH_ESCAPE", "Path changed while it was being moved", { path: from.rel });
28284
+ real = (0, import_node_path15.join)(from.parentReal, entry);
28285
+ } else {
28286
+ try {
28287
+ real = await (0, import_promises12.realpath)(from.target);
28288
+ } catch (error63) {
28289
+ throw mapFsError(error63, from.rel);
28290
+ }
28291
+ if (!this.#inside(from.rootReal, real))
28292
+ throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: from.rel });
28293
+ entry = real === (0, import_node_path15.join)(from.parentReal, (0, import_node_path15.basename)(real)) && names2.includes((0, import_node_path15.basename)(real)) ? (0, import_node_path15.basename)(real) : void 0;
28294
+ }
28295
+ try {
28296
+ this.#checkDeny(this.#relativeOf(from.rootReal, real));
28297
+ this.#checkReal(real);
28298
+ } catch (error63) {
28299
+ throw error63 instanceof FileOpError ? new FileOpError(error63.reason, error63.message, { path: from.rel }) : error63;
28300
+ }
28301
+ if (entry === void 0 || !sameName(entry)) {
28302
+ throw new FileOpError("PATH_INVALID", "Path does not match the name on disk; use the exact name files.list shows", { path: from.rel });
28303
+ }
28304
+ return { path: (0, import_node_path15.join)(from.parentReal, entry), real };
28305
+ }
27613
28306
  /** Move or rename inside this root. The destination must not exist; a symlink is moved as itself. */
27614
28307
  async move(input2, to) {
27615
28308
  this.#requireWritable();
27616
28309
  const from = await this.#resolveNew(input2);
27617
- const source = await (0, import_promises11.lstat)(from.target).catch(() => null);
28310
+ const source = await (0, import_promises12.lstat)(from.target).catch(() => null);
27618
28311
  if (!source)
27619
28312
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: from.rel });
27620
- const sourceReal = await (0, import_promises11.realpath)(from.target).catch(() => from.target);
27621
- if (this.#protected.some((path) => isSameOrInside(from.target, path) || isSameOrInside(sourceReal, path))) {
28313
+ const { path: sourcePath, real: sourceReal } = await this.#moveSource(from, source);
28314
+ const followed = source.isSymbolicLink() ? await (0, import_promises12.realpath)(sourcePath).catch(() => sourcePath) : sourceReal;
28315
+ if (this.#protected.some((path) => isSameOrInside(sourcePath, path) || isSameOrInside(followed, path))) {
27622
28316
  throw new FileOpError("PATH_DENIED", "Path contains files the agent protects", { path: from.rel });
27623
28317
  }
27624
28318
  const dest = await this.#resolveNew(to);
27625
- if (isSameOrInside(from.target, dest.target))
28319
+ if (isSameOrInside(sourcePath, dest.target))
27626
28320
  throw new FileOpError("PATH_INVALID", "Cannot move a folder into itself");
27627
- if (await (0, import_promises11.lstat)(dest.target).then(() => true, () => false))
28321
+ if (await (0, import_promises12.lstat)(dest.target).then(() => true, () => false))
27628
28322
  throw new FileOpError("ALREADY_EXISTS", "The destination already exists", { path: dest.rel });
28323
+ if (source.isDirectory())
28324
+ await this.#checkMovedTree({ rel: from.rel, rootReal: from.rootReal, real: sourceReal }, dest);
27629
28325
  try {
27630
- await (0, import_promises11.rename)(from.target, dest.target);
28326
+ await (0, import_promises12.rename)(sourcePath, dest.target);
27631
28327
  } catch (error63) {
27632
28328
  throw mapFsError(error63, from.rel);
27633
28329
  }
@@ -27638,14 +28334,14 @@ var RootedFs = class {
27638
28334
  async delete(input2, expectedSha256) {
27639
28335
  this.#requireWritable();
27640
28336
  const { rel, rootReal, target, parentReal } = await this.#resolveNew(input2);
27641
- const info = await (0, import_promises11.lstat)(target).catch(() => null);
28337
+ const info = await (0, import_promises12.lstat)(target).catch(() => null);
27642
28338
  if (!info)
27643
28339
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: rel });
27644
28340
  if (info.isDirectory()) {
27645
28341
  if (expectedSha256 !== null)
27646
28342
  throw new FileOpError("NOT_A_FILE", "Path is a directory; pass expected_sha256 null", { path: rel });
27647
28343
  try {
27648
- await (0, import_promises11.rmdir)(target);
28344
+ await (0, import_promises12.rmdir)(target);
27649
28345
  } catch (error63) {
27650
28346
  if (errorCode2(error63) === "ENOTEMPTY" || errorCode2(error63) === "EEXIST")
27651
28347
  throw new FileOpError("NOT_EMPTY", "Directory is not empty", { path: rel });
@@ -27659,7 +28355,7 @@ var RootedFs = class {
27659
28355
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: current.sha256 });
27660
28356
  }
27661
28357
  try {
27662
- await (0, import_promises11.unlink)(target);
28358
+ await (0, import_promises12.unlink)(target);
27663
28359
  } catch (error63) {
27664
28360
  throw mapFsError(error63, rel);
27665
28361
  }
@@ -27697,10 +28393,10 @@ async function verifyGrantAuthenticity(dispatch2, identity) {
27697
28393
  function actingUserId(dispatch2) {
27698
28394
  return dispatch2.grant.on_behalf_of ?? dispatch2.grant.user_id;
27699
28395
  }
27700
- function isExpired(dispatch2, nowMs) {
28396
+ function isExpired(dispatch2, gatewayNowMs) {
27701
28397
  const expires = Date.parse(dispatch2.grant.expires_at);
27702
28398
  const deadline = Date.parse(dispatch2.deadline_at);
27703
- return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= nowMs || deadline <= nowMs;
28399
+ return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= gatewayNowMs || deadline <= gatewayNowMs;
27704
28400
  }
27705
28401
  function isSupportedCapability(capability2) {
27706
28402
  return capabilityDefinition(capability2)?.connector === "desktop" && (isAgentCapability(capability2) || isDesktopCapability(capability2) || isSshCapability(capability2) || isShellCapability(capability2) || isDiagCapability(capability2));
@@ -27835,6 +28531,36 @@ function denialResult(denial) {
27835
28531
  output_excerpt: excerpt({ error: denial.code, reason: denial.reason, message: denial.message })
27836
28532
  };
27837
28533
  }
28534
+ var CHANGING_FILE_CAPABILITIES = /* @__PURE__ */ new Set(["files.write", "files.edit", "files.delete", "files.move", "files.mkdir"]);
28535
+ function confirmationFor(task) {
28536
+ const rootLabel = task.root.label;
28537
+ switch (task.capability) {
28538
+ case "files.write": {
28539
+ const payload = task.payload;
28540
+ return {
28541
+ action: "write",
28542
+ rootLabel,
28543
+ path: normalizeRelativePath(payload.path),
28544
+ bytes: Buffer.byteLength(payload.content, "utf8"),
28545
+ created: payload.expected_sha256 === null
28546
+ };
28547
+ }
28548
+ case "files.edit": {
28549
+ const payload = task.payload;
28550
+ return { action: "edit", rootLabel, path: normalizeRelativePath(payload.path), replacements: payload.expected_replacements };
28551
+ }
28552
+ case "files.delete":
28553
+ return { action: "delete", rootLabel, path: normalizeRelativePath(task.payload.path) };
28554
+ case "files.move": {
28555
+ const payload = task.payload;
28556
+ return { action: "move", rootLabel, path: normalizeRelativePath(payload.path), to: normalizeRelativePath(payload.to) };
28557
+ }
28558
+ case "files.mkdir":
28559
+ return { action: "mkdir", rootLabel, path: normalizeRelativePath(task.payload.path) };
28560
+ default:
28561
+ throw new FileOpError("PATH_INVALID", "Task does not change files");
28562
+ }
28563
+ }
27838
28564
  function fileErrorResult(error63) {
27839
28565
  return {
27840
28566
  state: "FAILED",
@@ -27857,6 +28583,8 @@ var Dispatcher = class {
27857
28583
  this.#logger = options.logger ?? silentLogger;
27858
28584
  this.#protectedPaths = options.protectedPaths ?? protectedAgentPaths(resolveStateDir(process.env));
27859
28585
  }
28586
+ /** The Gateway-anchored clock that grant expiry and task deadlines are checked against. */
28587
+ #gatewayNow = () => this.#options.gatewayNow?.() ?? (this.#options.now ?? Date.now)();
27860
28588
  get identity() {
27861
28589
  const { tenant_id, user_id, device_uuid } = this.#options.identity;
27862
28590
  return { tenant_id, user_id, device_uuid };
@@ -27918,7 +28646,7 @@ var Dispatcher = class {
27918
28646
  const taskId2 = dispatch2.task_id;
27919
28647
  if (taskId2 === null)
27920
28648
  return;
27921
- const now = this.#options.now ?? Date.now;
28649
+ const now = this.#gatewayNow;
27922
28650
  const journal = this.#options.journal;
27923
28651
  const denial = await verifyGrantAuthenticity(dispatch2, this.#options.identity);
27924
28652
  if (denial) {
@@ -27990,29 +28718,32 @@ var Dispatcher = class {
27990
28718
  }
27991
28719
  const actingUser = actingUserId(dispatch2);
27992
28720
  const meta3 = { capability: authorized.capability, nonce: dispatch2.grant.nonce, expires_at_ms: grantExpiryMs(dispatch2), acting_user_id: actingUser };
27993
- const state2 = { phase: "pending", cancelled: false, meta: meta3 };
28721
+ const state2 = { phase: "pending", cancelled: false, stopRequested: false, meta: meta3 };
27994
28722
  this.#inFlight.set(taskId2, state2);
27995
28723
  try {
27996
- const executionNonce = (0, import_node_crypto8.randomUUID)();
28724
+ const executionNonce = (0, import_node_crypto9.randomUUID)();
27997
28725
  this.#sendAck(dispatch2, "RECEIVED", executionNonce);
27998
28726
  let fileTask = isSshTask(authorized) || isShellTask(authorized) || isAgentTask(authorized) || isDiagTask(authorized) ? null : authorized;
27999
28727
  let fs = fileTask ? new RootedFs(fileTask.root, effectiveDenyGlobs(config2), { protectedPaths: this.#protectedPaths }) : null;
28000
- if (fileTask && fileTask.capability === "files.write" && config2.confirm_writes) {
28001
- const payload = fileTask.payload;
28728
+ if (fileTask && config2.confirm_writes && CHANGING_FILE_CAPABILITIES.has(fileTask.capability)) {
28729
+ let request;
28730
+ try {
28731
+ request = confirmationFor(fileTask);
28732
+ } catch (error63) {
28733
+ const refused = fileErrorResult(error63 instanceof FileOpError ? error63 : new FileOpError("PATH_INVALID", "Path is invalid"));
28734
+ await journal.done(taskId2, meta3, refused).catch(() => void 0);
28735
+ this.#sendResult(dispatch2, refused);
28736
+ return;
28737
+ }
28002
28738
  const confirm = this.#options.confirmWrite;
28003
- const confirmed = confirm ? await confirm({
28004
- rootLabel: fileTask.root.label,
28005
- path: payload.path,
28006
- bytes: Buffer.byteLength(payload.content, "utf8"),
28007
- created: payload.expected_sha256 === null
28008
- }).catch(() => false) : false;
28739
+ const confirmed = confirm ? await confirm(request).catch(() => false) : false;
28009
28740
  if (state2.cancelled)
28010
28741
  return;
28011
28742
  if (!confirmed) {
28012
28743
  const cancelled = {
28013
28744
  state: "CANCELLED",
28014
28745
  executed: false,
28015
- safe_message: "Write was declined on the device",
28746
+ safe_message: "Change was declined on the device",
28016
28747
  output_excerpt: excerpt({ error: "POLICY_DENIED", reason: "LOCAL_CONFIRM_DECLINED" })
28017
28748
  };
28018
28749
  await journal.done(taskId2, meta3, cancelled).catch(() => void 0);
@@ -28023,7 +28754,7 @@ var Dispatcher = class {
28023
28754
  if (state2.cancelled)
28024
28755
  return;
28025
28756
  if ("refused" in fresh) {
28026
- this.#logger.warn("write refused after local confirmation", { task_id: taskId2, reason: fresh.reason });
28757
+ this.#logger.warn("file change refused after local confirmation", { task_id: taskId2, reason: fresh.reason });
28027
28758
  await journal.done(taskId2, meta3, fresh.refused).catch(() => void 0);
28028
28759
  this.#sendResult(dispatch2, fresh.refused);
28029
28760
  return;
@@ -28047,6 +28778,7 @@ var Dispatcher = class {
28047
28778
  }
28048
28779
  this.#sendAck(dispatch2, "STARTED", executionNonce);
28049
28780
  const taskContext = { taskId: taskId2, contextId: dispatch2.context_id, actingUserId: actingUser };
28781
+ const shellContext = { ...taskContext, cancelled: () => state2.stopRequested };
28050
28782
  if (isAgentTask(authorized)) {
28051
28783
  let deadline = authorized.payload.run_at_ms;
28052
28784
  this.#scheduledRemovals.set(taskId2, meta3);
@@ -28091,7 +28823,7 @@ var Dispatcher = class {
28091
28823
  safe_message: "SSH task failed on the device",
28092
28824
  output_excerpt: excerpt({ error: "INVALID_MESSAGE", reason: "SSH_ERROR" })
28093
28825
  }
28094
- })) : isShellTask(authorized) ? await shellExecutor.run(authorized, taskContext).catch(() => ({
28826
+ })) : isShellTask(authorized) ? await shellExecutor.run(authorized, shellContext).catch(() => ({
28095
28827
  // Unexpected failure after STARTED: whether the action happened is not known, so never claim it did not.
28096
28828
  result: {
28097
28829
  state: "FAILED",
@@ -28144,7 +28876,9 @@ var Dispatcher = class {
28144
28876
  /**
28145
28877
  * Handle a CANCEL for a task. Before journal STARTED: journal DONE
28146
28878
  * CANCELLED and answer RESULT CANCELLED, also for a task whose DISPATCH has
28147
- * not arrived yet. After STARTED: ignored (the action cannot be undone).
28879
+ * not arrived yet. After STARTED: a command the task still runs is stopped
28880
+ * (no RESULT here; the task reports it); anything else is ignored (the action
28881
+ * cannot be undone).
28148
28882
  */
28149
28883
  async cancel(cancel2) {
28150
28884
  const taskId2 = cancel2.task_id;
@@ -28153,7 +28887,6 @@ var Dispatcher = class {
28153
28887
  return;
28154
28888
  }
28155
28889
  const journal = this.#options.journal;
28156
- const state2 = this.#inFlight.get(taskId2);
28157
28890
  const scheduledMeta = this.#scheduledRemovals.get(taskId2);
28158
28891
  if (this.#options.cancelRemoval) {
28159
28892
  const cancelled = await this.#options.cancelRemoval(taskId2);
@@ -28161,13 +28894,30 @@ var Dispatcher = class {
28161
28894
  return;
28162
28895
  if (cancelled === true || scheduledMeta) {
28163
28896
  this.#scheduledRemovals.delete(taskId2);
28164
- if (state2)
28165
- state2.cancelled = true;
28897
+ const removal = this.#inFlight.get(taskId2);
28898
+ if (removal)
28899
+ removal.cancelled = true;
28166
28900
  const record4 = journal.get(taskId2);
28167
28901
  await this.#tombstone(taskId2, scheduledMeta ?? { capability: "agent.remove", nonce: record4?.nonce ?? void 0 }, cancel2);
28168
28902
  return;
28169
28903
  }
28170
28904
  }
28905
+ const stopRunning = this.#options.stopRunning;
28906
+ if (stopRunning) {
28907
+ const starting = this.#inFlight.get(taskId2);
28908
+ const flagged = starting?.phase === "starting" && starting.meta.capability === "shell.exec";
28909
+ if (flagged)
28910
+ starting.stopRequested = true;
28911
+ if (await stopRunning(taskId2).catch(() => false)) {
28912
+ this.#logger.info("running command stopped on cancel", { task_id: taskId2, reason: cancel2.reason });
28913
+ return;
28914
+ }
28915
+ if (flagged) {
28916
+ this.#logger.info("cancel while the command was starting or finishing; it does not start", { task_id: taskId2, reason: cancel2.reason });
28917
+ return;
28918
+ }
28919
+ }
28920
+ const state2 = this.#inFlight.get(taskId2);
28171
28921
  if (state2) {
28172
28922
  if (state2.phase === "starting") {
28173
28923
  this.#logger.warn("cancel ignored: task already started and cannot be undone", { task_id: taskId2, reason: cancel2.reason });
@@ -28282,7 +29032,7 @@ var Dispatcher = class {
28282
29032
  };
28283
29033
 
28284
29034
  // dist/monitor.js
28285
- var import_promises12 = require("node:fs/promises");
29035
+ var import_promises13 = require("node:fs/promises");
28286
29036
  var import_node_os5 = require("node:os");
28287
29037
  var defaultMonitorSystem = {
28288
29038
  platform: process.platform,
@@ -28291,7 +29041,7 @@ var defaultMonitorSystem = {
28291
29041
  totalmem: import_node_os5.totalmem,
28292
29042
  freemem: import_node_os5.freemem,
28293
29043
  uptime: import_node_os5.uptime,
28294
- statfs: (path) => (0, import_promises12.statfs)(path),
29044
+ statfs: (path) => (0, import_promises13.statfs)(path),
28295
29045
  env: process.env
28296
29046
  };
28297
29047
  var MONITOR_FIRST_SAMPLE_MS = 1e3;
@@ -28426,11 +29176,11 @@ var import_node_os9 = require("node:os");
28426
29176
  var import_node_zlib2 = require("node:zlib");
28427
29177
 
28428
29178
  // dist/inventory/image-packages.js
28429
- var import_promises15 = require("node:fs/promises");
28430
- var import_node_path16 = require("node:path");
29179
+ var import_promises16 = require("node:fs/promises");
29180
+ var import_node_path17 = require("node:path");
28431
29181
 
28432
29182
  // dist/inventory/collection.js
28433
- var import_promises14 = require("node:fs/promises");
29183
+ var import_promises15 = require("node:fs/promises");
28434
29184
  var import_node_os8 = require("node:os");
28435
29185
 
28436
29186
  // dist/inventory/tls.js
@@ -28682,9 +29432,9 @@ var PS_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $Prog
28682
29432
 
28683
29433
  // dist/inventory/software.js
28684
29434
  var import_node_fs4 = require("node:fs");
28685
- var import_promises13 = require("node:fs/promises");
29435
+ var import_promises14 = require("node:fs/promises");
28686
29436
  var import_node_os7 = require("node:os");
28687
- var import_node_path15 = require("node:path");
29437
+ var import_node_path16 = require("node:path");
28688
29438
 
28689
29439
  // dist/inventory/parsers/system.js
28690
29440
  var RELEASE_KEYS = {
@@ -28876,8 +29626,8 @@ async function findExecutablesOnPath(name3, path = collectorEnv().PATH ?? "") {
28876
29626
  const found = [];
28877
29627
  for (const dir of path.split(":").filter((entry) => entry.startsWith("/"))) {
28878
29628
  try {
28879
- const real = await (0, import_promises13.realpath)(`${dir}/${name3}`);
28880
- await (0, import_promises13.access)(real, import_node_fs4.constants.X_OK);
29629
+ const real = await (0, import_promises14.realpath)(`${dir}/${name3}`);
29630
+ await (0, import_promises14.access)(real, import_node_fs4.constants.X_OK);
28881
29631
  if (!found.includes(real))
28882
29632
  found.push(real);
28883
29633
  } catch {
@@ -28965,7 +29715,7 @@ function xcodeTools(c) {
28965
29715
  }
28966
29716
  async function stampOf(real) {
28967
29717
  try {
28968
- const info = await (0, import_promises13.stat)(real);
29718
+ const info = await (0, import_promises14.stat)(real);
28969
29719
  return `${real}\0${info.mtimeMs}\0${info.size}`;
28970
29720
  } catch {
28971
29721
  return null;
@@ -29023,7 +29773,7 @@ async function readSmall(c, path) {
29023
29773
  return text6 === null ? "missing" : Buffer.byteLength(text6, "utf8") > PACKAGE_JSON_BYTES ? "large" : text6;
29024
29774
  }
29025
29775
  async function packageJsonVersion(c, key, real, names2) {
29026
- let dir = (0, import_node_path15.dirname)(real);
29776
+ let dir = (0, import_node_path16.dirname)(real);
29027
29777
  for (let level = 0; level < PACKAGE_JSON_LEVELS; level += 1) {
29028
29778
  const text6 = await readSmall(c, `${dir}/package.json`);
29029
29779
  if (text6 === "large")
@@ -29036,7 +29786,7 @@ async function packageJsonVersion(c, key, real, names2) {
29036
29786
  return null;
29037
29787
  }
29038
29788
  }
29039
- const parent = (0, import_node_path15.dirname)(dir);
29789
+ const parent = (0, import_node_path16.dirname)(dir);
29040
29790
  if (parent === dir)
29041
29791
  break;
29042
29792
  dir = parent;
@@ -29217,11 +29967,11 @@ var Collection = class {
29217
29967
  }
29218
29968
  }
29219
29969
  };
29220
- var defaultReader = async (path) => (0, import_promises14.readFile)(path, "utf8").catch(() => null);
29970
+ var defaultReader = async (path) => (0, import_promises15.readFile)(path, "utf8").catch(() => null);
29221
29971
  async function readFileTail(path, bytes3) {
29222
29972
  let handle = null;
29223
29973
  try {
29224
- handle = await (0, import_promises14.open)(path, "r");
29974
+ handle = await (0, import_promises15.open)(path, "r");
29225
29975
  const { size } = await handle.stat();
29226
29976
  const length = Math.min(size, bytes3);
29227
29977
  const buffer = Buffer.alloc(length);
@@ -29236,11 +29986,11 @@ async function readFileTail(path, bytes3) {
29236
29986
  }
29237
29987
  async function listDirFiles(path, dirs = false) {
29238
29988
  try {
29239
- const entries2 = await (0, import_promises14.readdir)(path, { withFileTypes: true });
29989
+ const entries2 = await (0, import_promises15.readdir)(path, { withFileTypes: true });
29240
29990
  const files = [];
29241
29991
  for (const entry of entries2.filter((item) => dirs ? item.isDirectory() : item.isFile()).slice(0, 2e3)) {
29242
29992
  try {
29243
- files.push({ name: entry.name, mtimeMs: (await (0, import_promises14.stat)(`${path}/${entry.name}`)).mtimeMs });
29993
+ files.push({ name: entry.name, mtimeMs: (await (0, import_promises15.stat)(`${path}/${entry.name}`)).mtimeMs });
29244
29994
  } catch {
29245
29995
  }
29246
29996
  }
@@ -29252,7 +30002,7 @@ async function listDirFiles(path, dirs = false) {
29252
30002
  async function readFileBytes(path, maxBytes) {
29253
30003
  let handle = null;
29254
30004
  try {
29255
- handle = await (0, import_promises14.open)(path, "r");
30005
+ handle = await (0, import_promises15.open)(path, "r");
29256
30006
  const buffer = Buffer.alloc(Math.max(0, maxBytes));
29257
30007
  let total = 0;
29258
30008
  while (total < buffer.length) {
@@ -29270,14 +30020,14 @@ async function readFileBytes(path, maxBytes) {
29270
30020
  }
29271
30021
  async function listProcPids() {
29272
30022
  try {
29273
- return (await (0, import_promises14.readdir)("/proc")).filter((name3) => /^[1-9]\d*$/.test(name3)).map(Number);
30023
+ return (await (0, import_promises15.readdir)("/proc")).filter((name3) => /^[1-9]\d*$/.test(name3)).map(Number);
29274
30024
  } catch {
29275
30025
  return null;
29276
30026
  }
29277
30027
  }
29278
30028
  async function readExeLink(pid) {
29279
30029
  try {
29280
- return await (0, import_promises14.readlink)(`/proc/${pid}/exe`);
30030
+ return await (0, import_promises15.readlink)(`/proc/${pid}/exe`);
29281
30031
  } catch {
29282
30032
  return null;
29283
30033
  }
@@ -29295,7 +30045,7 @@ var defaultCollectorSystem = {
29295
30045
  isRoot: typeof process.getuid === "function" ? process.getuid() === 0 : false,
29296
30046
  resolveExe: async (pid) => {
29297
30047
  try {
29298
- return await (0, import_promises14.realpath)(`/proc/${pid}/exe`);
30048
+ return await (0, import_promises15.realpath)(`/proc/${pid}/exe`);
29299
30049
  } catch {
29300
30050
  return null;
29301
30051
  }
@@ -29772,11 +30522,11 @@ async function loadImageCache(stateDir) {
29772
30522
  if (!stateDir)
29773
30523
  return empty;
29774
30524
  try {
29775
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
29776
- const info = await (0, import_promises15.lstat)(path);
30525
+ const path = (0, import_node_path17.join)(stateDir, IMAGE_CACHE_FILE);
30526
+ const info = await (0, import_promises16.lstat)(path);
29777
30527
  if (!info.isFile() || info.size > IMAGE_CACHE_MAX_BYTES)
29778
30528
  return empty;
29779
- const file2 = record2(JSON.parse(await (0, import_promises15.readFile)(path, "utf8")));
30529
+ const file2 = record2(JSON.parse(await (0, import_promises16.readFile)(path, "utf8")));
29780
30530
  if (!file2 || file2.version !== 1)
29781
30531
  return empty;
29782
30532
  const out = { version: 1, entries: {} };
@@ -29805,15 +30555,15 @@ async function saveImageCache(stateDir, cache, nowMs) {
29805
30555
  break;
29806
30556
  entries2.pop();
29807
30557
  }
29808
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
30558
+ const path = (0, import_node_path17.join)(stateDir, IMAGE_CACHE_FILE);
29809
30559
  const temp = `${path}.${process.pid}.tmp`;
29810
30560
  try {
29811
- await (0, import_promises15.rm)(temp, { force: true });
29812
- await (0, import_promises15.writeFile)(temp, text6, { mode: 384, flag: "wx" });
29813
- await (0, import_promises15.chmod)(temp, 384);
29814
- await (0, import_promises15.rename)(temp, path);
30561
+ await (0, import_promises16.rm)(temp, { force: true });
30562
+ await (0, import_promises16.writeFile)(temp, text6, { mode: 384, flag: "wx" });
30563
+ await (0, import_promises16.chmod)(temp, 384);
30564
+ await (0, import_promises16.rename)(temp, path);
29815
30565
  } catch {
29816
- await (0, import_promises15.rm)(temp, { force: true }).catch(() => void 0);
30566
+ await (0, import_promises16.rm)(temp, { force: true }).catch(() => void 0);
29817
30567
  }
29818
30568
  }
29819
30569
  function engineSupported(c) {
@@ -30119,190 +30869,6 @@ function legacyImagePackages(items) {
30119
30869
  // dist/ssh/exec.js
30120
30870
  var import_node_child_process9 = require("node:child_process");
30121
30871
  var import_node_path18 = require("node:path");
30122
-
30123
- // dist/ssh/hosts.js
30124
- var import_node_crypto9 = require("node:crypto");
30125
- var import_promises16 = require("node:fs/promises");
30126
- var import_node_path17 = require("node:path");
30127
- var MAX_SSH_HOSTS = 64;
30128
- var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
30129
- var DNS_HOST = /^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
30130
- var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
30131
- var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
30132
- function isValidSshHost(value) {
30133
- return DNS_HOST.test(value) || IPV6_HOST.test(value);
30134
- }
30135
- function isValidIdentityPath(value) {
30136
- return (0, import_node_path17.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
30137
- }
30138
- var PINNABLE_KEY_TYPES = Object.freeze([
30139
- "ssh-ed25519",
30140
- "ecdsa-sha2-nistp256",
30141
- "ecdsa-sha2-nistp384",
30142
- "ecdsa-sha2-nistp521",
30143
- "ssh-rsa"
30144
- ]);
30145
- var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
30146
- var sshHostSchema = external_exports.strictObject({
30147
- resource_id: external_exports.uuid(),
30148
- alias: external_exports.string().regex(SSH_ALIAS),
30149
- host: external_exports.string().refine(isValidSshHost, "Invalid host"),
30150
- port: external_exports.number().int().min(1).max(65535),
30151
- user: external_exports.string().regex(SSH_USER).optional(),
30152
- identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
30153
- production: external_exports.boolean(),
30154
- key_type: external_exports.enum(PINNABLE_KEY_TYPES),
30155
- public_key: external_exports.string().min(16).max(8192).regex(base643),
30156
- fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
30157
- pinned_at: external_exports.iso.datetime({ offset: true })
30158
- });
30159
- var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS) });
30160
- function sshPaths(stateDir) {
30161
- const dir = (0, import_node_path17.join)(stateDir, "ssh");
30162
- return { dir, hosts: (0, import_node_path17.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path17.join)(dir, "known_hosts") };
30163
- }
30164
- function knownHostsPath(paths, resourceId) {
30165
- return (0, import_node_path17.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
30166
- }
30167
- function hostKeyAlias(host) {
30168
- return "conbridge-" + host.resource_id;
30169
- }
30170
- function fingerprintOf(publicKey) {
30171
- return "SHA256:" + (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
30172
- }
30173
- function normalizeFingerprint(value) {
30174
- const trimmed = value.trim();
30175
- return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
30176
- }
30177
- function parseKeyscan(output2) {
30178
- const keys = [];
30179
- for (const line of output2.split("\n")) {
30180
- const trimmed = line.trim();
30181
- if (trimmed === "" || trimmed.startsWith("#"))
30182
- continue;
30183
- const [, type, key] = trimmed.split(/\s+/);
30184
- if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
30185
- continue;
30186
- keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
30187
- }
30188
- return keys;
30189
- }
30190
- function preferredKey(keys) {
30191
- for (const type of PINNABLE_KEY_TYPES) {
30192
- const key = keys.find((candidate) => candidate.key_type === type);
30193
- if (key)
30194
- return key;
30195
- }
30196
- return null;
30197
- }
30198
- async function loadSshHosts(paths) {
30199
- let text6;
30200
- try {
30201
- text6 = await (0, import_promises16.readFile)(paths.hosts, "utf8");
30202
- } catch (error63) {
30203
- if (errorCode2(error63) === "ENOENT")
30204
- return [];
30205
- throw error63;
30206
- }
30207
- return hostsFileSchema.parse(JSON.parse(text6)).hosts;
30208
- }
30209
- async function ensureSshDirs(paths) {
30210
- for (const dir of [paths.dir, paths.knownHostsDir]) {
30211
- await (0, import_promises16.mkdir)(dir, { recursive: true, mode: 448 });
30212
- await (0, import_promises16.chmod)(dir, 448);
30213
- }
30214
- }
30215
- async function saveSshHosts(paths, hosts) {
30216
- await ensureSshDirs(paths);
30217
- await writeFileAtomic(paths.hosts, JSON.stringify(hostsFileSchema.parse({ version: 1, hosts }), null, 2) + "\n", 384);
30218
- }
30219
- async function writeKnownHosts(paths, host) {
30220
- await ensureSshDirs(paths);
30221
- await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
30222
- `, 384);
30223
- }
30224
- async function validateNewHost(input2) {
30225
- if (!SSH_ALIAS.test(input2.alias))
30226
- throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
30227
- if (!isValidSshHost(input2.host))
30228
- throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
30229
- if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
30230
- throw new Error("Port must be 1-65535");
30231
- if (input2.user !== void 0 && !SSH_USER.test(input2.user))
30232
- throw new Error("User must be a plain login name");
30233
- if (input2.identity !== void 0) {
30234
- if (!isValidIdentityPath(input2.identity))
30235
- throw new Error("Identity must be an absolute path without quotes, % or control characters");
30236
- const info = await (0, import_promises16.stat)(input2.identity).catch(() => null);
30237
- if (!info?.isFile())
30238
- throw new Error("Identity file not found");
30239
- }
30240
- }
30241
- async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
30242
- await validateNewHost(input2);
30243
- const hosts = await loadSshHosts(paths);
30244
- if (hosts.some((host2) => host2.alias === input2.alias))
30245
- throw new Error(`An SSH host named ${input2.alias} already exists`);
30246
- if (hosts.length >= MAX_SSH_HOSTS)
30247
- throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
30248
- const host = sshHostSchema.parse({
30249
- resource_id: (0, import_node_crypto9.randomUUID)(),
30250
- alias: input2.alias,
30251
- host: input2.host,
30252
- port: input2.port ?? 22,
30253
- ...input2.user !== void 0 ? { user: input2.user } : {},
30254
- ...input2.identity !== void 0 ? { identity: input2.identity } : {},
30255
- production: input2.production === true,
30256
- key_type: key.key_type,
30257
- public_key: key.public_key,
30258
- fingerprint: key.fingerprint,
30259
- pinned_at: now.toISOString()
30260
- });
30261
- await writeKnownHosts(paths, host);
30262
- await saveSshHosts(paths, [...hosts, host]);
30263
- return host;
30264
- }
30265
- async function findSshHost(paths, alias) {
30266
- return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
30267
- }
30268
- async function updateHost(paths, alias, change) {
30269
- const hosts = await loadSshHosts(paths);
30270
- const index = hosts.findIndex((host) => host.alias === alias);
30271
- if (index < 0)
30272
- throw new Error(`No SSH host named ${alias}`);
30273
- const updated = sshHostSchema.parse(change(hosts[index]));
30274
- const next = [...hosts];
30275
- next[index] = updated;
30276
- if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
30277
- await writeKnownHosts(paths, updated);
30278
- await saveSshHosts(paths, next);
30279
- return updated;
30280
- }
30281
- async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
30282
- return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
30283
- }
30284
- async function setSshHostProduction(paths, alias, production) {
30285
- return await updateHost(paths, alias, (host) => ({ ...host, production }));
30286
- }
30287
- async function removeSshHost(paths, alias) {
30288
- const hosts = await loadSshHosts(paths);
30289
- const host = hosts.find((entry) => entry.alias === alias);
30290
- if (!host)
30291
- return false;
30292
- await saveSshHosts(paths, hosts.filter((entry) => entry !== host));
30293
- await (0, import_promises16.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
30294
- return true;
30295
- }
30296
- function hostAddress(host) {
30297
- if (host.port === 22)
30298
- return host.host;
30299
- return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
30300
- }
30301
- function inventoryResource2(host) {
30302
- return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
30303
- }
30304
-
30305
- // dist/ssh/exec.js
30306
30872
  var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
30307
30873
  function sshBinariesFromEnv(env = process.env) {
30308
30874
  const pick2 = (value, fallback) => value && (0, import_node_path18.isAbsolute)(value) ? value : fallback;
@@ -31665,7 +32231,7 @@ function socketOwnerOf(listener, exeByPid, packageByPath, options) {
31665
32231
  }
31666
32232
  return { kind: "process", name: "systemd" };
31667
32233
  }
31668
- function ownerOf(listener, exeByPid, packageByPath, containerByPort, options) {
32234
+ function ownerOf2(listener, exeByPid, packageByPath, containerByPort, options) {
31669
32235
  const name3 = processNameOf(listener.process);
31670
32236
  if (name3 !== null && CONTAINER_PLUMBING.has(name3)) {
31671
32237
  const containerId = containerByPort.get(listener.port);
@@ -31709,7 +32275,7 @@ function resolveListenerOwners(listeners, exeByPid, packageByPath, containers, o
31709
32275
  const out = [];
31710
32276
  const byKey = /* @__PURE__ */ new Map();
31711
32277
  for (const listener of listeners) {
31712
- const owner = ownerOf(listener, exeByPid, packageByPath, containerByPort, options);
32278
+ const owner = ownerOf2(listener, exeByPid, packageByPath, containerByPort, options);
31713
32279
  const stale = options?.markStale === true && listener.pids.some((pid) => options.stalePids?.has(pid) === true);
31714
32280
  const item = { proto: listener.proto, port: listener.port, bind: listener.bind, owner, ...stale ? { stale: true } : {} };
31715
32281
  const key = `${item.proto}\0${item.port}\0${item.bind}\0${JSON.stringify(item.owner)}`;
@@ -34526,9 +35092,81 @@ function unitFileEnablement(unitFiles) {
34526
35092
  return enablement;
34527
35093
  }
34528
35094
  var PER_CONNECTION_INSTANCE = /^[^@\s]+@\d+-[^-\s]+:\d+-\S+:\d+$/;
35095
+ var STATE_RANK = {
35096
+ failed: 0,
35097
+ unknown: 1,
35098
+ stopping: 2,
35099
+ starting: 3,
35100
+ stopped: 4,
35101
+ running: 5
35102
+ };
35103
+ var WORD_CHAR = /[A-Za-z0-9]/;
35104
+ function asciiLower(value) {
35105
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
35106
+ }
35107
+ function unescapeInstance(instance) {
35108
+ return instance.replace(/\\x([0-9A-Fa-f]{2})/g, (_match, hex3) => String.fromCharCode(Number.parseInt(hex3, 16)));
35109
+ }
35110
+ function maskForm(description, form) {
35111
+ if (form.length === 0 || form.length > description.length)
35112
+ return description;
35113
+ const haystack = asciiLower(description);
35114
+ const needle = asciiLower(form);
35115
+ const guardLead = WORD_CHAR.test(form[0] ?? "");
35116
+ const guardTail = WORD_CHAR.test(form[form.length - 1] ?? "");
35117
+ let result2 = "";
35118
+ let from = 0;
35119
+ let at = haystack.indexOf(needle);
35120
+ while (at >= 0) {
35121
+ const end = at + needle.length;
35122
+ const leadOk = !guardLead || at === 0 || !WORD_CHAR.test(description[at - 1] ?? "");
35123
+ const tailOk = !guardTail || end === description.length || !WORD_CHAR.test(description[end] ?? "");
35124
+ if (leadOk && tailOk) {
35125
+ result2 += `${description.slice(from, at)}<instance>`;
35126
+ from = end;
35127
+ at = haystack.indexOf(needle, end);
35128
+ } else {
35129
+ at = haystack.indexOf(needle, at + 1);
35130
+ }
35131
+ }
35132
+ return result2 + description.slice(from);
35133
+ }
35134
+ function maskInstance(description, instance) {
35135
+ const unescaped = unescapeInstance(instance);
35136
+ const forms = /* @__PURE__ */ new Set([instance, unescaped, `/${unescapeInstance(instance.replace(/-/g, "/"))}`, unescaped.replace(/-/g, "/")]);
35137
+ let result2 = description;
35138
+ for (const form of [...forms].sort((a, b) => b.length - a.length))
35139
+ result2 = maskForm(result2, form);
35140
+ return result2;
35141
+ }
35142
+ function enabledTemplates(enablement) {
35143
+ const templates = /* @__PURE__ */ new Set();
35144
+ for (const [unit2, enabled] of enablement) {
35145
+ const at = unit2.indexOf("@");
35146
+ if (enabled === true && at > 0 && at < unit2.length - 1)
35147
+ templates.add(unit2.slice(0, at + 1));
35148
+ }
35149
+ return templates;
35150
+ }
35151
+ function instanceEnablement(enablement, withEnabledInstance, template, instanceUnits) {
35152
+ if (withEnabledInstance.has(template))
35153
+ return true;
35154
+ const fallback = enablement.get(template) ?? null;
35155
+ let allDisabled = instanceUnits.length > 0;
35156
+ for (const unit2 of instanceUnits) {
35157
+ const enabled = enablement.has(unit2) ? enablement.get(unit2) ?? null : fallback;
35158
+ if (enabled === true)
35159
+ return true;
35160
+ if (enabled !== false)
35161
+ allDisabled = false;
35162
+ }
35163
+ return allDisabled ? false : null;
35164
+ }
34529
35165
  function parseSystemd(units, unitFiles) {
34530
35166
  const enablement = unitFileEnablement(unitFiles);
34531
- const result2 = [];
35167
+ const byName = /* @__PURE__ */ new Map();
35168
+ const mixed = /* @__PURE__ */ new Set();
35169
+ const instances = /* @__PURE__ */ new Map();
34532
35170
  for (const rawLine of lines2(units)) {
34533
35171
  const line = rawLine.trim().replace(/^[●*]\s+/, "");
34534
35172
  const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
@@ -34542,23 +35180,46 @@ function parseSystemd(units, unitFiles) {
34542
35180
  continue;
34543
35181
  if (load === "not-found")
34544
35182
  continue;
34545
- if (PER_CONNECTION_INSTANCE.test(unitName(unitToken)))
35183
+ const unit2 = unitName(unitToken);
35184
+ if (PER_CONNECTION_INSTANCE.test(unit2))
34546
35185
  continue;
34547
- const name3 = text3(unitName(unitToken), NAME_MAX4);
34548
- if (!name3)
35186
+ const at = unit2.indexOf("@");
35187
+ const instance = at >= 0 ? unit2.slice(at + 1) : "";
35188
+ const name3 = text3(at >= 0 ? unit2.slice(0, at + 1) : unit2, NAME_MAX4);
35189
+ if (!name3 || name3 === "@")
34549
35190
  continue;
34550
- const item = {
34551
- name: name3,
34552
- manager: "systemd",
34553
- state: systemdState(active.toLowerCase(), sub.toLowerCase()),
34554
- enabled: enablement.get(name3) ?? null
34555
- };
34556
- const description = text3(match[5] ?? "", DESCRIPTION_MAX);
35191
+ const rawDescription = match[5] ?? "";
35192
+ const description = text3(instance ? maskInstance(rawDescription, instance) : rawDescription, DESCRIPTION_MAX);
35193
+ const state2 = systemdState(active.toLowerCase(), sub.toLowerCase());
35194
+ if (instance) {
35195
+ const list = instances.get(name3);
35196
+ if (list)
35197
+ list.push(unit2);
35198
+ else
35199
+ instances.set(name3, [unit2]);
35200
+ }
35201
+ const seen = byName.get(name3);
35202
+ if (seen) {
35203
+ if (STATE_RANK[state2] < STATE_RANK[seen.state])
35204
+ seen.state = state2;
35205
+ if ((seen.description ?? "") !== description)
35206
+ mixed.add(name3);
35207
+ continue;
35208
+ }
35209
+ const item = { name: name3, manager: "systemd", state: state2, enabled: enablement.get(name3) ?? null };
34557
35210
  if (description)
34558
35211
  item.description = description;
34559
- result2.push(item);
35212
+ byName.set(name3, item);
34560
35213
  }
34561
- return sorted2(result2);
35214
+ for (const name3 of mixed)
35215
+ delete byName.get(name3)?.description;
35216
+ const withEnabledInstance = enabledTemplates(enablement);
35217
+ for (const [name3, units2] of instances) {
35218
+ const item = byName.get(name3);
35219
+ if (item)
35220
+ item.enabled = instanceEnablement(enablement, withEnabledInstance, name3, units2);
35221
+ }
35222
+ return sorted2([...byName.values()]);
34562
35223
  }
34563
35224
  function parseLaunchctl(stdout) {
34564
35225
  const result2 = [];
@@ -36233,6 +36894,7 @@ async function collectInventory(system = defaultCollectorSystem, options = LEGAC
36233
36894
  }
36234
36895
 
36235
36896
  // dist/relay.js
36897
+ var defaultMonotonicNow = () => performance.now();
36236
36898
  var HEARTBEAT_INTERVAL_MS = 2e4;
36237
36899
  var PING_INTERVAL_MS = 25e3;
36238
36900
  var PING_JITTER_MS = 5e3;
@@ -36246,6 +36908,10 @@ var RECONNECT_JITTER_MIN_MS = 1e3;
36246
36908
  var RECONNECT_JITTER_SPAN_MS = 29e3;
36247
36909
  var SERVER_DROP_CODES = /* @__PURE__ */ new Set([1001, 1006, 1011, 1012, 4e3]);
36248
36910
  var AUTH_TIMEOUT_MS = 2e4;
36911
+ var CHALLENGE_TTL_MS = 15e3;
36912
+ var CLOCK_SKEW_WARN_MS = 3e4;
36913
+ var REPLACED_CLOSE_REASON = "replaced";
36914
+ var REPLACED_BACKOFF_MAX_MS = 3e5;
36249
36915
  var CLOSE_POLICY_VIOLATION = 4008;
36250
36916
  function relayUrl(gatewayUrl, deviceUuid2) {
36251
36917
  const url2 = new URL("/v1/agent/connect", gatewayUrl);
@@ -36267,6 +36933,10 @@ var RelaySession = class {
36267
36933
  #gatewayFeatures = /* @__PURE__ */ new Set();
36268
36934
  /** Relay features both sides speak: the ones this agent listed in AUTH that AUTH_OK echoed. */
36269
36935
  #relayFeatures = /* @__PURE__ */ new Set();
36936
+ /** Gateway clock minus local clock, measured from this connection's CHALLENGE; 0 until one arrived. For logs only. */
36937
+ #clockOffsetMs = 0;
36938
+ /** Gateway time at this connection's CHALLENGE and the monotonic time it was read at; null until one arrived. */
36939
+ #gatewayAnchor = null;
36270
36940
  constructor(options) {
36271
36941
  this.#options = options;
36272
36942
  this.#logger = options.logger ?? silentLogger;
@@ -36274,6 +36944,26 @@ var RelaySession = class {
36274
36944
  get state() {
36275
36945
  return this.#state;
36276
36946
  }
36947
+ /**
36948
+ * Gateway clock minus local clock in ms, derived from this connection's CHALLENGE (`expires_at_ms - CHALLENGE_TTL_MS
36949
+ * - localNow`). It is lower than the true offset by the CHALLENGE's one-way network delay, so grant deadlines
36950
+ * evaluated with it are at most that delay late; no tolerance is added on top.
36951
+ */
36952
+ get clockOffsetMs() {
36953
+ return this.#clockOffsetMs;
36954
+ }
36955
+ /**
36956
+ * The Gateway clock for grant expiry and task deadlines, or null before a CHALLENGE arrived: the CHALLENGE's Gateway
36957
+ * time (`expires_at_ms - CHALLENGE_TTL_MS`) plus the monotonic time elapsed since. It never reads the wall clock, so
36958
+ * a device clock corrected after the CHALLENGE cannot shift it. Like clockOffsetMs it runs behind the true Gateway
36959
+ * clock by the CHALLENGE's one-way network delay; no tolerance is added on top.
36960
+ */
36961
+ gatewayNow = () => {
36962
+ const anchor2 = this.#gatewayAnchor;
36963
+ if (!anchor2)
36964
+ return null;
36965
+ return anchor2.gatewayMs + ((this.#options.monotonicNow ?? defaultMonotonicNow)() - anchor2.monotonicMs);
36966
+ };
36277
36967
  /** True once AUTH_OK echoed `ping.v1` for a session that listed it. */
36278
36968
  get pingEnabled() {
36279
36969
  return this.#state === "ready" && this.#relayFeatures.has("ping.v1");
@@ -36369,9 +37059,13 @@ var RelaySession = class {
36369
37059
  const parsed = relayChallengeSchema.safeParse(frame);
36370
37060
  if (!parsed.success)
36371
37061
  return this.#fail("expected CHALLENGE");
36372
- const now = (this.#options.now ?? Date.now)();
36373
- if (parsed.data.expires_at_ms <= now)
36374
- return this.#fail("challenge expired");
37062
+ const localNow = (this.#options.now ?? Date.now)();
37063
+ const gatewayMs = parsed.data.expires_at_ms - CHALLENGE_TTL_MS;
37064
+ this.#gatewayAnchor = { gatewayMs, monotonicMs: (this.#options.monotonicNow ?? defaultMonotonicNow)() };
37065
+ this.#clockOffsetMs = gatewayMs - localNow;
37066
+ if (Math.abs(this.#clockOffsetMs) > CLOCK_SKEW_WARN_MS) {
37067
+ this.#logger.warn("the device clock differs from the Gateway clock; task deadlines use the Gateway clock", { clock_offset_ms: this.#clockOffsetMs });
37068
+ }
36375
37069
  const deviceUuid2 = this.#options.identity.device_uuid;
36376
37070
  const signature = await signRelayChallenge(this.#options.key, deviceUuid2, parsed.data.nonce, parsed.data.connection_id);
36377
37071
  this.#state = "auth_sent";
@@ -36474,6 +37168,10 @@ var DEFAULT_BACKOFF = { baseMs: 1e3, maxMs: 6e4 };
36474
37168
  function reconnectDelay(connectionMs, closeCode, random = Math.random, context = {}) {
36475
37169
  if (context.requested === true)
36476
37170
  return 0;
37171
+ if (context.replaced === true) {
37172
+ const backoff = context.backoff ?? DEFAULT_BACKOFF;
37173
+ return backoffDelay(context.attempt ?? 0, { ...backoff, maxMs: Math.max(backoff.maxMs, REPLACED_BACKOFF_MAX_MS), random: backoff.random ?? random });
37174
+ }
36477
37175
  if (connectionMs >= LONG_CONNECTION_MS && SERVER_DROP_CODES.has(closeCode))
36478
37176
  return Math.floor(RECONNECT_JITTER_MIN_MS + random() * RECONNECT_JITTER_SPAN_MS);
36479
37177
  return backoffDelay(context.attempt ?? 0, { ...context.backoff ?? DEFAULT_BACKOFF, random: context.backoff?.random ?? random });
@@ -37310,7 +38008,7 @@ function sshDiagPlan(spec2, values) {
37310
38008
  root: DIAG_ROOT_REQUIRED[spec2.id],
37311
38009
  steps: Object.freeze(steps)
37312
38010
  });
37313
- const quoted = values.map(q).join(" ");
38011
+ const quoted2 = values.map(q).join(" ");
37314
38012
  switch (spec2.id) {
37315
38013
  case "os.release":
37316
38014
  return plan([step("os_release", "read", "cat /etc/os-release 2>&1", { merged: true })]);
@@ -37337,15 +38035,15 @@ function sshDiagPlan(spec2, values) {
37337
38035
  case "sshd.effective":
37338
38036
  return plan([step("sshd", "exec", "sshd -T 2>&1 || /usr/sbin/sshd -T 2>&1", { merged: true })]);
37339
38037
  case "dpkg.installed":
37340
- return plan([step("dpkg_query", "exec", `dpkg-query -W -f ${q(DPKG_QUERY_FORMAT)} -- ${quoted} 2>&1`, { merged: true, tabSplit: true })]);
38038
+ return plan([step("dpkg_query", "exec", `dpkg-query -W -f ${q(DPKG_QUERY_FORMAT)} -- ${quoted2} 2>&1`, { merged: true, tabSplit: true })]);
37341
38039
  case "apt.candidate":
37342
- return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted}`)]);
38040
+ return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted2}`)]);
37343
38041
  case "rpm.installed":
37344
- return plan([step("rpm", "exec", `rpm -q --qf ${q(RPM_QUERY_FORMAT)} -- ${quoted}`)]);
38042
+ return plan([step("rpm", "exec", `rpm -q --qf ${q(RPM_QUERY_FORMAT)} -- ${quoted2}`)]);
37345
38043
  case "listeners.public":
37346
38044
  return plan([step("ss", "exec", "ss -H -tuln")]);
37347
38045
  case "service.state":
37348
- return plan([step("systemctl", "exec", `systemctl show --property=LoadState,ActiveState,SubState,UnitFileState -- ${quoted}`)]);
38046
+ return plan([step("systemctl", "exec", `systemctl show --property=LoadState,ActiveState,SubState,UnitFileState -- ${quoted2}`)]);
37349
38047
  case "reboot.required":
37350
38048
  return plan([
37351
38049
  step("dpkg_status", "probe", "test -e /var/lib/dpkg/status"),
@@ -38043,6 +38741,7 @@ var ShellExecutor = class {
38043
38741
  background: session.background,
38044
38742
  running: session.endedAtMs === null,
38045
38743
  exit_code: session.exitCode,
38744
+ stopped: session.stoppedBy !== null,
38046
38745
  started_at: new Date(session.startedAtMs).toISOString(),
38047
38746
  duration_ms: (session.endedAtMs ?? this.#now()) - session.startedAtMs,
38048
38747
  output_bytes: session.output.total
@@ -38107,6 +38806,17 @@ var ShellExecutor = class {
38107
38806
  return failure3("INVALID_MESSAGE", "SHELL_UNAVAILABLE", error63 instanceof Error ? error63.message : "Shell is not available");
38108
38807
  }
38109
38808
  const windows = (this.#options.platform ?? process.platform) === "win32";
38809
+ if (context.cancelled?.() === true) {
38810
+ this.#logger.info("command cancelled before it started", { task_id: context.taskId });
38811
+ return {
38812
+ result: {
38813
+ state: "CANCELLED",
38814
+ executed: false,
38815
+ safe_message: "The command was cancelled before it started",
38816
+ output_excerpt: excerpt({ error: "POLICY_DENIED", reason: "CANCELLED_BEFORE_START" })
38817
+ }
38818
+ };
38819
+ }
38110
38820
  let child;
38111
38821
  try {
38112
38822
  child = (0, import_node_child_process11.spawn)(launch.file, [...launch.args], {
@@ -38183,8 +38893,24 @@ var ShellExecutor = class {
38183
38893
  if (session.stoppedBy === "timeout") {
38184
38894
  return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: `Command timed out after ${payload.timeout_s} s and was stopped` } };
38185
38895
  }
38896
+ if (session.stoppedBy === "cancelled") {
38897
+ return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: "The command was cancelled and stopped" } };
38898
+ }
38186
38899
  return outcome;
38187
38900
  }
38901
+ /**
38902
+ * Stop the running command of task `taskId` and everything it started (its process group), for a Gateway CANCEL of
38903
+ * that task. No ownership check: the CANCEL names the task, came over the authenticated relay session, and stopping
38904
+ * only ever takes access away. False when no command of that task runs (unknown, never a command, or already ended).
38905
+ */
38906
+ async stopTask(taskId2) {
38907
+ const session = this.#sessions.get(taskId2);
38908
+ if (!session || session.endedAtMs !== null || !session.child)
38909
+ return false;
38910
+ if (session.stoppedBy === null)
38911
+ await this.#stop(session, "cancelled");
38912
+ return true;
38913
+ }
38188
38914
  /** Session `taskId` if it belongs to this context and acting user. */
38189
38915
  #owned(taskId2, context) {
38190
38916
  const session = this.#sessions.get(taskId2);
@@ -38498,6 +39224,11 @@ var AgentRunner = class {
38498
39224
  #stopped = false;
38499
39225
  #sleep = null;
38500
39226
  #attempt = 0;
39227
+ /**
39228
+ * Gateway clock of the latest authenticated connection (RelaySession.gatewayNow, monotonic from its CHALLENGE); grant
39229
+ * deadlines use it. It stays valid across reconnects until the next connection authenticates.
39230
+ */
39231
+ #gatewayNow = null;
38501
39232
  /** Set by reconnectNow: the next connection attempt starts without a backoff wait. */
38502
39233
  #immediate = false;
38503
39234
  /** #immediate counts only for a connection that ends before this time (reconnectNow + 5 s). */
@@ -38540,9 +39271,13 @@ var AgentRunner = class {
38540
39271
  return true;
38541
39272
  },
38542
39273
  shell: this.#shell,
39274
+ // A Gateway CANCEL stops the command its task still runs: the owner stopped it, or its context was revoked or
39275
+ // ended while it ran (owner decision D11).
39276
+ stopRunning: (taskId2) => this.#shell.stopTask(taskId2),
38543
39277
  diag: new DiagExecutor({ logger: this.#logger }),
38544
39278
  identity: options.identity,
38545
39279
  config: () => this.#currentConfig(),
39280
+ gatewayNow: () => this.#gatewayNow?.() ?? null,
38546
39281
  loadConfig: async () => {
38547
39282
  if (await this.#reloadConfig())
38548
39283
  this.#session?.sendInventory();
@@ -38578,10 +39313,24 @@ var AgentRunner = class {
38578
39313
  });
38579
39314
  const hostKey = (list) => JSON.stringify(list.map(inventoryResource2));
38580
39315
  const changed = this.#config !== null && (!sameRoots(this.#config, config2) || hostKey(this.#sshHosts) !== hostKey(hosts) || this.#config.full_access === true !== (config2.full_access === true) || inventoryAllowed(this.#config) !== inventoryAllowed(config2));
39316
+ const fullAccessOff = this.#config?.full_access === true && config2.full_access !== true;
38581
39317
  this.#config = config2;
38582
39318
  this.#sshHosts = hosts;
39319
+ if (fullAccessOff)
39320
+ await this.#stopTerminalCommands();
38583
39321
  return changed;
38584
39322
  }
39323
+ async #stopTerminalCommands() {
39324
+ const running = this.#shell.runningCount;
39325
+ if (running === 0)
39326
+ return;
39327
+ this.#logger.info("full access turned off; stopping commands started by AI apps", { running });
39328
+ try {
39329
+ await this.#shell.shutdown();
39330
+ } catch (error63) {
39331
+ this.#logger.warn("stopping commands after full access was turned off failed", { error: errorMessage(error63) });
39332
+ }
39333
+ }
38585
39334
  async #compactJournal() {
38586
39335
  try {
38587
39336
  const stats = await this.#options.journal.compact();
@@ -38668,7 +39417,7 @@ var AgentRunner = class {
38668
39417
  }
38669
39418
  async #loop() {
38670
39419
  while (!this.#stopped) {
38671
- let outcome = { authenticated: false, connectionMs: 0, code: 1006 };
39420
+ let outcome = { authenticated: false, connectionMs: 0, code: 1006, replaced: false };
38672
39421
  this.#immediate = false;
38673
39422
  try {
38674
39423
  outcome = await this.#connectOnce();
@@ -38677,14 +39426,21 @@ var AgentRunner = class {
38677
39426
  }
38678
39427
  if (this.#stopped)
38679
39428
  break;
38680
- if (outcome.authenticated)
39429
+ if (outcome.authenticated && !outcome.replaced && outcome.connectionMs >= LONG_CONNECTION_MS)
38681
39430
  this.#attempt = 0;
38682
39431
  const requested = this.#immediate && (this.#options.now ?? Date.now)() <= this.#immediateUntil;
38683
39432
  this.#immediate = false;
38684
39433
  if (requested)
38685
39434
  continue;
38686
- const delay = reconnectDelay(outcome.connectionMs, outcome.code, this.#options.random ?? Math.random, { attempt: this.#attempt, backoff: this.#options.backoff ?? DEFAULT_BACKOFF });
39435
+ const delay = reconnectDelay(outcome.connectionMs, outcome.code, this.#options.random ?? Math.random, { attempt: this.#attempt, backoff: this.#options.backoff ?? DEFAULT_BACKOFF, replaced: outcome.replaced });
38687
39436
  this.#attempt += 1;
39437
+ if (outcome.replaced) {
39438
+ this.#logger.warn("another agent connected with this device identity and replaced this connection; backing off", {
39439
+ device_uuid: this.#options.identity.device_uuid,
39440
+ delay_ms: delay,
39441
+ hint: "the same identity runs elsewhere (copied state folder, cloned VM or restored backup); remove that copy or pair it as a new device"
39442
+ });
39443
+ }
38688
39444
  this.#logger.info("reconnecting", { delay_ms: delay });
38689
39445
  await this.#wait(delay);
38690
39446
  }
@@ -38768,7 +39524,11 @@ var AgentRunner = class {
38768
39524
  const actions = this.#options.lifecycleActions;
38769
39525
  try {
38770
39526
  if (reason2 === "removed:destroyed") {
38771
- await (actions?.purge() ?? purgeAgent({ reason: "destroyed", stateDir: this.#options.paths.dir, ...this.#options.stopKeepAwake ? { stopKeepAwake: this.#options.stopKeepAwake } : {} }));
39527
+ await (actions?.purge() ?? purgeAgent({
39528
+ reason: "destroyed",
39529
+ stateDir: this.#options.paths.dir,
39530
+ ...this.#options.stopKeepAwake ? { stopKeepAwake: this.#options.stopKeepAwake } : {}
39531
+ }, this.#options.lifecycleDeps));
38772
39532
  const dispatch2 = this.#destroyDispatch;
38773
39533
  if (dispatch2 && this.#session)
38774
39534
  this.#session.sendFrame(encode3(buildEnvelope(this.#options.identity, "RESULT", dispatch2.task_id, {
@@ -38777,9 +39537,9 @@ var AgentRunner = class {
38777
39537
  output_excerpt: JSON.stringify({ state: "removed" })
38778
39538
  }, dispatch2.correlation_id)));
38779
39539
  } else {
38780
- await (actions?.removeAutostart() ?? removeAgentAutostart(this.#options.paths.dir)).catch((error63) => this.#logger.warn("autostart removal failed", { error: errorMessage(error63) }));
39540
+ await (actions?.removeAutostart() ?? removeAgentAutostart(this.#options.paths.dir, this.#options.lifecycleDeps)).catch((error63) => this.#logger.warn("autostart removal failed", { error: errorMessage(error63) }));
38781
39541
  if (!passive)
38782
- await (actions?.removeIdentity() ?? removeAgentIdentity({ stateDir: this.#options.paths.dir }));
39542
+ await (actions?.removeIdentity() ?? removeAgentIdentity({ stateDir: this.#options.paths.dir }, this.#options.lifecycleDeps));
38783
39543
  }
38784
39544
  } catch (error63) {
38785
39545
  this.#logger.warn("lifecycle cleanup failed", { error: errorMessage(error63) });
@@ -38857,6 +39617,7 @@ var AgentRunner = class {
38857
39617
  onReady: () => {
38858
39618
  ready = true;
38859
39619
  readyAtMs = now();
39620
+ this.#gatewayNow = session.gatewayNow;
38860
39621
  lastPongMs = readyAtMs;
38861
39622
  const keepalive = session.pingEnabled;
38862
39623
  this.#logger.info("relay authenticated", { device_uuid: identity.device_uuid, keepalive: keepalive ? "ping.v1" : "heartbeat" });
@@ -38898,7 +39659,7 @@ var AgentRunner = class {
38898
39659
  this.#session = session;
38899
39660
  return new Promise((resolve10) => {
38900
39661
  let settled = false;
38901
- const end = (code) => {
39662
+ const end = (code, serverReason) => {
38902
39663
  if (settled)
38903
39664
  return;
38904
39665
  settled = true;
@@ -38931,7 +39692,7 @@ var AgentRunner = class {
38931
39692
  this.#featuresRefused = false;
38932
39693
  this.#logger.info("offering relay features again on the next connection");
38933
39694
  }
38934
- resolve10({ authenticated: ready, connectionMs, code });
39695
+ resolve10({ authenticated: ready, connectionMs, code, replaced: code === 4e3 && serverReason === REPLACED_CLOSE_REASON });
38935
39696
  };
38936
39697
  endConnection = end;
38937
39698
  this.#endConnection = end;
@@ -38970,7 +39731,7 @@ var AgentRunner = class {
38970
39731
  socket.addEventListener("close", (event) => {
38971
39732
  if (!settled)
38972
39733
  this.#handleClose(event.code, event.reason);
38973
- end(event.code);
39734
+ end(event.code, event.reason);
38974
39735
  });
38975
39736
  });
38976
39737
  }
@@ -39110,7 +39871,8 @@ async function cmdSsh(stateDir, args, io) {
39110
39871
  var USAGE = `conbridge-agent ${AGENT_VERSION}
39111
39872
 
39112
39873
  Usage:
39113
- conbridge-agent pair --code XXXX-XXXX [--gateway <url>] [--name <name>] [--full-access] [--no-service] [--key-store keychain|file] [--force]
39874
+ conbridge-agent pair --code XXXX-XXXX [--gateway <url>] [--name <name>] [--full-access [--home [--home-writable]]] [--no-service]
39875
+ [--key-store keychain|file] [--force]
39114
39876
  conbridge-agent connect <conbridge://pair?...> (used by the ConBridge Mac app; no terminal needed)
39115
39877
  conbridge-agent roots add <path> --label <label> [--writable] [--allow-broad-root]
39116
39878
  conbridge-agent roots list
@@ -39119,8 +39881,11 @@ Usage:
39119
39881
  conbridge-agent config keep-awake <on|off>
39120
39882
  conbridge-agent config inventory <on|off> software inventory the owner turns on in the Console (default on)
39121
39883
  ${SSH_USAGE}
39122
- conbridge-agent access full [--no-home] AI apps you approve may run commands here (terminal, processes)
39123
- conbridge-agent access files files only: shared folders, no terminal
39884
+ conbridge-agent access full [--home [--home-writable]] AI apps you approve may run commands here (terminal,
39885
+ processes); the home folder is not shared unless --home (read-only;
39886
+ --home-writable: read-write)
39887
+ conbridge-agent access files full access off: stops the commands AI apps started, removes the home
39888
+ folder share that access full added; other shared folders stay
39124
39889
  conbridge-agent access status
39125
39890
  conbridge-agent start foreground session; Ctrl+C stops it
39126
39891
  conbridge-agent kill [--yes] [--keep-runtime] remove this agent (alias: remove)
@@ -39131,7 +39896,8 @@ ${SSH_USAGE}
39131
39896
  conbridge-agent logs [-f] [-n <lines>]
39132
39897
  conbridge-agent service <install|uninstall|print>
39133
39898
  conbridge-agent update with npx --yes conbridge-agent@latest update: install that version and restart the service
39134
- conbridge-agent unpair stop the service and remove this computer's identity
39899
+ conbridge-agent unpair [--keep-local-access] stop the service, remove this computer's identity and its local access
39900
+ (shared folders, full access, SSH hosts) unless --keep-local-access
39135
39901
  conbridge-agent --version
39136
39902
 
39137
39903
  pair connects this computer to ConBridge (default gateway ${DEFAULT_GATEWAY_URL}, default name: this computer's
@@ -39139,7 +39905,13 @@ name) and installs the background service, so the agent reconnects by itself aft
39139
39905
  a LaunchAgent on macOS, a systemd user service on Linux (started at boot), a Task Scheduler task on Windows.
39140
39906
  While it runs, the agent keeps the computer from idle-sleeping (the display may still turn off); turn this off
39141
39907
  with config keep-awake off. Full access (pair --full-access or access full) lets AI apps you approve run commands
39142
- like a terminal; in the Console you choose per computer whether each command asks you first.
39908
+ like a terminal; it shares your home folder only with --home, read-only unless --home-writable is added too (the
39909
+ agent's own files and credential files such as .ssh, .aws, .env and keys stay blocked); in the Console you choose per
39910
+ computer whether each command, read or change asks you first. access files turns full access off, stops the commands
39911
+ AI apps started and removes the home folder share access full added.
39912
+
39913
+ Shared folders, full access and SSH hosts belong to the ConBridge account and organization this computer was paired
39914
+ with when they were set up: pairing with another account or organization (pair --force, a connect link) removes them first.
39143
39915
 
39144
39916
  Modes: persistent starts automatically; passive runs only with start; timed expires and removes identity;
39145
39917
  ephemeral expires or self-destructs and purges ConBridge files.
@@ -39242,7 +40014,7 @@ async function discardOldKey(paths, identity, env) {
39242
40014
  } catch {
39243
40015
  }
39244
40016
  }
39245
- async function cmdPair(paths, args, io) {
40017
+ async function cmdPair(paths, args, io, hooks = {}) {
39246
40018
  const { values } = (0, import_node_util2.parseArgs)({
39247
40019
  args,
39248
40020
  allowPositionals: false,
@@ -39254,14 +40026,25 @@ async function cmdPair(paths, args, io) {
39254
40026
  "key-store": { type: "string" },
39255
40027
  keychain: { type: "string" },
39256
40028
  "no-service": { type: "boolean" },
39257
- "full-access": { type: "boolean" }
40029
+ "full-access": { type: "boolean" },
40030
+ home: { type: "boolean" },
40031
+ "home-writable": { type: "boolean" }
39258
40032
  }
39259
40033
  });
39260
40034
  if (!values.code)
39261
40035
  throw new UsageError("pair needs --code (create one in the ConBridge Console under Connect)");
39262
- const installed = await runInstalledCopy(paths, ["pair", ...args], io, false);
39263
- if (installed !== null)
39264
- return installed;
40036
+ if ((values.home || values["home-writable"]) && !values["full-access"])
40037
+ throw new UsageError("--home and --home-writable need --full-access");
40038
+ if (values["home-writable"] && !values.home)
40039
+ throw new UsageError("--home-writable needs --home");
40040
+ if (hooks.confirmOffer) {
40041
+ if (runningFromNpm() && !await runningFromRuntime(paths.dir))
40042
+ throw new UsageError("connect runs from the installed agent (ConBridge.app); in a terminal use pair --code");
40043
+ } else {
40044
+ const installed = await runInstalledCopy(paths, ["pair", ...args], io, false);
40045
+ if (installed !== null)
40046
+ return installed;
40047
+ }
39265
40048
  const gateway = values.gateway ?? DEFAULT_GATEWAY_URL;
39266
40049
  const name3 = (values.name ?? (0, import_node_os15.hostname)()).trim().slice(0, 64) || "My computer";
39267
40050
  const keyStore = await newKeyStore(paths, values, io.env);
@@ -39270,16 +40053,27 @@ async function cmdPair(paths, args, io) {
39270
40053
  throw new UsageError("This agent is already paired; use --force to pair again (the old identity is replaced once the new pairing is approved)");
39271
40054
  await ensureStateDir(paths.dir);
39272
40055
  io.out(`Device key store: ${keyStore.descriptor.type === "keychain" ? "macOS Keychain" : `file ${paths.key}`}`);
40056
+ const shared = describeLocalGrants(await readLocalGrants(paths));
39273
40057
  const identity = await pairDevice({
39274
40058
  paths,
39275
40059
  keyStore,
39276
40060
  gatewayUrl: gateway,
39277
40061
  code: values.code,
39278
40062
  name: name3,
39279
- onOffered: ({ fingerprint }) => {
39280
- io.out(`Offer sent. Device fingerprint: ${fingerprint}`);
40063
+ onOffered: ({ fingerprint, organization_name, inviter }) => {
40064
+ io.out(`Offer sent to ${organization_name !== null ? `the organization "${organization_name}"` : "an organization not shown by this server"}${inviter !== null ? `, invited by ${inviter}` : ""}. Device fingerprint: ${fingerprint}`);
40065
+ if (shared.length > 0) {
40066
+ io.out("Already shared from this computer: " + shared.join("; ") + ".");
40067
+ io.out("It stays shared only if this approval comes from the ConBridge account and organization it was set up for; otherwise, or if it was set up while this computer was not paired, it is removed first.");
40068
+ }
39281
40069
  io.out("Approve this device in the ConBridge Console and check that the fingerprint matches. Waiting...");
39282
40070
  },
40071
+ ...hooks.confirmOffer ? { confirmOffer: hooks.confirmOffer } : {},
40072
+ onLocalGrantsCleared: (cleared) => {
40073
+ io.out("This computer's local access was set up for another ConBridge account or organization (or while it was not paired), so it was removed:");
40074
+ for (const line of describeClearedGrants(cleared))
40075
+ io.out(` ${line}`);
40076
+ },
39283
40077
  onApproved: async () => {
39284
40078
  if (keyStore.descriptor.type === "file")
39285
40079
  await (0, import_promises23.rename)(pendingKeyPath(paths), paths.key);
@@ -39288,8 +40082,9 @@ async function cmdPair(paths, args, io) {
39288
40082
  if (previous && !(keyStore.descriptor.type === "file" && previous.key_store?.type !== "keychain"))
39289
40083
  await discardOldKey(paths, previous, io.env);
39290
40084
  io.out(`Paired as "${identity.display_name}" (device ${identity.device_uuid}).`);
39291
- if (values["full-access"])
39292
- await cmdAccess(paths, ["full"], io);
40085
+ if (values["full-access"]) {
40086
+ await cmdAccess(paths, ["full", ...values.home ? ["--home"] : [], ...values["home-writable"] ? ["--home-writable"] : []], io);
40087
+ }
39293
40088
  if (identity.connection_mode === "passive") {
39294
40089
  await removeAgentAutostart(paths.dir, lifecycleDeps(io));
39295
40090
  await stopSupervisor(paths);
@@ -39320,11 +40115,12 @@ async function cmdConnect(paths, args, io) {
39320
40115
  return await runConnect(link, {
39321
40116
  dialogs: macConnectDialogs,
39322
40117
  isPaired: () => exists2(paths.identity),
40118
+ localAccess: () => readLocalGrants(paths),
39323
40119
  addFolder: async (path, label, writable) => {
39324
40120
  await addRoot(paths, { path, label, writable, allowBroadRoot: false, ...io.env.HOME ? { home: io.env.HOME } : {} });
39325
40121
  },
39326
- pair: async (request, replacing) => {
39327
- const code = await cmdPair(paths, ["--gateway", request.gateway, "--code", request.code, "--name", request.name, "--no-service", ...replacing ? ["--force"] : []], io);
40122
+ pair: async (request, replacing, confirmOffer) => {
40123
+ const code = await cmdPair(paths, ["--gateway", request.gateway, "--code", request.code, "--name", request.name, "--no-service", ...replacing ? ["--force"] : []], io, { confirmOffer });
39328
40124
  if (code !== 0)
39329
40125
  throw new Error("Pairing did not finish.");
39330
40126
  },
@@ -39678,31 +40474,60 @@ async function cmdSupervise(paths, io) {
39678
40474
  }
39679
40475
  return 0;
39680
40476
  }
40477
+ function sharedFolders(roots) {
40478
+ return roots.length === 0 ? "none" : roots.map((root) => `${root.label} (${root.writable ? "read-write" : "read-only"})`).join(", ");
40479
+ }
39681
40480
  async function cmdAccess(paths, args, io) {
39682
40481
  const [mode, ...rest] = args;
39683
40482
  const config2 = await loadConfig(paths);
39684
40483
  if (mode === "status" || mode === void 0) {
39685
40484
  io.out(`Full access (terminal): ${config2.full_access === true ? "on" : "off"}`);
39686
- io.out(`Shared folders: ${config2.roots.length === 0 ? "none" : config2.roots.map((root) => `${root.label} (${root.writable ? "read-write" : "read-only"})`).join(", ")}`);
40485
+ io.out(`Shared folders: ${sharedFolders(config2.roots)}`);
39687
40486
  return 0;
39688
40487
  }
39689
40488
  if (mode === "files") {
39690
- await saveConfig(paths, { ...config2, full_access: false });
39691
- io.out("Full access is off: AI apps can use only the shared folders, no terminal. A running agent applies this within a heartbeat.");
40489
+ const home2 = addedHomeRoot(config2);
40490
+ const roots = config2.roots.filter((root) => root !== home2);
40491
+ const next = { ...config2, roots, full_access: false };
40492
+ delete next.home_root_added;
40493
+ await saveConfig(paths, next);
40494
+ io.out("Full access is off: AI apps can no longer run terminal commands or manage processes on this computer, and the running agent stops the commands they started. It applies within a heartbeat.");
40495
+ if (home2)
40496
+ io.out(`Your home folder (${home2.path}), which access full shared ${home2.writable ? "read-write" : "read-only"}, is no longer shared.`);
40497
+ io.out(`AI apps can use only these shared folders: ${sharedFolders(roots)}.`);
39692
40498
  return 0;
39693
40499
  }
39694
40500
  if (mode !== "full")
39695
40501
  throw new UsageError("access needs full, files or status");
39696
- const { values } = (0, import_node_util2.parseArgs)({ args: rest, allowPositionals: false, options: { "no-home": { type: "boolean" } } });
39697
- await saveConfig(paths, { ...config2, full_access: true });
39698
- if (!values["no-home"]) {
39699
- const home = io.env.HOME ?? (0, import_node_os15.homedir)();
39700
- const real = await (0, import_promises23.realpath)(home).catch(() => null);
39701
- const covered = config2.roots.some((root) => root.path === real);
39702
- if (real && !covered) {
39703
- const root = await addRoot(paths, { path: real, label: "Home", writable: true, allowBroadRoot: true, home });
39704
- io.out(`Shared your home folder read-write as "${root.label}" (agent state and credential files stay blocked).`);
40502
+ const { values } = (0, import_node_util2.parseArgs)({
40503
+ args: rest,
40504
+ allowPositionals: false,
40505
+ options: { home: { type: "boolean" }, "home-writable": { type: "boolean" }, "no-home": { type: "boolean" } }
40506
+ });
40507
+ if (values["home-writable"] && !values.home)
40508
+ throw new UsageError("--home-writable needs --home");
40509
+ if (values.home && values["no-home"])
40510
+ throw new UsageError("--home and --no-home cannot be combined");
40511
+ const owner = await currentGrantOwner(paths);
40512
+ await saveConfig(paths, { ...config2, full_access: true, ...owner ? { granted_for: owner } : {} });
40513
+ if (values["no-home"])
40514
+ io.out("The home folder is no longer shared by default; --no-home is not needed.");
40515
+ const home = io.env.HOME ?? (0, import_node_os15.homedir)();
40516
+ const real = await (0, import_promises23.realpath)(home).catch(() => null);
40517
+ const existing = real === null ? void 0 : config2.roots.find((root) => root.path === real);
40518
+ if (existing) {
40519
+ io.out(`Your home folder (${existing.path}) is already shared as "${existing.label}" (${existing.writable ? "read-write" : "read-only"}); that share is left as it is.`);
40520
+ } else if (values.home) {
40521
+ if (real) {
40522
+ const writable = values["home-writable"] === true;
40523
+ const root = await addRoot(paths, { path: real, label: "Home", writable, allowBroadRoot: true, home });
40524
+ await saveConfig(paths, { ...await loadConfig(paths), home_root_added: { root_id: root.root_id, path: root.path } });
40525
+ io.out(writable ? `Shared your whole home folder (${root.path}) read-write as "${root.label}": AI apps you approve can list, read and search the files in it and change them. The agent's own files and credential files (.ssh, .aws, .env, keys and similar) stay blocked. Whether a read or a change asks you first follows your settings in the ConBridge Console.` : `Shared your whole home folder (${root.path}) read-only as "${root.label}": AI apps you approve can list, read and search the files in it. The agent's own files and credential files (.ssh, .aws, .env, keys and similar) stay blocked. Whether a read asks you first follows your settings in the ConBridge Console.`);
40526
+ } else {
40527
+ io.err(`Your home folder (${home}) was not found, so it was not shared.`);
39705
40528
  }
40529
+ } else {
40530
+ io.out("Your home folder is not shared. To share it read-only: conbridge-agent access full --home (add --home-writable to allow changes).");
39706
40531
  }
39707
40532
  io.out("Full access is on: AI apps you approve can run commands on this computer as this user, manage processes and change files.");
39708
40533
  io.out("In the ConBridge Console (Devices) choose whether commands run without asking or wait for your approval. Turn it off with: conbridge-agent access files");
@@ -39778,15 +40603,32 @@ async function cmdLogs(paths, args, io) {
39778
40603
  }
39779
40604
  }
39780
40605
  }
39781
- async function cmdUnpair(paths, io) {
40606
+ async function cmdUnpair(paths, args, io) {
40607
+ const { values } = (0, import_node_util2.parseArgs)({ args, allowPositionals: false, options: { "keep-local-access": { type: "boolean" } } });
39782
40608
  const identity = await loadIdentity(paths).catch(() => null);
39783
- if ((await serviceLocation(paths.dir))?.installed)
40609
+ if ((await serviceLocation(paths.dir, { home: io.env.HOME ?? io.env.USERPROFILE ?? (0, import_node_os15.homedir)() }))?.installed)
39784
40610
  await cmdService(paths, ["uninstall"], io).catch(() => 1);
39785
40611
  await stopAgentProcess(paths);
39786
40612
  if (identity)
39787
40613
  await discardOldKey(paths, identity, io.env);
39788
40614
  await (0, import_promises23.unlink)(paths.identity).catch(() => void 0);
39789
40615
  io.out(identity ? `Removed the identity of "${identity.display_name}". Remove it in the ConBridge Console (Devices) as well; its key no longer exists here.` : "This computer was not paired.");
40616
+ if (values["keep-local-access"]) {
40617
+ if (identity)
40618
+ await adoptUnownedGrants(paths, grantOwnerOf(identity));
40619
+ const kept = describeLocalGrants(await readLocalGrants(paths));
40620
+ if (kept.length > 0) {
40621
+ io.out("Kept the local access: " + kept.join("; ") + ".");
40622
+ io.out("Pairing again with the same ConBridge account and organization keeps it; pairing with another one removes it.");
40623
+ }
40624
+ return 0;
40625
+ }
40626
+ const cleared = await clearLocalGrants(paths);
40627
+ if (hasLocalGrants(cleared)) {
40628
+ io.out("Removed the local access as well (keep it next time with unpair --keep-local-access):");
40629
+ for (const line of describeClearedGrants(cleared))
40630
+ io.out(` ${line}`);
40631
+ }
39790
40632
  return 0;
39791
40633
  }
39792
40634
  function lifecycleDeps(io) {
@@ -39846,7 +40688,7 @@ async function main(argv, io) {
39846
40688
  case "supervise":
39847
40689
  return await cmdSupervise(paths, io);
39848
40690
  case "unpair":
39849
- return await cmdUnpair(paths, io);
40691
+ return await cmdUnpair(paths, args, io);
39850
40692
  case "service":
39851
40693
  return await cmdService(paths, args, io);
39852
40694
  case "update":