Hub v1: install API, licences, health dashboard, alerts
- Protocol 1 (docs/hub-protocol.md): public key, register, signed heartbeats - Ed25519 licence tokens (30-day validity, status, expiry, grace, limits) - Dashboard: installs, install detail, customers and licences, alerts, settings and audit log; two-factor login required - Alert checks every 5 minutes, emailed once; heartbeat roll-up after 30 days - Unit tests for encryption, tokens, signatures, TOTP and alert rules Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012mt6TCv85T9VKRq3cV7rXq
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
export const API_URL = (process.env.NEXT_PUBLIC_API_URL || "http://localhost:5200").replace(/\/$/, "");
|
||||
const TOKEN_KEY = "events_hub_token";
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message: string, public status: number, public code?: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
try { return localStorage.getItem(TOKEN_KEY); } catch { return null; }
|
||||
}
|
||||
|
||||
export function setToken(token: string | null) {
|
||||
try {
|
||||
if (token) localStorage.setItem(TOKEN_KEY, token);
|
||||
else localStorage.removeItem(TOKEN_KEY);
|
||||
} catch { /* private window */ }
|
||||
}
|
||||
|
||||
/** Call the Hub API. Logged-in calls send the session token; a 401 signs out. */
|
||||
export async function api<T = unknown>(path: string, options: { method?: string; body?: unknown; auth?: boolean } = {}): Promise<T> {
|
||||
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||
const token = getToken();
|
||||
if (options.auth !== false && token) headers.Authorization = `Bearer ${token}`;
|
||||
const res = await fetch(`${API_URL}${path}`, {
|
||||
method: options.method || "GET",
|
||||
headers,
|
||||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||||
});
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 && options.auth !== false) {
|
||||
setToken(null);
|
||||
if (typeof window !== "undefined" && !window.location.pathname.startsWith("/login")) window.location.href = "/login";
|
||||
}
|
||||
throw new ApiError(data?.message || `Request failed (${res.status})`, res.status, data?.code);
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const errorText = (e: unknown, fallback = "Something went wrong.") => (e instanceof Error && e.message) || fallback;
|
||||
@@ -0,0 +1,25 @@
|
||||
export function fmtDate(d: string | Date | null | undefined, withTime = true) {
|
||||
if (!d) return "—";
|
||||
return new Date(d).toLocaleString("en-ZA", withTime ? { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" } : { day: "numeric", month: "short", year: "numeric" });
|
||||
}
|
||||
|
||||
/** "5 min ago", "3 h ago", "2 days ago". */
|
||||
export function ago(d: string | Date | null | undefined) {
|
||||
if (!d) return "never";
|
||||
const s = Math.round((Date.now() - new Date(d).getTime()) / 1000);
|
||||
if (s < 90) return "just now";
|
||||
if (s < 3600) return `${Math.round(s / 60)} min ago`;
|
||||
if (s < 48 * 3600) return `${Math.round(s / 3600)} h ago`;
|
||||
return `${Math.round(s / 86400)} days ago`;
|
||||
}
|
||||
|
||||
export function bytes(n: number | null | undefined) {
|
||||
if (n == null) return "—";
|
||||
const units = ["B", "KB", "MB", "GB", "TB"];
|
||||
let i = 0;
|
||||
let v = n;
|
||||
while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
|
||||
return `${v.toFixed(i > 1 ? 1 : 0)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export const rand = (cents: number) => `R${(cents / 100).toFixed(2)}`;
|
||||
@@ -0,0 +1,65 @@
|
||||
export type Problem = { type: string; level: "info" | "warning" | "critical"; message: string };
|
||||
export type LicenceStatus = "active" | "suspended" | "revoked";
|
||||
|
||||
export type InstallSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
customer: { id: string; name: string } | null;
|
||||
version: string | null;
|
||||
behind: boolean;
|
||||
licence: { id: string; status: LicenceStatus; expiresAt: string | null } | null;
|
||||
lastHeartbeatAt: string | null;
|
||||
status: "ok" | "warning" | "critical";
|
||||
problems: Problem[];
|
||||
releasedAt: string | null;
|
||||
};
|
||||
|
||||
export type Licence = {
|
||||
id: string;
|
||||
key: string;
|
||||
plan: string;
|
||||
status: LicenceStatus;
|
||||
expiresAt: string | null;
|
||||
graceDays: number;
|
||||
aiMonthlyCapCents: number;
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
install?: { id: string; name: string; url: string; lastHeartbeatAt: string | null } | null;
|
||||
};
|
||||
|
||||
export type Customer = {
|
||||
id: string;
|
||||
name: string;
|
||||
contactName: string | null;
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
notes: string | null;
|
||||
createdAt: string;
|
||||
licences: Licence[];
|
||||
installs: { id: string; url: string; name?: string; lastHeartbeatAt: string | null; releasedAt?: string | null; version?: string | null }[];
|
||||
};
|
||||
|
||||
export type Health = {
|
||||
uptimeSeconds?: number;
|
||||
db?: boolean;
|
||||
jobs?: { mode?: string; failedLast24h?: number };
|
||||
lastBackupAt?: string | null;
|
||||
disk?: { freeBytes: number; totalBytes: number } | null;
|
||||
errorsLast24h?: number | null;
|
||||
pendingMigrations?: number;
|
||||
};
|
||||
|
||||
export type Stats = {
|
||||
users?: number;
|
||||
events?: { active?: number; upcoming?: number; total?: number };
|
||||
registrations?: { last30d?: number; total?: number };
|
||||
tickets?: { last30d?: number; total?: number };
|
||||
checkIns?: { last30d?: number };
|
||||
messages?: { email30d?: number; whatsapp30d?: number };
|
||||
paymentProviders?: string[];
|
||||
campuses?: boolean;
|
||||
income?: { last30d?: string; allTime?: string };
|
||||
};
|
||||
|
||||
export type InstallEvent = { id: string; type: string; level: Problem["level"]; message: string; createdAt: string; resolvedAt: string | null; install?: { id: string; name: string; url: string } };
|
||||
Reference in New Issue
Block a user