Deploy ttstd relay and configure secure public WSS clients
This commit is contained in:
1 parent
82adce545d
commit
c38f067bea
16 files changed
+379
-19
No files matched your search
@@ -9,3 +9,4 @@ __pycache__/
|
|||||||
.env
|
.env
|
||||||
*.log
|
*.log
|
||||||
*.env
|
*.env
|
||||||
|
/config/private/
|
||||||
Generated
+2
@@ -31,6 +31,7 @@ dependencies = [
|
|||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
@@ -705,6 +706,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"once_cell",
|
"once_cell",
|
||||||
|
"ring",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
"rustls-webpki",
|
"rustls-webpki",
|
||||||
"subtle",
|
"subtle",
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ async fn serve_session(args: Arc<Args>, session: String) -> Result<()> {
|
|||||||
&[("device", &args.device), ("session", &session)],
|
&[("device", &args.device), ("session", &session)],
|
||||||
)?,
|
)?,
|
||||||
&args.token,
|
&args.token,
|
||||||
|
args.network.connect_address.as_deref(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
relay(tcp, ws).await
|
relay(tcp, ws).await
|
||||||
@@ -68,6 +69,7 @@ async fn online(args: Arc<Args>) -> Result<()> {
|
|||||||
let mut ws = dial(
|
let mut ws = dial(
|
||||||
args.network.url("/v1/agent", &[("device", &args.device)])?,
|
args.network.url("/v1/agent", &[("device", &args.device)])?,
|
||||||
&args.token,
|
&args.token,
|
||||||
|
args.network.connect_address.as_deref(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let hello = next_control(&mut ws).await?;
|
let hello = next_control(&mut ws).await?;
|
||||||
|
|||||||
+2
-1
@@ -39,6 +39,7 @@ async fn lease_once(args: &Args, state: &watch::Sender<Option<String>>) -> Resul
|
|||||||
let mut ws = dial(
|
let mut ws = dial(
|
||||||
args.network.url("/v1/lease", &[("device", &args.device)])?,
|
args.network.url("/v1/lease", &[("device", &args.device)])?,
|
||||||
&args.token,
|
&args.token,
|
||||||
|
args.network.connect_address.as_deref(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let response = next_control(&mut ws).await?;
|
let response = next_control(&mut ws).await?;
|
||||||
@@ -123,7 +124,7 @@ async fn accept_connections(
|
|||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
let result = async {
|
let result = async {
|
||||||
let url = args.network.url("/v1/connect", &[("device", &args.device), ("lease", &lease)])?;
|
let url = args.network.url("/v1/connect", &[("device", &args.device), ("lease", &lease)])?;
|
||||||
let ws = dial(url, &args.token).await?;
|
let ws = dial(url, &args.token, args.network.connect_address.as_deref()).await?;
|
||||||
relay(tcp, ws).await
|
relay(tcp, ws).await
|
||||||
}.await;
|
}.await;
|
||||||
if let Err(error) = result { warn!(%error, "local device stream ended"); }
|
if let Err(error) = result { warn!(%error, "local device stream ended"); }
|
||||||
|
|||||||
@@ -14,3 +14,4 @@ tokio.workspace = true
|
|||||||
tokio-tungstenite.workspace = true
|
tokio-tungstenite.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber.workspace = true
|
||||||
url.workspace = true
|
url.workspace = true
|
||||||
|
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||||
+69
-12
@@ -9,7 +9,7 @@ use tokio::{
|
|||||||
time::timeout,
|
time::timeout,
|
||||||
};
|
};
|
||||||
use tokio_tungstenite::{
|
use tokio_tungstenite::{
|
||||||
connect_async_with_config,
|
client_async_tls_with_config, connect_async_with_config,
|
||||||
tungstenite::{client::IntoClientRequest, http::HeaderValue, Message},
|
tungstenite::{client::IntoClientRequest, http::HeaderValue, Message},
|
||||||
MaybeTlsStream, WebSocketStream,
|
MaybeTlsStream, WebSocketStream,
|
||||||
};
|
};
|
||||||
@@ -18,12 +18,16 @@ use url::Url;
|
|||||||
pub type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
pub type Ws = WebSocketStream<MaybeTlsStream<TcpStream>>;
|
||||||
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
pub const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
pub const IO_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
pub const DEFAULT_RELAY: &str = "wss://ttstd.com/ads";
|
||||||
|
|
||||||
#[derive(Args, Clone, Debug)]
|
#[derive(Args, Clone, Debug)]
|
||||||
pub struct NetworkArgs {
|
pub struct NetworkArgs {
|
||||||
/// Relay URL, e.g. wss://devices.example.com
|
/// Relay base URL; an optional reverse-proxy path prefix is supported
|
||||||
#[arg(long)]
|
#[arg(long, default_value = DEFAULT_RELAY)]
|
||||||
pub server: String,
|
pub server: String,
|
||||||
|
/// Optional origin host:port override; TLS still verifies the relay URL hostname
|
||||||
|
#[arg(long, env = "ADS_CONNECT_ADDRESS")]
|
||||||
|
pub connect_address: Option<String>,
|
||||||
/// Allow unencrypted ws:// for isolated development only
|
/// Allow unencrypted ws:// for isolated development only
|
||||||
#[arg(long, default_value_t = false)]
|
#[arg(long, default_value_t = false)]
|
||||||
pub allow_insecure: bool,
|
pub allow_insecure: bool,
|
||||||
@@ -44,10 +48,12 @@ impl NetworkArgs {
|
|||||||
{
|
{
|
||||||
bail!("relay URL must not contain credentials, query, or fragment");
|
bail!("relay URL must not contain credentials, query, or fragment");
|
||||||
}
|
}
|
||||||
if url.path() != "/" && !url.path().is_empty() {
|
let endpoint = format!(
|
||||||
bail!("relay URL must use the root path (no URL prefix)");
|
"{}/{}",
|
||||||
}
|
url.path().trim_end_matches('/'),
|
||||||
url.set_path(path);
|
path.trim_start_matches('/')
|
||||||
|
);
|
||||||
|
url.set_path(&endpoint);
|
||||||
url.query_pairs_mut().extend_pairs(params.iter().copied());
|
url.query_pairs_mut().extend_pairs(params.iter().copied());
|
||||||
Ok(url)
|
Ok(url)
|
||||||
}
|
}
|
||||||
@@ -69,7 +75,13 @@ pub fn validate_token(token: &str) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn dial(url: Url, token: &str) -> Result<Ws> {
|
pub async fn dial(url: Url, token: &str, connect_address: Option<&str>) -> Result<Ws> {
|
||||||
|
// WSS needs an explicit provider; relying on transitive feature defaults
|
||||||
|
// leaves pure WebSocket builds without one and panics at the first TLS dial.
|
||||||
|
static TLS_PROVIDER: std::sync::Once = std::sync::Once::new();
|
||||||
|
TLS_PROVIDER.call_once(|| {
|
||||||
|
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||||
|
});
|
||||||
let mut request = url.as_str().into_client_request()?;
|
let mut request = url.as_str().into_client_request()?;
|
||||||
request.headers_mut().insert(
|
request.headers_mut().insert(
|
||||||
"Authorization",
|
"Authorization",
|
||||||
@@ -79,10 +91,16 @@ pub async fn dial(url: Url, token: &str) -> Result<Ws> {
|
|||||||
let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
|
let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
|
||||||
.max_message_size(Some(128 * 1024))
|
.max_message_size(Some(128 * 1024))
|
||||||
.max_frame_size(Some(128 * 1024));
|
.max_frame_size(Some(128 * 1024));
|
||||||
let result = timeout(
|
let handshake = async {
|
||||||
CONNECT_TIMEOUT,
|
if let Some(address) = connect_address {
|
||||||
connect_async_with_config(request, Some(config), true),
|
let tcp = TcpStream::connect(address).await?;
|
||||||
)
|
tcp.set_nodelay(true)?;
|
||||||
|
client_async_tls_with_config(request, tcp, Some(config), None).await
|
||||||
|
} else {
|
||||||
|
connect_async_with_config(request, Some(config), true).await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let result = timeout(CONNECT_TIMEOUT, handshake)
|
||||||
.await
|
.await
|
||||||
.context("relay handshake timed out")?;
|
.context("relay handshake timed out")?;
|
||||||
match result {
|
match result {
|
||||||
@@ -221,6 +239,7 @@ mod tests {
|
|||||||
fn rejects_unsafe_configuration() {
|
fn rejects_unsafe_configuration() {
|
||||||
let network = NetworkArgs {
|
let network = NetworkArgs {
|
||||||
server: "ws://example.com".into(),
|
server: "ws://example.com".into(),
|
||||||
|
connect_address: None,
|
||||||
allow_insecure: false,
|
allow_insecure: false,
|
||||||
};
|
};
|
||||||
assert!(network.url("/v1/agent", &[]).is_err());
|
assert!(network.url("/v1/agent", &[]).is_err());
|
||||||
@@ -229,6 +248,44 @@ mod tests {
|
|||||||
assert!(valid_device_id("home-phone_1"));
|
assert!(valid_device_id("home-phone_1"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn relay_prefix_and_query_parameters_are_preserved() {
|
||||||
|
for base in ["wss://ttstd.com/ads", "wss://ttstd.com/ads/"] {
|
||||||
|
let network = NetworkArgs {
|
||||||
|
server: base.into(),
|
||||||
|
connect_address: None,
|
||||||
|
allow_insecure: false,
|
||||||
|
};
|
||||||
|
let url = network
|
||||||
|
.url(
|
||||||
|
"/v1/connect",
|
||||||
|
&[("device", "home-phone"), ("lease", "secret-ticket")],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(url.path(), "/ads/v1/connect");
|
||||||
|
assert_eq!(url.query(), Some("device=home-phone&lease=secret-ticket"));
|
||||||
|
}
|
||||||
|
assert_eq!(DEFAULT_RELAY, "wss://ttstd.com/ads");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn tls_failure_is_reported_without_a_provider_panic() {
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap().to_string();
|
||||||
|
let peer = tokio::spawn(async move {
|
||||||
|
let (mut sock, _) = listener.accept().await.unwrap();
|
||||||
|
sock.write_all(b"not a TLS record").await.unwrap();
|
||||||
|
});
|
||||||
|
let result = dial(
|
||||||
|
Url::parse("wss://relay.invalid/v1/agent").unwrap(),
|
||||||
|
"test-token-at-least-thirty-two-characters",
|
||||||
|
Some(&address),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(result.is_err());
|
||||||
|
peer.await.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn adb_handshake_selects_transport_and_phone_port() {
|
async fn adb_handshake_selects_transport_and_phone_port() {
|
||||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
|||||||
+3
-1
@@ -1,9 +1,11 @@
|
|||||||
# Process management examples
|
# Process management examples
|
||||||
|
|
||||||
|
Actual `ttstd.com` deployment and startup commands are documented in `docs/deployment-ttstd.md`.
|
||||||
|
|
||||||
Examples are templates, not installed automatically. Replace paths, domain, user and tokens before use. Public endpoints require HTTPS/WSS.
|
Examples are templates, not installed automatically. Replace paths, domain, user and tokens before use. Public endpoints require HTTPS/WSS.
|
||||||
|
|
||||||
- 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.
|
- 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`.
|
- 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 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.
|
||||||
|
|
||||||
These templates have not been exercised on Linux/macOS yet. Test the binaries and process manager on each target platform before relying on unattended startup.
|
The Linux server unit has been deployed and verified on Debian 12. Agent service and macOS templates still require target-platform validation.
|
||||||
@@ -8,11 +8,16 @@ Type=simple
|
|||||||
User=ads
|
User=ads
|
||||||
WorkingDirectory=/opt/ads
|
WorkingDirectory=/opt/ads
|
||||||
EnvironmentFile=/etc/ads/server.env
|
EnvironmentFile=/etc/ads/server.env
|
||||||
ExecStart=/opt/ads/ads-server --listen 127.0.0.1:8080
|
Environment=GOMEMLIMIT=128MiB
|
||||||
|
ExecStart=/opt/ads/ads-server --listen 127.0.0.1:18081
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=3
|
RestartSec=3
|
||||||
NoNewPrivileges=true
|
NoNewPrivileges=true
|
||||||
PrivateTmp=true
|
PrivateTmp=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
MemoryMax=256M
|
||||||
|
LimitNOFILE=8192
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Run as root after uploading the binary, unit, and nginx snippet to a staging dir.
|
||||||
|
# Usage: bash install-server.sh /root/ads-stage-<timestamp>
|
||||||
|
set -euo pipefail
|
||||||
|
stage=${1:?staging directory required}
|
||||||
|
case "$stage" in /root/ads-stage-*) ;; *) echo 'Unexpected staging path' >&2; exit 1;; esac
|
||||||
|
test -f "$stage/ads-server"
|
||||||
|
test -f "$stage/ads-server.service"
|
||||||
|
test -f "$stage/nginx-ads-path.conf"
|
||||||
|
nginx -t
|
||||||
|
|
||||||
|
backup="/var/backups/ads/$(date -u +%Y%m%dT%H%M%SZ)"
|
||||||
|
install -d -m 0700 "$backup"
|
||||||
|
nginx_site=$(readlink -f /etc/nginx/sites-enabled/zz-ttstd-main.conf)
|
||||||
|
test -f "$nginx_site"
|
||||||
|
cp -a "$nginx_site" "$backup/ttstd-main.conf"
|
||||||
|
if test -e /opt/ads/ads-server; then cp -a /opt/ads/ads-server "$backup/ads-server"; fi
|
||||||
|
if test -e /etc/systemd/system/ads-server.service; then cp -a /etc/systemd/system/ads-server.service "$backup/ads-server.service"; fi
|
||||||
|
if test -e /etc/nginx/snippets/ads-path.conf; then cp -a /etc/nginx/snippets/ads-path.conf "$backup/ads-path.conf"; fi
|
||||||
|
|
||||||
|
if ! id -u ads >/dev/null 2>&1; then
|
||||||
|
useradd --system --user-group --home-dir /var/lib/ads --shell /usr/sbin/nologin ads
|
||||||
|
fi
|
||||||
|
install -d -m 0755 /opt/ads
|
||||||
|
install -d -m 0700 /etc/ads
|
||||||
|
install -d -m 0750 -o ads -g ads /var/lib/ads
|
||||||
|
if ! test -f /etc/ads/server.env; then
|
||||||
|
python3 - <<'PY'
|
||||||
|
import os, secrets
|
||||||
|
fd = os.open('/etc/ads/server.env', os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||||
|
with os.fdopen(fd, 'w') as f:
|
||||||
|
f.write('ADS_AGENT_TOKEN=' + secrets.token_hex(32) + '\n')
|
||||||
|
f.write('ADS_CLIENT_TOKEN=' + secrets.token_hex(32) + '\n')
|
||||||
|
PY
|
||||||
|
fi
|
||||||
|
chmod 0600 /etc/ads/server.env
|
||||||
|
install -m 0755 "$stage/ads-server" /opt/ads/ads-server.next
|
||||||
|
mv /opt/ads/ads-server.next /opt/ads/ads-server
|
||||||
|
install -m 0644 "$stage/ads-server.service" /etc/systemd/system/ads-server.service
|
||||||
|
install -m 0644 "$stage/nginx-ads-path.conf" /etc/nginx/snippets/ads-path.conf
|
||||||
|
|
||||||
|
# Insert only into the inspected ttstd.com:443 block, not the other sites.
|
||||||
|
NGINX_SITE="$nginx_site" python3 - <<'PY'
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
p = Path(os.environ['NGINX_SITE'])
|
||||||
|
text = p.read_text()
|
||||||
|
include = ' include /etc/nginx/snippets/ads-path.conf;'
|
||||||
|
if include not in text:
|
||||||
|
anchor = ' listen 443 ssl;\n server_name ttstd.com;'
|
||||||
|
if text.count(anchor) != 1:
|
||||||
|
raise SystemExit('Expected unique ttstd.com HTTPS server block; refusing ambiguous edit')
|
||||||
|
if 'location ^~ /ads/' in text or 'location /ads/' in text:
|
||||||
|
raise SystemExit('An existing /ads/ location must be reviewed before deployment')
|
||||||
|
text = text.replace(anchor, anchor + '\n\n' + include, 1)
|
||||||
|
p.write_text(text)
|
||||||
|
PY
|
||||||
|
|
||||||
|
if ! nginx -t; then
|
||||||
|
cp -a "$backup/ttstd-main.conf" "$nginx_site"
|
||||||
|
if test -f "$backup/ads-path.conf"; then cp -a "$backup/ads-path.conf" /etc/nginx/snippets/ads-path.conf; fi
|
||||||
|
echo "Nginx validation failed; site configuration restored from $backup" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable ads-server.service
|
||||||
|
systemctl restart ads-server.service
|
||||||
|
for attempt in $(seq 1 20); do
|
||||||
|
if curl --fail --silent --max-time 2 http://127.0.0.1:18081/healthz >/dev/null; then break; fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
curl --fail --silent --max-time 5 http://127.0.0.1:18081/healthz
|
||||||
|
systemctl reload nginx
|
||||||
|
curl --noproxy '*' --fail --silent --max-time 10 --resolve ttstd.com:443:127.0.0.1 https://ttstd.com/ads/healthz
|
||||||
|
systemctl is-active ads-server nginx
|
||||||
|
systemctl show ads-server --property=MainPID,MemoryCurrent,MemoryPeak
|
||||||
|
printf 'Backup directory: %s\n' "$backup"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Include inside the existing ttstd.com HTTPS server block.
|
||||||
|
# URI prefix /ads/ is stripped before forwarding to the relay.
|
||||||
|
location = /ads {
|
||||||
|
return 308 /ads/;
|
||||||
|
}
|
||||||
|
location ^~ /ads/ {
|
||||||
|
proxy_pass http://127.0.0.1:18081/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
# Do not cache authenticated requests or log tickets in query strings.
|
||||||
|
proxy_cache off;
|
||||||
|
proxy_hide_header Cache-Control;
|
||||||
|
add_header Cache-Control "no-store" always;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# ttstd.com 实际部署
|
||||||
|
|
||||||
|
## 服务器与连接地址
|
||||||
|
|
||||||
|
- 服务器:`175.178.213.60`,Debian 12 amd64。
|
||||||
|
- 中继基地址:`wss://ttstd.com/ads`,已设为两端程序的默认值。
|
||||||
|
- 健康检查:`https://ttstd.com/ads/healthz`。
|
||||||
|
- 源站直连配置:`--connect-address 175.178.213.60:443`,或环境变量 `ADS_CONNECT_ADDRESS`。
|
||||||
|
|
||||||
|
`ttstd.com` 当前通过 Cloudflare 解析。部署测试中,当前电脑直连 Cloudflare 的 TLS 连接超时,而直连服务器正常。因此启动脚本默认指定源站地址:TCP 连接公网 IP,HTTP Host / TLS SNI 仍为 `ttstd.com`,证书链与主机名校验保持开启,不修改系统 hosts,也不关闭证书校验。
|
||||||
|
|
||||||
|
根域名已有解析和证书,当前方案**不需要添加或修改 DNS 记录**,主站内容仍由原配置处理。Nginx 仅新增 `/ads/` 路径,中继路径不缓存、不记录含票据的访问 URL。
|
||||||
|
|
||||||
|
## 服务器安装位置
|
||||||
|
|
||||||
|
| 项目 | 位置 |
|
||||||
|
|---|---|
|
||||||
|
| 程序 | `/opt/ads/ads-server` |
|
||||||
|
| 角色令牌 | `/etc/ads/server.env`,root 专用,0600 |
|
||||||
|
| systemd | `/etc/systemd/system/ads-server.service` |
|
||||||
|
| 内部监听 | `127.0.0.1:18081`,不开放公网 |
|
||||||
|
| Nginx 路径配置 | `/etc/nginx/snippets/ads-path.conf` |
|
||||||
|
| 主站配置 | 在现有 `zz-ttstd-main.conf` 的 `ttstd.com:443` 块中加入 include |
|
||||||
|
| 配置备份 | `/var/backups/ads/<UTC 时间>/` |
|
||||||
|
|
||||||
|
中继使用独立的 `ads` 系统用户,已设置开机启动、故障重启、`GOMEMLIMIT=128MiB` 和 systemd `MemoryMax=256M`。部署后 systemd 报告空闲服务内存约 2.8 MiB;这是当时的服务 cgroup 计量,不是负载峰值或完整机器内存。
|
||||||
|
|
||||||
|
管理命令:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl status ads-server --no-pager
|
||||||
|
journalctl -u ads-server -n 50 --no-pager
|
||||||
|
systemctl restart ads-server
|
||||||
|
curl --noproxy '*' --resolve ttstd.com:443:127.0.0.1 https://ttstd.com/ads/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
TLS 沿用现有主站证书,核验到的有效期截止 `2026-11-28 06:59:59 UTC`。需要按现有主站证书管理方式及时续期;本次未接管或修改其续期流程。
|
||||||
|
|
||||||
|
## 远程 Windows 电脑
|
||||||
|
|
||||||
|
复制以下文件并保持目录结构,角色配置不要公开或提交 Git:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<部署目录>/
|
||||||
|
bin/ads-agent.exe
|
||||||
|
scripts/start-agent.ps1
|
||||||
|
config/private/agent.env
|
||||||
|
```
|
||||||
|
|
||||||
|
在该部署目录执行:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\scripts\start-agent.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本默认接入手机 `192.168.100.141:5555`,注册 ID 为 `home-phone`。该地址必须从远程电脑可达。也可覆盖 `-Target` 和 `-Device`。此直接 TCP 模式不需要对公网暴露远程 ADB Server。
|
||||||
|
|
||||||
|
## 本地 Windows 电脑
|
||||||
|
|
||||||
|
本地配置位于 `config/private/client.env`,已配置目录 ACL 并被 Git 忽略。该文件只包含客户端角色凭据和非敏感连接地址,不包含服务器 root 密码。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\scripts\start-client.ps1
|
||||||
|
# adb 不在 PATH 时:
|
||||||
|
.\scripts\start-client.ps1 -Adb 'F:\AndroidSDK\platform-tools\adb.exe'
|
||||||
|
```
|
||||||
|
|
||||||
|
默认端口 `127.0.0.1:15555`。另开终端:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
adb devices -l
|
||||||
|
adb -s 127.0.0.1:15555 shell
|
||||||
|
scrcpy -s 127.0.0.1:15555
|
||||||
|
```
|
||||||
|
|
||||||
|
启动脚本读取角色令牌,不把令牌放到程序命令行。直接运行二进制时,需自行加载对应环境变量;`--server` 可省略,但若当前 DNS 链路仍不可达,需设置 `ADS_CONNECT_ADDRESS` 或显式传入源站地址。
|
||||||
|
|
||||||
|
## 域名如果以后改为独立子域名
|
||||||
|
|
||||||
|
当前根域名路径已经可用。若改成 `ads.ttstd.com`,需要额外完成以下三步,不能只添加 DNS 就直接使用:
|
||||||
|
|
||||||
|
1. DNS 添加 A 记录:主机名 `ads`,值 `175.178.213.60`,先用“仅 DNS”(关闭 Cloudflare 橙云),TTL 自动或 300 秒。不要修改现有根域名或其他子域名记录。
|
||||||
|
2. 服务器新增该域名的 Nginx 虚拟主机,取得覆盖 `ads.ttstd.com` 的公有 TLS 证书,并配置 WebSocket 反向代理。现有主站证书不覆盖此子域名。
|
||||||
|
3. 两端改用 `--server wss://ads.ttstd.com`。DNS 直连稳定后可去掉 `--connect-address` / `ADS_CONNECT_ADDRESS`。
|
||||||
|
|
||||||
|
## 本次验证
|
||||||
|
|
||||||
|
已使用正式 Rust 二进制经公网 Linux 中继完成真实手机测试:普通本地 `adb devices` 显示为 `device`,读取型号 `AOSP on crosshatch`,Shell 回显正确。临时网关为本地启动并借助已有 VPN 访问远程 ADB;因此该测试证明公网中继的数据路径,尚未证明远程 Windows 上开机自启或完全关闭 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
|
||||||
|
```
|
||||||
@@ -4,6 +4,8 @@ All requests use `Authorization: Bearer <token>`. Agent and client roles have se
|
|||||||
|
|
||||||
## Endpoints
|
## Endpoints
|
||||||
|
|
||||||
|
Paths below are relative to the relay base URL. A reverse proxy can strip a prefix such as `/ads/`; the deployed default base is `wss://ttstd.com/ads`. An optional TCP origin override preserves the URL hostname for HTTP Host, TLS SNI and certificate validation.
|
||||||
|
|
||||||
| Endpoint | Role | Purpose |
|
| Endpoint | Role | Purpose |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `GET /healthz` | Public | Liveness only |
|
| `GET /healthz` | Public | Liveness only |
|
||||||
|
|||||||
@@ -20,4 +20,11 @@ Read-only real-device smoke test:
|
|||||||
- App installation, Android Studio and scrcpy have not yet been exercised through the new path.
|
- App installation, Android Studio and scrcpy have not yet been exercised through the new path.
|
||||||
- Temporary processes and local ADB endpoint were disconnected after the test; unrelated local ADB devices were preserved.
|
- Temporary processes and local ADB endpoint were disconnected after the test; unrelated local ADB devices were preserved.
|
||||||
|
|
||||||
No public server was deployed. Production WSS certificates, real Internet latency, and Linux/macOS runtime behavior still need deployment-environment validation. The Linux Go server is cross-built separately; cross-building is not a Linux runtime test.
|
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.
|
||||||
|
- 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.
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
param(
|
||||||
|
[string]$Server = 'wss://ttstd.com/ads',
|
||||||
|
[string]$ConnectAddress = '175.178.213.60:443',
|
||||||
|
[string]$Device = 'home-phone',
|
||||||
|
[string]$Target = '192.168.100.141:5555',
|
||||||
|
[string]$AdbServer,
|
||||||
|
[string]$AdbSerial
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$projectRoot = Split-Path $PSScriptRoot -Parent
|
||||||
|
$tokenFile = Join-Path $projectRoot 'config/private/agent.env'
|
||||||
|
if (-not $env:ADS_AGENT_TOKEN -and (Test-Path -LiteralPath $tokenFile)) {
|
||||||
|
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) { throw 'Set ADS_AGENT_TOKEN or provide config/private/agent.env' }
|
||||||
|
$arguments = @('--server', $Server, '--device', $Device)
|
||||||
|
if ($ConnectAddress) { $arguments += @('--connect-address', $ConnectAddress) }
|
||||||
|
if ($AdbSerial) {
|
||||||
|
if (-not $AdbServer) { $AdbServer = '127.0.0.1:5037' }
|
||||||
|
$arguments += @('--adb-server', $AdbServer, '--adb-serial', $AdbSerial)
|
||||||
|
} else { $arguments += @('--target', $Target) }
|
||||||
|
& (Join-Path $projectRoot 'bin/ads-agent.exe') @arguments
|
||||||
|
exit $LASTEXITCODE
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
param(
|
||||||
|
[string]$Server = 'wss://ttstd.com/ads',
|
||||||
|
[string]$ConnectAddress = '175.178.213.60:443',
|
||||||
|
[string]$Device = 'home-phone',
|
||||||
|
[string]$Listen = '127.0.0.1:15555',
|
||||||
|
[string]$Adb = 'adb'
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$projectRoot = Split-Path $PSScriptRoot -Parent
|
||||||
|
$tokenFile = Join-Path $projectRoot 'config/private/client.env'
|
||||||
|
if (-not $env:ADS_CLIENT_TOKEN -and (Test-Path -LiteralPath $tokenFile)) {
|
||||||
|
foreach ($line in Get-Content -LiteralPath $tokenFile) {
|
||||||
|
if ($line.StartsWith('ADS_CLIENT_TOKEN=')) { $env:ADS_CLIENT_TOKEN = $line.Substring(17) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (-not $env:ADS_CLIENT_TOKEN) { throw 'Set ADS_CLIENT_TOKEN or provide config/private/client.env' }
|
||||||
|
$arguments = @('--server', $Server, '--device', $Device, '--listen', $Listen, '--adb', $Adb)
|
||||||
|
if ($ConnectAddress) { $arguments += @('--connect-address', $ConnectAddress) }
|
||||||
|
& (Join-Path $projectRoot 'bin/ads-client.exe') @arguments
|
||||||
|
exit $LASTEXITCODE
|
||||||
+44
-3
@@ -1,11 +1,16 @@
|
|||||||
"""Opt-in, read-only smoke test through a remote ADB smart socket and all three programs."""
|
"""Opt-in, read-only smoke test through a remote ADB smart socket and all three programs."""
|
||||||
import argparse
|
import argparse
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import secrets
|
import secrets
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
import subprocess
|
import subprocess
|
||||||
import time
|
import time
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
import urllib.parse
|
||||||
|
|
||||||
from e2e import ROOT, free_port, wait_until
|
from e2e import ROOT, free_port, wait_until
|
||||||
|
|
||||||
@@ -17,15 +22,31 @@ def main():
|
|||||||
parser.add_argument("--adb", default="adb")
|
parser.add_argument("--adb", default="adb")
|
||||||
parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin")
|
parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin")
|
||||||
parser.add_argument("--rust-dir", type=Path)
|
parser.add_argument("--rust-dir", type=Path)
|
||||||
|
parser.add_argument("--relay-url", help="Use an already deployed wss:// relay instead of a temporary local server")
|
||||||
|
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()
|
args = parser.parse_args()
|
||||||
suffix = ".exe" if os.name == "nt" else ""
|
suffix = ".exe" if os.name == "nt" else ""
|
||||||
rust_dir = args.rust_dir or args.bin_dir
|
rust_dir = args.rust_dir or args.bin_dir
|
||||||
relay_port, local_port = free_port(), free_port()
|
relay_port, local_port = free_port(), free_port()
|
||||||
server_url = f"ws://127.0.0.1:{relay_port}"
|
server_url = args.relay_url or f"ws://127.0.0.1:{relay_port}"
|
||||||
endpoint = f"127.0.0.1:{local_port}"
|
endpoint = f"127.0.0.1:{local_port}"
|
||||||
env = os.environ.copy()
|
env = os.environ.copy()
|
||||||
|
if args.relay_url:
|
||||||
|
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 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'):
|
||||||
|
raise SystemExit('External relay requires role tokens in env or --credentials-dir')
|
||||||
|
else:
|
||||||
env["ADS_AGENT_TOKEN"] = secrets.token_hex(32)
|
env["ADS_AGENT_TOKEN"] = secrets.token_hex(32)
|
||||||
env["ADS_CLIENT_TOKEN"] = secrets.token_hex(32)
|
env["ADS_CLIENT_TOKEN"] = secrets.token_hex(32)
|
||||||
|
env.pop('ADS_CONNECT_ADDRESS', None)
|
||||||
for key in ("ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT"):
|
for key in ("ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT"):
|
||||||
env.pop(key, None)
|
env.pop(key, None)
|
||||||
folder = ROOT / "work" / "real-device"
|
folder = ROOT / "work" / "real-device"
|
||||||
@@ -45,18 +66,38 @@ def main():
|
|||||||
text=True, timeout=10)
|
text=True, timeout=10)
|
||||||
|
|
||||||
def leased():
|
def leased():
|
||||||
|
if args.relay_url:
|
||||||
|
url = urllib.parse.urlsplit(args.relay_url)
|
||||||
|
connection = http.client.HTTPSConnection(url.hostname, url.port or 443, timeout=5)
|
||||||
|
if args.connect_address:
|
||||||
|
host, port = args.connect_address.rsplit(':', 1)
|
||||||
|
tcp = socket.create_connection((host, int(port)), timeout=5)
|
||||||
|
connection.sock = ssl.create_default_context().wrap_socket(tcp, server_hostname=url.hostname)
|
||||||
|
try:
|
||||||
|
connection.request('GET', url.path.rstrip('/') + '/v1/devices',
|
||||||
|
headers={'Authorization': 'Bearer ' + env['ADS_CLIENT_TOKEN']})
|
||||||
|
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))
|
||||||
|
finally:
|
||||||
|
connection.close()
|
||||||
request = urllib.request.Request(f"http://127.0.0.1:{relay_port}/v1/devices",
|
request = urllib.request.Request(f"http://127.0.0.1:{relay_port}/v1/devices",
|
||||||
headers={"Authorization": "Bearer " + env["ADS_CLIENT_TOKEN"]})
|
headers={"Authorization": "Bearer " + env["ADS_CLIENT_TOKEN"]})
|
||||||
with urllib.request.urlopen(request, timeout=2) as response:
|
with urllib.request.urlopen(request, timeout=2) as response:
|
||||||
return b'"busy":true' in response.read()
|
return b'"busy":true' in response.read()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
if not args.relay_url:
|
||||||
start("server", [(args.bin_dir / f"ads-server{suffix}").resolve(), "--listen", f"127.0.0.1:{relay_port}"])
|
start("server", [(args.bin_dir / f"ads-server{suffix}").resolve(), "--listen", f"127.0.0.1:{relay_port}"])
|
||||||
|
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,
|
start("agent", [(rust_dir / f"ads-agent{suffix}").resolve(), "--server", server_url,
|
||||||
"--allow-insecure", "--device", "smoke-phone", "--adb-server", args.adb_server,
|
*network_args, "--device", "smoke-phone", "--adb-server", args.adb_server,
|
||||||
"--adb-serial", args.serial])
|
"--adb-serial", args.serial])
|
||||||
start("client", [(rust_dir / f"ads-client{suffix}").resolve(), "--server", server_url,
|
start("client", [(rust_dir / f"ads-client{suffix}").resolve(), "--server", server_url,
|
||||||
"--allow-insecure", "--device", "smoke-phone", "--listen", endpoint,
|
*network_args, "--device", "smoke-phone", "--listen", endpoint,
|
||||||
"--no-auto-connect"])
|
"--no-auto-connect"])
|
||||||
wait_until(leased, "remote phone lease", seconds=20)
|
wait_until(leased, "remote phone lease", seconds=20)
|
||||||
print(adb("connect", endpoint).stdout.strip(), flush=True)
|
print(adb("connect", endpoint).stdout.strip(), flush=True)
|
||||||
|
|||||||
Reference in new issue
Block a user