Files
RustProxy/src/admin/web/api-tokens.js
T
2026-11-14 17:24:12 +01:00

85 lines
5.4 KiB
JavaScript

"use strict";
window.rustProxyApiTokens = (() => {
let loading = false, state = null, cidrs = null;
const hideSecret = () => { $("api-token-secret").textContent = ""; $("api-token-secret-wrap").hidden = true; };
const normalizeCidr = value => {
if (!window.rustProxyChipInput.validCidr(value)) return false;
if (value.includes("/")) return value;
return value.includes(":") ? `${value}/128` : `${value}/32`;
};
function closeEditor() { $("api-tokens-form").hidden = true; $("api-token-new").disabled = false; }
function openEditor() {
hideSecret();
$("api-token-comment").value = "";
$("api-token-permission-ro").checked = true;
cidrs = window.rustProxyChipInput.create({ className: "api-token-cidr-editor", placeholder: "192.0.2.10 / 10.0.0.0/24 / 2001:db8::/64", label: t("apiTokenIpAllow"), limit: 32, validate: normalizeCidr, invalidMessage: t("apiTokenCidrInvalid"), limitMessage: t("apiTokenCidrLimit") });
$("api-token-cidrs").replaceChildren(cidrs);
$("api-tokens-form").hidden = false;
$("api-token-new").disabled = true;
$("api-token-comment").focus?.();
}
function example(id) {
$("api-token-example").textContent = `curl -H "Authorization: Bearer $RUSTPROXY_API_TOKEN" ${location.origin}/api/status`;
if (id) $("api-token-example").textContent += `\n\n# ${id}`;
}
function render() {
const list = $("api-token-list"); list.replaceChildren();
const tokens = state?.tokens || [], max = Number(state?.max_tokens) || 0;
$("api-token-status").textContent = tokens.length ? t("apiTokenCount").replace("{count}", tokens.length).replace("{max}", max || "-") : t("apiTokenEmpty");
$("api-token-new").disabled = !$("api-tokens-form").hidden || (max && tokens.length >= max);
for (const entry of tokens) {
const item = el("div", undefined, "certificate-api-credential-item"), row = el("div", undefined, "certificate-api-credential-row"), info = el("div", undefined, "certificate-api-credential-info");
const title = el("div", undefined, "certificate-api-credential-title");
title.append(el("b", entry.id, "mono"), el("span", entry.permission === "rw" ? "RW" : "RO", `pill ${entry.permission === "rw" ? "warn" : "live"}`));
if (entry.comment) title.append(el("span", entry.comment, "fine"));
const chips = el("div", undefined, "certificate-api-chips");
for (const cidr of entry.allowed_cidrs || []) chips.append(el("span", cidr, "certificate-api-chip"));
const created = entry.created_at ? formatDateTime(entry.created_at * 1000) : "-", used = entry.last_used_at ? formatDateTime(entry.last_used_at * 1000) : t("certificateApiNeverUsed");
info.append(title, chips, el("span", `${t("certificateApiCreatedAt")}: ${created} · ${t("certificateApiLastUsed")}: ${used}`, "fine"));
const actions = el("div", undefined, "certificate-api-row-actions");
const revoke = action(t("apiTokenRevoke"), async () => {
if (!(await appConfirm(t("apiTokenRevokeConfirm").replace("{id}", entry.id), { danger: true }))) return;
revoke.disabled = true;
try { await api(`/api/api-tokens/${encodeURIComponent(entry.id)}`, { method: "DELETE" }); hideSecret(); await refresh(true); toast(t("apiTokenRevoked")); }
catch (error) { toast(error.message, true); revoke.disabled = false; }
});
revoke.classList.add("danger"); actions.append(revoke);
row.append(info, actions); item.append(row); list.append(item);
}
example();
}
async function refresh() {
if (!authenticated || loading) return;
loading = true;
try { state = await api("/api/api-tokens"); render(); }
catch (error) { if (error.status !== 401) toast(error.message, true); }
finally { loading = false; }
}
$("api-token-new").addEventListener("click", openEditor);
$("api-token-cancel").addEventListener("click", () => { closeEditor(); render(); });
$("api-token-secret-copy").addEventListener("click", async () => {
try { await navigator.clipboard.writeText($("api-token-secret").textContent); toast(t("copied")); }
catch { const range = document.createRange(); range.selectNodeContents($("api-token-secret")); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); }
});
$("api-tokens-form").addEventListener("submit", async event => {
event.preventDefault(); if (!authenticated) return;
const button = event.submitter; if (button) button.disabled = true;
hideSecret();
try {
const allowed = cidrs?.read() || [];
if (!allowed.length) throw fieldError(cidrs, t("apiTokenCidrRequired"));
const permission = $("api-token-permission-rw").checked ? "rw" : "ro";
const result = await api("/api/api-tokens", { method: "POST", body: JSON.stringify({ permission, comment: $("api-token-comment").value.trim(), allowed_cidrs: allowed }) });
closeEditor();
await refresh();
$("api-token-secret").textContent = result.token;
$("api-token-secret-title").textContent = t("apiTokenSecretTitle").replace("{id}", result.id);
$("api-token-secret-wrap").hidden = false;
toast(t("apiTokenCreated"));
} catch (error) { showFieldError(error, $("api-tokens-form")); toast(error.message, true); }
finally { if (button) button.disabled = false; }
});
example();
return { refresh, hideSecret, reset() { state = null; hideSecret(); closeEditor(); $("api-token-list").replaceChildren(); } };
})();