pinggy 0.6.7 → 0.6.9

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/dist/index.d.cts CHANGED
@@ -257,9 +257,8 @@ declare class TunnelManager implements ITunnelManager {
257
257
  */
258
258
  getAllTunnels(): Promise<TunnelList[]>;
259
259
  /**
260
- * Re-apply the given log level to every live tunnel's worker JS logger.
261
- * Native libpinggy level is fixed at worker init and cannot be re-pathed
262
- * or re-levelled at runtime without restarting the tunnel.
260
+ * Re-apply the given log level, and the tunnel-logging switch, to every live tunnel's worker
261
+ * JS logger. libpinggy has no log level at runtime, only on or off (see nativeLog.ts).
263
262
  */
264
263
  applyLogLevelToActiveTunnels(level: string): void;
265
264
  /**
@@ -1160,6 +1159,8 @@ interface DaemonInfo {
1160
1159
  ipcVersion?: number;
1161
1160
  /** The version this daemon started with. It never follows the installed binary. Absent in older builds. */
1162
1161
  cliVersion?: string;
1162
+ /** The OS boot ID when this daemon started. Absent in older builds, and where the OS gives none. */
1163
+ bootId?: string;
1163
1164
  }
1164
1165
 
1165
1166
  type StatsCallback = (tunnelId: string, stats: TunnelUsageType) => void;
package/dist/index.d.ts CHANGED
@@ -257,9 +257,8 @@ declare class TunnelManager implements ITunnelManager {
257
257
  */
258
258
  getAllTunnels(): Promise<TunnelList[]>;
259
259
  /**
260
- * Re-apply the given log level to every live tunnel's worker JS logger.
261
- * Native libpinggy level is fixed at worker init and cannot be re-pathed
262
- * or re-levelled at runtime without restarting the tunnel.
260
+ * Re-apply the given log level, and the tunnel-logging switch, to every live tunnel's worker
261
+ * JS logger. libpinggy has no log level at runtime, only on or off (see nativeLog.ts).
263
262
  */
264
263
  applyLogLevelToActiveTunnels(level: string): void;
265
264
  /**
@@ -1160,6 +1159,8 @@ interface DaemonInfo {
1160
1159
  ipcVersion?: number;
1161
1160
  /** The version this daemon started with. It never follows the installed binary. Absent in older builds. */
1162
1161
  cliVersion?: string;
1162
+ /** The OS boot ID when this daemon started. Absent in older builds, and where the OS gives none. */
1163
+ bootId?: string;
1163
1164
  }
1164
1165
 
1165
1166
  type StatsCallback = (tunnelId: string, stats: TunnelUsageType) => void;
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  getRemoteManagementState,
10
10
  initiateRemoteManagement,
11
11
  startRemoteManagement
12
- } from "./chunk-H527WMTF.js";
12
+ } from "./chunk-Q5RYSWFK.js";
13
13
  import "./chunk-MHQ3CVEB.js";
14
14
  import {
15
15
  bulkReplace,
@@ -28,15 +28,15 @@ import {
28
28
  validateName,
29
29
  validateNameForStorage,
30
30
  validateNameStrict
31
- } from "./chunk-2GIJXE4K.js";
31
+ } from "./chunk-3IPMFCEF.js";
32
32
  import {
33
33
  TunnelManager
34
- } from "./chunk-3WMTTJHI.js";
34
+ } from "./chunk-5HBGVJSW.js";
35
35
  import "./chunk-UB26QJ4T.js";
36
36
  import {
37
37
  getDaemonInfo,
38
38
  isDaemonRunning
39
- } from "./chunk-3KCXR33Y.js";
39
+ } from "./chunk-OQVFQ5VG.js";
40
40
  import {
41
41
  DeviceAgentState
42
42
  } from "./chunk-MKGD2QAI.js";
@@ -48,13 +48,13 @@ import {
48
48
  } from "./chunk-HTIWY3O5.js";
49
49
  import {
50
50
  enablePackageLogging
51
- } from "./chunk-LWCVB42S.js";
51
+ } from "./chunk-DGAH7UVX.js";
52
52
  import {
53
53
  ensureTunnelConfigDir,
54
54
  getDaemonInfoPath,
55
55
  getPinggyConfigDir,
56
56
  getTunnelConfigDir
57
- } from "./chunk-MAK5R4WQ.js";
57
+ } from "./chunk-WFHMERT3.js";
58
58
 
