conbridge-agent 0.3.2 → 0.4.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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/conbridge-agent.cjs +2240 -1925
  3. package/package.json +1 -1
@@ -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.3.2", commit: "3e6c8cc1bb37", built_at: "2026-10-30T02:48:39.631Z", keychain_helper_sha256: "359d0b3f3fedc26561d0e0b27a93df624fa55c1519c120e23fae46e9f2c2dc6a", distribution: "npm" };
32
+ var define_CONBRIDGE_BUILD_default = { version: "0.4.0", commit: "a5d55893f404", built_at: "2026-10-31T00:01:24.018Z", keychain_helper_sha256: "359d0b3f3fedc26561d0e0b27a93df624fa55c1519c120e23fae46e9f2c2dc6a", distribution: "npm" };
33
33
 
34
34
  // dist/cli.js
35
35
  var import_node_child_process10 = require("node:child_process");
@@ -19838,6 +19838,7 @@ var INVENTORY_DEFAULTS = Object.freeze({ enabled: false, interval_s: 86400 });
19838
19838
  var INVENTORY_MAX_COMPRESSED_BYTES = 15e5;
19839
19839
  var INVENTORY_PART_CHARS = 48e3;
19840
19840
  var INVENTORY_MAX_PARTS = Math.ceil(INVENTORY_MAX_COMPRESSED_BYTES * 4 / 3 / INVENTORY_PART_CHARS);
