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.
Files changed (32) hide show
  1. package/ARCHITECTURE.md +126 -57
  2. package/CLAUDE.md +25 -12
  3. package/README.md +5 -5
  4. package/dist/{TunnelManager-NGSUBZYI.js → TunnelManager-JRVEADS4.js} +4 -3
  5. package/dist/{TunnelTui-UCG2YSLX.js → TunnelTui-6H4NPUNF.js} +4 -3
  6. package/dist/{chunk-Y435RMHQ.js → chunk-2GIJXE4K.js} +3 -2
  7. package/dist/{chunk-QNUVQ6KD.js → chunk-3WMTTJHI.js} +11 -299
  8. package/dist/chunk-4XXAHYCJ.js +927 -0
  9. package/dist/{chunk-PD7HXVQ3.js → chunk-CZOKR73F.js} +18 -1
  10. package/dist/chunk-FQ22KFVV.js +882 -0
  11. package/dist/{chunk-UVJYL2ZN.js → chunk-HAFTH5MX.js} +933 -576
  12. package/dist/chunk-HTIWY3O5.js +293 -0
  13. package/dist/{chunk-MV56U3E6.js → chunk-LWCVB42S.js} +2 -2
  14. package/dist/{chunk-AFMTIELL.js → chunk-MAK5R4WQ.js} +20 -0
  15. package/dist/{chunk-7EQKHVQX.js → chunk-MHQ3CVEB.js} +4 -51
  16. package/dist/chunk-MKGD2QAI.js +51 -0
  17. package/dist/{chunk-CIOYQU7F.js → chunk-Q5NCTGNS.js} +49 -233
  18. package/dist/{configStore-RR5ZU4E3.js → configStore-JJUWT2YO.js} +3 -3
  19. package/dist/{daemonChild-WHS676G4.js → daemonChild-Q6WGYKYX.js} +14 -14
  20. package/dist/daemonConfig-VWK4TXVS.js +17 -0
  21. package/dist/index.cjs +3214 -935
  22. package/dist/index.d.cts +150 -129
  23. package/dist/index.d.ts +150 -129
  24. package/dist/index.js +18 -13
  25. package/dist/{ipcClient-XGF2KCQO.js → ipcClient-IZ5R6TPN.js} +2 -1
  26. package/dist/{main-JRVKAIHH.js → main-BI7ACRHS.js} +19 -14
  27. package/dist/updateChild-Z3SIRYO5.js +237 -0
  28. package/dist/workers/file_serve_worker.js +1 -1
  29. package/package.json +2 -1
  30. package/scripts/install/install.ps1 +49 -5
  31. package/scripts/install/install.sh +99 -12
  32. package/dist/daemonConfig-QVXQ47XH.js +0 -9
