SPB Git

Repository Public

main.js 12.4 KB 281 lines javascript

1// Dashboard administrateur : porte de connexion par clé d'accès, coquille, routage client sur /admin/<vue>.23import { ApiError, api, errorMessage, isSilent, post, refreshSession, send, setAuthLostHandler, setCsrf, setReauthHandler } from "./api.js";4import { h, hydrateIcons, icon, mount } from "./dom.js";5import { bindThemeButtons, note, openDialog, toast, toggleTheme, currentTheme } from "./ui.js";6import { describeWebAuthnError, getCredential, isSupported } from "../webauthn.js";7import overview from "./views/overview.js";8import monitoring from "./views/monitoring.js";9import analytics from "./views/analytics.js";10import keys from "./views/keys.js";11import models from "./views/models.js";12import security from "./views/security.js";13import audit from "./views/audit.js";1415const VIEWS = { "": overview, monitoring, analytics, keys, models, security, audit };16const $ = (id) => document.getElementById(id);17const boot = $("boot");18const gate = $("gate");19const app = $("app");20const viewEl = $("view");21const actionsEl = $("view-actions");2223let cleanups = [];24let inApp = false;2526// --- vue courante -----------------------------------------------------------------------------------27function teardown() {28  for (const fn of cleanups.splice(0)) {29    try { fn(); } catch { /* nettoyage au mieux */ }30  }31}3233function makeContext() {34  const ctx = {35    root: viewEl,36    actions: actionsEl,37    navigate,38    onCleanup: (fn) => cleanups.push(fn),39    /** Rafraîchissement périodique, suspendu quand l'onglet est masqué. */40    poll(fn, intervalMs) {41      let timer = null;42      let stopped = false;43      let running = false;44      const tick = async () => {45        if (stopped || running || document.hidden) return;46        running = true;47        try { await fn(); } catch (err) { if (!isSilent(err)) console.warn("rafraîchissement :", err.message); } finally { running = false; }48      };49      const start = () => { clearInterval(timer); timer = setInterval(tick, intervalMs); };50      const onVisibility = () => { if (document.hidden) clearInterval(timer); else { tick(); start(); } };51      document.addEventListener("visibilitychange", onVisibility);52      start();53      cleanups.push(() => { stopped = true; clearInterval(timer); document.removeEventListener("visibilitychange", onVisibility); });54      return tick;55    },56  };57  return ctx;58}5960function route() {61  if (!inApp) return;62  const seg = location.pathname.replace(/^\/admin\/?/, "").replace(/\/+$/, "");63  const view = VIEWS[seg];64  if (!view) { history.replaceState(null, "", "/admin"); route(); return; }65  teardown();66  const name = seg || "overview";67  for (const link of document.querySelectorAll("[data-view]")) {68    if (link.dataset.view === name) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current");69  }70  const more = $("tab-more");71  if (["models", "security", "audit"].includes(name)) more.setAttribute("aria-current", "page"); else more.removeAttribute("aria-current");72  $("view-title").textContent = view.title;73  $("view-sub").textContent = view.sub || "";74  document.title = `${view.title} — MacLustr LLM API`;75  mount(actionsEl);76  mount(viewEl);77  viewEl.style.animation = "none";78  void viewEl.offsetWidth; // relance l'animation d'entrée79  viewEl.style.animation = "";80  window.scrollTo(0, 0);81  try {82    view.mount(makeContext());83  } catch (err) {84    console.error(err);85    mount(viewEl, note("danger", "Cette vue n'a pas pu s'afficher."));86  }87}8889function navigate(path) {90  if (path !== location.pathname) history.pushState(null, "", path);91  route();92}9394// --- porte de connexion -----------------------------------------------------------------------------95function showGate({ activated = true, message = null } = {}) {96  inApp = false;97  teardown();98  for (const dlg of document.querySelectorAll("dialog[open]")) dlg.close();99  setCsrf(null);100  boot.hidden = true;101  app.hidden = true;102  gate.hidden = false;103  document.title = "Connexion — MacLustr LLM API";104  const stage = $("gate-stage");105  const feedback = h("div", { "aria-live": "assertive" });106  if (message) mount(feedback, note(message.kind || "info", message.text));107108  if (!activated) {109    mount(stage,110      h("div", { class: "gate-emblem" }, icon("shield")),111      h("h1", { id: "gate-title" }, "Administrateur non activé"),112      h("p", null, "Aucun administrateur n'est encore configuré sur ce serveur. L'activation se fait une seule fois, à l'aide d'un lien à usage unique généré localement."),113      h("ol", { class: "steps" },114        h("li", null, h("b", null, "1. Sur le Mac mini, dans le terminal"), h("span", { class: "cmd" }, "maclustr-llm setup-link")),115        h("li", null, h("b", null, "2. Ouvrez le lien affiché sur cet appareil"), h("span", null, " — il est valable 15 minutes et ne fonctionne qu'une fois. Vous y créerez votre clé d'accès."))),116      h("div", { class: "gate-actions" }, h("button", { class: "btn btn-lg", type: "button", onclick: () => location.reload() }, icon("refresh"), "Vérifier à nouveau")),117      h("p", { class: "gate-foot" }, h("a", { href: "/" }, "Retour au site")));118    return;119  }120121  const supported = isSupported();122  const button = h("button", { class: "btn btn-primary btn-lg", type: "button", disabled: !supported }, icon("passkey"), "Se connecter avec une clé d'accès");123  button.addEventListener("click", async () => {124    if (button.disabled) return;125    const saved = [...button.childNodes];126    button.disabled = true;127    button.replaceChildren(h("span", { class: "spinner", "aria-hidden": "true" }), "En attente de votre appareil…");128    mount(feedback);129    try {130      const options = await send("POST", "/admin/api/login/options", {});131      let credential;132      try {133        credential = await getCredential(options.publicKey);134      } catch (err) {135        mount(feedback, note(err.name === "NotAllowedError" ? "warn" : "danger", describeWebAuthnError(err, "get")));136        return;137      }138      const out = await send("POST", "/admin/api/login/verify", { challenge_id: options.challenge_id, credential });139      setCsrf(out.csrf_token);140      enterApp();141    } catch (err) {142      let text = errorMessage(err);143      if (err instanceof ApiError && err.code === "login_failed") {144        text = "Cette clé d'accès n'est pas reconnue par ce serveur. Choisissez une clé enregistrée pour MacLustr LLM API, ou utilisez la procédure de récupération.";145      } else if (err instanceof ApiError && err.code === "challenge_invalid") {146        text = "La demande a expiré avant d'aboutir. Réessayez.";147      }148      mount(feedback, note("danger", text));149    } finally {150      if (!inApp) { button.disabled = false; button.replaceChildren(...saved); }151    }152  });153154  mount(stage,155    h("div", { class: "gate-emblem" }, icon("passkey")),156    h("h1", { id: "gate-title" }, "Connexion au Dashboard"),157    h("p", null, "L'accès est réservé à l'administrateur et protégé par une clé d'accès : votre appareil confirme votre identité avec Touch ID ou Face ID. Aucun mot de passe."),158    supported ? null : note("danger", "Ce navigateur ne prend pas en charge les clés d'accès, ou la page n'est pas ouverte en HTTPS. Utilisez Safari ou Chrome à jour."),159    feedback,160    h("div", { class: "gate-actions" }, button),161    h("p", { class: "gate-foot" }, "Clé perdue ? Exécutez ", h("code", null, "maclustr-llm recover"), " sur le Mac mini. ", h("a", { href: "/" }, "Retour au site")));162  if (supported) button.focus({ preventScroll: true });163}164165// --- ré-authentification (actions critiques) --------------------------------------------------------166let reauthPending = null;167168function reauth() {169  if (reauthPending) return reauthPending;170  reauthPending = openDialog({171    title: "Confirmez avec votre clé d'accès",172    render: (close) => {173      const feedback = h("div", { "aria-live": "assertive" });174      const button = h("button", { class: "btn btn-primary", type: "button" }, icon("passkey"), "Confirmer");175      const run = async () => {176        if (button.disabled) return;177        const saved = [...button.childNodes];178        button.disabled = true;179        button.replaceChildren(h("span", { class: "spinner", "aria-hidden": "true" }), "En attente…");180        mount(feedback);181        try {182          const options = await api("POST", "/admin/api/reauth/options", {});183          const credential = await getCredential(options.publicKey);184          await api("POST", "/admin/api/reauth/verify", { challenge_id: options.challenge_id, credential });185          close(true);186        } catch (err) {187          if (err instanceof ApiError && err.code === "not_authenticated") { close(false); return; }188          const text = err instanceof ApiError189            ? (err.code === "login_failed" ? "Cette clé d'accès n'est pas reconnue. Utilisez une clé enregistrée pour ce Dashboard." : errorMessage(err))190            : describeWebAuthnError(err, "get");191          mount(feedback, note(err.name === "NotAllowedError" ? "warn" : "danger", text));192          button.disabled = false;193          button.replaceChildren(...saved);194          button.lastChild.textContent = "Réessayer";195        }196      };197      button.addEventListener("click", run);198      queueMicrotask(run);199      return {200        body: [201          h("p", null, "Cette action est sensible : elle exige une vérification de moins de cinq minutes. Votre appareil va vous demander de confirmer votre identité, puis l'action reprendra automatiquement."),202          feedback,203        ],204        foot: [h("button", { class: "btn btn-ghost", type: "button", onclick: () => close(false) }, "Annuler"), button],205      };206    },207  }).then((ok) => {208    reauthPending = null;209    if (ok !== true) throw new ApiError(401, "reauth_cancelled", "Action annulée.");210  }, (err) => { reauthPending = null; throw err; });211  return reauthPending;212}213214// --- coquille ---------------------------------------------------------------------------------------215async function logout() {216  try { await post("/admin/api/logout"); } catch (err) { if (!isSilent(err)) { toast(errorMessage(err), "danger"); return; } }217  showGate({ message: { kind: "ok", text: "Vous êtes déconnecté." } });218}219220function openMore() {221  const btn = $("tab-more");222  btn.setAttribute("aria-expanded", "true");223  openDialog({224    title: "Plus",225    render: (close) => {226      const go = (path) => () => { close(); navigate(path); };227      const link = (ic, label, fn) => h("button", { class: "nav-link", type: "button", onclick: fn }, icon(ic), label);228      return {229        body: h("div", { class: "sheet-links" },230          link("cube", "Modèles", go("/admin/models")),231          link("shield", "Sécurité", go("/admin/security")),232          link("list", "Journal d'audit", go("/admin/audit")),233          h("a", { class: "nav-link", href: "/docs" }, icon("external"), "Documentation"),234          link(currentTheme() === "dark" ? "sun" : "moon", currentTheme() === "dark" ? "Thème clair" : "Thème sombre", () => { toggleTheme(); close(); }),235          link("logout", "Se déconnecter", () => { close(); logout(); })),236      };237    },238  }).then(() => btn.setAttribute("aria-expanded", "false"));239}240241function enterApp() {242  inApp = true;243  boot.hidden = true;244  gate.hidden = true;245  app.hidden = false;246  route();247}248249function init() {250  hydrateIcons();251  bindThemeButtons();252  setReauthHandler(reauth);253  setAuthLostHandler(() => {254    if (inApp) showGate({ message: { kind: "warn", text: "Votre session a expiré ou a été révoquée. Reconnectez-vous." } });255  });256  document.addEventListener("click", (e) => {257    const link = e.target.closest("a[data-link]");258    if (!link || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;259    e.preventDefault();260    navigate(link.getAttribute("href"));261  });262  window.addEventListener("popstate", route);263  for (const btn of document.querySelectorAll("[data-logout]")) btn.addEventListener("click", logout);264  $("tab-more").addEventListener("click", openMore);265266  refreshSession().then((session) => {267    if (session.authenticated) enterApp();268    else showGate({ activated: session.activated !== false });269  }).catch((err) => {270    boot.hidden = true;271    gate.hidden = false;272    mount($("gate-stage"),273      h("div", { class: "gate-emblem is-danger" }, icon("alert")),274      h("h1", { id: "gate-title" }, "Serveur injoignable"),275      h("p", null, errorMessage(err)),276      h("div", { class: "gate-actions" }, h("button", { class: "btn btn-lg", type: "button", onclick: () => location.reload() }, icon("refresh"), "Réessayer")));277  });278}279280init();281
Files main
Menu

Theme