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;
|
||||
Reference in New Issue
Block a user