| 1 | /* 个人访问令牌页(docs/decisions/0014,0016 的 A2)。 |
| 2 | 令牌属于人、以人的身份行事:有效权限 = 角色 ∩ scope,`kb_ids` 只收窄不授权。 |
| 3 | 服务端三个端点早就在(发放 / 列表 / 撤销),缺的只是这一页——没有它, |
| 4 | MCP 对用户就是「有 API、配不了」。 |
| 5 | 明文只在发放那一次的响应里出现,所以这一页的重心是那一刻:把令牌和一段可复制的 |
| 6 | 客户端配置一起端出来,人复制完点「完成」,之后列表里只剩前缀。 */ |
| 7 | import { useMemo, useState } from "react"; |
| 8 | import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; |
| 9 | import { Check, Copy, KeyRound } from "lucide-react"; |
| 10 | import { api, type TokenView } from "../api"; |
| 11 | import { S } from "../i18n"; |
| 12 | import { useKb } from "../kb"; |
| 13 | import { Chip, Loading } from "../ui"; |
| 14 | import { toast } from "../toast"; |
| 15 | |
| 16 | const ymd = (iso: string) => iso.slice(0, 10); |
| 17 | const EXPIRY_CHOICES = [30, 90, 365, 0] as const; |
| 18 | |
| 19 | function copyText(text: string) { |
| 20 | navigator.clipboard |
| 21 | ?.writeText(text) |
| 22 | .then(() => toast.success(S.account.copied)) |
| 23 | .catch(() => {}); |
| 24 | } |
| 25 | |
| 26 | /** Claude Code / Claude Desktop 一族的 Streamable HTTP 写法。每个库一个端点(0014: |
| 27 | * 令牌限定到库,端点也按库分),所以片段里要把库选出来 */ |
| 28 | function mcpSnippet(kbId: string, kbName: string, token: string): string { |
| 29 | const slug = kbName |
| 30 | .toLowerCase() |
| 31 | .replace(/[^a-z0-9]+/g, "-") |
| 32 | .replace(/^-+|-+$/g, "") || "kb"; |
| 33 | const cfg = { |
| 34 | mcpServers: { |
| 35 | [`utopia-${slug}`]: { |
| 36 | type: "http", |
| 37 | url: `${window.location.origin}/api/v1/kbs/${kbId}/mcp`, |
| 38 | headers: { Authorization: `Bearer ${token}` }, |
| 39 | }, |
| 40 | }, |
| 41 | }; |
| 42 | return JSON.stringify(cfg, null, 2); |
| 43 | } |
| 44 | |
| 45 | function CopyButton({ text, small }: { text: string; small?: boolean }) { |
| 46 | const [done, setDone] = useState(false); |
| 47 | return ( |
| 48 | <button |
| 49 | className={`u-btn u-btn-ghost ${small ? "px-2 py-1 text-[11px]" : "px-3 py-1.5 text-xs"} flex items-center gap-1.5`} |
| 50 | onClick={() => { |
| 51 | copyText(text); |
| 52 | setDone(true); |
| 53 | setTimeout(() => setDone(false), 1500); |
| 54 | }} |
| 55 | > |
| 56 | {done ? <Check size={12} /> : <Copy size={12} />} |
| 57 | {done ? S.account.copied : S.account.copy} |
| 58 | </button> |
| 59 | ); |
| 60 | } |
| 61 | |
| 62 | /** 刚发出来的那一枚:明文 + 配置片段,关掉就再也看不到 */ |
| 63 | function IssuedPanel({ |
| 64 | token, |
| 65 | info, |
| 66 | kbs, |
| 67 | onDone, |
| 68 | }: { |
| 69 | token: string; |
| 70 | info: TokenView; |
| 71 | kbs: { id: string; name: string }[]; |
| 72 | onDone: () => void; |
| 73 | }) { |
| 74 | // 片段默认指向令牌限定的第一个库;没限定就取列表第一个 |
| 75 | const candidates = info.kb_ids?.length |
| 76 | ? kbs.filter((k) => info.kb_ids!.includes(k.id)) |
| 77 | : kbs; |
| 78 | const [kbId, setKbId] = useState(candidates[0]?.id ?? kbs[0]?.id ?? ""); |
| 79 | const kb = kbs.find((k) => k.id === kbId); |
| 80 | const snippet = kb ? mcpSnippet(kb.id, kb.name, token) : ""; |
| 81 | return ( |
| 82 | <div className="glass rounded-2xl p-5 mb-4 border border-[var(--u-warn)]/40"> |
| 83 | <div className="text-[13px] font-medium text-neutral-100">{S.account.issuedTitle}</div> |
| 84 | <p className="mt-1 text-xs text-neutral-500">{S.account.issuedHint}</p> |
| 85 | <div className="mt-3 flex items-center gap-2"> |
| 86 | <code className="flex-1 min-w-0 truncate rounded-lg bg-black/40 px-3 py-2 font-mono text-[12px] text-neutral-200"> |
| 87 | {token} |
| 88 | </code> |
| 89 | <CopyButton text={token} /> |
| 90 | </div> |
| 91 | |
| 92 | <div className="mt-5 flex items-baseline justify-between gap-3 flex-wrap"> |
| 93 | <div className="text-[13px] font-medium text-neutral-200">{S.account.mcpTitle}</div> |
| 94 | {candidates.length > 1 && ( |
| 95 | <label className="flex items-center gap-2 text-xs text-neutral-500"> |
| 96 | {S.account.mcpBase} |
| 97 | <select |
| 98 | className="input-dark px-2 py-1 text-xs" |
| 99 | value={kbId} |
| 100 | onChange={(e) => setKbId(e.target.value)} |
| 101 | > |
| 102 | {candidates.map((k) => ( |
| 103 | <option key={k.id} value={k.id}> |
| 104 | {k.name} |
| 105 | </option> |
| 106 | ))} |
| 107 | </select> |
| 108 | </label> |
| 109 | )} |
| 110 | </div> |
| 111 | <p className="mt-1 text-xs text-neutral-500">{S.account.mcpHint}</p> |
| 112 | <div className="mt-2 relative"> |
| 113 | <pre className="rounded-lg bg-black/40 px-3 py-2 font-mono text-[11.5px] text-neutral-300 overflow-x-auto u-scroll"> |
| 114 | {snippet} |
| 115 | </pre> |
| 116 | <div className="absolute top-1.5 right-1.5"> |
| 117 | <CopyButton text={snippet} small /> |
| 118 | </div> |
| 119 | </div> |
| 120 | |
| 121 | <div className="mt-4 flex justify-end"> |
| 122 | <button className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" onClick={onDone}> |
| 123 | {S.account.tokenDone} |
| 124 | </button> |
| 125 | </div> |
| 126 | </div> |
| 127 | ); |
| 128 | } |
| 129 | |
| 130 | function TokenRow({ |
| 131 | t, |
| 132 | kbName, |
| 133 | busy, |
| 134 | onRevoke, |
| 135 | }: { |
| 136 | t: TokenView; |
| 137 | kbName: (id: string) => string; |
| 138 | busy: boolean; |
| 139 | onRevoke: () => void; |
| 140 | }) { |
| 141 | // 撤销不可撤回,但代价只是重发一枚——轻确认(二次点击),不做打字解锁 |
| 142 | const [arm, setArm] = useState(false); |
| 143 | const revoked = !!t.revoked_at; |
| 144 | const bases = t.kb_ids?.length |
| 145 | ? t.kb_ids.map(kbName).join(" · ") |
| 146 | : S.account.allBases; |
| 147 | return ( |
| 148 | <div className={`glass rounded-xl px-4 py-3 ${revoked ? "opacity-55" : ""}`}> |
| 149 | <div className="flex items-center gap-2 flex-wrap"> |
| 150 | <KeyRound size={13} className="text-neutral-500 shrink-0" /> |
| 151 | <span className="text-sm font-medium text-neutral-100">{t.name}</span> |
| 152 | <code className="font-mono text-[11px] text-neutral-500">{t.token_prefix}…</code> |
| 153 | <Chip tone={t.scope === "write" ? "warn" : "neutral"}> |
| 154 | {t.scope === "write" ? S.account.scopeWrite : S.account.scopeRead} |
| 155 | </Chip> |
| 156 | {revoked && <Chip tone="danger">{S.account.revokedOn(ymd(t.revoked_at!))}</Chip>} |
| 157 | {!revoked && ( |
| 158 | <div className="ml-auto flex gap-2"> |
| 159 | {arm ? ( |
| 160 | <button |
| 161 | className="u-btn u-btn-ghost px-3 py-1.5 text-xs text-[var(--u-danger)]" |
| 162 | disabled={busy} |
| 163 | onClick={onRevoke} |
| 164 | onBlur={() => setArm(false)} |
| 165 | > |
| 166 | {S.account.revokeConfirm} |
| 167 | </button> |
| 168 | ) : ( |
| 169 | <button |
| 170 | className="u-btn u-btn-ghost px-3 py-1.5 text-xs" |
| 171 | disabled={busy} |
| 172 | onClick={() => setArm(true)} |
| 173 | > |
| 174 | {S.account.revoke} |
| 175 | </button> |
| 176 | )} |
| 177 | </div> |
| 178 | )} |
| 179 | </div> |
| 180 | <div className="mt-1.5 text-[11.5px] text-neutral-500 flex gap-x-3 gap-y-0.5 flex-wrap u-num"> |
| 181 | <span title={t.kb_ids?.length ? bases : undefined}> |
| 182 | {t.kb_ids?.length ? S.account.nBases(t.kb_ids.length) : S.account.allBases} |
| 183 | </span> |
| 184 | <span>·</span> |
| 185 | <span> |
| 186 | {t.last_used_at ? S.account.lastUsed(ymd(t.last_used_at)) : S.account.neverUsed} |
| 187 | </span> |
| 188 | <span>·</span> |
| 189 | <span>{t.expires_at ? S.account.expiresOn(ymd(t.expires_at)) : S.account.noExpiry}</span> |
| 190 | <span>·</span> |
| 191 | <span>{S.account.createdOn(ymd(t.created_at))}</span> |
| 192 | </div> |
| 193 | </div> |
| 194 | ); |
| 195 | } |
| 196 | |
| 197 | export function Tokens() { |
| 198 | const queryClient = useQueryClient(); |
| 199 | const { kbs } = useKb(); |
| 200 | const list = useQuery({ queryKey: ["tokens"], queryFn: api.tokens }); |
| 201 | |
| 202 | const [name, setName] = useState(""); |
| 203 | const [scope, setScope] = useState<"read" | "write">("read"); |
| 204 | const [picked, setPicked] = useState<Set<string>>(new Set()); |
| 205 | const [days, setDays] = useState<number>(90); |
| 206 | const [issued, setIssued] = useState<{ token: string; info: TokenView } | null>(null); |
| 207 | |
| 208 | const issue = useMutation({ |
| 209 | mutationFn: () => |
| 210 | api.issueToken({ |
| 211 | name: name.trim(), |
| 212 | scope, |
| 213 | kb_ids: picked.size ? Array.from(picked) : null, |
| 214 | expires_in_days: days, |
| 215 | }), |
| 216 | onSuccess: (res) => { |
| 217 | setIssued(res); |
| 218 | setName(""); |
| 219 | setPicked(new Set()); |
| 220 | queryClient.invalidateQueries({ queryKey: ["tokens"] }); |
| 221 | }, |
| 222 | onError: (e) => toast.error((e as Error).message), |
| 223 | }); |
| 224 | const revoke = useMutation({ |
| 225 | mutationFn: (id: string) => api.revokeToken(id), |
| 226 | onSettled: () => queryClient.invalidateQueries({ queryKey: ["tokens"] }), |
| 227 | onError: (e) => toast.error((e as Error).message), |
| 228 | }); |
| 229 | |
| 230 | const kbName = useMemo(() => { |
| 231 | const m = new Map(kbs.map((k) => [k.id, k.name])); |
| 232 | return (id: string) => m.get(id) ?? id.slice(0, 8); |
| 233 | }, [kbs]); |
| 234 | |
| 235 | if (list.isPending) return <Loading>{S.nav.loading}</Loading>; |
| 236 | // 活的在前、按新到旧;撤销过的沉底但仍然列着——撤过这件事本身要看得见 |
| 237 | const rows = [...(list.data?.tokens ?? [])].sort((a, b) => { |
| 238 | if (!!a.revoked_at !== !!b.revoked_at) return a.revoked_at ? 1 : -1; |
| 239 | return b.created_at.localeCompare(a.created_at); |
| 240 | }); |
| 241 | |
| 242 | const field = (label: string, node: React.ReactNode, hint?: string) => ( |
| 243 | <div className="mb-4"> |
| 244 | <div className="mb-1 text-[11px] font-medium text-neutral-500">{label}</div> |
| 245 | {node} |
| 246 | {hint && <p className="mt-1 text-[11px] text-neutral-600">{hint}</p>} |
| 247 | </div> |
| 248 | ); |
| 249 | |
| 250 | return ( |
| 251 | <div className="max-w-2xl p-8"> |
| 252 | <h1 className="u-title text-lg">{S.account.tokensTitle}</h1> |
| 253 | <p className="mt-1 mb-6 text-xs text-neutral-500 max-w-lg">{S.account.tokensHint}</p> |
| 254 | |
| 255 | {issued && ( |
| 256 | <IssuedPanel |
| 257 | token={issued.token} |
| 258 | info={issued.info} |
| 259 | kbs={kbs} |
| 260 | onDone={() => setIssued(null)} |
| 261 | /> |
| 262 | )} |
| 263 | |
| 264 | <div className="glass rounded-2xl p-5 mb-6"> |
| 265 | <h2 className="text-[13px] font-medium text-neutral-200 mb-4">{S.account.newToken}</h2> |
| 266 | {field( |
| 267 | S.account.tokenName, |
| 268 | <input |
| 269 | className="input-dark w-full px-3 py-2 text-sm" |
| 270 | placeholder={S.account.tokenNamePlaceholder} |
| 271 | value={name} |
| 272 | maxLength={64} |
| 273 | onChange={(e) => setName(e.target.value)} |
| 274 | />, |
| 275 | )} |
| 276 | {field( |
| 277 | S.account.tokenScope, |
| 278 | <div className="flex gap-2"> |
| 279 | {(["read", "write"] as const).map((s) => ( |
| 280 | <button |
| 281 | key={s} |
| 282 | className={`u-btn px-3 py-1.5 text-xs ${scope === s ? "u-btn-primary" : "u-btn-ghost"}`} |
| 283 | onClick={() => setScope(s)} |
| 284 | > |
| 285 | {s === "read" ? S.account.scopeRead : S.account.scopeWrite} |
| 286 | </button> |
| 287 | ))} |
| 288 | </div>, |
| 289 | S.account.scopeHint, |
| 290 | )} |
| 291 | {field( |
| 292 | S.account.tokenKbs, |
| 293 | <div className="flex gap-2 flex-wrap"> |
| 294 | {kbs.map((k) => { |
| 295 | const on = picked.has(k.id); |
| 296 | return ( |
| 297 | <button |
| 298 | key={k.id} |
| 299 | className={`u-btn px-2.5 py-1 text-xs ${on ? "u-btn-primary" : "u-btn-ghost"}`} |
| 300 | onClick={() => { |
| 301 | const next = new Set(picked); |
| 302 | if (on) next.delete(k.id); |
| 303 | else next.add(k.id); |
| 304 | setPicked(next); |
| 305 | }} |
| 306 | > |
| 307 | {k.name} |
| 308 | </button> |
| 309 | ); |
| 310 | })} |
| 311 | </div>, |
| 312 | S.account.kbsAllHint, |
| 313 | )} |
| 314 | {field( |
| 315 | S.account.tokenExpires, |
| 316 | <div className="flex gap-2"> |
| 317 | {EXPIRY_CHOICES.map((d) => ( |
| 318 | <button |
| 319 | key={d} |
| 320 | className={`u-btn px-2.5 py-1 text-xs u-num ${days === d ? "u-btn-primary" : "u-btn-ghost"}`} |
| 321 | onClick={() => setDays(d)} |
| 322 | > |
| 323 | {d === 0 ? S.account.expiresNever : S.account.expiresDays(d)} |
| 324 | </button> |
| 325 | ))} |
| 326 | </div>, |
| 327 | )} |
| 328 | <div className="flex justify-end"> |
| 329 | <button |
| 330 | className="u-btn u-btn-primary px-3.5 py-1.5 text-xs" |
| 331 | disabled={!name.trim() || issue.isPending} |
| 332 | onClick={() => issue.mutate()} |
| 333 | > |
| 334 | {S.account.issueToken} |
| 335 | </button> |
| 336 | </div> |
| 337 | </div> |
| 338 | |
| 339 | <h2 className="text-[13px] font-medium text-neutral-200 mb-3">{S.account.yourTokens}</h2> |
| 340 | {rows.length === 0 ? ( |
| 341 | <div className="glass rounded-xl p-8 text-center text-sm text-neutral-500"> |
| 342 | {S.account.noTokens} |
| 343 | </div> |
| 344 | ) : ( |
| 345 | <div className="space-y-2"> |
| 346 | {rows.map((t) => ( |
| 347 | <TokenRow |
| 348 | key={t.id} |
| 349 | t={t} |
| 350 | kbName={kbName} |
| 351 | busy={revoke.isPending && revoke.variables === t.id} |
| 352 | onRevoke={() => revoke.mutate(t.id)} |
| 353 | /> |
| 354 | ))} |
| 355 | </div> |
| 356 | )} |
| 357 | </div> |
| 358 | ); |
| 359 | } |