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