bugxhunter 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +41 -0
- package/LICENSE +21 -0
- package/README.md +347 -2
- package/SECURITY.md +121 -0
- package/bin/bugxhunter.mjs +154 -0
- package/bugxhunter-0.5.0.tgz +0 -0
- package/docker-compose.yml +118 -0
- package/package.json +37 -4
- package/scripts/vault-reset.mjs +30 -0
- package/server/dist/attachments.js +67 -0
- package/server/dist/audit.js +123 -0
- package/server/dist/auth.js +248 -0
- package/server/dist/env.js +15 -0
- package/server/dist/errors.js +3 -0
- package/server/dist/github.js +462 -0
- package/server/dist/index.js +783 -0
- package/server/dist/opencode.js +421 -0
- package/server/dist/providers.js +187 -0
- package/server/dist/rag.js +100 -0
- package/server/dist/scx.js +146 -0
- package/server/dist/vault.js +286 -0
- package/web/dist/assets/index-CqhtWJfv.css +1 -0
- package/web/dist/assets/index-DFfqRBl8.js +118 -0
- package/web/dist/claude-logo-ivory.svg +17 -0
- package/web/dist/example-tools.json +1 -0
- package/web/dist/favicon.png +0 -0
- package/web/dist/index.html +20 -0
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GitHub, read-only.
|
|
3
|
+
*
|
|
4
|
+
* The runner signs in to the public "BugXHunter" GitHub App with the device
|
|
5
|
+
* flow (the thing `gh auth login` does): a short code typed at
|
|
6
|
+
* github.com/login/device, no callback URL and no client secret, so one app
|
|
7
|
+
* registration serves every self-hosted runner. The app declares Contents:
|
|
8
|
+
* read-only and Metadata: read-only, and its user token reaches only the
|
|
9
|
+
* repositories the app was INSTALLED on ("Choose repositories"), so the reach
|
|
10
|
+
* is chosen and bounded by the user on GitHub's own screens. Tokens expire
|
|
11
|
+
* after eight hours and refresh; the pair is kept in the vault (item
|
|
12
|
+
* GITHUB_OAUTH), or in memory until restart when there is no vault yet.
|
|
13
|
+
*
|
|
14
|
+
* The token does two things: lists the repositories it reaches, and clones or
|
|
15
|
+
* fast-forwards them into the workspace. Nothing here pushes, writes or reads
|
|
16
|
+
* anything else.
|
|
17
|
+
*
|
|
18
|
+
* The token is passed to git through an environment-scoped config entry
|
|
19
|
+
* (GIT_CONFIG_*), so it is in neither the command line nor the clone's
|
|
20
|
+
* .git/config: the agent gets a plain working copy with an https origin and no
|
|
21
|
+
* credentials, which is what keeps the integration read-only in the sandbox
|
|
22
|
+
* too.
|
|
23
|
+
*
|
|
24
|
+
* The API helper's shape follows brainstorm-board's lib/github.ts; the OAuth
|
|
25
|
+
* half was left there on purpose: a self-hosted runner has no app to register.
|
|
26
|
+
*/
|
|
27
|
+
import { execFile } from "node:child_process";
|
|
28
|
+
import crypto from "node:crypto";
|
|
29
|
+
import fs from "node:fs";
|
|
30
|
+
import path from "node:path";
|
|
31
|
+
import { promisify } from "node:util";
|
|
32
|
+
import { httpError } from "./errors.js";
|
|
33
|
+
import { CLONE_ROOT, REMOTE_URL } from "./opencode.js";
|
|
34
|
+
import * as vault from "./vault.js";
|
|
35
|
+
const execFileP = promisify(execFile);
|
|
36
|
+
/** The signed-in connection (tokens + login), as JSON. */
|
|
37
|
+
export const CONNECTION_ITEM = "GITHUB_OAUTH";
|
|
38
|
+
/** The public BugXHunter GitHub App. Forks register their own and override these. */
|
|
39
|
+
export const CLIENT_ID = process.env.GITHUB_CLIENT_ID ?? "Iv23lijniIcrEZ0ZFNWD";
|
|
40
|
+
export const APP_SLUG = process.env.GITHUB_APP_SLUG ?? "bugxhunterapp";
|
|
41
|
+
const API_BASE = process.env.GITHUB_API_BASE ?? "https://api.github.com";
|
|
42
|
+
const OAUTH_BASE = process.env.GITHUB_OAUTH_BASE ?? "https://github.com";
|
|
43
|
+
/** Overridable so tests can clone from a local bare repository. */
|
|
44
|
+
const GIT_BASE = process.env.GITHUB_GIT_BASE ?? "https://github.com";
|
|
45
|
+
const NOT_CONNECTED = "Not connected to GitHub. Sidebar → clone from GitHub → Connect GitHub.";
|
|
46
|
+
// --- names and paths ----------------------------------------------------------------
|
|
47
|
+
/** `owner/name` (a trailing .git is tolerated), validated against GitHub's own rules. */
|
|
48
|
+
export function parseRepo(input) {
|
|
49
|
+
const s = typeof input === "string" ? input.trim().replace(/\.git$/i, "") : "";
|
|
50
|
+
const m = /^([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?)\/([A-Za-z0-9_.-]{1,100})$/.exec(s);
|
|
51
|
+
if (!m || m[2] === "." || m[2] === "..")
|
|
52
|
+
throw httpError(400, `Not a repository name (owner/name): ${JSON.stringify(input)}`);
|
|
53
|
+
return { owner: m[1], name: m[2], fullName: `${m[1]}/${m[2]}` };
|
|
54
|
+
}
|
|
55
|
+
/** A branch name git would accept, without the characters that change a command's meaning. */
|
|
56
|
+
export function validBranch(input) {
|
|
57
|
+
const b = typeof input === "string" ? input.trim() : "";
|
|
58
|
+
const bad = !b || b.length > 200 || b.startsWith("-") || b.startsWith("/") || b.endsWith("/") || b.endsWith(".")
|
|
59
|
+
|| b.endsWith(".lock") || b.includes("..") || b.includes("//") || b.includes("@{") || /[\s~^:?*[\\\x00-\x1f\x7f]/.test(b);
|
|
60
|
+
if (bad)
|
|
61
|
+
throw httpError(400, `Not a branch name: ${JSON.stringify(input)}`);
|
|
62
|
+
return b;
|
|
63
|
+
}
|
|
64
|
+
/** Where a repository is (or would be) cloned: `<CLONE_ROOT>/<owner>/<name>`. */
|
|
65
|
+
export function cloneDir(fullName) {
|
|
66
|
+
const { owner, name } = parseRepo(fullName);
|
|
67
|
+
return (REMOTE_URL ? path.posix : path).join(CLONE_ROOT, owner, name);
|
|
68
|
+
}
|
|
69
|
+
const remoteUrl = (fullName) => `${GIT_BASE}/${fullName}.git`;
|
|
70
|
+
/** `owner/name` from a clone's origin URL, or null when it is not a GitHub remote. */
|
|
71
|
+
export function parseOriginUrl(url) {
|
|
72
|
+
let u = url.trim();
|
|
73
|
+
// A non-default GIT_BASE (tests: a folder of bare repositories) counts as "GitHub" too.
|
|
74
|
+
const base = GIT_BASE.replace(/\\/g, "/");
|
|
75
|
+
if (base !== "https://github.com" && u.replace(/\\/g, "/").toLowerCase().startsWith(base.toLowerCase() + "/")) {
|
|
76
|
+
u = "https://github.com/" + u.replace(/\\/g, "/").slice(base.length + 1);
|
|
77
|
+
}
|
|
78
|
+
const m = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/.exec(u);
|
|
79
|
+
return m ? `${m[1]}/${m[2]}` : null;
|
|
80
|
+
}
|
|
81
|
+
// --- git ------------------------------------------------------------------------------
|
|
82
|
+
/**
|
|
83
|
+
* The token as git sees it: a config entry scoped to this one process, so it
|
|
84
|
+
* is never on a command line (visible in `ps`) and never written into the
|
|
85
|
+
* clone. Credential helpers are switched off so a bad token fails at once
|
|
86
|
+
* instead of popping a desktop prompt (Git Credential Manager on Windows).
|
|
87
|
+
*/
|
|
88
|
+
export function gitAuthEnv(token) {
|
|
89
|
+
const basic = Buffer.from(`x-access-token:${token}`).toString("base64");
|
|
90
|
+
return {
|
|
91
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
92
|
+
GIT_CONFIG_COUNT: "2",
|
|
93
|
+
GIT_CONFIG_KEY_0: `http.${GIT_BASE}/.extraheader`,
|
|
94
|
+
GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${basic}`,
|
|
95
|
+
GIT_CONFIG_KEY_1: "credential.helper",
|
|
96
|
+
GIT_CONFIG_VALUE_1: "",
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
async function git(args, token, cwd) {
|
|
100
|
+
try {
|
|
101
|
+
const { stdout } = await execFileP("git", args, {
|
|
102
|
+
cwd, windowsHide: true, timeout: 15 * 60_000, maxBuffer: 8 * 1024 * 1024,
|
|
103
|
+
env: { ...process.env, ...gitAuthEnv(token) },
|
|
104
|
+
});
|
|
105
|
+
return stdout;
|
|
106
|
+
}
|
|
107
|
+
catch (e) {
|
|
108
|
+
const err = e;
|
|
109
|
+
const text = String(err.stderr || err.message || e).split(/\r?\n/).filter((l) => l && !/^(remote: )?Enumerating|^Receiving|^Resolving|^Counting|^Compressing/.test(l)).slice(-4).join(" ");
|
|
110
|
+
if (err.code === "ENOENT")
|
|
111
|
+
throw httpError(503, "git is not installed on the runner.");
|
|
112
|
+
const status = /Authentication failed|could not read Username|403|Repository not found/i.test(text) ? 403 : 502;
|
|
113
|
+
// Belt and braces: the token travels in a header, never in output, but a clone's error is shown in the UI.
|
|
114
|
+
throw httpError(status, `git ${args[0]} failed: ${text.split(token).join("***")}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function readGitFile(dir, file) {
|
|
118
|
+
try {
|
|
119
|
+
return fs.readFileSync(path.join(dir, ".git", file), "utf8");
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** What a folder is a clone of, read from .git without spawning git. */
|
|
126
|
+
export function inspectClone(dir) {
|
|
127
|
+
const config = readGitFile(dir, "config");
|
|
128
|
+
if (!config)
|
|
129
|
+
return null;
|
|
130
|
+
// git escapes backslashes and quotes in config values.
|
|
131
|
+
const origin = /\[remote "origin"\][^[]*?\n\s*url\s*=\s*(.+)/.exec(config)?.[1]?.trim().replace(/^"(.*)"$/, "$1").replace(/\\(.)/g, "$1");
|
|
132
|
+
const fullName = origin ? parseOriginUrl(origin) : null;
|
|
133
|
+
if (!fullName)
|
|
134
|
+
return null;
|
|
135
|
+
const head = readGitFile(dir, "HEAD") ?? "";
|
|
136
|
+
const branch = /^ref: refs\/heads\/(.+?)\s*$/.exec(head)?.[1] ?? null;
|
|
137
|
+
return { fullName, directory: dir, branch };
|
|
138
|
+
}
|
|
139
|
+
/** Clones under the clone root: ours (`owner/name`) and any the user made one level down. */
|
|
140
|
+
export function listClones() {
|
|
141
|
+
const out = [];
|
|
142
|
+
const join = REMOTE_URL ? path.posix.join : path.join;
|
|
143
|
+
let owners = [];
|
|
144
|
+
try {
|
|
145
|
+
owners = fs.readdirSync(CLONE_ROOT, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name);
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return out;
|
|
149
|
+
}
|
|
150
|
+
for (const owner of owners) {
|
|
151
|
+
const ownerDir = join(CLONE_ROOT, owner);
|
|
152
|
+
const direct = inspectClone(ownerDir);
|
|
153
|
+
if (direct) {
|
|
154
|
+
out.push(direct);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
let names = [];
|
|
158
|
+
try {
|
|
159
|
+
names = fs.readdirSync(ownerDir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith(".")).map((d) => d.name);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
for (const name of names) {
|
|
165
|
+
const c = inspectClone(join(ownerDir, name));
|
|
166
|
+
if (c)
|
|
167
|
+
out.push(c);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return out.sort((a, b) => a.fullName.localeCompare(b.fullName));
|
|
171
|
+
}
|
|
172
|
+
/** Where the connection lives when there is no vault to seal it in: this process only. */
|
|
173
|
+
let memoryConnection = null;
|
|
174
|
+
function connectionStorage() {
|
|
175
|
+
if (!vault.isInitialised())
|
|
176
|
+
return "memory";
|
|
177
|
+
return vault.isUnsealed() ? "vault" : "sealed";
|
|
178
|
+
}
|
|
179
|
+
function loadConnection() {
|
|
180
|
+
if (connectionStorage() === "vault") {
|
|
181
|
+
const raw = vault.getItem(CONNECTION_ITEM);
|
|
182
|
+
if (!raw)
|
|
183
|
+
return null;
|
|
184
|
+
try {
|
|
185
|
+
return JSON.parse(raw);
|
|
186
|
+
}
|
|
187
|
+
catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return memoryConnection;
|
|
192
|
+
}
|
|
193
|
+
function saveConnection(c) {
|
|
194
|
+
const where = connectionStorage();
|
|
195
|
+
if (where === "sealed")
|
|
196
|
+
throw httpError(503, "The vault is locked. Unlock it (lock icon in the sidebar) and try again.");
|
|
197
|
+
if (where === "vault") {
|
|
198
|
+
if (c)
|
|
199
|
+
vault.setItem(CONNECTION_ITEM, JSON.stringify(c));
|
|
200
|
+
else if (vault.status("none").items.includes(CONNECTION_ITEM))
|
|
201
|
+
vault.deleteItem(CONNECTION_ITEM);
|
|
202
|
+
memoryConnection = null;
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
memoryConnection = c;
|
|
206
|
+
}
|
|
207
|
+
return where;
|
|
208
|
+
}
|
|
209
|
+
export function disconnect() {
|
|
210
|
+
saveConnection(null);
|
|
211
|
+
}
|
|
212
|
+
/** POST to GitHub's OAuth endpoints (form in, JSON out). No client secret: the device flow has none. */
|
|
213
|
+
async function oauthPost(path, params) {
|
|
214
|
+
const r = await fetch(`${OAUTH_BASE}${path}`, {
|
|
215
|
+
method: "POST",
|
|
216
|
+
headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "bugxhunter-runner" },
|
|
217
|
+
body: new URLSearchParams({ client_id: CLIENT_ID, ...params }).toString(),
|
|
218
|
+
signal: AbortSignal.timeout(20_000),
|
|
219
|
+
});
|
|
220
|
+
if (!r.ok)
|
|
221
|
+
throw httpError(502, `GitHub sign-in endpoint answered ${r.status}`);
|
|
222
|
+
return (await r.json());
|
|
223
|
+
}
|
|
224
|
+
function tokensFrom(data, login) {
|
|
225
|
+
if (!data.access_token)
|
|
226
|
+
throw httpError(502, data.error_description || data.error || "GitHub returned no token");
|
|
227
|
+
const c = { accessToken: data.access_token, login };
|
|
228
|
+
if (data.refresh_token) {
|
|
229
|
+
c.refreshToken = data.refresh_token;
|
|
230
|
+
// A minute early, so a token is never presented at the edge of expiry.
|
|
231
|
+
if (typeof data.expires_in === "number" && data.expires_in > 0)
|
|
232
|
+
c.expiresAt = Date.now() + (data.expires_in - 60) * 1000;
|
|
233
|
+
}
|
|
234
|
+
return c;
|
|
235
|
+
}
|
|
236
|
+
/** Device flows started from this process, by an opaque id the browser polls with. */
|
|
237
|
+
const pendingDevice = new Map();
|
|
238
|
+
/** Step 1: ask GitHub for a code the person types at github.com/login/device. */
|
|
239
|
+
export async function connectStart() {
|
|
240
|
+
if (connectionStorage() === "sealed")
|
|
241
|
+
throw httpError(503, "The vault is locked. Unlock it first so the connection can be sealed in it.");
|
|
242
|
+
const d = (await oauthPost("/login/device/code", {}));
|
|
243
|
+
if (!d.device_code || !d.user_code)
|
|
244
|
+
throw httpError(502, d.error_description || d.error || "GitHub did not start a device sign-in");
|
|
245
|
+
for (const [k, v] of pendingDevice)
|
|
246
|
+
if (v.expiresAt < Date.now())
|
|
247
|
+
pendingDevice.delete(k);
|
|
248
|
+
const id = crypto.randomBytes(16).toString("base64url");
|
|
249
|
+
const interval = Math.max(5, d.interval ?? 5);
|
|
250
|
+
pendingDevice.set(id, { deviceCode: d.device_code, interval, expiresAt: Date.now() + (d.expires_in ?? 900) * 1000, nextPoll: 0 });
|
|
251
|
+
return { id, userCode: d.user_code, verificationUri: d.verification_uri ?? `${OAUTH_BASE}/login/device`, expiresIn: d.expires_in ?? 900, interval };
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Step 2, repeated: has the person approved yet? GitHub's polling interval is
|
|
255
|
+
* respected here no matter how often the browser asks (a faster poll earns a
|
|
256
|
+
* `slow_down`). On approval the tokens are stored and the login looked up.
|
|
257
|
+
*/
|
|
258
|
+
export async function connectPoll(id) {
|
|
259
|
+
const p = typeof id === "string" ? pendingDevice.get(id) : undefined;
|
|
260
|
+
if (!p)
|
|
261
|
+
throw httpError(404, "That sign-in attempt is unknown or has expired. Start again.");
|
|
262
|
+
const key = id;
|
|
263
|
+
if (p.expiresAt < Date.now()) {
|
|
264
|
+
pendingDevice.delete(key);
|
|
265
|
+
return { status: "expired" };
|
|
266
|
+
}
|
|
267
|
+
if (Date.now() < p.nextPoll)
|
|
268
|
+
return { status: "pending" };
|
|
269
|
+
p.nextPoll = Date.now() + p.interval * 1000;
|
|
270
|
+
const data = await oauthPost("/login/oauth/access_token", { device_code: p.deviceCode, grant_type: "urn:ietf:params:oauth:grant-type:device_code" });
|
|
271
|
+
switch (data.error) {
|
|
272
|
+
case "authorization_pending": return { status: "pending" };
|
|
273
|
+
case "slow_down":
|
|
274
|
+
p.interval = Math.max(p.interval, (data.interval ?? p.interval) + 5);
|
|
275
|
+
p.nextPoll = Date.now() + p.interval * 1000;
|
|
276
|
+
return { status: "pending" };
|
|
277
|
+
case "expired_token":
|
|
278
|
+
pendingDevice.delete(key);
|
|
279
|
+
return { status: "expired" };
|
|
280
|
+
case "access_denied":
|
|
281
|
+
pendingDevice.delete(key);
|
|
282
|
+
return { status: "denied" };
|
|
283
|
+
case undefined: break;
|
|
284
|
+
default:
|
|
285
|
+
pendingDevice.delete(key);
|
|
286
|
+
throw httpError(502, `GitHub: ${data.error_description || data.error}`);
|
|
287
|
+
}
|
|
288
|
+
pendingDevice.delete(key);
|
|
289
|
+
const partial = tokensFrom(data, "");
|
|
290
|
+
const me = await api(partial.accessToken, "/user");
|
|
291
|
+
const storage = saveConnection({ ...partial, login: me.login });
|
|
292
|
+
return { status: "connected", login: me.login, storage };
|
|
293
|
+
}
|
|
294
|
+
/** A usable access token from the connection, refreshing it when it has expired. Null when not connected. */
|
|
295
|
+
async function connectionToken() {
|
|
296
|
+
const c = loadConnection();
|
|
297
|
+
if (!c)
|
|
298
|
+
return null;
|
|
299
|
+
if (!c.expiresAt || Date.now() < c.expiresAt)
|
|
300
|
+
return c.accessToken;
|
|
301
|
+
if (!c.refreshToken) {
|
|
302
|
+
saveConnection(null);
|
|
303
|
+
throw httpError(503, "The GitHub connection has expired. Connect again.");
|
|
304
|
+
}
|
|
305
|
+
let next;
|
|
306
|
+
try {
|
|
307
|
+
next = tokensFrom(await oauthPost("/login/oauth/access_token", { grant_type: "refresh_token", refresh_token: c.refreshToken }), c.login);
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
// A refresh token is single use and lasts six months; one that no longer
|
|
311
|
+
// works cannot be repaired from here.
|
|
312
|
+
saveConnection(null);
|
|
313
|
+
throw httpError(503, "GitHub would not renew the connection. Connect again.");
|
|
314
|
+
}
|
|
315
|
+
saveConnection(next);
|
|
316
|
+
return next.accessToken;
|
|
317
|
+
}
|
|
318
|
+
/** The token for this call. */
|
|
319
|
+
async function token() {
|
|
320
|
+
const c = await connectionToken();
|
|
321
|
+
if (!c)
|
|
322
|
+
throw httpError(503, NOT_CONNECTED);
|
|
323
|
+
return c;
|
|
324
|
+
}
|
|
325
|
+
async function api(tok, route) {
|
|
326
|
+
const r = await fetch(`${API_BASE}${route}`, {
|
|
327
|
+
headers: {
|
|
328
|
+
Accept: "application/vnd.github+json",
|
|
329
|
+
Authorization: `Bearer ${tok}`,
|
|
330
|
+
"X-GitHub-Api-Version": "2022-11-28",
|
|
331
|
+
"User-Agent": "bugxhunter-runner",
|
|
332
|
+
},
|
|
333
|
+
signal: AbortSignal.timeout(20_000),
|
|
334
|
+
});
|
|
335
|
+
if (r.ok)
|
|
336
|
+
return (await r.json());
|
|
337
|
+
let message = `GitHub answered ${r.status}`;
|
|
338
|
+
try {
|
|
339
|
+
message = (await r.json()).message ?? message;
|
|
340
|
+
}
|
|
341
|
+
catch { /* no body */ }
|
|
342
|
+
if (r.status === 401) {
|
|
343
|
+
// Revoked on GitHub's side: drop our copy and say so, rather than "Bad credentials" on every click.
|
|
344
|
+
if (connectionStorage() !== "sealed")
|
|
345
|
+
saveConnection(null);
|
|
346
|
+
throw httpError(503, `GitHub no longer accepts the connection (${message}). Connect again.`);
|
|
347
|
+
}
|
|
348
|
+
throw httpError(r.status === 404 || r.status === 403 ? r.status : 502, `GitHub: ${message}`);
|
|
349
|
+
}
|
|
350
|
+
/** The token's account, remembered per token so the status call stays cheap. */
|
|
351
|
+
const logins = new Map();
|
|
352
|
+
async function whoami(tok) {
|
|
353
|
+
const key = crypto.createHash("sha256").update(tok).digest("hex");
|
|
354
|
+
const hit = logins.get(key);
|
|
355
|
+
if (hit && Date.now() - hit.at < 10 * 60_000)
|
|
356
|
+
return hit.login;
|
|
357
|
+
const me = await api(tok, "/user");
|
|
358
|
+
logins.set(key, { login: me.login, at: Date.now() });
|
|
359
|
+
return me.login;
|
|
360
|
+
}
|
|
361
|
+
export async function status() {
|
|
362
|
+
const storage = connectionStorage();
|
|
363
|
+
const connected = storage !== "sealed" && loadConnection() !== null;
|
|
364
|
+
const base = {
|
|
365
|
+
connected, sealed: false, login: null, error: null,
|
|
366
|
+
installUrl: `${OAUTH_BASE}/apps/${encodeURIComponent(APP_SLUG)}/installations/new`,
|
|
367
|
+
storage: storage === "sealed" ? null : storage,
|
|
368
|
+
cloneRoot: CLONE_ROOT, clones: listClones(),
|
|
369
|
+
};
|
|
370
|
+
if (storage === "sealed") {
|
|
371
|
+
// The sign-in may be in the vault; say so rather than "not connected".
|
|
372
|
+
return vault.status("none").items.includes(CONNECTION_ITEM) ? { ...base, connected: true, sealed: true } : base;
|
|
373
|
+
}
|
|
374
|
+
if (!connected)
|
|
375
|
+
return base;
|
|
376
|
+
try {
|
|
377
|
+
return { ...base, login: await whoami(await token()) };
|
|
378
|
+
}
|
|
379
|
+
catch (e) {
|
|
380
|
+
return { ...base, error: e.message };
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/** Every repository the token can see (a fine-grained token: the ones it was granted), newest push first. */
|
|
384
|
+
export async function listRepos() {
|
|
385
|
+
const tok = await token();
|
|
386
|
+
const rows = [];
|
|
387
|
+
for (let page = 1; page <= 3; page++) {
|
|
388
|
+
const batch = await api(tok, `/user/repos?per_page=100&sort=pushed&affiliation=owner,collaborator,organization_member&page=${page}`);
|
|
389
|
+
rows.push(...batch);
|
|
390
|
+
if (batch.length < 100)
|
|
391
|
+
break;
|
|
392
|
+
}
|
|
393
|
+
const clones = new Map(listClones().map((c) => [c.fullName.toLowerCase(), c.directory]));
|
|
394
|
+
return rows.map((r) => ({
|
|
395
|
+
fullName: r.full_name,
|
|
396
|
+
description: r.description,
|
|
397
|
+
defaultBranch: r.default_branch,
|
|
398
|
+
private: r.private,
|
|
399
|
+
archived: Boolean(r.archived),
|
|
400
|
+
pushedAt: r.pushed_at ?? null,
|
|
401
|
+
...(clones.has(r.full_name.toLowerCase()) ? { directory: clones.get(r.full_name.toLowerCase()) } : {}),
|
|
402
|
+
}));
|
|
403
|
+
}
|
|
404
|
+
export async function listBranches(repo) {
|
|
405
|
+
const { fullName } = parseRepo(repo);
|
|
406
|
+
const tok = await token();
|
|
407
|
+
const [info, branches] = await Promise.all([
|
|
408
|
+
api(tok, `/repos/${fullName}`),
|
|
409
|
+
api(tok, `/repos/${fullName}/branches?per_page=100`),
|
|
410
|
+
]);
|
|
411
|
+
return branches
|
|
412
|
+
.map((b) => ({ name: b.name, isDefault: b.name === info.default_branch }))
|
|
413
|
+
.sort((a, b) => Number(b.isDefault) - Number(a.isDefault) || a.name.localeCompare(b.name));
|
|
414
|
+
}
|
|
415
|
+
// --- clone / update ------------------------------------------------------------------
|
|
416
|
+
const inFlight = new Map();
|
|
417
|
+
/**
|
|
418
|
+
* Clone `owner/name` into the workspace, or fast-forward the clone that is
|
|
419
|
+
* already there. Never a force, never a push: a clone the agent has edited
|
|
420
|
+
* that cannot fast-forward is reported, not reset.
|
|
421
|
+
*/
|
|
422
|
+
export function cloneOrUpdate(req) {
|
|
423
|
+
const { fullName } = parseRepo(req?.repo);
|
|
424
|
+
const dir = cloneDir(fullName);
|
|
425
|
+
const running = inFlight.get(dir);
|
|
426
|
+
if (running)
|
|
427
|
+
throw httpError(409, `${fullName} is already being cloned.`);
|
|
428
|
+
const p = doCloneOrUpdate(fullName, dir, req.branch === undefined || req.branch === "" ? undefined : validBranch(req.branch))
|
|
429
|
+
.finally(() => inFlight.delete(dir));
|
|
430
|
+
inFlight.set(dir, p);
|
|
431
|
+
return p;
|
|
432
|
+
}
|
|
433
|
+
async function doCloneOrUpdate(fullName, dir, branch) {
|
|
434
|
+
const tok = await token();
|
|
435
|
+
if (fs.existsSync(dir)) {
|
|
436
|
+
const existing = inspectClone(dir);
|
|
437
|
+
if (!existing)
|
|
438
|
+
throw httpError(409, `${dir} exists but is not a git clone. Move it aside first.`);
|
|
439
|
+
if (existing.fullName.toLowerCase() !== fullName.toLowerCase())
|
|
440
|
+
throw httpError(409, `${dir} is a clone of ${existing.fullName}, not ${fullName}.`);
|
|
441
|
+
const target = branch ?? existing.branch;
|
|
442
|
+
if (!target)
|
|
443
|
+
throw httpError(409, `${dir} has a detached HEAD. Choose a branch.`);
|
|
444
|
+
await git(["-C", dir, "fetch", "--prune", "origin"], tok);
|
|
445
|
+
if (target !== existing.branch)
|
|
446
|
+
await git(["-C", dir, "checkout", target], tok); // validBranch: never starts with "-"
|
|
447
|
+
await git(["-C", dir, "merge", "--ff-only", `origin/${target}`], tok);
|
|
448
|
+
return { directory: dir, branch: target, action: "updated" };
|
|
449
|
+
}
|
|
450
|
+
const target = branch ?? (await api(tok, `/repos/${fullName}`)).default_branch;
|
|
451
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
452
|
+
await git(["clone", "--branch", target, "--", remoteUrl(fullName), dir], tok);
|
|
453
|
+
// The header lives in the process environment, so it cannot end up in the
|
|
454
|
+
// clone's config. Check anyway: this is the file the agent will be able to read.
|
|
455
|
+
const config = readGitFile(dir, "config") ?? "";
|
|
456
|
+
if (/extraheader|AUTHORIZATION/i.test(config)) {
|
|
457
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
458
|
+
throw httpError(500, "The clone's .git/config held credentials; it was removed.");
|
|
459
|
+
}
|
|
460
|
+
return { directory: dir, branch: target, action: "cloned" };
|
|
461
|
+
}
|
|
462
|
+
//# sourceMappingURL=github.js.map
|