Phase 9: Hub API and Apprise alerts (/capabilities, /ask, /notify)
Build on Phases 1-8. Adds the project side of the frozen Hub contract
(central_ai_llm_master/docs/ask-contract.md) and the alert engine from
AGENTS.md §4 FR-12/FR-13, §8, §11 Phase 9.
- hub: internal/hub implements AskRequest/AskResponse/NotifyRequest and a
deterministic, read-only Answerer. It answers screen time today/yesterday,
what is blocked now, and device presence, scoped to one child or all kids.
Screen time is the foreground-app total per device-day; the domain total is
used only when a device reports no apps, so a report carrying both is never
double-counted.
- apprise: internal/apprise is a small Apprise API client (stored key or
stateless URL mode, optional bearer token, typed notifications).
- alert: internal/alert evaluates device state on an interval and raises one
Apprise alert per transition: a limit hit (a device becomes blocked) or a
device offline longer than the threshold. A never-seen device is never
alerted, and the first observation seeds state without replaying an old
limit. The alert is recorded before delivery, with its delivery outcome.
- store: migration 005 adds `alerts` (delivery outcome, audited) and
`alert_state` (per-device dedup). New usage reads from the telemetry detail
table so the daily answer can be checked independently.
- web: GET /capabilities, POST /ask (read-only) and POST /notify behind the
shared CONTROL_HUB_TOKEN, separate from the session and admin API tokens.
/notify accepts the contract's {from,level,message,person} and delivers it
through Apprise (the future tamper-report path, FR-17).
- cmd/control: start the alert engine (CONTROL_ALERTS_ENABLED,
CONTROL_ALERT_OFFLINE_AFTER, CONTROL_ALERT_INTERVAL) and add `alerts` and
`usage` subcommands for read-only inspection.
- deploy/verify-phase9.sh + `make verify-phase9` prove the definition of done;
version 0.7.0-phase9.
Measured on .13 (2026-10-13):
- GET /capabilities -> internet_use_control topics.
- POST /ask "how long have the kids been on screens today?" -> "The kids have
had 1h 22m of screen time today." (total_seconds=4925); the independent
count from the telemetry detail table is also 4925 (app=4925, domain=4800).
- A manual lock raised a delivered limit alert (id 4); an MQTT offline status
raised a delivered offline alert (id 5); POST /notify delivered (id 6). All
three report delivered=1 in `alerts`.
Tests: gofmt, go vet ./... and go test ./... pass in golang:1.25-alpine.
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
123
internal/apprise/apprise.go
Normal file
123
internal/apprise/apprise.go
Normal file
@@ -0,0 +1,123 @@
|
||||
// Package apprise delivers notifications through the house Apprise API
|
||||
// (AGENTS.md §8, §11 Phase 9).
|
||||
//
|
||||
// Apprise is the shared notification gateway that already reaches Sam by
|
||||
// email. This client speaks the standard Apprise API server shape:
|
||||
//
|
||||
// POST {base}/notify/{key} JSON {"title","body","type"}
|
||||
// POST {base}/notify JSON {"urls","title","body","type"} (stateless)
|
||||
//
|
||||
// A key names a stored Apprise configuration. When no key is set the client
|
||||
// uses the stateless form with an explicit list of Apprise URLs, which is how
|
||||
// the lab is configured (APPRISE_URLS). Secrets come from environment.d and are
|
||||
// never committed.
|
||||
package apprise
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Notification classes understood by Apprise.
|
||||
const (
|
||||
TypeInfo = "info"
|
||||
TypeSuccess = "success"
|
||||
TypeWarning = "warning"
|
||||
TypeFailure = "failure"
|
||||
)
|
||||
|
||||
// Client posts a notification to one Apprise API server.
|
||||
type Client struct {
|
||||
// BaseURL is the Apprise API root, e.g. http://192.168.20.35:8210.
|
||||
BaseURL string
|
||||
// Key names a stored Apprise configuration. Empty means stateless mode.
|
||||
Key string
|
||||
// URLs is the stateless destination list, used when Key is empty.
|
||||
URLs []string
|
||||
// Token is sent as a bearer token when the Apprise API is protected.
|
||||
Token string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
// New builds a client. A zero timeout defaults to ten seconds.
|
||||
func New(baseURL, key string, urls []string, token string, timeout time.Duration) *Client {
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
return &Client{
|
||||
BaseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
|
||||
Key: strings.TrimSpace(key),
|
||||
URLs: urls,
|
||||
Token: token,
|
||||
HTTP: &http.Client{Timeout: timeout},
|
||||
}
|
||||
}
|
||||
|
||||
// Configured reports whether a delivery can be attempted. A nil client is not
|
||||
// configured, so callers never need to branch on nil.
|
||||
func (c *Client) Configured() bool {
|
||||
if c == nil || strings.TrimSpace(c.BaseURL) == "" {
|
||||
return false
|
||||
}
|
||||
return c.Key != "" || len(c.URLs) > 0
|
||||
}
|
||||
|
||||
// notifyBody is the Apprise API request body. `type` selects the notification
|
||||
// class; alerts are warnings.
|
||||
type notifyBody struct {
|
||||
URLs []string `json:"urls,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Body string `json:"body"`
|
||||
Type string `json:"type,omitempty"`
|
||||
}
|
||||
|
||||
// Send delivers one informational notification.
|
||||
func (c *Client) Send(ctx context.Context, title, body string) error {
|
||||
return c.SendType(ctx, title, body, TypeInfo)
|
||||
}
|
||||
|
||||
// SendType delivers one notification with an explicit Apprise class. A failure
|
||||
// is returned; it is never retried here, so a caller can record the outcome.
|
||||
func (c *Client) SendType(ctx context.Context, title, body, notifyType string) error {
|
||||
if !c.Configured() {
|
||||
return fmt.Errorf("apprise is not configured")
|
||||
}
|
||||
if notifyType == "" {
|
||||
notifyType = TypeInfo
|
||||
}
|
||||
payload := notifyBody{Title: title, Body: body, Type: notifyType}
|
||||
url := c.BaseURL + "/notify"
|
||||
if c.Key != "" {
|
||||
url += "/" + c.Key
|
||||
} else {
|
||||
payload.URLs = c.URLs
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("encode apprise request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return fmt.Errorf("build apprise request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
}
|
||||
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("post apprise: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("post apprise: status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
103
internal/apprise/apprise_test.go
Normal file
103
internal/apprise/apprise_test.go
Normal file
@@ -0,0 +1,103 @@
|
||||
package apprise
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConfigured(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
c *Client
|
||||
want bool
|
||||
}{
|
||||
{"nil", nil, false},
|
||||
{"no base", New("", "key", nil, "", 0), false},
|
||||
{"base no destination", New("http://x", "", nil, "", 0), false},
|
||||
{"key mode", New("http://x", "key", nil, "", 0), true},
|
||||
{"stateless mode", New("http://x", "", []string{"mailto:a@b"}, "", 0), true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := tc.c.Configured(); got != tc.want {
|
||||
t.Errorf("%s: Configured() = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendKeyMode(t *testing.T) {
|
||||
var gotPath string
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotPath = r.URL.Path
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL, "sam_email", nil, "", 0)
|
||||
if err := c.Send(context.Background(), "title", "body"); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
if gotPath != "/notify/sam_email" {
|
||||
t.Errorf("path = %q, want /notify/sam_email", gotPath)
|
||||
}
|
||||
if gotBody["title"] != "title" || gotBody["body"] != "body" {
|
||||
t.Errorf("body = %#v", gotBody)
|
||||
}
|
||||
if _, ok := gotBody["urls"]; ok {
|
||||
t.Errorf("key mode must not send urls: %#v", gotBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendStatelessModeWithAuthAndType(t *testing.T) {
|
||||
var gotAuth, gotType string
|
||||
var gotURLs []any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
var body map[string]any
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
gotType, _ = body["type"].(string)
|
||||
gotURLs, _ = body["urls"].([]any)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL, "", []string{"mailto:sam@example.com"}, "secret", 0)
|
||||
if err := c.SendType(context.Background(), "t", "b", TypeWarning); err != nil {
|
||||
t.Fatalf("SendType: %v", err)
|
||||
}
|
||||
if gotAuth != "Bearer secret" {
|
||||
t.Errorf("auth = %q", gotAuth)
|
||||
}
|
||||
if gotType != TypeWarning {
|
||||
t.Errorf("type = %q, want %q", gotType, TypeWarning)
|
||||
}
|
||||
if len(gotURLs) != 1 || gotURLs[0] != "mailto:sam@example.com" {
|
||||
t.Errorf("urls = %#v", gotURLs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendErrorStatus(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(srv.URL, "key", nil, "", 0)
|
||||
if err := c.Send(context.Background(), "t", "b"); err == nil {
|
||||
t.Fatal("Send() error = nil, want a status error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendNotConfigured(t *testing.T) {
|
||||
c := New("", "", nil, "", 0)
|
||||
if err := c.Send(context.Background(), "t", "b"); err == nil {
|
||||
t.Fatal("Send() error = nil, want not-configured")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user