feat: add zulip integration

This commit is contained in:
Jet 2026-03-23 22:18:23 -07:00
parent 50468db20b
commit 3a0d464234
No known key found for this signature in database
14 changed files with 430 additions and 5 deletions

View file

@ -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"] }

View file

@ -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 |

107
remote/zulip-bot/module.nix Normal file
View file

@ -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;
};
};
};
}

View file

@ -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<Arc<AppState>>,
headers: HeaderMap,
Json(body): Json<WebhookPayload>,
) -> 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(())
}