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
package/ARCHITECTURE.md
CHANGED
|
@@ -12,11 +12,12 @@ The `pinggy` binary has three execution modes, dispatched in `src/main.ts`:
|
|
|
12
12
|
| -------------------- | -------------------------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
|
|
13
13
|
| Daemon child | `--_daemon-child` flag | `runDaemonChild()` in `src/daemon/daemonChild.ts` | Long-running background process. Owns the `TunnelManager` and the SDK. |
|
|
14
14
|
| Subcommand | First arg in `SUBCOMMANDS` set | `handleSubcommand()` in `src/cli/subcommands.ts` | Short-lived CLI invocation:`config`, `start`, `stop`, `ps`, `attach`, `daemon`, `logs`, `log`, `restart`, `device`, and `devices`, which prints the new spelling. |
|
|
15
|
+
| Update child | `--_update-child` flag | `runUpdateChild()` in `src/update/updateChild.ts` | Short-lived detached process. Checks for a release, downloads it, swaps it in. See section 20. |
|
|
15
16
|
| Legacy single-tunnel | No subcommand, has flags | `buildAndStartTunnel()` in `src/cli/buildAndStartTunnel.ts` | Backwards-compatible single-shot tunnel for flags like `-l 3000` or `-R0:...`. |
|
|
16
17
|
|
|
17
18
|
The CLI never opens an SDK tunnel itself. Every tunnel is created inside the daemon. CLI processes talk to the daemon over HTTP + WebSocket on `127.0.0.1`.
|
|
18
19
|
|
|
19
|
-
`pinggy device` is the exception. By default the daemon runs the device agent
|
|
20
|
+
`pinggy device` is the exception. By default the daemon runs the device agent, so it outlives the terminal. With `--foreground` it runs inside the CLI process and talks to the dashboard directly. It reads the daemon's tunnel list, and it stops, restarts and starts tunnels when the dashboard asks. See section 17.
|
|
20
21
|
|
|
21
22
|