59
59
  // src/utils/detect_vc_redist_on_windows.ts
60
60
  import fs from "fs";
@@ -146,7 +146,7 @@ async function verifyAndLoad() {
146
146
  process.exit(1);
147
147
  }
148
148
  }
149
- await import("./main-HSIFQAGU.js");
149
+ await import("./main-INPCUGAN.js");
150
150
  }
151
151
  verifyAndLoad().catch((err) => {
152
152
  printer_default.fatal(`Failed to start CLI:, ${err}`);
@@ -1,38 +1,38 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  runDaemonChild
4
- } from "./chunk-FWTQF6AB.js";
4
+ } from "./chunk-LF6WMFWT.js";
5
5
  import {
6
6
  RemoteManagementUnauthorizedError,
7
7
  TunnelOperations,
8
8
  closeRemoteManagement,
9
9
  getRemoteManagementState,
10
10
  initiateRemoteManagement
11
- } from "./chunk-H527WMTF.js";
12
- import "./chunk-CZOKR73F.js";
11
+ } from "./chunk-Q5RYSWFK.js";
12
+ import "./chunk-VD5ZFCZW.js";
13
13
  import "./chunk-MHQ3CVEB.js";
14
- import "./chunk-2GIJXE4K.js";
14
+ import "./chunk-3IPMFCEF.js";
15
15
  import "./chunk-XZ64ZAGO.js";
16
16
  import {
17
17
  TunnelManager
18
- } from "./chunk-3WMTTJHI.js";
18
+ } from "./chunk-5HBGVJSW.js";
19
19
  import "./chunk-UB26QJ4T.js";
20
- import "./chunk-PMZJ6HFH.js";
20
+ import "./chunk-HJECJ7LC.js";
21
21
  import {
22
22
  ensureDaemonRunning,
23
23
  getActiveTunnelSummaries,
24
24
  getDaemonInfo,
25
25
  getInProcessDaemonHandle,
26
26
  isDaemonRunning
27
- } from "./chunk-3KCXR33Y.js";
27
+ } from "./chunk-OQVFQ5VG.js";
28
28
  import {
29
29
  DaemonHost
30
30
  } from "./chunk-MKGD2QAI.js";
31
31
  import "./chunk-HTIWY3O5.js";
32
32
  import {
33
33
  enablePackageLogging
34
- } from "./chunk-LWCVB42S.js";
35
- import "./chunk-MAK5R4WQ.js";
34
+ } from "./chunk-DGAH7UVX.js";
35
+ import "./chunk-WFHMERT3.js";
36
36
  export {
37
37
  DaemonHost,
38
38
  RemoteManagementUnauthorizedError,
@@ -16,7 +16,7 @@ import {
16
16
  resolveLatestTag,
17
17
  runPinggyBinary,
18
18
  versionFromTag
19
- } from "./chunk-PMZJ6HFH.js";
19
+ } from "./chunk-HJECJ7LC.js";
20
20
  import {
21
21
  InstallKind,
22
22
  backgroundInstallKind,
@@ -30,17 +30,17 @@ import {
30
30
  recordLatestVersion,
31
31
  unixLayoutPaths,
32
32
  writeUpdateState
33
- } from "./chunk-3KCXR33Y.js";
33
+ } from "./chunk-OQVFQ5VG.js";
34
34
  import "./chunk-MKGD2QAI.js";
35
35
  import {
36
36
  errorMessage,
37
37
  getVersion
38
38
  } from "./chunk-HTIWY3O5.js";
39
- import "./chunk-LWCVB42S.js";
39
+ import "./chunk-DGAH7UVX.js";
40
40
  import {
41
41
  ensurePinggyLogDir,
42
42
  getUpdateLogPath
43
- } from "./chunk-MAK5R4WQ.js";
43
+ } from "./chunk-WFHMERT3.js";
44
44
 
45
45
  // src/update/updateChild.ts
46
46
  import fs from "fs";
@@ -3,7 +3,7 @@ import {
3
3
  } from "../chunk-UB26QJ4T.js";
4
4
  import {
5
5
  logger
6
- } from "../chunk-LWCVB42S.js";
6
+ } from "../chunk-DGAH7UVX.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.7",
3
+ "version": "0.6.9",
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. ",
@@ -49,7 +49,9 @@
49
49
  "node_modules/blessed/lib/**/*",
50
50
  "node_modules/blessed/usr/**/*",
