conbridge-agent 0.8.0 → 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.0", commit: "08e31b1ba7e1", built_at: "2026-11-12T14:15:52.250Z", 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");
@@ -20896,7 +20896,8 @@ var INTEL_PENDING_REASONS = [
20896
20896
  "query_failed",
20897
20897
  "record_missing",
20898
20898
  "record_unstorable",
20899
- "record_unchecked_for_package"
20899
+ "record_unchecked_for_package",
20900
+ "query_too_large"
20900
20901
  ];
20901
20902
  var CPE_PRODUCTS = Object.freeze({
20902
20903
  node: { cpe: "nodejs:node.js", scheme: "semver", name: "Node.js", releases: "node", packaged: /^nodejs$/ },
@@ -21106,6 +21107,202 @@ function compareDpkgVersions(a, b) {
21106
21107
  return sign(compareEpochs(left.epoch, right.epoch) || verrevcmp(left.upstream, right.upstream) || verrevcmp(left.revision, right.revision));
21107
21108
  }
21108
21109
 
21110
+ // ../../packages/protocol/dist/security/apk-version.js
21111
+ var MAX_VERSION_LENGTH2 = 128;
21112
+ var UINT64_MAX = "18446744073709551615";
21113
+ var Token = {
21114
+ InitialDigit: 0,
21115
+ Digit: 1,
21116
+ Letter: 2,
21117
+ Suffix: 3,
21118
+ SuffixNo: 4,
21119
+ CommitHash: 5,
21120
+ RevisionNo: 6,
21121
+ End: 7
21122
+ };
21123
+ var SUFFIXES = ["alpha", "beta", "pre", "rc", "", "cvs", "svn", "git", "hg", "p"];
21124
+ var SUFFIX_NONE = 4;
21125
+ function isDigit2(char) {
21126
+ return char >= "0" && char <= "9";
21127
+ }
21128
+ function isLower(char) {
21129
+ return char >= "a" && char <= "z";
21130
+ }
21131
+ function isHex(char) {
21132
+ return isDigit2(char) || char >= "a" && char <= "f";
21133
+ }
21134
+ function span(text6, start, accept) {
21135
+ let end = start;
21136
+ while (end < text6.length && accept(text6.charAt(end)))
21137
+ end++;
21138
+ return end;
21139
+ }
21140
+ function validNumber(digits) {
21141
+ if (digits.length === 0)
21142
+ return false;
21143
+ const trimmed = digits.replace(/^0+/, "");
21144
+ return trimmed.length < UINT64_MAX.length || trimmed.length === UINT64_MAX.length && trimmed <= UINT64_MAX;
21145
+ }
21146
+ function tokenize(version3) {
21147
+ const tokens = [];
21148
+ let position2 = span(version3, 0, isDigit2);
21149
+ const initial = version3.slice(0, position2);
21150
+ if (!validNumber(initial))
21151
+ return null;
21152
+ tokens.push({ type: Token.InitialDigit, value: initial, suffix: 0 });
21153
+ let previous = Token.InitialDigit;
21154
+ while (position2 < version3.length) {
21155
+ const char = version3.charAt(position2);
21156
+ let type;
21157
+ let value;
21158
+ let suffix = 0;
21159
+ if (isLower(char)) {
21160
+ if (previous > Token.Digit)
21161
+ return null;
21162
+ type = Token.Letter;
21163
+ value = char;
21164
+ position2++;
21165
+ } else if (char === "." || isDigit2(char)) {
21166
+ if (char === ".") {
21167
+ if (previous > Token.Digit)
21168
+ return null;
21169
+ position2++;
21170
+ }
21171
+ if (previous === Token.InitialDigit || previous === Token.Digit)
21172
+ type = Token.Digit;
21173
+ else if (previous === Token.Suffix)
21174
+ type = Token.SuffixNo;
21175
+ else
21176
+ return null;
21177
+ const end = span(version3, position2, isDigit2);
21178
+ value = version3.slice(position2, end);
21179
+ if (!validNumber(value))
21180
+ return null;
21181
+ position2 = end;
21182
+ } else if (char === "_") {
21183
+ if (previous > Token.SuffixNo)
21184
+ return null;
21185
+ const end = span(version3, position2 + 1, isLower);
21186
+ value = version3.slice(position2 + 1, end);
21187
+ suffix = value.length === 0 ? -1 : SUFFIXES.indexOf(value);
21188
+ if (suffix < 0 || suffix === SUFFIX_NONE)
21189
+ return null;
21190
+ type = Token.Suffix;
21191
+ position2 = end;
21192
+ } else if (char === "~") {
21193
+ if (previous >= Token.CommitHash)
21194
+ return null;
21195
+ const end = span(version3, position2 + 1, isHex);
21196
+ value = version3.slice(position2 + 1, end);
21197
+ if (value.length === 0)
21198
+ return null;
21199
+ type = Token.CommitHash;
21200
+ position2 = end;
21201
+ } else if (char === "-") {
21202
+ if (previous >= Token.RevisionNo || version3.charAt(position2 + 1) !== "r")
21203
+ return null;
21204
+ const end = span(version3, position2 + 2, isDigit2);
21205
+ value = version3.slice(position2 + 2, end);
21206
+ if (!validNumber(value))
21207
+ return null;
21208
+ type = Token.RevisionNo;
21209
+ position2 = end;
21210
+ } else {
21211
+ return null;
21212
+ }
21213
+ tokens.push({ type, value, suffix });
21214
+ previous = type;
21215
+ }
21216
+ return tokens;
21217
+ }
21218
+ function sign2(value) {
21219
+ return value < 0 ? -1 : value > 0 ? 1 : 0;
21220
+ }
21221
+ function compareNumbers(a, b) {
21222
+ const left = a.replace(/^0+/, "");
21223
+ const right = b.replace(/^0+/, "");
21224
+ if (left.length !== right.length)
21225
+ return left.length < right.length ? -1 : 1;
21226
+ return left === right ? 0 : left < right ? -1 : 1;
21227
+ }
21228
+ function compareStrings(a, b) {
21229
+ return a === b ? 0 : a < b ? -1 : 1;
21230
+ }
21231
+ function compareTokens(a, b) {
21232
+ switch (a.type) {
21233
+ case Token.Digit:
21234
+ if (a.value.startsWith("0") || b.value.startsWith("0"))
21235
+ return compareStrings(a.value, b.value);
21236
+ return compareNumbers(a.value, b.value);
21237
+ case Token.InitialDigit:
21238
+ case Token.SuffixNo:
21239
+ case Token.RevisionNo:
21240
+ return compareNumbers(a.value, b.value);
21241
+ case Token.Suffix:
21242
+ return sign2(a.suffix - b.suffix);
21243
+ default:
21244
+ return compareStrings(a.value, b.value);
21245
+ }
21246
+ }
21247
+ function acceptable(value) {
21248
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_VERSION_LENGTH2;
21249
+ }
21250
+ function compareApkVersions(a, b) {
21251
+ if (!acceptable(a) || !acceptable(b))
21252
+ return null;
21253
+ const left = tokenize(a);
21254
+ const right = tokenize(b);
21255
+ if (left === null || right === null)
21256
+ return null;
21257
+ let index = 0;
21258
+ for (; index < left.length && index < right.length; index++) {
21259
+ const ta2 = left[index];
21260
+ const tb2 = right[index];
21261
+ if (ta2.type !== tb2.type)
21262
+ break;
21263
+ const result2 = compareTokens(ta2, tb2);
21264
+ if (result2 !== 0)
21265
+ return result2;
21266
+ }
21267
+ const ta = left[index];
21268
+ const tb = right[index];
21269
+ const typeA = ta === void 0 ? Token.End : ta.type;
21270
+ const typeB = tb === void 0 ? Token.End : tb.type;
21271
+ if (typeA === typeB)
21272
+ return 0;
21273
+ if (ta !== void 0 && ta.type === Token.Suffix && ta.suffix < SUFFIX_NONE)
21274
+ return -1;
21275
+ if (tb !== void 0 && tb.type === Token.Suffix && tb.suffix < SUFFIX_NONE)
21276
+ return 1;
21277
+ return typeA > typeB ? -1 : 1;
21278
+ }
21279
+
21280
+ // ../../packages/protocol/dist/security/osv-ranges.js
21281
+ function distroComparatorOf(ecosystem) {
21282
+ if (typeof ecosystem !== "string")
21283
+ return null;
21284
+ if (ecosystem === "Alpine" || ecosystem.startsWith("Alpine:"))
21285
+ return compareApkVersions;
21286
+ if (ecosystem === "Debian" || ecosystem.startsWith("Debian:"))
21287
+ return compareDpkgVersions;
21288
+ if (ecosystem === "Ubuntu" || ecosystem.startsWith("Ubuntu:"))
21289
+ return compareDpkgVersions;
21290
+ return null;
21291
+ }
21292
+ var epochOf = (version3) => /^(\d+):/.exec(version3)?.[1] ?? "0";
21293
+ function distroAtOrBelow(ecosystem, fix, version3) {
21294
+ const cmp = distroComparatorOf(ecosystem);
21295
+ if (cmp === null || typeof fix !== "string" || typeof version3 !== "string")
21296
+ return false;
21297
+ if (cmp === compareDpkgVersions && epochOf(fix) !== epochOf(version3))
21298
+ return false;
21299
+ const order2 = cmp(fix, version3);
21300
+ return order2 === -1 || order2 === 0;
21301
+ }
21302
+ function carriesEveryDistroFix(ecosystem, fixed, version3) {
21303
+ return Array.isArray(fixed) && fixed.length > 0 && fixed.every((fix) => distroAtOrBelow(ecosystem, fix, version3));
21304
+ }
21305
+
21109
21306
  // ../../packages/protocol/dist/security/redact.js
21110
21307
  var LOG_TEMPLATE_MAX = 300;
21111
21308
  var WHITESPACE_RUN = /[ \t\r\n\f\v]+/g;
@@ -21126,6 +21323,7 @@ var WPDB_QUERY_PATTERN = /\bfor query\s.*?(?=\smade by\s|$)/gi;
21126
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;
21127
21324
  var BEARER_PATTERN = /\b(Bearer|Basic)\s+(?!<secret>)[A-Za-z0-9._~+/=-]+/g;
21128
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;
21129
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;
21130
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;
21131
21329
  var AUTH_NOT_ALLOWED_PATTERN = /\b(User) (.{1,120})(?= from \S+ not allowed because\b)/g;
@@ -21202,6 +21400,7 @@ function redactLogMessage(message, options = {}) {
21202
21400
  result2 = result2.replace(URL_PATTERN, "<url>");
21203
21401
  result2 = result2.replace(EMAIL_PATTERN, "<email>");
21204
21402
  result2 = result2.replace(SSH_FINGERPRINT_PATTERN, "SHA256:<fingerprint>");
21403
+ result2 = result2.replace(WINDOWS_ACCOUNT_PATTERN, "$1$2<account>");
21205
21404
  if (AUTH_LINE.test(result2)) {
21206
21405
  result2 = result2.replace(AUTH_NOT_ALLOWED_PATTERN, "$1 <user>");
21207
21406
  result2 = result2.replace(AUTH_USER_PATTERN, "$1 <user>");
@@ -21470,7 +21669,7 @@ function ratingOfCvss(score) {
21470
21669
  var WINDOWS_ECOSYSTEM = "windows";
21471
21670
 
21472
21671
  // ../../packages/protocol/dist/security/components.js
21473
- var COMPONENT_RULES_VERSION = "2026-11-11.3";
21672
+ var COMPONENT_RULES_VERSION = "2026-11-19.1";
21474
21673
  var DAEMON_PACKAGES = Object.freeze([
21475
21674
  "openssh-server",
21476
21675
  "postfix",
@@ -21535,7 +21734,7 @@ var PLATFORM_NAMES = Object.freeze({
21535
21734
  });
21536
21735
 
21537
21736
  // ../../packages/protocol/dist/security/buckets.js
21538
- var BUCKET_RULES_VERSION = "2026-11-11.1";
21737
+ var BUCKET_RULES_VERSION = "2026-11-13.3";
21539
21738
  var FINDING_BUCKETS = ["action_required", "waiting_vendor", "verify", "low"];
21540
21739
  var OPEN = /* @__PURE__ */ new Set(["confirmed", "potential", "unknown"]);
21541
21740
  var LOW_RATINGS = /* @__PURE__ */ new Set(["low", "negligible"]);
@@ -21543,6 +21742,8 @@ function bucketOf(row) {
21543
21742
  if (!OPEN.has(row.class))
21544
21743
  return null;
21545
21744
  const fix = row.fix_state ?? "unknown";
21745
+ if (row.verify_reason === "client_only")
21746
+ return { bucket: "verify", rule: 4, route: null, urgent: row.kev, reason: "client_only" };
21546
21747
  if (row.kev && (row.class === "confirmed" || row.class === "potential")) {
21547
21748
  return fix === "fix" ? { bucket: "action_required", rule: 1, route: "fix", urgent: false } : { bucket: "verify", rule: 1, route: null, urgent: true };
21548
21749
  }
@@ -21554,13 +21755,15 @@ function bucketOf(row) {
21554
21755
  return { bucket: "verify", rule: 4, route: null, urgent: false };
21555
21756
  return { bucket: "low", rule: 5, route: null, urgent: false };
21556
21757
  }
21557
- var BUCKET_RULES_VERSION_V2 = "2026-11-11.v2";
21758
+ var BUCKET_RULES_VERSION_V2 = "2026-11-13.3.v2";
21558
21759
  var FINDING_BUCKETS_V2 = [...FINDING_BUCKETS, "accepted"];
21559
21760
  function bucketOfV2(row) {
21560
21761
  if (!OPEN.has(row.class) || row.applicability === "not_affected")
21561
21762
  return null;
21562
21763
  const urgent = row.kev || row.vendor_critical && row.reachable;
21563
21764
  if (row.applicability === "unverified" || row.applicability === "affected" && (row.fix_state === null || row.fix_state === "unknown")) {
21765
+ if (row.verify_reason)
21766
+ return { bucket: "verify", rule: 3, route: null, urgent, reason: row.verify_reason };
21564
21767
  return urgent || row.fix_state === "fix" ? { bucket: "verify", rule: 3, route: null, urgent } : { bucket: "waiting_vendor", rule: 3, route: null, urgent: false };
21565
21768
  }
21566
21769
  if (row.applicability === "affected" && row.fix_state === "fix")
@@ -21731,8 +21934,32 @@ var APPLICABILITY_REASON_TEXT = Object.freeze({
21731
21934
  wrong_arch: "The affected kernel code is for another processor architecture.",
21732
21935
  upstream_fixed_before_series: "The upstream fix is older than this kernel series, but the vendor still lists it.",
21733
21936
  owner_not_affected: "The owner recorded that this does not apply here.",
21734
- owner_false_positive: "The owner recorded this match as a false positive."
21735
- });
21937
+ owner_false_positive: "The owner recorded this match as a false positive.",
21938
+ installed_carries_fix: "The installed version is outside every affected range of this advisory.",
21939
+ inconsistent_range: "The installed version is outside every affected range of this advisory; its version range is inconsistent (a fix below its start) and was read as affected below that fix.",
21940
+ version_unparsed: "The installed version or a bound of the advisory's version range could not be compared locally; the advisory database's match stands.",
21941
+ fix_on_newer_line: "The fix is only on a newer release line; whether it affects the installed line is not confirmed. Check the vendor's advisory for the installed line.",
21942
+ client_only: "Only the OpenSSH client is installed (no sshd service): server flaws do not apply unless sshd is installed; client flaws may still apply, so check first."
21943
+ });
21944
+ var LOCAL_REASONS = /* @__PURE__ */ new Set(["installed_carries_fix", "inconsistent_range", "version_unparsed", "fix_on_newer_line"]);
21945
+ function localRangeCheckOf(input2) {
21946
+ const { ecosystem, installed, matches } = input2;
21947
+ const noticeFixes = input2.notice_fixes ?? [];
21948
+ if (distroComparatorOf(ecosystem) === null || matches.length === 0)
21949
+ return null;
21950
+ const notices = noticeFixes.length === 0 || carriesEveryDistroFix(ecosystem, noticeFixes, installed);
21951
+ const said = (match) => match.local_check && LOCAL_REASONS.has(match.local_check.reason) ? match.local_check.value : null;
21952
+ if (notices && matches.every((match) => said(match) === "not_affected")) {
21953
+ return { value: "not_affected", reason: matches.some((match) => match.local_check?.reason === "inconsistent_range") ? "inconsistent_range" : "installed_carries_fix" };
21954
+ }
21955
+ const unverified = matches.some((match) => said(match) === "unverified");
21956
+ const hinted = (match) => said(match) !== null || match.branch === "fix_on_newer_line";
21957
+ if (matches.every(hinted) && matches.some((match) => said(match) !== "not_affected")) {
21958
+ return { value: "unverified", reason: unverified ? "version_unparsed" : "fix_on_newer_line" };
21959
+ }
21960
+ return null;
21961
+ }
21962
+ var CLIENT_ONLY_KEV_TEXT = `This advisory is listed as exploited (CISA KEV): check it first. ${APPLICABILITY_REASON_TEXT.client_only}`;
21736
21963
  function runningKernelFacts(facts) {
21737
21964
  const kernel = facts?.kernel ?? null;
21738
21965
  return kernel !== null && facts.running_kernel !== null && kernel.release === facts.running_kernel ? kernel : null;
@@ -21777,9 +22004,14 @@ function applicabilityOf(input2) {
21777
22004
  return vendor("unverified", "vendor_status_unknown");
21778
22005
  return vendor("not_affected", "vendor_not_affected");
21779
22006
  }
22007
+ const local = input2.local_check ?? null;
22008
+ if (local?.value === "not_affected")
22009
+ return { value: "not_affected", basis: "local_range_check", reason: local.reason, evidence: { vendor_status: status } };
21780
22010
  const host = hostRuleResult(input2);
21781
22011
  if (host !== null)
21782
22012
  return host;
22013
+ if (component.role === "client_only")
22014
+ return { value: "unverified", basis: "host_evidence", reason: "client_only", evidence: { vendor_status: status, facts: { role: "client_only" } } };
21783
22015
  if (matches.every((match) => match.undetermined === true))
21784
22016
  return { value: "unverified", basis: "range_only", reason: "undetermined", evidence: { vendor_status: status } };
21785
22017
  if (deciding !== null && deciding.undetermined !== true && isDistroEcosystem(component.ecosystem)) {
@@ -21932,9 +22164,9 @@ function riskInputsOf(args) {
21932
22164
  }
21933
22165
 
21934
22166
  // ../../packages/protocol/dist/security/matching.js
21935
- var MATCHING_RULES_VERSION = "2026-11-11.3";
22167
+ var MATCHING_RULES_VERSION = "2026-11-19.1";
21936
22168
  var EVALUATION_RULES_VERSION = [COMPONENT_RULES_VERSION, MATCHING_RULES_VERSION, RISK_RULES_VERSION, BUCKET_RULES_VERSION].join("+");
21937
- var MATCHING_RULES_VERSION_V2 = "2026-11-11.v2";
22169
+ var MATCHING_RULES_VERSION_V2 = "2026-11-19.1.v2";
21938
22170
  var EVALUATION_RULES_VERSION_V2 = [COMPONENT_RULES_VERSION, MATCHING_RULES_VERSION_V2, RISK_RULES_VERSION_V2, BUCKET_RULES_VERSION_V2].join("+");
21939
22171
  var OPEN_CLASSES = ["confirmed", "potential", "unknown"];
21940
22172
  var isOpenClass = (value) => OPEN_CLASSES.includes(value);
@@ -22081,15 +22313,13 @@ function stagedStatusOf(group3, hostHasEsm) {
22081
22313
  const status = deciding.match.vendor_status;
22082
22314
  return status?.status === "fix_staged" && status.source === "ubuntu-tracker" && typeof status.version === "string" && status.version !== "" ? status : null;
22083
22315
  }
22084
- var epochOf = (version3) => /^(\d+):/.exec(version3)?.[1] ?? "0";
22316
+ var dpkgAtOrBelow = (fix, other) => distroAtOrBelow("Debian", fix, other);
22317
+ var carriesEveryFix = (ecosystem, fixed, version3) => carriesEveryDistroFix(ecosystem, fixed, version3);
22085
22318
  function stagedTarget(status, component, next, candidate) {
22086
22319
  if (status === null || status.version === null)
22087
22320
  return null;
22088
22321
  const version3 = status.version;
22089
- const atOrBelow = (other) => {
22090
- const order2 = typeof other === "string" && epochOf(version3) === epochOf(other) ? compareDpkgVersions(version3, other) : null;
22091
- return order2 === -1 || order2 === 0;
22092
- };
22322
+ const atOrBelow = (other) => dpkgAtOrBelow(version3, other);
22093
22323
  if (atOrBelow(component.version))
22094
22324
  return { version: version3, installed: true, next_kernel: null, candidate_kernel: null };
22095
22325
  if (component.role === "running_kernel") {
@@ -22112,6 +22342,8 @@ function evaluateAsset(input2) {
22112
22342
  const v2 = input2.rules === "v2";
22113
22343
  const facts = input2.facts ?? null;
22114
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);
22115
22347
  const previousBy = new Map(previous.map((row) => [`${row.finding_id}\0${row.component_key}`, row]));
22116
22348
  const events = [];
22117
22349
  if (lookup2 === null || context.receivedAtMs === null) {
@@ -22136,6 +22368,7 @@ function evaluateAsset(input2) {
22136
22368
  }
22137
22369
  const stale = context.nowMs > context.receivedAtMs + context.staleAfterMs;
22138
22370
  const hostHasEsm = input2.components.some((component) => component.origin === "esm" || component.ecosystem.startsWith("Ubuntu:Pro:"));
22371
+ const proChannelFor = (component) => hostHasEsm && component.source === "dpkg";
22139
22372
  const pendingKeys = /* @__PURE__ */ new Set();
22140
22373
  const pendingComponents = [];
22141
22374
  const pendingBefore = new Map((input2.previousPending ?? []).map((entry) => [entry.component_key, entry.since_ms]));
@@ -22151,11 +22384,18 @@ function evaluateAsset(input2) {
22151
22384
  const [ecosystem = "", name3 = ""] = componentKey.split("|");
22152
22385
  return packageKey(ecosystem, name3);
22153
22386
  };
22387
+ const isImageKernelRow = (row) => {
22388
+ if (row.source !== "image" || !input2.imageKernelNames)
22389
+ return false;
22390
+ const [ecosystem = "", name3 = ""] = row.component_key.split("|");
22391
+ return input2.imageKernelNames.has(`${ecosystem}|${name3}`);
22392
+ };
22154
22393
  const isLeftOut = (component) => component.duplicate_of !== void 0 || component.revision_banner === true;
22155
22394
  const present = new Set(input2.components.filter((component) => !component.hidden && !isLeftOut(component)).map((component) => component.key));
22395
+ const imageKernelKeys = new Set(previous.filter(isImageKernelRow).map((row) => row.component_key));
22156
22396
  const carriedWaiting = /* @__PURE__ */ new Map();
22157
22397
  for (const key of Object.keys(input2.previousWaiting ?? {}).sort()) {
22158
- if (!present.has(key) && !carriedWaiting.has(packageOf2(key)))
22398
+ if (!present.has(key) && !imageKernelKeys.has(key) && !carriedWaiting.has(packageOf2(key)))
22159
22399
  carriedWaiting.set(packageOf2(key), key);
22160
22400
  }
22161
22401
  const previousWaitingOf = (component) => {
@@ -22252,21 +22492,42 @@ function evaluateAsset(input2) {
22252
22492
  for (const group3 of v2 ? groups : []) {
22253
22493
  if (group3.component.role !== "running_kernel")
22254
22494
  continue;
22255
- const target = stagedTarget(stagedStatusOf(group3, hostHasEsm), group3.component, nextKernelVersion, candidateKernelVersion);
22495
+ const target = stagedTarget(stagedStatusOf(group3, proChannelFor(group3.component)), group3.component, nextKernelVersion, candidateKernelVersion);
22256
22496
  if (target && !target.installed)
22257
22497
  stagedKernel.set(group3.canonical, target);
22258
22498
  }
22259
22499
  const closes = kernelCloses(next, candidate, runningAdvisories, stagedKernel);
22260
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
+ };
22261
22516
  const carry = /* @__PURE__ */ new Map();
22262
22517
  for (const row of previous) {
22263
- if (!isOpenClass(row.class) || present.has(row.component_key) || leftOut.has(row.component_key))
22518
+ if (!isOpenClass(row.class) || present.has(row.component_key) || leftOut.has(row.component_key) || isImageKernelRow(row))
22519
+ continue;
22520
+ if (row.source !== "image" && ownSourceUnseen(row))
22264
22521
  continue;
22265
22522
  const key = `${row.finding_id}\0${packageOf2(row.component_key)}`;
22266
22523
  const held = carry.get(key);
22267
22524
  if (!held || row.component_key < held.component_key)
22268
22525
  carry.set(key, row);
22269
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();
22270
22531
  const findingViews = /* @__PURE__ */ new Map();
22271
22532
  const rows = [];
22272
22533
  const settledRows = [];
@@ -22287,17 +22548,28 @@ function evaluateAsset(input2) {
22287
22548
  let fixState = states.includes("fix") || group3.noticeFixes.length > 0 ? "fix" : states.includes("no_fix") ? "no_fix" : "unknown";
22288
22549
  const deciding = group3.matches.find((match) => matchFixState2(match) === fixState) ?? group3.matches[0];
22289
22550
  const proFixed = fixState === "no_fix" ? [...new Set(group3.matches.flatMap((match) => match.pro_fixed ?? []))].slice(0, 20) : [];
22290
- const channel = proFixed.length > 0 && hostHasEsm ? "pro" : null;
22551
+ const channel = proFixed.length > 0 && proChannelFor(component) ? "pro" : null;
22291
22552
  if (channel)
22292
22553
  fixState = "fix";
22293
22554
  const exposure = component.exposure_unresolved ? "unknown" : component.exposure;
22294
- 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];
22295
22559
  let risk;
22296
22560
  let bucket;
22297
22561
  let rowClass = cls;
22298
22562
  let extra = {};
22299
22563
  let staged = null;
22564
+ const local = localRangeCheckOf({ ecosystem: component.ecosystem, installed: component.version, matches: group3.matches, notice_fixes: group3.noticeFixes });
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);
22300
22570
  if (!v2) {
22571
+ if (local?.value === "not_affected")
22572
+ rowClass = "not_affected";
22301
22573
  risk = riskScore({
22302
22574
  cvss: cvss?.score ?? null,
22303
22575
  rating: severity.rating,
@@ -22308,10 +22580,17 @@ function evaluateAsset(input2) {
22308
22580
  exposure,
22309
22581
  production: context.production,
22310
22582
  criticality: context.criticality,
22311
- class: cls,
22583
+ class: rowClass,
22312
22584
  fix_state: fixState
22313
22585
  });
22314
- bucket = bucketOf({ class: cls, fix_state: fixState, severity: severity.rating, kev });
22586
+ bucket = rowClass === "not_affected" ? { bucket: null, rule: 2, route: null } : bucketOf({
22587
+ class: cls,
22588
+ fix_state: fixState,
22589
+ severity: severity.rating,
22590
+ kev,
22591
+ verify_reason: clientOnly ? "client_only" : null
22592
+ });
22593
+ extra = local ? { local_check: local, ...rowClass === "not_affected" ? { closed: "local_range_check" } : {} } : {};
22315
22594
  } else {
22316
22595
  const inputs = riskInputsOf({
22317
22596
  views: group3.views,
@@ -22324,10 +22603,21 @@ function evaluateAsset(input2) {
22324
22603
  const vendorCritical = inputs.vendor_rating === "critical" && !inputs.vendor_rating_derived;
22325
22604
  const decidingOsv = decidingOsvEntry(group3, fixState);
22326
22605
  const previousRule = before?.applicability?.value === "not_affected" && before.applicability.basis === "host_evidence" ? before.applicability.evidence?.rule ?? null : null;
22327
- const applicability = applicabilityOf({ component, matches: group3.matches, views: group3.views, facts, fix_state: fixState, kev, vendor_critical: vendorCritical, previous_rule: previousRule });
22606
+ const applicability = applicabilityOf({
22607
+ component,
22608
+ matches: group3.matches,
22609
+ views: group3.views,
22610
+ facts,
22611
+ fix_state: fixState,
22612
+ kev,
22613
+ vendor_critical: vendorCritical,
22614
+ previous_rule: previousRule,
22615
+ local_check: local
22616
+ });
22617
+ const byLocal = applicability.basis === "local_range_check" ? local : null;
22328
22618
  const mitigation = applicability.value === "affected" && applicability.reason !== "vendor_status_unknown" ? mitigationOf({ view: decidingOsv?.view ?? null, component, facts }) : null;
22329
22619
  const settles = applicability.value === "not_affected";
22330
- staged = settles ? null : stagedTarget(stagedStatusOf(group3, hostHasEsm), component, nextKernelVersion, candidateKernelVersion);
22620
+ staged = settles ? null : stagedTarget(stagedStatusOf(group3, proChannelFor(component)), component, nextKernelVersion, candidateKernelVersion);
22331
22621
  const stagedInstalled = staged?.installed === true;
22332
22622
  if (staged)
22333
22623
  fixState = "fix";
@@ -22344,7 +22634,8 @@ function evaluateAsset(input2) {
22344
22634
  kev,
22345
22635
  vendor_critical: vendorCritical,
22346
22636
  reachable: inputs.reachable,
22347
- mitigation
22637
+ mitigation,
22638
+ verify_reason: applicability.reason === "client_only" ? "client_only" : null
22348
22639
  });
22349
22640
  bucket = settles || stagedInstalled ? { bucket: null, rule: 2, route: null } : result2;
22350
22641
  extra = {
@@ -22354,7 +22645,9 @@ function evaluateAsset(input2) {
22354
22645
  risk_inputs: inputs,
22355
22646
  urgent: stagedInstalled ? false : result2?.urgent ?? false,
22356
22647
  mitigation_id: stagedInstalled ? null : mitigation?.id ?? null,
22357
- ...settles ? { closed: applicability.basis === "host_evidence" ? "host_not_affected" : "vendor_not_affected" } : stagedInstalled ? { closed: "vendor_fix_staged_installed" } : {}
22648
+ ...settles ? { closed: applicability.basis === "host_evidence" ? "host_not_affected" : byLocal ? "local_range_check" : "vendor_not_affected" } : stagedInstalled ? { closed: "vendor_fix_staged_installed" } : {},
22649
+ // The unverified check is a note on an open row only.
22650
+ ...byLocal ? { local_check: byLocal } : local?.value === "unverified" && !settles && !stagedInstalled ? { local_check: local } : {}
22358
22651
  };
22359
22652
  }
22360
22653
  const settled = rowClass === "not_affected" || rowClass === "fixed";
@@ -22362,10 +22655,12 @@ function evaluateAsset(input2) {
22362
22655
  const role = component.role ?? null;
22363
22656
  const nextVersion = (role === "running_kernel" && next?.advisories && !next.advisories.has(group3.canonical) ? next.component.version : null) ?? staged?.next_kernel ?? null;
22364
22657
  const candidateVersion = (role === "running_kernel" && candidate?.advisories && !candidate.advisories.has(group3.canonical) ? candidate.component.version : null) ?? staged?.candidate_kernel ?? null;
22365
- 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;
22366
22661
  const summary = before || carried || settled ? void 0 : previousWaitingOf(component);
22367
22662
  const fromSummary = summary !== void 0 && previousListed(component).has(group3.canonical);
22368
- 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;
22369
22664
  const why = {
22370
22665
  rule: bucket.rule,
22371
22666
  severity: { rating: severity.rating, source: severity.source },
@@ -22403,6 +22698,7 @@ function evaluateAsset(input2) {
22403
22698
  candidate_kernel: candidateVersion,
22404
22699
  kernel_target: role === "running_kernel" ? kernelTarget : null,
22405
22700
  previous_component_key: carried?.component_key ?? null,
22701
+ ...moved ? { previous_finding_id: moved.finding_id } : {},
22406
22702
  first_seen_hint_ms: firstSeenHint,
22407
22703
  evidence: {
22408
22704
  advisory_ids: [...new Set(group3.views.map((view) => view.id))].sort(),
@@ -22424,6 +22720,8 @@ function evaluateAsset(input2) {
22424
22720
  epss_percentile: epssPercentile,
22425
22721
  candidate: component.candidate ?? null,
22426
22722
  exposure: component.exposure ?? null,
22723
+ ...component.image_state ? { image_state: component.image_state, images: component.images ?? [] } : {},
22724
+ ...clientOnly ? { client_only: true } : {},
22427
22725
  rules: v2 ? MATCHING_RULES_VERSION_V2 : MATCHING_RULES_VERSION,
22428
22726
  risk_rules: v2 ? RISK_RULES_VERSION_V2 : RISK_RULES_VERSION,
22429
22727
  ...extra
@@ -22482,13 +22780,31 @@ function evaluateAsset(input2) {
22482
22780
  modified: views.map((view) => view.modified).filter((value) => Boolean(value)).sort().at(-1) ?? null
22483
22781
  });
22484
22782
  }
22485
- const presentPackages = new Set(visible.map((component) => packageKey(component.ecosystem, component.name)));
22486
- const pendingPackages = new Set(visible.filter((component) => pendingKeys.has(component.key)).map((component) => packageKey(component.ecosystem, component.name)));
22783
+ const pendingPackages = /* @__PURE__ */ new Map();
22784
+ for (const component of visible) {
22785
+ if (!pendingKeys.has(component.key))
22786
+ continue;
22787
+ const key = packageKey(component.ecosystem, component.name);
22788
+ pendingPackages.set(key, [...pendingPackages.get(key) ?? [], component]);
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
+ }
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);
22487
22798
  const produced = new Set([...rows, ...settledRows].map((row) => `${row.finding_id}\0${row.component_key}`));
22488
- 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}`));
22489
22800
  const closed = [];
22490
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
+ }
22491
22805
  for (const row of previous) {
22806
+ if (movedRows.has(rowKey(row)))
22807
+ continue;
22492
22808
  if (!isOpenClass(row.class) || produced.has(`${row.finding_id}\0${row.component_key}`))
22493
22809
  continue;
22494
22810
  if (pendingKeys.has(row.component_key))
@@ -22499,16 +22815,42 @@ function evaluateAsset(input2) {
22499
22815
  if (incomplete.banner)
22500
22816
  continue;
22501
22817
  closing = closedRow(row, "not_affected", leftOutReason);
22818
+ } else if (!present.has(row.component_key) && isImageKernelRow(row)) {
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;
22502
22824
  } else if (!present.has(row.component_key)) {
22503
- const [ecosystem = "", name3 = ""] = row.component_key.split("|");
22825
+ const [ecosystem = "", name3 = "", version3 = ""] = row.component_key.split("|");
22504
22826
  if (presentPackages.has(packageKey(ecosystem, name3))) {
22505
- if (pendingPackages.has(packageKey(ecosystem, name3)))
22506
- continue;
22507
- if (carriedOn.has(`${row.finding_id}\0${row.component_key}`)) {
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);
22830
+ if (newVersions) {
22831
+ const fixedNow = !carriedOn.has(`${row.finding_id}\0${row.component_key}`) && [...newVersions, ...unanswered].every(carriesFix);
22832
+ if (!fixedNow) {
22833
+ marked.push({
22834
+ finding_id: row.finding_id,
22835
+ component_key: row.component_key,
22836
+ mark: "carried_from",
22837
+ installed_version: version3,
22838
+ current_version: lowestPending(newVersions).version,
22839
+ reason: "new_version_pending"
22840
+ });
22841
+ continue;
22842
+ }
22843
+ } else if (carriedOn.has(`${row.finding_id}\0${row.component_key}`)) {
22508
22844
  closed.push({ finding_id: row.finding_id, component_key: row.component_key, class: "fixed", reason: "superseded", score: 0, band: "none" });
22509
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
+ }
22510
22852
  }
22511
- closing = closedRow(row, "fixed", "component_changed");
22853
+ closing = unanswered.every(carriesFix) ? closedRow(row, "fixed", "component_changed") : closedRow(row, "unknown", "not_comparable");
22512
22854
  } else if (ecosystem === "cpe") {
22513
22855
  if (incomplete.banner)
22514
22856
  continue;
@@ -22874,6 +23216,32 @@ function safeParseCapabilityPayload(capability2, payload) {
22874
23216
  return { success: true, data };
22875
23217
  }
22876
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
+
22877
23245
  // ../../packages/protocol/dist/connectors/desktop.js
22878
23246
  var DESKTOP_CAPABILITIES = Object.freeze([
22879
23247
  "files.list",
@@ -22894,7 +23262,7 @@ var MAX_READ_BYTES = 256 * 1024;
22894
23262
  var MAX_EDIT_FILE_BYTES = 8 * 1024 * 1024;
22895
23263
  var MAX_EDIT_TEXT_BYTES = 48 * 1024;
22896
23264
  var MAX_EDIT_REPLACEMENTS = 1e3;
22897
- 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");
22898
23266
  var sha256 = external_exports.string().regex(/^[a-f0-9]{64}$/);
22899
23267
  var filePayloadSchemas = {
22900
23268
  "files.list": external_exports.strictObject({ path: relativePath }),
@@ -23971,7 +24339,7 @@ async function verifyEd25519(publicKeyB64u2, message, signatureB64u) {
23971
24339
  }
23972
24340
  }
23973
24341
 
23974
- // ../../packages/protocol/dist/security/dispositions.js
24342
+ // ../../packages/protocol/dist/security/disposition-constants.js
23975
24343
  var JUSTIFICATIONS = Object.freeze({
23976
24344
  not_affected: [
23977
24345
  "component_not_present",
@@ -23982,9 +24350,13 @@ var JUSTIFICATIONS = Object.freeze({
23982
24350
  ],
23983
24351
  false_positive: ["wrong_component_identity", "version_outside_range", "vendor_states_not_affected"],
23984
24352
  mitigated: ["configuration_changed", "network_restricted", "feature_disabled", "compensating_control"],
23985
- 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"]
23986
24356
  });
23987
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
23988
24360
  var CHECK_SECTIONS = Object.freeze({
23989
24361
  "os.release": null,
23990
24362
  "kernel.release": "kernel",
@@ -24078,6 +24450,24 @@ var SECTION_COLLECTORS = Object.freeze({
24078
24450
  docker: "host-docker"
24079
24451
  });
24080
24452
 
24453
+ // ../../packages/protocol/dist/security/posture-independent.js
24454
+ var INDEPENDENT_LIMITS = Object.freeze({
24455
+ /** The most all failed hardening checks together deduct. */
24456
+ advanced_cap: 40,
24457
+ /** Per exploited (KEV) vulnerability waiting for a vendor fix. */
24458
+ exploited_without_fix_points: 10,
24459
+ /** The most the exploited vulnerabilities without a vendor fix together deduct. */
24460
+ exploited_without_fix_cap: 20
24461
+ });
24462
+ var INDEPENDENT_REASON_TEXT = Object.freeze({
24463
+ official_not_rated: "The official score is not rated yet, so there is nothing to start from.",
24464
+ official_provisional: "The official score is provisional.",
24465
+ hardening_unknown: "The advanced security checks have not run on this asset; they deduct nothing until they do.",
24466
+ checks_not_read: "Some advanced security checks could not be read; 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."
24469
+ });
24470
+
24081
24471
  // ../../packages/protocol/dist/http.js
24082
24472
  var HTTP_API_VERSION = 1;
24083
24473
  var requestIdSchema = external_exports.uuid();
@@ -24159,28 +24549,6 @@ var unservedVerifiedOverviewSchema = external_exports.strictObject({
24159
24549
  ctx.addIssue({ code: "custom", message: "DUPLICATE_SCOPED_DEVICE" });
24160
24550
  });
24161
24551
 
24162
- // ../../packages/protocol/dist/paths.js
24163
- var DEFAULT_DENY_GLOBS = Object.freeze([
24164
- ".git/**",
24165
- "**/.git/**",
24166
- "**/.env*",
24167
- "**/*.pem",
24168
- "**/*.key",
24169
- "**/.ssh/**",
24170
- "**/id_rsa*",
24171
- "**/id_ed25519*",
24172
- "**/.aws/**",
24173
- "**/.netrc",
24174
- "**/.npmrc",
24175
- "**/.git-credentials",
24176
- "**/.gnupg/**",
24177
- "**/.config/gh/**",
24178
- "**/.kube/**",
24179
- "**/.docker/config.json",
24180
- "**/.conbridge/**",
24181
- "**/Library/Keychains/**"
24182
- ]);
24183
-
24184
24552
  // ../../packages/protocol/dist/index.js
24185
24553
  var moduleInfo = Object.freeze({ name: "@conbridge/protocol", runtime: "shared", status: "scaffold-only" });
24186
24554
 
@@ -24216,7 +24584,7 @@ var import_node_fs = require("node:fs");
24216
24584
  var import_node_path = require("node:path");
24217
24585
  var import_node_sea = require("node:sea");
24218
24586
  var import_node_url = require("node:url");
24219
- var SOURCE_VERSION = "0.8.0";
24587
+ var SOURCE_VERSION = "0.9.0";
24220
24588
  var BUILD_INFO = typeof define_CONBRIDGE_BUILD_default === "object" && define_CONBRIDGE_BUILD_default !== null ? define_CONBRIDGE_BUILD_default : null;
24221
24589
  var AGENT_VERSION = BUILD_INFO?.version ?? SOURCE_VERSION;
24222
24590
  function runningAsSea() {
@@ -24573,8 +24941,8 @@ function windowsPath(value) {
24573
24941
  }
24574
24942
  var vbsString = (value) => '"' + value.replace(/"/g, '""') + '"';
24575
24943
  function buildWindowsLauncher(options) {
24576
- const quoted = programArguments(options).map((arg2, index, all) => index === all.length - 1 ? arg2 : `"${windowsPath(arg2)}"`).join(" ");
24577
- 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"`;
24578
24946
  return [
24579
24947
  "' ConBridge Desktop Agent launcher (Task Scheduler). Generated by conbridge-agent service install.",
24580
24948
  "Option Explicit",
@@ -24765,6 +25133,17 @@ var identitySchema = external_exports.strictObject({
24765
25133
  destroy_deadline_ms: external_exports.number().int().nonnegative().nullable().optional(),
24766
25134
  key_store: keyStoreDescriptorSchema.optional()
24767
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
+ }
24768
25147
  var rootSchema = external_exports.strictObject({
24769
25148
  root_id: external_exports.uuid(),
24770
25149
  path: external_exports.string().min(1).refine((value) => (0, import_node_path4.isAbsolute)(value), "Root path must be absolute"),
@@ -24784,7 +25163,14 @@ var configSchema = external_exports.strictObject({
24784
25163
  */
24785
25164
  full_access: external_exports.boolean().optional(),
24786
25165
  /** Software inventory (ADR DEVICE_INVENTORY): the computer's own switch; the owner turns it on in the Console. Absent = allowed. */
24787
- 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()
24788
25174
  });
24789
25175
  function defaultConfig() {
24790
25176
  return { version: 1, roots: [], deny_globs: [...DEFAULT_DENY_GLOBS], confirm_writes: false };
@@ -24845,7 +25231,8 @@ async function addRoot(paths, input2) {
24845
25231
  if (label.length < 1 || label.length > 128)
24846
25232
  throw new Error("Label must be 1 to 128 characters");
24847
25233
  const root = { root_id: (0, import_node_crypto2.randomUUID)(), path: real, label, writable: input2.writable };
24848
- 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 } : {} });
24849
25236
  return root;
24850
25237
  }
24851
25238
  async function removeRoot(paths, rootId) {
@@ -24853,9 +25240,14 @@ async function removeRoot(paths, rootId) {
24853
25240
  const roots = config2.roots.filter((root) => root.root_id !== rootId);
24854
25241
  if (roots.length === config2.roots.length)
24855
25242
  return false;
24856
- 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 } : {} });
24857
25245
  return true;
24858
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
+ }
24859
25251
 
24860
25252
  // dist/keystore.js
24861
25253
  var import_node_path5 = require("node:path");
@@ -25718,21 +26110,45 @@ var import_node_util2 = require("node:util");
25718
26110
  var import_node_child_process5 = require("node:child_process");
25719
26111
  var import_node_path9 = require("node:path");
25720
26112
  var CONFIRM_TIMEOUT_MS = 13e4;
25721
- function confirmText(request) {
25722
- const verb = request.created ? "create" : "overwrite";
25723
- 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, " ")}"`;
25724
26116
  }
25725
- function appleScriptString(value) {
25726
- 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.`;
25727
26138
  }
25728
- function buildConfirmScript(request) {
25729
- 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)];
25730
26146
  }
25731
26147
  var macDialogConfirm = (request) => {
25732
26148
  if (process.platform !== "darwin")
25733
26149
  return Promise.resolve(false);
25734
26150
  return new Promise((resolve10) => {
25735
- (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) => {
25736
26152
  if (error63)
25737
26153
  return resolve10(false);
25738
26154
  resolve10(/button returned:Allow/.test(stdout) && !/gave up:true/.test(stdout));
@@ -25748,16 +26164,23 @@ var windowsConfirm = (request) => new Promise((resolve10) => {
25748
26164
  const powershell = import_node_path9.win32.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
25749
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));
25750
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
+ }
25751
26174
  var linuxConfirm = (request) => new Promise((resolve10) => {
25752
26175
  if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY)
25753
26176
  return resolve10(false);
25754
26177
  const text6 = confirmText(request);
25755
- (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) => {
25756
26179
  if (!error63)
25757
26180
  return resolve10(true);
25758
26181
  if (error63.code !== "ENOENT")
25759
26182
  return resolve10(false);
25760
- (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));
25761
26184
  });
25762
26185
  });
25763
26186
  var localConfirm = (request) => {
@@ -25772,7 +26195,220 @@ var localConfirm = (request) => {
25772
26195
 
25773
26196
  // dist/connect.js
25774
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");
25775
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
+ }
25776
26412
 
25777
26413
  // dist/pairing.js
25778
26414
  var PAIRING_CODE = /^[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}-?[ABCDEFGHJKLMNPQRSTUVWXYZ23456789]{4}$/;
@@ -25806,7 +26442,12 @@ function normalizePairingCode(input2) {
25806
26442
  return code.includes("-") ? code : `${code.slice(0, 4)}-${code.slice(4)}`;
25807
26443
  }
25808
26444
  var POLL_TOKEN_HEADER = "X-ConBridge-Poll-Token";
25809
- 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
+ });
25810
26451
  var statusResponseSchema = external_exports.discriminatedUnion("state", [
25811
26452
  external_exports.object({
25812
26453
  state: external_exports.literal("approved"),
@@ -25821,6 +26462,83 @@ var statusResponseSchema = external_exports.discriminatedUnion("state", [
25821
26462
  external_exports.object({ state: external_exports.enum(["open", "offered", "pending"]) }),
25822
26463
  external_exports.object({ state: external_exports.enum(["denied", "expired"]) })
25823
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
+ }
25824
26542
  var PairingError = class extends Error {
25825
26543
  state;
25826
26544
  constructor(state2, message) {
@@ -25860,7 +26578,15 @@ async function pairDevice(options) {
25860
26578
  headers: { "content-type": "application/json" },
25861
26579
  body: JSON.stringify({ code, public_key: publicKeyB64u(key), display_name: name3, platform: platform2, capabilities: [LIFECYCLE_CAPABILITY] })
25862
26580
  }), "Pairing offer"));
25863
- 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");
25864
26590
  const deadline = Date.now() + (options.timeoutMs ?? 11 * 6e4);
25865
26591
  const query = new URLSearchParams({ pairing_id: offer.pairing_id }).toString();
25866
26592
  const pollInit = { method: "GET", headers: { [POLL_TOKEN_HEADER]: offer.poll_token } };
@@ -25885,6 +26611,10 @@ async function pairDevice(options) {
25885
26611
  paired_at: (/* @__PURE__ */ new Date()).toISOString(),
25886
26612
  key_store: options.keyStore.descriptor
25887
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);
25888
26618
  await options.onApproved?.();
25889
26619
  await saveIdentity(options.paths, identity);
25890
26620
  succeeded = true;
@@ -25946,79 +26676,134 @@ async function runConnect(link, deps, extraHosts = []) {
25946
26676
  dialogs.fail(friendly(error63));
25947
26677
  return 2;
25948
26678
  }
26679
+ let cancelled = false;
25949
26680
  try {
25950
26681
  const replacing = await deps.isPaired();
25951
- 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)) {
25952
26684
  deps.log("Connect cancelled.");
25953
26685
  return 0;
25954
26686
  }
25955
- const folders = await dialogs.chooseFolders();
25956
- 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
+ });
25957
26708
  const skipped = [];
25958
26709
  for (const folder of folders) {
25959
26710
  try {
25960
- 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);
25961
26712
  } catch (error63) {
25962
- skipped.push(`${(0, import_node_path10.basename)(folder) || folder}: ${friendly(error63)}`);
26713
+ skipped.push(`${(0, import_node_path11.basename)(folder) || folder}: ${friendly(error63)}`);
25963
26714
  }
25964
26715
  }
25965
26716
  if (skipped.length > 0)
25966
26717
  dialogs.fail("Some folders were not added:\n" + skipped.join("\n"));
25967
- dialogs.notify("ConBridge", "Almost done. Go back to ConBridge in your browser and approve this Mac.");
25968
- await deps.pair(request, replacing);
25969
26718
  await deps.installService();
25970
26719
  dialogs.notify("ConBridge", "This Mac is connected. ConBridge keeps running in the background.");
25971
26720
  return 0;
25972
26721
  } catch (error63) {
26722
+ if (cancelled) {
26723
+ deps.log("Connect cancelled after the offer; this Mac was not connected.");
26724
+ return 0;
26725
+ }
25973
26726
  deps.log(`Connect failed: ${friendly(error63)}`);
25974
26727
  dialogs.fail("This Mac could not be connected.\n\n" + friendly(error63));
25975
26728
  return 1;
25976
26729
  }
25977
26730
  }
25978
- function appleScriptString2(value) {
25979
- return '"' + value.replace(/[\\"]/g, "\\$&").replace(/\r?\n/g, '" & linefeed & "') + '"';
25980
- }
25981
- function osascript(script, timeoutMs) {
25982
- return new Promise((resolve10) => {
25983
- (0, import_node_child_process6.execFile)("/usr/bin/osascript", ["-e", "tell current application to activate", "-e", script], { timeout: timeoutMs }, (error63, stdout) => {
25984
- resolve10({ ok: !error63, stdout: stdout ?? "" });
25985
- });
25986
- });
25987
- }
25988
- var macConnectDialogs = {
25989
- async confirmConnect(host, name3, replacing) {
25990
- 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?
25991
26733
 
25992
- 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.
25993
26735
 
25994
26736
  Address: ${host}
25995
- Name: ${name3}`;
25996
- 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);
25997
- return result2.ok && /button returned:Connect/.test(result2.stdout) && !/gave up:true/.test(result2.stdout);
25998
- },
25999
- async chooseFolders() {
26000
- 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';
26001
- const result2 = await osascript(script, 6e5);
26002
- if (!result2.ok)
26003
- return [];
26004
- return result2.stdout.split("\n").map((line) => line.trim().replace(/\/$/, "")).filter(Boolean);
26005
- },
26006
- async askAllowChanges() {
26007
- 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.";
26008
- 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);
26009
- return result2.ok && /button returned:Allow changes/.test(result2.stdout) && !/gave up:true/.test(result2.stdout);
26010
- },
26011
- notify(title, message) {
26012
- void osascript(`display notification ${appleScriptString2(message)} with title ${appleScriptString2(title)}`, 1e4);
26013
- },
26014
- fail(message) {
26015
- 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.");
26016
26756
  }
26017
- };
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();
26018
26803
 
26019
26804
  // dist/journal.js
26020
- var import_promises8 = require("node:fs/promises");
26021
- var import_node_path11 = require("node:path");
26805
+ var import_promises9 = require("node:fs/promises");
26806
+ var import_node_path12 = require("node:path");
26022
26807
  var storedResultSchema = external_exports.strictObject({
26023
26808
  state: external_exports.enum(["SUCCEEDED", "FAILED", "CANCELLED", "EXPIRED"]),
26024
26809
  executed: external_exports.boolean(),
@@ -26093,7 +26878,7 @@ var Journal = class _Journal {
26093
26878
  const journal = new _Journal(path);
26094
26879
  let text6 = "";
26095
26880
  try {
26096
- text6 = await (0, import_promises8.readFile)(path, "utf8");
26881
+ text6 = await (0, import_promises9.readFile)(path, "utf8");
26097
26882
  } catch (error63) {
26098
26883
  if (errorCode2(error63) !== "ENOENT")
26099
26884
  throw error63;
@@ -26151,7 +26936,7 @@ var Journal = class _Journal {
26151
26936
  async #append(entry) {
26152
26937
  const line = JSON.stringify(entrySchema.parse(entry)) + "\n";
26153
26938
  await this.#serialize(async () => {
26154
- const handle = await (0, import_promises8.open)(this.#path, "a", 384);
26939
+ const handle = await (0, import_promises9.open)(this.#path, "a", 384);
26155
26940
  try {
26156
26941
  await handle.appendFile(line, "utf8");
26157
26942
  await handle.sync();
@@ -26201,7 +26986,7 @@ var Journal = class _Journal {
26201
26986
  return this.#serialize(async () => {
26202
26987
  let text6 = "";
26203
26988
  try {
26204
- text6 = await (0, import_promises8.readFile)(this.#path, "utf8");
26989
+ text6 = await (0, import_promises9.readFile)(this.#path, "utf8");
26205
26990
  } catch (error63) {
26206
26991
  if (errorCode2(error63) === "ENOENT")
26207
26992
  return;
@@ -26236,24 +27021,24 @@ var Journal = class _Journal {
26236
27021
  const lines5 = kept.map((entry) => JSON.stringify(entry) + "\n");
26237
27022
  if (watermark !== null)
26238
27023
  lines5.unshift(JSON.stringify(watermarkSchema.parse({ type: "WATERMARK", at_ms: now, watermark_ms: watermark })) + "\n");
26239
- const temp = (0, import_node_path11.join)((0, import_node_path11.dirname)(this.#path), `.${(0, import_node_path11.basename)(this.#path)}.${randomToken(6)}.tmp`);
26240
- 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);
26241
27026
  try {
26242
27027
  await handle.writeFile(lines5.join(""), "utf8");
26243
27028
  await handle.sync();
26244
27029
  } catch (error63) {
26245
27030
  await handle.close().catch(() => void 0);
26246
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27031
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26247
27032
  throw error63;
26248
27033
  }
26249
27034
  await handle.close();
26250
27035
  try {
26251
- await (0, import_promises8.rename)(temp, this.#path);
27036
+ await (0, import_promises9.rename)(temp, this.#path);
26252
27037
  } catch (error63) {
26253
- await (0, import_promises8.unlink)(temp).catch(() => void 0);
27038
+ await (0, import_promises9.unlink)(temp).catch(() => void 0);
26254
27039
  throw error63;
26255
27040
  }
26256
- await fsyncDirectory((0, import_node_path11.dirname)(this.#path));
27041
+ await fsyncDirectory((0, import_node_path12.dirname)(this.#path));
26257
27042
  this.#records.clear();
26258
27043
  this.#nonces.clear();
26259
27044
  for (const entry of kept)
@@ -26265,22 +27050,22 @@ var Journal = class _Journal {
26265
27050
  };
26266
27051
 
26267
27052
  // dist/install.js
26268
- var import_promises9 = require("node:fs/promises");
26269
- var import_node_path12 = require("node:path");
27053
+ var import_promises10 = require("node:fs/promises");
27054
+ var import_node_path13 = require("node:path");
26270
27055
  var import_node_url2 = require("node:url");
26271
27056
  var RUNTIME_ENTRY = "conbridge-agent.cjs";
26272
27057
  function runtimeDir(stateDir) {
26273
- return (0, import_node_path12.join)(stateDir, "runtime");
27058
+ return (0, import_node_path13.join)(stateDir, "runtime");
26274
27059
  }
26275
27060
  function runtimeEntry(stateDir) {
26276
- return (0, import_node_path12.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
27061
+ return (0, import_node_path13.join)(runtimeDir(stateDir), RUNTIME_ENTRY);
26277
27062
  }
26278
27063
  function currentEntry() {
26279
27064
  return (0, import_node_url2.fileURLToPath)(__conbridge_import_meta_url);
26280
27065
  }
26281
27066
  async function sameBytes(a, b) {
26282
27067
  try {
26283
- 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)]);
26284
27069
  return left.equals(right);
26285
27070
  } catch {
26286
27071
  return false;
@@ -26289,11 +27074,11 @@ async function sameBytes(a, b) {
26289
27074
  async function copyAtomic(from, to, mode) {
26290
27075
  const temp = `${to}.${randomToken(6)}.tmp`;
26291
27076
  try {
26292
- await (0, import_promises9.copyFile)(from, temp);
26293
- await (0, import_promises9.chmod)(temp, mode);
26294
- 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);
26295
27080
  } catch (error63) {
26296
- await (0, import_promises9.unlink)(temp).catch(() => void 0);
27081
+ await (0, import_promises10.unlink)(temp).catch(() => void 0);
26297
27082
  throw error63;
26298
27083
  }
26299
27084
  }
@@ -26302,21 +27087,21 @@ async function installRuntime(stateDir, from = {}) {
26302
27087
  const sourceDir = from.codeDir ?? codeDirectory();
26303
27088
  const dir = runtimeDir(stateDir);
26304
27089
  const entry = runtimeEntry(stateDir);
26305
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
26306
- 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);
26307
27092
  let changed = false;
26308
27093
  if (!await sameBytes(source, entry)) {
26309
27094
  await copyAtomic(source, entry, 384);
26310
27095
  changed = true;
26311
27096
  }
26312
- const helper = (0, import_node_path12.join)(sourceDir, KEYCHAIN_HELPER_NAME);
26313
- const helperTarget = (0, import_node_path12.join)(dir, KEYCHAIN_HELPER_NAME);
26314
- 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);
26315
27100
  if (hasHelper && !await sameBytes(helper, helperTarget)) {
26316
27101
  await copyAtomic(helper, helperTarget, 493);
26317
27102
  changed = true;
26318
27103
  } else if (!hasHelper) {
26319
- await (0, import_promises9.unlink)(helperTarget).catch((error63) => {
27104
+ await (0, import_promises10.unlink)(helperTarget).catch((error63) => {
26320
27105
  if (errorCode2(error63) !== "ENOENT")
26321
27106
  throw error63;
26322
27107
  });
@@ -26326,26 +27111,26 @@ async function installRuntime(stateDir, from = {}) {
26326
27111
  async function snapshotRuntime(stateDir) {
26327
27112
  const dir = runtimeDir(stateDir);
26328
27113
  const backup = `${dir}.previous`;
26329
- await (0, import_promises9.rm)(backup, { recursive: true, force: true });
26330
- 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 });
26331
27116
  const saved = /* @__PURE__ */ new Map();
26332
27117
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
26333
- 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);
26334
27119
  if (!info?.isFile())
26335
27120
  continue;
26336
- 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));
26337
27122
  saved.set(name3, info.mode & 511);
26338
27123
  }
26339
- const discard = () => (0, import_promises9.rm)(backup, { recursive: true, force: true });
27124
+ const discard = () => (0, import_promises10.rm)(backup, { recursive: true, force: true });
26340
27125
  return {
26341
27126
  async restore() {
26342
- await (0, import_promises9.mkdir)(dir, { recursive: true, mode: 448 });
27127
+ await (0, import_promises10.mkdir)(dir, { recursive: true, mode: 448 });
26343
27128
  for (const name3 of [RUNTIME_ENTRY, KEYCHAIN_HELPER_NAME]) {
26344
27129
  const mode = saved.get(name3);
26345
27130
  if (mode !== void 0)
26346
- 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);
26347
27132
  else
26348
- 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) => {
26349
27134
  if (errorCode2(error63) !== "ENOENT")
26350
27135
  throw error63;
26351
27136
  });
@@ -26363,7 +27148,7 @@ async function runningFromRuntime(stateDir, entry = currentEntry()) {
26363
27148
  // dist/keepawake.js
26364
27149
  var import_node_child_process7 = require("node:child_process");
26365
27150
  var import_node_fs2 = require("node:fs");
26366
- var import_node_path13 = require("node:path");
27151
+ var import_node_path14 = require("node:path");
26367
27152
  var POWER_SUPPLY_DIR = "/sys/class/power_supply";
26368
27153
  var DISPLAY_SOCKET_DIRS = { x11: "/tmp/.X11-unix", runUser: "/run/user" };
26369
27154
  function entries(dir) {
@@ -26376,7 +27161,7 @@ function entries(dir) {
26376
27161
  function linuxDisplaySocket(env = process.env, dirs = DISPLAY_SOCKET_DIRS) {
26377
27162
  if (entries(dirs.x11).some((name3) => /^X\d+$/.test(name3)))
26378
27163
  return true;
26379
- 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))];
26380
27165
  return runtimeDirs.some((dir) => entries(dir).some((name3) => /^wayland-\d+$/.test(name3)));
26381
27166
  }
26382
27167
  function powerSupplies(dir) {
@@ -26393,7 +27178,7 @@ function powerSupplies(dir) {
26393
27178
  return null;
26394
27179
  }
26395
27180
  };
26396
- 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")) }));
26397
27182
  }
26398
27183
  var defaultProbe = {
26399
27184
  hasBattery: () => powerSupplies(POWER_SUPPLY_DIR).some((supply) => supply.type === "Battery"),
@@ -26558,7 +27343,7 @@ function startKeepAwake(options = {}) {
26558
27343
  }
26559
27344
 
26560
27345
  // dist/lock.js
26561
- var import_promises10 = require("node:fs/promises");
27346
+ var import_promises11 = require("node:fs/promises");
26562
27347
  function alive(pid) {
26563
27348
  try {
26564
27349
  process.kill(pid, 0);
@@ -26569,7 +27354,7 @@ function alive(pid) {
26569
27354
  }
26570
27355
  async function readLockPid(path) {
26571
27356
  try {
26572
- 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);
26573
27358
  return Number.isInteger(pid) && pid > 0 && alive(pid) ? pid : null;
26574
27359
  } catch {
26575
27360
  return null;
@@ -26578,12 +27363,12 @@ async function readLockPid(path) {
26578
27363
  async function acquireLock(path) {
26579
27364
  for (let attempt = 0; attempt < 2; attempt += 1) {
26580
27365
  try {
26581
- const handle = await (0, import_promises10.open)(path, "wx", 384);
27366
+ const handle = await (0, import_promises11.open)(path, "wx", 384);
26582
27367
  await handle.writeFile(`${process.pid}
26583
27368
  `);
26584
27369
  await handle.close();
26585
27370
  return async () => {
26586
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27371
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26587
27372
  };
26588
27373
  } catch (error63) {
26589
27374
  if (errorCode2(error63) !== "EEXIST")
@@ -26591,19 +27376,19 @@ async function acquireLock(path) {
26591
27376
  const pid = await readLockPid(path);
26592
27377
  if (pid !== null)
26593
27378
  throw new Error(`Another agent is already running (pid ${pid})`);
26594
- await (0, import_promises10.unlink)(path).catch(() => void 0);
27379
+ await (0, import_promises11.unlink)(path).catch(() => void 0);
26595
27380
  }
26596
27381
  }
26597
27382
  throw new Error("Could not acquire the agent lock");
26598
27383
  }
26599
27384
 
26600
27385
  // dist/envelope.js
26601
- var import_node_crypto6 = require("node:crypto");
26602
- 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)()) {
26603
27388
  return {
26604
27389
  version: 1,
26605
27390
  kind,
26606
- message_id: (0, import_node_crypto6.randomUUID)(),
27391
+ message_id: (0, import_node_crypto7.randomUUID)(),
26607
27392
  correlation_id: correlationId,
26608
27393
  tenant_id: identity.tenant_id,
26609
27394
  user_id: identity.user_id,
@@ -26647,13 +27432,13 @@ function excerpt(value) {
26647
27432
  var import_node_os14 = require("node:os");
26648
27433
 
26649
27434
  // dist/dispatcher.js
26650
- var import_node_crypto8 = require("node:crypto");
27435
+ var import_node_crypto9 = require("node:crypto");
26651
27436
 
26652
27437
  // dist/fileops.js
26653
27438
  var import_node_fs3 = require("node:fs");
26654
- var import_promises11 = require("node:fs/promises");
26655
- var import_node_crypto7 = require("node:crypto");
26656
- 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");
26657
27442
 
26658
27443
  // dist/glob.js
26659
27444
  function globToRegExp(glob) {
@@ -26681,18 +27466,29 @@ function globToRegExp(glob) {
26681
27466
  index += 1;
26682
27467
  }
26683
27468
  }
26684
- 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");
26685
27473
  }
26686
27474
  var DenyMatcher = class {
26687
27475
  #patterns;
26688
27476
  constructor(globs) {
26689
- this.#patterns = globs.map(globToRegExp);
27477
+ this.#patterns = [...new Set(globs.flatMap((glob) => [glob, foldPathText(glob)]))].map(globToRegExp);
26690
27478
  }
26691
- /** 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
+ */
26692
27483
  denies(relativePath3) {
26693
27484
  if (relativePath3 === "")
26694
27485
  return false;
26695
- 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("/");
26696
27492
  for (let length = 1; length <= segments.length; length += 1) {
26697
27493
  const prefix = segments.slice(0, length).join("/");
26698
27494
  if (this.#patterns.some((pattern) => pattern.test(prefix)))
@@ -26708,6 +27504,7 @@ var MAX_SEARCH_RESULTS = 100;
26708
27504
  var MAX_SEARCH_BYTES_PER_FILE = 2 * 1024 * 1024;
26709
27505
  var MAX_SEARCH_FILES = 1e4;
26710
27506
  var MAX_SEARCH_TOTAL_BYTES = 64 * 1024 * 1024;
27507
+ var MAX_MOVE_TREE_ENTRIES = 1e4;
26711
27508
  var PREVIEW_CHARS = 200;
26712
27509
  var READ_BLOCK = 64 * 1024;
26713
27510
  var OPEN_READ_FLAGS = import_node_fs3.constants.O_RDONLY | import_node_fs3.constants.O_NOFOLLOW | import_node_fs3.constants.O_NONBLOCK;
@@ -26725,7 +27522,8 @@ var WIRE_CODE = {
26725
27522
  EDIT_MISMATCH: "INVALID_MESSAGE",
26726
27523
  ALREADY_EXISTS: "INVALID_MESSAGE",
26727
27524
  NOT_EMPTY: "INVALID_MESSAGE",
26728
- TOO_LARGE: "SIZE_LIMIT"
27525
+ TOO_LARGE: "SIZE_LIMIT",
27526
+ OWNERSHIP_WOULD_CHANGE: "POLICY_DENIED"
26729
27527
  };
26730
27528
  var FileOpError = class extends Error {
26731
27529
  reason;
@@ -26744,6 +27542,8 @@ function normalizeRelativePath(input2) {
26744
27542
  throw new FileOpError("PATH_INVALID", "Path is invalid");
26745
27543
  if (input2.includes("\0"))
26746
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");
26747
27547
  if (input2.startsWith("/") || input2.startsWith("\\") || /^[A-Za-z]:/.test(input2) || input2.startsWith("~")) {
26748
27548
  throw new FileOpError("PATH_INVALID", "Path must be relative to the root");
26749
27549
  }
@@ -26797,7 +27597,7 @@ function decodeText(bytes3) {
26797
27597
  }
26798
27598
  }
26799
27599
  async function hashHandle(handle) {
26800
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27600
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
26801
27601
  const buffer = Buffer.allocUnsafe(READ_BLOCK);
26802
27602
  let position2 = 0;
26803
27603
  for (; ; ) {
@@ -26810,7 +27610,7 @@ async function hashHandle(handle) {
26810
27610
  return hash2.digest("hex");
26811
27611
  }
26812
27612
  function sha256OfBytes(bytes3) {
26813
- return (0, import_node_crypto7.createHash)("sha256").update(bytes3).digest("hex");
27613
+ return (0, import_node_crypto8.createHash)("sha256").update(bytes3).digest("hex");
26814
27614
  }
26815
27615
  var RootedFs = class {
26816
27616
  #root;
@@ -26830,7 +27630,7 @@ var RootedFs = class {
26830
27630
  return;
26831
27631
  const forms = /* @__PURE__ */ new Set();
26832
27632
  for (const path of this.#protectedInput) {
26833
- forms.add((0, import_node_path14.resolve)(path));
27633
+ forms.add((0, import_node_path15.resolve)(path));
26834
27634
  forms.add(await realpathLenient(path));
26835
27635
  }
26836
27636
  this.#protected = [...forms];
@@ -26840,7 +27640,7 @@ var RootedFs = class {
26840
27640
  #blockedReal(real) {
26841
27641
  if (this.#protected.some((dir) => isSameOrInside(dir, real)))
26842
27642
  return true;
26843
- 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("/"));
26844
27644
  }
26845
27645
  #checkReal(real) {
26846
27646
  if (this.#blockedReal(real))
@@ -26849,8 +27649,8 @@ var RootedFs = class {
26849
27649
  async #rootReal() {
26850
27650
  await this.#loadProtected();
26851
27651
  try {
26852
- const real = await (0, import_promises11.realpath)(this.#root.path);
26853
- 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())
26854
27654
  throw new FileOpError("NOT_FOUND", "Root is unavailable");
26855
27655
  return real;
26856
27656
  } catch (error63) {
@@ -26860,11 +27660,11 @@ var RootedFs = class {
26860
27660
  }
26861
27661
  }
26862
27662
  #inside(rootReal, real) {
26863
- 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;
26864
27664
  return real === rootReal || real.startsWith(prefix);
26865
27665
  }
26866
27666
  #relativeOf(rootReal, real) {
26867
- 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("/");
26868
27668
  }
26869
27669
  #checkDeny(rel) {
26870
27670
  if (this.#deny.denies(rel))
@@ -26877,7 +27677,7 @@ var RootedFs = class {
26877
27677
  const rootReal = await this.#rootReal();
26878
27678
  let real;
26879
27679
  try {
26880
- 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));
26881
27681
  } catch (error63) {
26882
27682
  throw mapFsError(error63, rel);
26883
27683
  }
@@ -26896,10 +27696,10 @@ var RootedFs = class {
26896
27696
  async #openVerified(rootReal, real) {
26897
27697
  let handle;
26898
27698
  try {
26899
- const before = await (0, import_promises11.lstat)(real);
27699
+ const before = await (0, import_promises12.lstat)(real);
26900
27700
  if (!before.isFile())
26901
27701
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
26902
- handle = await (0, import_promises11.open)(real, OPEN_READ_FLAGS);
27702
+ handle = await (0, import_promises12.open)(real, OPEN_READ_FLAGS);
26903
27703
  } catch (error63) {
26904
27704
  throw mapFsError(error63, "");
26905
27705
  }
@@ -26907,8 +27707,8 @@ var RootedFs = class {
26907
27707
  const info = await handle.stat();
26908
27708
  if (!info.isFile())
26909
27709
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file");
26910
- const again = await (0, import_promises11.realpath)(real);
26911
- 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);
26912
27712
  if (again !== real || !this.#inside(rootReal, again) || pathInfo.ino !== info.ino || pathInfo.dev !== info.dev) {
26913
27713
  throw new FileOpError("PATH_ESCAPE", "Path changed while it was being opened");
26914
27714
  }
@@ -26927,7 +27727,7 @@ var RootedFs = class {
26927
27727
  try {
26928
27728
  if (!info.isFile())
26929
27729
  throw new FileOpError("NOT_A_FILE", "Path is not a regular file", { path: rel });
26930
- const hash2 = (0, import_node_crypto7.createHash)("sha256");
27730
+ const hash2 = (0, import_node_crypto8.createHash)("sha256");
26931
27731
  const kept = [];
26932
27732
  let keptBytes = 0;
26933
27733
  let size = 0;
@@ -26960,18 +27760,18 @@ var RootedFs = class {
26960
27760
  async list(input2) {
26961
27761
  const { rel, real } = await this.resolveExisting(input2);
26962
27762
  try {
26963
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
27763
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
26964
27764
  throw new FileOpError("NOT_A_DIRECTORY", "Path is not a directory", { path: rel });
26965
- const dir = await (0, import_promises11.opendir)(real);
27765
+ const dir = await (0, import_promises12.opendir)(real);
26966
27766
  const names2 = [];
26967
27767
  for await (const entry of dir) {
26968
27768
  const childRel = rel === "" ? entry.name : `${rel}/${entry.name}`;
26969
27769
  if (this.#deny.denies(childRel))
26970
27770
  continue;
26971
- const childReal = (0, import_node_path14.join)(real, entry.name);
27771
+ const childReal = (0, import_node_path15.join)(real, entry.name);
26972
27772
  if (this.#blockedReal(childReal))
26973
27773
  continue;
26974
- 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)))
26975
27775
  continue;
26976
27776
  const type = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "other";
26977
27777
  names2.push({ name: entry.name, type });
@@ -26980,7 +27780,7 @@ var RootedFs = class {
26980
27780
  const entries2 = [];
26981
27781
  for (const item of names2.slice(0, MAX_LIST_ENTRIES)) {
26982
27782
  if (item.type === "file") {
26983
- 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);
26984
27784
  entries2.push(size === void 0 ? item : { ...item, size });
26985
27785
  } else
26986
27786
  entries2.push(item);
@@ -27003,7 +27803,7 @@ var RootedFs = class {
27003
27803
  return;
27004
27804
  let resolved;
27005
27805
  try {
27006
- resolved = await (0, import_promises11.realpath)(fileReal);
27806
+ resolved = await (0, import_promises12.realpath)(fileReal);
27007
27807
  } catch {
27008
27808
  return;
27009
27809
  }
@@ -27011,9 +27811,9 @@ var RootedFs = class {
27011
27811
  return;
27012
27812
  let handle;
27013
27813
  try {
27014
- if (!(await (0, import_promises11.lstat)(resolved)).isFile())
27814
+ if (!(await (0, import_promises12.lstat)(resolved)).isFile())
27015
27815
  return;
27016
- handle = await (0, import_promises11.open)(resolved, OPEN_READ_FLAGS);
27816
+ handle = await (0, import_promises12.open)(resolved, OPEN_READ_FLAGS);
27017
27817
  } catch {
27018
27818
  return;
27019
27819
  }
@@ -27055,7 +27855,7 @@ var RootedFs = class {
27055
27855
  await handle.close().catch(() => void 0);
27056
27856
  }
27057
27857
  };
27058
- const start = await (0, import_promises11.stat)(real).catch((error63) => {
27858
+ const start = await (0, import_promises12.stat)(real).catch((error63) => {
27059
27859
  throw mapFsError(error63, rel);
27060
27860
  });
27061
27861
  if (start.isFile()) {
@@ -27066,7 +27866,7 @@ var RootedFs = class {
27066
27866
  const current = queue.shift();
27067
27867
  let entries2;
27068
27868
  try {
27069
- const dir = await (0, import_promises11.opendir)(current.real);
27869
+ const dir = await (0, import_promises12.opendir)(current.real);
27070
27870
  entries2 = [];
27071
27871
  for await (const entry of dir) {
27072
27872
  entries2.push({ name: entry.name, file: entry.isFile(), dir: entry.isDirectory() });
@@ -27081,7 +27881,7 @@ var RootedFs = class {
27081
27881
  const childRel = current.rel === "" ? entry.name : `${current.rel}/${entry.name}`;
27082
27882
  if (this.#deny.denies(childRel))
27083
27883
  continue;
27084
- const childReal = (0, import_node_path14.join)(current.real, entry.name);
27884
+ const childReal = (0, import_node_path15.join)(current.real, entry.name);
27085
27885
  if (this.#blockedReal(childReal))
27086
27886
  continue;
27087
27887
  if (entry.dir)
@@ -27103,10 +27903,10 @@ var RootedFs = class {
27103
27903
  async #currentHash(rootReal, target) {
27104
27904
  let info;
27105
27905
  try {
27106
- info = await (0, import_promises11.lstat)(target);
27906
+ info = await (0, import_promises12.lstat)(target);
27107
27907
  } catch (error63) {
27108
27908
  if (errorCode2(error63) === "ENOENT")
27109
- return { sha256: null, mode: null };
27909
+ return { sha256: null, mode: null, uid: null, gid: null };
27110
27910
  throw mapFsError(error63, "");
27111
27911
  }
27112
27912
  if (info.isSymbolicLink())
@@ -27115,7 +27915,7 @@ var RootedFs = class {
27115
27915
  throw new FileOpError("NOT_A_FILE", "Target is not a regular file");
27116
27916
  const { handle } = await this.#openVerified(rootReal, target);
27117
27917
  try {
27118
- 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 };
27119
27919
  } finally {
27120
27920
  await handle.close().catch(() => void 0);
27121
27921
  }
@@ -27135,8 +27935,8 @@ var RootedFs = class {
27135
27935
  const name3 = slash < 0 ? rel : rel.slice(slash + 1);
27136
27936
  let parentReal;
27137
27937
  try {
27138
- parentReal = await (0, import_promises11.realpath)((0, import_node_path14.join)(rootReal, parentRel));
27139
- 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())
27140
27940
  throw new FileOpError("NOT_A_DIRECTORY", "Parent is not a directory");
27141
27941
  } catch (error63) {
27142
27942
  if (errorCode2(error63) === "ENOENT")
@@ -27147,44 +27947,76 @@ var RootedFs = class {
27147
27947
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27148
27948
  const parentRealRel = this.#relativeOf(rootReal, parentReal);
27149
27949
  this.#checkDeny(parentRealRel === "" ? name3 : `${parentRealRel}/${name3}`);
27150
- const target = (0, import_node_path14.join)(parentReal, name3);
27950
+ const target = (0, import_node_path15.join)(parentReal, name3);
27151
27951
  this.#checkReal(target);
27152
27952
  return { rel, rootReal, parentReal, name: name3, target };
27153
27953
  }
27154
- /** 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
+ */
27155
27983
  async #replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3) {
27156
- 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`);
27157
27985
  let handle;
27158
27986
  try {
27159
- 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);
27160
27988
  } catch (error63) {
27161
27989
  throw mapFsError(error63, rel);
27162
27990
  }
27163
27991
  let renamed = false;
27992
+ let groupLost = false;
27164
27993
  try {
27165
27994
  try {
27995
+ if (before.sha256 !== null)
27996
+ groupLost = await this.#keepOwnership(handle, before, rel);
27997
+ await handle.writeFile(bytes3);
27166
27998
  if (before.mode !== null)
27167
27999
  await handle.chmod(before.mode);
27168
- await handle.writeFile(bytes3);
27169
28000
  await handle.sync();
27170
28001
  } finally {
27171
28002
  await handle.close();
27172
28003
  }
27173
- if (await (0, import_promises11.realpath)(parentReal) !== parentReal)
28004
+ if (await (0, import_promises12.realpath)(parentReal) !== parentReal)
27174
28005
  throw new FileOpError("PATH_ESCAPE", "Directory changed during write");
27175
28006
  const again = await this.#currentHash(rootReal, target);
27176
28007
  if (again.sha256 !== before.sha256) {
27177
28008
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed during write", { path: rel, current_sha256: again.sha256 });
27178
28009
  }
27179
- await (0, import_promises11.rename)(temp, target);
28010
+ await (0, import_promises12.rename)(temp, target);
27180
28011
  renamed = true;
27181
28012
  await fsyncDirectory(parentReal);
27182
28013
  } catch (error63) {
27183
28014
  throw mapFsError(error63, rel);
27184
28015
  } finally {
27185
28016
  if (!renamed)
27186
- await (0, import_promises11.unlink)(temp).catch(() => void 0);
28017
+ await (0, import_promises12.unlink)(temp).catch(() => void 0);
27187
28018
  }
28019
+ return groupLost;
27188
28020
  }
27189
28021
  #requireWritable() {
27190
28022
  if (!this.#root.writable)
@@ -27192,8 +28024,9 @@ var RootedFs = class {
27192
28024
  }
27193
28025
  /**
27194
28026
  * Version-checked atomic write: `expectedSha256` must equal the current hash,
27195
- * or be null with the file absent. Writes a temp file in the same directory,
27196
- * 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.
27197
28030
  */
27198
28031
  async write(input2, expectedSha256, content) {
27199
28032
  this.#requireWritable();
@@ -27203,15 +28036,16 @@ var RootedFs = class {
27203
28036
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: before.sha256 });
27204
28037
  }
27205
28038
  const bytes3 = Buffer.from(content, "utf8");
27206
- await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
27207
- 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;
27208
28042
  }
27209
28043
  /** Size, dates and type of a file or directory; files up to 8 MiB also get their sha256 (for edit and delete). */
27210
28044
  async info(input2) {
27211
28045
  const { rel, real, rootReal } = await this.resolveExisting(input2);
27212
28046
  let info;
27213
28047
  try {
27214
- info = await (0, import_promises11.lstat)(real);
28048
+ info = await (0, import_promises12.lstat)(real);
27215
28049
  } catch (error63) {
27216
28050
  throw mapFsError(error63, rel);
27217
28051
  }
@@ -27233,7 +28067,7 @@ var RootedFs = class {
27233
28067
  }
27234
28068
  }
27235
28069
  if (type === "directory") {
27236
- 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);
27237
28071
  return entries2 === void 0 ? base2 : { ...base2, entries: entries2 };
27238
28072
  }
27239
28073
  return base2;
@@ -27270,8 +28104,9 @@ var RootedFs = class {
27270
28104
  throw new FileOpError("EDIT_MISMATCH", `old_text was found ${found} times, expected ${expectedReplacements}`, { path: rel, found });
27271
28105
  }
27272
28106
  const bytes3 = Buffer.from(parts.join(newText), "utf8");
27273
- await this.#replaceAtomic(rel, rootReal, parentReal, name3, target, before, bytes3);
27274
- 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;
27275
28110
  }
27276
28111
  /** Create a directory and its missing parents, each checked against the root and the deny rules. */
27277
28112
  async mkdir(input2) {
@@ -27283,14 +28118,14 @@ var RootedFs = class {
27283
28118
  let created = false;
27284
28119
  for (let index = 1; index <= segments.length; index += 1) {
27285
28120
  const { rootReal, target } = await this.#resolveNew(segments.slice(0, index).join("/"));
27286
- const existing = await (0, import_promises11.lstat)(target).catch(() => null);
28121
+ const existing = await (0, import_promises12.lstat)(target).catch(() => null);
27287
28122
  if (existing) {
27288
28123
  const segment = segments.slice(0, index).join("/");
27289
28124
  if (existing.isSymbolicLink()) {
27290
- const real = await (0, import_promises11.realpath)(target).catch(() => null);
28125
+ const real = await (0, import_promises12.realpath)(target).catch(() => null);
27291
28126
  if (real === null || !this.#inside(rootReal, real))
27292
28127
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root", { path: segment });
27293
- if (!(await (0, import_promises11.stat)(real)).isDirectory())
28128
+ if (!(await (0, import_promises12.stat)(real)).isDirectory())
27294
28129
  throw new FileOpError("ALREADY_EXISTS", "A file with that name exists", { path: segment });
27295
28130
  continue;
27296
28131
  }
@@ -27299,35 +28134,143 @@ var RootedFs = class {
27299
28134
  continue;
27300
28135
  }
27301
28136
  try {
27302
- await (0, import_promises11.mkdir)(target, { mode: 511 });
28137
+ await (0, import_promises12.mkdir)(target, { mode: 511 });
27303
28138
  } catch (error63) {
27304
28139
  if (errorCode2(error63) !== "EEXIST")
27305
28140
  throw mapFsError(error63, rel);
27306
28141
  }
27307
- if (!this.#inside(rootReal, await (0, import_promises11.realpath)(target)))
28142
+ if (!this.#inside(rootReal, await (0, import_promises12.realpath)(target)))
27308
28143
  throw new FileOpError("PATH_ESCAPE", "Path resolves outside the root");
27309
28144
  created = true;
27310
28145
  }
27311
28146
  return { path: rel, created };
27312
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
+ }
27313
28253
  /** Move or rename inside this root. The destination must not exist; a symlink is moved as itself. */
27314
28254
  async move(input2, to) {
27315
28255
  this.#requireWritable();
27316
28256
  const from = await this.#resolveNew(input2);
27317
- const source = await (0, import_promises11.lstat)(from.target).catch(() => null);
28257
+ const source = await (0, import_promises12.lstat)(from.target).catch(() => null);
27318
28258
  if (!source)
27319
28259
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: from.rel });
27320
- const sourceReal = await (0, import_promises11.realpath)(from.target).catch(() => from.target);
27321
- 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))) {
27322
28263
  throw new FileOpError("PATH_DENIED", "Path contains files the agent protects", { path: from.rel });
27323
28264
  }
27324
28265
  const dest = await this.#resolveNew(to);
27325
- if (isSameOrInside(from.target, dest.target))
28266
+ if (isSameOrInside(sourcePath, dest.target))
27326
28267
  throw new FileOpError("PATH_INVALID", "Cannot move a folder into itself");
27327
- if (await (0, import_promises11.lstat)(dest.target).then(() => true, () => false))
28268
+ if (await (0, import_promises12.lstat)(dest.target).then(() => true, () => false))
27328
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);
27329
28272
  try {
27330
- await (0, import_promises11.rename)(from.target, dest.target);
28273
+ await (0, import_promises12.rename)(sourcePath, dest.target);
27331
28274
  } catch (error63) {
27332
28275
  throw mapFsError(error63, from.rel);
27333
28276
  }
@@ -27338,14 +28281,14 @@ var RootedFs = class {
27338
28281
  async delete(input2, expectedSha256) {
27339
28282
  this.#requireWritable();
27340
28283
  const { rel, rootReal, target, parentReal } = await this.#resolveNew(input2);
27341
- const info = await (0, import_promises11.lstat)(target).catch(() => null);
28284
+ const info = await (0, import_promises12.lstat)(target).catch(() => null);
27342
28285
  if (!info)
27343
28286
  throw new FileOpError("NOT_FOUND", "Path does not exist", { path: rel });
27344
28287
  if (info.isDirectory()) {
27345
28288
  if (expectedSha256 !== null)
27346
28289
  throw new FileOpError("NOT_A_FILE", "Path is a directory; pass expected_sha256 null", { path: rel });
27347
28290
  try {
27348
- await (0, import_promises11.rmdir)(target);
28291
+ await (0, import_promises12.rmdir)(target);
27349
28292
  } catch (error63) {
27350
28293
  if (errorCode2(error63) === "ENOTEMPTY" || errorCode2(error63) === "EEXIST")
27351
28294
  throw new FileOpError("NOT_EMPTY", "Directory is not empty", { path: rel });
@@ -27359,7 +28302,7 @@ var RootedFs = class {
27359
28302
  throw new FileOpError("WORKSPACE_VERSION_CONFLICT", "File changed since it was read", { path: rel, current_sha256: current.sha256 });
27360
28303
  }
27361
28304
  try {
27362
- await (0, import_promises11.unlink)(target);
28305
+ await (0, import_promises12.unlink)(target);
27363
28306
  } catch (error63) {
27364
28307
  throw mapFsError(error63, rel);
27365
28308
  }
@@ -27397,10 +28340,10 @@ async function verifyGrantAuthenticity(dispatch2, identity) {
27397
28340
  function actingUserId(dispatch2) {
27398
28341
  return dispatch2.grant.on_behalf_of ?? dispatch2.grant.user_id;
27399
28342
  }
27400
- function isExpired(dispatch2, nowMs) {
28343
+ function isExpired(dispatch2, gatewayNowMs) {
27401
28344
  const expires = Date.parse(dispatch2.grant.expires_at);
27402
28345
  const deadline = Date.parse(dispatch2.deadline_at);
27403
- return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= nowMs || deadline <= nowMs;
28346
+ return !Number.isFinite(expires) || !Number.isFinite(deadline) || expires <= gatewayNowMs || deadline <= gatewayNowMs;
27404
28347
  }
27405
28348
  function isSupportedCapability(capability2) {
27406
28349
  return capabilityDefinition(capability2)?.connector === "desktop" && (isAgentCapability(capability2) || isDesktopCapability(capability2) || isSshCapability(capability2) || isShellCapability(capability2) || isDiagCapability(capability2));
@@ -27535,6 +28478,36 @@ function denialResult(denial) {
27535
28478
  output_excerpt: excerpt({ error: denial.code, reason: denial.reason, message: denial.message })
27536
28479
  };
27537
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
+ }
27538
28511
  function fileErrorResult(error63) {
27539
28512
  return {
27540
28513
  state: "FAILED",
@@ -27557,6 +28530,8 @@ var Dispatcher = class {
27557
28530
  this.#logger = options.logger ?? silentLogger;
27558
28531
  this.#protectedPaths = options.protectedPaths ?? protectedAgentPaths(resolveStateDir(process.env));
27559
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)();
27560
28535
  get identity() {
27561
28536
  const { tenant_id, user_id, device_uuid } = this.#options.identity;
27562
28537
  return { tenant_id, user_id, device_uuid };
@@ -27618,7 +28593,7 @@ var Dispatcher = class {
27618
28593
  const taskId2 = dispatch2.task_id;
27619
28594
  if (taskId2 === null)
27620
28595
  return;
27621
- const now = this.#options.now ?? Date.now;
28596
+ const now = this.#gatewayNow;
27622
28597
  const journal = this.#options.journal;
27623
28598
  const denial = await verifyGrantAuthenticity(dispatch2, this.#options.identity);
27624
28599
  if (denial) {
@@ -27690,29 +28665,32 @@ var Dispatcher = class {
27690
28665
  }
27691
28666
  const actingUser = actingUserId(dispatch2);
27692
28667
  const meta3 = { capability: authorized.capability, nonce: dispatch2.grant.nonce, expires_at_ms: grantExpiryMs(dispatch2), acting_user_id: actingUser };
27693
- const state2 = { phase: "pending", cancelled: false, meta: meta3 };
28668
+ const state2 = { phase: "pending", cancelled: false, stopRequested: false, meta: meta3 };
27694
28669
  this.#inFlight.set(taskId2, state2);
27695
28670
  try {
27696
- const executionNonce = (0, import_node_crypto8.randomUUID)();
28671
+ const executionNonce = (0, import_node_crypto9.randomUUID)();
27697
28672
  this.#sendAck(dispatch2, "RECEIVED", executionNonce);
27698
28673
  let fileTask = isSshTask(authorized) || isShellTask(authorized) || isAgentTask(authorized) || isDiagTask(authorized) ? null : authorized;
27699
28674
  let fs = fileTask ? new RootedFs(fileTask.root, effectiveDenyGlobs(config2), { protectedPaths: this.#protectedPaths }) : null;
27700
- if (fileTask && fileTask.capability === "files.write" && config2.confirm_writes) {
27701
- 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
+ }
27702
28685
  const confirm = this.#options.confirmWrite;
27703
- const confirmed = confirm ? await confirm({
27704
- rootLabel: fileTask.root.label,
27705
- path: payload.path,
27706
- bytes: Buffer.byteLength(payload.content, "utf8"),
27707
- created: payload.expected_sha256 === null
27708
- }).catch(() => false) : false;
28686
+ const confirmed = confirm ? await confirm(request).catch(() => false) : false;
27709
28687
  if (state2.cancelled)
27710
28688
  return;
27711
28689
  if (!confirmed) {
27712
28690
  const cancelled = {
27713
28691
  state: "CANCELLED",
27714
28692
  executed: false,
27715
- safe_message: "Write was declined on the device",
28693
+ safe_message: "Change was declined on the device",
27716
28694
  output_excerpt: excerpt({ error: "POLICY_DENIED", reason: "LOCAL_CONFIRM_DECLINED" })
27717
28695
  };
27718
28696
  await journal.done(taskId2, meta3, cancelled).catch(() => void 0);
@@ -27723,7 +28701,7 @@ var Dispatcher = class {
27723
28701
  if (state2.cancelled)
27724
28702
  return;
27725
28703
  if ("refused" in fresh) {
27726
- 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 });
27727
28705
  await journal.done(taskId2, meta3, fresh.refused).catch(() => void 0);
27728
28706
  this.#sendResult(dispatch2, fresh.refused);
27729
28707
  return;
@@ -27747,6 +28725,7 @@ var Dispatcher = class {
27747
28725
  }
27748
28726
  this.#sendAck(dispatch2, "STARTED", executionNonce);
27749
28727
  const taskContext = { taskId: taskId2, contextId: dispatch2.context_id, actingUserId: actingUser };
28728
+ const shellContext = { ...taskContext, cancelled: () => state2.stopRequested };
27750
28729
  if (isAgentTask(authorized)) {
27751
28730
  let deadline = authorized.payload.run_at_ms;
27752
28731
  this.#scheduledRemovals.set(taskId2, meta3);
@@ -27791,7 +28770,7 @@ var Dispatcher = class {
27791
28770
  safe_message: "SSH task failed on the device",
27792
28771
  output_excerpt: excerpt({ error: "INVALID_MESSAGE", reason: "SSH_ERROR" })
27793
28772
  }
27794
- })) : isShellTask(authorized) ? await shellExecutor.run(authorized, taskContext).catch(() => ({
28773
+ })) : isShellTask(authorized) ? await shellExecutor.run(authorized, shellContext).catch(() => ({
27795
28774
  // Unexpected failure after STARTED: whether the action happened is not known, so never claim it did not.
27796
28775
  result: {
27797
28776
  state: "FAILED",
@@ -27844,7 +28823,9 @@ var Dispatcher = class {
27844
28823
  /**
27845
28824
  * Handle a CANCEL for a task. Before journal STARTED: journal DONE
27846
28825
  * CANCELLED and answer RESULT CANCELLED, also for a task whose DISPATCH has
27847
- * 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).
27848
28829
  */
27849
28830
  async cancel(cancel2) {
27850
28831
  const taskId2 = cancel2.task_id;
@@ -27853,7 +28834,6 @@ var Dispatcher = class {
27853
28834
  return;
27854
28835
  }
27855
28836
  const journal = this.#options.journal;
27856
- const state2 = this.#inFlight.get(taskId2);
27857
28837
  const scheduledMeta = this.#scheduledRemovals.get(taskId2);
27858
28838
  if (this.#options.cancelRemoval) {
27859
28839
  const cancelled = await this.#options.cancelRemoval(taskId2);
@@ -27861,13 +28841,30 @@ var Dispatcher = class {
27861
28841
  return;
27862
28842
  if (cancelled === true || scheduledMeta) {
27863
28843
  this.#scheduledRemovals.delete(taskId2);
27864
- if (state2)
27865
- state2.cancelled = true;
28844
+ const removal = this.#inFlight.get(taskId2);
28845
+ if (removal)
28846
+ removal.cancelled = true;
27866
28847
  const record4 = journal.get(taskId2);
27867
28848
  await this.#tombstone(taskId2, scheduledMeta ?? { capability: "agent.remove", nonce: record4?.nonce ?? void 0 }, cancel2);
27868
28849
  return;
27869
28850
  }
27870
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);
27871
28868
  if (state2) {
27872
28869
  if (state2.phase === "starting") {
27873
28870
  this.#logger.warn("cancel ignored: task already started and cannot be undone", { task_id: taskId2, reason: cancel2.reason });
@@ -27982,7 +28979,7 @@ var Dispatcher = class {
27982
28979
  };
27983
28980
 
27984
28981
  // dist/monitor.js
27985
- var import_promises12 = require("node:fs/promises");
28982
+ var import_promises13 = require("node:fs/promises");
27986
28983
  var import_node_os5 = require("node:os");
27987
28984
  var defaultMonitorSystem = {
27988
28985
  platform: process.platform,
@@ -27991,7 +28988,7 @@ var defaultMonitorSystem = {
27991
28988
  totalmem: import_node_os5.totalmem,
27992
28989
  freemem: import_node_os5.freemem,
27993
28990
  uptime: import_node_os5.uptime,
27994
- statfs: (path) => (0, import_promises12.statfs)(path),
28991
+ statfs: (path) => (0, import_promises13.statfs)(path),
27995
28992
  env: process.env
27996
28993
  };
27997
28994
  var MONITOR_FIRST_SAMPLE_MS = 1e3;
@@ -28126,11 +29123,11 @@ var import_node_os9 = require("node:os");
28126
29123
  var import_node_zlib2 = require("node:zlib");
28127
29124
 
28128
29125
  // dist/inventory/image-packages.js
28129
- var import_promises15 = require("node:fs/promises");
28130
- var import_node_path16 = require("node:path");
29126
+ var import_promises16 = require("node:fs/promises");
29127
+ var import_node_path17 = require("node:path");
28131
29128
 
28132
29129
  // dist/inventory/collection.js
28133
- var import_promises14 = require("node:fs/promises");
29130
+ var import_promises15 = require("node:fs/promises");
28134
29131
  var import_node_os8 = require("node:os");
28135
29132
 
28136
29133
  // dist/inventory/tls.js
@@ -28382,9 +29379,9 @@ var PS_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $Prog
28382
29379
 
28383
29380
  // dist/inventory/software.js
28384
29381
  var import_node_fs4 = require("node:fs");
28385
- var import_promises13 = require("node:fs/promises");
29382
+ var import_promises14 = require("node:fs/promises");
28386
29383
  var import_node_os7 = require("node:os");
28387
- var import_node_path15 = require("node:path");
29384
+ var import_node_path16 = require("node:path");
28388
29385
 
28389
29386
  // dist/inventory/parsers/system.js
28390
29387
  var RELEASE_KEYS = {
@@ -28576,8 +29573,8 @@ async function findExecutablesOnPath(name3, path = collectorEnv().PATH ?? "") {
28576
29573
  const found = [];
28577
29574
  for (const dir of path.split(":").filter((entry) => entry.startsWith("/"))) {
28578
29575
  try {
28579
- const real = await (0, import_promises13.realpath)(`${dir}/${name3}`);
28580
- 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);
28581
29578
  if (!found.includes(real))
28582
29579
  found.push(real);
28583
29580
  } catch {
@@ -28665,7 +29662,7 @@ function xcodeTools(c) {
28665
29662
  }
28666
29663
  async function stampOf(real) {
28667
29664
  try {
28668
- const info = await (0, import_promises13.stat)(real);
29665
+ const info = await (0, import_promises14.stat)(real);
28669
29666
  return `${real}\0${info.mtimeMs}\0${info.size}`;
28670
29667
  } catch {
28671
29668
  return null;
@@ -28723,7 +29720,7 @@ async function readSmall(c, path) {
28723
29720
  return text6 === null ? "missing" : Buffer.byteLength(text6, "utf8") > PACKAGE_JSON_BYTES ? "large" : text6;
28724
29721
  }
28725
29722
  async function packageJsonVersion(c, key, real, names2) {
28726
- let dir = (0, import_node_path15.dirname)(real);
29723
+ let dir = (0, import_node_path16.dirname)(real);
28727
29724
  for (let level = 0; level < PACKAGE_JSON_LEVELS; level += 1) {
28728
29725
  const text6 = await readSmall(c, `${dir}/package.json`);
28729
29726
  if (text6 === "large")
@@ -28736,7 +29733,7 @@ async function packageJsonVersion(c, key, real, names2) {
28736
29733
  return null;
28737
29734
  }
28738
29735
  }
28739
- const parent = (0, import_node_path15.dirname)(dir);
29736
+ const parent = (0, import_node_path16.dirname)(dir);
28740
29737
  if (parent === dir)
28741
29738
  break;
28742
29739
  dir = parent;
@@ -28917,11 +29914,11 @@ var Collection = class {
28917
29914
  }
28918
29915
  }
28919
29916
  };
28920
- 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);
28921
29918
  async function readFileTail(path, bytes3) {
28922
29919
  let handle = null;
28923
29920
  try {
28924
- handle = await (0, import_promises14.open)(path, "r");
29921
+ handle = await (0, import_promises15.open)(path, "r");
28925
29922
  const { size } = await handle.stat();
28926
29923
  const length = Math.min(size, bytes3);
28927
29924
  const buffer = Buffer.alloc(length);
@@ -28936,11 +29933,11 @@ async function readFileTail(path, bytes3) {
28936
29933
  }
28937
29934
  async function listDirFiles(path, dirs = false) {
28938
29935
  try {
28939
- const entries2 = await (0, import_promises14.readdir)(path, { withFileTypes: true });
29936
+ const entries2 = await (0, import_promises15.readdir)(path, { withFileTypes: true });
28940
29937
  const files = [];
28941
29938
  for (const entry of entries2.filter((item) => dirs ? item.isDirectory() : item.isFile()).slice(0, 2e3)) {
28942
29939
  try {
28943
- 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 });
28944
29941
  } catch {
28945
29942
  }
28946
29943
  }
@@ -28952,7 +29949,7 @@ async function listDirFiles(path, dirs = false) {
28952
29949
  async function readFileBytes(path, maxBytes) {
28953
29950
  let handle = null;
28954
29951
  try {
28955
- handle = await (0, import_promises14.open)(path, "r");
29952
+ handle = await (0, import_promises15.open)(path, "r");
28956
29953
  const buffer = Buffer.alloc(Math.max(0, maxBytes));
28957
29954
  let total = 0;
28958
29955
  while (total < buffer.length) {
@@ -28970,14 +29967,14 @@ async function readFileBytes(path, maxBytes) {
28970
29967
  }
28971
29968
  async function listProcPids() {
28972
29969
  try {
28973
- 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);
28974
29971
  } catch {
28975
29972
  return null;
28976
29973
  }
28977
29974
  }
28978
29975
  async function readExeLink(pid) {
28979
29976
  try {
28980
- return await (0, import_promises14.readlink)(`/proc/${pid}/exe`);
29977
+ return await (0, import_promises15.readlink)(`/proc/${pid}/exe`);
28981
29978
  } catch {
28982
29979
  return null;
28983
29980
  }
@@ -28995,7 +29992,7 @@ var defaultCollectorSystem = {
28995
29992
  isRoot: typeof process.getuid === "function" ? process.getuid() === 0 : false,
28996
29993
  resolveExe: async (pid) => {
28997
29994
  try {
28998
- return await (0, import_promises14.realpath)(`/proc/${pid}/exe`);
29995
+ return await (0, import_promises15.realpath)(`/proc/${pid}/exe`);
28999
29996
  } catch {
29000
29997
  return null;
29001
29998
  }
@@ -29472,11 +30469,11 @@ async function loadImageCache(stateDir) {
29472
30469
  if (!stateDir)
29473
30470
  return empty;
29474
30471
  try {
29475
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
29476
- 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);
29477
30474
  if (!info.isFile() || info.size > IMAGE_CACHE_MAX_BYTES)
29478
30475
  return empty;
29479
- 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")));
29480
30477
  if (!file2 || file2.version !== 1)
29481
30478
  return empty;
29482
30479
  const out = { version: 1, entries: {} };
@@ -29505,15 +30502,15 @@ async function saveImageCache(stateDir, cache, nowMs) {
29505
30502
  break;
29506
30503
  entries2.pop();
29507
30504
  }
29508
- const path = (0, import_node_path16.join)(stateDir, IMAGE_CACHE_FILE);
30505
+ const path = (0, import_node_path17.join)(stateDir, IMAGE_CACHE_FILE);
29509
30506
  const temp = `${path}.${process.pid}.tmp`;
29510
30507
  try {
29511
- await (0, import_promises15.rm)(temp, { force: true });
29512
- await (0, import_promises15.writeFile)(temp, text6, { mode: 384, flag: "wx" });
29513
- await (0, import_promises15.chmod)(temp, 384);
29514
- 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);
29515
30512
  } catch {
29516
- await (0, import_promises15.rm)(temp, { force: true }).catch(() => void 0);
30513
+ await (0, import_promises16.rm)(temp, { force: true }).catch(() => void 0);
29517
30514
  }
29518
30515
  }
29519
30516
  function engineSupported(c) {
@@ -29819,190 +30816,6 @@ function legacyImagePackages(items) {
29819
30816
  // dist/ssh/exec.js
29820
30817
  var import_node_child_process9 = require("node:child_process");
29821
30818
  var import_node_path18 = require("node:path");
29822
-
29823
- // dist/ssh/hosts.js
29824
- var import_node_crypto9 = require("node:crypto");
29825
- var import_promises16 = require("node:fs/promises");
29826
- var import_node_path17 = require("node:path");
29827
- var MAX_SSH_HOSTS = 64;
29828
- var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
29829
- 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])?)*$/;
29830
- var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
29831
- var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
29832
- function isValidSshHost(value) {
29833
- return DNS_HOST.test(value) || IPV6_HOST.test(value);
29834
- }
29835
- function isValidIdentityPath(value) {
29836
- return (0, import_node_path17.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
29837
- }
29838
- var PINNABLE_KEY_TYPES = Object.freeze([
29839
- "ssh-ed25519",
29840
- "ecdsa-sha2-nistp256",
29841
- "ecdsa-sha2-nistp384",
29842
- "ecdsa-sha2-nistp521",
29843
- "ssh-rsa"
29844
- ]);
29845
- var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
29846
- var sshHostSchema = external_exports.strictObject({
29847
- resource_id: external_exports.uuid(),
29848
- alias: external_exports.string().regex(SSH_ALIAS),
29849
- host: external_exports.string().refine(isValidSshHost, "Invalid host"),
29850
- port: external_exports.number().int().min(1).max(65535),
29851
- user: external_exports.string().regex(SSH_USER).optional(),
29852
- identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
29853
- production: external_exports.boolean(),
29854
- key_type: external_exports.enum(PINNABLE_KEY_TYPES),
29855
- public_key: external_exports.string().min(16).max(8192).regex(base643),
29856
- fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
29857
- pinned_at: external_exports.iso.datetime({ offset: true })
29858
- });
29859
- var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS) });
29860
- function sshPaths(stateDir) {
29861
- const dir = (0, import_node_path17.join)(stateDir, "ssh");
29862
- return { dir, hosts: (0, import_node_path17.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path17.join)(dir, "known_hosts") };
29863
- }
29864
- function knownHostsPath(paths, resourceId) {
29865
- return (0, import_node_path17.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
29866
- }
29867
- function hostKeyAlias(host) {
29868
- return "conbridge-" + host.resource_id;
29869
- }
29870
- function fingerprintOf(publicKey) {
29871
- return "SHA256:" + (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
29872
- }
29873
- function normalizeFingerprint(value) {
29874
- const trimmed = value.trim();
29875
- return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
29876
- }
29877
- function parseKeyscan(output2) {
29878
- const keys = [];
29879
- for (const line of output2.split("\n")) {
29880
- const trimmed = line.trim();
29881
- if (trimmed === "" || trimmed.startsWith("#"))
29882
- continue;
29883
- const [, type, key] = trimmed.split(/\s+/);
29884
- if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
29885
- continue;
29886
- keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
29887
- }
29888
- return keys;
29889
- }
29890
- function preferredKey(keys) {
29891
- for (const type of PINNABLE_KEY_TYPES) {
29892
- const key = keys.find((candidate) => candidate.key_type === type);
29893
- if (key)
29894
- return key;
29895
- }
29896
- return null;
29897
- }
29898
- async function loadSshHosts(paths) {
29899
- let text6;
29900
- try {
29901
- text6 = await (0, import_promises16.readFile)(paths.hosts, "utf8");
29902
- } catch (error63) {
29903
- if (errorCode2(error63) === "ENOENT")
29904
- return [];
29905
- throw error63;
29906
- }
29907
- return hostsFileSchema.parse(JSON.parse(text6)).hosts;
29908
- }
29909
- async function ensureSshDirs(paths) {
29910
- for (const dir of [paths.dir, paths.knownHostsDir]) {
29911
- await (0, import_promises16.mkdir)(dir, { recursive: true, mode: 448 });
29912
- await (0, import_promises16.chmod)(dir, 448);
29913
- }
29914
- }
29915
- async function saveSshHosts(paths, hosts) {
29916
- await ensureSshDirs(paths);
29917
- await writeFileAtomic(paths.hosts, JSON.stringify(hostsFileSchema.parse({ version: 1, hosts }), null, 2) + "\n", 384);
29918
- }
29919
- async function writeKnownHosts(paths, host) {
29920
- await ensureSshDirs(paths);
29921
- await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
29922
- `, 384);
29923
- }
29924
- async function validateNewHost(input2) {
29925
- if (!SSH_ALIAS.test(input2.alias))
29926
- throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
29927
- if (!isValidSshHost(input2.host))
29928
- throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
29929
- if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
29930
- throw new Error("Port must be 1-65535");
29931
- if (input2.user !== void 0 && !SSH_USER.test(input2.user))
29932
- throw new Error("User must be a plain login name");
29933
- if (input2.identity !== void 0) {
29934
- if (!isValidIdentityPath(input2.identity))
29935
- throw new Error("Identity must be an absolute path without quotes, % or control characters");
29936
- const info = await (0, import_promises16.stat)(input2.identity).catch(() => null);
29937
- if (!info?.isFile())
29938
- throw new Error("Identity file not found");
29939
- }
29940
- }
29941
- async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
29942
- await validateNewHost(input2);
29943
- const hosts = await loadSshHosts(paths);
29944
- if (hosts.some((host2) => host2.alias === input2.alias))
29945
- throw new Error(`An SSH host named ${input2.alias} already exists`);
29946
- if (hosts.length >= MAX_SSH_HOSTS)
29947
- throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
29948
- const host = sshHostSchema.parse({
29949
- resource_id: (0, import_node_crypto9.randomUUID)(),
29950
- alias: input2.alias,
29951
- host: input2.host,
29952
- port: input2.port ?? 22,
29953
- ...input2.user !== void 0 ? { user: input2.user } : {},
29954
- ...input2.identity !== void 0 ? { identity: input2.identity } : {},
29955
- production: input2.production === true,
29956
- key_type: key.key_type,
29957
- public_key: key.public_key,
29958
- fingerprint: key.fingerprint,
29959
- pinned_at: now.toISOString()
29960
- });
29961
- await writeKnownHosts(paths, host);
29962
- await saveSshHosts(paths, [...hosts, host]);
29963
- return host;
29964
- }
29965
- async function findSshHost(paths, alias) {
29966
- return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
29967
- }
29968
- async function updateHost(paths, alias, change) {
29969
- const hosts = await loadSshHosts(paths);
29970
- const index = hosts.findIndex((host) => host.alias === alias);
29971
- if (index < 0)
29972
- throw new Error(`No SSH host named ${alias}`);
29973
- const updated = sshHostSchema.parse(change(hosts[index]));
29974
- const next = [...hosts];
29975
- next[index] = updated;
29976
- if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
29977
- await writeKnownHosts(paths, updated);
29978
- await saveSshHosts(paths, next);
29979
- return updated;
29980
- }
29981
- async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
29982
- return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
29983
- }
29984
- async function setSshHostProduction(paths, alias, production) {
29985
- return await updateHost(paths, alias, (host) => ({ ...host, production }));
29986
- }
29987
- async function removeSshHost(paths, alias) {
29988
- const hosts = await loadSshHosts(paths);
29989
- const host = hosts.find((entry) => entry.alias === alias);
29990
- if (!host)
29991
- return false;
29992
- await saveSshHosts(paths, hosts.filter((entry) => entry !== host));
29993
- await (0, import_promises16.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
29994
- return true;
29995
- }
29996
- function hostAddress(host) {
29997
- if (host.port === 22)
29998
- return host.host;
29999
- return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
30000
- }
30001
- function inventoryResource2(host) {
30002
- return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
30003
- }
30004
-
30005
- // dist/ssh/exec.js
30006
30819
  var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
30007
30820
  function sshBinariesFromEnv(env = process.env) {
30008
30821
  const pick2 = (value, fallback) => value && (0, import_node_path18.isAbsolute)(value) ? value : fallback;
@@ -34226,9 +35039,81 @@ function unitFileEnablement(unitFiles) {
34226
35039
  return enablement;
34227
35040
  }
34228
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
+ }
34229
35112
  function parseSystemd(units, unitFiles) {
34230
35113
  const enablement = unitFileEnablement(unitFiles);
34231
- const result2 = [];
35114
+ const byName = /* @__PURE__ */ new Map();
35115
+ const mixed = /* @__PURE__ */ new Set();
35116
+ const instances = /* @__PURE__ */ new Map();
34232
35117
  for (const rawLine of lines2(units)) {
34233
35118
  const line = rawLine.trim().replace(/^[●*]\s+/, "");
34234
35119
  const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
@@ -34242,23 +35127,46 @@ function parseSystemd(units, unitFiles) {
34242
35127
  continue;
34243
35128
  if (load === "not-found")
34244
35129
  continue;
34245
- if (PER_CONNECTION_INSTANCE.test(unitName(unitToken)))
35130
+ const unit2 = unitName(unitToken);
35131
+ if (PER_CONNECTION_INSTANCE.test(unit2))
34246
35132
  continue;
34247
- const name3 = text3(unitName(unitToken), NAME_MAX4);
34248
- 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 === "@")
34249
35137
  continue;
34250
- const item = {
34251
- name: name3,
34252
- manager: "systemd",
34253
- state: systemdState(active.toLowerCase(), sub.toLowerCase()),
34254
- enabled: enablement.get(name3) ?? null
34255
- };
34256
- 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 };
34257
35157
  if (description)
34258
35158
  item.description = description;
34259
- result2.push(item);
35159
+ byName.set(name3, item);
34260
35160
  }
34261
- 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()]);
34262
35170
  }
34263
35171
  function parseLaunchctl(stdout) {
34264
35172
  const result2 = [];
@@ -34362,6 +35270,10 @@ function windowsEnabled(value) {
34362
35270
  return WINDOWS_START_TYPES[value.trim().toLowerCase()] ?? null;
34363
35271
  return null;
34364
35272
  }
35273
+ function readWindowsServices(output2) {
35274
+ const services = parseWindowsServices(output2);
35275
+ return services.length > 0 ? services : null;
35276
+ }
34365
35277
  function parseWindowsServices(json2) {
34366
35278
  const parsed = parseJson4(json2);
34367
35279
  if (parsed === void 0 || parsed === null)
@@ -35870,9 +36782,14 @@ async function collectServices(c) {
35870
36782
  } else if (platform2 === "win32") {
35871
36783
  const win = await c.command("windows-services", "powershell.exe", [...POWERSHELL, PS_SERVICES], LIST);
35872
36784
  if (win !== null) {
35873
- const items = parseWindowsServices(win);
35874
- c.services.push(...items);
35875
- c.counted("windows-services", items.length, INVENTORY_LIMITS.services);
36785
+ const items = readWindowsServices(win);
36786
+ if (items === null) {
36787
+ const entry = c.coverage.find((e) => e.collector === "windows-services");
36788
+ c.cover("windows-services", "failed", 0, entry?.duration_ms ?? 0);
36789
+ } else {
36790
+ c.services.push(...items);
36791
+ c.counted("windows-services", items.length, INVENTORY_LIMITS.services);
36792
+ }
35876
36793
  }
35877
36794
  }
35878
36795
  }
@@ -35924,6 +36841,7 @@ async function collectInventory(system = defaultCollectorSystem, options = LEGAC
35924
36841
  }
35925
36842
 
35926
36843
  // dist/relay.js
36844
+ var defaultMonotonicNow = () => performance.now();
35927
36845
  var HEARTBEAT_INTERVAL_MS = 2e4;
35928
36846
  var PING_INTERVAL_MS = 25e3;
35929
36847
  var PING_JITTER_MS = 5e3;
@@ -35937,6 +36855,10 @@ var RECONNECT_JITTER_MIN_MS = 1e3;
35937
36855
  var RECONNECT_JITTER_SPAN_MS = 29e3;
35938
36856
  var SERVER_DROP_CODES = /* @__PURE__ */ new Set([1001, 1006, 1011, 1012, 4e3]);
35939
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;
35940
36862
  var CLOSE_POLICY_VIOLATION = 4008;
35941
36863
  function relayUrl(gatewayUrl, deviceUuid2) {
35942
36864
  const url2 = new URL("/v1/agent/connect", gatewayUrl);
@@ -35958,6 +36880,10 @@ var RelaySession = class {
35958
36880
  #gatewayFeatures = /* @__PURE__ */ new Set();
35959
36881
  /** Relay features both sides speak: the ones this agent listed in AUTH that AUTH_OK echoed. */
35960
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;
35961
36887
  constructor(options) {
35962
36888
  this.#options = options;
35963
36889
  this.#logger = options.logger ?? silentLogger;
@@ -35965,6 +36891,26 @@ var RelaySession = class {
35965
36891
  get state() {
35966
36892
  return this.#state;
35967
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
+ };
35968
36914
  /** True once AUTH_OK echoed `ping.v1` for a session that listed it. */
35969
36915
  get pingEnabled() {
35970
36916
  return this.#state === "ready" && this.#relayFeatures.has("ping.v1");
@@ -36060,9 +37006,13 @@ var RelaySession = class {
36060
37006
  const parsed = relayChallengeSchema.safeParse(frame);
36061
37007
  if (!parsed.success)
36062
37008
  return this.#fail("expected CHALLENGE");
36063
- const now = (this.#options.now ?? Date.now)();
36064
- if (parsed.data.expires_at_ms <= now)
36065
- 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
+ }
36066
37016
  const deviceUuid2 = this.#options.identity.device_uuid;
36067
37017
  const signature = await signRelayChallenge(this.#options.key, deviceUuid2, parsed.data.nonce, parsed.data.connection_id);
36068
37018
  this.#state = "auth_sent";
@@ -36165,6 +37115,10 @@ var DEFAULT_BACKOFF = { baseMs: 1e3, maxMs: 6e4 };
36165
37115
  function reconnectDelay(connectionMs, closeCode, random = Math.random, context = {}) {
36166
37116
  if (context.requested === true)
36167
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
+ }
36168
37122
  if (connectionMs >= LONG_CONNECTION_MS && SERVER_DROP_CODES.has(closeCode))
36169
37123
  return Math.floor(RECONNECT_JITTER_MIN_MS + random() * RECONNECT_JITTER_SPAN_MS);
36170
37124
  return backoffDelay(context.attempt ?? 0, { ...context.backoff ?? DEFAULT_BACKOFF, random: context.backoff?.random ?? random });
@@ -37001,7 +37955,7 @@ function sshDiagPlan(spec2, values) {
37001
37955
  root: DIAG_ROOT_REQUIRED[spec2.id],
37002
37956
  steps: Object.freeze(steps)
37003
37957
  });
37004
- const quoted = values.map(q).join(" ");
37958
+ const quoted2 = values.map(q).join(" ");
37005
37959
  switch (spec2.id) {
37006
37960
  case "os.release":
37007
37961
  return plan([step("os_release", "read", "cat /etc/os-release 2>&1", { merged: true })]);
@@ -37028,15 +37982,15 @@ function sshDiagPlan(spec2, values) {
37028
37982
  case "sshd.effective":
37029
37983
  return plan([step("sshd", "exec", "sshd -T 2>&1 || /usr/sbin/sshd -T 2>&1", { merged: true })]);
37030
37984
  case "dpkg.installed":
37031
- 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 })]);
37032
37986
  case "apt.candidate":
37033
- return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted}`)]);
37987
+ return plan([step("apt_policy", "exec", `apt-cache policy -- ${quoted2}`)]);
37034
37988
  case "rpm.installed":
37035
- 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}`)]);
37036
37990
  case "listeners.public":
37037
37991
  return plan([step("ss", "exec", "ss -H -tuln")]);
37038
37992
  case "service.state":
37039
- 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}`)]);
37040
37994
  case "reboot.required":
37041
37995
  return plan([
37042
37996
  step("dpkg_status", "probe", "test -e /var/lib/dpkg/status"),
@@ -37734,6 +38688,7 @@ var ShellExecutor = class {
37734
38688
  background: session.background,
37735
38689
  running: session.endedAtMs === null,
37736
38690
  exit_code: session.exitCode,
38691
+ stopped: session.stoppedBy !== null,
37737
38692
  started_at: new Date(session.startedAtMs).toISOString(),
37738
38693
  duration_ms: (session.endedAtMs ?? this.#now()) - session.startedAtMs,
37739
38694
  output_bytes: session.output.total
@@ -37798,6 +38753,17 @@ var ShellExecutor = class {
37798
38753
  return failure3("INVALID_MESSAGE", "SHELL_UNAVAILABLE", error63 instanceof Error ? error63.message : "Shell is not available");
37799
38754
  }
37800
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
+ }
37801
38767
  let child;
37802
38768
  try {
37803
38769
  child = (0, import_node_child_process11.spawn)(launch.file, [...launch.args], {
@@ -37874,8 +38840,24 @@ var ShellExecutor = class {
37874
38840
  if (session.stoppedBy === "timeout") {
37875
38841
  return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: `Command timed out after ${payload.timeout_s} s and was stopped` } };
37876
38842
  }
38843
+ if (session.stoppedBy === "cancelled") {
38844
+ return { ...outcome, result: { ...outcome.result, state: "FAILED", safe_message: "The command was cancelled and stopped" } };
38845
+ }
37877
38846
  return outcome;
37878
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
+ }
37879
38861
  /** Session `taskId` if it belongs to this context and acting user. */
37880
38862
  #owned(taskId2, context) {
37881
38863
  const session = this.#sessions.get(taskId2);
@@ -38189,6 +39171,11 @@ var AgentRunner = class {
38189
39171
  #stopped = false;
38190
39172
  #sleep = null;
38191
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;
38192
39179
  /** Set by reconnectNow: the next connection attempt starts without a backoff wait. */
38193
39180
  #immediate = false;
38194
39181
  /** #immediate counts only for a connection that ends before this time (reconnectNow + 5 s). */
@@ -38231,9 +39218,13 @@ var AgentRunner = class {
38231
39218
  return true;
38232
39219
  },
38233
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),
38234
39224
  diag: new DiagExecutor({ logger: this.#logger }),
38235
39225
  identity: options.identity,
38236
39226
  config: () => this.#currentConfig(),
39227
+ gatewayNow: () => this.#gatewayNow?.() ?? null,
38237
39228
  loadConfig: async () => {
38238
39229
  if (await this.#reloadConfig())
38239
39230
  this.#session?.sendInventory();
@@ -38269,10 +39260,24 @@ var AgentRunner = class {
38269
39260
  });
38270
39261
  const hostKey = (list) => JSON.stringify(list.map(inventoryResource2));
38271
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;
38272
39264
  this.#config = config2;
38273
39265
  this.#sshHosts = hosts;
39266
+ if (fullAccessOff)
39267
+ await this.#stopTerminalCommands();
38274
39268
  return changed;
38275
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
+ }
38276
39281
  async #compactJournal() {
38277
39282
  try {
38278
39283
  const stats = await this.#options.journal.compact();
@@ -38359,7 +39364,7 @@ var AgentRunner = class {
38359
39364
  }
38360
39365
  async #loop() {
38361
39366
  while (!this.#stopped) {
38362
- let outcome = { authenticated: false, connectionMs: 0, code: 1006 };
39367
+ let outcome = { authenticated: false, connectionMs: 0, code: 1006, replaced: false };
38363
39368
  this.#immediate = false;
38364
39369
  try {
38365
39370
  outcome = await this.#connectOnce();
@@ -38368,14 +39373,21 @@ var AgentRunner = class {
38368
39373
  }
38369
39374
  if (this.#stopped)
38370
39375
  break;
38371
- if (outcome.authenticated)
39376
+ if (outcome.authenticated && !outcome.replaced && outcome.connectionMs >= LONG_CONNECTION_MS)
38372
39377
  this.#attempt = 0;
38373
39378
  const requested = this.#immediate && (this.#options.now ?? Date.now)() <= this.#immediateUntil;
38374
39379
  this.#immediate = false;
38375
39380
  if (requested)
38376
39381
  continue;
38377
- 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 });
38378
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
+ }
38379
39391
  this.#logger.info("reconnecting", { delay_ms: delay });
38380
39392
  await this.#wait(delay);
38381
39393
  }
@@ -38548,6 +39560,7 @@ var AgentRunner = class {
38548
39560
  onReady: () => {
38549
39561
  ready = true;
38550
39562
  readyAtMs = now();
39563
+ this.#gatewayNow = session.gatewayNow;
38551
39564
  lastPongMs = readyAtMs;
38552
39565
  const keepalive = session.pingEnabled;
38553
39566
  this.#logger.info("relay authenticated", { device_uuid: identity.device_uuid, keepalive: keepalive ? "ping.v1" : "heartbeat" });
@@ -38589,7 +39602,7 @@ var AgentRunner = class {
38589
39602
  this.#session = session;
38590
39603
  return new Promise((resolve10) => {
38591
39604
  let settled = false;
38592
- const end = (code) => {
39605
+ const end = (code, serverReason) => {
38593
39606
  if (settled)
38594
39607
  return;
38595
39608
  settled = true;
@@ -38622,7 +39635,7 @@ var AgentRunner = class {
38622
39635
  this.#featuresRefused = false;
38623
39636
  this.#logger.info("offering relay features again on the next connection");
38624
39637
  }
38625
- resolve10({ authenticated: ready, connectionMs, code });
39638
+ resolve10({ authenticated: ready, connectionMs, code, replaced: code === 4e3 && serverReason === REPLACED_CLOSE_REASON });
38626
39639
  };
38627
39640
  endConnection = end;
38628
39641
  this.#endConnection = end;
@@ -38661,7 +39674,7 @@ var AgentRunner = class {
38661
39674
  socket.addEventListener("close", (event) => {
38662
39675
  if (!settled)
38663
39676
  this.#handleClose(event.code, event.reason);
38664
- end(event.code);
39677
+ end(event.code, event.reason);
38665
39678
  });
38666
39679
  });
38667
39680
  }
@@ -38801,7 +39814,8 @@ async function cmdSsh(stateDir, args, io) {
38801
39814
  var USAGE = `conbridge-agent ${AGENT_VERSION}
38802
39815
 
38803
39816
  Usage:
38804
- 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]
38805
39819
  conbridge-agent connect <conbridge://pair?...> (used by the ConBridge Mac app; no terminal needed)
38806
39820
  conbridge-agent roots add <path> --label <label> [--writable] [--allow-broad-root]
38807
39821
  conbridge-agent roots list
@@ -38810,8 +39824,11 @@ Usage:
38810
39824
  conbridge-agent config keep-awake <on|off>
38811
39825
  conbridge-agent config inventory <on|off> software inventory the owner turns on in the Console (default on)
38812
39826
  ${SSH_USAGE}
38813
- conbridge-agent access full [--no-home] AI apps you approve may run commands here (terminal, processes)
38814
- 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
38815
39832
  conbridge-agent access status
38816
39833
  conbridge-agent start foreground session; Ctrl+C stops it
38817
39834
  conbridge-agent kill [--yes] [--keep-runtime] remove this agent (alias: remove)
@@ -38822,7 +39839,8 @@ ${SSH_USAGE}
38822
39839
  conbridge-agent logs [-f] [-n <lines>]
38823
39840
  conbridge-agent service <install|uninstall|print>
38824
39841
  conbridge-agent update with npx --yes conbridge-agent@latest update: install that version and restart the service
38825
- 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
38826
39844
  conbridge-agent --version
38827
39845
 
38828
39846
  pair connects this computer to ConBridge (default gateway ${DEFAULT_GATEWAY_URL}, default name: this computer's
@@ -38830,7 +39848,13 @@ name) and installs the background service, so the agent reconnects by itself aft
38830
39848
  a LaunchAgent on macOS, a systemd user service on Linux (started at boot), a Task Scheduler task on Windows.
38831
39849
  While it runs, the agent keeps the computer from idle-sleeping (the display may still turn off); turn this off
38832
39850
  with config keep-awake off. Full access (pair --full-access or access full) lets AI apps you approve run commands
38833
- 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.
38834
39858
 
38835
39859
  Modes: persistent starts automatically; passive runs only with start; timed expires and removes identity;
38836
39860
  ephemeral expires or self-destructs and purges ConBridge files.
@@ -38933,7 +39957,7 @@ async function discardOldKey(paths, identity, env) {
38933
39957
  } catch {
38934
39958
  }
38935
39959
  }
38936
- async function cmdPair(paths, args, io) {
39960
+ async function cmdPair(paths, args, io, hooks = {}) {
38937
39961
  const { values } = (0, import_node_util2.parseArgs)({
38938
39962
  args,
38939
39963
  allowPositionals: false,
@@ -38945,14 +39969,25 @@ async function cmdPair(paths, args, io) {
38945
39969
  "key-store": { type: "string" },
38946
39970
  keychain: { type: "string" },
38947
39971
  "no-service": { type: "boolean" },
38948
- "full-access": { type: "boolean" }
39972
+ "full-access": { type: "boolean" },
39973
+ home: { type: "boolean" },
39974
+ "home-writable": { type: "boolean" }
38949
39975
  }
38950
39976
  });
38951
39977
  if (!values.code)
38952
39978
  throw new UsageError("pair needs --code (create one in the ConBridge Console under Connect)");
38953
- const installed = await runInstalledCopy(paths, ["pair", ...args], io, false);
38954
- if (installed !== null)
38955
- 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
+ }
38956
39991
  const gateway = values.gateway ?? DEFAULT_GATEWAY_URL;
38957
39992
  const name3 = (values.name ?? (0, import_node_os15.hostname)()).trim().slice(0, 64) || "My computer";
38958
39993
  const keyStore = await newKeyStore(paths, values, io.env);
@@ -38961,16 +39996,27 @@ async function cmdPair(paths, args, io) {
38961
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)");
38962
39997
  await ensureStateDir(paths.dir);
38963
39998
  io.out(`Device key store: ${keyStore.descriptor.type === "keychain" ? "macOS Keychain" : `file ${paths.key}`}`);
39999
+ const shared = describeLocalGrants(await readLocalGrants(paths));
38964
40000
  const identity = await pairDevice({
38965
40001
  paths,
38966
40002
  keyStore,
38967
40003
  gatewayUrl: gateway,
38968
40004
  code: values.code,
38969
40005
  name: name3,
38970
- onOffered: ({ fingerprint }) => {
38971
- 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
+ }
38972
40012
  io.out("Approve this device in the ConBridge Console and check that the fingerprint matches. Waiting...");
38973
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
+ },
38974
40020
  onApproved: async () => {
38975
40021
  if (keyStore.descriptor.type === "file")
38976
40022
  await (0, import_promises23.rename)(pendingKeyPath(paths), paths.key);
@@ -38979,8 +40025,9 @@ async function cmdPair(paths, args, io) {
38979
40025
  if (previous && !(keyStore.descriptor.type === "file" && previous.key_store?.type !== "keychain"))
38980
40026
  await discardOldKey(paths, previous, io.env);
38981
40027
  io.out(`Paired as "${identity.display_name}" (device ${identity.device_uuid}).`);
38982
- if (values["full-access"])
38983
- 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
+ }
38984
40031
  if (identity.connection_mode === "passive") {
38985
40032
  await removeAgentAutostart(paths.dir, lifecycleDeps(io));
38986
40033
  await stopSupervisor(paths);
@@ -39011,11 +40058,12 @@ async function cmdConnect(paths, args, io) {
39011
40058
  return await runConnect(link, {
39012
40059
  dialogs: macConnectDialogs,
39013
40060
  isPaired: () => exists2(paths.identity),
40061
+ localAccess: () => readLocalGrants(paths),
39014
40062
  addFolder: async (path, label, writable) => {
39015
40063
  await addRoot(paths, { path, label, writable, allowBroadRoot: false, ...io.env.HOME ? { home: io.env.HOME } : {} });
39016
40064
  },
39017
- pair: async (request, replacing) => {
39018
- 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 });
39019
40067
  if (code !== 0)
39020
40068
  throw new Error("Pairing did not finish.");
39021
40069
  },
@@ -39369,31 +40417,60 @@ async function cmdSupervise(paths, io) {
39369
40417
  }
39370
40418
  return 0;
39371
40419
  }
40420
+ function sharedFolders(roots) {
40421
+ return roots.length === 0 ? "none" : roots.map((root) => `${root.label} (${root.writable ? "read-write" : "read-only"})`).join(", ");
40422
+ }
39372
40423
  async function cmdAccess(paths, args, io) {
39373
40424
  const [mode, ...rest] = args;
39374
40425
  const config2 = await loadConfig(paths);
39375
40426
  if (mode === "status" || mode === void 0) {
39376
40427
  io.out(`Full access (terminal): ${config2.full_access === true ? "on" : "off"}`);
39377
- 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)}`);
39378
40429
  return 0;
39379
40430
  }
39380
40431
  if (mode === "files") {
39381
- await saveConfig(paths, { ...config2, full_access: false });
39382
- 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)}.`);
39383
40441
  return 0;
39384
40442
  }
39385
40443
  if (mode !== "full")
39386
40444
  throw new UsageError("access needs full, files or status");
39387
- const { values } = (0, import_node_util2.parseArgs)({ args: rest, allowPositionals: false, options: { "no-home": { type: "boolean" } } });
39388
- await saveConfig(paths, { ...config2, full_access: true });
39389
- if (!values["no-home"]) {
39390
- const home = io.env.HOME ?? (0, import_node_os15.homedir)();
39391
- const real = await (0, import_promises23.realpath)(home).catch(() => null);
39392
- const covered = config2.roots.some((root) => root.path === real);
39393
- if (real && !covered) {
39394
- const root = await addRoot(paths, { path: real, label: "Home", writable: true, allowBroadRoot: true, home });
39395
- 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.`);
39396
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).");
39397
40474
  }
39398
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.");
39399
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");
@@ -39469,15 +40546,32 @@ async function cmdLogs(paths, args, io) {
39469
40546
  }
39470
40547
  }
39471
40548
  }
39472
- 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" } } });
39473
40551
  const identity = await loadIdentity(paths).catch(() => null);
39474
- 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)
39475
40553
  await cmdService(paths, ["uninstall"], io).catch(() => 1);
39476
40554
  await stopAgentProcess(paths);
39477
40555
  if (identity)
39478
40556
  await discardOldKey(paths, identity, io.env);
39479
40557
  await (0, import_promises23.unlink)(paths.identity).catch(() => void 0);
39480
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
+ }
39481
40575
  return 0;
39482
40576
  }
39483
40577
  function lifecycleDeps(io) {
@@ -39537,7 +40631,7 @@ async function main(argv, io) {
39537
40631
  case "supervise":
39538
40632
  return await cmdSupervise(paths, io);
39539
40633
  case "unpair":
39540
- return await cmdUnpair(paths, io);
40634
+ return await cmdUnpair(paths, args, io);
39541
40635
  case "service":
39542
40636
  return await cmdService(paths, args, io);
39543
40637
  case "update":