"use client";import * as React from "react";import { NumberRoll } from "./number-roll";import { SudoGateMark } from "./sudo-gate-mark";import { SudoGatePanel, type SudoMethod, type SudoProof } from "./sudo-gate-panel";import { TextMorph } from "./text-morph";export type { SudoMethod, SudoProof } from "./sudo-gate-panel";/* ───────────────────────────────────────────────────────── * SUDO GATE: a dangerous button that knows if you're still you * * badge a small padlock sits on the button's corner. While * you're recently verified it's open, inside a ring of * the time left ("8 min", then "42s", the last minute * amber); when the time is up the shackle drops shut * ask click a locked button and it grows where it stands: * the button itself widens and deepens into the card * "Confirm it's you", pushing what's around it aside, * its label giving way to the question * unlock the big padlock swings open, the card folds back down * into the button with the small padlock riding its * corner, its ring filling, and your click goes through * share every gate on the page shares one trust window: verify * once and every other badge fills up too * * Wrap the app's own button. The gate stops its click until you're * verified, then clicks it for you; the button, its handler and the * request stay the app's. Always check freshness on the server too. * ───────────────────────────────────────────────────────── */export interface SudoGateProps { /** The app's own button (or link). Its click is held until you're verified. */ children: React.ReactElement<{ "aria-describedby"?: string }>; /** Checks the proof with your auth. Resolve to unlock (optionally with when the trust ends, as a Date or ms); throw to say why not. */ verify: (proof: SudoProof) => Promise<unknown>; /** When the current trust ends, from your session (e.g. createdAt + freshAge). Leave out to start locked. */ freshUntil?: Date | number | null; /** How long a verification lasts, in seconds, when verify doesn't say. */ trustFor?: number; /** The ways to verify, first one shown first. */ methods?: SudoMethod[]; /** Sends the one-time code; called as the code view opens and on resend. */ sendCode?: () => Promise<unknown>; /** Where the code went, e.g. "mira@northwind.com". */ codeHint?: string; /** Why this action asks, shown under "Confirm it's you". */ reason?: string; /** Gates with the same scope share one trust window. */ scope?: string; /** Hide the corner badge (the gate still asks). */ badge?: boolean; className?: string;}/* ── One trust window per scope, shared by every gate on the page ── */const trust = new Map<string, number>();// When each window was set, so a badge whose clock last ticked before it never counts from a stale time.const setAt = new Map<string, number>();const listeners = new Set<() => void>();function setTrust(scope: string, until: number) { if (trust.get(scope) === until) return; trust.set(scope, until); setAt.set(scope, Date.now()); listeners.forEach((l) => l());}const subscribeTrust = (l: () => void) => { listeners.add(l); return () => { listeners.delete(l); };};/** Locks every gate in a scope now, e.g. when your server answers that the session isn't fresh, or on sign-out. */export function expireSudo(scope = "session") { setTrust(scope, 0);}const toMs = (v: Date | number) => (typeof v === "number" ? v : v.getTime());const reducedQuery = "(prefers-reduced-motion: reduce)";const subscribeReduced = (onChange: () => void) => { const query = window.matchMedia(reducedQuery); query.addEventListener("change", onChange); return () => query.removeEventListener("change", onChange);};const useReducedMotion = () => React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);const EASE = "cubic-bezier(0.16,1,0.3,1)";const GROW = 520;const FOLD = 440;const CARD_W = 360;const RADIUS = 22;const METHODS: SudoMethod[] = ["passkey", "code"];/** The button's size and look, so the card can start and end as it. */interface Origin { width: number; height: number; radius: number; bg: string;}function originOf(target: HTMLElement): Origin { const style = getComputedStyle(target); const transparent = /rgba?\(\s*0,\s*0,\s*0,\s*0\s*\)|transparent/.test(style.backgroundColor); return { width: target.offsetWidth, height: target.offsetHeight, radius: Math.min(parseFloat(style.borderTopLeftRadius) || 0, target.offsetHeight / 2), bg: transparent ? "var(--background)" : style.backgroundColor, };}/** The padlock on the button's corner. It owns the per-second clock, so the app's button never re-renders with it. */function Badge({ until, since, trustFor, reduced, hidden, ringRef, landedRef,}: { until: number; since: number; trustFor: number; reduced: boolean; hidden: boolean; ringRef: React.RefObject<HTMLSpanElement | null>; landedRef: React.RefObject<boolean>;}) { const [now, setNow] = React.useState<number | null>(null); const arcRef = React.useRef<SVGCircleElement>(null); // Wakes once a second, on the second, only while trusted. React.useEffect(() => { const t0 = Date.now(); const delay = now === null ? 0 : until > t0 ? 1000 - (t0 % 1000) + 5 : -1; if (delay < 0) return; const t = window.setTimeout(() => setNow(Date.now()), delay); return () => window.clearTimeout(t); }, [now, until]); const left = now === null ? 0 : Math.max(0, until - Math.max(now, since)); const fresh = left > 0; const secs = Math.ceil(left / 1000); const ending = fresh && secs < 60; const shown = ending ? { n: secs, unit: "s" } : { n: Math.ceil(secs / 60), unit: "min" }; // The ring drains in one long animation; a new window fills it first (other gates), or starts it full (the one you just unlocked). React.useLayoutEffect(() => { const arc = arcRef.current; if (!arc) return; const read = parseFloat(getComputedStyle(arc).strokeDashoffset); const current = Number.isNaN(read) ? 1 : read; arc.getAnimations().forEach((a) => a.cancel()); if (!fresh) { if (current < 1 && !reduced) arc.animate([{ strokeDashoffset: current }, { strokeDashoffset: 1 }], { duration: 300, easing: EASE }); return; } const rest = until - Date.now(); const from = 1 - Math.min(1, rest / (trustFor * 1000)); const fill = landedRef.current || reduced ? 0 : 600; landedRef.current = false; arc.animate( fill ? [{ strokeDashoffset: current, easing: EASE }, { strokeDashoffset: from, offset: fill / (fill + rest), easing: "linear" }, { strokeDashoffset: 1 }] : [{ strokeDashoffset: from }, { strokeDashoffset: 1 }], { duration: fill + rest, fill: "forwards" }, ); }, [fresh, until, trustFor, reduced, landedRef]); return ( <span aria-hidden="true" className="pointer-events-none absolute -top-[11px] right-2.5 z-[1] flex h-[22px] items-center rounded-full bg-background p-px shadow-[0_0_0_1px_var(--border)]" // While the button is open as the card, its padlock is the big one inside; the badge comes back as the card folds. style={{ opacity: hidden ? 0 : 1, transition: reduced ? "none" : `opacity ${hidden ? 120 : 240}ms ${EASE}` }} > {/* The time sits to the padlock's left and folds toward it, so the padlock never moves off its corner. */} <span className="grid" style={{ gridTemplateColumns: fresh ? "1fr" : "0fr", opacity: fresh ? 1 : 0, filter: fresh || reduced ? "none" : "blur(3px)", transition: reduced ? "none" : `grid-template-columns 420ms ${EASE}, opacity ${fresh ? 320 : 160}ms ${EASE}, filter 320ms ${EASE}`, }} > <span className="flex min-w-0 justify-end [clip-path:inset(-2px_0_-2px_0)]"> <span className="flex w-max items-center pl-[7px] pr-[3px] text-[11px] font-medium leading-[14px] tabular-nums text-foreground"> <NumberRoll value={shown.n} direction="down" duration={700} /> <TextMorph className={shown.unit === "min" ? "ml-[2px]" : ""}>{shown.unit}</TextMorph> </span> </span> </span> <span ref={ringRef} className="block size-5 shrink-0"> <SudoGateMark open={fresh} ending={ending} reduced={reduced} arcRef={arcRef} className="size-5" /> </span> </span> );}export function SudoGate({ children, verify, freshUntil, trustFor = 600, methods = METHODS, sendCode, codeHint, reason = "This action needs a recent sign-in.", scope = "session", badge = true, className = "",}: SudoGateProps) { const reduced = useReducedMotion(); const until = React.useSyncExternalStore(subscribeTrust, () => trust.get(scope) ?? 0, () => 0); const [now, setNow] = React.useState<number | null>(null); const [phase, setPhase] = React.useState<"closed" | "opening" | "open" | "closing">("closed"); const [origin, setOrigin] = React.useState<Origin | null>(null); const [cardW, setCardW] = React.useState(CARD_W); const [height, setHeight] = React.useState<number | null>(null); const [verified, setVerified] = React.useState(false); const [said, setSaid] = React.useState(""); const [run, setRun] = React.useState(0); const wrapRef = React.useRef<HTMLSpanElement>(null); const targetRef = React.useRef<HTMLElement | null>(null); const cloneRef = React.useRef<HTMLElement | null>(null); const holderRef = React.useRef<HTMLSpanElement>(null); const contentRef = React.useRef<HTMLDivElement>(null); const markRef = React.useRef<HTMLSpanElement>(null); const ringRef = React.useRef<HTMLSpanElement>(null); const pass = React.useRef(false); const landedRef = React.useRef(false); const timers = React.useRef<number[]>([]); const descId = React.useId(); const titleId = React.useId(); // The server's word on freshness, whenever it changes. const seed = freshUntil == null ? null : toMs(freshUntil); React.useEffect(() => { if (seed !== null) setTrust(scope, seed); }, [seed, scope]); // The gate only needs to know when the window opens and when it runs out; the badge keeps its own clock. React.useEffect(() => { const t = window.setTimeout(() => setNow(Date.now()), 0); return () => window.clearTimeout(t); }, [until]); React.useEffect(() => { if (now === null || until <= now) return; const t = window.setTimeout(() => setNow(Date.now()), until - now + 5); return () => window.clearTimeout(t); }, [now, until]); React.useEffect(() => { const list = timers.current; return () => { list.forEach((t) => window.clearTimeout(t)); if (targetRef.current) targetRef.current.style.visibility = ""; }; }, []); const fresh = now !== null && until > now; const isOpen = phase === "open"; const showing = phase !== "closed"; // Growing: one frame at the button's size, then the card's. React.useLayoutEffect(() => { if (phase !== "opening") return; let f2 = 0; const f1 = requestAnimationFrame(() => { f2 = requestAnimationFrame(() => setPhase("open")); }); return () => { cancelAnimationFrame(f1); cancelAnimationFrame(f2); }; }, [phase]); // The button's own look sits at the top of the card while it grows, then gives way to the question. React.useLayoutEffect(() => { const holder = holderRef.current; const clone = cloneRef.current; if (!showing || !holder || !clone || holder.contains(clone)) return; holder.replaceChildren(clone); }, [showing]); // The card's height follows its content (a view switch, an error line, the code boxes). React.useLayoutEffect(() => { const el = contentRef.current; if (!showing || !el) return; const measure = () => setHeight((h) => (h === el.offsetHeight ? h : el.offsetHeight)); measure(); const ro = new ResizeObserver(measure); ro.observe(el); return () => ro.disconnect(); }, [showing]); /** Back down into the button, where it stands. */ const fold = React.useCallback( (refocus: boolean) => { const target = targetRef.current; if (!target) return; setPhase("closing"); timers.current.push( window.setTimeout( () => { setPhase("closed"); setVerified(false); setHeight(null); target.style.visibility = ""; if (refocus) target.focus({ preventScroll: true }); }, reduced ? 0 : FOLD, ), ); }, [reduced], ); // While open: Escape, a press elsewhere or focus leaving folds it back. React.useEffect(() => { if (phase !== "open") return; const down = (e: PointerEvent) => { if (!wrapRef.current?.contains(e.target as Node)) fold(false); }; document.addEventListener("pointerdown", down); return () => document.removeEventListener("pointerdown", down); }, [phase, fold]); const ask = (target: HTMLElement) => { targetRef.current = target; const o = originOf(target); // As wide as the card wants, never wider than the screen; whatever sits around it makes room. const room = window.innerWidth - 32; const clone = target.cloneNode(true) as HTMLElement; clone.removeAttribute("id"); clone.querySelectorAll("[id]").forEach((n) => n.removeAttribute("id")); clone.setAttribute("aria-hidden", "true"); clone.setAttribute("inert", ""); Object.assign(clone.style, { margin: "0", pointerEvents: "none", visibility: "visible", width: `${o.width}px`, height: `${o.height}px`, flexShrink: "0" }); cloneRef.current = clone; setOrigin(o); setCardW(Math.max(o.width, Math.min(CARD_W, room))); setVerified(false); setSaid(""); setRun((r) => r + 1); target.style.visibility = "hidden"; setPhase(reduced ? "open" : "opening"); }; const attempt = async (proof: SudoProof) => { const result = await verify(proof); const told = result instanceof Date || typeof result === "number" ? toMs(result) : null; const nextUntil = told ?? Date.now() + trustFor * 1000; setVerified(true); const secs = Math.round((nextUntil - Date.now()) / 1000); setSaid(`Verified. Unlocked for ${secs >= 90 ? `${Math.round(secs / 60)} minutes` : `${secs} seconds`}.`); timers.current.push( window.setTimeout( () => { const target = targetRef.current; // The card folds, and the small padlock rides its corner back down, its ring filling. fold(false); setTrust(scope, nextUntil); setNow(Date.now()); // With the button back, the click you made goes through to the app's own handler. timers.current.push( window.setTimeout( () => { if (!target) return; target.focus({ preventScroll: true }); pass.current = true; target.click(); pass.current = false; }, reduced ? 20 : FOLD + 40, ), ); }, reduced ? 200 : 760, ), ); }; const onClickCapture = (e: React.MouseEvent<HTMLSpanElement>) => { if (pass.current) return; const t = e.target as HTMLElement; const own = wrapRef.current?.firstElementChild; if (!own?.contains(t)) return; if (!showing && Date.now() < until) { ringRef.current?.animate([{ transform: "none" }, { transform: "scale(1.12)" }, { transform: "none" }], { duration: 300, easing: EASE }); return; } e.preventDefault(); e.stopPropagation(); if (showing) return; const target = (t.closest("button, a, [role='button'], input[type='submit']") as HTMLElement | null) ?? (own as HTMLElement); if (own.contains(target) || own === target) ask(target); }; const describedBy = [children.props["aria-describedby"], descId].filter(Boolean).join(" "); const grow = (prop: string) => `${prop} ${isOpen ? GROW : FOLD}ms ${EASE}`; const size = !showing || !origin ? undefined : isOpen || (reduced && phase !== "closing") ? { width: cardW, height: height ?? origin.height } : { width: origin.width, height: origin.height }; return ( <span ref={wrapRef} onClickCapture={onClickCapture} className={`relative inline-flex align-top ${className}`} // Never squeezed by a flex row it sits in: the card takes its full size and the row makes room. style={size ? { ...size, flexShrink: 0, transition: reduced ? "none" : `${grow("width")}, ${grow("height")}` } : undefined} > {React.cloneElement(children, { "aria-describedby": describedBy })} {showing && origin && ( <div role="group" aria-labelledby={titleId} onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); fold(true); } }} onBlur={(e) => { if (isOpen && !verified && document.hasFocus() && e.relatedTarget && !wrapRef.current?.contains(e.relatedTarget as Node)) fold(false); }} className="absolute inset-0 z-[1] overflow-clip text-popover-foreground" style={{ borderRadius: isOpen ? RADIUS : origin.radius, backgroundColor: isOpen ? "var(--popover)" : origin.bg, boxShadow: "inset 0 0 0 1px var(--border)", transition: reduced ? "none" : `${grow("border-radius")}, ${grow("background-color")}`, }} > {/* The button itself, at the top of the card as it grows, and back again as it folds. */} <span ref={holderRef} aria-hidden="true" className="pointer-events-none absolute left-1/2 top-0 flex" style={{ marginLeft: -origin.width / 2, opacity: isOpen || reduced ? 0 : 1, filter: isOpen && !reduced ? "blur(4px)" : "none", transition: reduced ? "none" : isOpen ? `opacity 140ms ${EASE}, filter 140ms ${EASE}` : `opacity 200ms ${EASE} ${FOLD - 240}ms, filter 200ms ${EASE} ${FOLD - 240}ms`, }} /> <div ref={contentRef} className="absolute left-1/2 top-0" style={{ width: cardW, marginLeft: -cardW / 2, opacity: isOpen ? 1 : 0, filter: isOpen || reduced ? "none" : "blur(6px)", transform: isOpen || reduced ? "none" : "translateY(-8px)", transition: reduced ? "none" : isOpen ? `opacity 300ms ${EASE} 150ms, filter 420ms ${EASE} 150ms, transform 520ms ${EASE} 120ms` : `opacity 120ms ${EASE}, filter 120ms ${EASE}, transform 200ms ${EASE}`, }} > <SudoGatePanel key={run} titleId={titleId} methods={methods} reason={reason} codeHint={codeHint} sendCode={sendCode} attempt={attempt} onCancel={() => fold(true)} verified={verified} reduced={reduced} markRef={markRef} /> </div> </div> )} {badge && <Badge until={until} since={setAt.get(scope) ?? 0} trustFor={trustFor} reduced={reduced} hidden={phase === "open" || phase === "opening"} ringRef={ringRef} landedRef={landedRef} />} <span id={descId} className="sr-only"> {fresh ? "Unlocked: you verified recently." : "Asks you to confirm it's you first."} </span> <span className="sr-only" role="status"> {said} </span> </span> );}