g1t/apps/web/app/routes/repo/settings-domains.tsx

343 lines15,167 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Agents and memory, checks and conflicts, profiles, slug renames, custom domains1import { CheckCircle2, Globe, Info, RotateCw, Trash2 } from "lucide-react";
2import { useEffect, useState } from "react";
A click away from a live page arrives: pages stop refreshing themselves while a navigation is pending3import { Form, Link, useNavigation } from "react-router";
Agents and memory, checks and conflicts, profiles, slug renames, custom domains4
5import type { Domain, DomainRecord, DomainStatus } from "@g1t/contracts";
6
7import type { Route } from "./+types/settings-domains";
8import { page } from "../../lib/meta";
Project settings move into the sidebar, grouped, with a heading per page9import { RepoSettingsHeading } from "../../components/repo-settings-heading";
Agents and memory, checks and conflicts, profiles, slug renames, custom domains10import { Button, CopyLine, EmptyState, ErrorText, Field, Input } from "../../components/ui";
11import {
12 AlertDialog,
13 AlertDialogAction,
14 AlertDialogCancel,
15 AlertDialogContent,
16 AlertDialogDescription,
17 AlertDialogFooter,
18 AlertDialogHeader,
19 AlertDialogTitle,
20 AlertDialogTrigger,
21} from "../../components/ui/alert-dialog";
22import { CheckboxOption } from "../../components/ui/checkbox";
23import { deployments } from "../../lib/services.server";
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look24import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
25import { requireCapability, requireInsider } from "../../lib/access.server";
A click away from a live page arrives: pages stop refreshing themselves while a navigation is pending26import { useRefreshWhile } from "../../lib/refresh";
Agents and memory, checks and conflicts, profiles, slug renames, custom domains27
28export function meta({ params, ...args }: Route.MetaArgs) {
29 return page(args, { title: `Domains · ${params.owner}/${params.repo} · g1t` });
30}
31
32export async function loader({ params, context }: Route.LoaderArgs) {
33 const viewer = getViewer(context);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look34 // Admins; to anyone without a role here the page does not exist.
35 await requireInsider(context, params, "manage_integrations");
Agents and memory, checks and conflicts, profiles, slug renames, custom domains36 const ref = { workspace: params.owner, slug: params.repo };
37 const [settings, domains] = await Promise.all([deployments.settings(ref, viewer), deployments.domains(ref, viewer)]);
38 return { settings: unwrap(settings), ...unwrap(domains) };
39}
40
41export async function action({ request, params, context }: Route.ActionArgs) {
42 assertSameOrigin(request);
43 const user = requireUser(context, request);
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look44 await requireCapability(context, params, "manage_integrations");
Agents and memory, checks and conflicts, profiles, slug renames, custom domains45 const form = await request.formData();
46 const ref = { workspace: params.owner, slug: params.repo };
47 const intent = form.get("intent");
48 const id = String(form.get("id") ?? "");
49 if (intent === "add") {
50 const added = await deployments.addDomain(user, ref, String(form.get("hostname") ?? ""), { twin: form.get("twin") === "on" });
51 if (!added.ok) return { error: added.error.message };
52 const names = added.value.map((d) => d.hostname);
53 return { notice: names.length ? `Added ${names.join(" and ")}. Add the DNS records below.` : "Saved." };
54 }
55 if (intent === "refresh") {
56 const checked = await deployments.refreshDomain(user, ref, id);
57 if (!checked.ok) return { error: checked.error.message };
58 return { notice: checked.value.status === "active" ? `${checked.value.hostname} is active.` : `Checked ${checked.value.hostname} again.` };
59 }
60 if (intent === "remove") {
61 const removed = await deployments.removeDomain(user, ref, id);
62 return removed.ok ? { notice: "Domain removed." } : { error: removed.error.message };
63 }
64 return { error: "Unknown request." };
65}
66
67const STATUS: Record<DomainStatus, { label: string; tone: string; live?: boolean }> = {
68 pending: { label: "Waiting for DNS", tone: "text-warn border-warn/30 bg-warn/5", live: true },
69 verifying: { label: "Issuing certificate", tone: "text-warn border-warn/30 bg-warn/5", live: true },
70 active: { label: "Active", tone: "text-accent border-accent/30 bg-accent/5" },
71 failed: { label: "Failed", tone: "text-danger border-danger/30 bg-danger/5" },
72 removing: { label: "Removing", tone: "text-faint border-line" },
73};
74
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas75/** A custom domain's monthly price, to the cent: `$0.12`. */
76function domainPrice(micros: number | undefined): string {
77 return `$${((micros ?? 120_000) / 1_000_000).toFixed(2)}`;
78}
79
Agents and memory, checks and conflicts, profiles, slug renames, custom domains80function StatusBadge({ status }: { status: DomainStatus }) {
81 const { label, tone, live } = STATUS[status];
82 return (
83 <span className={`inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium ${tone}`}>
84 <span className={`size-1.5 rounded-full bg-current ${live ? "animate-pulse motion-reduce:animate-none" : ""}`} />
85 {label}
86 </span>
87 );
88}
89
90/** The www or apex twin of what is typed, for the pairing option's label. */
91function twinOf(input: string): string | null {
92 const host = input.trim().toLowerCase().replace(/^https?:\/\//, "").replace(/[/?#].*$/, "").replace(/\.$/, "");
93 if (!/^[a-z0-9.-]+\.[a-z0-9-]+$/.test(host)) return null;
94 if (host.startsWith("www.")) return host.slice(4).includes(".") ? host.slice(4) : null;
95 return host.split(".").length === 2 ? `www.${host}` : null;
96}
97
98export default function DomainSettings({ loaderData, actionData, params }: Route.ComponentProps) {
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas99 const { settings, domains, target, available, notice, monthlyMicros, used } = loaderData;
Agents and memory, checks and conflicts, profiles, slug renames, custom domains100 const busy = useNavigation().state === "submitting";
101 const base = `/${params.owner}/${params.repo}`;
102 const [hostname, setHostname] = useState("");
103 const twin = twinOf(hostname);
104 const added = actionData && "notice" in actionData && !!actionData.notice?.startsWith("Added");
105 useEffect(() => {
106 if (added) setHostname("");
107 }, [added, actionData]);
108
109 // While a domain is on its way, the page follows it.
110 const waiting = domains.some((d) => d.status === "pending" || d.status === "verifying");
A click away from a live page arrives: pages stop refreshing themselves while a navigation is pending111 useRefreshWhile(waiting, 10_000);
Agents and memory, checks and conflicts, profiles, slug renames, custom domains112
113 // A redirecting domain is shown under the one it redirects to.
114 const primary = domains.filter((d) => !d.redirectTo || !domains.some((p) => p.hostname === d.redirectTo));
115
116 return (
117 <div className="max-w-4xl">
Project settings move into the sidebar, grouped, with a heading per page118 <RepoSettingsHeading base={base} />
Agents and memory, checks and conflicts, profiles, slug renames, custom domains119 <div className="min-h-6">
120 {actionData && "notice" in actionData && <p className="text-sm text-accent">{actionData.notice}</p>}
121 <ErrorText>{actionData && "error" in actionData ? actionData.error : null}</ErrorText>
122 </div>
123
124 <header className="mb-6">
125 <h2 className="flex items-center gap-2 font-medium">
126 <Globe size={16} className="text-accent" />
127 Custom domains
128 </h2>
129 <p className="mt-1 max-w-2xl text-sm text-muted">
130 Serve production at a domain of your own, such as <span className="font-mono text-fg">example.com</span> or{" "}
131 <span className="font-mono text-fg">www.example.com</span>, beside{" "}
132 <span className="font-mono text-fg">{settings.productionUrl.replace("https://", "")}</span>. Point it at{" "}
133 <span className="font-mono text-fg">{target}</span>; g1t issues and renews its certificate. Redeploys never change
134 it.{" "}
135 <a href="https://docs.g1t.sh/guides/deployments/#custom-domains" className="text-fg hover:underline">
136 How custom domains work
137 </a>
138 </p>
139 </header>
140
141 {!available && notice && (
142 <p className="mb-6 flex items-start gap-2 rounded-lg border border-warn/30 bg-warn/5 px-4 py-3 text-sm text-warn">
143 <Info size={15} className="mt-0.5 shrink-0" />
144 {notice}
145 </p>
146 )}
147
148 {!settings.enabled && (
149 <p className="mb-6 rounded-lg border border-line bg-surface px-4 py-3 text-sm text-muted">
150 Deployments are off for this project, so a domain added now shows that nothing is deployed until they are on.{" "}
151 <Link to={`${base}/settings/deployments`} className="text-fg hover:underline">
152 Turn on deployments
153 </Link>
154 </p>
155 )}
156
157 <Form method="post" className="rounded-xl border border-line bg-surface p-5">
158 <input type="hidden" name="intent" value="add" />
159 <div className="flex flex-col gap-3 sm:flex-row sm:items-end">
160 <div className="grow">
161 <Field label="Domain" hint="A domain (the apex, such as example.com) or any subdomain, such as www.example.com or app.example.com.">
162 <Input
163 name="hostname"
164 value={hostname}
165 onChange={(event) => setHostname(event.target.value)}
166 placeholder="example.com"
167 autoComplete="off"
168 spellCheck={false}
169 required
170 />
171 </Field>
172 </div>
173 <div className="sm:mb-6">
174 <Button type="submit" variant="accent" disabled={busy || !hostname.trim()}>
175 Add domain
176 </Button>
177 </div>
178 </div>
179 <CheckboxOption
180 name="twin"
181 defaultChecked
182 disabled={!twin}
183 className="mt-2"
184 label={twin ? `Also add ${twin}, redirecting to ${hostname.trim().toLowerCase()}` : "Also add the www or apex twin, redirecting to it"}
185 description="Most sites answer at both example.com and www.example.com; one serves the app and the other sends visitors to it, path and query kept."
186 />
187 <p className="mt-4 text-xs text-faint">
status.g1t.sh with incident management, invites that land you in the workspace, settings as pages, usage without quotas188 Each custom domain is {domainPrice(monthlyMicros)} a month on the g1t plan, its cost plus 20%, from the included usage
189 first. As many as you like: {used} in use across the workspace.
Agents and memory, checks and conflicts, profiles, slug renames, custom domains190 </p>
191 </Form>
192
193 <div className="mt-8 space-y-4">
194 {domains.length === 0 ? (
195 <EmptyState title="No custom domains yet">Add one above, then the DNS records it asks for.</EmptyState>
196 ) : (
197 primary.map((domain) => (
198 <DomainCard
199 key={domain.id}
200 domain={domain}
201 redirects={domains.filter((d) => d.redirectTo === domain.hostname)}
202 busy={busy}
203 />
204 ))
205 )}
206 </div>
207 </div>
208 );
209}
210
211function DomainCard({ domain, redirects, busy }: { domain: Domain; redirects: Domain[]; busy: boolean }) {
212 return (
213 <section className="overflow-hidden rounded-xl border border-line bg-surface">
214 <DomainRow domain={domain} busy={busy} />
215 {redirects.map((other) => (
216 <div key={other.id} className="border-t border-line">
217 <DomainRow domain={other} busy={busy} />
218 </div>
219 ))}
220 </section>
221 );
222}
223
224function DomainRow({ domain, busy }: { domain: Domain; busy: boolean }) {
225 const active = domain.status === "active";
226 return (
227 <div className="p-5">
228 <div className="flex flex-wrap items-center gap-x-3 gap-y-2">
229 {active ? (
230 <a href={`https://${domain.hostname}`} className="min-w-0 truncate font-mono text-sm font-medium hover:text-accent">
231 {domain.hostname}
232 </a>
233 ) : (
234 <span className="min-w-0 truncate font-mono text-sm font-medium">{domain.hostname}</span>
235 )}
236 <StatusBadge status={domain.status} />
237 {domain.redirectTo && <span className="text-xs text-muted">redirects to {domain.redirectTo}</span>}
238 <span className="ml-auto flex items-center gap-2">
239 {domain.status !== "removing" && (
240 <Form method="post">
241 <input type="hidden" name="intent" value="refresh" />
242 <input type="hidden" name="id" value={domain.id} />
243 <Button type="submit" variant="quiet" disabled={busy} title="Ask Cloudflare to check the records again now">
244 <RotateCw size={14} />
245 Check now
246 </Button>
247 </Form>
248 )}
249 <RemoveDomain domain={domain} busy={busy} />
250 </span>
251 </div>
252 {domain.error && !active && <p className="mt-2 text-sm text-muted">{domain.error}</p>}
253 {active ? (
254 <p className="mt-2 flex items-center gap-1.5 text-sm text-muted">
255 <CheckCircle2 size={14} className="text-accent" />
256 {domain.redirectTo ? "Redirecting, with its certificate." : "Serving production, with its certificate."}
257 {domain.verifiedAt && <span className="text-faint">Since {new Date(domain.verifiedAt).toLocaleDateString()}.</span>}
258 </p>
259 ) : (
260 <Records domain={domain} />
261 )}
262 </div>
263 );
264}
265
266function Records({ domain }: { domain: Domain }) {
267 return (
268 <div className="mt-4 space-y-3">
269 <p className="text-sm text-muted">Add these records where the domain's DNS is managed:</p>
270 {domain.records.map((record) => (
271 <RecordRow key={`${record.type}-${record.name}-${record.value}`} record={record} />
272 ))}
273 {domain.apex && (
274 <p className="text-xs text-faint">
275 The apex (the bare domain) cannot have a plain CNAME. Use your provider's flattened CNAME or ALIAS record: a CNAME
276 at <span className="font-mono">@</span> on Cloudflare DNS, an ALIAS on DNSimple, NS1, Namecheap, Porkbun or Gandi,
277 or an ANAME on DNS Made Easy. Route 53's alias records cannot point outside AWS. If your provider has none of
278 these, add only the www domain here and forward the apex to it at your provider.
279 </p>
280 )}
281 <p className="text-xs text-faint">
282 DNS changes can take a few minutes to an hour to be seen. The certificate is issued once the domain points here.
283 </p>
284 </div>
285 );
286}
287
288function RecordRow({ record }: { record: DomainRecord }) {
289 const type = record.type === "ALIAS" ? "CNAME (flattened) or ALIAS" : record.type;
290 return (
291 <div className="grid gap-2 rounded-lg border border-line bg-bg p-3 sm:grid-cols-[9rem_minmax(0,1fr)]">
292 <div className="text-xs">
293 <p className="font-medium text-fg">{type}</p>
294 <p className="mt-0.5 text-faint">{record.purpose}</p>
295 </div>
296 <div className="grid min-w-0 gap-2">
297 <div>
298 <p className="mb-1 text-xs text-faint">Name</p>
299 <CopyLine text={record.name} />
300 </div>
301 <div>
302 <p className="mb-1 text-xs text-faint">{record.type === "TXT" ? "Content" : "Target"}</p>
303 <CopyLine text={record.value} />
304 </div>
305 </div>
306 </div>
307 );
308}
309
310function RemoveDomain({ domain, busy }: { domain: Domain; busy: boolean }) {
311 return (
312 <AlertDialog>
313 <AlertDialogTrigger asChild>
314 <Button type="button" variant="quiet" disabled={busy} aria-label={`Remove ${domain.hostname}`}>
315 <Trash2 size={14} />
316 Remove
317 </Button>
318 </AlertDialogTrigger>
319 <AlertDialogContent>
320 <Form method="post" className="grid gap-4">
321 <input type="hidden" name="intent" value="remove" />
322 <input type="hidden" name="id" value={domain.id} />
323 <AlertDialogHeader>
324 <AlertDialogTitle>Remove {domain.hostname}?</AlertDialogTitle>
325 <AlertDialogDescription>
326 It stops serving this project at once, and its certificate is given up. Any domain redirecting to it is
327 removed too. You can add it again later; its DNS records stay as you set them.
328 </AlertDialogDescription>
329 </AlertDialogHeader>
330 <AlertDialogFooter>
331 <AlertDialogCancel>Cancel</AlertDialogCancel>
332 <AlertDialogAction asChild>
333 <button type="submit">
334 <Trash2 size={14} />
335 Remove domain
336 </button>
337 </AlertDialogAction>
338 </AlertDialogFooter>
339 </Form>
340 </AlertDialogContent>
341 </AlertDialog>
342 );
343}