Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat(tokens): redesign API tokens settings with dialogs and clean table

Marc Seitzb7a027441496
diff --git a/components/tokens/add-edit-token-modal.tsx b/components/tokens/add-edit-token-modal.tsx
new file mode 100644
index 00000000..a713fdff
--- /dev/null
+++ b/components/tokens/add-edit-token-modal.tsx
@@ -0,0 +1,401 @@
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+
+import { useTeam } from "@/context/team-context";
+import { CircleHelpIcon } from "lucide-react";
+import { toast } from "sonner";
+
+import { cn } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { BadgeTooltip } from "@/components/ui/tooltip";
+
+import {
+ DEFAULT_RESOURCE_STATE,
+ PRESET_DESCRIPTIONS,
+ PRESET_OPTIONS,
+ Preset,
+ RESOURCE_OPTIONS,
+ Resource,
+ ResourceState,
+ TOKEN_TYPE_OPTIONS,
+ TokenSubjectType,
+ buildScopesList,
+ scopesToEditorState,
+} from "./scopes";
+
+interface TokenForEdit {
+ id: string;
+ name: string;
+ scopes: string | null;
+}
+
+interface AddEditTokenModalProps {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ token?: TokenForEdit;
+ onTokenCreated?: (secret: string) => void;
+ onSaved?: () => void;
+}
+
+function AddEditTokenModal({
+ showModal,
+ setShowModal,
+ token,
+ onTokenCreated,
+ onSaved,
+}: AddEditTokenModalProps) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const isEdit = Boolean(token);
+
+ const initial = useMemo(
+ () =>
+ token
+ ? scopesToEditorState(token.scopes)
+ : {
+ preset: "all_access" as Preset,
+ resourceState: { ...DEFAULT_RESOURCE_STATE },
+ },
+ [token],
+ );
+
+ const [name, setName] = useState(token?.name ?? "");
+ const [subjectType, setSubjectType] = useState<TokenSubjectType>("user");
+ const [preset, setPreset] = useState<Preset>(initial.preset);
+ const [resourceState, setResourceState] = useState<ResourceState>(
+ initial.resourceState,
+ );
+ const [isLoading, setIsLoading] = useState(false);
+
+ // Reset state when the modal opens or the target token changes so re-opens
+ // don't leak input from a previous edit/create cycle.
+ useEffect(() => {
+ if (!showModal) return;
+ setName(token?.name ?? "");
+ setPreset(initial.preset);
+ setResourceState(initial.resourceState);
+ if (!isEdit) setSubjectType("user");
+ setIsLoading(false);
+ }, [showModal, token, initial, isEdit]);
+
+ const scopesList = useMemo(
+ () => buildScopesList(preset, resourceState),
+ [preset, resourceState],
+ );
+
+ const submitDisabled =
+ isLoading ||
+ (!isEdit && !name.trim()) ||
+ (isEdit && !name.trim()) ||
+ (preset === "restricted" && scopesList.length === 0);
+
+ const handleSubmit = async (event: React.FormEvent) => {
+ event.preventDefault();
+ if (preset === "restricted" && scopesList.length === 0) {
+ toast.error("Select at least one resource permission");
+ return;
+ }
+ try {
+ setIsLoading(true);
+
+ if (isEdit && token) {
+ const response = await fetch(`/api/teams/${teamId}/tokens`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ tokenId: token.id,
+ name: name.trim(),
+ scopes: scopesList,
+ }),
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error);
+ }
+ toast.success("API key updated");
+ setShowModal(false);
+ onSaved?.();
+ } else {
+ const response = await fetch(`/api/teams/${teamId}/tokens`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: name.trim(),
+ scopes: scopesList,
+ subjectType,
+ }),
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error);
+ }
+ const data = (await response.json()) as { token: string };
+ toast.success("API key created");
+ setShowModal(false);
+ onSaved?.();
+ onTokenCreated?.(data.token);
+ }
+ } catch (error) {
+ console.error(error);
+ toast.error((error as Error).message || "Something went wrong");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const setResource = (resource: Resource, value: "none" | "read" | "write") => {
+ setResourceState((prev) => ({ ...prev, [resource]: value }));
+ };
+
+ return (
+ <Dialog open={showModal} onOpenChange={setShowModal}>
+ <DialogContent className="bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100 sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {isEdit ? "Edit API key" : "Create new API key"}
+ </DialogTitle>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit} className="space-y-5">
+ <div className="space-y-2">
+ <Label htmlFor="token-name">Name</Label>
+ <Input
+ id="token-name"
+ autoFocus
+ placeholder="My API key"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ className="bg-white text-gray-900 dark:bg-white"
+ />
+ </div>
+
+ {!isEdit ? (
+ <div className="space-y-2">
+ <Label>Type</Label>
+ <div
+ role="radiogroup"
+ aria-label="Token subject type"
+ className="grid grid-cols-2 gap-3"
+ >
+ {TOKEN_TYPE_OPTIONS.map((option) => {
+ const active = option.value === subjectType;
+ return (
+ <button
+ type="button"
+ key={option.value}
+ role="radio"
+ aria-checked={active}
+ onClick={() => setSubjectType(option.value)}
+ className={cn(
+ "group flex items-center justify-between rounded-md border px-3 py-2.5 text-left text-sm transition-colors",
+ active
+ ? "border-gray-900 text-gray-900 ring-1 ring-gray-900 dark:border-gray-100 dark:ring-gray-100"
+ : "border-gray-200 text-gray-700 hover:border-gray-300 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-800",
+ )}
+ >
+ <span className="flex items-center gap-2">
+ <span
+ className={cn(
+ "flex h-4 w-4 items-center justify-center rounded-full border",
+ active
+ ? "border-gray-900 dark:border-gray-100"
+ : "border-gray-300 dark:border-gray-600",
+ )}
+ >
+ {active ? (
+ <span className="h-2 w-2 rounded-full bg-gray-900 dark:bg-gray-100" />
+ ) : null}
+ </span>
+ <span className="font-medium">{option.label}</span>
+ </span>
+ <BadgeTooltip
+ content={option.tooltip}
+ className="max-w-72 text-left leading-5 text-gray-600"
+ >
+ <CircleHelpIcon className="h-4 w-4 text-gray-400 group-hover:text-gray-600" />
+ </BadgeTooltip>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ) : null}
+
+ <div className="space-y-2">
+ <Label>Permissions</Label>
+ <div
+ role="radiogroup"
+ aria-label="Token permissions preset"
+ className="grid grid-cols-3 overflow-hidden rounded-md border border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800"
+ >
+ {PRESET_OPTIONS.map((option) => {
+ const active = preset === option.value;
+ return (
+ <button
+ type="button"
+ key={option.value}
+ role="radio"
+ aria-checked={active}
+ onClick={() => setPreset(option.value)}
+ className={cn(
+ "flex h-9 items-center justify-center text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400",
+ active
+ ? "bg-white font-medium text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 dark:bg-gray-900 dark:text-gray-100 dark:ring-gray-600"
+ : "text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700",
+ )}
+ >
+ {option.value === "all_access"
+ ? "All"
+ : option.value === "read_only"
+ ? "Read Only"
+ : "Restricted"}
+ </button>
+ );
+ })}
+ </div>
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ This API key will have{" "}
+ <span className="font-medium text-gray-700 dark:text-gray-200">
+ {PRESET_DESCRIPTIONS[preset]}
+ </span>
+ </p>
+ </div>
+
+ {preset === "restricted" ? (
+ <div className="space-y-3 border-t border-gray-100 pt-3 dark:border-gray-800">
+ {RESOURCE_OPTIONS.map((option) => (
+ <div
+ key={option.resource}
+ className="flex items-center justify-between gap-4"
+ >
+ <div className="flex items-center gap-1.5 text-sm font-medium text-gray-900 dark:text-gray-100">
+ {option.label}
+ <BadgeTooltip
+ content={option.description}
+ className="max-w-72 text-left leading-5 text-gray-600"
+ >
+ <CircleHelpIcon className="h-3.5 w-3.5 text-gray-400" />
+ </BadgeTooltip>
+ </div>
+ <div className="flex items-center gap-4 text-sm">
+ <RadioPill
+ label="None"
+ checked={resourceState[option.resource] === "none"}
+ onClick={() => setResource(option.resource, "none")}
+ />
+ <RadioPill
+ label="Read"
+ checked={resourceState[option.resource] === "read"}
+ onClick={() => setResource(option.resource, "read")}
+ />
+ {option.actions.includes("write") ? (
+ <RadioPill
+ label="Write"
+ checked={resourceState[option.resource] === "write"}
+ onClick={() => setResource(option.resource, "write")}
+ />
+ ) : (
+ <span className="w-[56px]" aria-hidden />
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : null}
+
+ <Button
+ type="submit"
+ disabled={submitDisabled}
+ loading={isLoading}
+ className="w-full bg-gray-900 text-gray-50 hover:bg-gray-900/90"
+ >
+ {isEdit ? "Save changes" : "Create API key"}
+ </Button>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function RadioPill({
+ label,
+ checked,
+ onClick,
+}: {
+ label: string;
+ checked: boolean;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={checked}
+ onClick={onClick}
+ className="group flex items-center gap-1.5 text-sm text-gray-700 dark:text-gray-300"
+ >
+ <span
+ className={cn(
+ "flex h-4 w-4 items-center justify-center rounded-full border transition-colors",
+ checked
+ ? "border-gray-900 dark:border-gray-100"
+ : "border-gray-300 group-hover:border-gray-500 dark:border-gray-600",
+ )}
+ >
+ {checked ? (
+ <span className="h-2 w-2 rounded-full bg-gray-900 dark:bg-gray-100" />
+ ) : null}
+ </span>
+ {label}
+ </button>
+ );
+}
+
+export function useAddEditTokenModal({
+ token,
+ onTokenCreated,
+ onSaved,
+}: {
+ token?: TokenForEdit;
+ onTokenCreated?: (secret: string) => void;
+ onSaved?: () => void;
+} = {}) {
+ const [showAddEditTokenModal, setShowAddEditTokenModal] = useState(false);
+
+ const AddEditTokenModalCallback = useCallback(
+ () => (
+ <AddEditTokenModal
+ showModal={showAddEditTokenModal}
+ setShowModal={setShowAddEditTokenModal}
+ token={token}
+ onTokenCreated={onTokenCreated}
+ onSaved={onSaved}
+ />
+ ),
+ [showAddEditTokenModal, token, onTokenCreated, onSaved],
+ );
+
+ return useMemo(
+ () => ({
+ showAddEditTokenModal,
+ setShowAddEditTokenModal,
+ AddEditTokenModal: AddEditTokenModalCallback,
+ }),
+ [showAddEditTokenModal, AddEditTokenModalCallback],
+ );
+}
diff --git a/components/tokens/delete-token-modal.tsx b/components/tokens/delete-token-modal.tsx
new file mode 100644
index 00000000..5f60783a
--- /dev/null
+++ b/components/tokens/delete-token-modal.tsx
@@ -0,0 +1,161 @@
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+
+import { useTeam } from "@/context/team-context";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+interface DeleteTokenModalProps {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ token: { id: string; name: string };
+ onDeleted?: () => void;
+}
+
+function DeleteTokenModal({
+ showModal,
+ setShowModal,
+ token,
+ onDeleted,
+}: DeleteTokenModalProps) {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+ const [confirm, setConfirm] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+
+ const expected = token.name;
+ const canDelete = confirm.trim() === expected && !isLoading && !!teamId;
+
+ const handleDelete = async (event: React.FormEvent) => {
+ event.preventDefault();
+ if (!canDelete) return;
+ if (!teamId) {
+ toast.error("No team selected. Please try again.");
+ return;
+ }
+ try {
+ setIsLoading(true);
+ const response = await fetch(`/api/teams/${teamId}/tokens`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ tokenId: token.id }),
+ });
+ if (!response.ok) {
+ const error = await response.json();
+ throw new Error(error.error);
+ }
+ toast.success("API key revoked");
+ setShowModal(false);
+ onDeleted?.();
+ } catch (error) {
+ console.error(error);
+ toast.error((error as Error).message || "Failed to revoke API key");
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open={showModal}
+ onOpenChange={(open) => {
+ setShowModal(open);
+ if (!open) setConfirm("");
+ }}
+ >
+ <DialogContent className="bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100 sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Revoke API key</DialogTitle>
+ <DialogDescription>
+ This action cannot be undone. Any apps or scripts using this key
+ will immediately lose access.
+ </DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleDelete} className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="confirm-name">
+ Type{" "}
+ <span className="font-semibold text-gray-900 dark:text-gray-100">
+ {expected}
+ </span>{" "}
+ to confirm
+ </Label>
+ <Input
+ id="confirm-name"
+ autoFocus
+ autoComplete="off"
+ value={confirm}
+ onChange={(e) => setConfirm(e.target.value)}
+ className="bg-white text-gray-900 dark:bg-white"
+ />
+ </div>
+
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setShowModal(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={!canDelete}
+ loading={isLoading}
+ >
+ Revoke key
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function useDeleteTokenModal({
+ token,
+ onDeleted,
+}: {
+ token: { id: string; name: string } | null;
+ onDeleted?: () => void;
+}) {
+ const [showDeleteTokenModal, setShowDeleteTokenModal] = useState(false);
+
+ const DeleteTokenModalCallback = useCallback(() => {
+ if (!token) return null;
+ return (
+ <DeleteTokenModal
+ showModal={showDeleteTokenModal}
+ setShowModal={setShowDeleteTokenModal}
+ token={token}
+ onDeleted={onDeleted}
+ />
+ );
+ }, [showDeleteTokenModal, token, onDeleted]);
+
+ return useMemo(
+ () => ({
+ showDeleteTokenModal,
+ setShowDeleteTokenModal,
+ DeleteTokenModal: DeleteTokenModalCallback,
+ }),
+ [showDeleteTokenModal, DeleteTokenModalCallback],
+ );
+}
diff --git a/components/tokens/scopes.ts b/components/tokens/scopes.ts
new file mode 100644
index 00000000..4073500a
--- /dev/null
+++ b/components/tokens/scopes.ts
@@ -0,0 +1,177 @@
+import { GRANULAR_SCOPES } from "@/lib/oauth/scopes";
+
+export type TokenSubjectType = "user" | "machine";
+
+export type Preset = "all_access" | "read_only" | "restricted";
+
+export const TOKEN_TYPE_LABELS: Record<TokenSubjectType, string> = {
+ user: "User key",
+ machine: "Machine key",
+};
+
+export const PRESET_OPTIONS: { value: Preset; label: string }[] = [
+ { value: "all_access", label: "All" },
+ { value: "read_only", label: "Read Only" },
+ { value: "restricted", label: "Restricted" },
+];
+
+export const PRESET_DESCRIPTIONS: Record<Preset, string> = {
+ all_access: "full access to all resources",
+ read_only: "read-only access to all resources",
+ restricted: "restricted access to some resources",
+};
+
+export const PRESET_LABELS: Record<Preset, string> = {
+ all_access: "All access",
+ read_only: "Read only",
+ restricted: "Restricted",
+};
+
+export type Resource =
+ | "documents"
+ | "links"
+ | "datarooms"
+ | "analytics"
+ | "visitors";
+
+export const RESOURCE_OPTIONS: {
+ resource: Resource;
+ label: string;
+ description: string;
+ actions: ("read" | "write")[];
+}[] = [
+ {
+ resource: "documents",
+ label: "Documents",
+ description: "Upload, list, update, and delete documents.",
+ actions: ["read", "write"],
+ },
+ {
+ resource: "links",
+ label: "Links",
+ description: "Create, list, update, and revoke share links.",
+ actions: ["read", "write"],
+ },
+ {
+ resource: "datarooms",
+ label: "Datarooms",
+ description: "Create, list, and modify datarooms.",
+ actions: ["read", "write"],
+ },
+ {
+ resource: "analytics",
+ label: "Analytics",
+ description: "Read views and analytics data.",
+ actions: ["read"],
+ },
+ {
+ resource: "visitors",
+ label: "Visitors",
+ description: "Read visitor records.",
+ actions: ["read"],
+ },
+];
+
+export const TOKEN_TYPE_OPTIONS: {
+ value: TokenSubjectType;
+ label: string;
+ summary: string;
+ tooltip: string;
+}[] = [
+ {
+ value: "user",
+ label: "You",
+ summary: "Revoked automatically when your workspace access ends.",
+ tooltip:
+ "This API key is tied to your user account. If you are removed from the workspace, it will stop working automatically.",
+ },
+ {
+ value: "machine",
+ label: "Machine",
+ summary: "Best for CI, servers, and long-lived automations.",
+ tooltip:
+ "Machine keys stay valid even if the creator leaves the workspace. Use them for bots, deployments, and background jobs.",
+ },
+];
+
+/** Build the scope strings to send to the API based on the editor state. */
+export function buildScopesList(
+ preset: Preset,
+ resourceState: Record<Resource, "none" | "read" | "write">,
+): string[] {
+ if (preset === "all_access") return ["apis.all"];
+ if (preset === "read_only") return ["apis.read"];
+
+ const scopes: string[] = [];
+ for (const [resource, action] of Object.entries(resourceState)) {
+ if (action === "none") continue;
+ if (action === "read") {
+ scopes.push(`${resource}.read`);
+ } else if (action === "write") {
+ // Write implies read; match dub.co semantics so callers don't have to
+ // remember to pick both checkboxes.
+ scopes.push(`${resource}.read`, `${resource}.write`);
+ }
+ }
+ return Array.from(new Set(scopes));
+}
+
+export type ResourceState = Record<Resource, "none" | "read" | "write">;
+
+export const DEFAULT_RESOURCE_STATE: ResourceState = {
+ documents: "none",
+ links: "none",
+ datarooms: "none",
+ analytics: "none",
+ visitors: "none",
+};
+
+/** Infer the editor state (preset + resource map) from a stored scope string. */
+export function scopesToEditorState(rawScopes: string | null | undefined): {
+ preset: Preset;
+ resourceState: ResourceState;
+} {
+ const list = (rawScopes ?? "")
+ .split(/\s+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+
+ if (list.length === 0 || list.includes("apis.all")) {
+ return {
+ preset: "all_access",
+ resourceState: { ...DEFAULT_RESOURCE_STATE },
+ };
+ }
+ if (list.includes("apis.read")) {
+ return {
+ preset: "read_only",
+ resourceState: { ...DEFAULT_RESOURCE_STATE },
+ };
+ }
+
+ const state: ResourceState = { ...DEFAULT_RESOURCE_STATE };
+ for (const scope of list) {
+ if (!GRANULAR_SCOPES.includes(scope as (typeof GRANULAR_SCOPES)[number]))
+ continue;
+ const [resource, action] = scope.split(".") as [Resource, "read" | "write"];
+ if (!(resource in state)) continue;
+ // `write` wins over `read` because we treat write as implying read.
+ if (action === "write" || state[resource] === "none") {
+ state[resource] = action;
+ }
+ }
+ return { preset: "restricted", resourceState: state };
+}
+
+/** Pretty label for the permissions column in the table. */
+export function scopesToPermissionLabel(
+ rawScopes: string | null | undefined,
+): string {
+ const list = (rawScopes ?? "")
+ .split(/\s+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
+ if (list.length === 0 || list.includes("apis.all")) return "All access";
+ if (list.includes("apis.read")) return "Read only";
+ return "Restricted";
+}
diff --git a/components/tokens/token-created-modal.tsx b/components/tokens/token-created-modal.tsx
new file mode 100644
index 00000000..34f90a21
--- /dev/null
+++ b/components/tokens/token-created-modal.tsx
@@ -0,0 +1,118 @@
+import {
+ Dispatch,
+ SetStateAction,
+ useCallback,
+ useMemo,
+ useState,
+} from "react";
+
+import { CheckIcon, CopyIcon } from "lucide-react";
+
+import { copyToClipboard } from "@/lib/utils";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+
+interface TokenCreatedModalProps {
+ showModal: boolean;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ token: string;
+}
+
+function TokenCreatedModal({
+ showModal,
+ setShowModal,
+ token,
+}: TokenCreatedModalProps) {
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = () => {
+ copyToClipboard(token, "API key copied to clipboard");
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1500);
+ };
+
+ return (
+ <Dialog
+ open={showModal}
+ onOpenChange={(open) => {
+ setShowModal(open);
+ if (!open) {
+ setCopied(false);
+ }
+ }}
+ >
+ <DialogContent className="bg-white text-gray-900 dark:bg-gray-900 dark:text-gray-100 sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Your new API key</DialogTitle>
+ <DialogDescription>
+ Copy your API key now. For security, it won&apos;t be shown again.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="flex items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800">
+ <code className="min-w-0 flex-1 break-all font-mono text-sm text-gray-900 dark:text-gray-100">
+ {token}
+ </code>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={handleCopy}
+ className="shrink-0"
+ >
+ {copied ? (
+ <>
+ <CheckIcon className="!h-4 !w-4" />
+ Copied
+ </>
+ ) : (
+ <>
+ <CopyIcon className="!h-4 !w-4" />
+ Copy
+ </>
+ )}
+ </Button>
+ </div>
+
+ <Button
+ type="button"
+ onClick={() => setShowModal(false)}
+ className="w-full bg-gray-900 text-gray-50 hover:bg-gray-900/90"
+ >
+ Done
+ </Button>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+export function useTokenCreatedModal({ token }: { token: string }) {
+ const [showTokenCreatedModal, setShowTokenCreatedModal] = useState(false);
+
+ const TokenCreatedModalCallback = useCallback(
+ () => (
+ <TokenCreatedModal
+ showModal={showTokenCreatedModal}
+ setShowModal={setShowTokenCreatedModal}
+ token={token}
+ />
+ ),
+ [showTokenCreatedModal, token],
+ );
+
+ return useMemo(
+ () => ({
+ showTokenCreatedModal,
+ setShowTokenCreatedModal,
+ TokenCreatedModal: TokenCreatedModalCallback,
+ }),
+ [showTokenCreatedModal, TokenCreatedModalCallback],
+ );
+}
diff --git a/pages/api/teams/[teamId]/tokens/index.ts b/pages/api/teams/[teamId]/tokens/index.ts
index 8641c051..df41f800 100644
--- a/pages/api/teams/[teamId]/tokens/index.ts
+++ b/pages/api/teams/[teamId]/tokens/index.ts
@@ -216,6 +216,109 @@ export default async function handle(
console.error(error);
return res.status(500).json({ error: "Error creating token" });
}
+ } else if (req.method === "PATCH") {
+ try {
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const {
+ tokenId,
+ name,
+ scopes,
+ } = req.body as {
+ tokenId?: string;
+ name?: string;
+ scopes?: string[] | string;
+ };
+ const userId = (session.user as CustomUser).id;
+
+ if (!tokenId || typeof tokenId !== "string") {
+ return res.status(400).json({ error: "tokenId is required" });
+ }
+
+ const userTeam = await prisma.userTeam.findUnique({
+ where: { userId_teamId: { userId, teamId } },
+ select: { role: true },
+ });
+ if (!userTeam) {
+ return res.status(403).json({ error: "Unauthorized" });
+ }
+
+ const existing = await prisma.restrictedToken.findFirst({
+ where: { id: tokenId, teamId, source: "dashboard" },
+ select: { id: true, userId: true },
+ });
+ if (!existing) {
+ return res.status(404).json({ error: "Token not found" });
+ }
+
+ // Only admins or the token's owner may edit it.
+ if (userTeam.role !== "ADMIN" && existing.userId !== userId) {
+ return res.status(403).json({ error: "Unauthorized" });
+ }
+
+ const data: { name?: string; scopes?: string } = {};
+
+ if (typeof name !== "undefined") {
+ if (typeof name !== "string" || name.trim().length === 0) {
+ return res.status(400).json({ error: "Name is required" });
+ }
+ data.name = name.trim();
+ }
+
+ if (typeof scopes !== "undefined") {
+ const ALLOWED_SCOPES: readonly string[] = [
+ ...PRESET_SCOPES,
+ ...GRANULAR_SCOPES,
+ ];
+ const rawScopesList = Array.isArray(scopes)
+ ? scopes
+ : typeof scopes === "string"
+ ? scopes.split(/[\s,]+/).filter(Boolean)
+ : [];
+ const scopesList = rawScopesList.map((s) =>
+ s === "full-access" ? "apis.all" : s,
+ );
+ if (scopesList.length === 0) {
+ return res.status(400).json({
+ error:
+ "At least one scope is required. Use `apis.all` for full access or `apis.read` for read-only.",
+ });
+ }
+ const invalid = scopesList.filter((s) => !ALLOWED_SCOPES.includes(s));
+ if (invalid.length > 0) {
+ return res
+ .status(400)
+ .json({ error: `Invalid scope(s): ${invalid.join(", ")}` });
+ }
+ let normalizedScopes: string[];
+ if (scopesList.includes("apis.all")) {
+ normalizedScopes = ["apis.all"];
+ } else if (scopesList.includes("apis.read")) {
+ normalizedScopes = ["apis.read"];
+ } else {
+ normalizedScopes = Array.from(new Set(scopesList));
+ }
+ data.scopes = normalizedScopes.join(" ");
+ }
+
+ if (Object.keys(data).length === 0) {
+ return res.status(400).json({ error: "No fields to update" });
+ }
+
+ await prisma.restrictedToken.update({
+ where: { id: tokenId },
+ data,
+ });
+
+ return res.status(200).json({ message: "Token updated successfully" });
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Error updating token" });
+ }
} else if (req.method === "DELETE") {
try {
const session = await getServerSession(req, res, authOptions);
@@ -267,7 +370,7 @@ export default async function handle(
return res.status(500).json({ error: "Error deleting token" });
}
} else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
+ res.setHeader("Allow", ["GET", "POST", "PATCH", "DELETE"]);
return res.status(405).json({ error: "Method not allowed" });
}
}
diff --git a/pages/settings/tokens.tsx b/pages/settings/tokens.tsx
index 7dfb19c8..3a40e573 100644
--- a/pages/settings/tokens.tsx
+++ b/pages/settings/tokens.tsx
@@ -1,26 +1,48 @@
import { useRouter } from "next/router";
-import { type ReactNode, useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useTeam } from "@/context/team-context";
import { format } from "date-fns";
-import { CircleHelpIcon, CopyIcon } from "lucide-react";
+import {
+ CircleHelpIcon,
+ KeyRoundIcon,
+ MoreHorizontalIcon,
+ PencilIcon,
+ TrashIcon,
+} from "lucide-react";
import { toast } from "sonner";
import useSWR from "swr";
-import { cn, copyToClipboard, fetcher } from "@/lib/utils";
+import { cn, fetcher, timeAgo } from "@/lib/utils";
import AppLayout from "@/components/layouts/app";
import { SettingsHeader } from "@/components/settings/settings-header";
+import { useAddEditTokenModal } from "@/components/tokens/add-edit-token-modal";
+import { useDeleteTokenModal } from "@/components/tokens/delete-token-modal";
+import {
+ TOKEN_TYPE_LABELS,
+ TokenSubjectType,
+ scopesToPermissionLabel,
+} from "@/components/tokens/scopes";
+import { useTokenCreatedModal } from "@/components/tokens/token-created-modal";
import { Button } from "@/components/ui/button";
-import { Checkbox } from "@/components/ui/checkbox";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/components/ui/table";
import { BadgeTooltip } from "@/components/ui/tooltip";
-type TokenSubjectType = "user" | "machine";
-
interface Token {
id: string;
name: string;
@@ -35,123 +57,10 @@ interface Token {
};
}
-type Preset = "all_access" | "read_only" | "restricted";
-
-const PRESETS: { value: Preset; label: string; description: string }[] = [
- {
- value: "all_access",
- label: "All access",
- description: "Read and write everything in the team.",
- },
- {
- value: "read_only",
- label: "Read only",
- description: "Read everything in the team. Cannot modify any data.",
- },
- {
- value: "restricted",
- label: "Restricted",
- description: "Pick the exact resources and actions this token can access.",
- },
-];
-
-const SCOPE_OPTIONS: { value: string; label: string; description: string }[] = [
- {
- value: "documents.read",
- label: "Documents — Read",
- description: "List and read documents",
- },
- {
- value: "documents.write",
- label: "Documents — Write",
- description: "Upload, update, delete documents",
- },
- {
- value: "links.read",
- label: "Links — Read",
- description: "List and read share links",
- },
- {
- value: "links.write",
- label: "Links — Write",
- description: "Create, update, revoke share links",
- },
- {
- value: "datarooms.read",
- label: "Datarooms — Read",
- description: "List and read datarooms",
- },
- {
- value: "datarooms.write",
- label: "Datarooms — Write",
- description: "Create and modify datarooms",
- },
- {
- value: "analytics.read",
- label: "Analytics — Read",
- description: "Read views and analytics data",
- },
- {
- value: "visitors.read",
- label: "Visitors — Read",
- description: "Read visitor records",
- },
-];
-
-const TOKEN_TYPE_OPTIONS: {
- value: TokenSubjectType;
- label: string;
- summary: string;
- tooltip: ReactNode;
-}[] = [
- {
- value: "user",
- label: "You",
- summary: "Revoked automatically when your workspace access ends.",
- tooltip: (
- <>
- This API key is tied to your user account. If you are removed from the
- workspace, it will stop working automatically.
- </>
- ),
- },
- {
- value: "machine",
- label: "Machine",
- summary: "Best for CI, servers, and long-lived automations.",
- tooltip: (
- <>
- Machine keys stay valid even if the creator leaves the workspace. Use
- them for bots, deployments, and background jobs.
- </>
- ),
- },
-];
-
-const TOKEN_TYPE_LABELS: Record<TokenSubjectType, string> = {
- user: "User key",
- machine: "Machine key",
-};
-
-function presetToScopes(preset: Preset, restricted: Set<string>): string[] {
- if (preset === "all_access") return ["apis.all"];
- if (preset === "read_only") return ["apis.read"];
- return Array.from(restricted);
-}
-
export default function TokenSettings() {
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
const router = useRouter();
- const [name, setName] = useState("");
- const [subjectType, setSubjectType] = useState<TokenSubjectType>("user");
- const [preset, setPreset] = useState<Preset>("all_access");
- // Granular selection — only consulted when preset === "restricted".
- const [restrictedScopes, setRestrictedScopes] = useState<Set<string>>(
- () => new Set(["documents.read", "links.read"]),
- );
- const [token, setToken] = useState<string | null>(null);
- const [isLoading, setIsLoading] = useState(false);
const { data: features } = useSWR<{ tokens: boolean }>(
teamId ? `/api/feature-flags?teamId=${teamId}` : null,
@@ -165,381 +74,271 @@ export default function TokenSettings() {
}
}, [features, router]);
- const { data: tokens, mutate } = useSWR<Token[]>(
- teamId ? `/api/teams/${teamId}/tokens` : null,
- fetcher,
- );
-
- const toggleRestrictedScope = (scope: string) => {
- setRestrictedScopes((prev) => {
- const next = new Set(prev);
- if (next.has(scope)) next.delete(scope);
- else next.add(scope);
- return next;
- });
- };
-
- const scopeList = useMemo(
- () => presetToScopes(preset, restrictedScopes),
- [preset, restrictedScopes],
- );
+ const {
+ data: tokens,
+ isLoading,
+ mutate,
+ } = useSWR<Token[]>(teamId ? `/api/teams/${teamId}/tokens` : null, fetcher);
- const generateDisabled =
- !name.trim() ||
- isLoading ||
- (preset === "restricted" && restrictedScopes.size === 0);
+ const [createdToken, setCreatedToken] = useState<string | null>(null);
+ const [selectedToken, setSelectedToken] = useState<Token | null>(null);
- const submitToken = async () => {
- try {
- setIsLoading(true);
- const response = await fetch(`/api/teams/${teamId}/tokens`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, scopes: scopeList, subjectType }),
- });
+ const { TokenCreatedModal, setShowTokenCreatedModal } = useTokenCreatedModal({
+ token: createdToken ?? "",
+ });
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error);
- }
-
- const data = await response.json();
- setToken(data.token);
- toast.success("API key created successfully");
- mutate();
- } catch (error) {
- console.error(error);
- toast.error((error as Error).message || "Failed to create API key");
- } finally {
- setIsLoading(false);
- }
+ const onTokenCreated = (secret: string) => {
+ setCreatedToken(secret);
+ setShowTokenCreatedModal(true);
};
- const generateToken = () => {
- if (preset === "restricted" && restrictedScopes.size === 0) {
- toast.error("Select at least one scope for this token");
- return;
- }
- void submitToken();
+ const {
+ AddEditTokenModal: CreateTokenModal,
+ setShowAddEditTokenModal: setShowCreateTokenModal,
+ } = useAddEditTokenModal({
+ onTokenCreated,
+ onSaved: () => mutate(),
+ });
+
+ const {
+ AddEditTokenModal: EditTokenModal,
+ setShowAddEditTokenModal: setShowEditTokenModal,
+ } = useAddEditTokenModal({
+ token: selectedToken
+ ? {
+ id: selectedToken.id,
+ name: selectedToken.name,
+ scopes: selectedToken.scopes,
+ }
+ : undefined,
+ onSaved: () => mutate(),
+ });
+
+ const { DeleteTokenModal, setShowDeleteTokenModal } = useDeleteTokenModal({
+ token: selectedToken
+ ? { id: selectedToken.id, name: selectedToken.name }
+ : null,
+ onDeleted: () => mutate(),
+ });
+
+ const openEdit = (token: Token) => {
+ setSelectedToken(token);
+ setShowEditTokenModal(true);
};
- const selectedTokenType = useMemo(
- () => TOKEN_TYPE_OPTIONS.find((option) => option.value === subjectType),
- [subjectType],
- );
-
- const deleteToken = async (tokenId: string) => {
- try {
- const response = await fetch(`/api/teams/${teamId}/tokens`, {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ tokenId }),
- });
-
- if (!response.ok) {
- const error = await response.json();
- throw new Error(error.error);
- }
-
- mutate();
- toast.success("API key revoked successfully");
- } catch (error) {
- console.error(error);
- toast.error((error as Error).message || "Failed to revoke API key");
- }
+ const openDelete = (token: Token) => {
+ setSelectedToken(token);
+ setShowDeleteTokenModal(true);
};
+ const hasTokens = useMemo(() => (tokens?.length ?? 0) > 0, [tokens]);
+
return (
<AppLayout>
+ <CreateTokenModal />
+ <EditTokenModal />
+ <DeleteTokenModal />
+ <TokenCreatedModal />
+
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
<SettingsHeader />
- <div className="rounded-lg border border-gray-200 bg-white">
- <div className="flex flex-col items-center justify-between gap-4 space-y-3 border-b border-gray-200 p-5 sm:flex-row sm:space-y-0 sm:p-10">
- <div className="flex max-w-screen-sm flex-col space-y-3">
+ <div className="rounded-lg border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
+ <div className="flex flex-col items-start justify-between gap-3 border-b border-gray-200 p-5 sm:flex-row sm:items-center sm:p-6 dark:border-gray-800">
+ <div className="space-y-1">
<div className="flex items-center gap-2">
- <h2 className="text-xl font-medium text-gray-900">API Keys</h2>
- <BadgeTooltip content="Use these tokens to authenticate your API requests">
- <CircleHelpIcon className="h-4 w-4 text-gray-500" />
+ <h2 className="text-base font-semibold text-gray-900 dark:text-gray-100">
+ Secret keys
+ </h2>
+ <BadgeTooltip
+ content="These API keys allow other apps to access your workspace. Use them with caution — do not share your API key with others, or expose it in the browser or other client-side code."
+ className="max-w-80 text-left leading-5 text-gray-600"
+ >
+ <CircleHelpIcon className="h-4 w-4 text-gray-400" />
</BadgeTooltip>
</div>
- <p className="text-sm text-gray-500">
+ <p className="text-sm text-gray-500 dark:text-gray-400">
Create scoped API keys for your apps, automation, and MCP
- clients. Keep them secure and never share them publicly.
+ clients.
</p>
</div>
+ <Button
+ type="button"
+ onClick={() => setShowCreateTokenModal(true)}
+ className="bg-gray-900 text-gray-50 hover:bg-gray-900/90"
+ >
+ Create API key
+ </Button>
</div>
- <div className="p-5 sm:p-10">
- <div className="flex flex-col space-y-4">
- <div className="rounded-2xl border border-gray-200 bg-gray-50/70 p-4 sm:p-6">
- <div>
- <Label htmlFor="token-name" className="text-gray-900">
- Name
- </Label>
- <Input
- id="token-name"
- placeholder="Enter a name for your token"
- value={name}
- onChange={(e) => setName(e.target.value)}
- className="mt-2 text-gray-900 dark:bg-white"
+ {isLoading ? (
+ <div className="p-6">
+ <div className="space-y-2">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div
+ key={i}
+ className="h-12 animate-pulse rounded-md bg-gray-100 dark:bg-gray-800"
/>
- </div>
-
- <div className="mt-5">
- <div className="flex items-center gap-2">
- <Label className="text-gray-900">Type</Label>
- </div>
- <p className="mt-1 text-xs text-gray-500">
- Choose whether this key should follow your workspace access
- or stay durable for automation.
- </p>
-
- <RadioGroup
- value={subjectType}
- onValueChange={(value) =>
- setSubjectType(value as TokenSubjectType)
- }
- className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2"
- >
- {TOKEN_TYPE_OPTIONS.map((option) => {
- const active = option.value === subjectType;
- return (
- <label
- key={option.value}
- htmlFor={`subject-type-${option.value}`}
- className={cn(
- "group cursor-pointer rounded-xl border bg-white p-4 transition-all",
- active
- ? "border-gray-900 shadow-[0_0_0_1px_rgba(17,24,39,1)]"
- : "border-gray-200 hover:border-gray-300 hover:bg-gray-50",
- )}
- >
- <div className="flex items-start justify-between gap-3">
- <div className="flex items-start gap-3">
- <RadioGroupItem
- value={option.value}
- id={`subject-type-${option.value}`}
- className="mt-0.5"
- />
- <div className="space-y-1">
- <div className="font-medium text-gray-900">
- {option.label}
- </div>
- <p className="text-sm leading-5 text-gray-500">
- {option.summary}
- </p>
- </div>
- </div>
-
- <BadgeTooltip
- content={option.tooltip}
- className="max-w-80 text-left leading-6 text-gray-600"
- >
- <CircleHelpIcon className="mt-0.5 h-4 w-4 flex-shrink-0 text-gray-400 transition-colors group-hover:text-gray-600" />
- </BadgeTooltip>
- </div>
- </label>
- );
- })}
- </RadioGroup>
-
- <p className="mt-3 rounded-lg border border-dashed border-gray-200 bg-white/80 px-3 py-2 text-xs text-gray-600">
- <span className="font-medium text-gray-900">
- {TOKEN_TYPE_LABELS[subjectType]}
- </span>{" "}
- {selectedTokenType ? selectedTokenType.summary : null}
- </p>
- </div>
- </div>
-
- <div>
- <Label className="text-gray-900">Permissions</Label>
- <p className="text-xs text-gray-500">
- Pick a preset or restrict the token to specific resources.
- </p>
- <div
- role="radiogroup"
- aria-label="Token permissions preset"
- className="mt-3 grid grid-cols-1 overflow-hidden rounded-md border border-gray-200 bg-gray-50 sm:grid-cols-3"
- >
- {PRESETS.map((p) => {
- const active = preset === p.value;
- return (
- <button
- type="button"
- key={p.value}
- role="radio"
- aria-checked={active}
- onClick={() => setPreset(p.value)}
- className={cn(
- "flex h-9 items-center justify-center text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-400",
- active
- ? "bg-white font-medium text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300"
- : "text-gray-600 hover:bg-gray-100",
- )}
- >
- {p.label}
- </button>
- );
- })}
- </div>
- <p className="mt-2 text-xs text-gray-500">
- This API key will have{" "}
- <span className="font-medium text-gray-700">
- {PRESETS.find((p) => p.value === preset)?.description}
- </span>
- </p>
-
- {preset === "restricted" && (
- <div className="mt-3 grid grid-cols-1 gap-2 sm:grid-cols-2">
- {SCOPE_OPTIONS.map((opt) => (
- <label
- key={opt.value}
- className="flex cursor-pointer items-start gap-2 rounded border border-gray-200 p-2 text-sm text-gray-900 hover:bg-gray-50"
- >
- <Checkbox
- checked={restrictedScopes.has(opt.value)}
- onCheckedChange={() =>
- toggleRestrictedScope(opt.value)
- }
- />
- <div className="space-y-0.5">
- <div className="font-medium">{opt.label}</div>
- <div className="text-xs text-gray-500">
- {opt.description}
- </div>
- <code className="text-[10px] text-gray-400">
- {opt.value}
- </code>
- </div>
- </label>
- ))}
- </div>
- )}
+ ))}
</div>
-
- {token && (
- <div className="rounded-lg bg-gray-50 p-4 text-gray-900">
- <div className="flex items-center gap-2">
- <Label>
- Your API key (copy it now, it won&apos;t be shown again)
- </Label>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6"
- onClick={() =>
- copyToClipboard(`${token}`, "Token copied to clipboard")
- }
+ </div>
+ ) : !hasTokens ? (
+ <EmptyState onCreate={() => setShowCreateTokenModal(true)} />
+ ) : (
+ <div className="overflow-x-auto">
+ <Table>
+ <TableHeader>
+ <TableRow className="hover:bg-transparent">
+ <TableHead className="text-xs font-medium uppercase tracking-wide text-gray-500">
+ Name
+ </TableHead>
+ <TableHead className="text-xs font-medium uppercase tracking-wide text-gray-500">
+ Permissions
+ </TableHead>
+ <TableHead className="text-xs font-medium uppercase tracking-wide text-gray-500">
+ Created
+ </TableHead>
+ <TableHead className="text-xs font-medium uppercase tracking-wide text-gray-500">
+ Key
+ </TableHead>
+ <TableHead className="text-xs font-medium uppercase tracking-wide text-gray-500">
+ Last used
+ </TableHead>
+ <TableHead className="w-10" />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {tokens?.map((token) => (
+ <TableRow
+ key={token.id}
+ className="cursor-pointer"
+ onClick={() => openEdit(token)}
>
- <CopyIcon />
- </Button>
- </div>
- <code className="mt-2 block break-all rounded bg-gray-100 p-2 font-mono text-sm">
- {token}
- </code>
- </div>
- )}
-
- <Button
- onClick={generateToken}
- disabled={generateDisabled}
- className="w-full bg-gray-900 text-gray-50 hover:bg-gray-900/90"
- >
- {isLoading ? "Creating API key..." : "Create API key"}
- </Button>
-
- <div className="mt-8">
- <h3 className="mb-4 text-lg font-medium text-gray-900">
- Existing Keys
- </h3>
- <div className="rounded-lg border border-gray-200">
- {tokens?.length === 0 ? (
- <div className="p-4 text-center text-sm text-gray-500">
- No API keys created yet
- </div>
- ) : (
- <div className="divide-y divide-gray-200">
- {tokens?.map((t) => (
- <div
- key={t.id}
- className="flex items-center justify-between p-4"
- >
- <div className="space-y-1">
- <div className="flex items-center gap-2">
- <p className="font-medium text-gray-900">
- {t.name}
- </p>
- <span className="rounded-full bg-gray-100 px-2 py-0.5 text-[10px] font-medium uppercase tracking-[0.14em] text-gray-600">
- {TOKEN_TYPE_LABELS[t.subjectType]}
- </span>
- </div>
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-gray-500">
- <span className="font-mono">{t.partialKey}</span>
- <span>•</span>
- <span>
- Created by{" "}
- {t.user.name ?? t.user.email ?? "Unknown user"}
- </span>
- <span>•</span>
- <span>
- {format(new Date(t.createdAt), "MMM d, yyyy")}
- </span>
- {t.lastUsed ? (
- <>
- <span>•</span>
- <span>
- Last used{" "}
- {format(
- new Date(t.lastUsed),
- "MMM d, yyyy",
- )}
- </span>
- </>
- ) : null}
- </div>
- <div className="flex flex-wrap gap-1 pt-1">
- {(() => {
- const list = t.scopes
- ? t.scopes.split(/\s+/)
- : ["apis.all"];
- const isPreset = list.some(
- (s) => s === "apis.all" || s === "apis.read",
- );
- return list.map((s) => (
- <code
- key={s}
- className={cn(
- "rounded px-1.5 py-0.5 text-[10px]",
- isPreset
- ? "bg-amber-100 text-amber-700"
- : "bg-gray-100 text-gray-700",
- )}
- >
- {s}
- </code>
- ));
- })()}
- </div>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <KeyRoundIcon className="h-4 w-4 text-gray-400" />
+ <div className="flex flex-col">
+ <span className="font-medium text-gray-900 dark:text-gray-100">
+ {token.name}
+ </span>
+ <span className="text-xs text-gray-500">
+ {TOKEN_TYPE_LABELS[token.subjectType]}
+ </span>
</div>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => deleteToken(t.id)}
- >
- Revoke
- </Button>
</div>
- ))}
- </div>
- )}
- </div>
- </div>
+ </TableCell>
+ <TableCell className="text-sm text-gray-700 dark:text-gray-300">
+ {scopesToPermissionLabel(token.scopes)}
+ </TableCell>
+ <TableCell className="text-sm text-gray-700 dark:text-gray-300">
+ <div className="flex flex-col">
+ <span>
+ {format(new Date(token.createdAt), "MMM d, yyyy")}
+ </span>
+ <span className="text-xs text-gray-500">
+ by{" "}
+ {token.user.name ??
+ token.user.email ??
+ "Unknown user"}
+ </span>
+ </div>
+ </TableCell>
+ <TableCell className="font-mono text-sm text-gray-700 dark:text-gray-300">
+ {token.partialKey}
+ </TableCell>
+ <TableCell className="text-sm text-gray-700 dark:text-gray-300">
+ {token.lastUsed ? timeAgo(token.lastUsed) : "Never"}
+ </TableCell>
+ <TableCell
+ className={cn("text-right")}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <RowMenu
+ onEdit={() => openEdit(token)}
+ onDelete={() => openDelete(token)}
+ />
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
</div>
- </div>
+ )}
</div>
</main>
</AppLayout>
);
}
+
+function EmptyState({ onCreate }: { onCreate: () => void }) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-3 px-6 py-16 text-center">
+ <div className="flex h-10 w-10 items-center justify-center rounded-full border border-gray-200 bg-gray-50 text-gray-500 dark:border-gray-700 dark:bg-gray-800">
+ <KeyRoundIcon className="h-5 w-5" />
+ </div>
+ <div className="space-y-1">
+ <p className="text-sm font-medium text-gray-900 dark:text-gray-100">
+ No API keys yet
+ </p>
+ <p className="text-sm text-gray-500 dark:text-gray-400">
+ Create your first API key to use the Papermark API.
+ </p>
+ </div>
+ <Button
+ type="button"
+ onClick={onCreate}
+ className="bg-gray-900 text-gray-50 hover:bg-gray-900/90"
+ >
+ Create API key
+ </Button>
+ </div>
+ );
+}
+
+function RowMenu({
+ onEdit,
+ onDelete,
+}: {
+ onEdit: () => void;
+ onDelete: () => void;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <DropdownMenu open={open} onOpenChange={setOpen}>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8"
+ aria-label="Open token actions"
+ >
+ <MoreHorizontalIcon className="!h-4 !w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-36">
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ setOpen(false);
+ onEdit();
+ }}
+ >
+ <PencilIcon className="!h-4 !w-4 text-gray-500" />
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ setOpen(false);
+ onDelete();
+ }}
+ className="text-red-600 focus:bg-red-50 focus:text-red-700 dark:focus:bg-red-900/20"
+ >
+ <TrashIcon className="!h-4 !w-4" />
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}