conbridge-agent 0.8.1 → 0.9.0

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.0", commit: "3118837e46a8", built_at: "2026-11-20T04:41:10.179Z", keychain_helper_sha256: "5a29362ad38d1b42cab3b8c6cec774fedfd1157a1a0152d7763899a1480ea123", 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.0";
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() {
@@ -24873,8 +24941,8 @@ function windowsPath(value) {
24873
24941
  }
24874
24942
  var vbsString = (value) => '"' + value.replace(/"/g, '""') + '"';
24875
24943
  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"`;
24944
+ const quoted2 = programArguments(options).map((arg2, index, all) => index === all.length - 1 ? arg2 : `"${windowsPath(arg2)}"`).join(" ");
24945
+ const command2 = `cmd.exe /d /s /c "${quoted2} >> "${windowsPath(options.logPath)}" 2>&1"`;
24878
24946
  return [
24879
24947
  "' ConBridge Desktop Agent launcher (Task Scheduler). Generated by conbridge-agent service install.",
24880
24948
  "Option Explicit",
@@ -25065,6 +25133,17 @@ var identitySchema = external_exports.strictObject({
25065
25133
  destroy_deadline_ms: external_exports.number().int().nonnegative().nullable().optional(),
25066
25134
  key_store: keyStoreDescriptorSchema.optional()
25067
25135
  });
25136
+ var grantOwnerSchema = external_exports.strictObject({ gateway_url: external_exports.url(), tenant_id: opaque2, user_id: opaque2 });
25137
+ function grantOwnerOf(identity) {
25138
+ return { gateway_url: identity.gateway_url, tenant_id: identity.tenant_id, user_id: identity.user_id };
25139
+ }
25140
+ function sameGrantOwner(a, b) {
25141
+ 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;
25142
+ }
25143
+ async function currentGrantOwner(paths) {
25144
+ const identity = await loadIdentity(paths).catch(() => null);
25145
+ return identity ? grantOwnerOf(identity) : void 0;
25146
+ }
25068
25147
  var rootSchema = external_exports.strictObject({
25069
25148
  root_id: external_exports.uuid(),
25070
25149
  path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute"),
@@ -25084,7 +25163,14 @@ var configSchema = external_exports.strictObject({
25084
25163
  */
25085
25164
  full_access: external_exports.boolean().optional(),
25086
25165
  /** 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()
25166
+ inventory: external_exports.boolean().optional(),
25167
+ /** Whose grants `roots` and `full_access` are (see grantOwnerSchema). Absent: made while unpaired, or by an older agent. */
25168
+ granted_for: grantOwnerSchema.optional(),
25169
+ /** The home folder root `access full` added, so `access files` can take exactly that share back. */
25170
+ home_root_added: external_exports.strictObject({
25171
+ root_id: external_exports.uuid(),
25172
+ path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute")
25173
+ }).optional()
25088
25174
  });
25089
25175
  function defaultConfig() {
25090
25176
  return { version: 1, roots: [], deny_globs: [...DEFAULT_DENY_GLOBS], confirm_writes: false };
@@ -25145,7 +25231,8 @@ async function addRoot(paths, input2) {
25145
25231
  if (label.length < 1 || label.length > 128)
25146
25232
  throw new Error("Label must be 1 to 128 characters");
25147
25233
  const root = { root_id: (0, import_node_crypto2.randomUUID)(), path: real, label, writable: input2.writable };
25148
- await saveConfig(paths, { ...config2, roots: [...config2.roots, root] });
25234
+ const owner = await currentGrantOwner(paths);
25235
+ await saveConfig(paths, { ...config2, roots: [...config2.roots, root], ...owner ? { granted_for: owner } : {} });
25149
25236
  return root;
25150
25237
  }
25151
25238
  async function removeRoot(paths, rootId) {
@@ -25153,9 +25240,14 @@ async function removeRoot(paths, rootId) {
25153
25240
  const roots = config2.roots.filter((root) => root.root_id !== rootId);
25154
25241
  if (roots.length === config2.roots.length)
25155
25242
  return false;
25156
- await saveConfig(paths, { ...config2, roots });
25243
+ const { home_root_added: home, ...rest } = config2;
25244
+ await saveConfig(paths, { ...rest, roots, ...home && home.root_id !== rootId ? { home_root_added: home } : {} });
25157
25245
  return true;
25158
25246
  }
25247
+ function addedHomeRoot(config2) {
25248
+ const added = config2.home_root_added;
25249
+ return added ? config2.roots.find((root) => root.root_id === added.root_id && root.path === added.path) : void 0;
25250
+ }
25159
25251
 
25160
25252
  // dist/keystore.js
25161
25253
  var import_node_path5 = require("node:path");
@@ -26018,21 +26110,45 @@ var import_node_util2 = require("node:util");
26018
26110
  var import_node_child_process5 = require("node:child_process");
26019
26111
  var import_node_path9 = require("node:path");
26020
26112
  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, " ");
26113
+ var UNSAFE_TEXT = new RegExp(UNSAFE_PATH_CHARS.source, "gu");
26114
+ function quoted(value) {
26115
+ return `"${value.replace(UNSAFE_TEXT, " ")}"`;
26024
26116
  }
26025
- function appleScriptString(value) {
26026
- return '"' + value.replace(/[\\"]/g, "\\$&").replace(/[\r\n]+/g, " ") + '"';
26117
+ function confirmText(request) {
26118
+ const where = `in root ${quoted(request.rootLabel)}`;
26119
+ let what;
26120
+ switch (request.action) {
26121
+ case "write":
26122
+ what = `${request.created ? "create" : "overwrite"} ${quoted(request.path)} ${where}${request.bytes === void 0 ? "" : ` (${request.bytes} bytes)`}`;
26123
+ break;
26124
+ case "edit":
26125
+ what = `edit ${quoted(request.path)} ${where}${request.replacements === void 0 ? "" : ` (${request.replacements} replacement${request.replacements === 1 ? "" : "s"})`}`;
26126
+ break;
26127
+ case "delete":
26128
+ what = `delete ${quoted(request.path)} ${where}`;
26129
+ break;
26130
+ case "move":
26131
+ what = `move ${quoted(request.path)} to ${quoted(request.to ?? "")} ${where}`;
26132
+ break;
26133
+ case "mkdir":
26134
+ what = `create the folder ${quoted(request.path)} ${where}`;
26135
+ break;
26136
+ }
26137
+ return `ConBridge wants to ${what}. This change was approved in the Console.`;
26027
26138
  }
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`;
26139
+ var MAC_CONFIRM_SCRIPT = [
26140
+ "on run argv",
26141
+ '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',
26142
+ "end run"
26143
+ ];
26144
+ function buildConfirmArgs(request) {
26145
+ return [...MAC_CONFIRM_SCRIPT.flatMap((line) => ["-e", line]), confirmText(request)];
26030
26146
  }
26031
26147
  var macDialogConfirm = (request) => {
26032
26148
  if (process.platform !== "darwin")
26033
26149
  return Promise.resolve(false);
26034
26150
  return new Promise((resolve10) => {
26035
- (0, import_node_child_process5.execFile)("/usr/bin/osascript", ["-e", buildConfirmScript(request)], { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
26151
+ (0, import_node_child_process5.execFile)("/usr/bin/osascript", buildConfirmArgs(request), { timeout: CONFIRM_TIMEOUT_MS }, (error63, stdout) => {
26036
26152
  if (error63)
26037
26153
  return resolve10(false);
26038
26154
  resolve10(/button returned:Allow/.test(stdout) && !/gave up:true/.test(stdout));
@@ -26048,16 +26164,23 @@ var windowsConfirm = (request) => new Promise((resolve10) => {
26048
26164
  const powershell = import_node_path9.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
26049
26165
  (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
26166
  });
26167
+ function linuxZenityArgs(text6) {
26168
+ return ["--question", "--no-markup", "--title=ConBridge", `--text=${text6}`, "--ok-label=Allow", "--cancel-label=Deny", "--default-cancel", "--timeout=120"];
26169
+ }
26170
+ function linuxKdialogArgs(text6) {
26171
+ const escaped = text6.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
26172
+ return ["--title", "ConBridge", "--warningyesno", `<qt>${escaped}</qt>`, "--yes-label", "Allow", "--no-label", "Deny"];
26173
+ }
26051
26174
  var linuxConfirm = (request) => new Promise((resolve10) => {
26052
26175
  if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
26053
26176
  return resolve10(false);
26054
26177
  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) => {
26178
+ (0, import_node_child_process5.execFile)("zenity", linuxZenityArgs(text6), { timeout: CONFIRM_TIMEOUT_MS }, (error63) => {
26056
26179
  if (!error63)
26057
26180
  return resolve10(true);
26058
26181
  if (error63.code !== "ENOENT")
26059
26182
  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));
26183
+ (0, import_node_child_process5.execFile)("kdialog", linuxKdialogArgs(text6), { timeout: CONFIRM_TIMEOUT_MS }, (fallback) => resolve10(!fallback));
26061
26184
  });
26062
26185
  });
26063
26186
  var localConfirm = (request) => {
@@ -26072,7 +26195,220 @@ var localConfirm = (request) => {
26072
26195
 
26073
26196
  // dist/connect.js
26074
26197
  var import_node_child_process6 = require("node:child_process");
26198
+ var import_node_path11 = require("node:path");
26199
+
26200
+ // dist/ssh/hosts.js
26201
+ var import_node_crypto6 = require("node:crypto");
26202
+ var import_promises8 = require("node:fs/promises");
26075
26203
  var import_node_path10 = require("node:path");
26204
+ var MAX_SSH_HOSTS = 64;
26205
+ var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
26206
+ 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])?)*$/;
26207
+ var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
26208
+ var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
26209
+ function isValidSshHost(value) {
26210
+ return DNS_HOST.test(value) || IPV6_HOST.test(value);
26211
+ }
26212
+ function isValidIdentityPath(value) {
26213
+ return (0, import_node_path10.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
26214
+ }
26215
+ var PINNABLE_KEY_TYPES = Object.freeze([
26216
+ "ssh-ed25519",
26217
+ "ecdsa-sha2-nistp256",
26218
+ "ecdsa-sha2-nistp384",
26219
+ "ecdsa-sha2-nistp521",
26220
+ "ssh-rsa"
26221
+ ]);
26222
+ var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
26223
+ var sshHostSchema = external_exports.strictObject({
26224
+ resource_id: external_exports.uuid(),
26225
+ alias: external_exports.string().regex(SSH_ALIAS),
26226
+ host: external_exports.string().refine(isValidSshHost, "Invalid host"),
26227
+ port: external_exports.number().int().min(1).max(65535),
26228
+ user: external_exports.string().regex(SSH_USER).optional(),
26229
+ identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
26230
+ production: external_exports.boolean(),
26231
+ key_type: external_exports.enum(PINNABLE_KEY_TYPES),
26232
+ public_key: external_exports.string().min(16).max(8192).regex(base643),
26233
+ fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
26234
+ pinned_at: external_exports.iso.datetime({ offset: true })
26235
+ });
26236
+ var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS), granted_for: grantOwnerSchema.optional() });
26237
+ function sshPaths(stateDir) {
26238
+ const dir = (0, import_node_path10.join)(stateDir, "ssh");
26239
+ return { dir, hosts: (0, import_node_path10.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path10.join)(dir, "known_hosts") };
26240
+ }
26241
+ function knownHostsPath(paths, resourceId) {
26242
+ return (0, import_node_path10.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
26243
+ }
26244
+ function hostKeyAlias(host) {
26245
+ return "conbridge-" + host.resource_id;
26246
+ }
26247
+ function fingerprintOf(publicKey) {
26248
+ return "SHA256:" + (0, import_node_crypto6.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
26249
+ }
26250
+ function normalizeFingerprint(value) {
26251
+ const trimmed = value.trim();
26252
+ return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
26253
+ }
26254
+ function parseKeyscan(output2) {
26255
+ const keys = [];
26256
+ for (const line of output2.split("\n")) {
26257
+ const trimmed = line.trim();
26258
+ if (trimmed === "" || trimmed.startsWith("#"))
26259
+ continue;
26260
+ const [, type, key] = trimmed.split(/\s+/);
26261
+ if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
26262
+ continue;
26263
+ keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
26264
+ }
26265
+ return keys;
26266
+ }
26267
+ function preferredKey(keys) {
26268
+ for (const type of PINNABLE_KEY_TYPES) {
26269
+ const key = keys.find((candidate) => candidate.key_type === type);
26270
+ if (key)
26271
+ return key;
26272
+ }
26273
+ return null;
26274
+ }
26275
+ async function loadHostsFile(paths) {
26276
+ let text6;
26277
+ try {
26278
+ text6 = await (0, import_promises8.readFile)(paths.hosts, "utf8");
26279
+ } catch (error63) {
26280
+ if (errorCode2(error63) === "ENOENT")
26281
+ return null;
26282
+ throw error63;
26283
+ }
26284
+ return hostsFileSchema.parse(JSON.parse(text6));
26285
+ }
26286
+ async function loadSshHosts(paths) {
26287
+ return (await loadHostsFile(paths))?.hosts ?? [];
26288
+ }
26289
+ async function sshHostsOwner(paths) {
26290
+ return (await loadHostsFile(paths))?.granted_for;
26291
+ }
26292
+ async function setSshHostsOwner(paths, owner) {
26293
+ const file2 = await loadHostsFile(paths);
26294
+ if (file2)
26295
+ await saveSshHosts(paths, file2.hosts, owner);
26296
+ }
26297
+ async function clearSshHosts(paths) {
26298
+ const hosts = await loadSshHosts(paths).catch(() => []);
26299
+ await (0, import_promises8.rm)(paths.hosts, { force: true });
26300
+ const pins = await (0, import_promises8.readdir)(paths.knownHostsDir).catch((error63) => {
26301
+ if (errorCode2(error63) === "ENOENT")
26302
+ return [];
26303
+ throw error63;
26304
+ });
26305
+ for (const name3 of pins)
26306
+ if (external_exports.uuid().safeParse(name3).success)
26307
+ await (0, import_promises8.rm)((0, import_node_path10.join)(paths.knownHostsDir, name3), { force: true });
26308
+ return hosts;
26309
+ }
26310
+ async function ensureSshDirs(paths) {
26311
+ for (const dir of [paths.dir, paths.knownHostsDir]) {
26312
+ await (0, import_promises8.mkdir)(dir, { recursive: true, mode: 448 });
26313
+ await (0, import_promises8.chmod)(dir, 448);
26314
+ }
26315
+ }
26316
+ async function saveSshHosts(paths, hosts, owner) {
26317
+ await ensureSshDirs(paths);
26318
+ const file2 = hostsFileSchema.parse({ version: 1, hosts, ...owner ? { granted_for: owner } : {} });
26319
+ await writeFileAtomic(paths.hosts, JSON.stringify(file2, null, 2) + "\n", 384);
26320
+ }
26321
+ async function ownerForNewHost(paths, recorded) {
26322
+ return await currentGrantOwner(statePaths((0, import_node_path10.dirname)(paths.dir))) ?? recorded;
26323
+ }
26324
+ async function writeKnownHosts(paths, host) {
26325
+ await ensureSshDirs(paths);
26326
+ await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
26327
+ `, 384);
26328
+ }
26329
+ async function validateNewHost(input2) {
26330
+ if (!SSH_ALIAS.test(input2.alias))
26331
+ throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
26332
+ if (!isValidSshHost(input2.host))
26333
+ throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
26334
+ if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
26335
+ throw new Error("Port must be 1-65535");
26336
+ if (input2.user !== void 0 && !SSH_USER.test(input2.user))
26337
+ throw new Error("User must be a plain login name");
26338
+ if (input2.identity !== void 0) {
26339
+ if (!isValidIdentityPath(input2.identity))
26340
+ throw new Error("Identity must be an absolute path without quotes, % or control characters");
26341
+ const info = await (0, import_promises8.stat)(input2.identity).catch(() => null);
26342
+ if (!info?.isFile())
26343
+ throw new Error("Identity file not found");
26344
+ }
26345
+ }
26346
+ async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
26347
+ await validateNewHost(input2);
26348
+ const file2 = await loadHostsFile(paths);
26349
+ const hosts = file2?.hosts ?? [];
26350
+ if (hosts.some((host2) => host2.alias === input2.alias))
26351
+ throw new Error(`An SSH host named ${input2.alias} already exists`);
26352
+ if (hosts.length >= MAX_SSH_HOSTS)
26353
+ throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
26354
+ const host = sshHostSchema.parse({
26355
+ resource_id: (0, import_node_crypto6.randomUUID)(),
26356
+ alias: input2.alias,
26357
+ host: input2.host,
26358
+ port: input2.port ?? 22,
26359
+ ...input2.user !== void 0 ? { user: input2.user } : {},
26360
+ ...input2.identity !== void 0 ? { identity: input2.identity } : {},
26361
+ production: input2.production === true,
26362
+ key_type: key.key_type,
26363
+ public_key: key.public_key,
26364
+ fingerprint: key.fingerprint,
26365
+ pinned_at: now.toISOString()
26366
+ });
26367
+ await writeKnownHosts(paths, host);
26368
+ await saveSshHosts(paths, [...hosts, host], await ownerForNewHost(paths, file2?.granted_for));
26369
+ return host;
26370
+ }
26371
+ async function findSshHost(paths, alias) {
26372
+ return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
26373
+ }
26374
+ async function updateHost(paths, alias, change) {
26375
+ const file2 = await loadHostsFile(paths);
26376
+ const hosts = file2?.hosts ?? [];
26377
+ const index = hosts.findIndex((host) => host.alias === alias);
26378
+ if (index < 0)
26379
+ throw new Error(`No SSH host named ${alias}`);
26380
+ const updated = sshHostSchema.parse(change(hosts[index]));
26381
+ const next = [...hosts];
26382
+ next[index] = updated;
26383
+ if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
26384
+ await writeKnownHosts(paths, updated);
26385
+ await saveSshHosts(paths, next, file2?.granted_for);
26386
+ return updated;
26387
+ }
26388
+ async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
26389
+ return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
26390
+ }
26391
+ async function setSshHostProduction(paths, alias, production) {
26392
+ return await updateHost(paths, alias, (host) => ({ ...host, production }));
26393
+ }
26394
+ async function removeSshHost(paths, alias) {
26395
+ const file2 = await loadHostsFile(paths);
26396
+ const hosts = file2?.hosts ?? [];
26397
+ const host = hosts.find((entry) => entry.alias === alias);
26398
+ if (!host)
26399
+ return false;
26400
+ await saveSshHosts(paths, hosts.filter((entry) => entry !== host), file2?.granted_for);
26401
+ await (0, import_promises8.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
26402
+ return true;
26403
+ }
26404
+ function hostAddress(host) {
26405
+ if (host.port === 22)
26406
+ return host.host;
26407
+ return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
26408
+ }
26409
+ function inventoryResource2(host) {
26410
+ return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
26411
+ }
26076
26412
 
26077
26413
  // dist/pairing.js
26078
26414
  var PAIRING_CODE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}-?[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/;
@@ -26106,7 +26442,12 @@ function normalizePairingCode(input2) {
26106
26442
  return code.includes("-") ? code : `${code.slice(0, 4)}-${code.slice(4)}`;
26107
26443
  }
26108
26444
  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) });
26445
+ var offerResponseSchema = external_exports.object({
26446
+ pairing_id: external_exports.string().min(1).max(128),
26447
+ poll_token: external_exports.string().min(16).max(512),
26448
+ organization_name: external_exports.string().max(1024).optional().catch(void 0),
26449
+ inviter: external_exports.string().max(1024).optional().catch(void 0)
26450
+ });
26110
26451
  var statusResponseSchema = external_exports.discriminatedUnion("state", [
26111
26452
  external_exports.object({
26112
26453
  state: external_exports.literal("approved"),
@@ -26121,6 +26462,83 @@ var statusResponseSchema = external_exports.discriminatedUnion("state", [
26121
26462
  external_exports.object({ state: external_exports.enum(["open", "offered", "pending"]) }),
26122
26463
  external_exports.object({ state: external_exports.enum(["denied", "expired"]) })
26123
26464
  ]);
26465
+ var UNSAFE_TEXT2 = new RegExp(UNSAFE_PATH_CHARS.source, "gu");
26466
+ function displayText(value, max = 80) {
26467
+ const text6 = (value ?? "").replace(UNSAFE_TEXT2, " ").replace(/\s+/g, " ").trim();
26468
+ if (text6 === "")
26469
+ return null;
26470
+ return text6.length > max ? text6.slice(0, max - 3) + "..." : text6;
26471
+ }
26472
+ function hasLocalGrants(grants) {
26473
+ return grants.roots.length > 0 || grants.full_access || grants.ssh_hosts.length > 0;
26474
+ }
26475
+ function grantsOf(config2, hosts) {
26476
+ return {
26477
+ roots: config2.roots.map(({ label, path, writable }) => ({ label, path, writable })),
26478
+ full_access: config2.full_access === true,
26479
+ ssh_hosts: hosts.map(({ alias, production }) => ({ alias, production }))
26480
+ };
26481
+ }
26482
+ async function readLocalGrants(paths) {
26483
+ return grantsOf(await loadConfig(paths), await loadSshHosts(sshPaths(paths.dir)).catch(() => []));
26484
+ }
26485
+ function describeLocalGrants(grants) {
26486
+ const lines5 = [];
26487
+ if (grants.roots.length > 0) {
26488
+ lines5.push("Shared folders: " + grants.roots.map((root) => `${displayText(root.label, 64) ?? "folder"} (${root.writable ? "read-write" : "read-only"})`).join(", "));
26489
+ }
26490
+ if (grants.full_access)
26491
+ lines5.push("Full access (terminal): on");
26492
+ if (grants.ssh_hosts.length > 0)
26493
+ lines5.push("SSH hosts: " + grants.ssh_hosts.map((host) => host.production ? `${host.alias} (production)` : host.alias).join(", "));
26494
+ return lines5;
26495
+ }
26496
+ function describeClearedGrants(grants) {
26497
+ const lines5 = [];
26498
+ if (grants.roots.length > 0)
26499
+ lines5.push("Stopped sharing folders: " + grants.roots.map((root) => `${displayText(root.label, 64) ?? "folder"} (${displayText(root.path, 256) ?? ""})`).join(", "));
26500
+ if (grants.full_access)
26501
+ lines5.push("Turned full access (terminal) off");
26502
+ if (grants.ssh_hosts.length > 0)
26503
+ lines5.push("Removed SSH hosts and their pinned keys: " + grants.ssh_hosts.map((host) => host.alias).join(", "));
26504
+ return lines5;
26505
+ }
26506
+ async function adoptUnownedGrants(paths, owner) {
26507
+ const config2 = await loadConfig(paths);
26508
+ if (config2.granted_for === void 0 && hasLocalGrants(grantsOf(config2, [])))
26509
+ await saveConfig(paths, { ...config2, granted_for: owner });
26510
+ const ssh = sshPaths(paths.dir);
26511
+ const hosts = await loadSshHosts(ssh).then((list) => list, () => []);
26512
+ if (hosts.length > 0 && await sshHostsOwner(ssh) === void 0)
26513
+ await setSshHostsOwner(ssh, owner);
26514
+ }
26515
+ function withoutGrants(config2) {
26516
+ const next = { ...config2, roots: [] };
26517
+ delete next.full_access;
26518
+ delete next.home_root_added;
26519
+ delete next.granted_for;
26520
+ return next;
26521
+ }
26522
+ async function clearLocalGrants(paths) {
26523
+ const config2 = await loadConfig(paths);
26524
+ await saveConfig(paths, withoutGrants(config2));
26525
+ const hosts = await clearSshHosts(sshPaths(paths.dir));
26526
+ return grantsOf(config2, hosts);
26527
+ }
26528
+ async function bindLocalGrants(paths, owner, previous) {
26529
+ const replaced = previous ? grantOwnerOf(previous) : void 0;
26530
+ const config2 = await loadConfig(paths);
26531
+ const keepConfig = sameGrantOwner(config2.granted_for ?? replaced, owner);
26532
+ await saveConfig(paths, { ...keepConfig ? config2 : withoutGrants(config2), granted_for: owner });
26533
+ const ssh = sshPaths(paths.dir);
26534
+ const hostsOwner = await sshHostsOwner(ssh).then((recorded) => ({ readable: true, recorded }), () => ({ readable: false, recorded: void 0 }));
26535
+ let clearedHosts = [];
26536
+ if (hostsOwner.readable && sameGrantOwner(hostsOwner.recorded ?? replaced, owner))
26537
+ await setSshHostsOwner(ssh, owner);
26538
+ else
26539
+ clearedHosts = await clearSshHosts(ssh);
26540
+ return keepConfig ? grantsOf({ ...config2, roots: [], full_access: false }, clearedHosts) : grantsOf(config2, clearedHosts);
26541
+ }
26124
26542
  var PairingError = class extends Error {
26125
26543
  state;
26126
26544
  constructor(state2, message) {
@@ -26160,7 +26578,15 @@ async function pairDevice(options) {
26160
26578
  headers: { "content-type": "application/json" },
26161
26579
  body: JSON.stringify({ code, public_key: publicKeyB64u(key), display_name: name3, platform: platform2, capabilities: [LIFECYCLE_CAPABILITY] })
26162
26580
  }), "Pairing offer"));
26163
- options.onOffered?.({ fingerprint, pairing_id: offer.pairing_id });
26581
+ const offered = {
26582
+ pairing_id: offer.pairing_id,
26583
+ fingerprint,
26584
+ organization_name: displayText(offer.organization_name),
26585
+ inviter: displayText(offer.inviter, 120)
26586
+ };
26587
+ options.onOffered?.(offered);
26588
+ if (options.confirmOffer && !await options.confirmOffer(offered))
26589
+ throw new PairingError("cancelled", "Pairing was cancelled on this computer");
26164
26590
  const deadline = Date.now() + (options.timeoutMs ?? 11 * 6e4);
26165
26591
  const query = new URLSearchParams({ pairing_id: offer.pairing_id }).toString();
26166
26592
  const pollInit = { method: "GET", headers: { [POLL_TOKEN_HEADER]: offer.poll_token } };
@@ -26185,6 +26611,10 @@ async function pairDevice(options) {
26185
26611
  paired_at: (/* @__PURE__ */ new Date()).toISOString(),
26186
26612
  key_store: options.keyStore.descriptor
26187
26613
  };
26614
+ const previous = await loadIdentity(options.paths).catch(() => null);
26615
+ const cleared = await bindLocalGrants(options.paths, grantOwnerOf(identity), previous);
26616
+ if (hasLocalGrants(cleared))
26617
+ options.onLocalGrantsCleared?.(cleared);
26188
26618
  await options.onApproved?.();
26189
26619
  await saveIdentity(options.paths, identity);
26190
26620
  succeeded = true;
@@ -26246,79 +26676,134 @@ async function runConnect(link, deps, extraHosts = []) {
26246
26676
  dialogs.fail(friendly(error63));
26247
26677
  return 2;
26248
26678
  }
26679
+ let cancelled = false;
26249
26680
  try {
26250
26681
  const replacing = await deps.isPaired();
26251
- if (!await dialogs.confirmConnect(new URL(request.gateway).host, request.name, replacing)) {
26682
+ const host = new URL(request.gateway).host;
26683
+ if (!await dialogs.confirmConnect(host, request.name, replacing)) {
26252
26684
  deps.log("Connect cancelled.");
26253
26685
  return 0;
26254
26686
  }
26255
- const folders = await dialogs.chooseFolders();
26256
- const writable = folders.length > 0 ? await dialogs.askAllowChanges() : false;
26687
+ let folders = [];
26688
+ let writable = false;
26689
+ await deps.pair(request, replacing, async (offer) => {
26690
+ const view = {
26691
+ host,
26692
+ requestedName: request.name,
26693
+ replacing,
26694
+ organization: offer.organization_name,
26695
+ inviter: offer.inviter,
26696
+ fingerprint: offer.fingerprint,
26697
+ shared: await deps.localAccess()
26698
+ };
26699
+ if (!await dialogs.confirmOffer(view)) {
26700
+ cancelled = true;
26701
+ return false;
26702
+ }
26703
+ folders = await dialogs.chooseFolders();
26704
+ writable = folders.length > 0 ? await dialogs.askAllowChanges() : false;
26705
+ dialogs.notify("ConBridge", `Almost done. Go back to ConBridge in your browser and approve this Mac if it shows the fingerprint ${offer.fingerprint}.`);
26706
+ return true;
26707
+ });
26257
26708
  const skipped = [];
26258
26709
  for (const folder of folders) {
26259
26710
  try {
26260
- await deps.addFolder(folder, (0, import_node_path10.basename)(folder) || folder, writable);
26711
+ await deps.addFolder(folder, (0, import_node_path11.basename)(folder) || folder, writable);
26261
26712
  } catch (error63) {
26262
- skipped.push(`${(0, import_node_path10.basename)(folder) || folder}: ${friendly(error63)}`);
26713
+ skipped.push(`${(0, import_node_path11.basename)(folder) || folder}: ${friendly(error63)}`);
26263
26714
  }
26264
26715
  }
26265
26716
  if (skipped.length > 0)
26266
26717
  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
26718
  await deps.installService();
26270
26719
  dialogs.notify("ConBridge", "This Mac is connected. ConBridge keeps running in the background.");
26271
26720
  return 0;
26272
26721
  } catch (error63) {
26722
+ if (cancelled) {
26723
+ deps.log("Connect cancelled after the offer; this Mac was not connected.");
26724
+ return 0;
26725
+ }
26273
26726
  deps.log(`Connect failed: ${friendly(error63)}`);
26274
26727
  dialogs.fail("This Mac could not be connected.\n\n" + friendly(error63));
26275
26728
  return 1;
26276
26729
  }
26277
26730
  }
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?
26731
+ function connectStartText(host, requestedName, replacing) {
26732
+ return (replacing ? "This Mac is already connected. Connecting again replaces that connection.\n\n" : "") + `Connect this Mac to ConBridge?
26291
26733
 
26292
- Your AI apps can use only the folders you choose, with the permissions you set in ConBridge.
26734
+ Before anything is shared, the next window shows which organization invited this Mac and its device fingerprint.
26293
26735
 
26294
26736
  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);
26737
+ Requested name: ${requestedName}`;
26738
+ }
26739
+ function connectOfferText(view) {
26740
+ const lines5 = [];
26741
+ if (view.replacing)
26742
+ lines5.push("This Mac is already connected. Connecting again replaces that connection.", "");
26743
+ lines5.push("Connect this Mac to this ConBridge organization?", "");
26744
+ lines5.push(`Organization: ${view.organization !== null ? `"${view.organization}"` : "organization not shown by this server"}`);
26745
+ lines5.push(`Invited by: ${view.inviter ?? "not shown by this server"}`);
26746
+ lines5.push(`Device fingerprint: ${view.fingerprint}`);
26747
+ lines5.push(`Requested name: ${view.requestedName}`);
26748
+ lines5.push(`Address: ${view.host}`, "");
26749
+ lines5.push("Continue only if you know this organization and ConBridge in your browser shows the same fingerprint.", "");
26750
+ const shared = describeLocalGrants(view.shared);
26751
+ if (shared.length === 0) {
26752
+ lines5.push("Nothing is shared from this Mac yet. You choose folders next.");
26753
+ } else {
26754
+ lines5.push("Already shared from this Mac:", ...shared.map((line) => `- ${line}`));
26755
+ 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
26756
  }
26317
- };
26757
+ return lines5.join("\n");
26758
+ }
26759
+ function appleScriptString(value) {
26760
+ return '"' + value.replace(/[\\"]/g, "\\$&").replace(/\r?\n/g, '" & linefeed & "') + '"';
26761
+ }
26762
+ var osascript = (script, timeoutMs) => new Promise((resolve10) => {
26763
+ (0, import_node_child_process6.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
26764
+ resolve10({ ok: !error63, stdout: stdout ?? "" });
26765
+ });
26766
+ });
26767
+ function pressed(result2, button) {
26768
+ return result2.ok && result2.stdout.includes(`button returned:${button}`) && !/gave up:true/.test(result2.stdout);
26769
+ }
26770
+ function createMacConnectDialogs(run2 = osascript) {
26771
+ return {
26772
+ async confirmConnect(host, requestedName, replacing) {
26773
+ const text6 = connectStartText(host, requestedName, replacing);
26774
+ 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);
26775
+ return pressed(result2, "Continue");
26776
+ },
26777
+ async confirmOffer(view) {
26778
+ const text6 = connectOfferText(view);
26779
+ 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);
26780
+ return pressed(result2, "Connect");
26781
+ },
26782
+ async chooseFolders() {
26783
+ 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';
26784
+ const result2 = await run2(script, 6e5);
26785
+ if (!result2.ok)
26786
+ return [];
26787
+ return result2.stdout.split("\n").map((line) => line.trim().replace(/\/$/, "")).filter(Boolean);
26788
+ },
26789
+ async askAllowChanges() {
26790
+ 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.";
26791
+ 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);
26792
+ return pressed(result2, "Allow changes");
26793
+ },
26794
+ notify(title, message) {
26795
+ void run2(`display notification ${appleScriptString(message)} with title ${appleScriptString(title)}`, 1e4);
26796
+ },
26797
+ fail(message) {
26798
+ void run2(`display dialog ${appleScriptString(message)} with title "ConBridge" buttons {"OK"} default button "OK" with icon caution`, 12e4);
26799
+ }
26800
+ };
26801
+ }
26802
+ var macConnectDialogs = createMacConnectDialogs();
26318
26803
 
26319
26804
  // dist/journal.js
26320
- var import_promises8 = require("node:fs/promises");
26321
- var import_node_path11 = require("node:path");
26805
+ var import_promises9 = require("node:fs/promises");
26806
+ var import_node_path12 = require("node:path");
26322
26807
  var storedResultSchema = external_exports.strictObject({
26323
26808
  state: external_exports.enum(["SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED"]),
26324
26809
  executed: external_exports.boolean(),
@@ -26393,7 +26878,7 @@ var Journal = class _Journal {
26393
26878
  const journal = new _Journal(path);
26394
26879
  let text6 = "";
26395
26880
  try {
26396
- text6 = await (0, import_promises8.readFile)(path, "utf8");
26881
+ text6 = await (0, import_promises9.readFile)(path, "utf8");
26397
26882
  } catch (error63) {
26398
26883
  if (errorCode2(error63) !== "ENOENT")
26399
26884
  throw error63;
@@ -26451,7 +26936,7 @@ var Journal = class _Journal {
26451
26936
  async #append(entry) {
26452
26937
  const line = JSON.stringify(entrySchema.parse(entry)) + "\n";
26453
26938
  await this.#serialize(async () => {
26454
- const handle = await (0, import_promises8.open)(this.#path, "a", 384);
26939
+ const handle = await (0, import_promises9.open)(this.#path, "a", 384);
26455
26940
  try {
26456
26941
  await handle.appendFile(line, "utf8");
26457
26942
  await handle.sync();
@@ -26501,7 +26986,7 @@ var Journal = class _Journal {
26501
26986
  return this.#serialize(async () => {
26502
26987
  let text6 = "";
26503
26988
  try {
26504
- text6 = await (0, import_promises8.readFile)(this.#path, "utf8");
26989
+ text6 = await (0, import_promises9.readFile)(this.#path, "utf8");
26505
26990
  } catch (error63) {
26506
26991
  if (errorCode2(error63) === "ENOENT")
26507
26992
  return;
@@ -26536,24 +27021,24 @@ var Journal = class _Journal {
26536
27021
  const lines5 = kept.map((entry) => JSON.stringify(entry) + "\n");
26537
27022
  if (watermark !== null)
26538
27023
  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);
27024
+ const temp = (0, import_node_path12.join)((0, import_node_path12.dirname)(this.#path), `.${(0, import_node_path12.basename)(this.#path)}.${randomToken(6)}.tmp`);
27025
+ const handle = await (0, import_promises9.open)(temp, "wx", 384);
26541
27026
  try {
26542
27027
  await handle.writeFile(lines5.join(""), "utf8");
26543
27028
  await handle.sync();
26544
27029
  } catch (error63) {
26545
27030
  await handle.close().catch(() => void 0);
26546
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27031
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26547
27032
  throw error63;
26548
27033
  }
26549
27034
  await handle.close();
26550
27035
  try {
26551
- await (0, import_promises8.rename)(temp, this.#path);
27036
+ await (0, import_promises9.rename)(temp, this.#path);
26552
27037
  } catch (error63) {
26553
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27038
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26554
27039
  throw error63;
26555
27040
  }
26556
- await fsyncDirectory((0, import_node_path11.dirname)(this.#path));
27041
+ await fsyncDirectory((0, import_node_path12.dirname)(this.#path));
26557
27042
  this.#records.clear();
26558
27043
  this.#nonces.clear();
26559
27044
  for (const entry of kept)
@@ -26565,22 +27050,22 @@ var Journal = class _Journal {
26565
27050
  };
26566
27051
 
26567
27052
  // dist/install.js
26568
- var import_promises9 = require("node:fs/promises");
26569
- var import_node_path12 = require("node:path");
27053
+ var import_promises10 = require("node:fs/promises");
27054
+ var import_node_path13 = require("node:path");
26570
27055
  var import_node_url2 = require("node:url");
26571
27056
  var RUNTIME_ENTRY = "conbridge-agent.cjs";
26572
27057
  function runtimeDir(stateDir) {
26573
- return (0, import_node_path12.join)(stateDir, "runtime");
27058
+ return (0, import_node_path13.join)(stateDir, "runtime");
26574
27059
  }
26575
27060
  function runtimeEntry(stateDir) {
26576
- return (0, import_node_path12.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
27061
+ return (0, import_node_path13.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
26577
27062
  }
26578
27063
  function currentEntry() {
26579
27064
  return (0, import_node_url2.fileURLToPath)(__conbridge_import_meta_url);
26580
27065
  }
26581
27066
  async function sameBytes(a, b) {
26582
27067
  try {
26583
- const [left, right] = await Promise.all([(0, import_promises9.readFile)(a), (0, import_promises9.readFile)(b)]);
27068
+ const [left, right] = await Promise.all([(0, import_promises10.readFile)(a), (0, import_promises10.readFile)(b)]);
26584
27069
  return left.equals(right);
26585
27070
  } catch {
26586
27071
  return false;
@@ -26589,11 +27074,11 @@ async function sameBytes(a, b) {
26589
27074
  async function copyAtomic(from, to, mode) {
26590
27075
  const temp = `${to}.${randomToken(6)}.tmp`;
26591
27076
  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);
27077
+ await (0, import_promises10.copyFile)(from, temp);
27078
+ await (0, import_promises10.chmod)(temp, mode);
27079
+ await (0, import_promises10.rename)(temp, to);
26595
27080
  } catch (error63) {
26596
- await (0, import_promises9.unlink)(temp).catch(() => void 0);
27081
+ await (0, import_promises10.unlink)(temp).catch(() => void 0);
26597
27082
  throw error63;
26598
27083
  }
26599
27084
  }
@@ -26602,21 +27087,21 @@ async function installRuntime(stateDir, from = {}) {
26602
27087
  const sourceDir = from.codeDir ?? codeDirectory();
26603
27088
  const dir = runtimeDir(stateDir);
26604
27089
  const entry = runtimeEntry(stateDir);
26605
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
26606
- await (0, import_promises9.chmod)(dir, 448);
27090
+ await (0, import_promises10.mkdir)(dir, { recursive: true, mode: 448 });
27091
+ await (0, import_promises10.chmod)(dir, 448);
26607
27092
  let changed = false;
26608
27093
  if (!await sameBytes(source, entry)) {
26609
27094
  await copyAtomic(source, entry, 384);
26610
27095
  changed = true;
26611
27096
  }
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);
27097
+ const helper = (0, import_node_path13.join)(sourceDir, KEYCHAIN_HELPER_NAME);
27098
+ const helperTarget = (0, import_node_path13.join)(dir, KEYCHAIN_HELPER_NAME);
27099
+ const hasHelper = await (0, import_promises10.stat)(helper).then((info) => info.isFile(), () => false);
26615
27100
  if (hasHelper && !await sameBytes(helper, helperTarget)) {
26616
27101
  await copyAtomic(helper, helperTarget, 493);
26617
27102
  changed = true;
26618
27103
  } else if (!hasHelper) {
26619
- await (0, import_promises9.unlink)(helperTarget).catch((error63) => {
27104
+ await (0, import_promises10.unlink)(helperTarget).catch((error63) => {
26620
27105
  if (errorCode2(error63) !== "ENOENT")
26621
27106
  throw error63;
26622
27107
  });
@@ -26626,26 +27111,26 @@ async function installRuntime(stateDir, from = {}) {
26626
27111
  async function snapshotRuntime(stateDir) {
26627
27112
  const dir = runtimeDir(stateDir);
26628
27113
  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 });
27114
+ await (0, import_promises10.rm)(backup, { recursive: true, force: true });
27115
+ await (0, import_promises10.mkdir)(backup, { recursive: true, mode: 448 });
26631
27116
  const saved = /* @__PURE__ */ new Map();
26632
27117
  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);
27118
+ const info = await (0, import_promises10.stat)((0, import_node_path13.join)(dir, name3)).catch(() => null);
26634
27119
  if (!info?.isFile())
26635
27120
  continue;
26636
- await (0, import_promises9.copyFile)((0, import_node_path12.join)(dir, name3), (0, import_node_path12.join)(backup, name3));
27121
+ await (0, import_promises10.copyFile)((0, import_node_path13.join)(dir, name3), (0, import_node_path13.join)(backup, name3));
26637
27122
  saved.set(name3, info.mode & 511);
26638
27123
  }
26639
- const discard = () => (0, import_promises9.rm)(backup, { recursive: true, force: true });
27124
+ const discard = () => (0, import_promises10.rm)(backup, { recursive: true, force: true });
26640
27125
  return {
26641
27126
  async restore() {
26642
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
27127
+ await (0, import_promises10.mkdir)(dir, { recursive: true, mode: 448 });
26643
27128
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
26644
27129
  const mode = saved.get(name3);
26645
27130
  if (mode !== void 0)
26646
- await copyAtomic((0, import_node_path12.join)(backup, name3), (0, import_node_path12.join)(dir, name3), mode);
27131
+ await copyAtomic((0, import_node_path13.join)(backup, name3), (0, import_node_path13.join)(dir, name3), mode);
26647
27132
  else
26648
- await (0, import_promises9.unlink)((0, import_node_path12.join)(dir, name3)).catch((error63) => {
27133
+ await (0, import_promises10.unlink)((0, import_node_path13.join)(dir, name3)).catch((error63) => {
26649
27134
  if (errorCode2(error63) !== "ENOENT")
26650
27135
  throw error63;
26651
27136
  });
@@ -26663,7 +27148,7 @@ async function runningFromRuntime(stateDir, entry = currentEntry()) {
26663
27148
  // dist/keepawake.js
26664
27149
  var import_node_child_process7 = require("node:child_process");
26665
27150
  var import_node_fs2 = require("node:fs");
26666
- var import_node_path13 = require("node:path");
27151
+ var import_node_path14 = require("node:path");
26667
27152
  var POWER_SUPPLY_DIR = "/sys/class/power_supply";
26668
27153
  var DISPLAY_SOCKET_DIRS = { x11: "/tmp/.X11-unix", runUser: "/run/user" };
26669
27154
  function entries(dir) {
@@ -26676,7 +27161,7 @@ function entries(dir) {
26676
27161
  function linuxDisplaySocket(env = process.env, dirs = DISPLAY_SOCKET_DIRS) {
26677
27162
  if (entries(dirs.x11).some((name3) => /^X\d+$/.test(name3)))
26678
27163
  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))];
27164
+ const runtimeDirs = [...env.XDG_RUNTIME_DIR ? [env.XDG_RUNTIME_DIR] : [], ...entries(dirs.runUser).map((uid) => (0, import_node_path14.join)(dirs.runUser, uid))];
26680
27165
  return runtimeDirs.some((dir) => entries(dir).some((name3) => /^wayland-\d+$/.test(name3)));
26681
27166
  }
26682
27167
  function powerSupplies(dir) {
@@ -26693,7 +27178,7 @@ function powerSupplies(dir) {
26693
27178
  return null;
26694
27179
  }
26695
27180
  };
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")) }));
27181
+ 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
27182
  }
26698
27183
  var defaultProbe = {
26699
27184
  hasBattery: () => powerSupplies(POWER_SUPPLY_DIR).some((supply) => supply.type === "Battery"),
@@ -26858,7 +27343,7 @@ function startKeepAwake(options = {}) {
26858
27343
  }
26859
27344
 
26860
27345
  // dist/lock.js
26861
- var import_promises10 = require("node:fs/promises");
27346
+ var import_promises11 = require("node:fs/promises");
26862
27347
  function alive(pid) {
26863
27348
  try {
26864
27349
  process.kill(pid, 0);
@@ -26869,7 +27354,7 @@ function alive(pid) {
26869
27354
  }
26870
27355
  async function readLockPid(path) {
26871
27356
  try {
26872
- const pid = Number.parseInt((await (0, import_promises10.readFile)(path, "utf8")).trim(), 10);
27357
+ const pid = Number.parseInt((await (0, import_promises11.readFile)(path, "utf8")).trim(), 10);
26873
27358
  return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
26874
27359
  } catch {
26875
27360
  return null;
@@ -26878,12 +27363,12 @@ async function readLockPid(path) {
26878
27363
  async function acquireLock(path) {
26879
27364
  for (let attempt = 0; attempt < 2; attempt += 1) {
26880
27365
  try {
26881
- const handle = await (0, import_promises10.open)(path, "wx", 384);
27366
+ const handle = await (0, import_promises11.open)(path, "wx", 384);
26882
27367
  await handle.writeFile(`${process.pid}
26883
27368
  `);
26884
27369
  await handle.close();
26885
27370
  return async () => {
26886
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27371
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26887
27372
  };
26888
27373
  } catch (error63) {
26889
27374
  if (errorCode2(error63) !== "EEXIST")
@@ -26891,19 +27376,19 @@ async function acquireLock(path) {
26891
27376
  const pid = await readLockPid(path);
26892
27377
  if (pid !== null)
26893
27378
  throw new Error(`Another agent is already running (pid ${pid})`);
26894
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27379
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26895
27380
  }
26896
27381
  }
26897
27382
  throw new Error("Could not acquire the agent lock");
26898
27383
  }
26899
27384
 
26900
27385
  // dist/envelope.js
26901
- var import_node_crypto6 = require("node:crypto");
26902
- function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto6.randomUUID)()) {
27386
+ var import_node_crypto7 = require("node:crypto");
27387
+ function buildEnvelope(identity, kind, taskId2, body, correlationId = (0, import_node_crypto7.randomUUID)()) {
26903
27388
  return {
26904
27389
  version: 1,
26905
27390
  kind,
26906
- message_id: (0, import_node_crypto6.randomUUID)(),
27391
+ message_id: (0, import_node_crypto7.randomUUID)(),
26907
27392
  correlation_id: correlationId,
26908
27393
  tenant_id: identity.tenant_id,
26909
27394
  user_id: identity.user_id,
@@ -26947,13 +27432,13 @@ function excerpt(value) {
26947
27432
  var import_node_os14 = require("node:os");
26948
27433
 
26949
27434
  // dist/dispatcher.js
26950
- var import_node_crypto8 = require("node:crypto");
27435
+ var import_node_crypto9 = require("node:crypto");
26951
27436
 
26952
27437
  // dist/fileops.js
26953
27438
  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");
27439
+ var import_promises12 = require("node:fs/promises");
27440
+ var import_node_crypto8 = require("node:crypto");
27441
+ var import_node_path15 = require("node:path");
26957
27442
 
26958
27443
  // dist/glob.js
26959
27444
  function globToRegExp(glob) {
@@ -26981,18 +27466,29 @@ function globToRegExp(glob) {
26981
27466
  index += 1;
26982
27467
  }
26983
27468
  }
26984
- return new RegExp("^" + source + "$", "i");
27469
+ return new RegExp("^" + source + "$", "ius");
27470
+ }
27471
+ function foldPathText(text6) {
27472
+ return text6.normalize("NFKC").toUpperCase().toLowerCase().replace(/\u00df/gu, "ss");
26985
27473
  }
26986
27474
  var DenyMatcher = class {
26987
27475
  #patterns;
26988
27476
  constructor(globs) {
26989
- this.#patterns = globs.map(globToRegExp);
27477
+ this.#patterns = [...new Set(globs.flatMap((glob) => [glob, foldPathText(glob)]))].map(globToRegExp);
26990
27478
  }
26991
- /** True when the path or any of its ancestor directories matches a deny glob. */
27479
+ /**
27480
+ * True when the path or any of its ancestor directories matches a deny glob,
27481
+ * as written or folded (see {@link foldPathText}).
27482
+ */
26992
27483
  denies(relativePath3) {
26993
27484
  if (relativePath3 === "")
26994
27485
  return false;
26995
- const segments = relativePath3.split("/");
27486
+ const folded = foldPathText(relativePath3);
27487
+ const asciiLower2 = relativePath3.replace(/[A-Z]/gu, (letter) => letter.toLowerCase());
27488
+ return this.#matches(relativePath3) || folded !== asciiLower2 && this.#matches(folded);
27489
+ }
27490
+ #matches(path) {
27491
+ const segments = path.split("/");
26996
27492
  for (let length = 1; length <= segments.length; length += 1) {
26997
27493
  const prefix = segments.slice(0, length).join("/");
26998
27494
  if (this.#patterns.some((pattern) => pattern.test(prefix)))
@@ -27008,6 +27504,7 @@ var MAX_SEARCH_RESULTS = 100;
27008
27504
  var MAX_SEARCH_BYTES_PER_FILE = 2 * 1024 * 1024;
27009
27505
  var MAX_SEARCH_FILES = 1e4;
27010
27506
  var MAX_SEARCH_TOTAL_BYTES = 64 * 1024 * 1024;
27507
+ var MAX_MOVE_TREE_ENTRIES = 1e4;
27011
27508
  var PREVIEW_CHARS = 200;
27012
27509
  var READ_BLOCK = 64 * 1024;
27013
27510
  var OPEN_READ_FLAGS = import_node_fs3.constants.O_RDONLY | import_node_fs3.constants.O_NOFOLLOW | import_node_fs3.constants.O_NONBLOCK;
@@ -27025,7 +27522,8 @@ var WIRE_CODE = {
27025
27522
  EDIT_MISMATCH: "INVALID_MESSAGE",
27026
27523
  ALREADY_EXISTS: "INVALID_MESSAGE",
27027
27524
  NOT_EMPTY: "INVALID_MESSAGE",
27028
- TOO_LARGE: "SIZE_LIMIT"
27525
+ TOO_LARGE: "SIZE_LIMIT",
27526
+ OWNERSHIP_WOULD_CHANGE: "POLICY_DENIED"
27029
27527
  };
27030
27528
  var FileOpError = class extends Error {
27031
27529
  reason;
@@ -27044,6 +27542,8 @@ function normalizeRelativePath(input2) {
27044
27542
  throw new FileOpError("PATH_INVALID", "Path is invalid");
27045
27543
  if (input2.includes("\0"))
27046
27544
  throw new FileOpError("PATH_INVALID", "Path contains NUL");
27545
+ if (!isSafePathText(input2))
27546
+ throw new FileOpError("PATH_INVALID", "Path contains control, bidi or invisible characters");
27047
27547
  if (input2.startsWith("/") || input2.startsWith("\\") || /^[A-Za-z]:/.test(input2) || input2.startsWith("~")) {
27048
27548
  throw new FileOpError("PATH_INVALID", "Path must be relative to the root");
27049
27549
  }
@@ -27097,7 +27597,7 @@ function decodeText(bytes3) {
27097
27597
  }
27098
27598
  }
27099
27599
  async function hashHandle(handle) {
27100
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27600
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
27101
27601
  const buffer = Buffer.allocUnsafe(READ_BLOCK);
27102
27602
  let position2 = 0;
27103
27603
  for (; ; ) {
@@ -27110,7 +27610,7 @@ async function hashHandle(handle) {
27110
27610
  return hash2.digest("hex");
27111
27611
  }
27112
27612
  function sha256OfBytes(bytes3) {
27113
- return (0, import_node_crypto7.createHash)("sha256").update(bytes3).digest("hex");
27613
+ return (0, import_node_crypto8.createHash)("sha256").update(bytes3).digest("hex");
27114
27614
  }
27115
27615
  var RootedFs = class {
27116
27616
  #root;
@@ -27130,7 +27630,7 @@ var RootedFs = class {
27130
27630
  return;
27131
27631
  const forms = /* @__PURE__ */ new Set();
27132
27632
  for (const path of this.#protectedInput) {
27133
- forms.add((0, import_node_path14.resolve)(path));
27633
+ forms.add((0, import_node_path15.resolve)(path));
27134
27634
  forms.add(await realpathLenient(path));
27135
27635
  }
27136
27636
  this.#protected = [...forms];
@@ -27140,7 +27640,7 @@ var RootedFs = class {
27140
27640
  #blockedReal(real) {
27141
27641
  if (this.#protected.some((dir) => isSameOrInside(dir, real)))
27142
27642
  return true;
27143
- return this.#hardDeny.denies(real.split(import_node_path14.sep).filter((segment) => segment !== "").join("/"));
27643
+ return this.#hardDeny.denies(real.split(import_node_path15.sep).filter((segment) => segment !== "").join("/"));
27144
27644
  }
27145
27645
  #checkReal(real) {
27146
27646
  if (this.#blockedReal(real))
@@ -27149,8 +27649,8 @@ var RootedFs = class {
27149
27649
  async #rootReal() {
27150
27650
  await this.#loadProtected();
27151
27651
  try {
27152
- const real = await (0, import_promises11.realpath)(this.#root.path);
27153
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
27652
+ const real = await (0, import_promises12.realpath)(this.#root.path);
27653
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27154
27654
  throw new FileOpError("NOT_FOUND", "Root is unavailable");
27155
27655
  return real;
27156
27656
  } catch (error63) {
@@ -27160,11 +27660,11 @@ var RootedFs = class {
27160
27660
  }
27161
27661
  }
27162
27662
  #inside(rootReal, real) {
27163
- const prefix = rootReal.endsWith(import_node_path14.sep) ? rootReal : rootReal + import_node_path14.sep;
27663
+ const prefix = rootReal.endsWith(import_node_path15.sep) ? rootReal : rootReal + import_node_path15.sep;
27164
27664
  return real === rootReal || real.startsWith(prefix);
27165
27665
  }
27166
27666
  #relativeOf(rootReal, real) {
27167
- return (0, import_node_path14.relative)(rootReal, real).split(import_node_path14.sep).join("/");
27667
+ return (0, import_node_path15.relative)(rootReal, real).split(import_node_path15.sep).join("/");
27168
27668
  }
27169
27669
  #checkDeny(rel) {
27170
27670
  if (this.#deny.denies(rel))
@@ -27177,7 +27677,7 @@ var RootedFs = class {
27177
27677
  const rootReal = await this.#rootReal();
27178
27678
  let real;
27179
27679
  try {
27180
- real = await (0, import_promises11.realpath)((0, import_node_path14.join)(rootReal, rel));
27680
+ real = await (0, import_promises12.realpath)((0, import_node_path15.join)(rootReal, rel));
27181
27681
  } catch (error63) {
27182
27682
  throw mapFsError(error63, rel);
27183
27683
  }
@@ -27196,10 +27696,10 @@ var RootedFs = class {
27196
27696
  async #openVerified(rootReal, real) {
27197
27697
  let handle;
27198
27698
  try {
27199
- const before = await (0, import_promises11.lstat)(real);
27699
+ const before = await (0, import_promises12.lstat)(real);
27200
27700
  if (!before.isFile())
27201
27701
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
27202
- handle = await (0, import_promises11.open)(real, OPEN_READ_FLAGS);
27702
+ handle = await (0, import_promises12.open)(real, OPEN_READ_FLAGS);
27203
27703
  } catch (error63) {
27204
27704
  throw mapFsError(error63, "");
27205
27705
  }
@@ -27207,8 +27707,8 @@ var RootedFs = class {
27207
27707
  const info = await handle.stat();
27208
27708
  if (!info.isFile())
27209
27709
  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);
27710
+ const again = await (0, import_promises12.realpath)(real);
27711
+ const pathInfo = await (0, import_promises12.stat)(again);
27212
27712
  if (again !== real || !this.#inside(rootReal, again) || pathInfo.ino !== info.ino || pathInfo.dev !== info.dev) {
27213
27713
  throw new FileOpError("PATH_ESCAPE", "Path changed while it was being opened");
27214
27714
  }
@@ -27227,7 +27727,7 @@ var RootedFs = class {
27227
27727
  try {
27228
27728
  if (!info.isFile())
27229
27729
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file", { path: rel });
27230
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27730
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
27231
27731
  const kept = [];
27232
27732
  let keptBytes = 0;
27233
27733
  let size = 0;
@@ -27260,18 +27760,18 @@ var RootedFs = class {
27260
27760
  async list(input2) {
27261
27761
  const { rel, real } = await this.resolveExisting(input2);
27262
27762
  try {
27263
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
27763
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27264
27764
  throw new FileOpError("NOT_A_DIRECTORY", "Path is not a directory", { path: rel });
27265
- const dir = await (0, import_promises11.opendir)(real);
27765
+ const dir = await (0, import_promises12.opendir)(real);
27266
27766
  const names2 = [];
27267
27767
  for await (const entry of dir) {
27268
27768
  const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
27269
27769
  if (this.#deny.denies(childRel))
27270
27770
  continue;
27271
- const childReal = (0, import_node_path14.join)(real, entry.name);
27771
+ const childReal = (0, import_node_path15.join)(real, entry.name);
27272
27772
  if (this.#blockedReal(childReal))
27273
27773
  continue;
27274
- if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises11.realpath)(childReal).catch(() => childReal)))
27774
+ if (entry.isSymbolicLink() && this.#blockedReal(await (0, import_promises12.realpath)(childReal).catch(() => childReal)))
27275
27775
  continue;
27276
27776
  const type = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "other";
27277
27777
  names2.push({ name: entry.name, type });
@@ -27280,7 +27780,7 @@ var RootedFs = class {
27280
27780
  const entries2 = [];
27281
27781
  for (const item of names2.slice(0, MAX_LIST_ENTRIES)) {
27282
27782
  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);
27783
+ const size = await (0, import_promises12.lstat)((0, import_node_path15.join)(real, item.name)).then((s) => s.size, () => void 0);
27284
27784
  entries2.push(size === void 0 ? item : { ...item, size });
27285
27785
  } else
27286
27786
  entries2.push(item);
@@ -27303,7 +27803,7 @@ var RootedFs = class {
27303
27803
  return;
27304
27804
  let resolved;
27305
27805
  try {
27306
- resolved = await (0, import_promises11.realpath)(fileReal);
27806
+ resolved = await (0, import_promises12.realpath)(fileReal);
27307
27807
  } catch {
27308
27808
  return;
27309
27809
  }
@@ -27311,9 +27811,9 @@ var RootedFs = class {
27311
27811
  return;
27312
27812
  let handle;
27313
27813
  try {
27314
- if (!(await (0, import_promises11.lstat)(resolved)).isFile())
27814
+ if (!(await (0, import_promises12.lstat)(resolved)).isFile())
27315
27815
  return;
27316
- handle = await (0, import_promises11.open)(resolved, OPEN_READ_FLAGS);
27816
+ handle = await (0, import_promises12.open)(resolved, OPEN_READ_FLAGS);
27317
27817
  } catch {
27318
27818
  return;
27319
27819
  }
@@ -27355,7 +27855,7 @@ var RootedFs = class {
27355
27855
  await handle.close().catch(() => void 0);
27356
27856
  }
27357
27857
  };
27358
- const start = await (0, import_promises11.stat)(real).catch((error63) => {
27858
+ const start = await (0, import_promises12.stat)(real).catch((error63) => {
27359
27859
  throw mapFsError(error63, rel);
27360
27860
  });
27361
27861
  if (start.isFile()) {
@@ -27366,7 +27866,7 @@ var RootedFs = class {
27366
27866
  const current = queue.shift();
27367
27867
  let entries2;
27368
27868
  try {
27369
- const dir = await (0, import_promises11.opendir)(current.real);
27869
+ const dir = await (0, import_promises12.opendir)(current.real);
27370
27870
  entries2 = [];
27371
27871
  for await (const entry of dir) {
27372
27872
  entries2.push({ name: entry.name, file: entry.isFile(), dir: entry.isDirectory() });
@@ -27381,7 +27881,7 @@ var RootedFs = class {
27381
27881
  const childRel = current.rel === "" ? entry.name : `${current.rel}/${entry.name}`;
27382
27882
  if (this.#deny.denies(childRel))
27383
27883
  continue;
27384
- const childReal = (0, import_node_path14.join)(current.real, entry.name);
27884
+ const childReal = (0, import_node_path15.join)(current.real, entry.name);
27385
27885
  if (this.#blockedReal(childReal))
27386
27886
  continue;
27387
27887
  if (entry.dir)
@@ -27403,10 +27903,10 @@ var RootedFs = class {
27403
27903
  async #currentHash(rootReal, target) {
27404
27904
  let info;
27405
27905
  try {
27406
- info = await (0, import_promises11.lstat)(target);
27906
+ info = await (0, import_promises12.lstat)(target);
27407
27907
  } catch (error63) {
27408
27908
  if (errorCode2(error63) === "ENOENT")
27409
- return { sha256: null, mode: null };
27909
+ return { sha256: null, mode: null, uid: null, gid: null };
27410
27910
  throw mapFsError(error63, "");
27411
27911
  }
27412
27912
  if (info.isSymbolicLink())
@@ -27415,7 +27915,7 @@ var RootedFs = class {
27415
27915
  throw new FileOpError("NOT_A_FILE", "Target is not a regular file");
27416
27916
  const { handle } = await this.#openVerified(rootReal, target);
27417
27917
  try {
27418
- return { sha256: await hashHandle(handle), mode: info.mode & 4095 };
27918
+ return { sha256: await hashHandle(handle), mode: info.mode & 4095, uid: info.uid, gid: info.gid };
27419
27919
  } finally {
27420
27920
  await handle.close().catch(() => void 0);
27421
27921
  }
@@ -27435,8 +27935,8 @@ var RootedFs = class {
27435
27935
  const name3 = slash < 0 ? rel : rel.slice(slash + 1);
27436
27936
  let parentReal;
27437
27937
  try {
27438
- parentReal = await (0, import_promises11.realpath)((0, import_node_path14.join)(rootReal, parentRel));
27439
- if (!(await (0, import_promises11.stat)(parentReal)).isDirectory())
27938
+ parentReal = await (0, import_promises12.realpath)((0, import_node_path15.join)(rootReal, parentRel));
27939
+ if (!(await (0, import_promises12.stat)(parentReal)).isDirectory())
27440
27940
  throw new FileOpError("NOT_A_DIRECTORY", "Parent is not a directory");
27441
27941
  } catch (error63) {
27442
27942
  if (errorCode2(error63) === "ENOENT")
@@ -27447,44 +27947,76 @@ var RootedFs = class {
27447
27947
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27448
27948
  const parentRealRel = this.#relativeOf(rootReal, parentReal);
27449
27949
  this.#checkDeny(parentRealRel === "" ? name3 : `${parentRealRel}/${name3}`);
27450
- const target = (0, import_node_path14.join)(parentReal, name3);
27950
+ const target = (0, import_node_path15.join)(parentReal, name3);
27451
27951
  this.#checkReal(target);
27452
27952
  return { rel, rootReal, parentReal, name: name3, target };
27453
27953
  }
27454
- /** Temp file in the same directory, fsync, re-check the version, rename over the target. */
27954
+ /**
27955
+ * Give the temp file that replaces an existing file the file's owner and group, so a fix keeps a
27956
+ * www-data:www-data file readable by the web server. Ownership of a new inode can only be changed with chown: a
27957
+ * root agent can always set both; another agent user can set a group it belongs to but cannot give a file away.
27958
+ * When the owner would change (the agent does not own the file, or the file system ignored the chown) the write is
27959
+ * refused with OWNERSHIP_WOULD_CHANGE before anything is renamed. When only the group cannot be kept, the write
27960
+ * goes ahead and returns true (reported as `ownership_changed`). Runs before chmod: chown clears setuid/setgid.
27961
+ */
27962
+ async #keepOwnership(handle, before, rel) {
27963
+ if (before.uid === null || before.gid === null)
27964
+ return false;
27965
+ let temp = await handle.stat();
27966
+ if (temp.uid !== before.uid) {
27967
+ await handle.chown(before.uid, before.gid).catch(() => void 0);
27968
+ temp = await handle.stat();
27969
+ if (temp.uid !== before.uid) {
27970
+ 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 });
27971
+ }
27972
+ }
27973
+ if (temp.gid !== before.gid) {
27974
+ await handle.chown(-1, before.gid).catch(() => void 0);
27975
+ temp = await handle.stat();
27976
+ }
27977
+ return temp.gid !== before.gid;
27978
+ }
27979
+ /**
27980
+ * Temp file in the same directory with the replaced file's owner, group and mode; fsync, re-check the version,
27981
+ * rename over the target. Returns true when the file's group could not be kept.
27982
+ */
27455
27983
  async #replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3) {
27456
- const temp = (0, import_node_path14.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
27984
+ const temp = (0, import_node_path15.join)(parentReal, `.${name3}.conbridge-${randomToken(8)}.tmp`);
27457
27985
  let handle;
27458
27986
  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);
27987
+ 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
27988
  } catch (error63) {
27461
27989
  throw mapFsError(error63, rel);
27462
27990
  }
27463
27991
  let renamed = false;
27992
+ let groupLost = false;
27464
27993
  try {
27465
27994
  try {
27995
+ if (before.sha256 !== null)
27996
+ groupLost = await this.#keepOwnership(handle, before, rel);
27997
+ await handle.writeFile(bytes3);
27466
27998
  if (before.mode !== null)
27467
27999
  await handle.chmod(before.mode);
27468
- await handle.writeFile(bytes3);
27469
28000
  await handle.sync();
27470
28001
  } finally {
27471
28002
  await handle.close();
27472
28003
  }
27473
- if (await (0, import_promises11.realpath)(parentReal) !== parentReal)
28004
+ if (await (0, import_promises12.realpath)(parentReal) !== parentReal)
27474
28005
  throw new FileOpError("PATH_ESCAPE", "Directory changed during write");
27475
28006
  const again = await this.#currentHash(rootReal, target);
27476
28007
  if (again.sha256 !== before.sha256) {
27477
28008
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed during write", { path: rel, current_sha256: again.sha256 });
27478
28009
  }
27479
- await (0, import_promises11.rename)(temp, target);
28010
+ await (0, import_promises12.rename)(temp, target);
27480
28011
  renamed = true;
27481
28012
  await fsyncDirectory(parentReal);
27482
28013
  } catch (error63) {
27483
28014
  throw mapFsError(error63, rel);
27484
28015
  } finally {
27485
28016
  if (!renamed)
27486
- await (0, import_promises11.unlink)(temp).catch(() => void 0);
28017
+ await (0, import_promises12.unlink)(temp).catch(() => void 0);
27487
28018
  }
28019
+ return groupLost;
27488
28020
  }
27489
28021
  #requireWritable() {
27490
28022
  if (!this.#root.writable)
@@ -27492,8 +28024,9 @@ var RootedFs = class {
27492
28024
  }
27493
28025
  /**
27494
28026
  * 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.
28027
+ * or be null with the file absent. Writes a temp file in the same directory
28028
+ * (with the replaced file's owner, group and mode), fsyncs it, re-checks the
28029
+ * version and renames over the target.
27497
28030
  */
27498
28031
  async write(input2, expectedSha256, content) {
27499
28032
  this.#requireWritable();
@@ -27503,15 +28036,16 @@ var RootedFs = class {
27503
28036
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: before.sha256 });
27504
28037
  }
27505
28038
  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 };
28039
+ const groupLost = await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
28040
+ const result2 = { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, created: before.sha256 === null };
28041
+ return groupLost ? { ...result2, ownership_changed: true } : result2;
27508
28042
  }
27509
28043
  /** Size, dates and type of a file or directory; files up to 8 MiB also get their sha256 (for edit and delete). */
27510
28044
  async info(input2) {
27511
28045
  const { rel, real, rootReal } = await this.resolveExisting(input2);
27512
28046
  let info;
27513
28047
  try {
27514
- info = await (0, import_promises11.lstat)(real);
28048
+ info = await (0, import_promises12.lstat)(real);
27515
28049
  } catch (error63) {
27516
28050
  throw mapFsError(error63, rel);
27517
28051
  }
@@ -27533,7 +28067,7 @@ var RootedFs = class {
27533
28067
  }
27534
28068
  }
27535
28069
  if (type === "directory") {
27536
- const entries2 = await (0, import_promises11.readdir)(real).then((names2) => names2.length, () => void 0);
28070
+ const entries2 = await (0, import_promises12.readdir)(real).then((names2) => names2.length, () => void 0);
27537
28071
  return entries2 === void 0 ? base2 : { ...base2, entries: entries2 };
27538
28072
  }
27539
28073
  return base2;
@@ -27570,8 +28104,9 @@ var RootedFs = class {
27570
28104
  throw new FileOpError("EDIT_MISMATCH", `old_text was found ${found} times, expected ${expectedReplacements}`, { path: rel, found });
27571
28105
  }
27572
28106
  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 };
28107
+ const groupLost = await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
28108
+ const result2 = { path: rel, sha256_after: sha256OfBytes(bytes3), bytes: bytes3.length, replacements: found };
28109
+ return groupLost ? { ...result2, ownership_changed: true } : result2;
27575
28110
  }
27576
28111
  /** Create a directory and its missing parents, each checked against the root and the deny rules. */
27577
28112
  async mkdir(input2) {
@@ -27583,14 +28118,14 @@ var RootedFs = class {
27583
28118
  let created = false;
27584
28119
  for (let index = 1; index <= segments.length; index += 1) {
27585
28120
  const { rootReal, target } = await this.#resolveNew(segments.slice(0, index).join("/"));
27586
- const existing = await (0, import_promises11.lstat)(target).catch(() => null);
28121
+ const existing = await (0, import_promises12.lstat)(target).catch(() => null);
27587
28122
  if (existing) {
27588
28123
  const segment = segments.slice(0, index).join("/");
27589
28124
  if (existing.isSymbolicLink()) {
27590
- const real = await (0, import_promises11.realpath)(target).catch(() => null);
28125
+ const real = await (0, import_promises12.realpath)(target).catch(() => null);
27591
28126
  if (real === null || !this.#inside(rootReal, real))
27592
28127
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: segment });
27593
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
28128
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27594
28129
  throw new FileOpError("ALREADY_EXISTS", "A file with that name exists", { path: segment });
27595
28130
  continue;
27596
28131
  }
@@ -27599,35 +28134,143 @@ var RootedFs = class {
27599
28134
  continue;
27600
28135
  }
27601
28136
  try {
27602
- await (0, import_promises11.mkdir)(target, { mode: 511 });
28137
+ await (0, import_promises12.mkdir)(target, { mode: 511 });
27603
28138
  } catch (error63) {
27604
28139
  if (errorCode2(error63) !== "EEXIST")
27605
28140
  throw mapFsError(error63, rel);
27606
28141
  }
27607
- if (!this.#inside(rootReal, await (0, import_promises11.realpath)(target)))
28142
+ if (!this.#inside(rootReal, await (0, import_promises12.realpath)(target)))
27608
28143
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27609
28144
  created = true;
27610
28145
  }
27611
28146
  return { path: rel, created };
27612
28147
  }
28148
+ /**
28149
+ * Walk a folder about to be moved, without following symlinks, and refuse (PATH_DENIED) when any entry, file or
28150
+ * folder, is denied at its current path or at the path it would get after the move: by the root-relative deny
28151
+ * globs (requested and real form) or by the absolute hard-deny/protected check `read` uses. More than
28152
+ * MAX_MOVE_TREE_ENTRIES entries, or a folder that cannot be read, refuses the move: unchecked content never moves.
28153
+ * `from.real` is the folder's real path (see #moveSource), so its real name is what the globs see.
28154
+ */
28155
+ async #checkMovedTree(from, dest) {
28156
+ const bases = [
28157
+ { rel: from.rel, realRel: this.#relativeOf(from.rootReal, from.real), real: from.real },
28158
+ { rel: dest.rel, realRel: this.#relativeOf(dest.rootReal, dest.target), real: dest.target }
28159
+ ];
28160
+ 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("/"))));
28161
+ const queue = [""];
28162
+ let seen = 0;
28163
+ while (queue.length > 0) {
28164
+ const dirSuffix = queue.shift();
28165
+ const dirReal = dirSuffix === "" ? from.real : (0, import_node_path15.join)(from.real, ...dirSuffix.split("/"));
28166
+ try {
28167
+ for await (const entry of await (0, import_promises12.opendir)(dirReal)) {
28168
+ seen += 1;
28169
+ if (seen > MAX_MOVE_TREE_ENTRIES) {
28170
+ throw new FileOpError("TOO_LARGE", `Folder has more than ${MAX_MOVE_TREE_ENTRIES} entries; move it on the computer itself`, { path: from.rel });
28171
+ }
28172
+ const suffix = dirSuffix === "" ? entry.name : `${dirSuffix}/${entry.name}`;
28173
+ if (denied(suffix)) {
28174
+ throw new FileOpError("PATH_DENIED", "Folder contains files blocked by a local deny rule", { path: from.rel });
28175
+ }
28176
+ let isDir = entry.isDirectory();
28177
+ if (!isDir && !entry.isFile() && !entry.isSymbolicLink() && !entry.isFIFO() && !entry.isSocket() && !entry.isBlockDevice() && !entry.isCharacterDevice()) {
28178
+ isDir = (await (0, import_promises12.lstat)((0, import_node_path15.join)(dirReal, entry.name))).isDirectory();
28179
+ }
28180
+ if (isDir)
28181
+ queue.push(suffix);
28182
+ }
28183
+ } catch (error63) {
28184
+ if (error63 instanceof FileOpError)
28185
+ throw error63;
28186
+ throw new FileOpError("IO_ERROR", "Folder contents could not be checked; nothing was moved", { path: from.rel });
28187
+ }
28188
+ }
28189
+ }
28190
+ /**
28191
+ * The entry a move would rename, judged under its real name. A case-insensitive file system (APFS by default,
28192
+ * NTFS, casefold ext4) resolves a typed alias to another entry: with a long s (U+017F), Kelvin sign (U+212A),
28193
+ * fi ligature (U+FB01) or sharp s (U+00DF) a typed name reaches `.aws`, `.kube`, `.config` or `.ssh`. The deny
28194
+ * rules must judge that entry, so they run on its real path: for a file or folder the native realpath
28195
+ * (case-correcting on macOS), for a symlink the parent's entry with the same inode (the link is not followed).
28196
+ * The typed name must then be that entry's own name (canonically equal Unicode is accepted), otherwise
28197
+ * PATH_INVALID: an alias never moves and never reaches an approval preview as a look-alike name.
28198
+ */
28199
+ async #moveSource(from, source) {
28200
+ let names2;
28201
+ try {
28202
+ names2 = await (0, import_promises12.readdir)(from.parentReal);
28203
+ } catch (error63) {
28204
+ throw mapFsError(error63, from.rel);
28205
+ }
28206
+ const typed = from.name.normalize("NFC");
28207
+ const sameName = (name3) => name3 === from.name || name3.normalize("NFC") === typed;
28208
+ let entry;
28209
+ let real;
28210
+ if (source.isSymbolicLink()) {
28211
+ const sameEntry = async (name3) => {
28212
+ const info = await (0, import_promises12.lstat)((0, import_node_path15.join)(from.parentReal, name3)).catch(() => null);
28213
+ return info !== null && info.isSymbolicLink() && info.ino === source.ino && info.dev === source.dev;
28214
+ };
28215
+ for (const name3 of names2.filter(sameName)) {
28216
+ if (await sameEntry(name3)) {
28217
+ entry = name3;
28218
+ break;
28219
+ }
28220
+ }
28221
+ if (entry === void 0) {
28222
+ for (const name3 of names2) {
28223
+ if (await sameEntry(name3)) {
28224
+ entry = name3;
28225
+ break;
28226
+ }
28227
+ }
28228
+ }
28229
+ if (entry === void 0)
28230
+ throw new FileOpError("PATH_ESCAPE", "Path changed while it was being moved", { path: from.rel });
28231
+ real = (0, import_node_path15.join)(from.parentReal, entry);
28232
+ } else {
28233
+ try {
28234
+ real = await (0, import_promises12.realpath)(from.target);
28235
+ } catch (error63) {
28236
+ throw mapFsError(error63, from.rel);
28237
+ }
28238
+ if (!this.#inside(from.rootReal, real))
28239
+ throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: from.rel });
28240
+ 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;
28241
+ }
28242
+ try {
28243
+ this.#checkDeny(this.#relativeOf(from.rootReal, real));
28244
+ this.#checkReal(real);
28245
+ } catch (error63) {
28246
+ throw error63 instanceof FileOpError ? new FileOpError(error63.reason, error63.message, { path: from.rel }) : error63;
28247
+ }
28248
+ if (entry === void 0 || !sameName(entry)) {
28249
+ throw new FileOpError("PATH_INVALID", "Path does not match the name on disk; use the exact name files.list shows", { path: from.rel });
28250
+ }
28251
+ return { path: (0, import_node_path15.join)(from.parentReal, entry), real };
28252
+ }
27613
28253
  /** Move or rename inside this root. The destination must not exist; a symlink is moved as itself. */
27614
28254
  async move(input2, to) {
27615
28255
  this.#requireWritable();
27616
28256
  const from = await this.#resolveNew(input2);
27617
- const source = await (0, import_promises11.lstat)(from.target).catch(() => null);
28257
+ const source = await (0, import_promises12.lstat)(from.target).catch(() => null);
27618
28258
  if (!source)
27619
28259
  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))) {
28260
+ const { path: sourcePath, real: sourceReal } = await this.#moveSource(from, source);
28261
+ const followed = source.isSymbolicLink() ? await (0, import_promises12.realpath)(sourcePath).catch(() => sourcePath) : sourceReal;
28262
+ if (this.#protected.some((path) => isSameOrInside(sourcePath, path) || isSameOrInside(followed, path))) {
27622
28263
  throw new FileOpError("PATH_DENIED", "Path contains files the agent protects", { path: from.rel });
27623
28264
  }
27624
28265
  const dest = await this.#resolveNew(to);
27625
- if (isSameOrInside(from.target, dest.target))
28266
+ if (isSameOrInside(sourcePath, dest.target))
27626
28267
  throw new FileOpError("PATH_INVALID", "Cannot move a folder into itself");
27627
- if (await (0, import_promises11.lstat)(dest.target).then(() => true, () => false))
28268
+ if (await (0, import_promises12.lstat)(dest.target).then(() => true, () => false))
27628
28269
  throw new FileOpError("ALREADY_EXISTS", "The destination already exists", { path: dest.rel });
28270
+ if (source.isDirectory())
28271
+ await this.#checkMovedTree({ rel: from.rel, rootReal: from.rootReal, real: sourceReal }, dest);
27629
28272
  try {
27630
- await (0, import_promises11.rename)(from.target, dest.target);
28273
+ await (0, import_promises12.rename)(sourcePath, dest.target);
27631
28274
  } catch (error63) {
27632
28275
  throw mapFsError(error63, from.rel);
27633
28276
  }
@@ -27638,14 +28281,14 @@ var RootedFs = class {
27638
28281
  async delete(input2, expectedSha256) {
27639
28282
  this.#requireWritable();
27640
28283
  const { rel, rootReal, target, parentReal } = await this.#resolveNew(input2);
27641
- const info = await (0, import_promises11.lstat)(target).catch(() => null);
28284
+ const info = await (0, import_promises12.lstat)(target).catch(() => null);
27642
28285
  if (!info)
27643
28286
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: rel });
27644
28287
  if (info.isDirectory()) {
27645
28288
  if (expectedSha256 !== null)
27646
28289
  throw new FileOpError("NOT_A_FILE", "Path is a directory; pass expected_sha256 null", { path: rel });
27647
28290
  try {
27648
- await (0, import_promises11.rmdir)(target);
28291
+ await (0, import_promises12.rmdir)(target);
27649
28292
  } catch (error63) {
27650
28293
  if (errorCode2(error63) === "ENOTEMPTY" || errorCode2(error63) === "EEXIST")
27651
28294
  throw new FileOpError("NOT_EMPTY", "Directory is not empty", { path: rel });
@@ -27659,7 +28302,7 @@ var RootedFs = class {
27659
28302
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: current.sha256 });
27660
28303
  }
27661
28304
  try {
27662
- await (0, import_promises11.unlink)(target);
28305
+ await (0, import_promises12.unlink)(target);
27663
28306
  } catch (error63) {
27664
28307
  throw mapFsError(error63, rel);
27665
28308
  }
@@ -27697,10 +28340,10 @@ async function verifyGrantAuthenticity(dispatch2, identity) {
27697
28340
  function actingUserId(dispatch2) {
27698
28341
  return dispatch2.grant.on_behalf_of ?? dispatch2.grant.user_id;
27699
28342
  }
27700
- function isExpired(dispatch2, nowMs) {
28343
+ function isExpired(dispatch2, gatewayNowMs) {
27701
28344
  const expires = Date.parse(dispatch2.grant.expires_at);
27702
28345
  const deadline = Date.parse(dispatch2.deadline_at);
27703
- return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= nowMs || deadline <= nowMs;
28346
+ return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= gatewayNowMs || deadline <= gatewayNowMs;
27704
28347
  }
27705
28348
  function isSupportedCapability(capability2) {
27706
28349
  return capabilityDefinition(capability2)?.connector === "desktop" && (isAgentCapability(capability2) || isDesktopCapability(capability2) || isSshCapability(capability2) || isShellCapability(capability2) || isDiagCapability(capability2));
@@ -27835,6 +28478,36 @@ function denialResult(denial) {
27835
28478
  output_excerpt: excerpt({ error: denial.code, reason: denial.reason, message: denial.message })
27836
28479
  };
27837
28480
  }
28481
+ var CHANGING_FILE_CAPABILITIES = /* @__PURE__ */ new Set(["files.write", "files.edit", "files.delete", "files.move", "files.mkdir"]);
28482
+ function confirmationFor(task) {
28483
+ const rootLabel = task.root.label;
28484
+ switch (task.capability) {
28485
+ case "files.write": {
28486
+ const payload = task.payload;
28487
+ return {
28488
+ action: "write",
28489
+ rootLabel,
28490
+ path: normalizeRelativePath(payload.path),
28491
+ bytes: Buffer.byteLength(payload.content, "utf8"),
28492
+ created: payload.expected_sha256 === null
28493
+ };
28494
+ }
28495
+ case "files.edit": {
28496
+ const payload = task.payload;
28497
+ return { action: "edit", rootLabel, path: normalizeRelativePath(payload.path), replacements: payload.expected_replacements };
28498
+ }
28499
+ case "files.delete":
28500
+ return { action: "delete", rootLabel, path: normalizeRelativePath(task.payload.path) };
28501
+ case "files.move": {
28502
+ const payload = task.payload;
28503
+ return { action: "move", rootLabel, path: normalizeRelativePath(payload.path), to: normalizeRelativePath(payload.to) };
28504
+ }
28505
+ case "files.mkdir":
28506
+ return { action: "mkdir", rootLabel, path: normalizeRelativePath(task.payload.path) };
28507
+ default:
28508
+ throw new FileOpError("PATH_INVALID", "Task does not change files");
28509
+ }
28510
+ }
27838
28511
  function fileErrorResult(error63) {
27839
28512
  return {
27840
28513
  state: "FAILED",
@@ -27857,6 +28530,8 @@ var Dispatcher = class {
27857
28530
  this.#logger = options.logger ?? silentLogger;
27858
28531
  this.#protectedPaths = options.protectedPaths ?? protectedAgentPaths(resolveStateDir(process.env));
27859
28532
  }
28533
+ /** The Gateway-anchored clock that grant expiry and task deadlines are checked against. */
28534
+ #gatewayNow = () => this.#options.gatewayNow?.() ?? (this.#options.now ?? Date.now)();
27860
28535
  get identity() {
27861
28536
  const { tenant_id, user_id, device_uuid } = this.#options.identity;
27862
28537
  return { tenant_id, user_id, device_uuid };
@@ -27918,7 +28593,7 @@ var Dispatcher = class {
27918
28593
  const taskId2 = dispatch2.task_id;
27919
28594
  if (taskId2 === null)
27920
28595
  return;
27921
- const now = this.#options.now ?? Date.now;
28596
+ const now = this.#gatewayNow;
27922
28597
  const journal = this.#options.journal;
27923
28598
  const denial = await verifyGrantAuthenticity(dispatch2, this.#options.identity);
27924
28599
  if (denial) {
@@ -27990,29 +28665,32 @@ var Dispatcher = class {
27990
28665
  }
27991
28666
  const actingUser = actingUserId(dispatch2);
27992
28667
  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 };
28668
+ const state2 = { phase: "pending", cancelled: false, stopRequested: false, meta: meta3 };
27994
28669
  this.#inFlight.set(taskId2, state2);
27995
28670
  try {
27996
- const executionNonce = (0, import_node_crypto8.randomUUID)();
28671
+ const executionNonce = (0, import_node_crypto9.randomUUID)();
27997
28672
  this.#sendAck(dispatch2, "RECEIVED", executionNonce);
27998
28673
  let fileTask = isSshTask(authorized) || isShellTask(authorized) || isAgentTask(authorized) || isDiagTask(authorized) ? null : authorized;
27999
28674
  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;
28675
+ if (fileTask && config2.confirm_writes && CHANGING_FILE_CAPABILITIES.has(fileTask.capability)) {
28676
+ let request;
28677
+ try {
28678
+ request = confirmationFor(fileTask);
28679
+ } catch (error63) {
28680
+ const refused = fileErrorResult(error63 instanceof FileOpError ? error63 : new FileOpError("PATH_INVALID", "Path is invalid"));
28681
+ await journal.done(taskId2, meta3, refused).catch(() => void 0);
28682
+ this.#sendResult(dispatch2, refused);
28683
+ return;
28684
+ }
28002
28685
  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;
28686
+ const confirmed = confirm ? await confirm(request).catch(() => false) : false;
28009
28687
  if (state2.cancelled)
28010
28688
  return;
28011
28689
  if (!confirmed) {
28012
28690
  const cancelled = {
28013
28691
  state: "CANCELLED",
28014
28692
  executed: false,
28015
- safe_message: "Write was declined on the device",
28693
+ safe_message: "Change was declined on the device",
28016
28694
  output_excerpt: excerpt({ error: "POLICY_DENIED", reason: "LOCAL_CONFIRM_DECLINED" })
28017
28695
  };
28018
28696
  await journal.done(taskId2, meta3, cancelled).catch(() => void 0);
@@ -28023,7 +28701,7 @@ var Dispatcher = class {
28023
28701
  if (state2.cancelled)
28024
28702
  return;
28025
28703
  if ("refused" in fresh) {
28026
- this.#logger.warn("write refused after local confirmation", { task_id: taskId2, reason: fresh.reason });
28704
+ this.#logger.warn("file change refused after local confirmation", { task_id: taskId2, reason: fresh.reason });
28027
28705
  await journal.done(taskId2, meta3, fresh.refused).catch(() => void 0);
28028
28706
  this.#sendResult(dispatch2, fresh.refused);
28029
28707
  return;
@@ -28047,6 +28725,7 @@ var Dispatcher = class {
28047
28725
  }
28048
28726
  this.#sendAck(dispatch2, "STARTED", executionNonce);
28049
28727
  const taskContext = { taskId: taskId2, contextId: dispatch2.context_id, actingUserId: actingUser };
28728
+ const shellContext = { ...taskContext, cancelled: () => state2.stopRequested };
28050
28729
  if (isAgentTask(authorized)) {
28051
28730
  let deadline = authorized.payload.run_at_ms;
28052
28731
  this.#scheduledRemovals.set(taskId2, meta3);
@@ -28091,7 +28770,7 @@ var Dispatcher = class {
28091
28770
  safe_message: "SSH task failed on the device",
28092
28771
  output_excerpt: excerpt({ error: "INVALID_MESSAGE", reason: "SSH_ERROR" })
28093
28772
  }
28094
- })) : isShellTask(authorized) ? await shellExecutor.run(authorized, taskContext).catch(() => ({
28773
+ })) : isShellTask(authorized) ? await shellExecutor.run(authorized, shellContext).catch(() => ({
28095
28774
  // Unexpected failure after STARTED: whether the action happened is not known, so never claim it did not.
28096
28775
  result: {
28097
28776
  state: "FAILED",
@@ -28144,7 +28823,9 @@ var Dispatcher = class {
28144
28823
  /**
28145
28824
  * Handle a CANCEL for a task. Before journal STARTED: journal DONE
28146
28825
  * CANCELLED and answer RESULT CANCELLED, also for a task whose DISPATCH has
28147
- * not arrived yet. After STARTED: ignored (the action cannot be undone).
28826
+ * not arrived yet. After STARTED: a command the task still runs is stopped
28827
+ * (no RESULT here; the task reports it); anything else is ignored (the action
28828
+ * cannot be undone).
28148
28829
  */
28149
28830
  async cancel(cancel2) {
28150
28831
  const taskId2 = cancel2.task_id;
@@ -28153,7 +28834,6 @@ var Dispatcher = class {
28153
28834
  return;
28154
28835
  }
28155
28836
  const journal = this.#options.journal;
28156
- const state2 = this.#inFlight.get(taskId2);
28157
28837
  const scheduledMeta = this.#scheduledRemovals.get(taskId2);
28158
28838
  if (this.#options.cancelRemoval) {
28159
28839
  const cancelled = await this.#options.cancelRemoval(taskId2);
@@ -28161,13 +28841,30 @@ var Dispatcher = class {
28161
28841
  return;
28162
28842
  if (cancelled === true || scheduledMeta) {
28163
28843
  this.#scheduledRemovals.delete(taskId2);
28164
- if (state2)
28165
- state2.cancelled = true;
28844
+ const removal = this.#inFlight.get(taskId2);
28845
+ if (removal)
28846
+ removal.cancelled = true;
28166
28847
  const record4 = journal.get(taskId2);
28167
28848
  await this.#tombstone(taskId2, scheduledMeta ?? { capability: "agent.remove", nonce: record4?.nonce ?? void 0 }, cancel2);
28168
28849
  return;
28169
28850
  }
28170
28851
  }
28852
+ const stopRunning = this.#options.stopRunning;
28853
+ if (stopRunning) {
28854
+ const starting = this.#inFlight.get(taskId2);
28855
+ const flagged = starting?.phase === "starting" && starting.meta.capability === "shell.exec";
28856
+ if (flagged)
28857
+ starting.stopRequested = true;
28858
+ if (await stopRunning(taskId2).catch(() => false)) {
28859
+ this.#logger.info("running command stopped on cancel", { task_id: taskId2, reason: cancel2.reason });
28860
+ return;
28861
+ }
28862
+ if (flagged) {
28863
+ this.#logger.info("cancel while the command was starting or finishing; it does not start", { task_id: taskId2, reason: cancel2.reason });
28864
+ return;
28865
+ }
28866
+ }
28867
+ const state2 = this.#inFlight.get(taskId2);
28171
28868
  if (state2) {
28172
28869
  if (state2.phase === "starting") {
28173
28870
  this.#logger.warn("cancel ignored: task already started and cannot be undone", { task_id: taskId2, reason: cancel2.reason });
@@ -28282,7 +28979,7 @@ var Dispatcher = class {
28282
28979
  };
28283
28980
 
28284
28981
  // dist/monitor.js
28285
- var import_promises12 = require("node:fs/promises");
28982
+ var import_promises13 = require("node:fs/promises");
28286
28983
  var import_node_os5 = require("node:os");
28287
28984
  var defaultMonitorSystem = {
28288
28985
  platform: process.platform,
@@ -28291,7 +28988,7 @@ var defaultMonitorSystem = {
28291
28988
  totalmem: import_node_os5.totalmem,
28292
28989
  freemem: import_node_os5.freemem,
28293
28990
  uptime: import_node_os5.uptime,
28294
- statfs: (path) => (0, import_promises12.statfs)(path),
28991
+ statfs: (path) => (0, import_promises13.statfs)(path),
28295
28992
  env: process.env
28296
28993
  };
28297
28994
  var MONITOR_FIRST_SAMPLE_MS = 1e3;
@@ -28426,11 +29123,11 @@ var import_node_os9 = require("node:os");
28426
29123
  var import_node_zlib2 = require("node:zlib");
28427
29124
 
28428
29125
  // dist/inventory/image-packages.js
28429
- var import_promises15 = require("node:fs/promises");
28430
- var import_node_path16 = require("node:path");
29126
+ var import_promises16 = require("node:fs/promises");
29127
+ var import_node_path17 = require("node:path");
28431
29128
 
28432
29129
  // dist/inventory/collection.js
28433
- var import_promises14 = require("node:fs/promises");
29130
+ var import_promises15 = require("node:fs/promises");
28434
29131
  var import_node_os8 = require("node:os");
28435
29132
 
28436
29133
  // dist/inventory/tls.js
@@ -28682,9 +29379,9 @@ var PS_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $Prog
28682
29379
 
28683
29380
  // dist/inventory/software.js
28684
29381
  var import_node_fs4 = require("node:fs");
28685
- var import_promises13 = require("node:fs/promises");
29382
+ var import_promises14 = require("node:fs/promises");
28686
29383
  var import_node_os7 = require("node:os");
28687
- var import_node_path15 = require("node:path");
29384
+ var import_node_path16 = require("node:path");
28688
29385
 
28689
29386
  // dist/inventory/parsers/system.js
28690
29387
  var RELEASE_KEYS = {
@@ -28876,8 +29573,8 @@ async function findExecutablesOnPath(name3, path = collectorEnv().PATH ?? "") {
28876
29573
  const found = [];
28877
29574
  for (const dir of path.split(":").filter((entry) => entry.startsWith("/"))) {
28878
29575
  try {
28879
- const real = await (0, import_promises13.realpath)(`${dir}/${name3}`);
28880
- await (0, import_promises13.access)(real, import_node_fs4.constants.X_OK);
29576
+ const real = await (0, import_promises14.realpath)(`${dir}/${name3}`);
29577
+ await (0, import_promises14.access)(real, import_node_fs4.constants.X_OK);
28881
29578
  if (!found.includes(real))
28882
29579
  found.push(real);
28883
29580
  } catch {
@@ -28965,7 +29662,7 @@ function xcodeTools(c) {
28965
29662
  }
28966
29663
  async function stampOf(real) {
28967
29664
  try {
28968
- const info = await (0, import_promises13.stat)(real);
29665
+ const info = await (0, import_promises14.stat)(real);
28969
29666
  return `${real}\0${info.mtimeMs}\0${info.size}`;
28970
29667
  } catch {
28971
29668
  return null;
@@ -29023,7 +29720,7 @@ async function readSmall(c, path) {
29023
29720
  return text6 === null ? "missing" : Buffer.byteLength(text6, "utf8") > PACKAGE_JSON_BYTES ? "large" : text6;
29024
29721
  }
29025
29722
  async function packageJsonVersion(c, key, real, names2) {
29026
- let dir = (0, import_node_path15.dirname)(real);
29723
+ let dir = (0, import_node_path16.dirname)(real);
29027
29724
  for (let level = 0; level < PACKAGE_JSON_LEVELS; level += 1) {
29028
29725
  const text6 = await readSmall(c, `${dir}/package.json`);
29029
29726
  if (text6 === "large")
@@ -29036,7 +29733,7 @@ async function packageJsonVersion(c, key, real, names2) {
29036
29733
  return null;
29037
29734
  }
29038
29735
  }
29039
- const parent = (0, import_node_path15.dirname)(dir);
29736
+ const parent = (0, import_node_path16.dirname)(dir);
29040
29737
  if (parent === dir)
29041
29738
  break;
29042
29739
  dir = parent;
@@ -29217,11 +29914,11 @@ var Collection = class {
29217
29914
  }
29218
29915
  }
29219
29916
  };
29220
- var defaultReader = async (path) => (0, import_promises14.readFile)(path, "utf8").catch(() => null);
29917
+ var defaultReader = async (path) => (0, import_promises15.readFile)(path, "utf8").catch(() => null);
29221
29918
  async function readFileTail(path, bytes3) {
29222
29919
  let handle = null;
29223
29920
  try {
29224
- handle = await (0, import_promises14.open)(path, "r");
29921
+ handle = await (0, import_promises15.open)(path, "r");
29225
29922
  const { size } = await handle.stat();
29226
29923
  const length = Math.min(size, bytes3);
29227
29924
  const buffer = Buffer.alloc(length);
@@ -29236,11 +29933,11 @@ async function readFileTail(path, bytes3) {
29236
29933
  }
29237
29934
  async function listDirFiles(path, dirs = false) {
29238
29935
  try {
29239
- const entries2 = await (0, import_promises14.readdir)(path, { withFileTypes: true });
29936
+ const entries2 = await (0, import_promises15.readdir)(path, { withFileTypes: true });
29240
29937
  const files = [];
29241
29938
  for (const entry of entries2.filter((item) => dirs ? item.isDirectory() : item.isFile()).slice(0, 2e3)) {
29242
29939
  try {
29243
- files.push({ name: entry.name, mtimeMs: (await (0, import_promises14.stat)(`${path}/${entry.name}`)).mtimeMs });
29940
+ files.push({ name: entry.name, mtimeMs: (await (0, import_promises15.stat)(`${path}/${entry.name}`)).mtimeMs });
29244
29941
  } catch {
29245
29942
  }
29246
29943
  }
@@ -29252,7 +29949,7 @@ async function listDirFiles(path, dirs = false) {
29252
29949
  async function readFileBytes(path, maxBytes) {
29253
29950
  let handle = null;
29254
29951
  try {
29255
- handle = await (0, import_promises14.open)(path, "r");
29952
+ handle = await (0, import_promises15.open)(path, "r");
29256
29953
  const buffer = Buffer.alloc(Math.max(0, maxBytes));
29257
29954
  let total = 0;
29258
29955
  while (total < buffer.length) {
@@ -29270,14 +29967,14 @@ async function readFileBytes(path, maxBytes) {
29270
29967
  }
29271
29968
  async function listProcPids() {
29272
29969
  try {
29273
- return (await (0, import_promises14.readdir)("/proc")).filter((name3) => /^[1-9]\d*$/.test(name3)).map(Number);
29970
+ return (await (0, import_promises15.readdir)("/proc")).filter((name3) => /^[1-9]\d*$/.test(name3)).map(Number);
29274
29971
  } catch {
29275
29972
  return null;
29276
29973
  }
29277
29974
  }
29278
29975
  async function readExeLink(pid) {
29279
29976
  try {
29280
- return await (0, import_promises14.readlink)(`/proc/${pid}/exe`);
29977
+ return await (0, import_promises15.readlink)(`/proc/${pid}/exe`);
29281
29978
  } catch {
29282
29979
  return null;
29283
29980
  }
@@ -29295,7 +29992,7 @@ var defaultCollectorSystem = {
29295
29992
  isRoot: typeof process.getuid === "function" ? process.getuid() === 0 : false,
29296
29993
  resolveExe: async (pid) => {
29297
29994
  try {
29298
- return await (0, import_promises14.realpath)(`/proc/${pid}/exe`);
29995
+ return await (0, import_promises15.realpath)(`/proc/${pid}/exe`);
29299
29996
  } catch {
29300
29997
  return null;
29301
29998
  }
@@ -29772,11 +30469,11 @@ async function loadImageCache(stateDir) {
29772
30469
  if (!stateDir)
29773
30470
  return empty;
29774
30471
  try {
29775
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
29776
- const info = await (0, import_promises15.lstat)(path);
30472
+ const path = (0, import_node_path17.join)(stateDir, IMAGE_CACHE_FILE);
30473
+ const info = await (0, import_promises16.lstat)(path);
29777
30474
  if (!info.isFile() || info.size > IMAGE_CACHE_MAX_BYTES)
29778
30475
  return empty;
29779
- const file2 = record2(JSON.parse(await (0, import_promises15.readFile)(path, "utf8")));
30476
+ const file2 = record2(JSON.parse(await (0, import_promises16.readFile)(path, "utf8")));
29780
30477
  if (!file2 || file2.version !== 1)
29781
30478
  return empty;
29782
30479
  const out = { version: 1, entries: {} };
@@ -29805,15 +30502,15 @@ async function saveImageCache(stateDir, cache, nowMs) {
29805
30502
  break;
29806
30503
  entries2.pop();
29807
30504
  }
29808
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
30505
+ const path = (0, import_node_path17.join)(stateDir, IMAGE_CACHE_FILE);
29809
30506
  const temp = `${path}.${process.pid}.tmp`;
29810
30507
  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);
30508
+ await (0, import_promises16.rm)(temp, { force: true });
30509
+ await (0, import_promises16.writeFile)(temp, text6, { mode: 384, flag: "wx" });
30510
+ await (0, import_promises16.chmod)(temp, 384);
30511
+ await (0, import_promises16.rename)(temp, path);
29815
30512
  } catch {
29816
- await (0, import_promises15.rm)(temp, { force: true }).catch(() => void 0);
30513
+ await (0, import_promises16.rm)(temp, { force: true }).catch(() => void 0);
29817
30514
  }
29818
30515
  }
29819
30516
  function engineSupported(c) {
@@ -30119,190 +30816,6 @@ function legacyImagePackages(items) {
30119
30816
  // dist/ssh/exec.js
30120
30817
  var import_node_child_process9 = require("node:child_process");
30121
30818
  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
30819
  var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
30307
30820
  function sshBinariesFromEnv(env = process.env) {
30308
30821
  const pick2 = (value, fallback) => value && (0, import_node_path18.isAbsolute)(value) ? value : fallback;
@@ -34526,9 +35039,81 @@ function unitFileEnablement(unitFiles) {
34526
35039
  return enablement;
34527
35040
  }
34528
35041
  var PER_CONNECTION_INSTANCE = /^[^@\s]+@\d+-[^-\s]+:\d+-\S+:\d+$/;
35042
+ var STATE_RANK = {
35043
+ failed: 0,
35044
+ unknown: 1,
35045
+ stopping: 2,
35046
+ starting: 3,
35047
+ stopped: 4,
35048
+ running: 5
35049
+ };
35050
+ var WORD_CHAR = /[A-Za-z0-9]/;
35051
+ function asciiLower(value) {
35052
+ return value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
35053
+ }
35054
+ function unescapeInstance(instance) {
35055
+ return instance.replace(/\\x([0-9A-Fa-f]{2})/g, (_match, hex3) => String.fromCharCode(Number.parseInt(hex3, 16)));
35056
+ }
35057
+ function maskForm(description, form) {
35058
+ if (form.length === 0 || form.length > description.length)
35059
+ return description;
35060
+ const haystack = asciiLower(description);
35061
+ const needle = asciiLower(form);
35062
+ const guardLead = WORD_CHAR.test(form[0] ?? "");
35063
+ const guardTail = WORD_CHAR.test(form[form.length - 1] ?? "");
35064
+ let result2 = "";
35065
+ let from = 0;
35066
+ let at = haystack.indexOf(needle);
35067
+ while (at >= 0) {
35068
+ const end = at + needle.length;
35069
+ const leadOk = !guardLead || at === 0 || !WORD_CHAR.test(description[at - 1] ?? "");
35070
+ const tailOk = !guardTail || end === description.length || !WORD_CHAR.test(description[end] ?? "");
35071
+ if (leadOk && tailOk) {
35072
+ result2 += `${description.slice(from, at)}<instance>`;
35073
+ from = end;
35074
+ at = haystack.indexOf(needle, end);
35075
+ } else {
35076
+ at = haystack.indexOf(needle, at + 1);
35077
+ }
35078
+ }
35079
+ return result2 + description.slice(from);
35080
+ }
35081
+ function maskInstance(description, instance) {
35082
+ const unescaped = unescapeInstance(instance);
35083
+ const forms = /* @__PURE__ */ new Set([instance, unescaped, `/${unescapeInstance(instance.replace(/-/g, "/"))}`, unescaped.replace(/-/g, "/")]);
35084
+ let result2 = description;
35085
+ for (const form of [...forms].sort((a, b) => b.length - a.length))
35086
+ result2 = maskForm(result2, form);
35087
+ return result2;
35088
+ }
35089
+ function enabledTemplates(enablement) {
35090
+ const templates = /* @__PURE__ */ new Set();
35091
+ for (const [unit2, enabled] of enablement) {
35092
+ const at = unit2.indexOf("@");
35093
+ if (enabled === true && at > 0 && at < unit2.length - 1)
35094
+ templates.add(unit2.slice(0, at + 1));
35095
+ }
35096
+ return templates;
35097
+ }
35098
+ function instanceEnablement(enablement, withEnabledInstance, template, instanceUnits) {
35099
+ if (withEnabledInstance.has(template))
35100
+ return true;
35101
+ const fallback = enablement.get(template) ?? null;
35102
+ let allDisabled = instanceUnits.length > 0;
35103
+ for (const unit2 of instanceUnits) {
35104
+ const enabled = enablement.has(unit2) ? enablement.get(unit2) ?? null : fallback;
35105
+ if (enabled === true)
35106
+ return true;
35107
+ if (enabled !== false)
35108
+ allDisabled = false;
35109
+ }
35110
+ return allDisabled ? false : null;
35111
+ }
34529
35112
  function parseSystemd(units, unitFiles) {
34530
35113
  const enablement = unitFileEnablement(unitFiles);
34531
- const result2 = [];
35114
+ const byName = /* @__PURE__ */ new Map();
35115
+ const mixed = /* @__PURE__ */ new Set();
35116
+ const instances = /* @__PURE__ */ new Map();
34532
35117
  for (const rawLine of lines2(units)) {
34533
35118
  const line = rawLine.trim().replace(/^[●*]\s+/, "");
34534
35119
  const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
@@ -34542,23 +35127,46 @@ function parseSystemd(units, unitFiles) {
34542
35127
  continue;
34543
35128
  if (load === "not-found")
34544
35129
  continue;
34545
- if (PER_CONNECTION_INSTANCE.test(unitName(unitToken)))
35130
+ const unit2 = unitName(unitToken);
35131
+ if (PER_CONNECTION_INSTANCE.test(unit2))
34546
35132
  continue;
34547
- const name3 = text3(unitName(unitToken), NAME_MAX4);
34548
- if (!name3)
35133
+ const at = unit2.indexOf("@");
35134
+ const instance = at >= 0 ? unit2.slice(at + 1) : "";
35135
+ const name3 = text3(at >= 0 ? unit2.slice(0, at + 1) : unit2, NAME_MAX4);
35136
+ if (!name3 || name3 === "@")
34549
35137
  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);
35138
+ const rawDescription = match[5] ?? "";
35139
+ const description = text3(instance ? maskInstance(rawDescription, instance) : rawDescription, DESCRIPTION_MAX);
35140
+ const state2 = systemdState(active.toLowerCase(), sub.toLowerCase());
35141
+ if (instance) {
35142
+ const list = instances.get(name3);
35143
+ if (list)
35144
+ list.push(unit2);
35145
+ else
35146
+ instances.set(name3, [unit2]);
35147
+ }
35148
+ const seen = byName.get(name3);
35149
+ if (seen) {
35150
+ if (STATE_RANK[state2] < STATE_RANK[seen.state])
35151
+ seen.state = state2;
35152
+ if ((seen.description ?? "") !== description)
35153
+ mixed.add(name3);
35154
+ continue;
35155
+ }
35156
+ const item = { name: name3, manager: "systemd", state: state2, enabled: enablement.get(name3) ?? null };
34557
35157
  if (description)
34558
35158
  item.description = description;
34559
- result2.push(item);
35159
+ byName.set(name3, item);
34560
35160
  }
34561
- return sorted2(result2);
35161
+ for (const name3 of mixed)
35162
+ delete byName.get(name3)?.description;
35163
+ const withEnabledInstance = enabledTemplates(enablement);
35164
+ for (const [name3, units2] of instances) {
35165
+ const item = byName.get(name3);
35166
+ if (item)
35167
+ item.enabled = instanceEnablement(enablement, withEnabledInstance, name3, units2);
35168
+ }
35169
+ return sorted2([...byName.values()]);
34562
35170
  }
34563
35171
  function parseLaunchctl(stdout) {
34564
35172
  const result2 = [];
@@ -36233,6 +36841,7 @@ async function collectInventory(system = defaultCollectorSystem, options = LEGAC
36233
36841
  }
36234
36842
 
36235
36843
  // dist/relay.js
36844
+ var defaultMonotonicNow = () => performance.now();
36236
36845
  var HEARTBEAT_INTERVAL_MS = 2e4;
36237
36846
  var PING_INTERVAL_MS = 25e3;
36238
36847
  var PING_JITTER_MS = 5e3;
@@ -36246,6 +36855,10 @@ var RECONNECT_JITTER_MIN_MS = 1e3;
36246
36855
  var RECONNECT_JITTER_SPAN_MS = 29e3;
36247
36856
  var SERVER_DROP_CODES = /* @__PURE__ */ new Set([1001, 1006, 1011, 1012, 4e3]);
36248
36857
  var AUTH_TIMEOUT_MS = 2e4;
36858
+ var CHALLENGE_TTL_MS = 15e3;
36859
+ var CLOCK_SKEW_WARN_MS = 3e4;
36860
+ var REPLACED_CLOSE_REASON = "replaced";
36861
+ var REPLACED_BACKOFF_MAX_MS = 3e5;
36249
36862
  var CLOSE_POLICY_VIOLATION = 4008;
36250
36863
  function relayUrl(gatewayUrl, deviceUuid2) {
36251
36864
  const url2 = new URL("/v1/agent/connect", gatewayUrl);
@@ -36267,6 +36880,10 @@ var RelaySession = class {
36267
36880
  #gatewayFeatures = /* @__PURE__ */ new Set();
36268
36881
  /** Relay features both sides speak: the ones this agent listed in AUTH that AUTH_OK echoed. */
36269
36882
  #relayFeatures = /* @__PURE__ */ new Set();
36883
+ /** Gateway clock minus local clock, measured from this connection's CHALLENGE; 0 until one arrived. For logs only. */
36884
+ #clockOffsetMs = 0;
36885
+ /** Gateway time at this connection's CHALLENGE and the monotonic time it was read at; null until one arrived. */
36886
+ #gatewayAnchor = null;
36270
36887
  constructor(options) {
36271
36888
  this.#options = options;
36272
36889
  this.#logger = options.logger ?? silentLogger;
@@ -36274,6 +36891,26 @@ var RelaySession = class {
36274
36891
  get state() {
36275
36892
  return this.#state;
36276
36893
  }
36894
+ /**
36895
+ * Gateway clock minus local clock in ms, derived from this connection's CHALLENGE (`expires_at_ms - CHALLENGE_TTL_MS
36896
+ * - localNow`). It is lower than the true offset by the CHALLENGE's one-way network delay, so grant deadlines
36897
+ * evaluated with it are at most that delay late; no tolerance is added on top.
36898
+ */
36899
+ get clockOffsetMs() {
36900
+ return this.#clockOffsetMs;
36901
+ }
36902
+ /**
36903
+ * The Gateway clock for grant expiry and task deadlines, or null before a CHALLENGE arrived: the CHALLENGE's Gateway
36904
+ * time (`expires_at_ms - CHALLENGE_TTL_MS`) plus the monotonic time elapsed since. It never reads the wall clock, so
36905
+ * a device clock corrected after the CHALLENGE cannot shift it. Like clockOffsetMs it runs behind the true Gateway
36906
+ * clock by the CHALLENGE's one-way network delay; no tolerance is added on top.
36907
+ */
36908
+ gatewayNow = () => {
36909
+ const anchor2 = this.#gatewayAnchor;
36910
+ if (!anchor2)
36911
+ return null;
36912
+ return anchor2.gatewayMs + ((this.#options.monotonicNow ?? defaultMonotonicNow)() - anchor2.monotonicMs);
36913
+ };
36277
36914
  /** True once AUTH_OK echoed `ping.v1` for a session that listed it. */
36278
36915
  get pingEnabled() {
36279
36916
  return this.#state === "ready" && this.#relayFeatures.has("ping.v1");
@@ -36369,9 +37006,13 @@ var RelaySession = class {
36369
37006
  const parsed = relayChallengeSchema.safeParse(frame);
36370
37007
  if (!parsed.success)
36371
37008
  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");
37009
+ const localNow = (this.#options.now ?? Date.now)();
37010
+ const gatewayMs = parsed.data.expires_at_ms - CHALLENGE_TTL_MS;
37011
+ this.#gatewayAnchor = { gatewayMs, monotonicMs: (this.#options.monotonicNow ?? defaultMonotonicNow)() };
37012
+ this.#clockOffsetMs = gatewayMs - localNow;
37013
+ if (Math.abs(this.#clockOffsetMs) > CLOCK_SKEW_WARN_MS) {
37014
+ this.#logger.warn("the device clock differs from the Gateway clock; task deadlines use the Gateway clock", { clock_offset_ms: this.#clockOffsetMs });
37015
+ }
36375
37016
  const deviceUuid2 = this.#options.identity.device_uuid;
36376
37017
  const signature = await signRelayChallenge(this.#options.key, deviceUuid2, parsed.data.nonce, parsed.data.connection_id);
36377
37018
  this.#state = "auth_sent";
@@ -36474,6 +37115,10 @@ var DEFAULT_BACKOFF = { baseMs: 1e3, maxMs: 6e4 };
36474
37115
  function reconnectDelay(connectionMs, closeCode, random = Math.random, context = {}) {
36475
37116
  if (context.requested === true)
36476
37117
  return 0;
37118
+ if (context.replaced === true) {
37119
+ const backoff = context.backoff ?? DEFAULT_BACKOFF;
37120
+ return backoffDelay(context.attempt ?? 0, { ...backoff, maxMs: Math.max(backoff.maxMs, REPLACED_BACKOFF_MAX_MS), random: backoff.random ?? random });
37121
+ }
36477
37122
  if (connectionMs >= LONG_CONNECTION_MS && SERVER_DROP_CODES.has(closeCode))
36478
37123
  return Math.floor(RECONNECT_JITTER_MIN_MS + random() * RECONNECT_JITTER_SPAN_MS);
36479
37124
  return backoffDelay(context.attempt ?? 0, { ...context.backoff ?? DEFAULT_BACKOFF, random: context.backoff?.random ?? random });
@@ -37310,7 +37955,7 @@ function sshDiagPlan(spec2, values) {
37310
37955
  root: DIAG_ROOT_REQUIRED[spec2.id],
37311
37956
  steps: Object.freeze(steps)
37312
37957
  });
37313
- const quoted = values.map(q).join(" ");
37958
+ const quoted2 = values.map(q).join(" ");
37314
37959
  switch (spec2.id) {
37315
37960
  case "os.release":
37316
37961
  return plan([step("os_release", "read", "cat /etc/os-release 2>&1", { merged: true })]);
@@ -37337,15 +37982,15 @@ function sshDiagPlan(spec2, values) {
37337
37982
  case "sshd.effective":
37338
37983
  return plan([step("sshd", "exec", "sshd -T 2>&1 || /usr/sbin/sshd -T 2>&1", { merged: true })]);
37339
37984
  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 })]);
37985
+ return plan([step("dpkg_query", "exec", `dpkg-query -W -f ${q(DPKG_QUERY_FORMAT)} -- ${quoted2} 2>&1`, { merged: true, tabSplit: true })]);
37341
37986
  case "apt.candidate":
37342
- return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted}`)]);
37987
+ return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted2}`)]);
37343
37988
  case "rpm.installed":
37344
- return plan([step("rpm", "exec", `rpm -q --qf ${q(RPM_QUERY_FORMAT)} -- ${quoted}`)]);
37989
+ return plan([step("rpm", "exec", `rpm -q --qf ${q(RPM_QUERY_FORMAT)} -- ${quoted2}`)]);
37345
37990
  case "listeners.public":
37346
37991
  return plan([step("ss", "exec", "ss -H -tuln")]);
37347
37992
  case "service.state":
37348
- return plan([step("systemctl", "exec", `systemctl show --property=LoadState,ActiveState,SubState,UnitFileState -- ${quoted}`)]);
37993
+ return plan([step("systemctl", "exec", `systemctl show --property=LoadState,ActiveState,SubState,UnitFileState -- ${quoted2}`)]);
37349
37994
  case "reboot.required":
37350
37995
  return plan([
37351
37996
  step("dpkg_status", "probe", "test -e /var/lib/dpkg/status"),
@@ -38043,6 +38688,7 @@ var ShellExecutor = class {
38043
38688
  background: session.background,
38044
38689
  running: session.endedAtMs === null,
38045
38690
  exit_code: session.exitCode,
38691
+ stopped: session.stoppedBy !== null,
38046
38692
  started_at: new Date(session.startedAtMs).toISOString(),
38047
38693
  duration_ms: (session.endedAtMs ?? this.#now()) - session.startedAtMs,
38048
38694
  output_bytes: session.output.total
@@ -38107,6 +38753,17 @@ var ShellExecutor = class {
38107
38753
  return failure3("INVALID_MESSAGE", "SHELL_UNAVAILABLE", error63 instanceof Error ? error63.message : "Shell is not available");
38108
38754
  }
38109
38755
  const windows = (this.#options.platform ?? process.platform) === "win32";
38756
+ if (context.cancelled?.() === true) {
38757
+ this.#logger.info("command cancelled before it started", { task_id: context.taskId });
38758
+ return {
38759
+ result: {
38760
+ state: "CANCELLED",
38761
+ executed: false,
38762
+ safe_message: "The command was cancelled before it started",
38763
+ output_excerpt: excerpt({ error: "POLICY_DENIED", reason: "CANCELLED_BEFORE_START" })
38764
+ }
38765
+ };
38766
+ }
38110
38767
  let child;
38111
38768
  try {
38112
38769
  child = (0, import_node_child_process11.spawn)(launch.file, [...launch.args], {
@@ -38183,8 +38840,24 @@ var ShellExecutor = class {
38183
38840
  if (session.stoppedBy === "timeout") {
38184
38841
  return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: `Command timed out after ${payload.timeout_s} s and was stopped` } };
38185
38842
  }
38843
+ if (session.stoppedBy === "cancelled") {
38844
+ return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: "The command was cancelled and stopped" } };
38845
+ }
38186
38846
  return outcome;
38187
38847
  }
38848
+ /**
38849
+ * Stop the running command of task `taskId` and everything it started (its process group), for a Gateway CANCEL of
38850
+ * that task. No ownership check: the CANCEL names the task, came over the authenticated relay session, and stopping
38851
+ * only ever takes access away. False when no command of that task runs (unknown, never a command, or already ended).
38852
+ */
38853
+ async stopTask(taskId2) {
38854
+ const session = this.#sessions.get(taskId2);
38855
+ if (!session || session.endedAtMs !== null || !session.child)
38856
+ return false;
38857
+ if (session.stoppedBy === null)
38858
+ await this.#stop(session, "cancelled");
38859
+ return true;
38860
+ }
38188
38861
  /** Session `taskId` if it belongs to this context and acting user. */
38189
38862
  #owned(taskId2, context) {
38190
38863
  const session = this.#sessions.get(taskId2);
@@ -38498,6 +39171,11 @@ var AgentRunner = class {
38498
39171
  #stopped = false;
38499
39172
  #sleep = null;
38500
39173
  #attempt = 0;
39174
+ /**
39175
+ * Gateway clock of the latest authenticated connection (RelaySession.gatewayNow, monotonic from its CHALLENGE); grant
39176
+ * deadlines use it. It stays valid across reconnects until the next connection authenticates.
39177
+ */
39178
+ #gatewayNow = null;
38501
39179
  /** Set by reconnectNow: the next connection attempt starts without a backoff wait. */
38502
39180
  #immediate = false;
38503
39181
  /** #immediate counts only for a connection that ends before this time (reconnectNow + 5 s). */
@@ -38540,9 +39218,13 @@ var AgentRunner = class {
38540
39218
  return true;
38541
39219
  },
38542
39220
  shell: this.#shell,
39221
+ // A Gateway CANCEL stops the command its task still runs: the owner stopped it, or its context was revoked or
39222
+ // ended while it ran (owner decision D11).
39223
+ stopRunning: (taskId2) => this.#shell.stopTask(taskId2),
38543
39224
  diag: new DiagExecutor({ logger: this.#logger }),
38544
39225
  identity: options.identity,
38545
39226
  config: () => this.#currentConfig(),
39227
+ gatewayNow: () => this.#gatewayNow?.() ?? null,
38546
39228
  loadConfig: async () => {
38547
39229
  if (await this.#reloadConfig())
38548
39230
  this.#session?.sendInventory();
@@ -38578,10 +39260,24 @@ var AgentRunner = class {
38578
39260
  });
38579
39261
  const hostKey = (list) => JSON.stringify(list.map(inventoryResource2));
38580
39262
  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));
39263
+ const fullAccessOff = this.#config?.full_access === true && config2.full_access !== true;
38581
39264
  this.#config = config2;
38582
39265
  this.#sshHosts = hosts;
39266
+ if (fullAccessOff)
39267
+ await this.#stopTerminalCommands();
38583
39268
  return changed;
38584
39269
  }
39270
+ async #stopTerminalCommands() {
39271
+ const running = this.#shell.runningCount;
39272
+ if (running === 0)
39273
+ return;
39274
+ this.#logger.info("full access turned off; stopping commands started by AI apps", { running });
39275
+ try {
39276
+ await this.#shell.shutdown();
39277
+ } catch (error63) {
39278
+ this.#logger.warn("stopping commands after full access was turned off failed", { error: errorMessage(error63) });
39279
+ }
39280
+ }
38585
39281
  async #compactJournal() {
38586
39282
  try {
38587
39283
  const stats = await this.#options.journal.compact();
@@ -38668,7 +39364,7 @@ var AgentRunner = class {
38668
39364
  }
38669
39365
  async #loop() {
38670
39366
  while (!this.#stopped) {
38671
- let outcome = { authenticated: false, connectionMs: 0, code: 1006 };
39367
+ let outcome = { authenticated: false, connectionMs: 0, code: 1006, replaced: false };
38672
39368
  this.#immediate = false;
38673
39369
  try {
38674
39370
  outcome = await this.#connectOnce();
@@ -38677,14 +39373,21 @@ var AgentRunner = class {
38677
39373
  }
38678
39374
  if (this.#stopped)
38679
39375
  break;
38680
- if (outcome.authenticated)
39376
+ if (outcome.authenticated && !outcome.replaced && outcome.connectionMs >= LONG_CONNECTION_MS)
38681
39377
  this.#attempt = 0;
38682
39378
  const requested = this.#immediate && (this.#options.now ?? Date.now)() <= this.#immediateUntil;
38683
39379
  this.#immediate = false;
38684
39380
  if (requested)
38685
39381
  continue;
38686
- const delay = reconnectDelay(outcome.connectionMs, outcome.code, this.#options.random ?? Math.random, { attempt: this.#attempt, backoff: this.#options.backoff ?? DEFAULT_BACKOFF });
39382
+ 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
39383
  this.#attempt += 1;
39384
+ if (outcome.replaced) {
39385
+ this.#logger.warn("another agent connected with this device identity and replaced this connection; backing off", {
39386
+ device_uuid: this.#options.identity.device_uuid,
39387
+ delay_ms: delay,
39388
+ hint: "the same identity runs elsewhere (copied state folder, cloned VM or restored backup); remove that copy or pair it as a new device"
39389
+ });
39390
+ }
38688
39391
  this.#logger.info("reconnecting", { delay_ms: delay });
38689
39392
  await this.#wait(delay);
38690
39393
  }
@@ -38857,6 +39560,7 @@ var AgentRunner = class {
38857
39560
  onReady: () => {
38858
39561
  ready = true;
38859
39562
  readyAtMs = now();
39563
+ this.#gatewayNow = session.gatewayNow;
38860
39564
  lastPongMs = readyAtMs;
38861
39565
  const keepalive = session.pingEnabled;
38862
39566
  this.#logger.info("relay authenticated", { device_uuid: identity.device_uuid, keepalive: keepalive ? "ping.v1" : "heartbeat" });
@@ -38898,7 +39602,7 @@ var AgentRunner = class {
38898
39602
  this.#session = session;
38899
39603
  return new Promise((resolve10) => {
38900
39604
  let settled = false;
38901
- const end = (code) => {
39605
+ const end = (code, serverReason) => {
38902
39606
  if (settled)
38903
39607
  return;
38904
39608
  settled = true;
@@ -38931,7 +39635,7 @@ var AgentRunner = class {
38931
39635
  this.#featuresRefused = false;
38932
39636
  this.#logger.info("offering relay features again on the next connection");
38933
39637
  }
38934
- resolve10({ authenticated: ready, connectionMs, code });
39638
+ resolve10({ authenticated: ready, connectionMs, code, replaced: code === 4e3 && serverReason === REPLACED_CLOSE_REASON });
38935
39639
  };
38936
39640
  endConnection = end;
38937
39641
  this.#endConnection = end;
@@ -38970,7 +39674,7 @@ var AgentRunner = class {
38970
39674
  socket.addEventListener("close", (event) => {
38971
39675
  if (!settled)
38972
39676
  this.#handleClose(event.code, event.reason);
38973
- end(event.code);
39677
+ end(event.code, event.reason);
38974
39678
  });
38975
39679
  });
38976
39680
  }
@@ -39110,7 +39814,8 @@ async function cmdSsh(stateDir, args, io) {
39110
39814
  var USAGE = `conbridge-agent ${AGENT_VERSION}
39111
39815
 
39112
39816
  Usage:
39113
- conbridge-agent pair --code XXXX-XXXX [--gateway <url>] [--name <name>] [--full-access] [--no-service] [--key-store keychain|file] [--force]
39817
+ conbridge-agent pair --code XXXX-XXXX [--gateway <url>] [--name <name>] [--full-access [--home [--home-writable]]] [--no-service]
39818
+ [--key-store keychain|file] [--force]
39114
39819
  conbridge-agent connect <conbridge://pair?...> (used by the ConBridge Mac app; no terminal needed)
39115
39820
  conbridge-agent roots add <path> --label <label> [--writable] [--allow-broad-root]
39116
39821
  conbridge-agent roots list
@@ -39119,8 +39824,11 @@ Usage:
39119
39824
  conbridge-agent config keep-awake <on|off>
39120
39825
  conbridge-agent config inventory <on|off> software inventory the owner turns on in the Console (default on)
39121
39826
  ${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
39827
+ conbridge-agent access full [--home [--home-writable]] AI apps you approve may run commands here (terminal,
39828
+ processes); the home folder is not shared unless --home (read-only;
39829
+ --home-writable: read-write)
39830
+ conbridge-agent access files full access off: stops the commands AI apps started, removes the home
39831
+ folder share that access full added; other shared folders stay
39124
39832
  conbridge-agent access status
39125
39833
  conbridge-agent start foreground session; Ctrl+C stops it
39126
39834
  conbridge-agent kill [--yes] [--keep-runtime] remove this agent (alias: remove)
@@ -39131,7 +39839,8 @@ ${SSH_USAGE}
39131
39839
  conbridge-agent logs [-f] [-n <lines>]
39132
39840
  conbridge-agent service <install|uninstall|print>
39133
39841
  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
39842
+ conbridge-agent unpair [--keep-local-access] stop the service, remove this computer's identity and its local access
39843
+ (shared folders, full access, SSH hosts) unless --keep-local-access
39135
39844
  conbridge-agent --version
39136
39845
 
39137
39846
  pair connects this computer to ConBridge (default gateway ${DEFAULT_GATEWAY_URL}, default name: this computer's
@@ -39139,7 +39848,13 @@ name) and installs the background service, so the agent reconnects by itself aft
39139
39848
  a LaunchAgent on macOS, a systemd user service on Linux (started at boot), a Task Scheduler task on Windows.
39140
39849
  While it runs, the agent keeps the computer from idle-sleeping (the display may still turn off); turn this off
39141
39850
  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.
39851
+ like a terminal; it shares your home folder only with --home, read-only unless --home-writable is added too (the
39852
+ agent's own files and credential files such as .ssh, .aws, .env and keys stay blocked); in the Console you choose per
39853
+ computer whether each command, read or change asks you first. access files turns full access off, stops the commands
39854
+ AI apps started and removes the home folder share access full added.
39855
+
39856
+ Shared folders, full access and SSH hosts belong to the ConBridge account and organization this computer was paired
39857
+ with when they were set up: pairing with another account or organization (pair --force, a connect link) removes them first.
39143
39858
 
39144
39859
  Modes: persistent starts automatically; passive runs only with start; timed expires and removes identity;
39145
39860
  ephemeral expires or self-destructs and purges ConBridge files.
@@ -39242,7 +39957,7 @@ async function discardOldKey(paths, identity, env) {
39242
39957
  } catch {
39243
39958
  }
39244
39959
  }
39245
- async function cmdPair(paths, args, io) {
39960
+ async function cmdPair(paths, args, io, hooks = {}) {
39246
39961
  const { values } = (0, import_node_util2.parseArgs)({
39247
39962
  args,
39248
39963
  allowPositionals: false,
@@ -39254,14 +39969,25 @@ async function cmdPair(paths, args, io) {
39254
39969
  "key-store": { type: "string" },
39255
39970
  keychain: { type: "string" },
39256
39971
  "no-service": { type: "boolean" },
39257
- "full-access": { type: "boolean" }
39972
+ "full-access": { type: "boolean" },
39973
+ home: { type: "boolean" },
39974
+ "home-writable": { type: "boolean" }
39258
39975
  }
39259
39976
  });
39260
39977
  if (!values.code)
39261
39978
  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;
39979
+ if ((values.home || values["home-writable"]) && !values["full-access"])
39980
+ throw new UsageError("--home and --home-writable need --full-access");
39981
+ if (values["home-writable"] && !values.home)
39982
+ throw new UsageError("--home-writable needs --home");
39983
+ if (hooks.confirmOffer) {
39984
+ if (runningFromNpm() && !await runningFromRuntime(paths.dir))
39985
+ throw new UsageError("connect runs from the installed agent (ConBridge.app); in a terminal use pair --code");
39986
+ } else {
39987
+ const installed = await runInstalledCopy(paths, ["pair", ...args], io, false);
39988
+ if (installed !== null)
39989
+ return installed;
39990
+ }
39265
39991
  const gateway = values.gateway ?? DEFAULT_GATEWAY_URL;
39266
39992
  const name3 = (values.name ?? (0, import_node_os15.hostname)()).trim().slice(0, 64) || "My computer";
39267
39993
  const keyStore = await newKeyStore(paths, values, io.env);
@@ -39270,16 +39996,27 @@ async function cmdPair(paths, args, io) {
39270
39996
  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
39997
  await ensureStateDir(paths.dir);
39272
39998
  io.out(`Device key store: ${keyStore.descriptor.type === "keychain" ? "macOS Keychain" : `file ${paths.key}`}`);
39999
+ const shared = describeLocalGrants(await readLocalGrants(paths));
39273
40000
  const identity = await pairDevice({
39274
40001
  paths,
39275
40002
  keyStore,
39276
40003
  gatewayUrl: gateway,
39277
40004
  code: values.code,
39278
40005
  name: name3,
39279
- onOffered: ({ fingerprint }) => {
39280
- io.out(`Offer sent. Device fingerprint: ${fingerprint}`);
40006
+ onOffered: ({ fingerprint, organization_name, inviter }) => {
40007
+ 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}`);
40008
+ if (shared.length > 0) {
40009
+ io.out("Already shared from this computer: " + shared.join("; ") + ".");
40010
+ 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.");
40011
+ }
39281
40012
  io.out("Approve this device in the ConBridge Console and check that the fingerprint matches. Waiting...");
39282
40013
  },
40014
+ ...hooks.confirmOffer ? { confirmOffer: hooks.confirmOffer } : {},
40015
+ onLocalGrantsCleared: (cleared) => {
40016
+ 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:");
40017
+ for (const line of describeClearedGrants(cleared))
40018
+ io.out(` ${line}`);
40019
+ },
39283
40020
  onApproved: async () => {
39284
40021
  if (keyStore.descriptor.type === "file")
39285
40022
  await (0, import_promises23.rename)(pendingKeyPath(paths), paths.key);
@@ -39288,8 +40025,9 @@ async function cmdPair(paths, args, io) {
39288
40025
  if (previous && !(keyStore.descriptor.type === "file" && previous.key_store?.type !== "keychain"))
39289
40026
  await discardOldKey(paths, previous, io.env);
39290
40027
  io.out(`Paired as "${identity.display_name}" (device ${identity.device_uuid}).`);
39291
- if (values["full-access"])
39292
- await cmdAccess(paths, ["full"], io);
40028
+ if (values["full-access"]) {
40029
+ await cmdAccess(paths, ["full", ...values.home ? ["--home"] : [], ...values["home-writable"] ? ["--home-writable"] : []], io);
40030
+ }
39293
40031
  if (identity.connection_mode === "passive") {
39294
40032
  await removeAgentAutostart(paths.dir, lifecycleDeps(io));
39295
40033
  await stopSupervisor(paths);
@@ -39320,11 +40058,12 @@ async function cmdConnect(paths, args, io) {
39320
40058
  return await runConnect(link, {
39321
40059
  dialogs: macConnectDialogs,
39322
40060
  isPaired: () => exists2(paths.identity),
40061
+ localAccess: () => readLocalGrants(paths),
39323
40062
  addFolder: async (path, label, writable) => {
39324
40063
  await addRoot(paths, { path, label, writable, allowBroadRoot: false, ...io.env.HOME ? { home: io.env.HOME } : {} });
39325
40064
  },
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);
40065
+ pair: async (request, replacing, confirmOffer) => {
40066
+ const code = await cmdPair(paths, ["--gateway", request.gateway, "--code", request.code, "--name", request.name, "--no-service", ...replacing ? ["--force"] : []], io, { confirmOffer });
39328
40067
  if (code !== 0)
39329
40068
  throw new Error("Pairing did not finish.");
39330
40069
  },
@@ -39678,31 +40417,60 @@ async function cmdSupervise(paths, io) {
39678
40417
  }
39679
40418
  return 0;
39680
40419
  }
40420
+ function sharedFolders(roots) {
40421
+ return roots.length === 0 ? "none" : roots.map((root) => `${root.label} (${root.writable ? "read-write" : "read-only"})`).join(", ");
40422
+ }
39681
40423
  async function cmdAccess(paths, args, io) {
39682
40424
  const [mode, ...rest] = args;
39683
40425
  const config2 = await loadConfig(paths);
39684
40426
  if (mode === "status" || mode === void 0) {
39685
40427
  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(", ")}`);
40428
+ io.out(`Shared folders: ${sharedFolders(config2.roots)}`);
39687
40429
  return 0;
39688
40430
  }
39689
40431
  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.");
40432
+ const home2 = addedHomeRoot(config2);
40433
+ const roots = config2.roots.filter((root) => root !== home2);
40434
+ const next = { ...config2, roots, full_access: false };
40435
+ delete next.home_root_added;
40436
+ await saveConfig(paths, next);
40437
+ 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.");
40438
+ if (home2)
40439
+ io.out(`Your home folder (${home2.path}), which access full shared ${home2.writable ? "read-write" : "read-only"}, is no longer shared.`);
40440
+ io.out(`AI apps can use only these shared folders: ${sharedFolders(roots)}.`);
39692
40441
  return 0;
39693
40442
  }
39694
40443
  if (mode !== "full")
39695
40444
  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).`);
40445
+ const { values } = (0, import_node_util2.parseArgs)({
40446
+ args: rest,
40447
+ allowPositionals: false,
40448
+ options: { home: { type: "boolean" }, "home-writable": { type: "boolean" }, "no-home": { type: "boolean" } }
40449
+ });
40450
+ if (values["home-writable"] && !values.home)
40451
+ throw new UsageError("--home-writable needs --home");
40452
+ if (values.home && values["no-home"])
40453
+ throw new UsageError("--home and --no-home cannot be combined");
40454
+ const owner = await currentGrantOwner(paths);
40455
+ await saveConfig(paths, { ...config2, full_access: true, ...owner ? { granted_for: owner } : {} });
40456
+ if (values["no-home"])
40457
+ io.out("The home folder is no longer shared by default; --no-home is not needed.");
40458
+ const home = io.env.HOME ?? (0, import_node_os15.homedir)();
40459
+ const real = await (0, import_promises23.realpath)(home).catch(() => null);
40460
+ const existing = real === null ? void 0 : config2.roots.find((root) => root.path === real);
40461
+ if (existing) {
40462
+ 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.`);
40463
+ } else if (values.home) {
40464
+ if (real) {
40465
+ const writable = values["home-writable"] === true;
40466
+ const root = await addRoot(paths, { path: real, label: "Home", writable, allowBroadRoot: true, home });
40467
+ await saveConfig(paths, { ...await loadConfig(paths), home_root_added: { root_id: root.root_id, path: root.path } });
40468
+ 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.`);
40469
+ } else {
40470
+ io.err(`Your home folder (${home}) was not found, so it was not shared.`);
39705
40471
  }
40472
+ } else {
40473
+ 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
40474
  }
39707
40475
  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
40476
  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 +40546,32 @@ async function cmdLogs(paths, args, io) {
39778
40546
  }
39779
40547
  }
39780
40548
  }
39781
- async function cmdUnpair(paths, io) {
40549
+ async function cmdUnpair(paths, args, io) {
40550
+ const { values } = (0, import_node_util2.parseArgs)({ args, allowPositionals: false, options: { "keep-local-access": { type: "boolean" } } });
39782
40551
  const identity = await loadIdentity(paths).catch(() => null);
39783
- if ((await serviceLocation(paths.dir))?.installed)
40552
+ if ((await serviceLocation(paths.dir, { home: io.env.HOME ?? io.env.USERPROFILE ?? (0, import_node_os15.homedir)() }))?.installed)
39784
40553
  await cmdService(paths, ["uninstall"], io).catch(() => 1);
39785
40554
  await stopAgentProcess(paths);
39786
40555
  if (identity)
39787
40556
  await discardOldKey(paths, identity, io.env);
39788
40557
  await (0, import_promises23.unlink)(paths.identity).catch(() => void 0);
39789
40558
  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.");
40559
+ if (values["keep-local-access"]) {
40560
+ if (identity)
40561
+ await adoptUnownedGrants(paths, grantOwnerOf(identity));
40562
+ const kept = describeLocalGrants(await readLocalGrants(paths));
40563
+ if (kept.length > 0) {
40564
+ io.out("Kept the local access: " + kept.join("; ") + ".");
40565
+ io.out("Pairing again with the same ConBridge account and organization keeps it; pairing with another one removes it.");
40566
+ }
40567
+ return 0;
40568
+ }
40569
+ const cleared = await clearLocalGrants(paths);
40570
+ if (hasLocalGrants(cleared)) {
40571
+ io.out("Removed the local access as well (keep it next time with unpair --keep-local-access):");
40572
+ for (const line of describeClearedGrants(cleared))
40573
+ io.out(` ${line}`);
40574
+ }
39790
40575
  return 0;
39791
40576
  }
39792
40577
  function lifecycleDeps(io) {
@@ -39846,7 +40631,7 @@ async function main(argv, io) {
39846
40631
  case "supervise":
39847
40632
  return await cmdSupervise(paths, io);
39848
40633
  case "unpair":
39849
- return await cmdUnpair(paths, io);
40634
+ return await cmdUnpair(paths, args, io);
39850
40635
  case "service":
39851
40636
  return await cmdService(paths, args, io);
39852
40637
  case "update":