pinggy 0.6.9 → 0.6.11

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.
@@ -0,0 +1,1947 @@
1
+ import {
2
+ DaemonHost,
3
+ IPC_VERSION,
4
+ ShutdownStatus
5
+ } from "./chunk-MKGD2QAI.js";
6
+ import {
7
+ errorMessage,
8
+ getLocalAddress,
9
+ getVersion,
10
+ printer_default
11
+ } from "./chunk-HTIWY3O5.js";
12
+ import {
13
+ logger
14
+ } from "./chunk-DGAH7UVX.js";
15
+ import {
16
+ ensurePinggyConfigDir,
17
+ getDaemonInfoPath,
18
+ getDaemonLockPath,
19
+ getDaemonLogPath,
20
+ getPinggyConfigDir,
21
+ getUpdateLockPath,
22
+ getUpdateStatePath
23
+ } from "./chunk-WFHMERT3.js";
24
+
25
+ // src/update/updateState.ts
26
+ import fs from "fs";
27
+ import path from "path";
28
+ var NUMBER_FIELDS = [
29
+ "lastCheckEpochSeconds",
30
+ "lastAttemptEpochSeconds",
31
+ "latestSeenEpochSeconds",
32
+ "lastCheckFailureNoticeEpochSeconds",
33
+ "failedAttempts",
34
+ "deferredIpcVersion",
35
+ "cachedVersionSizeBytes",
36
+ "cachedVersionModifiedMillis"
37
+ ];
38
+ var STRING_FIELDS = [
39
+ "latestVersion",
40
+ "lastNoticeVersion",
41
+ "lastDaemonNoticeVersion",
42
+ "rolledBackFromVersion",
43
+ "updatedFromVersion",
44
+ "updatedToVersion",
45
+ "failedVersion",
46
+ "deferredVersion",
47
+ "declinedInstallPath",
48
+ "declinedInstallVersion",
49
+ "cachedVersionPath",
50
+ "cachedVersion"
51
+ ];
52
+ function nowEpochSeconds() {
53
+ return Math.floor(Date.now() / 1e3);
54
+ }
55
+ function keepKnownFields(parsed) {
56
+ const state = {};
57
+ for (const field of NUMBER_FIELDS) {
58
+ const value = parsed[field];
59
+ if (typeof value === "number" && Number.isFinite(value)) state[field] = value;
60
+ }
61
+ for (const field of STRING_FIELDS) {
62
+ const value = parsed[field];
63
+ if (typeof value === "string") state[field] = value;
64
+ }
65
+ return state;
66
+ }
67
+ function readUpdateState() {
68
+ try {
69
+ const parsed = JSON.parse(fs.readFileSync(getUpdateStatePath(), "utf-8"));
70
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
71
+ return keepKnownFields(parsed);
72
+ } catch {
73
+ return {};
74
+ }
75
+ }
76
+ function writeUpdateState(patch) {
77
+ try {
78
+ ensurePinggyConfigDir();
79
+ const statePath = getUpdateStatePath();
80
+ const temporaryPath = path.join(path.dirname(statePath), `update.json.${process.pid}.tmp`);
81
+ fs.writeFileSync(temporaryPath, JSON.stringify({ ...readUpdateState(), ...patch }, null, 2), "utf-8");
82
+ fs.renameSync(temporaryPath, statePath);
83
+ return true;
84
+ } catch (error) {
85
+ logger.debug("Could not write update.json", { error: errorMessage(error) });
86
+ return false;
87
+ }
88
+ }
89
+ function recordLatestVersion(version) {
90
+ const changed = readUpdateState().latestVersion !== version;
91
+ return writeUpdateState(changed ? { latestVersion: version, latestSeenEpochSeconds: nowEpochSeconds() } : { latestVersion: version });
92
+ }
93
+ function moveDeclinedInstallToVersion(execPath, newVersion) {
94
+ if (readUpdateState().declinedInstallPath?.toLowerCase() === execPath.toLowerCase()) {
95
+ writeUpdateState({ declinedInstallVersion: newVersion });
96
+ }
97
+ }
98
+
99
+ // src/devices/terminal/nodePtyRuntime.ts
100
+ import crypto from "crypto";
101
+ import fs2 from "fs";
102
+ import path2 from "path";
103
+ import { createRequire } from "module";
104
+ var require2 = createRequire(import.meta.url);
105
+ var PACKAGE_NAME = "node-pty";
106
+ var NATIVE_FILE = "pty.node";
107
+ var SPAWN_HELPER_FILE = "spawn-helper";
108
+ var EXECUTABLE_MODE = 493;
109
+ var EXECUTE_BITS = 73;
110
+ var RUNTIME_DIR_NAME = "runtime";
111
+ var ASAR_ARCHIVE_SUFFIX = ".asar";
112
+ var HASH_LENGTH = 12;
113
+ var NATIVE_DIRECTORIES = [
114
+ path2.join("build", "Release"),
115
+ path2.join("prebuilds", `${process.platform}-${process.arch}`)
116
+ ];
117
+ function isPackagedBinary() {
118
+ return Boolean(process.pkg);
119
+ }
120
+ function isInsideAsarArchive(packageRoot) {
121
+ if (!process.versions.electron) return false;
122
+ return packageRoot.split(path2.sep).some((segment) => segment.endsWith(ASAR_ARCHIVE_SUFFIX));
123
+ }
124
+ function resolveNodePtyRoot() {
125
+ const resolvedRoot = path2.dirname(require2.resolve(`${PACKAGE_NAME}/package.json`));
126
+ if (!isPackagedBinary() && !isInsideAsarArchive(resolvedRoot)) return resolvedRoot;
127
+ return unpackNodePty(resolvedRoot);
128
+ }
129
+ function requireNodePty(packageRoot) {
130
+ return require2(packageRoot);
131
+ }
132
+ function spawnHelperPaths(packageRoot, platform = process.platform) {
133
+ if (platform !== "darwin") return [];
134
+ return NATIVE_DIRECTORIES.map((directory) => path2.join(packageRoot, directory, SPAWN_HELPER_FILE));
135
+ }
136
+ function hasExecutableSpawnHelper(packageRoot, platform = process.platform) {
137
+ const helpers = spawnHelperPaths(packageRoot, platform);
138
+ if (helpers.length === 0) return true;
139
+ return helpers.some((helper) => {
140
+ try {
141
+ const stat = fs2.statSync(helper);
142
+ return stat.isFile() && (stat.mode & EXECUTE_BITS) !== 0;
143
+ } catch {
144
+ return false;
145
+ }
146
+ });
147
+ }
148
+ function makeSpawnHelperExecutable(packageRoot) {
149
+ for (const helper of spawnHelperPaths(packageRoot)) {
150
+ try {
151
+ const stat = fs2.statSync(helper);
152
+ if ((stat.mode & EXECUTE_BITS) === 0) {
153
+ fs2.chmodSync(helper, EXECUTABLE_MODE);
154
+ }
155
+ } catch {
156
+ }
157
+ }
158
+ }
159
+ function unpackNodePty(snapshotRoot) {
160
+ const unpackedRoot = unpackedRootPath(snapshotRoot);
161
+ if (isCommittedCopy(unpackedRoot)) return unpackedRoot;
162
+ const stagingRoot = `${unpackedRoot}.${process.pid}`;
163
+ fs2.rmSync(stagingRoot, { recursive: true, force: true });
164
+ try {
165
+ copyRuntimeFiles(snapshotRoot, stagingRoot);
166
+ makeSpawnHelperExecutable(stagingRoot);
167
+ fs2.renameSync(stagingRoot, unpackedRoot);
168
+ } catch (error) {
169
+ fs2.rmSync(stagingRoot, { recursive: true, force: true });
170
+ if (!isCommittedCopy(unpackedRoot)) throw error;
171
+ }
172
+ return unpackedRoot;
173
+ }
174
+ function isCommittedCopy(unpackedRoot) {
175
+ return fs2.existsSync(path2.join(unpackedRoot, "package.json"));
176
+ }
177
+ function unpackedRootPath(snapshotRoot) {
178
+ const version = readPackageVersion(snapshotRoot);
179
+ const hash = addonHash(snapshotRoot);
180
+ const directoryName = `${PACKAGE_NAME}-${version}-${process.platform}-${process.arch}-${hash}`;
181
+ return path2.join(getPinggyConfigDir(), RUNTIME_DIR_NAME, directoryName);
182
+ }
183
+ function readPackageVersion(packageRoot) {
184
+ const manifest = JSON.parse(fs2.readFileSync(path2.join(packageRoot, "package.json"), "utf8"));
185
+ return String(manifest.version);
186
+ }
187
+ function addonHash(snapshotRoot) {
188
+ const hash = crypto.createHash("sha256");
189
+ for (const directory of nativeDirectories(snapshotRoot)) {
190
+ hash.update(`${directory}\0`);
191
+ hash.update(fs2.readFileSync(path2.join(snapshotRoot, directory, NATIVE_FILE)));
192
+ }
193
+ return hash.digest("hex").slice(0, HASH_LENGTH);
194
+ }
195
+ function nativeDirectories(packageRoot) {
196
+ return NATIVE_DIRECTORIES.filter((directory) => fs2.existsSync(path2.join(packageRoot, directory, NATIVE_FILE)));
197
+ }
198
+ function copyRuntimeFiles(sourceRoot, targetRoot) {
199
+ fs2.mkdirSync(targetRoot, { recursive: true });
200
+ copyFile(path2.join(sourceRoot, "package.json"), path2.join(targetRoot, "package.json"));
201
+ copyDirectory(path2.join(sourceRoot, "lib"), path2.join(targetRoot, "lib"));
202
+ for (const directory of nativeDirectories(sourceRoot)) {
203
+ copyDirectory(path2.join(sourceRoot, directory), path2.join(targetRoot, directory));
204
+ }
205
+ }
206
+ function copyDirectory(sourceDirectory, targetDirectory) {
207
+ fs2.mkdirSync(targetDirectory, { recursive: true });
208
+ for (const entry of fs2.readdirSync(sourceDirectory, { withFileTypes: true })) {
209
+ const source = path2.join(sourceDirectory, entry.name);
210
+ const target = path2.join(targetDirectory, entry.name);
211
+ if (entry.isDirectory()) {
212
+ copyDirectory(source, target);
213
+ continue;
214
+ }
215
+ copyFile(source, target);
216
+ }
217
+ }
218
+ function copyFile(source, target) {
219
+ fs2.writeFileSync(target, fs2.readFileSync(source));
220
+ }
221
+
222
+ // src/update/installKind.ts
223
+ import fs3 from "fs";
224
+ import os from "os";
225
+ import path3 from "path";
226
+ var InstallKind = {
227
+ WindowsWritable: "windows-writable",
228
+ WindowsReadOnly: "windows-read-only",
229
+ UnixLayout: "unix-layout",
230
+ UnixPlainFile: "unix-plain-file",
231
+ UnixLoose: "unix-loose",
232
+ Npm: "npm",
233
+ DevCheckout: "dev-checkout"
234
+ };
235
+ var NODE_MODULES_SEGMENT = "node_modules";
236
+ var WINDOWS_INSTALL_COMMAND = "irm https://pinggy.io/install.ps1 | iex";
237
+ var UNIX_INSTALL_COMMAND = "curl -fsSL https://pinggy.io/install.sh | sh";
238
+ var NPM_INSTALL_COMMAND = "npm i -g pinggy";
239
+ var NPM_UNINSTALL_COMMAND = "npm uninstall -g pinggy";
240
+ function hasPathSegment(candidate, segment) {
241
+ return candidate !== null && candidate.split(/[\\/]/).includes(segment);
242
+ }
243
+ function unixLayoutPaths(homeRealPath) {
244
+ const root = path3.posix.join(homeRealPath, ".pinggy");
245
+ const binDirectory = path3.posix.join(root, "bin");
246
+ return {
247
+ binDirectory,
248
+ link: path3.posix.join(binDirectory, "pinggy"),
249
+ versionsDirectory: path3.posix.join(root, "versions")
250
+ };
251
+ }
252
+ function detectInstallKind(probe) {
253
+ if (!probe.isPackaged) {
254
+ if (probe.isElectron) return InstallKind.Npm;
255
+ return hasPathSegment(probe.scriptRealPath, NODE_MODULES_SEGMENT) ? InstallKind.Npm : InstallKind.DevCheckout;
256
+ }
257
+ if (probe.platform === "win32") {
258
+ return probe.directoryIsWritable() ? InstallKind.WindowsWritable : InstallKind.WindowsReadOnly;
259
+ }
260
+ const layout = unixLayoutPaths(probe.homeRealPath);
261
+ if (probe.execPath.startsWith(`${layout.versionsDirectory}/`)) return InstallKind.UnixLayout;
262
+ return probe.execPath === layout.link ? InstallKind.UnixPlainFile : InstallKind.UnixLoose;
263
+ }
264
+ function canReplaceItself(kind) {
265
+ return kind === InstallKind.WindowsWritable || kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
266
+ }
267
+ function backgroundInstallKind(kind, execPath, homeRealPath) {
268
+ if (kind !== InstallKind.WindowsWritable) return kind;
269
+ const relative = path3.win32.relative(homeRealPath, execPath);
270
+ const insideProfile = relative !== "" && !relative.startsWith("..") && !path3.win32.isAbsolute(relative);
271
+ return insideProfile ? kind : InstallKind.WindowsReadOnly;
272
+ }
273
+ function installCommandFor(platform) {
274
+ return platform === "win32" ? WINDOWS_INSTALL_COMMAND : UNIX_INSTALL_COMMAND;
275
+ }
276
+ function realPathOr(candidate, fallback) {
277
+ try {
278
+ return fs3.realpathSync(candidate);
279
+ } catch {
280
+ return fallback;
281
+ }
282
+ }
283
+ function canCreateFileNextTo(filePath) {
284
+ const probePath = path3.join(path3.dirname(filePath), `.pinggy-write-test-${process.pid}`);
285
+ try {
286
+ fs3.closeSync(fs3.openSync(probePath, "wx"));
287
+ fs3.unlinkSync(probePath);
288
+ return true;
289
+ } catch {
290
+ return false;
291
+ }
292
+ }
293
+ function createInstallProbe() {
294
+ const execPath = process.execPath;
295
+ const scriptPath = process.argv[1];
296
+ return {
297
+ isPackaged: isPackagedBinary(),
298
+ isElectron: Boolean(process.versions.electron),
299
+ platform: process.platform,
300
+ execPath,
301
+ scriptRealPath: scriptPath ? realPathOr(scriptPath, scriptPath) : null,
302
+ homeRealPath: realPathOr(os.homedir(), os.homedir()),
303
+ directoryIsWritable: () => canCreateFileNextTo(execPath)
304
+ };
305
+ }
306
+
307
+ // src/daemon/lifecycle/bootId.ts
308
+ import fs4 from "fs";
309
+ import os2 from "os";
310
+ import { execFileSync } from "child_process";
311
+ var LINUX_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id";
312
+ var MACOS_SYSCTL_PATH = "/usr/sbin/sysctl";
313
+ var MACOS_BOOT_ID_KEY = "kern.bootsessionuuid";
314
+ var SYSCTL_TIMEOUT_MILLIS = 2e3;
315
+ var BOOT_TIME_TOLERANCE_MILLIS = 6e4;
316
+ var machineBootIdSources = {
317
+ platform: process.platform,
318
+ readFile: (filePath) => fs4.readFileSync(filePath, "utf-8"),
319
+ runCommand: (command, args) => execFileSync(command, args, {
320
+ encoding: "utf-8",
321
+ stdio: ["ignore", "pipe", "ignore"],
322
+ timeout: SYSCTL_TIMEOUT_MILLIS
323
+ })
324
+ };
325
+ var cachedBootId;
326
+ function readBootId(sources) {
327
+ try {
328
+ switch (sources.platform) {
329
+ case "linux":
330
+ return nonEmpty(sources.readFile(LINUX_BOOT_ID_PATH));
331
+ case "darwin":
332
+ return nonEmpty(sources.runCommand(MACOS_SYSCTL_PATH, ["-n", MACOS_BOOT_ID_KEY]));
333
+ default:
334
+ return null;
335
+ }
336
+ } catch {
337
+ return null;
338
+ }
339
+ }
340
+ function currentBootId() {
341
+ if (cachedBootId === void 0) {
342
+ cachedBootId = readBootId(machineBootIdSources);
343
+ }
344
+ return cachedBootId;
345
+ }
346
+ function startedInEarlierBoot(recordedBootId, startedAt, bootId = currentBootId()) {
347
+ if (typeof recordedBootId === "string" && recordedBootId.length > 0 && bootId) {
348
+ return recordedBootId !== bootId;
349
+ }
350
+ return startedBeforeBoot(startedAt);
351
+ }
352
+ function startedBeforeBoot(startedAt) {
353
+ const startedAtMillis = Date.parse(startedAt);
354
+ const bootMillis = Date.now() - os2.uptime() * 1e3;
355
+ return Number.isNaN(startedAtMillis) || startedAtMillis < bootMillis - BOOT_TIME_TOLERANCE_MILLIS;
356
+ }
357
+ function nonEmpty(text) {
358
+ const trimmed = text.trim();
359
+ return trimmed.length > 0 ? trimmed : null;
360
+ }
361
+
362
+ // src/update/latestRelease.ts
363
+ import http from "http";
364
+ import https from "https";
365
+ var DEFAULT_RELEASES_URL = "https://github.com/Pinggy-io/cli-js/releases";
366
+ var RELEASES_URL_OVERRIDE_ENV = "PINGGY_UPDATE_RELEASES_URL";
367
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost"]);
368
+ var TAG_PATTERN = /^v\d+\.\d+\.\d+$/;
369
+ var VERSION_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
370
+ var USER_AGENT = "pinggy-cli";
371
+ var NPM_REGISTRY_LATEST_URL = "https://registry.npmjs.org/pinggy/latest";
372
+ var SHA256SUMS_FILE = "SHA256SUMS";
373
+ function loopbackReleasesOverride() {
374
+ const value = process.env[RELEASES_URL_OVERRIDE_ENV];
375
+ if (!value) return null;
376
+ try {
377
+ const url = new URL(value);
378
+ if (url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname)) return value.replace(/\/+$/, "");
379
+ } catch {
380
+ }
381
+ logger.debug(`Ignoring ${RELEASES_URL_OVERRIDE_ENV}. It accepts a loopback http URL only`);
382
+ return null;
383
+ }
384
+ function getReleasesUrl() {
385
+ return loopbackReleasesOverride() ?? DEFAULT_RELEASES_URL;
386
+ }
387
+ function isAllowedRequestUrl(url) {
388
+ if (url.protocol === "https:") return true;
389
+ return url.protocol === "http:" && LOOPBACK_HOSTS.has(url.hostname) && loopbackReleasesOverride() !== null;
390
+ }
391
+ function requestModuleFor(url) {
392
+ if (!isAllowedRequestUrl(url)) throw new Error(`Refused a request to ${url.protocol}//${url.host}`);
393
+ return url.protocol === "https:" ? https : http;
394
+ }
395
+ function headWithoutRedirect(target, timeoutMillis) {
396
+ return new Promise((resolve, reject) => {
397
+ const url = new URL(target);
398
+ const request = requestModuleFor(url).request(
399
+ url,
400
+ { method: "HEAD", headers: { "User-Agent": USER_AGENT } },
401
+ (response) => {
402
+ clearTimeout(timer);
403
+ response.resume();
404
+ resolve({ status: response.statusCode ?? 0, location: response.headers.location });
405
+ }
406
+ );
407
+ const timer = setTimeout(
408
+ () => request.destroy(new Error(`No answer within ${timeoutMillis} ms`)),
409
+ timeoutMillis
410
+ );
411
+ request.on("error", (error) => {
412
+ clearTimeout(timer);
413
+ reject(error);
414
+ });
415
+ request.end();
416
+ });
417
+ }
418
+ async function resolveLatestTag({ timeoutMillis }) {
419
+ const { status, location } = await headWithoutRedirect(`${getReleasesUrl()}/latest`, timeoutMillis);
420
+ const tag = location?.split("?")[0].split("/").filter(Boolean).pop();
421
+ if (status < 300 || status >= 400 || !tag || !TAG_PATTERN.test(tag)) {
422
+ throw new Error(`Unexpected answer for the latest release: status ${status}`);
423
+ }
424
+ return tag;
425
+ }
426
+ async function isReleaseComplete(tag, { timeoutMillis }) {
427
+ const { status } = await headWithoutRedirect(`${getReleasesUrl()}/download/${tag}/${SHA256SUMS_FILE}`, timeoutMillis);
428
+ if (status >= 200 && status < 400) return true;
429
+ if (status === 404) return false;
430
+ throw new Error(`Unexpected answer for ${SHA256SUMS_FILE}: status ${status}`);
431
+ }
432
+ function getJson(target, timeoutMillis) {
433
+ return new Promise((resolve, reject) => {
434
+ const url = new URL(target);
435
+ const request = requestModuleFor(url).get(url, { headers: { "User-Agent": USER_AGENT } }, (response) => {
436
+ const chunks = [];
437
+ response.on("data", (chunk) => chunks.push(chunk));
438
+ response.on("error", reject);
439
+ response.on("end", () => {
440
+ clearTimeout(timer);
441
+ try {
442
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf-8")));
443
+ } catch (error) {
444
+ reject(error instanceof Error ? error : new Error(String(error)));
445
+ }
446
+ });
447
+ });
448
+ const timer = setTimeout(
449
+ () => request.destroy(new Error(`No answer within ${timeoutMillis} ms`)),
450
+ timeoutMillis
451
+ );
452
+ request.on("error", (error) => {
453
+ clearTimeout(timer);
454
+ reject(error);
455
+ });
456
+ });
457
+ }
458
+ async function resolveLatestNpmVersion({ timeoutMillis }, registryUrl = NPM_REGISTRY_LATEST_URL) {
459
+ const version = (await getJson(registryUrl, timeoutMillis))?.version;
460
+ if (typeof version !== "string" || parseVersion(version) === null) {
461
+ throw new Error("Unexpected answer from the npm registry");
462
+ }
463
+ return version;
464
+ }
465
+ function versionFromTag(tag) {
466
+ return tag.replace(/^v/, "");
467
+ }
468
+ function parseVersion(text) {
469
+ const match = VERSION_PATTERN.exec(text);
470
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
471
+ }
472
+ function isNewerVersion(candidate, current) {
473
+ const candidateParts = parseVersion(candidate);
474
+ const currentParts = parseVersion(current);
475
+ if (!candidateParts || !currentParts) return false;
476
+ for (let index = 0; index < candidateParts.length; index++) {
477
+ if (candidateParts[index] !== currentParts[index]) return candidateParts[index] > currentParts[index];
478
+ }
479
+ return false;
480
+ }
481
+
482
+ // src/update/binaryUpdater.ts
483
+ import crypto2 from "crypto";
484
+ import { execFile } from "child_process";
485
+ import fs5 from "fs";
486
+ import path4 from "path";
487
+ var UpdateErrorCode = {
488
+ NotReady: "not-ready",
489
+ Network: "network",
490
+ NoDiskSpace: "no-disk-space",
491
+ Incomplete: "incomplete",
492
+ Checksum: "checksum",
493
+ BadBinary: "bad-binary",
494
+ RenameFailed: "rename-failed",
495
+ PostSwapFailed: "post-swap-failed",
496
+ RestoreFailed: "restore-failed",
497
+ NothingToRollBack: "nothing-to-roll-back"
498
+ };
499
+ var BAD_RELEASE_CODES = /* @__PURE__ */ new Set([
500
+ UpdateErrorCode.Incomplete,
501
+ UpdateErrorCode.Checksum,
502
+ UpdateErrorCode.BadBinary,
503
+ UpdateErrorCode.PostSwapFailed
504
+ ]);
505
+ var UpdateError = class extends Error {
506
+ constructor(code, message, options = {}) {
507
+ super(message);
508
+ this.name = "UpdateError";
509
+ this.code = code;
510
+ this.countsAsBadRelease = options.countsAsBadRelease ?? BAD_RELEASE_CODES.has(code);
511
+ }
512
+ };
513
+ var BINARY_RUN_TIMEOUT_MILLIS = 3e4;
514
+ var DEVICE_TOKEN_ENV = "DEVICE_AGENT_TOKEN";
515
+ var VERSION_LINE = /^Pinggy CLI version: (\d+\.\d+\.\d+)\s*$/m;
516
+ function environmentWithoutDeviceToken() {
517
+ const environment = { ...process.env };
518
+ delete environment[DEVICE_TOKEN_ENV];
519
+ return environment;
520
+ }
521
+ function pinggyBinaryRunOptions() {
522
+ return {
523
+ timeout: BINARY_RUN_TIMEOUT_MILLIS,
524
+ windowsHide: true,
525
+ env: { ...environmentWithoutDeviceToken(), PKG_EXECPATH: "" }
526
+ };
527
+ }
528
+ var runPinggyBinary = (binaryPath, args) => new Promise((resolve, reject) => {
529
+ execFile(binaryPath, args, pinggyBinaryRunOptions(), (error, stdout) => {
530
+ if (error) reject(error);
531
+ else resolve(String(stdout));
532
+ });
533
+ });
534
+ async function readBinaryVersion(binaryPath, runBinary) {
535
+ const match = VERSION_LINE.exec(await runBinary(binaryPath, ["--version"]));
536
+ if (!match) throw new Error(`${binaryPath} printed no version`);
537
+ return match[1];
538
+ }
539
+ async function readBinaryIpcVersion(binaryPath, runBinary) {
540
+ const version = Number((await runBinary(binaryPath, ["--_ipc-version"])).trim());
541
+ if (!Number.isInteger(version)) throw new UpdateError(UpdateErrorCode.BadBinary, "The new binary reported no IPC version.");
542
+ return version;
543
+ }
544
+ var ASSET_NAMES = {
545
+ "linux-x64": "pinggy-linux-x64",
546
+ "linux-arm64": "pinggy-linux-arm64",
547
+ "darwin-x64": "pinggy-macos-x64",
548
+ "darwin-arm64": "pinggy-macos-arm64",
549
+ "win32-x64": "pinggy-win-x64.exe",
550
+ "win32-arm64": "pinggy-win-arm64.exe"
551
+ };
552
+ function assetNameFor(platform, architecture) {
553
+ const name = ASSET_NAMES[`${platform}-${architecture}`];
554
+ if (!name) throw new Error(`No release asset for ${platform}-${architecture}`);
555
+ return name;
556
+ }
557
+ var MAX_REDIRECTS = 5;
558
+ var IDLE_TIMEOUT_MILLIS = 3e4;
559
+ var FREE_SPACE_MARGIN_BYTES = 50 * 1024 * 1024;
560
+ var WINDOWS_FREE_SPACE_FACTOR = 2;
561
+ var UNIX_FREE_SPACE_FACTOR = 1;
562
+ var EXECUTABLE_MODE2 = 493;
563
+ var USER_AGENT2 = "pinggy-cli";
564
+ var SUMS_LINE = /^([0-9a-f]{64}) {2}(.+)$/;
565
+ function realFreeBytes(directory) {
566
+ try {
567
+ const stats = fs5.statfsSync(directory);
568
+ return Number(stats.bavail) * Number(stats.bsize);
569
+ } catch {
570
+ return null;
571
+ }
572
+ }
573
+ var defaultDownloadDependencies = {
574
+ runBinary: runPinggyBinary,
575
+ freeBytes: realFreeBytes,
576
+ idleTimeoutMillis: IDLE_TIMEOUT_MILLIS
577
+ };
578
+ function getFollowingRedirects(target, idleTimeoutMillis, hopsLeft = MAX_REDIRECTS) {
579
+ return new Promise((resolve, reject) => {
580
+ const url = new URL(target);
581
+ const request = requestModuleFor(url).get(url, { headers: { "User-Agent": USER_AGENT2 } }, (response) => {
582
+ const status = response.statusCode ?? 0;
583
+ const location = response.headers.location;
584
+ if (status < 300 || status >= 400 || !location) {
585
+ resolve(response);
586
+ return;
587
+ }
588
+ response.resume();
589
+ if (hopsLeft === 0) {
590
+ reject(new Error("too many redirects"));
591
+ return;
592
+ }
593
+ getFollowingRedirects(new URL(location, url).href, idleTimeoutMillis, hopsLeft - 1).then(resolve, reject);
594
+ });
595
+ request.setTimeout(idleTimeoutMillis, () => request.destroy(new Error("no data arrived in time")));
596
+ request.on("error", reject);
597
+ });
598
+ }
599
+ function unchanged(running) {
600
+ return `pinggy ${running} is unchanged.`;
601
+ }
602
+ function networkError(reason, running) {
603
+ return new UpdateError(UpdateErrorCode.Network, `The download failed: ${reason}. ${unchanged(running)}`);
604
+ }
605
+ function notReady(tag) {
606
+ return new UpdateError(UpdateErrorCode.NotReady, `Release ${tag} is not ready. Try again later.`);
607
+ }
608
+ async function open(url, running, idleTimeoutMillis) {
609
+ try {
610
+ return await getFollowingRedirects(url, idleTimeoutMillis);
611
+ } catch (error) {
612
+ throw networkError(errorMessage(error), running);
613
+ }
614
+ }
615
+ function readBody(response) {
616
+ return new Promise((resolve, reject) => {
617
+ const chunks = [];
618
+ response.on("data", (chunk) => chunks.push(chunk));
619
+ response.on("end", () => resolve(Buffer.concat(chunks)));
620
+ response.on("error", reject);
621
+ });
622
+ }
623
+ function hashForAsset(sums, assetName) {
624
+ for (const line of sums.split("\n")) {
625
+ const match = SUMS_LINE.exec(line.trim());
626
+ if (match && match[2] === assetName) return match[1];
627
+ }
628
+ return null;
629
+ }
630
+ async function readExpectedHash(request, releaseUrl, dependencies) {
631
+ const { tag, assetName, runningVersion } = request;
632
+ const response = await open(`${releaseUrl}/${SHA256SUMS_FILE}`, runningVersion, dependencies.idleTimeoutMillis);
633
+ if (response.statusCode === 404) {
634
+ response.resume();
635
+ throw notReady(tag);
636
+ }
637
+ if (response.statusCode !== 200) {
638
+ response.resume();
639
+ throw networkError(`status ${response.statusCode}`, runningVersion);
640
+ }
641
+ let sumsBytes;
642
+ try {
643
+ sumsBytes = await readBody(response);
644
+ } catch (error) {
645
+ throw networkError(errorMessage(error), runningVersion);
646
+ }
647
+ const expectedHash = hashForAsset(sumsBytes.toString("utf-8"), assetName);
648
+ if (!expectedHash) throw notReady(tag);
649
+ return expectedHash;
650
+ }
651
+ function writeFully(fileDescriptor, chunk) {
652
+ let written = 0;
653
+ while (written < chunk.length) {
654
+ written += fs5.writeSync(fileDescriptor, chunk, written);
655
+ }
656
+ }
657
+ function receiveBody(response, fileDescriptor) {
658
+ return new Promise((resolve, reject) => {
659
+ const hash = crypto2.createHash("sha256");
660
+ let byteCount = 0;
661
+ response.on("data", (chunk) => {
662
+ try {
663
+ writeFully(fileDescriptor, chunk);
664
+ } catch (error) {
665
+ response.destroy();
666
+ reject(error);
667
+ return;
668
+ }
669
+ hash.update(chunk);
670
+ byteCount += chunk.length;
671
+ });
672
+ response.on("end", () => resolve({ byteCount, sha256: hash.digest("hex") }));
673
+ response.on("error", reject);
674
+ response.on("close", () => reject(new Error("the connection closed early")));
675
+ });
676
+ }
677
+ function noDiskSpace(running) {
678
+ return new UpdateError(UpdateErrorCode.NoDiskSpace, `Not enough free disk space for the update. ${unchanged(running)}`);
679
+ }
680
+ function ensureFreeSpace(request, contentLength, dependencies) {
681
+ const factor = request.assetName.endsWith(".exe") ? WINDOWS_FREE_SPACE_FACTOR : UNIX_FREE_SPACE_FACTOR;
682
+ const freeBytes = dependencies.freeBytes(path4.dirname(request.tempPath));
683
+ if (freeBytes !== null && freeBytes < contentLength * factor + FREE_SPACE_MARGIN_BYTES) {
684
+ throw noDiskSpace(request.runningVersion);
685
+ }
686
+ }
687
+ function bodyFailure(error, running) {
688
+ if (error.code === "ENOSPC") return noDiskSpace(running);
689
+ return new UpdateError(
690
+ UpdateErrorCode.Incomplete,
691
+ `The download was incomplete. ${unchanged(running)}`,
692
+ { countsAsBadRelease: false }
693
+ );
694
+ }
695
+ async function receiveVerifiedFile(response, request, expectedHash, contentLength) {
696
+ const { tempPath, runningVersion } = request;
697
+ const fileDescriptor = fs5.openSync(tempPath, "w", EXECUTABLE_MODE2);
698
+ try {
699
+ const body = await receiveBody(response, fileDescriptor).catch((error) => {
700
+ throw bodyFailure(error, runningVersion);
701
+ });
702
+ if (body.byteCount !== contentLength) {
703
+ throw new UpdateError(UpdateErrorCode.Incomplete, `The download was incomplete. ${unchanged(runningVersion)}`);
704
+ }
705
+ if (body.sha256 !== expectedHash) {
706
+ throw new UpdateError(UpdateErrorCode.Checksum, `The download failed its checksum. ${unchanged(runningVersion)}`);
707
+ }
708
+ fs5.fsyncSync(fileDescriptor);
709
+ if (process.platform !== "win32") fs5.fchmodSync(fileDescriptor, EXECUTABLE_MODE2);
710
+ } finally {
711
+ fs5.closeSync(fileDescriptor);
712
+ }
713
+ }
714
+ async function downloadAsset(request, releaseUrl, expectedHash, dependencies) {
715
+ const { assetName, runningVersion } = request;
716
+ const response = await open(`${releaseUrl}/${assetName}`, runningVersion, dependencies.idleTimeoutMillis);
717
+ if (response.statusCode !== 200) {
718
+ response.resume();
719
+ throw networkError(`status ${response.statusCode}`, runningVersion);
720
+ }
721
+ const contentLength = Number(response.headers["content-length"]);
722
+ if (!Number.isInteger(contentLength)) {
723
+ response.destroy();
724
+ throw new UpdateError(UpdateErrorCode.Incomplete, `The download was incomplete. ${unchanged(runningVersion)}`);
725
+ }
726
+ try {
727
+ ensureFreeSpace(request, contentLength, dependencies);
728
+ } catch (error) {
729
+ response.destroy();
730
+ throw error;
731
+ }
732
+ await receiveVerifiedFile(response, request, expectedHash, contentLength);
733
+ }
734
+ async function ensureBinaryRuns(request, dependencies) {
735
+ const expected = versionFromTag(request.tag);
736
+ const reported = await readBinaryVersion(request.tempPath, dependencies.runBinary).catch(() => null);
737
+ if (reported !== expected) {
738
+ throw new UpdateError(
739
+ UpdateErrorCode.BadBinary,
740
+ `The new binary did not run correctly. ${unchanged(request.runningVersion)}`
741
+ );
742
+ }
743
+ }
744
+ function removeQuietly(filePath) {
745
+ fs5.rmSync(filePath, { force: true });
746
+ }
747
+ async function downloadAndVerify(request, dependencies = defaultDownloadDependencies) {
748
+ const releaseUrl = `${getReleasesUrl()}/download/${request.tag}`;
749
+ try {
750
+ const expectedHash = await readExpectedHash(request, releaseUrl, dependencies);
751
+ await downloadAsset(request, releaseUrl, expectedHash, dependencies);
752
+ await ensureBinaryRuns(request, dependencies);
753
+ } catch (error) {
754
+ removeQuietly(request.tempPath);
755
+ throw error;
756
+ }
757
+ }
758
+
759
+ // src/update/windowsSwap.ts
760
+ import fs8 from "fs";
761
+ import path7 from "path";
762
+
763
+ // src/daemon/lifecycle/daemonManager.ts
764
+ import os4 from "os";
765
+ import fs7 from "fs";
766
+ import { spawn } from "child_process";
767
+
768
+ // src/daemon/lifecycle/serviceInstaller.ts
769
+ import os3 from "os";
770
+ import fs6 from "fs";
771
+ import path6 from "path";
772
+ import { execSync, execFileSync as execFileSync2 } from "child_process";
773
+
774
+ // src/daemon/lifecycle/servicePaths.ts
775
+ import path5 from "path";
776
+ var SERVICE_LABEL = "io.pinggy.agent";
777
+ var SYSTEMD_SERVICE_NAME = "pinggy";
778
+ function installerBinaryPath(platform, home, env) {
779
+ if (platform === "win32") {
780
+ const localAppData = env.LOCALAPPDATA || path5.win32.join(home, "AppData", "Local");
781
+ return path5.win32.join(localAppData, "Pinggy", "bin", "pinggy.exe");
782
+ }
783
+ return path5.posix.join(home, ".pinggy", "bin", "pinggy");
784
+ }
785
+ function systemdServicePath(home) {
786
+ return path5.posix.join(home, ".config", "systemd", "user", `${SYSTEMD_SERVICE_NAME}.service`);
787
+ }
788
+ function launchdPlistPath(home) {
789
+ return path5.posix.join(home, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
790
+ }
791
+ function autostartFilePath(platform, home) {
792
+ if (platform === "linux") return systemdServicePath(home);
793
+ if (platform === "darwin") return launchdPlistPath(home);
794
+ return null;
795
+ }
796
+
797
+ // src/daemon/lifecycle/serviceInstaller.ts
798
+ var SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
799
+ function realPath(p) {
800
+ try {
801
+ return fs6.realpathSync(p);
802
+ } catch {
803
+ return p;
804
+ }
805
+ }
806
+ function serviceProgramPath(ctx) {
807
+ if (ctx.platform === "win32") return ctx.execPath;
808
+ const kind = detectInstallKind({
809
+ isPackaged: ctx.isPkg,
810
+ isElectron: false,
811
+ platform: ctx.platform,
812
+ execPath: ctx.execPath,
813
+ scriptRealPath: null,
814
+ homeRealPath: realPath(ctx.home),
815
+ directoryIsWritable: () => false
816
+ });
817
+ const inLayout = kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
818
+ return inLayout ? installerBinaryPath(ctx.platform, ctx.home, ctx.env) : ctx.execPath;
819
+ }
820
+ function isInstallerBinary(ctx) {
821
+ const actual = realPath(ctx.execPath);
822
+ const expected = realPath(installerBinaryPath(ctx.platform, ctx.home, ctx.env));
823
+ if (ctx.platform === "win32") return actual.toLowerCase() === expected.toLowerCase();
824
+ return actual === expected;
825
+ }
826
+ function installerFix(platform) {
827
+ return [
828
+ "pinggy can only run as a service when it is installed with the Pinggy installer.",
829
+ "Install it, then run this command again:",
830
+ ` ${installCommandFor(platform)}`,
831
+ " pinggy daemon service-install"
832
+ ].join("\n");
833
+ }
834
+ function npmInstallerFix(platform) {
835
+ return [
836
+ "The npm version of pinggy cannot run as a service.",
837
+ "Remove it, install pinggy with the Pinggy installer, then run this command again:",
838
+ ` ${NPM_UNINSTALL_COMMAND}`,
839
+ ` ${installCommandFor(platform)}`,
840
+ " pinggy daemon service-install"
841
+ ].join("\n");
842
+ }
843
+ function installedCopyFix(installedPath) {
844
+ return [
845
+ "This pinggy is not the installed one. Run this command with the installed copy:",
846
+ ` ${installedPath} daemon service-install`
847
+ ].join("\n");
848
+ }
849
+ function serviceInstallRefusal(ctx, fileExists = fs6.existsSync) {
850
+ if (!ctx.isPkg) return npmInstallerFix(ctx.platform);
851
+ if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
852
+ const installedPath = installerBinaryPath(ctx.platform, ctx.home, ctx.env);
853
+ if (fileExists(installedPath)) return installedCopyFix(installedPath);
854
+ return installerFix(ctx.platform);
855
+ }
856
+ function printInstalled() {
857
+ printer_default.success("pinggy now starts automatically when this computer starts.");
858
+ }
859
+ function printUninstalled() {
860
+ printer_default.success("pinggy no longer starts automatically when this computer starts.");
861
+ }
862
+ function printNotInstalled() {
863
+ printer_default.print("pinggy is not set to start automatically.");
864
+ }
865
+ var QUIET = { stdio: ["ignore", "ignore", "pipe"] };
866
+ function toolError(err) {
867
+ const stderr = err.stderr?.toString().trim();
868
+ return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
869
+ }
870
+ function getSystemdServicePath() {
871
+ return systemdServicePath(os3.homedir());
872
+ }
873
+ function generateSystemdUnit(program) {
874
+ const execStart = `${program} --_daemon-child`;
875
+ return `[Unit]
876
+ Description=Pinggy Tunnel Daemon
877
+ After=network-online.target
878
+ Wants=network-online.target
879
+
880
+ [Service]
881
+ Type=simple
882
+ ExecStart=${execStart}
883
+ Restart=on-failure
884
+ RestartSec=5
885
+
886
+ [Install]
887
+ WantedBy=default.target
888
+ `;
889
+ }
890
+ function installSystemd(program) {
891
+ const servicePath = getSystemdServicePath();
892
+ const dir = path6.dirname(servicePath);
893
+ fs6.mkdirSync(dir, { recursive: true });
894
+ fs6.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
895
+ execSync("systemctl --user daemon-reload", QUIET);
896
+ execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`, QUIET);
897
+ execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`, QUIET);
898
+ logger.info("systemd user service installed", { servicePath });
899
+ printInstalled();
900
+ enableLinger(os3.userInfo().username);
901
+ }
902
+ function lingerEnabled(username) {
903
+ try {
904
+ const output = execFileSync2("loginctl", ["show-user", username, "--property=Linger"], {
905
+ encoding: "utf-8",
906
+ stdio: ["ignore", "pipe", "ignore"]
907
+ });
908
+ return output.trim() === "Linger=yes";
909
+ } catch {
910
+ return false;
911
+ }
912
+ }
913
+ function enableLinger(username) {
914
+ if (lingerEnabled(username)) return;
915
+ try {
916
+ execFileSync2("loginctl", ["--no-ask-password", "enable-linger", username], QUIET);
917
+ logger.info("systemd lingering enabled", { username });
918
+ } catch (err) {
919
+ logger.warn("loginctl enable-linger failed", { error: errorMessage(err) });
920
+ printer_default.print(`pinggy starts when ${username} signs in. To start it before anyone signs in, run: loginctl enable-linger ${username}`);
921
+ }
922
+ }
923
+ function uninstallSystemd() {
924
+ const servicePath = getSystemdServicePath();
925
+ try {
926
+ execSync(`systemctl --user stop ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
927
+ execSync(`systemctl --user disable ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
928
+ } catch {
929
+ }
930
+ if (fs6.existsSync(servicePath)) {
931
+ fs6.unlinkSync(servicePath);
932
+ execSync("systemctl --user daemon-reload", QUIET);
933
+ logger.info("systemd user service removed", { servicePath });
934
+ printUninstalled();
935
+ } else {
936
+ printNotInstalled();
937
+ }
938
+ }
939
+ function getLaunchdPlistPath() {
940
+ return launchdPlistPath(os3.homedir());
941
+ }
942
+ function generateLaunchdPlist(program) {
943
+ const allArgs = [program, "--_daemon-child"];
944
+ const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
945
+ return `<?xml version="1.0" encoding="UTF-8"?>
946
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
947
+ "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
948
+ <plist version="1.0">
949
+ <dict>
950
+ <key>Label</key>
951
+ <string>${SERVICE_LABEL}</string>
952
+ <key>ProgramArguments</key>
953
+ <array>
954
+ ${programArgs}
955
+ </array>
956
+ <key>RunAtLoad</key>
957
+ <true/>
958
+ <key>KeepAlive</key>
959
+ <false/>
960
+ </dict>
961
+ </plist>
962
+ `;
963
+ }
964
+ function installLaunchd(program) {
965
+ const plistPath = getLaunchdPlistPath();
966
+ const dir = path6.dirname(plistPath);
967
+ fs6.mkdirSync(dir, { recursive: true });
968
+ fs6.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
969
+ const uid = process.getuid?.() ?? 501;
970
+ try {
971
+ execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
972
+ } catch {
973
+ }
974
+ loadLaunchdPlist(uid, plistPath);
975
+ logger.info("launchd agent installed", { plistPath });
976
+ printInstalled();
977
+ }
978
+ function loadLaunchdPlist(uid, plistPath) {
979
+ try {
980
+ execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
981
+ } catch {
982
+ try {
983
+ execSync(`launchctl load -w ${plistPath}`);
984
+ } catch {
985
+ }
986
+ }
987
+ }
988
+ function uninstallLaunchd() {
989
+ const plistPath = getLaunchdPlistPath();
990
+ const uid = process.getuid?.() ?? 501;
991
+ try {
992
+ execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
993
+ } catch {
994
+ try {
995
+ execSync(`launchctl unload ${plistPath} 2>/dev/null || true`);
996
+ } catch {
997
+ }
998
+ }
999
+ if (fs6.existsSync(plistPath)) {
1000
+ fs6.unlinkSync(plistPath);
1001
+ logger.info("launchd agent removed", { plistPath });
1002
+ printUninstalled();
1003
+ } else {
1004
+ printNotInstalled();
1005
+ }
1006
+ }
1007
+ var WINDOWS_TASK_NAME = "PinggyDaemon";
1008
+ function escapeXml(value) {
1009
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1010
+ }
1011
+ function getWindowsUserId() {
1012
+ const user = process.env.USERNAME || os3.userInfo().username;
1013
+ const domain = process.env.USERDOMAIN;
1014
+ return domain ? `${domain}\\${user}` : user;
1015
+ }
1016
+ function generateTaskXml(program, userId) {
1017
+ const user = escapeXml(userId);
1018
+ return `<?xml version="1.0" encoding="UTF-16"?>
1019
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
1020
+ <Triggers>
1021
+ <LogonTrigger>
1022
+ <Enabled>true</Enabled>
1023
+ <UserId>${user}</UserId>
1024
+ </LogonTrigger>
1025
+ </Triggers>
1026
+ <Principals>
1027
+ <Principal id="Author">
1028
+ <UserId>${user}</UserId>
1029
+ <LogonType>InteractiveToken</LogonType>
1030
+ <RunLevel>LeastPrivilege</RunLevel>
1031
+ </Principal>
1032
+ </Principals>
1033
+ <Settings>
1034
+ <Hidden>true</Hidden>
1035
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
1036
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
1037
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
1038
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
1039
+ <RestartOnFailure>
1040
+ <Interval>PT1M</Interval>
1041
+ <Count>3</Count>
1042
+ </RestartOnFailure>
1043
+ </Settings>
1044
+ <Actions>
1045
+ <Exec>
1046
+ <Command>${escapeXml(program)}</Command>
1047
+ <Arguments>daemon start</Arguments>
1048
+ </Exec>
1049
+ </Actions>
1050
+ </Task>`;
1051
+ }
1052
+ function createWindowsTask(program) {
1053
+ const xml = generateTaskXml(program, getWindowsUserId());
1054
+ const tmpPath = path6.join(os3.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
1055
+ fs6.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
1056
+ try {
1057
+ execFileSync2("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
1058
+ } finally {
1059
+ try {
1060
+ fs6.unlinkSync(tmpPath);
1061
+ } catch {
1062
+ }
1063
+ }
1064
+ }
1065
+ function windowsTaskExists() {
1066
+ try {
1067
+ execFileSync2("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
1068
+ return true;
1069
+ } catch {
1070
+ return false;
1071
+ }
1072
+ }
1073
+ function isElevated() {
1074
+ try {
1075
+ return /S-1-16-(12288|16384)\b/.test(execFileSync2("whoami", ["/groups"], { encoding: "utf-8" }));
1076
+ } catch {
1077
+ return false;
1078
+ }
1079
+ }
1080
+ function windowsTaskError(action, undo, err) {
1081
+ if (windowsTaskExists() && !isElevated()) {
1082
+ return `Could not ${action}. It was set up from an Administrator terminal. Run this command from an Administrator terminal to ${undo}.`;
1083
+ }
1084
+ return `Could not ${action}: ${toolError(err)}`;
1085
+ }
1086
+ function installWindows(program) {
1087
+ try {
1088
+ createWindowsTask(program);
1089
+ execFileSync2("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], QUIET);
1090
+ } catch (err) {
1091
+ printer_default.error(windowsTaskError("set pinggy to start automatically", "change it", err));
1092
+ process.exit(1);
1093
+ }
1094
+ logger.info("Scheduled task installed", { task: WINDOWS_TASK_NAME });
1095
+ printInstalled();
1096
+ }
1097
+ async function uninstallWindows() {
1098
+ if (!windowsTaskExists()) {
1099
+ printNotInstalled();
1100
+ return;
1101
+ }
1102
+ try {
1103
+ execFileSync2("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], QUIET);
1104
+ } catch (err) {
1105
+ printer_default.error(windowsTaskError("stop pinggy from starting automatically", "turn it off", err));
1106
+ process.exit(1);
1107
+ }
1108
+ logger.info("Scheduled task removed", { task: WINDOWS_TASK_NAME });
1109
+ if (isDaemonRunning()) {
1110
+ const result = await stopDaemon();
1111
+ if (!result.ok) console.log(`Could not stop the daemon: ${result.error}`);
1112
+ }
1113
+ printUninstalled();
1114
+ }
1115
+ function readServiceEntryText() {
1116
+ const platform = os3.platform();
1117
+ if (platform !== "linux" && platform !== "darwin") return "";
1118
+ try {
1119
+ return fs6.readFileSync(platform === "linux" ? getSystemdServicePath() : getLaunchdPlistPath(), "utf-8");
1120
+ } catch {
1121
+ return "";
1122
+ }
1123
+ }
1124
+ var SERVICE_QUERY_TIMEOUT_MILLIS = 2e3;
1125
+ function runServiceQuery(command, args) {
1126
+ return execFileSync2(command, args, { encoding: "utf-8", timeout: SERVICE_QUERY_TIMEOUT_MILLIS, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1127
+ }
1128
+ function serviceRestartInstruction(info, platform = os3.platform(), query = runServiceQuery, uid = process.getuid?.() ?? 501) {
1129
+ try {
1130
+ if (platform === "linux") {
1131
+ const mainPid = query("systemctl", ["--user", "show", "-p", "MainPID", "--value", SYSTEMD_SERVICE_NAME]).trim();
1132
+ return mainPid === String(info.pid) ? `"systemctl --user restart ${SYSTEMD_SERVICE_NAME}"` : null;
1133
+ }
1134
+ if (platform === "darwin") {
1135
+ const target = `gui/${uid}/${SERVICE_LABEL}`;
1136
+ const pid = /^\s*pid = (\d+)/m.exec(query("launchctl", ["print", target]))?.[1];
1137
+ return pid === String(info.pid) ? `"launchctl kickstart -k ${target}"` : null;
1138
+ }
1139
+ } catch {
1140
+ return null;
1141
+ }
1142
+ return null;
1143
+ }
1144
+ function installService() {
1145
+ const platform = os3.platform();
1146
+ const context = {
1147
+ platform,
1148
+ isPkg: "pkg" in process,
1149
+ execPath: process.execPath,
1150
+ home: os3.homedir(),
1151
+ env: process.env
1152
+ };
1153
+ const refusal = serviceInstallRefusal(context);
1154
+ if (refusal) {
1155
+ console.error(refusal);
1156
+ process.exit(1);
1157
+ }
1158
+ const program = serviceProgramPath(context);
1159
+ switch (platform) {
1160
+ case "linux":
1161
+ installSystemd(program);
1162
+ break;
1163
+ case "darwin":
1164
+ installLaunchd(program);
1165
+ break;
1166
+ case "win32":
1167
+ installWindows(program);
1168
+ break;
1169
+ default:
1170
+ console.error(`Unsupported platform: ${platform}`);
1171
+ process.exit(1);
1172
+ }
1173
+ }
1174
+ async function uninstallService() {
1175
+ const platform = os3.platform();
1176
+ switch (platform) {
1177
+ case "linux":
1178
+ uninstallSystemd();
1179
+ break;
1180
+ case "darwin":
1181
+ uninstallLaunchd();
1182
+ break;
1183
+ case "win32":
1184
+ await uninstallWindows();
1185
+ break;
1186
+ default:
1187
+ console.error(`Unsupported platform: ${platform}`);
1188
+ process.exit(1);
1189
+ }
1190
+ }
1191
+
1192
+ // src/daemon/lifecycle/daemonManager.ts
1193
+ var inProcessHandle = null;
1194
+ var daemonLauncher = null;
1195
+ function setDaemonLauncher(launcher) {
1196
+ daemonLauncher = launcher;
1197
+ }
1198
+ var DAEMON_SPAWN_TIMEOUT_MS = 8e3;
1199
+ var DAEMON_POLL_INTERVAL_MS = 200;
1200
+ var SPAWN_FAILED_EXIT_CODE = -1;
1201
+ var DAEMON_STOP_INSTRUCTION = '"pinggy daemon stop"';
1202
+ function isProcessAlive(pid) {
1203
+ try {
1204
+ process.kill(pid, 0);
1205
+ return true;
1206
+ } catch (err) {
1207
+ return err.code === "EPERM";
1208
+ }
1209
+ }
1210
+ function getDaemonInfo() {
1211
+ const infoPath = getDaemonInfoPath();
1212
+ if (!fs7.existsSync(infoPath)) return null;
1213
+ try {
1214
+ const data = JSON.parse(fs7.readFileSync(infoPath, "utf-8"));
1215
+ if (!data.pid || !data.port) return null;
1216
+ if (startedInEarlierBoot(data.bootId, data.startedAt) || !isProcessAlive(data.pid)) {
1217
+ logger.info("Stale daemon.json found, cleaning up", { stalePid: data.pid });
1218
+ try {
1219
+ fs7.unlinkSync(infoPath);
1220
+ } catch {
1221
+ }
1222
+ return null;
1223
+ }
1224
+ return data;
1225
+ } catch {
1226
+ return null;
1227
+ }
1228
+ }
1229
+ function isDaemonRunning() {
1230
+ return getDaemonInfo() !== null;
1231
+ }
1232
+ function daemonIpcVersion(info) {
1233
+ return info.ipcVersion ?? 0;
1234
+ }
1235
+ function isIpcCompatible(info) {
1236
+ return daemonIpcVersion(info) === IPC_VERSION;
1237
+ }
1238
+ function ipcMismatchMessage(info) {
1239
+ const versions = `daemon IPC v${daemonIpcVersion(info)}, this CLI expects v${IPC_VERSION}`;
1240
+ if (info.host === DaemonHost.APP) {
1241
+ return `The Pinggy app is running a daemon from a different version (${versions}). Update or restart the Pinggy app.`;
1242
+ }
1243
+ return `A daemon from a different Pinggy CLI version is running (PID ${info.pid}; ${versions}). Run "pinggy daemon stop" and retry. This stops all running tunnels.`;
1244
+ }
1245
+ function printDaemonVersionNoticeOnce(info, restartInstruction = serviceRestartInstruction, running = getVersion()) {
1246
+ if (process.stdout.isTTY !== true || info.host === DaemonHost.APP) return;
1247
+ if (!running || info.cliVersion === running || readUpdateState().lastDaemonNoticeVersion === running) return;
1248
+ const runs = info.cliVersion ? `The daemon runs ${info.cliVersion}.` : "The daemon runs an older version.";
1249
+ const instruction = restartInstruction(info) ?? DAEMON_STOP_INSTRUCTION;
1250
+ if (writeUpdateState({ lastDaemonNoticeVersion: running })) {
1251
+ printer_default.print(`${runs} Run ${instruction} to start ${running}. This stops all running tunnels.`);
1252
+ }
1253
+ }
1254
+ var installedBinaryForDaemon = null;
1255
+ function startDaemonFromInstalledBinary(binaryPath) {
1256
+ installedBinaryForDaemon = binaryPath;
1257
+ }
1258
+ function getDaemonSpawnArgs(isPackaged = isPackagedBinary(), executableExists = fs7.existsSync(process.execPath), linkPath = unixLayoutPaths(os4.homedir()).link, installedBinary = installedBinaryForDaemon) {
1259
+ if (isPackaged && installedBinary) {
1260
+ return { command: installedBinary, args: ["--_daemon-child"], env: { ...process.env } };
1261
+ }
1262
+ if (isPackaged && !executableExists) {
1263
+ return { command: linkPath, args: ["--_daemon-child"], env: { ...process.env } };
1264
+ }
1265
+ return {
1266
+ command: process.execPath,
1267
+ args: [process.argv[1], "--_daemon-child"],
1268
+ env: { ...process.env }
1269
+ };
1270
+ }
1271
+ async function startDaemon() {
1272
+ const existing = getDaemonInfo();
1273
+ if (existing) {
1274
+ return existing;
1275
+ }
1276
+ const { command, args, env } = getDaemonSpawnArgs();
1277
+ logger.info("Spawning daemon child", { command, args });
1278
+ let stderrOutput = "";
1279
+ let exited = false;
1280
+ let exitCode = null;
1281
+ const child = spawn(command, args, {
1282
+ detached: true,
1283
+ stdio: ["ignore", "ignore", "pipe"],
1284
+ env,
1285
+ ...os4.platform() === "win32" ? { windowsHide: true } : {}
1286
+ });
1287
+ child.stderr?.on("data", (chunk) => {
1288
+ stderrOutput += chunk.toString("utf-8");
1289
+ });
1290
+ child.on("exit", (code) => {
1291
+ exited = true;
1292
+ exitCode = code;
1293
+ });
1294
+ child.on("error", (error) => {
1295
+ exited = true;
1296
+ exitCode = SPAWN_FAILED_EXIT_CODE;
1297
+ stderrOutput = errorMessage(error);
1298
+ });
1299
+ child.unref();
1300
+ const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited && exitCode !== 0);
1301
+ if (!info) {
1302
+ const logPath = getDaemonLogPath();
1303
+ if (exited) {
1304
+ const detail = stderrOutput.trim() || `Check ${logPath} for details.`;
1305
+ throw new Error(`Daemon child exited with code ${exitCode}. ${detail}`);
1306
+ }
1307
+ throw new Error(`Daemon failed to start within timeout. Check ${logPath} for details.`);
1308
+ }
1309
+ child.stderr?.removeAllListeners();
1310
+ child.stderr?.destroy();
1311
+ return info;
1312
+ }
1313
+ async function ensureDaemonRunning() {
1314
+ const existing = getDaemonInfo();
1315
+ if (existing) {
1316
+ if (!isIpcCompatible(existing)) throw new Error(ipcMismatchMessage(existing));
1317
+ return existing;
1318
+ }
1319
+ if (daemonLauncher) {
1320
+ await daemonLauncher();
1321
+ const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS);
1322
+ if (!info) throw new Error(`Daemon failed to start. Check ${getDaemonLogPath()} for details.`);
1323
+ if (!isIpcCompatible(info)) throw new Error(ipcMismatchMessage(info));
1324
+ return info;
1325
+ }
1326
+ if (process.versions.electron) {
1327
+ const { runDaemonChild } = await import("./daemonChild-GGG34AOT.js");
1328
+ const handle = await runDaemonChild({
1329
+ installSignalHandlers: false,
1330
+ exitOnFailure: false,
1331
+ host: DaemonHost.APP
1332
+ });
1333
+ inProcessHandle = handle;
1334
+ return getDaemonInfo() ?? {
1335
+ pid: handle.pid,
1336
+ port: handle.port,
1337
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
1338
+ host: DaemonHost.APP,
1339
+ ipcVersion: IPC_VERSION
1340
+ };
1341
+ }
1342
+ return startDaemon();
1343
+ }
1344
+ function getInProcessDaemonHandle() {
1345
+ return inProcessHandle;
1346
+ }
1347
+ function removeDeadDaemonFiles(pid) {
1348
+ for (const filePath of [getDaemonInfoPath(), getDaemonLockPath()]) {
1349
+ try {
1350
+ const record = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
1351
+ if (record.pid === pid) fs7.rmSync(filePath, { force: true });
1352
+ } catch {
1353
+ }
1354
+ }
1355
+ }
1356
+ async function getActiveTunnelSummaries(origin = "app") {
1357
+ const info = getDaemonInfo();
1358
+ if (!info) return [];
1359
+ const { IPCClient } = await import("./ipcClient-6QESURCH.js");
1360
+ const client = new IPCClient(info.port, origin);
1361
+ let tunnels;
1362
+ try {
1363
+ tunnels = await client.listTunnels();
1364
+ } catch (err) {
1365
+ logger.warn("Failed to list tunnels from daemon", { error: errorMessage(err) });
1366
+ return [];
1367
+ }
1368
+ if (!Array.isArray(tunnels)) return [];
1369
+ return tunnels.filter((t) => {
1370
+ const state = t?.status?.state;
1371
+ return state !== "closed" /* Closed */ && state !== "exited" /* Exited */;
1372
+ }).map((t) => ({
1373
+ tunnelId: t.tunnelid,
1374
+ name: t.tunnelconfig?.name || t.tunnelid.slice(0, 8),
1375
+ localAddress: getLocalAddress(t.tunnelconfig),
1376
+ urls: t.remoteurls ?? []
1377
+ }));
1378
+ }
1379
+ function pollForDaemonInfo(timeoutMs, hasExited) {
1380
+ return new Promise((resolve) => {
1381
+ const start = Date.now();
1382
+ const check = () => {
1383
+ const info = getDaemonInfo();
1384
+ if (info) {
1385
+ resolve(info);
1386
+ return;
1387
+ }
1388
+ if (hasExited?.()) {
1389
+ resolve(null);
1390
+ return;
1391
+ }
1392
+ if (Date.now() - start > timeoutMs) {
1393
+ resolve(null);
1394
+ return;
1395
+ }
1396
+ setTimeout(check, DAEMON_POLL_INTERVAL_MS);
1397
+ };
1398
+ check();
1399
+ });
1400
+ }
1401
+ async function stopDaemon() {
1402
+ const info = getDaemonInfo();
1403
+ if (!info) return { ok: false, error: "No daemon is running." };
1404
+ let daemonErrors = [];
1405
+ try {
1406
+ const { IPCClient } = await import("./ipcClient-6QESURCH.js");
1407
+ const client = new IPCClient(info.port);
1408
+ const result = await client.shutdown();
1409
+ logger.debug("Sent shutdown command to daemon", { result });
1410
+ if (result?.status === ShutdownStatus.RefusedInApp) {
1411
+ return {
1412
+ ok: false,
1413
+ reason: DaemonHost.APP,
1414
+ error: "The daemon is running inside the Pinggy app."
1415
+ };
1416
+ }
1417
+ if (Array.isArray(result?.errors)) daemonErrors = result.errors;
1418
+ } catch (e) {
1419
+ return { ok: false, error: `Failed to reach daemon: ${errorMessage(e)}` };
1420
+ }
1421
+ const exited = await waitForExit(info.pid, 5e3);
1422
+ if (!exited) {
1423
+ const detail = daemonErrors.length > 0 ? ` Daemon reported: ${daemonErrors.join("; ")}` : "";
1424
+ return { ok: false, error: `Daemon PID ${info.pid} did not exit within 5s.${detail}` };
1425
+ }
1426
+ if (daemonErrors.length > 0) {
1427
+ return { ok: false, error: `Daemon exited but reported errors: ${daemonErrors.join("; ")}` };
1428
+ }
1429
+ return { ok: true };
1430
+ }
1431
+ async function waitForExit(pid, timeoutMs) {
1432
+ const deadline = Date.now() + timeoutMs;
1433
+ while (Date.now() < deadline) {
1434
+ if (!isProcessAlive(pid)) return true;
1435
+ await new Promise((r) => setTimeout(r, 100));
1436
+ }
1437
+ return !isProcessAlive(pid);
1438
+ }
1439
+
1440
+ // src/update/windowsSwap.ts
1441
+ var WINDOWS_PATH = path7.win32;
1442
+ var BACKUP_MARKER = ".prev";
1443
+ var NEW_FILE_SUFFIX = ".new.exe";
1444
+ var OLD_FILE_SUFFIX = ".old";
1445
+ var RETRYABLE_RENAME_CODES = /* @__PURE__ */ new Set(["EPERM", "EBUSY", "EACCES"]);
1446
+ var RENAME_RETRY_INTERVAL_MILLIS = 250;
1447
+ var RENAME_RETRY_LIMIT_MILLIS = 1e4;
1448
+ var POST_SWAP_WAIT_MILLIS = 2e3;
1449
+ var INSTALL_COMMAND = "irm https://pinggy.io/install.ps1 | iex";
1450
+ var realWindowsFileOperations = {
1451
+ exists: (filePath) => fs8.existsSync(filePath),
1452
+ copyFile: (from, to) => fs8.copyFileSync(from, to),
1453
+ rename: (from, to) => fs8.renameSync(from, to),
1454
+ // Synchronous, so no other JavaScript runs between the 2 renames of a swap.
1455
+ sleepMillis: (millis) => {
1456
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, millis);
1457
+ },
1458
+ nowMillis: () => Date.now()
1459
+ };
1460
+ function windowsInstallPaths(execPath) {
1461
+ const directory = WINDOWS_PATH.dirname(execPath);
1462
+ const { name, ext, base } = WINDOWS_PATH.parse(execPath);
1463
+ if (name.endsWith(BACKUP_MARKER)) {
1464
+ const liveName = `${name.slice(0, -BACKUP_MARKER.length)}${ext}`;
1465
+ return { directory, liveName, livePath: WINDOWS_PATH.join(directory, liveName), backupPath: execPath, runningFromBackup: true };
1466
+ }
1467
+ const backupName = `${name}${BACKUP_MARKER}${ext}`;
1468
+ return { directory, liveName: base, livePath: execPath, backupPath: WINDOWS_PATH.join(directory, backupName), runningFromBackup: false };
1469
+ }
1470
+ function windowsDownloadPath(execPath) {
1471
+ return `${execPath}.${process.pid}${NEW_FILE_SUFFIX}`;
1472
+ }
1473
+ function renameWithRetry(operations, from, to) {
1474
+ const attempts = Math.ceil(RENAME_RETRY_LIMIT_MILLIS / RENAME_RETRY_INTERVAL_MILLIS);
1475
+ for (let attempt = 0; ; attempt++) {
1476
+ try {
1477
+ operations.rename(from, to);
1478
+ return;
1479
+ } catch (error) {
1480
+ const retryable = RETRYABLE_RENAME_CODES.has(error.code ?? "");
1481
+ if (!retryable || attempt >= attempts) throw error;
1482
+ operations.sleepMillis(RENAME_RETRY_INTERVAL_MILLIS);
1483
+ }
1484
+ }
1485
+ }
1486
+ function restoreLiveFile(operations, paths, oldPath) {
1487
+ try {
1488
+ renameWithRetry(operations, oldPath, paths.livePath);
1489
+ return;
1490
+ } catch {
1491
+ }
1492
+ try {
1493
+ operations.copyFile(paths.backupPath, paths.livePath);
1494
+ } catch {
1495
+ throw new UpdateError(
1496
+ UpdateErrorCode.RestoreFailed,
1497
+ `Could not restore ${paths.livePath}. The old binary is at ${oldPath}. Run: ${INSTALL_COMMAND}`
1498
+ );
1499
+ }
1500
+ }
1501
+ function renameFailure(livePath, error, running) {
1502
+ return new UpdateError(
1503
+ UpdateErrorCode.RenameFailed,
1504
+ `Could not replace ${livePath}: ${errorMessage(error)}. pinggy ${running} is unchanged.`
1505
+ );
1506
+ }
1507
+ function oldFilePath(livePath, operations) {
1508
+ return `${livePath}.${operations.nowMillis()}${OLD_FILE_SUFFIX}`;
1509
+ }
1510
+ async function swapWindowsBinary(request, operations, runBinary) {
1511
+ const { downloadPath, newVersion, runningVersion } = request;
1512
+ const paths = windowsInstallPaths(request.execPath);
1513
+ const oldPath = oldFilePath(paths.livePath, operations);
1514
+ try {
1515
+ operations.copyFile(paths.livePath, paths.backupPath);
1516
+ renameWithRetry(operations, paths.livePath, oldPath);
1517
+ } catch (error) {
1518
+ throw renameFailure(paths.livePath, error, runningVersion);
1519
+ }
1520
+ try {
1521
+ renameWithRetry(operations, downloadPath, paths.livePath);
1522
+ } catch (error) {
1523
+ restoreLiveFile(operations, paths, oldPath);
1524
+ throw renameFailure(paths.livePath, error, runningVersion);
1525
+ }
1526
+ operations.sleepMillis(POST_SWAP_WAIT_MILLIS);
1527
+ const reported = await readBinaryVersion(paths.livePath, runBinary).catch(() => null);
1528
+ if (reported !== newVersion) {
1529
+ restoreLiveFile(operations, paths, oldPath);
1530
+ throw new UpdateError(
1531
+ UpdateErrorCode.PostSwapFailed,
1532
+ `The new binary did not run after the update. pinggy ${runningVersion} is restored.`
1533
+ );
1534
+ }
1535
+ }
1536
+ async function versionBeingLeft(request, paths, runBinary) {
1537
+ if (!paths.runningFromBackup) return request.runningVersion;
1538
+ const reported = await readBinaryVersion(paths.livePath, runBinary).catch(() => null);
1539
+ return reported ?? request.latestVersion ?? "the newer version";
1540
+ }
1541
+ function nothingToRollBack() {
1542
+ return new UpdateError(UpdateErrorCode.NothingToRollBack, "No previous version to go back to.");
1543
+ }
1544
+ async function rollbackWindowsBinary(request, operations, runBinary) {
1545
+ const paths = windowsInstallPaths(request.execPath);
1546
+ if (!operations.exists(paths.backupPath)) throw nothingToRollBack();
1547
+ const to = await readBinaryVersion(paths.backupPath, runBinary).catch(() => null);
1548
+ if (to === null) throw nothingToRollBack();
1549
+ const from = await versionBeingLeft(request, paths, runBinary);
1550
+ const oldPath = oldFilePath(paths.livePath, operations);
1551
+ const liveExists = operations.exists(paths.livePath);
1552
+ try {
1553
+ if (liveExists) renameWithRetry(operations, paths.livePath, oldPath);
1554
+ } catch (error) {
1555
+ throw renameFailure(paths.livePath, error, from);
1556
+ }
1557
+ try {
1558
+ renameWithRetry(operations, paths.backupPath, paths.livePath);
1559
+ } catch (error) {
1560
+ if (liveExists) renameWithRetry(operations, oldPath, paths.livePath);
1561
+ throw renameFailure(paths.livePath, error, from);
1562
+ }
1563
+ return { from, to };
1564
+ }
1565
+ var realStaleFileOperations = {
1566
+ list: (directory) => fs8.readdirSync(directory),
1567
+ remove: (filePath) => fs8.rmSync(filePath, { force: true }),
1568
+ isAlive: isProcessAlive
1569
+ };
1570
+ function isRemovableStaleFile(fileName, liveName, operations) {
1571
+ const prefix = `${liveName}.`;
1572
+ if (!fileName.startsWith(prefix)) return false;
1573
+ if (fileName.endsWith(OLD_FILE_SUFFIX)) return true;
1574
+ if (!fileName.endsWith(NEW_FILE_SUFFIX)) return false;
1575
+ const pidText = fileName.slice(prefix.length, -NEW_FILE_SUFFIX.length);
1576
+ return /^\d+$/.test(pidText) && !operations.isAlive(Number(pidText));
1577
+ }
1578
+ function removeStaleUpdateFiles(execPath = process.execPath, operations = realStaleFileOperations) {
1579
+ const directory = WINDOWS_PATH.dirname(execPath);
1580
+ const liveName = WINDOWS_PATH.basename(execPath);
1581
+ let fileNames;
1582
+ try {
1583
+ fileNames = operations.list(directory);
1584
+ } catch {
1585
+ return;
1586
+ }
1587
+ for (const fileName of fileNames) {
1588
+ try {
1589
+ if (isRemovableStaleFile(fileName, liveName, operations)) operations.remove(WINDOWS_PATH.join(directory, fileName));
1590
+ } catch {
1591
+ }
1592
+ }
1593
+ }
1594
+
1595
+ // src/update/updateLock.ts
1596
+ import fs9 from "fs";
1597
+ var STALE_AFTER_MILLIS = 30 * 60 * 1e3;
1598
+ var REPLACEMENT_SETTLE_MILLIS = 200;
1599
+ var LockState = {
1600
+ Absent: "absent",
1601
+ Held: "held",
1602
+ Stale: "stale"
1603
+ };
1604
+ function readLockPid(lockPath) {
1605
+ try {
1606
+ const parsed = JSON.parse(fs9.readFileSync(lockPath, "utf-8"));
1607
+ return typeof parsed.pid === "number" && parsed.pid > 0 ? parsed.pid : null;
1608
+ } catch {
1609
+ return null;
1610
+ }
1611
+ }
1612
+ function lockState(lockPath) {
1613
+ let modifiedMillis;
1614
+ try {
1615
+ modifiedMillis = fs9.statSync(lockPath).mtimeMs;
1616
+ } catch {
1617
+ return LockState.Absent;
1618
+ }
1619
+ if (Date.now() - modifiedMillis >= STALE_AFTER_MILLIS) return LockState.Stale;
1620
+ const pid = readLockPid(lockPath);
1621
+ return pid === null || isProcessAlive(pid) ? LockState.Held : LockState.Stale;
1622
+ }
1623
+ function lockContents() {
1624
+ return JSON.stringify({ pid: process.pid, startedAt: Date.now() });
1625
+ }
1626
+ function createLock(lockPath) {
1627
+ try {
1628
+ const fileDescriptor = fs9.openSync(lockPath, "wx");
1629
+ fs9.writeSync(fileDescriptor, lockContents());
1630
+ fs9.closeSync(fileDescriptor);
1631
+ return true;
1632
+ } catch (error) {
1633
+ if (error.code === "EEXIST") return false;
1634
+ throw error;
1635
+ }
1636
+ }
1637
+ function wait(millis) {
1638
+ return new Promise((resolve) => setTimeout(resolve, millis));
1639
+ }
1640
+ async function replaceStaleLock(lockPath) {
1641
+ const temporaryPath = `${lockPath}.${process.pid}`;
1642
+ fs9.writeFileSync(temporaryPath, lockContents());
1643
+ fs9.renameSync(temporaryPath, lockPath);
1644
+ await wait(REPLACEMENT_SETTLE_MILLIS);
1645
+ return readLockPid(lockPath) === process.pid;
1646
+ }
1647
+ async function acquireUpdateLock() {
1648
+ ensurePinggyConfigDir();
1649
+ const lockPath = getUpdateLockPath();
1650
+ if (createLock(lockPath)) return true;
1651
+ switch (lockState(lockPath)) {
1652
+ case LockState.Held:
1653
+ return false;
1654
+ case LockState.Absent:
1655
+ return createLock(lockPath);
1656
+ case LockState.Stale:
1657
+ return replaceStaleLock(lockPath);
1658
+ }
1659
+ }
1660
+ function isUpdateLockHeld() {
1661
+ return lockState(getUpdateLockPath()) === LockState.Held;
1662
+ }
1663
+ function isUpdateLockOurs() {
1664
+ return readLockPid(getUpdateLockPath()) === process.pid;
1665
+ }
1666
+ function releaseUpdateLock() {
1667
+ if (isUpdateLockOurs()) fs9.rmSync(getUpdateLockPath(), { force: true });
1668
+ }
1669
+
1670
+ // src/update/unixLinkSwap.ts
1671
+ import fs10 from "fs";
1672
+ import path8 from "path";
1673
+ var BINARY_NAME = "pinggy";
1674
+ var DOWNLOAD_PREFIX = "pinggy.download.";
1675
+ var CONVERT_PREFIX = "pinggy.convert.";
1676
+ var LINK_TEMP_PREFIX = "pinggy.link.";
1677
+ var EXECUTABLE_MODE3 = 493;
1678
+ function fsyncPath(target, flags) {
1679
+ const fileDescriptor = fs10.openSync(target, flags);
1680
+ try {
1681
+ fs10.fsyncSync(fileDescriptor);
1682
+ } finally {
1683
+ fs10.closeSync(fileDescriptor);
1684
+ }
1685
+ }
1686
+ var realUnixSwapEnvironment = {
1687
+ fsyncFile: (filePath) => fsyncPath(filePath, "r+"),
1688
+ fsyncDirectory: (directory) => fsyncPath(directory, "r"),
1689
+ daemonVersion: () => getDaemonInfo()?.cliVersion,
1690
+ serviceEntryText: readServiceEntryText,
1691
+ isAlive: isProcessAlive
1692
+ };
1693
+ function unixDownloadPath(layout) {
1694
+ return path8.posix.join(layout.versionsDirectory, `${DOWNLOAD_PREFIX}${process.pid}`);
1695
+ }
1696
+ function versionDirectory(layout, version) {
1697
+ return path8.posix.join(layout.versionsDirectory, version);
1698
+ }
1699
+ function versionBinaryPath(layout, version) {
1700
+ return path8.posix.join(versionDirectory(layout, version), BINARY_NAME);
1701
+ }
1702
+ function readLinkVersion(layout) {
1703
+ try {
1704
+ const version = path8.posix.basename(path8.posix.dirname(fs10.readlinkSync(layout.link)));
1705
+ return parseVersion(version) ? version : null;
1706
+ } catch {
1707
+ return null;
1708
+ }
1709
+ }
1710
+ function installedVersions(layout) {
1711
+ return fs10.readdirSync(layout.versionsDirectory).filter((name) => parseVersion(name) !== null);
1712
+ }
1713
+ function highestVersionBelow(layout, ceiling) {
1714
+ const lower = installedVersions(layout).filter((version) => isNewerVersion(ceiling, version));
1715
+ return lower.reduce((best, version) => best === null || isNewerVersion(version, best) ? version : best, null);
1716
+ }
1717
+ function moveLink(layout, version, environment) {
1718
+ fs10.mkdirSync(layout.binDirectory, { recursive: true });
1719
+ const temporaryLink = path8.posix.join(layout.binDirectory, `${LINK_TEMP_PREFIX}${process.pid}`);
1720
+ fs10.rmSync(temporaryLink, { force: true });
1721
+ fs10.symlinkSync(versionBinaryPath(layout, version), temporaryLink);
1722
+ fs10.renameSync(temporaryLink, layout.link);
1723
+ environment.fsyncDirectory(layout.binDirectory);
1724
+ }
1725
+ function convertPlainFile(layout, execPath, runningVersion, environment) {
1726
+ const temporaryPath = path8.posix.join(layout.versionsDirectory, `${CONVERT_PREFIX}${process.pid}`);
1727
+ fs10.copyFileSync(execPath, temporaryPath);
1728
+ fs10.chmodSync(temporaryPath, EXECUTABLE_MODE3);
1729
+ environment.fsyncFile(temporaryPath);
1730
+ fs10.mkdirSync(versionDirectory(layout, runningVersion), { recursive: true });
1731
+ fs10.renameSync(temporaryPath, versionBinaryPath(layout, runningVersion));
1732
+ environment.fsyncDirectory(versionDirectory(layout, runningVersion));
1733
+ }
1734
+ function isNamedByService(layout, version, environment) {
1735
+ return environment.serviceEntryText().includes(versionBinaryPath(layout, version));
1736
+ }
1737
+ function removeDeadProcessTemp(directory, prefix, environment) {
1738
+ for (const name of fs10.readdirSync(directory)) {
1739
+ const pidText = name.startsWith(prefix) ? name.slice(prefix.length) : "";
1740
+ if (/^\d+$/.test(pidText) && !environment.isAlive(Number(pidText))) {
1741
+ fs10.rmSync(path8.posix.join(directory, name), { force: true });
1742
+ }
1743
+ }
1744
+ }
1745
+ function removeStaleUnixFiles(layout, environment = realUnixSwapEnvironment) {
1746
+ const locations = [
1747
+ [layout.versionsDirectory, DOWNLOAD_PREFIX],
1748
+ [layout.versionsDirectory, CONVERT_PREFIX],
1749
+ [layout.binDirectory, LINK_TEMP_PREFIX]
1750
+ ];
1751
+ for (const [directory, prefix] of locations) {
1752
+ try {
1753
+ removeDeadProcessTemp(directory, prefix, environment);
1754
+ } catch {
1755
+ }
1756
+ }
1757
+ }
1758
+ function pruneVersions(layout, environment = realUnixSwapEnvironment) {
1759
+ removeStaleUnixFiles(layout, environment);
1760
+ const target = readLinkVersion(layout);
1761
+ if (target === null) return;
1762
+ const keep = /* @__PURE__ */ new Set([target, highestVersionBelow(layout, target), environment.daemonVersion()]);
1763
+ for (const version of installedVersions(layout)) {
1764
+ if (keep.has(version) || isNamedByService(layout, version, environment)) continue;
1765
+ fs10.rmSync(versionDirectory(layout, version), { recursive: true, force: true });
1766
+ }
1767
+ }
1768
+ function replaceFailure(layout, error, running) {
1769
+ return new UpdateError(
1770
+ UpdateErrorCode.RenameFailed,
1771
+ `Could not replace ${layout.link}: ${errorMessage(error)}. pinggy ${running} is unchanged.`
1772
+ );
1773
+ }
1774
+ function installVersion(request, environment = realUnixSwapEnvironment) {
1775
+ const { layout, plainFileToConvert, runningVersion, newVersion } = request;
1776
+ try {
1777
+ fs10.mkdirSync(layout.versionsDirectory, { recursive: true });
1778
+ if (plainFileToConvert !== null) convertPlainFile(layout, plainFileToConvert, runningVersion, environment);
1779
+ fs10.mkdirSync(versionDirectory(layout, newVersion), { recursive: true });
1780
+ fs10.renameSync(unixDownloadPath(layout), versionBinaryPath(layout, newVersion));
1781
+ environment.fsyncDirectory(versionDirectory(layout, newVersion));
1782
+ moveLink(layout, newVersion, environment);
1783
+ } catch (error) {
1784
+ throw replaceFailure(layout, error, runningVersion);
1785
+ }
1786
+ try {
1787
+ pruneVersions(layout, environment);
1788
+ } catch {
1789
+ }
1790
+ }
1791
+ function nothingToRollBack2() {
1792
+ return new UpdateError(UpdateErrorCode.NothingToRollBack, "No previous version to go back to.");
1793
+ }
1794
+ function previousVersion(layout, current) {
1795
+ try {
1796
+ const version = highestVersionBelow(layout, current);
1797
+ if (version !== null) return version;
1798
+ } catch {
1799
+ }
1800
+ throw nothingToRollBack2();
1801
+ }
1802
+ function rollbackUnixVersion(layout, environment = realUnixSwapEnvironment) {
1803
+ const current = readLinkVersion(layout);
1804
+ if (current === null) throw nothingToRollBack2();
1805
+ const previous = previousVersion(layout, current);
1806
+ try {
1807
+ moveLink(layout, previous, environment);
1808
+ } catch (error) {
1809
+ throw replaceFailure(layout, error, current);
1810
+ }
1811
+ writeUpdateState({ rolledBackFromVersion: current });
1812
+ if (environment.daemonVersion() !== current && !isNamedByService(layout, current, environment)) {
1813
+ fs10.rmSync(versionDirectory(layout, current), { recursive: true, force: true });
1814
+ }
1815
+ return { from: current, to: previous };
1816
+ }
1817
+
1818
+ // src/update/applyUpdate.ts
1819
+ import fs11 from "fs";
1820
+ function windowsUpdateTarget(execPath, runBinary) {
1821
+ return {
1822
+ downloadPath: windowsDownloadPath(execPath),
1823
+ rollbackBinaryPath: () => windowsInstallPaths(execPath).livePath,
1824
+ installedVersion: (runningVersion) => runningVersion,
1825
+ prepareDownload: () => void 0,
1826
+ install: async ({ newVersion, runningVersion }) => {
1827
+ await swapWindowsBinary(
1828
+ { execPath, downloadPath: windowsDownloadPath(execPath), newVersion, runningVersion },
1829
+ realWindowsFileOperations,
1830
+ runBinary
1831
+ );
1832
+ moveDeclinedInstallToVersion(execPath, newVersion);
1833
+ },
1834
+ rollback: async (runningVersion) => {
1835
+ const result = await rollbackWindowsBinary(
1836
+ { execPath, runningVersion, latestVersion: readUpdateState().latestVersion },
1837
+ realWindowsFileOperations,
1838
+ runBinary
1839
+ );
1840
+ writeUpdateState({ rolledBackFromVersion: result.from });
1841
+ return result;
1842
+ }
1843
+ };
1844
+ }
1845
+ function unixUpdateTarget(kind, probe) {
1846
+ const layout = unixLayoutPaths(probe.homeRealPath);
1847
+ const isPlainFile = kind === InstallKind.UnixPlainFile;
1848
+ return {
1849
+ downloadPath: unixDownloadPath(layout),
1850
+ rollbackBinaryPath: (version) => versionBinaryPath(layout, version),
1851
+ installedVersion: (runningVersion) => readLinkVersion(layout) ?? runningVersion,
1852
+ prepareDownload: () => {
1853
+ fs11.mkdirSync(layout.versionsDirectory, { recursive: true });
1854
+ },
1855
+ install: ({ newVersion, runningVersion }) => installVersion({
1856
+ layout,
1857
+ plainFileToConvert: isPlainFile ? probe.execPath : null,
1858
+ newVersion,
1859
+ runningVersion
1860
+ }),
1861
+ rollback: () => {
1862
+ if (isPlainFile) throw nothingToRollBack2();
1863
+ return rollbackUnixVersion(layout);
1864
+ }
1865
+ };
1866
+ }
1867
+ function createUpdateTarget(kind, probe, runBinary = runPinggyBinary) {
1868
+ switch (kind) {
1869
+ case InstallKind.WindowsWritable:
1870
+ return windowsUpdateTarget(probe.execPath, runBinary);
1871
+ case InstallKind.UnixLayout:
1872
+ case InstallKind.UnixPlainFile:
1873
+ return unixUpdateTarget(kind, probe);
1874
+ default:
1875
+ return null;
1876
+ }
1877
+ }
1878
+ function downloadRelease(target, tag, assetName, runningVersion, dependencies = defaultDownloadDependencies) {
1879
+ target.prepareDownload();
1880
+ return downloadAndVerify({ tag, assetName, tempPath: target.downloadPath, runningVersion }, dependencies);
1881
+ }
1882
+
1883
+ export {
1884
+ nowEpochSeconds,
1885
+ readUpdateState,
1886
+ writeUpdateState,
1887
+ recordLatestVersion,
1888
+ isPackagedBinary,
1889
+ resolveNodePtyRoot,
1890
+ requireNodePty,
1891
+ hasExecutableSpawnHelper,
1892
+ makeSpawnHelperExecutable,
1893
+ InstallKind,
1894
+ NPM_INSTALL_COMMAND,
1895
+ hasPathSegment,
1896
+ unixLayoutPaths,
1897
+ detectInstallKind,
1898
+ canReplaceItself,
1899
+ backgroundInstallKind,
1900
+ installCommandFor,
1901
+ createInstallProbe,
1902
+ installerBinaryPath,
1903
+ autostartFilePath,
1904
+ installService,
1905
+ uninstallService,
1906
+ currentBootId,
1907
+ startedInEarlierBoot,
1908
+ resolveLatestTag,
1909
+ isReleaseComplete,
1910
+ resolveLatestNpmVersion,
1911
+ versionFromTag,
1912
+ parseVersion,
1913
+ isNewerVersion,
1914
+ UpdateError,
1915
+ environmentWithoutDeviceToken,
1916
+ pinggyBinaryRunOptions,
1917
+ runPinggyBinary,
1918
+ readBinaryVersion,
1919
+ readBinaryIpcVersion,
1920
+ assetNameFor,
1921
+ removeQuietly,
1922
+ windowsInstallPaths,
1923
+ removeStaleUpdateFiles,
1924
+ acquireUpdateLock,
1925
+ isUpdateLockHeld,
1926
+ isUpdateLockOurs,
1927
+ releaseUpdateLock,
1928
+ readLinkVersion,
1929
+ removeStaleUnixFiles,
1930
+ createUpdateTarget,
1931
+ downloadRelease,
1932
+ setDaemonLauncher,
1933
+ isProcessAlive,
1934
+ getDaemonInfo,
1935
+ isDaemonRunning,
1936
+ daemonIpcVersion,
1937
+ isIpcCompatible,
1938
+ ipcMismatchMessage,
1939
+ printDaemonVersionNoticeOnce,
1940
+ startDaemonFromInstalledBinary,
1941
+ startDaemon,
1942
+ ensureDaemonRunning,
1943
+ getInProcessDaemonHandle,
1944
+ removeDeadDaemonFiles,
1945
+ getActiveTunnelSummaries,
1946
+ stopDaemon
1947
+ };