One component, PageIntro, for the text under a page's title: shown as it is when it fits in two lines, otherwise folded with a Show more, remembered per page in this browser, opened by tabbing to a link in it, unfolded in print. Used on 41 pages. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
223 lines
9.2 KiB
TypeScript
223 lines
9.2 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import { api, type ApiToken } from "../api/client";
|
|
import CopyButton from "../components/CopyButton";
|
|
import { EmptyRow } from "../components/EmptyState";
|
|
import { ErrorNotice } from "../components/Notice";
|
|
import { BlockSkeleton } from "../components/Skeleton";
|
|
import TimeAgo from "../components/TimeAgo";
|
|
import { confirmDialog } from "../utils/dialogs";
|
|
import { formatDate } from "../utils/date";
|
|
import { readableError } from "../utils/errors";
|
|
import { toast } from "../utils/toast";
|
|
import PageIntro from "../components/PageIntro";
|
|
|
|
const EXPIRY = [
|
|
{ value: "90", label: "90 days" },
|
|
{ value: "30", label: "30 days" },
|
|
{ value: "365", label: "1 year" },
|
|
{ value: "", label: "No end — until I remove it" },
|
|
];
|
|
|
|
const READS = [
|
|
["/api/v1/servers", "every server: whether it is online, its addresses, load, memory, disks and waiting updates"],
|
|
["/api/v1/servers/:id/metrics?days=365", "a server's load, memory and disks, up to a year back"],
|
|
["/api/v1/alerts", "what is wrong now, and whether somebody is on it"],
|
|
["/api/v1/incidents?status=open", "the record of alerts that began and ended"],
|
|
["/api/v1/inventory", "the hardware"],
|
|
["/api/v1/network", "switches, access points and gateways, networks and Wi-Fi names"],
|
|
["/api/v1/endpoints", "the checks, and /endpoints/:id/history for how one has done"],
|
|
["/api/v1/maintenance", "what is under maintenance now, and what is coming"],
|
|
];
|
|
|
|
/**
|
|
* A person's own read-only tokens for the API (/api/v1): a script, Home Assistant or a dashboard sends one in a header and gets JSON back. A token can only read, sees
|
|
* what its owner sees, and is gone when its owner is. The secret is shown once, here, when it is made.
|
|
*/
|
|
export default function ApiTokens() {
|
|
const [tokens, setTokens] = useState<ApiToken[] | null>(null);
|
|
const [max, setMax] = useState(10);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [label, setLabel] = useState("");
|
|
const [expiry, setExpiry] = useState("90");
|
|
const [busy, setBusy] = useState(false);
|
|
const [fresh, setFresh] = useState<{ label: string; secret: string } | null>(null);
|
|
|
|
function load() {
|
|
api.apiTokens
|
|
.list()
|
|
.then((res) => {
|
|
setTokens(res.tokens);
|
|
setMax(res.max);
|
|
})
|
|
.catch((err) => setError(readableError(err)));
|
|
}
|
|
useEffect(load, []);
|
|
|
|
async function make(e: React.FormEvent) {
|
|
e.preventDefault();
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
const res = await api.apiTokens.create({ label: label.trim(), expiresInDays: expiry === "" ? null : Number(expiry) });
|
|
setFresh({ label: res.token.label, secret: res.secret });
|
|
setLabel("");
|
|
load();
|
|
} catch (err) {
|
|
setError(readableError(err));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
async function remove(t: ApiToken) {
|
|
// Not undoable: the secret is not kept, so a token cannot be made again the same.
|
|
if (!(await confirmDialog({ title: "Remove a token", message: `Remove "${t.label}"? Whatever uses it stops working at once, and it cannot be put back.`, confirmLabel: "Remove", danger: true }))) return;
|
|
try {
|
|
await api.apiTokens.remove(t.id);
|
|
toast.success(`Removed "${t.label}".`);
|
|
load();
|
|
} catch (err) {
|
|
toast.error(readableError(err));
|
|
}
|
|
}
|
|
|
|
const origin = window.location.origin;
|
|
|
|
return (
|
|
<>
|
|
<div className="d-flex align-items-center mb-1">
|
|
<h2 className="page-title mb-0">API tokens</h2>
|
|
</div>
|
|
<PageIntro>
|
|
Read-only access to your installation’s data for scripts, Home Assistant and dashboards. A token can only read, sees what you see, and stops working when you are removed. Make one for each thing that reads, so each can be removed on its own.
|
|
</PageIntro>
|
|
<ErrorNotice error={error} />
|
|
|
|
{fresh && (
|
|
<div className="alert alert-success" role="status">
|
|
<div className="w-100">
|
|
<div className="fw-bold mb-1">Your token “{fresh.label}” — copy it now, it is not shown again</div>
|
|
<div className="d-flex flex-wrap align-items-center gap-2 mb-2">
|
|
<code className="text-break">{fresh.secret}</code>
|
|
<CopyButton text={fresh.secret} />
|
|
</div>
|
|
<div className="small">Send it in a header, never in the address:</div>
|
|
<pre className="mb-2 mt-1 small">{`curl -H "Authorization: Bearer ${fresh.secret}" ${origin}/api/v1/alerts`}</pre>
|
|
<button type="button" className="btn btn-sm" onClick={() => setFresh(null)}>
|
|
I have copied it
|
|
</button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<form className="card mb-3" onSubmit={make}>
|
|
<div className="card-header">
|
|
<h3 className="card-title">Make a token</h3>
|
|
</div>
|
|
<div className="card-body row g-3 align-items-end">
|
|
<div className="col-md-5">
|
|
<label className="form-label" htmlFor="tok-label">
|
|
What it is for
|
|
</label>
|
|
<input id="tok-label" className="form-control" maxLength={60} required placeholder="e.g. Home Assistant" value={label} onChange={(e) => setLabel(e.target.value)} />
|
|
</div>
|
|
<div className="col-md-4">
|
|
<label className="form-label" htmlFor="tok-exp">
|
|
Works for
|
|
</label>
|
|
<select id="tok-exp" className="form-select" value={expiry} onChange={(e) => setExpiry(e.target.value)}>
|
|
{EXPIRY.map((o) => (
|
|
<option key={o.value} value={o.value}>
|
|
{o.label}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
<div className="col-md-3">
|
|
<button type="submit" className="btn btn-primary w-100" disabled={busy || label.trim() === "" || (tokens?.length ?? 0) >= max}>
|
|
{busy ? "Making…" : "Make the token"}
|
|
</button>
|
|
</div>
|
|
{(tokens?.length ?? 0) >= max && <div className="col-12 text-secondary small">You have {max} tokens, the most there can be. Remove one you do not use.</div>}
|
|
</div>
|
|
</form>
|
|
|
|
<div className="card mb-3">
|
|
<div className="card-header">
|
|
<h3 className="card-title">Your tokens</h3>
|
|
</div>
|
|
<div className="table-responsive">
|
|
<table className="table table-vcenter card-table table-stack">
|
|
<thead>
|
|
<tr>
|
|
<th>Name</th>
|
|
<th>Starts with</th>
|
|
<th>Made</th>
|
|
<th>Last used</th>
|
|
<th>Ends</th>
|
|
<th className="w-1">
|
|
<span className="visually-hidden">Actions</span>
|
|
</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{tokens === null && !error && (
|
|
<tr>
|
|
<td colSpan={6}>
|
|
<BlockSkeleton lines={2} />
|
|
</td>
|
|
</tr>
|
|
)}
|
|
{tokens?.map((t) => (
|
|
<tr key={t.id}>
|
|
<td className="stack-wide">
|
|
<strong>{t.label}</strong>
|
|
{t.expired && <span className="badge bg-red-lt text-red ms-2">expired</span>}
|
|
</td>
|
|
<td className="stack-label font-monospace" data-label="Starts with">
|
|
{t.tokenPrefix}…
|
|
</td>
|
|
<td className="stack-label" data-label="Made">
|
|
<TimeAgo value={t.createdAt} fromDb />
|
|
</td>
|
|
<td className="stack-label" data-label="Last used">
|
|
{t.lastUsedAt ? <TimeAgo value={t.lastUsedAt} /> : <span className="text-secondary">never</span>}
|
|
</td>
|
|
<td className="stack-label" data-label="Ends">
|
|
{t.expiresAt ? formatDate(new Date(t.expiresAt)) : <span className="text-secondary">no end</span>}
|
|
</td>
|
|
<td className="stack-wide">
|
|
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(t)}>
|
|
Remove
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
))}
|
|
{tokens !== null && tokens.length === 0 && <EmptyRow colSpan={6} title="No tokens yet" hint="Make one above, and copy it when it is shown: that is the only time it is." />}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="card">
|
|
<div className="card-header">
|
|
<h3 className="card-title">What it can read</h3>
|
|
</div>
|
|
<div className="card-body">
|
|
<p className="text-secondary">
|
|
Everything is a <code>GET</code> that answers JSON, under <code>{origin}/api/v1</code>, with the token as <code>Authorization: Bearer …</code>. Nothing can be changed through it. Dates are ISO 8601 in UTC and sizes are in bytes.
|
|
</p>
|
|
<ul className="mb-2">
|
|
{READS.map(([path, what]) => (
|
|
<li key={path}>
|
|
<code>{path}</code> — {what}
|
|
</li>
|
|
))}
|
|
</ul>
|
|
<div className="text-secondary small">The full list, with an example of each answer, is in docs/API.md.</div>
|
|
</div>
|
|
</div>
|
|
</>
|
|
);
|
|
}
|