// Copyright (C) 2026 Dcntrlized // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see . package db import ( "context" "crypto/sha256" "encoding/hex" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5/pgconn" ) // The one durable, anonymised lifecycle log: alarm.event_log. It records only // important events — never stdout (that stays on stdout), never request // metadata, never a network identifier. // // Event values are stable slugs; `reason` is the minimal discriminator an ending // needs (`delivered`, `expired`, `disarmed`, `deleted`). Identities are SHA-256 // hex of the UUID string: UUIDs carry ~122 random bits, so a plain digest is // genuinely one-way here. const ( EventCreated = "created" EventJoined = "joined" EventTriggered = "triggered" EventDelivered = "delivered" EventDestroyed = "destroyed" EventLoginFail = "login_failed" EventJoinReject = "join_rejected" ) // Destruction reasons, set on `destroyed` rows only. const ( DestroyReasonDelivered = "delivered" // the delivery ledger drained DestroyReasonExpired = "expired" // the owner's persistence cap fired DestroyReasonDeleted = "deleted" // the owner explicitly deleted it DestroyReasonDisarmed = "disarmed" // the owner disarmed it ) // hashUUID returns SHA-256 hex of the UUID's canonical string. func hashUUID(id uuid.UUID) string { sum := sha256.Sum256([]byte(id.String())) return hex.EncodeToString(sum[:]) } // HashUUID exposes the digest so tests can query rows without the raw id. func HashUUID(id uuid.UUID) string { return hashUUID(id) } // execer is the subset of pgxpool.Pool / pgx.Tx the event writer needs, so a // lifecycle row can be written inside the transaction that caused it. type execer interface { Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) } // recordEvent appends one anonymised lifecycle row. It never receives a raw id: // callers pass UUIDs and this is the only place identities are hashed. func recordEvent(ctx context.Context, ex execer, alertID uuid.UUID, userID *uuid.UUID, event, reason string) error { var userHash *string if userID != nil { h := hashUUID(*userID) userHash = &h } var reasonPtr *string if reason != "" { reasonPtr = &reason } _, err := ex.Exec(ctx, `INSERT INTO alarm.event_log (event, alert_hash, user_hash, reason) VALUES ($1, $2, $3, $4)`, event, hashUUID(alertID), userHash, reasonPtr) return err } // RecordDelivered appends the `delivered` row for a device that just acknowledged // an alarm. Callers fire it only when an ack actually cleared a ledger row, so a // repeated ack does not inflate the count. func RecordDelivered(ctx context.Context, alertID, userID uuid.UUID) error { return recordEvent(ctx, Pool(), alertID, &userID, EventDelivered, "") } // EventLogRetention is the age-based retention for the event log. const EventLogRetention = 7 * 24 * time.Hour // PruneEventLog enforces the age-based retention: the growth table is swept with // expiry, and seven days is enough to answer "what happened last night" without // keeping a permanent behavioural record. Returns rows deleted. func PruneEventLog(ctx context.Context, maxAge time.Duration) (int64, error) { tag, err := Pool().Exec(ctx, `DELETE FROM alarm.event_log WHERE occurred_at < now() - $1::interval`, maxAge.String()) if err != nil { return 0, err } return tag.RowsAffected(), nil }