From 3a0d464234b2df01be85da317b2dbbf54e6f4344 Mon Sep 17 00:00:00 2001 From: Jet Date: Mon, 23 Mar 2026 22:18:23 -0700 Subject: [PATCH] feat: add zulip integration --- Cargo.lock | 15 +++ Cargo.toml | 1 + README.md | 6 +- flake.nix | 4 + remote/README.md | 4 + remote/cache-service/README.md | 31 ++++++ remote/hosted-module.nix | 32 +++++- remote/zulip-bot/Cargo.toml | 18 ++++ remote/zulip-bot/README.md | 28 ++++++ remote/zulip-bot/module.nix | 107 ++++++++++++++++++++ remote/zulip-bot/src/main.rs | 167 +++++++++++++++++++++++++++++++ secrets/secrets.nix | 8 ++ secrets/zulip-api-key.age | 7 ++ secrets/zulip-webhook-secret.age | 7 ++ 14 files changed, 430 insertions(+), 5 deletions(-) create mode 100644 remote/zulip-bot/Cargo.toml create mode 100644 remote/zulip-bot/README.md create mode 100644 remote/zulip-bot/module.nix create mode 100644 remote/zulip-bot/src/main.rs create mode 100644 secrets/zulip-api-key.age create mode 100644 secrets/zulip-webhook-secret.age diff --git a/Cargo.lock b/Cargo.lock index b81fe4b..9fa68da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -921,6 +921,21 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "noisebell-zulip" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "noisebell-common", + "reqwest", + "serde", + "tokio", + "tower-http", + "tracing", + "tracing-subscriber", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" diff --git a/Cargo.toml b/Cargo.toml index b8e0be0..b7ad6d7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "remote/cache-service", "remote/rss-service", "remote/discord-bot", + "remote/zulip-bot", ] resolver = "2" diff --git a/README.md b/README.md index ec121f4..44a56ec 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ Monitors the door at [Noisebridge](https://www.noisebridge.net) and tells you whether it's open or closed. -A Raspberry Pi reads a magnetic sensor on the door and pushes state changes to a cache server. The cache keeps the latest state and fans updates out to Discord. +A Raspberry Pi reads a magnetic sensor on the door and pushes state changes to a cache server. The cache keeps the latest state and fans updates out to chat integrations such as Discord and Zulip. ``` -Pi (door sensor) ──webhook──> Cache ──webhook──> Discord +Pi (door sensor) ──webhook──> Cache ──webhook──> Discord / Zulip | polls Pi <-+ ``` @@ -15,7 +15,7 @@ Pi (door sensor) ──webhook──> Cache ──webhook──> Discord | Directory | What it is | |-----------|------------| | [`pi/`](pi/) | Raspberry Pi OS base with laptop-built Noisebell deploy | -| [`remote/`](remote/) | Server-side services (cache and Discord bot) | +| [`remote/`](remote/) | Server-side services (cache, RSS, Discord, Zulip) | | [`secrets/`](secrets/) | Shared agenix-encrypted secrets and recipient rules | Each directory has its own README with setup and configuration details. diff --git a/flake.nix b/flake.nix index 7d41d68..eb3404f 100644 --- a/flake.nix +++ b/flake.nix @@ -68,6 +68,7 @@ noisebell-cache = buildRemoteMember "noisebell-cache"; noisebell-rss = buildRemoteMember "noisebell-rss"; noisebell-discord = buildRemoteMember "noisebell-discord"; + noisebell-zulip = buildRemoteMember "noisebell-zulip"; crossPkgs = import nixpkgs { inherit system; @@ -349,6 +350,7 @@ noisebell-cache noisebell-rss noisebell-discord + noisebell-zulip flash-pi-sd pi-serial ; @@ -365,11 +367,13 @@ cache = import ./remote/cache-service/module.nix noisebell-cache; rss = import ./remote/rss-service/module.nix noisebell-rss; discord = import ./remote/discord-bot/module.nix noisebell-discord; + zulip = import ./remote/zulip-bot/module.nix noisebell-zulip; default = { imports = [ (import ./remote/cache-service/module.nix noisebell-cache) (import ./remote/rss-service/module.nix noisebell-rss) (import ./remote/discord-bot/module.nix noisebell-discord) + (import ./remote/zulip-bot/module.nix noisebell-zulip) (import ./remote/hosted-module.nix { inherit self agenix; }) diff --git a/remote/README.md b/remote/README.md index 20782d0..6304fa5 100644 --- a/remote/README.md +++ b/remote/README.md @@ -7,6 +7,7 @@ Cargo workspace with the server-side pieces of Noisebell. Runs on any Linux box. | [`cache-service/`](cache-service/) | 3000 | Polls the Pi, stores the latest state in SQLite, fans out webhooks | | [`rss-service/`](rss-service/) | 3002 | Fetches current status from cache and serves RSS/Atom feeds | | [`discord-bot/`](discord-bot/) | 3001 | Posts door status to a Discord channel | +| [`zulip-bot/`](zulip-bot/) | 3003 | Posts door status to a Zulip stream | | [`noisebell-common/`](noisebell-common/) | — | Shared types and helpers | See each service's README for configuration and API docs. @@ -23,6 +24,7 @@ Or with Nix: nix build .#noisebell-cache nix build .#noisebell-rss nix build .#noisebell-discord +nix build .#noisebell-zulip ``` ## NixOS deployment @@ -67,6 +69,8 @@ The flake exports a NixOS module for the hosted remote machine. It imports `agen | `secrets/pi-to-cache-key.age` | Pi + remote | Pi authenticates to cache `/webhook` | | `secrets/cache-to-pi-key.age` | Pi + remote | cache authenticates to Pi GET endpoints | | `secrets/discord-webhook-secret.age` | remote | cache authenticates to Discord bot `/webhook` | +| `secrets/zulip-webhook-secret.age` | remote | cache authenticates to Zulip bridge `/webhook` | | `secrets/discord-token.age` | remote | Discord bot login | +| `secrets/zulip-api-key.age` | remote | Zulip bot API authentication | When `extremist-software` builds a system using the Noisebell flake input, Nix uses the checked-out flake source for that input. The module points `agenix` at encrypted files inside that Noisebell source tree, such as `${inputs.noisebell}/secrets/discord-token.age`. At activation time `agenix` decrypts them locally on the target host into runtime paths like `/run/agenix/noisebell-discord-token`. The service modules then read those local decrypted files when systemd starts them. diff --git a/remote/cache-service/README.md b/remote/cache-service/README.md index c667f52..5065ba6 100644 --- a/remote/cache-service/README.md +++ b/remote/cache-service/README.md @@ -42,3 +42,34 @@ NixOS options under `services.noisebell-cache`: | `piApiKeyFile` | Bearer token to poll the Pi's GET endpoints | | `inboundApiKeyFile` | Bearer token the Pi sends when POSTing to `/webhook` | | `outboundWebhooks[].secretFile` | Bearer token sent with outbound webhook POSTs | + +## Home Assistant + +Home Assistant works well as another `outboundWebhooks` target. + +- For fast automations, point a webhook target at Home Assistant's `/api/webhook/` endpoint. +- For current-state display and restart recovery, have Home Assistant also poll `GET /status`. + +Example NixOS config: + +```nix +{ + services.noisebell-cache.outboundWebhooks = [ + { + url = "https://homeassistant.example.com/api/webhook/noisebell-door"; + secretFile = null; + } + ]; +} +``` + +The webhook payload sent by cache-service is: + +```json +{ + "status": "open", + "timestamp": 1710000000 +} +``` + +`secretFile = null` is usually fine for Home Assistant webhook triggers because the webhook ID itself acts as the secret. If you place Home Assistant behind an extra auth layer that expects a bearer token, set `secretFile` to a file containing that token. diff --git a/remote/hosted-module.nix b/remote/hosted-module.nix index e3169fa..9b80661 100644 --- a/remote/hosted-module.nix +++ b/remote/hosted-module.nix @@ -5,6 +5,7 @@ let cfgCache = config.services.noisebell-cache; cfgRss = config.services.noisebell-rss; cfgDiscord = config.services.noisebell-discord; + cfgZulip = config.services.noisebell-zulip; in { imports = [ agenix.nixosModules.default ]; @@ -14,6 +15,7 @@ in users.users.noisebell-cache.extraGroups = lib.mkIf cfgCache.enable [ "noisebell" ]; users.users.noisebell-rss.extraGroups = lib.mkIf cfgRss.enable [ "noisebell" ]; users.users.noisebell-discord.extraGroups = lib.mkIf cfgDiscord.enable [ "noisebell" ]; + users.users.noisebell-zulip.extraGroups = lib.mkIf cfgZulip.enable [ "noisebell" ]; age.secrets.noisebell-pi-to-cache-key = { file = "${self}/secrets/pi-to-cache-key.age"; @@ -33,20 +35,36 @@ in mode = "0440"; }; + age.secrets.noisebell-zulip-api-key = { + file = "${self}/secrets/zulip-api-key.age"; + group = "noisebell"; + mode = "0440"; + }; + age.secrets.noisebell-discord-webhook-secret = { file = "${self}/secrets/discord-webhook-secret.age"; group = "noisebell"; mode = "0440"; }; + age.secrets.noisebell-zulip-webhook-secret = { + file = "${self}/secrets/zulip-webhook-secret.age"; + group = "noisebell"; + mode = "0440"; + }; + services.noisebell-cache = lib.mkIf cfgCache.enable { piApiKeyFile = lib.mkDefault config.age.secrets.noisebell-cache-to-pi-key.path; inboundApiKeyFile = lib.mkDefault config.age.secrets.noisebell-pi-to-cache-key.path; outboundWebhooks = lib.mkDefault ( - lib.optional cfgDiscord.enable { + (lib.optional cfgDiscord.enable { url = "http://127.0.0.1:${toString cfgDiscord.port}/webhook"; secretFile = config.age.secrets.noisebell-discord-webhook-secret.path; - } + }) + ++ (lib.optional cfgZulip.enable { + url = "http://127.0.0.1:${toString cfgZulip.port}/webhook"; + secretFile = cfgZulip.webhookSecretFile; + }) ); }; @@ -66,4 +84,14 @@ in imageBaseUrl = lib.mkDefault "https://${cfgCache.domain}/image"; } ); + + services.noisebell-zulip = lib.mkIf cfgZulip.enable ( + { + apiKeyFile = lib.mkDefault config.age.secrets.noisebell-zulip-api-key.path; + webhookSecretFile = lib.mkDefault config.age.secrets.noisebell-zulip-webhook-secret.path; + } + // lib.optionalAttrs cfgCache.enable { + imageBaseUrl = lib.mkDefault "https://${cfgCache.domain}/image"; + } + ); } diff --git a/remote/zulip-bot/Cargo.toml b/remote/zulip-bot/Cargo.toml new file mode 100644 index 0000000..a51e347 --- /dev/null +++ b/remote/zulip-bot/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "noisebell-zulip" +version = "0.1.0" +edition = "2021" + +[lints] +workspace = true + +[dependencies] +anyhow = "1.0" +axum = "0.8" +noisebell-common = { path = "../noisebell-common" } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +serde = { version = "1.0", features = ["derive"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] } +tower-http = { version = "0.6", features = ["trace"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/remote/zulip-bot/README.md b/remote/zulip-bot/README.md new file mode 100644 index 0000000..d40c78a --- /dev/null +++ b/remote/zulip-bot/README.md @@ -0,0 +1,28 @@ +# Zulip Bridge + +Receives webhooks from the cache service and posts door status updates into a Zulip stream. + +Validates inbound webhooks with a Bearer token, then sends a stream message through the Zulip API using a bot email and API key. + +## API + +| Method | Path | Auth | Description | +|--------|------|------|-------------| +| `POST` | `/webhook` | Bearer | Status update from the cache service | +| `GET` | `/health` | - | Health check | + +## Configuration + +NixOS options under `services.noisebell-zulip`: + +| Option | Default | Description | +|--------|---------|-------------| +| `domain` | required | Caddy virtual host domain | +| `zulipUrl` | required | Base URL of the Zulip server | +| `botEmail` | required | Zulip bot email address | +| `apiKeyFile` | required | Zulip bot API key file | +| `stream` | required | Zulip stream for updates | +| `topic` | `noisebell` | Zulip topic for updates | +| `imageBaseUrl` | `https://noisebell.extremist.software/image` | Base URL for status image links | +| `webhookSecretFile` | required | Shared secret with the cache service | +| `port` | `3003` | Listen port | diff --git a/remote/zulip-bot/module.nix b/remote/zulip-bot/module.nix new file mode 100644 index 0000000..5acd575 --- /dev/null +++ b/remote/zulip-bot/module.nix @@ -0,0 +1,107 @@ +pkg: +{ config, lib, ... }: + +let + cfg = config.services.noisebell-zulip; + bin = "${pkg}/bin/noisebell-zulip"; +in +{ + options.services.noisebell-zulip = { + enable = lib.mkEnableOption "noisebell Zulip bridge"; + + domain = lib.mkOption { + type = lib.types.str; + description = "Domain for the Caddy virtual host."; + }; + + port = lib.mkOption { + type = lib.types.port; + default = 3003; + }; + + zulipUrl = lib.mkOption { + type = lib.types.str; + description = "Base URL of the Zulip server (for example https://chat.example.com)."; + }; + + botEmail = lib.mkOption { + type = lib.types.str; + description = "Email address for the Zulip bot user."; + }; + + apiKeyFile = lib.mkOption { + type = lib.types.path; + description = "Path to file containing the Zulip bot API key."; + }; + + stream = lib.mkOption { + type = lib.types.str; + description = "Zulip stream that receives Noisebell updates."; + }; + + topic = lib.mkOption { + type = lib.types.str; + default = "noisebell"; + description = "Zulip topic used for Noisebell updates."; + }; + + imageBaseUrl = lib.mkOption { + type = lib.types.str; + default = "https://noisebell.extremist.software/image"; + description = "Base URL for status images linked in Zulip messages."; + }; + + webhookSecretFile = lib.mkOption { + type = lib.types.path; + description = "Path to file containing the inbound webhook bearer token."; + }; + }; + + config = lib.mkIf cfg.enable { + users.users.noisebell-zulip = { + isSystemUser = true; + group = "noisebell-zulip"; + }; + users.groups.noisebell-zulip = { }; + + services.caddy.virtualHosts.${cfg.domain}.extraConfig = '' + reverse_proxy localhost:${toString cfg.port} + ''; + + systemd.services.noisebell-zulip = { + description = "Noisebell Zulip bridge"; + wantedBy = [ "multi-user.target" ]; + after = [ "network-online.target" ]; + wants = [ "network-online.target" ]; + environment = { + NOISEBELL_ZULIP_PORT = toString cfg.port; + NOISEBELL_ZULIP_SITE_URL = cfg.zulipUrl; + NOISEBELL_ZULIP_BOT_EMAIL = cfg.botEmail; + NOISEBELL_ZULIP_STREAM = cfg.stream; + NOISEBELL_ZULIP_TOPIC = cfg.topic; + NOISEBELL_ZULIP_IMAGE_BASE_URL = cfg.imageBaseUrl; + RUST_LOG = "info"; + }; + script = '' + export NOISEBELL_ZULIP_API_KEY="$(cat ${cfg.apiKeyFile})" + export NOISEBELL_ZULIP_WEBHOOK_SECRET="$(cat ${cfg.webhookSecretFile})" + exec ${bin} + ''; + serviceConfig = { + Type = "simple"; + Restart = "on-failure"; + RestartSec = 5; + User = "noisebell-zulip"; + Group = "noisebell-zulip"; + NoNewPrivileges = true; + ProtectSystem = "strict"; + ProtectHome = true; + PrivateTmp = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictSUIDSGID = true; + }; + }; + }; +} diff --git a/remote/zulip-bot/src/main.rs b/remote/zulip-bot/src/main.rs new file mode 100644 index 0000000..6ede2fd --- /dev/null +++ b/remote/zulip-bot/src/main.rs @@ -0,0 +1,167 @@ +use std::sync::Arc; + +use anyhow::{Context, Result}; +use axum::extract::State as AxumState; +use axum::http::{HeaderMap, StatusCode}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use noisebell_common::{validate_bearer, DoorStatus, WebhookPayload}; +use serde::Serialize; +use tower_http::trace::TraceLayer; +use tracing::{error, info, Level}; + +struct AppState { + client: reqwest::Client, + webhook_secret: String, + site_url: String, + bot_email: String, + api_key: String, + stream: String, + topic: String, + image_base_url: String, +} + +#[derive(Serialize)] +struct ZulipMessageRequest<'a> { + r#type: &'static str, + to: &'a str, + topic: &'a str, + content: String, +} + +fn build_content(status: DoorStatus, image_base_url: &str) -> String { + let image_url = |name: &str| format!("{image_base_url}/{name}.png"); + + match status { + DoorStatus::Open => format!( + "# Noisebridge is Open!\nIt's time to start hacking.\n[Open image]({})", + image_url("open"), + ), + DoorStatus::Closed => format!( + "# Noisebridge is Closed!\nWe'll see you again soon.\n[Closed image]({})", + image_url("closed"), + ), + DoorStatus::Offline => format!( + "# Noisebridge is Offline\nThe Noisebridge Pi is not responding.\n[Offline image]({})", + image_url("offline"), + ), + } +} + +async fn post_webhook( + AxumState(state): AxumState>, + headers: HeaderMap, + Json(body): Json, +) -> StatusCode { + if !validate_bearer(&headers, &state.webhook_secret) { + return StatusCode::UNAUTHORIZED; + } + + info!(status = %body.status, timestamp = body.timestamp, "received webhook"); + + let request = ZulipMessageRequest { + r#type: "stream", + to: &state.stream, + topic: &state.topic, + content: build_content(body.status, &state.image_base_url), + }; + + match state + .client + .post(format!("{}/api/v1/messages", state.site_url)) + .basic_auth(&state.bot_email, Some(&state.api_key)) + .form(&request) + .send() + .await + { + Ok(resp) if resp.status().is_success() => { + info!(status = %body.status, "message sent to Zulip"); + StatusCode::OK + } + Ok(resp) => { + error!(status_code = %resp.status(), "failed to send message to Zulip"); + StatusCode::BAD_GATEWAY + } + Err(err) => { + error!(error = %err, "failed to send message to Zulip"); + StatusCode::BAD_GATEWAY + } + } +} + +#[tokio::main] +async fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::from_default_env()) + .init(); + + let port: u16 = std::env::var("NOISEBELL_ZULIP_PORT") + .unwrap_or_else(|_| "3003".into()) + .parse() + .context("NOISEBELL_ZULIP_PORT must be a valid u16")?; + + let webhook_secret = std::env::var("NOISEBELL_ZULIP_WEBHOOK_SECRET") + .context("NOISEBELL_ZULIP_WEBHOOK_SECRET is required")?; + + let site_url = std::env::var("NOISEBELL_ZULIP_SITE_URL") + .context("NOISEBELL_ZULIP_SITE_URL is required")? + .trim_end_matches('/') + .to_string(); + + let bot_email = std::env::var("NOISEBELL_ZULIP_BOT_EMAIL") + .context("NOISEBELL_ZULIP_BOT_EMAIL is required")?; + + let api_key = + std::env::var("NOISEBELL_ZULIP_API_KEY").context("NOISEBELL_ZULIP_API_KEY is required")?; + + let stream = + std::env::var("NOISEBELL_ZULIP_STREAM").context("NOISEBELL_ZULIP_STREAM is required")?; + + let topic = std::env::var("NOISEBELL_ZULIP_TOPIC").unwrap_or_else(|_| "noisebell".into()); + + let image_base_url = std::env::var("NOISEBELL_ZULIP_IMAGE_BASE_URL") + .unwrap_or_else(|_| "https://noisebell.extremist.software/image".into()) + .trim_end_matches('/') + .to_string(); + + let client = reqwest::Client::builder().build().context("failed to build HTTP client")?; + + info!(port, stream, topic, site_url, image_base_url, "starting noisebell-zulip"); + + let app = Router::new() + .route("/health", get(|| async { StatusCode::OK })) + .route("/webhook", post(post_webhook)) + .layer( + TraceLayer::new_for_http() + .make_span_with(tower_http::trace::DefaultMakeSpan::new().level(Level::INFO)) + .on_response(tower_http::trace::DefaultOnResponse::new().level(Level::INFO)), + ) + .with_state(Arc::new(AppState { + client, + webhook_secret, + site_url, + bot_email, + api_key, + stream, + topic, + image_base_url, + })); + + let listener = tokio::net::TcpListener::bind(("0.0.0.0", port)) + .await + .context(format!("failed to bind to 0.0.0.0:{port}"))?; + + info!(port, "webhook listener ready"); + + let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .context("failed to register SIGTERM handler")?; + axum::serve(listener, app) + .with_graceful_shutdown(async move { + sigterm.recv().await; + }) + .await + .context("server error")?; + + info!("shutdown complete"); + Ok(()) +} diff --git a/secrets/secrets.nix b/secrets/secrets.nix index bf47478..4c3cbdf 100644 --- a/secrets/secrets.nix +++ b/secrets/secrets.nix @@ -27,8 +27,16 @@ in jet server ]; + "zulip-api-key.age".publicKeys = [ + jet + server + ]; "discord-webhook-secret.age".publicKeys = [ jet server ]; + "zulip-webhook-secret.age".publicKeys = [ + jet + server + ]; } diff --git a/secrets/zulip-api-key.age b/secrets/zulip-api-key.age new file mode 100644 index 0000000..27e16d4 --- /dev/null +++ b/secrets/zulip-api-key.age @@ -0,0 +1,7 @@ +age-encryption.org/v1 +-> ssh-ed25519 Ziw7aw 6YAV0osp6aSWIIPCsP2kxAMkrDU28P1zBmUBwQ+p8zg +AfON2WAv+DlE6huU1/A16RAcYvs/HTmbST7gtOcn4HA +-> ssh-ed25519 uKftJg r9Ci+Heth7AyRm2ZXNH1Sa/jpnepEPfyYfT2uf9q9jc +NQI11W4r8JRkoSsJUnGPc97DFfJy0Gqj83IlRShXgcU +--- ZY8XqiGC40WiD9RRAYWC5nQ+ymXdMsTdt1G+YohJxxk ++qmDZٹROߣF[Th\";W5{vtgWCb,ѻ:b9 \ No newline at end of file diff --git a/secrets/zulip-webhook-secret.age b/secrets/zulip-webhook-secret.age new file mode 100644 index 0000000..ed9634f --- /dev/null +++ b/secrets/zulip-webhook-secret.age @@ -0,0 +1,7 @@ +age-encryption.org/v1 +-> ssh-ed25519 Ziw7aw 9Da19useHIZG/q7hc3+FcMTfV0hsS4A3E/e16TTNgCU +y4/UsjxFSbAgdC1ADa/Mz3NxTutPayOPHE2Kczu69Yg +-> ssh-ed25519 uKftJg Sr4MInGNiNaL9LleBT9i7vbI5VrVkOr//h5Jm7ktwCA +lI3v7oSGgtnR78+hKEFft1O1B1JPlJTx2JB66NFGYdQ +--- 72Wb0XrPWRaPWxh6hmgB+BAEC1CI+oI0EsDIQRNZP4M +B;ʓ(8_F#ZmFęJ_jnovyY2JfJ&aM933[ r (+t \ No newline at end of file