Files
PaperClipAI/ui/src/pages/apps/gateways/panels/TokensPanel.tsx
T
DottaandClaude Opus 5.5 353945c86d fix(tool-gateway): let agents create gateway tokens without receiving the value (#20613)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Tool gateways let external MCP clients use a company's tools with a
gateway client token
> - Since delegated connection management (#17737), an agent can create
and revoke gateway client tokens for its responsible person
> - #20581 stopped agents from getting the one-time token value, but it
did this by making token creation person-only
> - The product decision is that agents keep their delegated authority
to create and revoke tokens
> - This pull request restores agent token creation, but the agent never
receives the token value: the person reveals the value once on the
gateway's Tokens page
> - The benefit is that an agent can do the rotation work for the
person, and the secret still never enters chat, run events, logs or tool
output

## Linked Issues or Issue Description

Refs #17737
Refs #20581

**What happened**
After #20581, `POST /api/tool-gateway/gateways/{gatewayId}/tokens`
returns 403 `gateway_token_requires_person` to every agent caller.
Agents lost the delegated authority to create gateway client tokens that
#17737 gave them. Before #20581, an agent that created a token received
the plaintext value in its tool result and could repeat it in chat.

**Expected behavior**
An agent with delegated connection management can create and revoke
gateway client tokens. The agent never receives a token value. The
responsible person gets the value once, on the gateway's Tokens page.
Person callers keep today's behavior.

**Steps to reproduce**
1. Give an agent delegated connection management for a responsible
person with `tools:admin`.
2. As the agent, call `POST
/api/tool-gateway/gateways/{gatewayId}/tokens` (for example through
`call_api`).
3. See 403 `gateway_token_requires_person`.

## What Changed

- Agent create: `POST /api/tool-gateway/gateways/:gatewayId/tokens` from
an agent with delegated authority returns 201 with token metadata only
(`id`, `tokenPrefix`, `expiresAt`, `pendingReveal: true`), plus
`tokensPath`, a `reveal_credential` `requiredUserAction` for the
responsible person, and a `nextStep` instruction. The saved row has no
usable value: its stored hash is of a value that is generated and then
discarded. Gateway authentication also rejects `pendingReveal` rows.
- Person reveal: new person-only `POST
/api/tool-gateway/gateway-tokens/:tokenId/reveal`. It generates the
value, stores its hash, clears `pendingReveal` and returns the value
once. A conditional update makes a second or concurrent reveal return
409. Only the token's responsible person can reveal it (403
`gateway_token_reveal_requires_responsible_person`). Agent callers get
403 `gateway_token_requires_person`. A token revoked before reveal
cannot be revealed.
- Why a reveal that generates the value: no stored plaintext existed to
reveal, and storing one (even encrypted) for later display adds a secret
at rest. Generating the value at reveal time keeps the existing one-time
display and stores only a hash.
- Schema: `tool_mcp_gateway_tokens.pending_reveal boolean not null
default false` (migration `0460_gateway_token_pending_reveal`). Shared
`ToolMcpGatewayToken.pendingReveal`, and `ConnectionRequiredUserAction`
gets `reveal_credential` / `gateway_token`.
- UI: the Tokens page shows a "Waiting for you to reveal" section for
pending tokens with a "Reveal token" button. The value appears in the
existing "New token — copy now" one-time block. Pending tokens show the
status "Not revealed".
- Agent gateway create: the 201 for agent callers also includes
`gatewayPath`, `tokensPath` and a `nextStep` that tells the agent to
link the saved gateway.
- The agent create-token `nextStep` and the catalog say not to revoke
the old token in the same turn: its client keeps working on it until the
person installs the new value.
- The reveal update and its `tool_gateway.token_revealed` activity entry
commit in one transaction. The Tokens page offers Reveal only for tokens
that act for the signed-in person.
- API reference: new `docs/api/tool-gateway-tokens.md` (create, reveal,
revoke) in the docs nav.
- Revoke stays allowed for agents with delegated authority (unchanged
route).
- API catalog: create-gateway, create-token, reveal and revoke
descriptions now say who acts, that agents never receive values, the
page paths, and that the old token is revoked only after the client
works with the new one.
- Agent access map: create-token policy note and a new reveal entry.
- Evals `gateways-profiles.create-gateway` and
`gateways-profiles.rotate-token`:
- Remove the keyword grader (`human|operator|admin|manage`) and the
handoff text checks. Grade saved state, rendered links and secret
absence. A plain reply or a question card is accepted.
- Remove the setup probes that called the create routes as the agent.
Under delegated authority, those probes created a real gateway
("Forbidden agent gateway"), which failed create-gateway before the
agent ran.
- create-gateway: exactly one gateway for the intended profile and
company, created by the agent (or by the person after a handoff); the
person opens it from a rendered link; attribution matches the creator;
any agent-created token is still pending reveal; no token value in chat,
cards or run events.
- rotate-token: after the agent's turn, both setup tokens still work and
any replacement the agent created is pending the person's reveal; the
person follows the rendered Tokens page link and reveals (or issues) the
value in a private browser; the new value works before the old token is
revoked; the unrelated client keeps access; no token value appears
anywhere, including a regex scan for any full `pcgw_<id>.<secret>`
value.
- The changed scenario context and outcomes are recorded in
`chat-full-catalog-testops-manifest.json` `changedFields` and pinned in
the manifest test. The inventory digest, descriptors (`oracleVersion`
v2, `sourceFiles`) and SDK public input pins are updated. The unused
`external-gateway-handoff.ts` module is removed.
- Fixture realism: the create-gateway profile now allows a real read
tool (an empty profile made the agent ask which apps to add instead of
finishing), and the rotation tokens get a neutral owner note instead of
"Disposable rotation fixture" (the agent read that note as an eval
hint).
- Shared private-browser helpers (`external-private-browser.ts`,
`external-private-browser-worker.ts`) get one optional `pendingTokenId`
input and one `revealedPending` receipt field.

## Verification

- Red: on `master` route code, the new integration tests `lets agents
create and revoke gateway client tokens without ever receiving a token
value` and `reveals an agent-created gateway token value only to its
responsible person` fail (403 `gateway_token_requires_person`).
- Green: `cd server && npx vitest run
src/__tests__/connection-management.integration.test.ts -t gateway` (25
passed). The test checks that the agent `call_api` result has no `token`
field and no token-shaped value, that the agent cannot reveal, that the
person reveals once (second reveal 409) and the value authenticates,
that agent revoke works and stops the value, that a token revoked before
reveal never gets a value, and that person create still returns the
value.
- `npx vitest run src/__tests__/tool-gateway.test.ts
src/__tests__/openapi-routes.test.ts
src/services/native-runtime/runner-api.test.ts` (2247 passed).
- `cd ui && npx vitest run
src/pages/apps/gateways/panels/TokensPanel.test.tsx
src/pages/apps/gateways/gateway-helpers.test.ts` (16 passed); `pnpm
check:token-gates` clean.
- Eval graders and catalog: `pnpm exec vitest run --config
tests/runner-e2e/vitest.config.ts` on the gateway oracle tests,
`external.test.ts`, catalog consistency/contract, TestOps
export/retained, phase/clock callers and SDK input/type tests (all
pass); `node --test` on the TestOps manifest, adapter, contract,
streaming and reconcile tests (all pass); `node
tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`
(unchanged).
- `node scripts/check-maps.mjs` passes. `tsc --noEmit` for `server`,
`ui` and `tests/runner-e2e`: no errors in changed files.
- Paid end-to-end run of both eval cases, run
[42872921890](https://github.com/paperclipai/paperclip/actions/runs/42872921890)
on 39f38a7f6c (before the last three commits): both FAILED, for
agent-behavior reasons the later commits address. Not rerun yet.
- rotate-token: the agent created the replacement (pending reveal, no
value), then revoked the old token in the same turn, despite the create
response saying to wait. Its reasoning cited the eval-looking fixture
note. The grader rejected the premature revocation. The reply linked the
Tokens page correctly.
- create-gateway: the agent created the gateway and one pending token,
then asked a question card about which apps to add to the empty profile,
with no link to the gateway. The grader rejected the missing link.
- Token values: a scan of all evidence files of both cells found no full
`pcgw_<id>.<secret>` value and no `pcgw_<uuid>` form. Agent `call_api`
payloads in run events are redacted; the integration test proves the
agent tool result has no value.

## Risks

- Behavior change for agents: token create returns metadata and a Tokens
page path, not a value. Agents that expect `token` in the response must
send the person to the Tokens page.
- Migration adds one boolean column with a default. Existing tokens get
`false` and keep working.
- A pending token that is never revealed stays as an unusable row until
someone revokes it. It cannot authenticate.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), tool use and code
execution in Claude Code.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:13:34 -06:00

500 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { type FormEvent, type ReactNode, useEffect, useMemo, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, Copy, KeyRound, Plus } from "lucide-react";
import type {
ToolMcpGatewayToken,
ToolMcpGatewayTokenAction,
ToolMcpGatewayTokenCreated,
ToolMcpGatewayWithTokens,
} from "@paperclipai/shared";
import { toolsApi } from "@/api/tools";
import { useAccountIdentity } from "@/api/companies-query";
import { Button } from "@/components/ui/button";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { Input } from "@/components/ui/input";
import { useToast } from "@/context/ToastContext";
import { copyTextToClipboard } from "@/lib/clipboard";
import { cn } from "@/lib/utils";
import { RelativeTime } from "@/pages/tools/shared";
import { gatewaysQueryKey } from "../NewGatewayDialog";
import {
defaultGatewayTokenName,
maskedTokenLabel,
TOKEN_STATUS_LABEL,
toDate,
tokenStatus,
type TokenStatus,
} from "../gateway-helpers";
import { describeError } from "@/api/errors";
const DEFAULT_ACTIONS: ToolMcpGatewayTokenAction[] = ["tools/list", "tools/call"];
const TOKEN_PAGE_SIZE = 10;
function defaultExpiry(): string {
return new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);
}
const STATUS_CLASS: Record<TokenStatus, string> = {
pending: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
active: "border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
expiring: "border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300",
expired: "border-border bg-muted text-muted-foreground",
revoked: "border-foreground bg-foreground text-background",
};
function StatusBadge({ status }: { status: TokenStatus }) {
return (
<span
className={cn(
"inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-xs font-medium",
STATUS_CLASS[status],
)}
>
{TOKEN_STATUS_LABEL[status]}
</span>
);
}
function TokenField({ label, value }: { label: string; value: ReactNode }) {
return (
<div className="min-w-0">
<dt className="text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">{label}</dt>
<dd className="mt-0.5 truncate text-foreground">{value}</dd>
</div>
);
}
function ExpiryValue({ token }: { token: ToolMcpGatewayToken }) {
const expiresAt = toDate(token.expiresAt);
if (!expiresAt) return <>No expiry</>;
if (expiresAt.getTime() <= Date.now()) {
return <><span className="font-medium text-foreground">Expired</span> <RelativeTime value={token.expiresAt} /></>;
}
return <>Expires <RelativeTime value={token.expiresAt} /></>;
}
export function TokensPanel({
companyId,
gateway,
onTokenCreated,
}: {
companyId: string;
gateway: ToolMcpGatewayWithTokens;
onTokenCreated?: (token: ToolMcpGatewayTokenCreated) => void;
}) {
const queryClient = useQueryClient();
const { pushToast } = useToast();
const [minting, setMinting] = useState(false);
const [name, setName] = useState("");
const [ownerNote, setOwnerNote] = useState("");
const [expiresAt, setExpiresAt] = useState(defaultExpiry());
const [created, setCreated] = useState<ToolMcpGatewayTokenCreated | null>(null);
const [revealed, setRevealed] = useState(false);
const [historyOpen, setHistoryOpen] = useState(false);
const [historyPage, setHistoryPage] = useState(1);
const [revokeName, setRevokeName] = useState("");
const [confirmToken, setConfirmToken] = useState<{ id: string; name: string } | null>(null);
const invalidate = () => queryClient.invalidateQueries({ queryKey: gatewaysQueryKey(companyId) });
const tokens = useMemo(
() => [...gateway.tokens].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()),
[gateway.tokens],
);
// Only the person an agent-created token acts for can reveal it.
const { userId } = useAccountIdentity();
const pendingTokens = useMemo(
() => tokens.filter((token) => tokenStatus(token) === "pending" && (!token.responsibleUserId || !userId || token.responsibleUserId === userId)),
[tokens, userId],
);
const pageCount = Math.max(1, Math.ceil(tokens.length / TOKEN_PAGE_SIZE));
const visibleTokens = tokens.slice((historyPage - 1) * TOKEN_PAGE_SIZE, historyPage * TOKEN_PAGE_SIZE);
useEffect(() => {
setHistoryPage((current) => Math.min(current, pageCount));
}, [pageCount]);
const createMutation = useMutation({
mutationFn: () =>
toolsApi.createGatewayToken(companyId, gateway.id, {
name: name.trim(),
clientLabel: name.trim(),
ownerNote: ownerNote.trim(),
allowedActions: DEFAULT_ACTIONS,
expiresAt: expiresAt ? `${expiresAt}T23:59:59.000Z` : null,
}),
onSuccess: async (token) => {
setCreated(token);
setRevealed(true);
setMinting(false);
setName("");
setOwnerNote("");
setExpiresAt(defaultExpiry());
pushToast({
title: "Token issued",
body: "Copy it now — you won’t see the full value again after leaving this page.",
tone: "success",
});
onTokenCreated?.(token);
await invalidate();
},
onError: (error) =>
pushToast({
title: "Token was not issued",
body: describeError(error).body,
tone: "error",
}),
});
// Agent-created tokens get their value only when the person reveals them here.
const revealMutation = useMutation({
mutationFn: (tokenId: string) => toolsApi.revealGatewayToken(companyId, tokenId),
onSuccess: async (token) => {
setCreated(token);
setRevealed(true);
pushToast({
title: "Token revealed",
body: "Copy it now — you won’t see the full value again after leaving this page.",
tone: "success",
});
onTokenCreated?.(token);
await invalidate();
},
onError: (error) =>
pushToast({
title: "Token was not revealed",
body: describeError(error).body,
tone: "error",
}),
});
const revokeMutation = useMutation({
mutationFn: (tokenId: string) => toolsApi.revokeGatewayToken(companyId, tokenId),
onSuccess: async (token) => {
setConfirmToken(null);
setRevokeName("");
pushToast({ title: "Token revoked", body: `${token.name} can no longer connect.`, tone: "success" });
await invalidate();
},
onError: (error) =>
pushToast({
title: "Token was not revoked",
body: describeError(error).body,
tone: "error",
}),
});
async function copyToken(value: string) {
try {
await copyTextToClipboard(value);
pushToast({ title: "Copied", body: "Access token", tone: "success" });
} catch (error) {
pushToast({
title: "Copy failed",
body: describeError(error).body,
tone: "error",
});
}
}
function startIssuing() {
if (!minting && !name.trim()) setName(defaultGatewayTokenName(gateway));
setMinting((value) => !value);
}
function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!name.trim()) return;
createMutation.mutate();
}
function startRevoke(token: ToolMcpGatewayToken) {
setConfirmToken({ id: token.id, name: token.name });
setRevokeName("");
}
return (
<div className="space-y-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="max-w-2xl space-y-1">
<p className="text-sm text-muted-foreground">
Issue a reusable token for an external client. Its name is also used as the client label.
</p>
<p className="text-xs text-muted-foreground">
Paperclip creates a fresh one-hour runtime token when an agent run starts, then revokes it when the
run ends. Codex can receive the same gateway through both an app connection and the managed-gateway
path, so one run may leave two revoked rows. These are audit history, not repeated manual tokens.
</p>
</div>
<Button size="sm" onClick={startIssuing}>
<Plus className="mr-1.5 h-3.5 w-3.5" />
Issue token
</Button>
</div>
{minting ? (
<form className="space-y-3" onSubmit={submit}>
<div className="grid gap-3 md:grid-cols-[1fr_auto]">
<label className="space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Token name</span>
<Input value={name} onChange={(event) => setName(event.target.value)} required autoFocus />
<span className="text-xs text-muted-foreground">Also used as the client label.</span>
</label>
<label className="space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Expires</span>
<Input type="date" value={expiresAt} onChange={(event) => setExpiresAt(event.target.value)} required />
</label>
</div>
<label className="block space-y-1.5 text-sm">
<span className="text-xs font-medium text-muted-foreground">Owner note (optional)</span>
<Input
value={ownerNote}
onChange={(event) => setOwnerNote(event.target.value)}
placeholder="Who uses this token or why it exists"
/>
</label>
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setMinting(false)}>
Cancel
</Button>
<Button type="submit" size="sm" disabled={createMutation.isPending || !name.trim()}>
{createMutation.isPending ? "Issuing…" : "Issue token"}
</Button>
</div>
</form>
) : null}
{pendingTokens.length > 0 ? (
<section className="space-y-2 border-y border-border py-4" aria-label="Tokens waiting to be revealed">
<div>
<div className="text-sm font-semibold text-foreground">Waiting for you to reveal</div>
<div className="text-xs text-muted-foreground">
An agent created these tokens for you. A value is generated when you reveal it and is shown only once.
</div>
</div>
{pendingTokens.map((token) => (
<div key={token.id} className="flex flex-wrap items-center justify-between gap-2">
<div className="min-w-0">
<div className="truncate font-medium text-foreground">{token.name}</div>
<div className="text-xs text-muted-foreground">
{maskedTokenLabel(token)} · <ExpiryValue token={token} />
</div>
</div>
<Button
size="sm"
disabled={revealMutation.isPending}
onClick={() => revealMutation.mutate(token.id)}
aria-label={`Reveal token ${token.name}`}
>
Reveal token
</Button>
</div>
))}
</section>
) : null}
{created ? (
<div className="space-y-2 border-y border-border py-4">
<div className="flex items-center justify-between gap-2">
<div>
<div className="text-sm font-semibold text-foreground">New token — copy now</div>
<div className="text-xs text-muted-foreground">
It is now available in Client snippets for a copy-ready configuration.
</div>
</div>
<Button variant="ghost" size="sm" onClick={() => setCreated(null)} aria-label="Dismiss new token">
Dismiss
</Button>
</div>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 truncate rounded bg-muted px-3 py-2 font-mono text-xs text-foreground">
{revealed ? created.token : maskedTokenLabel(created)}
</code>
{revealed ? (
<Button variant="outline" size="sm" onClick={() => void copyToken(created.token)}>
<Copy className="mr-1 h-3.5 w-3.5" />
Copy
</Button>
) : (
<Button variant="outline" size="sm" onClick={() => setRevealed(true)}>Show</Button>
)}
</div>
</div>
) : null}
<Collapsible open={historyOpen} onOpenChange={setHistoryOpen}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="h-auto w-full justify-between px-0 py-1 hover:bg-transparent">
<span className="flex items-center gap-2 text-sm font-semibold text-foreground">
<KeyRound className="h-4 w-4 text-muted-foreground" />
Token history
<span className="font-normal text-muted-foreground">{tokens.length}</span>
</span>
{historyOpen ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="space-y-3 pt-3">
{tokens.length === 0 ? (
<p className="py-4 text-sm text-muted-foreground">No tokens have been issued for this gateway.</p>
) : (
<>
<div className="hidden overflow-x-auto rounded-lg border border-border sm:block">
<table className="w-full min-w-(--sz-44rem) text-sm">
<thead>
<tr className="border-b border-border bg-muted/40 text-left text-(length:--text-micro) font-semibold uppercase tracking-wide text-muted-foreground">
<th className="px-4 py-2.5">Token</th>
<th className="px-4 py-2.5">Owner</th>
<th className="px-4 py-2.5">Created</th>
<th className="px-4 py-2.5">Last used</th>
<th className="px-4 py-2.5">Expiry</th>
<th className="px-4 py-2.5">Status</th>
<th className="px-4 py-2.5 text-right" />
</tr>
</thead>
<tbody>
{visibleTokens.map((token) => {
const status = tokenStatus(token);
return (
<tr key={token.id} className="border-b border-border last:border-0">
<td className="px-4 py-3">
<div className="font-medium text-foreground">{token.name}</div>
<div className="font-mono text-xs text-muted-foreground">{maskedTokenLabel(token)}</div>
</td>
<td className="px-4 py-3 text-muted-foreground">{token.clientLabel || token.ownerNote || "—"}</td>
<td className="px-4 py-3 text-muted-foreground"><RelativeTime value={token.createdAt} /></td>
<td className="px-4 py-3 text-muted-foreground">
{token.lastUsedAt ? <RelativeTime value={token.lastUsedAt} /> : "—"}
</td>
<td className="px-4 py-3 text-muted-foreground"><ExpiryValue token={token} /></td>
<td className="px-4 py-3"><StatusBadge status={status} /></td>
<td className="px-4 py-3 text-right">
{status !== "revoked" ? (
<Button
variant="ghost"
size="sm"
className="h-7 px-2 text-xs text-destructive hover:text-destructive"
onClick={() => startRevoke(token)}
>
Revoke
</Button>
) : null}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<div className="space-y-3 sm:hidden">
{visibleTokens.map((token) => {
const status = tokenStatus(token);
return (
<div key={token.id} className="border-b border-border py-3 last:border-0">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="font-medium text-foreground">{token.name}</div>
<div className="font-mono text-xs text-muted-foreground">{maskedTokenLabel(token)}</div>
</div>
<StatusBadge status={status} />
</div>
<dl className="mt-3 grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
<TokenField label="Owner" value={token.clientLabel || token.ownerNote || "—"} />
<TokenField label="Created" value={<RelativeTime value={token.createdAt} />} />
<TokenField label="Last used" value={token.lastUsedAt ? <RelativeTime value={token.lastUsedAt} /> : "—"} />
<TokenField label="Expiry" value={<ExpiryValue token={token} />} />
</dl>
{status !== "revoked" ? (
<Button
variant="ghost"
size="sm"
className="mt-3 w-full text-xs text-destructive hover:text-destructive"
onClick={() => startRevoke(token)}
>
Revoke
</Button>
) : null}
</div>
);
})}
</div>
{pageCount > 1 ? (
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
Page {historyPage} of {pageCount} · {tokens.length} tokens
</p>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
disabled={historyPage === 1}
onClick={() => setHistoryPage((page) => Math.max(1, page - 1))}
aria-label="Previous token page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
disabled={historyPage === pageCount}
onClick={() => setHistoryPage((page) => Math.min(pageCount, page + 1))}
aria-label="Next token page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
) : null}
</>
)}
</CollapsibleContent>
</Collapsible>
{confirmToken ? (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true">
<div className="w-full max-w-md space-y-3 rounded-lg border border-border bg-card p-5 shadow-lg">
<div>
<h3 className="text-sm font-semibold text-foreground">Revoke this token?</h3>
<p className="mt-1 text-sm text-muted-foreground">
Any client using <span className="font-medium text-foreground">{confirmToken.name}</span> goes
silent immediately. This can’t be undone. Type the token name to confirm.
</p>
</div>
<Input
value={revokeName}
onChange={(event) => setRevokeName(event.target.value)}
placeholder={confirmToken.name}
aria-label="Type the token name to confirm"
autoFocus
/>
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => {
setConfirmToken(null);
setRevokeName("");
}}
>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
disabled={revokeName.trim() !== confirmToken.name || revokeMutation.isPending}
onClick={() => revokeMutation.mutate(confirmToken.id)}
>
{revokeMutation.isPending ? "Revoking…" : "Revoke token"}
</Button>
</div>
</div>
</div>
) : null}
</div>
);
}