#requires -version 5.1 try { [Console]::BackgroundColor = [ConsoleColor]::DarkBlue; [Console]::ForegroundColor = [ConsoleColor]::Cyan; System.Management.Automation.Internal.Host.InternalHost.UI.RawUI.BackgroundColor = [ConsoleColor]::DarkBlue; System.Management.Automation.Internal.Host.InternalHost.UI.RawUI.ForegroundColor = [ConsoleColor]::Cyan } catch {} # NEXORA TOOLS - Launcher v0.3.0 (Matrix++ UI) # Ejecutar: irm https://tools.nexoraapps.com.ar | iex # Con URL local: $env:NEXORA_TOOLS_URL="http://127.0.0.1:8095"; irm http://127.0.0.1:8095 | iex $BaseUrl = if ($env:NEXORA_TOOLS_URL) { $env:NEXORA_TOOLS_URL } else { "https://tools.nexoraapps.com.ar" } [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 $OutputEncoding = [System.Text.Encoding]::UTF8 try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 } catch { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } $ErrorActionPreference = "SilentlyContinue" $Global:NexoraToken = $null $Global:NexoraUser = $null $Global:NexoraConfigPath = "$env:USERPROFILE\.nexora-tools" $Global:TokenFile = "$Global:NexoraConfigPath\token.json" $script:UiWidth = 78 function Get-UiWidth { try { $w = $Host.UI.RawUI.WindowSize.Width if ($w -and $w -gt 60) { # dejar margen y evitar desbordes por el prefijo de 2 espacios $usable = $w - 4 if ($usable -gt 110) { $usable = 110 } if ($usable -lt 60) { $usable = 60 } $script:UiWidth = $usable } } catch { $script:UiWidth = 78 } } function Test-IsAdmin { $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) return $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) } function Initialize-Config { if (-not (Test-Path $Global:NexoraConfigPath)) { New-Item -ItemType Directory -Path $Global:NexoraConfigPath -Force | Out-Null } } function Write-UiLine { param([string]$Text = "", [string]$Color = "Cyan", [switch]$NoPrefix) if ($NoPrefix) { Write-Host $Text -ForegroundColor $Color } else { Write-Host " $Text" -ForegroundColor $Color } } function Write-FrameTop { param([string]$Title = "") $inner = $script:UiWidth - 2 if ($Title) { $label = " $Title " $pad = $inner - $label.Length if ($pad -lt 0) { $pad = 0 } $left = [math]::Floor($pad / 2) $right = $pad - $left Write-Host (" +" + ("=" * $left) + $label + ("=" * $right) + "+") -ForegroundColor Cyan } else { Write-Host (" +" + ("=" * $inner) + "+") -ForegroundColor Cyan } } function Write-FrameMid { $inner = $script:UiWidth - 2 Write-Host (" +" + ("-" * $inner) + "+") -ForegroundColor Cyan } function Write-FrameBottom { $inner = $script:UiWidth - 2 Write-Host (" +" + ("=" * $inner) + "+") -ForegroundColor Cyan } function Write-FrameRow { param([string]$Text = "", [string]$Color = "Cyan") $inner = $script:UiWidth - 4 $t = [string]$Text if ($t.Length -gt $inner) { $t = $t.Substring(0, $inner) } # sin "..." para no perder info; se usa wrap afuera $pad = $inner - $t.Length if ($pad -lt 0) { $pad = 0 } Write-Host (" | " + $t + (" " * $pad) + " |") -ForegroundColor $Color } function Write-FrameRowWrap { param([string]$Text = "", [string]$Color = "Cyan", [string]$Prefix = "", [string]$ContinuationPrefix = "") $inner = $script:UiWidth - 4 $max = $inner - $Prefix.Length if ($max -lt 10) { $max = 10 } $words = ([string]$Text) -split '\s+' $line = $Prefix $first = $true foreach ($w in $words) { if (-not $w) { continue } $candidate = $line + $w if (($candidate.Length -gt $inner) -and ($line.TrimEnd().Length -gt $Prefix.Length)) { Write-FrameRow $line $Color $line = $ContinuationPrefix + $w + " " $first = $false } else { $line = $candidate + " " } } if ($line.Trim().Length -gt 0 -or $first) { Write-FrameRow $line.TrimEnd() $Color } } function Invoke-MatrixRain { param([int]$Rows = 3, [int]$Cols = 0, [int]$DelayMs = 18) $random = New-Object System.Random $chars = "01ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#$%&*+-=" if ($Cols -le 0) { $Cols = [Math]::Max(40, $script:UiWidth - 2) } for ($row = 0; $row -lt $Rows; $row++) { $line = " " for ($col = 0; $col -lt $Cols; $col++) { $line += $chars[$random.Next(0, $chars.Length)] } Write-Host $line -ForegroundColor Gray Start-Sleep -Milliseconds $DelayMs } } function Show-Banner { Clear-Host Get-UiWidth [Console]::BackgroundColor = [ConsoleColor]::DarkBlue [Console]::ForegroundColor = [ConsoleColor]::Cyan try { $host.UI.RawUI.WindowTitle = "NEXORA TOOLS v0.3.0" } catch {} Invoke-MatrixRain -Rows 1 -DelayMs 8 Write-Host "" Write-Host " ███╗ ██╗███████╗██╗ ██╗ ██████╗ ██████╗ █████╗ " -NoNewline -ForegroundColor Cyan; Write-Host " ████████╗ ██████╗ ██████╗ ██╗ ███████╗" -ForegroundColor Gray Write-Host " ████╗ ██║██╔════╝╚██╗██╔╝██╔═══██╗██╔══██╗██╔══██╗" -NoNewline -ForegroundColor Cyan; Write-Host " ╚══██╔══╝██╔═══██╗██╔═══██╗██║ ██╔════╝" -ForegroundColor Gray Write-Host " ██╔██╗ ██║█████╗ ╚███╔╝ ██║ ██║██████╔╝███████║" -NoNewline -ForegroundColor Cyan; Write-Host " ██║ ██║ ██║██║ ██║██║ ███████╗" -ForegroundColor Gray Write-Host " ██║╚██╗██║██╔══╝ ██╔██╗ ██║ ██║██╔══██╗██╔══██║" -NoNewline -ForegroundColor Cyan; Write-Host " ██║ ██║ ██║██║ ██║██║ ╚════██║" -ForegroundColor Gray Write-Host " ██║ ╚████║███████╗██╔╝ ██╗╚██████╔╝██║ ██║██║ ██║" -NoNewline -ForegroundColor Cyan; Write-Host " ██║ ╚██████╔╝╚██████╔╝███████╗███████║" -ForegroundColor Gray Write-Host " ╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝" -NoNewline -ForegroundColor Cyan; Write-Host " ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝╚══════╝" -ForegroundColor Gray Write-Host "" Write-FrameTop -Title "NEXORA TOOLS | Suite de Mantenimiento para Windows" $who = if ($Global:NexoraUser) { $Global:NexoraUser } else { "sin sesion" } $admin = if (Test-IsAdmin) { "Administrador" } else { "Usuario estándar" } Write-FrameRow ("Version 0.3.0 | Sesion: $who | Privilegios: $admin") "Gray" Write-FrameBottom Write-Host "" } function Show-Section { param([string]$Title) Write-Host "" Write-FrameTop -Title $Title } function Get-HttpStatusCode { param($ErrorRecord) try { $resp = $ErrorRecord.Exception.Response if ($resp) { return [int]$resp.StatusCode } } catch {} return 0 } function Save-Token { param([string]$Token, [string]$Username, [int]$ExpiresAt) Initialize-Config @{ token = $Token; username = $Username; expires_at = $ExpiresAt } | ConvertTo-Json | Out-File -FilePath $Global:TokenFile -Encoding UTF8 } function Load-SavedToken { Initialize-Config if (Test-Path $Global:TokenFile) { try { $saved = Get-Content $Global:TokenFile -Raw -Encoding UTF8 | ConvertFrom-Json if ($saved.token -and $saved.expires_at) { # Comparar en UTC (evita bug de zona horaria: expiracion fantasma) $exp = [DateTimeOffset]::FromUnixTimeSeconds([long]$saved.expires_at) if ($exp -gt [DateTimeOffset]::UtcNow) { # Validar con el servidor antes de confiar en el archivo local try { $headers = @{ Authorization = "Bearer $($saved.token)" } $me = Invoke-RestMethod -Uri "$BaseUrl/api/me" -Headers $headers -TimeoutSec 15 $Global:NexoraToken = $saved.token $Global:NexoraUser = $me.username return $true } catch { # Servidor rechazo el token: descartar y pedir login limpio Remove-Item $Global:TokenFile -Force -ErrorAction SilentlyContinue return $false } } } } catch {} # Token local vencido o corrupto: limpiar para evitar estados raros Remove-Item $Global:TokenFile -Force -ErrorAction SilentlyContinue } return $false } function Connect-Nexora { if (Load-SavedToken) { Write-UiLine "[OK] Sesion restaurada: $Global:NexoraUser" "Cyan" Start-Sleep -Milliseconds 700 return $true } Show-Section "AUTENTICACION" Write-FrameRow "Acceso seguro a Nexora Tools" "Gray" Write-FrameRow "Ingresa tus credenciales para continuar" "Gray" Write-FrameBottom Write-Host "" $username = Read-Host " Usuario" $securePass = Read-Host " Contrasena" -AsSecureString $password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePass)) $body = @{ username = $username; password = $password } | ConvertTo-Json # Reintentos ante fallos transitorios de red (max 3) for ($attempt = 1; $attempt -le 3; $attempt++) { try { Write-Host " [..] Conectando con el servidor..." -ForegroundColor Gray $resp = Invoke-RestMethod -Uri "$BaseUrl/api/login" -Method Post -Body $body -ContentType "application/json" -TimeoutSec 30 $Global:NexoraToken = $resp.token $Global:NexoraUser = $resp.username Save-Token -Token $resp.token -Username $resp.username -ExpiresAt (([DateTimeOffset]::UtcNow).ToUnixTimeSeconds() + $resp.expires_in) Write-Host "" Write-UiLine "[OK] Acceso concedido: $Global:NexoraUser" "Cyan" Start-Sleep -Milliseconds 800 return $true } catch { $code = Get-HttpStatusCode $_ if ($code -eq 401 -or $code -eq 429) { # Error de credenciales o cuenta bloqueada: no tiene sentido reintentar Write-Host "" if ($code -eq 429) { Write-UiLine "[X] Demasiados intentos. Cuenta bloqueada temporalmente (15 min)." "Red" } else { Write-UiLine "[X] Usuario o contrasena incorrectos." "Red" } return $false } if ($attempt -lt 3) { Write-UiLine "[!] Sin conexion con el servidor, reintentando ($attempt/3)..." "Yellow" Start-Sleep -Seconds 3 } else { Write-Host "" Write-UiLine "[X] No se pudo conectar con el servidor (red/servicio no disponible)." "Red" Write-UiLine "[i] Verifica tu conexion o reintenta en unos segundos." "Gray" return $false } } } return $false } function Get-Modules { # Reintentos ante fallos transitorios; si el token expira, pide login de nuevo for ($attempt = 1; $attempt -le 3; $attempt++) { try { $headers = @{ Authorization = "Bearer $Global:NexoraToken" } $resp = Invoke-RestMethod -Uri "$BaseUrl/api/modules" -Headers $headers -TimeoutSec 30 return $resp.modules } catch { $code = Get-HttpStatusCode $_ if ($code -eq 401 -and $attempt -eq 1) { # Token expiro en pleno uso: limpiar y volver a autenticar Remove-Item $Global:TokenFile -Force -ErrorAction SilentlyContinue $Global:NexoraToken = $null if (Connect-Nexora) { continue } return @() } if ($attempt -lt 3) { Write-UiLine "[!] Sin conexion, reintentando ($attempt/3)..." "Yellow" Start-Sleep -Seconds 3 } } } Write-UiLine "[X] No se pudieron obtener los modulos (servidor no disponible)." "Red" return @() } function Invoke-Module { param([string]$ModuleName, [string]$ModuleTitle) # Descargar codigo con reintentos y recuperacion de sesion $code = $null for ($attempt = 1; $attempt -le 3; $attempt++) { try { Write-Host " [..] Descargando modulo..." -ForegroundColor Gray $headers = @{ Authorization = "Bearer $Global:NexoraToken" } $code = Invoke-RestMethod -Uri "$BaseUrl/api/module/$ModuleName" -Headers $headers -TimeoutSec 90 break } catch { $errCode = Get-HttpStatusCode $_ if ($errCode -eq 401 -and $attempt -eq 1) { Remove-Item $Global:TokenFile -Force -ErrorAction SilentlyContinue $Global:NexoraToken = $null if (Connect-Nexora) { continue } return } if ($attempt -lt 3) { Write-UiLine "[!] Error al descargar el modulo, reintentando ($attempt/3)..." "Yellow" Start-Sleep -Seconds 3 } else { Write-Host "" Write-UiLine "[X] No se pudo descargar el modulo '$ModuleName' (red o servidor)." "Red" Start-Sleep -Seconds 3 return } } } if (-not $code) { return } try { $tempFile = "$env:TEMP\nexora_$ModuleName_$(Get-Random).ps1" $code | Out-File -FilePath $tempFile -Encoding UTF8 Write-Host "" Write-FrameTop -Title "EJECUTANDO MODULO" Write-FrameRow ("Modulo : " + $ModuleTitle) "Cyan" Write-FrameRow ("ID : " + $ModuleName) "Gray" Write-FrameRow ("Temp : " + $tempFile) "Gray" if (-not (Test-IsAdmin)) { Write-FrameRow "AVISO : sin privilegios de Administrador (algunos modulos pueden fallar)" "Yellow" } else { Write-FrameRow "AVISO : ejecutando con privilegios de Administrador" "Gray" } Write-FrameBottom Write-Host "" Invoke-MatrixRain -Rows 1 -Cols 76 -DelayMs 6 Write-Host "" & powershell -ExecutionPolicy Bypass -File $tempFile $modExit = $LASTEXITCODE Write-Host "" Write-FrameTop -Title "RESULTADO" if ($modExit -ne 0 -and $null -ne $modExit) { Write-FrameRow ("Modulo finalizado con avisos (codigo $modExit)") "Yellow" } else { Write-FrameRow "Modulo finalizado correctamente" "Cyan" } Write-FrameBottom Start-Sleep -Seconds 1 Remove-Item $tempFile -Force -ErrorAction SilentlyContinue } catch { Write-Host "" Write-UiLine "[X] Fallo al ejecutar modulo: $_" "Red" Start-Sleep -Seconds 3 } } function Show-Menu { param([array]$Modules) while ($true) { Show-Banner Write-FrameTop -Title "PANEL DE CONTROL" $u = if ($Global:NexoraUser) { $Global:NexoraUser } else { "-" } $priv = if (Test-IsAdmin) { "ADMIN" } else { "USUARIO" } Write-FrameRow ("Usuario: $u | Privilegios: $priv | Modulos: $($Modules.Count)") "Gray" Write-FrameMid $i = 1 foreach ($mod in $Modules) { $num = "{0,2}" -f $i $name = [string]$mod.title $desc = [string]$mod.desc Write-FrameRow ("[{0}] {1}" -f $num, $name) "Cyan" # Descripcion completa debajo (sin cortar), con wrap si no entra Write-FrameRowWrap -Text $desc -Color "Gray" -Prefix " " -ContinuationPrefix " " $i++ } Write-FrameMid Write-FrameRow "[ 0] Salir / Cerrar sesion" "Gray" Write-FrameRow "Tip: seleccion multiple con comas (ej: 1,2,4) o 'q' para salir" "Gray" Write-FrameBottom Write-Host "" $choice = Read-Host " >> Selecciona opcion" if ($choice -eq "0" -or $choice -eq "q" -or $choice -eq "Q" -or $choice -eq "exit") { Show-Section "SESION" Write-FrameRow "Cerrando sesion..." "Yellow" Write-FrameBottom Remove-Item $Global:TokenFile -Force -ErrorAction SilentlyContinue $Global:NexoraToken = $null $Global:NexoraUser = $null Start-Sleep -Seconds 1 Clear-Host Write-Host "" Write-UiLine "[OK] Hasta luego. Nexora Tools finalizado." "Cyan" Write-Host "" return } # Soporta seleccion multiple: "1,2,4" o "1 2 4" if ($choice -match '[,\s]') { $parts = $choice -split '[,\s]+' | Where-Object { $_ -ne '' } $indices = @() foreach ($p in $parts) { $trimmed = $p.Trim() if ($trimmed -match '^\d+$') { $indices += [int]$trimmed } } if ($indices.Count -eq 0) { Write-Host "" Write-UiLine "[X] No se ingresaron numeros validos" "Red" Start-Sleep -Seconds 2 continue } $validIndices = $indices | Where-Object { $_ -ge 1 -and $_ -le $Modules.Count } if ($validIndices.Count -eq 0) { Write-Host "" Write-UiLine "[X] Ningun numero valido (rango: 1-$($Modules.Count))" "Red" Start-Sleep -Seconds 2 continue } Write-Host "" Write-FrameTop -Title "EJECUCION EN COLA" foreach ($idx in $validIndices) { $mod = $Modules[$idx - 1] Write-FrameRow ("[$idx] " + $mod.title) "Cyan" } Write-FrameBottom Write-Host "" $confirm = Read-Host " Ejecutar en orden? (S/N)" if ($confirm -ne "S" -and $confirm -ne "s") { continue } foreach ($idx in $validIndices) { $selected = $Modules[$idx - 1] Invoke-Module -ModuleName $selected.name -ModuleTitle $selected.title Write-Host "" Write-Host " Presiona Enter para continuar con el siguiente..." -ForegroundColor Gray Read-Host } continue } if ($choice -match '^\d+$' -and [int]$choice -ge 1 -and [int]$choice -le $Modules.Count) { $selected = $Modules[[int]$choice - 1] Invoke-Module -ModuleName $selected.name -ModuleTitle $selected.title Write-Host "" Write-Host " Presiona Enter para volver al menu..." -ForegroundColor Gray Read-Host } else { Write-Host "" Write-UiLine "[X] Opcion invalida. Usa un numero del menu, 1,2,4 o q para salir." "Red" Start-Sleep -Seconds 1 } } } # ==================== MAIN ==================== Show-Banner if (Connect-Nexora) { Write-Host " [..] Cargando modulos..." -ForegroundColor Gray $modules = Get-Modules if ($modules.Count -gt 0) { Write-UiLine "[OK] $($modules.Count) modulos listos." "Cyan" Start-Sleep -Milliseconds 500 Show-Menu -Modules $modules } else { Write-UiLine "[X] No hay modulos disponibles" "Red" Start-Sleep -Seconds 2 } } else { Write-Host "" Write-UiLine "[X] No se pudo iniciar sesion. Verifica la URL o tu conexion." "Red" Write-UiLine "[i] Local: `$env:NEXORA_TOOLS_URL='http://127.0.0.1:8095'; irm http://127.0.0.1:8095 | iex" "Gray" Start-Sleep -Seconds 4 }