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
|
@@ -3,31 +3,21 @@ import {
|
|
|
3
3
|
TunnelConfigV1Schema,
|
|
4
4
|
TunnelOperations,
|
|
5
5
|
buildRemoteManagementWsUrl,
|
|
6
|
-
daemonIpcVersion,
|
|
7
|
-
ensureDaemonRunning,
|
|
8
|
-
getDaemonInfo,
|
|
9
6
|
initiateRemoteManagement,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
isIpcCompatible,
|
|
13
|
-
startDaemon,
|
|
14
|
-
startRemoteManagement,
|
|
15
|
-
stopDaemon
|
|
16
|
-
} from "./chunk-CIOYQU7F.js";
|
|
7
|
+
startRemoteManagement
|
|
8
|
+
} from "./chunk-Q5NCTGNS.js";
|
|
17
9
|
import {
|
|
18
|
-
|
|
19
|
-
|
|
10
|
+
configuredLogLevel,
|
|
11
|
+
forgetDeviceAgent,
|
|
12
|
+
saveDeviceAgent,
|
|
13
|
+
savedDeviceAgent,
|
|
14
|
+
writeDaemonConfig
|
|
15
|
+
} from "./chunk-CZOKR73F.js";
|
|
20
16
|
import {
|
|
21
|
-
DaemonHost,
|
|
22
|
-
DeviceAgentState,
|
|
23
17
|
HTTP_NOT_FOUND,
|
|
24
18
|
IPCClient,
|
|
25
|
-
IPCHttpError
|
|
26
|
-
|
|
27
|
-
Route,
|
|
28
|
-
SessionMode,
|
|
29
|
-
ShutdownStatus
|
|
30
|
-
} from "./chunk-7EQKHVQX.js";
|
|
19
|
+
IPCHttpError
|
|
20
|
+
} from "./chunk-MHQ3CVEB.js";
|
|
31
21
|
import {
|
|
32
22
|
ConfigVerb,
|
|
33
23
|
SUBCOMMANDS,
|
|
@@ -46,43 +36,106 @@ import {
|
|
|
46
36
|
upsertConfig,
|
|
47
37
|
validateName,
|
|
48
38
|
validateNameStrict
|
|
49
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-2GIJXE4K.js";
|
|
50
40
|
import {
|
|
51
41
|
createQrCodes
|
|
52
42
|
} from "./chunk-XZ64ZAGO.js";
|
|
53
43
|
import {
|
|
54
|
-
ErrorCode,
|
|
55
44
|
TunnelManager,
|
|
56
|
-
TunnelStateType,
|
|
57
45
|
detachAllTunnelLoggers,
|
|
46
|
+
isTunnelLoggingEnabled,
|
|
47
|
+
setTunnelLoggingEnabled
|
|
48
|
+
} from "./chunk-3WMTTJHI.js";
|
|
49
|
+
import {
|
|
50
|
+
UpdateError,
|
|
51
|
+
acquireUpdateLock,
|
|
52
|
+
assetNameFor,
|
|
53
|
+
createUpdateTarget,
|
|
54
|
+
downloadRelease,
|
|
55
|
+
environmentWithoutDeviceToken,
|
|
56
|
+
isNewerVersion,
|
|
57
|
+
isReleaseComplete,
|
|
58
|
+
isUpdateLockHeld,
|
|
59
|
+
parseVersion,
|
|
60
|
+
readBinaryIpcVersion,
|
|
61
|
+
releaseUpdateLock,
|
|
62
|
+
removeQuietly,
|
|
63
|
+
removeStaleUpdateFiles,
|
|
64
|
+
resolveLatestTag,
|
|
65
|
+
runPinggyBinary,
|
|
66
|
+
versionFromTag,
|
|
67
|
+
windowsInstallPaths
|
|
68
|
+
} from "./chunk-FQ22KFVV.js";
|
|
69
|
+
import {
|
|
70
|
+
InstallKind,
|
|
71
|
+
NPM_INSTALL_COMMAND,
|
|
72
|
+
backgroundInstallKind,
|
|
73
|
+
canReplaceItself,
|
|
74
|
+
createInstallProbe,
|
|
75
|
+
daemonIpcVersion,
|
|
76
|
+
detectInstallKind,
|
|
77
|
+
ensureDaemonRunning,
|
|
78
|
+
getDaemonInfo,
|
|
79
|
+
hasExecutableSpawnHelper,
|
|
80
|
+
hasPathSegment,
|
|
81
|
+
installCommandFor,
|
|
82
|
+
installService,
|
|
83
|
+
ipcMismatchMessage,
|
|
84
|
+
isDaemonRunning,
|
|
85
|
+
isIpcCompatible,
|
|
86
|
+
isPackagedBinary,
|
|
87
|
+
isProcessAlive,
|
|
88
|
+
makeSpawnHelperExecutable,
|
|
89
|
+
nowEpochSeconds,
|
|
90
|
+
readUpdateState,
|
|
91
|
+
recordLatestVersion,
|
|
92
|
+
requireNodePty,
|
|
93
|
+
resolveNodePtyRoot,
|
|
94
|
+
startDaemon,
|
|
95
|
+
startedBeforeBoot,
|
|
96
|
+
stopDaemon,
|
|
97
|
+
uninstallService,
|
|
98
|
+
writeUpdateState
|
|
99
|
+
} from "./chunk-4XXAHYCJ.js";
|
|
100
|
+
import {
|
|
101
|
+
DaemonHost,
|
|
102
|
+
DeviceAgentState,
|
|
103
|
+
IPC_VERSION,
|
|
104
|
+
Route,
|
|
105
|
+
SessionMode,
|
|
106
|
+
ShutdownStatus
|
|
107
|
+
} from "./chunk-MKGD2QAI.js";
|
|
108
|
+
import {
|
|
109
|
+
ErrorCode,
|
|
110
|
+
TunnelStateType,
|
|
58
111
|
errorMessage,
|
|
59
112
|
getLocalAddress,
|
|
60
113
|
getRandomId,
|
|
61
114
|
getVersion,
|
|
62
115
|
isErrorResponse,
|
|
63
|
-
isTunnelLoggingEnabled,
|
|
64
116
|
isValidPort,
|
|
65
117
|
newErrorResponse,
|
|
66
|
-
printer_default
|
|
67
|
-
|
|
68
|
-
} from "./chunk-QNUVQ6KD.js";
|
|
118
|
+
printer_default
|
|
119
|
+
} from "./chunk-HTIWY3O5.js";
|
|
69
120
|
import {
|
|
70
121
|
configureLogger,
|
|
71
122
|
enablePackageLogging,
|
|
72
123
|
getLogLevel,
|
|
73
124
|
logger,
|
|
74
125
|
setLogLevel
|
|
75
|
-
} from "./chunk-
|
|
126
|
+
} from "./chunk-LWCVB42S.js";
|
|
76
127
|
import {
|
|
77
128
|
ensurePinggyConfigDir,
|
|
78
129
|
ensurePinggyLogDir,
|
|
79
130
|
getDaemonInfoPath,
|
|
131
|
+
getDaemonLockPath,
|
|
80
132
|
getDaemonLogPath,
|
|
81
133
|
getDeviceConfigPath,
|
|
134
|
+
getForegroundAgentPath,
|
|
82
135
|
getPinggyConfigDir,
|
|
83
136
|
getTunnelLogDir,
|
|
84
137
|
getTunnelLogPath
|
|
85
|
-
} from "./chunk-
|
|
138
|
+
} from "./chunk-MAK5R4WQ.js";
|
|
86
139
|
|
|
87
140
|
// src/cli/options.ts
|
|
88
141
|
var cliOptions = {
|
|
@@ -131,8 +184,15 @@ var cliOptions = {
|
|
|
131
184
|
all: { type: "boolean", description: "Start all auto-start tunnels" },
|
|
132
185
|
// `pinggy device login` and `connect` only. Their agent runs in the daemon unless this is set.
|
|
133
186
|
foreground: { type: "boolean", description: "Run the device agent in this terminal", hidden: true },
|
|
187
|
+
// `pinggy update` only.
|
|
188
|
+
check: { type: "boolean", description: "Print the latest version and change nothing", hidden: true },
|
|
189
|
+
rollback: { type: "boolean", description: "Go back to the previous version", hidden: true },
|
|
134
190
|
// Internal daemon child marker
|
|
135
191
|
"_daemon-child": { type: "boolean", description: "Internal: daemon child process marker", hidden: true },
|
|
192
|
+
// Internal: the detached process that checks for a release and installs it.
|
|
193
|
+
"_update-child": { type: "boolean", description: "Internal: background updater marker", hidden: true },
|
|
194
|
+
// Internal: prints IPC_VERSION, so an updater can compare a downloaded binary with a running daemon.
|
|
195
|
+
"_ipc-version": { type: "boolean", description: "Internal: print the IPC protocol version", hidden: true },
|
|
136
196
|
// Misc
|
|
137
197
|
version: { type: "boolean", description: "Print version" },
|
|
138
198
|
// Help
|
|
@@ -206,10 +266,17 @@ function printHelpMessage() {
|
|
|
206
266
|
console.log(" pinggy device login --foreground # Same, with the agent in this terminal");
|
|
207
267
|
console.log(" pinggy device status # Show this device and its agent");
|
|
208
268
|
console.log(" pinggy device stop # Stop the background agent");
|
|
269
|
+
console.log("\nUpdates:");
|
|
270
|
+
console.log(" pinggy update --check # Print the latest version");
|
|
271
|
+
console.log(" pinggy update # Update to the latest version now");
|
|
272
|
+
console.log(" pinggy update --rollback # Go back to the previous version");
|
|
273
|
+
console.log(" PINGGY_AUTO_UPDATE=false # Turn off automatic updates");
|
|
209
274
|
console.log("\nDaemon Lifecycle (also: pinggy d <command>):");
|
|
210
275
|
console.log(" pinggy daemon start # Start the background daemon");
|
|
211
276
|
console.log(" pinggy daemon stop # Stop the daemon (stops all tunnels)");
|
|
212
277
|
console.log(" pinggy daemon status # Show daemon PID and uptime");
|
|
278
|
+
console.log(" pinggy daemon service-install # Run the daemon at login as a system service");
|
|
279
|
+
console.log(" pinggy daemon service-uninstall # Stop the daemon and remove the system service");
|
|
213
280
|
}
|
|
214
281
|
|
|
215
282
|
// src/utils/parseArgs.ts
|
|
@@ -273,9 +340,153 @@ function parseCliArgs(options, overrideArgs) {
|
|
|
273
340
|
};
|
|
274
341
|
}
|
|
275
342
|
|
|
343
|
+
// src/update/backgroundUpdate.ts
|
|
344
|
+
import { spawn } from "child_process";
|
|
345
|
+
import fs from "fs";
|
|
346
|
+
import os2 from "os";
|
|
347
|
+
|
|
348
|
+
// src/update/updateMessages.ts
|
|
349
|
+
function daemonRestartLine(version, host) {
|
|
350
|
+
const firstSentence = `pinggy ${version} needs a daemon restart.`;
|
|
351
|
+
if (host === DaemonHost.APP) return `${firstSentence} Update the Pinggy app, then run "pinggy update".`;
|
|
352
|
+
return `${firstSentence} Run "pinggy daemon stop", then "pinggy update". This stops all running tunnels.`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// src/update/backgroundUpdate.ts
|
|
356
|
+
var AUTO_UPDATE_ENV = "PINGGY_AUTO_UPDATE";
|
|
357
|
+
var OFF_VALUES = /* @__PURE__ */ new Set(["false", "0"]);
|
|
358
|
+
var ON_VALUES = /* @__PURE__ */ new Set(["true", "1"]);
|
|
359
|
+
var SUDO_UID_ENV = "SUDO_UID";
|
|
360
|
+
var CONTAINER_MARKER_FILES = ["/.dockerenv", "/run/.containerenv"];
|
|
361
|
+
var NPX_SEGMENT = "_npx";
|
|
362
|
+
var UPDATE_SUBCOMMAND = "update";
|
|
363
|
+
var UPDATE_CHILD_FLAG = "--_update-child";
|
|
364
|
+
var SECONDS_PER_DAY = 24 * 60 * 60;
|
|
365
|
+
var CHECK_INTERVAL_SECONDS = SECONDS_PER_DAY;
|
|
366
|
+
var ATTEMPT_INTERVAL_SECONDS = 60 * 60;
|
|
367
|
+
var COULD_NOT_UPDATE_AFTER_SECONDS = 7 * SECONDS_PER_DAY;
|
|
368
|
+
var COULD_NOT_CHECK_AFTER_SECONDS = 30 * SECONDS_PER_DAY;
|
|
369
|
+
function isDue(lastEpochSeconds, intervalSeconds, now) {
|
|
370
|
+
return lastEpochSeconds === void 0 || lastEpochSeconds > now || now - lastEpochSeconds > intervalSeconds;
|
|
371
|
+
}
|
|
372
|
+
function isAutoUpdateOff(variables) {
|
|
373
|
+
const value = variables[AUTO_UPDATE_ENV]?.toLowerCase();
|
|
374
|
+
if (value === void 0) return false;
|
|
375
|
+
if (!OFF_VALUES.has(value) && !ON_VALUES.has(value)) {
|
|
376
|
+
logger.debug(`Unknown ${AUTO_UPDATE_ENV} value leaves auto-update on`, { value });
|
|
377
|
+
}
|
|
378
|
+
return OFF_VALUES.has(value);
|
|
379
|
+
}
|
|
380
|
+
function isExplicitOrPrintOnly({ rawArgs, values, hasAnyArgs }) {
|
|
381
|
+
return rawArgs[0] === UPDATE_SUBCOMMAND || !hasAnyArgs || Boolean(values.help) || Boolean(values.version);
|
|
382
|
+
}
|
|
383
|
+
function isExcludedProcess(environment) {
|
|
384
|
+
return Boolean(environment.variables[SUDO_UID_ENV]) || CONTAINER_MARKER_FILES.some(environment.fileExists) || parseVersion(environment.runningVersion) === null || hasPathSegment(environment.scriptRealPath, NPX_SEGMENT);
|
|
385
|
+
}
|
|
386
|
+
function updatedNotice(state, running) {
|
|
387
|
+
if (state.updatedToVersion !== running || !state.updatedFromVersion) return null;
|
|
388
|
+
return {
|
|
389
|
+
line: `Updated pinggy ${state.updatedFromVersion} to ${running}.`,
|
|
390
|
+
patch: { updatedFromVersion: void 0, updatedToVersion: void 0 }
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function deferredNotice(state, environment) {
|
|
394
|
+
const version = state.deferredVersion;
|
|
395
|
+
if (!version || state.lastNoticeVersion === version) return null;
|
|
396
|
+
const daemon = environment.liveDaemon();
|
|
397
|
+
if (!daemon) return null;
|
|
398
|
+
return { line: daemonRestartLine(version, daemon.host), patch: { lastNoticeVersion: version } };
|
|
399
|
+
}
|
|
400
|
+
function availableLine(kind, latest, platform3) {
|
|
401
|
+
if (kind === InstallKind.Npm) return `pinggy ${latest} is available. Run: ${NPM_INSTALL_COMMAND}`;
|
|
402
|
+
if (kind === InstallKind.WindowsReadOnly || kind === InstallKind.UnixLoose) {
|
|
403
|
+
return `pinggy ${latest} is available. Run: ${installCommandFor(platform3)}`;
|
|
404
|
+
}
|
|
405
|
+
return null;
|
|
406
|
+
}
|
|
407
|
+
function newVersionNotice(state, kind, environment) {
|
|
408
|
+
const latest = state.latestVersion;
|
|
409
|
+
if (!latest || !isNewerVersion(latest, environment.runningVersion) || state.lastNoticeVersion === latest) return null;
|
|
410
|
+
const patch = { lastNoticeVersion: latest };
|
|
411
|
+
const available = availableLine(kind(), latest, environment.platform);
|
|
412
|
+
if (available) return { line: available, patch };
|
|
413
|
+
const seenLongAgo = state.latestSeenEpochSeconds !== void 0 && environment.nowEpochSeconds() - state.latestSeenEpochSeconds > COULD_NOT_UPDATE_AFTER_SECONDS;
|
|
414
|
+
if (canReplaceItself(kind()) && seenLongAgo && latest !== state.rolledBackFromVersion) {
|
|
415
|
+
return { line: `pinggy could not update itself to ${latest}. Run: pinggy update`, patch };
|
|
416
|
+
}
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
function couldNotCheckNotice(state, kind, environment) {
|
|
420
|
+
const now = environment.nowEpochSeconds();
|
|
421
|
+
const lastCheck = state.lastCheckEpochSeconds;
|
|
422
|
+
if (lastCheck === void 0 || now - lastCheck <= COULD_NOT_CHECK_AFTER_SECONDS) return null;
|
|
423
|
+
if (!isDue(state.lastCheckFailureNoticeEpochSeconds, COULD_NOT_CHECK_AFTER_SECONDS, now)) return null;
|
|
424
|
+
if (kind() === InstallKind.DevCheckout) return null;
|
|
425
|
+
return { line: "pinggy could not check for updates. Run: pinggy update", patch: { lastCheckFailureNoticeEpochSeconds: now } };
|
|
426
|
+
}
|
|
427
|
+
function pendingNotice(state, kind, environment) {
|
|
428
|
+
return updatedNotice(state, environment.runningVersion) ?? deferredNotice(state, environment) ?? newVersionNotice(state, kind, environment) ?? couldNotCheckNotice(state, kind, environment);
|
|
429
|
+
}
|
|
430
|
+
function printPendingNotice(state, kind, environment) {
|
|
431
|
+
const notice = pendingNotice(state, kind, environment);
|
|
432
|
+
if (notice && environment.writeState(notice.patch)) environment.print(notice.line);
|
|
433
|
+
}
|
|
434
|
+
function runGates(command, environment) {
|
|
435
|
+
if (isExplicitOrPrintOnly(command) || !environment.stdoutIsTerminal) return;
|
|
436
|
+
if (isAutoUpdateOff(environment.variables) || isExcludedProcess(environment)) return;
|
|
437
|
+
let detectedKind;
|
|
438
|
+
const kind = () => detectedKind ?? (detectedKind = environment.detectKind());
|
|
439
|
+
const state = environment.readState();
|
|
440
|
+
printPendingNotice(state, kind, environment);
|
|
441
|
+
const now = environment.nowEpochSeconds();
|
|
442
|
+
if (!isDue(state.lastCheckEpochSeconds, CHECK_INTERVAL_SECONDS, now)) return;
|
|
443
|
+
if (!isDue(state.lastAttemptEpochSeconds, ATTEMPT_INTERVAL_SECONDS, now)) return;
|
|
444
|
+
if (kind() === InstallKind.DevCheckout || environment.isLockHeld()) return;
|
|
445
|
+
if (environment.writeState({ lastAttemptEpochSeconds: now })) environment.spawnUpdater();
|
|
446
|
+
}
|
|
447
|
+
function spawnUpdater(spawnProcess = spawn) {
|
|
448
|
+
const child = spawnProcess(process.execPath, [process.argv[1], UPDATE_CHILD_FLAG], {
|
|
449
|
+
detached: true,
|
|
450
|
+
stdio: "ignore",
|
|
451
|
+
// On Windows a process holds its working directory open, so inheriting it would block deleting that folder.
|
|
452
|
+
cwd: os2.homedir(),
|
|
453
|
+
env: environmentWithoutDeviceToken(),
|
|
454
|
+
...os2.platform() === "win32" ? { windowsHide: true } : {}
|
|
455
|
+
});
|
|
456
|
+
child.on("error", (error) => logger.debug("Could not start the updater", { error: errorMessage(error) }));
|
|
457
|
+
child.unref();
|
|
458
|
+
}
|
|
459
|
+
function realEnvironment() {
|
|
460
|
+
const probe = createInstallProbe();
|
|
461
|
+
return {
|
|
462
|
+
variables: process.env,
|
|
463
|
+
stdoutIsTerminal: process.stdout.isTTY === true,
|
|
464
|
+
runningVersion: getVersion(),
|
|
465
|
+
platform: probe.platform,
|
|
466
|
+
scriptRealPath: probe.scriptRealPath,
|
|
467
|
+
nowEpochSeconds,
|
|
468
|
+
fileExists: (filePath) => fs.existsSync(filePath),
|
|
469
|
+
detectKind: () => backgroundInstallKind(detectInstallKind(probe), probe.execPath, probe.homeRealPath),
|
|
470
|
+
readState: readUpdateState,
|
|
471
|
+
writeState: writeUpdateState,
|
|
472
|
+
isLockHeld: isUpdateLockHeld,
|
|
473
|
+
liveDaemon: getDaemonInfo,
|
|
474
|
+
print: (line) => printer_default.print(line),
|
|
475
|
+
spawnUpdater: () => spawnUpdater()
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
function startBackgroundUpdate(command, createEnvironment = realEnvironment) {
|
|
479
|
+
try {
|
|
480
|
+
runGates(command, createEnvironment());
|
|
481
|
+
} catch (error) {
|
|
482
|
+
logger.debug("Background update gate failed", { error: errorMessage(error) });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
276
486
|
// src/main.ts
|
|
277
487
|
import { fileURLToPath } from "url";
|
|
278
488
|
import { argv } from "process";
|
|
489
|
+
import { platform as platform2 } from "os";
|
|
279
490
|
import { realpathSync } from "fs";
|
|
280
491
|
|
|
281
492
|
// src/cli/defaults.ts
|
|
@@ -448,7 +659,7 @@ function isValidIpV6Cidr(input) {
|
|
|
448
659
|
|
|
449
660
|
// src/cli/buildConfig.ts
|
|
450
661
|
import { TunnelType } from "@pinggy/pinggy";
|
|
451
|
-
import
|
|
662
|
+
import fs2 from "fs";
|
|
452
663
|
import path from "path";
|
|
453
664
|
import { isIP as isIP2 } from "net";
|
|
454
665
|
var domainRegex = /^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
|
|
@@ -819,10 +1030,10 @@ function parseArgs2(finalConfig, remainingPositionals) {
|
|
|
819
1030
|
}
|
|
820
1031
|
function storeJson(config, saveconf) {
|
|
821
1032
|
if (saveconf) {
|
|
822
|
-
const
|
|
1033
|
+
const path5 = saveconf;
|
|
823
1034
|
try {
|
|
824
|
-
|
|
825
|
-
logger.info(`Configuration saved to ${
|
|
1035
|
+
fs2.writeFileSync(path5, JSON.stringify(config, null, 2), { encoding: "utf-8", flag: "w" });
|
|
1036
|
+
logger.info(`Configuration saved to ${path5}`);
|
|
826
1037
|
} catch (err) {
|
|
827
1038
|
const msg = err instanceof Error ? err.message : String(err);
|
|
828
1039
|
logger.error("Error loading configuration:", msg);
|
|
@@ -834,7 +1045,7 @@ function loadJsonConfig(config) {
|
|
|
834
1045
|
if (typeof configpath === "string" && configpath.trim().length > 0) {
|
|
835
1046
|
const filepath = path.resolve(configpath);
|
|
836
1047
|
try {
|
|
837
|
-
const data =
|
|
1048
|
+
const data = fs2.readFileSync(filepath, { encoding: "utf-8" });
|
|
838
1049
|
const json = JSON.parse(data);
|
|
839
1050
|
return json;
|
|
840
1051
|
} catch (err) {
|
|
@@ -1029,13 +1240,14 @@ async function initTunnelClient() {
|
|
|
1029
1240
|
const client = new TunnelClient();
|
|
1030
1241
|
printer_default.startSpinner("Initializing...");
|
|
1031
1242
|
try {
|
|
1032
|
-
await client.ensureDaemon();
|
|
1243
|
+
await client.ensureDaemon({ holdVersionNotice: true });
|
|
1033
1244
|
} catch (err) {
|
|
1034
1245
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1035
1246
|
printer_default.stopSpinnerFail(`Failed to start daemon: ${msg}`);
|
|
1036
1247
|
process.exit(1);
|
|
1037
1248
|
}
|
|
1038
1249
|
printer_default.stopSpinnerSuccess("Initialized");
|
|
1250
|
+
client.printHeldVersionNotice();
|
|
1039
1251
|
return client;
|
|
1040
1252
|
}
|
|
1041
1253
|
function printRemoteUrls(urls) {
|
|
@@ -1147,7 +1359,7 @@ async function connectTui(opts) {
|
|
|
1147
1359
|
const exitMessage = opts.exitMessage || "Stopping tunnel...";
|
|
1148
1360
|
if (!noTui && process.stdin.isTTY) {
|
|
1149
1361
|
try {
|
|
1150
|
-
const { TunnelTui } = await import("./TunnelTui-
|
|
1362
|
+
const { TunnelTui } = await import("./TunnelTui-6H4NPUNF.js");
|
|
1151
1363
|
const tui = new TunnelTui({
|
|
1152
1364
|
urls,
|
|
1153
1365
|
greet,
|
|
@@ -1370,7 +1582,7 @@ async function startBackgroundTunnels(configs, values, positionals) {
|
|
|
1370
1582
|
client.close();
|
|
1371
1583
|
}
|
|
1372
1584
|
async function startAutoStartTunnels() {
|
|
1373
|
-
const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-
|
|
1585
|
+
const { getAutoStartConfigs: getAutoStartConfigs2 } = await import("./configStore-JJUWT2YO.js");
|
|
1374
1586
|
const configs = getAutoStartConfigs2();
|
|
1375
1587
|
if (configs.length === 0) {
|
|
1376
1588
|
printer_default.warn("No configs marked for auto-start. Use: pinggy config auto <name>");
|
|
@@ -1493,251 +1705,6 @@ async function initRemoteManagement(values, blocking) {
|
|
|
1493
1705
|
// src/cli/subcommand/handlers/daemonCommandsHandler.ts
|
|
1494
1706
|
import pico6 from "picocolors";
|
|
1495
1707
|
|
|
1496
|
-
// src/daemon/lifecycle/serviceInstaller.ts
|
|
1497
|
-
import os2 from "os";
|
|
1498
|
-
import fs2 from "fs";
|
|
1499
|
-
import path2 from "path";
|
|
1500
|
-
import { execSync, execFileSync } from "child_process";
|
|
1501
|
-
var SERVICE_LABEL = "io.pinggy.agent";
|
|
1502
|
-
var SYSTEMD_SERVICE_NAME = "pinggy";
|
|
1503
|
-
function resolveBinary() {
|
|
1504
|
-
const isPkg = "pkg" in process;
|
|
1505
|
-
if (isPkg) return { program: process.execPath, args: [] };
|
|
1506
|
-
try {
|
|
1507
|
-
const bin = execSync(os2.platform() === "win32" ? "where pinggy" : "which pinggy", {
|
|
1508
|
-
encoding: "utf-8"
|
|
1509
|
-
}).trim().split(/\r?\n/)[0];
|
|
1510
|
-
return { program: bin, args: [] };
|
|
1511
|
-
} catch {
|
|
1512
|
-
return { program: process.execPath, args: [process.argv[1]] };
|
|
1513
|
-
}
|
|
1514
|
-
}
|
|
1515
|
-
function getSystemdServicePath() {
|
|
1516
|
-
const dir = path2.join(os2.homedir(), ".config", "systemd", "user");
|
|
1517
|
-
return path2.join(dir, `${SYSTEMD_SERVICE_NAME}.service`);
|
|
1518
|
-
}
|
|
1519
|
-
function generateSystemdUnit(bin) {
|
|
1520
|
-
const execStart = [bin.program, ...bin.args, "--_daemon-child"].join(" ");
|
|
1521
|
-
return `[Unit]
|
|
1522
|
-
Description=Pinggy Tunnel Daemon
|
|
1523
|
-
After=network-online.target
|
|
1524
|
-
Wants=network-online.target
|
|
1525
|
-
|
|
1526
|
-
[Service]
|
|
1527
|
-
Type=simple
|
|
1528
|
-
ExecStart=${execStart}
|
|
1529
|
-
Restart=on-failure
|
|
1530
|
-
RestartSec=5
|
|
1531
|
-
|
|
1532
|
-
[Install]
|
|
1533
|
-
WantedBy=default.target
|
|
1534
|
-
`;
|
|
1535
|
-
}
|
|
1536
|
-
function installSystemd() {
|
|
1537
|
-
const bin = resolveBinary();
|
|
1538
|
-
const servicePath = getSystemdServicePath();
|
|
1539
|
-
const dir = path2.dirname(servicePath);
|
|
1540
|
-
fs2.mkdirSync(dir, { recursive: true });
|
|
1541
|
-
fs2.writeFileSync(servicePath, generateSystemdUnit(bin), "utf-8");
|
|
1542
|
-
execSync("systemctl --user daemon-reload");
|
|
1543
|
-
execSync(`systemctl --user enable ${SYSTEMD_SERVICE_NAME}`);
|
|
1544
|
-
execSync(`systemctl --user start ${SYSTEMD_SERVICE_NAME}`);
|
|
1545
|
-
logger.info("systemd user service installed and started", { servicePath });
|
|
1546
|
-
console.log(`Service installed: ${servicePath}`);
|
|
1547
|
-
console.log(`Enable at boot: loginctl enable-linger ${os2.userInfo().username}`);
|
|
1548
|
-
}
|
|
1549
|
-
function uninstallSystemd() {
|
|
1550
|
-
const servicePath = getSystemdServicePath();
|
|
1551
|
-
try {
|
|
1552
|
-
execSync(`systemctl --user stop ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
|
|
1553
|
-
execSync(`systemctl --user disable ${SYSTEMD_SERVICE_NAME} 2>/dev/null || true`);
|
|
1554
|
-
} catch {
|
|
1555
|
-
}
|
|
1556
|
-
if (fs2.existsSync(servicePath)) {
|
|
1557
|
-
fs2.unlinkSync(servicePath);
|
|
1558
|
-
execSync("systemctl --user daemon-reload");
|
|
1559
|
-
console.log(`Service removed: ${servicePath}`);
|
|
1560
|
-
} else {
|
|
1561
|
-
console.log("No systemd service found to remove.");
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
function getLaunchdPlistPath() {
|
|
1565
|
-
return path2.join(os2.homedir(), "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
|
|
1566
|
-
}
|
|
1567
|
-
function generateLaunchdPlist(bin) {
|
|
1568
|
-
const allArgs = [bin.program, ...bin.args, "--_daemon-child"];
|
|
1569
|
-
const programArgs = allArgs.map((p) => ` <string>${p}</string>`).join("\n");
|
|
1570
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1571
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
|
|
1572
|
-
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1573
|
-
<plist version="1.0">
|
|
1574
|
-
<dict>
|
|
1575
|
-
<key>Label</key>
|
|
1576
|
-
<string>${SERVICE_LABEL}</string>
|
|
1577
|
-
<key>ProgramArguments</key>
|
|
1578
|
-
<array>
|
|
1579
|
-
${programArgs}
|
|
1580
|
-
</array>
|
|
1581
|
-
<key>RunAtLoad</key>
|
|
1582
|
-
<true/>
|
|
1583
|
-
<key>KeepAlive</key>
|
|
1584
|
-
<false/>
|
|
1585
|
-
</dict>
|
|
1586
|
-
</plist>
|
|
1587
|
-
`;
|
|
1588
|
-
}
|
|
1589
|
-
function installLaunchd() {
|
|
1590
|
-
const bin = resolveBinary();
|
|
1591
|
-
const plistPath = getLaunchdPlistPath();
|
|
1592
|
-
const dir = path2.dirname(plistPath);
|
|
1593
|
-
fs2.mkdirSync(dir, { recursive: true });
|
|
1594
|
-
fs2.writeFileSync(plistPath, generateLaunchdPlist(bin), "utf-8");
|
|
1595
|
-
const uid = process.getuid?.() ?? 501;
|
|
1596
|
-
try {
|
|
1597
|
-
execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
|
|
1598
|
-
} catch {
|
|
1599
|
-
}
|
|
1600
|
-
try {
|
|
1601
|
-
execSync(`launchctl bootstrap gui/${uid} ${plistPath}`);
|
|
1602
|
-
} catch {
|
|
1603
|
-
try {
|
|
1604
|
-
execSync(`launchctl load -w ${plistPath}`);
|
|
1605
|
-
} catch {
|
|
1606
|
-
}
|
|
1607
|
-
}
|
|
1608
|
-
logger.info("launchd agent installed and started", { plistPath });
|
|
1609
|
-
console.log(`Service installed and started: ${plistPath}`);
|
|
1610
|
-
}
|
|
1611
|
-
function uninstallLaunchd() {
|
|
1612
|
-
const plistPath = getLaunchdPlistPath();
|
|
1613
|
-
const uid = process.getuid?.() ?? 501;
|
|
1614
|
-
try {
|
|
1615
|
-
execSync(`launchctl bootout gui/${uid}/${SERVICE_LABEL} 2>/dev/null || true`);
|
|
1616
|
-
} catch {
|
|
1617
|
-
try {
|
|
1618
|
-
execSync(`launchctl unload ${plistPath} 2>/dev/null || true`);
|
|
1619
|
-
} catch {
|
|
1620
|
-
}
|
|
1621
|
-
}
|
|
1622
|
-
if (fs2.existsSync(plistPath)) {
|
|
1623
|
-
fs2.unlinkSync(plistPath);
|
|
1624
|
-
console.log(`Service removed: ${plistPath}`);
|
|
1625
|
-
} else {
|
|
1626
|
-
console.log("No launchd agent found to remove.");
|
|
1627
|
-
}
|
|
1628
|
-
}
|
|
1629
|
-
var WINDOWS_TASK_NAME = "PinggyDaemon";
|
|
1630
|
-
function generateTaskXml(bin) {
|
|
1631
|
-
const command = bin.program;
|
|
1632
|
-
const args = [...bin.args, "--_daemon-child"].join(" ");
|
|
1633
|
-
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
1634
|
-
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
1635
|
-
<Triggers>
|
|
1636
|
-
<LogonTrigger>
|
|
1637
|
-
<Enabled>true</Enabled>
|
|
1638
|
-
</LogonTrigger>
|
|
1639
|
-
</Triggers>
|
|
1640
|
-
<Principals>
|
|
1641
|
-
<Principal id="Author">
|
|
1642
|
-
<LogonType>InteractiveToken</LogonType>
|
|
1643
|
-
<RunLevel>LeastPrivilege</RunLevel>
|
|
1644
|
-
</Principal>
|
|
1645
|
-
</Principals>
|
|
1646
|
-
<Settings>
|
|
1647
|
-
<Hidden>true</Hidden>
|
|
1648
|
-
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
1649
|
-
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
1650
|
-
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
1651
|
-
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
1652
|
-
<RestartOnFailure>
|
|
1653
|
-
<Interval>PT1M</Interval>
|
|
1654
|
-
<Count>3</Count>
|
|
1655
|
-
</RestartOnFailure>
|
|
1656
|
-
</Settings>
|
|
1657
|
-
<Actions>
|
|
1658
|
-
<Exec>
|
|
1659
|
-
<Command>${command}</Command>${args ? `
|
|
1660
|
-
<Arguments>${args}</Arguments>` : ""}
|
|
1661
|
-
</Exec>
|
|
1662
|
-
</Actions>
|
|
1663
|
-
</Task>`;
|
|
1664
|
-
}
|
|
1665
|
-
function installWindows() {
|
|
1666
|
-
const bin = resolveBinary();
|
|
1667
|
-
const xml = generateTaskXml(bin);
|
|
1668
|
-
const tmpPath = path2.join(os2.tmpdir(), `${WINDOWS_TASK_NAME}.xml`);
|
|
1669
|
-
fs2.writeFileSync(tmpPath, "\uFEFF" + xml, "utf16le");
|
|
1670
|
-
try {
|
|
1671
|
-
execFileSync("schtasks", [
|
|
1672
|
-
"/Create",
|
|
1673
|
-
"/TN",
|
|
1674
|
-
WINDOWS_TASK_NAME,
|
|
1675
|
-
"/XML",
|
|
1676
|
-
tmpPath,
|
|
1677
|
-
"/F"
|
|
1678
|
-
], { stdio: "inherit" });
|
|
1679
|
-
} finally {
|
|
1680
|
-
try {
|
|
1681
|
-
fs2.unlinkSync(tmpPath);
|
|
1682
|
-
} catch {
|
|
1683
|
-
}
|
|
1684
|
-
}
|
|
1685
|
-
execFileSync("schtasks", ["/Run", "/TN", WINDOWS_TASK_NAME], { stdio: "inherit" });
|
|
1686
|
-
console.log(`Scheduled task "${WINDOWS_TASK_NAME}" created and started (runs at login, hidden).`);
|
|
1687
|
-
}
|
|
1688
|
-
function uninstallWindows() {
|
|
1689
|
-
try {
|
|
1690
|
-
execFileSync("schtasks", ["/End", "/TN", WINDOWS_TASK_NAME], { stdio: "ignore" });
|
|
1691
|
-
} catch {
|
|
1692
|
-
}
|
|
1693
|
-
try {
|
|
1694
|
-
execFileSync("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
|
|
1695
|
-
console.log(`Scheduled task "${WINDOWS_TASK_NAME}" removed.`);
|
|
1696
|
-
} catch {
|
|
1697
|
-
console.log("No scheduled task found to remove.");
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
function installService() {
|
|
1701
|
-
const platform2 = os2.platform();
|
|
1702
|
-
const bin = resolveBinary();
|
|
1703
|
-
if (!("pkg" in process) && bin.program !== process.execPath) {
|
|
1704
|
-
console.warn(
|
|
1705
|
-
"Warning: Using npm-installed binary. The path may change if Node.js is updated.\nConsider using a standalone binary (pkg) for system services."
|
|
1706
|
-
);
|
|
1707
|
-
}
|
|
1708
|
-
switch (platform2) {
|
|
1709
|
-
case "linux":
|
|
1710
|
-
installSystemd();
|
|
1711
|
-
break;
|
|
1712
|
-
case "darwin":
|
|
1713
|
-
installLaunchd();
|
|
1714
|
-
break;
|
|
1715
|
-
case "win32":
|
|
1716
|
-
installWindows();
|
|
1717
|
-
break;
|
|
1718
|
-
default:
|
|
1719
|
-
console.error(`Unsupported platform: ${platform2}`);
|
|
1720
|
-
process.exit(1);
|
|
1721
|
-
}
|
|
1722
|
-
}
|
|
1723
|
-
function uninstallService() {
|
|
1724
|
-
const platform2 = os2.platform();
|
|
1725
|
-
switch (platform2) {
|
|
1726
|
-
case "linux":
|
|
1727
|
-
uninstallSystemd();
|
|
1728
|
-
break;
|
|
1729
|
-
case "darwin":
|
|
1730
|
-
uninstallLaunchd();
|
|
1731
|
-
break;
|
|
1732
|
-
case "win32":
|
|
1733
|
-
uninstallWindows();
|
|
1734
|
-
break;
|
|
1735
|
-
default:
|
|
1736
|
-
console.error(`Unsupported platform: ${platform2}`);
|
|
1737
|
-
process.exit(1);
|
|
1738
|
-
}
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
1708
|
// src/utils/helpMessages.ts
|
|
1742
1709
|
function printDaemonHelp() {
|
|
1743
1710
|
console.log("\nUsage: pinggy daemon <command>");
|
|
@@ -1746,6 +1713,8 @@ function printDaemonHelp() {
|
|
|
1746
1713
|
console.log(" start Start the daemon process");
|
|
1747
1714
|
console.log(" stop Stop the daemon (stops all tunnels)");
|
|
1748
1715
|
console.log(" status Show daemon PID and uptime");
|
|
1716
|
+
console.log(" service-install Run the daemon at login as a system service");
|
|
1717
|
+
console.log(" service-uninstall Stop the daemon and remove the system service");
|
|
1749
1718
|
console.log("Tunnel operations:");
|
|
1750
1719
|
console.log(" pinggy ps List running tunnels");
|
|
1751
1720
|
console.log(" pinggy stop <name|id> Stop a specific tunnel");
|
|
@@ -1786,20 +1755,31 @@ function printDeviceHelp() {
|
|
|
1786
1755
|
console.log(" background");
|
|
1787
1756
|
console.log(" connect --token <TOKEN> Enrol with a token from the dashboard, then run the agent in the");
|
|
1788
1757
|
console.log(" background. Without --token: start the enrolled device's agent again");
|
|
1789
|
-
console.log(" stop Stop the agent running in the background");
|
|
1758
|
+
console.log(" stop Stop the agent running in the background, until the daemon");
|
|
1759
|
+
console.log(" starts again");
|
|
1790
1760
|
console.log(" status Show the enrolment, and the agent running in the background");
|
|
1791
|
-
console.log(" remove
|
|
1792
|
-
console.log("
|
|
1761
|
+
console.log(" remove Stop the agent and forget the local credential, after asking.");
|
|
1762
|
+
console.log(" The device stays in the dashboard\n");
|
|
1763
|
+
console.log("By default the agent runs in the daemon, and stays connected after this terminal closes.");
|
|
1764
|
+
console.log("Each time the daemon starts, it starts the agent again, until remove.\n");
|
|
1793
1765
|
console.log("Options:");
|
|
1794
1766
|
console.log(" --foreground login and connect: run the agent in this terminal until Ctrl+C");
|
|
1795
1767
|
console.log(" -b login and connect: run the agent in the background. The default");
|
|
1796
1768
|
console.log(" --token <TOKEN> Device token from the dashboard");
|
|
1797
1769
|
console.log(" --manage <HOST> Dashboard address. Default: dashboard.pinggy.io");
|
|
1798
|
-
console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname
|
|
1770
|
+
console.log(" --name <NAME> login only: the device's name. Default: this machine's hostname");
|
|
1771
|
+
console.log(" -f remove only: remove without asking\n");
|
|
1799
1772
|
console.log("Environment:");
|
|
1800
1773
|
console.log(" DEVICE_AGENT_TOKEN connect only: the device token, when --token is not given. With no");
|
|
1801
1774
|
console.log(" --manage, it dials dashboard.pinggy.io. Removed once read\n");
|
|
1802
1775
|
}
|
|
1776
|
+
function printUpdateHelp() {
|
|
1777
|
+
console.log("\nUsage: pinggy update [--check | --rollback]\n");
|
|
1778
|
+
console.log("Commands:");
|
|
1779
|
+
console.log(" pinggy update Update to the latest version now");
|
|
1780
|
+
console.log(" pinggy update --check Print the latest version and change nothing");
|
|
1781
|
+
console.log(" pinggy update --rollback Go back to the previous version\n");
|
|
1782
|
+
}
|
|
1803
1783
|
|
|
1804
1784
|
// src/devices/backgroundAgent.ts
|
|
1805
1785
|
import pico5 from "picocolors";
|
|
@@ -1901,7 +1881,7 @@ var WelcomeSchema = z.object({
|
|
|
1901
1881
|
// No default either. Without it the agent runs no expiry timer, and the dashboard's sweep
|
|
1902
1882
|
// still ends an idle shell, only later. A shell has no cap on its running time.
|
|
1903
1883
|
terminal_idle_timeout_seconds: z.number().optional(),
|
|
1904
|
-
// Optional: without it the agent keeps
|
|
1884
|
+
// Optional: without it the agent keeps the window brake and never skips output.
|
|
1905
1885
|
terminal_resync: z.boolean().optional(),
|
|
1906
1886
|
// Optional: a dashboard older than these sends neither, and the agent prints only the device id.
|
|
1907
1887
|
email: z.string().optional(),
|
|
@@ -2647,9 +2627,9 @@ var MAX_CWD_CHARACTERS = 1024;
|
|
|
2647
2627
|
var MAX_COMMAND_CHARACTERS = 64;
|
|
2648
2628
|
var PROCESS_READ_TIMEOUT_MILLIS = 2e3;
|
|
2649
2629
|
var HOME_PREFIX = "~";
|
|
2650
|
-
function processTableReader(
|
|
2651
|
-
if (
|
|
2652
|
-
if (
|
|
2630
|
+
function processTableReader(platform3 = process.platform) {
|
|
2631
|
+
if (platform3 === "linux") return readFromProc;
|
|
2632
|
+
if (platform3 === "darwin") return readFromPsAndLsof;
|
|
2653
2633
|
return null;
|
|
2654
2634
|
}
|
|
2655
2635
|
function programName(rawName) {
|
|
@@ -2853,7 +2833,7 @@ var ScreenMirror = class _ScreenMirror {
|
|
|
2853
2833
|
}
|
|
2854
2834
|
/**
|
|
2855
2835
|
* Fed and not yet parsed. xterm queues writes without limit, so a shell that skips its output
|
|
2856
|
-
*
|
|
2836
|
+
* pauses on this, and on nothing else.
|
|
2857
2837
|
*/
|
|
2858
2838
|
get backlogBytes() {
|
|
2859
2839
|
return this.unparsedBytes;
|
|
@@ -2929,9 +2909,9 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
2929
2909
|
this.dependencies = dependencies;
|
|
2930
2910
|
this.enabled = true;
|
|
2931
2911
|
this.suspended = false;
|
|
2932
|
-
/** `terminal_resync` in `welcome
|
|
2912
|
+
/** `terminal_resync` in `welcome`. Off, every shell keeps the window brake. */
|
|
2933
2913
|
this.resyncEnabled = false;
|
|
2934
|
-
/** Paused by `suspend`
|
|
2914
|
+
/** Paused by `suspend` without skip mode, so `resumeAll` resumes them if `welcome` turned skip mode on. */
|
|
2935
2915
|
this.pausedBySuspend = /* @__PURE__ */ new Set();
|
|
2936
2916
|
this.expiryTimer = null;
|
|
2937
2917
|
this.contextTimer = null;
|
|
@@ -3026,9 +3006,9 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3026
3006
|
this.dependencies.registry.killAll();
|
|
3027
3007
|
}
|
|
3028
3008
|
/**
|
|
3029
|
-
* The socket dropped and the agent will redial.
|
|
3009
|
+
* The socket dropped and the agent will redial. Without skip mode every shell stops being read and
|
|
3030
3010
|
* keeps running: whatever it prints waits in the kernel, and the shell blocks once that buffer is
|
|
3031
|
-
* full. In skip mode
|
|
3011
|
+
* full. In skip mode a shell is read on, and its output is skipped.
|
|
3032
3012
|
*/
|
|
3033
3013
|
suspend() {
|
|
3034
3014
|
if (this.suspended) return;
|
|
@@ -3048,7 +3028,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3048
3028
|
/**
|
|
3049
3029
|
* `welcome` arrived. Every shell the dashboard did not close is read again, except one whose
|
|
3050
3030
|
* window is still full. That one resumes on the `ack` that reopens it. A shell in skip mode was
|
|
3051
|
-
* never paused, and resyncs instead
|
|
3031
|
+
* never paused, and resyncs instead.
|
|
3052
3032
|
*/
|
|
3053
3033
|
resumeAll() {
|
|
3054
3034
|
if (!this.suspended) return;
|
|
@@ -3209,7 +3189,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3209
3189
|
}
|
|
3210
3190
|
/**
|
|
3211
3191
|
* The shell exited on its own. A shell that skipped its last output sends its last screen first, at
|
|
3212
|
-
* once, so the tabs see how it ended
|
|
3192
|
+
* once, so the tabs see how it ended. Then `exit` and `close`. With nothing to resync this
|
|
3213
3193
|
* runs to the end without yielding, as before.
|
|
3214
3194
|
*/
|
|
3215
3195
|
async finishExit(terminalId, stream, exitCode, signal) {
|
|
@@ -3241,7 +3221,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3241
3221
|
* exactly the bundles up to its `after_seq`. Fed when the pty is read, a bundle still being cut
|
|
3242
3222
|
* would be in the screen and drawn a second time when it is sent.
|
|
3243
3223
|
*
|
|
3244
|
-
* In skip mode
|
|
3224
|
+
* In skip mode `sendOrSkip` decides instead, and never pauses the pty.
|
|
3245
3225
|
*/
|
|
3246
3226
|
sendData(terminalId, chunk) {
|
|
3247
3227
|
const stream = this.streams.get(terminalId);
|
|
@@ -3270,7 +3250,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3270
3250
|
return this.resyncEnabled && stream.mirror !== null;
|
|
3271
3251
|
}
|
|
3272
3252
|
/**
|
|
3273
|
-
* Skip mode
|
|
3253
|
+
* Skip mode. A resync being serialised holds the bundle. A skipping stream, a socket that is
|
|
3274
3254
|
* down, or a closed window skips it. Otherwise it goes out as `data`.
|
|
3275
3255
|
*/
|
|
3276
3256
|
sendOrSkip(terminalId, stream, chunk) {
|
|
@@ -3316,7 +3296,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3316
3296
|
this.brakeIfMirrorBehind(terminalId, stream);
|
|
3317
3297
|
this.reportActivityWhileSkipping(terminalId, stream);
|
|
3318
3298
|
}
|
|
3319
|
-
/** As
|
|
3299
|
+
/** As the send without skip mode, minus the pause: with the window closed, the next bundle is skipped instead. */
|
|
3320
3300
|
transmit(terminalId, stream, chunk) {
|
|
3321
3301
|
stream.sentSeq += 1;
|
|
3322
3302
|
stream.mirror?.feed(chunk, () => this.mirrorParsed(terminalId, stream));
|
|
@@ -3404,7 +3384,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3404
3384
|
return stream.resyncInFlight;
|
|
3405
3385
|
}
|
|
3406
3386
|
/**
|
|
3407
|
-
* The latest screen to every tab
|
|
3387
|
+
* The latest screen to every tab. `after_seq` and `after_bytes` are read before the mirror
|
|
3408
3388
|
* is asked, as for a snapshot, and skipped bytes took neither: the screen holds the output up to
|
|
3409
3389
|
* `after_seq` plus everything skipped. Serialised under the window size, so a resync never puts more in
|
|
3410
3390
|
* flight than the window allows. Bundles held meanwhile go out after the parts, from `after_seq + 1`.
|
|
@@ -3564,7 +3544,7 @@ var TerminalHandler = class _TerminalHandler {
|
|
|
3564
3544
|
this.dependencies.send(event(CHANNEL_TERMINAL, OP_CLOSE, { terminal_id: terminalId, reason }));
|
|
3565
3545
|
}
|
|
3566
3546
|
/**
|
|
3567
|
-
* A tab attached and asked for the screen it missed
|
|
3547
|
+
* A tab attached and asked for the screen it missed. Answered in parts, each 1 frame,
|
|
3568
3548
|
* which the dashboard routes to that tab alone.
|
|
3569
3549
|
*
|
|
3570
3550
|
* `after_seq` and `after_bytes` are read in the same tick as the request, before the mirror is
|
|
@@ -3716,123 +3696,8 @@ var TerminalRegistry = class {
|
|
|
3716
3696
|
|
|
3717
3697
|
// src/devices/terminal/ptySession.ts
|
|
3718
3698
|
import { execFile as execFile2 } from "child_process";
|
|
3719
|
-
import fs6 from "fs";
|
|
3720
|
-
import os7 from "os";
|
|
3721
|
-
|
|
3722
|
-
// src/devices/terminal/nodePtyRuntime.ts
|
|
3723
3699
|
import fs5 from "fs";
|
|
3724
|
-
import
|
|
3725
|
-
import { createRequire as createRequire2 } from "module";
|
|
3726
|
-
var require3 = createRequire2(import.meta.url);
|
|
3727
|
-
var PACKAGE_NAME = "node-pty";
|
|
3728
|
-
var NATIVE_FILE = "pty.node";
|
|
3729
|
-
var SPAWN_HELPER_FILE = "spawn-helper";
|
|
3730
|
-
var EXECUTABLE_MODE = 493;
|
|
3731
|
-
var EXECUTE_BITS = 73;
|
|
3732
|
-
var RUNTIME_DIR_NAME = "runtime";
|
|
3733
|
-
var ASAR_ARCHIVE_SUFFIX = ".asar";
|
|
3734
|
-
var NATIVE_DIRECTORIES = [
|
|
3735
|
-
path3.join("build", "Release"),
|
|
3736
|
-
path3.join("prebuilds", `${process.platform}-${process.arch}`)
|
|
3737
|
-
];
|
|
3738
|
-
function isPackagedBinary() {
|
|
3739
|
-
return Boolean(process.pkg);
|
|
3740
|
-
}
|
|
3741
|
-
function isInsideAsarArchive(packageRoot) {
|
|
3742
|
-
if (!process.versions.electron) return false;
|
|
3743
|
-
return packageRoot.split(path3.sep).some((segment) => segment.endsWith(ASAR_ARCHIVE_SUFFIX));
|
|
3744
|
-
}
|
|
3745
|
-
function resolveNodePtyRoot() {
|
|
3746
|
-
const resolvedRoot = path3.dirname(require3.resolve(`${PACKAGE_NAME}/package.json`));
|
|
3747
|
-
if (!isPackagedBinary() && !isInsideAsarArchive(resolvedRoot)) return resolvedRoot;
|
|
3748
|
-
return unpackNodePty(resolvedRoot);
|
|
3749
|
-
}
|
|
3750
|
-
function requireNodePty(packageRoot) {
|
|
3751
|
-
return require3(packageRoot);
|
|
3752
|
-
}
|
|
3753
|
-
function spawnHelperPaths(packageRoot) {
|
|
3754
|
-
if (process.platform === "win32") return [];
|
|
3755
|
-
return NATIVE_DIRECTORIES.map((directory) => path3.join(packageRoot, directory, SPAWN_HELPER_FILE));
|
|
3756
|
-
}
|
|
3757
|
-
function hasExecutableSpawnHelper(packageRoot) {
|
|
3758
|
-
const helpers = spawnHelperPaths(packageRoot);
|
|
3759
|
-
if (helpers.length === 0) return true;
|
|
3760
|
-
return helpers.some((helper) => {
|
|
3761
|
-
try {
|
|
3762
|
-
const stat = fs5.statSync(helper);
|
|
3763
|
-
return stat.isFile() && (stat.mode & EXECUTE_BITS) !== 0;
|
|
3764
|
-
} catch {
|
|
3765
|
-
return false;
|
|
3766
|
-
}
|
|
3767
|
-
});
|
|
3768
|
-
}
|
|
3769
|
-
function makeSpawnHelperExecutable(packageRoot) {
|
|
3770
|
-
for (const helper of spawnHelperPaths(packageRoot)) {
|
|
3771
|
-
try {
|
|
3772
|
-
const stat = fs5.statSync(helper);
|
|
3773
|
-
if ((stat.mode & EXECUTE_BITS) === 0) {
|
|
3774
|
-
fs5.chmodSync(helper, EXECUTABLE_MODE);
|
|
3775
|
-
}
|
|
3776
|
-
} catch {
|
|
3777
|
-
}
|
|
3778
|
-
}
|
|
3779
|
-
}
|
|
3780
|
-
function unpackNodePty(snapshotRoot) {
|
|
3781
|
-
const unpackedRoot = unpackedRootPath(snapshotRoot);
|
|
3782
|
-
if (isLoadable(unpackedRoot)) return unpackedRoot;
|
|
3783
|
-
const stagingRoot = `${unpackedRoot}.${process.pid}`;
|
|
3784
|
-
fs5.rmSync(stagingRoot, { recursive: true, force: true });
|
|
3785
|
-
try {
|
|
3786
|
-
copyRuntimeFiles(snapshotRoot, stagingRoot);
|
|
3787
|
-
makeSpawnHelperExecutable(stagingRoot);
|
|
3788
|
-
fs5.renameSync(stagingRoot, unpackedRoot);
|
|
3789
|
-
} catch (error) {
|
|
3790
|
-
fs5.rmSync(stagingRoot, { recursive: true, force: true });
|
|
3791
|
-
if (!isLoadable(unpackedRoot)) throw error;
|
|
3792
|
-
}
|
|
3793
|
-
return unpackedRoot;
|
|
3794
|
-
}
|
|
3795
|
-
function unpackedRootPath(snapshotRoot) {
|
|
3796
|
-
const version = readPackageVersion(snapshotRoot);
|
|
3797
|
-
const directoryName = `${PACKAGE_NAME}-${version}-${process.platform}-${process.arch}`;
|
|
3798
|
-
return path3.join(getPinggyConfigDir(), RUNTIME_DIR_NAME, directoryName);
|
|
3799
|
-
}
|
|
3800
|
-
function readPackageVersion(packageRoot) {
|
|
3801
|
-
const manifest = JSON.parse(fs5.readFileSync(path3.join(packageRoot, "package.json"), "utf8"));
|
|
3802
|
-
return String(manifest.version);
|
|
3803
|
-
}
|
|
3804
|
-
function isLoadable(packageRoot) {
|
|
3805
|
-
if (!fs5.existsSync(path3.join(packageRoot, "package.json"))) return false;
|
|
3806
|
-
return NATIVE_DIRECTORIES.some((directory) => fs5.existsSync(path3.join(packageRoot, directory, NATIVE_FILE)));
|
|
3807
|
-
}
|
|
3808
|
-
function copyRuntimeFiles(sourceRoot, targetRoot) {
|
|
3809
|
-
fs5.mkdirSync(targetRoot, { recursive: true });
|
|
3810
|
-
copyFile(path3.join(sourceRoot, "package.json"), path3.join(targetRoot, "package.json"));
|
|
3811
|
-
copyDirectory(path3.join(sourceRoot, "lib"), path3.join(targetRoot, "lib"));
|
|
3812
|
-
for (const directory of NATIVE_DIRECTORIES) {
|
|
3813
|
-
const source = path3.join(sourceRoot, directory);
|
|
3814
|
-
if (fs5.existsSync(source)) {
|
|
3815
|
-
copyDirectory(source, path3.join(targetRoot, directory));
|
|
3816
|
-
}
|
|
3817
|
-
}
|
|
3818
|
-
}
|
|
3819
|
-
function copyDirectory(sourceDirectory, targetDirectory) {
|
|
3820
|
-
fs5.mkdirSync(targetDirectory, { recursive: true });
|
|
3821
|
-
for (const entry of fs5.readdirSync(sourceDirectory, { withFileTypes: true })) {
|
|
3822
|
-
const source = path3.join(sourceDirectory, entry.name);
|
|
3823
|
-
const target = path3.join(targetDirectory, entry.name);
|
|
3824
|
-
if (entry.isDirectory()) {
|
|
3825
|
-
copyDirectory(source, target);
|
|
3826
|
-
continue;
|
|
3827
|
-
}
|
|
3828
|
-
copyFile(source, target);
|
|
3829
|
-
}
|
|
3830
|
-
}
|
|
3831
|
-
function copyFile(source, target) {
|
|
3832
|
-
fs5.writeFileSync(target, fs5.readFileSync(source));
|
|
3833
|
-
}
|
|
3834
|
-
|
|
3835
|
-
// src/devices/terminal/ptySession.ts
|
|
3700
|
+
import os7 from "os";
|
|
3836
3701
|
var loadedPty;
|
|
3837
3702
|
var TERM_NAME = "xterm-256color";
|
|
3838
3703
|
function foregroundProcessGroup(shellPid) {
|
|
@@ -3880,7 +3745,7 @@ function ensureSpawnHelperExecutable(packageRoot) {
|
|
|
3880
3745
|
function resolveCwd(requested) {
|
|
3881
3746
|
if (requested) {
|
|
3882
3747
|
try {
|
|
3883
|
-
if (
|
|
3748
|
+
if (fs5.statSync(requested).isDirectory()) return requested;
|
|
3884
3749
|
} catch {
|
|
3885
3750
|
}
|
|
3886
3751
|
}
|
|
@@ -3930,14 +3795,14 @@ function spawnPty(request2) {
|
|
|
3930
3795
|
}
|
|
3931
3796
|
|
|
3932
3797
|
// src/devices/terminal/shellAllowlist.ts
|
|
3933
|
-
import
|
|
3798
|
+
import fs6 from "fs";
|
|
3934
3799
|
var FALLBACK_UNIX_SHELLS = ["/bin/bash", "/bin/zsh", "/bin/sh", "/usr/bin/bash", "/usr/bin/zsh"];
|
|
3935
3800
|
var WINDOWS_SHELLS = ["powershell.exe", "cmd.exe"];
|
|
3936
3801
|
var ETC_SHELLS_PATH = "/etc/shells";
|
|
3937
3802
|
function readShellEnvironment() {
|
|
3938
3803
|
let etcShells = null;
|
|
3939
3804
|
try {
|
|
3940
|
-
etcShells =
|
|
3805
|
+
etcShells = fs6.readFileSync(ETC_SHELLS_PATH, "utf8");
|
|
3941
3806
|
} catch {
|
|
3942
3807
|
etcShells = null;
|
|
3943
3808
|
}
|
|
@@ -3945,9 +3810,9 @@ function readShellEnvironment() {
|
|
|
3945
3810
|
platform: process.platform,
|
|
3946
3811
|
loginShell: process.env.SHELL,
|
|
3947
3812
|
etcShells,
|
|
3948
|
-
exists: (
|
|
3813
|
+
exists: (path5) => {
|
|
3949
3814
|
try {
|
|
3950
|
-
return
|
|
3815
|
+
return fs6.statSync(path5).isFile();
|
|
3951
3816
|
} catch {
|
|
3952
3817
|
return false;
|
|
3953
3818
|
}
|
|
@@ -3979,6 +3844,104 @@ function resolveShell(requested, environment) {
|
|
|
3979
3844
|
return firstUsable ? { shell: firstUsable } : { error: "No allowed shell exists on this machine." };
|
|
3980
3845
|
}
|
|
3981
3846
|
|
|
3847
|
+
// src/devices/foregroundAgent.ts
|
|
3848
|
+
import fs7 from "fs";
|
|
3849
|
+
var RECORD_CHECK_INTERVAL_MILLIS = 1e3;
|
|
3850
|
+
var STOP_WAIT_MILLIS = 1e4;
|
|
3851
|
+
var STOP_POLL_INTERVAL_MILLIS = 200;
|
|
3852
|
+
function readRecordFile(filePath) {
|
|
3853
|
+
try {
|
|
3854
|
+
const record = JSON.parse(fs7.readFileSync(filePath, "utf-8"));
|
|
3855
|
+
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
3856
|
+
} catch {
|
|
3857
|
+
return null;
|
|
3858
|
+
}
|
|
3859
|
+
}
|
|
3860
|
+
function deleteRecordFile(filePath) {
|
|
3861
|
+
try {
|
|
3862
|
+
fs7.unlinkSync(filePath);
|
|
3863
|
+
} catch (err) {
|
|
3864
|
+
logger.debug("No foreground agent record to delete", { error: errorMessage(err) });
|
|
3865
|
+
}
|
|
3866
|
+
}
|
|
3867
|
+
function readForegroundAgent() {
|
|
3868
|
+
const filePath = getForegroundAgentPath();
|
|
3869
|
+
const record = readRecordFile(filePath);
|
|
3870
|
+
if (!record) {
|
|
3871
|
+
return null;
|
|
3872
|
+
}
|
|
3873
|
+
if (record.pid === process.pid) {
|
|
3874
|
+
return null;
|
|
3875
|
+
}
|
|
3876
|
+
if (startedBeforeBoot(record.started_at) || !isProcessAlive(record.pid)) {
|
|
3877
|
+
logger.info("Stale device-agent.json found, cleaning up", { stalePid: record.pid });
|
|
3878
|
+
deleteRecordFile(filePath);
|
|
3879
|
+
return null;
|
|
3880
|
+
}
|
|
3881
|
+
return record;
|
|
3882
|
+
}
|
|
3883
|
+
function recordForegroundAgent(onRecordDeleted) {
|
|
3884
|
+
const filePath = getForegroundAgentPath();
|
|
3885
|
+
const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3886
|
+
try {
|
|
3887
|
+
ensurePinggyConfigDir();
|
|
3888
|
+
fs7.writeFileSync(filePath, JSON.stringify(record, null, 2), "utf-8");
|
|
3889
|
+
} catch (err) {
|
|
3890
|
+
logger.warn(
|
|
3891
|
+
"Could not write device-agent.json. pinggy device remove cannot stop this agent.",
|
|
3892
|
+
{ error: errorMessage(err) }
|
|
3893
|
+
);
|
|
3894
|
+
return () => void 0;
|
|
3895
|
+
}
|
|
3896
|
+
const timer = setInterval(() => {
|
|
3897
|
+
if (!fs7.existsSync(filePath)) {
|
|
3898
|
+
clearInterval(timer);
|
|
3899
|
+
onRecordDeleted();
|
|
3900
|
+
}
|
|
3901
|
+
}, RECORD_CHECK_INTERVAL_MILLIS);
|
|
3902
|
+
timer.unref();
|
|
3903
|
+
return () => {
|
|
3904
|
+
clearInterval(timer);
|
|
3905
|
+
if (readRecordFile(filePath)?.pid === process.pid) {
|
|
3906
|
+
deleteRecordFile(filePath);
|
|
3907
|
+
}
|
|
3908
|
+
};
|
|
3909
|
+
}
|
|
3910
|
+
function machineForegroundStopDependencies() {
|
|
3911
|
+
return {
|
|
3912
|
+
readAgent: readForegroundAgent,
|
|
3913
|
+
deleteRecord: () => deleteRecordFile(getForegroundAgentPath()),
|
|
3914
|
+
isAlive: isProcessAlive,
|
|
3915
|
+
sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),
|
|
3916
|
+
now: () => Date.now(),
|
|
3917
|
+
print: (message) => printer_default.print(message),
|
|
3918
|
+
printError: (message) => printer_default.error(message)
|
|
3919
|
+
};
|
|
3920
|
+
}
|
|
3921
|
+
async function stopForegroundAgentBeforeRemove(dependencies = machineForegroundStopDependencies()) {
|
|
3922
|
+
const record = dependencies.readAgent();
|
|
3923
|
+
if (!record) {
|
|
3924
|
+
return true;
|
|
3925
|
+
}
|
|
3926
|
+
dependencies.deleteRecord();
|
|
3927
|
+
const deadline = dependencies.now() + STOP_WAIT_MILLIS;
|
|
3928
|
+
while (dependencies.isAlive(record.pid)) {
|
|
3929
|
+
if (dependencies.now() >= deadline) {
|
|
3930
|
+
dependencies.printError(`The device agent in another terminal (PID ${record.pid}) did not stop. Press Ctrl+C in that terminal, then run: pinggy device remove`);
|
|
3931
|
+
return false;
|
|
3932
|
+
}
|
|
3933
|
+
await dependencies.sleep(STOP_POLL_INTERVAL_MILLIS);
|
|
3934
|
+
}
|
|
3935
|
+
dependencies.print(`Stopped the device agent running in another terminal (PID ${record.pid}).`);
|
|
3936
|
+
return true;
|
|
3937
|
+
}
|
|
3938
|
+
function foregroundAgentRefusal(record = readForegroundAgent()) {
|
|
3939
|
+
if (!record) {
|
|
3940
|
+
return null;
|
|
3941
|
+
}
|
|
3942
|
+
return `This machine already runs as a device in another terminal (PID ${record.pid}). Press Ctrl+C in that terminal first.`;
|
|
3943
|
+
}
|
|
3944
|
+
|
|
3982
3945
|
// src/devices/deviceAgent.ts
|
|
3983
3946
|
var CLOSE_CODE_REVOKED = 4001;
|
|
3984
3947
|
var CLOSE_CODE_NORMAL = 1e3;
|
|
@@ -4092,14 +4055,20 @@ function startDeviceAgent(token, manage, options = {}) {
|
|
|
4092
4055
|
}
|
|
4093
4056
|
async function runDeviceAgent(token, manage, options = {}) {
|
|
4094
4057
|
const run2 = startDeviceAgent(token, manage, options);
|
|
4058
|
+
const reporter = options.reporter ?? printingReporter;
|
|
4095
4059
|
const sigintHandler = () => {
|
|
4096
4060
|
void run2.stop();
|
|
4097
4061
|
};
|
|
4062
|
+
const releaseRecord = recordForegroundAgent(() => {
|
|
4063
|
+
reporter.warn("Stopping: pinggy device remove ran in another terminal.");
|
|
4064
|
+
void run2.stop();
|
|
4065
|
+
});
|
|
4098
4066
|
process.once("SIGINT", sigintHandler);
|
|
4099
4067
|
try {
|
|
4100
4068
|
await run2.done;
|
|
4101
4069
|
} finally {
|
|
4102
4070
|
process.removeListener("SIGINT", sigintHandler);
|
|
4071
|
+
releaseRecord();
|
|
4103
4072
|
}
|
|
4104
4073
|
}
|
|
4105
4074
|
async function runLoop(context) {
|
|
@@ -4424,8 +4393,8 @@ var DeviceLoginApiError = class extends Error {
|
|
|
4424
4393
|
var UNREADABLE_ANSWER = "invalid_answer";
|
|
4425
4394
|
function createDeviceLoginApi(manage, fetchImpl = fetch) {
|
|
4426
4395
|
const baseUrl = buildDashboardHttpUrl(manage);
|
|
4427
|
-
async function post(
|
|
4428
|
-
const response2 = await fetchImpl(`${baseUrl}/${
|
|
4396
|
+
async function post(path5, body, schema) {
|
|
4397
|
+
const response2 = await fetchImpl(`${baseUrl}/${path5}`, {
|
|
4429
4398
|
method: "POST",
|
|
4430
4399
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
4431
4400
|
body: JSON.stringify(body)
|
|
@@ -4771,9 +4740,9 @@ var POLL_INTERVAL_MILLIS = 500;
|
|
|
4771
4740
|
var CONNECT_WAIT_MILLIS = 15e3;
|
|
4772
4741
|
var MANAGE_COMMANDS = [
|
|
4773
4742
|
["pinggy device status", "Show this device, and whether its agent runs"],
|
|
4774
|
-
["pinggy device stop", "Stop the agent. The device shows offline"],
|
|
4775
|
-
["pinggy device connect", "Start the agent again
|
|
4776
|
-
["pinggy device remove", "
|
|
4743
|
+
["pinggy device stop", "Stop the agent until the daemon starts again. The device shows offline"],
|
|
4744
|
+
["pinggy device connect", "Start the agent again after a stop"],
|
|
4745
|
+
["pinggy device remove", "Stop the agent and forget this machine's credential"]
|
|
4777
4746
|
];
|
|
4778
4747
|
var verifyingReporter = {
|
|
4779
4748
|
connecting: () => void 0,
|
|
@@ -4787,7 +4756,10 @@ var verifyingReporter = {
|
|
|
4787
4756
|
function machineBackgroundAgentDependencies() {
|
|
4788
4757
|
return {
|
|
4789
4758
|
readIdentity: readDeviceIdentity,
|
|
4759
|
+
readForegroundAgent,
|
|
4790
4760
|
findDaemon: getDaemonInfo,
|
|
4761
|
+
hasSavedAgent: () => savedDeviceAgent() !== null,
|
|
4762
|
+
forgetSavedAgent: forgetDeviceAgent,
|
|
4791
4763
|
ensureDaemon: ensureDaemonRunning,
|
|
4792
4764
|
client: (port) => new IPCClient(port, "cli"),
|
|
4793
4765
|
verify: (token, manage) => startDeviceAgent(token, manage, {
|
|
@@ -4867,7 +4839,7 @@ async function stopAgentInBackground(dependencies) {
|
|
|
4867
4839
|
if (!await stopReadAgent(reading, dependencies)) {
|
|
4868
4840
|
return EXIT_FAILED;
|
|
4869
4841
|
}
|
|
4870
|
-
dependencies.printSuccess("Stopped. The device shows offline in the dashboard.");
|
|
4842
|
+
dependencies.printSuccess("Stopped. The device shows offline in the dashboard until the daemon starts again.");
|
|
4871
4843
|
return EXIT_OK;
|
|
4872
4844
|
}
|
|
4873
4845
|
async function stopAgentBeforeRemove(dependencies) {
|
|
@@ -5004,7 +4976,7 @@ async function handleDaemon(args) {
|
|
|
5004
4976
|
installService();
|
|
5005
4977
|
return;
|
|
5006
4978
|
case "service-uninstall":
|
|
5007
|
-
uninstallService();
|
|
4979
|
+
await uninstallService();
|
|
5008
4980
|
return;
|
|
5009
4981
|
default:
|
|
5010
4982
|
printer_default.error(`Unknown daemon command: "${verb}"`);
|
|
@@ -5089,7 +5061,10 @@ import pico7 from "picocolors";
|
|
|
5089
5061
|
async function handlePs() {
|
|
5090
5062
|
const client = new TunnelClient();
|
|
5091
5063
|
try {
|
|
5092
|
-
|
|
5064
|
+
if (!client.connectIfRunning()) {
|
|
5065
|
+
printer_default.print("No active tunnels. The daemon is not running.");
|
|
5066
|
+
return;
|
|
5067
|
+
}
|
|
5093
5068
|
} catch (err) {
|
|
5094
5069
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5095
5070
|
return;
|
|
@@ -5101,7 +5076,7 @@ async function handlePs() {
|
|
|
5101
5076
|
return;
|
|
5102
5077
|
}
|
|
5103
5078
|
if (tunnels.length === 0) {
|
|
5104
|
-
printer_default.print("No tunnels
|
|
5079
|
+
printer_default.print("No active tunnels.");
|
|
5105
5080
|
return;
|
|
5106
5081
|
}
|
|
5107
5082
|
const header = `${pad("ID", 14)} ${pad("NAME", 16)} ${pad("STATUS", 10)} ${pad("LOCAL", 20)} URL`;
|
|
@@ -5136,7 +5111,10 @@ async function handleStop(args) {
|
|
|
5136
5111
|
}
|
|
5137
5112
|
const client = new TunnelClient();
|
|
5138
5113
|
try {
|
|
5139
|
-
|
|
5114
|
+
if (!client.connectIfRunning()) {
|
|
5115
|
+
printer_default.print("Nothing to stop. No tunnels are running.");
|
|
5116
|
+
return;
|
|
5117
|
+
}
|
|
5140
5118
|
} catch (err) {
|
|
5141
5119
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5142
5120
|
return;
|
|
@@ -5188,6 +5166,20 @@ function resolveTargets(tunnels, args) {
|
|
|
5188
5166
|
|
|
5189
5167
|
// src/cli/subcommand/handlers/attachCommand.ts
|
|
5190
5168
|
import pico8 from "picocolors";
|
|
5169
|
+
|
|
5170
|
+
// src/cli/subcommand/handlers/noDaemon.ts
|
|
5171
|
+
function startCommand(name) {
|
|
5172
|
+
return /\s/.test(name) ? `pinggy start "${name}"` : `pinggy start ${name}`;
|
|
5173
|
+
}
|
|
5174
|
+
function tunnelNotRunningMessage(nameOrId) {
|
|
5175
|
+
const saved = findConfig(nameOrId);
|
|
5176
|
+
if (saved) {
|
|
5177
|
+
return `Tunnel "${saved.name}" is not running. Start it with: ${startCommand(saved.name)}`;
|
|
5178
|
+
}
|
|
5179
|
+
return `No tunnel matches "${nameOrId}". No tunnels are running.`;
|
|
5180
|
+
}
|
|
5181
|
+
|
|
5182
|
+
// src/cli/subcommand/handlers/attachCommand.ts
|
|
5191
5183
|
async function handleAttach(args) {
|
|
5192
5184
|
if (args.length === 0) {
|
|
5193
5185
|
printer_default.error("Usage: pinggy attach <name|id>");
|
|
@@ -5196,7 +5188,10 @@ async function handleAttach(args) {
|
|
|
5196
5188
|
const nameOrId = args[0];
|
|
5197
5189
|
const client = new TunnelClient();
|
|
5198
5190
|
try {
|
|
5199
|
-
|
|
5191
|
+
if (!client.connectIfRunning()) {
|
|
5192
|
+
printer_default.error(tunnelNotRunningMessage(nameOrId));
|
|
5193
|
+
return;
|
|
5194
|
+
}
|
|
5200
5195
|
} catch (err) {
|
|
5201
5196
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5202
5197
|
return;
|
|
@@ -5243,12 +5238,86 @@ async function handleAttach(args) {
|
|
|
5243
5238
|
}
|
|
5244
5239
|
|
|
5245
5240
|
// src/cli/subcommand/handlers/logsCommand.ts
|
|
5241
|
+
import fs9 from "fs";
|
|
5242
|
+
|
|
5243
|
+
// src/daemon/logPaths.ts
|
|
5246
5244
|
import fs8 from "fs";
|
|
5245
|
+
import path2 from "path";
|
|
5246
|
+
var TUNNEL_ORIGINS = ["app", "cli", "remote", "device"];
|
|
5247
|
+
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
5248
|
+
function parseTunnelLogFilename(filename) {
|
|
5249
|
+
const base = filename.replace(/\.log$/, "");
|
|
5250
|
+
const parts = base.split("__");
|
|
5251
|
+
if (parts.length < 2) return null;
|
|
5252
|
+
const origin = parts[0];
|
|
5253
|
+
if (!TUNNEL_ORIGINS.includes(origin)) return null;
|
|
5254
|
+
if (parts.length === 2) {
|
|
5255
|
+
const second = parts[1];
|
|
5256
|
+
if (UUID_RE.test(second)) return { origin, tunnelId: second };
|
|
5257
|
+
return { origin, name: second };
|
|
5258
|
+
}
|
|
5259
|
+
const tunnelId = parts[parts.length - 1];
|
|
5260
|
+
const name = parts.slice(1, -1).join("__");
|
|
5261
|
+
return { origin, name, tunnelId };
|
|
5262
|
+
}
|
|
5263
|
+
function listTunnelLogFiles() {
|
|
5264
|
+
const logDir = getTunnelLogDir();
|
|
5265
|
+
if (!fs8.existsSync(logDir)) return [];
|
|
5266
|
+
return fs8.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
|
|
5267
|
+
}
|
|
5268
|
+
function newestLogFile(q) {
|
|
5269
|
+
const logDir = getTunnelLogDir();
|
|
5270
|
+
const matches = [];
|
|
5271
|
+
for (const file of listTunnelLogFiles()) {
|
|
5272
|
+
const parsed = parseTunnelLogFilename(file);
|
|
5273
|
+
if (!parsed) continue;
|
|
5274
|
+
const nameMatch = parsed.name !== void 0 && parsed.name === q;
|
|
5275
|
+
const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
|
|
5276
|
+
if (nameMatch || idMatch) {
|
|
5277
|
+
const filePath = path2.join(logDir, file);
|
|
5278
|
+
matches.push({ ...parsed, path: filePath, mtime: fs8.statSync(filePath).mtimeMs });
|
|
5279
|
+
}
|
|
5280
|
+
}
|
|
5281
|
+
if (matches.length === 0) return null;
|
|
5282
|
+
matches.sort((a, b) => b.mtime - a.mtime);
|
|
5283
|
+
const best = matches[0];
|
|
5284
|
+
return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
|
|
5285
|
+
}
|
|
5286
|
+
function resolveStoppedLogPath(q) {
|
|
5287
|
+
if (!q) return { status: "not-found" };
|
|
5288
|
+
const historical = newestLogFile(q);
|
|
5289
|
+
if (historical) return historical;
|
|
5290
|
+
const saved = listSavedConfigs();
|
|
5291
|
+
const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
|
|
5292
|
+
if (matchedConfig) {
|
|
5293
|
+
return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
|
|
5294
|
+
}
|
|
5295
|
+
return { status: "not-found" };
|
|
5296
|
+
}
|
|
5297
|
+
|
|
5298
|
+
// src/cli/subcommand/handlers/logLookup.ts
|
|
5299
|
+
function openLogLookup() {
|
|
5300
|
+
const client = new TunnelClient();
|
|
5301
|
+
if (!client.connectIfRunning()) {
|
|
5302
|
+
return {
|
|
5303
|
+
daemonLogPath: () => Promise.resolve(getDaemonLogPath()),
|
|
5304
|
+
resolve: (nameOrId) => Promise.resolve(resolveStoppedLogPath(nameOrId)),
|
|
5305
|
+
close: () => void 0
|
|
5306
|
+
};
|
|
5307
|
+
}
|
|
5308
|
+
return {
|
|
5309
|
+
daemonLogPath: async () => (await client.getLogPaths()).daemon,
|
|
5310
|
+
resolve: (nameOrId) => client.resolveLogPath(nameOrId),
|
|
5311
|
+
close: () => client.close()
|
|
5312
|
+
};
|
|
5313
|
+
}
|
|
5314
|
+
|
|
5315
|
+
// src/cli/subcommand/handlers/logsCommand.ts
|
|
5247
5316
|
async function handleLogs(args, follow) {
|
|
5248
5317
|
const arg = args.find((a) => !a.startsWith("-"));
|
|
5249
|
-
|
|
5318
|
+
let client;
|
|
5250
5319
|
try {
|
|
5251
|
-
|
|
5320
|
+
client = openLogLookup();
|
|
5252
5321
|
} catch (err) {
|
|
5253
5322
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5254
5323
|
return;
|
|
@@ -5256,7 +5325,7 @@ async function handleLogs(args, follow) {
|
|
|
5256
5325
|
let filePath;
|
|
5257
5326
|
try {
|
|
5258
5327
|
if (arg) {
|
|
5259
|
-
const result = await client.
|
|
5328
|
+
const result = await client.resolve(arg);
|
|
5260
5329
|
if (result.status === "config-only") {
|
|
5261
5330
|
printer_default.error(`Tunnel "${arg}" is saved but has not been started yet. No logs available.`);
|
|
5262
5331
|
client.close();
|
|
@@ -5274,8 +5343,7 @@ async function handleLogs(args, follow) {
|
|
|
5274
5343
|
}
|
|
5275
5344
|
filePath = result.path;
|
|
5276
5345
|
} else {
|
|
5277
|
-
|
|
5278
|
-
filePath = paths.daemon;
|
|
5346
|
+
filePath = await client.daemonLogPath();
|
|
5279
5347
|
}
|
|
5280
5348
|
} catch (err) {
|
|
5281
5349
|
printer_default.error(`Failed to resolve log path: ${errorMessage(err)}`);
|
|
@@ -5283,7 +5351,7 @@ async function handleLogs(args, follow) {
|
|
|
5283
5351
|
return;
|
|
5284
5352
|
}
|
|
5285
5353
|
client.close();
|
|
5286
|
-
if (!filePath || !
|
|
5354
|
+
if (!filePath || !fs9.existsSync(filePath)) {
|
|
5287
5355
|
printer_default.error(`Log file not found: ${filePath}`);
|
|
5288
5356
|
process.exit(1);
|
|
5289
5357
|
}
|
|
@@ -5294,18 +5362,18 @@ async function handleLogs(args, follow) {
|
|
|
5294
5362
|
}
|
|
5295
5363
|
}
|
|
5296
5364
|
function printTail(filePath, lines) {
|
|
5297
|
-
const content =
|
|
5365
|
+
const content = fs9.readFileSync(filePath, "utf-8");
|
|
5298
5366
|
const allLines = content.split("\n");
|
|
5299
5367
|
const tail = allLines.slice(-lines).join("\n");
|
|
5300
5368
|
process.stdout.write(tail);
|
|
5301
5369
|
if (!tail.endsWith("\n")) process.stdout.write("\n");
|
|
5302
5370
|
}
|
|
5303
5371
|
async function followFile(filePath) {
|
|
5304
|
-
if (
|
|
5305
|
-
let fileSize =
|
|
5372
|
+
if (fs9.existsSync(filePath)) printTail(filePath, 20);
|
|
5373
|
+
let fileSize = fs9.existsSync(filePath) ? fs9.statSync(filePath).size : 0;
|
|
5306
5374
|
let watcher = null;
|
|
5307
5375
|
const openStream = () => {
|
|
5308
|
-
const stream =
|
|
5376
|
+
const stream = fs9.createReadStream(filePath, { start: fileSize, encoding: "utf-8" });
|
|
5309
5377
|
stream.on("data", (chunk) => {
|
|
5310
5378
|
process.stdout.write(chunk);
|
|
5311
5379
|
fileSize += Buffer.byteLength(chunk, "utf-8");
|
|
@@ -5313,9 +5381,9 @@ async function followFile(filePath) {
|
|
|
5313
5381
|
stream.on("error", () => {
|
|
5314
5382
|
});
|
|
5315
5383
|
};
|
|
5316
|
-
watcher =
|
|
5384
|
+
watcher = fs9.watch(filePath, { persistent: true }, (event2) => {
|
|
5317
5385
|
if (event2 === "change") {
|
|
5318
|
-
const stat =
|
|
5386
|
+
const stat = fs9.existsSync(filePath) ? fs9.statSync(filePath) : null;
|
|
5319
5387
|
if (!stat || stat.size < fileSize) {
|
|
5320
5388
|
fileSize = 0;
|
|
5321
5389
|
}
|
|
@@ -5351,26 +5419,39 @@ async function handleLog(args) {
|
|
|
5351
5419
|
printLogHelp();
|
|
5352
5420
|
}
|
|
5353
5421
|
}
|
|
5422
|
+
function parseLevel(arg) {
|
|
5423
|
+
const level = arg.toLowerCase();
|
|
5424
|
+
if (!VALID_LEVELS.includes(level)) {
|
|
5425
|
+
printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
|
|
5426
|
+
process.exit(1);
|
|
5427
|
+
}
|
|
5428
|
+
return level;
|
|
5429
|
+
}
|
|
5430
|
+
function handleLogLevelWithoutDaemon(level) {
|
|
5431
|
+
if (!level) {
|
|
5432
|
+
printer_default.print(`Log level: ${configuredLogLevel()}`);
|
|
5433
|
+
return;
|
|
5434
|
+
}
|
|
5435
|
+
writeDaemonConfig({ logLevel: level });
|
|
5436
|
+
printer_default.success(`Log level set to "${level}". The daemon uses it when it starts.`);
|
|
5437
|
+
}
|
|
5354
5438
|
async function handleLogLevel(args) {
|
|
5439
|
+
const level = args.length > 0 ? parseLevel(args[0]) : void 0;
|
|
5355
5440
|
const client = new TunnelClient();
|
|
5356
5441
|
try {
|
|
5357
|
-
|
|
5442
|
+
if (!client.connectIfRunning()) {
|
|
5443
|
+
handleLogLevelWithoutDaemon(level);
|
|
5444
|
+
return;
|
|
5445
|
+
}
|
|
5358
5446
|
} catch (err) {
|
|
5359
5447
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5360
5448
|
return;
|
|
5361
5449
|
}
|
|
5362
5450
|
try {
|
|
5363
|
-
if (
|
|
5364
|
-
|
|
5365
|
-
printer_default.print(`Log level: ${level2}`);
|
|
5451
|
+
if (!level) {
|
|
5452
|
+
printer_default.print(`Log level: ${await client.getLogLevel()}`);
|
|
5366
5453
|
return;
|
|
5367
5454
|
}
|
|
5368
|
-
const level = args[0].toLowerCase();
|
|
5369
|
-
if (!VALID_LEVELS.includes(level)) {
|
|
5370
|
-
printer_default.error(`Invalid log level: "${level}". Must be one of: ${VALID_LEVELS.join(", ")}`);
|
|
5371
|
-
client.close();
|
|
5372
|
-
process.exit(1);
|
|
5373
|
-
}
|
|
5374
5455
|
await client.setLogLevel(level);
|
|
5375
5456
|
printer_default.success(`Log level set to "${level}". Affects daemon JS logs and new tunnels. Run \`pinggy restart <name>\` to apply to a running tunnel.`);
|
|
5376
5457
|
} catch (err) {
|
|
@@ -5380,21 +5461,20 @@ async function handleLogLevel(args) {
|
|
|
5380
5461
|
}
|
|
5381
5462
|
}
|
|
5382
5463
|
async function handleLogPath(args) {
|
|
5383
|
-
|
|
5464
|
+
let client;
|
|
5384
5465
|
try {
|
|
5385
|
-
|
|
5466
|
+
client = openLogLookup();
|
|
5386
5467
|
} catch (err) {
|
|
5387
5468
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5388
5469
|
return;
|
|
5389
5470
|
}
|
|
5390
5471
|
try {
|
|
5391
5472
|
if (args.length === 0) {
|
|
5392
|
-
|
|
5393
|
-
printer_default.print(paths.daemon);
|
|
5473
|
+
printer_default.print(await client.daemonLogPath());
|
|
5394
5474
|
return;
|
|
5395
5475
|
}
|
|
5396
5476
|
const arg = args[0];
|
|
5397
|
-
const result = await client.
|
|
5477
|
+
const result = await client.resolve(arg);
|
|
5398
5478
|
switch (result.status) {
|
|
5399
5479
|
case "running":
|
|
5400
5480
|
case "historical":
|
|
@@ -5427,7 +5507,10 @@ async function handleRestart(args) {
|
|
|
5427
5507
|
const nameOrId = args[0];
|
|
5428
5508
|
const client = new TunnelClient();
|
|
5429
5509
|
try {
|
|
5430
|
-
|
|
5510
|
+
if (!client.connectIfRunning()) {
|
|
5511
|
+
printer_default.error(tunnelNotRunningMessage(nameOrId));
|
|
5512
|
+
process.exit(1);
|
|
5513
|
+
}
|
|
5431
5514
|
} catch (err) {
|
|
5432
5515
|
printer_default.error(`Cannot connect to daemon: ${errorMessage(err)}`);
|
|
5433
5516
|
return;
|
|
@@ -5458,7 +5541,89 @@ async function handleRestart(args) {
|
|
|
5458
5541
|
}
|
|
5459
5542
|
|
|
5460
5543
|
// src/cli/subcommand/handlers/deviceCommand.ts
|
|
5544
|
+
import pico10 from "picocolors";
|
|
5545
|
+
|
|
5546
|
+
// src/devices/removeDevice.ts
|
|
5461
5547
|
import pico9 from "picocolors";
|
|
5548
|
+
var YES_ANSWER2 = /^y(es)?$/i;
|
|
5549
|
+
var NO_TERMINAL_MESSAGE2 = "pinggy device remove asks before it removes the device. Run it in a terminal, or add -f to remove without asking.";
|
|
5550
|
+
function machineDeviceRemoveDependencies(background) {
|
|
5551
|
+
return {
|
|
5552
|
+
background,
|
|
5553
|
+
foreground: machineForegroundStopDependencies(),
|
|
5554
|
+
clearIdentity: clearDeviceIdentity,
|
|
5555
|
+
isInteractive: isInteractiveTerminal,
|
|
5556
|
+
prompter: terminalPrompter,
|
|
5557
|
+
print: (message) => printer_default.print(message),
|
|
5558
|
+
printSuccess: (message) => printer_default.success(message),
|
|
5559
|
+
printError: (message) => printer_default.error(message)
|
|
5560
|
+
};
|
|
5561
|
+
}
|
|
5562
|
+
async function readActivity(dependencies) {
|
|
5563
|
+
const reading = await readBackgroundAgent(dependencies.background);
|
|
5564
|
+
return {
|
|
5565
|
+
identity: dependencies.background.readIdentity(),
|
|
5566
|
+
background: reading && isAgentRunning(reading.status) ? reading : null,
|
|
5567
|
+
foreground: dependencies.background.readForegroundAgent()
|
|
5568
|
+
};
|
|
5569
|
+
}
|
|
5570
|
+
function describeActivity(activity) {
|
|
5571
|
+
const { identity, background, foreground } = activity;
|
|
5572
|
+
const lines = [];
|
|
5573
|
+
if (identity) {
|
|
5574
|
+
const deviceAgentId = identity.device_agent_id ?? "(id not yet assigned)";
|
|
5575
|
+
lines.push(`This machine is device ${deviceAgentId} on ${identity.server}.`);
|
|
5576
|
+
}
|
|
5577
|
+
if (background) {
|
|
5578
|
+
lines.push(`The device agent runs in the background: ${describeAgent(background)}.`);
|
|
5579
|
+
}
|
|
5580
|
+
if (foreground) {
|
|
5581
|
+
lines.push(`The device agent runs in another terminal, PID ${foreground.pid}.`);
|
|
5582
|
+
}
|
|
5583
|
+
if (background || foreground) {
|
|
5584
|
+
lines.push("Removing it stops the agent, and the device shows offline in the dashboard.");
|
|
5585
|
+
} else {
|
|
5586
|
+
lines.push("The device is not connected now.");
|
|
5587
|
+
}
|
|
5588
|
+
return lines;
|
|
5589
|
+
}
|
|
5590
|
+
async function confirmed(options, dependencies) {
|
|
5591
|
+
if (options.skipConfirmation) {
|
|
5592
|
+
return true;
|
|
5593
|
+
}
|
|
5594
|
+
const answer = await dependencies.prompter.ask("Remove this device from this machine? [y/N] ");
|
|
5595
|
+
return YES_ANSWER2.test(answer.trim());
|
|
5596
|
+
}
|
|
5597
|
+
async function runDeviceRemove(options, dependencies) {
|
|
5598
|
+
const activity = await readActivity(dependencies);
|
|
5599
|
+
if (!activity.identity && !activity.background && !activity.foreground) {
|
|
5600
|
+
dependencies.print(pico9.yellow("This machine is not enrolled."));
|
|
5601
|
+
return EXIT_OK;
|
|
5602
|
+
}
|
|
5603
|
+
if (!options.skipConfirmation && !dependencies.isInteractive()) {
|
|
5604
|
+
dependencies.printError(NO_TERMINAL_MESSAGE2);
|
|
5605
|
+
return EXIT_FAILED;
|
|
5606
|
+
}
|
|
5607
|
+
describeActivity(activity).forEach((line) => dependencies.print(line));
|
|
5608
|
+
if (!await confirmed(options, dependencies)) {
|
|
5609
|
+
dependencies.print("Nothing removed.");
|
|
5610
|
+
return EXIT_OK;
|
|
5611
|
+
}
|
|
5612
|
+
if (!await stopAgentBeforeRemove(dependencies.background)) {
|
|
5613
|
+
return EXIT_FAILED;
|
|
5614
|
+
}
|
|
5615
|
+
if (!await stopForegroundAgentBeforeRemove(dependencies.foreground)) {
|
|
5616
|
+
return EXIT_FAILED;
|
|
5617
|
+
}
|
|
5618
|
+
dependencies.background.forgetSavedAgent();
|
|
5619
|
+
if (dependencies.clearIdentity()) {
|
|
5620
|
+
dependencies.printSuccess("Local device credential removed.");
|
|
5621
|
+
dependencies.print(pico9.gray("The device still exists in the dashboard. Delete it there to revoke it."));
|
|
5622
|
+
}
|
|
5623
|
+
return EXIT_OK;
|
|
5624
|
+
}
|
|
5625
|
+
|
|
5626
|
+
// src/cli/subcommand/handlers/deviceCommand.ts
|
|
5462
5627
|
var DeviceVerb = {
|
|
5463
5628
|
Login: "login",
|
|
5464
5629
|
Connect: "connect",
|
|
@@ -5519,7 +5684,10 @@ async function handleDevice(args, background = machineBackgroundAgentDependencie
|
|
|
5519
5684
|
await handleDeviceStatus(background);
|
|
5520
5685
|
return;
|
|
5521
5686
|
case DeviceVerb.Remove:
|
|
5522
|
-
exitUnlessOk(await
|
|
5687
|
+
exitUnlessOk(await runDeviceRemove(
|
|
5688
|
+
{ skipConfirmation: Boolean(values.force) },
|
|
5689
|
+
machineDeviceRemoveDependencies(background)
|
|
5690
|
+
));
|
|
5523
5691
|
return;
|
|
5524
5692
|
default:
|
|
5525
5693
|
if (verb === "help" || verb === "--help" || verb === "-h") {
|
|
@@ -5545,7 +5713,15 @@ function devicesSpellingMessage(args) {
|
|
|
5545
5713
|
return `"pinggy devices" is now "pinggy device". Run: pinggy device ${suggestion}`;
|
|
5546
5714
|
}
|
|
5547
5715
|
async function mayRunInForeground(background) {
|
|
5548
|
-
const refusal = await foregroundRefusal(background);
|
|
5716
|
+
const refusal = foregroundAgentRefusal(background.readForegroundAgent()) ?? await foregroundRefusal(background);
|
|
5717
|
+
if (refusal) {
|
|
5718
|
+
printer_default.error(refusal);
|
|
5719
|
+
return false;
|
|
5720
|
+
}
|
|
5721
|
+
return true;
|
|
5722
|
+
}
|
|
5723
|
+
function mayRunInBackground(background) {
|
|
5724
|
+
const refusal = foregroundAgentRefusal(background.readForegroundAgent());
|
|
5549
5725
|
if (refusal) {
|
|
5550
5726
|
printer_default.error(refusal);
|
|
5551
5727
|
return false;
|
|
@@ -5557,6 +5733,7 @@ async function handleDeviceLogin(manage, name, inBackground, background) {
|
|
|
5557
5733
|
if (!await mayRunInForeground(background)) return EXIT_FAILED;
|
|
5558
5734
|
return runDeviceLogin({ manage, name });
|
|
5559
5735
|
}
|
|
5736
|
+
if (!mayRunInBackground(background)) return EXIT_FAILED;
|
|
5560
5737
|
return runDeviceLogin({ manage, name }, {
|
|
5561
5738
|
...machineDeviceLoginDependencies(),
|
|
5562
5739
|
runAgent: (token, agentManage, signInShown) => startAgentInBackground({ token, manage: agentManage }, background, { signInShown })
|
|
@@ -5569,6 +5746,7 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
|
|
|
5569
5746
|
return EXIT_FAILED;
|
|
5570
5747
|
}
|
|
5571
5748
|
if (inBackground) {
|
|
5749
|
+
if (!mayRunInBackground(background)) return EXIT_FAILED;
|
|
5572
5750
|
return startAgentInBackground(target, background);
|
|
5573
5751
|
}
|
|
5574
5752
|
if (!await mayRunInForeground(background)) return EXIT_FAILED;
|
|
@@ -5578,26 +5756,186 @@ async function handleDeviceConnect(flagToken, environmentToken, manage, inBackgr
|
|
|
5578
5756
|
async function handleDeviceStatus(background) {
|
|
5579
5757
|
const identity = background.readIdentity();
|
|
5580
5758
|
if (!identity) {
|
|
5581
|
-
printer_default.print(
|
|
5759
|
+
printer_default.print(pico10.yellow("This machine is not enrolled. Run: pinggy device login"));
|
|
5582
5760
|
return;
|
|
5583
5761
|
}
|
|
5584
|
-
printer_default.print(` Device id ${identity.device_agent_id ??
|
|
5762
|
+
printer_default.print(` Device id ${identity.device_agent_id ?? pico10.gray("not yet assigned")}`);
|
|
5585
5763
|
printer_default.print(` Server ${identity.server}`);
|
|
5586
5764
|
printer_default.print(` Token ${maskToken(identity.token)}`);
|
|
5587
|
-
printer_default.print(` Enrolled ${identity.enrolled_at ??
|
|
5765
|
+
printer_default.print(` Enrolled ${identity.enrolled_at ?? pico10.gray("never")}`);
|
|
5766
|
+
printer_default.print(` Autostart ${background.hasSavedAgent() ? "on, starts with the daemon" : pico10.gray("off")}`);
|
|
5767
|
+
const foreground = background.readForegroundAgent();
|
|
5768
|
+
if (foreground) {
|
|
5769
|
+
printer_default.print(` Foreground running in another terminal, PID ${foreground.pid}`);
|
|
5770
|
+
}
|
|
5588
5771
|
await printBackgroundStatus(background);
|
|
5589
5772
|
}
|
|
5590
|
-
|
|
5591
|
-
|
|
5592
|
-
|
|
5773
|
+
|
|
5774
|
+
// src/cli/subcommand/handlers/updateCommand.ts
|
|
5775
|
+
var EXIT_OK2 = 0;
|
|
5776
|
+
var EXIT_FAILURE = 1;
|
|
5777
|
+
var CHECK_TIMEOUT_MILLIS = 1e4;
|
|
5778
|
+
var CHECK_FLAG = "--check";
|
|
5779
|
+
var ROLLBACK_FLAG = "--rollback";
|
|
5780
|
+
var KNOWN_FLAGS = /* @__PURE__ */ new Set([CHECK_FLAG, ROLLBACK_FLAG]);
|
|
5781
|
+
var HELP_FLAGS = /* @__PURE__ */ new Set(["--help", "-h"]);
|
|
5782
|
+
var SUDO_UID_ENV2 = "SUDO_UID";
|
|
5783
|
+
function createContext() {
|
|
5784
|
+
return { probe: createInstallProbe(), runningVersion: getVersion() };
|
|
5785
|
+
}
|
|
5786
|
+
function targetFor(kind, context) {
|
|
5787
|
+
return context.target !== void 0 ? context.target : createUpdateTarget(kind, context.probe);
|
|
5788
|
+
}
|
|
5789
|
+
function printAvailable(latest, running, command) {
|
|
5790
|
+
printer_default.print(`pinggy ${latest} is available. You run ${running}.`);
|
|
5791
|
+
printer_default.print(`Run: ${command}`);
|
|
5792
|
+
}
|
|
5793
|
+
function installCommand(kind, probe) {
|
|
5794
|
+
return kind === InstallKind.Npm ? NPM_INSTALL_COMMAND : installCommandFor(probe.platform);
|
|
5795
|
+
}
|
|
5796
|
+
async function lookUpRelease(installed) {
|
|
5797
|
+
try {
|
|
5798
|
+
const tag = await resolveLatestTag({ timeoutMillis: CHECK_TIMEOUT_MILLIS });
|
|
5799
|
+
const latest = versionFromTag(tag);
|
|
5800
|
+
const newer = isNewerVersion(latest, installed);
|
|
5801
|
+
if (newer && !await isReleaseComplete(tag, { timeoutMillis: CHECK_TIMEOUT_MILLIS })) {
|
|
5802
|
+
printer_default.error(`Release ${tag} is not ready. Try again later.`);
|
|
5803
|
+
return null;
|
|
5804
|
+
}
|
|
5805
|
+
return { tag, latest, newer };
|
|
5806
|
+
} catch {
|
|
5807
|
+
printer_default.error("Could not reach GitHub to check for updates.");
|
|
5808
|
+
return null;
|
|
5593
5809
|
}
|
|
5594
|
-
|
|
5595
|
-
|
|
5596
|
-
|
|
5597
|
-
|
|
5598
|
-
|
|
5810
|
+
}
|
|
5811
|
+
async function runCheck(kind, context) {
|
|
5812
|
+
const running = context.runningVersion;
|
|
5813
|
+
const release = await lookUpRelease(running);
|
|
5814
|
+
if (!release) return EXIT_FAILURE;
|
|
5815
|
+
recordLatestVersion(release.latest);
|
|
5816
|
+
if (release.newer) printAvailable(release.latest, running, installCommand(kind, context.probe));
|
|
5817
|
+
else printer_default.print(`pinggy ${running} is up to date.`);
|
|
5818
|
+
return EXIT_OK2;
|
|
5819
|
+
}
|
|
5820
|
+
async function underUpdateLock(action) {
|
|
5821
|
+
if (!await acquireUpdateLock()) {
|
|
5822
|
+
printer_default.error("Another pinggy update is running.");
|
|
5823
|
+
return EXIT_FAILURE;
|
|
5599
5824
|
}
|
|
5600
|
-
|
|
5825
|
+
try {
|
|
5826
|
+
return await action();
|
|
5827
|
+
} catch (error) {
|
|
5828
|
+
if (!(error instanceof UpdateError)) throw error;
|
|
5829
|
+
printer_default.error(error.message);
|
|
5830
|
+
return EXIT_FAILURE;
|
|
5831
|
+
} finally {
|
|
5832
|
+
releaseUpdateLock();
|
|
5833
|
+
}
|
|
5834
|
+
}
|
|
5835
|
+
async function installRelease(release, target, context) {
|
|
5836
|
+
const { tag, latest } = release;
|
|
5837
|
+
const runningVersion = context.runningVersion;
|
|
5838
|
+
const assetName = assetNameFor(context.probe.platform, context.architecture ?? process.arch);
|
|
5839
|
+
return underUpdateLock(async () => {
|
|
5840
|
+
let daemonRestart;
|
|
5841
|
+
try {
|
|
5842
|
+
await downloadRelease(target, tag, assetName, runningVersion, context.download);
|
|
5843
|
+
daemonRestart = await daemonRestartLineFor(target.downloadPath, latest, context);
|
|
5844
|
+
await target.install({ newVersion: latest, runningVersion });
|
|
5845
|
+
} finally {
|
|
5846
|
+
removeQuietly(target.downloadPath);
|
|
5847
|
+
}
|
|
5848
|
+
writeUpdateState({
|
|
5849
|
+
rolledBackFromVersion: void 0,
|
|
5850
|
+
failedVersion: void 0,
|
|
5851
|
+
failedAttempts: void 0,
|
|
5852
|
+
deferredVersion: void 0,
|
|
5853
|
+
deferredIpcVersion: void 0
|
|
5854
|
+
});
|
|
5855
|
+
printer_default.print(`Updated pinggy ${runningVersion} to ${latest}.`);
|
|
5856
|
+
if (daemonRestart) printer_default.print(daemonRestart);
|
|
5857
|
+
return EXIT_OK2;
|
|
5858
|
+
});
|
|
5859
|
+
}
|
|
5860
|
+
async function daemonRestartLineFor(binaryPath, version, context) {
|
|
5861
|
+
const daemon = getDaemonInfo();
|
|
5862
|
+
if (!daemon) return null;
|
|
5863
|
+
const ipcVersion = await readBinaryIpcVersion(binaryPath, context.runBinary ?? runPinggyBinary).catch(() => null);
|
|
5864
|
+
return ipcVersion !== null && ipcVersion !== daemonIpcVersion(daemon) ? daemonRestartLine(version, daemon.host) : null;
|
|
5865
|
+
}
|
|
5866
|
+
function isRollbackCopy(kind, context) {
|
|
5867
|
+
return kind === InstallKind.WindowsWritable && windowsInstallPaths(context.probe.execPath).runningFromBackup;
|
|
5868
|
+
}
|
|
5869
|
+
async function runUpdate(kind, context) {
|
|
5870
|
+
if (isRollbackCopy(kind, context)) {
|
|
5871
|
+
const { liveName } = windowsInstallPaths(context.probe.execPath);
|
|
5872
|
+
printer_default.error(`This is the rollback copy of ${liveName}. It runs only: update ${ROLLBACK_FLAG}`);
|
|
5873
|
+
return EXIT_FAILURE;
|
|
5874
|
+
}
|
|
5875
|
+
const target = targetFor(kind, context);
|
|
5876
|
+
const running = context.runningVersion;
|
|
5877
|
+
const release = await lookUpRelease(target ? target.installedVersion(running) : running);
|
|
5878
|
+
if (!release) return EXIT_FAILURE;
|
|
5879
|
+
recordLatestVersion(release.latest);
|
|
5880
|
+
if (!release.newer) {
|
|
5881
|
+
printer_default.print(`pinggy ${running} is up to date.`);
|
|
5882
|
+
return EXIT_OK2;
|
|
5883
|
+
}
|
|
5884
|
+
if (!target) {
|
|
5885
|
+
printAvailable(release.latest, running, installCommand(kind, context.probe));
|
|
5886
|
+
return EXIT_OK2;
|
|
5887
|
+
}
|
|
5888
|
+
return installRelease(release, target, context);
|
|
5889
|
+
}
|
|
5890
|
+
async function runRollback(kind, context) {
|
|
5891
|
+
const target = targetFor(kind, context);
|
|
5892
|
+
if (!target) {
|
|
5893
|
+
printer_default.error(rollbackRefusal(kind));
|
|
5894
|
+
return EXIT_FAILURE;
|
|
5895
|
+
}
|
|
5896
|
+
return underUpdateLock(async () => {
|
|
5897
|
+
const { from, to } = await target.rollback(context.runningVersion);
|
|
5898
|
+
writeUpdateState({ updatedFromVersion: void 0, updatedToVersion: void 0 });
|
|
5899
|
+
printer_default.print(`Rolled back pinggy ${from} to ${to}.`);
|
|
5900
|
+
const daemonRestart = await daemonRestartLineFor(target.rollbackBinaryPath(to), to, context);
|
|
5901
|
+
if (daemonRestart) printer_default.print(daemonRestart);
|
|
5902
|
+
return EXIT_OK2;
|
|
5903
|
+
});
|
|
5904
|
+
}
|
|
5905
|
+
function rollbackRefusal(kind) {
|
|
5906
|
+
if (kind === InstallKind.WindowsReadOnly || kind === InstallKind.UnixLoose) return "This copy of pinggy cannot update itself.";
|
|
5907
|
+
return "Rollback is not available for this install.";
|
|
5908
|
+
}
|
|
5909
|
+
async function runUpdateCommand(rest, context = createContext()) {
|
|
5910
|
+
if (rest.some((argument) => HELP_FLAGS.has(argument))) {
|
|
5911
|
+
printUpdateHelp();
|
|
5912
|
+
return EXIT_OK2;
|
|
5913
|
+
}
|
|
5914
|
+
const check = rest.includes(CHECK_FLAG);
|
|
5915
|
+
const rollback = rest.includes(ROLLBACK_FLAG);
|
|
5916
|
+
if (rest.some((argument) => !KNOWN_FLAGS.has(argument)) || check && rollback) {
|
|
5917
|
+
printUpdateHelp();
|
|
5918
|
+
return EXIT_FAILURE;
|
|
5919
|
+
}
|
|
5920
|
+
const kind = detectInstallKind(context.probe);
|
|
5921
|
+
if (kind === InstallKind.DevCheckout) {
|
|
5922
|
+
printer_default.print("This is not a packaged build. Run from your checkout, or install a release.");
|
|
5923
|
+
return EXIT_OK2;
|
|
5924
|
+
}
|
|
5925
|
+
if (parseVersion(context.runningVersion) === null) {
|
|
5926
|
+
printer_default.error("Could not read the running version.");
|
|
5927
|
+
return EXIT_FAILURE;
|
|
5928
|
+
}
|
|
5929
|
+
if (check) return runCheck(kind, context);
|
|
5930
|
+
if (process.env[SUDO_UID_ENV2]) {
|
|
5931
|
+
printer_default.error("pinggy update does not run under sudo. Run it without sudo.");
|
|
5932
|
+
return EXIT_FAILURE;
|
|
5933
|
+
}
|
|
5934
|
+
return rollback ? runRollback(kind, context) : runUpdate(kind, context);
|
|
5935
|
+
}
|
|
5936
|
+
async function handleUpdate(rest) {
|
|
5937
|
+
const exitCode = await runUpdateCommand(rest);
|
|
5938
|
+
if (exitCode !== EXIT_OK2) process.exit(exitCode);
|
|
5601
5939
|
}
|
|
5602
5940
|
|
|
5603
5941
|
// src/cli/subcommand/subcommands.ts
|
|
@@ -5646,6 +5984,9 @@ async function handleSubcommand(rawArgs) {
|
|
|
5646
5984
|
case Subcommand.Devices:
|
|
5647
5985
|
refuseDevicesSpelling(rest);
|
|
5648
5986
|
return;
|
|
5987
|
+
case Subcommand.Update:
|
|
5988
|
+
await handleUpdate(rest);
|
|
5989
|
+
return;
|
|
5649
5990
|
}
|
|
5650
5991
|
}
|
|
5651
5992
|
function handleConfig(args) {
|
|
@@ -5868,12 +6209,12 @@ async function initRemoteManagementBackground(values) {
|
|
|
5868
6209
|
}
|
|
5869
6210
|
|
|
5870
6211
|
// src/daemon/lifecycle/daemonChild.ts
|
|
5871
|
-
import
|
|
6212
|
+
import fs13 from "fs";
|
|
5872
6213
|
|
|
5873
6214
|
// src/daemon/ipc/ipcServer.ts
|
|
5874
6215
|
import http from "http";
|
|
5875
|
-
import
|
|
5876
|
-
import
|
|
6216
|
+
import fs11 from "fs";
|
|
6217
|
+
import path4 from "path";
|
|
5877
6218
|
import { WebSocketServer, WebSocket as WebSocket2 } from "ws";
|
|
5878
6219
|
|
|
5879
6220
|
// src/daemon/ws/wsProtocol.ts
|
|
@@ -5900,17 +6241,17 @@ function parseClientMessage(raw) {
|
|
|
5900
6241
|
}
|
|
5901
6242
|
|
|
5902
6243
|
// src/daemon/lifecycle/stateStore.ts
|
|
5903
|
-
import
|
|
5904
|
-
import
|
|
6244
|
+
import fs10 from "fs";
|
|
6245
|
+
import path3 from "path";
|
|
5905
6246
|
var STATE_FILENAME = "daemon-state.json";
|
|
5906
6247
|
function getStatePath() {
|
|
5907
|
-
return
|
|
6248
|
+
return path3.join(getPinggyConfigDir(), STATE_FILENAME);
|
|
5908
6249
|
}
|
|
5909
6250
|
function loadDaemonState() {
|
|
5910
6251
|
const statePath = getStatePath();
|
|
5911
6252
|
try {
|
|
5912
|
-
if (!
|
|
5913
|
-
const raw =
|
|
6253
|
+
if (!fs10.existsSync(statePath)) return null;
|
|
6254
|
+
const raw = fs10.readFileSync(statePath, "utf-8");
|
|
5914
6255
|
const state = JSON.parse(raw);
|
|
5915
6256
|
if (!Array.isArray(state.tunnels)) return null;
|
|
5916
6257
|
return state;
|
|
@@ -5924,8 +6265,8 @@ function persistDaemonState(state) {
|
|
|
5924
6265
|
const tmpPath = statePath + ".tmp";
|
|
5925
6266
|
try {
|
|
5926
6267
|
state.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
|
|
5927
|
-
|
|
5928
|
-
|
|
6268
|
+
fs10.writeFileSync(tmpPath, JSON.stringify(state, null, 2), "utf-8");
|
|
6269
|
+
fs10.renameSync(tmpPath, statePath);
|
|
5929
6270
|
} catch (err) {
|
|
5930
6271
|
logger.error("Failed to persist daemon state", { error: errorMessage(err) });
|
|
5931
6272
|
}
|
|
@@ -5933,8 +6274,8 @@ function persistDaemonState(state) {
|
|
|
5933
6274
|
function clearDaemonState() {
|
|
5934
6275
|
const statePath = getStatePath();
|
|
5935
6276
|
try {
|
|
5936
|
-
if (
|
|
5937
|
-
|
|
6277
|
+
if (fs10.existsSync(statePath)) {
|
|
6278
|
+
fs10.unlinkSync(statePath);
|
|
5938
6279
|
}
|
|
5939
6280
|
} catch {
|
|
5940
6281
|
}
|
|
@@ -5948,33 +6289,16 @@ function removeTunnelFromState(state, tunnelId) {
|
|
|
5948
6289
|
}
|
|
5949
6290
|
|
|
5950
6291
|
// src/daemon/ipc/ipcServer.ts
|
|
5951
|
-
var VALID_ORIGINS = ["app", "cli", "remote", "device"];
|
|
5952
6292
|
function parseOrigin(req) {
|
|
5953
6293
|
const raw = req.headers["x-pinggy-origin"];
|
|
5954
6294
|
const v = Array.isArray(raw) ? raw[0] : raw;
|
|
5955
|
-
return v &&
|
|
6295
|
+
return v && TUNNEL_ORIGINS.includes(v) ? v : "cli";
|
|
5956
6296
|
}
|
|
5957
6297
|
function parseBody(method, body) {
|
|
5958
6298
|
if (method === "GET") return void 0;
|
|
5959
6299
|
if (!body) return {};
|
|
5960
6300
|
return JSON.parse(body);
|
|
5961
6301
|
}
|
|
5962
|
-
var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
5963
|
-
function parseTunnelLogFilename(filename) {
|
|
5964
|
-
const base = filename.replace(/\.log$/, "");
|
|
5965
|
-
const parts = base.split("__");
|
|
5966
|
-
if (parts.length < 2) return null;
|
|
5967
|
-
const origin = parts[0];
|
|
5968
|
-
if (!VALID_ORIGINS.includes(origin)) return null;
|
|
5969
|
-
if (parts.length === 2) {
|
|
5970
|
-
const second = parts[1];
|
|
5971
|
-
if (UUID_RE.test(second)) return { origin, tunnelId: second };
|
|
5972
|
-
return { origin, name: second };
|
|
5973
|
-
}
|
|
5974
|
-
const tunnelId = parts[parts.length - 1];
|
|
5975
|
-
const name = parts.slice(1, -1).join("__");
|
|
5976
|
-
return { origin, name, tunnelId };
|
|
5977
|
-
}
|
|
5978
6302
|
var IPCServer = class {
|
|
5979
6303
|
constructor() {
|
|
5980
6304
|
this.sessions = /* @__PURE__ */ new Map();
|
|
@@ -6110,8 +6434,8 @@ var IPCServer = class {
|
|
|
6110
6434
|
const logDir = getTunnelLogDir();
|
|
6111
6435
|
const daemonPath = getDaemonLogPath();
|
|
6112
6436
|
const tunnels = [];
|
|
6113
|
-
|
|
6114
|
-
|
|
6437
|
+
const files = listTunnelLogFiles();
|
|
6438
|
+
if (files.length > 0) {
|
|
6115
6439
|
const manager = TunnelManager.getInstance();
|
|
6116
6440
|
const activeIds = manager.getActiveTunnelIds();
|
|
6117
6441
|
const activeNames = /* @__PURE__ */ new Set();
|
|
@@ -6121,8 +6445,8 @@ var IPCServer = class {
|
|
|
6121
6445
|
if (n) activeNames.add(n);
|
|
6122
6446
|
}
|
|
6123
6447
|
for (const file of files) {
|
|
6124
|
-
const filePath =
|
|
6125
|
-
const stat =
|
|
6448
|
+
const filePath = path4.join(logDir, file);
|
|
6449
|
+
const stat = fs11.statSync(filePath);
|
|
6126
6450
|
const parsed = parseTunnelLogFilename(file);
|
|
6127
6451
|
if (!parsed) continue;
|
|
6128
6452
|
const running = parsed.tunnelId ? activeIds.has(parsed.tunnelId) : parsed.name ? activeNames.has(parsed.name) : false;
|
|
@@ -6229,7 +6553,6 @@ var IPCServer = class {
|
|
|
6229
6553
|
}
|
|
6230
6554
|
async resolveLogPath(q) {
|
|
6231
6555
|
if (!q) return { status: "not-found" };
|
|
6232
|
-
const logDir = getTunnelLogDir();
|
|
6233
6556
|
const manager = TunnelManager.getInstance();
|
|
6234
6557
|
const activeIds = manager.getActiveTunnelIds();
|
|
6235
6558
|
for (const t of await manager.getAllTunnels()) {
|
|
@@ -6241,32 +6564,7 @@ var IPCServer = class {
|
|
|
6241
6564
|
return { status: "running", path: logPath, tunnelId: t.tunnelid, name, origin, running: true };
|
|
6242
6565
|
}
|
|
6243
6566
|
}
|
|
6244
|
-
|
|
6245
|
-
const files = fs10.readdirSync(logDir).filter((f) => f.endsWith(".log") && !/\.log\.\d+$/.test(f));
|
|
6246
|
-
const matches = [];
|
|
6247
|
-
for (const file of files) {
|
|
6248
|
-
const parsed = parseTunnelLogFilename(file);
|
|
6249
|
-
if (!parsed) continue;
|
|
6250
|
-
const nameMatch = parsed.name !== void 0 && parsed.name === q;
|
|
6251
|
-
const idMatch = parsed.tunnelId !== void 0 && (parsed.tunnelId === q || parsed.tunnelId.startsWith(q));
|
|
6252
|
-
if (nameMatch || idMatch) {
|
|
6253
|
-
const filePath = path5.join(logDir, file);
|
|
6254
|
-
const stat = fs10.statSync(filePath);
|
|
6255
|
-
matches.push({ path: filePath, mtime: stat.mtimeMs, tunnelId: parsed.tunnelId, name: parsed.name, origin: parsed.origin });
|
|
6256
|
-
}
|
|
6257
|
-
}
|
|
6258
|
-
if (matches.length > 0) {
|
|
6259
|
-
matches.sort((a, b) => b.mtime - a.mtime);
|
|
6260
|
-
const best = matches[0];
|
|
6261
|
-
return { status: "historical", path: best.path, tunnelId: best.tunnelId, name: best.name, origin: best.origin, running: false };
|
|
6262
|
-
}
|
|
6263
|
-
}
|
|
6264
|
-
const saved = listSavedConfigs();
|
|
6265
|
-
const matchedConfig = saved.find((c) => c.name === q || c.configId === q || c.configId.startsWith(q));
|
|
6266
|
-
if (matchedConfig) {
|
|
6267
|
-
return { status: "config-only", name: matchedConfig.name, configId: matchedConfig.configId };
|
|
6268
|
-
}
|
|
6269
|
-
return { status: "not-found" };
|
|
6567
|
+
return resolveStoppedLogPath(q);
|
|
6270
6568
|
}
|
|
6271
6569
|
setupWebSocket() {
|
|
6272
6570
|
this.server.on("upgrade", (req, socket, head) => {
|
|
@@ -6628,7 +6926,7 @@ var DeviceAgentHost = class {
|
|
|
6628
6926
|
this.statusValue = stoppedStatus();
|
|
6629
6927
|
/** Bumped on every start and stop. A run's reporter whose number is old belongs to a run that ended. */
|
|
6630
6928
|
this.generation = 0;
|
|
6631
|
-
/** Set once the daemon shuts down. Nothing starts and nothing more
|
|
6929
|
+
/** Set once the daemon shuts down. Nothing starts and nothing more is recorded. */
|
|
6632
6930
|
this.closed = false;
|
|
6633
6931
|
/** Start and stop chain on this, so 1 finishes before the next begins. */
|
|
6634
6932
|
this.queue = Promise.resolve();
|
|
@@ -6666,8 +6964,8 @@ var DeviceAgentHost = class {
|
|
|
6666
6964
|
});
|
|
6667
6965
|
}
|
|
6668
6966
|
/**
|
|
6669
|
-
* The daemon is shutting down. Stops the run at once, outside the queue,
|
|
6670
|
-
*
|
|
6967
|
+
* The daemon is shutting down. Stops the run at once, outside the queue. Records nothing, so the saved
|
|
6968
|
+
* agent stays and the next daemon start runs it again.
|
|
6671
6969
|
*/
|
|
6672
6970
|
close() {
|
|
6673
6971
|
this.closed = true;
|
|
@@ -6710,9 +7008,6 @@ var DeviceAgentHost = class {
|
|
|
6710
7008
|
this.current = null;
|
|
6711
7009
|
this.generation += 1;
|
|
6712
7010
|
this.statusValue = { ...this.statusValue, state: DeviceAgentState.Stopped, connectedAt: null };
|
|
6713
|
-
if (!this.closed) {
|
|
6714
|
-
this.dependencies.recordStopped();
|
|
6715
|
-
}
|
|
6716
7011
|
await current.run.stop();
|
|
6717
7012
|
logger.info("Device agent stopped in the daemon");
|
|
6718
7013
|
}
|
|
@@ -6796,6 +7091,56 @@ function machineDeviceAgentHostDependencies(port, record) {
|
|
|
6796
7091
|
};
|
|
6797
7092
|
}
|
|
6798
7093
|
|
|
7094
|
+
// src/daemon/lifecycle/daemonLock.ts
|
|
7095
|
+
import fs12 from "fs";
|
|
7096
|
+
var UNREADABLE_LOCK_GRACE_MILLIS = 1e4;
|
|
7097
|
+
function readLock(lockPath) {
|
|
7098
|
+
try {
|
|
7099
|
+
const record = JSON.parse(fs12.readFileSync(lockPath, "utf-8"));
|
|
7100
|
+
return Number.isInteger(record.pid) && record.pid > 0 ? record : null;
|
|
7101
|
+
} catch {
|
|
7102
|
+
return null;
|
|
7103
|
+
}
|
|
7104
|
+
}
|
|
7105
|
+
function isUnreadableLockOld(lockPath) {
|
|
7106
|
+
try {
|
|
7107
|
+
return Date.now() - fs12.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_GRACE_MILLIS;
|
|
7108
|
+
} catch {
|
|
7109
|
+
return true;
|
|
7110
|
+
}
|
|
7111
|
+
}
|
|
7112
|
+
function isStale(lockPath, holder) {
|
|
7113
|
+
if (!holder) return isUnreadableLockOld(lockPath);
|
|
7114
|
+
return startedBeforeBoot(holder.started_at) || !isProcessAlive(holder.pid);
|
|
7115
|
+
}
|
|
7116
|
+
function createLock(lockPath, record) {
|
|
7117
|
+
try {
|
|
7118
|
+
fs12.writeFileSync(lockPath, JSON.stringify(record), { encoding: "utf-8", flag: "wx" });
|
|
7119
|
+
return true;
|
|
7120
|
+
} catch (err) {
|
|
7121
|
+
if (err.code === "EEXIST") return false;
|
|
7122
|
+
throw err;
|
|
7123
|
+
}
|
|
7124
|
+
}
|
|
7125
|
+
function acquireDaemonLock() {
|
|
7126
|
+
ensurePinggyConfigDir();
|
|
7127
|
+
const lockPath = getDaemonLockPath();
|
|
7128
|
+
const record = { pid: process.pid, started_at: (/* @__PURE__ */ new Date()).toISOString() };
|
|
7129
|
+
if (createLock(lockPath, record)) return true;
|
|
7130
|
+
const holder = readLock(lockPath);
|
|
7131
|
+
if (holder?.pid === process.pid) return true;
|
|
7132
|
+
if (!isStale(lockPath, holder)) return false;
|
|
7133
|
+
logger.info("Stale daemon.lock found, replacing it", { stalePid: holder?.pid });
|
|
7134
|
+
fs12.rmSync(lockPath, { force: true });
|
|
7135
|
+
return createLock(lockPath, record);
|
|
7136
|
+
}
|
|
7137
|
+
function releaseDaemonLock() {
|
|
7138
|
+
const lockPath = getDaemonLockPath();
|
|
7139
|
+
if (readLock(lockPath)?.pid === process.pid) {
|
|
7140
|
+
fs12.rmSync(lockPath, { force: true });
|
|
7141
|
+
}
|
|
7142
|
+
}
|
|
7143
|
+
|
|
6799
7144
|
// src/daemon/lifecycle/daemonChild.ts
|
|
6800
7145
|
var daemonState = { tunnels: [], lastUpdated: "" };
|
|
6801
7146
|
var daemonHost = DaemonHost.CLI;
|
|
@@ -6810,13 +7155,14 @@ function writeDaemonInfo(info) {
|
|
|
6810
7155
|
ensurePinggyConfigDir();
|
|
6811
7156
|
const infoPath = getDaemonInfoPath();
|
|
6812
7157
|
const tmpPath = infoPath + ".tmp";
|
|
6813
|
-
|
|
6814
|
-
|
|
7158
|
+
fs13.writeFileSync(tmpPath, JSON.stringify(info, null, 2), "utf-8");
|
|
7159
|
+
fs13.renameSync(tmpPath, infoPath);
|
|
6815
7160
|
}
|
|
6816
7161
|
function removeDaemonInfo() {
|
|
6817
7162
|
try {
|
|
6818
7163
|
const infoPath = getDaemonInfoPath();
|
|
6819
|
-
|
|
7164
|
+
const info = JSON.parse(fs13.readFileSync(infoPath, "utf-8"));
|
|
7165
|
+
if (info.pid === process.pid) fs13.unlinkSync(infoPath);
|
|
6820
7166
|
} catch {
|
|
6821
7167
|
}
|
|
6822
7168
|
}
|
|
@@ -6841,27 +7187,23 @@ function trackTunnelStop(tunnelId) {
|
|
|
6841
7187
|
persistDaemonState(daemonState);
|
|
6842
7188
|
sessionTrackerRef?.removeTunnel(tunnelId);
|
|
6843
7189
|
}
|
|
6844
|
-
function
|
|
6845
|
-
|
|
6846
|
-
|
|
6847
|
-
}
|
|
6848
|
-
|
|
6849
|
-
|
|
6850
|
-
delete daemonState.deviceAgent;
|
|
6851
|
-
persistDaemonState(daemonState);
|
|
6852
|
-
}
|
|
6853
|
-
async function restoreCrashedDeviceAgent(host, saved) {
|
|
7190
|
+
async function startSavedDeviceAgent(host, saved) {
|
|
7191
|
+
const foreground = readForegroundAgent();
|
|
7192
|
+
if (foreground) {
|
|
7193
|
+
logger.info("Device agent not started: it runs in a terminal", { pid: foreground.pid });
|
|
7194
|
+
return;
|
|
7195
|
+
}
|
|
6854
7196
|
try {
|
|
6855
7197
|
const result = await host.start(saved.startedBy);
|
|
6856
7198
|
if (isErrorResponse(result)) {
|
|
6857
|
-
logger.warn("
|
|
6858
|
-
|
|
7199
|
+
logger.warn("Saved device agent not started", { reason: result.message });
|
|
7200
|
+
forgetDeviceAgent();
|
|
6859
7201
|
return;
|
|
6860
7202
|
}
|
|
6861
|
-
logger.info("
|
|
7203
|
+
logger.info("Saved device agent started");
|
|
6862
7204
|
} catch (err) {
|
|
6863
|
-
logger.error("
|
|
6864
|
-
|
|
7205
|
+
logger.error("Saved device agent failed to start", { error: errorMessage(err) });
|
|
7206
|
+
forgetDeviceAgent();
|
|
6865
7207
|
}
|
|
6866
7208
|
}
|
|
6867
7209
|
function trackIPCTunnelStart(tunnelId, origin, mode = SessionMode.Detached) {
|
|
@@ -6956,9 +7298,7 @@ async function runDaemonChild(opts = {}) {
|
|
|
6956
7298
|
const exitOnFailure = opts.exitOnFailure ?? true;
|
|
6957
7299
|
daemonHost = opts.host ?? DaemonHost.CLI;
|
|
6958
7300
|
ensurePinggyConfigDir();
|
|
6959
|
-
const
|
|
6960
|
-
const envLevel = process.env.PINGGY_LOG_LEVEL;
|
|
6961
|
-
const initialLevel = persistedLevel ?? envLevel ?? "info";
|
|
7301
|
+
const initialLevel = configuredLogLevel();
|
|
6962
7302
|
setLogLevel(initialLevel);
|
|
6963
7303
|
ensurePinggyLogDir();
|
|
6964
7304
|
const logPath = getDaemonLogPath();
|
|
@@ -6969,6 +7309,11 @@ async function runDaemonChild(opts = {}) {
|
|
|
6969
7309
|
enableSdkLog: true
|
|
6970
7310
|
});
|
|
6971
7311
|
logger.info("Daemon starting", { pid: process.pid, inProcess: !installSignalHandlers });
|
|
7312
|
+
if (!acquireDaemonLock()) {
|
|
7313
|
+
logger.info("Another daemon holds daemon.lock. Exiting.");
|
|
7314
|
+
if (exitOnFailure) process.exit(0);
|
|
7315
|
+
throw new Error("Another pinggy daemon is running.");
|
|
7316
|
+
}
|
|
6972
7317
|
const manager = TunnelManager.getInstance();
|
|
6973
7318
|
const ipcServer = new IPCServer();
|
|
6974
7319
|
const sessionTracker = new SessionTracker();
|
|
@@ -6991,6 +7336,10 @@ async function runDaemonChild(opts = {}) {
|
|
|
6991
7336
|
removeDaemonInfo();
|
|
6992
7337
|
} catch {
|
|
6993
7338
|
}
|
|
7339
|
+
try {
|
|
7340
|
+
releaseDaemonLock();
|
|
7341
|
+
} catch {
|
|
7342
|
+
}
|
|
6994
7343
|
try {
|
|
6995
7344
|
clearDaemonState();
|
|
6996
7345
|
} catch {
|
|
@@ -7033,20 +7382,17 @@ async function runDaemonChild(opts = {}) {
|
|
|
7033
7382
|
try {
|
|
7034
7383
|
const port = await ipcServer.listen();
|
|
7035
7384
|
deviceAgentHost = new DeviceAgentHost(machineDeviceAgentHostDependencies(port, {
|
|
7036
|
-
recordRunning:
|
|
7037
|
-
recordStopped:
|
|
7385
|
+
recordRunning: saveDeviceAgent,
|
|
7386
|
+
recordStopped: forgetDeviceAgent
|
|
7038
7387
|
}));
|
|
7039
7388
|
ipcServer.setDeviceAgentHost(deviceAgentHost);
|
|
7040
|
-
const crashedDeviceAgent = loadDaemonState()?.deviceAgent;
|
|
7041
|
-
if (crashedDeviceAgent) {
|
|
7042
|
-
daemonState.deviceAgent = crashedDeviceAgent;
|
|
7043
|
-
}
|
|
7044
7389
|
const info = {
|
|
7045
7390
|
pid: process.pid,
|
|
7046
7391
|
port,
|
|
7047
7392
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7048
7393
|
host: daemonHost,
|
|
7049
|
-
ipcVersion: IPC_VERSION
|
|
7394
|
+
ipcVersion: IPC_VERSION,
|
|
7395
|
+
cliVersion: getVersion()
|
|
7050
7396
|
};
|
|
7051
7397
|
writeDaemonInfo(info);
|
|
7052
7398
|
logger.info("Daemon info written", info);
|
|
@@ -7064,8 +7410,9 @@ async function runDaemonChild(opts = {}) {
|
|
|
7064
7410
|
} else {
|
|
7065
7411
|
logger.info("No auto-start tunnels configured");
|
|
7066
7412
|
}
|
|
7067
|
-
|
|
7068
|
-
|
|
7413
|
+
const savedAgent = savedDeviceAgent();
|
|
7414
|
+
if (savedAgent) {
|
|
7415
|
+
await startSavedDeviceAgent(deviceAgentHost, savedAgent);
|
|
7069
7416
|
}
|
|
7070
7417
|
logger.info("Daemon ready", { pid: process.pid, port });
|
|
7071
7418
|
return {
|
|
@@ -7076,6 +7423,7 @@ async function runDaemonChild(opts = {}) {
|
|
|
7076
7423
|
} catch (err) {
|
|
7077
7424
|
logger.error("Daemon failed to start", { error: errorMessage(err) });
|
|
7078
7425
|
removeDaemonInfo();
|
|
7426
|
+
releaseDaemonLock();
|
|
7079
7427
|
if (exitOnFailure) {
|
|
7080
7428
|
process.exit(1);
|
|
7081
7429
|
}
|
|
@@ -7090,10 +7438,21 @@ async function main() {
|
|
|
7090
7438
|
const { values, positionals, hasAnyArgs } = parseCliArgs(cliOptions);
|
|
7091
7439
|
configureLogger(values);
|
|
7092
7440
|
if (values["_daemon-child"]) {
|
|
7093
|
-
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-
|
|
7441
|
+
const { runDaemonChild: runDaemonChild2 } = await import("./daemonChild-Q6WGYKYX.js");
|
|
7094
7442
|
await runDaemonChild2();
|
|
7095
7443
|
return;
|
|
7096
7444
|
}
|
|
7445
|
+
if (values["_ipc-version"]) {
|
|
7446
|
+
printer_default.print(String(IPC_VERSION));
|
|
7447
|
+
return;
|
|
7448
|
+
}
|
|
7449
|
+
if (values["_update-child"]) {
|
|
7450
|
+
const { runUpdateChild } = await import("./updateChild-Z3SIRYO5.js");
|
|
7451
|
+
await runUpdateChild();
|
|
7452
|
+
process.exit(0);
|
|
7453
|
+
}
|
|
7454
|
+
if (isPackagedBinary() && platform2() === "win32") removeStaleUpdateFiles();
|
|
7455
|
+
startBackgroundUpdate({ rawArgs, values, hasAnyArgs });
|
|
7097
7456
|
if (isSubcommand(rawArgs)) {
|
|
7098
7457
|
await handleSubcommand(rawArgs);
|
|
7099
7458
|
return;
|
|
@@ -7129,8 +7488,6 @@ export {
|
|
|
7129
7488
|
removeDaemonInfo,
|
|
7130
7489
|
trackTunnelStart,
|
|
7131
7490
|
trackTunnelStop,
|
|
7132
|
-
trackDeviceAgentStart,
|
|
7133
|
-
trackDeviceAgentStop,
|
|
7134
7491
|
trackIPCTunnelStart,
|
|
7135
7492
|
runDaemonChild
|
|
7136
7493
|
};
|