Deploy Windows gateway as persistent scheduled task and verify public ADB

This commit is contained in:
tongtong committed 2026-11-12 13:32:50 +08:00
1 parent c38f067bea
commit 3fb894c1a1
9 files changed
+193 -13

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
# Windows device gateway deployment
These scripts install the Rust gateway as a background Scheduled Task. This is not a native Windows Service binary. They require an administrator account to register the startup trigger, and prefer PowerShell 7 when installed.
## Installation
Default private directory: `%LOCALAPPDATA%\AndroidDeviceStreaming\agent`.
1. Run `prepare-agent.ps1` on the target computer. It creates the directory and grants access only to the current account, SYSTEM and Administrators.
2. Copy the following staged files into that directory:
| Source | Staged name |
|---|---|
| `bin/ads-agent.exe` | `ads-agent.exe.new` |
| `run-agent.ps1` | `run-agent.ps1.new` |
| Your edited `agent.example.json` | `agent.json.new` |
| Private agent-role environment file | `agent.env.new` |
| `install-agent.ps1` | `install-agent.ps1` |
3. Run `install-agent.ps1` from that directory. Supply the current Windows account credential at the secure prompt. For an encrypted remote-management channel, `-PasswordFromStdin` reads the password from standard input rather than the command line. Do not put passwords into scripts.
The installer backs up existing gateway files inside the protected directory, replaces only its own files, and refuses to overwrite an unrelated task with the same name. Its installation path is checked before any process stop or file replacement.
Task `ADS-Agent` uses password logon so it can run without an interactive desktop session. Windows Task Scheduler stores the account credential; it is not stored in the gateway JSON, environment file or source repository. Re-register the task if the Windows account password changes.
Configured behavior:
- Startup and account-logon triggers; duplicate instances ignored.
- Hidden, non-interactive PowerShell runner, with the Rust child in its process tree.
- No execution time limit; restart on process failure after one minute, up to 999 retries.
- Rust itself reconnects to the relay with a 1–30 second backoff.
- `agent.json` configures relay URL, public origin override, device alias and phone endpoint.
- `agent.env` contains only the gateway role credential and optional non-sensitive connection settings.
- Log: `logs/agent.log`; rotated on runner start when it exceeds 10 MiB.
## Deployed computer
Installed on `192.168.5.222` as account `TT`:
```text
C:\Users\TT\AppData\Local\AndroidDeviceStreaming\agent
```
Device: `home-phone`; target: `192.168.100.141:5555`; relay: `wss://ttstd.com/ads`; public origin: `175.178.213.60:443` with normal domain TLS validation.
Task registration, task restart, executable hash and post-restart public ADB smoke test were verified. Startup triggers were inspected; the computer was not rebooted. The Rust process working set was about 8.7 MiB at the sampled instant, excluding the PowerShell runner.
Management commands on that computer:
```powershell
Get-ScheduledTask -TaskName ADS-Agent
Get-ScheduledTaskInfo -TaskName ADS-Agent
Get-Content "$env:LOCALAPPDATA\AndroidDeviceStreaming\agent\logs\agent.log" -Tail 30
Start-ScheduledTask -TaskName ADS-Agent
Stop-ScheduledTask -TaskName ADS-Agent
```
+6
View File
@@ -0,0 +1,6 @@
{
"server": "wss://ttstd.com/ads",
"connect_address": "175.178.213.60:443",
"device": "home-phone",
"target": "192.168.100.141:5555"
}
+65
View File
@@ -0,0 +1,65 @@
param(
[string]$Directory = (Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent'),
[switch]$PasswordFromStdin
)
$ErrorActionPreference = 'Stop'
$root = [System.IO.Path]::GetFullPath($Directory).TrimEnd('\')
$expected = [System.IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent')).TrimEnd('\')
if (-not $root.Equals($expected, [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'Unexpected installation directory; refusing to replace files or stop processes'
}
$identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$taskName = 'ADS-Agent'
$runner = Join-Path $root 'run-agent.ps1'
$executable = Join-Path $root 'ads-agent.exe'
$files = @('ads-agent.exe', 'run-agent.ps1', 'agent.json', 'agent.env')
foreach ($file in $files) {
if (-not (Test-Path -LiteralPath (Join-Path $root ($file + '.new')))) { throw "Missing staging file: $file.new" }
}
$newConfig = Get-Content -LiteralPath (Join-Path $root 'agent.json.new') -Raw | ConvertFrom-Json
if (-not $newConfig.server.StartsWith('wss://') -or -not $newConfig.device -or -not $newConfig.target) {
throw 'Invalid gateway configuration'
}
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
if ($existingTask) {
$owned = @($existingTask.Actions | Where-Object {
$_.Arguments -and $_.Arguments.IndexOf($runner, [System.StringComparison]::OrdinalIgnoreCase) -ge 0
}).Count -gt 0
if (-not $owned) { throw 'A different task already owns ADS-Agent; refusing to overwrite it' }
Stop-ScheduledTask -TaskName $taskName
}
Get-Process ads-agent -ErrorAction SilentlyContinue | Where-Object {
$_.Path -and $_.Path.Equals($executable, [System.StringComparison]::OrdinalIgnoreCase)
} | Stop-Process -Force
$stamp = Get-Date -Format yyyyMMdd-HHmmss
foreach ($file in $files) {
$destination = Join-Path $root $file
if (Test-Path -LiteralPath $destination) { Copy-Item -LiteralPath $destination -Destination ($destination + '.backup-' + $stamp) }
Move-Item -LiteralPath (Join-Path $root ($file + '.new')) -Destination $destination -Force
}
$account = $identity.Name
$shell = Get-Command pwsh.exe -ErrorAction SilentlyContinue
$shellPath = if ($shell) { $shell.Source } else { "$env:WINDIR\System32\WindowsPowerShell\v1.0\powershell.exe" }
$action = New-ScheduledTaskAction -Execute $shellPath `
-Argument "-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$runner`"" -WorkingDirectory $root
$triggers = @((New-ScheduledTaskTrigger -AtStartup), (New-ScheduledTaskTrigger -AtLogOn -User $account))
$settings = New-ScheduledTaskSettingsSet -MultipleInstances IgnoreNew -RestartCount 999 `
-RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) `
-StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden
$principal = New-ScheduledTaskPrincipal -UserId $account -LogonType Password -RunLevel Limited
$task = New-ScheduledTask -Action $action -Trigger $triggers -Settings $settings -Principal $principal
if ($PasswordFromStdin) {
$password = [Console]::In.ReadLine()
} else {
$credential = Get-Credential -UserName $account -Message 'Account password for unattended gateway startup'
$password = $credential.GetNetworkCredential().Password
}
try {
Register-ScheduledTask -TaskName $taskName -InputObject $task -User $account -Password $password -Force | Out-Null
} finally { $password = $null }
Start-ScheduledTask -TaskName $taskName
Start-Sleep -Seconds 2
Get-ScheduledTask -TaskName $taskName | Select-Object TaskName,State
Get-ScheduledTaskInfo -TaskName $taskName | Select-Object LastRunTime,LastTaskResult
Write-Output "Installed gateway in $root"
+8
View File
@@ -0,0 +1,8 @@
$ErrorActionPreference = 'Stop'
$root = [System.IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent'))
New-Item -ItemType Directory -Path $root -Force | Out-Null
$sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$grant = '*' + $sid + ':(OI)(CI)F'
icacls $root /inheritance:r /grant:r $grant '*S-1-5-18:(OI)(CI)F' '*S-1-5-32-544:(OI)(CI)F'
if ($LASTEXITCODE -ne 0) { throw 'Cannot protect deployment directory ACL' }
Write-Output "Prepared private deployment directory: $root"
+23
View File
@@ -0,0 +1,23 @@
$ErrorActionPreference = 'Stop'
$root = [System.IO.Path]::GetFullPath($PSScriptRoot)
$config = Get-Content -LiteralPath (Join-Path $root 'agent.json') -Raw | ConvertFrom-Json
$tokenFile = Join-Path $root 'agent.env'
foreach ($line in Get-Content -LiteralPath $tokenFile) {
if ($line.StartsWith('ADS_AGENT_TOKEN=')) { $env:ADS_AGENT_TOKEN = $line.Substring(16) }
}
if (-not $env:ADS_AGENT_TOKEN -or $env:ADS_AGENT_TOKEN.Length -lt 32) { throw 'Missing agent token' }
if (-not $config.server.StartsWith('wss://')) { throw 'Public relay requires WSS' }
$env:RUST_LOG = 'info'
$logDirectory = Join-Path $root 'logs'
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
$logFile = Join-Path $logDirectory 'agent.log'
if ((Test-Path -LiteralPath $logFile) -and (Get-Item -LiteralPath $logFile).Length -gt 10MB) {
Move-Item -LiteralPath $logFile -Destination ($logFile + '.1') -Force
}
$arguments = @('--server', [string]$config.server, '--device', [string]$config.device, '--target', [string]$config.target)
if ($config.connect_address) { $arguments += @('--connect-address', [string]$config.connect_address) }
# Keep the child in this task's process tree. Task Scheduler owns its lifecycle.
# Tracing writes to stdout; stderr is also retained for startup diagnostics.
$ErrorActionPreference = 'Continue'
& (Join-Path $root 'ads-agent.exe') @arguments >> $logFile 2>&1
exit $LASTEXITCODE