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

BitbucketCredentialsSettings.tsx

223 lines7.8 KB

1import type { BitbucketSettings, EnvironmentId } from "@t3tools/contracts";
2import { ExternalLinkIcon } from "lucide-react";
3import { useState } from "react";
4​
5import { useEnvironmentSettings } from "../../hooks/useSettings";
6import { serverEnvironment } from "../../state/server";
7import { useAtomCommand } from "../../state/use-atom-command";
8import { Button, InlineButton } from "../ui/button";
9import { Input } from "../ui/input";
10import { Label } from "../ui/label";
11import { Toggle, ToggleGroup } from "../ui/toggle-group";
12​
13type CredentialMethod = "access-token" | "api-token";
14​
15const METHODS: Record<
16 CredentialMethod,
17 {
18 readonly label: string;
19 readonly description: string;
20 readonly link: string;
21 readonly linkLabel: string;
22 }
23> = {
24 "access-token": {
25 label: "Access token",
26 description:
27 "Scoped to one repository, project, or workspace. Create it in that item's Bitbucket settings.",
28 link: "https://support.atlassian.com/bitbucket-cloud/docs/access-tokens/",
29 linkLabel: "Learn more",
30 },
31 "api-token": {
32 label: "API token",
33 description:
34 "Uses your Atlassian account, so it reaches every repository you can. Give it read and write access to repositories and pull requests, and read:user:bitbucket.",
35 link: "https://id.atlassian.com/manage-profile/security/api-tokens",
36 linkLabel: "Create an API token",
37 },
38};
39​
40function savedMethod(saved: BitbucketSettings): CredentialMethod | null {
41 if (saved.accessToken.length > 0) return "access-token";
42 if (saved.email.length > 0 && saved.apiToken.length > 0) return "api-token";
43 return null;
45​
46/** A write-only token field. It never shows the saved token; typing a new one replaces it. */
47function TokenInput({
48 id,
49 isSaved,
50 draft,
51 onDraftChange,
52}: {
53 readonly id: string;
54 readonly isSaved: boolean;
55 readonly draft: string;
56 readonly onDraftChange: (draft: string) => void;
57}) {
58 return (
59 <Input
60 id={id}
61 type="password"
62 autoComplete="off"
63 size="sm"
64 placeholder={isSaved ? "Stored secret, enter a new value to replace" : "Not set"}
65 value={draft}
66 onChange={(event) => onDraftChange(event.target.value)}
67 />
68 );
70​
71/**
72 * Bitbucket credentials for one environment: an access token or an Atlassian
73 * account email + API token, never both. Tokens are write-only: the server
74 * keeps them in its secret store and only reports whether each one is set.
75 */
76export function BitbucketCredentialsSettings({
77 environmentId,
78 onSaved,
79}: {
80 readonly environmentId: EnvironmentId;
81 readonly onSaved: () => void;
82}) {
83 const saved = useEnvironmentSettings(environmentId, (settings) => settings.bitbucket);
84 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
85 label: "save Bitbucket credentials",
86 });
87 const [methodChoice, setMethodChoice] = useState<CredentialMethod | null>(null);
88 const [accessToken, setAccessToken] = useState("");
89 const [emailDraft, setEmailDraft] = useState<string | null>(null);
90 const [apiToken, setApiToken] = useState("");
91 const [saving, setSaving] = useState(false);
92 const current = savedMethod(saved);
93 const method = methodChoice ?? current ?? "access-token";
94 const methodIsSaved = current === method;
95 const email = (emailDraft ?? saved.email).trim();
96 const newAccessToken = accessToken.trim();
97 const newApiToken = apiToken.trim();
98 const info = METHODS[method];
99​
100 // Saving one method clears the other, so a hidden credential never wins over the visible one.
101 const patch: BitbucketSettings | null =
102 method === "access-token"
103 ? newAccessToken
104 ? { accessToken: newAccessToken, email: "", apiToken: "" }
105 : null
106 : email && (newApiToken || saved.apiToken)
107 ? // Resending the saved token's redacted value keeps it.
108 { accessToken: "", email, apiToken: newApiToken || saved.apiToken }
109 : null;
110 const canSave =
111 patch !== null &&
112 (method === "access-token" || !methodIsSaved || newApiToken !== "" || email !== saved.email);
113​
114 const save = async (next: BitbucketSettings) => {
115 setSaving(true);
116 try {
117 const result = await updateSettings({
118 environmentId,
119 input: { patch: { bitbucket: next } },
120 });
121 if (result._tag === "Success") {
122 setAccessToken("");
123 setApiToken("");
124 setEmailDraft(null);
125 onSaved();
126 }
127 } finally {
128 setSaving(false);
129 }
130 };
131​
132 return (
133 <form
134 className="grid gap-4"
135 onSubmit={(event) => {
136 event.preventDefault();
137 if (canSave && patch) void save(patch);
138 }}
139 >
140 {/* Locked while saving: a successful save clears the drafts, which would drop edits made mid-request. */}
141 <fieldset disabled={saving} className="contents">
142 <ToggleGroup
143 aria-label="Bitbucket sign-in method"
144 variant="segmented"
145 value={[method]}
146 onValueChange={(next) => {
147 const value = next[0];
148 if (value === "access-token" || value === "api-token") setMethodChoice(value);
149 }}
150 >
151 <Toggle value="access-token">{METHODS["access-token"].label}</Toggle>
152 <Toggle value="api-token">{METHODS["api-token"].label}</Toggle>
153 </ToggleGroup>
154 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
155 {info.description}{" "}
156 <InlineButton render={<a href={info.link} target="_blank" rel="noreferrer noopener" />}>
157 {info.linkLabel}
158 <ExternalLinkIcon aria-hidden className="size-3" />
159 </InlineButton>
160 </p>
161 {method === "access-token" ? (
162 <div className="grid gap-1.5">
163 <Label htmlFor={`bitbucket-access-token-${environmentId}`}>Access token</Label>
164 <TokenInput
165 id={`bitbucket-access-token-${environmentId}`}
166 isSaved={methodIsSaved}
167 draft={accessToken}
168 onDraftChange={setAccessToken}
169 />
170 </div>
171 ) : (
172 <>
173 <div className="grid gap-1.5">
174 <Label htmlFor={`bitbucket-email-${environmentId}`}>Atlassian account email</Label>
175 <Input
176 id={`bitbucket-email-${environmentId}`}
177 type="email"
178 autoComplete="off"
179 size="sm"
180 placeholder="you@example.com"
181 value={emailDraft ?? saved.email}
182 onChange={(event) => setEmailDraft(event.target.value)}
183 />
184 </div>
185 <div className="grid gap-1.5">
186 <Label htmlFor={`bitbucket-api-token-${environmentId}`}>API token</Label>
187 <TokenInput
188 id={`bitbucket-api-token-${environmentId}`}
189 isSaved={methodIsSaved}
190 draft={apiToken}
191 onDraftChange={setApiToken}
192 />
193 </div>
194 </>
195 )}
196 <div className="flex items-center justify-between gap-3">
197 <p className="text-xs text-muted-foreground">
198 {current === null
199 ? "Without a saved token, the server falls back to its T3CODE_BITBUCKET_* environment variables."
200 : methodIsSaved
201 ? null
202 : `Saving replaces your ${METHODS[current].label.toLowerCase()}.`}
203 </p>
204 <div className="flex shrink-0 gap-2">
205 {current !== null ? (
206 <Button
207 size="xs"
208 variant="outline"
209 disabled={saving}
210 onClick={() => void save({ accessToken: "", email: "", apiToken: "" })}
211 >
212 Remove
213 </Button>
214 ) : null}
215 <Button type="submit" size="xs" disabled={!canSave || saving}>
216 Save
217 </Button>
218 </div>
219 </div>
220 </fieldset>
221 </form>
222 );