Skip to main content

REMOTE_SCRIPT

Constant REMOTE_SCRIPT 

Source
pub const REMOTE_SCRIPT: &str = "# Windows OpenSSH runs outside the desktop session. A short-lived task runs as\n# the same signed-in user, at limited privilege. No passwords are stored.\n$ErrorActionPreference = \'Stop\'\n$ProgressPreference = \'SilentlyContinue\'\n[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)\n[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$task = \'OneNoteCli-\' + [Guid]::NewGuid().ToString(\'N\')\n$directory = $null\n$registered = $false\n$started = $false\n$envelope = $null\ntry {\n    $envelope = [Console]::In.ReadToEnd() | ConvertFrom-Json\n    $user = [Security.Principal.WindowsIdentity]::GetCurrent()\n    $directory = Join-Path $env:LOCALAPPDATA (\'OneNoteCli\\requests\\\' + $task)\n    # Set permissions at creation, before any page text is written.\n    $acl = New-Object Security.AccessControl.DirectorySecurity\n    $acl.SetAccessRuleProtection($true, $false)\n    foreach ($sid in @($user.User, [Security.Principal.SecurityIdentifier]::new(\'S-1-5-18\'))) {\n        $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, \'FullControl\', \'ContainerInherit,ObjectInherit\', \'None\', \'Allow\'))\n    }\n    [void][IO.Directory]::CreateDirectory($directory, $acl)\n    $utf8 = New-Object Text.UTF8Encoding($false)\n    [IO.File]::WriteAllBytes((Join-Path $directory \'bridge.ps1\'), [Convert]::FromBase64String($envelope.script_base64))\n    [IO.File]::WriteAllText((Join-Path $directory \'input.json\'), ($envelope.request | ConvertTo-Json -Depth 10 -Compress), $utf8)\n    # The runner has its own deadline, even if the SSH client disconnects.\n    $runner = @\'\n$ErrorActionPreference = \'Stop\'\n$process = $null\ntry {\n    $process = Start-Process -FilePath \"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -ArgumentList \'-NoLogo -NoProfile -NonInteractive -STA -ExecutionPolicy Bypass -File bridge.ps1\' -WorkingDirectory $pwd.Path -RedirectStandardInput input.json -RedirectStandardOutput output.json -RedirectStandardError error.txt -WindowStyle Hidden -PassThru\n    if (-not $process.WaitForExit(45000)) {\n        $process.Kill()\n        $process.WaitForExit()\n        throw \'OneNote did not respond within 45 seconds; check its desktop for prompts.\'\n    }\n    [IO.File]::WriteAllText((Join-Path $pwd.Path \'done\'), \'complete\')\n} catch {\n    [IO.File]::WriteAllText((Join-Path $pwd.Path \'failed\'), $_.Exception.Message)\n} finally {\n    if ($null -ne $process) { $process.Dispose() }\n}\n\'@\n    $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($runner))\n    $action = New-ScheduledTaskAction -Execute \"$env:SystemRoot\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -Argument \"-NoLogo -NoProfile -NonInteractive -STA -WindowStyle Hidden -EncodedCommand $encoded\" -WorkingDirectory $directory\n    $principal = New-ScheduledTaskPrincipal -UserId $user.Name -LogonType Interactive -RunLevel Limited\n    $settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Seconds 60) -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries\n    Register-ScheduledTask -TaskName $task -Action $action -Principal $principal -Settings $settings | Out-Null\n    $registered = $true\n    # Once Start is attempted, an interrupted write must be treated as uncertain.\n    $started = $true\n    Start-ScheduledTask -TaskName $task\n    $clock = [Diagnostics.Stopwatch]::StartNew()\n    while (-not (Test-Path (Join-Path $directory \'done\'))) {\n        if (Test-Path (Join-Path $directory \'failed\')) { throw [IO.File]::ReadAllText((Join-Path $directory \'failed\')) }\n        if ($clock.Elapsed.TotalSeconds -gt 65) { throw \'Desktop task timed out. Sign in to Windows as the SSH user and open OneNote, then run onenote doctor.\' }\n        Start-Sleep -Milliseconds 200\n    }\n    $output = Join-Path $directory \'output.json\'\n    if ((Get-Item $output).Length -gt 33554432) { throw \'OneNote response exceeded 32 MiB; narrow the scope.\' }\n    $response = [IO.File]::ReadAllText($output)\n    if ([string]::IsNullOrWhiteSpace($response)) { throw \'The desktop bridge returned no response; check OneNote in the signed-in desktop.\' }\n    [Console]::Write($response)\n} catch {\n    $kind = if ($started -and $envelope.write) { \'write_uncertain\' } else { \'desktop_error\' }\n    $message = $_.Exception.Message\n    if (-not $started) { $message += \' SSH desktop access requires a signed-in Windows user with permission to register an interactive scheduled task.\' }\n    if ($kind -eq \'write_uncertain\') { $message += \' The write may have taken effect; inspect OneNote before retrying.\' }\n    [Console]::WriteLine((@{error=@{kind=$kind;message=$message}} | ConvertTo-Json -Compress))\n} finally {\n    if ($registered) {\n        Stop-ScheduledTask -TaskName $task -ErrorAction SilentlyContinue\n        Unregister-ScheduledTask -TaskName $task -Confirm:$false -ErrorAction SilentlyContinue\n    }\n    if ($null -ne $directory -and (Test-Path $directory)) { Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue }\n}\n";