Open History to see the last commit
1import type { EnvironmentId } from "@t3tools/contracts";
2import { ExternalLinkIcon } from "lucide-react";
3import { useState } from "react";
4
5import { useEnvironmentSettings } from "../../hooks/useSettings";
6import { readGitHubSettings } from "@t3tools/client-runtime/source-control-clients";
7import { serverEnvironment } from "../../state/server";
8import { useAtomCommand } from "../../state/use-atom-command";
9import { Button, InlineButton } from "../ui/button";
10import { Input } from "../ui/input";
11import { Label } from "../ui/label";
12
13const DEFAULT_HOST = "github.com";
14
15/** Where to create a token for a host: GitHub's own page, or the same path on an Enterprise host. */
16function newTokenUrl(host: string): string {
17 return `https://${host}/settings/personal-access-tokens/new`;
18}
19
20/**
21 * A GitHub token for one host, kept in the server's secret store. It is used before
22 * `GH_TOKEN` and the `gh` login, so it also works on a server without `gh` installed.
23 * Write-only: the saved token is never shown, only whether one is set.
24 */
25export function GitHubTokenSettings({
26 environmentId,
27 onSaved,
28}: {
29 readonly environmentId: EnvironmentId;
30 readonly onSaved: () => void;
31}) {
32 const { tokens } = useEnvironmentSettings(environmentId, readGitHubSettings);
33 const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {
34 label: "save GitHub token",
35 });
36 const [host, setHost] = useState(DEFAULT_HOST);
37 const [draft, setDraft] = useState("");
38 const [saving, setSaving] = useState(false);
39 const normalizedHost = host.trim().toLowerCase();
40 const isSaved = (tokens[normalizedHost] ?? "").length > 0;
41 const savedHosts = Object.entries(tokens)
42 .filter(([, value]) => value.length > 0)
43 .map(([saved]) => saved);
44
45 const save = async (target: string, token: string) => {
46 setSaving(true);
47 try {
48 const result = await updateSettings({
49 environmentId,
50 // The map travels whole: every other saved token as its redaction marker, which keeps it.
51 input: {
52 patch: { sourceControlHosts: { github: { tokens: { ...tokens, [target]: token } } } },
53 },
54 });
55 if (result._tag === "Success") {
56 setDraft("");
57 onSaved();
58 }
59 } finally {
60 setSaving(false);
61 }
62 };
63
64 return (
65 <form
66 className="grid gap-3"
67 onSubmit={(event) => {
68 event.preventDefault();
69 if (normalizedHost && draft.trim()) void save(normalizedHost, draft.trim());
70 }}
71 >
72 {/* Locked while saving: a successful save clears the draft, which would drop edits made mid-request. */}
73 <fieldset disabled={saving} className="contents">
74 <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">
75 A token saved here is used before{" "}
76 <code className="rounded bg-muted px-1 py-px text-2xs">GH_TOKEN</code> and the{" "}
77 <code className="rounded bg-muted px-1 py-px text-2xs">gh</code> login, so GitHub works
78 without the GitHub CLI. Give it read and write access to pull requests and contents.{" "}
79 <InlineButton
80 render={
81 <a
82 href={newTokenUrl(normalizedHost || DEFAULT_HOST)}
83 target="_blank"
84 rel="noreferrer noopener"
85 />
86 }
87 >
88 Create a token
89 <ExternalLinkIcon aria-hidden className="size-3" />
90 </InlineButton>
91 </p>
92 <div className="grid gap-3 sm:grid-cols-[12rem_1fr]">
93 <div className="grid gap-1.5">
94 <Label htmlFor={`github-token-host-${environmentId}`}>Host</Label>
95 <Input
96 id={`github-token-host-${environmentId}`}
97 autoComplete="off"
98 size="sm"
99 placeholder={DEFAULT_HOST}
100 value={host}
101 onChange={(event) => setHost(event.target.value)}
102 />
103 </div>
104 <div className="grid gap-1.5">
105 <Label htmlFor={`github-token-${environmentId}`}>Token</Label>
106 <Input
107 id={`github-token-${environmentId}`}
108 type="password"
109 autoComplete="off"
110 size="sm"
111 placeholder={isSaved ? "Stored secret, enter a new value to replace" : "Not set"}
112 value={draft}
113 onChange={(event) => setDraft(event.target.value)}
114 />
115 </div>
116 </div>
117 <div className="flex items-center justify-between gap-3">
118 <p className="text-xs text-muted-foreground">
119 {savedHosts.length === 0
120 ? "No token saved; the server uses GH_TOKEN or the gh login."
121 : `Saved for ${savedHosts.join(", ")}.`}
122 </p>
123 <div className="flex shrink-0 gap-2">
124 {isSaved ? (
125 <Button
126 size="xs"
127 variant="outline"
128 disabled={saving}
129 onClick={() => void save(normalizedHost, "")}
130 >
131 Remove
132 </Button>
133 ) : null}
134 <Button type="submit" size="xs" disabled={!normalizedHost || !draft.trim() || saving}>
135 Save
136 </Button>
137 </div>
138 </div>
139 </fieldset>
140 </form>
141 );
142}