Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t.sh
240 linesCodeBlameRaw
1import { RefreshCw, ShieldCheck } from "lucide-react";
2import { useFetcher, useSearchParams } from "react-router";
3
4import type { AlertState, DismissReason } from "@g1t/contracts";
5
6import type { Route } from "./+types/security";
7import { page } from "../../lib/meta";
8import {
9 type PullInfo,
10 ScanSummary,
11 SeverityCountsGrid,
12 StateFilter,
13 type UpgradeFix,
14 VulnerabilityList,
15} from "../../components/security";
16import { Button } from "../../components/ui/button";
17import { Card } from "../../components/ui/card";
18import { Hint } from "../../components/ui/hint";
19import { Switch } from "../../components/ui/switch";
20import { security, work } from "../../lib/services.server";
21import { assertSameOrigin, getViewer, requireUser, unwrap } from "../../lib/session.server";
22import { refusal, requireInsider } from "../../lib/access.server";
23import { whyNot } from "../../lib/access";
24import { useRepoMirror } from "../../components/mirror";
25import { updatesWaitReason } from "../../lib/mirror";
26import { alertCapability, countByState, parseAlertState } from "../../lib/security-alerts";
27import { severityCounts } from "../../lib/security-suite";
28import { repoPages } from "../../lib/repo-live";
29import { useRepoLive } from "../../lib/use-repo-live";
30
31export function meta({ params, ...args }: Route.MetaArgs) {
32 return page(args, { title: `Vulnerabilities · ${params.owner}/${params.repo} · g1t` });
33}
34
35/** Upgrade issues and security update pull requests looked up per page, at most. */
36const MAX_FIXES = 30;
37
38export async function loader({ params, context, request }: Route.LoaderArgs) {
39 // Git's refusal links here; someone signed out signs in first.
40 const viewer = getViewer(context) ?? requireUser(context, request);
41 // Findings are for people who can push, public project or not: Write and up.
42 const { access } = await requireInsider(context, params, "security_alerts");
43 const repo = { namespace: params.owner, name: params.repo };
44 const overview = unwrap(await security.overview(repo, viewer));
45 const unique = (numbers: (number | null | undefined)[]) =>
46 [...new Set(numbers.filter((n): n is number => n != null))].slice(0, MAX_FIXES);
47 // Security updates' pull requests, for their live status.
48 const pullNumbers = unique(overview.vulnerabilities.map((vuln) => vuln.update?.pull));
49 // Older upgrade issues, from before g1t opened pull requests itself.
50 const issueNumbers = unique(overview.vulnerabilities.filter((vuln) => !vuln.update).map((vuln) => vuln.issue));
51 const [pullDetails, issueDetails] = await Promise.all([
52 Promise.all(pullNumbers.map((number) => work.getPull(repo, number, viewer).catch(() => null))),
53 Promise.all(issueNumbers.map((number) => work.getIssue(repo, number, viewer).catch(() => null))),
54 ]);
55 const pulls: Record<number, PullInfo> = {};
56 for (const found of pullDetails) {
57 if (!found?.ok) continue;
58 const { pull } = found.value;
59 pulls[pull.number] = { number: pull.number, status: pull.status, title: pull.title };
60 }
61 const fixes: Record<number, UpgradeFix> = {};
62 for (const found of issueDetails) {
63 if (!found?.ok) continue;
64 const { issue, pulls: issuePulls } = found.value;
65 const latest = issuePulls.at(-1) ?? null;
66 fixes[issue.number] = {
67 number: issue.number,
68 state: issue.state,
69 resolvedBy: issue.resolvedBy,
70 pull: latest ? { number: latest.number, status: latest.status, agent: latest.runtime === "hosted" ? latest.agent : null } : null,
71 };
72 }
73 return { overview, fixes, pulls, can: access.can };
74}
75
76const DISMISS_REASONS = new Set<string>([
77 "false_positive",
78 "used_in_tests",
79 "revoked",
80 "wont_fix",
81 "fix_started",
82 "no_bandwidth",
83 "tolerable_risk",
84 "inaccurate",
85 "not_used",
86]);
87
88export async function action({ params, context, request }: Route.ActionArgs) {
89 assertSameOrigin(request);
90 const user = requireUser(context, request);
91 const repo = { namespace: params.owner, name: params.repo };
92 const form = await request.formData();
93 const intent = String(form.get("intent") ?? "");
94 const id = String(form.get("id") ?? "");
95 // Scanning spends compute (Write); security updates are a setting
96 // (Maintain); an alert is dismissed or reopened with Write, or by a
97 // security manager of the workspace.
98 const capability =
99 intent === "rescan" ? "run" : intent === "upkeep" ? "manage_settings" : intent === "dismiss" || intent === "reopen" ? alertCapability(id) : null;
100 if (!capability) return { ok: false, error: "Unknown action." };
101 const refused = await refusal(context, params, capability);
102 if (refused) return { ok: false, error: refused };
103 if (intent === "dismiss") {
104 const reason = String(form.get("reason") ?? "");
105 if (!DISMISS_REASONS.has(reason)) return { ok: false, error: "Choose a reason." };
106 const comment = String(form.get("comment") ?? "").trim().slice(0, 500);
107 const dismissed = await security.dismiss(user, repo, id, reason as DismissReason, comment);
108 return dismissed.ok ? { ok: true } : { ok: false, error: dismissed.error.message };
109 }
110 if (intent === "reopen") {
111 const reopened = await security.reopen(user, repo, id);
112 return reopened.ok ? { ok: true } : { ok: false, error: reopened.error.message };
113 }
114 if (intent === "rescan") {
115 const scanned = await security.rescan(user, repo);
116 return scanned.ok ? { ok: true } : { ok: false, error: scanned.error.message };
117 }
118 const set = await security.setUpkeep(user, repo, form.get("enabled") === "true");
119 return set.ok ? { ok: true } : { ok: false, error: set.error.message };
120}
121
122export default function ProjectSecurity({ loaderData, params }: Route.ComponentProps) {
123 const { overview, fixes, pulls, can } = loaderData;
124 // Alerts opening, fixed and dismissed show as it happens.
125 useRepoLive({ match: repoPages.security() });
126 const base = `/${params.owner}/${params.repo}`;
127 const action = `${base}/security/vulnerabilities`;
128 const [search, setSearch] = useSearchParams();
129 const rescan = useFetcher<{ ok: boolean; error?: string }>();
130 const upkeep = useFetcher<{ ok: boolean; error?: string }>();
131 const upkeepOn = upkeep.formData ? upkeep.formData.get("enabled") === "true" : overview.upkeep;
132 // A mirror g1t does not lead opens nothing on its own: the scan runs and
133 // the alerts show, but each update waits (lib/mirror.ts `offers`).
134 const updatesWait = updatesWaitReason(useRepoMirror().repo);
135 const vulnCounts = countByState(overview.vulnerabilities);
136 // A link to one alert shows it wherever it stands.
137 const focus = search.get("finding");
138 const focused = focus ? overview.vulnerabilities.find((vuln) => vuln.id === focus) : undefined;
139 const state: AlertState = search.get("state") ? parseAlertState(search.get("state")) : (focused?.state ?? "open");
140 const navigate = (change: (next: URLSearchParams) => void) => {
141 const next = new URLSearchParams(search);
142 change(next);
143 next.delete("finding");
144 setSearch(next, { replace: true, preventScrollReset: true });
145 };
146 const setState = (value: AlertState) =>
147 navigate((next) => (value === "open" ? next.delete("state") : next.set("state", value)));
148 return (
149 <div className="max-w-5xl">
150 <div className="flex flex-wrap items-start justify-between gap-4">
151 <div>
152 <h2 className="flex items-center gap-2 text-xl font-semibold tracking-tight">
153 <ShieldCheck size={19} className="text-accent" />
154 Vulnerabilities
155 </h2>
156 <p className="mt-1.5 max-w-2xl text-sm text-muted">
157 Every package the lockfiles resolve is checked for known vulnerabilities, on every push to the default branch and
158 daily.{" "}
159 {updatesWait ?? "With security updates on, g1t opens a pull request to upgrade each one that has a fix."}
160 </p>
161 </div>
162 {can.run && (
163 <rescan.Form method="post" action={action}>
164 <input type="hidden" name="intent" value="rescan" />
165 <Button
166 type="submit"
167 disabled={rescan.state !== "idle"}
168 variant="outline"
169 size="sm"
170 className="gap-2 px-3 text-sm font-normal"
171 >
172 <RefreshCw size={14} className={rescan.state !== "idle" ? "animate-spin" : ""} />
173 {rescan.state !== "idle" ? "Scanning…" : "Re-scan now"}
174 </Button>
175 {rescan.data?.error && <p className="mt-1.5 text-xs text-danger">{rescan.data.error}</p>}
176 </rescan.Form>
177 )}
178 </div>
179
180 <div className="mt-6">
181 <SeverityCountsGrid counts={severityCounts(overview.vulnerabilities)} />
182 <p className="mt-2 text-xs text-faint">Open vulnerability alerts by severity.</p>
183 </div>
184
185 <div className="mt-4">
186 <ScanSummary scan={overview.scan} />
187 </div>
188
189 <div className="mt-8">
190 <div>
191 <StateFilter counts={vulnCounts} value={state} onChange={setState} />
192 <div className="mt-3">
193 <VulnerabilityList
194 vulnerabilities={overview.vulnerabilities.filter((vuln) => vuln.state === state)}
195 state={state}
196 activity={overview.activity}
197 fixes={fixes}
198 pulls={pulls}
199 upkeep={overview.upkeep}
200 updatesWait={updatesWait}
201 base={base}
202 action={action}
203 focus={focus}
204 canDismiss={can.push}
205 />
206 </div>
207 </div>
208 </div>
209
210 <section className="mt-10" aria-labelledby="security-settings">
211 <h3 id="security-settings" className="text-base font-semibold tracking-tight">
212 Settings
213 </h3>
214 <div className="mt-3 space-y-3">
215 <Card asChild className="flex cursor-pointer items-start justify-between gap-4 p-4 transition-colors hover:border-line-strong">
216 <label>
217 <span className="min-w-0">
218 <span className="block text-sm font-medium">Security updates</span>
219 <span className="mt-1 block text-sm text-muted">
220 Open a pull request to upgrade each vulnerable dependency that has a fix. It lands through your branch's
221 required checks.
222 {updatesWait && " On this mirror, it takes effect once the repository is taken over or moved to g1t."}
223 </span>
224 {upkeep.data?.error && <span className="mt-1 block text-xs text-danger">{upkeep.data.error}</span>}
225 </span>
226 <Hint label={whyNot(can, "manage_settings")} disabled={!can.manage_settings}>
227 <Switch
228 className="mt-0.5"
229 checked={upkeepOn}
230 disabled={upkeep.state !== "idle" || !can.manage_settings}
231 onCheckedChange={(checked) => upkeep.submit({ intent: "upkeep", enabled: String(checked) }, { method: "post", action })}
232 />
233 </Hint>
234 </label>
235 </Card>
236 </div>
237 </section>
238 </div>
239 );
240}