ha: Remove Home Assistant notifications
CI / Check (push) Successful in 4m56s

The web app's Web Push notifications replace them: they are encrypted
end to end, and the page holds every pending request, so a dismissed
notification loses nothing. Drops `src/ha.rs`, the
`services.slop-broker.homeAssistant` options and `tokio-tungstenite`.
A config that still has `home_assistant` is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-24 08:39:53 +00:00
1 parent 9d54664f5c
commit 2af7c55a17
11 files changed
+21 -425

No files matched your search

+2 -3
View File
@@ -16,9 +16,8 @@ them.
`slop-broker` runs privileged operations (SSH commands, deploys, builds and age secrets, and later
DNS and previews) for coding agents, under a policy and usually after a human approves each one. Agents use
the `slop` CLI; approvers use `slop-approve`, Home Assistant notifications or the web app. It's a
Rust crate (one library, the `slop-broker` and `slop` binaries) plus NixOS and home-manager modules,
all in this flake.
the `slop` CLI; approvers use `slop-approve` or the web app. It's a Rust crate (one library, the
`slop-broker` and `slop` binaries) plus NixOS and home-manager modules, all in this flake.
Its reference deployment is [nixfiles](https://git.nul.ie/dev/nixfiles), which consumes this
flake as an input; box-specific configuration (which box runs the broker, its policies, firewall,
Generated
+3 -71
View File
@@ -964,12 +964,6 @@ dependencies = [
"syn 3.0.10",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "der"
version = "0.4.5"
@@ -1811,7 +1805,7 @@ dependencies = [
"tokio",
"tokio-rustls",
"tower-service",
"webpki-roots 1.0.12",
"webpki-roots",
]
[[package]]
@@ -3267,7 +3261,7 @@ dependencies = [
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"webpki-roots 1.0.12",
"webpki-roots",
]
[[package]]
@@ -3767,17 +3761,6 @@ dependencies = [
"serde",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
@@ -3897,12 +3880,11 @@ dependencies = [
"serde",
"serde_bytes",
"serde_json",
"sha1 0.11.0",
"sha1",
"sha2 0.11.1",
"ssh-key",
"tempfile",
"tokio",
"tokio-tungstenite",
"tokio-util",
"tokio-vsock",
"toml 0.9.12+spec-1.1.0",
@@ -4264,22 +4246,6 @@ dependencies = [
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "489a59b6730eda1b0171fcfda8b121f4bee2b35cba8645ca35c5f7ba3eb736c1"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
"webpki-roots 0.26.11",
]
[[package]]
name = "tokio-util"
version = "0.7.20"
@@ -4520,25 +4486,6 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tungstenite"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d"
dependencies = [
"bytes",
"data-encoding",
"http 1.5.0",
"httparse",
"log",
"rand 0.9.5",
"rustls",
"rustls-pki-types",
"sha1 0.10.7",
"thiserror 2.0.21",
"utf-8",
]
[[package]]
name = "type-map"
version = "0.5.1"
@@ -4630,12 +4577,6 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "utf8_iter"
version = "1.1.0"
@@ -4817,15 +4758,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.12",
]
[[package]]
name = "webpki-roots"
version = "1.0.12"
-1
View File
@@ -30,7 +30,6 @@ sha1 = "0.11"
sha2 = "0.11.1"
ssh-key = { version = "0.6.7", default-features = false, features = ["ed25519", "std", "alloc"] }
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = { version = "0.27", features = ["rustls-tls-webpki-roots"] }
tokio-util = { version = "0.7", features = ["codec"] }
tokio-vsock = "0.7"
toml = { version = "0.9", default-features = false, features = ["parse", "serde", "std"] }
+2 -2
View File
@@ -2,8 +2,8 @@
An approval broker that runs privileged operations (SSH commands, deploys, builds and age
secrets, and later DNS and previews) for coding agents, under a policy and usually after a human approves
each one. Agents use the `slop` CLI; approvers use `slop-approve`, a web app (sign-in with OpenID
Connect, passkeys, Web Push) or Home Assistant notifications.
each one. Agents use the `slop` CLI; approvers use `slop-approve` or a web app (sign-in with
OpenID Connect, passkeys, Web Push).
- [`docs/design.md`](docs/design.md) — the design and its rationale.
- [`docs/architecture.md`](docs/architecture.md) — how the code is put together and how to add an
+3 -14
View File
@@ -21,7 +21,6 @@ How the code is put together, and how to extend it. The design and its rationale
| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also looks secrets up on the main branch |
| `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver |
| `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) |
| `src/ha.rs` | Home Assistant Companion notifications |
| `src/audit.rs` | Typed audit events: a text line to the journal, a JSON line to the file; `tail` for `slop-approve log` |
| `src/bin/slop-broker.rs` | Daemon (`serve`); `slop-approve` when run under that name |
| `src/bin/slop.rs` | Agent client; `slop guide` prints `slop-tools.md` |
@@ -118,11 +117,6 @@ Arguments from the requester are validated so none can be read as an option.
- `approve.sock` is restricted to the `slop-broker-approve` group. A requester's UID is refused
even if it is in the group. The approver is recorded by user name.
- Over SSH, approvers are named in `sshApprovers` and recorded as `<name> (ssh)`.
- Home Assistant: an outbound WebSocket connection. Each pending request becomes a persistent,
sticky notification with random action IDs for Once, the shortest lease and Deny (Android shows
at most three). Replies must match a live action and the configured `device_id`, which is the
Companion app's own ID (the broker logs the ID of answers it ignores). It resyncs whenever the
queue changes (`Queue::subscribe`) and every five seconds, and logs why a connection failed.
- All of them call `approve::approve`, which records the decision and audits it; the approver's
name travels with the outcome into the `approved` event.
@@ -130,7 +124,7 @@ Arguments from the requester are validated so none can be read as an option.
- `nix/modules/nixos/broker.nix` (`services.slop-broker`) turns options into the TOML config
(`pkgs.formats.toml`, nulls dropped). Credentials arrive through `LoadCredential` under fixed
names (`ssh-key`, `cache-key`, `ha-token`, `oidc-secret`), which `config::credential` resolves in
names (`ssh-key`, `cache-key`, `oidc-secret`, `age-identity`), which `config::credential` resolves in
`$CREDENTIALS_DIRECTORY`.
- The service runs as `slop-broker` with a strict systemd sandbox. Each operation that needs more
(address families, writable paths, helper users) adds it in the module, and the VM test should be
@@ -146,8 +140,6 @@ Arguments from the requester are validated so none can be read as an option.
- Builds: `services.slop-broker.cache` (broker side) and `services.slop-broker-cache` on the cache's
box, whose forced command allows `nix-daemon --stdio` (exactly what `ssh-ng` sends) and
`root <path>…`. The broker adds roots before copying, in case the store collects garbage often.
- Home Assistant: the broker's user there must be an admin, because non-admins can't subscribe to
notification actions.
- What the modules leave to the deployment: persisting `/var/lib/slop-broker` and the builder's
home on an ephemeral root, the firewall in front of the web app's port, which boxes are SSH
targets, and the policies. [nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and
@@ -206,8 +198,5 @@ Arguments from the requester are validated so none can be read as an option.
## Known gaps
- Home Assistant notifications can be swiped away on Android 14 and later; `persistent` no longer
prevents it. The possible fix (re-post on `mobile_app_notification_cleared`, on a quiet channel)
is described in [`design.md`](design.md) and left for now.
- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It doesn't cover deploys, Home
Assistant or the web app; the demo covers the web app by hand.
- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It doesn't cover deploys or the
web app; the demo covers the web app by hand.
+9 -34
View File
@@ -11,8 +11,8 @@ The usual setup runs agents in a VM (the **agents' VM**) and the broker on the b
[nixfiles](https://git.nul.ie/dev/nixfiles), whose `docs/slop-broker.md` describes how its boxes use
the broker.
**Status:** the core, the box queries, `slop ssh`, the SSH transport, deploys, builds, Home
Assistant notifications and the approvals web app are implemented. The other operations here are
**Status:** the core, the box queries, `slop ssh`, the SSH transport, deploys, builds, age
secrets and the approvals web app are implemented. The other operations here are
designed but not built yet (see [Planned operations](#planned-operations)). How the code is put
together is in [`architecture.md`](architecture.md); the NixOS and home-manager modules are in
[`nix/modules`](../nix/modules).
@@ -113,40 +113,16 @@ automatically where it can. Approvals show it marked as agent-supplied.
`policy`, so several requesters, for example agents on different boxes, can share the same rules.
- An `ask` request waits for an answer (`services.slop-broker.timeout`) from the
[approvals web app](#approvals-web-app), `slop-approve` (on the broker's box, or over SSH from
another box) or a Home Assistant Companion notification. The answers are **once**, a **lease**
another box). The answers are **once**, a **lease**
(the same scope is approved for a while, and only lengths the policy allows are offered) or
**deny**.
- An operation or rule can also set `confirm = "passkey"`: approving such a request needs a fresh
passkey in the web app, so `slop-approve` and Home Assistant can only deny it. Deploys to routers
passkey in the web app, so `slop-approve` can only deny it. Deploys to routers
are a typical use.
- `auto` operations are rate-limited per requester, so a looping agent can't hammer boxes or APIs.
- Pending requests are capped per requester and overall to limit notification spam. If the broker
restarts, pending requests and leases are dropped.
### Home Assistant notifications
The broker keeps an outbound connection to Home Assistant's
[WebSocket API](https://developers.home-assistant.io/docs/api/websocket/) and sends a
[Companion actionable notification](https://companion.home-assistant.io/docs/notifications/actionable-notifications/)
for each `ask` request.
- The notification text is built from the scope, followed by the agent's label. Requests that
reveal a secret or change recipients are marked.
- Notifications are sticky and persistent: tapping one doesn't remove it, and before Android 14 it
can't be swiped away either. The broker clears each one once its request is answered, expires or
is cancelled. Since Android 14, users can dismiss even persistent notifications, and apps can't
prevent it. A dismissed request stays pending until it's answered elsewhere or expires.
- A possible fix: the Companion app fires `mobile_app_notification_cleared` when a notification is
dismissed. The broker could watch for it and re-post the notification while its request is still
pending, on a quiet notification channel so it doesn't alert again. Check first that the event
carries the notification's `tag`. The approvals web app (below) makes this matter less.
- Action IDs are random and never shown to the VM. A reply must match a live action and the
configured `device_id`: the Companion app's own ID, which differs from the device registry's.
The broker logs the ID of any answer it ignores, which is how to find it. Home Assistant, and
anyone who can fire events on it, is trusted to approve.
- If the connection fails, requests stay pending; a failure never approves anything. When the
broker reconnects, it reissues pending notifications with new action IDs.
### Approvals web app
Phone notifications are easy to lose, and a terminal isn't always at hand. The broker serves a web
@@ -213,11 +189,10 @@ worker answers with the session like the page does. Requests that need a passkey
- **Endpoints.** The broker only accepts subscriptions at the major push services (Google's
`fcm.googleapis.com` and `jmt<N>.google.com`, Mozilla, Apple, Microsoft), so a session can't make
it send requests elsewhere.
| Channel | Arrives with the app closed | Action buttons | Who can read it on the way | Needs |
|---|---|---|---|---|
| Web Push to the web app | Android; desktop while the browser runs; iOS 16.4 and later once added to the Home Screen | Yes, except on iOS | Nobody: the payload is end-to-end encrypted to the browser | An OIDC provider and a reverse proxy |
| [Home Assistant Companion](#home-assistant-notifications) | Yes | Yes | Google: pushes go through Firebase Cloud Messaging, encrypted only in transit, except with Local Push while the app holds its own connection to Home Assistant | Home Assistant |
- **Replacing Home Assistant.** The broker used to send Home Assistant Companion notifications
instead. Those pass through Firebase Cloud Messaging readable in transit, can be swiped away on
Android 14 and later with nothing to fall back on, and need an admin user on Home Assistant. Web
Push is end-to-end encrypted, and the page holds every pending request.
### Request details
@@ -230,7 +205,7 @@ what needs attention, such as a secret whose content belongs to another file.
marked as code (commands, commits, paths, keys) are in monospace, and diffs are coloured.
- **Everything else** shows the text rendering: a field per line, then each section under its
title, with tables in aligned columns and warnings marked `⚠`. `slop-approve` shows it as it is,
Home Assistant and Web Push a cut-down version that puts headline fields first.
and Web Push a cut-down version that puts headline fields first.
- **Audit log and passkeys:** the audit log keeps the text rendering, so old records read the same
whatever the structure becomes, and passkey confirmations fingerprint it.
- **Limits:** each value, row count and text section is capped, and sections past the total limit
+1 -23
View File
@@ -9,7 +9,6 @@ let
mkBoolOpt' = default: description: mkOpt' lib.types.bool default description;
cfg = config.services.slop-broker;
ha = cfg.homeAssistant;
web = cfg.web;
secrets = cfg.secrets;
@@ -114,13 +113,6 @@ let
approvers = attrNames cfg.sshApprovers;
} else null;
home_assistant = if ha.enable then {
inherit (ha) url;
notify_service = ha.notifyService;
device_id = ha.deviceId;
token = "ha-token";
} else null;
web = if web.enable then {
listen = "${if hasInfix ":" web.address then "[${web.address}]" else web.address}:${toString web.port}";
inherit (web) url issuer group;
@@ -184,15 +176,6 @@ in
keyFile = mkOpt' str "" "Runtime path to the cache's SSH private key; never a Nix store path.";
};
homeAssistant = {
enable = mkBoolOpt' false "Whether to send Companion approval notifications.";
url = mkOpt' str "" "Home Assistant WebSocket endpoint, preferably wss://host/api/websocket.";
notifyService = mkOpt' str "" "Companion notification service name, without the notify. prefix.";
deviceId = mkOpt' str ""
"The Companion app's own ID (the `device_id` in its notification answers, not the device registry's); the broker logs it when it ignores an answer.";
tokenFile = mkOpt' str "" "Runtime path to a Home Assistant token; never a Nix store path.";
};
web = {
enable = mkBoolOpt' false "Whether to serve the approvals web app (sign-in with OpenID Connect, Web Push).";
address = mkOpt' str "127.0.0.1" "Address the web app listens on; only the reverse proxy should reach it.";
@@ -236,10 +219,6 @@ in
assertion = length (unique (map (k: k.key) remoteKeys)) == length remoteKeys;
message = "slop-broker SSH keys must be distinct; use separate keys for requesting and approving.";
}
{
assertion = ha.enable -> (ha.url != "" && ha.notifyService != "" && ha.deviceId != "" && isRuntimePath ha.tokenFile);
message = "slop-broker Home Assistant needs a URL, service, device ID and runtime token file.";
}
{
assertion = web.enable -> (web.url != "" && web.issuer != "" && isRuntimePath web.clientSecretFile);
message = "slop-broker's web app needs a URL, an issuer and a runtime client secret file.";
@@ -287,7 +266,6 @@ in
LoadCredential =
optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++
optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++
optional ha.enable "ha-token:${ha.tokenFile}" ++
optional web.enable "oidc-secret:${web.clientSecretFile}" ++
optional secrets.enable "age-identity:${secrets.identityFile}";
@@ -312,7 +290,7 @@ in
LockPersonality = true;
RestrictAddressFamilies = [ "AF_UNIX" ]
++ optional hasVsockRequesters "AF_VSOCK"
++ optionals (cfg.ssh.enable || ha.enable || web.enable) [ "AF_INET" "AF_INET6" ];
++ optionals (cfg.ssh.enable || web.enable) [ "AF_INET" "AF_INET6" ];
CapabilityBoundingSet = "";
UMask = "0077";
};
+1 -20
View File
@@ -9,7 +9,7 @@ use nix::sys::signal::{SigHandler, Signal, signal};
use slop_broker::config::{Config, credential, group_id, user_id};
use slop_broker::remote::{self, Role};
use slop_broker::server::{self, Broker};
use slop_broker::{approve, ha, web};
use slop_broker::{approve, web};
#[derive(Parser)]
#[command(about = "Approval broker for coding agents")]
@@ -82,17 +82,6 @@ async fn serve(path: &Path) -> Result<()> {
let config = Config::load(path)?;
let _ = rustls::crypto::ring::default_provider().install_default();
let home_assistant = match &config.home_assistant {
Some(settings) => {
ha::validate(settings)?;
let token = std::fs::read_to_string(credential(&settings.token)).context("reading Home Assistant token")?;
let token = token.trim().to_owned();
anyhow::ensure!(!token.is_empty(), "Home Assistant token is empty");
Some((settings.clone(), token))
}
None => None,
};
let web = match &config.web {
Some(settings) => {
let secret = std::fs::read_to_string(credential(&settings.client_secret))
@@ -136,14 +125,6 @@ async fn serve(path: &Path) -> Result<()> {
if let Some(port) = broker.config.vsock_port {
tasks.spawn(server::listen_vsock(broker.clone(), port));
}
if let Some((settings, token)) = home_assistant {
let broker = broker.clone();
tasks.spawn(async move {
ha::run(broker, settings, token).await;
Ok(())
});
}
if let Some((settings, secret)) = web {
tasks.spawn(web::run(broker.clone(), settings, secret));
}
-13
View File
@@ -36,8 +36,6 @@ pub struct Config {
#[serde(default)]
pub ssh: Option<SshConfig>,
#[serde(default)]
pub home_assistant: Option<HomeAssistantConfig>,
#[serde(default)]
pub remote: Option<RemoteConfig>,
#[serde(default)]
pub deploy: Option<DeployConfig>,
@@ -204,17 +202,6 @@ fn default_sudo() -> String {
"sudo -u".into()
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HomeAssistantConfig {
pub url: String,
/// Companion notification service, without the `notify.` prefix.
pub notify_service: String,
pub device_id: String,
/// Long-lived access token; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
pub token: PathBuf,
}
/// A duration in seconds, written as `"5m"` or as a number of seconds.
pub fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
#[derive(Deserialize)]
-243
View File
@@ -1,243 +0,0 @@
//! Home Assistant Companion notifications for pending requests. The broker connects out to Home
//! Assistant's WebSocket API; nothing listens for approvals over HTTP.
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use futures_util::{SinkExt, StreamExt};
use serde_json::{Value, json};
use tokio_tungstenite::tungstenite::Message;
use url::Url;
use crate::approve;
use crate::config::HomeAssistantConfig;
use crate::ops::truncate;
use crate::queue::{Decision, PendingInfo};
use crate::server::Broker;
pub fn validate(config: &HomeAssistantConfig) -> Result<()> {
let url = Url::parse(&config.url)?;
if !matches!(url.scheme(), "ws" | "wss") || url.host_str().is_none() || url.path() != "/api/websocket" {
bail!("Home Assistant URL must be ws(s)://host/api/websocket");
}
if !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() {
bail!("Home Assistant URL must not contain credentials, a query or a fragment");
}
let service = config.notify_service.strip_prefix("mobile_app_").unwrap_or("");
if service.is_empty() || !service.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'_') {
bail!("notification service must be mobile_app_<device>");
}
if config.device_id.is_empty() {
bail!("Home Assistant device_id is required");
}
Ok(())
}
pub async fn run(broker: Arc<Broker>, config: HomeAssistantConfig, token: String) {
loop {
// The token is only ever sent, and the URL can't hold credentials, so errors are safe to log.
if let Err(error) = session(&broker, &config, &token).await {
eprintln!("<4>Home Assistant connection unavailable ({error:#}); retrying in 5 seconds");
}
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
/// Notification state for one connection; action IDs are never reused across connections.
struct Notifier<'a> {
broker: &'a Broker,
config: &'a HomeAssistantConfig,
sequence: u64,
/// Random action ID → (request ID, decision).
actions: HashMap<String, (String, Decision)>,
sent: HashSet<String>,
}
async fn session(broker: &Broker, config: &HomeAssistantConfig, token: &str) -> Result<()> {
let (mut socket, _) =
tokio::time::timeout(Duration::from_secs(10), tokio_tungstenite::connect_async(&config.url)).await??;
if read_message(&mut socket).await?["type"] != "auth_required" {
bail!("expected authentication challenge");
}
send(&mut socket, json!({ "type": "auth", "access_token": token })).await?;
if read_message(&mut socket).await?["type"] != "auth_ok" {
bail!("authentication failed");
}
let mut notifier = Notifier { broker, config, sequence: 0, actions: HashMap::new(), sent: HashSet::new() };
let subscription = notifier.next_id();
send(
&mut socket,
json!({ "id": subscription, "type": "subscribe_events", "event_type": "mobile_app_notification_action" }),
)
.await?;
let response = read_message(&mut socket).await?;
if response["id"] != subscription || response["type"] != "result" || response["success"] != true {
bail!("subscribing to notification actions failed: {}", response["error"]["message"]);
}
let mut changes = broker.queue.subscribe();
let mut tick = tokio::time::interval(Duration::from_secs(5));
loop {
notifier.sync(&mut socket).await?;
tokio::select! {
message = read_message(&mut socket) => {
let message = message?;
if message["type"] == "result" && message["success"] == false {
bail!("service call failed");
}
notifier.handle_event(&message);
}
_ = changes.changed() => {}
_ = tick.tick() => {}
}
}
}
type Socket = tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
async fn read_message(socket: &mut Socket) -> Result<Value> {
loop {
match socket.next().await.context("connection closed")?? {
Message::Text(text) => return Ok(serde_json::from_str(&text)?),
Message::Close(_) => bail!("connection closed"),
_ => continue,
}
}
}
async fn send(socket: &mut Socket, message: Value) -> Result<()> {
socket.send(Message::text(message.to_string())).await?;
Ok(())
}
impl Notifier<'_> {
fn next_id(&mut self) -> u64 {
self.sequence += 1;
self.sequence
}
async fn notify(&mut self, socket: &mut Socket, data: Value) -> Result<()> {
let id = self.next_id();
let message = json!({
"id": id, "type": "call_service", "domain": "notify", "service": self.config.notify_service, "service_data": data,
});
send(socket, message).await
}
async fn sync(&mut self, socket: &mut Socket) -> Result<()> {
let pending: HashMap<String, PendingInfo> =
self.broker.queue.list().into_iter().map(|e| (e.id.clone(), e)).collect();
self.actions.retain(|_, (id, _)| pending.contains_key(id));
let gone: Vec<String> = self.sent.iter().filter(|id| !pending.contains_key(*id)).cloned().collect();
for id in gone {
self.notify(socket, json!({ "message": "clear_notification", "data": { "tag": format!("slop-{id}") } }))
.await?;
self.sent.remove(&id);
}
for (id, entry) in pending {
if !self.sent.contains(&id) {
let data = self.notification(&entry);
self.notify(socket, data).await?;
self.sent.insert(id);
}
}
Ok(())
}
fn notification(&mut self, entry: &PendingInfo) -> Value {
// Android shows at most three actions: once, the shortest lease and deny. Requests that
// need a passkey can only be denied here.
let mut decisions = vec![];
if !entry.passkey {
decisions.push(Decision::Once);
if let Some(&lease) = entry.offers.iter().find(|d| matches!(d, Decision::Lease(_))) {
decisions.push(lease);
}
}
decisions.push(Decision::Deny);
let buttons: Vec<Value> = decisions
.into_iter()
.map(|decision| {
// Independent of request IDs, which requesters can see.
let action = format!("SLOP_{}", hex::encode(rand::random::<[u8; 32]>()));
self.actions.insert(action.clone(), (entry.id.clone(), decision));
json!({ "action": action, "title": decision.title(), "authenticationRequired": true })
})
.collect();
let mut message = format!("{}\n{}", entry.summary, truncate(&entry.detail.brief(), 400));
if let Some(label) = &entry.label {
message += &format!("\nAgent says: {}", truncate(label, 120));
}
message += &format!("\nFrom {}", entry.requester);
if entry.passkey {
message += "\nNeeds a passkey: approve in the web app";
}
let title = if entry.sensitive { "Agent approval (sensitive)" } else { "Agent approval" };
// Sticky, so tapping it doesn't remove it, and persistent, which stops swiping it away on
// Android before 14; the broker clears it by tag once it's answered or expired.
let data = json!({
"tag": format!("slop-{}", entry.id),
"actions": buttons,
"persistent": true,
"sticky": "true",
});
json!({ "title": title, "message": message, "data": data })
}
fn handle_event(&mut self, message: &Value) {
let event = &message["event"];
if message["type"] != "event" || event["event_type"] != "mobile_app_notification_action" {
return;
}
// Other automations' actions aren't ours to mention.
let data = &event["data"];
let Some(action) = data["action"].as_str().filter(|a| a.starts_with("SLOP_")) else { return };
let device = data["device_id"].as_str();
if device != Some(self.config.device_id.as_str()) {
eprintln!("<4>ignored a notification answer from device {device:?}; only the configured device may answer");
return;
}
let Some((id, decision)) = self.actions.get(action).cloned() else {
eprintln!("<4>ignored a notification answer for a request that's no longer pending");
return;
};
// Fails harmlessly if it expired, was answered in a terminal, or arrived twice.
let _ = approve::approve(self.broker, &id, decision, "home-assistant", false);
self.actions.retain(|_, (other, _)| *other != id);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config(url: &str, service: &str) -> HomeAssistantConfig {
HomeAssistantConfig {
url: url.into(),
notify_service: service.into(),
device_id: "d".into(),
token: "t".into(),
}
}
#[test]
fn validates_config() {
assert!(validate(&config("wss://hass.example.org/api/websocket", "mobile_app_pixel")).is_ok());
assert!(validate(&config("https://hass.example.org/api/websocket", "mobile_app_pixel")).is_err());
assert!(validate(&config("wss://u:p@hass.example.org/api/websocket", "mobile_app_pixel")).is_err());
assert!(validate(&config("wss://hass.example.org/api/websocket?x", "mobile_app_pixel")).is_err());
assert!(validate(&config("wss://hass.example.org/api/websocket", "persistent_notification")).is_err());
}
}
-1
View File
@@ -6,7 +6,6 @@ pub mod builder;
pub mod config;
pub mod detail;
pub mod exec;
pub mod ha;
pub mod ops;
pub mod policy;
pub mod proto;