@lethevimlet/sshift 0.9.6 → 0.9.8

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,1121 @@
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
+ # Merge default values into existing config:
566
+ # - Preserves user's existing values
567
+ # - Adds new default properties from newer versions
568
+ # - If -port was explicitly set, overrides the port value
569
+ $defaults = @{
570
+ port = [int]$port
571
+ devPort = 3000
572
+ bind = "0.0.0.0"
573
+ enableHttps = $true
574
+ sticky = $true
575
+ sshKeepaliveInterval = 15000
576
+ sshKeepaliveCountMax = 500
577
+ bookmarks = @()
578
+ folders = @()
579
+ }
580
+
581
+ $wasNew = $true
582
+ if (Test-Path $configFile) {
583
+ try {
584
+ $existing = Get-Content $configFile -Raw | ConvertFrom-Json
585
+ $wasNew = $false
586
+ } catch {
587
+ Write-Warning "Could not parse existing config, using defaults"
588
+ $existing = [PSCustomObject]@{}
589
+ }
590
+ } else {
591
+ $existing = [PSCustomObject]@{}
592
+ }
593
+
594
+ # Build merged config: start with defaults, overlay existing values
595
+ $merged = [PSCustomObject]@{}
596
+ foreach ($key in $defaults.Keys) {
597
+ $merged | Add-Member -NotePropertyName $key -NotePropertyValue $defaults[$key] -Force
598
+ }
599
+ foreach ($prop in $existing.PSObject.Properties) {
600
+ $merged | Add-Member -NotePropertyName $prop.Name -NotePropertyValue $prop.Value -Force
601
+ }
602
+
603
+ # If -port was explicitly set, override the port value
604
+ if ($ServerPort -ne "") {
605
+ $merged.port = [int]$ServerPort
606
+ }
607
+
608
+ # Write merged config
609
+ $merged | ConvertTo-Json -Depth 10 | Set-Content -Path $configFile -Encoding ASCII
610
+
611
+ if ($wasNew) {
612
+ Write-Info "Configuration created at $configFile"
613
+ } else {
614
+ Write-Info "Existing configuration merged with defaults at $configFile"
615
+ }
616
+
617
+ $effectivePort = $merged.port
618
+ Write-Success "Configuration created with HTTPS enabled on port $effectivePort"
619
+ }
620
+
621
+ # Add to PATH
622
+ function Add-ToPath {
623
+ # Check if sshift command is already accessible
624
+ $sshiftPath = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
625
+
626
+ if ($sshiftPath) {
627
+ Write-Success "sshift command available at $sshiftPath"
628
+
629
+ # Check if its directory is in user PATH
630
+ $sshiftDir = Split-Path $sshiftPath -Parent
631
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
632
+ if ($userPath -like "*$sshiftDir*") {
633
+ return
634
+ }
635
+
636
+ # Add to user PATH if not already there
637
+ $newPath = "$sshiftDir;$userPath"
638
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
639
+ Write-Success "Added $sshiftDir to PATH"
640
+ Write-Info "Restart your terminal for PATH changes to take effect"
641
+ return
642
+ }
643
+
644
+ # sshift not found - add npm global bin directory to PATH
645
+ $npmPrefix = npm config get prefix 2>$null
646
+ if ($npmPrefix) {
647
+ $npmBinDir = Join-Path $npmPrefix ""
648
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
649
+
650
+ if ($userPath -notlike "*$npmBinDir*") {
651
+ $newPath = "$npmBinDir;$userPath"
652
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
653
+ Write-Success "Added $npmBinDir to PATH"
654
+ Write-Info "Restart your terminal for PATH changes to take effect"
655
+ }
656
+ } else {
657
+ Write-Warning "Could not determine sshift binary location. You may need to add it to PATH manually."
658
+ }
659
+ }
660
+
661
+ # Setup autostart via Task Scheduler
662
+ function Enable-Autostart {
663
+ Write-Info "Setting up autostart (on boot) via Task Scheduler..."
664
+
665
+ # Find node executable
666
+ $nodeExe = (Get-Command -Name "node" -ErrorAction SilentlyContinue).Source
667
+ if (-not $nodeExe) {
668
+ Write-Error "Could not find node executable."
669
+ return
670
+ }
671
+
672
+ # Resolve the actual entry point (npm shims can't be used directly in Task Scheduler)
673
+ $sshiftScript = $null
674
+ $npmPrefix = npm config get prefix 2>$null
675
+ if ($npmPrefix) {
676
+ $candidateScripts = @(
677
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\sshift"),
678
+ (Join-Path $npmPrefix "node_modules\@lethevimlet\sshift\src\server\index.js")
679
+ )
680
+ foreach ($candidate in $candidateScripts) {
681
+ if (Test-Path $candidate) {
682
+ $sshiftScript = $candidate
683
+ break
684
+ }
685
+ }
686
+ }
687
+
688
+ if (-not $sshiftScript) {
689
+ $sshiftCmd = (Get-Command -Name "sshift" -ErrorAction SilentlyContinue).Source
690
+ if ($sshiftCmd) {
691
+ $shimDir = Split-Path $sshiftCmd -Parent
692
+ $pkgDir = Join-Path $shimDir "node_modules\@lethevimlet\sshift"
693
+ if (Test-Path (Join-Path $pkgDir "sshift")) {
694
+ $sshiftScript = Join-Path $pkgDir "sshift"
695
+ } elseif (Test-Path (Join-Path $pkgDir "src\server\index.js")) {
696
+ $sshiftScript = Join-Path $pkgDir "src\server\index.js"
697
+ }
698
+ }
699
+ }
700
+
701
+ if (-not $sshiftScript) {
702
+ Write-Error "Could not resolve sshift script path."
703
+ return
704
+ }
705
+
706
+ # Ensure config directory exists
707
+ $envDir = Join-Path $installDir ".env"
708
+ if (-not (Test-Path $envDir)) {
709
+ New-Item -ItemType Directory -Force -Path $envDir | Out-Null
710
+ }
711
+
712
+ # Create a VBS wrapper script to run sshift without a visible window.
713
+ # Task Scheduler running node.exe directly shows a console window; wscript
714
+ # with Run(...,0) launches it completely hidden.
715
+ $vbsPath = Join-Path $installDir "sshift-launcher.vbs"
716
+ $vbsContent = @"
717
+ Set WshShell = CreateObject("WScript.Shell")
718
+ WshShell.CurrentDirectory = "$installDir"
719
+ WshShell.Run """$nodeExe"" ""$sshiftScript""", 0, False
720
+ "@
721
+ Set-Content -Path $vbsPath -Value $vbsContent -Encoding ASCII
722
+
723
+ # Create task action using wscript to run the VBS launcher (no console window)
724
+ $wscriptExe = Join-Path $env:SystemRoot "System32\wscript.exe"
725
+ $action = New-ScheduledTaskAction -Execute $wscriptExe -Argument "//B `"$vbsPath`"" -WorkingDirectory $installDir
726
+
727
+ # Create task trigger (at startup)
728
+ $trigger = New-ScheduledTaskTrigger -AtStartup
729
+
730
+ # Create task settings
731
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -DontStopOnIdleEnd -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
732
+
733
+ # Register the task
734
+ Register-ScheduledTask -TaskName $ServiceName -Action $action -Trigger $trigger -Settings $settings -RunLevel Highest -Force
735
+
736
+ Write-Success "Autostart configured via Task Scheduler"
737
+ }
738
+
739
+ # Remove autostart
740
+ function Remove-Autostart {
741
+ # Unregister scheduled task
742
+ Unregister-ScheduledTask -TaskName $ServiceName -Confirm:$false -ErrorAction SilentlyContinue
743
+
744
+ # Remove VBS launcher script
745
+ $vbsPath = Join-Path $installDir "sshift-launcher.vbs"
746
+ if (Test-Path $vbsPath) {
747
+ Remove-Item -Path $vbsPath -Force -ErrorAction SilentlyContinue
748
+ }
749
+ }
750
+
751
+ # Get LAN IP address
752
+ function Get-LANIP {
753
+ try {
754
+ $ip = (Get-NetIPConfiguration | Where-Object {
755
+ $_.IPv4DefaultGateway -ne $null -and
756
+ $_.NetAdapter.Status -eq "Up"
757
+ } | Select-Object -First 1).IPv4Address.IPAddress
758
+
759
+ if (-not $ip) {
760
+ $ip = (Test-Connection -ComputerName (hostname) -Count 1 -ErrorAction SilentlyContinue).IPV4Address.IPAddressToString
761
+ }
762
+
763
+ if (-not $ip) {
764
+ $ip = "0.0.0.0"
765
+ }
766
+ } catch {
767
+ $ip = "0.0.0.0"
768
+ }
769
+ return $ip
770
+ }
771
+
772
+ # Get effective port from config or default
773
+ function Get-EffectivePort {
774
+ $port = if ($ServerPort -ne "") { $ServerPort } else { "8022" }
775
+ if ($ServerPort -eq "") {
776
+ $configFile = Join-Path $installDir ".env\config.json"
777
+ if (Test-Path $configFile) {
778
+ try {
779
+ $config = Get-Content $configFile -Raw | ConvertFrom-Json
780
+ if ($config.port) {
781
+ $port = $config.port
782
+ }
783
+ } catch {
784
+ # Use default
785
+ }
786
+ }
787
+ }
788
+ return $port
789
+ }
790
+
791
+ # Print installation summary
792
+ function Show-Summary {
793
+ $effectivePort = Get-EffectivePort
794
+ $lanIP = Get-LANIP
795
+
796
+ $url1 = "https://localhost:$effectivePort"
797
+ $url2 = "https://${lanIP}:$effectivePort"
798
+ $dataDir = $installDir
799
+
800
+ $content = @(
801
+ " sshift installed (Task Scheduler)",
802
+ "",
803
+ " Path: $dataDir",
804
+ "",
805
+ " URLs:",
806
+ " $url1",
807
+ " $url2"
808
+ )
809
+
810
+ $maxW = 0
811
+ foreach ($line in $content) {
812
+ if ($line.Length -gt $maxW) { $maxW = $line.Length }
813
+ }
814
+ $maxW += 2
815
+
816
+ $border = [string]::new('-', $maxW)
817
+
818
+ Write-Host ""
819
+ Write-Host " +$border+" -ForegroundColor Green
820
+ foreach ($line in $content) {
821
+ $padded = $line.PadRight($maxW)
822
+ Write-Host " |" -ForegroundColor Green -NoNewline
823
+ Write-Host "$padded" -NoNewline
824
+ Write-Host "|" -ForegroundColor Green
825
+ }
826
+ Write-Host " +$border+" -ForegroundColor Green
827
+ Write-Host ""
828
+ }
829
+
830
+ # Uninstall sshift
831
+ function Uninstall-Sshift {
832
+ Write-Host ""
833
+ Write-Host "=========================================="
834
+ Write-Host " sshift Uninstallation Script"
835
+ Write-Host "=========================================="
836
+ Write-Host ""
837
+
838
+ # Check if installed
839
+ if (-not (Command-Exists "sshift")) {
840
+ Write-Warning "sshift is not installed"
841
+ return
842
+ }
843
+
844
+ Write-Info "This will remove:"
845
+ Write-Host " - sshift npm package"
846
+ Write-Host " - Configuration files in $installDir"
847
+ Write-Host " - Autostart configuration (if any)"
848
+ Write-Host " - PATH configuration"
849
+ Write-Host ""
850
+
851
+ $confirm = Read-Host "Continue with uninstallation? [y/N]"
852
+ if ($confirm -notmatch "^[Yy]$") {
853
+ Write-Info "Uninstallation cancelled"
854
+ return
855
+ }
856
+
857
+ Write-Host ""
858
+
859
+ # Stop running instance
860
+ if (Test-IsRunning) {
861
+ Write-Info "Stopping running instance..."
862
+ Stop-App
863
+ } else {
864
+ # Check for orphaned sshift node processes
865
+ Stop-AllSshiftProcesses
866
+ }
867
+
868
+ # Give extra time for file handles to be released
869
+ Write-Info "Waiting for file handles to be released..."
870
+ Start-Sleep -Seconds 3
871
+
872
+ # Remove autostart
873
+ Write-Info "Removing autostart configuration..."
874
+ Remove-Autostart
875
+
876
+ # Uninstall via npm
877
+ Write-Info "Uninstalling sshift..."
878
+ npm uninstall -g @lethevimlet/sshift
879
+
880
+ if ($LASTEXITCODE -ne 0) {
881
+ Write-Warning "npm uninstall failed. If you see permission errors, try running PowerShell as Administrator"
882
+
883
+ # Retry once after a longer wait if it failed (file may still be locked)
884
+ Write-Info "Retrying uninstall after waiting for file handles to be released..."
885
+ Start-Sleep -Seconds 5
886
+ npm uninstall -g @lethevimlet/sshift
887
+
888
+ if ($LASTEXITCODE -ne 0) {
889
+ Write-Warning "Uninstall still failed. You may need to close any applications using sshift and try again"
890
+ } else {
891
+ Write-Success "sshift uninstalled successfully on retry"
892
+ }
893
+ }
894
+
895
+ # Remove installation directory
896
+ if (Test-Path $installDir) {
897
+ Write-Info "Removing configuration directory..."
898
+ Remove-Item -Path $installDir -Recurse -Force -ErrorAction SilentlyContinue
899
+ Write-Success "Configuration directory removed"
900
+ }
901
+
902
+ # Remove from PATH
903
+ Write-Info "Removing PATH configuration..."
904
+ $userPath = [Environment]::GetEnvironmentVariable("PATH", "User")
905
+ $newPath = ($userPath -split ';' | Where-Object { $_ -ne $BinDir }) -join ';'
906
+ [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")
907
+
908
+ Write-Host ""
909
+ Write-Host "=========================================="
910
+ Write-Host "sshift uninstalled successfully!" -ForegroundColor Green
911
+ Write-Host "=========================================="
912
+ Write-Host ""
913
+ Write-Info "You may need to restart your terminal for PATH changes to take effect"
914
+ }
915
+
916
+ # Check for updates
917
+ function Test-Updates {
918
+ Write-Info "Checking for updates..."
919
+
920
+ $localVersion = Get-InstalledVersion
921
+ $remoteVersion = Get-LatestVersion
922
+
923
+ Write-Info "Installed version: $localVersion"
924
+ Write-Info "Latest version: $remoteVersion"
925
+
926
+ $result = Compare-Versions -LocalVersion $localVersion -RemoteVersion $remoteVersion
927
+
928
+ if ($result -eq 1) {
929
+ Write-Warning "New version available: $remoteVersion (current: $localVersion)"
930
+ return $false
931
+ } elseif ($result -eq 2) {
932
+ Write-Info "Local version is newer than remote (development version?)"
933
+ return $true
934
+ } else {
935
+ Write-Success "Already up to date (version $localVersion)"
936
+ return $true
937
+ }
938
+ }
939
+
940
+ # Main installation process
941
+ function Main {
942
+ # Check if running as Administrator
943
+ $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
944
+ if (-not $isAdmin) {
945
+ Write-Host ""
946
+ Write-Host "=========================================="
947
+ Write-Host " sshift Installation Script"
948
+ Write-Host "=========================================="
949
+ Write-Host ""
950
+ Write-Host "[ERROR] This script requires Administrator privileges." -ForegroundColor Red
951
+ Write-Host ""
952
+ Write-Host "Please run PowerShell as Administrator and try again:" -ForegroundColor Yellow
953
+ Write-Host " 1. Right-click PowerShell -> 'Run as Administrator'" -ForegroundColor Cyan
954
+ Write-Host " 2. Run the installation command again" -ForegroundColor Cyan
955
+ Write-Host ""
956
+ Write-Host "Press any key to exit..."
957
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
958
+ exit 1
959
+ }
960
+
961
+ # Handle uninstall
962
+ if ($uninstall) {
963
+ Uninstall-Sshift
964
+ Write-Host ""
965
+ Write-Host "Press any key to exit..."
966
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
967
+ exit 0
968
+ }
969
+
970
+ # Handle status check
971
+ if ($status) {
972
+ if (Test-IsRunning) {
973
+ $pid = Get-Content $PidFile
974
+ Write-Success "sshift is running (PID: $pid)"
975
+ } else {
976
+ Write-Info "sshift is not running"
977
+ }
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 stop
985
+ if ($stop) {
986
+ Stop-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 restart
994
+ if ($restart) {
995
+ Write-Info "Restarting sshift..."
996
+ Stop-App
997
+ Start-App
998
+ Write-Host ""
999
+ Write-Host "Press any key to exit..."
1000
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1001
+ exit 0
1002
+ }
1003
+
1004
+ # Handle start
1005
+ if ($start) {
1006
+ Start-App
1007
+ Write-Host ""
1008
+ Write-Host "Press any key to exit..."
1009
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1010
+ exit 0
1011
+ }
1012
+
1013
+ # Handle update-only mode
1014
+ if ($update) {
1015
+ # Check if installed
1016
+ if (-not (Command-Exists "sshift")) {
1017
+ Write-Error "sshift is not installed"
1018
+ }
1019
+
1020
+ Write-Host ""
1021
+ Write-Host "=========================================="
1022
+ Write-Host " sshift Update Script"
1023
+ Write-Host "=========================================="
1024
+ Write-Host ""
1025
+
1026
+ Update-Sshift
1027
+
1028
+ Show-Summary
1029
+
1030
+ Write-Host ""
1031
+ Write-Host "Press any key to exit..."
1032
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1033
+ exit 0
1034
+ }
1035
+
1036
+ Write-Host ""
1037
+ Write-Host "=========================================="
1038
+ Write-Host " sshift Installation Script"
1039
+ Write-Host "=========================================="
1040
+ Write-Host ""
1041
+
1042
+ # Show configuration
1043
+ Write-Info "Installation method: npm"
1044
+ if ($ServerPort -ne "") {
1045
+ Write-Info "Server port: $ServerPort"
1046
+ }
1047
+
1048
+ # Check if already installed
1049
+ if (Command-Exists "sshift") {
1050
+ Write-Info "sshift is already installed"
1051
+
1052
+ # Check for updates
1053
+ $upToDate = Test-Updates
1054
+ if ($upToDate) {
1055
+ # No update needed
1056
+ if (Test-IsRunning) {
1057
+ $pid = Get-Content $PidFile
1058
+ Write-Info "sshift is already running (PID: $pid)"
1059
+ }
1060
+ } else {
1061
+ # Update available
1062
+ $confirm = Read-Host "Update sshift? [Y/n]"
1063
+ if ($confirm -notmatch "^[Nn]$") {
1064
+ Update-Sshift
1065
+ }
1066
+ }
1067
+ } else {
1068
+ # Fresh installation
1069
+ # Install Node.js if needed
1070
+ Install-NodeJS
1071
+
1072
+ # Install sshift via npm
1073
+ Install-Sshift
1074
+
1075
+ # Create config file with port (if specified)
1076
+ New-Config
1077
+ }
1078
+
1079
+ # Always ask about PATH and autostart (even if already installed)
1080
+ Write-Host ""
1081
+ Write-Info "Configuration options:"
1082
+ Write-Host ""
1083
+
1084
+ # Add to PATH
1085
+ $addToPath = Read-Host "Add sshift to PATH? [Y/n]"
1086
+ if ($addToPath -notmatch "^[Nn]$") {
1087
+ Add-ToPath
1088
+ }
1089
+
1090
+ # Ask about autostart
1091
+ $enableAutostart = Read-Host "Start sshift automatically on boot? [y/N]"
1092
+ if ($enableAutostart -match "^[Yy]$") {
1093
+ Enable-Autostart
1094
+ }
1095
+
1096
+ # Start sshift if not already running
1097
+ if (-not (Test-IsRunning)) {
1098
+ Start-App
1099
+ }
1100
+
1101
+ # Print summary
1102
+ Show-Summary
1103
+
1104
+ # Pause before exit
1105
+ Write-Host ""
1106
+ Write-Host "Press any key to exit..."
1107
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1108
+ }
1109
+
1110
+ # Run main function
1111
+ try {
1112
+ Main
1113
+ } catch {
1114
+ Write-Host ""
1115
+ Write-Host "[ERROR] An unexpected error occurred:" -ForegroundColor Red
1116
+ Write-Host $_.Exception.Message
1117
+ Write-Host ""
1118
+ Write-Host "Press any key to exit..."
1119
+ $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
1120
+ exit 1
1121
+ }