Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SecretRequestCard.tsx

381 lines13.1 KB

1import { pipe } from "effect/Function";
2import {
3 secretRequestAnswerInput,
4 secretRequestDisplay,
5 secretRequestFailureMessage,
6 secretRequestInputs,
7 secretRequestLink,
8 secretRequestPrivacyNote,
9 secretRequestReference,
10 secretRequestSources,
11 secretRequestValue,
12 type SecretRequestInput,
13 type SecretRequestItem,
14 type SecretRequestReply,
15 type SecretRequestSource,
16} from "@t3tools/client-runtime/secret-request";
17import {
18 isAtomCommandInterrupted,
19 squashAtomCommandFailure,
20} from "@t3tools/client-runtime/state/runtime";
21import {
22 AuthProvidersManageScope,
23 type EnvironmentId,
24 type OrchestrationV2ProjectedTurnItem,
25 type SecretProviderId,
26} from "@t3tools/contracts";
27import { useAtomValue } from "@effect/atom-react";
28import { hasFeatureFlag } from "@t3tools/client-runtime/state/server";
29import { T, useGT, useMessages, Var } from "gt-react";
30import {
31 CheckIcon,
32 ExternalLinkIcon,
33 EyeIcon,
34 EyeOffIcon,
35 LockIcon,
36 MinusIcon,
37 ShieldCheckIcon,
38} from "lucide-react";
39import { useId, useRef, useState, type FormEvent } from "react";
40import { flushSync } from "react-dom";
41​
42import { serverEnvironment } from "../../state/server";
43import { useEnvironmentScope } from "../../state/session";
44import { useAtomCommand } from "../../state/use-atom-command";
45import { Button } from "../ui/button";
46import { Input } from "../ui/input";
47import { InputGroup, InputGroupAddon, InputGroupInput } from "../ui/input-group";
48import { SecretSourceSelect } from "../settings/SecretSourceInput";
49import { WorkLogRow } from "./WorkLog";
50​
51export function SecretRequestCard(props: {
52 readonly environmentId: EnvironmentId;
53 readonly item: SecretRequestItem;
54 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
55}) {
56 const { item } = props;
57 const messages = useMessages();
58 const display = secretRequestDisplay(item, props.visibility, messages);
59 if (display.kind === "answered" || display.kind === "pending-elsewhere") {
60 const Icon =
61 display.kind === "pending-elsewhere"
62 ? LockIcon
63 : display.outcome === "saved"
64 ? CheckIcon
65 : MinusIcon;
66 return (
67 <WorkLogRow
68 data-v2-item-type={item.type}
69 icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
70 label={
71 <>
72 {item.label} · {display.label}
73 </>
74 }
75 />
76 );
77 }
78 return <PendingSecretRequestForm environmentId={props.environmentId} item={item} />;
80​
81const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
82​
83function useSecretRequestSources(environmentId: EnvironmentId) {
84 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
85 const messages = useMessages();
86 // The server accepts a reference answer only with this scope; without it the card is typed.
87 const canUseReferences = useEnvironmentScope(environmentId, AuthProvidersManageScope);
88 return canUseReferences && hasFeatureFlag(config, "secretProviders")
89 ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages)
90 : NO_SOURCES;
92​
93function PendingSecretRequestForm(props: {
94 readonly environmentId: EnvironmentId;
95 readonly item: SecretRequestItem;
96}) {
97 const { item } = props;
98 const messages = useMessages();
99 const formId = useId();
100 const errorId = useId();
101 const privacyId = useId();
102 const answer = useAtomCommand(serverEnvironment.answerSecretRequest, {
103 label: "answer secret request",
104 // The failure cause holds the request; keep it out of the console.
105 reportFailure: false,
106 reportDefect: false,
107 });
108 const multiple = item.fields !== undefined;
109 // A reference answers one value, so a card with fields is always typed.
110 const configuredSources = useSecretRequestSources(props.environmentId);
111 const sources = multiple ? NO_SOURCES : configuredSources;
112 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
113 const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
114 const [values, setValues] = useState<Readonly<Record<string, string>>>({});
115 const [reference, setReference] = useState("");
116 const [submitting, setSubmitting] = useState(false);
117 const [error, setError] = useState<string | null>(null);
118 // Enter and click can both submit before a render.
119 const inFlight = useRef(false);
120 const inputs = secretRequestInputs(item, messages);
121 const inputId = (index: number) => `${formId}-${index}`;
122 const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId;
123 const canSave =
124 source === null
125 ? secretRequestAnswerInput(item, { type: "save", values }) !== null
126 : reference.trim().length > 0;
127​
128 const send = async (reply: SecretRequestReply) => {
129 const input = secretRequestAnswerInput(item, reply);
130 if (input === null || inFlight.current) return;
131 inFlight.current = true;
132 setSubmitting(true);
133 setError(null);
134 // A password field that leaves the page with text in it can prompt to save a login,
135 // so the card is emptied before it closes; a failed answer puts the values back.
136 const typed = values;
137 setValues({});
138 const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
139 inFlight.current = false;
140 setSubmitting(false);
141 });
142 if (result._tag === "Success") {
143 setReference("");
144 return;
145 }
146 setValues(typed);
147 if (!isAtomCommandInterrupted(result)) {
148 pipe(
149 squashAtomCommandFailure(result),
150 (failure) => secretRequestFailureMessage(failure, messages),
151 setError,
152 );
153 }
154 };
155​
156 const onSubmit = (event: FormEvent<HTMLFormElement>) => {
157 event.preventDefault();
158 if (source === null) {
159 void send({ type: "save", values });
160 } else if (secretRequestReference(source, reference) === undefined) {
161 setError(source.invalidReferenceMessage);
162 } else {
163 void send({ type: "reference", source, reference });
164 }
165 };
166​
167 const link = secretRequestLink(item);
168 const field = (input: SecretRequestInput, index: number) => (
169 <SecretRequestField
170 key={input.key}
171 id={inputId(index)}
172 input={input}
173 // A single input is labelled by the card title.
174 label={multiple ? input.label : undefined}
175 value={secretRequestValue(values, input.key)}
176 disabled={submitting}
177 invalid={error !== null}
178 describedBy={describedBy}
179 onChange={(value) => setValues((current) => ({ ...current, [input.key]: value }))}
180 />
181 );
182 const saveButton = (
183 <Button type="submit" disabled={submitting || !canSave}>
184 <T>Save securely</T>
185 </Button>
186 );
187​
188 return (
189 <form
190 data-v2-item-type={item.type}
191 className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
192 onSubmit={onSubmit}
193 autoComplete="off"
194 // On click, not pointerdown: the mousedown that follows a pointerdown
195 // moves focus back off the input. A click that ends a text selection
196 // leaves it alone so the reason can still be copied.
197 onClick={(event) => {
198 if (!(event.target instanceof Element)) return;
199 if (event.target.closest("input, button, a")) return;
200 if (window.getSelection()?.isCollapsed === false) return;
201 const empty = inputs.findIndex((input) => !secretRequestValue(values, input.key).trim());
202 document.getElementById(inputId(Math.max(empty, 0)))?.focus();
203 }}
204 >
205 <div className="flex min-w-0 flex-col gap-1">
206 {multiple ? (
207 <p className="text-sm font-medium text-foreground">{item.label}</p>
208 ) : (
209 <label htmlFor={inputId(0)} className="text-sm font-medium text-foreground">
210 {item.label}
211 </label>
212 )}
213 {item.reason.trim() ? (
214 <p className="text-sm wrap-anywhere text-muted-foreground">{item.reason}</p>
215 ) : null}
216 </div>
217 {link !== null ? (
218 <div className="flex min-w-0 flex-col items-start gap-1.5">
219 <Button
220 variant="outline"
221 size="sm"
222 render={<a href={link.href} target="_blank" rel="noopener noreferrer" />}
223 >
224 <T>
225 Open <Var>{link.host}</Var>
226 </T>
227 <ExternalLinkIcon aria-hidden />
228 </Button>
229 {/* A link found in the reason is already shown there. */}
230 {item.url !== undefined ? (
231 <p className="font-mono text-xs wrap-anywhere text-muted-foreground">{item.url}</p>
232 ) : null}
233 </div>
234 ) : null}
235 {multiple ? (
236 <div className="flex min-w-0 flex-col gap-2.5">{inputs.map(field)}</div>
237 ) : (
238 <div className="flex min-w-0 items-center gap-2">
239 {sources.length > 0 ? (
240 <SecretSourceSelect
241 value={source?.id ?? null}
242 sources={sources}
243 label={item.label}
244 disabled={submitting}
245 onValueChange={(next) => {
246 setSourceId(next);
247 setError(null);
248 }}
249 />
250 ) : null}
251 <div className="min-w-0 flex-1">
252 {source === null ? (
253 inputs.map(field)
254 ) : (
255 <Input
256 id={inputId(0)}
257 font="mono"
258 autoComplete="off"
259 autoCorrect="off"
260 autoCapitalize="off"
261 spellCheck={false}
262 placeholder={source.referencePlaceholder}
263 value={reference}
264 disabled={submitting}
265 aria-invalid={error !== null || undefined}
266 aria-describedby={describedBy}
267 onChange={(event) => {
268 setReference(event.currentTarget.value);
269 setError(null);
270 }}
271 />
272 )}
273 </div>
274 {saveButton}
275 </div>
276 )}
277 {error !== null ? (
278 <p id={errorId} role="alert" className="text-xs text-destructive">
279 {error}
280 </p>
281 ) : null}
282 <div className="flex min-w-0 flex-wrap items-center justify-between gap-2">
283 <p
284 id={privacyId}
285 className="flex min-w-0 grow basis-52 items-center gap-1.5 text-xs text-muted-foreground"
286 >
287 <ShieldCheckIcon className="size-3.5 shrink-0" aria-hidden />
288 {secretRequestPrivacyNote(item, messages)}
289 </p>
290 <div className="ms-auto flex shrink-0 items-center gap-2">
291 <Button
292 type="button"
293 size="xs"
294 variant="ghost-muted"
295 disabled={submitting}
296 onClick={() => void send({ type: "decline" })}
297 >
298 <T>Decline</T>
299 </Button>
300 {multiple ? saveButton : null}
301 </div>
302 </div>
303 </form>
304 );
306​
307function SecretRequestField(props: {
308 readonly id: string;
309 readonly input: SecretRequestInput;
310 readonly label: string | undefined;
311 readonly value: string;
312 readonly disabled: boolean;
313 readonly invalid: boolean;
314 readonly describedBy: string;
315 readonly onChange: (value: string) => void;
316}) {
317 const { input } = props;
318 const gt = useGT();
319 const [revealed, setRevealed] = useState(false);
320 const inputRef = useRef<HTMLInputElement>(null);
321 const masked = input.secret && !revealed;
322 const toggleRevealed = () => {
323 const field = inputRef.current;
324 const start = field?.selectionStart ?? null;
325 const end = field?.selectionEnd ?? null;
326 flushSync(() => setRevealed((current) => !current));
327 // After a click changes a focused input's type, Chromium moves the caret to the
328 // start unless the new type is laid out before the selection is restored.
329 field?.getBoundingClientRect();
330 field?.setSelectionRange(start, end);
331 };
332 const control = (
333 <InputGroup>
334 <InputGroupInput
335 ref={inputRef}
336 id={props.id}
337 // A CSS-masked text field still exposes its value to screen readers.
338 type={masked ? "password" : "text"}
339 autoComplete="off"
340 autoCorrect="off"
341 autoCapitalize="off"
342 spellCheck={false}
343 data-1p-ignore
344 data-lpignore="true"
345 data-bwignore
346 placeholder={input.placeholder}
347 value={props.value}
348 disabled={props.disabled}
349 aria-invalid={props.invalid || undefined}
350 aria-describedby={props.describedBy}
351 onChange={(event) => props.onChange(event.currentTarget.value)}
352 />
353 {input.secret ? (
354 <InputGroupAddon align="inline-end">
355 <Button
356 type="button"
357 size="icon-xs"
358 variant="ghost"
359 aria-label={gt("Show {label}", { label: input.label })}
360 aria-pressed={revealed}
361 disabled={props.disabled}
362 // Keep focus, and the caret, in the input.
363 onMouseDown={(event) => event.preventDefault()}
364 onClick={toggleRevealed}
365 >
366 {revealed ? <EyeOffIcon aria-hidden /> : <EyeIcon aria-hidden />}
367 </Button>
368 </InputGroupAddon>
369 ) : null}
370 </InputGroup>
371 );
372 if (props.label === undefined) return control;
373 return (
374 <div className="flex min-w-0 flex-col gap-1">
375 <label htmlFor={props.id} className="text-xs font-medium text-muted-foreground">
376 {props.label}
377 </label>
378 {control}
379 </div>
380 );