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.
- package/ARCHITECTURE.md +21 -8
- package/CLAUDE.md +7 -3
- package/README.md +12 -0
- package/dist/{chunk-MHQ3CVEB.js → chunk-P54K7NPF.js} +5 -1
- package/dist/chunk-RYO5T2JT.js +1947 -0
- package/dist/{chunk-LF6WMFWT.js → chunk-W47AYOH2.js} +6800 -2025
- package/dist/{daemonChild-WTZ7X6SZ.js → daemonChild-GGG34AOT.js} +7 -5
- package/dist/index.cjs +3234 -432
- package/dist/index.d.cts +75 -2
- package/dist/index.d.ts +75 -2
- package/dist/index.js +21 -5
- package/dist/{ipcClient-IZ5R6TPN.js → ipcClient-6QESURCH.js} +1 -1
- package/dist/{main-INPCUGAN.js → main-FCIOVX5I.js} +5 -8
- package/dist/{updateChild-BPWBQ3WR.js → updateChild-RNCLN24C.js} +12 -14
- package/package.json +1 -1
- package/scripts/install/install.ps1 +3 -2
- package/scripts/install/install.sh +13 -7
- package/dist/chunk-HJECJ7LC.js +0 -889
- package/dist/chunk-OQVFQ5VG.js +0 -1041
- package/dist/chunk-Q5RYSWFK.js +0 -2204
package/dist/chunk-OQVFQ5VG.js
DELETED
|
@@ -1,1041 +0,0 @@
|
|
|
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
|
-
getDaemonLogPath,
|
|
19
|
-
getPinggyConfigDir,
|
|
20
|
-
getUpdateStatePath
|
|
21
|
-
} from "./chunk-WFHMERT3.js";
|
|
22
|
-
|
|
23
|
-
// src/update/updateState.ts
|
|
24
|
-
import fs from "fs";
|
|
25
|
-
import path from "path";
|
|
26
|
-
var NUMBER_FIELDS = [
|
|
27
|
-
"lastCheckEpochSeconds",
|
|
28
|
-
"lastAttemptEpochSeconds",
|
|
29
|
-
"latestSeenEpochSeconds",
|
|
30
|
-
"lastCheckFailureNoticeEpochSeconds",
|
|
31
|
-
"failedAttempts",
|
|
32
|
-
"deferredIpcVersion",
|
|
33
|
-
"cachedVersionSizeBytes",
|
|
34
|
-
"cachedVersionModifiedMillis"
|
|
35
|
-
];
|
|
36
|
-
var STRING_FIELDS = [
|
|
37
|
-
"latestVersion",
|
|
38
|
-
"lastNoticeVersion",
|
|
39
|
-
"lastDaemonNoticeVersion",
|
|
40
|
-
"rolledBackFromVersion",
|
|
41
|
-
"updatedFromVersion",
|
|
42
|
-
"updatedToVersion",
|
|
43
|
-
"failedVersion",
|
|
44
|
-
"deferredVersion",
|
|
45
|
-
"declinedInstallPath",
|
|
46
|
-
"declinedInstallVersion",
|
|
47
|
-
"cachedVersionPath",
|
|
48
|
-
"cachedVersion"
|
|
49
|
-
];
|
|
50
|
-
function nowEpochSeconds() {
|
|
51
|
-
return Math.floor(Date.now() / 1e3);
|
|
52
|
-
}
|
|
53
|
-
function keepKnownFields(parsed) {
|
|
54
|
-
const state = {};
|
|
55
|
-
for (const field of NUMBER_FIELDS) {
|
|
56
|
-
const value = parsed[field];
|
|
57
|
-
if (typeof value === "number" && Number.isFinite(value)) state[field] = value;
|
|
58
|
-
}
|
|
59
|
-
for (const field of STRING_FIELDS) {
|
|
60
|
-
const value = parsed[field];
|
|
61
|
-
if (typeof value === "string") state[field] = value;
|
|
62
|
-
}
|
|
63
|
-
return state;
|
|
64
|
-
}
|
|
65
|
-
function readUpdateState() {
|
|
66
|
-
try {
|
|
67
|
-
const parsed = JSON.parse(fs.readFileSync(getUpdateStatePath(), "utf-8"));
|
|
68
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
|
|
69
|
-
return keepKnownFields(parsed);
|
|
70
|
-
} catch {
|
|
71
|
-
return {};
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
function writeUpdateState(patch) {
|
|
75
|
-
try {
|
|
76
|
-
ensurePinggyConfigDir();
|
|
77
|
-
const statePath = getUpdateStatePath();
|
|
78
|
-
const temporaryPath = path.join(path.dirname(statePath), `update.json.${process.pid}.tmp`);
|
|
79
|
-
fs.writeFileSync(temporaryPath, JSON.stringify({ ...readUpdateState(), ...patch }, null, 2), "utf-8");
|
|
80
|
-
fs.renameSync(temporaryPath, statePath);
|
|
81
|
-
return true;
|
|
82
|
-
} catch (error) {
|
|
83
|
-
logger.debug("Could not write update.json", { error: errorMessage(error) });
|
|
84
|
-
return false;
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
function recordLatestVersion(version) {
|
|
88
|
-
const changed = readUpdateState().latestVersion !== version;
|
|
89
|
-
return writeUpdateState(changed ? { latestVersion: version, latestSeenEpochSeconds: nowEpochSeconds() } : { latestVersion: version });
|
|
90
|
-
}
|
|
91
|
-
function moveDeclinedInstallToVersion(execPath, newVersion) {
|
|
92
|
-
if (readUpdateState().declinedInstallPath?.toLowerCase() === execPath.toLowerCase()) {
|
|
93
|
-
writeUpdateState({ declinedInstallVersion: newVersion });
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// src/devices/terminal/nodePtyRuntime.ts
|
|
98
|
-
import crypto from "crypto";
|
|
99
|
-
import fs2 from "fs";
|
|
100
|
-
import path2 from "path";
|
|
101
|
-
import { createRequire } from "module";
|
|
102
|
-
var require2 = createRequire(import.meta.url);
|
|
103
|
-
var PACKAGE_NAME = "node-pty";
|
|
104
|
-
var NATIVE_FILE = "pty.node";
|
|
105
|
-
var SPAWN_HELPER_FILE = "spawn-helper";
|
|
106
|
-
var EXECUTABLE_MODE = 493;
|
|
107
|
-
var EXECUTE_BITS = 73;
|
|
108
|
-
var RUNTIME_DIR_NAME = "runtime";
|
|
109
|
-
var ASAR_ARCHIVE_SUFFIX = ".asar";
|
|
110
|
-
var HASH_LENGTH = 12;
|
|
111
|
-
var NATIVE_DIRECTORIES = [
|
|
112
|
-
path2.join("build", "Release"),
|
|
113
|
-
path2.join("prebuilds", `${process.platform}-${process.arch}`)
|
|
114
|
-
];
|
|
115
|
-
function isPackagedBinary() {
|
|
116
|
-
return Boolean(process.pkg);
|
|
117
|
-
}
|
|
118
|
-
function isInsideAsarArchive(packageRoot) {
|
|
119
|
-
if (!process.versions.electron) return false;
|
|
120
|
-
return packageRoot.split(path2.sep).some((segment) => segment.endsWith(ASAR_ARCHIVE_SUFFIX));
|
|
121
|
-
}
|
|
122
|
-
function resolveNodePtyRoot() {
|
|
123
|
-
const resolvedRoot = path2.dirname(require2.resolve(`${PACKAGE_NAME}/package.json`));
|
|
124
|
-
if (!isPackagedBinary() && !isInsideAsarArchive(resolvedRoot)) return resolvedRoot;
|
|
125
|
-
return unpackNodePty(resolvedRoot);
|
|
126
|
-
}
|
|
127
|
-
function requireNodePty(packageRoot) {
|
|
128
|
-
return require2(packageRoot);
|
|
129
|
-
}
|
|
130
|
-
function spawnHelperPaths(packageRoot, platform = process.platform) {
|
|
131
|
-
if (platform !== "darwin") return [];
|
|
132
|
-
return NATIVE_DIRECTORIES.map((directory) => path2.join(packageRoot, directory, SPAWN_HELPER_FILE));
|
|
133
|
-
}
|
|
134
|
-
function hasExecutableSpawnHelper(packageRoot, platform = process.platform) {
|
|
135
|
-
const helpers = spawnHelperPaths(packageRoot, platform);
|
|
136
|
-
if (helpers.length === 0) return true;
|
|
137
|
-
return helpers.some((helper) => {
|
|
138
|
-
try {
|
|
139
|
-
const stat = fs2.statSync(helper);
|
|
140
|
-
return stat.isFile() && (stat.mode & EXECUTE_BITS) !== 0;
|
|
141
|
-
} catch {
|
|
142
|
-
return false;
|
|
143
|
-
}
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
function makeSpawnHelperExecutable(packageRoot) {
|
|
147
|
-
for (const helper of spawnHelperPaths(packageRoot)) {
|
|
148
|
-
try {
|
|
149
|
-
const stat = fs2.statSync(helper);
|
|
150
|
-
if ((stat.mode & EXECUTE_BITS) === 0) {
|
|
151
|
-
fs2.chmodSync(helper, EXECUTABLE_MODE);
|
|
152
|
-
}
|
|
153
|
-
} catch {
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
function unpackNodePty(snapshotRoot) {
|
|
158
|
-
const unpackedRoot = unpackedRootPath(snapshotRoot);
|
|
159
|
-
if (isCommittedCopy(unpackedRoot)) return unpackedRoot;
|
|
160
|
-
const stagingRoot = `${unpackedRoot}.${process.pid}`;
|
|
161
|
-
fs2.rmSync(stagingRoot, { recursive: true, force: true });
|
|
162
|
-
try {
|
|
163
|
-
copyRuntimeFiles(snapshotRoot, stagingRoot);
|
|
164
|
-
makeSpawnHelperExecutable(stagingRoot);
|
|
165
|
-
fs2.renameSync(stagingRoot, unpackedRoot);
|
|
166
|
-
} catch (error) {
|
|
167
|
-
fs2.rmSync(stagingRoot, { recursive: true, force: true });
|
|
168
|
-
if (!isCommittedCopy(unpackedRoot)) throw error;
|
|
169
|
-
}
|
|
170
|
-
return unpackedRoot;
|
|
171
|
-
}
|
|
172
|
-
function isCommittedCopy(unpackedRoot) {
|
|
173
|
-
return fs2.existsSync(path2.join(unpackedRoot, "package.json"));
|
|
174
|
-
}
|
|
175
|
-
function unpackedRootPath(snapshotRoot) {
|
|
176
|
-
const version = readPackageVersion(snapshotRoot);
|
|
177
|
-
const hash = addonHash(snapshotRoot);
|
|
178
|
-
const directoryName = `${PACKAGE_NAME}-${version}-${process.platform}-${process.arch}-${hash}`;
|
|
179
|
-
return path2.join(getPinggyConfigDir(), RUNTIME_DIR_NAME, directoryName);
|
|
180
|
-
}
|
|
181
|
-
function readPackageVersion(packageRoot) {
|
|
182
|
-
const manifest = JSON.parse(fs2.readFileSync(path2.join(packageRoot, "package.json"), "utf8"));
|
|
183
|
-
return String(manifest.version);
|
|
184
|
-
}
|
|
185
|
-
function addonHash(snapshotRoot) {
|
|
186
|
-
const hash = crypto.createHash("sha256");
|
|
187
|
-
for (const directory of nativeDirectories(snapshotRoot)) {
|
|
188
|
-
hash.update(`${directory}\0`);
|
|
189
|
-
hash.update(fs2.readFileSync(path2.join(snapshotRoot, directory, NATIVE_FILE)));
|
|
190
|
-
}
|
|
191
|
-
return hash.digest("hex").slice(0, HASH_LENGTH);
|
|
192
|
-
}
|
|
193
|
-
function nativeDirectories(packageRoot) {
|
|
194
|
-
return NATIVE_DIRECTORIES.filter((directory) => fs2.existsSync(path2.join(packageRoot, directory, NATIVE_FILE)));
|
|
195
|
-
}
|
|
196
|
-
function copyRuntimeFiles(sourceRoot, targetRoot) {
|
|
197
|
-
fs2.mkdirSync(targetRoot, { recursive: true });
|
|
198
|
-
copyFile(path2.join(sourceRoot, "package.json"), path2.join(targetRoot, "package.json"));
|
|
199
|
-
copyDirectory(path2.join(sourceRoot, "lib"), path2.join(targetRoot, "lib"));
|
|
200
|
-
for (const directory of nativeDirectories(sourceRoot)) {
|
|
201
|
-
copyDirectory(path2.join(sourceRoot, directory), path2.join(targetRoot, directory));
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
function copyDirectory(sourceDirectory, targetDirectory) {
|
|
205
|
-
fs2.mkdirSync(targetDirectory, { recursive: true });
|
|
206
|
-
for (const entry of fs2.readdirSync(sourceDirectory, { withFileTypes: true })) {
|
|
207
|
-
const source = path2.join(sourceDirectory, entry.name);
|
|
208
|
-
const target = path2.join(targetDirectory, entry.name);
|
|
209
|
-
if (entry.isDirectory()) {
|
|
210
|
-
copyDirectory(source, target);
|
|
211
|
-
continue;
|
|
212
|
-
}
|
|
213
|
-
copyFile(source, target);
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
function copyFile(source, target) {
|
|
217
|
-
fs2.writeFileSync(target, fs2.readFileSync(source));
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
// src/update/installKind.ts
|
|
221
|
-
import fs3 from "fs";
|
|
222
|
-
import os from "os";
|
|
223
|
-
import path3 from "path";
|
|
224
|
-
var InstallKind = {
|
|
225
|
-
WindowsWritable: "windows-writable",
|
|
226
|
-
WindowsReadOnly: "windows-read-only",
|
|
227
|
-
UnixLayout: "unix-layout",
|
|
228
|
-
UnixPlainFile: "unix-plain-file",
|
|
229
|
-
UnixLoose: "unix-loose",
|
|
230
|
-
Npm: "npm",
|
|
231
|
-
DevCheckout: "dev-checkout"
|
|
232
|
-
};
|
|
233
|
-
var NODE_MODULES_SEGMENT = "node_modules";
|
|
234
|
-
var WINDOWS_INSTALL_COMMAND = "irm https://pinggy.io/install.ps1 | iex";
|
|
235
|
-
var UNIX_INSTALL_COMMAND = "curl -fsSL https://pinggy.io/install.sh | sh";
|
|
236
|
-
var NPM_INSTALL_COMMAND = "npm i -g pinggy";
|
|
237
|
-
var NPM_UNINSTALL_COMMAND = "npm uninstall -g pinggy";
|
|
238
|
-
function hasPathSegment(candidate, segment) {
|
|
239
|
-
return candidate !== null && candidate.split(/[\\/]/).includes(segment);
|
|
240
|
-
}
|
|
241
|
-
function unixLayoutPaths(homeRealPath) {
|
|
242
|
-
const root = path3.posix.join(homeRealPath, ".pinggy");
|
|
243
|
-
const binDirectory = path3.posix.join(root, "bin");
|
|
244
|
-
return {
|
|
245
|
-
binDirectory,
|
|
246
|
-
link: path3.posix.join(binDirectory, "pinggy"),
|
|
247
|
-
versionsDirectory: path3.posix.join(root, "versions")
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
function detectInstallKind(probe) {
|
|
251
|
-
if (!probe.isPackaged) {
|
|
252
|
-
if (probe.isElectron) return InstallKind.Npm;
|
|
253
|
-
return hasPathSegment(probe.scriptRealPath, NODE_MODULES_SEGMENT) ? InstallKind.Npm : InstallKind.DevCheckout;
|
|
254
|
-
}
|
|
255
|
-
if (probe.platform === "win32") {
|
|
256
|
-
return probe.directoryIsWritable() ? InstallKind.WindowsWritable : InstallKind.WindowsReadOnly;
|
|
257
|
-
}
|
|
258
|
-
const layout = unixLayoutPaths(probe.homeRealPath);
|
|
259
|
-
if (probe.execPath.startsWith(`${layout.versionsDirectory}/`)) return InstallKind.UnixLayout;
|
|
260
|
-
return probe.execPath === layout.link ? InstallKind.UnixPlainFile : InstallKind.UnixLoose;
|
|
261
|
-
}
|
|
262
|
-
function canReplaceItself(kind) {
|
|
263
|
-
return kind === InstallKind.WindowsWritable || kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
|
|
264
|
-
}
|
|
265
|
-
function backgroundInstallKind(kind, execPath, homeRealPath) {
|
|
266
|
-
if (kind !== InstallKind.WindowsWritable) return kind;
|
|
267
|
-
const relative = path3.win32.relative(homeRealPath, execPath);
|
|
268
|
-
const insideProfile = relative !== "" && !relative.startsWith("..") && !path3.win32.isAbsolute(relative);
|
|
269
|
-
return insideProfile ? kind : InstallKind.WindowsReadOnly;
|
|
270
|
-
}
|
|
271
|
-
function installCommandFor(platform) {
|
|
272
|
-
return platform === "win32" ? WINDOWS_INSTALL_COMMAND : UNIX_INSTALL_COMMAND;
|
|
273
|
-
}
|
|
274
|
-
function realPathOr(candidate, fallback) {
|
|
275
|
-
try {
|
|
276
|
-
return fs3.realpathSync(candidate);
|
|
277
|
-
} catch {
|
|
278
|
-
return fallback;
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
function canCreateFileNextTo(filePath) {
|
|
282
|
-
const probePath = path3.join(path3.dirname(filePath), `.pinggy-write-test-${process.pid}`);
|
|
283
|
-
try {
|
|
284
|
-
fs3.closeSync(fs3.openSync(probePath, "wx"));
|
|
285
|
-
fs3.unlinkSync(probePath);
|
|
286
|
-
return true;
|
|
287
|
-
} catch {
|
|
288
|
-
return false;
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
function createInstallProbe() {
|
|
292
|
-
const execPath = process.execPath;
|
|
293
|
-
const scriptPath = process.argv[1];
|
|
294
|
-
return {
|
|
295
|
-
isPackaged: isPackagedBinary(),
|
|
296
|
-
isElectron: Boolean(process.versions.electron),
|
|
297
|
-
platform: process.platform,
|
|
298
|
-
execPath,
|
|
299
|
-
scriptRealPath: scriptPath ? realPathOr(scriptPath, scriptPath) : null,
|
|
300
|
-
homeRealPath: realPathOr(os.homedir(), os.homedir()),
|
|
301
|
-
directoryIsWritable: () => canCreateFileNextTo(execPath)
|
|
302
|
-
};
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// src/daemon/lifecycle/bootId.ts
|
|
306
|
-
import fs4 from "fs";
|
|
307
|
-
import os2 from "os";
|
|
308
|
-
import { execFileSync } from "child_process";
|
|
309
|
-
var LINUX_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id";
|
|
310
|
-
var MACOS_SYSCTL_PATH = "/usr/sbin/sysctl";
|
|
311
|
-
var MACOS_BOOT_ID_KEY = "kern.bootsessionuuid";
|
|
312
|
-
var SYSCTL_TIMEOUT_MILLIS = 2e3;
|
|
313
|
-
var BOOT_TIME_TOLERANCE_MILLIS = 6e4;
|
|
314
|
-
var machineBootIdSources = {
|
|
315
|
-
platform: process.platform,
|
|
316
|
-
readFile: (filePath) => fs4.readFileSync(filePath, "utf-8"),
|
|
317
|
-
runCommand: (command, args) => execFileSync(command, args, {
|
|
318
|
-
encoding: "utf-8",
|
|
319
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
320
|
-
timeout: SYSCTL_TIMEOUT_MILLIS
|
|
321
|
-
})
|
|
322
|
-
};
|
|
323
|
-
var cachedBootId;
|
|
324
|
-
function readBootId(sources) {
|
|
325
|
-
try {
|
|
326
|
-
switch (sources.platform) {
|
|
327
|
-
case "linux":
|
|
328
|
-
return nonEmpty(sources.readFile(LINUX_BOOT_ID_PATH));
|
|
329
|
-
case "darwin":
|
|
330
|
-
return nonEmpty(sources.runCommand(MACOS_SYSCTL_PATH, ["-n", MACOS_BOOT_ID_KEY]));
|
|
331
|
-
default:
|
|
332
|
-
return null;
|
|
333
|
-
}
|
|
334
|
-
} catch {
|
|
335
|
-
return null;
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
function currentBootId() {
|
|
339
|
-
if (cachedBootId === void 0) {
|
|
340
|
-
cachedBootId = readBootId(machineBootIdSources);
|
|
341
|
-
}
|
|
342
|
-
return cachedBootId;
|
|
343
|
-
}
|
|
344
|
-
function startedInEarlierBoot(recordedBootId, startedAt, bootId = currentBootId()) {
|
|
345
|
-
if (typeof recordedBootId === "string" && recordedBootId.length > 0 && bootId) {
|
|
346
|
-
return recordedBootId !== bootId;
|
|
347
|
-
}
|
|
348
|
-
return startedBeforeBoot(startedAt);
|
|
349
|
-
}
|
|
350
|
-
function startedBeforeBoot(startedAt) {
|
|
351
|
-
const startedAtMillis = Date.parse(startedAt);
|
|
352
|
-
const bootMillis = Date.now() - os2.uptime() * 1e3;
|
|
353
|
-
return Number.isNaN(startedAtMillis) || startedAtMillis < bootMillis - BOOT_TIME_TOLERANCE_MILLIS;
|
|
354
|
-
}
|
|
355
|
-
function nonEmpty(text) {
|
|
356
|
-
const trimmed = text.trim();
|
|
357
|
-
return trimmed.length > 0 ? trimmed : null;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// src/daemon/lifecycle/daemonManager.ts
|
|
361
|
-
import os4 from "os";
|
|
362
|
-
import fs6 from "fs";
|
|
363
|
-
import { spawn } from "child_process";
|
|
364
|
-
|
|
365
|
-
// src/daemon/lifecycle/serviceInstaller.ts
|
|
366
|
-
import os3 from "os";
|
|
367
|
-
import fs5 from "fs";
|
|
368
|
-
import path4 from "path";
|
|
369
|
-
import { execSync, execFileSync as execFileSync2 } from "child_process";
|
|
370
|
-
var SERVICE_LABEL = "io.pinggy.agent";
|
|
371
|
-
var SYSTEMD_SERVICE_NAME = "pinggy";
|
|
372
|
-
var SERVICE_ANY_LOCATION_ENV = "PINGGY_SERVICE_ANY_LOCATION";
|
|
373
|
-
function installerBinaryPath(platform, home, env) {
|
|
374
|
-
if (platform === "win32") {
|
|
375
|
-
const localAppData = env.LOCALAPPDATA || path4.win32.join(home, "AppData", "Local");
|
|
376
|
-
return path4.win32.join(localAppData, "Pinggy", "bin", "pinggy.exe");
|
|
377
|
-
}
|
|
378
|
-
return path4.posix.join(home, ".pinggy", "bin", "pinggy");
|
|
379
|
-
}
|
|
380
|
-
function realPath(p) {
|
|
381
|
-
try {
|
|
382
|
-
return fs5.realpathSync(p);
|
|
383
|
-
} catch {
|
|
384
|
-
return p;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
function serviceProgramPath(ctx) {
|
|
388
|
-
if (ctx.platform === "win32") return ctx.execPath;
|
|
389
|
-
const kind = detectInstallKind({
|
|
390
|
-
isPackaged: ctx.isPkg,
|
|
391
|
-
isElectron: false,
|
|
392
|
-
platform: ctx.platform,
|
|
393
|
-
execPath: ctx.execPath,
|
|
394
|
-
scriptRealPath: null,
|
|
395
|
-
homeRealPath: realPath(ctx.home),
|
|
396
|
-
directoryIsWritable: () => false
|
|
397
|
-
});
|
|
398
|
-
const inLayout = kind === InstallKind.UnixLayout || kind === InstallKind.UnixPlainFile;
|
|
399
|
-
return inLayout ? installerBinaryPath(ctx.platform, ctx.home, ctx.env) : ctx.execPath;
|
|
400
|
-
}
|
|
401
|
-
function isInstallerBinary(ctx) {
|
|
402
|
-
const actual = realPath(ctx.execPath);
|
|
403
|
-
const expected = realPath(installerBinaryPath(ctx.platform, ctx.home, ctx.env));
|
|
404
|
-
if (ctx.platform === "win32") return actual.toLowerCase() === expected.toLowerCase();
|
|
405
|
-
return actual === expected;
|
|
406
|
-
}
|
|
407
|
-
function installerFix(platform) {
|
|
408
|
-
return [
|
|
409
|
-
"pinggy can only run as a service when it is installed with the Pinggy installer.",
|
|
410
|
-
"Install it, then run this command again:",
|
|
411
|
-
` ${installCommandFor(platform)}`,
|
|
412
|
-
" pinggy daemon service-install"
|
|
413
|
-
].join("\n");
|
|
414
|
-
}
|
|
415
|
-
function npmInstallerFix(platform) {
|
|
416
|
-
return [
|
|
417
|
-
"The npm version of pinggy cannot run as a service.",
|
|
418
|
-
"Remove it, install pinggy with the Pinggy installer, then run this command again:",
|
|
419
|
-
` ${NPM_UNINSTALL_COMMAND}`,
|
|
420
|
-
` ${installCommandFor(platform)}`,
|
|
421
|
-
" pinggy daemon service-install"
|
|
422
|
-
].join("\n");
|
|
423
|
-
}
|
|
424
|
-
function installedCopyFix(installedPath) {
|
|
425
|
-
return [
|
|
426
|
-
"This pinggy is not the installed one. Run this command with the installed copy:",
|
|
427
|
-
` ${installedPath} daemon service-install`
|
|
428
|
-
].join("\n");
|
|
429
|
-
}
|
|
430
|
-
function serviceInstallRefusal(ctx, fileExists = fs5.existsSync) {
|
|
431
|
-
if (!ctx.isPkg) return npmInstallerFix(ctx.platform);
|
|
432
|
-
if (ctx.env[SERVICE_ANY_LOCATION_ENV] === "1" || isInstallerBinary(ctx)) return null;
|
|
433
|
-
const installedPath = installerBinaryPath(ctx.platform, ctx.home, ctx.env);
|
|
434
|
-
if (fileExists(installedPath)) return installedCopyFix(installedPath);
|
|
435
|
-
return installerFix(ctx.platform);
|
|
436
|
-
}
|
|
437
|
-
function printInstalled() {
|
|
438
|
-
printer_default.success("pinggy now starts automatically when this computer starts.");
|
|
439
|
-
}
|
|
440
|
-
function printUninstalled() {
|
|
441
|
-
printer_default.success("pinggy no longer starts automatically when this computer starts.");
|
|
442
|
-
}
|
|
443
|
-
function printNotInstalled() {
|
|
444
|
-
printer_default.print("pinggy is not set to start automatically.");
|
|
445
|
-
}
|
|
446
|
-
var QUIET = { stdio: ["ignore", "ignore", "pipe"] };
|
|
447
|
-
function toolError(err) {
|
|
448
|
-
const stderr = err.stderr?.toString().trim();
|
|
449
|
-
return stderr ? stderr.replace(/^ERROR:\s*/i, "") : errorMessage(err);
|
|
450
|
-
}
|
|
451
|
-
function getSystemdServicePath() {
|
|
452
|
-
const dir = path4.join(os3.homedir(), ".config", "systemd", "user");
|
|
453
|
-
return path4.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
|
|
454
|
-
}
|
|
455
|
-
function generateSystemdUnit(program) {
|
|
456
|
-
const execStart = `${program} --_daemon-child`;
|
|
457
|
-
return `[Unit]
|
|
458
|
-
Description=Pinggy Tunnel Daemon
|
|
459
|
-
After=network-online.target
|
|
460
|
-
Wants=network-online.target
|
|
461
|
-
|
|
462
|
-
[Service]
|
|
463
|
-
Type=simple
|
|
464
|
-
ExecStart=${execStart}
|
|
465
|
-
Restart=on-failure
|
|
466
|
-
RestartSec=5
|
|
467
|
-
|
|
468
|
-
[Install]
|
|
469
|
-
WantedBy=default.target
|
|
470
|
-
`;
|
|
471
|
-
}
|
|
472
|
-
function installSystemd(program) {
|
|
473
|
-
const servicePath = getSystemdServicePath();
|
|
474
|
-
const dir = path4.dirname(servicePath);
|
|
475
|
-
fs5.mkdirSync(dir, { recursive: true });
|
|
476
|
-
fs5.writeFileSync(servicePath, generateSystemdUnit(program), "utf-8");
|
|
477
|
-
execSync("systemctl --user daemon-reload", QUIET);
|
|
478
|
-
execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`, QUIET);
|
|
479
|
-
execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`, QUIET);
|
|
480
|
-
logger.info("systemd user service installed", { servicePath });
|
|
481
|
-
printInstalled();
|
|
482
|
-
enableLinger(os3.userInfo().username);
|
|
483
|
-
}
|
|
484
|
-
function lingerEnabled(username) {
|
|
485
|
-
try {
|
|
486
|
-
const output = execFileSync2("loginctl", ["show-user", username, "--property=Linger"], {
|
|
487
|
-
encoding: "utf-8",
|
|
488
|
-
stdio: ["ignore", "pipe", "ignore"]
|
|
489
|
-
});
|
|
490
|
-
return output.trim() === "Linger=yes";
|
|
491
|
-
} catch {
|
|
492
|
-
return false;
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
function enableLinger(username) {
|
|
496
|
-
if (lingerEnabled(username)) return;
|
|
497
|
-
try {
|
|
498
|
-
execFileSync2("loginctl", ["--no-ask-password", "enable-linger", username], QUIET);
|
|
499
|
-
logger.info("systemd lingering enabled", { username });
|
|
500
|
-
} catch (err) {
|
|
501
|
-
logger.warn("loginctl enable-linger failed", { error: errorMessage(err) });
|
|
502
|
-
printer_default.print(`pinggy starts when ${username} signs in. To start it before anyone signs in, run: loginctl enable-linger ${username}`);
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
function uninstallSystemd() {
|
|
506
|
-
const servicePath = getSystemdServicePath();
|
|
507
|
-
try {
|
|
508
|
-
execSync(`systemctl --user stop ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
|
|
509
|
-
execSync(`systemctl --user disable ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
|
|
510
|
-
} catch {
|
|
511
|
-
}
|
|
512
|
-
if (fs5.existsSync(servicePath)) {
|
|
513
|
-
fs5.unlinkSync(servicePath);
|
|
514
|
-
execSync("systemctl --user daemon-reload", QUIET);
|
|
515
|
-
logger.info("systemd user service removed", { servicePath });
|
|
516
|
-
printUninstalled();
|
|
517
|
-
} else {
|
|
518
|
-
printNotInstalled();
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
function getLaunchdPlistPath() {
|
|
522
|
-
return path4.join(os3.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
|
|
523
|
-
}
|
|
524
|
-
function generateLaunchdPlist(program) {
|
|
525
|
-
const allArgs = [program, "--_daemon-child"];
|
|
526
|
-
const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
|
|
527
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
528
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
|
|
529
|
-
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
530
|
-
<plist version="1.0">
|
|
531
|
-
<dict>
|
|
532
|
-
<key>Label</key>
|
|
533
|
-
<string>${SERVICE_LABEL}</string>
|
|
534
|
-
<key>ProgramArguments</key>
|
|
535
|
-
<array>
|
|
536
|
-
${programArgs}
|
|
537
|
-
</array>
|
|
538
|
-
<key>RunAtLoad</key>
|
|
539
|
-
<true/>
|
|
540
|
-
<key>KeepAlive</key>
|
|
541
|
-
<false/>
|
|
542
|
-
</dict>
|
|
543
|
-
</plist>
|
|
544
|
-
`;
|
|
545
|
-
}
|
|
546
|
-
function installLaunchd(program) {
|
|
547
|
-
const plistPath = getLaunchdPlistPath();
|
|
548
|
-
const dir = path4.dirname(plistPath);
|
|
549
|
-
fs5.mkdirSync(dir, { recursive: true });
|
|
550
|
-
fs5.writeFileSync(plistPath, generateLaunchdPlist(program), "utf-8");
|
|
551
|
-
const uid = process.getuid?.() ?? 501;
|
|
552
|
-
try {
|
|
553
|
-
execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
|
|
554
|
-
} catch {
|
|
555
|
-
}
|
|
556
|
-
loadLaunchdPlist(uid, plistPath);
|
|
557
|
-
logger.info("launchd agent installed", { plistPath });
|
|
558
|
-
printInstalled();
|
|
559
|
-
}
|
|
560
|
-
function loadLaunchdPlist(uid, plistPath) {
|
|
561
|
-
try {
|
|
562
|
-
execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
|
|
563
|
-
} catch {
|
|
564
|
-
try {
|
|
565
|
-
execSync(`launchctl load -w ${plistPath}`);
|
|
566
|
-
} catch {
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
function uninstallLaunchd() {
|
|
571
|
-
const plistPath = getLaunchdPlistPath();
|
|
572
|
-
const uid = process.getuid?.() ?? 501;
|
|
573
|
-
try {
|
|
574
|
-
execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
|
|
575
|
-
} catch {
|
|
576
|
-
try {
|
|
577
|
-
execSync(`launchctl unload ${plistPath} 2>/dev/null || true`);
|
|
578
|
-
} catch {
|
|
579
|
-
}
|
|
580
|
-
}
|
|
581
|
-
if (fs5.existsSync(plistPath)) {
|
|
582
|
-
fs5.unlinkSync(plistPath);
|
|
583
|
-
logger.info("launchd agent removed", { plistPath });
|
|
584
|
-
printUninstalled();
|
|
585
|
-
} else {
|
|
586
|
-
printNotInstalled();
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
var WINDOWS_TASK_NAME = "PinggyDaemon";
|
|
590
|
-
function escapeXml(value) {
|
|
591
|
-
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
592
|
-
}
|
|
593
|
-
function getWindowsUserId() {
|
|
594
|
-
const user = process.env.USERNAME || os3.userInfo().username;
|
|
595
|
-
const domain = process.env.USERDOMAIN;
|
|
596
|
-
return domain ? `${domain}\\${user}` : user;
|
|
597
|
-
}
|
|
598
|
-
function generateTaskXml(program, userId) {
|
|
599
|
-
const user = escapeXml(userId);
|
|
600
|
-
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
601
|
-
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
602
|
-
<Triggers>
|
|
603
|
-
<LogonTrigger>
|
|
604
|
-
<Enabled>true</Enabled>
|
|
605
|
-
<UserId>${user}</UserId>
|
|
606
|
-
</LogonTrigger>
|
|
607
|
-
</Triggers>
|
|
608
|
-
<Principals>
|
|
609
|
-
<Principal id="Author">
|
|
610
|
-
<UserId>${user}</UserId>
|
|
611
|
-
<LogonType>InteractiveToken</LogonType>
|
|
612
|
-
<RunLevel>LeastPrivilege</RunLevel>
|
|
613
|
-
</Principal>
|
|
614
|
-
</Principals>
|
|
615
|
-
<Settings>
|
|
616
|
-
<Hidden>true</Hidden>
|
|
617
|
-
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
618
|
-
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
619
|
-
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
620
|
-
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
621
|
-
<RestartOnFailure>
|
|
622
|
-
<Interval>PT1M</Interval>
|
|
623
|
-
<Count>3</Count>
|
|
624
|
-
</RestartOnFailure>
|
|
625
|
-
</Settings>
|
|
626
|
-
<Actions>
|
|
627
|
-
<Exec>
|
|
628
|
-
<Command>${escapeXml(program)}</Command>
|
|
629
|
-
<Arguments>daemon start</Arguments>
|
|
630
|
-
</Exec>
|
|
631
|
-
</Actions>
|
|
632
|
-
</Task>`;
|
|
633
|
-
}
|
|
634
|
-
function createWindowsTask(program) {
|
|
635
|
-
const xml = generateTaskXml(program, getWindowsUserId());
|
|
636
|
-
const tmpPath = path4.join(os3.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
|
|
637
|
-
fs5.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
|
|
638
|
-
try {
|
|
639
|
-
execFileSync2("schtasks", ["/Create", "/TN", WINDOWS_TASK_NAME, "/XML", tmpPath, "/F"], QUIET);
|
|
640
|
-
} finally {
|
|
641
|
-
try {
|
|
642
|
-
fs5.unlinkSync(tmpPath);
|
|
643
|
-
} catch {
|
|
644
|
-
}
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
function windowsTaskExists() {
|
|
648
|
-
try {
|
|
649
|
-
execFileSync2("schtasks", ["/Query", "/TN", WINDOWS_TASK_NAME], QUIET);
|
|
650
|
-
return true;
|
|
651
|
-
} catch {
|
|
652
|
-
return false;
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
function isElevated() {
|
|
656
|
-
try {
|
|
657
|
-
return /S-1-16-(12288|16384)\b/.test(execFileSync2("whoami", ["/groups"], { encoding: "utf-8" }));
|
|
658
|
-
} catch {
|
|
659
|
-
return false;
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
function windowsTaskError(action, undo, err) {
|
|
663
|
-
if (windowsTaskExists() && !isElevated()) {
|
|
664
|
-
return `Could not ${action}. It was set up from an Administrator terminal. Run this command from an Administrator terminal to ${undo}.`;
|
|
665
|
-
}
|
|
666
|
-
return `Could not ${action}: ${toolError(err)}`;
|
|
667
|
-
}
|
|
668
|
-
function installWindows(program) {
|
|
669
|
-
try {
|
|
670
|
-
createWindowsTask(program);
|
|
671
|
-
execFileSync2("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], QUIET);
|
|
672
|
-
} catch (err) {
|
|
673
|
-
printer_default.error(windowsTaskError("set pinggy to start automatically", "change it", err));
|
|
674
|
-
process.exit(1);
|
|
675
|
-
}
|
|
676
|
-
logger.info("Scheduled task installed", { task: WINDOWS_TASK_NAME });
|
|
677
|
-
printInstalled();
|
|
678
|
-
}
|
|
679
|
-
async function uninstallWindows() {
|
|
680
|
-
if (!windowsTaskExists()) {
|
|
681
|
-
printNotInstalled();
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
684
|
-
try {
|
|
685
|
-
execFileSync2("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], QUIET);
|
|
686
|
-
} catch (err) {
|
|
687
|
-
printer_default.error(windowsTaskError("stop pinggy from starting automatically", "turn it off", err));
|
|
688
|
-
process.exit(1);
|
|
689
|
-
}
|
|
690
|
-
logger.info("Scheduled task removed", { task: WINDOWS_TASK_NAME });
|
|
691
|
-
if (isDaemonRunning()) {
|
|
692
|
-
const result = await stopDaemon();
|
|
693
|
-
if (!result.ok) console.log(`Could not stop the daemon: ${result.error}`);
|
|
694
|
-
}
|
|
695
|
-
printUninstalled();
|
|
696
|
-
}
|
|
697
|
-
function readServiceEntryText() {
|
|
698
|
-
const platform = os3.platform();
|
|
699
|
-
if (platform !== "linux" && platform !== "darwin") return "";
|
|
700
|
-
try {
|
|
701
|
-
return fs5.readFileSync(platform === "linux" ? getSystemdServicePath() : getLaunchdPlistPath(), "utf-8");
|
|
702
|
-
} catch {
|
|
703
|
-
return "";
|
|
704
|
-
}
|
|
705
|
-
}
|
|
706
|
-
var SERVICE_QUERY_TIMEOUT_MILLIS = 2e3;
|
|
707
|
-
function runServiceQuery(command, args) {
|
|
708
|
-
return execFileSync2(command, args, { encoding: "utf-8", timeout: SERVICE_QUERY_TIMEOUT_MILLIS, stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
|
|
709
|
-
}
|
|
710
|
-
function serviceRestartInstruction(info, platform = os3.platform(), query = runServiceQuery, uid = process.getuid?.() ?? 501) {
|
|
711
|
-
try {
|
|
712
|
-
if (platform === "linux") {
|
|
713
|
-
const mainPid = query("systemctl", ["--user", "show", "-p", "MainPID", "--value", SYSTEMD_SERVICE_NAME]).trim();
|
|
714
|
-
return mainPid === String(info.pid) ? `"systemctl --user restart ${SYSTEMD_SERVICE_NAME}"` : null;
|
|
715
|
-
}
|
|
716
|
-
if (platform === "darwin") {
|
|
717
|
-
const target = `gui/${uid}/${SERVICE_LABEL}`;
|
|
718
|
-
const pid = /^\s*pid = (\d+)/m.exec(query("launchctl", ["print", target]))?.[1];
|
|
719
|
-
return pid === String(info.pid) ? `"launchctl kickstart -k ${target}"` : null;
|
|
720
|
-
}
|
|
721
|
-
} catch {
|
|
722
|
-
return null;
|
|
723
|
-
}
|
|
724
|
-
return null;
|
|
725
|
-
}
|
|
726
|
-
function installService() {
|
|
727
|
-
const platform = os3.platform();
|
|
728
|
-
const context = {
|
|
729
|
-
platform,
|
|
730
|
-
isPkg: "pkg" in process,
|
|
731
|
-
execPath: process.execPath,
|
|
732
|
-
home: os3.homedir(),
|
|
733
|
-
env: process.env
|
|
734
|
-
};
|
|
735
|
-
const refusal = serviceInstallRefusal(context);
|
|
736
|
-
if (refusal) {
|
|
737
|
-
console.error(refusal);
|
|
738
|
-
process.exit(1);
|
|
739
|
-
}
|
|
740
|
-
const program = serviceProgramPath(context);
|
|
741
|
-
switch (platform) {
|
|
742
|
-
case "linux":
|
|
743
|
-
installSystemd(program);
|
|
744
|
-
break;
|
|
745
|
-
case "darwin":
|
|
746
|
-
installLaunchd(program);
|
|
747
|
-
break;
|
|
748
|
-
case "win32":
|
|
749
|
-
installWindows(program);
|
|
750
|
-
break;
|
|
751
|
-
default:
|
|
752
|
-
console.error(`Unsupported platform: ${platform}`);
|
|
753
|
-
process.exit(1);
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
async function uninstallService() {
|
|
757
|
-
const platform = os3.platform();
|
|
758
|
-
switch (platform) {
|
|
759
|
-
case "linux":
|
|
760
|
-
uninstallSystemd();
|
|
761
|
-
break;
|
|
762
|
-
case "darwin":
|
|
763
|
-
uninstallLaunchd();
|
|
764
|
-
break;
|
|
765
|
-
case "win32":
|
|
766
|
-
await uninstallWindows();
|
|
767
|
-
break;
|
|
768
|
-
default:
|
|
769
|
-
console.error(`Unsupported platform: ${platform}`);
|
|
770
|
-
process.exit(1);
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
// src/daemon/lifecycle/daemonManager.ts
|
|
775
|
-
var inProcessHandle = null;
|
|
776
|
-
var DAEMON_SPAWN_TIMEOUT_MS = 8e3;
|
|
777
|
-
var DAEMON_POLL_INTERVAL_MS = 200;
|
|
778
|
-
var SPAWN_FAILED_EXIT_CODE = -1;
|
|
779
|
-
var DAEMON_STOP_INSTRUCTION = '"pinggy daemon stop"';
|
|
780
|
-
function isProcessAlive(pid) {
|
|
781
|
-
try {
|
|
782
|
-
process.kill(pid, 0);
|
|
783
|
-
return true;
|
|
784
|
-
} catch (err) {
|
|
785
|
-
return err.code === "EPERM";
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
function getDaemonInfo() {
|
|
789
|
-
const infoPath = getDaemonInfoPath();
|
|
790
|
-
if (!fs6.existsSync(infoPath)) return null;
|
|
791
|
-
try {
|
|
792
|
-
const data = JSON.parse(fs6.readFileSync(infoPath, "utf-8"));
|
|
793
|
-
if (!data.pid || !data.port) return null;
|
|
794
|
-
if (startedInEarlierBoot(data.bootId, data.startedAt) || !isProcessAlive(data.pid)) {
|
|
795
|
-
logger.info("Stale daemon.json found, cleaning up", { stalePid: data.pid });
|
|
796
|
-
try {
|
|
797
|
-
fs6.unlinkSync(infoPath);
|
|
798
|
-
} catch {
|
|
799
|
-
}
|
|
800
|
-
return null;
|
|
801
|
-
}
|
|
802
|
-
return data;
|
|
803
|
-
} catch {
|
|
804
|
-
return null;
|
|
805
|
-
}
|
|
806
|
-
}
|
|
807
|
-
function isDaemonRunning() {
|
|
808
|
-
return getDaemonInfo() !== null;
|
|
809
|
-
}
|
|
810
|
-
function daemonIpcVersion(info) {
|
|
811
|
-
return info.ipcVersion ?? 0;
|
|
812
|
-
}
|
|
813
|
-
function isIpcCompatible(info) {
|
|
814
|
-
return daemonIpcVersion(info) === IPC_VERSION;
|
|
815
|
-
}
|
|
816
|
-
function ipcMismatchMessage(info) {
|
|
817
|
-
const versions = `daemon IPC v${daemonIpcVersion(info)}, this CLI expects v${IPC_VERSION}`;
|
|
818
|
-
if (info.host === DaemonHost.APP) {
|
|
819
|
-
return `The Pinggy app is running a daemon from a different version (${versions}). Update or restart the Pinggy app.`;
|
|
820
|
-
}
|
|
821
|
-
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.`;
|
|
822
|
-
}
|
|
823
|
-
function printDaemonVersionNoticeOnce(info, restartInstruction = serviceRestartInstruction, running = getVersion()) {
|
|
824
|
-
if (process.stdout.isTTY !== true || info.host === DaemonHost.APP) return;
|
|
825
|
-
if (!running || info.cliVersion === running || readUpdateState().lastDaemonNoticeVersion === running) return;
|
|
826
|
-
const runs = info.cliVersion ? `The daemon runs ${info.cliVersion}.` : "The daemon runs an older version.";
|
|
827
|
-
const instruction = restartInstruction(info) ?? DAEMON_STOP_INSTRUCTION;
|
|
828
|
-
if (writeUpdateState({ lastDaemonNoticeVersion: running })) {
|
|
829
|
-
printer_default.print(`${runs} Run ${instruction} to start ${running}. This stops all running tunnels.`);
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
var installedBinaryForDaemon = null;
|
|
833
|
-
function startDaemonFromInstalledBinary(binaryPath) {
|
|
834
|
-
installedBinaryForDaemon = binaryPath;
|
|
835
|
-
}
|
|
836
|
-
function getDaemonSpawnArgs(isPackaged = isPackagedBinary(), executableExists = fs6.existsSync(process.execPath), linkPath = unixLayoutPaths(os4.homedir()).link, installedBinary = installedBinaryForDaemon) {
|
|
837
|
-
if (isPackaged && installedBinary) {
|
|
838
|
-
return { command: installedBinary, args: ["--_daemon-child"], env: { ...process.env } };
|
|
839
|
-
}
|
|
840
|
-
if (isPackaged && !executableExists) {
|
|
841
|
-
return { command: linkPath, args: ["--_daemon-child"], env: { ...process.env } };
|
|
842
|
-
}
|
|
843
|
-
return {
|
|
844
|
-
command: process.execPath,
|
|
845
|
-
args: [process.argv[1], "--_daemon-child"],
|
|
846
|
-
env: { ...process.env }
|
|
847
|
-
};
|
|
848
|
-
}
|
|
849
|
-
async function startDaemon() {
|
|
850
|
-
const existing = getDaemonInfo();
|
|
851
|
-
if (existing) {
|
|
852
|
-
return existing;
|
|
853
|
-
}
|
|
854
|
-
const { command, args, env } = getDaemonSpawnArgs();
|
|
855
|
-
logger.info("Spawning daemon child", { command, args });
|
|
856
|
-
let stderrOutput = "";
|
|
857
|
-
let exited = false;
|
|
858
|
-
let exitCode = null;
|
|
859
|
-
const child = spawn(command, args, {
|
|
860
|
-
detached: true,
|
|
861
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
862
|
-
env,
|
|
863
|
-
...os4.platform() === "win32" ? { windowsHide: true } : {}
|
|
864
|
-
});
|
|
865
|
-
child.stderr?.on("data", (chunk) => {
|
|
866
|
-
stderrOutput += chunk.toString("utf-8");
|
|
867
|
-
});
|
|
868
|
-
child.on("exit", (code) => {
|
|
869
|
-
exited = true;
|
|
870
|
-
exitCode = code;
|
|
871
|
-
});
|
|
872
|
-
child.on("error", (error) => {
|
|
873
|
-
exited = true;
|
|
874
|
-
exitCode = SPAWN_FAILED_EXIT_CODE;
|
|
875
|
-
stderrOutput = errorMessage(error);
|
|
876
|
-
});
|
|
877
|
-
child.unref();
|
|
878
|
-
const info = await pollForDaemonInfo(DAEMON_SPAWN_TIMEOUT_MS, () => exited && exitCode !== 0);
|
|
879
|
-
if (!info) {
|
|
880
|
-
const logPath = getDaemonLogPath();
|
|
881
|
-
if (exited) {
|
|
882
|
-
const detail = stderrOutput.trim() || `Check ${logPath} for details.`;
|
|
883
|
-
throw new Error(`Daemon child exited with code ${exitCode}. ${detail}`);
|
|
884
|
-
}
|
|
885
|
-
throw new Error(`Daemon failed to start within timeout. Check ${logPath} for details.`);
|
|
886
|
-
}
|
|
887
|
-
child.stderr?.removeAllListeners();
|
|
888
|
-
child.stderr?.destroy();
|
|
889
|
-
return info;
|
|
890
|
-
}
|
|
891
|
-
async function ensureDaemonRunning() {
|
|
892
|
-
const existing = getDaemonInfo();
|
|
893
|
-
if (existing) {
|
|
894
|
-
if (!isIpcCompatible(existing)) throw new Error(ipcMismatchMessage(existing));
|
|
895
|
-
return existing;
|
|
896
|
-
}
|
|
897
|
-
if (process.versions.electron) {
|
|
898
|
-
const { runDaemonChild } = await import("./daemonChild-WTZ7X6SZ.js");
|
|
899
|
-
const handle = await runDaemonChild({
|
|
900
|
-
installSignalHandlers: false,
|
|
901
|
-
exitOnFailure: false,
|
|
902
|
-
host: DaemonHost.APP
|
|
903
|
-
});
|
|
904
|
-
inProcessHandle = handle;
|
|
905
|
-
return getDaemonInfo() ?? {
|
|
906
|
-
pid: handle.pid,
|
|
907
|
-
port: handle.port,
|
|
908
|
-
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
909
|
-
host: DaemonHost.APP,
|
|
910
|
-
ipcVersion: IPC_VERSION
|
|
911
|
-
};
|
|
912
|
-
}
|
|
913
|
-
return startDaemon();
|
|
914
|
-
}
|
|
915
|
-
function getInProcessDaemonHandle() {
|
|
916
|
-
return inProcessHandle;
|
|
917
|
-
}
|
|
918
|
-
async function getActiveTunnelSummaries(origin = "app") {
|
|
919
|
-
const info = getDaemonInfo();
|
|
920
|
-
if (!info) return [];
|
|
921
|
-
const { IPCClient } = await import("./ipcClient-IZ5R6TPN.js");
|
|
922
|
-
const client = new IPCClient(info.port, origin);
|
|
923
|
-
let tunnels;
|
|
924
|
-
try {
|
|
925
|
-
tunnels = await client.listTunnels();
|
|
926
|
-
} catch (err) {
|
|
927
|
-
logger.warn("Failed to list tunnels from daemon", { error: errorMessage(err) });
|
|
928
|
-
return [];
|
|
929
|
-
}
|
|
930
|
-
if (!Array.isArray(tunnels)) return [];
|
|
931
|
-
return tunnels.filter((t) => {
|
|
932
|
-
const state = t?.status?.state;
|
|
933
|
-
return state !== "closed" /* Closed */ && state !== "exited" /* Exited */;
|
|
934
|
-
}).map((t) => ({
|
|
935
|
-
tunnelId: t.tunnelid,
|
|
936
|
-
name: t.tunnelconfig?.name || t.tunnelid.slice(0, 8),
|
|
937
|
-
localAddress: getLocalAddress(t.tunnelconfig),
|
|
938
|
-
urls: t.remoteurls ?? []
|
|
939
|
-
}));
|
|
940
|
-
}
|
|
941
|
-
function pollForDaemonInfo(timeoutMs, hasExited) {
|
|
942
|
-
return new Promise((resolve) => {
|
|
943
|
-
const start = Date.now();
|
|
944
|
-
const check = () => {
|
|
945
|
-
const info = getDaemonInfo();
|
|
946
|
-
if (info) {
|
|
947
|
-
resolve(info);
|
|
948
|
-
return;
|
|
949
|
-
}
|
|
950
|
-
if (hasExited?.()) {
|
|
951
|
-
resolve(null);
|
|
952
|
-
return;
|
|
953
|
-
}
|
|
954
|
-
if (Date.now() - start > timeoutMs) {
|
|
955
|
-
resolve(null);
|
|
956
|
-
return;
|
|
957
|
-
}
|
|
958
|
-
setTimeout(check, DAEMON_POLL_INTERVAL_MS);
|
|
959
|
-
};
|
|
960
|
-
check();
|
|
961
|
-
});
|
|
962
|
-
}
|
|
963
|
-
async function stopDaemon() {
|
|
964
|
-
const info = getDaemonInfo();
|
|
965
|
-
if (!info) return { ok: false, error: "No daemon is running." };
|
|
966
|
-
let daemonErrors = [];
|
|
967
|
-
try {
|
|
968
|
-
const { IPCClient } = await import("./ipcClient-IZ5R6TPN.js");
|
|
969
|
-
const client = new IPCClient(info.port);
|
|
970
|
-
const result = await client.shutdown();
|
|
971
|
-
logger.debug("Sent shutdown command to daemon", { result });
|
|
972
|
-
if (result?.status === ShutdownStatus.RefusedInApp) {
|
|
973
|
-
return {
|
|
974
|
-
ok: false,
|
|
975
|
-
reason: DaemonHost.APP,
|
|
976
|
-
error: "The daemon is running inside the Pinggy app."
|
|
977
|
-
};
|
|
978
|
-
}
|
|
979
|
-
if (Array.isArray(result?.errors)) daemonErrors = result.errors;
|
|
980
|
-
} catch (e) {
|
|
981
|
-
return { ok: false, error: `Failed to reach daemon: ${errorMessage(e)}` };
|
|
982
|
-
}
|
|
983
|
-
const exited = await waitForExit(info.pid, 5e3);
|
|
984
|
-
if (!exited) {
|
|
985
|
-
const detail = daemonErrors.length > 0 ? ` Daemon reported: ${daemonErrors.join("; ")}` : "";
|
|
986
|
-
return { ok: false, error: `Daemon PID ${info.pid} did not exit within 5s.${detail}` };
|
|
987
|
-
}
|
|
988
|
-
if (daemonErrors.length > 0) {
|
|
989
|
-
return { ok: false, error: `Daemon exited but reported errors: ${daemonErrors.join("; ")}` };
|
|
990
|
-
}
|
|
991
|
-
return { ok: true };
|
|
992
|
-
}
|
|
993
|
-
async function waitForExit(pid, timeoutMs) {
|
|
994
|
-
const deadline = Date.now() + timeoutMs;
|
|
995
|
-
while (Date.now() < deadline) {
|
|
996
|
-
if (!isProcessAlive(pid)) return true;
|
|
997
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
998
|
-
}
|
|
999
|
-
return !isProcessAlive(pid);
|
|
1000
|
-
}
|
|
1001
|
-
|
|
1002
|
-
export {
|
|
1003
|
-
nowEpochSeconds,
|
|
1004
|
-
readUpdateState,
|
|
1005
|
-
writeUpdateState,
|
|
1006
|
-
recordLatestVersion,
|
|
1007
|
-
moveDeclinedInstallToVersion,
|
|
1008
|
-
isPackagedBinary,
|
|
1009
|
-
resolveNodePtyRoot,
|
|
1010
|
-
requireNodePty,
|
|
1011
|
-
hasExecutableSpawnHelper,
|
|
1012
|
-
makeSpawnHelperExecutable,
|
|
1013
|
-
InstallKind,
|
|
1014
|
-
NPM_INSTALL_COMMAND,
|
|
1015
|
-
hasPathSegment,
|
|
1016
|
-
unixLayoutPaths,
|
|
1017
|
-
detectInstallKind,
|
|
1018
|
-
canReplaceItself,
|
|
1019
|
-
backgroundInstallKind,
|
|
1020
|
-
installCommandFor,
|
|
1021
|
-
createInstallProbe,
|
|
1022
|
-
installerBinaryPath,
|
|
1023
|
-
readServiceEntryText,
|
|
1024
|
-
installService,
|
|
1025
|
-
uninstallService,
|
|
1026
|
-
currentBootId,
|
|
1027
|
-
startedInEarlierBoot,
|
|
1028
|
-
isProcessAlive,
|
|
1029
|
-
getDaemonInfo,
|
|
1030
|
-
isDaemonRunning,
|
|
1031
|
-
daemonIpcVersion,
|
|
1032
|
-
isIpcCompatible,
|
|
1033
|
-
ipcMismatchMessage,
|
|
1034
|
-
printDaemonVersionNoticeOnce,
|
|
1035
|
-
startDaemonFromInstalledBinary,
|
|
1036
|
-
startDaemon,
|
|
1037
|
-
ensureDaemonRunning,
|
|
1038
|
-
getInProcessDaemonHandle,
|
|
1039
|
-
getActiveTunnelSummaries,
|
|
1040
|
-
stopDaemon
|
|
1041
|
-
};
|