Open History to see the last commit
1import { pipe } from "effect/Function";
2import {
3 SECRET_REQUEST_DEFAULT_PLACEHOLDER,
4 secretRequestAnswerInput,
5 secretRequestDisplay,
6 secretRequestFailureMessage,
7 secretRequestLink,
8 secretRequestPrivacyNote,
9 secretRequestReference,
10 secretRequestSources,
11 type SecretRequestItem,
12 type SecretRequestReply,
13 type SecretRequestSource,
14} from "@t3tools/client-runtime/secret-request";
15import {
16 isAtomCommandInterrupted,
17 squashAtomCommandFailure,
18} from "@t3tools/client-runtime/state/runtime";
19import type {
20 EnvironmentId,
21 OrchestrationV2ProjectedTurnItem,
22 SecretProviderId,
23} from "@t3tools/contracts";
24import { useAtomValue } from "@effect/atom-react";
25import { T, useMessages, Var } from "gt-react";
26import { CheckIcon, ExternalLinkIcon, LockIcon, MinusIcon, ShieldCheckIcon } from "lucide-react";
27import { useId, useRef, useState, type FormEvent } from "react";
28
29import { isSecretsFeatureEnabled } from "../../env";
30import { serverEnvironment } from "../../state/server";
31import { useAtomCommand } from "../../state/use-atom-command";
32import { Button } from "../ui/button";
33import { Input } from "../ui/input";
34import { SecretSourceSelect } from "../settings/SecretSourceInput";
35import { WorkLogRow } from "./WorkLog";
36
37export function SecretRequestCard(props: {
38 readonly environmentId: EnvironmentId;
39 readonly item: SecretRequestItem;
40 readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"];
41}) {
42 const { item } = props;
43 const messages = useMessages();
44 const display = secretRequestDisplay(item, props.visibility, messages);
45 if (display.kind === "answered" || display.kind === "pending-elsewhere") {
46 const Icon =
47 display.kind === "pending-elsewhere"
48 ? LockIcon
49 : display.outcome === "saved"
50 ? CheckIcon
51 : MinusIcon;
52 return (
53 <WorkLogRow
54 data-v2-item-type={item.type}
55 icon={<Icon className="size-3.5 text-icon-muted" aria-hidden />}
56 label={
57 <>
58 {item.label} · {display.label}
59 </>
60 }
61 />
62 );
63 }
64 return <PendingSecretRequestForm environmentId={props.environmentId} item={item} />;
65}
66
67const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
68
69function useSecretRequestSources(environmentId: EnvironmentId) {
70 const config = useAtomValue(serverEnvironment.configValueAtom(environmentId));
71 const messages = useMessages();
72 return isSecretsFeatureEnabled
73 ? secretRequestSources(config, config?.settings.secretProviders ?? {}, messages)
74 : NO_SOURCES;
75}
76
77function PendingSecretRequestForm(props: {
78 readonly environmentId: EnvironmentId;
79 readonly item: SecretRequestItem;
80}) {
81 const { item } = props;
82 const messages = useMessages();
83 const inputId = useId();
84 const errorId = useId();
85 const privacyId = useId();
86 const answer = useAtomCommand(serverEnvironment.answerSecretRequest, {
87 label: "answer secret request",
88 // The failure cause holds the request; keep it out of the console.
89 reportFailure: false,
90 reportDefect: false,
91 });
92 const sources = useSecretRequestSources(props.environmentId);
93 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
94 const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
95 const [secret, setSecret] = useState("");
96 const [reference, setReference] = useState("");
97 const [submitting, setSubmitting] = useState(false);
98 const [error, setError] = useState<string | null>(null);
99 // Enter and click can both submit before a render.
100 const inFlight = useRef(false);
101
102 const send = async (reply: SecretRequestReply) => {
103 const input = secretRequestAnswerInput(item, reply);
104 if (input === null || inFlight.current) return;
105 inFlight.current = true;
106 setSubmitting(true);
107 setError(null);
108 const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
109 inFlight.current = false;
110 setSubmitting(false);
111 });
112 if (result._tag === "Success") {
113 setSecret("");
114 setReference("");
115 return;
116 }
117 if (!isAtomCommandInterrupted(result)) {
118 pipe(
119 squashAtomCommandFailure(result),
120 (failure) => secretRequestFailureMessage(failure, messages),
121 setError,
122 );
123 }
124 };
125
126 const onSubmit = (event: FormEvent<HTMLFormElement>) => {
127 event.preventDefault();
128 if (source === null) {
129 void send({ type: "save", secret });
130 } else if (secretRequestReference(source, reference) === undefined) {
131 setError(source.invalidReferenceMessage);
132 } else {
133 void send({ type: "reference", source, reference });
134 }
135 };
136 const draft = source === null ? secret : reference;
137 const link = secretRequestLink(item);
138 const describedBy = error !== null ? `${privacyId} ${errorId}` : privacyId;
139
140 return (
141 <form
142 data-v2-item-type={item.type}
143 className="flex min-w-0 flex-col gap-3 rounded-xl border border-border/60 bg-card p-4"
144 onSubmit={onSubmit}
145 autoComplete="off"
146 // On click, not pointerdown: the mousedown that follows a pointerdown
147 // moves focus back off the input. A click that ends a text selection
148 // leaves it alone so the reason can still be copied.
149 onClick={(event) => {
150 if (!(event.target instanceof Element)) return;
151 if (event.target.closest("input, button, a")) return;
152 if (window.getSelection()?.isCollapsed === false) return;
153 document.getElementById(inputId)?.focus();
154 }}
155 >
156 <div className="flex min-w-0 flex-col gap-1">
157 <label htmlFor={inputId} className="text-sm font-medium text-foreground">
158 {item.label}
159 </label>
160 {item.reason.trim() ? (
161 <p className="text-sm wrap-anywhere text-muted-foreground">{item.reason}</p>
162 ) : null}
163 </div>
164 {link !== null ? (
165 <div className="flex min-w-0 flex-col items-start gap-1.5">
166 <Button
167 variant="outline"
168 size="sm"
169 render={<a href={link.href} target="_blank" rel="noopener noreferrer" />}
170 >
171 <T>
172 Open <Var>{link.host}</Var>
173 </T>
174 <ExternalLinkIcon aria-hidden />
175 </Button>
176 {/* A link found in the reason is already shown there. */}
177 {item.url !== undefined ? (
178 <p className="font-mono text-xs wrap-anywhere text-muted-foreground">{item.url}</p>
179 ) : null}
180 </div>
181 ) : null}
182 <div className="flex min-w-0 items-center gap-2">
183 {sources.length > 0 ? (
184 <SecretSourceSelect
185 value={source?.id ?? null}
186 sources={sources}
187 label={item.label}
188 disabled={submitting}
189 onValueChange={(next) => {
190 setSourceId(next);
191 setError(null);
192 }}
193 />
194 ) : null}
195 <div className="min-w-0 flex-1">
196 {source === null ? (
197 <Input
198 id={inputId}
199 // A CSS-masked text field still exposes its value to screen readers.
200 type="password"
201 autoComplete="off"
202 autoCorrect="off"
203 autoCapitalize="off"
204 spellCheck={false}
205 data-1p-ignore
206 data-lpignore="true"
207 data-bwignore
208 placeholder={item.placeholder ?? messages(SECRET_REQUEST_DEFAULT_PLACEHOLDER)}
209 value={secret}
210 disabled={submitting}
211 aria-invalid={error !== null || undefined}
212 aria-describedby={describedBy}
213 onChange={(event) => setSecret(event.currentTarget.value)}
214 />
215 ) : (
216 <Input
217 id={inputId}
218 font="mono"
219 autoComplete="off"
220 autoCorrect="off"
221 autoCapitalize="off"
222 spellCheck={false}
223 placeholder={source.referencePlaceholder}
224 value={reference}
225 disabled={submitting}
226 aria-invalid={error !== null || undefined}
227 aria-describedby={describedBy}
228 onChange={(event) => {
229 setReference(event.currentTarget.value);
230 setError(null);
231 }}
232 />
233 )}
234 </div>
235 <Button type="submit" disabled={submitting || draft.trim().length === 0}>
236 <T>Save securely</T>
237 </Button>
238 </div>
239 {error !== null ? (
240 <p id={errorId} role="alert" className="text-xs text-destructive">
241 {error}
242 </p>
243 ) : null}
244 <div className="flex min-w-0 items-center justify-between gap-2">
245 <p
246 id={privacyId}
247 className="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
248 >
249 <ShieldCheckIcon className="size-3.5 shrink-0" aria-hidden />
250 {secretRequestPrivacyNote(item, messages)}
251 </p>
252 <Button
253 type="button"
254 size="xs"
255 variant="ghost-muted"
256 disabled={submitting}
257 onClick={() => void send({ type: "decline" })}
258 >
259 <T>Decline</T>
260 </Button>
261 </div>
262 </form>
263 );
264}