Deploy Windows gateway as persistent scheduled task and verify public ADB
This commit is contained in:
1 parent
c38f067bea
commit
3fb894c1a1
9 files changed
+193
-13
No files matched your search
+1
-1
@@ -6,6 +6,6 @@ Examples are templates, not installed automatically. Replace paths, domain, user
|
||||
|
||||
- Linux: create a dedicated `ads` user and `/opt/ads`; protect `/etc/ads/*.env` so only the intended account/root can read them. `server.env` contains `ADS_AGENT_TOKEN=...` and `ADS_CLIENT_TOKEN=...`; `agent.env` contains only `ADS_AGENT_TOKEN=...`. Copy the respective systemd unit to `/etc/systemd/system/`, then enable it. The local client normally runs as the desktop user, so it shares that user's ADB server and keys.
|
||||
- macOS: edit the launchd plist, restrict its file permissions, and install it as the appropriate user's LaunchAgent. It contains a credential, so do not publish the edited file. Client launchd configuration can use the same pattern with `ads-client` and `ADS_CLIENT_TOKEN`.
|
||||
- Windows: the binaries run as foreground long-lived processes. Use Task Scheduler to launch them under the intended account at logon, with a startup wrapper that sets the token environment variable, and configure restart on failure. Keep wrapper/config files readable only by that account and administrators. Native Service Control Manager support and installers are not implemented; do not use `sc.exe create` directly on these binaries.
|
||||
- Windows: the gateway can be hosted as a background Scheduled Task using `deploy/windows/`; installation and task restart have been verified on the remote Windows PC. Credentials stay in an ACL-protected directory and the account password is stored by Task Scheduler. Native Service Control Manager support is not implemented; do not use `sc.exe create` directly on these binaries.
|
||||
|
||||
The Linux server unit has been deployed and verified on Debian 12. Agent service and macOS templates still require target-platform validation.
|
||||
@@ -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
|
||||
```
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -38,6 +38,8 @@ TLS 沿用现有主站证书,核验到的有效期截止 `2026-11-28 06:59:59
|
||||
|
||||
## 远程 Windows 电脑
|
||||
|
||||
已部署到 `192.168.5.222`,目录为 `C:\Users\TT\AppData\Local\AndroidDeviceStreaming\agent`。`ADS-Agent` 计划任务已运行,使用账号 `TT` 的后台密码登录,设置开机和登录触发、故障重启。详细管理方式见 `deploy/windows/README.md`。以下项目目录脚本方式仍可用于手动运行其他网关,勿对同一设备 ID 重复启动。
|
||||
|
||||
复制以下文件并保持目录结构,角色配置不要公开或提交 Git:
|
||||
|
||||
```text
|
||||
@@ -85,10 +87,12 @@ scrcpy -s 127.0.0.1:15555
|
||||
|
||||
## 本次验证
|
||||
|
||||
已使用正式 Rust 二进制经公网 Linux 中继完成真实手机测试:普通本地 `adb devices` 显示为 `device`,读取型号 `AOSP on crosshatch`,Shell 回显正确。临时网关为本地启动并借助已有 VPN 访问远程 ADB;因此该测试证明公网中继的数据路径,尚未证明远程 Windows 上开机自启或完全关闭 VPN 后的现场部署。
|
||||
已使用正式 Rust 二进制经公网 Linux 中继完成真实手机测试:普通本地 `adb devices` 显示为 `device`,读取型号 `AOSP on crosshatch`,Shell 回显正确。最新测试只启动本地客户端,连接远程 Windows 后台任务注册的 `home-phone`;远程守护程序直接接入手机 TCP 5555。没有在本地启动网关,也没有通过远程 ADB Server 5037 中转。
|
||||
|
||||
远程任务重启后重复测试也通过。测试的 ADB 数据链路只使用公网中继;部署管理仍通过提供的 VPN 地址 SSH 进行,没有关闭系统 VPN,以免影响其他工作。开机启动触发器已配置和检查,未重启远程电脑。测试临时本地连接已清理,远程网关保留后台运行。
|
||||
|
||||
可复现命令(角色令牌只从私有文件读取):
|
||||
|
||||
```powershell
|
||||
python tests/real_device.py --relay-url wss://ttstd.com/ads --connect-address 175.178.213.60:443 --credentials-dir config/private --adb-server 192.168.5.222:5037 --serial 192.168.100.141:5555
|
||||
python tests/real_device.py --relay-url wss://ttstd.com/ads --connect-address 175.178.213.60:443 --credentials-dir config/private --existing-device home-phone
|
||||
```
|
||||
+10
-1
@@ -25,6 +25,15 @@ Public deployment follow-up:
|
||||
- Linux amd64 server is now running on Debian 12 at `175.178.213.60`, as an enabled systemd service under a dedicated user.
|
||||
- Existing Nginx proxies `https://ttstd.com/ads/` to loopback `127.0.0.1:18081`, stripping the prefix. Its existing root-domain certificate was verified without disabling certificate checks.
|
||||
- A real public WSS smoke test passed: both Rust daemons connected to the public origin while keeping TLS SNI/hostname `ttstd.com`; ordinary local ADB listed `127.0.0.1:59671` as `device`, and both read-only shell commands passed.
|
||||
- The test gateway still used the existing VPN-reachable remote ADB Server to reach the phone. Installing the gateway on the remote Windows PC and verifying with VPN disabled remain separate deployment steps.
|
||||
- The initial public test used a temporary local gateway and the VPN-reachable remote ADB Server. Follow-up deployment now runs the actual gateway on the remote Windows PC; see the next section.
|
||||
- Public Cloudflare DNS connectivity timed out from the current PC; the explicit origin-address option was used. No DNS records were changed.
|
||||
- macOS runtime and Linux Rust daemon hosting remain untested. See `deployment-ttstd.md` for deployed configuration and certificate expiry.
|
||||
|
||||
Remote Windows gateway follow-up:
|
||||
|
||||
- Installed release `ads-agent.exe` on `192.168.5.222`, under `C:\Users\TT\AppData\Local\AndroidDeviceStreaming\agent`. Remote SHA256 matched the local release artifact.
|
||||
- Created an ACL-protected credential directory and registered `ADS-Agent` as a hidden background task under `TT`, with password logon, startup/logon triggers and failure restart. No account password is written into source or deployment files.
|
||||
- The gateway directly connects to phone `192.168.100.141:5555` and public relay origin `175.178.213.60:443`, retaining hostname `ttstd.com` and normal TLS checks.
|
||||
- Ran `tests/real_device.py --existing-device home-phone`: only a local client was started; no local gateway and no remote ADB Server transport were used. Ordinary local ADB showed the phone as `device`, and model query plus shell marker passed.
|
||||
- Restarted the remote task and repeated that test: passed again, with local endpoint `127.0.0.1:49832` and model `AOSP on crosshatch`.
|
||||
- Remote gateway remains running. Temporary local smoke-test endpoints/processes were cleaned up. Startup trigger configuration was inspected without rebooting the PC. System VPN was not disabled; it was only needed for remote SSH management, not the tested ADB data path.
|
||||
+18
-9
@@ -17,8 +17,9 @@ from e2e import ROOT, free_port, wait_until
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--adb-server", required=True)
|
||||
parser.add_argument("--serial", required=True)
|
||||
parser.add_argument("--adb-server")
|
||||
parser.add_argument("--serial")
|
||||
parser.add_argument("--existing-device", help="Use a deployed gateway device; do not start a temporary agent")
|
||||
parser.add_argument("--adb", default="adb")
|
||||
parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin")
|
||||
parser.add_argument("--rust-dir", type=Path)
|
||||
@@ -26,6 +27,11 @@ def main():
|
||||
parser.add_argument("--connect-address", help="Optional origin host:port; TLS still verifies relay hostname")
|
||||
parser.add_argument("--credentials-dir", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.existing_device and not args.relay_url:
|
||||
parser.error('--existing-device requires --relay-url')
|
||||
if not args.existing_device and (not args.adb_server or not args.serial):
|
||||
parser.error('provide --adb-server and --serial, or use --existing-device')
|
||||
device_id = args.existing_device or 'smoke-phone'
|
||||
suffix = ".exe" if os.name == "nt" else ""
|
||||
rust_dir = args.rust_dir or args.bin_dir
|
||||
relay_port, local_port = free_port(), free_port()
|
||||
@@ -36,13 +42,15 @@ def main():
|
||||
if not args.relay_url.startswith('wss://'):
|
||||
raise SystemExit('External relay smoke test requires wss://')
|
||||
if args.credentials_dir:
|
||||
for role in ('agent', 'client'):
|
||||
for role in (('client',) if args.existing_device else ('agent', 'client')):
|
||||
for line in (args.credentials_dir / (role + '.env')).read_text().splitlines():
|
||||
name, separator, value = line.partition('=')
|
||||
if separator and name in ('ADS_AGENT_TOKEN', 'ADS_CLIENT_TOKEN'):
|
||||
env[name] = value
|
||||
if not env.get('ADS_AGENT_TOKEN') or not env.get('ADS_CLIENT_TOKEN'):
|
||||
if not env.get('ADS_CLIENT_TOKEN') or (not args.existing_device and not env.get('ADS_AGENT_TOKEN')):
|
||||
raise SystemExit('External relay requires role tokens in env or --credentials-dir')
|
||||
if args.existing_device:
|
||||
env.pop('ADS_AGENT_TOKEN', None)
|
||||
else:
|
||||
env["ADS_AGENT_TOKEN"] = secrets.token_hex(32)
|
||||
env["ADS_CLIENT_TOKEN"] = secrets.token_hex(32)
|
||||
@@ -79,7 +87,7 @@ def main():
|
||||
response = connection.getresponse()
|
||||
if response.status != 200:
|
||||
raise ConnectionError(f'Device query failed: HTTP {response.status}')
|
||||
return any(device['id'] == 'smoke-phone' and device['busy'] for device in json.load(response))
|
||||
return any(device['id'] == device_id and device['busy'] for device in json.load(response))
|
||||
finally:
|
||||
connection.close()
|
||||
request = urllib.request.Request(f"http://127.0.0.1:{relay_port}/v1/devices",
|
||||
@@ -93,11 +101,12 @@ def main():
|
||||
network_args = [] if args.relay_url else ['--allow-insecure']
|
||||
if args.connect_address:
|
||||
network_args += ['--connect-address', args.connect_address]
|
||||
start("agent", [(rust_dir / f"ads-agent{suffix}").resolve(), "--server", server_url,
|
||||
*network_args, "--device", "smoke-phone", "--adb-server", args.adb_server,
|
||||
"--adb-serial", args.serial])
|
||||
if not args.existing_device:
|
||||
start("agent", [(rust_dir / f"ads-agent{suffix}").resolve(), "--server", server_url,
|
||||
*network_args, "--device", device_id, "--adb-server", args.adb_server,
|
||||
"--adb-serial", args.serial])
|
||||
start("client", [(rust_dir / f"ads-client{suffix}").resolve(), "--server", server_url,
|
||||
*network_args, "--device", "smoke-phone", "--listen", endpoint,
|
||||
*network_args, "--device", device_id, "--listen", endpoint,
|
||||
"--no-auto-connect"])
|
||||
wait_until(leased, "remote phone lease", seconds=20)
|
||||
print(adb("connect", endpoint).stdout.strip(), flush=True)
|
||||
|
||||
Reference in new issue
Block a user