Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
"use client";
import { useState, useEffect, useCallback } from "react";
import { Card, Button, Input, Select, Badge, Spinner, ConfirmModal } from "@/shared/components";
import { useFormatter, useTranslations } from "next-intl";
interface AccessTokenRow {
id: string;
name: string;
scope: "read" | "write" | "admin";
tokenPrefix: string;
createdAt: string;
lastUsedAt: string | null;
expiresAt: string | null;
revokedAt: string | null;
}
const SCOPE_VARIANT: Record<string, "info" | "warning" | "error" | "default"> = {
read: "info",
write: "warning",
admin: "error",
};
async function fetchTokens(): Promise<AccessTokenRow[]> {
const res = await fetch("/api/cli/tokens");
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return Array.isArray(data.tokens) ? data.tokens : [];
}
export default function AccessTokensTab() {
const t = useTranslations("settings");
const format = useFormatter();
const scopeLabels = {
read: t("accessTokensScopeReadLabel"),
write: t("accessTokensScopeWriteLabel"),
admin: t("accessTokensScopeAdminLabel"),
};
const [tokens, setTokens] = useState<AccessTokenRow[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [name, setName] = useState("");
const [scope, setScope] = useState("read");
const [expires, setExpires] = useState("");
const [creating, setCreating] = useState(false);
const [newSecret, setNewSecret] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [revokeTarget, setRevokeTarget] = useState<AccessTokenRow | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError("");
try {
setTokens(await fetchTokens());
} catch {
setError(t("accessTokensLoadError"));
} finally {
setLoading(false);
}
}, [t]);
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const tokens = await fetchTokens();
if (!cancelled) setTokens(tokens);
} catch {
if (!cancelled) setError(t("accessTokensLoadError"));
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [t]);
const createToken = async () => {
if (!name.trim()) return;
setCreating(true);
setError("");
try {
const body: Record<string, unknown> = { name: name.trim(), scope };
const days = Number(expires);
if (expires && Number.isFinite(days) && days > 0) body.expiresInDays = days;
const res = await fetch("/api/cli/tokens", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
// API diagnostics are server data; localize the UI context, not the diagnostic.
const detail = data?.error?.message || data?.error;
setError(
`${t("accessTokensCreateError")} ${typeof detail === "string" ? detail : `HTTP ${res.status}`}`
);
return;
}
setNewSecret(data.token);
setCopied(false);
setName("");
setExpires("");
setScope("read");
await load();
} catch {
setError(t("accessTokensCreateError"));
} finally {
setCreating(false);
}
};
const confirmRevoke = async () => {
if (!revokeTarget) return;
const target = revokeTarget;
setRevokeTarget(null);
try {
const res = await fetch(`/api/cli/tokens/${encodeURIComponent(target.id)}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
await load();
} catch {
setError(t("accessTokensRevokeError"));
}
};
const copySecret = async () => {
if (!newSecret) return;
try {
await navigator.clipboard.writeText(newSecret);
setCopied(true);
} catch {
/* clipboard unavailable — user can select manually */
}
};
const fmt = (iso: string | null) => {
if (!iso) return "—";
const date = new Date(iso);
return Number.isNaN(date.getTime())
? "—"
: format.dateTime(date, { dateStyle: "medium", timeStyle: "short" });
};
return (
<div className="space-y-6">
<Card>
<div className="p-5">
<h2 className="text-lg font-semibold text-text">{t("accessTokensTitle")}</h2>
<p className="mt-1 text-sm text-text-muted">{t("accessTokensDescription")}</p>
</div>
</Card>
{/* Create */}
<Card>
<div className="p-5 space-y-4">
<h3 className="text-sm font-semibold text-text">{t("accessTokensCreateHeading")}</h3>
<div className="grid gap-3 sm:grid-cols-4">
<Input
aria-label={t("accessTokensColName")}
placeholder={t("accessTokensNamePlaceholder")}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<Select
aria-label={t("accessTokensColScope")}
value={scope}
onChange={(e) => setScope(e.target.value)}
options={[
{ value: "read", label: t("accessTokensScopeRead") },
{ value: "write", label: t("accessTokensScopeWrite") },
{ value: "admin", label: t("accessTokensScopeAdmin") },
]}
/>
<Input
type="number"
min={1}
aria-label={t("accessTokensExpiresPlaceholder")}
placeholder={t("accessTokensExpiresPlaceholder")}
value={expires}
onChange={(e) => setExpires(e.target.value)}
/>
<Button onClick={createToken} disabled={creating || !name.trim()}>
{creating ? t("accessTokensCreating") : t("accessTokensCreate")}
</Button>
</div>
{newSecret && (
<div className="rounded-control border border-primary/40 bg-primary/5 p-4">
<p className="text-sm font-medium text-text">{t("accessTokensCopyNow")}</p>
<div className="mt-2 flex items-center gap-2">
<code className="flex-1 break-all rounded bg-surface px-3 py-2 font-mono text-xs text-text">
{newSecret}
</code>
<Button variant="secondary" onClick={copySecret}>
{copied ? t("accessTokensCopied") : t("accessTokensCopy")}
</Button>
<Button variant="ghost" onClick={() => setNewSecret(null)}>
{t("accessTokensDismiss")}
</Button>
</div>
</div>
)}
</div>
</Card>
{error && (
<div className="rounded-control border border-red-500/40 bg-red-500/5 px-4 py-3 text-sm text-red-400">
{error}
</div>
)}
{/* List */}
<Card>
<div className="p-5">
<h3 className="mb-3 text-sm font-semibold text-text">{t("accessTokensExisting")}</h3>
{loading ? (
<div className="flex justify-center py-8">
<Spinner />
</div>
) : tokens.length === 0 ? (
<p className="py-6 text-center text-sm text-text-muted">{t("accessTokensEmpty")}</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-border text-start text-text-muted">
<th className="py-2 pe-4 font-medium">{t("accessTokensColName")}</th>
<th className="py-2 pe-4 font-medium">{t("accessTokensColScope")}</th>
<th className="py-2 pe-4 font-medium">{t("accessTokensColPrefix")}</th>
<th className="py-2 pe-4 font-medium">{t("accessTokensColStatus")}</th>
<th className="py-2 pe-4 font-medium">{t("accessTokensColLastUsed")}</th>
<th className="py-2 pe-4 font-medium">{t("accessTokensColExpires")}</th>
<th className="py-2 font-medium" />
</tr>
</thead>
<tbody>
{tokens.map((tk) => {
const revoked = Boolean(tk.revokedAt);
return (
<tr key={tk.id} className="border-b border-border/50">
<td className="py-2 pe-4 text-text">{tk.name}</td>
<td className="py-2 pe-4">
<Badge variant={SCOPE_VARIANT[tk.scope] || "default"}>
{scopeLabels[tk.scope] || tk.scope}
</Badge>
</td>
<td className="py-2 pe-4 font-mono text-xs text-text-muted">
{tk.tokenPrefix}
</td>
<td className="py-2 pe-4">
<Badge variant={revoked ? "default" : "success"}>
{revoked
? t("accessTokensStatusRevoked")
: t("accessTokensStatusActive")}
</Badge>
</td>
<td className="py-2 pe-4 text-text-muted">{fmt(tk.lastUsedAt)}</td>
<td className="py-2 pe-4 text-text-muted">{fmt(tk.expiresAt)}</td>
<td className="py-2 text-end">
{!revoked && (
<Button variant="ghost" size="sm" onClick={() => setRevokeTarget(tk)}>
{t("accessTokensRevoke")}
</Button>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</div>
</Card>
<ConfirmModal
isOpen={Boolean(revokeTarget)}
onClose={() => setRevokeTarget(null)}
onConfirm={confirmRevoke}
title={t("accessTokensRevokeTitle")}
message={t("accessTokensRevokeConfirm")}
confirmText={t("accessTokensRevoke")}
variant="danger"
/>
</div>
);
}