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

SecretRequestCard.tsx

236 lines8.0 KB

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