@@ -1,33 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runDaemonChild
4
- } from "./chunk-UVJYL2ZN.js";
4
+ } from "./chunk-HAFTH5MX.js";
5
5
  import {
6
6
  RemoteManagementUnauthorizedError,
7
7
  TunnelOperations,
8
8
  closeRemoteManagement,
9
+ getRemoteManagementState,
10
+ initiateRemoteManagement
11
+ } from "./chunk-Q5NCTGNS.js";
12
+ import "./chunk-CZOKR73F.js";
13
+ import "./chunk-MHQ3CVEB.js";
14
+ import "./chunk-2GIJXE4K.js";
15
+ import "./chunk-XZ64ZAGO.js";
16
+ import {
17
+ TunnelManager
18
+ } from "./chunk-3WMTTJHI.js";
19
+ import "./chunk-UB26QJ4T.js";
20
+ import "./chunk-FQ22KFVV.js";
21
+ import {
9
22
  ensureDaemonRunning,
10
23
  getActiveTunnelSummaries,
11
24
  getDaemonInfo,
12
25
  getInProcessDaemonHandle,
13
- getRemoteManagementState,
14
- initiateRemoteManagement,
15
26
  isDaemonRunning
16
- } from "./chunk-CIOYQU7F.js";
17
- import "./chunk-PD7HXVQ3.js";
27
+ } from "./chunk-4XXAHYCJ.js";
18
28
  import {
19
29
  DaemonHost
20
- } from "./chunk-7EQKHVQX.js";
21
- import "./chunk-Y435RMHQ.js";
22
- import "./chunk-XZ64ZAGO.js";
23
- import {
24
- TunnelManager
25
- } from "./chunk-QNUVQ6KD.js";
26
- import "./chunk-UB26QJ4T.js";
30
+ } from "./chunk-MKGD2QAI.js";
31
+ import "./chunk-HTIWY3O5.js";
27
32
  import {
28
33
  enablePackageLogging
29
- } from "./chunk-MV56U3E6.js";
30
- import "./chunk-AFMTIELL.js";
34
+ } from "./chunk-LWCVB42S.js";
35
+ import "./chunk-MAK5R4WQ.js";
31
36
  export {
32
37
  DaemonHost,
33
38
  RemoteManagementUnauthorizedError,
@@ -0,0 +1,237 @@
1
+ import {
2
+ UpdateError,
3
+ acquireUpdateLock,
4
+ assetNameFor,
5
+ createUpdateTarget,
6
+ downloadRelease,
7
+ isNewerVersion,
8
+ isReleaseComplete,
9
+ isUpdateLockOurs,
10
+ readBinaryIpcVersion,
11
+ releaseUpdateLock,
12
+ removeQuietly,
13
+ removeStaleUnixFiles,
14
+ removeStaleUpdateFiles,
15
+ resolveLatestNpmVersion,
16
+ resolveLatestTag,
17
+ runPinggyBinary,
18
+ versionFromTag
19
+ } from "./chunk-FQ22KFVV.js";
20
+ import {
21
+ InstallKind,
22
+ backgroundInstallKind,
23
+ canReplaceItself,
24
+ createInstallProbe,
25
+ daemonIpcVersion,
26
+ detectInstallKind,
27
+ getDaemonInfo,
28
+ nowEpochSeconds,
29
+ readUpdateState,
30
+ recordLatestVersion,
31
+ unixLayoutPaths,
32
+ writeUpdateState
33
+ } from "./chunk-4XXAHYCJ.js";
34
+ import "./chunk-MKGD2QAI.js";
35
+ import {
36
+ errorMessage,
37
+ getVersion
38
+ } from "./chunk-HTIWY3O5.js";
39
+ import "./chunk-LWCVB42S.js";
40
+ import {
41
+ ensurePinggyLogDir,
42
+ getUpdateLogPath
43
+ } from "./chunk-MAK5R4WQ.js";
44
+
45
+ // src/update/updateChild.ts
46
+ import fs from "fs";
47
+ import os from "os";
48
+ var TIME_LIMIT_MILLIS = 30 * 60 * 1e3;
49
+ var CHECK_TIMEOUT_MILLIS = 15e3;
50
+ var CHECK_INTERVAL_SECONDS = 24 * 60 * 60;
51
+ var MAX_FAILED_ATTEMPTS = 3;
52
+ function checkedRecently(state, now) {
53
+ const last = state.lastCheckEpochSeconds;
54
+ return last !== void 0 && last <= now && now - last < CHECK_INTERVAL_SECONDS;
55
+ }
56
+ function saveCheckTime(environment) {
57
+ environment.writeState({ lastCheckEpochSeconds: environment.nowEpochSeconds() });
58
+ }
59
+ async function latestVersionAndTag(environment) {
60
+ try {
61
+ if (environment.kind === InstallKind.Npm) {
62
+ const latest = await environment.resolveNpmVersion();
63
+ return { tag: `v${latest}`, latest };
64
+ }
65
+ const tag = await environment.resolveTag();
66
+ return { tag, latest: versionFromTag(tag) };
67
+ } catch (error) {
68
+ environment.log(`Could not find the latest version: ${errorMessage(error)}`);
69
+ return null;
70
+ }
71
+ }
72
+ async function releaseIsReady(tag, environment) {
73
+ if (environment.kind === InstallKind.Npm) return true;
74
+ try {
75
+ if (await environment.isReleaseComplete(tag)) return true;
76
+ environment.log(`Release ${tag} has no SHA256SUMS yet`);
77
+ } catch (error) {
78
+ environment.log(`Could not check release ${tag}: ${errorMessage(error)}`);
79
+ }
80
+ return false;
81
+ }
82
+ function daemonStillDiffers(state, environment) {
83
+ const daemon = environment.liveDaemon();
84
+ return daemon !== null && daemonIpcVersion(daemon) !== state.deferredIpcVersion;
85
+ }
86
+ function skipReason(latest, state, environment) {
87
+ if (!canReplaceItself(environment.kind) || environment.target === null) return "this install cannot update itself";
88
+ if (latest === state.rolledBackFromVersion) return "the user rolled back from this version";
89
+ if (latest === state.failedVersion && (state.failedAttempts ?? 0) >= MAX_FAILED_ATTEMPTS) return "this version failed too many times";
90
+ if (latest === state.deferredVersion && daemonStillDiffers(state, environment)) return "a live daemon still needs a restart first";
91
+ return null;
92
+ }
93
+ function countFailure(latest, environment) {
94
+ const state = environment.readState();
95
+ const attempts = state.failedVersion === latest ? (state.failedAttempts ?? 0) + 1 : 1;
96
+ environment.writeState({ failedVersion: latest, failedAttempts: attempts });
97
+ }
98
+ async function holdForLiveDaemon(latest, target, environment) {
99
+ const newIpcVersion = await environment.readIpcVersion(target.downloadPath);
100
+ const daemon = environment.liveDaemon();
101
+ if (daemon === null || daemonIpcVersion(daemon) === newIpcVersion) return false;
102
+ environment.writeState({ deferredVersion: latest, deferredIpcVersion: newIpcVersion });
103
+ environment.log(`Held ${latest}: the running daemon speaks IPC v${daemonIpcVersion(daemon)}, this release v${newIpcVersion}`);
104
+ return true;
105
+ }
106
+ function lostTheRight(latest, environment) {
107
+ return !environment.isLockOurs() || environment.readState().rolledBackFromVersion === latest;
108
+ }
109
+ var Outcome = {
110
+ Finished: "finished",
111
+ TryAgainSoon: "try-again-soon"
112
+ };
113
+ async function installRelease(release, installed, target, environment) {
114
+ const { tag, latest } = release;
115
+ try {
116
+ await environment.download(target, tag);
117
+ if (await holdForLiveDaemon(latest, target, environment)) return Outcome.Finished;
118
+ if (lostTheRight(latest, environment)) {
119
+ environment.log("Stopped before the swap: the lock was lost, or the user rolled back");
120
+ return Outcome.TryAgainSoon;
121
+ }
122
+ await target.install({ newVersion: latest, runningVersion: environment.runningVersion });
123
+ environment.writeState({
124
+ updatedFromVersion: installed,
125
+ updatedToVersion: latest,
126
+ failedVersion: void 0,
127
+ failedAttempts: void 0,
128
+ deferredVersion: void 0,
129
+ deferredIpcVersion: void 0
130
+ });
131
+ environment.log(`Updated ${installed} to ${latest}`);
132
+ } catch (error) {
133
+ if (error instanceof UpdateError && error.countsAsBadRelease) countFailure(latest, environment);
134
+ environment.log(`Update to ${latest} failed: ${errorMessage(error)}`);
135
+ } finally {
136
+ environment.removeFile(target.downloadPath);
137
+ }
138
+ return Outcome.Finished;
139
+ }
140
+ async function runLocked(environment) {
141
+ environment.startLog();
142
+ if (checkedRecently(environment.readState(), environment.nowEpochSeconds())) {
143
+ environment.log("Another update checked within the last 24 hours");
144
+ return;
145
+ }
146
+ const release = await latestVersionAndTag(environment);
147
+ if (!release) return;
148
+ const installed = environment.target?.installedVersion(environment.runningVersion) ?? environment.runningVersion;
149
+ if (!isNewerVersion(release.latest, installed)) {
150
+ environment.recordLatestVersion(release.latest);
151
+ saveCheckTime(environment);
152
+ environment.log(`${installed} is up to date`);
153
+ return;
154
+ }
155
+ if (!await releaseIsReady(release.tag, environment)) return;
156
+ environment.recordLatestVersion(release.latest);
157
+ const reason = skipReason(release.latest, environment.readState(), environment);
158
+ if (reason || environment.target === null) {
159
+ saveCheckTime(environment);
160
+ environment.log(`No download: ${reason}`);
161
+ return;
162
+ }
163
+ if (await installRelease(release, installed, environment.target, environment) === Outcome.Finished) saveCheckTime(environment);
164
+ }
165
+ async function runUpdateChild(environment = createUpdateChildEnvironment()) {
166
+ const cancelTimeLimit = environment.startTimeLimit(() => {
167
+ if (environment.target) environment.removeFile(environment.target.downloadPath);
168
+ environment.exitProcess();
169
+ });
170
+ try {
171
+ environment.removeStaleFiles();
172
+ if (!await environment.acquireLock()) return;
173
+ try {
174
+ await runLocked(environment);
175
+ } finally {
176
+ environment.releaseLock();
177
+ }
178
+ } catch (error) {
179
+ environment.log(`Failed: ${errorMessage(error)}`);
180
+ } finally {
181
+ cancelTimeLimit();
182
+ }
183
+ }
184
+ function removeStaleFilesFor(platform, homeRealPath) {
185
+ if (platform === "win32") removeStaleUpdateFiles();
186
+ else removeStaleUnixFiles(unixLayoutPaths(homeRealPath));
187
+ }
188
+ function writeLogLine(logPath, line) {
189
+ try {
190
+ fs.appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}${os.EOL}`);
191
+ } catch {
192
+ }
193
+ }
194
+ function startLogFile(logPath) {
195
+ try {
196
+ ensurePinggyLogDir();
197
+ fs.writeFileSync(logPath, "");
198
+ } catch {
199
+ }
200
+ }
201
+ function createUpdateChildEnvironment() {
202
+ const probe = createInstallProbe();
203
+ const kind = backgroundInstallKind(detectInstallKind(probe), probe.execPath, probe.homeRealPath);
204
+ const runningVersion = getVersion();
205
+ const timeout = { timeoutMillis: CHECK_TIMEOUT_MILLIS };
206
+ const logPath = getUpdateLogPath();
207
+ return {
208
+ kind,
209
+ target: createUpdateTarget(kind, probe),
210
+ runningVersion,
211
+ nowEpochSeconds,
212
+ acquireLock: acquireUpdateLock,
213
+ releaseLock: releaseUpdateLock,
214
+ isLockOurs: isUpdateLockOurs,
215
+ readState: readUpdateState,
216
+ writeState: writeUpdateState,
217
+ recordLatestVersion,
218
+ resolveTag: () => resolveLatestTag(timeout),
219
+ resolveNpmVersion: () => resolveLatestNpmVersion(timeout),
220
+ isReleaseComplete: (tag) => isReleaseComplete(tag, timeout),
221
+ download: (target, tag) => downloadRelease(target, tag, assetNameFor(probe.platform, process.arch), runningVersion),
222
+ readIpcVersion: (binaryPath) => readBinaryIpcVersion(binaryPath, runPinggyBinary),
223
+ liveDaemon: getDaemonInfo,
224
+ removeStaleFiles: () => removeStaleFilesFor(probe.platform, probe.homeRealPath),
225
+ removeFile: removeQuietly,
226
+ startLog: () => startLogFile(logPath),
227
+ log: (line) => writeLogLine(logPath, line),
228
+ startTimeLimit: (onLimit) => {
229
+ const timer = setTimeout(onLimit, TIME_LIMIT_MILLIS);
230
+ return () => clearTimeout(timer);
231
+ },
232
+ exitProcess: () => process.exit(0)
233
+ };
234
+ }
235
+ export {
236
+ runUpdateChild
237
+ };
@@ -3,7 +3,7 @@ import {
3
3
  } from "../chunk-UB26QJ4T.js";
4
4
  import {
5
5
  logger
6
- } from "../chunk-MV56U3E6.js";
6
+ } from "../chunk-LWCVB42S.js";
7
7
 
8
8
  // src/workers/file_serve_worker.ts
9
9
  import { parentPort, workerData } from "worker_threads";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinggy",
3
- "version": "0.6.4",
3
+ "version": "0.6.6",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "description": "Create secure, shareable tunnels to your localhost and manage them from the command line. ",
@@ -48,6 +48,7 @@
48
48
  "node_modules/@pinggy/pinggy/**/*",
49
49
  "node_modules/blessed/lib/**/*",
50
50
  "node_modules/blessed/usr/**/*",
51
+ "node_modules/node-pty/build/Release/pty.node",
51
52
  "dist/workers/**/*"
52
53
  ],
53
54
  "ignore": [
@@ -1,4 +1,5 @@
1
- # Installs or updates the Pinggy CLI on Windows, then signs this machine in as a Pinggy device.
1
+ # Installs or updates the Pinggy CLI on Windows, then asks whether to sign this machine in as a Pinggy device.
2
+ # Once the device connects, it asks whether to start pinggy at login, unless that task is already registered.
2
3
  #
3
4
  # irm https://pinggy.io/install.ps1 | iex
4
5
  # $env:DEVICE_AGENT_TOKEN='<token>'; irm https://pinggy.io/install.ps1 | iex
@@ -16,7 +17,6 @@
16
17
  # $env:PINGGY_MANAGE a non-production dashboard host, passed to `pinggy device login` or `connect` as --manage
17
18
  #
18
19
  # The source lives in Pinggy-io/cli-js, scripts/install/. A release copies it to pinggy.io.
19
- # Design: docs/pinggy-devices/install-script-plan.md in the pinggy_backend repo.
20
20
  #
21
21
  # iex runs this inside the user's own session. So it never calls exit, which would close their window, and every
22
22
  # helper and preference is local to Install-Pinggy. Nothing runs until the last line.
@@ -34,6 +34,9 @@ function Install-Pinggy {
34
34
  $installDir = Join-Path $env:LOCALAPPDATA 'Pinggy\bin'
35
35
  $installPath = Join-Path $installDir 'pinggy.exe'
36
36
  $versionPattern = 'Pinggy CLI version:\s*(\S+)'
37
+ $autoUpdatePinLine = 'Auto-update replaces this version. Set PINGGY_AUTO_UPDATE=false to keep it.'
38
+ # The task `pinggy daemon service-install` registers. Its name lives in src/daemon/lifecycle/serviceInstaller.ts.
39
+ $loginTaskName = 'PinggyDaemon'
37
40
  $cpuArchitectureX64 = 9
38
41
  $cpuArchitectureArm64 = 12
39
42
 
@@ -97,7 +100,7 @@ function Install-Pinggy {
97
100
  }
98
101
 
99
102
  # Enter, or no terminal, means yes. Only an answer starting with n means no.
100
- function Confirm-Update([string] $question) {
103
+ function Confirm-Question([string] $question) {
101
104
  if (-not (Test-Interactive)) { return $true }
102
105
  $answer = Read-Host $question
103
106
  return -not ($answer -match '^\s*n')
@@ -177,10 +180,11 @@ function Install-Pinggy {
177
180
  # An older CLI ignores DEVICE_AGENT_TOKEN, so keeping it would leave the machine unconnected.
178
181
  Write-Host "Updating pinggy $installedVersion to $targetVersion."
179
182
  Install-Binary $tag $cpu
180
- } elseif (Confirm-Update "pinggy $installedVersion is installed. Update to $($targetVersion)? [Y/n]") {
183
+ } elseif (Confirm-Question "pinggy $installedVersion is installed. Update to $($targetVersion)? [Y/n]") {
181
184
  Install-Binary $tag $cpu
182
185
  } else {
183
186
  Write-Host "Keeping pinggy $installedVersion."
187
+ if (-not $env:PINGGY_VERSION) { Write-Host $autoUpdatePinLine }
184
188
  }
185
189
  }
186
190
 
@@ -214,6 +218,36 @@ function Install-Pinggy {
214
218
  }
215
219
  }
216
220
 
221
+ # The task counts only when it runs the binary this script installs. A task left by a pinggy elsewhere gets the
222
+ # question, and service-install replaces it. Get-ScheduledTask, because schtasks prints field names in the
223
+ # language of Windows.
224
+ function Test-LoginTask {
225
+ try {
226
+ $task = Get-ScheduledTask -TaskName $loginTaskName -ErrorAction Stop
227
+ } catch {
228
+ return $false
229
+ }
230
+ return @($task.Actions | Where-Object { $_.Execute -ieq $installPath }).Count -gt 0
231
+ }
232
+
233
+ # Asks once the device connects, so the agent starts again after a restart. Leaves a registered task as it is.
234
+ function Invoke-LoginServiceOffer {
235
+ if (Test-LoginTask) { return }
236
+ if (-not (Test-Interactive)) {
237
+ Write-Host 'To start pinggy when this computer starts, run: pinggy daemon service-install'
238
+ return
239
+ }
240
+ Write-Host ''
241
+ if (-not (Confirm-Question 'Start pinggy automatically when this computer starts? [Y/n]')) {
242
+ Write-Host 'To start pinggy when this computer starts, run: pinggy daemon service-install'
243
+ return
244
+ }
245
+ & $installPath daemon service-install
246
+ if ($LASTEXITCODE -ne 0) {
247
+ Write-Host 'Could not set up the login service. To try again, run: pinggy daemon service-install'
248
+ }
249
+ }
250
+
217
251
  # Runs the installed file by its full path, so an npm-installed pinggy earlier on PATH does not answer. -b is the
218
252
  # default now. It is passed anyway, so an older pinggy the user kept runs the agent in its daemon too.
219
253
  function Invoke-DeviceLogin {
@@ -227,16 +261,25 @@ function Install-Pinggy {
227
261
  return
228
262
  }
229
263
  Write-Host ''
264
+ if (-not (Confirm-Question 'Connect this device to Pinggy? [Y/n]')) {
265
+ Write-Host "Installed. To connect this device later, run: pinggy $($loginArguments -join ' ')"
266
+ return
267
+ }
230
268
  & $installPath @loginArguments -b
269
+ if ($LASTEXITCODE -eq 0) { Invoke-LoginServiceOffer }
231
270
  }
232
271
 
233
272
  # Runs the installed file by its full path, with -b, as Invoke-DeviceLogin does. connect reads DEVICE_AGENT_TOKEN
234
- # from the environment it inherits, and reads no key, so it runs the same with no console.
273
+ # from the environment it inherits, and reads no key, so it runs the same with no console. The token leaves the
274
+ # environment before the service question, so no later command inherits it.
235
275
  function Invoke-DeviceConnect {
236
276
  $connectArguments = @('device', 'connect', '-b')
237
277
  if ($env:PINGGY_MANAGE) { $connectArguments += @('--manage', $env:PINGGY_MANAGE) }
238
278
  Write-Host ''
239
279
  & $installPath @connectArguments
280
+ $connectExitCode = $LASTEXITCODE
281
+ Remove-Item -Path Env:\DEVICE_AGENT_TOKEN -ErrorAction SilentlyContinue
282
+ if ($connectExitCode -eq 0) { Invoke-LoginServiceOffer }
240
283
  }
241
284
 
242
285
  # Older Windows PowerShell 5.1 setups offer less than TLS 1.2, and GitHub refuses them.
@@ -246,6 +289,7 @@ function Install-Pinggy {
246
289
  try {
247
290
  $cpu = Get-Cpu
248
291
  Install-OrUpdate $cpu
292
+ if ($env:PINGGY_VERSION) { Write-Host $autoUpdatePinLine }
249
293
  Add-InstallDirToPath
250
294
  if ($env:DEVICE_AGENT_TOKEN) {
251
295
  Invoke-DeviceConnect
@@ -1,11 +1,13 @@
1
1
  #!/bin/sh
2
- # Installs or updates the Pinggy CLI on macOS and Linux, then signs this machine in as a Pinggy device.
2
+ # Installs or updates the Pinggy CLI on macOS and Linux, then asks whether to sign this machine in as a Pinggy device.
3
+ # Once the device connects, it asks whether to start pinggy at login, unless that service is already installed.
3
4
  #
4
5
  # curl -fsSL https://pinggy.io/install.sh | sh
5
6
  # curl -fsSL https://pinggy.io/install.sh | DEVICE_AGENT_TOKEN=<token> sh
6
7
  #
7
- # The binary goes to ~/.pinggy/bin/pinggy, and a symlink in ~/.local/bin puts it on PATH. No sudo: every write is
8
- # under $HOME. When ~/.local/bin is not on PATH, 1 marked block goes into the shell's rc file, once.
8
+ # The binary goes to ~/.pinggy/versions/<version>/pinggy. ~/.pinggy/bin/pinggy links to it, and a symlink in
9
+ # ~/.local/bin puts it on PATH. No sudo: every write is under $HOME. When ~/.local/bin is not on PATH, 1 marked block
10
+ # goes into the shell's rc file, once.
9
11
  #
10
12
  # Setting, from the dashboard's command:
11
13
  # DEVICE_AGENT_TOKEN a device token. An older pinggy updates without asking, then `pinggy device connect` runs
@@ -18,7 +20,6 @@
18
20
  # PINGGY_MANAGE a non-production dashboard host, passed to `pinggy device login` or `connect` as --manage
19
21
  #
20
22
  # The source lives in Pinggy-io/cli-js, scripts/install/. A release copies it to pinggy.io.
21
- # Design: docs/pinggy-devices/install-script-plan.md in the pinggy_backend repo.
22
23
  #
23
24
  # Nothing runs until the last line. A download cut off halfway defines some functions and runs no command.
24
25
 
@@ -27,6 +28,7 @@ set -eu
27
28
  RELEASES_URL="https://github.com/Pinggy-io/cli-js/releases"
28
29
  INSTALL_DIR="$HOME/.pinggy/bin"
29
30
  INSTALL_PATH="$INSTALL_DIR/pinggy"
31
+ VERSIONS_DIR="$HOME/.pinggy/versions"
30
32
  LINK_DIR="$HOME/.local/bin"
31
33
  LINK_PATH="$LINK_DIR/pinggy"
32
34
  RC_MARKER="# Added by the Pinggy installer"
@@ -197,8 +199,8 @@ remove_partial_download() {
197
199
  fi
198
200
  }
199
201
 
200
- # Writes the binary to a temp file in the install directory, so the final mv is a rename on 1 filesystem. A
201
- # running agent keeps the old inode, so replacing the file under it is safe.
202
+ # Writes the binary to a temp file under ~/.pinggy, so the final mv is a rename on 1 filesystem. The binary goes in its
203
+ # own version folder and ~/.pinggy/bin/pinggy links to it. A running agent keeps its own file.
202
204
  install_binary() {
203
205
  if [ -n "${PINGGY_BINARY_URL:-}" ]; then
204
206
  url="$PINGGY_BINARY_URL"
@@ -221,11 +223,29 @@ install_binary() {
221
223
  fail_does_not_run
222
224
  fi
223
225
 
224
- mv -f "$download_path" "$INSTALL_PATH"
226
+ previous_target=$(readlink "$INSTALL_PATH" 2>/dev/null || true)
227
+ mkdir -p "$VERSIONS_DIR/$downloaded_version"
228
+ mv -f "$download_path" "$VERSIONS_DIR/$downloaded_version/pinggy"
225
229
  download_path=""
230
+ # A temp link and a rename, because ln -sf removes the old link before it creates the new one.
231
+ ln -s "$VERSIONS_DIR/$downloaded_version/pinggy" "$INSTALL_DIR/pinggy.link.$$"
232
+ mv -f "$INSTALL_DIR/pinggy.link.$$" "$INSTALL_PATH"
233
+ prune_versions "$downloaded_version" "$(basename "$(dirname "${previous_target:-none}")")"
226
234
  say "Installed pinggy $downloaded_version to $(shown "$INSTALL_PATH")"
227
235
  }
228
236
 
237
+ # Keeps the new version and the one the link named before. Only names made of digits and dots are versions. With
238
+ # auto-update off, nothing else removes old versions.
239
+ prune_versions() {
240
+ for version_dir in "$VERSIONS_DIR"/*/; do
241
+ version_name=$(basename "$version_dir")
242
+ case "$version_name" in
243
+ *[!0-9.]* | "$1" | "$2") continue ;;
244
+ esac
245
+ rm -rf "$version_dir"
246
+ done
247
+ }
248
+
229
249
  # Steps 2 to 6 of the plan: compare with the installed binary, then download only when needed.
230
250
  install_or_update() {
231
251
  if [ -n "${PINGGY_BINARY_URL:-}" ]; then
@@ -255,6 +275,14 @@ install_or_update() {
255
275
  install_binary
256
276
  else
257
277
  say "Keeping pinggy $installed_version."
278
+ kept_older_version=1
279
+ fi
280
+ }
281
+
282
+ # A pinned or kept version lasts only until the next terminal command, unless auto-update is off.
283
+ warn_auto_update_replaces_it() {
284
+ if [ -n "${PINGGY_VERSION:-}" ] || [ "${kept_older_version:-0}" = 1 ]; then
285
+ say "Auto-update replaces this version. Set PINGGY_AUTO_UPDATE=false to keep it."
258
286
  fi
259
287
  }
260
288
 
@@ -333,17 +361,64 @@ add_link_dir_to_rc_file() {
333
361
  say "In this terminal, run: source $(shown "$rc_file")"
334
362
  }
335
363
 
364
+ # The service file `pinggy daemon service-install` writes. Its paths live in src/daemon/lifecycle/serviceInstaller.ts.
365
+ # The service counts only when it runs the binary this script installs. A service left by a pinggy elsewhere gets the
366
+ # question, and service-install replaces it.
367
+ login_service_installed() {
368
+ case "$os" in
369
+ macos) service_file="$HOME/Library/LaunchAgents/io.pinggy.agent.plist" ;;
370
+ linux) service_file="$HOME/.config/systemd/user/pinggy.service" ;;
371
+ esac
372
+ [ -f "$service_file" ] && grep -qF "$INSTALL_PATH" "$service_file"
373
+ }
374
+
375
+ # A container or a session with no systemd user manager cannot run the Linux service.
376
+ login_service_supported() {
377
+ if [ "$os" = macos ]; then
378
+ return 0
379
+ fi
380
+ has_command systemctl && systemctl --user show-environment >/dev/null 2>&1
381
+ }
382
+
383
+ # Asks once the device connects, so the agent starts again after a restart. Leaves an installed service as it is.
384
+ offer_login_service() {
385
+ if login_service_installed || ! login_service_supported; then
386
+ return 0
387
+ fi
388
+ if ! has_terminal; then
389
+ say "To start pinggy when this computer starts, run: pinggy daemon service-install"
390
+ return 0
391
+ fi
392
+
393
+ say ""
394
+ if ! confirm "Start pinggy automatically when this computer starts? [Y/n] "; then
395
+ say "To start pinggy when this computer starts, run: pinggy daemon service-install"
396
+ return 0
397
+ fi
398
+ if ! "$INSTALL_PATH" daemon service-install </dev/null; then
399
+ say "Could not set up the login service. To try again, run: pinggy daemon service-install"
400
+ fi
401
+ }
402
+
336
403
  # Runs the installed file by its full path, so an npm-installed pinggy earlier on PATH does not answer. connect reads
337
404
  # DEVICE_AGENT_TOKEN from the environment this script passes on, and reads no key, so it runs the same with no
338
405
  # terminal. -b is the default now. It is passed anyway, so an older pinggy the user kept runs the agent in its daemon
339
- # too.
406
+ # too. The token leaves the environment before the service question, so no later command inherits it.
340
407
  connect_with_device_token() {
341
408
  export DEVICE_AGENT_TOKEN
342
409
  say ""
410
+ status=0
343
411
  if [ -n "${PINGGY_MANAGE:-}" ]; then
344
- exec "$INSTALL_PATH" device connect -b --manage "$PINGGY_MANAGE" </dev/null
412
+ "$INSTALL_PATH" device connect -b --manage "$PINGGY_MANAGE" </dev/null || status=$?
413
+ else
414
+ "$INSTALL_PATH" device connect -b </dev/null || status=$?
345
415
  fi
346
- exec "$INSTALL_PATH" device connect -b </dev/null
416
+ unset DEVICE_AGENT_TOKEN
417
+ if [ "$status" -ne 0 ]; then
418
+ exit "$status"
419
+ fi
420
+ offer_login_service
421
+ exit 0
347
422
  }
348
423
 
349
424
  # Runs the installed file by its full path, so an npm-installed pinggy earlier on PATH does not answer. -b as above.
@@ -361,10 +436,21 @@ start_sign_in() {
361
436
  fi
362
437
 
363
438
  say ""
439
+ if ! confirm "Connect this device to Pinggy? [Y/n] "; then
440
+ say "Installed. To connect this device later, run: $login_command"
441
+ return 0
442
+ fi
443
+
444
+ status=0
364
445
  if [ -n "${PINGGY_MANAGE:-}" ]; then
365
- exec "$INSTALL_PATH" device login -b --manage "$PINGGY_MANAGE" </dev/tty
446
+ "$INSTALL_PATH" device login -b --manage "$PINGGY_MANAGE" </dev/tty || status=$?
447
+ else
448
+ "$INSTALL_PATH" device login -b </dev/tty || status=$?
449
+ fi
450
+ if [ "$status" -ne 0 ]; then
451
+ exit "$status"
366
452
  fi
367
- exec "$INSTALL_PATH" device login -b </dev/tty
453
+ offer_login_service
368
454
  }
369
455
 
370
456
  main() {
@@ -378,6 +464,7 @@ main() {
378
464
  *) require_downloader ;;
379
465
  esac
380
466
  install_or_update
467
+ warn_auto_update_replaces_it
381
468
  link_into_path
382
469
  if has_device_token; then
383
470
  connect_with_device_token
@@ -1,9 +0,0 @@
1
- import {
2
- readDaemonConfig,
3
- writeDaemonConfig
4
- } from "./chunk-PD7HXVQ3.js";
5
- import "./chunk-AFMTIELL.js";
6
- export {
7
- readDaemonConfig,
8
- writeDaemonConfig
9
- };