51
51
  "node_modules/node-pty/build/Release/pty.node",
52
- "dist/workers/**/*"
52
+ "dist/workers/**/*",
53
+ "scripts/install/install.sh",
54
+ "scripts/install/install.ps1"
53
55
  ],
54
56
  "ignore": [
55
57
  "**/node_modules/node-pty/prebuilds/**/*.pdb",
@@ -1,21 +1,35 @@
1
1
  # Installs or updates the Pinggy CLI on Windows, then asks whether to sign this machine in as a Pinggy device.
2
2
  # Once the device connects, it asks whether to start pinggy at login, unless that task is already registered.
3
+ # Before the sign-in, when a pinggy daemon runs another version than the installed one, it asks to restart the daemon.
3
4
  #
4
5
  # irm https://pinggy.io/install.ps1 | iex
5
6
  # $env:DEVICE_AGENT_TOKEN='<token>'; irm https://pinggy.io/install.ps1 | iex
6
7
  #
8
+ # It updates the copy that the pinggy command runs in this window:
9
+ # no copy, or this script's binary installs or updates the binary, as below
10
+ # an npm copy updates it with `npm install -g`. No binary, no PATH change, and no login
11
+ # task question, because the npm version cannot run as a service
12
+ # another pinggy.exe asks to install this script's binary. No signs in with that file
13
+ # a script (npm link, pnpm, yarn, bun) stops with a message
14
+ #
7
15
  # The binary goes to %LOCALAPPDATA%\Pinggy\bin\pinggy.exe, and that directory goes on the user PATH. No admin.
8
16
  #
9
17
  # Setting, from the dashboard's command:
10
- # $env:DEVICE_AGENT_TOKEN a device token. An older pinggy updates without asking, then `pinggy device connect`
11
- # runs with no email and no code. The token reaches it in its environment, never on a
12
- # command line. The script removes the variable from this window when it ends
18
+ # $env:DEVICE_AGENT_TOKEN a device token. `pinggy device connect` runs with no email and no code. Every update
19
+ # question is still asked, and a pinggy older than 0.6.2 ignores the token. The token
20
+ # reaches the CLI in its environment, never on a command line. The script removes the
21
+ # variable from this window when it ends
13
22
  #
14
23
  # Overrides, for dev and tests:
15
- # $env:PINGGY_VERSION a release tag, such as v0.6.1. Default: the version pinggy.io publishes
16
- # $env:PINGGY_BINARY_URL a full binary URL, file:// included. Replaces the installed binary without a version check
24
+ # $env:PINGGY_VERSION a release tag, such as v0.6.1. Default: the version pinggy.io publishes, or for an npm
25
+ # copy the npm registry's latest
26
+ # $env:PINGGY_BINARY_URL a full binary URL, file:// included. Replaces the installed binary without a version check,
27
+ # whatever the pinggy command runs
17
28
  # $env:PINGGY_MANAGE a non-production dashboard host, passed to `pinggy device login` or `connect` as --manage
18
29
  #
30
+ # Set by a downloaded pinggy.exe that installs itself, with PINGGY_BINARY_URL naming that file:
31
+ # $env:PINGGY_INSTALL_ONLY 1: install, then end, with no sign-in
32
+ #
19
33
  # The source lives in Pinggy-io/cli-js, scripts/install/. A release copies it to pinggy.io.
20
34
  #
21
35
  # iex runs this inside the user's own session. So it never calls exit, which would close their window, and every
@@ -36,10 +50,22 @@ function Install-Pinggy {
36
50
  $installPath = Join-Path $installDir 'pinggy.exe'
37
51
  $versionPattern = 'Pinggy CLI version:\s*(\S+)'
38
52
  $autoUpdatePinLine = 'Auto-update replaces this version. Set PINGGY_AUTO_UPDATE=false to keep it.'
53
+ $npmPackage = 'pinggy'
54
+ # The file a running daemon writes. Its path lives in src/utils/configDir.ts.
55
+ $daemonInfoPath = Join-Path $env:APPDATA 'pinggy\daemon.json'
39
56
  # The task `pinggy daemon service-install` registers. Its name lives in src/daemon/lifecycle/serviceInstaller.ts.
40
57
  $loginTaskName = 'PinggyDaemon'
41
58
  $cpuArchitectureX64 = 9
42
59
  $cpuArchitectureArm64 = 12
60
+ # Windows PowerShell 5.1 has no stall check, so a limit on the total time stands in. A healthy request ends in
61
+ # under 1 s, so the limit ends only a stalled one.
62
+ $versionRequestTimeoutSeconds = 60
63
+ # Every daemon process runs with this flag (getDaemonSpawnArgs() in src/daemon/lifecycle/daemonManager.ts).
64
+ $daemonProcessFlag = '--_daemon-child'
65
+ # How long a restarted daemon may take to stop, and then to write daemon.json.
66
+ $daemonRestartWaitSeconds = 10
67
+ # PowerShell 5.1 has no &&. `pinggy daemon stop` waits for the exit before it returns.
68
+ $daemonRestartCommand = 'pinggy daemon stop; pinggy daemon start'
43
69
 
44
70
  # Win32_Processor describes the machine. PROCESSOR_ARCHITECTURE describes this process, and reads AMD64 in an
45
71
  # x64 PowerShell emulated on ARM64.
@@ -68,8 +94,9 @@ function Install-Pinggy {
68
94
  return "v$($env:PINGGY_VERSION)"
69
95
  }
70
96
  $retryHint = 'Try again later, or set $env:PINGGY_VERSION to a release tag, such as v0.6.1.'
97
+ Write-Host 'Checking the latest version of Pinggy...'
71
98
  try {
72
- $latest = Invoke-RestMethod -Uri $versionUrl -UseBasicParsing
99
+ $latest = Invoke-RestMethod -Uri $versionUrl -UseBasicParsing -TimeoutSec $versionRequestTimeoutSeconds
73
100
  } catch {
74
101
  throw "pinggy install: could not reach $versionUrl. $retryHint"
75
102
  }
@@ -97,9 +124,9 @@ function Install-Pinggy {
97
124
  return [Environment]::UserInteractive -and -not [Console]::IsInputRedirected
98
125
  }
99
126
 
100
- # Enter, or no terminal, means yes. Only an answer starting with n means no.
101
- function Confirm-Question([string] $question) {
102
- if (-not (Test-Interactive)) { return $true }
127
+ # Enter means yes. Only an answer starting with n means no. With no terminal, the answer is $noTerminalAnswer.
128
+ function Confirm-Question([string] $question, [bool] $noTerminalAnswer = $true) {
129
+ if (-not (Test-Interactive)) { return $noTerminalAnswer }
103
130
  $answer = Read-Host $question
104
131
  return -not ($answer -match '^\s*n')
105
132
  }
@@ -135,7 +162,11 @@ function Install-Pinggy {
135
162
  New-Item -ItemType Directory -Force -Path $installDir | Out-Null
136
163
  $newPath = "$installPath.new.exe"
137
164
 
138
- Write-Host "Downloading $url"
165
+ if ($url -like 'file://*') {
166
+ Write-Host "Copying $(([Uri] $url).LocalPath)"
167
+ } else {
168
+ Write-Host "Downloading $url"
169
+ }
139
170
  try {
140
171
  try {
141
172
  Save-Binary $url $newPath
@@ -174,10 +205,6 @@ function Install-Pinggy {
174
205
  Install-Binary $tag $cpu
175
206
  } elseif ($installedVersion -eq $targetVersion) {
176
207
  Write-Host "pinggy $installedVersion is up to date."
177
- } elseif ($env:DEVICE_AGENT_TOKEN) {
178
- # An older CLI ignores DEVICE_AGENT_TOKEN, so keeping it would leave the machine unconnected.
179
- Write-Host "Updating pinggy $installedVersion to $targetVersion."
180
- Install-Binary $tag $cpu
181
208
  } elseif (Confirm-Question "pinggy $installedVersion is installed. Update to $($targetVersion)? [Y/n]") {
182
209
  Install-Binary $tag $cpu
183
210
  } else {
@@ -186,6 +213,152 @@ function Install-Pinggy {
186
213
  }
187
214
  }
188
215
 
216
+ function Install-WithBinary {
217
+ $cpu = Get-Cpu
218
+ Install-OrUpdate $cpu
219
+ if ($env:PINGGY_VERSION) { Write-Host $autoUpdatePinLine }
220
+ Add-InstallDirToPath
221
+ }
222
+
223
+ # For a pinggy.exe this script did not install: installs the latest only when this script's binary is older.
224
+ function Install-LatestBinary([string] $tag, [string] $cpu) {
225
+ $targetVersion = $tag.Substring(1)
226
+ if ((Get-BinaryVersion $installPath) -eq $targetVersion) {
227
+ Write-Host "pinggy $targetVersion is up to date in $installPath."
228
+ } else {
229
+ Install-Binary $tag $cpu
230
+ }
231
+ if ($env:PINGGY_VERSION) { Write-Host $autoUpdatePinLine }
232
+ Add-InstallDirToPath
233
+ }
234
+
235
+ # A registry install from npm keeps the package at <launcher folder>\node_modules\pinggy. `npm link` puts a
236
+ # junction there instead, to a source checkout.
237
+ function Test-NpmPackageFolder([string] $folder) {
238
+ $packageDir = Join-Path $folder "node_modules\$npmPackage"
239
+ if (-not (Test-Path -LiteralPath (Join-Path $packageDir 'package.json') -PathType Leaf)) { return $false }
240
+ return -not (Get-Item -LiteralPath $packageDir -Force).LinkType
241
+ }
242
+
243
+ # The copy the pinggy command runs in this window. Kind is none, binary (this script's), npm, otherBinary or
244
+ # otherScript. npm, pnpm and yarn write launcher files, not links. bun's launcher is a pinggy.exe beside a
245
+ # pinggy.bunx, so it counts as a script.
246
+ function Find-PinggyCommand {
247
+ $command = Get-Command -Name 'pinggy' -CommandType Application, ExternalScript -ErrorAction SilentlyContinue |
248
+ Select-Object -First 1
249
+ if (-not $command) { return [pscustomobject]@{ Kind = 'none'; Path = ''; Folder = '' } }
250
+ $path = $command.Path
251
+ $folder = Split-Path -Parent $path
252
+ if ($path -ieq $installPath) {
253
+ $kind = 'binary'
254
+ } elseif (Test-NpmPackageFolder $folder) {
255
+ $kind = 'npm'
256
+ } elseif ($path -like '*.exe' -and -not (Test-Path -LiteralPath (Join-Path $folder 'pinggy.bunx'))) {
257
+ $kind = 'otherBinary'
258
+ } else {
259
+ $kind = 'otherScript'
260
+ }
261
+ return [pscustomobject]@{ Kind = $kind; Path = $path; Folder = $folder }
262
+ }
263
+
264
+ # npm.cmd and pinggy.cmd, not npm and pinggy: PowerShell picks the .ps1 launcher first, and an execution policy
265
+ # that blocks scripts blocks it.
266
+ function New-NpmCopy($found) {
267
+ $npmCommand = Get-Command -Name 'npm.cmd' -CommandType Application -ErrorAction SilentlyContinue |
268
+ Select-Object -First 1
269
+ $launcher = Join-Path $found.Folder 'pinggy.cmd'
270
+ if (-not (Test-Path -LiteralPath $launcher)) { $launcher = $found.Path }
271
+ return [pscustomobject]@{
272
+ Path = $found.Path
273
+ Folder = $found.Folder
274
+ Npm = $(if ($npmCommand) { $npmCommand.Path } else { '' })
275
+ Launcher = $launcher
276
+ }
277
+ }
278
+
279
+ # npm publish runs as a separate job from the binaries, so the registry can name an older version than
280
+ # pinggy.io. npm install -g reads the registry, so the target comes from there.
281
+ function Get-NpmTargetVersion([string] $npm) {
282
+ if ($env:PINGGY_VERSION) { return $env:PINGGY_VERSION.TrimStart('v') }
283
+ Write-Host 'Checking the latest version of pinggy on npm...'
284
+ $ErrorActionPreference = 'Continue'
285
+ $version = (& $npm view $npmPackage version 2>$null | Out-String).Trim()
286
+ if ($LASTEXITCODE -ne 0 -or -not $version) {
287
+ throw 'pinggy install: could not read the latest pinggy version from the npm registry. Try again later.'
288
+ }
289
+ return $version
290
+ }
291
+
292
+ # The fields of daemon.json while its process runs, or $null. pinggy daemon status exits 0 either way, so the
293
+ # script reads the file the daemon writes and checks its process.
294
+ function Get-RunningDaemon {
295
+ try {
296
+ $daemonInfo = Get-Content -LiteralPath $daemonInfoPath -Raw | ConvertFrom-Json
297
+ Get-Process -Id ([int] $daemonInfo.pid) -ErrorAction Stop | Out-Null
298
+ return $daemonInfo
299
+ } catch {
300
+ return $null
301
+ }
302
+ }
303
+
304
+ # Out-Host keeps npm's lines out of the output stream, as Write-Host does for messages.
305
+ function Invoke-NpmInstall($npmCopy, [string] $packageSpec) {
306
+ Write-Host "Running: npm install -g --prefix $($npmCopy.Folder) $packageSpec"
307
+ $ErrorActionPreference = 'Continue'
308
+ & $npmCopy.Npm install -g --prefix $npmCopy.Folder --no-fund --no-audit $packageSpec | Out-Host
309
+ return $LASTEXITCODE -eq 0
310
+ }
311
+
312
+ # Windows blocks replacing a file that a running program has open, so a running pinggy can fail the update. With
313
+ # no terminal, the script keeps pinggy and its tunnels running.
314
+ function Install-NpmPackage($npmCopy, [string] $version) {
315
+ $packageSpec = "$npmPackage@$version"
316
+ $failure = "pinggy install: npm could not install $packageSpec. npm printed the reason above."
317
+ if (-not (Invoke-NpmInstall $npmCopy $packageSpec)) {
318
+ if (-not (Get-RunningDaemon)) { throw $failure }
319
+ if (-not (Confirm-Question 'pinggy is running. Stop it and all its tunnels, then retry? [Y/n]' $false)) {
320
+ throw "$failure If pinggy is running, run: pinggy daemon stop, then run this script again."
321
+ }
322
+ & $npmCopy.Launcher daemon stop | Out-Host
323
+ if (-not (Invoke-NpmInstall $npmCopy $packageSpec)) { throw $failure }
324
+ }
325
+ Write-Host "Installed pinggy $version with npm"
326
+ }
327
+
328
+ # The same questions as for the binary, with versions from npm's copy and the npm registry. Auto-update leaves an
329
+ # npm install alone, so a kept version gets no auto-update line.
330
+ function Update-NpmCopy($npmCopy) {
331
+ if (-not $npmCopy.Npm) {
332
+ throw "pinggy install: pinggy at $($npmCopy.Path) came from npm, but npm is not on PATH."
333
+ }
334
+ $targetVersion = Get-NpmTargetVersion $npmCopy.Npm
335
+ $installedVersion = Get-BinaryVersion $npmCopy.Launcher
336
+ if (-not $installedVersion) {
337
+ if (-not (Confirm-Question "$($npmCopy.Launcher) does not run. Reinstall it with npm? [Y/n]")) {
338
+ throw "pinggy install: $($npmCopy.Launcher) does not run, so it cannot sign in this device."
339
+ }
340
+ Install-NpmPackage $npmCopy $targetVersion
341
+ } elseif ($installedVersion -eq $targetVersion) {
342
+ Write-Host "pinggy $installedVersion, installed with npm, is up to date."
343
+ } elseif (Confirm-Question ("pinggy $installedVersion is installed with npm. " +
344
+ "Update to $($targetVersion)? [Y/n]")) {
345
+ Install-NpmPackage $npmCopy $targetVersion
346
+ } else {
347
+ Write-Host "Keeping pinggy $installedVersion."
348
+ }
349
+ }
350
+
351
+ # A pinggy.exe this script did not install, such as one downloaded by hand. Returns whether the user said yes.
352
+ function Confirm-BinaryOverOtherCopy([string] $otherPath, [string] $targetVersion) {
353
+ $otherVersion = Get-BinaryVersion $otherPath
354
+ if ($otherVersion) {
355
+ Write-Host "pinggy $otherVersion at $otherPath was not installed by this script."
356
+ } else {
357
+ Write-Host "$otherPath was not installed by this script."
358
+ }
359
+ return Confirm-Question "Install the latest pinggy, $targetVersion, to $($installPath)? [Y/n]"
360
+ }
361
+
189
362
  function Test-PathListHasInstallDir([string] $pathList) {
190
363
  $wanted = $installDir.TrimEnd('\')
191
364
  foreach ($entry in ($pathList -split ';')) {
@@ -229,7 +402,9 @@ function Install-Pinggy {
229
402
  }
230
403
 
231
404
  # Asks once the device connects, so the agent starts again after a restart. Leaves a registered task as it is.
405
+ # `pinggy daemon service-install` runs only from this script's binary, so another copy skips the question.
232
406
  function Invoke-LoginServiceOffer {
407
+ if ($skipLoginService) { return }
233
408
  if (Test-LoginTask) { return }
234
409
  if (-not (Test-Interactive)) {
235
410
  Write-Host 'To start pinggy when this computer starts, run: pinggy daemon service-install'
@@ -246,8 +421,84 @@ function Install-Pinggy {
246
421
  }
247
422
  }
248
423
 
249
- # Runs the installed file by its full path, so an npm-installed pinggy earlier on PATH does not answer. -b is the
250
- # default now. It is passed anyway, so an older pinggy the user kept runs the agent in its daemon too.
424
+ # A daemon.json left by a crash can name a pid that a reboot gave to another program, so the process must run
425
+ # $daemonProcessFlag.
426
+ function Test-DaemonProcess([int] $processId) {
427
+ try {
428
+ $process = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $processId" -ErrorAction Stop
429
+ } catch {
430
+ return $false
431
+ }
432
+ return [bool] ($process -and $process.CommandLine -like "*$daemonProcessFlag*")
433
+ }
434
+
435
+ # A daemon copies the environment of the command that starts it, so DEVICE_AGENT_TOKEN leaves for the restart and
436
+ # comes back for `device connect`. `pinggy daemon stop` exits 0 when the stop fails, so the script waits for the
437
+ # process itself before `daemon start`. Windows has no service that owns the daemon: the login task runs
438
+ # `daemon start` and ends.
439
+ function Restart-Daemon([int] $oldPid) {
440
+ $deviceToken = $env:DEVICE_AGENT_TOKEN
441
+ Remove-Item -Path Env:\DEVICE_AGENT_TOKEN -ErrorAction SilentlyContinue
442
+ $ErrorActionPreference = 'Continue'
443
+ try {
444
+ & $pinggyPath daemon stop | Out-Null
445
+ Wait-Process -Id $oldPid -Timeout $daemonRestartWaitSeconds -ErrorAction SilentlyContinue
446
+ if (-not (Get-Process -Id $oldPid -ErrorAction SilentlyContinue)) {
447
+ & $pinggyPath daemon start | Out-Null
448
+ }
449
+ } finally {
450
+ if ($deviceToken) { $env:DEVICE_AGENT_TOKEN = $deviceToken }
451
+ }
452
+ }
453
+
454
+ # True once daemon.json names a daemon other than $oldPid that runs $version.
455
+ function Wait-NewDaemon([int] $oldPid, [string] $version) {
456
+ for ($second = 0; $second -lt $daemonRestartWaitSeconds; $second++) {
457
+ $daemon = Get-RunningDaemon
458
+ if ($daemon -and [int] $daemon.pid -ne $oldPid -and [string] $daemon.cliVersion -eq $version) {
459
+ return $true
460
+ }
461
+ Start-Sleep -Seconds 1
462
+ }
463
+ return $false
464
+ }
465
+
466
+ # A daemon keeps the version it started with. When it runs another version than $pinggyPath, the copy this script
467
+ # signs in with, the script asks to restart it, so the device agent and auto-start tunnels run the new version.
468
+ # The Pinggy app's daemon belongs to the app, which refuses /shutdown. A daemon.json with no cliVersion comes from
469
+ # an older build, so it differs.
470
+ function Invoke-DaemonRestartOffer {
471
+ $daemon = Get-RunningDaemon
472
+ if (-not $daemon -or $daemon.host -eq 'app' -or -not (Test-DaemonProcess ([int] $daemon.pid))) { return }
473
+ $newVersion = Get-BinaryVersion $pinggyPath
474
+ $runningVersion = [string] $daemon.cliVersion
475
+ if (-not $newVersion -or $runningVersion -eq $newVersion) { return }
476
+ if (-not $runningVersion) { $runningVersion = 'an older version' }
477
+
478
+ Write-Host ''
479
+ # Confirm-Question takes no terminal as yes, and a restart stops tunnels.
480
+ if (-not (Test-Interactive)) {
481
+ Write-Host ("The pinggy daemon still runs $runningVersion. " +
482
+ "To restart it with $newVersion, run: $daemonRestartCommand")
483
+ return
484
+ }
485
+ Write-Host ("The pinggy daemon still runs $runningVersion. Restarting it stops its tunnels. " +
486
+ 'Auto-start tunnels and the device agent start again.')
487
+ if (-not (Confirm-Question "Restart it with $($newVersion)? [Y/n]")) {
488
+ Write-Host "To restart it later, run: $daemonRestartCommand"
489
+ return
490
+ }
491
+ Restart-Daemon ([int] $daemon.pid)
492
+ if (Wait-NewDaemon ([int] $daemon.pid) $newVersion) {
493
+ Write-Host "The pinggy daemon now runs $newVersion."
494
+ } else {
495
+ Write-Host "Could not restart the pinggy daemon. Run: $daemonRestartCommand"
496
+ }
497
+ }
498
+
499
+ # Runs $pinggyPath, the copy this script installed, updated or kept, by its full path, so another pinggy earlier
500
+ # on PATH does not answer. -b is the default now. It is passed anyway, so an older pinggy the user kept runs the
501
+ # agent in its daemon too.
251
502
  function Invoke-DeviceLogin {
252
503
  $loginArguments = @('device', 'login')
253
504
  if ($env:PINGGY_MANAGE) { $loginArguments += @('--manage', $env:PINGGY_MANAGE) }
@@ -263,18 +514,18 @@ function Install-Pinggy {
263
514
  Write-Host "Installed. To connect this device later, run: pinggy $($loginArguments -join ' ')"
264
515
  return
265
516
  }
266
- & $installPath @loginArguments -b
517
+ & $pinggyPath @loginArguments -b
267
518
  if ($LASTEXITCODE -eq 0) { Invoke-LoginServiceOffer }
268
519
  }
269
520
 
270
- # Runs the installed file by its full path, with -b, as Invoke-DeviceLogin does. connect reads DEVICE_AGENT_TOKEN
521
+ # Runs $pinggyPath by its full path, with -b, as Invoke-DeviceLogin does. connect reads DEVICE_AGENT_TOKEN
271
522
  # from the environment it inherits, and reads no key, so it runs the same with no console. The token leaves the
272
523
  # environment before the service question, so no later command inherits it.
273
524
  function Invoke-DeviceConnect {
274
525
  $connectArguments = @('device', 'connect', '-b')
275
526
  if ($env:PINGGY_MANAGE) { $connectArguments += @('--manage', $env:PINGGY_MANAGE) }
276
527
  Write-Host ''
277
- & $installPath @connectArguments
528
+ & $pinggyPath @connectArguments
278
529
  $connectExitCode = $LASTEXITCODE
279
530
  Remove-Item -Path Env:\DEVICE_AGENT_TOKEN -ErrorAction SilentlyContinue
280
531
  if ($connectExitCode -eq 0) { Invoke-LoginServiceOffer }
@@ -285,10 +536,37 @@ function Install-Pinggy {
285
536
  [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
286
537
 
287
538
  try {
288
- $cpu = Get-Cpu
289
- Install-OrUpdate $cpu
290
- if ($env:PINGGY_VERSION) { Write-Host $autoUpdatePinLine }
291
- Add-InstallDirToPath
539
+ $pinggyPath = $installPath
540
+ $skipLoginService = $false
541
+ $found = [pscustomobject]@{ Kind = 'none'; Path = ''; Folder = '' }
542
+ if (-not $env:PINGGY_BINARY_URL) { $found = Find-PinggyCommand }
543
+ switch ($found.Kind) {
544
+ 'npm' {
545
+ $npmCopy = New-NpmCopy $found
546
+ Update-NpmCopy $npmCopy
547
+ $pinggyPath = $npmCopy.Launcher
548
+ $skipLoginService = $true
549
+ }
550
+ 'otherBinary' {
551
+ $cpu = Get-Cpu
552
+ $tag = Get-TargetTag
553
+ $targetVersion = $tag.Substring(1)
554
+ if (Confirm-BinaryOverOtherCopy $found.Path $targetVersion) {
555
+ Install-LatestBinary $tag $cpu
556
+ } else {
557
+ Write-Host "Keeping $($found.Path)."
558
+ $pinggyPath = $found.Path
559
+ $skipLoginService = $true
560
+ }
561
+ }
562
+ 'otherScript' {
563
+ throw ("pinggy install: pinggy at $($found.Path) was not installed by this script or npm.`n" +
564
+ 'Update it the way you installed it.')
565
+ }
566
+ default { Install-WithBinary }
567
+ }
568
+ if ($env:PINGGY_INSTALL_ONLY -eq '1') { return }
569
+ Invoke-DaemonRestartOffer
292
570
  if ($env:DEVICE_AGENT_TOKEN) {
293
571
  Invoke-DeviceConnect
294
572
  } else {