Alerts can post into a Matrix room as formatted messages

A Matrix room is where a Matrix admin already looks. The alerts account
joins the room by its address or ID and posts m.text (so it notifies)
with an HTML body: the headline coloured red, green or purple by what it
says, problems and changelog entries as a list, and a footer naming the
server and time. The token travels in the 0600 vars file and env file
like the URL does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vvvomitandClaude Opus 5.5 committed 2026-10-29 05:38:17 +03:30
1 parent 1412810103
commit adde5b48ac
5 files changed
+147 -13

No files matched your search

+5 -1
View File
@@ -250,7 +250,11 @@ or the [Telegram group](https://t.me/+6UwIu9F4gZQxNjM0).
(registry, packages, playbook) not answering, and
sends a message when that changes (once when something breaks, once
when it's fixed) to an ntfy topic, or as `{"text": …}` to a webhook
such as a Hookshot room, Slack, Discord or Mattermost. Applying sends
such as a Hookshot room, Slack, Discord or Mattermost, or straight
into a Matrix room as formatted messages (a coloured headline and a
list), posted by an account you make for it with its access token.
Use a room on another server for that, or ntfy: an alert that your
homeserver is down can't come through it. Applying sends
a test message. Once a day it also looks at the playbook's changelog
and sends the entries newer than your last update, marking with ★
those about your homeserver or enabled components.
+6
View File
@@ -109,6 +109,12 @@ type Alerts struct {
URL string // where messages are POSTed
JSON bool // {"text": …} for webhooks (Hookshot, Slack, Discord), else plain text (ntfy)
Every string // systemd OnCalendar, e.g. "*:0/5"
// Matrix, when set, posts to Room on Homeserver as the account Token
// belongs to, instead of to URL.
Matrix bool `json:",omitempty"`
Homeserver string `json:",omitempty"` // e.g. https://matrix.example.org
Room string `json:",omitempty"` // !id:server or #alias:server
Token string `json:",omitempty"`
}
// BackupSchedule configures the database backups the server makes itself.
+61 -6
View File
@@ -27,8 +27,42 @@ set -uo pipefail
set -a; . "${IZ_ENV:-/etc/interzone-alerts.env}"; set +a
state=${IZ_STATE:-/var/lib/interzone-alerts.state}
# A Matrix message: the headline coloured by what it says, the lines after
# it as a list (★ ones in bold), and where and when it came from.
send_matrix() {
python3 - "$1" <<'PY'
import html, json, os, ssl, sys, time, urllib.parse, urllib.request
msg = sys.argv[1]
head, *rest = msg.split("\n")
color = {"✗": "#e5484d", "✓": "#30a46c"}.get(head[:1], "#8e4ec6")
out = ['<h4><font data-mx-color="%s" color="%s">%s</font></h4>' % (color, color, html.escape(head))]
items = []
for line in rest:
if line[:2] in ("• ", "★ "):
text = html.escape(line[2:])
items.append("<li><b>★ %s</b></li>" % text if line[0] == "★" else "<li>%s</li>" % text)
elif line.strip():
out.append("<p>%s</p>" % html.escape(line))
if items:
out.append("<ul>%s</ul>" % "".join(items))
out.append("<p><sub>interzone · %s · %s</sub></p>" % (html.escape(os.environ["IZ_HOST"]), time.strftime("%Y-%m-%d %H:%M %Z")))
ctx = ssl._create_unverified_context() if os.environ.get("IZ_MATRIX_INSECURE") == "true" else None
def call(method, path, body):
req = urllib.request.Request(os.environ["IZ_MATRIX_HS"].rstrip("/") + path, json.dumps(body).encode(), method=method,
headers={"Authorization": "Bearer " + os.environ["IZ_MATRIX_TOKEN"], "Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=20, context=ctx) as resp:
return json.load(resp)
# Joining is how an alias becomes a room ID; in a room already, it changes nothing.
room = call("POST", "/_matrix/client/v3/join/" + urllib.parse.quote(os.environ["IZ_MATRIX_ROOM"], safe=""), {})["room_id"]
call("PUT", "/_matrix/client/v3/rooms/%s/send/m.room.message/interzone%d" % (urllib.parse.quote(room, safe=""), time.time_ns()),
{"msgtype": "m.text", "body": msg, "format": "org.matrix.custom.html", "formatted_body": "".join(out)})
PY
}
send() {
if [ "$IZ_JSON" = true ]; then
if [ "${IZ_MATRIX:-}" = true ]; then
send_matrix "$1"
elif [ "$IZ_JSON" = true ]; then
printf '%s' "$1" | python3 -c 'import json, sys; m = sys.stdin.read(); print(json.dumps({"text": m, "body": m, "content": m}))' |
curl -fsS -m 20 -o /dev/null -H 'Content-Type: application/json' --data-binary @- "$IZ_URL"
else
@@ -143,6 +177,11 @@ const alertsPlay = `- name: Set up alerts
IZ_PORT={{ interzone_port | quote }}
IZ_URL={{ interzone_url | quote }}
IZ_JSON={{ interzone_json | bool | lower }}
IZ_MATRIX={{ interzone_matrix | bool | lower }}
IZ_MATRIX_HS={{ interzone_matrix_hs | quote }}
IZ_MATRIX_ROOM={{ interzone_matrix_room | quote }}
IZ_MATRIX_TOKEN={{ interzone_matrix_token | quote }}
IZ_MATRIX_INSECURE={{ interzone_matrix_insecure | bool | lower }}
IZ_MIRRORS={{ interzone_mirrors | join(' ') | quote }}
IZ_PLAYBOOK={{ interzone_playbook | quote }}
IZ_HOMESERVER={{ interzone_homeserver | quote }}
@@ -282,11 +321,23 @@ func seenTitles(c *config.Config) string {
return out.String()
}
// AlertsURLProblem says what's wrong with an alerts URL, or "".
func AlertsURLProblem(u string) string {
p, err := url.Parse(u)
if err != nil || (p.Scheme != "https" && p.Scheme != "http") || p.Host == "" {
// AlertsProblem says what's wrong with where alerts go, or "".
func AlertsProblem(a config.Alerts) string {
web := func(u string) bool {
p, err := url.Parse(u)
return err == nil && (p.Scheme == "https" || p.Scheme == "http") && p.Host != ""
}
switch {
case !a.Matrix && !web(a.URL):
return "The alerts address must be an http(s):// URL, e.g. https://ntfy.sh/a-long-random-topic."
case !a.Matrix:
return ""
case !web(a.Homeserver):
return "The homeserver must be an http(s):// URL, e.g. https://matrix.example.org."
case !strings.Contains(a.Room, ":") || (a.Room[0] != '!' && a.Room[0] != '#'):
return "The room is its ID (!abc…:example.org) or an address (#alerts:example.org)."
case strings.TrimSpace(a.Token) == "":
return "The access token of the account that posts the alerts is missing."
}
return ""
}
@@ -298,7 +349,7 @@ func (r *Runner) alerts(ctx context.Context) error {
if !calendarSafe.MatchString(a.Every) {
return fmt.Errorf("%q isn't a schedule systemd understands (try *:0/5 for every 5 minutes)", a.Every)
}
if p := AlertsURLProblem(a.URL); p != "" {
if p := AlertsProblem(a); p != "" {
return fmt.Errorf("%s", p)
}
}
@@ -306,9 +357,13 @@ func (r *Runner) alerts(ctx context.Context) error {
if r.cfg.SSL.Mode == "none" {
scheme, port = "http", "80"
}
// A self-signed certificate is only trusted on this server's own name.
insecure := r.cfg.SSL.Mode == "selfsigned" && strings.Contains(a.Homeserver, "//"+r.cfg.HostName())
// The URL may hold a secret topic or token, so it goes in a file, not
// on the command line.
vars, _ := json.Marshal(map[string]any{"interzone_enabled": a.Enabled, "interzone_every": a.Every,
"interzone_matrix": a.Matrix, "interzone_matrix_hs": a.Homeserver, "interzone_matrix_room": a.Room,
"interzone_matrix_token": a.Token, "interzone_matrix_insecure": insecure,
"interzone_url": a.URL, "interzone_json": a.JSON, "interzone_domain": r.cfg.Domain,
"interzone_host": r.cfg.HostName(), "interzone_scheme": scheme, "interzone_port": port,
"interzone_script": alertsScript, "interzone_mirrors": alertMirrors(r.cfg),
+47
View File
@@ -1,12 +1,18 @@
package deploy
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
"interzone/internal/config"
)
// The alert script sends once when problems appear, nothing while they
@@ -87,4 +93,45 @@ printf '# 2026-10-28\n\n## Something about Jitsi\n\nOther.\n\n## Bridges: see [d
if got := run("test"); !strings.Contains(got, `"text": "interzone alerts are on for example.org`) {
t.Errorf("JSON test message sent as %q", got)
}
// To a Matrix room: joined by its alias, then a formatted message.
var paths []string
var msg map[string]string
hs := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.Method+" "+r.URL.EscapedPath()+" "+r.Header.Get("Authorization"))
if r.Method == "PUT" {
b, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(b, &msg)
}
_, _ = io.WriteString(w, `{"room_id": "!abc:example.org", "event_id": "$e"}`)
}))
defer hs.Close()
_ = os.WriteFile(env, []byte("IZ_DOMAIN=example.org\nIZ_HOST=matrix.example.org\nIZ_SCHEME=http\nIZ_PORT=80\nIZ_URL=\nIZ_JSON=false\n"+
"IZ_MATRIX=true\nIZ_MATRIX_HS="+hs.URL+"\nIZ_MATRIX_ROOM='#alerts:example.org'\nIZ_MATRIX_TOKEN=sekrit\n"), 0o600)
t.Setenv("no_proxy", "127.0.0.1")
_ = os.WriteFile(filepath.Join(dir, "failing"), nil, 0o644)
run()
if len(paths) != 2 || paths[0] != "POST /_matrix/client/v3/join/%23alerts%3Aexample.org Bearer sekrit" ||
!strings.HasPrefix(paths[1], "PUT /_matrix/client/v3/rooms/%21abc%3Aexample.org/send/m.room.message/interzone") {
t.Fatalf("Matrix requests: %q", paths)
}
f := msg["formatted_body"]
if msg["format"] != "org.matrix.custom.html" || !strings.HasPrefix(f, `<h4><font data-mx-color="#e5484d"`) ||
!strings.Contains(f, "<li>matrix-synapse.service has failed</li>") || !strings.Contains(f, "doesn&#x27;t answer") ||
!strings.Contains(msg["body"], "• matrix-synapse.service has failed") {
t.Errorf("Matrix message: %q", msg)
}
}
func TestAlertsProblem(t *testing.T) {
ok := config.Alerts{Matrix: true, Homeserver: "https://matrix.example.org", Room: "#alerts:example.org", Token: "t"}
if p := AlertsProblem(ok); p != "" {
t.Error(p)
}
for _, bad := range []config.Alerts{{URL: "ntfy.sh/x"}, {Matrix: true, Homeserver: "matrix.example.org", Room: "#a:b", Token: "t"},
{Matrix: true, Homeserver: "https://m.example", Room: "alerts", Token: "t"}, {Matrix: true, Homeserver: "https://m.example", Room: "!a:b"}} {
if AlertsProblem(bad) == "" {
t.Errorf("%+v passed", bad)
}
}
}
+28 -6
View File
@@ -12,8 +12,8 @@ import (
// ── Alerts ─────────────────────────────────────────────────────────
//
// The server checks itself on a timer and sends a message to ntfy or a
// webhook when something breaks and when it's fixed (deploy/alerts.go).
// The server checks itself on a timer and sends a message to ntfy, a
// webhook or a Matrix room when something breaks and when it's fixed (deploy/alerts.go).
type alertsScreen struct {
cfg *config.Config
@@ -47,17 +47,34 @@ func (s *alertsScreen) enter(c *config.Config) tea.Cmd {
if a.JSON {
format = "json"
}
if a.Matrix {
format = "matrix"
}
hs := a.Homeserver
if hs == "" {
hs = map[bool]string{true: "http://", false: "https://"}[c.SSL.Mode == "none"] + c.HostName()
}
s.form = newForm(
toggleField("on", "Send alerts", a.Enabled,
"The server checks itself, even when this computer is off: failed services, the homeserver not answering, a certificate expiring within 14 days, a disk over 90% full, a mirror not answering. Once a day, new entries in the playbook's changelog too."),
textField("url", "Send them to", a.URL, example,
"An ntfy topic (subscribe to it in the ntfy app), or a webhook: a Hookshot room webhook, Slack, Discord or Mattermost. Anyone who knows an ntfy topic can read it, so make it long and random."),
choiceField("format", "Message format", []string{"text", "json"},
[]string{"Plain text (ntfy)", `JSON {"text": …} (webhooks)`}, format, ""),
[]string{"Plain text (ntfy)", `JSON {"text": …} (webhooks)`, "Matrix room"}, format,
"A Matrix room gets them as formatted messages. An alert that the homeserver is down can't arrive through that same homeserver, so a room on another server, or ntfy, is safer."),
textField("hs", "Homeserver", hs, "https://matrix.example.org", "The homeserver of the account that posts the alerts."),
textField("room", "Room", a.Room, "#alerts:"+c.Domain, "The room's address (#…) or ID (!…), from its settings › Advanced. Invite the alerts account to it."),
secretField("token", "Access token", a.Token,
"Make an account just for alerts, sign in with it in Element, and copy its token from Settings › Help & About › Access token. Don't sign it out: that ends the token."),
textField("every", "Check", a.Every, "*:0/5", "A systemd calendar time: *:0/5 is every 5 minutes, hourly, daily …"),
)
off := func() bool { return !s.form.get("on").on }
s.form.get("url").hidden, s.form.get("format").hidden, s.form.get("every").hidden = off, off, off
matrix := func() bool { return !off() && s.form.value("format") == "matrix" }
notMatrix := func() bool { return off() || matrix() }
s.form.get("url").hidden, s.form.get("format").hidden, s.form.get("every").hidden = notMatrix, off, off
for _, k := range []string{"hs", "room", "token"} {
s.form.get(k).hidden = func() bool { return !matrix() }
}
return nil
}
@@ -73,9 +90,14 @@ func (s *alertsScreen) update(msg tea.Msg) tea.Cmd {
func (s *alertsScreen) apply() tea.Cmd {
a := config.Alerts{Enabled: s.form.get("on").on, URL: strings.TrimSpace(s.form.value("url")),
JSON: s.form.value("format") == "json", Every: strings.TrimSpace(s.form.value("every"))}
JSON: s.form.value("format") == "json", Every: strings.TrimSpace(s.form.value("every")),
Matrix: s.form.value("format") == "matrix", Homeserver: strings.TrimSpace(s.form.value("hs")),
Room: strings.TrimSpace(s.form.value("room")), Token: strings.TrimSpace(s.form.value("token"))}
if !a.Matrix {
a.Homeserver, a.Room, a.Token = "", "", ""
}
if a.Enabled {
if p := deploy.AlertsURLProblem(a.URL); p != "" {
if p := deploy.AlertsProblem(a); p != "" {
s.err = p
return nil
}