19841
+ var INVENTORY_MAX_SSH_HOSTS = 50;
19841
19842
  var INVENTORY_LIMITS = Object.freeze({
19842
19843
  packages: 2e4,
19843
19844
  software: 128,
@@ -20122,7 +20123,8 @@ var metrics = base.extend({
20122
20123
  var softwareInventoryConfig = base.extend({
20123
20124
  kind: external_exports.literal("SOFTWARE_INVENTORY_CONFIG"),
20124
20125
  enabled: external_exports.boolean(),
20125
- interval_s: external_exports.literal([...INVENTORY_INTERVALS_S])
20126
+ interval_s: external_exports.literal([...INVENTORY_INTERVALS_S]),
20127
+ ssh_hosts: external_exports.array(uuid3).max(INVENTORY_MAX_SSH_HOSTS).optional()
20126
20128
  });
20127
20129
  var softwareInventoryRequest = base.extend({
20128
20130
  kind: external_exports.literal("SOFTWARE_INVENTORY_REQUEST"),
@@ -20135,7 +20137,9 @@ var softwareInventoryPart = base.extend({
20135
20137
  sequence: external_exports.number().int().min(0).max(INVENTORY_MAX_PARTS - 1),
20136
20138
  total: external_exports.number().int().min(1).max(INVENTORY_MAX_PARTS),
20137
20139
  sha256: external_exports.string().regex(/^[0-9a-f]{64}$/),
20138
- data: external_exports.string().min(1).max(INVENTORY_PART_CHARS).regex(/^[A-Za-z0-9+/]+={0,2}$/)
20140
+ data: external_exports.string().min(1).max(INVENTORY_PART_CHARS).regex(/^[A-Za-z0-9+/]+={0,2}$/),
20141
+ /** Set when the snapshot is of a pinned SSH host of this agent rather than the computer itself. */
20142
+ resource_id: uuid3.optional()
20139
20143
  });
20140
20144
  var envelopeSchema = external_exports.discriminatedUnion("kind", [
20141
20145
  hello,
@@ -20252,7 +20256,12 @@ var AGENT_FEATURE_MIN_VERSION = Object.freeze({
20252
20256
  /** MONITOR_CONFIG / METRICS (ADR DEVICE_MONITORING). */
20253
20257
  monitoring: "0.2.0",
20254
20258
  /** SOFTWARE_INVENTORY_* (ADR DEVICE_INVENTORY). */
20255
- inventory: "0.3.0"
20259
+ inventory: "0.3.0",
20260
+ /**
20261
+ * `ssh_hosts` in SOFTWARE_INVENTORY_CONFIG (ADR SECURITY_INTELLIGENCE 11.6). Older agents drop the whole config frame
20262
+ * when it carries the field, so the relay sends it only to agents known to have this version.
20263
+ */
20264
+ ssh_inventory: "0.4.0"
20256
20265
  });
20257
20266
 
20258
20267
  // ../../packages/protocol/dist/security/types.js
@@ -20370,6 +20379,52 @@ var IMAGE_PRODUCTS = Object.freeze({
20370
20379
  alpine: "alpine"
20371
20380
  });
20372
20381
 
20382
+ // ../../packages/protocol/dist/security/intel.js
20383
+ var CPE_PRODUCTS = Object.freeze({
20384
+ node: { cpe: "nodejs:node.js", scheme: "semver", name: "Node.js", releases: "node", packaged: /^nodejs$/ },
20385
+ php: { cpe: "php:php", scheme: "php", name: "PHP", releases: "php", packaged: /^php(\d+(\.\d+)?)?$/ },
20386
+ python: { cpe: "python:python", scheme: "dotted", name: "Python", packaged: /^python3(\.\d+)?$/ },
20387
+ openssl: { cpe: "openssl:openssl", scheme: "dotted", name: "OpenSSL", packaged: /^openssl(\d+(\.\d+)?)?$/ },
20388
+ nginx: { cpe: "f5:nginx", scheme: "dotted", name: "nginx", packaged: /^nginx$/ },
20389
+ apache: { cpe: "apache:http_server", scheme: "dotted", name: "Apache HTTP Server", packaged: /^(apache2|httpd)$/ },
20390
+ httpd: { cpe: "apache:http_server", scheme: "dotted", name: "Apache HTTP Server", packaged: /^(apache2|httpd)$/ },
20391
+ redis: { cpe: "redis:redis", scheme: "dotted", name: "Redis", packaged: /^redis$/ },
20392
+ mysql: { cpe: "oracle:mysql", scheme: "dotted", name: "MySQL", packaged: /^mysql-(server|community)?.*$|^mysql\d.*$/ },
20393
+ mariadb: { cpe: "mariadb:mariadb", scheme: "dotted", name: "MariaDB", packaged: /^mariadb(-\d+(\.\d+)?)?$/ },
20394
+ postgresql: { cpe: "postgresql:postgresql", scheme: "dotted", name: "PostgreSQL", packaged: /^postgresql(-\d+)?$/ },
20395
+ curl: { cpe: "haxx:curl", scheme: "dotted", name: "curl", packaged: /^curl$/ },
20396
+ git: { cpe: "git-scm:git", scheme: "dotted", name: "Git", packaged: /^git$/ },
20397
+ openssh: { cpe: "openbsd:openssh", scheme: "dotted", name: "OpenSSH", packaged: /^openssh(-server|-client)?$/ },
20398
+ sqlite: { cpe: "sqlite:sqlite", scheme: "dotted", name: "SQLite", packaged: /^sqlite3?$/ },
20399
+ ruby: { cpe: "ruby-lang:ruby", scheme: "dotted", name: "Ruby", packaged: /^ruby(\d+(\.\d+)?)?$/ },
20400
+ go: { cpe: "golang:go", scheme: "dotted", name: "Go", packaged: /^golang(-\d+(\.\d+)?)?$/ },
20401
+ composer: { cpe: "getcomposer:composer", scheme: "dotted", name: "Composer", packaged: /^composer$/ },
20402
+ bash: { cpe: "gnu:bash", scheme: "dotted", name: "Bash", packaged: /^bash$/ },
20403
+ caddy: { cpe: "caddyserver:caddy", scheme: "dotted", name: "Caddy", packaged: /^caddy$/ },
20404
+ haproxy: { cpe: "haproxy:haproxy", scheme: "dotted", name: "HAProxy", packaged: /^haproxy$/ },
20405
+ traefik: { cpe: "traefik:traefik", scheme: "dotted", name: "Traefik", packaged: /^traefik$/ },
20406
+ docker: { cpe: "docker:engine", scheme: "dotted", name: "Docker Engine", packaged: /^(docker\.io|docker-ce|moby-engine)$/ }
20407
+ });
20408
+ var EOL_SLUGS = Object.freeze({
20409
+ ubuntu: "ubuntu",
20410
+ debian: "debian",
20411
+ centos: "centos",
20412
+ alpine: "alpine-linux",
20413
+ "windows-server": "windows-server",
20414
+ node: "nodejs",
20415
+ php: "php",
20416
+ python: "python",
20417
+ mysql: "mysql",
20418
+ mariadb: "mariadb",
20419
+ postgresql: "postgresql",
20420
+ ruby: "ruby"
20421
+ });
20422
+
20423
+ // ../../packages/protocol/dist/security/risk.js
20424
+ var RATING_BASE = Object.freeze({ critical: 95, high: 80, medium: 55, low: 25, negligible: 10 });
20425
+ var CRITICALITY_FACTOR = Object.freeze({ low: 0.8, normal: 1, high: 1.1, critical: 1.2 });
20426
+ var CLASS_FACTOR = Object.freeze({ confirmed: 1, potential: 0.7, unknown: 0.5, not_affected: 0, fixed: 0 });
20427
+
20373
20428
  // ../../packages/protocol/dist/http.js
20374
20429
  var HTTP_API_VERSION = 1;
20375
20430
  var requestIdSchema = external_exports.uuid();
@@ -21994,7 +22049,7 @@ var import_node_fs = require("node:fs");
21994
22049
  var import_node_path2 = require("node:path");
21995
22050
  var import_node_sea = require("node:sea");
21996
22051
  var import_node_url = require("node:url");
21997
- var SOURCE_VERSION = "0.3.2";
22052
+ var SOURCE_VERSION = "0.4.0";
21998
22053
  var BUILD_INFO = typeof define_CONBRIDGE_BUILD_default === "object" && define_CONBRIDGE_BUILD_default !== null ? define_CONBRIDGE_BUILD_default : null;
21999
22054
  var AGENT_VERSION = BUILD_INFO?.version ?? SOURCE_VERSION;
22000
22055
  function runningAsSea() {
@@ -25014,406 +25069,341 @@ var MonitorLoop = class {
25014
25069
  };
25015
25070
 
25016
25071
  // dist/inventory/loop.js
25017
- var import_node_crypto8 = require("node:crypto");
25072
+ var import_node_crypto9 = require("node:crypto");
25018
25073
  var import_node_zlib = require("node:zlib");
25019
- function encodeSnapshot(snapshot, requestId, runId = (0, import_node_crypto8.randomUUID)()) {
25020
- const gz = (0, import_node_zlib.gzipSync)(Buffer.from(JSON.stringify(snapshot), "utf8"), { level: 9 });
25021
- if (gz.byteLength > INVENTORY_MAX_COMPRESSED_BYTES)
25022
- return null;
25023
- const sha2563 = (0, import_node_crypto8.createHash)("sha256").update(gz).digest("hex");
25024
- const data = gz.toString("base64");
25025
- const total = Math.max(1, Math.ceil(data.length / INVENTORY_PART_CHARS));
25026
- return Array.from({ length: total }, (_, sequence) => ({
25027
- run_id: runId,
25028
- request_id: requestId,
25029
- sequence,
25030
- total,
25031
- sha256: sha2563,
25032
- data: data.slice(sequence * INVENTORY_PART_CHARS, (sequence + 1) * INVENTORY_PART_CHARS)
25033
- }));
25034
- }
25035
- var InventoryLoop = class {
25036
- #options;
25037
- #logger;
25038
- #intervalS = null;
25039
- #timer = null;
25040
- #running = false;
25041
- #stopped = false;
25042
- constructor(options) {
25043
- this.#options = options;
25044
- this.#logger = options.logger ?? silentLogger;
25045
- }
25046
- get enabled() {
25047
- return this.#intervalS !== null;
25048
- }
25049
- apply(config2) {
25050
- if (this.#stopped)
25051
- return;
25052
- if (!config2.enabled) {
25053
- if (this.#intervalS !== null)
25054
- this.#logger.info("software inventory stopped");
25055
- this.#intervalS = null;
25056
- this.#clear();
25057
- return;
25058
- }
25059
- if (this.#intervalS === config2.interval_s && this.#timer)
25060
- return;
25061
- const first = this.#intervalS === null;
25062
- this.#intervalS = config2.interval_s;
25063
- this.#clear();
25064
- const jitter = (this.#options.firstRunMs ?? (() => 5e3 + Math.floor(Math.random() * 25e3)))();
25065
- const last = this.#options.lastSentAtMs?.() ?? null;
25066
- const now = (this.#options.now ?? Date.now)();
25067
- const due = last === null ? jitter : Math.max(jitter, last + config2.interval_s * 1e3 - now);
25068
- this.#schedule(first ? due : config2.interval_s * 1e3);
25069
- this.#logger.info("software inventory scheduled", { interval_s: config2.interval_s });
25070
- }
25071
- /** Console Refresh: one run now (ignored while off or while a run is in progress). */
25072
- request(requestId) {
25073
- if (this.#stopped || this.#intervalS === null || this.#running)
25074
- return;
25075
- void this.#run(requestId);
25076
- }
25077
- stop() {
25078
- this.#stopped = true;
25079
- this.#intervalS = null;
25080
- this.#clear();
25081
- }
25082
- #clear() {
25083
- if (this.#timer)
25084
- clearTimeout(this.#timer);
25085
- this.#timer = null;
25086
- }
25087
- #schedule(ms) {
25088
- this.#timer = setTimeout(() => {
25089
- this.#timer = null;
25090
- void this.#run(null).finally(() => {
25091
- if (!this.#stopped && this.#intervalS !== null && !this.#timer)
25092
- this.#schedule(this.#intervalS * 1e3);
25093
- });
25094
- }, ms);
25095
- this.#timer.unref?.();
25096
- }
25097
- async #run(requestId) {
25098
- if (this.#running)
25099
- return;
25100
- if (!this.#options.allowed()) {
25101
- this.#logger.info("software inventory is off on this computer (conbridge-agent config inventory on)");
25102
- return;
25103
- }
25104
- this.#running = true;
25105
- const started = Date.now();
25106
- try {
25107
- const snapshot = await this.#options.collect();
25108
- if (this.#stopped || this.#intervalS === null)
25109
- return;
25110
- const parts = encodeSnapshot(snapshot, requestId);
25111
- if (!parts) {
25112
- this.#logger.warn("software inventory too large to send");
25113
- return;
25114
- }
25115
- this.#options.send(parts);
25116
- this.#options.onSent?.((this.#options.now ?? Date.now)());
25117
- this.#logger.info("software inventory sent", { packages: snapshot.packages.length, containers: snapshot.containers.length, parts: parts.length, ms: Date.now() - started });
25118
- } catch (error63) {
25119
- this.#logger.warn("software inventory failed", { error: error63 instanceof Error ? error63.name : "unknown" });
25120
- } finally {
25121
- this.#running = false;
25122
- }
25123
- }
25124
- };
25125
25074
 
25126
- // dist/inventory/collector.js
25075
+ // dist/ssh/exec.js
25127
25076
  var import_node_child_process6 = require("node:child_process");
25128
- var import_promises11 = require("node:fs/promises");
25129
- var import_node_os4 = require("node:os");
25077
+ var import_node_path13 = require("node:path");
25130
25078
 
25131
- // dist/inventory/parsers/packages.js
25132
- var NAME_MAX = 200;
25133
- var VERSION_MAX = 128;
25134
- var ARCH_MAX = 32;
25135
- var PUBLISHER_MAX = 200;
25136
- var MAX_PACKAGES = INVENTORY_LIMITS.packages;
25137
- function text(value, max) {
25138
- if (typeof value !== "string")
25139
- return "";
25140
- const trimmed = value.trim();
25141
- if (trimmed.length <= max)
25142
- return trimmed;
25143
- return trimmed.slice(0, max).trimEnd();
25144
- }
25145
- function nameOf(value) {
25146
- return text(value, NAME_MAX);
25147
- }
25148
- function versionOf(value) {
25149
- return text(value, VERSION_MAX);
25150
- }
25151
- function asRecord(value) {
25152
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
25079
+ // dist/ssh/hosts.js
25080
+ var import_node_crypto8 = require("node:crypto");
25081
+ var import_promises11 = require("node:fs/promises");
25082
+ var import_node_path12 = require("node:path");
25083
+ var MAX_SSH_HOSTS = 64;
25084
+ var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
25085
+ 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])?)*$/;
25086
+ var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
25087
+ var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
25088
+ function isValidSshHost(value) {
25089
+ return DNS_HOST.test(value) || IPV6_HOST.test(value);
25153
25090
  }
25154
- function lines(stdout) {
25155
- if (typeof stdout !== "string")
25156
- return [];
25157
- return stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
25091
+ function isValidIdentityPath(value) {
25092
+ return (0, import_node_path12.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
25158
25093
  }
25159
- function push(result2, item) {
25160
- if (result2.length < MAX_PACKAGES)
25161
- result2.push(item);
25094
+ var PINNABLE_KEY_TYPES = Object.freeze([
25095
+ "ssh-ed25519",
25096
+ "ecdsa-sha2-nistp256",
25097
+ "ecdsa-sha2-nistp384",
25098
+ "ecdsa-sha2-nistp521",
25099
+ "ssh-rsa"
25100
+ ]);
25101
+ var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
25102
+ var sshHostSchema = external_exports.strictObject({
25103
+ resource_id: external_exports.uuid(),
25104
+ alias: external_exports.string().regex(SSH_ALIAS),
25105
+ host: external_exports.string().refine(isValidSshHost, "Invalid host"),
25106
+ port: external_exports.number().int().min(1).max(65535),
25107
+ user: external_exports.string().regex(SSH_USER).optional(),
25108
+ identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
25109
+ production: external_exports.boolean(),
25110
+ key_type: external_exports.enum(PINNABLE_KEY_TYPES),
25111
+ public_key: external_exports.string().min(16).max(8192).regex(base643),
25112
+ fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
25113
+ pinned_at: external_exports.iso.datetime({ offset: true })
25114
+ });
25115
+ var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS) });
25116
+ function sshPaths(stateDir) {
25117
+ const dir = (0, import_node_path12.join)(stateDir, "ssh");
25118
+ return { dir, hosts: (0, import_node_path12.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path12.join)(dir, "known_hosts") };
25162
25119
  }
25163
- function integerText(value) {
25164
- const raw = text(value, 64);
25165
- if (!/^\d+$/.test(raw))
25166
- return void 0;
25167
- const number4 = Number(raw);
25168
- return Number.isSafeInteger(number4) ? number4 : void 0;
25120
+ function knownHostsPath(paths, resourceId) {
25121
+ return (0, import_node_path12.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
25169
25122
  }
25170
- function sizeFromKiB(value) {
25171
- const kib = integerText(value);
25172
- if (kib === void 0)
25173
- return void 0;
25174
- const bytes3 = kib * 1024;
25175
- return Number.isSafeInteger(bytes3) ? bytes3 : void 0;
25123
+ function hostKeyAlias(host) {
25124
+ return "conbridge-" + host.resource_id;
25176
25125
  }
25177
- function sizeFromKb(value) {
25178
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
25179
- return void 0;
25180
- const bytes3 = value * 1024;
25181
- return Number.isSafeInteger(bytes3) && bytes3 > 0 ? bytes3 : void 0;
25126
+ function fingerprintOf(publicKey) {
25127
+ return "SHA256:" + (0, import_node_crypto8.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
25182
25128
  }
25183
- function isApplicationPath(path) {
25184
- return path.startsWith("/Applications/") || /^\/Users\/[^/]+\/Applications\//.test(path);
25129
+ function normalizeFingerprint(value) {
25130
+ const trimmed = value.trim();
25131
+ return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
25185
25132
  }
25186
- function installDate(value) {
25187
- if (typeof value !== "string")
25188
- return void 0;
25189
- const raw = value.trim();
25190
- if (!/^\d{8}$/.test(raw))
25191
- return void 0;
25192
- const year = Number(raw.slice(0, 4));
25193
- const month = Number(raw.slice(4, 6));
25194
- const day = Number(raw.slice(6, 8));
25195
- if (month < 1 || month > 12 || day < 1)
25196
- return void 0;
25197
- const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
25198
- const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
25199
- const limit = days[month - 1];
25200
- if (limit === void 0 || day > limit)
25201
- return void 0;
25202
- return `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;
25133
+ function parseKeyscan(output2) {
25134
+ const keys = [];
25135
+ for (const line of output2.split("\n")) {
25136
+ const trimmed = line.trim();
25137
+ if (trimmed === "" || trimmed.startsWith("#"))
25138
+ continue;
25139
+ const [, type, key] = trimmed.split(/\s+/);
25140
+ if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
25141
+ continue;
25142
+ keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
25143
+ }
25144
+ return keys;
25203
25145
  }
25204
- function parseJson(json2) {
25205
- try {
25206
- return JSON.parse(json2);
25207
- } catch {
25208
- return void 0;
25146
+ function preferredKey(keys) {
25147
+ for (const type of PINNABLE_KEY_TYPES) {
25148
+ const key = keys.find((candidate) => candidate.key_type === type);
25149
+ if (key)
25150
+ return key;
25209
25151
  }
25152
+ return null;
25210
25153
  }
25211
- function parseDpkg(stdout) {
25212
- const result2 = [];
25213
- for (const line of lines(stdout)) {
25214
- const parts = line.split(" ");
25215
- if (parts.length < 5)
25216
- continue;
25217
- const status = text(parts[4], 16);
25218
- if (!status.startsWith("ii") && !status.startsWith("hi"))
25219
- continue;
25220
- const name3 = nameOf(parts[0]);
25221
- if (!name3)
25222
- continue;
25223
- const version6 = versionOf(parts[1]);
25224
- const item = { name: name3, version: version6, manager: "dpkg" };
25225
- const arch3 = text(parts[2], ARCH_MAX);
25226
- if (arch3)
25227
- item.arch = arch3;
25228
- const size = sizeFromKiB(parts[3]);
25229
- if (size !== void 0)
25230
- item.size_bytes = size;
25231
- const sourceName = nameOf(parts[5]);
25232
- if (sourceName && sourceName !== name3)
25233
- item.source_name = sourceName;
25234
- const sourceVersion = versionOf(parts[6]);
25235
- if (sourceVersion && sourceVersion !== version6)
25236
- item.source_version = sourceVersion;
25237
- push(result2, item);
25154
+ async function loadSshHosts(paths) {
25155
+ let text4;
25156
+ try {
25157
+ text4 = await (0, import_promises11.readFile)(paths.hosts, "utf8");
25158
+ } catch (error63) {
25159
+ if (errorCode2(error63) === "ENOENT")
25160
+ return [];
25161
+ throw error63;
25238
25162
  }
25239
- return result2;
25163
+ return hostsFileSchema.parse(JSON.parse(text4)).hosts;
25240
25164
  }
25241
- function parseRpm(stdout) {
25242
- const result2 = [];
25243
- for (const line of lines(stdout)) {
25244
- const parts = line.split(" ");
25245
- if (parts.length < 6)
25246
- continue;
25247
- const name3 = nameOf(parts[0]);
25248
- if (!name3 || name3 === "gpg-pubkey")
25249
- continue;
25250
- const version6 = versionOf(parts[2]);
25251
- const release2 = versionOf(parts[3]);
25252
- if (!version6 || !release2)
25253
- continue;
25254
- const epoch = text(parts[1], 32);
25255
- const epochPrefix = /^\d+$/.test(epoch) ? `${epoch}:` : "";
25256
- const item = { name: name3, version: versionOf(`${epochPrefix}${version6}-${release2}`), manager: "rpm" };
25257
- const arch3 = text(parts[4], ARCH_MAX);
25258
- if (arch3 && arch3 !== "(none)")
25259
- item.arch = arch3;
25260
- const size = integerText(parts[5]);
25261
- if (size !== void 0)
25262
- item.size_bytes = size;
25263
- push(result2, item);
25165
+ async function ensureSshDirs(paths) {
25166
+ for (const dir of [paths.dir, paths.knownHostsDir]) {
25167
+ await (0, import_promises11.mkdir)(dir, { recursive: true, mode: 448 });
25168
+ await (0, import_promises11.chmod)(dir, 448);
25264
25169
  }
25265
- return result2;
25266
25170
  }
25267
- function parseApk(stdout) {
25268
- const result2 = [];
25269
- for (const line of lines(stdout)) {
25270
- const trimmed = line.trim();
25271
- const match = /^(.+)-([0-9][^-\s]*-r\d+)\s/.exec(trimmed);
25272
- if (!match)
25273
- continue;
25274
- const name3 = nameOf(match[1]);
25275
- if (!name3)
25276
- continue;
25277
- const item = { name: name3, version: versionOf(match[2]), manager: "apk" };
25278
- const rest = trimmed.slice(match[0].length).trim().split(/\s+/);
25279
- const arch3 = text(rest[0], ARCH_MAX);
25280
- if (arch3)
25281
- item.arch = arch3;
25282
- push(result2, item);
25283
- }
25284
- return result2;
25171
+ async function saveSshHosts(paths, hosts) {
25172
+ await ensureSshDirs(paths);
25173
+ await writeFileAtomic(paths.hosts, JSON.stringify(hostsFileSchema.parse({ version: 1, hosts }), null, 2) + "\n", 384);
25285
25174
  }
25286
- function parsePacman(stdout) {
25287
- const result2 = [];
25288
- for (const line of lines(stdout)) {
25289
- const parts = line.trim().split(/\s+/);
25290
- if (parts.length < 2)
25291
- continue;
25292
- const name3 = nameOf(parts[0]);
25293
- if (!name3)
25294
- continue;
25295
- push(result2, { name: name3, version: versionOf(parts[1]), manager: "pacman" });
25296
- }
25297
- return result2;
25175
+ async function writeKnownHosts(paths, host) {
25176
+ await ensureSshDirs(paths);
25177
+ await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
25178
+ `, 384);
25298
25179
  }
25299
- function parseSnap(stdout) {
25300
- const result2 = [];
25301
- for (const line of lines(stdout)) {
25302
- const parts = line.trim().split(/\s+/);
25303
- if (parts.length < 2)
25304
- continue;
25305
- if (parts[0] === "Name" && parts[1] === "Version")
25306
- continue;
25307
- const name3 = nameOf(parts[0]);
25308
- if (!name3)
25309
- continue;
25310
- const item = { name: name3, version: versionOf(parts[1]), manager: "snap" };
25311
- const publisher = text(parts[4], PUBLISHER_MAX).replace(/[✓*]+$/u, "").trim();
25312
- if (publisher && publisher !== "-")
25313
- item.publisher = publisher;
25314
- push(result2, item);
25180
+ async function validateNewHost(input2) {
25181
+ if (!SSH_ALIAS.test(input2.alias))
25182
+ throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
25183
+ if (!isValidSshHost(input2.host))
25184
+ throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
25185
+ if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
25186
+ throw new Error("Port must be 1-65535");
25187
+ if (input2.user !== void 0 && !SSH_USER.test(input2.user))
25188
+ throw new Error("User must be a plain login name");
25189
+ if (input2.identity !== void 0) {
25190
+ if (!isValidIdentityPath(input2.identity))
25191
+ throw new Error("Identity must be an absolute path without quotes, % or control characters");
25192
+ const info = await (0, import_promises11.stat)(input2.identity).catch(() => null);
25193
+ if (!info?.isFile())
25194
+ throw new Error("Identity file not found");
25315
25195
  }
25316
- return result2;
25317
25196
  }
25318
- function parseBrewVersions(stdout, manager) {
25319
- const result2 = [];
25320
- for (const line of lines(stdout)) {
25321
- const parts = line.trim().split(/\s+/);
25322
- if (parts.length < 2)
25323
- continue;
25324
- const name3 = nameOf(parts[0]);
25325
- if (!name3)
25326
- continue;
25327
- push(result2, { name: name3, version: versionOf(parts[1]), manager });
25328
- }
25329
- return result2;
25197
+ async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
25198
+ await validateNewHost(input2);
25199
+ const hosts = await loadSshHosts(paths);
25200
+ if (hosts.some((host2) => host2.alias === input2.alias))
25201
+ throw new Error(`An SSH host named ${input2.alias} already exists`);
25202
+ if (hosts.length >= MAX_SSH_HOSTS)
25203
+ throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
25204
+ const host = sshHostSchema.parse({
25205
+ resource_id: (0, import_node_crypto8.randomUUID)(),
25206
+ alias: input2.alias,
25207
+ host: input2.host,
25208
+ port: input2.port ?? 22,
25209
+ ...input2.user !== void 0 ? { user: input2.user } : {},
25210
+ ...input2.identity !== void 0 ? { identity: input2.identity } : {},
25211
+ production: input2.production === true,
25212
+ key_type: key.key_type,
25213
+ public_key: key.public_key,
25214
+ fingerprint: key.fingerprint,
25215
+ pinned_at: now.toISOString()
25216
+ });
25217
+ await writeKnownHosts(paths, host);
25218
+ await saveSshHosts(paths, [...hosts, host]);
25219
+ return host;
25330
25220
  }
25331
- function parseNpmGlobal(json2) {
25332
- const root = asRecord(parseJson(json2));
25333
- const dependencies = asRecord(root?.dependencies);
25334
- if (!dependencies)
25335
- return [];
25336
- const result2 = [];
25337
- for (const [rawName, value] of Object.entries(dependencies)) {
25338
- const info = asRecord(value);
25339
- if (!info || typeof info.version !== "string")
25340
- continue;
25341
- const name3 = nameOf(rawName);
25342
- if (!name3)
25343
- continue;
25344
- push(result2, { name: name3, version: versionOf(info.version), manager: "npm-global" });
25345
- }
25346
- return result2;
25221
+ async function findSshHost(paths, alias) {
25222
+ return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
25347
25223
  }
25348
- function parseMacApps(json2) {
25349
- const root = asRecord(parseJson(json2));
25350
- const items = root?.SPApplicationsDataType;
25351
- if (!Array.isArray(items))
25352
- return [];
25353
- const result2 = [];
25354
- const seen = /* @__PURE__ */ new Set();
25355
- for (const value of items) {
25356
- const info = asRecord(value);
25357
- if (!info)
25358
- continue;
25359
- const name3 = nameOf(info._name);
25360
- if (!name3)
25361
- continue;
25362
- const path = text(info.path, 4096);
25363
- if (!isApplicationPath(path))
25364
- continue;
25365
- const version6 = versionOf(info.version);
25366
- const key = `${name3}\0${version6}`;
25367
- if (seen.has(key))
25368
- continue;
25369
- seen.add(key);
25370
- const item = { name: name3, version: version6, manager: "macos-app" };
25371
- const source = text(info.obtained_from, 60);
25372
- if (source === "apple")
25373
- item.publisher = "Apple";
25374
- else if (source === "mac_app_store")
25375
- item.publisher = "App Store";
25376
- push(result2, item);
25377
- }
25378
- return result2;
25224
+ async function updateHost(paths, alias, change) {
25225
+ const hosts = await loadSshHosts(paths);
25226
+ const index = hosts.findIndex((host) => host.alias === alias);
25227
+ if (index < 0)
25228
+ throw new Error(`No SSH host named ${alias}`);
25229
+ const updated = sshHostSchema.parse(change(hosts[index]));
25230
+ const next = [...hosts];
25231
+ next[index] = updated;
25232
+ if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
25233
+ await writeKnownHosts(paths, updated);
25234
+ await saveSshHosts(paths, next);
25235
+ return updated;
25379
25236
  }
25380
- function parseWindowsPrograms(json2) {
25381
- const parsed = parseJson(json2);
25382
- const entries = Array.isArray(parsed) ? parsed : [parsed];
25383
- const result2 = [];
25384
- const seen = /* @__PURE__ */ new Set();
25385
- for (const value of entries) {
25386
- const info = asRecord(value);
25387
- if (!info)
25388
- continue;
25389
- const name3 = nameOf(info.DisplayName);
25390
- if (!name3)
25391
- continue;
25392
- const version6 = versionOf(info.DisplayVersion);
25393
- const key = `${name3}\0${version6}`;
25394
- if (seen.has(key))
25395
- continue;
25396
- seen.add(key);
25397
- const item = { name: name3, version: version6, manager: "windows" };
25398
- const publisher = text(info.Publisher, PUBLISHER_MAX);
25399
- if (publisher)
25400
- item.publisher = publisher;
25401
- const size = sizeFromKb(info.EstimatedSize);
25402
- if (size !== void 0)
25403
- item.size_bytes = size;
25404
- const installedOn = installDate(info.InstallDate);
25405
- if (installedOn)
25406
- item.installed_on = installedOn;
25407
- push(result2, item);
25408
- }
25409
- return result2;
25237
+ async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
25238
+ return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
25239
+ }
25240
+ async function setSshHostProduction(paths, alias, production) {
25241
+ return await updateHost(paths, alias, (host) => ({ ...host, production }));
25242
+ }
25243
+ async function removeSshHost(paths, alias) {
25244
+ const hosts = await loadSshHosts(paths);
25245
+ const host = hosts.find((entry) => entry.alias === alias);
25246
+ if (!host)
25247
+ return false;
25248
+ await saveSshHosts(paths, hosts.filter((entry) => entry !== host));
25249
+ await (0, import_promises11.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
25250
+ return true;
25251
+ }
25252
+ function hostAddress(host) {
25253
+ if (host.port === 22)
25254
+ return host.host;
25255
+ return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
25256
+ }
25257
+ function inventoryResource2(host) {
25258
+ return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
25410
25259
  }
25411
25260
 
25412
- // dist/inventory/parsers/services.js
25413
- var NAME_MAX2 = 200;
25414
- var DESCRIPTION_MAX = 200;
25415
- var MAX_SERVICES = INVENTORY_LIMITS.services;
25416
- function text2(value, max) {
25261
+ // dist/ssh/exec.js
25262
+ var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
25263
+ function sshBinariesFromEnv(env = process.env) {
25264
+ const pick2 = (value, fallback) => value && (0, import_node_path13.isAbsolute)(value) ? value : fallback;
25265
+ return { ssh: pick2(env.CONBRIDGE_SSH_BIN, DEFAULT_SSH_BINARIES.ssh), keyscan: pick2(env.CONBRIDGE_SSH_KEYSCAN_BIN, DEFAULT_SSH_BINARIES.keyscan) };
25266
+ }
25267
+ function sshChildEnv(env = process.env) {
25268
+ const child = {};
25269
+ for (const key of ["PATH", "HOME", "USER", "LOGNAME", "SSH_AUTH_SOCK", "LANG", "TMPDIR"]) {
25270
+ if (env[key] !== void 0)
25271
+ child[key] = env[key];
25272
+ }
25273
+ return child;
25274
+ }
25275
+ function runProcess(file2, args, options) {
25276
+ const started = Date.now();
25277
+ return new Promise((resolve8) => {
25278
+ const kept = { stdout: [], stderr: [] };
25279
+ const totals = { stdout: 0, stderr: 0 };
25280
+ let keptBytes = 0;
25281
+ let truncated = false;
25282
+ let timedOut = false;
25283
+ let settled = false;
25284
+ const child = (0, import_node_child_process6.spawn)(file2, [...args], { stdio: ["ignore", "pipe", "pipe"], env: options.env, shell: false });
25285
+ const collect = (stream) => (chunk2) => {
25286
+ totals[stream] += chunk2.length;
25287
+ const room = options.maxBytes - keptBytes;
25288
+ if (room <= 0) {
25289
+ truncated = true;
25290
+ return;
25291
+ }
25292
+ const piece = chunk2.length > room ? chunk2.subarray(0, room) : chunk2;
25293
+ if (piece.length < chunk2.length)
25294
+ truncated = true;
25295
+ kept[stream].push(piece);
25296
+ keptBytes += piece.length;
25297
+ };
25298
+ child.stdout.on("data", collect("stdout"));
25299
+ child.stderr.on("data", collect("stderr"));
25300
+ let killTimer;
25301
+ const timer = setTimeout(() => {
25302
+ timedOut = true;
25303
+ child.kill("SIGTERM");
25304
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 2e3);
25305
+ }, options.timeoutMs);
25306
+ const finish = (exitCode, spawnError) => {
25307
+ if (settled)
25308
+ return;
25309
+ settled = true;
25310
+ clearTimeout(timer);
25311
+ if (killTimer)
25312
+ clearTimeout(killTimer);
25313
+ resolve8({
25314
+ exitCode,
25315
+ timedOut,
25316
+ truncated,
25317
+ durationMs: Date.now() - started,
25318
+ stdout: Buffer.concat(kept.stdout).toString("utf8"),
25319
+ stderr: Buffer.concat(kept.stderr).toString("utf8"),
25320
+ stdoutBytes: totals.stdout,
25321
+ stderrBytes: totals.stderr,
25322
+ ...spawnError !== void 0 ? { spawnError } : {}
25323
+ });
25324
+ };
25325
+ child.on("error", (error63) => finish(null, error63.code ?? "SPAWN_FAILED"));
25326
+ child.on("close", (code) => finish(code));
25327
+ });
25328
+ }
25329
+ function keyscanType(type) {
25330
+ if (type === "ssh-ed25519")
25331
+ return "ed25519";
25332
+ if (type === "ssh-rsa")
25333
+ return "rsa";
25334
+ return "ecdsa";
25335
+ }
25336
+ function hostKeyAlgorithms(type) {
25337
+ return type === "ssh-rsa" ? "rsa-sha2-512,rsa-sha2-256" : type;
25338
+ }
25339
+ function sshConfigPath(path) {
25340
+ if (/["\n\r]/.test(path))
25341
+ throw new Error("Path cannot be used in an ssh option");
25342
+ const escaped = path.replace(/%/g, "%%");
25343
+ return /\s/.test(escaped) ? `"${escaped}"` : escaped;
25344
+ }
25345
+ var KEYSCAN_TIMEOUT_S = 10;
25346
+ async function scanHostKeys(binaries, target, options = {}) {
25347
+ const types = options.types ?? ["ssh-ed25519", "ecdsa-sha2-nistp256", "ssh-rsa"];
25348
+ const args = ["-T", String(KEYSCAN_TIMEOUT_S), "-p", String(target.port), "-t", [...new Set(types.map(keyscanType))].join(","), "--", target.host];
25349
+ const result2 = await runProcess(binaries.keyscan, args, { timeoutMs: (KEYSCAN_TIMEOUT_S + 5) * 1e3, maxBytes: 64 * 1024, env: sshChildEnv(options.env) });
25350
+ if (result2.spawnError)
25351
+ return { keys: [], error: "ssh-keyscan could not be started (" + result2.spawnError + ")" };
25352
+ const keys = parseKeyscan(result2.stdout);
25353
+ return { keys, error: keys.length === 0 ? result2.timedOut ? "Host did not answer in time" : "Host returned no usable host key" : null };
25354
+ }
25355
+ function buildSshArgs(paths, host, command2) {
25356
+ const options = [
25357
+ "BatchMode=yes",
25358
+ "StrictHostKeyChecking=yes",
25359
+ `UserKnownHostsFile=${sshConfigPath(knownHostsPath(paths, host.resource_id))}`,
25360
+ "GlobalKnownHostsFile=/dev/null",
25361
+ `HostKeyAlias=${hostKeyAlias(host)}`,
25362
+ `HostKeyAlgorithms=${hostKeyAlgorithms(host.key_type)}`,
25363
+ "UpdateHostKeys=no",
25364
+ "CheckHostIP=no",
25365
+ "PasswordAuthentication=no",
25366
+ "KbdInteractiveAuthentication=no",
25367
+ "ProxyCommand=none",
25368
+ "PermitLocalCommand=no",
25369
+ "ForwardAgent=no",
25370
+ "ForwardX11=no",
25371
+ "ClearAllForwardings=yes",
25372
+ "ControlMaster=no",
25373
+ "ControlPath=none",
25374
+ "RequestTTY=no",
25375
+ "ConnectTimeout=15",
25376
+ "ServerAliveInterval=15",
25377
+ "ServerAliveCountMax=3",
25378
+ "LogLevel=ERROR",
25379
+ ...host.identity !== void 0 ? ["IdentitiesOnly=yes"] : []
25380
+ ];
25381
+ return [
25382
+ "-F",
25383
+ "/dev/null",
25384
+ ...options.flatMap((option) => ["-o", option]),
25385
+ ...host.identity !== void 0 ? ["-i", host.identity] : [],
25386
+ "-p",
25387
+ String(host.port),
25388
+ ...host.user !== void 0 ? ["-l", host.user] : [],
25389
+ "-n",
25390
+ "-T",
25391
+ "--",
25392
+ host.host,
25393
+ command2
25394
+ ];
25395
+ }
25396
+ function isHostKeyFailure(result2) {
25397
+ return result2.exitCode === 255 && result2.stdoutBytes === 0 && /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No (?:ED25519|ECDSA|RSA) host key is known/i.test(result2.stderr);
25398
+ }
25399
+
25400
+ // dist/inventory/parsers/packages.js
25401
+ var NAME_MAX = 200;
25402
+ var VERSION_MAX = 128;
25403
+ var ARCH_MAX = 32;
25404
+ var PUBLISHER_MAX = 200;
25405
+ var MAX_PACKAGES = INVENTORY_LIMITS.packages;
25406
+ function text(value, max) {
25417
25407
  if (typeof value !== "string")
25418
25408
  return "";
25419
25409
  const trimmed = value.trim();
@@ -25421,1702 +25411,2021 @@ function text2(value, max) {
25421
25411
  return trimmed;
25422
25412
  return trimmed.slice(0, max).trimEnd();
25423
25413
  }
25424
- function asRecord2(value) {
25414
+ function nameOf(value) {
25415
+ return text(value, NAME_MAX);
25416
+ }
25417
+ function versionOf(value) {
25418
+ return text(value, VERSION_MAX);
25419
+ }
25420
+ function asRecord(value) {
25425
25421
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
25426
25422
  }
25427
- function lines2(stdout) {
25423
+ function lines(stdout) {
25428
25424
  if (typeof stdout !== "string")
25429
25425
  return [];
25430
25426
  return stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
25431
25427
  }
25432
- function parseJson2(value) {
25428
+ function push(result2, item) {
25429
+ if (result2.length < MAX_PACKAGES)
25430
+ result2.push(item);
25431
+ }
25432
+ function integerText(value) {
25433
+ const raw = text(value, 64);
25434
+ if (!/^\d+$/.test(raw))
25435
+ return void 0;
25436
+ const number4 = Number(raw);
25437
+ return Number.isSafeInteger(number4) ? number4 : void 0;
25438
+ }
25439
+ function sizeFromKiB(value) {
25440
+ const kib = integerText(value);
25441
+ if (kib === void 0)
25442
+ return void 0;
25443
+ const bytes3 = kib * 1024;
25444
+ return Number.isSafeInteger(bytes3) ? bytes3 : void 0;
25445
+ }
25446
+ function sizeFromKb(value) {
25447
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0)
25448
+ return void 0;
25449
+ const bytes3 = value * 1024;
25450
+ return Number.isSafeInteger(bytes3) && bytes3 > 0 ? bytes3 : void 0;
25451
+ }
25452
+ function isApplicationPath(path) {
25453
+ return path.startsWith("/Applications/") || /^\/Users\/[^/]+\/Applications\//.test(path);
25454
+ }
25455
+ function installDate(value) {
25433
25456
  if (typeof value !== "string")
25434
25457
  return void 0;
25458
+ const raw = value.trim();
25459
+ if (!/^\d{8}$/.test(raw))
25460
+ return void 0;
25461
+ const year = Number(raw.slice(0, 4));
25462
+ const month = Number(raw.slice(4, 6));
25463
+ const day = Number(raw.slice(6, 8));
25464
+ if (month < 1 || month > 12 || day < 1)
25465
+ return void 0;
25466
+ const leap = year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
25467
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
25468
+ const limit = days[month - 1];
25469
+ if (limit === void 0 || day > limit)
25470
+ return void 0;
25471
+ return `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6, 8)}`;
25472
+ }
25473
+ function parseJson(json2) {
25435
25474
  try {
25436
- return JSON.parse(value);
25475
+ return JSON.parse(json2);
25437
25476
  } catch {
25438
25477
  return void 0;
25439
25478
  }
25440
25479
  }
25441
- function sorted(result2) {
25442
- result2.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
25443
- return result2.slice(0, MAX_SERVICES);
25444
- }
25445
- function unitName(unit) {
25446
- return unit.endsWith(".service") ? unit.slice(0, -".service".length) : unit;
25447
- }
25448
- function systemdState(active, sub) {
25449
- if (active === "active")
25450
- return sub === "running" ? "running" : "stopped";
25451
- if (active === "failed")
25452
- return "failed";
25453
- if (active === "activating" || active === "reloading")
25454
- return "starting";
25455
- if (active === "deactivating")
25456
- return "stopping";
25457
- if (active === "inactive")
25458
- return "stopped";
25459
- return "unknown";
25460
- }
25461
- function unitFileEnablement(unitFiles) {
25462
- const enablement = /* @__PURE__ */ new Map();
25463
- for (const line of lines2(unitFiles)) {
25464
- const parts = line.trim().split(/\s+/);
25465
- const unit = parts[0];
25466
- const state2 = parts[1];
25467
- if (!unit || !state2)
25468
- continue;
25469
- if (state2 === "enabled" || state2 === "enabled-runtime")
25470
- enablement.set(unitName(unit), true);
25471
- else if (state2 === "disabled" || state2 === "masked")
25472
- enablement.set(unitName(unit), false);
25473
- else
25474
- enablement.set(unitName(unit), null);
25480
+ function parseDpkg(stdout) {
25481
+ const result2 = [];
25482
+ for (const line of lines(stdout)) {
25483
+ const parts = line.split(" ");
25484
+ if (parts.length < 5)
25485
+ continue;
25486
+ const status = text(parts[4], 16);
25487
+ if (!status.startsWith("ii") && !status.startsWith("hi"))
25488
+ continue;
25489
+ const name3 = nameOf(parts[0]);
25490
+ if (!name3)
25491
+ continue;
25492
+ const version6 = versionOf(parts[1]);
25493
+ const item = { name: name3, version: version6, manager: "dpkg" };
25494
+ const arch3 = text(parts[2], ARCH_MAX);
25495
+ if (arch3)
25496
+ item.arch = arch3;
25497
+ const size = sizeFromKiB(parts[3]);
25498
+ if (size !== void 0)
25499
+ item.size_bytes = size;
25500
+ const sourceName = nameOf(parts[5]);
25501
+ if (sourceName && sourceName !== name3)
25502
+ item.source_name = sourceName;
25503
+ const sourceVersion = versionOf(parts[6]);
25504
+ if (sourceVersion && sourceVersion !== version6)
25505
+ item.source_version = sourceVersion;
25506
+ push(result2, item);
25475
25507
  }
25476
- return enablement;
25508
+ return result2;
25477
25509
  }
25478
- function parseSystemd(units, unitFiles) {
25479
- const enablement = unitFileEnablement(unitFiles);
25510
+ function parseRpm(stdout) {
25480
25511
  const result2 = [];
25481
- for (const rawLine of lines2(units)) {
25482
- const line = rawLine.trim().replace(/^[●*]\s+/, "");
25483
- const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
25512
+ for (const line of lines(stdout)) {
25513
+ const parts = line.split(" ");
25514
+ if (parts.length < 6)
25515
+ continue;
25516
+ const name3 = nameOf(parts[0]);
25517
+ if (!name3 || name3 === "gpg-pubkey")
25518
+ continue;
25519
+ const version6 = versionOf(parts[2]);
25520
+ const release2 = versionOf(parts[3]);
25521
+ if (!version6 || !release2)
25522
+ continue;
25523
+ const epoch = text(parts[1], 32);
25524
+ const epochPrefix = /^\d+$/.test(epoch) ? `${epoch}:` : "";
25525
+ const item = { name: name3, version: versionOf(`${epochPrefix}${version6}-${release2}`), manager: "rpm" };
25526
+ const arch3 = text(parts[4], ARCH_MAX);
25527
+ if (arch3 && arch3 !== "(none)")
25528
+ item.arch = arch3;
25529
+ const size = integerText(parts[5]);
25530
+ if (size !== void 0)
25531
+ item.size_bytes = size;
25532
+ push(result2, item);
25533
+ }
25534
+ return result2;
25535
+ }
25536
+ function parseApk(stdout) {
25537
+ const result2 = [];
25538
+ for (const line of lines(stdout)) {
25539
+ const trimmed = line.trim();
25540
+ const match = /^(.+)-([0-9][^-\s]*-r\d+)\s/.exec(trimmed);
25484
25541
  if (!match)
25485
25542
  continue;
25486
- const unitToken = match[1];
25487
- const load = match[2];
25488
- const active = match[3];
25489
- const sub = match[4];
25490
- if (!unitToken || !load || !active || !sub)
25543
+ const name3 = nameOf(match[1]);
25544
+ if (!name3)
25491
25545
  continue;
25492
- if (load === "not-found")
25546
+ const item = { name: name3, version: versionOf(match[2]), manager: "apk" };
25547
+ const rest = trimmed.slice(match[0].length).trim().split(/\s+/);
25548
+ const arch3 = text(rest[0], ARCH_MAX);
25549
+ if (arch3)
25550
+ item.arch = arch3;
25551
+ push(result2, item);
25552
+ }
25553
+ return result2;
25554
+ }
25555
+ function parsePacman(stdout) {
25556
+ const result2 = [];
25557
+ for (const line of lines(stdout)) {
25558
+ const parts = line.trim().split(/\s+/);
25559
+ if (parts.length < 2)
25493
25560
  continue;
25494
- const name3 = text2(unitName(unitToken), NAME_MAX2);
25561
+ const name3 = nameOf(parts[0]);
25495
25562
  if (!name3)
25496
25563
  continue;
25497
- const item = {
25498
- name: name3,
25499
- manager: "systemd",
25500
- state: systemdState(active.toLowerCase(), sub.toLowerCase()),
25501
- enabled: enablement.get(name3) ?? null
25502
- };
25503
- const description = text2(match[5] ?? "", DESCRIPTION_MAX);
25504
- if (description)
25505
- item.description = description;
25506
- result2.push(item);
25564
+ push(result2, { name: name3, version: versionOf(parts[1]), manager: "pacman" });
25507
25565
  }
25508
- return sorted(result2);
25566
+ return result2;
25509
25567
  }
25510
- function parseLaunchctl(stdout) {
25568
+ function parseSnap(stdout) {
25511
25569
  const result2 = [];
25512
- for (const line of lines2(stdout)) {
25513
- const parts = line.split(" ");
25514
- if (parts.length < 3)
25570
+ for (const line of lines(stdout)) {
25571
+ const parts = line.trim().split(/\s+/);
25572
+ if (parts.length < 2)
25515
25573
  continue;
25516
- const pid = (parts[0] ?? "").trim();
25517
- const statusText = (parts[1] ?? "").trim();
25518
- const label = text2(parts[2], NAME_MAX2);
25519
- if (!label)
25574
+ if (parts[0] === "Name" && parts[1] === "Version")
25520
25575
  continue;
25521
- if (label.startsWith("com.apple.") || label.startsWith("application."))
25576
+ const name3 = nameOf(parts[0]);
25577
+ if (!name3)
25522
25578
  continue;
25523
- let state2;
25524
- if (pid === "-") {
25525
- if (!/^\d+$/.test(statusText))
25526
- continue;
25527
- state2 = Number(statusText) === 0 ? "stopped" : "failed";
25528
- } else if (/^\d+$/.test(pid)) {
25529
- state2 = "running";
25530
- } else {
25579
+ const item = { name: name3, version: versionOf(parts[1]), manager: "snap" };
25580
+ const publisher = text(parts[4], PUBLISHER_MAX).replace(/[✓*]+$/u, "").trim();
25581
+ if (publisher && publisher !== "-")
25582
+ item.publisher = publisher;
25583
+ push(result2, item);
25584
+ }
25585
+ return result2;
25586
+ }
25587
+ function parseBrewVersions(stdout, manager) {
25588
+ const result2 = [];
25589
+ for (const line of lines(stdout)) {
25590
+ const parts = line.trim().split(/\s+/);
25591
+ if (parts.length < 2)
25531
25592
  continue;
25532
- }
25533
- result2.push({ name: label, manager: "launchd", state: state2, enabled: null });
25593
+ const name3 = nameOf(parts[0]);
25594
+ if (!name3)
25595
+ continue;
25596
+ push(result2, { name: name3, version: versionOf(parts[1]), manager });
25534
25597
  }
25535
- return sorted(result2);
25598
+ return result2;
25536
25599
  }
25537
- function parseBrewServices(json2) {
25538
- const parsed = parseJson2(json2);
25539
- if (!Array.isArray(parsed))
25600
+ function parseNpmGlobal(json2) {
25601
+ const root = asRecord(parseJson(json2));
25602
+ const dependencies = asRecord(root?.dependencies);
25603
+ if (!dependencies)
25540
25604
  return [];
25541
25605
  const result2 = [];
25542
- for (const value of parsed) {
25543
- const info = asRecord2(value);
25544
- if (!info)
25606
+ for (const [rawName, value] of Object.entries(dependencies)) {
25607
+ const info = asRecord(value);
25608
+ if (!info || typeof info.version !== "string")
25545
25609
  continue;
25546
- const name3 = text2(info.name, NAME_MAX2);
25610
+ const name3 = nameOf(rawName);
25547
25611
  if (!name3)
25548
25612
  continue;
25549
- const status = typeof info.status === "string" ? info.status.trim().toLowerCase() : "";
25550
- let state2;
25551
- let enabled;
25552
- switch (status) {
25553
- case "started":
25554
- state2 = "running";
25555
- enabled = true;
25556
- break;
25557
- case "error":
25558
- state2 = "failed";
25559
- enabled = true;
25560
- break;
25561
- case "scheduled":
25562
- state2 = "starting";
25563
- enabled = true;
25564
- break;
25565
- case "none":
25566
- case "stopped":
25567
- state2 = "stopped";
25568
- enabled = false;
25569
- break;
25570
- default:
25571
- state2 = "unknown";
25572
- enabled = null;
25573
- }
25574
- result2.push({ name: name3, manager: "brew", state: state2, enabled });
25613
+ push(result2, { name: name3, version: versionOf(info.version), manager: "npm-global" });
25575
25614
  }
25576
- return sorted(result2);
25577
- }
25578
- var WINDOWS_STATES = {
25579
- "4": "running",
25580
- running: "running",
25581
- "1": "stopped",
25582
- stopped: "stopped",
25583
- "2": "starting",
25584
- startpending: "starting",
25585
- "3": "stopping",
25586
- stoppending: "stopping",
25587
- "7": "stopped",
25588
- paused: "stopped"
25589
- };
25590
- var WINDOWS_START_TYPES = {
25591
- "2": true,
25592
- automatic: true,
25593
- "3": false,
25594
- manual: false,
25595
- "4": false,
25596
- disabled: false
25597
- };
25598
- function windowsState(value) {
25599
- if (typeof value === "number")
25600
- return WINDOWS_STATES[String(value)] ?? "unknown";
25601
- if (typeof value === "string")
25602
- return WINDOWS_STATES[value.trim().toLowerCase()] ?? "unknown";
25603
- return "unknown";
25604
- }
25605
- function windowsEnabled(value) {
25606
- if (typeof value === "number")
25607
- return WINDOWS_START_TYPES[String(value)] ?? null;
25608
- if (typeof value === "string")
25609
- return WINDOWS_START_TYPES[value.trim().toLowerCase()] ?? null;
25610
- return null;
25615
+ return result2;
25611
25616
  }
25612
- function parseWindowsServices(json2) {
25613
- const parsed = parseJson2(json2);
25614
- if (parsed === void 0 || parsed === null)
25617
+ function parseMacApps(json2) {
25618
+ const root = asRecord(parseJson(json2));
25619
+ const items = root?.SPApplicationsDataType;
25620
+ if (!Array.isArray(items))
25615
25621
  return [];
25616
- const entries = Array.isArray(parsed) ? parsed : [parsed];
25617
25622
  const result2 = [];
25618
- for (const value of entries) {
25619
- const info = asRecord2(value);
25623
+ const seen = /* @__PURE__ */ new Set();
25624
+ for (const value of items) {
25625
+ const info = asRecord(value);
25620
25626
  if (!info)
25621
25627
  continue;
25622
- const name3 = text2(info.Name, NAME_MAX2);
25628
+ const name3 = nameOf(info._name);
25623
25629
  if (!name3)
25624
25630
  continue;
25625
- const item = {
25626
- name: name3,
25627
- manager: "windows",
25628
- state: windowsState(info.Status),
25629
- enabled: windowsEnabled(info.StartType)
25630
- };
25631
- const description = text2(info.DisplayName, DESCRIPTION_MAX);
25632
- if (description && description !== name3)
25633
- item.description = description;
25634
- result2.push(item);
25635
- }
25636
- return sorted(result2);
25637
- }
25638
-
25639
- // dist/inventory/parsers/containers.js
25640
- var NAME_MAX3 = 200;
25641
- var STATUS_MAX = 200;
25642
- var PORT_MAX = 80;
25643
- var TAG_MAX = 128;
25644
- var POD_STATUS_MAX = 40;
25645
- var MAX_CONTAINERS = INVENTORY_LIMITS.containers;
25646
- var MAX_IMAGES = INVENTORY_LIMITS.images;
25647
- var MAX_PODS = INVENTORY_LIMITS.pods;
25648
- var MAX_PORTS = INVENTORY_LIMITS.ports;
25649
- var CONTAINER_STATE_VALUES = /* @__PURE__ */ new Set([
25650
- "running",
25651
- "paused",
25652
- "restarting",
25653
- "exited",
25654
- "created",
25655
- "dead",
25656
- "removing"
25657
- ]);
25658
- var BYTE_MULTIPLIERS = {
25659
- b: 1,
25660
- kb: 1e3,
25661
- mb: 1e6,
25662
- gb: 1e9,
25663
- tb: 1e12,
25664
- kib: 1024,
25665
- mib: 1024 * 1024,
25666
- gib: 1024 * 1024 * 1024,
25667
- tib: 1024 * 1024 * 1024 * 1024
25668
- };
25669
- function text3(value, max) {
25670
- if (typeof value !== "string")
25671
- return "";
25672
- const trimmed = value.trim();
25673
- if (trimmed.length <= max)
25674
- return trimmed;
25675
- return trimmed.slice(0, max).trimEnd();
25676
- }
25677
- function nameOf2(value) {
25678
- return text3(value, NAME_MAX3);
25679
- }
25680
- function asRecord3(value) {
25681
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
25682
- }
25683
- function lines3(stdout) {
25684
- if (typeof stdout !== "string")
25685
- return [];
25686
- return stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
25687
- }
25688
- function parseJson3(value) {
25689
- if (typeof value !== "string")
25690
- return void 0;
25691
- try {
25692
- return JSON.parse(value);
25693
- } catch {
25694
- return void 0;
25695
- }
25696
- }
25697
- function push2(result2, item, max) {
25698
- if (result2.length < max)
25699
- result2.push(item);
25700
- }
25701
- function shortId(value) {
25702
- if (typeof value !== "string")
25703
- return void 0;
25704
- let raw = value.trim().toLowerCase();
25705
- if (raw.startsWith("sha256:"))
25706
- raw = raw.slice("sha256:".length);
25707
- if (raw.length < 12 || !/^[0-9a-f]+$/.test(raw))
25708
- return void 0;
25709
- return raw.slice(0, 12);
25710
- }
25711
- function containerState(value) {
25712
- if (typeof value !== "string")
25713
- return "unknown";
25714
- const state2 = value.trim().toLowerCase();
25715
- return CONTAINER_STATE_VALUES.has(state2) ? state2 : "unknown";
25716
- }
25717
- function nonNegativeInteger(value) {
25718
- if (typeof value !== "number" || !Number.isFinite(value))
25719
- return void 0;
25720
- const rounded = Math.round(value);
25721
- return rounded >= 0 && Number.isSafeInteger(rounded) ? rounded : void 0;
25722
- }
25723
- function isoFromUnix(value) {
25724
- if (typeof value !== "number" || !Number.isFinite(value))
25725
- return void 0;
25726
- const date5 = new Date(value * 1e3);
25727
- return Number.isNaN(date5.getTime()) ? void 0 : date5.toISOString();
25728
- }
25729
- function isoString(value) {
25730
- if (typeof value !== "string")
25731
- return void 0;
25732
- const raw = value.trim();
25733
- if (!raw)
25734
- return void 0;
25735
- return Number.isNaN(new Date(raw).getTime()) ? void 0 : raw;
25736
- }
25737
- function stringList(value) {
25738
- return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
25739
- }
25740
- function firstName(value) {
25741
- if (typeof value !== "string")
25742
- return "";
25743
- return nameOf2(value.split(",")[0] ?? "");
25744
- }
25745
- function dockerPorts(value) {
25746
- if (typeof value !== "string")
25747
- return [];
25748
- const ports = [];
25749
- for (const part of value.split(",")) {
25750
- const port = text3(part, PORT_MAX);
25751
- if (!port)
25631
+ const path = text(info.path, 4096);
25632
+ if (!isApplicationPath(path))
25752
25633
  continue;
25753
- ports.push(port);
25754
- if (ports.length >= MAX_PORTS)
25755
- break;
25634
+ const version6 = versionOf(info.version);
25635
+ const key = `${name3}\0${version6}`;
25636
+ if (seen.has(key))
25637
+ continue;
25638
+ seen.add(key);
25639
+ const item = { name: name3, version: version6, manager: "macos-app" };
25640
+ const source = text(info.obtained_from, 60);
25641
+ if (source === "apple")
25642
+ item.publisher = "Apple";
25643
+ else if (source === "mac_app_store")
25644
+ item.publisher = "App Store";
25645
+ push(result2, item);
25756
25646
  }
25757
- return ports;
25758
- }
25759
- function portText(value) {
25760
- if (typeof value === "number" && Number.isFinite(value))
25761
- return String(value);
25762
- return text3(value, 16);
25647
+ return result2;
25763
25648
  }
25764
- function podmanPorts(value) {
25765
- if (!Array.isArray(value))
25766
- return [];
25767
- const ports = [];
25768
- for (const entry of value) {
25769
- const port = asRecord3(entry);
25770
- if (!port)
25649
+ function parseWindowsPrograms(json2) {
25650
+ const parsed = parseJson(json2);
25651
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
25652
+ const result2 = [];
25653
+ const seen = /* @__PURE__ */ new Set();
25654
+ for (const value of entries) {
25655
+ const info = asRecord(value);
25656
+ if (!info)
25771
25657
  continue;
25772
- const hostIp = text3(port.host_ip, 64) || "0.0.0.0";
25773
- const hostPort = portText(port.host_port);
25774
- const containerPort = portText(port.container_port);
25775
- if (!hostPort || !containerPort)
25658
+ const name3 = nameOf(info.DisplayName);
25659
+ if (!name3)
25776
25660
  continue;
25777
- const protocol = text3(port.protocol, 8) || "tcp";
25778
- const rendered = text3(`${hostIp}:${hostPort}->${containerPort}/${protocol}`, PORT_MAX);
25779
- if (!rendered)
25661
+ const version6 = versionOf(info.DisplayVersion);
25662
+ const key = `${name3}\0${version6}`;
25663
+ if (seen.has(key))
25780
25664
  continue;
25781
- ports.push(rendered);
25782
- if (ports.length >= MAX_PORTS)
25665
+ seen.add(key);
25666
+ const item = { name: name3, version: version6, manager: "windows" };
25667
+ const publisher = text(info.Publisher, PUBLISHER_MAX);
25668
+ if (publisher)
25669
+ item.publisher = publisher;
25670
+ const size = sizeFromKb(info.EstimatedSize);
25671
+ if (size !== void 0)
25672
+ item.size_bytes = size;
25673
+ const installedOn = installDate(info.InstallDate);
25674
+ if (installedOn)
25675
+ item.installed_on = installedOn;
25676
+ push(result2, item);
25677
+ }
25678
+ return result2;
25679
+ }
25680
+
25681
+ // dist/inventory/parsers/sections.js
25682
+ var SECTION_MARKER = "@@conbridge-section";
25683
+ var MARKER_PATTERN = /^@@conbridge-section ([a-z0-9-]{1,32})$/;
25684
+ function splitSections(output2) {
25685
+ const sections = /* @__PURE__ */ new Map();
25686
+ if (typeof output2 !== "string")
25687
+ return { sections, complete: false };
25688
+ const lines4 = output2.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
25689
+ let current;
25690
+ let buffer = [];
25691
+ let complete = false;
25692
+ const flush = () => {
25693
+ if (current === void 0)
25694
+ return;
25695
+ let end = buffer.length;
25696
+ while (end > 0 && buffer[end - 1] === "")
25697
+ end -= 1;
25698
+ const content2 = buffer.slice(0, end).join("\n");
25699
+ if (!sections.has(current))
25700
+ sections.set(current, content2);
25701
+ current = void 0;
25702
+ buffer = [];
25703
+ };
25704
+ for (const line of lines4) {
25705
+ const match = MARKER_PATTERN.exec(line);
25706
+ if (!match) {
25707
+ if (current !== void 0)
25708
+ buffer.push(line);
25709
+ continue;
25710
+ }
25711
+ flush();
25712
+ const name3 = match[1] ?? "";
25713
+ if (name3 === "end") {
25714
+ complete = true;
25783
25715
  break;
25716
+ }
25717
+ current = name3;
25784
25718
  }
25785
- return ports;
25719
+ if (!complete)
25720
+ flush();
25721
+ return { sections, complete };
25786
25722
  }
25787
- function dockerSize(value) {
25788
- if (typeof value !== "string")
25789
- return {};
25790
- const raw = value.trim();
25791
- if (!raw)
25792
- return {};
25793
- const virtual = /\(virtual\s+([^)]+)\)/i.exec(raw);
25794
- const rwText = raw.replace(/\(virtual[^)]*\)/i, "").trim();
25795
- const result2 = {};
25796
- const rw = parseHumanBytes(rwText);
25797
- if (rw !== null)
25798
- result2.rw = rw;
25799
- if (virtual) {
25800
- const root = parseHumanBytes(virtual[1] ?? "");
25801
- if (root !== null)
25802
- result2.root = root;
25723
+
25724
+ // dist/inventory/parsers/system.js
25725
+ var RELEASE_KEYS = {
25726
+ ID: "id",
25727
+ VERSION_ID: "versionId",
25728
+ VERSION_CODENAME: "codename",
25729
+ PRETTY_NAME: "prettyName",
25730
+ NAME: "name",
25731
+ VERSION: "version"
25732
+ };
25733
+ function unquote(raw) {
25734
+ const value = raw.trim();
25735
+ if (value.length >= 2 && value.startsWith('"')) {
25736
+ const end = value.lastIndexOf('"');
25737
+ if (end > 0)
25738
+ return value.slice(1, end).replace(/\\"/g, '"').trim();
25803
25739
  }
25804
- return result2;
25740
+ if (value.length >= 2 && value.startsWith("'")) {
25741
+ const end = value.lastIndexOf("'");
25742
+ if (end > 0)
25743
+ return value.slice(1, end).trim();
25744
+ }
25745
+ return value;
25805
25746
  }
25806
- function dockerComposeProject(value) {
25807
- if (typeof value !== "string")
25808
- return void 0;
25809
- for (const pair of value.split(",")) {
25810
- const separator = pair.indexOf("=");
25747
+ function parseOsRelease(text4) {
25748
+ const result2 = {};
25749
+ if (typeof text4 !== "string")
25750
+ return result2;
25751
+ for (const rawLine of text4.split(/\r?\n/)) {
25752
+ const line = rawLine.trim();
25753
+ if (!line || line.startsWith("#"))
25754
+ continue;
25755
+ const separator = line.indexOf("=");
25811
25756
  if (separator <= 0)
25812
25757
  continue;
25813
- const key = pair.slice(0, separator).trim();
25814
- if (key !== "com.docker.compose.project")
25758
+ const key = line.slice(0, separator).trim();
25759
+ const field = RELEASE_KEYS[key];
25760
+ if (!field)
25815
25761
  continue;
25816
- const project = nameOf2(pair.slice(separator + 1));
25817
- if (project)
25818
- return project;
25762
+ const value = unquote(line.slice(separator + 1));
25763
+ if (!value)
25764
+ continue;
25765
+ result2[field] = value;
25819
25766
  }
25820
- return void 0;
25767
+ return result2;
25821
25768
  }
25822
- function podmanComposeProject(value) {
25823
- const labels = asRecord3(value);
25824
- if (!labels)
25825
- return void 0;
25826
- for (const key of ["com.docker.compose.project", "io.podman.compose.project"]) {
25827
- const project = nameOf2(labels[key]);
25828
- if (project)
25829
- return project;
25769
+ function parseSwVers(text4) {
25770
+ const result2 = {};
25771
+ if (typeof text4 !== "string")
25772
+ return result2;
25773
+ for (const rawLine of text4.split(/\r?\n/)) {
25774
+ const line = rawLine.trim();
25775
+ if (!line)
25776
+ continue;
25777
+ const separator = line.indexOf(":");
25778
+ if (separator <= 0)
25779
+ continue;
25780
+ const key = line.slice(0, separator).trim();
25781
+ const value = line.slice(separator + 1).trim();
25782
+ if (!value)
25783
+ continue;
25784
+ if (key === "ProductName")
25785
+ result2.productName = value;
25786
+ else if (key === "ProductVersion")
25787
+ result2.productVersion = value;
25788
+ else if (key === "BuildVersion")
25789
+ result2.buildVersion = value;
25830
25790
  }
25831
- return void 0;
25791
+ return result2;
25832
25792
  }
25833
- function splitImageName(value) {
25834
- const name3 = value.trim();
25835
- if (!name3)
25836
- return { repository: "<none>", tag: "" };
25837
- const slash = name3.lastIndexOf("/");
25838
- const colon = name3.lastIndexOf(":");
25839
- if (colon > slash) {
25840
- return {
25841
- repository: nameOf2(name3.slice(0, colon)) || "<none>",
25842
- tag: text3(name3.slice(colon + 1), TAG_MAX)
25843
- };
25793
+ function asRecord2(value) {
25794
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
25795
+ }
25796
+ function stringField(value) {
25797
+ return typeof value === "string" ? value.trim() : "";
25798
+ }
25799
+ function windowsArch(value) {
25800
+ const arch3 = value.trim();
25801
+ switch (arch3.toLowerCase()) {
25802
+ case "64-bit":
25803
+ return "x64";
25804
+ case "arm 64-bit":
25805
+ case "arm64":
25806
+ return "arm64";
25807
+ case "32-bit":
25808
+ return "x86";
25809
+ default:
25810
+ return arch3;
25844
25811
  }
25845
- return { repository: nameOf2(name3) || "<none>", tag: "" };
25846
25812
  }
25847
- function parseHumanBytes(value) {
25848
- if (typeof value !== "string")
25813
+ function parseWindowsOs(json2) {
25814
+ if (typeof json2 !== "string")
25849
25815
  return null;
25850
- const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/i.exec(value.trim());
25851
- if (!match)
25816
+ let parsed;
25817
+ try {
25818
+ parsed = JSON.parse(json2);
25819
+ } catch {
25852
25820
  return null;
25853
- const amount = Number(match[1]);
25854
- const multiplier = BYTE_MULTIPLIERS[(match[2] ?? "").toLowerCase()];
25855
- if (multiplier === void 0 || !Number.isFinite(amount) || amount < 0)
25821
+ }
25822
+ const info = asRecord2(parsed);
25823
+ if (!info)
25856
25824
  return null;
25857
- const bytes3 = Math.round(amount * multiplier);
25858
- return Number.isSafeInteger(bytes3) ? bytes3 : null;
25825
+ const caption = stringField(info.Caption).replace(/^Microsoft\s+/i, "");
25826
+ const version6 = stringField(info.Version);
25827
+ if (!caption || !version6)
25828
+ return null;
25829
+ const buildNumber = stringField(info.BuildNumber);
25830
+ const ubr = info.UBR;
25831
+ const build = typeof ubr === "number" ? `${buildNumber}.${ubr}` : buildNumber;
25832
+ return { caption, version: version6, build, arch: windowsArch(stringField(info.OSArchitecture)) };
25859
25833
  }
25860
- function parseDockerTime(value) {
25861
- if (typeof value !== "string")
25834
+ var MODEL_PLACEHOLDERS = /* @__PURE__ */ new Set(["to be filled by o.e.m.", "system product name", "default string"]);
25835
+ function cleanModel(text4) {
25836
+ if (typeof text4 !== "string")
25862
25837
  return null;
25863
- const match = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) ([+-]\d{2})(\d{2})/.exec(value.trim());
25864
- if (!match)
25838
+ const cleaned = text4.replace(/\0/g, "").trim().slice(0, 200);
25839
+ if (!cleaned)
25865
25840
  return null;
25866
- return `${match[1]}T${match[2]}${match[3]}:${match[4]}`;
25841
+ if (MODEL_PLACEHOLDERS.has(cleaned.toLowerCase()))
25842
+ return null;
25843
+ return cleaned;
25867
25844
  }
25868
- function parseDockerPs(jsonLines) {
25869
- const result2 = [];
25870
- for (const line of lines3(jsonLines)) {
25871
- const info = asRecord3(parseJson3(line));
25872
- if (!info)
25873
- continue;
25874
- const id = shortId(info.ID);
25875
- if (!id)
25876
- continue;
25877
- const name3 = firstName(info.Names);
25878
- const image = nameOf2(info.Image);
25879
- if (!name3 || !image)
25880
- continue;
25881
- const item = {
25882
- id,
25883
- name: name3,
25884
- image,
25885
- engine: "docker",
25886
- state: containerState(info.State),
25887
- status: text3(info.Status, STATUS_MAX),
25888
- ports: dockerPorts(info.Ports)
25889
- };
25890
- const createdAt = parseDockerTime(typeof info.CreatedAt === "string" ? info.CreatedAt : "");
25891
- if (createdAt)
25892
- item.created_at = createdAt;
25893
- const size = dockerSize(info.Size);
25894
- if (size.rw !== void 0)
25895
- item.size_rw_bytes = size.rw;
25896
- if (size.root !== void 0)
25897
- item.size_root_fs_bytes = size.root;
25898
- const composeProject = dockerComposeProject(info.Labels);
25899
- if (composeProject)
25900
- item.compose_project = composeProject;
25901
- push2(result2, item, MAX_CONTAINERS);
25845
+ function firstNonEmptyLine(output2) {
25846
+ for (const line of output2.split(/\r?\n/)) {
25847
+ const trimmed = line.trim();
25848
+ if (trimmed)
25849
+ return trimmed;
25902
25850
  }
25903
- return result2;
25851
+ return "";
25904
25852
  }
25905
- function parseDockerImages(jsonLines) {
25906
- const result2 = [];
25853
+ function group(match) {
25854
+ if (!match)
25855
+ return null;
25856
+ const value = match[1];
25857
+ if (typeof value !== "string")
25858
+ return null;
25859
+ const trimmed = value.trim();
25860
+ return trimmed ? trimmed : null;
25861
+ }
25862
+ function capture(pattern, value) {
25863
+ return group(pattern.exec(value));
25864
+ }
25865
+ var GENERIC_VERSION = /^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/;
25866
+ var VERSION_PARSERS = {
25867
+ node: (output2) => capture(/^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/, firstNonEmptyLine(output2)),
25868
+ python: (output2) => capture(/^Python\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
25869
+ php: (output2) => capture(/^PHP\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
25870
+ ruby: (output2) => capture(/^ruby\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
25871
+ go: (output2) => capture(/^go version go(\S+)/, firstNonEmptyLine(output2)),
25872
+ java: (output2) => capture(/^(?:openjdk|java)\s+version\s+"([^"]+)"/, firstNonEmptyLine(output2)),
25873
+ deno: (output2) => capture(/^deno\s+(\S+)/, firstNonEmptyLine(output2)),
25874
+ perl: (output2) => capture(/^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/, firstNonEmptyLine(output2)) ?? capture(/\(v(\d+\.\d+(?:\.\d+)?)\)/, output2),
25875
+ rust: (output2) => capture(/^rustc\s+(\S+)/, firstNonEmptyLine(output2)),
25876
+ nginx: (output2) => capture(/nginx\/(\S+)/, output2),
25877
+ apache: (output2) => capture(/Server version:\s*Apache\/(\S+)/, output2),
25878
+ caddy: (output2) => capture(/^v?(\d\S*)/, firstNonEmptyLine(output2)),
25879
+ haproxy: (output2) => capture(/^HAProxy version\s+(\S+)/, firstNonEmptyLine(output2)),
25880
+ traefik: (output2) => capture(/^Version:\s*(\S+)/m, output2),
25881
+ mysql: (output2) => /MariaDB/i.test(output2) ? null : capture(/\bVer\s+(\S+)/, output2),
25882
+ mariadb: (output2) => capture(/(\d+\.\d+(?:\.\d+)?)-MariaDB/, output2),
25883
+ postgresql: (output2) => capture(/PostgreSQL\)\s+(\S+)/, output2),
25884
+ redis: (output2) => capture(/\bv=(\S+)/, output2),
25885
+ mongodb: (output2) => capture(/db version v(\S+)/, output2),
25886
+ sqlite: (output2) => capture(/^(\d+\.\d+(?:\.\d+)?)/, firstNonEmptyLine(output2)),
25887
+ docker: (output2) => capture(/Docker version\s+([^,\s]+)/, output2),
25888
+ podman: (output2) => capture(/podman version\s+(\S+)/, output2),
25889
+ kubectl: (output2) => capture(/Client Version:\s*v?(\S+)/, output2),
25890
+ git: (output2) => capture(/git version\s+(\S+)/, output2),
25891
+ openssl: (output2) => capture(/^(?:OpenSSL|LibreSSL)\s+(\S+)/, firstNonEmptyLine(output2)),
25892
+ openssh: (output2) => capture(/^OpenSSH_([^,\s]+)/, firstNonEmptyLine(output2)),
25893
+ composer: (output2) => capture(/Composer version\s+(\S+)/, output2),
25894
+ curl: (output2) => capture(/^curl\s+(\S+)/, firstNonEmptyLine(output2)),
25895
+ powershell: (output2) => capture(/^PowerShell\s+(\S+)/, firstNonEmptyLine(output2)),
25896
+ bash: (output2) => capture(/version\s+(\d+\.\d+(?:\.\d+)?)/, firstNonEmptyLine(output2)),
25897
+ certbot: (output2) => capture(/^certbot\s+(\S+)/, firstNonEmptyLine(output2))
25898
+ };
25899
+ function extractVersion(key, output2) {
25900
+ if (typeof key !== "string" || typeof output2 !== "string")
25901
+ return null;
25902
+ const parser = VERSION_PARSERS[key];
25903
+ const version6 = parser ? parser(output2) : capture(GENERIC_VERSION, firstNonEmptyLine(output2));
25904
+ if (!version6)
25905
+ return null;
25906
+ return version6.slice(0, 128);
25907
+ }
25908
+
25909
+ // dist/inventory/ssh.js
25910
+ var SSH_INVENTORY_TIMEOUT_S = 120;
25911
+ var SSH_INVENTORY_MAX_BYTES = 8 * 1024 * 1024;
25912
+ var SCRIPT_BODY = [
25913
+ `M="${SECTION_MARKER}"`,
25914
+ "export LC_ALL=C",
25915
+ 'echo "$M os-release"',
25916
+ "{ cat /etc/os-release 2>/dev/null || cat /usr/lib/os-release 2>/dev/null; }",
25917
+ 'echo "$M uname"',
25918
+ "uname -srm 2>/dev/null",
25919
+ 'if command -v dpkg-query >/dev/null 2>&1; then echo "$M dpkg"; dpkg-query -W -f="\\${Package}\\t\\${Version}\\t\\${Architecture}\\t\\${Installed-Size}\\t\\${db:Status-Abbrev}\\t\\${source:Package}\\t\\${source:Version}\\n" 2>/dev/null; r=$?; echo "$M rc"; echo "$r"; elif command -v rpm >/dev/null 2>&1; then echo "$M rpm"; rpm -qa --qf "%{NAME}\\t%{EPOCH}\\t%{VERSION}\\t%{RELEASE}\\t%{ARCH}\\t%{SIZE}\\n" 2>/dev/null; r=$?; echo "$M rc"; echo "$r"; elif command -v apk >/dev/null 2>&1; then echo "$M apk"; apk list --installed 2>/dev/null; r=$?; echo "$M rc"; echo "$r"; fi',
25920
+ 'echo "$M end"'
25921
+ ].join("; ");
25922
+ var SSH_INVENTORY_SCRIPT = `/bin/sh -c '${SCRIPT_BODY}'`;
25923
+ var PACKAGE_SECTIONS = Object.freeze([
25924
+ ["dpkg", parseDpkg],
25925
+ ["rpm", parseRpm],
25926
+ ["apk", parseApk]
25927
+ ]);
25928
+ function selectInventoryHosts(ids, hosts) {
25929
+ const byId = new Map(hosts.map((host) => [host.resource_id, host]));
25907
25930
  const seen = /* @__PURE__ */ new Set();
25908
- for (const line of lines3(jsonLines)) {
25909
- const info = asRecord3(parseJson3(line));
25910
- if (!info)
25911
- continue;
25912
- const id = shortId(info.ID);
25913
- if (!id)
25914
- continue;
25915
- const repository = nameOf2(info.Repository) || "<none>";
25916
- const rawTag = text3(info.Tag, TAG_MAX);
25917
- const tag = rawTag === "<none>" ? "" : rawTag;
25918
- const key = `${id}\0${repository}\0${tag}`;
25919
- if (seen.has(key))
25931
+ const selected = [];
25932
+ for (const id of ids) {
25933
+ const host = byId.get(id);
25934
+ if (!host || seen.has(id))
25920
25935
  continue;
25921
- seen.add(key);
25922
- const item = { id, repository, tag, engine: "docker" };
25923
- const createdAt = parseDockerTime(typeof info.CreatedAt === "string" ? info.CreatedAt : "");
25924
- if (createdAt)
25925
- item.created_at = createdAt;
25926
- const size = parseHumanBytes(typeof info.Size === "string" ? info.Size : "");
25927
- if (size !== null)
25928
- item.size_bytes = size;
25929
- push2(result2, item, MAX_IMAGES);
25936
+ seen.add(id);
25937
+ selected.push(host);
25938
+ }
25939
+ return selected;
25940
+ }
25941
+ function familyOf(kernelName) {
25942
+ const name3 = kernelName.toLowerCase();
25943
+ if (name3 === "linux")
25944
+ return "linux";
25945
+ if (name3 === "darwin")
25946
+ return "darwin";
25947
+ return "other";
25948
+ }
25949
+ function osFrom(osRelease2, uname) {
25950
+ const release2 = parseOsRelease(osRelease2);
25951
+ const [kernelName = "", kernel = "", ...rest] = uname.trim().split(/\s+/);
25952
+ const arch3 = rest.at(-1) ?? "";
25953
+ const os = {
25954
+ family: familyOf(kernelName),
25955
+ name: release2.prettyName ?? release2.name ?? (kernelName || "Unknown"),
25956
+ version: release2.versionId ?? release2.version ?? "",
25957
+ arch: arch3.slice(0, 32),
25958
+ ...kernel ? { kernel } : {},
25959
+ ...release2.id ? { distro_id: release2.id } : {},
25960
+ ...release2.versionId ? { distro_version: release2.versionId } : {},
25961
+ ...release2.codename ? { distro_codename: release2.codename } : {}
25962
+ };
25963
+ return inventoryOsSchema.safeParse(os).success ? os : { family: familyOf(kernelName), name: kernelName || "Unknown", version: "", arch: "" };
25964
+ }
25965
+ function buildSshSnapshot(output2, now = /* @__PURE__ */ new Date(), durationMs = 0) {
25966
+ const { sections, complete } = splitSections(output2);
25967
+ if (!complete)
25968
+ return null;
25969
+ const coverage = [];
25970
+ const duration3 = Math.max(0, Math.round(durationMs));
25971
+ const os = osFrom(sections.get("os-release") ?? "", sections.get("uname") ?? "");
25972
+ coverage.push({ collector: "os", status: sections.has("os-release") || sections.has("uname") ? "ok" : "failed", count: 0, duration_ms: duration3 });
25973
+ let packages = [];
25974
+ const found = PACKAGE_SECTIONS.find(([name3]) => sections.has(name3));
25975
+ if (found) {
25976
+ const [name3, parse3] = found;
25977
+ if ((sections.get("rc") ?? "").trim() === "0") {
25978
+ packages = parse3(sections.get(name3) ?? "").filter((item) => inventoryPackageSchema.safeParse(item).success);
25979
+ coverage.push({ collector: name3, status: packages.length >= INVENTORY_LIMITS.packages ? "truncated" : "ok", count: packages.length, duration_ms: duration3 });
25980
+ } else {
25981
+ coverage.push({ collector: name3, status: "failed", count: 0, duration_ms: duration3 });
25982
+ }
25983
+ } else {
25984
+ coverage.push({ collector: "packages", status: "unavailable", count: 0, duration_ms: duration3 });
25930
25985
  }
25931
- return result2;
25986
+ return inventorySnapshotSchema.parse({
25987
+ schema: 1,
25988
+ collected_at: now.toISOString(),
25989
+ agent_version: AGENT_VERSION,
25990
+ os,
25991
+ packages: packages.slice(0, INVENTORY_LIMITS.packages),
25992
+ software: [],
25993
+ services: [],
25994
+ containers: [],
25995
+ images: [],
25996
+ pods: [],
25997
+ coverage: coverage.filter((entry) => inventoryCoverageSchema.safeParse(entry).success)
25998
+ });
25932
25999
  }
25933
- function parsePodmanPs(json2) {
25934
- const parsed = parseJson3(json2);
25935
- if (!Array.isArray(parsed))
25936
- return [];
25937
- const result2 = [];
25938
- for (const value of parsed) {
25939
- const info = asRecord3(value);
25940
- if (!info)
25941
- continue;
25942
- const id = shortId(info.Id);
25943
- if (!id)
25944
- continue;
25945
- const name3 = firstName(stringList(info.Names).join(","));
25946
- const image = nameOf2(info.Image);
25947
- if (!name3 || !image)
25948
- continue;
25949
- const item = {
25950
- id,
25951
- name: name3,
25952
- image,
25953
- engine: "podman",
25954
- state: containerState(info.State),
25955
- status: text3(info.Status, STATUS_MAX),
25956
- ports: podmanPorts(info.Ports)
25957
- };
25958
- const createdAt = isoFromUnix(info.Created) ?? isoString(info.CreatedAt);
25959
- if (createdAt)
25960
- item.created_at = createdAt;
25961
- const size = asRecord3(info.Size);
25962
- const rw = nonNegativeInteger(size?.rwSize);
25963
- if (rw !== void 0)
25964
- item.size_rw_bytes = rw;
25965
- const root = nonNegativeInteger(size?.rootFsSize);
25966
- if (root !== void 0)
25967
- item.size_root_fs_bytes = root;
25968
- const pod = nameOf2(info.PodName);
25969
- if (pod)
25970
- item.pod = pod;
25971
- const composeProject = podmanComposeProject(info.Labels);
25972
- if (composeProject)
25973
- item.compose_project = composeProject;
25974
- push2(result2, item, MAX_CONTAINERS);
25975
- }
25976
- return result2;
26000
+ function defaultSshInventoryExec(paths, binaries, env) {
26001
+ return (host) => runProcess(binaries.ssh, buildSshArgs(paths, host, SSH_INVENTORY_SCRIPT), {
26002
+ timeoutMs: SSH_INVENTORY_TIMEOUT_S * 1e3,
26003
+ maxBytes: SSH_INVENTORY_MAX_BYTES,
26004
+ env: sshChildEnv(env)
26005
+ });
25977
26006
  }
25978
- function parsePodmanImages(json2) {
25979
- const parsed = parseJson3(json2);
25980
- if (!Array.isArray(parsed))
25981
- return [];
25982
- const result2 = [];
25983
- for (const value of parsed) {
25984
- const info = asRecord3(value);
25985
- if (!info)
25986
- continue;
25987
- const id = shortId(info.Id);
25988
- if (!id)
25989
- continue;
25990
- const first = stringList(info.Names)[0] ?? "";
25991
- const { repository, tag } = splitImageName(first);
25992
- const item = { id, repository, tag, engine: "podman" };
25993
- const size = nonNegativeInteger(info.Size);
25994
- if (size !== void 0)
25995
- item.size_bytes = size;
25996
- const createdAt = isoFromUnix(info.Created);
25997
- if (createdAt)
25998
- item.created_at = createdAt;
25999
- const containers = nonNegativeInteger(info.Containers);
26000
- if (containers !== void 0)
26001
- item.containers = containers;
26002
- push2(result2, item, MAX_IMAGES);
26003
- }
26004
- return result2;
26007
+ async function collectSshHostInventory(host, exec, now = () => /* @__PURE__ */ new Date()) {
26008
+ const result2 = await exec(host);
26009
+ if (result2.spawnError)
26010
+ return { ok: false, reason: "ssh could not be started" };
26011
+ if (isHostKeyFailure(result2))
26012
+ return { ok: false, reason: "host key does not match the pin" };
26013
+ if (result2.timedOut)
26014
+ return { ok: false, reason: `timed out after ${SSH_INVENTORY_TIMEOUT_S} s` };
26015
+ if (result2.truncated)
26016
+ return { ok: false, reason: "output over 8 MB" };
26017
+ if (result2.exitCode === 255)
26018
+ return { ok: false, reason: "unreachable or authentication failed" };
26019
+ if (result2.exitCode !== 0)
26020
+ return { ok: false, reason: `script exited with ${result2.exitCode === null ? "a signal" : String(result2.exitCode)}` };
26021
+ const snapshot = buildSshSnapshot(result2.stdout, now(), result2.durationMs);
26022
+ if (!snapshot)
26023
+ return { ok: false, reason: "incomplete output" };
26024
+ return { ok: true, snapshot };
26005
26025
  }
26006
- function parsePodmanPods(json2) {
26007
- const parsed = parseJson3(json2);
26008
- if (!Array.isArray(parsed))
26009
- return [];
26010
- const result2 = [];
26011
- for (const value of parsed) {
26012
- const info = asRecord3(value);
26013
- if (!info)
26014
- continue;
26015
- const name3 = nameOf2(info.Name);
26016
- if (!name3)
26017
- continue;
26018
- const containerList = Array.isArray(info.Containers) ? info.Containers : void 0;
26019
- const containers = containerList ? containerList.length : nonNegativeInteger(info.NumberOfContainers) ?? 0;
26020
- const item = {
26021
- name: name3,
26022
- engine: "podman",
26023
- status: text3(info.Status, POD_STATUS_MAX) || "Unknown",
26024
- containers
26025
- };
26026
- if (containerList) {
26027
- let ready = 0;
26028
- for (const entry of containerList) {
26029
- const container = asRecord3(entry);
26030
- if (container && text3(container.Status, POD_STATUS_MAX).toLowerCase() === "running")
26031
- ready += 1;
26032
- }
26033
- item.ready = ready;
26034
- }
26035
- const createdAt = isoString(info.Created) ?? isoString(info.CreatedAt);
26036
- if (createdAt)
26037
- item.created_at = createdAt;
26038
- push2(result2, item, MAX_PODS);
26039
- }
26040
- return result2;
26026
+
26027
+ // dist/inventory/loop.js
26028
+ var SEND_SPACING_MS = 2e3;
26029
+ var HOST_MIN_INTERVAL_MS = 6e4;
26030
+ function encodeSnapshot(snapshot, requestId, runId = (0, import_node_crypto9.randomUUID)(), resourceId) {
26031
+ const gz = (0, import_node_zlib.gzipSync)(Buffer.from(JSON.stringify(snapshot), "utf8"), { level: 9 });
26032
+ if (gz.byteLength > INVENTORY_MAX_COMPRESSED_BYTES)
26033
+ return null;
26034
+ const sha2563 = (0, import_node_crypto9.createHash)("sha256").update(gz).digest("hex");
26035
+ const data = gz.toString("base64");
26036
+ const total = Math.max(1, Math.ceil(data.length / INVENTORY_PART_CHARS));
26037
+ return Array.from({ length: total }, (_, sequence) => ({
26038
+ run_id: runId,
26039
+ request_id: requestId,
26040
+ sequence,
26041
+ total,
26042
+ sha256: sha2563,
26043
+ data: data.slice(sequence * INVENTORY_PART_CHARS, (sequence + 1) * INVENTORY_PART_CHARS),
26044
+ ...resourceId !== void 0 ? { resource_id: resourceId } : {}
26045
+ }));
26041
26046
  }
26042
- function parseKubectlPods(stdout) {
26043
- const result2 = [];
26044
- for (const line of lines3(stdout)) {
26045
- const parts = line.trim().split(/\s+/);
26046
- if (parts.length < 7)
26047
- continue;
26048
- const namespace = nameOf2(parts[0]);
26049
- const name3 = nameOf2(parts[1]);
26050
- if (!name3)
26051
- continue;
26052
- const readyField = parts[5] ?? "";
26053
- const restartsField = parts[6] ?? "";
26054
- let containers = 0;
26055
- let ready;
26056
- if (readyField !== "<none>") {
26057
- const values = readyField.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
26058
- containers = values.length;
26059
- ready = values.filter((entry) => entry.toLowerCase() === "true").length;
26047
+ var InventoryLoop = class {
26048
+ #options;
26049
+ #logger;
26050
+ #intervalS = null;
26051
+ /** `ssh_hosts` of the latest config; missing means none. */
26052
+ #sshHostIds = [];
26053
+ /** When the last snapshot's parts finished sending (any snapshot, this connection). */
26054
+ #lastSendEndMs = null;
26055
+ /** When each SSH host's snapshot was last sent (this connection). */
26056
+ #hostSentAtMs = /* @__PURE__ */ new Map();
26057
+ #timer = null;
26058
+ #running = false;
26059
+ #stopped = false;
26060
+ constructor(options) {
26061
+ this.#options = options;
26062
+ this.#logger = options.logger ?? silentLogger;
26063
+ }
26064
+ get enabled() {
26065
+ return this.#intervalS !== null;
26066
+ }
26067
+ apply(config2) {
26068
+ if (this.#stopped)
26069
+ return;
26070
+ this.#sshHostIds = config2.enabled ? [...new Set(config2.ssh_hosts ?? [])] : [];
26071
+ if (!config2.enabled) {
26072
+ if (this.#intervalS !== null)
26073
+ this.#logger.info("software inventory stopped");
26074
+ this.#intervalS = null;
26075
+ this.#clear();
26076
+ return;
26060
26077
  }
26061
- let restarts;
26062
- if (restartsField !== "<none>") {
26063
- const values = restartsField.split(",").map((entry) => entry.trim()).filter((entry) => /^\d+$/.test(entry));
26064
- if (values.length > 0)
26065
- restarts = values.reduce((total, entry) => total + Number(entry), 0);
26078
+ if (this.#intervalS === config2.interval_s && this.#timer)
26079
+ return;
26080
+ const first = this.#intervalS === null;
26081
+ this.#intervalS = config2.interval_s;
26082
+ this.#clear();
26083
+ const jitter = (this.#options.firstRunMs ?? (() => 5e3 + Math.floor(Math.random() * 25e3)))();
26084
+ const last = this.#options.lastSentAtMs?.() ?? null;
26085
+ const now = (this.#options.now ?? Date.now)();
26086
+ const due = last === null ? jitter : Math.max(jitter, last + config2.interval_s * 1e3 - now);
26087
+ this.#schedule(first ? due : config2.interval_s * 1e3);
26088
+ this.#logger.info("software inventory scheduled", { interval_s: config2.interval_s });
26089
+ }
26090
+ /** Console Refresh: one run now (ignored while off or while a run is in progress). */
26091
+ request(requestId) {
26092
+ if (this.#stopped || this.#intervalS === null || this.#running)
26093
+ return;
26094
+ void this.#run(requestId);
26095
+ }
26096
+ /** SSH host ids of the latest config (deduplicated, not yet filtered by the pinned list). */
26097
+ get sshHostIds() {
26098
+ return this.#sshHostIds;
26099
+ }
26100
+ stop() {
26101
+ this.#stopped = true;
26102
+ this.#intervalS = null;
26103
+ this.#sshHostIds = [];
26104
+ this.#clear();
26105
+ }
26106
+ #clear() {
26107
+ if (this.#timer)
26108
+ clearTimeout(this.#timer);
26109
+ this.#timer = null;
26110
+ }
26111
+ #schedule(ms) {
26112
+ this.#timer = setTimeout(() => {
26113
+ this.#timer = null;
26114
+ void this.#run(null).finally(() => {
26115
+ if (!this.#stopped && this.#intervalS !== null && !this.#timer)
26116
+ this.#schedule(this.#intervalS * 1e3);
26117
+ });
26118
+ }, ms);
26119
+ this.#timer.unref?.();
26120
+ }
26121
+ async #run(requestId) {
26122
+ if (this.#running)
26123
+ return;
26124
+ if (!this.#options.allowed()) {
26125
+ this.#logger.info("software inventory is off on this computer (conbridge-agent config inventory on)");
26126
+ return;
26066
26127
  }
26067
- const item = {
26068
- name: name3,
26069
- engine: "kubernetes",
26070
- status: text3(parts[2], POD_STATUS_MAX) || "Unknown",
26071
- containers
26072
- };
26073
- if (namespace)
26074
- item.namespace = namespace;
26075
- if (ready !== void 0)
26076
- item.ready = ready;
26077
- if (restarts !== void 0)
26078
- item.restarts = restarts;
26079
- const node2 = nameOf2(parts[3]);
26080
- if (node2 && node2 !== "<none>")
26081
- item.node = node2;
26082
- const created = text3(parts[4], 64);
26083
- if (created && created !== "<none>") {
26084
- const createdAt = isoString(created);
26085
- if (createdAt)
26086
- item.created_at = createdAt;
26128
+ this.#running = true;
26129
+ try {
26130
+ await this.#runComputer(requestId);
26131
+ await this.#runSshHosts(requestId);
26132
+ } finally {
26133
+ this.#running = false;
26087
26134
  }
26088
- push2(result2, item, MAX_PODS);
26089
26135
  }
26090
- return result2;
26091
- }
26092
-
26093
- // dist/inventory/parsers/system.js
26094
- var RELEASE_KEYS = {
26095
- ID: "id",
26096
- VERSION_ID: "versionId",
26097
- VERSION_CODENAME: "codename",
26098
- PRETTY_NAME: "prettyName",
26099
- NAME: "name",
26100
- VERSION: "version"
26101
- };
26102
- function unquote(raw) {
26103
- const value = raw.trim();
26104
- if (value.length >= 2 && value.startsWith('"')) {
26105
- const end = value.lastIndexOf('"');
26106
- if (end > 0)
26107
- return value.slice(1, end).replace(/\\"/g, '"').trim();
26136
+ #now() {
26137
+ return (this.#options.now ?? Date.now)();
26108
26138
  }
26109
- if (value.length >= 2 && value.startsWith("'")) {
26110
- const end = value.lastIndexOf("'");
26111
- if (end > 0)
26112
- return value.slice(1, end).trim();
26139
+ /** Waits out the gap since the previous send; false when the loop stopped or was turned off meanwhile. */
26140
+ async #awaitSpacing() {
26141
+ const spacing = this.#options.sendSpacingMs ?? SEND_SPACING_MS;
26142
+ const wait = this.#lastSendEndMs === null ? 0 : this.#lastSendEndMs + spacing - this.#now();
26143
+ if (wait > 0)
26144
+ await new Promise((resolve8) => {
26145
+ setTimeout(resolve8, wait).unref?.();
26146
+ });
26147
+ return this.#active;
26113
26148
  }
26114
- return value;
26115
- }
26116
- function parseOsRelease(text4) {
26117
- const result2 = {};
26118
- if (typeof text4 !== "string")
26119
- return result2;
26120
- for (const rawLine of text4.split(/\r?\n/)) {
26121
- const line = rawLine.trim();
26122
- if (!line || line.startsWith("#"))
26123
- continue;
26124
- const separator = line.indexOf("=");
26125
- if (separator <= 0)
26126
- continue;
26127
- const key = line.slice(0, separator).trim();
26128
- const field = RELEASE_KEYS[key];
26129
- if (!field)
26130
- continue;
26131
- const value = unquote(line.slice(separator + 1));
26132
- if (!value)
26133
- continue;
26134
- result2[field] = value;
26149
+ #sendParts(parts) {
26150
+ try {
26151
+ this.#options.send(parts);
26152
+ } finally {
26153
+ this.#lastSendEndMs = this.#now();
26154
+ }
26135
26155
  }
26136
- return result2;
26137
- }
26138
- function parseSwVers(text4) {
26139
- const result2 = {};
26140
- if (typeof text4 !== "string")
26141
- return result2;
26142
- for (const rawLine of text4.split(/\r?\n/)) {
26143
- const line = rawLine.trim();
26144
- if (!line)
26145
- continue;
26146
- const separator = line.indexOf(":");
26147
- if (separator <= 0)
26148
- continue;
26149
- const key = line.slice(0, separator).trim();
26150
- const value = line.slice(separator + 1).trim();
26151
- if (!value)
26152
- continue;
26153
- if (key === "ProductName")
26154
- result2.productName = value;
26155
- else if (key === "ProductVersion")
26156
- result2.productVersion = value;
26157
- else if (key === "BuildVersion")
26158
- result2.buildVersion = value;
26156
+ get #active() {
26157
+ return !this.#stopped && this.#intervalS !== null;
26159
26158
  }
26160
- return result2;
26159
+ async #runComputer(requestId) {
26160
+ const started = Date.now();
26161
+ try {
26162
+ const snapshot = await this.#options.collect();
26163
+ if (!this.#active)
26164
+ return;
26165
+ const parts = encodeSnapshot(snapshot, requestId);
26166
+ if (!parts) {
26167
+ this.#logger.warn("software inventory too large to send");
26168
+ return;
26169
+ }
26170
+ if (!await this.#awaitSpacing())
26171
+ return;
26172
+ this.#sendParts(parts);
26173
+ this.#options.onSent?.(this.#now());
26174
+ this.#logger.info("software inventory sent", { packages: snapshot.packages.length, containers: snapshot.containers.length, parts: parts.length, ms: Date.now() - started });
26175
+ } catch (error63) {
26176
+ this.#logger.warn("software inventory failed", { error: error63 instanceof Error ? error63.name : "unknown" });
26177
+ }
26178
+ }
26179
+ /** Listed, pinned hosts one after another; the list and the pin are re-checked before each host. */
26180
+ async #runSshHosts(requestId) {
26181
+ const { sshHosts, collectSshHost } = this.#options;
26182
+ if (!sshHosts || !collectSshHost)
26183
+ return;
26184
+ const ids = this.#sshHostIds;
26185
+ for (const id of ids) {
26186
+ if (!this.#active || !this.#sshHostIds.includes(id))
26187
+ continue;
26188
+ const [host] = selectInventoryHosts([id], sshHosts());
26189
+ if (!host)
26190
+ continue;
26191
+ const last = this.#hostSentAtMs.get(id);
26192
+ if (last !== void 0 && this.#now() - last < (this.#options.hostMinIntervalMs ?? HOST_MIN_INTERVAL_MS)) {
26193
+ this.#logger.info("ssh host inventory skipped", { host: host.alias, reason: "sent less than a minute ago" });
26194
+ continue;
26195
+ }
26196
+ const started = Date.now();
26197
+ try {
26198
+ const outcome = await collectSshHost(host);
26199
+ if (!outcome.ok) {
26200
+ this.#logger.warn("ssh host inventory skipped", { host: host.alias, reason: outcome.reason });
26201
+ continue;
26202
+ }
26203
+ const parts = encodeSnapshot(outcome.snapshot, requestId, (0, import_node_crypto9.randomUUID)(), host.resource_id);
26204
+ if (!parts) {
26205
+ this.#logger.warn("ssh host inventory skipped", { host: host.alias, reason: "snapshot too large to send" });
26206
+ continue;
26207
+ }
26208
+ if (!await this.#awaitSpacing())
26209
+ return;
26210
+ if (!this.#sshHostIds.includes(id) || selectInventoryHosts([id], sshHosts()).length === 0)
26211
+ continue;
26212
+ this.#sendParts(parts);
26213
+ this.#hostSentAtMs.set(id, this.#now());
26214
+ this.#logger.info("ssh host inventory sent", { host: host.alias, packages: outcome.snapshot.packages.length, parts: parts.length, ms: Date.now() - started });
26215
+ } catch (error63) {
26216
+ this.#logger.warn("ssh host inventory skipped", { host: host.alias, reason: error63 instanceof Error ? error63.name : "unknown" });
26217
+ }
26218
+ }
26219
+ }
26220
+ };
26221
+
26222
+ // dist/inventory/collector.js
26223
+ var import_node_child_process7 = require("node:child_process");
26224
+ var import_promises12 = require("node:fs/promises");
26225
+ var import_node_os4 = require("node:os");
26226
+
26227
+ // dist/inventory/parsers/services.js
26228
+ var NAME_MAX2 = 200;
26229
+ var DESCRIPTION_MAX = 200;
26230
+ var MAX_SERVICES = INVENTORY_LIMITS.services;
26231
+ function text2(value, max) {
26232
+ if (typeof value !== "string")
26233
+ return "";
26234
+ const trimmed = value.trim();
26235
+ if (trimmed.length <= max)
26236
+ return trimmed;
26237
+ return trimmed.slice(0, max).trimEnd();
26161
26238
  }
26162
- function asRecord4(value) {
26239
+ function asRecord3(value) {
26163
26240
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
26164
26241
  }
26165
- function stringField(value) {
26166
- return typeof value === "string" ? value.trim() : "";
26167
- }
26168
- function windowsArch(value) {
26169
- const arch3 = value.trim();
26170
- switch (arch3.toLowerCase()) {
26171
- case "64-bit":
26172
- return "x64";
26173
- case "arm 64-bit":
26174
- case "arm64":
26175
- return "arm64";
26176
- case "32-bit":
26177
- return "x86";
26178
- default:
26179
- return arch3;
26180
- }
26242
+ function lines2(stdout) {
26243
+ if (typeof stdout !== "string")
26244
+ return [];
26245
+ return stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
26181
26246
  }
26182
- function parseWindowsOs(json2) {
26183
- if (typeof json2 !== "string")
26184
- return null;
26185
- let parsed;
26247
+ function parseJson2(value) {
26248
+ if (typeof value !== "string")
26249
+ return void 0;
26186
26250
  try {
26187
- parsed = JSON.parse(json2);
26251
+ return JSON.parse(value);
26188
26252
  } catch {
26189
- return null;
26253
+ return void 0;
26190
26254
  }
26191
- const info = asRecord4(parsed);
26192
- if (!info)
26193
- return null;
26194
- const caption = stringField(info.Caption).replace(/^Microsoft\s+/i, "");
26195
- const version6 = stringField(info.Version);
26196
- if (!caption || !version6)
26197
- return null;
26198
- const buildNumber = stringField(info.BuildNumber);
26199
- const ubr = info.UBR;
26200
- const build = typeof ubr === "number" ? `${buildNumber}.${ubr}` : buildNumber;
26201
- return { caption, version: version6, build, arch: windowsArch(stringField(info.OSArchitecture)) };
26202
26255
  }
26203
- var MODEL_PLACEHOLDERS = /* @__PURE__ */ new Set(["to be filled by o.e.m.", "system product name", "default string"]);
26204
- function cleanModel(text4) {
26205
- if (typeof text4 !== "string")
26206
- return null;
26207
- const cleaned = text4.replace(/\0/g, "").trim().slice(0, 200);
26208
- if (!cleaned)
26209
- return null;
26210
- if (MODEL_PLACEHOLDERS.has(cleaned.toLowerCase()))
26211
- return null;
26212
- return cleaned;
26256
+ function sorted(result2) {
26257
+ result2.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
26258
+ return result2.slice(0, MAX_SERVICES);
26213
26259
  }
26214
- function firstNonEmptyLine(output2) {
26215
- for (const line of output2.split(/\r?\n/)) {
26216
- const trimmed = line.trim();
26217
- if (trimmed)
26218
- return trimmed;
26219
- }
26220
- return "";
26260
+ function unitName(unit) {
26261
+ return unit.endsWith(".service") ? unit.slice(0, -".service".length) : unit;
26221
26262
  }
26222
- function group(match) {
26223
- if (!match)
26224
- return null;
26225
- const value = match[1];
26226
- if (typeof value !== "string")
26227
- return null;
26228
- const trimmed = value.trim();
26229
- return trimmed ? trimmed : null;
26263
+ function systemdState(active, sub) {
26264
+ if (active === "active")
26265
+ return sub === "running" ? "running" : "stopped";
26266
+ if (active === "failed")
26267
+ return "failed";
26268
+ if (active === "activating" || active === "reloading")
26269
+ return "starting";
26270
+ if (active === "deactivating")
26271
+ return "stopping";
26272
+ if (active === "inactive")
26273
+ return "stopped";
26274
+ return "unknown";
26230
26275
  }
26231
- function capture(pattern, value) {
26232
- return group(pattern.exec(value));
26276
+ function unitFileEnablement(unitFiles) {
26277
+ const enablement = /* @__PURE__ */ new Map();
26278
+ for (const line of lines2(unitFiles)) {
26279
+ const parts = line.trim().split(/\s+/);
26280
+ const unit = parts[0];
26281
+ const state2 = parts[1];
26282
+ if (!unit || !state2)
26283
+ continue;
26284
+ if (state2 === "enabled" || state2 === "enabled-runtime")
26285
+ enablement.set(unitName(unit), true);
26286
+ else if (state2 === "disabled" || state2 === "masked")
26287
+ enablement.set(unitName(unit), false);
26288
+ else
26289
+ enablement.set(unitName(unit), null);
26290
+ }
26291
+ return enablement;
26233
26292
  }
26234
- var GENERIC_VERSION = /^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/;
26235
- var VERSION_PARSERS = {
26236
- node: (output2) => capture(/^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/, firstNonEmptyLine(output2)),
26237
- python: (output2) => capture(/^Python\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
26238
- php: (output2) => capture(/^PHP\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
26239
- ruby: (output2) => capture(/^ruby\s+(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)/, firstNonEmptyLine(output2)),
26240
- go: (output2) => capture(/^go version go(\S+)/, firstNonEmptyLine(output2)),
26241
- java: (output2) => capture(/^(?:openjdk|java)\s+version\s+"([^"]+)"/, firstNonEmptyLine(output2)),
26242
- deno: (output2) => capture(/^deno\s+(\S+)/, firstNonEmptyLine(output2)),
26243
- perl: (output2) => capture(/^v?(\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?)\s*$/, firstNonEmptyLine(output2)) ?? capture(/\(v(\d+\.\d+(?:\.\d+)?)\)/, output2),
26244
- rust: (output2) => capture(/^rustc\s+(\S+)/, firstNonEmptyLine(output2)),
26245
- nginx: (output2) => capture(/nginx\/(\S+)/, output2),
26246
- apache: (output2) => capture(/Server version:\s*Apache\/(\S+)/, output2),
26247
- caddy: (output2) => capture(/^v?(\d\S*)/, firstNonEmptyLine(output2)),
26248
- haproxy: (output2) => capture(/^HAProxy version\s+(\S+)/, firstNonEmptyLine(output2)),
26249
- traefik: (output2) => capture(/^Version:\s*(\S+)/m, output2),
26250
- mysql: (output2) => /MariaDB/i.test(output2) ? null : capture(/\bVer\s+(\S+)/, output2),
26251
- mariadb: (output2) => capture(/(\d+\.\d+(?:\.\d+)?)-MariaDB/, output2),
26252
- postgresql: (output2) => capture(/PostgreSQL\)\s+(\S+)/, output2),
26253
- redis: (output2) => capture(/\bv=(\S+)/, output2),
26254
- mongodb: (output2) => capture(/db version v(\S+)/, output2),
26255
- sqlite: (output2) => capture(/^(\d+\.\d+(?:\.\d+)?)/, firstNonEmptyLine(output2)),
26256
- docker: (output2) => capture(/Docker version\s+([^,\s]+)/, output2),
26257
- podman: (output2) => capture(/podman version\s+(\S+)/, output2),
26258
- kubectl: (output2) => capture(/Client Version:\s*v?(\S+)/, output2),
26259
- git: (output2) => capture(/git version\s+(\S+)/, output2),
26260
- openssl: (output2) => capture(/^(?:OpenSSL|LibreSSL)\s+(\S+)/, firstNonEmptyLine(output2)),
26261
- openssh: (output2) => capture(/^OpenSSH_([^,\s]+)/, firstNonEmptyLine(output2)),
26262
- composer: (output2) => capture(/Composer version\s+(\S+)/, output2),
26263
- curl: (output2) => capture(/^curl\s+(\S+)/, firstNonEmptyLine(output2)),
26264
- powershell: (output2) => capture(/^PowerShell\s+(\S+)/, firstNonEmptyLine(output2)),
26265
- bash: (output2) => capture(/version\s+(\d+\.\d+(?:\.\d+)?)/, firstNonEmptyLine(output2)),
26266
- certbot: (output2) => capture(/^certbot\s+(\S+)/, firstNonEmptyLine(output2))
26267
- };
26268
- function extractVersion(key, output2) {
26269
- if (typeof key !== "string" || typeof output2 !== "string")
26270
- return null;
26271
- const parser = VERSION_PARSERS[key];
26272
- const version6 = parser ? parser(output2) : capture(GENERIC_VERSION, firstNonEmptyLine(output2));
26273
- if (!version6)
26274
- return null;
26275
- return version6.slice(0, 128);
26293
+ function parseSystemd(units, unitFiles) {
26294
+ const enablement = unitFileEnablement(unitFiles);
26295
+ const result2 = [];
26296
+ for (const rawLine of lines2(units)) {
26297
+ const line = rawLine.trim().replace(/^[●*]\s+/, "");
26298
+ const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
26299
+ if (!match)
26300
+ continue;
26301
+ const unitToken = match[1];
26302
+ const load = match[2];
26303
+ const active = match[3];
26304
+ const sub = match[4];
26305
+ if (!unitToken || !load || !active || !sub)
26306
+ continue;
26307
+ if (load === "not-found")
26308
+ continue;
26309
+ const name3 = text2(unitName(unitToken), NAME_MAX2);
26310
+ if (!name3)
26311
+ continue;
26312
+ const item = {
26313
+ name: name3,
26314
+ manager: "systemd",
26315
+ state: systemdState(active.toLowerCase(), sub.toLowerCase()),
26316
+ enabled: enablement.get(name3) ?? null
26317
+ };
26318
+ const description = text2(match[5] ?? "", DESCRIPTION_MAX);
26319
+ if (description)
26320
+ item.description = description;
26321
+ result2.push(item);
26322
+ }
26323
+ return sorted(result2);
26276
26324
  }
26277
-
26278
- // dist/inventory/collector.js
26279
- var POSIX_PATH = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/opt/homebrew/bin", "/opt/homebrew/sbin", "/snap/bin"];
26280
- var DENIED = /permission denied|EACCES|access is denied|got permission denied while trying to connect/i;
26281
- function collectorEnv(env = process.env, platform2 = process.platform) {
26282
- const base2 = { ...env, NO_COLOR: "1", PAGER: "cat", SYSTEMD_PAGER: "", TERM: "dumb", COMPOSER_ALLOW_SUPERUSER: "1", HOMEBREW_NO_AUTO_UPDATE: "1" };
26283
- if (platform2 === "win32")
26284
- return base2;
26285
- const path = [.../* @__PURE__ */ new Set([...(env.PATH ?? "").split(":").filter(Boolean), ...POSIX_PATH])].join(":");
26286
- return { ...base2, PATH: path };
26287
- }
26288
- var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resolve8) => {
26289
- (0, import_node_child_process6.execFile)(file2, [...args], {
26290
- timeout: timeoutMs,
26291
- maxBuffer: maxBytes,
26292
- killSignal: "SIGKILL",
26293
- windowsHide: true,
26294
- encoding: "utf8",
26295
- env: collectorEnv()
26296
- }, (error63, stdout, stderr) => {
26297
- const code = error63?.code;
26298
- const killed = error63?.killed === true;
26299
- const out = String(stdout ?? ""), err = String(stderr ?? "");
26300
- resolve8({
26301
- stdout: out,
26302
- stderr: err,
26303
- ok: !error63,
26304
- missing: code === "ENOENT",
26305
- timedOut: killed && !code,
26306
- denied: DENIED.test(err) || code === "EACCES"
26307
- });
26308
- });
26309
- });
26310
- var defaultReader = async (path) => (0, import_promises11.readFile)(path, "utf8").catch(() => null);
26311
- var defaultCollectorSystem = {
26312
- platform: (0, import_node_os4.platform)(),
26313
- arch: (0, import_node_os4.arch)(),
26314
- kernel: (0, import_node_os4.release)(),
26315
- run: defaultRunner,
26316
- readText: defaultReader,
26317
- now: () => /* @__PURE__ */ new Date()
26318
- };
26319
- var SHORT = { timeoutMs: 1e4, maxBytes: 2 * 1024 * 1024 };
26320
- var LIST = { timeoutMs: 45e3, maxBytes: 48 * 1024 * 1024 };
26321
- var POWERSHELL = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
26322
- var PS_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $ProgressPreference = 'SilentlyContinue'; ";
26323
- var PS_OS = PS_PREFIX + "$o = Get-CimInstance Win32_OperatingSystem; $ubr = (Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' -ErrorAction SilentlyContinue).UBR; [pscustomobject]@{Caption=$o.Caption;Version=$o.Version;BuildNumber=$o.BuildNumber;OSArchitecture=$o.OSArchitecture;UBR=$ubr} | ConvertTo-Json -Compress";
26324
- var PS_PROGRAMS = PS_PREFIX + "$p = 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'; Get-ItemProperty -Path $p -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -and -not $_.SystemComponent } | Select-Object DisplayName,DisplayVersion,Publisher,EstimatedSize,InstallDate | ConvertTo-Json -Compress";
26325
- var PS_SERVICES = PS_PREFIX + "Get-Service | Select-Object Name,DisplayName,Status,StartType | ConvertTo-Json -Compress";
26326
- var SOFTWARE_PROBES = Object.freeze([
26327
- { key: "node", name: "Node.js", kind: "runtime", commands: [["node", "--version"], ["nodejs", "--version"]] },
26328
- { key: "python", name: "Python", kind: "runtime", commands: [["python3", "--version"], ["python", "--version"]] },
26329
- { key: "php", name: "PHP", kind: "runtime", commands: [["php", "--version"]] },
26330
- { key: "ruby", name: "Ruby", kind: "runtime", commands: [["ruby", "--version"]] },
26331
- { key: "go", name: "Go", kind: "runtime", commands: [["go", "version"]] },
26332
- { key: "java", name: "Java", kind: "runtime", commands: [["java", "-version"]] },
26333
- { key: "dotnet", name: ".NET", kind: "runtime", commands: [["dotnet", "--version"]] },
26334
- { key: "deno", name: "Deno", kind: "runtime", commands: [["deno", "--version"]] },
26335
- { key: "bun", name: "Bun", kind: "runtime", commands: [["bun", "--version"]] },
26336
- { key: "rust", name: "Rust", kind: "runtime", commands: [["rustc", "--version"]] },
26337
- { key: "nginx", name: "nginx", kind: "web_server", commands: [["nginx", "-v"]], posixOnly: true },
26338
- { key: "apache", name: "Apache HTTP Server", kind: "web_server", commands: [["apache2ctl", "-v"], ["httpd", "-v"]], posixOnly: true },
26339
- { key: "caddy", name: "Caddy", kind: "web_server", commands: [["caddy", "version"]] },
26340
- { key: "haproxy", name: "HAProxy", kind: "web_server", commands: [["haproxy", "-v"]], posixOnly: true },
26341
- { key: "traefik", name: "Traefik", kind: "web_server", commands: [["traefik", "version"]] },
26342
- { key: "mysql", name: "MySQL", kind: "database", commands: [["mysql", "--version"]] },
26343
- { key: "mariadb", name: "MariaDB", kind: "database", commands: [["mariadb", "--version"]] },
26344
- { key: "postgresql", name: "PostgreSQL", kind: "database", commands: [["psql", "--version"]] },
26345
- { key: "redis", name: "Redis", kind: "database", commands: [["redis-server", "--version"]] },
26346
- { key: "mongodb", name: "MongoDB", kind: "database", commands: [["mongod", "--version"]] },
26347
- { key: "sqlite", name: "SQLite", kind: "database", commands: [["sqlite3", "--version"]] },
26348
- { key: "docker", name: "Docker", kind: "container_engine", commands: [["docker", "--version"]] },
26349
- { key: "podman", name: "Podman", kind: "container_engine", commands: [["podman", "--version"]] },
26350
- { key: "kubectl", name: "kubectl", kind: "container_engine", commands: [["kubectl", "version", "--client"]] },
26351
- { key: "git", name: "Git", kind: "tool", commands: [["git", "--version"]] },
26352
- { key: "openssl", name: "OpenSSL", kind: "tool", commands: [["openssl", "version"]] },
26353
- { key: "openssh", name: "OpenSSH", kind: "tool", commands: [["ssh", "-V"]] },
26354
- { key: "curl", name: "curl", kind: "tool", commands: [["curl", "--version"]] },
26355
- { key: "bash", name: "Bash", kind: "tool", commands: [["bash", "--version"]], posixOnly: true },
26356
- { key: "powershell", name: "PowerShell", kind: "tool", commands: [["pwsh", "--version"]] },
26357
- { key: "composer", name: "Composer", kind: "tool", commands: [["composer", "--version", "--no-ansi"]], posixOnly: true },
26358
- { key: "npm", name: "npm", kind: "tool", commands: [["npm", "--version"]], posixOnly: true },
26359
- { key: "pnpm", name: "pnpm", kind: "tool", commands: [["pnpm", "--version"]], posixOnly: true },
26360
- { key: "yarn", name: "Yarn", kind: "tool", commands: [["yarn", "--version"]], posixOnly: true },
26361
- { key: "certbot", name: "Certbot", kind: "tool", commands: [["certbot", "--version"]], posixOnly: true }
26362
- ]);
26363
- function valid(schema, items, limit) {
26364
- const out = [];
26365
- for (const item of items) {
26366
- if (out.length >= limit)
26367
- break;
26368
- const parsed = schema.safeParse(item);
26369
- if (parsed.success)
26370
- out.push(parsed.data);
26371
- }
26372
- return out;
26373
- }
26374
- async function pool(items, width, work) {
26375
- let next = 0;
26376
- await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {
26377
- while (next < items.length)
26378
- await work(items[next++]);
26379
- }));
26380
- }
26381
- var Collection = class {
26382
- system;
26383
- packages = [];
26384
- software = [];
26385
- services = [];
26386
- containers = [];
26387
- images = [];
26388
- pods = [];
26389
- coverage = [];
26390
- constructor(system) {
26391
- this.system = system;
26392
- }
26393
- /** Runs one collector command and records its coverage; returns the stdout only when the command succeeded. */
26394
- async command(collector, file2, args, limits = SHORT, merge2 = false) {
26395
- const started = Date.now();
26396
- const result2 = await this.system.run(file2, args, limits);
26397
- const status = result2.ok ? "ok" : result2.missing ? "unavailable" : result2.timedOut ? "timeout" : result2.denied ? "denied" : "failed";
26398
- this.cover(collector, status, 0, Date.now() - started);
26399
- if (!result2.ok)
26400
- return null;
26401
- return merge2 ? result2.stdout + "\n" + result2.stderr : result2.stdout;
26402
- }
26403
- cover(collector, status, count3, durationMs) {
26404
- const existing = this.coverage.find((entry) => entry.collector === collector);
26405
- if (existing)
26406
- Object.assign(existing, { status, count: count3, duration_ms: Math.max(0, Math.round(durationMs)) });
26407
- else
26408
- this.coverage.push({ collector, status, count: count3, duration_ms: Math.max(0, Math.round(durationMs)) });
26409
- }
26410
- counted(collector, count3, limit) {
26411
- const entry = this.coverage.find((e) => e.collector === collector);
26412
- if (entry && entry.status === "ok") {
26413
- entry.count = count3;
26414
- if (count3 >= limit)
26415
- entry.status = "truncated";
26416
- }
26417
- }
26418
- };
26419
- async function collectOs(c) {
26420
- const { platform: platform2, arch: arch3, kernel } = c.system;
26421
- if (platform2 === "linux") {
26422
- const release2 = parseOsRelease(await c.system.readText("/etc/os-release") ?? await c.system.readText("/usr/lib/os-release") ?? "");
26423
- const model = cleanModel(await c.system.readText("/proc/device-tree/model") ?? await c.system.readText("/sys/devices/virtual/dmi/id/product_name") ?? "");
26424
- return {
26425
- family: "linux",
26426
- name: release2.prettyName ?? release2.name ?? "Linux",
26427
- version: release2.versionId ?? release2.version ?? "",
26428
- kernel,
26429
- arch: arch3,
26430
- ...release2.id ? { distro_id: release2.id } : {},
26431
- ...release2.versionId ? { distro_version: release2.versionId } : {},
26432
- ...release2.codename ? { distro_codename: release2.codename } : {},
26433
- ...model ? { model } : {}
26434
- };
26435
- }
26436
- if (platform2 === "darwin") {
26437
- const vers = parseSwVers(await c.command("os", "sw_vers", []) ?? "");
26438
- return {
26439
- family: "darwin",
26440
- name: `${vers.productName ?? "macOS"} ${vers.productVersion ?? ""}`.trim(),
26441
- version: vers.productVersion ?? "",
26442
- ...vers.buildVersion ? { build: vers.buildVersion } : {},
26443
- kernel,
26444
- arch: arch3
26445
- };
26446
- }
26447
- if (platform2 === "win32") {
26448
- const win = parseWindowsOs(await c.command("os", "powershell.exe", [...POWERSHELL, PS_OS]) ?? "");
26449
- return win ? { family: "windows", name: win.caption, version: win.version, build: win.build, kernel, arch: win.arch } : { family: "windows", name: "Windows", version: kernel, kernel, arch: arch3 };
26450
- }
26451
- return { family: "other", name: platform2, version: kernel, kernel, arch: arch3 };
26452
- }
26453
- async function collectPackages(c) {
26454
- const { platform: platform2 } = c.system;
26455
- const add = (collector, items) => {
26456
- c.packages.push(...items);
26457
- c.counted(collector, items.length, INVENTORY_LIMITS.packages);
26458
- };
26459
- if (platform2 === "linux") {
26460
- const dpkg = await c.command("dpkg", "dpkg-query", ["-W", "-f=${Package}\\t${Version}\\t${Architecture}\\t${Installed-Size}\\t${db:Status-Abbrev}\\t${source:Package}\\t${source:Version}\\n"], LIST);
26461
- if (dpkg !== null)
26462
- add("dpkg", parseDpkg(dpkg));
26463
- else {
26464
- const rpm = await c.command("rpm", "rpm", ["-qa", "--qf", "%{NAME}\\t%{EPOCH}\\t%{VERSION}\\t%{RELEASE}\\t%{ARCH}\\t%{SIZE}\\n"], LIST);
26465
- if (rpm !== null)
26466
- add("rpm", parseRpm(rpm));
26467
- else {
26468
- const apk = await c.command("apk", "apk", ["list", "--installed"], LIST);
26469
- if (apk !== null)
26470
- add("apk", parseApk(apk));
26471
- else {
26472
- const pacman = await c.command("pacman", "pacman", ["-Q"], LIST);
26473
- if (pacman !== null)
26474
- add("pacman", parsePacman(pacman));
26475
- }
26476
- }
26477
- }
26478
- const snap = await c.command("snap", "snap", ["list"], SHORT);
26479
- if (snap !== null)
26480
- add("snap", parseSnap(snap));
26481
- } else if (platform2 === "darwin") {
26482
- const formulae = await c.command("brew", "brew", ["list", "--versions"], LIST);
26483
- if (formulae !== null)
26484
- add("brew", parseBrewVersions(formulae, "brew"));
26485
- const casks = await c.command("brew-cask", "brew", ["list", "--cask", "--versions"], LIST);
26486
- if (casks !== null)
26487
- add("brew-cask", parseBrewVersions(casks, "brew-cask"));
26488
- const apps = await c.command("macos-apps", "system_profiler", ["SPApplicationsDataType", "-json", "-detailLevel", "mini"], { timeoutMs: 9e4, maxBytes: 64 * 1024 * 1024 });
26489
- if (apps !== null)
26490
- add("macos-apps", parseMacApps(apps));
26491
- } else if (platform2 === "win32") {
26492
- const programs = await c.command("windows-programs", "powershell.exe", [...POWERSHELL, PS_PROGRAMS], LIST);
26493
- if (programs !== null)
26494
- add("windows-programs", parseWindowsPrograms(programs));
26495
- }
26496
- const npm = platform2 === "win32" ? await c.command("npm-global", "cmd.exe", ["/d", "/s", "/c", "npm ls -g --depth=0 --json"], LIST) : await c.command("npm-global", "npm", ["ls", "-g", "--depth=0", "--json"], LIST);
26497
- if (npm !== null)
26498
- add("npm-global", parseNpmGlobal(npm));
26499
- }
26500
- async function collectSoftware(c) {
26501
- const probes = SOFTWARE_PROBES.filter((probe) => !(probe.posixOnly && c.system.platform === "win32"));
26502
- const found = [];
26503
- const started = Date.now();
26504
- await pool(probes, 4, async (probe) => {
26505
- for (const [file2, ...args] of probe.commands) {
26506
- const result2 = await c.system.run(file2, args, { timeoutMs: 8e3, maxBytes: 256 * 1024 });
26507
- if (result2.missing)
26325
+ function parseLaunchctl(stdout) {
26326
+ const result2 = [];
26327
+ for (const line of lines2(stdout)) {
26328
+ const parts = line.split(" ");
26329
+ if (parts.length < 3)
26330
+ continue;
26331
+ const pid = (parts[0] ?? "").trim();
26332
+ const statusText = (parts[1] ?? "").trim();
26333
+ const label = text2(parts[2], NAME_MAX2);
26334
+ if (!label)
26335
+ continue;
26336
+ if (label.startsWith("com.apple.") || label.startsWith("application."))
26337
+ continue;
26338
+ let state2;
26339
+ if (pid === "-") {
26340
+ if (!/^\d+$/.test(statusText))
26508
26341
  continue;
26509
- const version6 = extractVersion(probe.key, `${result2.stdout}
26510
- ${result2.stderr}`);
26511
- if (version6) {
26512
- found.push({ key: probe.key, name: probe.name, version: version6, kind: probe.kind });
26513
- break;
26514
- }
26515
- }
26516
- });
26517
- found.sort((a, b) => SOFTWARE_PROBES.findIndex((p) => p.key === a.key) - SOFTWARE_PROBES.findIndex((p) => p.key === b.key));
26518
- c.software.push(...found);
26519
- c.cover("software", "ok", found.length, Date.now() - started);
26520
- }
26521
- async function collectServices(c) {
26522
- const { platform: platform2 } = c.system;
26523
- if (platform2 === "linux") {
26524
- const units = await c.command("systemd", "systemctl", ["list-units", "--type=service", "--all", "--no-legend", "--plain", "--no-pager"], SHORT);
26525
- if (units !== null) {
26526
- const files = (await c.system.run("systemctl", ["list-unit-files", "--type=service", "--no-legend", "--no-pager"], SHORT)).stdout;
26527
- const services = parseSystemd(units, files);
26528
- c.services.push(...services);
26529
- c.counted("systemd", services.length, INVENTORY_LIMITS.services);
26530
- }
26531
- } else if (platform2 === "darwin") {
26532
- const launchd = await c.command("launchd", "launchctl", ["list"], SHORT);
26533
- if (launchd !== null) {
26534
- const items = parseLaunchctl(launchd);
26535
- c.services.push(...items);
26536
- c.counted("launchd", items.length, INVENTORY_LIMITS.services);
26537
- }
26538
- const brew = await c.command("brew-services", "brew", ["services", "list", "--json"], SHORT);
26539
- if (brew !== null) {
26540
- const items = parseBrewServices(brew);
26541
- c.services.push(...items);
26542
- c.counted("brew-services", items.length, INVENTORY_LIMITS.services);
26543
- }
26544
- } else if (platform2 === "win32") {
26545
- const win = await c.command("windows-services", "powershell.exe", [...POWERSHELL, PS_SERVICES], LIST);
26546
- if (win !== null) {
26547
- const items = parseWindowsServices(win);
26548
- c.services.push(...items);
26549
- c.counted("windows-services", items.length, INVENTORY_LIMITS.services);
26342
+ state2 = Number(statusText) === 0 ? "stopped" : "failed";
26343
+ } else if (/^\d+$/.test(pid)) {
26344
+ state2 = "running";
26345
+ } else {
26346
+ continue;
26550
26347
  }
26348
+ result2.push({ name: label, manager: "launchd", state: state2, enabled: null });
26551
26349
  }
26350
+ return sorted(result2);
26552
26351
  }
26553
- async function collectContainers(c) {
26554
- let ps = await c.command("docker", "docker", ["ps", "-a", "--no-trunc", "--size", "--format", "{{json .}}"], LIST);
26555
- if (ps === null && c.coverage.find((e) => e.collector === "docker")?.status === "timeout") {
26556
- ps = await c.command("docker", "docker", ["ps", "-a", "--no-trunc", "--format", "{{json .}}"], SHORT);
26557
- }
26558
- if (ps !== null) {
26559
- const items = parseDockerPs(ps);
26560
- c.containers.push(...items);
26561
- c.counted("docker", items.length, INVENTORY_LIMITS.containers);
26562
- const images = await c.command("docker-images", "docker", ["image", "ls", "--no-trunc", "--format", "{{json .}}"], SHORT);
26563
- if (images !== null) {
26564
- const list = parseDockerImages(images);
26565
- c.images.push(...list);
26566
- c.counted("docker-images", list.length, INVENTORY_LIMITS.images);
26567
- }
26568
- }
26569
- const podman = await c.command("podman", "podman", ["ps", "-a", "--size", "--format", "json"], LIST);
26570
- if (podman !== null) {
26571
- const items = parsePodmanPs(podman);
26572
- c.containers.push(...items);
26573
- c.counted("podman", items.length, INVENTORY_LIMITS.containers);
26574
- const images = await c.command("podman-images", "podman", ["images", "--format", "json"], SHORT);
26575
- if (images !== null) {
26576
- const list = parsePodmanImages(images);
26577
- c.images.push(...list);
26578
- c.counted("podman-images", list.length, INVENTORY_LIMITS.images);
26579
- }
26580
- const pods = await c.command("podman-pods", "podman", ["pod", "ps", "--format", "json"], SHORT);
26581
- if (pods !== null) {
26582
- const list = parsePodmanPods(pods);
26583
- c.pods.push(...list);
26584
- c.counted("podman-pods", list.length, INVENTORY_LIMITS.pods);
26352
+ function parseBrewServices(json2) {
26353
+ const parsed = parseJson2(json2);
26354
+ if (!Array.isArray(parsed))
26355
+ return [];
26356
+ const result2 = [];
26357
+ for (const value of parsed) {
26358
+ const info = asRecord3(value);
26359
+ if (!info)
26360
+ continue;
26361
+ const name3 = text2(info.name, NAME_MAX2);
26362
+ if (!name3)
26363
+ continue;
26364
+ const status = typeof info.status === "string" ? info.status.trim().toLowerCase() : "";
26365
+ let state2;
26366
+ let enabled;
26367
+ switch (status) {
26368
+ case "started":
26369
+ state2 = "running";
26370
+ enabled = true;
26371
+ break;
26372
+ case "error":
26373
+ state2 = "failed";
26374
+ enabled = true;
26375
+ break;
26376
+ case "scheduled":
26377
+ state2 = "starting";
26378
+ enabled = true;
26379
+ break;
26380
+ case "none":
26381
+ case "stopped":
26382
+ state2 = "stopped";
26383
+ enabled = false;
26384
+ break;
26385
+ default:
26386
+ state2 = "unknown";
26387
+ enabled = null;
26585
26388
  }
26389
+ result2.push({ name: name3, manager: "brew", state: state2, enabled });
26586
26390
  }
26587
- const kube = await c.command("kubernetes", "kubectl", [
26588
- "get",
26589
- "pods",
26590
- "-A",
26591
- "--no-headers",
26592
- "--request-timeout=10s",
26593
- "-o",
26594
- "custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName,CREATED:.metadata.creationTimestamp,READY:.status.containerStatuses[*].ready,RESTARTS:.status.containerStatuses[*].restartCount"
26595
- ], { timeoutMs: 2e4, maxBytes: 8 * 1024 * 1024 });
26596
- if (kube !== null) {
26597
- const list = parseKubectlPods(kube);
26598
- c.pods.push(...list);
26599
- c.counted("kubernetes", list.length, INVENTORY_LIMITS.pods);
26600
- }
26601
- for (const image of c.images) {
26602
- if (image.containers !== void 0)
26391
+ return sorted(result2);
26392
+ }
26393
+ var WINDOWS_STATES = {
26394
+ "4": "running",
26395
+ running: "running",
26396
+ "1": "stopped",
26397
+ stopped: "stopped",
26398
+ "2": "starting",
26399
+ startpending: "starting",
26400
+ "3": "stopping",
26401
+ stoppending: "stopping",
26402
+ "7": "stopped",
26403
+ paused: "stopped"
26404
+ };
26405
+ var WINDOWS_START_TYPES = {
26406
+ "2": true,
26407
+ automatic: true,
26408
+ "3": false,
26409
+ manual: false,
26410
+ "4": false,
26411
+ disabled: false
26412
+ };
26413
+ function windowsState(value) {
26414
+ if (typeof value === "number")
26415
+ return WINDOWS_STATES[String(value)] ?? "unknown";
26416
+ if (typeof value === "string")
26417
+ return WINDOWS_STATES[value.trim().toLowerCase()] ?? "unknown";
26418
+ return "unknown";
26419
+ }
26420
+ function windowsEnabled(value) {
26421
+ if (typeof value === "number")
26422
+ return WINDOWS_START_TYPES[String(value)] ?? null;
26423
+ if (typeof value === "string")
26424
+ return WINDOWS_START_TYPES[value.trim().toLowerCase()] ?? null;
26425
+ return null;
26426
+ }
26427
+ function parseWindowsServices(json2) {
26428
+ const parsed = parseJson2(json2);
26429
+ if (parsed === void 0 || parsed === null)
26430
+ return [];
26431
+ const entries = Array.isArray(parsed) ? parsed : [parsed];
26432
+ const result2 = [];
26433
+ for (const value of entries) {
26434
+ const info = asRecord3(value);
26435
+ if (!info)
26603
26436
  continue;
26604
- const ref = `${image.repository}:${image.tag}`;
26605
- const count3 = c.containers.filter((ct) => ct.engine === image.engine && (ct.image === ref || image.tag === "latest" && ct.image === image.repository || ct.image.startsWith(image.id))).length;
26606
- image.containers = count3;
26437
+ const name3 = text2(info.Name, NAME_MAX2);
26438
+ if (!name3)
26439
+ continue;
26440
+ const item = {
26441
+ name: name3,
26442
+ manager: "windows",
26443
+ state: windowsState(info.Status),
26444
+ enabled: windowsEnabled(info.StartType)
26445
+ };
26446
+ const description = text2(info.DisplayName, DESCRIPTION_MAX);
26447
+ if (description && description !== name3)
26448
+ item.description = description;
26449
+ result2.push(item);
26607
26450
  }
26451
+ return sorted(result2);
26608
26452
  }
26609
- async function collectInventory(system = defaultCollectorSystem) {
26610
- const c = new Collection(system);
26611
- const os = await collectOs(c);
26612
- await collectPackages(c);
26613
- await collectSoftware(c);
26614
- await collectServices(c);
26615
- await collectContainers(c);
26616
- const snapshot = {
26617
- schema: 1,
26618
- collected_at: system.now().toISOString(),
26619
- agent_version: AGENT_VERSION,
26620
- os: inventoryOsSchema.safeParse(os).success ? os : { family: "other", name: system.platform, version: "", arch: system.arch },
26621
- packages: valid(inventoryPackageSchema, c.packages, INVENTORY_LIMITS.packages),
26622
- software: valid(inventorySoftwareSchema, c.software, INVENTORY_LIMITS.software),
26623
- services: valid(inventoryServiceSchema, c.services, INVENTORY_LIMITS.services),
26624
- containers: valid(inventoryContainerSchema, c.containers, INVENTORY_LIMITS.containers),
26625
- images: valid(inventoryImageSchema, c.images, INVENTORY_LIMITS.images),
26626
- pods: valid(inventoryPodSchema, c.pods, INVENTORY_LIMITS.pods),
26627
- coverage: valid(inventoryCoverageSchema, c.coverage, INVENTORY_LIMITS.coverage)
26628
- };
26629
- return inventorySnapshotSchema.parse(snapshot);
26453
+
26454
+ // dist/inventory/parsers/containers.js
26455
+ var NAME_MAX3 = 200;
26456
+ var STATUS_MAX = 200;
26457
+ var PORT_MAX = 80;
26458
+ var TAG_MAX = 128;
26459
+ var POD_STATUS_MAX = 40;
26460
+ var MAX_CONTAINERS = INVENTORY_LIMITS.containers;
26461
+ var MAX_IMAGES = INVENTORY_LIMITS.images;
26462
+ var MAX_PODS = INVENTORY_LIMITS.pods;
26463
+ var MAX_PORTS = INVENTORY_LIMITS.ports;
26464
+ var CONTAINER_STATE_VALUES = /* @__PURE__ */ new Set([
26465
+ "running",
26466
+ "paused",
26467
+ "restarting",
26468
+ "exited",
26469
+ "created",
26470
+ "dead",
26471
+ "removing"
26472
+ ]);
26473
+ var BYTE_MULTIPLIERS = {
26474
+ b: 1,
26475
+ kb: 1e3,
26476
+ mb: 1e6,
26477
+ gb: 1e9,
26478
+ tb: 1e12,
26479
+ kib: 1024,
26480
+ mib: 1024 * 1024,
26481
+ gib: 1024 * 1024 * 1024,
26482
+ tib: 1024 * 1024 * 1024 * 1024
26483
+ };
26484
+ function text3(value, max) {
26485
+ if (typeof value !== "string")
26486
+ return "";
26487
+ const trimmed = value.trim();
26488
+ if (trimmed.length <= max)
26489
+ return trimmed;
26490
+ return trimmed.slice(0, max).trimEnd();
26491
+ }
26492
+ function nameOf2(value) {
26493
+ return text3(value, NAME_MAX3);
26494
+ }
26495
+ function asRecord4(value) {
26496
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
26497
+ }
26498
+ function lines3(stdout) {
26499
+ if (typeof stdout !== "string")
26500
+ return [];
26501
+ return stdout.split(/\r?\n/).filter((line) => line.trim() !== "");
26502
+ }
26503
+ function parseJson3(value) {
26504
+ if (typeof value !== "string")
26505
+ return void 0;
26506
+ try {
26507
+ return JSON.parse(value);
26508
+ } catch {
26509
+ return void 0;
26510
+ }
26511
+ }
26512
+ function push2(result2, item, max) {
26513
+ if (result2.length < max)
26514
+ result2.push(item);
26515
+ }
26516
+ function shortId(value) {
26517
+ if (typeof value !== "string")
26518
+ return void 0;
26519
+ let raw = value.trim().toLowerCase();
26520
+ if (raw.startsWith("sha256:"))
26521
+ raw = raw.slice("sha256:".length);
26522
+ if (raw.length < 12 || !/^[0-9a-f]+$/.test(raw))
26523
+ return void 0;
26524
+ return raw.slice(0, 12);
26525
+ }
26526
+ function containerState(value) {
26527
+ if (typeof value !== "string")
26528
+ return "unknown";
26529
+ const state2 = value.trim().toLowerCase();
26530
+ return CONTAINER_STATE_VALUES.has(state2) ? state2 : "unknown";
26531
+ }
26532
+ function nonNegativeInteger(value) {
26533
+ if (typeof value !== "number" || !Number.isFinite(value))
26534
+ return void 0;
26535
+ const rounded = Math.round(value);
26536
+ return rounded >= 0 && Number.isSafeInteger(rounded) ? rounded : void 0;
26630
26537
  }
26631
-
26632
- // dist/relay.js
26633
- var HEARTBEAT_INTERVAL_MS = 2e4;
26634
- var AUTH_TIMEOUT_MS = 2e4;
26635
- var CLOSE_POLICY_VIOLATION = 4008;
26636
- function relayUrl(gatewayUrl, deviceUuid2) {
26637
- const url2 = new URL("/v1/agent/connect", gatewayUrl);
26638
- url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
26639
- url2.search = new URLSearchParams({ device: deviceUuid2 }).toString();
26640
- return url2.toString();
26538
+ function isoFromUnix(value) {
26539
+ if (typeof value !== "number" || !Number.isFinite(value))
26540
+ return void 0;
26541
+ const date5 = new Date(value * 1e3);
26542
+ return Number.isNaN(date5.getTime()) ? void 0 : date5.toISOString();
26641
26543
  }
26642
- async function signRelayChallenge(key, deviceUuid2, nonce, connectionId) {
26643
- const message = agentAuthMessage({ deviceUuid: deviceUuid2, nonce, connectionId });
26644
- return toBase64Url(await key.sign(new TextEncoder().encode(message)));
26544
+ function isoString(value) {
26545
+ if (typeof value !== "string")
26546
+ return void 0;
26547
+ const raw = value.trim();
26548
+ if (!raw)
26549
+ return void 0;
26550
+ return Number.isNaN(new Date(raw).getTime()) ? void 0 : raw;
26645
26551
  }
26646
- var RelaySession = class {
26647
- #options;
26648
- #logger;
26649
- #state = "challenge";
26650
- #connectionEpoch = 0;
26651
- #queue = Promise.resolve();
26652
- constructor(options) {
26653
- this.#options = options;
26654
- this.#logger = options.logger ?? silentLogger;
26655
- }
26656
- get state() {
26657
- return this.#state;
26658
- }
26659
- get identity() {
26660
- const { tenant_id, user_id, device_uuid } = this.#options.identity;
26661
- return { tenant_id, user_id, device_uuid };
26662
- }
26663
- /** Feed one incoming text frame; frames are processed strictly in order. */
26664
- onMessage(text4) {
26665
- const next = this.#queue.then(() => this.#process(text4));
26666
- this.#queue = next.catch(() => void 0);
26667
- return next;
26668
- }
26669
- #fail(reason) {
26670
- if (this.#state === "closed")
26671
- return;
26672
- this.#logger.warn("closing relay connection", { reason });
26673
- this.#state = "closed";
26674
- this.#options.close(CLOSE_POLICY_VIOLATION, reason);
26675
- }
26676
- markClosed() {
26677
- this.#state = "closed";
26678
- }
26679
- async #process(text4) {
26680
- if (this.#state === "closed")
26681
- return;
26682
- if (this.#state === "challenge" || this.#state === "auth_sent") {
26683
- let frame;
26684
- try {
26685
- frame = JSON.parse(text4);
26686
- } catch {
26687
- return this.#fail("invalid pre-auth frame");
26688
- }
26689
- if (this.#state === "challenge")
26690
- return this.#onChallenge(frame);
26691
- return this.#onAuthOk(frame);
26692
- }
26693
- let envelope;
26694
- try {
26695
- envelope = decodeEnvelope(text4);
26696
- } catch (error63) {
26697
- this.#logger.warn("ignoring invalid envelope", { code: error63 instanceof ProtocolDecodeError ? error63.code : "INVALID_MESSAGE" });
26698
- return;
26699
- }
26700
- const identity = this.#options.identity;
26701
- if (envelope.tenant_id !== identity.tenant_id || envelope.user_id !== identity.user_id || envelope.device_uuid !== identity.device_uuid) {
26702
- return this.#fail("envelope identity mismatch");
26703
- }
26704
- switch (envelope.kind) {
26705
- case "DISPATCH":
26706
- void this.#options.dispatcher.handle(envelope);
26707
- return;
26708
- case "CANCEL":
26709
- void this.#options.dispatcher.cancel(envelope).catch((error63) => {
26710
- this.#logger.error("cancel handling failed", { task_id: envelope.task_id, error: error63 instanceof Error ? error63.name : "unknown" });
26711
- });
26712
- return;
26713
- case "ERROR":
26714
- this.#logger.warn("relay error", { code: envelope.code, message: envelope.safe_message });
26715
- return;
26716
- case "MONITOR_CONFIG":
26717
- this.#options.onMonitorConfig?.({ enabled: envelope.enabled, interval_s: envelope.interval_s });
26718
- return;
26719
- case "SOFTWARE_INVENTORY_CONFIG":
26720
- this.#options.onInventoryConfig?.({ enabled: envelope.enabled, interval_s: envelope.interval_s });
26721
- return;
26722
- case "SOFTWARE_INVENTORY_REQUEST":
26723
- this.#options.onInventoryRequest?.(envelope.request_id);
26724
- return;
26725
- default:
26726
- return;
26727
- }
26728
- }
26729
- async #onChallenge(frame) {
26730
- const parsed = relayChallengeSchema.safeParse(frame);
26731
- if (!parsed.success)
26732
- return this.#fail("expected CHALLENGE");
26733
- const now = (this.#options.now ?? Date.now)();
26734
- if (parsed.data.expires_at_ms <= now)
26735
- return this.#fail("challenge expired");
26736
- const deviceUuid2 = this.#options.identity.device_uuid;
26737
- const signature = await signRelayChallenge(this.#options.key, deviceUuid2, parsed.data.nonce, parsed.data.connection_id);
26738
- this.#state = "auth_sent";
26739
- this.#options.send(JSON.stringify({ kind: "AUTH", device_uuid: deviceUuid2, connection_id: parsed.data.connection_id, signature }));
26740
- }
26741
- #onAuthOk(frame) {
26742
- const parsed = relayAuthOkSchema.safeParse(frame);
26743
- if (!parsed.success)
26744
- return this.#fail("expected AUTH_OK");
26745
- const identity = this.#options.identity;
26746
- if (parsed.data.tenant_id !== identity.tenant_id || parsed.data.user_id !== identity.user_id || parsed.data.device_uuid !== identity.device_uuid) {
26747
- return this.#fail("AUTH_OK identity mismatch");
26748
- }
26749
- this.#connectionEpoch = parsed.data.connection_epoch;
26750
- this.#state = "ready";
26751
- this.#sendEnvelope(buildEnvelope(this.identity, "HELLO", null, {
26752
- agent_id: identity.device_uuid,
26753
- supported_versions: [...SUPPORTED_VERSIONS],
26754
- capabilities: [...DESKTOP_CAPABILITIES, ...SSH_CAPABILITIES, ...SHELL_CAPABILITIES]
26755
- }));
26756
- this.sendInventory();
26757
- this.#options.onReady?.();
26758
- }
26759
- #sendEnvelope(envelope) {
26760
- if (this.#state !== "ready")
26761
- return;
26762
- this.#options.send(encode3(envelope));
26763
- }
26764
- sendInventory() {
26765
- const roots = this.#options.config().roots.map(({ root_id, label, writable }) => ({ root_id, label, writable }));
26766
- const resources = this.#options.resources?.().map((resource) => ({ ...resource, ...resource.attrs ? { attrs: { ...resource.attrs } } : {} }));
26767
- this.#sendEnvelope(buildEnvelope(this.identity, "INVENTORY", null, { roots, ...resources && resources.length > 0 ? { resources } : {}, agent_version: AGENT_VERSION }));
26768
- }
26769
- sendHeartbeat() {
26770
- this.#sendEnvelope(buildEnvelope(this.identity, "HEARTBEAT", null, { connection_epoch: this.#connectionEpoch, status: "ONLINE" }));
26771
- }
26772
- /** One resource sample (telemetry, never a task); dropped silently unless authenticated. */
26773
- sendMetrics(body) {
26774
- if (this.#state !== "ready")
26775
- return;
26776
- this.#sendEnvelope(buildEnvelope(this.identity, "METRICS", null, body));
26552
+ function stringList(value) {
26553
+ return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
26554
+ }
26555
+ function firstName(value) {
26556
+ if (typeof value !== "string")
26557
+ return "";
26558
+ return nameOf2(value.split(",")[0] ?? "");
26559
+ }
26560
+ function dockerPorts(value) {
26561
+ if (typeof value !== "string")
26562
+ return [];
26563
+ const ports = [];
26564
+ for (const part of value.split(",")) {
26565
+ const port = text3(part, PORT_MAX);
26566
+ if (!port)
26567
+ continue;
26568
+ ports.push(port);
26569
+ if (ports.length >= MAX_PORTS)
26570
+ break;
26777
26571
  }
26778
- /** The parts of one software inventory run (telemetry, never a task); dropped silently unless authenticated. */
26779
- sendInventoryParts(parts) {
26780
- if (this.#state !== "ready")
26781
- return;
26782
- for (const part of parts)
26783
- this.#sendEnvelope(buildEnvelope(this.identity, "SOFTWARE_INVENTORY_PART", null, part));
26572
+ return ports;
26573
+ }
26574
+ function portText(value) {
26575
+ if (typeof value === "number" && Number.isFinite(value))
26576
+ return String(value);
26577
+ return text3(value, 16);
26578
+ }
26579
+ function podmanPorts(value) {
26580
+ if (!Array.isArray(value))
26581
+ return [];
26582
+ const ports = [];
26583
+ for (const entry of value) {
26584
+ const port = asRecord4(entry);
26585
+ if (!port)
26586
+ continue;
26587
+ const hostIp = text3(port.host_ip, 64) || "0.0.0.0";
26588
+ const hostPort = portText(port.host_port);
26589
+ const containerPort = portText(port.container_port);
26590
+ if (!hostPort || !containerPort)
26591
+ continue;
26592
+ const protocol = text3(port.protocol, 8) || "tcp";
26593
+ const rendered = text3(`${hostIp}:${hostPort}->${containerPort}/${protocol}`, PORT_MAX);
26594
+ if (!rendered)
26595
+ continue;
26596
+ ports.push(rendered);
26597
+ if (ports.length >= MAX_PORTS)
26598
+ break;
26784
26599
  }
26785
- /** Forward a pre-encoded task frame (ACK/CHUNK/RESULT) if authenticated. */
26786
- sendFrame(frame) {
26787
- if (this.#state !== "ready")
26788
- throw new Error("Relay session is not authenticated");
26789
- this.#options.send(frame);
26600
+ return ports;
26601
+ }
26602
+ function dockerSize(value) {
26603
+ if (typeof value !== "string")
26604
+ return {};
26605
+ const raw = value.trim();
26606
+ if (!raw)
26607
+ return {};
26608
+ const virtual = /\(virtual\s+([^)]+)\)/i.exec(raw);
26609
+ const rwText = raw.replace(/\(virtual[^)]*\)/i, "").trim();
26610
+ const result2 = {};
26611
+ const rw = parseHumanBytes(rwText);
26612
+ if (rw !== null)
26613
+ result2.rw = rw;
26614
+ if (virtual) {
26615
+ const root = parseHumanBytes(virtual[1] ?? "");
26616
+ if (root !== null)
26617
+ result2.root = root;
26790
26618
  }
26791
- };
26792
- function backoffDelay(attempt, options) {
26793
- const cap = Math.min(options.maxMs, options.baseMs * 2 ** Math.min(attempt, 16));
26794
- return Math.floor(cap / 2 + (options.random ?? Math.random)() * (cap / 2));
26619
+ return result2;
26795
26620
  }
26796
-
26797
- // dist/ssh/exec.js
26798
- var import_node_child_process7 = require("node:child_process");
26799
- var import_node_path13 = require("node:path");
26800
-
26801
- // dist/ssh/hosts.js
26802
- var import_node_crypto9 = require("node:crypto");
26803
- var import_promises12 = require("node:fs/promises");
26804
- var import_node_path12 = require("node:path");
26805
- var MAX_SSH_HOSTS = 64;
26806
- var SSH_ALIAS = /^[a-z0-9][a-z0-9_-]{0,62}$/;
26807
- 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])?)*$/;
26808
- var IPV6_HOST = /^(?=.{2,45}$)[0-9A-Fa-f:.]*:[0-9A-Fa-f:.]*$/;
26809
- var SSH_USER = /^[A-Za-z_][A-Za-z0-9_.-]{0,31}$/;
26810
- function isValidSshHost(value) {
26811
- return DNS_HOST.test(value) || IPV6_HOST.test(value);
26621
+ function dockerComposeProject(value) {
26622
+ if (typeof value !== "string")
26623
+ return void 0;
26624
+ for (const pair of value.split(",")) {
26625
+ const separator = pair.indexOf("=");
26626
+ if (separator <= 0)
26627
+ continue;
26628
+ const key = pair.slice(0, separator).trim();
26629
+ if (key !== "com.docker.compose.project")
26630
+ continue;
26631
+ const project = nameOf2(pair.slice(separator + 1));
26632
+ if (project)
26633
+ return project;
26634
+ }
26635
+ return void 0;
26812
26636
  }
26813
- function isValidIdentityPath(value) {
26814
- return (0, import_node_path12.isAbsolute)(value) && value.length <= 1024 && !/[\u0000-\u001f\u007f%"]/.test(value);
26637
+ function podmanComposeProject(value) {
26638
+ const labels = asRecord4(value);
26639
+ if (!labels)
26640
+ return void 0;
26641
+ for (const key of ["com.docker.compose.project", "io.podman.compose.project"]) {
26642
+ const project = nameOf2(labels[key]);
26643
+ if (project)
26644
+ return project;
26645
+ }
26646
+ return void 0;
26815
26647
  }
26816
- var PINNABLE_KEY_TYPES = Object.freeze([
26817
- "ssh-ed25519",
26818
- "ecdsa-sha2-nistp256",
26819
- "ecdsa-sha2-nistp384",
26820
- "ecdsa-sha2-nistp521",
26821
- "ssh-rsa"
26822
- ]);
26823
- var base643 = /^[A-Za-z0-9+/]+={0,2}$/;
26824
- var sshHostSchema = external_exports.strictObject({
26825
- resource_id: external_exports.uuid(),
26826
- alias: external_exports.string().regex(SSH_ALIAS),
26827
- host: external_exports.string().refine(isValidSshHost, "Invalid host"),
26828
- port: external_exports.number().int().min(1).max(65535),
26829
- user: external_exports.string().regex(SSH_USER).optional(),
26830
- identity: external_exports.string().refine(isValidIdentityPath, "Invalid identity path").optional(),
26831
- production: external_exports.boolean(),
26832
- key_type: external_exports.enum(PINNABLE_KEY_TYPES),
26833
- public_key: external_exports.string().min(16).max(8192).regex(base643),
26834
- fingerprint: external_exports.string().regex(/^SHA256:[A-Za-z0-9+/]{43}$/),
26835
- pinned_at: external_exports.iso.datetime({ offset: true })
26836
- });
26837
- var hostsFileSchema = external_exports.strictObject({ version: external_exports.literal(1), hosts: external_exports.array(sshHostSchema).max(MAX_SSH_HOSTS) });
26838
- function sshPaths(stateDir) {
26839
- const dir = (0, import_node_path12.join)(stateDir, "ssh");
26840
- return { dir, hosts: (0, import_node_path12.join)(dir, "hosts.json"), knownHostsDir: (0, import_node_path12.join)(dir, "known_hosts") };
26648
+ function splitImageName(value) {
26649
+ const name3 = value.trim();
26650
+ if (!name3)
26651
+ return { repository: "<none>", tag: "" };
26652
+ const slash = name3.lastIndexOf("/");
26653
+ const colon = name3.lastIndexOf(":");
26654
+ if (colon > slash) {
26655
+ return {
26656
+ repository: nameOf2(name3.slice(0, colon)) || "<none>",
26657
+ tag: text3(name3.slice(colon + 1), TAG_MAX)
26658
+ };
26659
+ }
26660
+ return { repository: nameOf2(name3) || "<none>", tag: "" };
26841
26661
  }
26842
- function knownHostsPath(paths, resourceId) {
26843
- return (0, import_node_path12.join)(paths.knownHostsDir, external_exports.uuid().parse(resourceId));
26662
+ function parseHumanBytes(value) {
26663
+ if (typeof value !== "string")
26664
+ return null;
26665
+ const match = /^(\d+(?:\.\d+)?)\s*([a-z]+)$/i.exec(value.trim());
26666
+ if (!match)
26667
+ return null;
26668
+ const amount = Number(match[1]);
26669
+ const multiplier = BYTE_MULTIPLIERS[(match[2] ?? "").toLowerCase()];
26670
+ if (multiplier === void 0 || !Number.isFinite(amount) || amount < 0)
26671
+ return null;
26672
+ const bytes3 = Math.round(amount * multiplier);
26673
+ return Number.isSafeInteger(bytes3) ? bytes3 : null;
26844
26674
  }
26845
- function hostKeyAlias(host) {
26846
- return "conbridge-" + host.resource_id;
26675
+ function parseDockerTime(value) {
26676
+ if (typeof value !== "string")
26677
+ return null;
26678
+ const match = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) ([+-]\d{2})(\d{2})/.exec(value.trim());
26679
+ if (!match)
26680
+ return null;
26681
+ return `${match[1]}T${match[2]}${match[3]}:${match[4]}`;
26847
26682
  }
26848
- function fingerprintOf(publicKey) {
26849
- return "SHA256:" + (0, import_node_crypto9.createHash)("sha256").update(Buffer.from(publicKey, "base64")).digest("base64").replace(/=+$/, "");
26683
+ function parseDockerPs(jsonLines) {
26684
+ const result2 = [];
26685
+ for (const line of lines3(jsonLines)) {
26686
+ const info = asRecord4(parseJson3(line));
26687
+ if (!info)
26688
+ continue;
26689
+ const id = shortId(info.ID);
26690
+ if (!id)
26691
+ continue;
26692
+ const name3 = firstName(info.Names);
26693
+ const image = nameOf2(info.Image);
26694
+ if (!name3 || !image)
26695
+ continue;
26696
+ const item = {
26697
+ id,
26698
+ name: name3,
26699
+ image,
26700
+ engine: "docker",
26701
+ state: containerState(info.State),
26702
+ status: text3(info.Status, STATUS_MAX),
26703
+ ports: dockerPorts(info.Ports)
26704
+ };
26705
+ const createdAt = parseDockerTime(typeof info.CreatedAt === "string" ? info.CreatedAt : "");
26706
+ if (createdAt)
26707
+ item.created_at = createdAt;
26708
+ const size = dockerSize(info.Size);
26709
+ if (size.rw !== void 0)
26710
+ item.size_rw_bytes = size.rw;
26711
+ if (size.root !== void 0)
26712
+ item.size_root_fs_bytes = size.root;
26713
+ const composeProject = dockerComposeProject(info.Labels);
26714
+ if (composeProject)
26715
+ item.compose_project = composeProject;
26716
+ push2(result2, item, MAX_CONTAINERS);
26717
+ }
26718
+ return result2;
26850
26719
  }
26851
- function normalizeFingerprint(value) {
26852
- const trimmed = value.trim();
26853
- return trimmed.startsWith("SHA256:") ? trimmed : "SHA256:" + trimmed;
26720
+ function parseDockerImages(jsonLines) {
26721
+ const result2 = [];
26722
+ const seen = /* @__PURE__ */ new Set();
26723
+ for (const line of lines3(jsonLines)) {
26724
+ const info = asRecord4(parseJson3(line));
26725
+ if (!info)
26726
+ continue;
26727
+ const id = shortId(info.ID);
26728
+ if (!id)
26729
+ continue;
26730
+ const repository = nameOf2(info.Repository) || "<none>";
26731
+ const rawTag = text3(info.Tag, TAG_MAX);
26732
+ const tag = rawTag === "<none>" ? "" : rawTag;
26733
+ const key = `${id}\0${repository}\0${tag}`;
26734
+ if (seen.has(key))
26735
+ continue;
26736
+ seen.add(key);
26737
+ const item = { id, repository, tag, engine: "docker" };
26738
+ const createdAt = parseDockerTime(typeof info.CreatedAt === "string" ? info.CreatedAt : "");
26739
+ if (createdAt)
26740
+ item.created_at = createdAt;
26741
+ const size = parseHumanBytes(typeof info.Size === "string" ? info.Size : "");
26742
+ if (size !== null)
26743
+ item.size_bytes = size;
26744
+ push2(result2, item, MAX_IMAGES);
26745
+ }
26746
+ return result2;
26854
26747
  }
26855
- function parseKeyscan(output2) {
26856
- const keys = [];
26857
- for (const line of output2.split("\n")) {
26858
- const trimmed = line.trim();
26859
- if (trimmed === "" || trimmed.startsWith("#"))
26748
+ function parsePodmanPs(json2) {
26749
+ const parsed = parseJson3(json2);
26750
+ if (!Array.isArray(parsed))
26751
+ return [];
26752
+ const result2 = [];
26753
+ for (const value of parsed) {
26754
+ const info = asRecord4(value);
26755
+ if (!info)
26860
26756
  continue;
26861
- const [, type, key] = trimmed.split(/\s+/);
26862
- if (!type || !key || !PINNABLE_KEY_TYPES.includes(type) || !base643.test(key) || key.length > 8192)
26757
+ const id = shortId(info.Id);
26758
+ if (!id)
26863
26759
  continue;
26864
- keys.push({ key_type: type, public_key: key, fingerprint: fingerprintOf(key) });
26760
+ const name3 = firstName(stringList(info.Names).join(","));
26761
+ const image = nameOf2(info.Image);
26762
+ if (!name3 || !image)
26763
+ continue;
26764
+ const item = {
26765
+ id,
26766
+ name: name3,
26767
+ image,
26768
+ engine: "podman",
26769
+ state: containerState(info.State),
26770
+ status: text3(info.Status, STATUS_MAX),
26771
+ ports: podmanPorts(info.Ports)
26772
+ };
26773
+ const createdAt = isoFromUnix(info.Created) ?? isoString(info.CreatedAt);
26774
+ if (createdAt)
26775
+ item.created_at = createdAt;
26776
+ const size = asRecord4(info.Size);
26777
+ const rw = nonNegativeInteger(size?.rwSize);
26778
+ if (rw !== void 0)
26779
+ item.size_rw_bytes = rw;
26780
+ const root = nonNegativeInteger(size?.rootFsSize);
26781
+ if (root !== void 0)
26782
+ item.size_root_fs_bytes = root;
26783
+ const pod = nameOf2(info.PodName);
26784
+ if (pod)
26785
+ item.pod = pod;
26786
+ const composeProject = podmanComposeProject(info.Labels);
26787
+ if (composeProject)
26788
+ item.compose_project = composeProject;
26789
+ push2(result2, item, MAX_CONTAINERS);
26865
26790
  }
26866
- return keys;
26791
+ return result2;
26867
26792
  }
26868
- function preferredKey(keys) {
26869
- for (const type of PINNABLE_KEY_TYPES) {
26870
- const key = keys.find((candidate) => candidate.key_type === type);
26871
- if (key)
26872
- return key;
26793
+ function parsePodmanImages(json2) {
26794
+ const parsed = parseJson3(json2);
26795
+ if (!Array.isArray(parsed))
26796
+ return [];
26797
+ const result2 = [];
26798
+ for (const value of parsed) {
26799
+ const info = asRecord4(value);
26800
+ if (!info)
26801
+ continue;
26802
+ const id = shortId(info.Id);
26803
+ if (!id)
26804
+ continue;
26805
+ const first = stringList(info.Names)[0] ?? "";
26806
+ const { repository, tag } = splitImageName(first);
26807
+ const item = { id, repository, tag, engine: "podman" };
26808
+ const size = nonNegativeInteger(info.Size);
26809
+ if (size !== void 0)
26810
+ item.size_bytes = size;
26811
+ const createdAt = isoFromUnix(info.Created);
26812
+ if (createdAt)
26813
+ item.created_at = createdAt;
26814
+ const containers = nonNegativeInteger(info.Containers);
26815
+ if (containers !== void 0)
26816
+ item.containers = containers;
26817
+ push2(result2, item, MAX_IMAGES);
26873
26818
  }
26874
- return null;
26819
+ return result2;
26875
26820
  }
26876
- async function loadSshHosts(paths) {
26877
- let text4;
26878
- try {
26879
- text4 = await (0, import_promises12.readFile)(paths.hosts, "utf8");
26880
- } catch (error63) {
26881
- if (errorCode2(error63) === "ENOENT")
26882
- return [];
26883
- throw error63;
26821
+ function parsePodmanPods(json2) {
26822
+ const parsed = parseJson3(json2);
26823
+ if (!Array.isArray(parsed))
26824
+ return [];
26825
+ const result2 = [];
26826
+ for (const value of parsed) {
26827
+ const info = asRecord4(value);
26828
+ if (!info)
26829
+ continue;
26830
+ const name3 = nameOf2(info.Name);
26831
+ if (!name3)
26832
+ continue;
26833
+ const containerList = Array.isArray(info.Containers) ? info.Containers : void 0;
26834
+ const containers = containerList ? containerList.length : nonNegativeInteger(info.NumberOfContainers) ?? 0;
26835
+ const item = {
26836
+ name: name3,
26837
+ engine: "podman",
26838
+ status: text3(info.Status, POD_STATUS_MAX) || "Unknown",
26839
+ containers
26840
+ };
26841
+ if (containerList) {
26842
+ let ready = 0;
26843
+ for (const entry of containerList) {
26844
+ const container = asRecord4(entry);
26845
+ if (container && text3(container.Status, POD_STATUS_MAX).toLowerCase() === "running")
26846
+ ready += 1;
26847
+ }
26848
+ item.ready = ready;
26849
+ }
26850
+ const createdAt = isoString(info.Created) ?? isoString(info.CreatedAt);
26851
+ if (createdAt)
26852
+ item.created_at = createdAt;
26853
+ push2(result2, item, MAX_PODS);
26884
26854
  }
26885
- return hostsFileSchema.parse(JSON.parse(text4)).hosts;
26855
+ return result2;
26886
26856
  }
26887
- async function ensureSshDirs(paths) {
26888
- for (const dir of [paths.dir, paths.knownHostsDir]) {
26889
- await (0, import_promises12.mkdir)(dir, { recursive: true, mode: 448 });
26890
- await (0, import_promises12.chmod)(dir, 448);
26857
+ function parseKubectlPods(stdout) {
26858
+ const result2 = [];
26859
+ for (const line of lines3(stdout)) {
26860
+ const parts = line.trim().split(/\s+/);
26861
+ if (parts.length < 7)
26862
+ continue;
26863
+ const namespace = nameOf2(parts[0]);
26864
+ const name3 = nameOf2(parts[1]);
26865
+ if (!name3)
26866
+ continue;
26867
+ const readyField = parts[5] ?? "";
26868
+ const restartsField = parts[6] ?? "";
26869
+ let containers = 0;
26870
+ let ready;
26871
+ if (readyField !== "<none>") {
26872
+ const values = readyField.split(",").map((entry) => entry.trim()).filter((entry) => entry !== "");
26873
+ containers = values.length;
26874
+ ready = values.filter((entry) => entry.toLowerCase() === "true").length;
26875
+ }
26876
+ let restarts;
26877
+ if (restartsField !== "<none>") {
26878
+ const values = restartsField.split(",").map((entry) => entry.trim()).filter((entry) => /^\d+$/.test(entry));
26879
+ if (values.length > 0)
26880
+ restarts = values.reduce((total, entry) => total + Number(entry), 0);
26881
+ }
26882
+ const item = {
26883
+ name: name3,
26884
+ engine: "kubernetes",
26885
+ status: text3(parts[2], POD_STATUS_MAX) || "Unknown",
26886
+ containers
26887
+ };
26888
+ if (namespace)
26889
+ item.namespace = namespace;
26890
+ if (ready !== void 0)
26891
+ item.ready = ready;
26892
+ if (restarts !== void 0)
26893
+ item.restarts = restarts;
26894
+ const node2 = nameOf2(parts[3]);
26895
+ if (node2 && node2 !== "<none>")
26896
+ item.node = node2;
26897
+ const created = text3(parts[4], 64);
26898
+ if (created && created !== "<none>") {
26899
+ const createdAt = isoString(created);
26900
+ if (createdAt)
26901
+ item.created_at = createdAt;
26902
+ }
26903
+ push2(result2, item, MAX_PODS);
26891
26904
  }
26905
+ return result2;
26892
26906
  }
26893
- async function saveSshHosts(paths, hosts) {
26894
- await ensureSshDirs(paths);
26895
- await writeFileAtomic(paths.hosts, JSON.stringify(hostsFileSchema.parse({ version: 1, hosts }), null, 2) + "\n", 384);
26896
- }
26897
- async function writeKnownHosts(paths, host) {
26898
- await ensureSshDirs(paths);
26899
- await writeFileAtomic(knownHostsPath(paths, host.resource_id), `${hostKeyAlias(host)} ${host.key_type} ${host.public_key}
26900
- `, 384);
26901
- }
26902
- async function validateNewHost(input2) {
26903
- if (!SSH_ALIAS.test(input2.alias))
26904
- throw new Error('Alias must be 1-63 lowercase letters, digits, "-" or "_", starting with a letter or digit');
26905
- if (!isValidSshHost(input2.host))
26906
- throw new Error("Host must be a DNS name, IPv4 or IPv6 address");
26907
- if (input2.port !== void 0 && (!Number.isInteger(input2.port) || input2.port < 1 || input2.port > 65535))
26908
- throw new Error("Port must be 1-65535");
26909
- if (input2.user !== void 0 && !SSH_USER.test(input2.user))
26910
- throw new Error("User must be a plain login name");
26911
- if (input2.identity !== void 0) {
26912
- if (!isValidIdentityPath(input2.identity))
26913
- throw new Error("Identity must be an absolute path without quotes, % or control characters");
26914
- const info = await (0, import_promises12.stat)(input2.identity).catch(() => null);
26915
- if (!info?.isFile())
26916
- throw new Error("Identity file not found");
26917
- }
26907
+
26908
+ // dist/inventory/collector.js
26909
+ var POSIX_PATH = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin", "/opt/homebrew/bin", "/opt/homebrew/sbin", "/snap/bin"];
26910
+ var DENIED = /permission denied|EACCES|access is denied|got permission denied while trying to connect/i;
26911
+ function collectorEnv(env = process.env, platform2 = process.platform) {
26912
+ const base2 = { ...env, NO_COLOR: "1", PAGER: "cat", SYSTEMD_PAGER: "", TERM: "dumb", COMPOSER_ALLOW_SUPERUSER: "1", HOMEBREW_NO_AUTO_UPDATE: "1" };
26913
+ if (platform2 === "win32")
26914
+ return base2;
26915
+ const path = [.../* @__PURE__ */ new Set([...(env.PATH ?? "").split(":").filter(Boolean), ...POSIX_PATH])].join(":");
26916
+ return { ...base2, PATH: path };
26918
26917
  }
26919
- async function addSshHost(paths, input2, key, now = /* @__PURE__ */ new Date()) {
26920
- await validateNewHost(input2);
26921
- const hosts = await loadSshHosts(paths);
26922
- if (hosts.some((host2) => host2.alias === input2.alias))
26923
- throw new Error(`An SSH host named ${input2.alias} already exists`);
26924
- if (hosts.length >= MAX_SSH_HOSTS)
26925
- throw new Error(`At most ${MAX_SSH_HOSTS} SSH hosts are supported`);
26926
- const host = sshHostSchema.parse({
26927
- resource_id: (0, import_node_crypto9.randomUUID)(),
26928
- alias: input2.alias,
26929
- host: input2.host,
26930
- port: input2.port ?? 22,
26931
- ...input2.user !== void 0 ? { user: input2.user } : {},
26932
- ...input2.identity !== void 0 ? { identity: input2.identity } : {},
26933
- production: input2.production === true,
26934
- key_type: key.key_type,
26935
- public_key: key.public_key,
26936
- fingerprint: key.fingerprint,
26937
- pinned_at: now.toISOString()
26918
+ var defaultRunner = (file2, args, { timeoutMs, maxBytes }) => new Promise((resolve8) => {
26919
+ (0, import_node_child_process7.execFile)(file2, [...args], {
26920
+ timeout: timeoutMs,
26921
+ maxBuffer: maxBytes,
26922
+ killSignal: "SIGKILL",
26923
+ windowsHide: true,
26924
+ encoding: "utf8",
26925
+ env: collectorEnv()
26926
+ }, (error63, stdout, stderr) => {
26927
+ const code = error63?.code;
26928
+ const killed = error63?.killed === true;
26929
+ const out = String(stdout ?? ""), err = String(stderr ?? "");
26930
+ resolve8({
26931
+ stdout: out,
26932
+ stderr: err,
26933
+ ok: !error63,
26934
+ missing: code === "ENOENT",
26935
+ timedOut: killed && !code,
26936
+ denied: DENIED.test(err) || code === "EACCES"
26937
+ });
26938
26938
  });
26939
- await writeKnownHosts(paths, host);
26940
- await saveSshHosts(paths, [...hosts, host]);
26941
- return host;
26942
- }
26943
- async function findSshHost(paths, alias) {
26944
- return (await loadSshHosts(paths)).find((host) => host.alias === alias) ?? null;
26945
- }
26946
- async function updateHost(paths, alias, change) {
26947
- const hosts = await loadSshHosts(paths);
26948
- const index = hosts.findIndex((host) => host.alias === alias);
26949
- if (index < 0)
26950
- throw new Error(`No SSH host named ${alias}`);
26951
- const updated = sshHostSchema.parse(change(hosts[index]));
26952
- const next = [...hosts];
26953
- next[index] = updated;
26954
- if (updated.public_key !== hosts[index].public_key || updated.key_type !== hosts[index].key_type)
26955
- await writeKnownHosts(paths, updated);
26956
- await saveSshHosts(paths, next);
26957
- return updated;
26958
- }
26959
- async function repinSshHost(paths, alias, key, now = /* @__PURE__ */ new Date()) {
26960
- return await updateHost(paths, alias, (host) => ({ ...host, key_type: key.key_type, public_key: key.public_key, fingerprint: key.fingerprint, pinned_at: now.toISOString() }));
26961
- }
26962
- async function setSshHostProduction(paths, alias, production) {
26963
- return await updateHost(paths, alias, (host) => ({ ...host, production }));
26964
- }
26965
- async function removeSshHost(paths, alias) {
26966
- const hosts = await loadSshHosts(paths);
26967
- const host = hosts.find((entry) => entry.alias === alias);
26968
- if (!host)
26969
- return false;
26970
- await saveSshHosts(paths, hosts.filter((entry) => entry !== host));
26971
- await (0, import_promises12.unlink)(knownHostsPath(paths, host.resource_id)).catch(() => void 0);
26972
- return true;
26973
- }
26974
- function hostAddress(host) {
26975
- if (host.port === 22)
26976
- return host.host;
26977
- return host.host.includes(":") ? `[${host.host}]:${host.port}` : `${host.host}:${host.port}`;
26939
+ });
26940
+ var defaultReader = async (path) => (0, import_promises12.readFile)(path, "utf8").catch(() => null);
26941
+ var defaultCollectorSystem = {
26942
+ platform: (0, import_node_os4.platform)(),
26943
+ arch: (0, import_node_os4.arch)(),
26944
+ kernel: (0, import_node_os4.release)(),
26945
+ run: defaultRunner,
26946
+ readText: defaultReader,
26947
+ now: () => /* @__PURE__ */ new Date()
26948
+ };
26949
+ var SHORT = { timeoutMs: 1e4, maxBytes: 2 * 1024 * 1024 };
26950
+ var LIST = { timeoutMs: 45e3, maxBytes: 48 * 1024 * 1024 };
26951
+ var POWERSHELL = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
26952
+ var PS_PREFIX = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $ProgressPreference = 'SilentlyContinue'; ";
26953
+ var PS_OS = PS_PREFIX + "$o = Get-CimInstance Win32_OperatingSystem; $ubr = (Get-ItemProperty 'HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion' -ErrorAction SilentlyContinue).UBR; [pscustomobject]@{Caption=$o.Caption;Version=$o.Version;BuildNumber=$o.BuildNumber;OSArchitecture=$o.OSArchitecture;UBR=$ubr} | ConvertTo-Json -Compress";
26954
+ var PS_PROGRAMS = PS_PREFIX + "$p = 'HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKLM:\\Software\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*','HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'; Get-ItemProperty -Path $p -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -and -not $_.SystemComponent } | Select-Object DisplayName,DisplayVersion,Publisher,EstimatedSize,InstallDate | ConvertTo-Json -Compress";
26955
+ var PS_SERVICES = PS_PREFIX + "Get-Service | Select-Object Name,DisplayName,Status,StartType | ConvertTo-Json -Compress";
26956
+ var SOFTWARE_PROBES = Object.freeze([
26957
+ { key: "node", name: "Node.js", kind: "runtime", commands: [["node", "--version"], ["nodejs", "--version"]] },
26958
+ { key: "python", name: "Python", kind: "runtime", commands: [["python3", "--version"], ["python", "--version"]] },
26959
+ { key: "php", name: "PHP", kind: "runtime", commands: [["php", "--version"]] },
26960
+ { key: "ruby", name: "Ruby", kind: "runtime", commands: [["ruby", "--version"]] },
26961
+ { key: "go", name: "Go", kind: "runtime", commands: [["go", "version"]] },
26962
+ { key: "java", name: "Java", kind: "runtime", commands: [["java", "-version"]] },
26963
+ { key: "dotnet", name: ".NET", kind: "runtime", commands: [["dotnet", "--version"]] },
26964
+ { key: "deno", name: "Deno", kind: "runtime", commands: [["deno", "--version"]] },
26965
+ { key: "bun", name: "Bun", kind: "runtime", commands: [["bun", "--version"]] },
26966
+ { key: "rust", name: "Rust", kind: "runtime", commands: [["rustc", "--version"]] },
26967
+ { key: "nginx", name: "nginx", kind: "web_server", commands: [["nginx", "-v"]], posixOnly: true },
26968
+ { key: "apache", name: "Apache HTTP Server", kind: "web_server", commands: [["apache2ctl", "-v"], ["httpd", "-v"]], posixOnly: true },
26969
+ { key: "caddy", name: "Caddy", kind: "web_server", commands: [["caddy", "version"]] },
26970
+ { key: "haproxy", name: "HAProxy", kind: "web_server", commands: [["haproxy", "-v"]], posixOnly: true },
26971
+ { key: "traefik", name: "Traefik", kind: "web_server", commands: [["traefik", "version"]] },
26972
+ { key: "mysql", name: "MySQL", kind: "database", commands: [["mysql", "--version"]] },
26973
+ { key: "mariadb", name: "MariaDB", kind: "database", commands: [["mariadb", "--version"]] },
26974
+ { key: "postgresql", name: "PostgreSQL", kind: "database", commands: [["psql", "--version"]] },
26975
+ { key: "redis", name: "Redis", kind: "database", commands: [["redis-server", "--version"]] },
26976
+ { key: "mongodb", name: "MongoDB", kind: "database", commands: [["mongod", "--version"]] },
26977
+ { key: "sqlite", name: "SQLite", kind: "database", commands: [["sqlite3", "--version"]] },
26978
+ { key: "docker", name: "Docker", kind: "container_engine", commands: [["docker", "--version"]] },
26979
+ { key: "podman", name: "Podman", kind: "container_engine", commands: [["podman", "--version"]] },
26980
+ { key: "kubectl", name: "kubectl", kind: "container_engine", commands: [["kubectl", "version", "--client"]] },
26981
+ { key: "git", name: "Git", kind: "tool", commands: [["git", "--version"]] },
26982
+ { key: "openssl", name: "OpenSSL", kind: "tool", commands: [["openssl", "version"]] },
26983
+ { key: "openssh", name: "OpenSSH", kind: "tool", commands: [["ssh", "-V"]] },
26984
+ { key: "curl", name: "curl", kind: "tool", commands: [["curl", "--version"]] },
26985
+ { key: "bash", name: "Bash", kind: "tool", commands: [["bash", "--version"]], posixOnly: true },
26986
+ { key: "powershell", name: "PowerShell", kind: "tool", commands: [["pwsh", "--version"]] },
26987
+ { key: "composer", name: "Composer", kind: "tool", commands: [["composer", "--version", "--no-ansi"]], posixOnly: true },
26988
+ { key: "npm", name: "npm", kind: "tool", commands: [["npm", "--version"]], posixOnly: true },
26989
+ { key: "pnpm", name: "pnpm", kind: "tool", commands: [["pnpm", "--version"]], posixOnly: true },
26990
+ { key: "yarn", name: "Yarn", kind: "tool", commands: [["yarn", "--version"]], posixOnly: true },
26991
+ { key: "certbot", name: "Certbot", kind: "tool", commands: [["certbot", "--version"]], posixOnly: true }
26992
+ ]);
26993
+ function valid(schema, items, limit) {
26994
+ const out = [];
26995
+ for (const item of items) {
26996
+ if (out.length >= limit)
26997
+ break;
26998
+ const parsed = schema.safeParse(item);
26999
+ if (parsed.success)
27000
+ out.push(parsed.data);
27001
+ }
27002
+ return out;
26978
27003
  }
26979
- function inventoryResource2(host) {
26980
- return { resource_id: host.resource_id, kind: "ssh_host", label: host.alias, attrs: { production: host.production, address: hostAddress(host) } };
27004
+ async function pool(items, width, work) {
27005
+ let next = 0;
27006
+ await Promise.all(Array.from({ length: Math.min(width, items.length) }, async () => {
27007
+ while (next < items.length)
27008
+ await work(items[next++]);
27009
+ }));
26981
27010
  }
26982
-
26983
- // dist/ssh/exec.js
26984
- var DEFAULT_SSH_BINARIES = Object.freeze({ ssh: "/usr/bin/ssh", keyscan: "/usr/bin/ssh-keyscan" });
26985
- function sshBinariesFromEnv(env = process.env) {
26986
- const pick2 = (value, fallback) => value && (0, import_node_path13.isAbsolute)(value) ? value : fallback;
26987
- return { ssh: pick2(env.CONBRIDGE_SSH_BIN, DEFAULT_SSH_BINARIES.ssh), keyscan: pick2(env.CONBRIDGE_SSH_KEYSCAN_BIN, DEFAULT_SSH_BINARIES.keyscan) };
27011
+ var Collection = class {
27012
+ system;
27013
+ packages = [];
27014
+ software = [];
27015
+ services = [];
27016
+ containers = [];
27017
+ images = [];
27018
+ pods = [];
27019
+ coverage = [];
27020
+ constructor(system) {
27021
+ this.system = system;
27022
+ }
27023
+ /** Runs one collector command and records its coverage; returns the stdout only when the command succeeded. */
27024
+ async command(collector, file2, args, limits = SHORT, merge2 = false) {
27025
+ const started = Date.now();
27026
+ const result2 = await this.system.run(file2, args, limits);
27027
+ const status = result2.ok ? "ok" : result2.missing ? "unavailable" : result2.timedOut ? "timeout" : result2.denied ? "denied" : "failed";
27028
+ this.cover(collector, status, 0, Date.now() - started);
27029
+ if (!result2.ok)
27030
+ return null;
27031
+ return merge2 ? result2.stdout + "\n" + result2.stderr : result2.stdout;
27032
+ }
27033
+ cover(collector, status, count3, durationMs) {
27034
+ const existing = this.coverage.find((entry) => entry.collector === collector);
27035
+ if (existing)
27036
+ Object.assign(existing, { status, count: count3, duration_ms: Math.max(0, Math.round(durationMs)) });
27037
+ else
27038
+ this.coverage.push({ collector, status, count: count3, duration_ms: Math.max(0, Math.round(durationMs)) });
27039
+ }
27040
+ counted(collector, count3, limit) {
27041
+ const entry = this.coverage.find((e) => e.collector === collector);
27042
+ if (entry && entry.status === "ok") {
27043
+ entry.count = count3;
27044
+ if (count3 >= limit)
27045
+ entry.status = "truncated";
27046
+ }
27047
+ }
27048
+ };
27049
+ async function collectOs(c) {
27050
+ const { platform: platform2, arch: arch3, kernel } = c.system;
27051
+ if (platform2 === "linux") {
27052
+ const release2 = parseOsRelease(await c.system.readText("/etc/os-release") ?? await c.system.readText("/usr/lib/os-release") ?? "");
27053
+ const model = cleanModel(await c.system.readText("/proc/device-tree/model") ?? await c.system.readText("/sys/devices/virtual/dmi/id/product_name") ?? "");
27054
+ return {
27055
+ family: "linux",
27056
+ name: release2.prettyName ?? release2.name ?? "Linux",
27057
+ version: release2.versionId ?? release2.version ?? "",
27058
+ kernel,
27059
+ arch: arch3,
27060
+ ...release2.id ? { distro_id: release2.id } : {},
27061
+ ...release2.versionId ? { distro_version: release2.versionId } : {},
27062
+ ...release2.codename ? { distro_codename: release2.codename } : {},
27063
+ ...model ? { model } : {}
27064
+ };
27065
+ }
27066
+ if (platform2 === "darwin") {
27067
+ const vers = parseSwVers(await c.command("os", "sw_vers", []) ?? "");
27068
+ return {
27069
+ family: "darwin",
27070
+ name: `${vers.productName ?? "macOS"} ${vers.productVersion ?? ""}`.trim(),
27071
+ version: vers.productVersion ?? "",
27072
+ ...vers.buildVersion ? { build: vers.buildVersion } : {},
27073
+ kernel,
27074
+ arch: arch3
27075
+ };
27076
+ }
27077
+ if (platform2 === "win32") {
27078
+ const win = parseWindowsOs(await c.command("os", "powershell.exe", [...POWERSHELL, PS_OS]) ?? "");
27079
+ return win ? { family: "windows", name: win.caption, version: win.version, build: win.build, kernel, arch: win.arch } : { family: "windows", name: "Windows", version: kernel, kernel, arch: arch3 };
27080
+ }
27081
+ return { family: "other", name: platform2, version: kernel, kernel, arch: arch3 };
26988
27082
  }
26989
- function sshChildEnv(env = process.env) {
26990
- const child = {};
26991
- for (const key of ["PATH", "HOME", "USER", "LOGNAME", "SSH_AUTH_SOCK", "LANG", "TMPDIR"]) {
26992
- if (env[key] !== void 0)
26993
- child[key] = env[key];
27083
+ async function collectPackages(c) {
27084
+ const { platform: platform2 } = c.system;
27085
+ const add = (collector, items) => {
27086
+ c.packages.push(...items);
27087
+ c.counted(collector, items.length, INVENTORY_LIMITS.packages);
27088
+ };
27089
+ if (platform2 === "linux") {
27090
+ const dpkg = await c.command("dpkg", "dpkg-query", ["-W", "-f=${Package}\\t${Version}\\t${Architecture}\\t${Installed-Size}\\t${db:Status-Abbrev}\\t${source:Package}\\t${source:Version}\\n"], LIST);
27091
+ if (dpkg !== null)
27092
+ add("dpkg", parseDpkg(dpkg));
27093
+ else {
27094
+ const rpm = await c.command("rpm", "rpm", ["-qa", "--qf", "%{NAME}\\t%{EPOCH}\\t%{VERSION}\\t%{RELEASE}\\t%{ARCH}\\t%{SIZE}\\n"], LIST);
27095
+ if (rpm !== null)
27096
+ add("rpm", parseRpm(rpm));
27097
+ else {
27098
+ const apk = await c.command("apk", "apk", ["list", "--installed"], LIST);
27099
+ if (apk !== null)
27100
+ add("apk", parseApk(apk));
27101
+ else {
27102
+ const pacman = await c.command("pacman", "pacman", ["-Q"], LIST);
27103
+ if (pacman !== null)
27104
+ add("pacman", parsePacman(pacman));
27105
+ }
27106
+ }
27107
+ }
27108
+ const snap = await c.command("snap", "snap", ["list"], SHORT);
27109
+ if (snap !== null)
27110
+ add("snap", parseSnap(snap));
27111
+ } else if (platform2 === "darwin") {
27112
+ const formulae = await c.command("brew", "brew", ["list", "--versions"], LIST);
27113
+ if (formulae !== null)
27114
+ add("brew", parseBrewVersions(formulae, "brew"));
27115
+ const casks = await c.command("brew-cask", "brew", ["list", "--cask", "--versions"], LIST);
27116
+ if (casks !== null)
27117
+ add("brew-cask", parseBrewVersions(casks, "brew-cask"));
27118
+ const apps = await c.command("macos-apps", "system_profiler", ["SPApplicationsDataType", "-json", "-detailLevel", "mini"], { timeoutMs: 9e4, maxBytes: 64 * 1024 * 1024 });
27119
+ if (apps !== null)
27120
+ add("macos-apps", parseMacApps(apps));
27121
+ } else if (platform2 === "win32") {
27122
+ const programs = await c.command("windows-programs", "powershell.exe", [...POWERSHELL, PS_PROGRAMS], LIST);
27123
+ if (programs !== null)
27124
+ add("windows-programs", parseWindowsPrograms(programs));
26994
27125
  }
26995
- return child;
27126
+ const npm = platform2 === "win32" ? await c.command("npm-global", "cmd.exe", ["/d", "/s", "/c", "npm ls -g --depth=0 --json"], LIST) : await c.command("npm-global", "npm", ["ls", "-g", "--depth=0", "--json"], LIST);
27127
+ if (npm !== null)
27128
+ add("npm-global", parseNpmGlobal(npm));
26996
27129
  }
26997
- function runProcess(file2, args, options) {
27130
+ async function collectSoftware(c) {
27131
+ const probes = SOFTWARE_PROBES.filter((probe) => !(probe.posixOnly && c.system.platform === "win32"));
27132
+ const found = [];
26998
27133
  const started = Date.now();
26999
- return new Promise((resolve8) => {
27000
- const kept = { stdout: [], stderr: [] };
27001
- const totals = { stdout: 0, stderr: 0 };
27002
- let keptBytes = 0;
27003
- let truncated = false;
27004
- let timedOut = false;
27005
- let settled = false;
27006
- const child = (0, import_node_child_process7.spawn)(file2, [...args], { stdio: ["ignore", "pipe", "pipe"], env: options.env, shell: false });
27007
- const collect = (stream) => (chunk2) => {
27008
- totals[stream] += chunk2.length;
27009
- const room = options.maxBytes - keptBytes;
27010
- if (room <= 0) {
27011
- truncated = true;
27012
- return;
27134
+ await pool(probes, 4, async (probe) => {
27135
+ for (const [file2, ...args] of probe.commands) {
27136
+ const result2 = await c.system.run(file2, args, { timeoutMs: 8e3, maxBytes: 256 * 1024 });
27137
+ if (result2.missing)
27138
+ continue;
27139
+ const version6 = extractVersion(probe.key, `${result2.stdout}
27140
+ ${result2.stderr}`);
27141
+ if (version6) {
27142
+ found.push({ key: probe.key, name: probe.name, version: version6, kind: probe.kind });
27143
+ break;
27013
27144
  }
27014
- const piece = chunk2.length > room ? chunk2.subarray(0, room) : chunk2;
27015
- if (piece.length < chunk2.length)
27016
- truncated = true;
27017
- kept[stream].push(piece);
27018
- keptBytes += piece.length;
27019
- };
27020
- child.stdout.on("data", collect("stdout"));
27021
- child.stderr.on("data", collect("stderr"));
27022
- let killTimer;
27023
- const timer = setTimeout(() => {
27024
- timedOut = true;
27025
- child.kill("SIGTERM");
27026
- killTimer = setTimeout(() => child.kill("SIGKILL"), 2e3);
27027
- }, options.timeoutMs);
27028
- const finish = (exitCode, spawnError) => {
27029
- if (settled)
27030
- return;
27031
- settled = true;
27032
- clearTimeout(timer);
27033
- if (killTimer)
27034
- clearTimeout(killTimer);
27035
- resolve8({
27036
- exitCode,
27037
- timedOut,
27038
- truncated,
27039
- durationMs: Date.now() - started,
27040
- stdout: Buffer.concat(kept.stdout).toString("utf8"),
27041
- stderr: Buffer.concat(kept.stderr).toString("utf8"),
27042
- stdoutBytes: totals.stdout,
27043
- stderrBytes: totals.stderr,
27044
- ...spawnError !== void 0 ? { spawnError } : {}
27045
- });
27046
- };
27047
- child.on("error", (error63) => finish(null, error63.code ?? "SPAWN_FAILED"));
27048
- child.on("close", (code) => finish(code));
27145
+ }
27049
27146
  });
27147
+ found.sort((a, b) => SOFTWARE_PROBES.findIndex((p) => p.key === a.key) - SOFTWARE_PROBES.findIndex((p) => p.key === b.key));
27148
+ c.software.push(...found);
27149
+ c.cover("software", "ok", found.length, Date.now() - started);
27050
27150
  }
27051
- function keyscanType(type) {
27052
- if (type === "ssh-ed25519")
27053
- return "ed25519";
27054
- if (type === "ssh-rsa")
27055
- return "rsa";
27056
- return "ecdsa";
27151
+ async function collectServices(c) {
27152
+ const { platform: platform2 } = c.system;
27153
+ if (platform2 === "linux") {
27154
+ const units = await c.command("systemd", "systemctl", ["list-units", "--type=service", "--all", "--no-legend", "--plain", "--no-pager"], SHORT);
27155
+ if (units !== null) {
27156
+ const files = (await c.system.run("systemctl", ["list-unit-files", "--type=service", "--no-legend", "--no-pager"], SHORT)).stdout;
27157
+ const services = parseSystemd(units, files);
27158
+ c.services.push(...services);
27159
+ c.counted("systemd", services.length, INVENTORY_LIMITS.services);
27160
+ }
27161
+ } else if (platform2 === "darwin") {
27162
+ const launchd = await c.command("launchd", "launchctl", ["list"], SHORT);
27163
+ if (launchd !== null) {
27164
+ const items = parseLaunchctl(launchd);
27165
+ c.services.push(...items);
27166
+ c.counted("launchd", items.length, INVENTORY_LIMITS.services);
27167
+ }
27168
+ const brew = await c.command("brew-services", "brew", ["services", "list", "--json"], SHORT);
27169
+ if (brew !== null) {
27170
+ const items = parseBrewServices(brew);
27171
+ c.services.push(...items);
27172
+ c.counted("brew-services", items.length, INVENTORY_LIMITS.services);
27173
+ }
27174
+ } else if (platform2 === "win32") {
27175
+ const win = await c.command("windows-services", "powershell.exe", [...POWERSHELL, PS_SERVICES], LIST);
27176
+ if (win !== null) {
27177
+ const items = parseWindowsServices(win);
27178
+ c.services.push(...items);
27179
+ c.counted("windows-services", items.length, INVENTORY_LIMITS.services);
27180
+ }
27181
+ }
27057
27182
  }
27058
- function hostKeyAlgorithms(type) {
27059
- return type === "ssh-rsa" ? "rsa-sha2-512,rsa-sha2-256" : type;
27183
+ async function collectContainers(c) {
27184
+ let ps = await c.command("docker", "docker", ["ps", "-a", "--no-trunc", "--size", "--format", "{{json .}}"], LIST);
27185
+ if (ps === null && c.coverage.find((e) => e.collector === "docker")?.status === "timeout") {
27186
+ ps = await c.command("docker", "docker", ["ps", "-a", "--no-trunc", "--format", "{{json .}}"], SHORT);
27187
+ }
27188
+ if (ps !== null) {
27189
+ const items = parseDockerPs(ps);
27190
+ c.containers.push(...items);
27191
+ c.counted("docker", items.length, INVENTORY_LIMITS.containers);
27192
+ const images = await c.command("docker-images", "docker", ["image", "ls", "--no-trunc", "--format", "{{json .}}"], SHORT);
27193
+ if (images !== null) {
27194
+ const list = parseDockerImages(images);
27195
+ c.images.push(...list);
27196
+ c.counted("docker-images", list.length, INVENTORY_LIMITS.images);
27197
+ }
27198
+ }
27199
+ const podman = await c.command("podman", "podman", ["ps", "-a", "--size", "--format", "json"], LIST);
27200
+ if (podman !== null) {
27201
+ const items = parsePodmanPs(podman);
27202
+ c.containers.push(...items);
27203
+ c.counted("podman", items.length, INVENTORY_LIMITS.containers);
27204
+ const images = await c.command("podman-images", "podman", ["images", "--format", "json"], SHORT);
27205
+ if (images !== null) {
27206
+ const list = parsePodmanImages(images);
27207
+ c.images.push(...list);
27208
+ c.counted("podman-images", list.length, INVENTORY_LIMITS.images);
27209
+ }
27210
+ const pods = await c.command("podman-pods", "podman", ["pod", "ps", "--format", "json"], SHORT);
27211
+ if (pods !== null) {
27212
+ const list = parsePodmanPods(pods);
27213
+ c.pods.push(...list);
27214
+ c.counted("podman-pods", list.length, INVENTORY_LIMITS.pods);
27215
+ }
27216
+ }
27217
+ const kube = await c.command("kubernetes", "kubectl", [
27218
+ "get",
27219
+ "pods",
27220
+ "-A",
27221
+ "--no-headers",
27222
+ "--request-timeout=10s",
27223
+ "-o",
27224
+ "custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,PHASE:.status.phase,NODE:.spec.nodeName,CREATED:.metadata.creationTimestamp,READY:.status.containerStatuses[*].ready,RESTARTS:.status.containerStatuses[*].restartCount"
27225
+ ], { timeoutMs: 2e4, maxBytes: 8 * 1024 * 1024 });
27226
+ if (kube !== null) {
27227
+ const list = parseKubectlPods(kube);
27228
+ c.pods.push(...list);
27229
+ c.counted("kubernetes", list.length, INVENTORY_LIMITS.pods);
27230
+ }
27231
+ for (const image of c.images) {
27232
+ if (image.containers !== void 0)
27233
+ continue;
27234
+ const ref = `${image.repository}:${image.tag}`;
27235
+ const count3 = c.containers.filter((ct) => ct.engine === image.engine && (ct.image === ref || image.tag === "latest" && ct.image === image.repository || ct.image.startsWith(image.id))).length;
27236
+ image.containers = count3;
27237
+ }
27060
27238
  }
27061
- function sshConfigPath(path) {
27062
- if (/["\n\r]/.test(path))
27063
- throw new Error("Path cannot be used in an ssh option");
27064
- const escaped = path.replace(/%/g, "%%");
27065
- return /\s/.test(escaped) ? `"${escaped}"` : escaped;
27239
+ async function collectInventory(system = defaultCollectorSystem) {
27240
+ const c = new Collection(system);
27241
+ const os = await collectOs(c);
27242
+ await collectPackages(c);
27243
+ await collectSoftware(c);
27244
+ await collectServices(c);
27245
+ await collectContainers(c);
27246
+ const snapshot = {
27247
+ schema: 1,
27248
+ collected_at: system.now().toISOString(),
27249
+ agent_version: AGENT_VERSION,
27250
+ os: inventoryOsSchema.safeParse(os).success ? os : { family: "other", name: system.platform, version: "", arch: system.arch },
27251
+ packages: valid(inventoryPackageSchema, c.packages, INVENTORY_LIMITS.packages),
27252
+ software: valid(inventorySoftwareSchema, c.software, INVENTORY_LIMITS.software),
27253
+ services: valid(inventoryServiceSchema, c.services, INVENTORY_LIMITS.services),
27254
+ containers: valid(inventoryContainerSchema, c.containers, INVENTORY_LIMITS.containers),
27255
+ images: valid(inventoryImageSchema, c.images, INVENTORY_LIMITS.images),
27256
+ pods: valid(inventoryPodSchema, c.pods, INVENTORY_LIMITS.pods),
27257
+ coverage: valid(inventoryCoverageSchema, c.coverage, INVENTORY_LIMITS.coverage)
27258
+ };
27259
+ return inventorySnapshotSchema.parse(snapshot);
27066
27260
  }
27067
- var KEYSCAN_TIMEOUT_S = 10;
27068
- async function scanHostKeys(binaries, target, options = {}) {
27069
- const types = options.types ?? ["ssh-ed25519", "ecdsa-sha2-nistp256", "ssh-rsa"];
27070
- const args = ["-T", String(KEYSCAN_TIMEOUT_S), "-p", String(target.port), "-t", [...new Set(types.map(keyscanType))].join(","), "--", target.host];
27071
- const result2 = await runProcess(binaries.keyscan, args, { timeoutMs: (KEYSCAN_TIMEOUT_S + 5) * 1e3, maxBytes: 64 * 1024, env: sshChildEnv(options.env) });
27072
- if (result2.spawnError)
27073
- return { keys: [], error: "ssh-keyscan could not be started (" + result2.spawnError + ")" };
27074
- const keys = parseKeyscan(result2.stdout);
27075
- return { keys, error: keys.length === 0 ? result2.timedOut ? "Host did not answer in time" : "Host returned no usable host key" : null };
27261
+
27262
+ // dist/relay.js
27263
+ var HEARTBEAT_INTERVAL_MS = 2e4;
27264
+ var AUTH_TIMEOUT_MS = 2e4;
27265
+ var CLOSE_POLICY_VIOLATION = 4008;
27266
+ function relayUrl(gatewayUrl, deviceUuid2) {
27267
+ const url2 = new URL("/v1/agent/connect", gatewayUrl);
27268
+ url2.protocol = url2.protocol === "https:" ? "wss:" : "ws:";
27269
+ url2.search = new URLSearchParams({ device: deviceUuid2 }).toString();
27270
+ return url2.toString();
27076
27271
  }
27077
- function buildSshArgs(paths, host, command2) {
27078
- const options = [
27079
- "BatchMode=yes",
27080
- "StrictHostKeyChecking=yes",
27081
- `UserKnownHostsFile=${sshConfigPath(knownHostsPath(paths, host.resource_id))}`,
27082
- "GlobalKnownHostsFile=/dev/null",
27083
- `HostKeyAlias=${hostKeyAlias(host)}`,
27084
- `HostKeyAlgorithms=${hostKeyAlgorithms(host.key_type)}`,
27085
- "UpdateHostKeys=no",
27086
- "CheckHostIP=no",
27087
- "PasswordAuthentication=no",
27088
- "KbdInteractiveAuthentication=no",
27089
- "ProxyCommand=none",
27090
- "PermitLocalCommand=no",
27091
- "ForwardAgent=no",
27092
- "ForwardX11=no",
27093
- "ClearAllForwardings=yes",
27094
- "ControlMaster=no",
27095
- "ControlPath=none",
27096
- "RequestTTY=no",
27097
- "ConnectTimeout=15",
27098
- "ServerAliveInterval=15",
27099
- "ServerAliveCountMax=3",
27100
- "LogLevel=ERROR",
27101
- ...host.identity !== void 0 ? ["IdentitiesOnly=yes"] : []
27102
- ];
27103
- return [
27104
- "-F",
27105
- "/dev/null",
27106
- ...options.flatMap((option) => ["-o", option]),
27107
- ...host.identity !== void 0 ? ["-i", host.identity] : [],
27108
- "-p",
27109
- String(host.port),
27110
- ...host.user !== void 0 ? ["-l", host.user] : [],
27111
- "-n",
27112
- "-T",
27113
- "--",
27114
- host.host,
27115
- command2
27116
- ];
27272
+ async function signRelayChallenge(key, deviceUuid2, nonce, connectionId) {
27273
+ const message = agentAuthMessage({ deviceUuid: deviceUuid2, nonce, connectionId });
27274
+ return toBase64Url(await key.sign(new TextEncoder().encode(message)));
27117
27275
  }
27118
- function isHostKeyFailure(result2) {
27119
- return result2.exitCode === 255 && result2.stdoutBytes === 0 && /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED|No (?:ED25519|ECDSA|RSA) host key is known/i.test(result2.stderr);
27276
+ var RelaySession = class {
27277
+ #options;
27278
+ #logger;
27279
+ #state = "challenge";
27280
+ #connectionEpoch = 0;
27281
+ #queue = Promise.resolve();
27282
+ constructor(options) {
27283
+ this.#options = options;
27284
+ this.#logger = options.logger ?? silentLogger;
27285
+ }
27286
+ get state() {
27287
+ return this.#state;
27288
+ }
27289
+ get identity() {
27290
+ const { tenant_id, user_id, device_uuid } = this.#options.identity;
27291
+ return { tenant_id, user_id, device_uuid };
27292
+ }
27293
+ /** Feed one incoming text frame; frames are processed strictly in order. */
27294
+ onMessage(text4) {
27295
+ const next = this.#queue.then(() => this.#process(text4));
27296
+ this.#queue = next.catch(() => void 0);
27297
+ return next;
27298
+ }
27299
+ #fail(reason) {
27300
+ if (this.#state === "closed")
27301
+ return;
27302
+ this.#logger.warn("closing relay connection", { reason });
27303
+ this.#state = "closed";
27304
+ this.#options.close(CLOSE_POLICY_VIOLATION, reason);
27305
+ }
27306
+ markClosed() {
27307
+ this.#state = "closed";
27308
+ }
27309
+ async #process(text4) {
27310
+ if (this.#state === "closed")
27311
+ return;
27312
+ if (this.#state === "challenge" || this.#state === "auth_sent") {
27313
+ let frame;
27314
+ try {
27315
+ frame = JSON.parse(text4);
27316
+ } catch {
27317
+ return this.#fail("invalid pre-auth frame");
27318
+ }
27319
+ if (this.#state === "challenge")
27320
+ return this.#onChallenge(frame);
27321
+ return this.#onAuthOk(frame);
27322
+ }
27323
+ let envelope;
27324
+ try {
27325
+ envelope = decodeEnvelope(text4);
27326
+ } catch (error63) {
27327
+ this.#logger.warn("ignoring invalid envelope", { code: error63 instanceof ProtocolDecodeError ? error63.code : "INVALID_MESSAGE" });
27328
+ return;
27329
+ }
27330
+ const identity = this.#options.identity;
27331
+ if (envelope.tenant_id !== identity.tenant_id || envelope.user_id !== identity.user_id || envelope.device_uuid !== identity.device_uuid) {
27332
+ return this.#fail("envelope identity mismatch");
27333
+ }
27334
+ switch (envelope.kind) {
27335
+ case "DISPATCH":
27336
+ void this.#options.dispatcher.handle(envelope);
27337
+ return;
27338
+ case "CANCEL":
27339
+ void this.#options.dispatcher.cancel(envelope).catch((error63) => {
27340
+ this.#logger.error("cancel handling failed", { task_id: envelope.task_id, error: error63 instanceof Error ? error63.name : "unknown" });
27341
+ });
27342
+ return;
27343
+ case "ERROR":
27344
+ this.#logger.warn("relay error", { code: envelope.code, message: envelope.safe_message });
27345
+ return;
27346
+ case "MONITOR_CONFIG":
27347
+ this.#options.onMonitorConfig?.({ enabled: envelope.enabled, interval_s: envelope.interval_s });
27348
+ return;
27349
+ case "SOFTWARE_INVENTORY_CONFIG":
27350
+ this.#options.onInventoryConfig?.({
27351
+ enabled: envelope.enabled,
27352
+ interval_s: envelope.interval_s,
27353
+ ...envelope.ssh_hosts !== void 0 ? { ssh_hosts: envelope.ssh_hosts } : {}
27354
+ });
27355
+ return;
27356
+ case "SOFTWARE_INVENTORY_REQUEST":
27357
+ this.#options.onInventoryRequest?.(envelope.request_id);
27358
+ return;
27359
+ default:
27360
+ return;
27361
+ }
27362
+ }
27363
+ async #onChallenge(frame) {
27364
+ const parsed = relayChallengeSchema.safeParse(frame);
27365
+ if (!parsed.success)
27366
+ return this.#fail("expected CHALLENGE");
27367
+ const now = (this.#options.now ?? Date.now)();
27368
+ if (parsed.data.expires_at_ms <= now)
27369
+ return this.#fail("challenge expired");
27370
+ const deviceUuid2 = this.#options.identity.device_uuid;
27371
+ const signature = await signRelayChallenge(this.#options.key, deviceUuid2, parsed.data.nonce, parsed.data.connection_id);
27372
+ this.#state = "auth_sent";
27373
+ this.#options.send(JSON.stringify({ kind: "AUTH", device_uuid: deviceUuid2, connection_id: parsed.data.connection_id, signature }));
27374
+ }
27375
+ #onAuthOk(frame) {
27376
+ const parsed = relayAuthOkSchema.safeParse(frame);
27377
+ if (!parsed.success)
27378
+ return this.#fail("expected AUTH_OK");
27379
+ const identity = this.#options.identity;
27380
+ if (parsed.data.tenant_id !== identity.tenant_id || parsed.data.user_id !== identity.user_id || parsed.data.device_uuid !== identity.device_uuid) {
27381
+ return this.#fail("AUTH_OK identity mismatch");
27382
+ }
27383
+ this.#connectionEpoch = parsed.data.connection_epoch;
27384
+ this.#state = "ready";
27385
+ this.#sendEnvelope(buildEnvelope(this.identity, "HELLO", null, {
27386
+ agent_id: identity.device_uuid,
27387
+ supported_versions: [...SUPPORTED_VERSIONS],
27388
+ capabilities: [...DESKTOP_CAPABILITIES, ...SSH_CAPABILITIES, ...SHELL_CAPABILITIES]
27389
+ }));
27390
+ this.sendInventory();
27391
+ this.#options.onReady?.();
27392
+ }
27393
+ #sendEnvelope(envelope) {
27394
+ if (this.#state !== "ready")
27395
+ return;
27396
+ this.#options.send(encode3(envelope));
27397
+ }
27398
+ sendInventory() {
27399
+ const roots = this.#options.config().roots.map(({ root_id, label, writable }) => ({ root_id, label, writable }));
27400
+ const resources = this.#options.resources?.().map((resource) => ({ ...resource, ...resource.attrs ? { attrs: { ...resource.attrs } } : {} }));
27401
+ this.#sendEnvelope(buildEnvelope(this.identity, "INVENTORY", null, { roots, ...resources && resources.length > 0 ? { resources } : {}, agent_version: AGENT_VERSION }));
27402
+ }
27403
+ sendHeartbeat() {
27404
+ this.#sendEnvelope(buildEnvelope(this.identity, "HEARTBEAT", null, { connection_epoch: this.#connectionEpoch, status: "ONLINE" }));
27405
+ }
27406
+ /** One resource sample (telemetry, never a task); dropped silently unless authenticated. */
27407
+ sendMetrics(body) {
27408
+ if (this.#state !== "ready")
27409
+ return;
27410
+ this.#sendEnvelope(buildEnvelope(this.identity, "METRICS", null, body));
27411
+ }
27412
+ /** The parts of one software inventory run (telemetry, never a task); dropped silently unless authenticated. */
27413
+ sendInventoryParts(parts) {
27414
+ if (this.#state !== "ready")
27415
+ return;
27416
+ for (const part of parts)
27417
+ this.#sendEnvelope(buildEnvelope(this.identity, "SOFTWARE_INVENTORY_PART", null, part));
27418
+ }
27419
+ /** Forward a pre-encoded task frame (ACK/CHUNK/RESULT) if authenticated. */
27420
+ sendFrame(frame) {
27421
+ if (this.#state !== "ready")
27422
+ throw new Error("Relay session is not authenticated");
27423
+ this.#options.send(frame);
27424
+ }
27425
+ };
27426
+ function backoffDelay(attempt, options) {
27427
+ const cap = Math.min(options.maxMs, options.baseMs * 2 ** Math.min(attempt, 16));
27428
+ return Math.floor(cap / 2 + (options.random ?? Math.random)() * (cap / 2));
27120
27429
  }
27121
27430
 
27122
27431
  // dist/ssh/handler.js
@@ -27842,6 +28151,8 @@ var AgentRunner = class {
27842
28151
  #logger;
27843
28152
  #dispatcher;
27844
28153
  #shell;
28154
+ /** Runs the constant SSH inventory script on one pinned host (ADR SECURITY_INTELLIGENCE 11.6). */
28155
+ #sshInventoryExec;
27845
28156
  #config = null;
27846
28157
  #sshHosts = [];
27847
28158
  #session = null;
@@ -27857,6 +28168,8 @@ var AgentRunner = class {
27857
28168
  this.#options = options;
27858
28169
  this.#logger = options.logger ?? silentLogger;
27859
28170
  this.#shell = new ShellExecutor({ logger: this.#logger });
28171
+ const binaries = options.sshBinaries ?? sshBinariesFromEnv();
28172
+ this.#sshInventoryExec = options.inventory?.sshExec ?? defaultSshInventoryExec(sshPaths(options.paths.dir), binaries);
27860
28173
  const dispatcherOptions = {
27861
28174
  shell: this.#shell,
27862
28175
  identity: options.identity,
@@ -27875,7 +28188,7 @@ var AgentRunner = class {
27875
28188
  logger: this.#logger,
27876
28189
  protectedPaths: options.protectedPaths ?? protectedAgentPaths(options.paths.dir),
27877
28190
  sshHosts: () => this.#sshHosts,
27878
- ssh: new SshExecutor({ paths: sshPaths(options.paths.dir), binaries: options.sshBinaries ?? sshBinariesFromEnv(), logger: this.#logger })
28191
+ ssh: new SshExecutor({ paths: sshPaths(options.paths.dir), binaries, logger: this.#logger })
27879
28192
  };
27880
28193
  this.#dispatcher = new Dispatcher(options.confirmWrite ? { ...dispatcherOptions, confirmWrite: options.confirmWrite } : dispatcherOptions);
27881
28194
  }
@@ -28034,6 +28347,8 @@ var AgentRunner = class {
28034
28347
  onSent: (at) => {
28035
28348
  this.#inventorySentAtMs = at;
28036
28349
  },
28350
+ sshHosts: () => this.#sshHosts,
28351
+ collectSshHost: (host) => collectSshHostInventory(host, this.#sshInventoryExec),
28037
28352
  send: (parts) => session.sendInventoryParts(parts),
28038
28353
  logger: this.#logger
28039
28354
  });