|
|
22
23
|
|
|
@@ -39,13 +40,18 @@ Logs live under `getPinggyLogDir()`:
|
|
|
39
40
|
```
|
|
40
41
|
<configDir>/
|
|
41
42
|
├── daemon.json Daemon discovery: {pid, port, startedAt}
|
|
42
|
-
├── daemon
|
|
43
|
+
├── daemon.lock Held by the running daemon: {pid, started_at}
|
|
44
|
+
├── daemon-config.json Persisted settings: log level, and the background device agent to start
|
|
45
|
+
├── daemon-state.json Active tunnels, for crash recovery
|
|
43
46
|
├── device.json Device agent identity + token, mode 0600
|
|
47
|
+
├── update.json What the update checks found and which lines printed
|
|
48
|
+
├── update.lock Held by the 1 process replacing the binary: {pid, startedAt}
|
|
44
49
|
└── tunnels/
|
|
45
50
|
└── <name>_<configId>.json Saved tunnel configs (from `pinggy config save`)
|
|
46
51
|
|
|
47
52
|
<logDir>/
|
|
48
53
|
├── daemon.log Daemon process log (rolled)
|
|
54
|
+
├── update.log The last background update, overwritten each run
|
|
49
55
|
└── tunnels/
|
|
50
56
|
└── <origin>__<name>__<tunnelId>.log Per-tunnel logs (rolled 10MB×3)
|
|
51
57
|
```
|
|
@@ -54,7 +60,7 @@ Helpers live in `src/utils/configDir.ts`: `getDaemonInfoPath`, `getDaemonLogPath
|
|
|
54
60
|
|
|
55
61
|
## 3. Daemon discovery and spawn
|
|
56
62
|
|
|
57
|
-
Every CLI invocation that touches a tunnel asks one question first: is there a live daemon to talk to? `getDaemonInfo()` answers it by reading `daemon.json` and validating the recorded PID with `process.kill(pid, 0)`. Signal 0 never delivers anything; it just throws when the target process is gone, which is exactly the liveness probe we need. A missing file, malformed JSON,
|
|
63
|
+
Every CLI invocation that touches a tunnel asks one question first: is there a live daemon to talk to? `getDaemonInfo()` answers it by reading `daemon.json` and validating the recorded PID with `process.kill(pid, 0)`. Signal 0 never delivers anything; it just throws when the target process is gone, which is exactly the liveness probe we need. A missing file, malformed JSON, a dead PID, or a `startedAt` before the last boot all collapse to the same result: return `null`. After a reboot, another process can have the old daemon's PID, so the boot check runs first. Only commands that start a tunnel (`pinggy start`, legacy `pinggy -l 3000`) then call `ensureDaemonRunning()` to spawn a fresh child. `ps`, `stop`, `restart`, `attach`, `logs` and `log` call `TunnelClient.connectIfRunning()` instead, which never spawns: a new daemon would start every auto-start tunnel. With no daemon, `ps` prints "No active tunnels. The daemon is not running.", `stop` prints "Nothing to stop.", and `restart` and `attach` name the `pinggy start` command when a saved config matches. `logs` and `log path` read the log files directly (`src/daemon/logPaths.ts`), and `log level` reads or writes `daemon-config.json`, which the next daemon starts with.
|
|
58
64
|
|
|
59
65
|
The spawn path is deliberately one-way. The CLI fires off a detached child with the `--_daemon-child` flag and then polls `daemon.json` until the child writes it. The poll budget is 8 seconds at 200ms intervals; a timeout almost always means the SDK failed to load inside the child, in which case the stderr captured from the spawned process is surfaced in the thrown error. Atomic writes of `daemon.json` (write to `.tmp`, then `fs.renameSync`) keep concurrent readers from ever seeing a half-written file.
|
|
60
66
|
|
|
@@ -92,7 +98,9 @@ The spawn path is deliberately one-way. The CLI fires off a detached child with
|
|
|
92
98
|
|
|
93
99
|
Implementation: `src/daemon/daemonManager.ts`.
|
|
94
100
|
|
|
95
|
-
The
|
|
101
|
+
The `daemon.json` check only stops the CLI from spawning a child. 2 CLIs started at the same moment can both find no `daemon.json` and both spawn one, and systemd and launchd run `--_daemon-child` with no check at all. So the daemon itself takes `daemon.lock` (`src/daemon/lifecycle/daemonLock.ts`) before it opens its IPC port. The file is created with the `wx` flag, so only 1 process creates it. A daemon that finds a live holder exits 0, or throws when the app hosts it in-process. Exit code 0 keeps systemd's `Restart=on-failure` from starting it again. The spawning CLI keeps polling after a child exits 0, and gets the winner's `daemon.json`. A lock is stale when its PID is dead (`process.kill(pid, 0)` throws `ESRCH`), when its `started_at` is before the last boot (the PID may name another process now), or when it is unreadable and older than 10s (a crash between create and write). The next daemon deletes a stale lock and creates its own. 2 daemons that find the same stale lock at the same moment can both take it. `EPERM` counts as alive: the service task runs without admin rights, and gets `EPERM` for a daemon started from an Administrator shell. Treating that as dead started a 2nd daemon on Windows. The daemon deletes `daemon.lock` and `daemon.json` on exit only when they hold its own PID.
|
|
102
|
+
|
|
103
|
+
The CLI keeps its `daemon.json` check. It reads the port from that file anyway, and it skips a process start when a daemon already runs.
|
|
96
104
|
|
|
97
105
|
## 4. Daemon child startup sequence
|
|
98
106
|
|
|
@@ -103,6 +111,7 @@ The race between two CLIs invoked at the same moment is bounded but not eliminat
|
|
|
103
111
|
```
|
|
104
112
|
1. ensurePinggyConfigDir(), ensurePinggyLogDir()
|
|
105
113
|
2. Configure winston logger → file: daemon.log, stdout: false
|
|
114
|
+
2a. acquireDaemonLock(): another live daemon holds daemon.lock → exit 0
|
|
106
115
|
3. Create TunnelManager singleton
|
|
107
116
|
4. Create IPCServer (HTTP + WS, port not yet bound)
|
|
108
117
|
5. Create SessionTracker, wire onSessionDisconnect
|
|
@@ -111,6 +120,7 @@ The race between two CLIs invoked at the same moment is bounded but not eliminat
|
|
|
111
120
|
8. Write daemon.json atomically (write to .tmp, rename)
|
|
112
121
|
9. restoreCrashedTunnels() — replay detached tunnels from daemon-state.json
|
|
113
122
|
10. Start auto-start tunnels (getAutoStartConfigs())
|
|
123
|
+
10a. startSavedDeviceAgent(): the background device agent saved in daemon-config.json
|
|
114
124
|
11. Log "Daemon ready"
|
|
115
125
|
|
|
116
126
|
|
|
@@ -143,7 +153,7 @@ Server: `src/daemon/ipcServer.ts`. Client: `src/daemon/ipcClient.ts`. Public fac
|
|
|
143
153
|
| GET | `/logs/paths` | All tunnel log file paths + running flags |
|
|
144
154
|
| GET | `/logs/resolve?q=` | Resolve a name/id/configId to a log path |
|
|
145
155
|
| POST | `/shutdown` | Graceful shutdown |
|
|
146
|
-
| GET | `/device` | The background device agent's status
|
|
156
|
+
| GET | `/device` | The background device agent's status |
|
|
147
157
|
| POST | `/device/start` | Start the device agent on `device.json` |
|
|
148
158
|
| POST | `/device/stop` | Stop the device agent |
|
|
149
159
|
|
|
@@ -257,18 +267,19 @@ Key invariants:
|
|
|
257
267
|
```ts
|
|
258
268
|
interface DaemonState {
|
|
259
269
|
tunnels: DaemonStateTunnel[]; // {tunnelId, configId, name, origin, config, mode, startedAt}
|
|
260
|
-
deviceAgent?: { startedAt: string; startedBy: TunnelOrigin }; // slice 17, absent when none runs
|
|
261
270
|
lastUpdated: string;
|
|
262
271
|
}
|
|
263
272
|
```
|
|
264
273
|
|
|
265
274
|
Two lifecycle paths:
|
|
266
275
|
|
|
267
|
-
- **Clean shutdown** (`/shutdown` or signal): `clearDaemonState()` deletes the file. Next daemon start sees nothing to recover.
|
|
268
|
-
- **Crash** (SIGKILL, OOM, panic): the file remains. Next daemon start calls `restoreCrashedTunnels()`, which restarts each `mode === "detached"` tunnel using the persisted config and stable `tunnelId` (so log files stay continuous). Foreground tunnels are not restored: there is no CLI to attach.
|
|
276
|
+
- **Clean shutdown** (`/shutdown` or signal): `clearDaemonState()` deletes the file. Next daemon start sees nothing to recover.
|
|
277
|
+
- **Crash** (SIGKILL, OOM, panic): the file remains. Next daemon start calls `restoreCrashedTunnels()`, which restarts each `mode === "detached"` tunnel using the persisted config and stable `tunnelId` (so log files stay continuous). Foreground tunnels are not restored: there is no CLI to attach.
|
|
269
278
|
|
|
270
279
|
Auto-start tunnels are independent of crash recovery. They come from saved configs marked `autoStart: true` (`getAutoStartConfigs()`), not from the state file.
|
|
271
280
|
|
|
281
|
+
The background device agent is not in this file either. `deviceAgent` (`{startedAt, startedBy}`) in `daemon-config.json` survives a clean shutdown, so every daemon start runs the agent: after a crash, a `pinggy daemon stop`, or a reboot with `pinggy daemon service-install`. See section 17.
|
|
282
|
+
|
|
272
283
|
## 9. Tunnel lifecycle end-to-end
|
|
273
284
|
|
|
274
285
|
Foreground start (`pinggy start <name>`):
|
|
@@ -346,7 +357,7 @@ src/
|
|
|
346
357
|
│ ├── buildAndStartTunnel.ts Legacy single-tunnel path
|
|
347
358
|
│ ├── buildConfig.ts CLI flags + positionals → FinalConfig
|
|
348
359
|
│ ├── configStore.ts Persisted saved-config CRUD
|
|
349
|
-
│ ├── daemonCommands.ts `pinggy daemon start|stop|status|install
|
|
360
|
+
│ ├── daemonCommands.ts `pinggy daemon start|stop|status|service-install|...`
|
|
350
361
|
│ ├── attachCommand.ts `pinggy attach`
|
|
351
362
|
│ ├── psCommand.ts `pinggy ps`
|
|
352
363
|
│ ├── stopCommand.ts `pinggy stop`
|
|
@@ -374,8 +385,8 @@ src/
|
|
|
374
385
|
│ ├── envelope.ts Versioned frame wrapper + channel/op constants
|
|
375
386
|
│ ├── device_schema.ts Zod schemas for welcome, error, disconnect payloads
|
|
376
387
|
│ ├── tunnels/tunnelList.ts device/tunnels: daemon poll, whitelist, change detection
|
|
377
|
-
│ ├── tunnels/tunnelActions.ts tunnel/start, stop, restart
|
|
378
|
-
│ └── login/ `pinggy device login
|
|
388
|
+
│ ├── tunnels/tunnelActions.ts tunnel/start, stop, restart, update against the daemon
|
|
389
|
+
│ └── login/ `pinggy device login`: email sign-in over HTTPS, then the agent
|
|
379
390
|
│
|
|
380
391
|
├── remote_management/ Remote control via Pinggy management WS
|
|
381
392
|
│ ├── remoteManagement.ts Connect/disconnect + state machine
|
|
@@ -402,7 +413,7 @@ src/
|
|
|
402
413
|
|
|
403
414
|
## 11. Key types
|
|
404
415
|
|
|
405
|
-
- `TunnelOrigin = "app" | "cli" | "remote" | "device"` (`src/tunnel_manager/TunnelManager.ts`). `device` is the device agent acting for the dashboard's device page
|
|
416
|
+
- `TunnelOrigin = "app" | "cli" | "remote" | "device"` (`src/tunnel_manager/TunnelManager.ts`). `device` is the device agent acting for the dashboard's device page. Set on every tunnel at creation; flows into log filenames.
|
|
406
417
|
- `ClientOrigin = "app" | "cli" | "remote" | "device"` (`src/daemon/ipcClient.ts`). Same values, used in the `X-Pinggy-Origin` header.
|
|
407
418
|
- `TunnelStateType` (`src/types.ts`): `idle | starting | running | live | closed | exited`.
|
|
408
419
|
- `FinalConfig` (`src/types.ts`): the SDK's `TunnelConfigurationV1` plus `conf?` and `saveconf?`. Used by `buildConfig.ts` and threaded through to the daemon.
|
|
@@ -466,35 +477,37 @@ Same code path as user-typed subcommands: the daemon does not know or care that
|
|
|
466
477
|
|
|
467
478
|
## 16. Service installation
|
|
468
479
|
|
|
469
|
-
`pinggy daemon install
|
|
480
|
+
`pinggy daemon service-install` writes a platform-specific service file and enables it. `pinggy daemon service-uninstall` stops the daemon and removes it. Code: `src/daemon/lifecycle/serviceInstaller.ts`.
|
|
470
481
|
|
|
471
|
-
- Linux: systemd user unit at `~/.config/systemd/user/pinggy.service`. `Type=simple`, runs `<binary> --_daemon-child` directly (no fork). `systemctl --user enable
|
|
482
|
+
- Linux: systemd user unit at `~/.config/systemd/user/pinggy.service`. `Type=simple`, runs `<binary> --_daemon-child` directly (no fork). `systemctl --user enable`, then `start`.
|
|
472
483
|
- macOS: launchd `LaunchAgent` at `~/Library/LaunchAgents/io.pinggy.agent.plist`. `launchctl load`.
|
|
473
|
-
- Windows: Task Scheduler
|
|
484
|
+
- Windows: Task Scheduler task `PinggyDaemon`, created with `schtasks /Create` and no admin rights. A logon trigger for the current user runs `<binary> daemon start`. `daemon start` spawns `--_daemon-child` detached with `windowsHide`, then exits. The task does not run `--_daemon-child` directly: `pinggy.exe` is a console program, so Task Scheduler opens a console window for it, and closing that window kills the daemon. The `daemon start` window shows for about 1s. The task ends once the daemon is up, so uninstall stops the daemon over IPC. It deletes the task first, so a failed delete leaves the daemon running. With no task, it stops nothing. A task created from an Administrator terminal keeps admin-only permissions, so a normal terminal cannot replace or delete it. When `schtasks` fails, the task exists, and `whoami /groups` shows no High or System integrity SID, pinggy tells the user to run the command from an Administrator terminal. It checks the SID, not the "Access is denied" text, because `schtasks` prints that text in the Windows language.
|
|
474
485
|
|
|
475
|
-
The
|
|
486
|
+
The service stores the full path of the binary (`process.execPath`). If the user moves or deletes that file, the service fails at login with no message. So `service-install` runs only from the path the install scripts write: `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` on Windows, `~/.pinggy/bin/pinggy` on Linux and macOS (`installerBinaryPath()`). The scripts update the binary in place, so the stored path stays valid. From any other path, and from an npm install, it prints the install script command and exits 1. The message names no paths. `PINGGY_SERVICE_ANY_LOCATION=1` skips the path check, for development and CI. It does not allow npm installs. `service-uninstall` runs from any path. On Linux and macOS, `service-install` starts the service at once, and the service runs `--_daemon-child`. When a daemon already runs, for example after `pinggy device login`, the service's daemon finds `daemon.lock` held and exits 0, so 1 daemon and 1 device agent stay. On Windows the task runs `daemon start`, which finds the running daemon and exits. Changing the install directory in either script means changing `installerBinaryPath()` in the same commit.
|
|
476
487
|
|
|
477
488
|
A system service gives restart-on-failure and start-at-login. The plain daemon mode does not.
|
|
478
489
|
|
|
490
|
+
On macOS and Linux an installed binary sits behind the link `~/.pinggy/bin/pinggy` (section 20), so `serviceProgramPath()` stores the link. A versioned path would pin the service to 1 file that a later prune deletes.
|
|
491
|
+
|
|
479
492
|
## 17. Device agent (`pinggy device`)
|
|
480
493
|
|
|
481
|
-
The one long-lived surface that is not a tunnel. `pinggy device connect` enrols the machine with the Pinggy dashboard and holds 1 WebSocket open so the dashboard can show it as online. By default the daemon runs it (
|
|
494
|
+
The one long-lived surface that is not a tunnel. `pinggy device connect` enrols the machine with the Pinggy dashboard and holds 1 WebSocket open so the dashboard can show it as online. By default the daemon runs it (see Background mode below). With `--foreground` it runs in the CLI process. Code lives in `src/devices/`, entered from `src/cli/subcommand/handlers/deviceCommand.ts`.
|
|
482
495
|
|
|
483
|
-
**Email sign-in
|
|
496
|
+
**Email sign-in.** `pinggy device login` gets the device token without the dashboard: it asks for an email, `POST /backend/api/v1/device-agent/login/start` emails a 6-digit code, and the code prompt races a `poll` every few seconds under 1 `AbortController`. A right code (and the TOTP, with MFA on) answers the token once. The email also carries an Approve link: the CLI prints the `match_code` its page shows as `Device Code: <code>`, then `We have sent a 6-digit code to <email>.` and `Enter the code below or click the approve button in the email.` A poll collects a link's approval, and a typed code answered `pending` stops the prompt so the poll can. The CLI writes `device.json`, prints the device's browser link and its QR code (`createQrCodes`, shared with the TUI): a one-time sign-in link after a typed code, the plain device page after the emailed link. Then it runs the same agent. Code in `src/devices/login/`: `deviceLogin.ts` (the command; every dependency injected, so `src/_tests_/deviceLogin.test.ts` runs it with no dashboard or terminal), `loginApi.ts` (`fetch`, `buildDashboardHttpUrl`, the public client token), `login_schema.ts` (zod), `prompts.ts` (`readline/promises`, 1 interface per question, closed on answer or abort; every question starts with a cyan `→`, and the sign-in result with a green one, through `picocolors`; `askHidden` reads the authenticator code without showing it, since the code still works after it is typed and the open link asks for one). A stdin that is not a TTY stops at once and points at `connect --token`. The token is never printed.
|
|
484
497
|
|
|
485
|
-
**Install scripts
|
|
498
|
+
**Install scripts.** `scripts/install/install.sh` (macOS, Linux, POSIX `sh`) and `scripts/install/install.ps1` (Windows PowerShell 5.1 and 7) install or update the binary, put `pinggy` on PATH with no sudo, then ask "Connect this device to Pinggy? [Y/n]". Enter or `y` runs `pinggy device login -b` by full path. `-b` is the default, and the scripts pass it so an older binary the user kept also runs the agent in its daemon. An answer starting with `n` prints the login command and exits 0, so the CLI is installed with no device. With no terminal, the scripts ask nothing and print the command. `install.sh` writes `~/.pinggy/bin/pinggy` and links `~/.local/bin/pinggy` to it, adding 1 marked block to the shell's rc file when `~/.local/bin` is not on PATH. `install.ps1` writes `%LOCALAPPDATA%\Pinggy\bin\pinggy.exe` and adds that directory to the user PATH. Both read 3 things this repo owns: the release asset names, the `Pinggy CLI version: <x.y.z>` line, and the `--manage` and `-b` flags of `device login` and `connect`. A change to any of them changes both scripts in the same commit. `.github/workflows/website-cli-download-links-pr.yml` copies both, read at the release tag, to the website's `static/`, so pinggy.io serves `/install.sh` and `/install.ps1`. After `device login` or `connect` exits 0, both scripts ask "Start pinggy automatically when this computer starts? [Y/n]" and run `pinggy daemon service-install`. The question says "starts" for users. The service actually starts pinggy after the user signs in, not at boot. They skip the question when the service exists and runs the installed binary: `install.sh` looks for that binary's path in the launchd plist or the systemd unit file, `install.ps1` compares the command of the `PinggyDaemon` task (`Get-ScheduledTask`) with it. A service that runs any other binary gets the question, and `service-install` replaces it. `install.sh` also skips it on Linux with no systemd user manager. With no terminal, they print the `service-install` command. They remove `DEVICE_AGENT_TOKEN` before the question. Renaming the task, the plist or the unit file changes both scripts in the same commit. Lint with `shellcheck -s sh` and `PSScriptAnalyzer`.
|
|
486
499
|
|
|
487
|
-
**The token command
|
|
500
|
+
**The token command.** The dashboard shows `curl -fsSL https://pinggy.io/install.sh | DEVICE_AGENT_TOKEN=<token> sh`, and `$env:DEVICE_AGENT_TOKEN='<token>'; irm https://pinggy.io/install.ps1 | iex` on Windows. With the variable set, both scripts update an older binary without asking, then run `pinggy device connect -b` by full path, with `--manage` when `PINGGY_MANAGE` is set. The token reaches the CLI in its environment, never on a command line, where `ps` would show it. `install.sh` gives `connect` `/dev/null` as stdin, since it reads no key. `install.ps1` removes the variable in a `finally`, because `iex` runs in the user's own window. `handleDevice()` reads `DEVICE_AGENT_TOKEN` and deletes it from `process.env` before any verb runs, so no shell, daemon or other child inherits it (`takeEnvironmentToken()` in `deviceCommand.ts`). `connect` then picks the token from `--token`, else the variable, else `device.json`, and the server from `--manage`, else `dashboard.pinggy.io` for a token from the variable, else the server in `device.json` (`resolveConnectTarget()`). An empty variable counts as unset.
|
|
488
501
|
|
|
489
|
-
The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli.md` is the CLI contract
|
|
502
|
+
The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli.md` is the CLI contract. The wire format is `src/devices/envelope.ts` and the zod schemas under `src/devices/`. This section records what the CLI implements today.
|
|
490
503
|
|
|
491
|
-
**With `--foreground` it runs in the CLI process.** The agent owns no tunnel.
|
|
504
|
+
**With `--foreground` it runs in the CLI process.** The agent owns no tunnel. It reads the daemon: `getDaemonInfo()` for `daemon.json`, then `IPCClient.listTunnels()` for `GET /tunnels`, every 5 s, and `listSavedConfigs()` for the saved configs. Listing never starts a daemon, and it refuses a daemon whose `ipcVersion` differs, as `ensureDaemonRunning()` does. It also acts on the daemon when the dashboard asks (see Device tunnel actions below); only a start of a config may call `ensureDaemonRunning()`. `TunnelManager` and `TunnelClient` stay off this path. Killing the agent leaves running tunnels alone.
|
|
492
505
|
|
|
493
|
-
**It does not reuse `src/remote_management/`.** Remote management is a dashboard-driven tunnel controller keyed by an API key. A device is the machine itself, keyed by its own token, and the 2 sockets speak different protocols. The duplication is deliberate: the backend `
|
|
506
|
+
**It does not reuse `src/remote_management/`.** Remote management is a dashboard-driven tunnel controller keyed by an API key. A device is the machine itself, keyed by its own token, and the 2 sockets speak different protocols. The duplication is deliberate: the backend's do-not-touch list (`docs/pinggy-devices/must-not-change.txt`) names the remote-management files, and that loop keeps its fixed 5000 ms retry with no cap and no watchdog.
|
|
494
507
|
|
|
495
|
-
### Background mode
|
|
508
|
+
### Background mode
|
|
496
509
|
|
|
497
|
-
`pinggy device connect` and `pinggy device login` hand the agent to the daemon, as `pinggy start -b` hands it a tunnel, and exit once the device connects. This is the default. `--foreground` (`cliOptions.foreground`, hidden) keeps the agent in the CLI process. `-b` (`cliOptions.b`) still parses and changes nothing. `-b` with `--foreground` exits 1 before anything runs. Whoever hosts the daemon hosts the agent: the CLI's detached child, `pinggy daemon install
|
|
510
|
+
`pinggy device connect` and `pinggy device login` hand the agent to the daemon, as `pinggy start -b` hands it a tunnel, and exit once the device connects. This is the default. `--foreground` (`cliOptions.foreground`, hidden) keeps the agent in the CLI process. `-b` (`cliOptions.b`) still parses and changes nothing. `-b` with `--foreground` exits 1 before anything runs. Whoever hosts the daemon hosts the agent: the CLI's detached child, `pinggy daemon service-install`, or the Pinggy app, whose in-process daemon runs the same `runDaemonChild()`. The app reaches it through `TunnelClient.getDeviceAgentStatus()`, `startDeviceAgent()` and `stopDeviceAgent()`.
|
|
498
511
|
|
|
499
512
|
**The token never goes over IPC.** `device.json` is the hand-off: the CLI writes it, the daemon reads it. The 3 `/device` routes (section 5) read no request field. A target that differs from `device.json` (another token, or another server) is checked first in the CLI with `startDeviceAgent(..., { verifyOnly: true })`: 1 attempt, ended at `welcome`, which writes `device.json` as the foreground agent does. A token the dashboard refuses never reaches the file or the daemon.
|
|
500
513
|
|
|
@@ -509,7 +522,11 @@ The design lives in the `pinggy_backend` repo under `docs/pinggy-devices/`: `cli
|
|
|
509
522
|
|
|
510
523
|
`login` signs in as the foreground does, then runs steps 3 to 6 in place of `runAgent`. After a new sign-in, `runAgent` gets `signInShown`, and step 6 leaves out the email and the device link, which the sign-in already printed. `device stop` calls `POST /device/stop`. `device status` adds a `Background` line from `GET /device`. `device remove` stops a running background agent before it deletes `device.json`. A `--foreground` `connect` or `login` refuses while `GET /device` reports a run: 2 agents on 1 credential refuse each other with `already_connected`.
|
|
511
524
|
|
|
512
|
-
|
|
525
|
+
**The foreground record** (`src/devices/foregroundAgent.ts`). The daemon cannot see an agent started with `--foreground`, so `runDeviceAgent()` writes `device-agent.json` (`{pid, started_at}`) beside `device.json` while it runs, and deletes it on exit if it still names its own PID. The agent checks once a second that the file exists. `device remove` (`src/devices/removeDevice.ts`) first prints the device id, the background agent's state and the foreground record's PID, and asks "Remove this device from this machine? [y/N]". Only `y` or `yes` goes on. `-f`, the existing `cliOptions.force`, skips the question. With no TTY and no `-f`, it exits 1 and changes nothing. Then it deletes the file, waits up to 10 s for the PID to exit, and deletes `device.json`. An agent still running after that fails the remove with exit 1 and leaves `device.json` in place. No signal goes to the PID: a record left by a crash can name an unrelated process. `readForegroundAgent()` deletes a record whose PID is dead or whose `started_at` is before the last boot. `connect` and `login` refuse while a live record names another process, both in the default background start and with `--foreground`. The background start writes no record: the daemon's `GET /device` already reports it. `device status` adds a `Foreground` line.
|
|
526
|
+
|
|
527
|
+
**`DeviceAgentHost`** (`src/daemon/deviceAgentHost.ts`) holds at most 1 run, built in `runDaemonChild()` once the IPC port is known. `start(origin)` reads `device.json`: none answers `DEVICE_NOT_ENROLLED`, a run on the same token and server is left alone, and a run on another is stopped before the new one starts. Start and stop run 1 at a time through 1 promise chain. A run that ends on its own (401, revoked, deleted, replaced) keeps why in `lastError`. The host saves the run in `daemon-config.json` through `saveDeviceAgent()`, and forgets it through `forgetDeviceAgent()` on a terminal outcome. A stop keeps it saved: `device stop` ends the current run only. `close()` on shutdown records nothing, so the run stays saved.
|
|
528
|
+
|
|
529
|
+
**Start with the daemon.** After the auto-start tunnels, `startSavedDeviceAgent()` in `runDaemonChild()` starts the saved agent with its `startedBy`. This runs on every daemon start, the way auto-start tunnels do, so the Pinggy app's in-process daemon starts it too. It skips the start while `device-agent.json` names a live foreground agent: 2 agents on 1 credential refuse each other with `already_connected`. The record stays for the next start. With no `device.json`, the start fails with `DEVICE_NOT_ENROLLED` and the record is deleted. Only `pinggy device remove` deletes the record from the CLI, before it deletes `device.json`. `pinggy device status` prints `Autostart on` while the record exists. A `--foreground` agent never writes it.
|
|
513
530
|
|
|
514
531
|
The daemon's run differs from the foreground one in 3 dependencies, passed through `DeviceAgentOptions`:
|
|
515
532
|
|
|
@@ -520,12 +537,14 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
|
|
|
520
537
|
| Event | The background agent |
|
|
521
538
|
| --- | --- |
|
|
522
539
|
| The CLI that ran `connect` exits, or its terminal closes | Keeps running. The daemon is detached |
|
|
523
|
-
| Daemon crash |
|
|
524
|
-
| `pinggy daemon stop`, or the Pinggy app quits | Stops. The socket closes with 1000 and every shell ends |
|
|
525
|
-
| Reboot |
|
|
526
|
-
|
|
|
540
|
+
| Daemon crash | Starts again with the next daemon |
|
|
541
|
+
| `pinggy daemon stop`, or the Pinggy app quits | Stops. The socket closes with 1000 and every shell ends. Starts again with the next daemon |
|
|
542
|
+
| Reboot | Starts again when the daemon starts, at sign-in with `pinggy daemon service-install` |
|
|
543
|
+
| `pinggy device stop` | Stops. Starts again with the next daemon |
|
|
544
|
+
| `pinggy device remove` | Stops, and the daemon never starts it again |
|
|
545
|
+
| A terminal outcome | Stops, with `lastError`, and stays stopped until the next `connect` or `login` |
|
|
527
546
|
|
|
528
|
-
**Inside the Pinggy app** `node-pty` resolves inside `app.asar`, where `spawn-helper` is not on real disk, and a spawn without its helper kills the process. `resolveNodePtyRoot()` copies the package out of an `.asar` archive the way it does out of a `pkg` snapshot, and `loadNodePty()` offers a terminal only when `hasExecutableSpawnHelper()` holds.
|
|
547
|
+
**Inside the Pinggy app** `node-pty` resolves inside `app.asar`, where `spawn-helper` is not on real disk, and on macOS a spawn without its helper kills the process. `resolveNodePtyRoot()` copies the package out of an `.asar` archive the way it does out of a `pkg` snapshot, and `loadNodePty()` offers a terminal only when `hasExecutableSpawnHelper()` holds.
|
|
529
548
|
|
|
530
549
|
`IPC_VERSION` stays 1: the routes are additive, and a bump would make every installed app refuse a newer CLI daemon.
|
|
531
550
|
|
|
@@ -551,8 +570,8 @@ The daemon's run differs from the foreground one in 3 dependencies, passed throu
|
|
|
551
570
|
| `src/devices/terminal/frameSplitter.ts` | `FrameSplitter`: bundles pty output into `data` frames at the raw cap derived from `max_frame_bytes`, or after `BUNDLE_MILLIS` |
|
|
552
571
|
| `src/devices/terminal/shellContext.ts` | Each shell's `cwd` and foreground program from the process table: `/proc` on Linux, `ps` and `lsof` on macOS, nothing on Windows. `programName()` keeps the first word, basename only, because a process can write its arguments into its own name. `ShellContextTracker` turns polls into `context` events, only on change |
|
|
553
572
|
| `src/devices/terminal/terminalRegistry.ts` | `TerminalRegistry`: terminal id to pty handle, with the per-device ceiling from `welcome` |
|
|
554
|
-
| `src/devices/terminal/ptySession.ts` | Lazy `node-pty` load, `isTerminalSupported()` (false unless `spawn-helper` can be exec'd), `spawnPty()`, the `spawn-helper` execute-bit repair, `signalForeground()` to the tty's foreground process group |
|
|
555
|
-
| `src/devices/terminal/nodePtyRuntime.ts` | `resolveNodePtyRoot()`: where `node-pty` loads from. Unpacks it onto real disk inside a `pkg` binary or an Electron `.asar` archive. `hasExecutableSpawnHelper()
|
|
573
|
+
| `src/devices/terminal/ptySession.ts` | Lazy `node-pty` load, `isTerminalSupported()` (false unless the addon loads and, on macOS, `spawn-helper` can be exec'd), `spawnPty()`, the `spawn-helper` execute-bit repair, `signalForeground()` to the tty's foreground process group |
|
|
574
|
+
| `src/devices/terminal/nodePtyRuntime.ts` | `resolveNodePtyRoot()`: where `node-pty` loads from. Unpacks it onto real disk inside a `pkg` binary or an Electron `.asar` archive, and replaces a copy with no addon. `hasExecutableSpawnHelper()`, true off macOS |
|
|
556
575
|
| `src/devices/terminal/shellAllowlist.ts` | `resolveShell()`: exact match against `/etc/shells`, or `powershell.exe` and `cmd.exe` on Windows |
|
|
557
576
|
| `src/cli/subcommand/handlers/deviceCommand.ts` | The `login`, `connect`, `stop`, `status`, `remove` verbs, and `--foreground`. `refuseDevicesSpelling()` for the old spelling |
|
|
558
577
|
| `src/utils/helpMessages.ts` | `printDeviceHelp()` |
|
|
@@ -621,7 +640,7 @@ No daemon, or a dead pid in `daemon.json`, sends `daemon_running: false` with th
|
|
|
621
640
|
|
|
622
641
|
### Device tunnel actions
|
|
623
642
|
|
|
624
|
-
`ch: "tunnel"` frames go to `handleTunnelAction()
|
|
643
|
+
`ch: "tunnel"` frames go to `handleTunnelAction()`. The dashboard sends 4 requests, and the agent answers each on its `id` and op with `{tunnel_id, state}`, `{config_id}` for a rewritten saved config, or an error. The agent advertises `tunnel_control` in `hello` for start, stop and restart, `tunnel_update` for update, and `saved_config_update` for an update of a saved config; a dashboard refuses an op to an agent without its capability.
|
|
625
644
|
|
|
626
645
|
| Request | Daemon route | Starts a daemon |
|
|
627
646
|
| --- | --- | --- |
|
|
@@ -642,7 +661,7 @@ Every call goes through an `IPCClient` with origin `device`. With no daemon, a s
|
|
|
642
661
|
|
|
643
662
|
The dashboard answers an unreadable payload with `invalid_payload` on the `device` channel. The agent ignores every non-`system` frame, so that answer is logged at debug and changes nothing.
|
|
644
663
|
|
|
645
|
-
### Terminal (
|
|
664
|
+
### Terminal (open, close, shells that outlive the socket, output, input, screen)
|
|
646
665
|
|
|
647
666
|
`ch: "terminal"` frames go to the run's `TerminalHandler`, never to `handleFrame()`. Output flows up as `data`, and keystrokes flow down as `data`.
|
|
648
667
|
|
|
@@ -668,51 +687,55 @@ The dashboard answers an unreadable payload with `invalid_payload` on the `devic
|
|
|
668
687
|
│ terminal/close event {terminal_id, user_closed} │
|
|
669
688
|
│◀───────────────────────────────────────────────────────┤ only when the shell exits on its own
|
|
670
689
|
│ terminal/snapshot event {terminal_id, snapshot_id} │
|
|
671
|
-
├───────────────────────────────────────────────────────▶│ a tab attached and asks for its screen
|
|
690
|
+
├───────────────────────────────────────────────────────▶│ a tab attached and asks for its screen
|
|
672
691
|
│ terminal/snapshot event {part, last, after_seq, data} │
|
|
673
692
|
│◀───────────────────────────────────────────────────────┤ the screen, to that tab only
|
|
674
693
|
│ terminal/resync event {resync_id, part, after_seq, data}
|
|
675
|
-
│◀───────────────────────────────────────────────────────┤ the latest screen after a skip, to every tab
|
|
694
|
+
│◀───────────────────────────────────────────────────────┤ the latest screen after a skip, to every tab
|
|
676
695
|
│ terminal/activity event {terminal_id, skipped_bytes} │
|
|
677
|
-
│◀───────────────────────────────────────────────────────┤ still busy while skipping, not forwarded
|
|
696
|
+
│◀───────────────────────────────────────────────────────┤ still busy while skipping, not forwarded
|
|
678
697
|
```
|
|
679
698
|
|
|
680
699
|
- **`terminal` is advertised only when `node-pty` loads.** `buildCapabilities(isTerminalSupported())`. The capability is what un-greys the Terminal button, so an agent must never advertise a shell it cannot spawn.
|
|
681
700
|
- **The dashboard validates neither shell nor cwd.** `resolveShell()` is the only check. A requested shell must equal an `/etc/shells` line exactly and exist; no request picks `$SHELL` when it is allowed. A missing cwd falls back to home rather than refusing.
|
|
682
701
|
- **A refusal answers on `opened`** with `{terminal_id, error: {code, message}}`: `invalid_payload`, `terminal_disabled`, `terminal_limit_reached`, `shell_not_allowed`, or `spawn_failed`.
|
|
683
|
-
- **A shell outlives the socket that opened it
|
|
702
|
+
- **A shell outlives the socket that opened it.** `runDeviceAgent()` builds 1 `TerminalHandler` for the whole run. When `connectOnce()` settles, `suspend()` pauses every pty (stops reading its master, so the shell blocks once the kernel buffer fills) and kills none. In skip mode (below) it pauses none. The next `hello` lists them in `terminals`. The dashboard answers `close` with `device_gone` for any it forgot, possibly before `welcome`, and `welcome` calls `resumeAll()`.
|
|
684
703
|
- **Only the agent stopping kills shells.** When the loop ends (interrupted, revoked, refused), `closeAll()` kills them. Killing the agent process reaps them too, through `SIGHUP` when the pty master closes.
|
|
685
704
|
- **A shell that exits while the socket is down sends nothing.** Its `close` has no socket to go to, and the next `hello` simply omits it. The dashboard records that as `device_gone`.
|
|
686
705
|
- **Output is read as raw bytes and sent as base64.** `spawnPty()` passes `encoding: null`, so a read that ends mid-character is not decoded into a replacement character. `FrameSplitter` sends a bundle at the raw cap from `rawBundleBytes(max_frame_bytes)` or after `BUNDLE_MILLIS`, whichever comes first. A frame above `max_frame_bytes` would close the socket, and every other terminal on it.
|
|
687
|
-
- **
|
|
706
|
+
- **Without skip mode, a full window stops the reads, not the sends.** `FlowWindow` counts raw bytes sent minus the browser's cumulative `ack_bytes`, clamped to what was sent. When it reaches the window, the handler pauses the pty and the shell blocks in the kernel. The next `ack` that reopens it resumes reads. Nothing is buffered on the agent.
|
|
688
707
|
- **Ctrl-C is input, not a signal.** It arrives as `data` byte `0x03`, and the pty's line discipline turns it into SIGINT for the foreground process group.
|
|
689
708
|
- **`signal` goes to the foreground process group**, never the shell's pid. `signalForeground()` reads the tty's `tpgid` with `ps` and calls `process.kill(-tpgid)`, falling back to the shell's own group. `node-pty`'s `kill(signal)` signals the pid only, and bash ignores SIGINT while `sleep` holds the terminal. The allowlist is `TERMINAL_SIGNALS`, enforced by the zod schema, so `KILL` and anything else never reach `kill`. Ignored on Windows.
|
|
690
709
|
- **`resize` touches the pty only on an actual change.** Every call is a `TIOCSWINSZ` and a SIGWINCH, and a full-screen program redraws on each.
|
|
691
|
-
- **
|
|
710
|
+
- **Without skip mode, 2 things pause a pty, and neither lifts the other's.** A suspended handler (socket down) and a full window. `resumeAll()` skips a shell whose window is still full, and an `ack` does not resume a shell while the handler is suspended.
|
|
692
711
|
- **The window has no default.** `welcome.terminal_window_bytes` is the only place the number lives. Without it the handler answers every `open` with `terminal_disabled`.
|
|
693
712
|
- **`seq` counts per terminal from 1**, on every `data` frame, for the life of the shell rather than the socket. The dashboard closes a terminal with `sequence_gap` on a hole.
|
|
694
|
-
- **
|
|
695
|
-
- **The window still assumes 1 viewer.**
|
|
696
|
-
- **Every shell keeps its screen
|
|
713
|
+
- **Without skip mode, a bundle cut while the socket is down is held**, not sent into no socket. It takes no `seq` and does not count against the window until `resumeAll()` sends it first. It is at most what was already read when `suspend()` paused the pty.
|
|
714
|
+
- **The window still assumes 1 viewer.** The slowest-viewer rule (the window moves on the slowest viewer's ack) and the 10 s `too_slow` detach are not built. The replay for a late attach is the screen snapshot, below, not a buffer of bytes.
|
|
715
|
+
- **Every shell keeps its screen.** `ScreenMirror` is a headless xterm (`@xterm/headless`, 1000 lines of scrollback) fed each bundle in `sendData`, in the same tick as its `seq`, never when the pty is read: a bundle still being cut would otherwise be in the screen and drawn twice. `snapshot` notes `after_seq` and `after_bytes`, then serialises inside the callback of an empty write queued on the mirror, which xterm runs before it parses anything fed later. The text goes out in parts of the raw bundle size. Parts take no `seq` and never count against the window. Over 1 MB it is serialised again with 200 lines, then with the screen alone, and past that it is not sent. The serialize addon needs `allowProposedApi`.
|
|
697
716
|
- **`terminal_snapshot` is advertised only beside `terminal`**, and only when both xterm packages load. The mirror is memory only, disposed with its shell, never logged and never written to disk.
|
|
698
|
-
- **Output never waits
|
|
699
|
-
- **After `welcome`, a resync at once** for every stream that skipped or had bytes in flight, since frames in flight died with the old socket. A shell that exits while skipping sends 1 last resync, then `exit` and `close`. A
|
|
717
|
+
- **Output never waits.** With `welcome.terminal_resync` and a mirror, `sendOrSkip` replaces the window brake. A bundle cut while the window is closed, the socket is down, or the stream is already skipping is skipped: fed to the mirror, given no `seq`, not sent, not counted against the window. Once every sent byte is acked, and no sooner than `RESYNC_MIN_INTERVAL_MILLIS` (1 s) after the last, the latest screen goes to every tab as `resync` parts, then live `data`. `after_seq` and `after_bytes` are read before the mirror is asked, as for a snapshot. The screen is serialised under the window size, and a screen alone over it still goes, up to 1 MB. The dashboard treats each part as a `seq` barrier.
|
|
718
|
+
- **After `welcome`, a resync at once** for every stream that skipped or had bytes in flight, since frames in flight died with the old socket. A shell that exits while skipping sends 1 last resync, then `exit` and `close`. A snapshot never ends skip mode: it reaches 1 tab.
|
|
700
719
|
- **A bundle cut while a resync is serialised waits** in `resyncHeldBundles`, unfed, and goes out after the parts. Past the window size the held bundles and every later one are skipped, and another resync follows.
|
|
701
720
|
- **The only pause in skip mode is the mirror's.** `ScreenMirror.feed` counts bytes fed and not yet parsed through xterm's write callback. The pty pauses above `MIRROR_HIGH_WATER_BYTES` (1 MB) and resumes under `MIRROR_LOW_WATER_BYTES` (256 KB). That is local CPU, never the network: a loud shell runs at the parse rate, about 22.5 MB/s measured on 2026-11-03.
|
|
702
721
|
- **A skipping shell sends `activity`** with its `skipped_bytes`, at most every `ACTIVITY_REPORT_MILLIS` (60 s), so the dashboard's sweep does not close it as idle. The agent's own idle timer counts every pty read already.
|
|
703
|
-
- **`terminal_resync` is advertised beside `terminal_snapshot`**, on the same condition. A `welcome` without the flag ends skip mode on every shell with no resync, and the shells go back to
|
|
722
|
+
- **`terminal_resync` is advertised beside `terminal_snapshot`**, on the same condition. A `welcome` without the flag ends skip mode on every shell with no resync, and the shells go back to the window brake.
|
|
704
723
|
- **No log line carries a payload.** Ids, pids, and codes only, and an error's class name rather than its message. Input is what a person typed, so it is never logged at any level.
|
|
705
724
|
- `welcome.terminal_enabled` and `welcome.max_terminals_per_device` are optional, so an older dashboard leaves the defaults (enabled, 3).
|
|
706
725
|
|
|
707
726
|
`node-pty` 1.1.0 publishes its macOS `spawn-helper` without the execute bit, and every spawn then fails with `posix_spawnp failed`. `ensureSpawnHelperExecutable()` restores it once, at load.
|
|
708
727
|
|
|
709
|
-
**A packaged binary loads `node-pty` from real disk, not from the snapshot.** `node-pty` does not exec the shell directly. It execs `spawn-helper`, at a path it derives from wherever its own module sits. Inside a `pkg` binary that path is `/snapshot/...`, which only exists in the `fs` module pkg patches, so the kernel cannot exec it and `posix_spawn` fails with `ENOENT`. The throw is fatal inside the addon, so no caller gets to answer for it.
|
|
728
|
+
**A packaged binary loads `node-pty` from real disk, not from the snapshot.** On macOS `node-pty` does not exec the shell directly. It execs `spawn-helper`, at a path it derives from wherever its own module sits. Inside a `pkg` binary that path is `/snapshot/...`, which only exists in the `fs` module pkg patches, so the kernel cannot exec it and `posix_spawn` fails with `ENOENT`. The throw is fatal inside the addon, so no caller gets to answer for it. node-pty builds `spawn-helper` on macOS only: Linux forks the shell with `forkpty()`, and Windows uses ConPTY. `hasExecutableSpawnHelper()` asks for a helper on macOS only.
|
|
710
729
|
|
|
711
730
|
`resolveNodePtyRoot()` copies the package out of the snapshot on first use and returns that path, so every path `node-pty` derives afterwards is a real one. It copies `package.json`, `lib/`, and this platform's native directory only: 41 files and 404 KB. The snapshot carries the native directories of all 4 prebuilt platforms, about 5 MB. The `pkg.ignore` list in `package.json` keeps the package's `.pdb` debug symbols and C++ source, 56 MB, out of the binary. A glob added there must not remove anything else from the 3 copied paths. The copy lands in `~/.config/pinggy/runtime/node-pty-<version>-<platform>-<arch>`, staged under a sibling name and renamed into place, so 2 agents starting at once cannot load a half-written copy. An unpackaged run resolves through `require` as normal and copies nothing.
|
|
712
731
|
|
|
732
|
+
**Linux has no prebuild.** node-pty 1.1.0 ships prebuilds for `darwin-arm64`, `darwin-x64`, `win32-arm64` and `win32-x64`. On Linux `npm ci` compiles `build/Release/pty.node`. node-pty's `files` list leaves `build/` out, and pkg packs only what that list names, so `pkg.assets` names `pty.node`. Linux binaries up to 0.6.5 carried no addon, and their copy holds `package.json` and `lib/` only. `rename(2)` does not replace a directory with files in it, so the unpack deletes a copy with no addon before the rename.
|
|
733
|
+
|
|
734
|
+
The compiled addon needs glibc 2.34 (`forkpty` and `openpty`). The SDK's `libpinggy.so` already needs the system's OpenSSL 3 (`libssl.so.3`), and every distro that ships it has glibc 2.34 or newer, so a build on `ubuntu-latest` narrows nothing. Measured on Debian 10 and 11: the CLI does not start there, because `libssl.so.3` is missing.
|
|
735
|
+
|
|
713
736
|
Not `pkg`'s own cache. `pkg` already unpacks the addon to `~/.cache/pkg/<hash>/` at mode 644, but the hash is undocumented and `node-pty` never looks there.
|
|
714
737
|
|
|
715
|
-
Measured on `macos-arm64` and `macos-x64
|
|
738
|
+
Measured on `macos-arm64` and `macos-x64`, and on `linux-arm64` in Docker (Debian 12 and 13). The `device-agent-terminal` e2e case opens a shell and runs 1 command on all 6 CI platforms.
|
|
716
739
|
|
|
717
740
|
### Outcomes
|
|
718
741
|
|
|
@@ -747,7 +770,7 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
|
|
|
747
770
|
|
|
748
771
|
**Written 0600, then chmodded again on every rewrite**, because `writeFileSync` applies `mode` only when it creates the file. This diverges from `configStore.ts`, which writes tunnel tokens at 0644 under a normal umask. Do not copy that pattern into anything new.
|
|
749
772
|
|
|
750
|
-
`pinggy device remove` deletes this file and
|
|
773
|
+
`pinggy device remove` deletes this file and `device-agent.json`, after it stops a background agent and a `--foreground` agent in another terminal. Revoking the device server-side is a dashboard action, because a machine that has lost its credential cannot authenticate the delete.
|
|
751
774
|
|
|
752
775
|
### Composition with other subcommands
|
|
753
776
|
|
|
@@ -760,6 +783,7 @@ Retry sleeps an exponential backoff with full jitter: 1 s doubling to a 60 s cap
|
|
|
760
783
|
| `device connect -l 3000 -b --all --remote-management KEY` | Runs the agent in the daemon, the default, and ignores the other 3. Only `values.token`, `values.manage`, `values.b` and `values.foreground` are read. No tunnel and no remote management | `handleDevice` reads 4 fields off `values` |
|
|
761
784
|
| `device connect -b --foreground` | `-b and --foreground contradict each other`, exit 1. Nothing runs | `handleDevice`, before the verb switch |
|
|
762
785
|
| `device connect --foreground`, `device login --foreground` while the daemon runs an agent | Refused, exit 1: "This machine already runs as device <id> in the background. Stop it first: pinggy device stop" | `foregroundRefusal()` in `backgroundAgent.ts` |
|
|
786
|
+
| `device connect`, `device login`, with or without `--foreground`, while another terminal runs a `--foreground` agent | Refused, exit 1: "This machine already runs as a device in another terminal (PID <pid>). Press Ctrl+C in that terminal first." | `foregroundAgentRefusal()` in `foregroundAgent.ts` |
|
|
763
787
|
| `device stop` with no background agent | "No device agent is running in the background.", exit 0. Never starts a daemon | `stopAgentInBackground()` |
|
|
764
788
|
| `device connect --typo` | `Fatal Error: Unknown option '--typo'`, exit 1, before dispatch | `main()` parses the full argv with `parseArgs` in strict mode, then calls `isSubcommand` |
|
|
765
789
|
| `device connect --help` | Ignores `--help` and connects. Only `device` and `device --help` reach `printDeviceHelp()` | The verb switch tests `--help` in its `default` arm only |
|
|
@@ -782,15 +806,15 @@ With `--foreground` the agent shares no state with the daemon or with tunnels, w
|
|
|
782
806
|
- Ctrl+C on the agent touches no tunnel. There is no `SessionTracker` entry, no grace timer, and no origin tag.
|
|
783
807
|
- The agent logs through `CLIPrinter` and the CLI logger, not the daemon log. Nothing about it reaches `daemon.log` or the per-tunnel logs.
|
|
784
808
|
|
|
785
|
-
Without `--foreground` the daemon owns the agent: `ensureDaemonRunning()` may start a daemon, `pinggy daemon stop` stops the agent too and says so, the agent logs to `daemon.log`, and `daemon-
|
|
809
|
+
Without `--foreground` the daemon owns the agent: `ensureDaemonRunning()` may start a daemon, `pinggy daemon stop` stops the agent too and says so, the agent logs to `daemon.log`, and `daemon-config.json` saves it, so the next daemon start runs it again. It still has no `SessionTracker` entry and no origin tag of its own.
|
|
786
810
|
|
|
787
|
-
1 identity per config dir, last write wins: a run keeps what `device.json` holds while the token matches, sets the server, and rewrites the file on every `welcome`.
|
|
811
|
+
1 identity per config dir, last write wins: a run keeps what `device.json` holds while the token matches, sets the server, and rewrites the file on every `welcome`. `device remove` stops a foreground agent through its record first, so the file stays deleted. 2 agents sharing 1 credential lose the race by design: the dashboard refuses the second with `already_connected`, and it retries on the backoff until the first socket drops. The daemon's run rewrites the file only while it holds its own token (`writeIdentityWhileOwned()`).
|
|
788
812
|
|
|
789
813
|
### Not built yet
|
|
790
814
|
|
|
791
|
-
In this repo: terminal input, output, flow control, resize, and signals
|
|
792
|
-
carries `node-pty
|
|
793
|
-
`device/metrics` collectors, and
|
|
815
|
+
In this repo: terminal input, output, flow control, resize, and signals. A `pkg` build that
|
|
816
|
+
carries `node-pty`. The reconnect backoff and pong watchdog, the `device/info` and
|
|
817
|
+
`device/metrics` collectors, and the terminal open and close have all landed. Everything else
|
|
794
818
|
outstanding is dashboard or frontend work.
|
|
795
819
|
|
|
796
820
|
## 18. Reference for AI agents
|
|
@@ -839,7 +863,7 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
|
|
|
839
863
|
- The IPC server only listens on `127.0.0.1`. Do not change to `0.0.0.0` without adding authentication. The current design assumes loopback isolation.
|
|
840
864
|
- Every tunnel reconnects without limit. `_createTunnelWithProcessedConfig()` in `TunnelManager.ts` sets `maxReconnectAttempts` to 0 and ignores the value the caller sends. Create, restart and update all pass through it, so the rule covers the CLI, the app, autostart, crash recovery and remote management. libpinggy counts reconnects over the whole tunnel lifetime and does not reset the count after a successful reconnect. Any limit, including the libpinggy default of 20 for an omitted value, stops a long-running tunnel permanently.
|
|
841
865
|
- Do not route `pinggy device --foreground` through the daemon. Without it the daemon runs the agent, and no IPC route takes or returns a token or a server: the daemon reads both from `device.json`. Any local user can reach the IPC port.
|
|
842
|
-
- Do not generalise `src/remote_management/` to serve the device agent. Those files are on the backend
|
|
866
|
+
- Do not generalise `src/remote_management/` to serve the device agent. Those files are on the backend's do-not-touch list (`docs/pinggy-devices/must-not-change.txt`).
|
|
843
867
|
- `device.json` holds a live credential. Any code that writes it goes through `writeDeviceIdentity()`, which keeps the 0600 mode on rewrites.
|
|
844
868
|
|
|
845
869
|
## 19. Quick diagrams
|
|
@@ -891,7 +915,8 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
|
|
|
891
915
|
└──────────────────────────────────┘
|
|
892
916
|
│ next pinggy command
|
|
893
917
|
▼
|
|
894
|
-
getDaemonInfo() returns null (PID dead
|
|
918
|
+
getDaemonInfo() returns null (PID dead, or ──▶ unlinks daemon.json
|
|
919
|
+
started before the last boot)
|
|
895
920
|
│
|
|
896
921
|
▼
|
|
897
922
|
startDaemon() spawns new child
|
|
@@ -933,3 +958,47 @@ No em-dashes. Short phrases. Present tense. See `CLAUDE.md` § "English Style" b
|
|
|
933
958
|
│ Daemon keeps running with t1 still live.
|
|
934
959
|
▼
|
|
935
960
|
```
|
|
961
|
+
|
|
962
|
+
## 20. Auto-update
|
|
963
|
+
|
|
964
|
+
The CLI updates itself from GitHub releases. `pinggy update` does it on request. Every other command can start a detached process, `pinggy --_update-child`, at most once a day. The command never waits for it. Code: `src/update/`.
|
|
965
|
+
|
|
966
|
+
| File | Purpose |
|
|
967
|
+
| --- | --- |
|
|
968
|
+
| `installKind.ts` | How this copy was installed, which decides whether it can replace itself. An unknown location gets a hint and never a write |
|
|
969
|
+
| `updateState.ts` | `update.json`. Every field is optional, and a corrupt file reads as empty |
|
|
970
|
+
| `latestRelease.ts` | The latest tag from the `/releases/latest` redirect, `isReleaseComplete()`, the npm registry, version compare |
|
|
971
|
+
| `binaryUpdater.ts` | `downloadAndVerify()`, `runPinggyBinary()`, `UpdateError` |
|
|
972
|
+
| `updateLock.ts` | `update.lock`. 1 process replaces the binary at a time |
|
|
973
|
+
| `windowsSwap.ts` | Rename swap with retries, the post-swap run, the restore, rollback, cleanup on start |
|
|
974
|
+
| `unixLinkSwap.ts` | Versioned layout, atomic link move, prune, rollback, plain-file conversion |
|
|
975
|
+
| `applyUpdate.ts` | The swap for this install kind, behind 1 interface |
|
|
976
|
+
| `backgroundUpdate.ts` | The gates on every command, the pending notice, starting the detached process |
|
|
977
|
+
| `updateChild.ts` | The detached process |
|
|
978
|
+
|
|
979
|
+
**Layout on macOS and Linux.** `~/.local/bin/pinggy` links to `~/.pinggy/bin/pinggy`, which links to `~/.pinggy/versions/<x.y.z>/pinggy`. The updater moves the 2nd link with a temp link and a rename, because `ln -sf` removes the old link first. No step touches a running binary. A process whose file was pruned keeps its code, and `getDaemonSpawnArgs()` starts any new daemon from the link.
|
|
980
|
+
|
|
981
|
+
**Windows.** A running `.exe` can be renamed but not overwritten. The live file becomes `<live name>.<epochMillis>.old`, the download takes the live name, and `<stem>.prev.exe` holds a copy for rollback. Every file stays in the folder of `execPath`. Each rename retries for 10 seconds, because a scanner can hold a new `.exe` open, and the live path runs once after the swap, because a scanner can remove it.
|
|
982
|
+
|
|
983
|
+
**Verify.** `SHA256SUMS` first, then free space, the download, size, SHA-256, and `--version`. Nothing runs the new file before its hash matches. `runPinggyBinary()` sets `windowsHide` and an empty `PKG_EXECPATH`: pkg adds `PKG_EXECPATH=<execPath>` to every child, and a file at the running binary's own path then reads its first argument as a script.
|
|
984
|
+
|
|
985
|
+
**Background gates, in order.** Not an explicit or print-only command, stdout is a terminal, `PINGGY_AUTO_UPDATE` is not off, not under `sudo` or in a container, the running version parses, not under `_npx`. Any pending notice prints here. Then the last check is over 24 hours old, the last attempt is over 1 hour old, not a dev checkout, no live lock, and `lastAttemptEpochSeconds` is written.
|
|
986
|
+
|
|
987
|
+
**A live daemon.** A daemon keeps the code it started with. The updater reads `--_ipc-version` from the verified file. When a live daemon speaks another IPC version, the background update holds the swap, because the swap would break every daemon command until the user stops all tunnels. This costs 1 download per release.
|
|
988
|
+
|
|
989
|
+
**A release.** `publish-binaries.yml` uploads the 6 binaries, then `SHA256SUMS`. A release with no `SHA256SUMS` is unfinished, and the updater refuses it.
|
|
990
|
+
|
|
991
|
+
**What installed updaters read.** Each installed copy keeps the updater it shipped with, so these never change: the `/releases/latest` redirect, the tag format `vX.Y.Z`, the 6 asset names, `SHA256SUMS` and its format, the `Pinggy CLI version: <x.y.z>` line, the `--_ipc-version` output, and the `update.json` field names.
|
|
992
|
+
|
|
993
|
+
**After a rollback.** Older code reads `daemon-state.json`, `device.json` and saved configs. They carry no version, so they change by adding fields only. A breaking change uses a new file name.
|
|
994
|
+
|
|
995
|
+
**Stopping a bad release.**
|
|
996
|
+
|
|
997
|
+
1. Stop further updates: `gh release delete-asset <bad-tag> SHA256SUMS --repo Pinggy-io/cli-js --yes`.
|
|
998
|
+
2. Send new installs to the last good release: `gh release edit <good-tag> --latest --repo Pinggy-io/cli-js`.
|
|
999
|
+
3. Publish the fix as a higher patch version. Copies on the bad version take it on their next check.
|
|
1000
|
+
4. Tell users on the bad version to run `pinggy update --rollback`.
|
|
1001
|
+
|
|
1002
|
+
Step 3 needs a working updater in the bad build. If the updater is the bug, those users run the install script.
|
|
1003
|
+
|
|
1004
|
+
**Overrides, for dev and tests.** `PINGGY_UPDATE_RELEASES_URL` accepts a loopback `http` URL only.
|