Approval request
A card that shows what an agent wants to do, why, and for how long, with Approve and Deny.
The single request that a person decides on. The agent has stopped, and it continues only after a person answers. Press a button: the preview waits a moment, as a real request would, then shows the decision.
Installation
- CLI
- Manual
The command adds the file to your project, with the shadcn/ui components that it uses. Your project needs shadcn/ui.
- pnpm
- npm
- yarn
- bun
pnpm dlx shadcn@latest add https://examples.lumoauth.dev/r/approval-request.json
npx shadcn@latest add https://examples.lumoauth.dev/r/approval-request.json
yarn dlx shadcn@latest add https://examples.lumoauth.dev/r/approval-request.json
bunx --bun shadcn@latest add https://examples.lumoauth.dev/r/approval-request.json
Add the shadcn/ui components that the pattern uses.
npx shadcn@latest add badge button card separator textareaInstall the packages.
npm install lucide-reactCopy the code into your project.
components/approval-request.tsx'use client';import * as React from 'react';import { Bot, Check, Clock, ShieldAlert, UserRound, X } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';import { Separator } from '@/components/ui/separator';import { Textarea } from '@/components/ui/textarea';import { cn } from '@/lib/utils';export type ApprovalImpact = 'low' | 'medium' | 'high' | 'critical';export type ApprovalState = 'pending' | 'approved' | 'denied' | 'expired';/** One request of an agent that waits for a person. */export interface ApprovalRequestData {id: string;agentName: string;agentId?: string;/** The person that the agent acts for, when there is one. */onBehalfOf?: string | null;/** The action in plain words. */summary: string;/** The reason that the agent gave. */justification?: string | null;impact?: ApprovalImpact | string | null;/** The structured detail of the request: `authorization_details` (RFC 9396). */details?: Array<Record<string, unknown>>;/** How long the permission lasts after approval, in seconds. */ttlSeconds?: number | null;/** When the request stops waiting (ISO 8601). */expiresAt?: string | null;state?: ApprovalState;/** Who decided, or the rule that approved the request by itself. */decidedBy?: string | null;decidedAt?: string | null;}/*** Maps a row of `GET /jit/pending`, or the payload of the webhook* `jit.approval_required`, to the props of the card.*/export function fromJitRequest(row: Record<string, any>): ApprovalRequestData {// A request carries one authorization_details object; the JIT token carries a list.const raw = row.authorization_details;const details: Array<Record<string, unknown>> = Array.isArray(raw) ? raw : raw && typeof raw === 'object' ? [raw] : [];const first = details[0] as { type?: string; actions?: string[]; identifier?: string } | undefined;// The pending list has no summary. Build the same words that the webhook's summary uses.const target = [first?.type, first?.identifier].filter(Boolean).join(' ');const fallback = first?.actions?.length? `Wants to ${first.actions.join(', ')}${target ? ` on ${target}` : ''}`: target? `Wants access to ${target}`: 'Permission request';return {id: String(row.request_id),agentName: row.agent_name ?? 'Agent',agentId: row.agent_id,onBehalfOf: row.on_behalf_of ?? null,summary: row.summary ?? fallback,justification: row.justification ?? null,impact: row.risk_level ?? null,details,ttlSeconds: row.requested_ttl ?? null,expiresAt: row.expires_at ?? null,state: 'pending',};}const IMPACT_STYLE: Record<string, string> = {low: 'border-transparent bg-muted text-muted-foreground',medium: 'border-transparent bg-amber-500/15 text-amber-700 dark:text-amber-400',high: 'border-transparent bg-orange-500/15 text-orange-700 dark:text-orange-400',critical: 'border-transparent bg-red-500/15 text-red-700 dark:text-red-400',};function duration(seconds: number) {if (seconds < 90) return `${seconds} seconds`;if (seconds < 5400) return `${Math.round(seconds / 60)} minutes`;return `${Math.round(seconds / 3600)} hours`;}/*** The current time, or null on the server and in the first render. Reading* the clock during render breaks prerendering and hydration, so it is read* in an effect.*/function useNow(active = true) {const [now, setNow] = React.useState<number | null>(null);React.useEffect(() => {if (!active) return;setNow(Date.now());const timer = setInterval(() => setNow(Date.now()), 1000);return () => clearInterval(timer);}, [active]);return now;}/** Time that is left until `expiresAt`, updated every second. */function useRemaining(expiresAt?: string | null) {const now = useNow(Boolean(expiresAt));if (!expiresAt || now === null) return null;const left = Math.max(0, Math.floor((new Date(expiresAt).getTime() - now) / 1000));return { left, text: `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` };}export interface ApprovalRequestProps {request: ApprovalRequestData;/** Called with the note of the approver. Return a promise to show progress. */onApprove?: (id: string, note: string) => void | Promise<void>;onDeny?: (id: string, note: string) => void | Promise<void>;/** Why this person cannot decide. The buttons are then disabled. */disabledReason?: string;className?: string;}export function ApprovalRequest({ request, onApprove, onDeny, disabledReason, className }: ApprovalRequestProps) {const [note, setNote] = React.useState('');const [busy, setBusy] = React.useState<'approve' | 'deny' | null>(null);const remaining = useRemaining(request.state === 'pending' || !request.state ? request.expiresAt : null);const state: ApprovalState = request.state === 'pending' && remaining?.left === 0 ? 'expired' : request.state ?? 'pending';const impact = request.impact ? String(request.impact).toLowerCase() : null;const decide = async (kind: 'approve' | 'deny') => {setBusy(kind);try {await (kind === 'approve' ? onApprove : onDeny)?.(request.id, note);} finally {setBusy(null);}};return (<Card className={cn('w-full max-w-md gap-4', className)}><CardHeader className="gap-3"><div className="flex items-center justify-between gap-2"><div className="flex min-w-0 items-center gap-2 text-sm"><span className="flex size-7 shrink-0 items-center justify-center rounded-md bg-muted"><Bot className="size-4" aria-hidden="true" /></span><span className="truncate font-medium">{request.agentName}</span></div>{impact && (<Badge className={cn('capitalize', IMPACT_STYLE[impact] ?? IMPACT_STYLE.low)}><ShieldAlert aria-hidden="true" />{impact} impact</Badge>)}</div><CardTitle className="text-base leading-snug">{request.summary}</CardTitle>{request.onBehalfOf && (<CardDescription className="flex items-center gap-1.5"><UserRound className="size-3.5" aria-hidden="true" />Acting for {request.onBehalfOf}</CardDescription>)}</CardHeader><CardContent className="grid gap-4">{request.justification && (<blockquote className="border-l-2 pl-3 text-sm text-muted-foreground">{request.justification}</blockquote>)}{request.details && request.details.length > 0 && (<dl className="grid gap-1.5 rounded-md border bg-muted/40 p-3 text-sm">{request.details.flatMap((detail, i) =>Object.entries(detail).map(([key, value]) => (<div key={`${i}-${key}`} className="grid grid-cols-[7rem_1fr] gap-2"><dt className="text-muted-foreground">{key}</dt><dd className="min-w-0 font-mono text-xs leading-5 break-words">{Array.isArray(value) ? value.join(', ') : typeof value === 'object' ? JSON.stringify(value) : String(value)}</dd></div>)),)}</dl>)}<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">{request.ttlSeconds ? <span>Lasts {duration(request.ttlSeconds)} after approval</span> : null}{state === 'pending' && remaining && (<span className="flex items-center gap-1 tabular-nums"><Clock className="size-3.5" aria-hidden="true" />Expires in {remaining.text}</span>)}</div></CardContent><Separator />{state === 'pending' ? (<CardFooter className="grid gap-3">{disabledReason ? (<p className="text-sm text-muted-foreground">{disabledReason}</p>) : (<Textareavalue={note}onChange={(event) => setNote(event.target.value)}placeholder="Add a note (optional)"aria-label="Note for this decision"className="min-h-9"/>)}<div className="grid grid-cols-2 gap-2"><Button variant="outline" disabled={Boolean(disabledReason) || busy !== null} onClick={() => decide('deny')}><X aria-hidden="true" />{busy === 'deny' ? 'Denying…' : 'Deny'}</Button><Button disabled={Boolean(disabledReason) || busy !== null} onClick={() => decide('approve')}><Check aria-hidden="true" />{busy === 'approve' ? 'Approving…' : 'Approve'}</Button></div></CardFooter>) : (<CardFooter className="text-sm"><spanclassName={cn('flex items-center gap-2 font-medium',state === 'approved' && 'text-emerald-700 dark:text-emerald-400',state === 'denied' && 'text-red-700 dark:text-red-400',state === 'expired' && 'text-muted-foreground',)}>{state === 'approved' ? <Check className="size-4" /> : state === 'denied' ? <X className="size-4" /> : <Clock className="size-4" />}{state === 'approved' ? 'Approved' : state === 'denied' ? 'Denied' : 'Expired with no decision'}</span>{request.decidedBy && state !== 'expired' && (<span className="ml-2 text-muted-foreground">by {request.decidedBy}{request.decidedAt && (// The server and the browser may format a time differently.<time dateTime={request.decidedAt} suppressHydrationWarning>, {new Date(request.decidedAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</time>)}</span>)}</CardFooter>)}</Card>);}Change the import paths if your project keeps its components in another place.
Usage
The card takes one request and two callbacks. fromJitRequest maps a row of the pending list, or the payload of the jit.approval_required webhook, to the request.
'use client';
import { ApprovalRequest, fromJitRequest } from '@/components/approval-request';
export function Approval({ row }: { row: Record<string, unknown> }) {
const decide = (decision: 'approve' | 'deny') => async (id: string, note: string) => {
await fetch(`/api/approvals/${id}/${decision}`, { method: 'POST', body: JSON.stringify({ note }) });
};
return <ApprovalRequest request={fromJitRequest(row)} onApprove={decide('approve')} onDeny={decide('deny')} />;
}
Your API route makes the call to LumoAuth with the access token of the approver. Never call LumoAuth from the browser with a secret.
Where the data comes from
| What the card shows | Call |
|---|---|
| The pending requests | GET /jit/pending, or lumo.jit.listPendingRequests() |
| A request as it arrives | The webhook jit.approval_required |
| Approve or deny | POST /jit/approve/{id}, POST /jit/deny/{id} |
| The state of one request | GET /jit/request/{id}/status, or lumo.jit.getRequestStatus() |
The card shows the fields of the request as LumoAuth sends them: justification, risk_level, authorization_details (one object), requested_ttl, expires_at and on_behalf_of. The webhook also sends a summary, such as "Invoice Copilot wants to refund on payment_initiation INV-4471". The pending list has none, so fromJitRequest builds the same words from authorization_details.
States
- Approved and denied, with who decided and when.
- Approved by a rule. Pass the name of the rule as
decidedBy. - Expired. A pending request whose time ran out shows this state by itself.
- Not yours to decide.
disabledReasondisables the buttons and says why.
Props
| Prop | Type | Description |
|---|---|---|
requestrequired | ApprovalRequestData | The request. Its state is pending unless you set state. |
onApprove | (id: string, note: string) => void | Promise<void> | Called when the person approves. Return a promise, and the button shows progress until it settles. |
onDeny | (id: string, note: string) => void | Promise<void> | Called when the person denies. |
disabledReason | string | Why this person cannot decide. The buttons are disabled and the note field gives way to this text. |
className | string | Class name for the card. |
ApprovalRequestData
| Option | Type | Default | Description |
|---|---|---|---|
idrequired | string | The request ID (request_id). | |
agentNamerequired | string | The name of the agent. | |
summaryrequired | string | The action in plain words. | |
onBehalfOf | string | null | The person that the agent acts for. | |
justification | string | null | The reason that the agent gave. | |
impact | 'low' | 'medium' | 'high' | 'critical' | The risk level of the request. | |
details | Record<string, unknown>[] | The structured detail: authorization_details. | |
ttlSeconds | number | null | How long the permission lasts after approval. | |
expiresAt | string | null | When the request stops waiting. The card counts down to it. | |
state | 'pending' | 'approved' | 'denied' | 'expired' | 'pending' | The state of the request. |
decidedBy | string | null | Who decided, or the rule that approved the request. | |
decidedAt | string | null | When the decision was made. |