@lethevimlet/sshift 0.9.5 → 0.9.7

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.
@@ -0,0 +1,1101 @@
1
+ # sshift Installation Script for Windows
2
+ # Installs Node.js (if not present) and installs sshift via npm
3
+ # Checks for updates and restarts the app if needed
4
+ #
5
+ # Usage: ./sshift-install.ps1 [OPTIONS]
6
+ # -installDir DIR Installation directory (default: ~/.local/share/sshift)
7
+ # -port PORT Server port (default: 8022)
8
+ # -start Start sshift after installation/update
9
+ # -stop Stop running sshift instance
10
+ # -restart Restart sshift
11
+ # -status Check if sshift is running
12
+ # -update Update existing installation (non-interactive)
13
+ # -uninstall Remove sshift from the system
14
+ # -help Show this help message
15
+
16
+ param(
17
+ [string]$installDir = "",
18
+ [string]$port = "",
19
+ [switch]$start,
20
+ [switch]$stop,
21
+ [switch]$restart,
22
+ [switch]$status,
23
+ [switch]$uninstall,
24
+ [switch]$update,
25
+ [switch]$help
26
+ )
27
+
28
+ # Configuration (defaults, can be overridden by arguments)
29
+ $NodeVersion = "20"
30
+ $NpmPackage = "@lethevimlet/sshift"
31
+ if ($installDir -eq "") {
32
+ $installDir = "$env:USERPROFILE\.local\share\sshift"
33
+ }
34
+ $BinDir = Split-Path $installDir -Parent
35
+ $BinDir = Join-Path $BinDir "bin"
36
+ $PidFile = "$env:TEMP\sshift.pid"
37
+ $ServiceName = "sshift"
38
+ $ServerPort = $port
39
+
40
+ # Show help message
41
+ function Show-Help {
42
+ Write-Host "sshift Installation Script for Windows"
43
+ Write-Host ""
44
+ Write-Host "Usage: ./sshift-install.ps1 [OPTIONS]"
45
+ Write-Host ""
46
+ Write-Host "Options:"
47
+ Write-Host " -installDir DIR Installation directory (default: ~/.local/share/sshift)"
48
+ Write-Host " -port PORT Server port (default: 8022)"
49
+ Write-Host " -start Start sshift after installation/update"
50
+ Write-Host " -stop Stop running sshift instance"
51
+ Write-Host " -restart Restart sshift"
52
+ Write-Host " -status Check if sshift is running"
53
+ Write-Host " -update Update existing installation (non-interactive)"
54
+ Write-Host " -uninstall Remove sshift from the system"
55
+ Write-Host " -help Show this help message"
56
+ Write-Host ""
57
+ Write-Host "IMPORTANT: Run PowerShell as Administrator before executing this script."
58
+ Write-Host " This is required for npm global installations."
59
+ Write-Host ""
60
+ Write-Host "Examples:"
61
+ Write-Host " ./sshift-install.ps1 # Install with defaults"
62
+ Write-Host " ./sshift-install.ps1 -port 8080 # Install with custom port"
63
+ Write-Host " ./sshift-install.ps1 -installDir C:\sshift # Install to custom directory"
64
+ Write-Host " ./sshift-install.ps1 -update # Update existing installation"
65
+ Write-Host " ./sshift-install.ps1 -start # Start sshift"
66
+ Write-Host " ./sshift-install.ps1 -stop # Stop sshift"
67
+ Write-Host " ./sshift-install.ps1 -restart # Restart sshift"
68
+ Write-Host " ./sshift-install.ps1 -status # Check status"
69
+ Write-Host " ./sshift-install.ps1 -uninstall # Remove sshift"
70
+ Write-Host ""
71
+ Write-Host "One-liner installation:"
72
+ Write-Host " Invoke-Expression (Invoke-WebRequest -Uri 'https://raw.githubusercontent.com/lethevimlet/sshift/main/sshift-install.ps1' -UseBasicParsing).Content"
73
+ exit 0
74
+ }
75
+
76
+ if ($help) {
77
+ Show-Help
78
+ }
79
+
80
+ # Check if running in PowerShell (not just double-clicked)
81
+ if ($Host.Name -eq "ConsoleHost") {
82
+ # Running in console, good
83
+ } else {
84
+ Write-Host ""
85
+ Write-Host "Note: This script is designed to run in PowerShell console." -ForegroundColor Yellow
86
+ Write-Host "If you double-clicked the .ps1 file, you may need to:" -ForegroundColor Yellow
87
+ Write-Host " 1. Right-click the file -> 'Run with PowerShell'" -ForegroundColor Cyan
88
+ Write-Host " 2. Or open PowerShell and run: .\sshift-install.ps1" -ForegroundColor Cyan
89
+ Write-Host ""
90
+ }
91
+
92
+ # Colors for output
93
+ function Write-Info { Write-Host "[INFO] " -ForegroundColor Blue -NoNewline; Write-Host $args }
94
+ function Write-Success { Write-Host "[SUCCESS] " -ForegroundColor Green -NoNewline; Write-Host $args }
95
+ function Write-Warning { Write-Host "[WARNING] " -ForegroundColor Yellow -NoNewline; Write-Host $args }
96
+ function Write-Error {
97
+ Write-Host "[ERROR] " -ForegroundColor Red -NoNewline;
98
+ Write-Host $args
99
+ Write-Host ""
100
+ Write-Host "Press any key to exit..."
101
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
102
+ exit 1
103
+ }
104
+
105
+ # Check if command exists
106
+ function Command-Exists {
107
+ param($Command)
108
+ return [bool](Get-Command -Name $Command -ErrorAction SilentlyContinue)
109
+ }
110
+
111
+ # Get installed version from npm
112
+ function Get-InstalledVersion {
113
+ if (Command-Exists "sshift") {
114
+ try {
115
+ $result = npm list -g @lethevimlet/sshift --depth=0 --json 2>$null | ConvertFrom-Json
116
+ if ($result.dependencies -and $result.dependencies.'@lethevimlet/sshift') {
117
+ return $result.dependencies.'@lethevimlet/sshift'.version
118
+ }
119
+ } catch {
120
+ try {
121
+ $result = npm list -g @lethevimlet/sshift --depth=0 2>$null
122
+ if ($result -match "@lethevimlet/sshift@(\d+\.\d+\.\d+)") {
123
+ return $matches[1]
124
+ }
125
+ } catch {
126
+ # Ignore errors
127
+ }
128
+ }
129
+ }
130
+ return "0.0.0"
131
+ }
132
+
133
+ # Get latest version from npm
134
+ function Get-LatestVersion {
135
+ try {
136
+ $result = npm view @lethevimlet/sshift version 2>$null
137
+ if ($result) {
138
+ return $result.Trim()
139
+ }
140
+ } catch {
141
+ # Ignore errors
142
+ }
143
+ return "0.0.0"
144
+ }
145
+
146
+ # Compare versions (returns 0 if equal, 1 if local < remote, 2 if local > remote)
147
+ function Compare-Versions {
148
+ param($LocalVersion, $RemoteVersion)
149
+
150
+ if ($LocalVersion -eq $RemoteVersion) {
151
+ return 0
152
+ }
153
+
154
+ $localParts = $LocalVersion -split '\.'
155
+ $remoteParts = $RemoteVersion -split '\.'
156
+
157
+ for ($i = 0; $i -lt 3; $i++) {
158
+ $local = [int]($localParts[$i] -as [int])
159
+ $remote = [int]($remoteParts[$i] -as [int])
160
+
161
+ if ($local -lt $remote) {
162
+ return 1
163
+ } elseif ($local -gt $remote) {
164
+ return 2
165
+ }
166
+ }
167
+
168
+ return 0
169
+ }
170
+
171
+ # Check if sshift is running
172
+ function Test-IsRunning {
173
+ # Check PID file (direct start instances)
174
+ if (Test-Path $PidFile) {
175
+ try {
176
+ $pid = Get-Content $PidFile -ErrorAction SilentlyContinue
177
+ $process = Get-Process -Id $pid -ErrorAction SilentlyContinue
178
+ if ($process) {
179
+ return $true
180
+ }
181
+ } catch {
182
+ # Process not running
183
+ }
184
+ # Clean up stale PID file
185
+ Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
186
+ }
187
+
188
+ # Check for running sshift node processes (handles autostart / Task Scheduler which uses no PID file)
189
+ $nodeProcesses = Get-Process -Name "node" -ErrorAction SilentlyContinue
190
+ foreach ($nodeProc in $nodeProcesses) {
191
+ try {
192
+ $cmdLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($nodeProc.Id)" -ErrorAction SilentlyContinue).CommandLine
193
+ if ($cmdLine -and $cmdLine -match "sshift") {
194
+ return $true
195
+ }
196
+ } catch {
197
+ # Ignore errors accessing process info
198
+ }
199
+ }
200
+
201
+ return $false
202
+ }
203
+
204
+ # Wait for a process to fully terminate and release file handles
205
+ function Wait-ProcessTerminated {
206
+ param(
207
+ [int]$ProcessId,
208
+ [int]$TimeoutSeconds = 15
209
+ )
210
+
211
+ $startTime = Get-Date
212
+ while (((Get-Date) - $startTime).TotalSeconds -lt $TimeoutSeconds) {
213
+ $process = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
214
+ if (-not $process) {
215
+ Write-Info "Process $ProcessId has terminated"
216
+ return $true
217
+ }
218
+ Start-Sleep -Milliseconds 500
219
+ }
220
+
221
+ # Process still running after timeout
222
+ $process = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
223
+ if ($process) {
224
+ Write-Warning "Process $ProcessId did not terminate within $TimeoutSeconds seconds"
225
+ return $false
226
+ }
227
+ return $true
228
+ }
229
+
230
+ # Kill all node processes running sshift (handles orphaned processes)
231
+ function Stop-AllSshiftProcesses {
232
+ $sshiftScript = $null
233
+ $npmPrefix = npm config get prefix 2>$null
234
+ if ($npmPrefix) {
235
+ $candidateScripts = @(
236
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\sshift"),
237
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\src\server\index.js")
238
+ )
239
+ foreach ($candidate in $candidateScripts) {
240
+ if (Test-Path $candidate) {
241
+ $sshiftScript = $candidate
242
+ break
243
+ }
244
+ }
245
+ }
246
+
247
+ if (-not $sshiftScript) {
248
+ $sshiftCmd = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
249
+ if ($sshiftCmd) {
250
+ $shimDir = Split-Path $sshiftCmd -Parent
251
+ $pkgDir = Join-Path $shimDir "node_modules\@lethevimlet\sshift"
252
+ if (Test-Path (Join-Path $pkgDir "sshift")) {
253
+ $sshiftScript = Join-Path $pkgDir "sshift"
254
+ } elseif (Test-Path (Join-Path $pkgDir "src\server\index.js")) {
255
+ $sshiftScript = Join-Path $pkgDir "src\server\index.js"
256
+ }
257
+ }
258
+ }
259
+
260
+ # Find node processes that are running the sshift script
261
+ $killedAny = $false
262
+ $nodeProcesses = Get-Process -Name "node" -ErrorAction SilentlyContinue
263
+ foreach ($nodeProc in $nodeProcesses) {
264
+ try {
265
+ $cmdLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($nodeProc.Id)" -ErrorAction SilentlyContinue).CommandLine
266
+ if ($cmdLine -and $cmdLine -match "sshift") {
267
+ Write-Info "Stopping sshift node process (PID: $($nodeProc.Id))..."
268
+ Stop-Process -Id $nodeProc.Id -Force -ErrorAction SilentlyContinue
269
+ $killedAny = $true
270
+ }
271
+ } catch {
272
+ # Ignore errors accessing process info
273
+ }
274
+ }
275
+
276
+ if ($killedAny) {
277
+ Start-Sleep -Seconds 2
278
+ }
279
+
280
+ return $killedAny
281
+ }
282
+
283
+ # Stop running instance
284
+ function Stop-App {
285
+ # Check if running via Task Scheduler
286
+ $task = Get-ScheduledTask -TaskName $ServiceName -ErrorAction SilentlyContinue
287
+ if ($task -and $task.State -eq "Running") {
288
+ Write-Info "Stopping sshift via Task Scheduler..."
289
+ Stop-ScheduledTask -TaskName $ServiceName
290
+ Start-Sleep -Seconds 3
291
+
292
+ # Verify task stopped
293
+ $task = Get-ScheduledTask -TaskName $ServiceName -ErrorAction SilentlyContinue
294
+ if ($task -and $task.State -eq "Running") {
295
+ Write-Warning "Task Scheduler task did not stop, will force kill process..."
296
+ }
297
+ }
298
+
299
+ # Stop via PID file
300
+ if (Test-IsRunning) {
301
+ $pid = Get-Content $PidFile
302
+ Write-Info "Stopping sshift (PID: $pid)..."
303
+
304
+ try {
305
+ # Try graceful stop first
306
+ Stop-Process -Id $pid -ErrorAction SilentlyContinue
307
+ Start-Sleep -Seconds 3
308
+
309
+ # Check if still running
310
+ $process = Get-Process -Id $pid -ErrorAction SilentlyContinue
311
+ if ($process) {
312
+ Write-Warning "Process did not stop gracefully, force killing..."
313
+ Stop-Process -Id $pid -Force -ErrorAction SilentlyContinue
314
+ Start-Sleep -Seconds 2
315
+ }
316
+
317
+ # Wait for process to fully terminate and release file handles
318
+ $terminated = Wait-ProcessTerminated -ProcessId $pid -TimeoutSeconds 10
319
+
320
+ if (-not $terminated) {
321
+ Write-Warning "Attempting to kill any remaining sshift node processes..."
322
+ Stop-AllSshiftProcesses
323
+ Start-Sleep -Seconds 3
324
+ }
325
+
326
+ Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
327
+ Write-Success "sshift stopped"
328
+ } catch {
329
+ Write-Error "Failed to stop sshift"
330
+ }
331
+ } else {
332
+ # Check for orphaned processes (no PID file but process may still be running)
333
+ $orphaned = Stop-AllSshiftProcesses
334
+ if (-not $orphaned) {
335
+ if (Test-Path $PidFile) {
336
+ Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
337
+ Write-Info "Removed stale PID file"
338
+ }
339
+ }
340
+ }
341
+ }
342
+
343
+ # Start the app
344
+ function Start-App {
345
+ Write-Info "Starting sshift..."
346
+
347
+ # Check if already running
348
+ if (Test-IsRunning) {
349
+ $pid = Get-Content $PidFile
350
+ Write-Warning "sshift is already running (PID: $pid)"
351
+ return
352
+ }
353
+
354
+ # Find node executable
355
+ $nodeExe = (Get-Command -Name "node" -ErrorAction SilentlyContinue).Source
356
+ if (-not $nodeExe) {
357
+ Write-Error "Could not find node executable."
358
+ return
359
+ }
360
+
361
+ # npm creates .cmd and .ps1 shims on Windows that can't be run directly by Start-Process
362
+ # Always resolve the actual entry point in node_modules
363
+ $sshiftScript = $null
364
+ $npmPrefix = npm config get prefix 2>$null
365
+ if ($npmPrefix) {
366
+ $candidateScripts = @(
367
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\sshift"),
368
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\src\server\index.js")
369
+ )
370
+ foreach ($candidate in $candidateScripts) {
371
+ if (Test-Path $candidate) {
372
+ $sshiftScript = $candidate
373
+ break
374
+ }
375
+ }
376
+ }
377
+
378
+ if (-not $sshiftScript) {
379
+ # Fallback: try to resolve from the sshift command location
380
+ $sshiftCmd = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
381
+ if ($sshiftCmd) {
382
+ # Walk up from shim to find the package directory
383
+ $shimDir = Split-Path $sshiftCmd -Parent
384
+ $pkgDir = Join-Path $shimDir "node_modules\@lethevimlet\sshift"
385
+ if (Test-Path (Join-Path $pkgDir "sshift")) {
386
+ $sshiftScript = Join-Path $pkgDir "sshift"
387
+ } elseif (Test-Path (Join-Path $pkgDir "src\server\index.js")) {
388
+ $sshiftScript = Join-Path $pkgDir "src\server\index.js"
389
+ }
390
+ }
391
+ }
392
+
393
+ if (-not $sshiftScript) {
394
+ Write-Error "Could not resolve sshift script path. Make sure sshift is installed."
395
+ return
396
+ }
397
+
398
+ # Ensure config directory exists
399
+ $envDir = Join-Path $installDir ".env"
400
+ if (-not (Test-Path $envDir)) {
401
+ New-Item -ItemType Directory -Force -Path $envDir | Out-Null
402
+ }
403
+
404
+ # Start sshift in background using node directly
405
+ try {
406
+ $process = Start-Process -FilePath $nodeExe -ArgumentList "`"$sshiftScript`"" -WorkingDirectory $installDir -WindowStyle Hidden -PassThru
407
+
408
+ # Save PID
409
+ New-Item -ItemType Directory -Force -Path (Split-Path $PidFile -Parent) | Out-Null
410
+ $process.Id | Out-File -FilePath $PidFile -Encoding ASCII
411
+
412
+ Start-Sleep -Seconds 4
413
+
414
+ # Check if process is still running
415
+ $running = Get-Process -Id $process.Id -ErrorAction SilentlyContinue
416
+ if ($running) {
417
+ $effectivePort = Get-EffectivePort
418
+ Write-Success "sshift started (PID: $($process.Id))"
419
+ Write-Info "Access: https://localhost:$effectivePort"
420
+ } else {
421
+ # Process crashed - try to provide useful diagnostics
422
+ Write-Error "sshift failed to start."
423
+ Write-Host ""
424
+ Write-Host "Diagnostic information:" -ForegroundColor Yellow
425
+ Write-Host " Node path: $nodeExe" -ForegroundColor Yellow
426
+ Write-Host " Script path: $sshiftScript" -ForegroundColor Yellow
427
+ Write-Host " Working dir: $installDir" -ForegroundColor Yellow
428
+ Write-Host ""
429
+ Write-Host "Try running manually to see the error:" -ForegroundColor Cyan
430
+ Write-Host " node `"$sshiftScript`"" -ForegroundColor Cyan
431
+ }
432
+ } catch {
433
+ Write-Error "Failed to start sshift: $_"
434
+ }
435
+ }
436
+
437
+ # Install Node.js if not present
438
+ function Install-NodeJS {
439
+ if (Command-Exists "node") {
440
+ $installedNodeVersion = (node -v) -replace 'v', ''
441
+ $majorVersion = $installedNodeVersion.Split('.')[0]
442
+
443
+ if ([int]$majorVersion -ge [int]$NodeVersion) {
444
+ Write-Success "Node.js $(node -v) is already installed"
445
+ return
446
+ } else {
447
+ Write-Warning "Node.js version $(node -v) is too old, upgrading..."
448
+ }
449
+ }
450
+
451
+ Write-Info "Installing Node.js $NodeVersion..."
452
+
453
+ # Use Chocolatey if available
454
+ if (Command-Exists "choco") {
455
+ choco install nodejs-lts -y
456
+ } else {
457
+ Write-Host ""
458
+ Write-Host "[ERROR] Chocolatey is not installed." -ForegroundColor Red
459
+ Write-Host ""
460
+ Write-Host "To install Node.js on Windows, you have several options:" -ForegroundColor Yellow
461
+ Write-Host ""
462
+ Write-Host "Option 1: Install Chocolatey (recommended)" -ForegroundColor Cyan
463
+ Write-Host " Visit: https://chocolatey.org/install"
464
+ Write-Host " Then run this script again"
465
+ Write-Host ""
466
+ Write-Host "Option 2: Install Node.js directly" -ForegroundColor Cyan
467
+ Write-Host " Visit: https://nodejs.org/"
468
+ Write-Host " Download and install Node.js LTS version"
469
+ Write-Host " Then run this script again"
470
+ Write-Host ""
471
+ Write-Host "Option 3: Use nvm-windows" -ForegroundColor Cyan
472
+ Write-Host " Visit: https://github.com/coreybutler/nvm-windows"
473
+ Write-Host " Install nvm-windows, then: nvm install lts"
474
+ Write-Host ""
475
+ Write-Host "Press any key to exit..."
476
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
477
+ exit 1
478
+ }
479
+
480
+ # Verify installation
481
+ if (Command-Exists "node") {
482
+ Write-Success "Node.js $(node -v) installed successfully"
483
+ } else {
484
+ Write-Error "Failed to install Node.js"
485
+ }
486
+ }
487
+
488
+ # Install sshift via npm
489
+ function Install-Sshift {
490
+ Write-Info "Installing sshift via npm..."
491
+
492
+ # Install globally (may require admin privileges on Windows)
493
+ npm install -g @lethevimlet/sshift
494
+
495
+ if ($LASTEXITCODE -eq 0) {
496
+ Write-Success "sshift installed successfully"
497
+ } else {
498
+ Write-Host ""
499
+ Write-Host "[ERROR] Failed to install sshift" -ForegroundColor Red
500
+ Write-Host ""
501
+ Write-Host "Common solutions:" -ForegroundColor Yellow
502
+ Write-Host " 1. Run PowerShell as Administrator and try again" -ForegroundColor Cyan
503
+ Write-Host " 2. Check your internet connection" -ForegroundColor Cyan
504
+ Write-Host " 3. Try: npm cache clean --force" -ForegroundColor Cyan
505
+ Write-Host " 4. Check npm logs for details" -ForegroundColor Cyan
506
+ Write-Host ""
507
+ Write-Host "Press any key to exit..."
508
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
509
+ exit 1
510
+ }
511
+ }
512
+
513
+ # Update sshift
514
+ function Update-Sshift {
515
+ Write-Info "Updating sshift..."
516
+
517
+ # Stop running instance before updating
518
+ $wasRunning = $false
519
+ if (Test-IsRunning) {
520
+ $wasRunning = $true
521
+ Stop-App
522
+ } else {
523
+ # Check for orphaned sshift node processes
524
+ Stop-AllSshiftProcesses
525
+ }
526
+
527
+ # Give extra time for file handles to be released after stopping
528
+ Write-Info "Waiting for file handles to be released..."
529
+ Start-Sleep -Seconds 3
530
+
531
+ # Update via npm (may require admin privileges on Windows)
532
+ npm update -g @lethevimlet/sshift
533
+
534
+ if ($LASTEXITCODE -eq 0) {
535
+ Write-Success "sshift updated successfully"
536
+ } else {
537
+ Write-Host ""
538
+ Write-Host "[ERROR] Failed to update sshift" -ForegroundColor Red
539
+ Write-Host ""
540
+ Write-Host "Common solutions:" -ForegroundColor Yellow
541
+ Write-Host " 1. Run PowerShell as Administrator and try again" -ForegroundColor Cyan
542
+ Write-Host " 2. Check your internet connection" -ForegroundColor Cyan
543
+ Write-Host " 3. Try: npm cache clean --force" -ForegroundColor Cyan
544
+ Write-Host " 4. Check npm logs for details" -ForegroundColor Cyan
545
+ Write-Host " 5. If sshift was running, stop it first: ./sshift-install.ps1 -stop" -ForegroundColor Cyan
546
+ Write-Host ""
547
+ Write-Host "Press any key to exit..."
548
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
549
+ exit 1
550
+ }
551
+ }
552
+
553
+ # Create config file with port setting
554
+ function New-Config {
555
+ Write-Info "Creating configuration..."
556
+
557
+ # Create .env directory if it doesn't exist
558
+ $envDir = Join-Path $installDir ".env"
559
+ New-Item -ItemType Directory -Force -Path $envDir | Out-Null
560
+
561
+ # Create config.json with HTTPS enabled
562
+ $configFile = Join-Path $envDir "config.json"
563
+ $port = if ($ServerPort -ne "") { $ServerPort } else { "8022" }
564
+
565
+ $configContent = @"
566
+ {
567
+ "port": $port,
568
+ "devPort": 3000,
569
+ "bind": "0.0.0.0",
570
+ "enableHttps": true,
571
+ "sticky": true,
572
+ "sshKeepaliveInterval": 15000,
573
+ "sshKeepaliveCountMax": 500,
574
+ "bookmarks": [],
575
+ "folders": []
576
+ }
577
+ "@
578
+
579
+ # Write config to user install directory (preferred by updated config loader)
580
+ $configContent | Out-File -FilePath $configFile -Encoding ASCII
581
+
582
+ # Also write config to the npm package directory so the older config loader finds it
583
+ $sshiftPath = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
584
+ if ($sshiftPath) {
585
+ # sshift is typically at <npm_prefix>\sshift.cmd, package dir is <npm_prefix>\node_modules\@lethevimlet\sshift
586
+ $npmPrefix = npm config get prefix 2>$null
587
+ if ($npmPrefix) {
588
+ $pkgDir = Join-Path $npmPrefix "node_modules\@lethevimlet\sshift"
589
+ if (Test-Path $pkgDir) {
590
+ $pkgEnvDir = Join-Path $pkgDir ".env"
591
+ New-Item -ItemType Directory -Force -Path $pkgEnvDir | Out-Null
592
+ $configContent | Out-File -FilePath (Join-Path $pkgEnvDir "config.json") -Encoding ASCII
593
+ $configContent | Out-File -FilePath (Join-Path $pkgDir "config.json") -Encoding ASCII
594
+ }
595
+ }
596
+ }
597
+
598
+ Write-Success "Configuration created with HTTPS enabled on port $port"
599
+ }
600
+
601
+ # Add to PATH
602
+ function Add-ToPath {
603
+ # Check if sshift command is already accessible
604
+ $sshiftPath = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
605
+
606
+ if ($sshiftPath) {
607
+ Write-Success "sshift command available at $sshiftPath"
608
+
609
+ # Check if its directory is in user PATH
610
+ $sshiftDir = Split-Path $sshiftPath -Parent
611
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
612
+ if ($userPath -like "*$sshiftDir*") {
613
+ return
614
+ }
615
+
616
+ # Add to user PATH if not already there
617
+ $newPath = "$sshiftDir;$userPath"
618
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
619
+ Write-Success "Added $sshiftDir to PATH"
620
+ Write-Info "Restart your terminal for PATH changes to take effect"
621
+ return
622
+ }
623
+
624
+ # sshift not found - add npm global bin directory to PATH
625
+ $npmPrefix = npm config get prefix 2>$null
626
+ if ($npmPrefix) {
627
+ $npmBinDir = Join-Path $npmPrefix ""
628
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
629
+
630
+ if ($userPath -notlike "*$npmBinDir*") {
631
+ $newPath = "$npmBinDir;$userPath"
632
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
633
+ Write-Success "Added $npmBinDir to PATH"
634
+ Write-Info "Restart your terminal for PATH changes to take effect"
635
+ }
636
+ } else {
637
+ Write-Warning "Could not determine sshift binary location. You may need to add it to PATH manually."
638
+ }
639
+ }
640
+
641
+ # Setup autostart via Task Scheduler
642
+ function Enable-Autostart {
643
+ Write-Info "Setting up autostart (on boot) via Task Scheduler..."
644
+
645
+ # Find node executable
646
+ $nodeExe = (Get-Command -Name "node" -ErrorAction SilentlyContinue).Source
647
+ if (-not $nodeExe) {
648
+ Write-Error "Could not find node executable."
649
+ return
650
+ }
651
+
652
+ # Resolve the actual entry point (npm shims can't be used directly in Task Scheduler)
653
+ $sshiftScript = $null
654
+ $npmPrefix = npm config get prefix 2>$null
655
+ if ($npmPrefix) {
656
+ $candidateScripts = @(
657
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\sshift"),
658
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\src\server\index.js")
659
+ )
660
+ foreach ($candidate in $candidateScripts) {
661
+ if (Test-Path $candidate) {
662
+ $sshiftScript = $candidate
663
+ break
664
+ }
665
+ }
666
+ }
667
+
668
+ if (-not $sshiftScript) {
669
+ $sshiftCmd = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
670
+ if ($sshiftCmd) {
671
+ $shimDir = Split-Path $sshiftCmd -Parent
672
+ $pkgDir = Join-Path $shimDir "node_modules\@lethevimlet\sshift"
673
+ if (Test-Path (Join-Path $pkgDir "sshift")) {
674
+ $sshiftScript = Join-Path $pkgDir "sshift"
675
+ } elseif (Test-Path (Join-Path $pkgDir "src\server\index.js")) {
676
+ $sshiftScript = Join-Path $pkgDir "src\server\index.js"
677
+ }
678
+ }
679
+ }
680
+
681
+ if (-not $sshiftScript) {
682
+ Write-Error "Could not resolve sshift script path."
683
+ return
684
+ }
685
+
686
+ # Ensure config directory exists
687
+ $envDir = Join-Path $installDir ".env"
688
+ if (-not (Test-Path $envDir)) {
689
+ New-Item -ItemType Directory -Force -Path $envDir | Out-Null
690
+ }
691
+
692
+ # Create a VBS wrapper script to run sshift without a visible window.
693
+ # Task Scheduler running node.exe directly shows a console window; wscript
694
+ # with Run(...,0) launches it completely hidden.
695
+ $vbsPath = Join-Path $installDir "sshift-launcher.vbs"
696
+ $vbsContent = @"
697
+ Set WshShell = CreateObject("WScript.Shell")
698
+ WshShell.CurrentDirectory = "$installDir"
699
+ WshShell.Run """$nodeExe"" ""$sshiftScript""", 0, False
700
+ "@
701
+ Set-Content -Path $vbsPath -Value $vbsContent -Encoding ASCII
702
+
703
+ # Create task action using wscript to run the VBS launcher (no console window)
704
+ $wscriptExe = Join-Path $env:SystemRoot "System32\wscript.exe"
705
+ $action = New-ScheduledTaskAction -Execute $wscriptExe -Argument "//B `"$vbsPath`"" -WorkingDirectory $installDir
706
+
707
+ # Create task trigger (at startup)
708
+ $trigger = New-ScheduledTaskTrigger -AtStartup
709
+
710
+ # Create task settings
711
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
712
+
713
+ # Register the task
714
+ Register-ScheduledTask -TaskName $ServiceName -Action $action -Trigger $trigger -Settings $settings -RunLevel Highest -Force
715
+
716
+ Write-Success "Autostart configured via Task Scheduler"
717
+ }
718
+
719
+ # Remove autostart
720
+ function Remove-Autostart {
721
+ # Unregister scheduled task
722
+ Unregister-ScheduledTask -TaskName $ServiceName -Confirm:$false -ErrorAction SilentlyContinue
723
+
724
+ # Remove VBS launcher script
725
+ $vbsPath = Join-Path $installDir "sshift-launcher.vbs"
726
+ if (Test-Path $vbsPath) {
727
+ Remove-Item -Path $vbsPath -Force -ErrorAction SilentlyContinue
728
+ }
729
+ }
730
+
731
+ # Get LAN IP address
732
+ function Get-LANIP {
733
+ try {
734
+ $ip = (Get-NetIPConfiguration | Where-Object {
735
+ $_.IPv4DefaultGateway -ne $null -and
736
+ $_.NetAdapter.Status -eq "Up"
737
+ } | Select-Object -First 1).IPv4Address.IPAddress
738
+
739
+ if (-not $ip) {
740
+ $ip = (Test-Connection -ComputerName (hostname) -Count 1 -ErrorAction SilentlyContinue).IPV4Address.IPAddressToString
741
+ }
742
+
743
+ if (-not $ip) {
744
+ $ip = "0.0.0.0"
745
+ }
746
+ } catch {
747
+ $ip = "0.0.0.0"
748
+ }
749
+ return $ip
750
+ }
751
+
752
+ # Get effective port from config or default
753
+ function Get-EffectivePort {
754
+ $port = if ($ServerPort -ne "") { $ServerPort } else { "8022" }
755
+ if ($ServerPort -eq "") {
756
+ $configFile = Join-Path $installDir ".env\config.json"
757
+ if (Test-Path $configFile) {
758
+ try {
759
+ $config = Get-Content $configFile -Raw | ConvertFrom-Json
760
+ if ($config.port) {
761
+ $port = $config.port
762
+ }
763
+ } catch {
764
+ # Use default
765
+ }
766
+ }
767
+ }
768
+ return $port
769
+ }
770
+
771
+ # Print installation summary
772
+ function Show-Summary {
773
+ $effectivePort = Get-EffectivePort
774
+ $lanIP = Get-LANIP
775
+
776
+ $url1 = "https://localhost:$effectivePort"
777
+ $url2 = "https://${lanIP}:$effectivePort"
778
+ $dataDir = $installDir
779
+
780
+ $content = @(
781
+ " sshift installed (Task Scheduler)",
782
+ "",
783
+ " Path: $dataDir",
784
+ "",
785
+ " URLs:",
786
+ " $url1",
787
+ " $url2"
788
+ )
789
+
790
+ $maxW = 0
791
+ foreach ($line in $content) {
792
+ if ($line.Length -gt $maxW) { $maxW = $line.Length }
793
+ }
794
+ $maxW += 2
795
+
796
+ $border = [string]::new('-', $maxW)
797
+
798
+ Write-Host ""
799
+ Write-Host " +$border+" -ForegroundColor Green
800
+ foreach ($line in $content) {
801
+ $padded = $line.PadRight($maxW)
802
+ Write-Host " |" -ForegroundColor Green -NoNewline
803
+ Write-Host "$padded" -NoNewline
804
+ Write-Host "|" -ForegroundColor Green
805
+ }
806
+ Write-Host " +$border+" -ForegroundColor Green
807
+ Write-Host ""
808
+ }
809
+
810
+ # Uninstall sshift
811
+ function Uninstall-Sshift {
812
+ Write-Host ""
813
+ Write-Host "=========================================="
814
+ Write-Host " sshift Uninstallation Script"
815
+ Write-Host "=========================================="
816
+ Write-Host ""
817
+
818
+ # Check if installed
819
+ if (-not (Command-Exists "sshift")) {
820
+ Write-Warning "sshift is not installed"
821
+ return
822
+ }
823
+
824
+ Write-Info "This will remove:"
825
+ Write-Host " - sshift npm package"
826
+ Write-Host " - Configuration files in $installDir"
827
+ Write-Host " - Autostart configuration (if any)"
828
+ Write-Host " - PATH configuration"
829
+ Write-Host ""
830
+
831
+ $confirm = Read-Host "Continue with uninstallation? [y/N]"
832
+ if ($confirm -notmatch "^[Yy]$") {
833
+ Write-Info "Uninstallation cancelled"
834
+ return
835
+ }
836
+
837
+ Write-Host ""
838
+
839
+ # Stop running instance
840
+ if (Test-IsRunning) {
841
+ Write-Info "Stopping running instance..."
842
+ Stop-App
843
+ } else {
844
+ # Check for orphaned sshift node processes
845
+ Stop-AllSshiftProcesses
846
+ }
847
+
848
+ # Give extra time for file handles to be released
849
+ Write-Info "Waiting for file handles to be released..."
850
+ Start-Sleep -Seconds 3
851
+
852
+ # Remove autostart
853
+ Write-Info "Removing autostart configuration..."
854
+ Remove-Autostart
855
+
856
+ # Uninstall via npm
857
+ Write-Info "Uninstalling sshift..."
858
+ npm uninstall -g @lethevimlet/sshift
859
+
860
+ if ($LASTEXITCODE -ne 0) {
861
+ Write-Warning "npm uninstall failed. If you see permission errors, try running PowerShell as Administrator"
862
+
863
+ # Retry once after a longer wait if it failed (file may still be locked)
864
+ Write-Info "Retrying uninstall after waiting for file handles to be released..."
865
+ Start-Sleep -Seconds 5
866
+ npm uninstall -g @lethevimlet/sshift
867
+
868
+ if ($LASTEXITCODE -ne 0) {
869
+ Write-Warning "Uninstall still failed. You may need to close any applications using sshift and try again"
870
+ } else {
871
+ Write-Success "sshift uninstalled successfully on retry"
872
+ }
873
+ }
874
+
875
+ # Remove installation directory
876
+ if (Test-Path $installDir) {
877
+ Write-Info "Removing configuration directory..."
878
+ Remove-Item -Path $installDir -Recurse -Force -ErrorAction SilentlyContinue
879
+ Write-Success "Configuration directory removed"
880
+ }
881
+
882
+ # Remove from PATH
883
+ Write-Info "Removing PATH configuration..."
884
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
885
+ $newPath = ($userPath -split ';' | Where-Object { $_ -ne $BinDir }) -join ';'
886
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
887
+
888
+ Write-Host ""
889
+ Write-Host "=========================================="
890
+ Write-Host "sshift uninstalled successfully!" -ForegroundColor Green
891
+ Write-Host "=========================================="
892
+ Write-Host ""
893
+ Write-Info "You may need to restart your terminal for PATH changes to take effect"
894
+ }
895
+
896
+ # Check for updates
897
+ function Test-Updates {
898
+ Write-Info "Checking for updates..."
899
+
900
+ $localVersion = Get-InstalledVersion
901
+ $remoteVersion = Get-LatestVersion
902
+
903
+ Write-Info "Installed version: $localVersion"
904
+ Write-Info "Latest version: $remoteVersion"
905
+
906
+ $result = Compare-Versions -LocalVersion $localVersion -RemoteVersion $remoteVersion
907
+
908
+ if ($result -eq 1) {
909
+ Write-Warning "New version available: $remoteVersion (current: $localVersion)"
910
+ return $false
911
+ } elseif ($result -eq 2) {
912
+ Write-Info "Local version is newer than remote (development version?)"
913
+ return $true
914
+ } else {
915
+ Write-Success "Already up to date (version $localVersion)"
916
+ return $true
917
+ }
918
+ }
919
+
920
+ # Main installation process
921
+ function Main {
922
+ # Check if running as Administrator
923
+ $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
924
+ if (-not $isAdmin) {
925
+ Write-Host ""
926
+ Write-Host "=========================================="
927
+ Write-Host " sshift Installation Script"
928
+ Write-Host "=========================================="
929
+ Write-Host ""
930
+ Write-Host "[ERROR] This script requires Administrator privileges." -ForegroundColor Red
931
+ Write-Host ""
932
+ Write-Host "Please run PowerShell as Administrator and try again:" -ForegroundColor Yellow
933
+ Write-Host " 1. Right-click PowerShell -> 'Run as Administrator'" -ForegroundColor Cyan
934
+ Write-Host " 2. Run the installation command again" -ForegroundColor Cyan
935
+ Write-Host ""
936
+ Write-Host "Press any key to exit..."
937
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
938
+ exit 1
939
+ }
940
+
941
+ # Handle uninstall
942
+ if ($uninstall) {
943
+ Uninstall-Sshift
944
+ Write-Host ""
945
+ Write-Host "Press any key to exit..."
946
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
947
+ exit 0
948
+ }
949
+
950
+ # Handle status check
951
+ if ($status) {
952
+ if (Test-IsRunning) {
953
+ $pid = Get-Content $PidFile
954
+ Write-Success "sshift is running (PID: $pid)"
955
+ } else {
956
+ Write-Info "sshift is not running"
957
+ }
958
+ Write-Host ""
959
+ Write-Host "Press any key to exit..."
960
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
961
+ exit 0
962
+ }
963
+
964
+ # Handle stop
965
+ if ($stop) {
966
+ Stop-App
967
+ Write-Host ""
968
+ Write-Host "Press any key to exit..."
969
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
970
+ exit 0
971
+ }
972
+
973
+ # Handle restart
974
+ if ($restart) {
975
+ Write-Info "Restarting sshift..."
976
+ Stop-App
977
+ Start-App
978
+ Write-Host ""
979
+ Write-Host "Press any key to exit..."
980
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
981
+ exit 0
982
+ }
983
+
984
+ # Handle start
985
+ if ($start) {
986
+ Start-App
987
+ Write-Host ""
988
+ Write-Host "Press any key to exit..."
989
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
990
+ exit 0
991
+ }
992
+
993
+ # Handle update-only mode
994
+ if ($update) {
995
+ # Check if installed
996
+ if (-not (Command-Exists "sshift")) {
997
+ Write-Error "sshift is not installed"
998
+ }
999
+
1000
+ Write-Host ""
1001
+ Write-Host "=========================================="
1002
+ Write-Host " sshift Update Script"
1003
+ Write-Host "=========================================="
1004
+ Write-Host ""
1005
+
1006
+ Update-Sshift
1007
+
1008
+ Show-Summary
1009
+
1010
+ Write-Host ""
1011
+ Write-Host "Press any key to exit..."
1012
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1013
+ exit 0
1014
+ }
1015
+
1016
+ Write-Host ""
1017
+ Write-Host "=========================================="
1018
+ Write-Host " sshift Installation Script"
1019
+ Write-Host "=========================================="
1020
+ Write-Host ""
1021
+
1022
+ # Show configuration
1023
+ Write-Info "Installation method: npm"
1024
+ if ($ServerPort -ne "") {
1025
+ Write-Info "Server port: $ServerPort"
1026
+ }
1027
+
1028
+ # Check if already installed
1029
+ if (Command-Exists "sshift") {
1030
+ Write-Info "sshift is already installed"
1031
+
1032
+ # Check for updates
1033
+ $upToDate = Test-Updates
1034
+ if ($upToDate) {
1035
+ # No update needed
1036
+ if (Test-IsRunning) {
1037
+ $pid = Get-Content $PidFile
1038
+ Write-Info "sshift is already running (PID: $pid)"
1039
+ }
1040
+ } else {
1041
+ # Update available
1042
+ $confirm = Read-Host "Update sshift? [Y/n]"
1043
+ if ($confirm -notmatch "^[Nn]$") {
1044
+ Update-Sshift
1045
+ }
1046
+ }
1047
+ } else {
1048
+ # Fresh installation
1049
+ # Install Node.js if needed
1050
+ Install-NodeJS
1051
+
1052
+ # Install sshift via npm
1053
+ Install-Sshift
1054
+
1055
+ # Create config file with port (if specified)
1056
+ New-Config
1057
+ }
1058
+
1059
+ # Always ask about PATH and autostart (even if already installed)
1060
+ Write-Host ""
1061
+ Write-Info "Configuration options:"
1062
+ Write-Host ""
1063
+
1064
+ # Add to PATH
1065
+ $addToPath = Read-Host "Add sshift to PATH? [Y/n]"
1066
+ if ($addToPath -notmatch "^[Nn]$") {
1067
+ Add-ToPath
1068
+ }
1069
+
1070
+ # Ask about autostart
1071
+ $enableAutostart = Read-Host "Start sshift automatically on boot? [y/N]"
1072
+ if ($enableAutostart -match "^[Yy]$") {
1073
+ Enable-Autostart
1074
+ }
1075
+
1076
+ # Start sshift if not already running
1077
+ if (-not (Test-IsRunning)) {
1078
+ Start-App
1079
+ }
1080
+
1081
+ # Print summary
1082
+ Show-Summary
1083
+
1084
+ # Pause before exit
1085
+ Write-Host ""
1086
+ Write-Host "Press any key to exit..."
1087
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1088
+ }
1089
+
1090
+ # Run main function
1091
+ try {
1092
+ Main
1093
+ } catch {
1094
+ Write-Host ""
1095
+ Write-Host "[ERROR] An unexpected error occurred:" -ForegroundColor Red
1096
+ Write-Host $_.Exception.Message
1097
+ Write-Host ""
1098
+ Write-Host "Press any key to exit..."
1099
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1100
+ exit 1
1101
+ }