package dashboard import ( "context" "crypto/sha256" "database/sql" "embed" "time" ) // Migrations contain only replay digests and clock bounds, never pulled content. // //go:embed migrations/*.sql var Migrations embed.FS // Consume commits replay use before an app resolves identity or reads content. // The clock watermark survives restart and rejects backward movement beyond 30s. func Consume(ctx context.Context, db *sql.DB, c Claims, now time.Time) error { tx, e := db.BeginTx(ctx, nil) if e != nil { return ErrUnavailable } defer tx.Rollback() var observed int64 if e = tx.QueryRowContext(ctx, `UPDATE oficina_dashboard_clock SET observed=MAX(observed,?) WHERE id=1 RETURNING observed`, now.Unix()).Scan(&observed); e != nil { return ErrUnavailable } if now.Unix() < observed-30 || c.Expires <= now.Unix() { return ErrRefused } if _, e = tx.ExecContext(ctx, `DELETE FROM oficina_dashboard_replay WHERE expires < ?`, now.Unix()-30); e != nil { return ErrUnavailable } var count int if e = tx.QueryRowContext(ctx, `SELECT count(*) FROM oficina_dashboard_replay`).Scan(&count); e != nil || count >= 10000 { return ErrUnavailable } h := sha256.Sum256([]byte(c.Issuer + "\x00" + c.ID)) res, e := tx.ExecContext(ctx, `INSERT INTO oficina_dashboard_replay(digest,expires) VALUES(?,?) ON CONFLICT(digest) DO NOTHING`, h[:], c.Expires) if e != nil { return ErrUnavailable } n, e := res.RowsAffected() if e != nil || n != 1 { return ErrRefused } if tx.Commit() != nil { return ErrUnavailable } return nil }