// Client de l'API Go (voir internal/api/api.go). export type Role = "admin" | "user"; export type Status = "active" | "pending" | "disabled"; export type Registration = "closed" | "approval" | "open"; /** Session courante et réglages publics (GET /api/me, accessible sans connexion). */ export interface Me { mode: "none" | "local" | "oidc" | "both"; local: boolean; oidc: boolean; oidcName?: string; registration: Registration; /** Aucun administrateur : le premier compte créé le devient. */ setup?: boolean; title: string; version?: string; user?: { id: string; name: string; email?: string; role: Role; provider?: "local" | "oidc" }; admin: boolean; canChangePassword?: boolean; logout?: string; /** Administrateur : inscriptions à valider. */ pending?: number; } export interface Account { id: string; username?: string; name: string; email?: string; provider: "local" | "oidc"; role: Role; status: Status; created: string; lastLogin?: string; } // --- Suivi des stacks -------------------------------------------------------------- export type StackStatus = "uptodate" | "updates" | "stopped" | "error"; export interface Target { id: string; user: string; roots: string[]; depth: number; } export interface Service { name: string; image: string; running: string; latest: string; state: "ok" | "update" | "unknown"; } export interface Applied { at: string; by: string; ok: boolean; message: string; } export interface Stack { dir: string; name: string; file: string; status: StackStatus; error?: string; services?: Service[]; applied?: Applied; /** Exclue des mises à jour par un administrateur (reste analysée et affichée). */ excluded?: boolean; /** Mise a jour automatique programmee (crontab). */ auto?: AutoInfo; } export interface AutoInfo { schedule: string; by?: string; since: string; /** Prochaine execution (absente : jamais). */ next?: string; lastRun?: string; lastOk: boolean; lastMessage?: string; /** Echeance atteinte, connexion occupee : nouvel essai a la minute suivante. */ pending?: boolean; } /** Resultat d'une stack lors d'une mise a jour globale programmee. */ export interface HostStackResult { target: string; user: string; dir: string; name: string; ok: boolean; /** Rien a faire (deja a jour, stack arretee). */ skipped?: boolean; message: string; } /** Mise a jour globale programmee d'un serveur. */ export interface HostAutoInfo { schedule: string; by?: string; since: string; next?: string; lastRun?: string; lastOk: boolean; lastMessage?: string; results?: HostStackResult[]; pending?: boolean; running?: boolean; /** Stack en cours pendant une execution. */ current?: string; } export interface Scan { running: boolean; task?: "scan" | "apply"; current?: string; started?: string; finished?: string; error?: string; warnings?: string[]; stacks: Stack[]; docker?: string; compose?: string; } export interface ServerInput { id?: string; name: string; host: string; port: number; note?: string; enabled: boolean; targets: { id?: string; user: string; roots: string[]; depth: number }[]; } export interface Server extends ServerInput { id: string; targets: Target[]; /** Résultat de chaque connexion, par identifiant de connexion. */ scans: Record; /** Mise a jour globale programmee du serveur. */ auto?: HostAutoInfo; } export interface Summary { servers: number; stacks: number; updates: number; excluded: number; errors: number; stopped: number; unreachable: number; scanning: number; } export interface Fleet { servers: Server[]; summary: Summary; /** Secondes entre deux analyses automatiques (0 : désactivées). */ interval: number; /** Fuseau horaire des planifications. */ tz?: string; /** Administrateur : clé publique SSH à autoriser sur les serveurs. */ publicKey?: string; } export interface PingResult { target: string; user: string; ok: boolean; message: string; } export class ApiError extends Error { constructor( public status: number, message: string, public code?: string, ) { super(message); } } async function request(url: string, init?: RequestInit): Promise { const res = await fetch(url, init); if (!res.ok) { // Session OIDC expirée : reconnexion, puis retour sur la page courante. const login = res.status === 401 ? res.headers.get("X-Auth-Login") : null; if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`); let msg = res.statusText; let code: string | undefined; try { const j = await res.json(); msg = j.error ?? msg; code = j.code; } catch { /* corps non JSON */ } throw new ApiError(res.status, msg, code); } return res; } const q = (p: string) => encodeURIComponent(p); const json = (body: unknown, method = "POST"): RequestInit => ({ method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); export const api = { me: async (): Promise => (await request("/api/me")).json(), // --- Connexion --------------------------------------------------------------- login: async (username: string, password: string): Promise => { await request("/auth/local/login", json({ username, password })); }, /** Renvoie « active » (connecté d'office) ou « pending » (à valider par un administrateur). */ register: async (v: { username: string; name: string; email: string; password: string }): Promise<"active" | "pending"> => { const res = await request("/auth/local/register", json(v)); return (await res.json()).status; }, // --- Serveurs et analyses ---------------------------------------------------- fleet: async (): Promise => (await request("/api/fleet")).json(), checkAll: async (): Promise => { await request("/api/check", { method: "POST" }); }, check: async (serverId: string, targetId?: string): Promise => { await request(`/api/servers/${q(serverId)}/check${targetId ? `?target=${q(targetId)}` : ""}`, { method: "POST" }); }, addServer: async (v: ServerInput): Promise<{ id: string }> => (await request("/api/servers", json(v))).json(), updateServer: async (id: string, v: ServerInput): Promise<{ id: string }> => (await request(`/api/servers/${q(id)}`, json(v, "PUT"))).json(), deleteServer: async (id: string): Promise => { await request(`/api/servers/${q(id)}`, { method: "DELETE" }); }, /** Teste la connexion SSH, docker et docker compose (id « - » : serveur pas encore enregistré, décrit par v). */ testServer: async (id: string, v?: ServerInput): Promise => (await request(`/api/servers/${q(id)}/test`, v ? json(v) : { method: "POST" })).json(), applyStack: async (serverId: string, targetId: string, dir: string): Promise => { await request(`/api/servers/${q(serverId)}/targets/${q(targetId)}/apply`, json({ dir })); }, /** Exclut une stack des mises à jour (on) ou la réactive. */ excludeStack: async (serverId: string, targetId: string, dir: string, on: boolean): Promise => { await request(`/api/servers/${q(serverId)}/targets/${q(targetId)}/exclude`, json({ dir, excluded: on }, "PUT")); }, /** Programme la mise a jour automatique d'une stack (crontab) ; schedule vide : la desactive. */ autoStack: async (serverId: string, targetId: string, dir: string, schedule: string): Promise => { await request(`/api/servers/${q(serverId)}/targets/${q(targetId)}/auto`, json({ dir, schedule }, "PUT")); }, /** Programme la mise a jour globale d'un serveur (crontab) ; schedule vide : la desactive. */ autoServer: async (serverId: string, schedule: string): Promise => { await request(`/api/servers/${q(serverId)}/auto`, json({ schedule }, "PUT")); }, /** Valide une planification et renvoie ses prochaines executions. */ cronPreview: async (expr: string): Promise => (await (await request(`/api/cron?expr=${q(expr)}`)).json()).next, // --- Compte ------------------------------------------------------------------ changePassword: async (current: string, next: string): Promise => { await request("/api/account/password", json({ current, new: next })); }, patchAccount: async (v: { name?: string; email?: string }): Promise => { await request("/api/account", json(v, "PATCH")); }, // --- Administration ---------------------------------------------------------- users: async (): Promise => (await request("/api/admin/users")).json(), createUser: async (v: { username: string; name: string; email: string; password: string; role: Role }): Promise => (await request("/api/admin/users", json(v))).json(), patchUser: async (id: string, v: Partial<{ name: string; email: string; role: Role; status: Status; password: string }>): Promise => (await request(`/api/admin/users/${q(id)}`, json(v, "PATCH"))).json(), deleteUser: async (id: string): Promise => { await request(`/api/admin/users/${q(id)}`, { method: "DELETE" }); }, };