-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-auth.ts
More file actions
61 lines (51 loc) · 1.37 KB
/
github-auth.ts
File metadata and controls
61 lines (51 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { execFileSync } from "node:child_process";
import { type McpErrorEnvelope, mkError } from "./json.js";
interface AuthOk {
ok: true;
token: string;
}
interface AuthError {
ok: false;
envelope: McpErrorEnvelope;
}
type AuthResult = AuthOk | AuthError;
let cached: AuthResult | undefined;
/**
* Resolve a GitHub personal access token.
*
* Priority: GITHUB_TOKEN env → GH_TOKEN env → `gh auth token` subprocess.
* Result is cached after first call.
*/
export function gateAuth(): AuthResult {
if (cached) return cached;
const envToken = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN;
if (envToken) {
cached = { ok: true, token: envToken };
return cached;
}
// Fallback: try `gh auth token`
try {
const token = execFileSync("gh", ["auth", "token"], {
encoding: "utf8",
timeout: 5_000,
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (token) {
cached = { ok: true, token };
return cached;
}
} catch {
// gh not installed or not authenticated — fall through
}
cached = {
ok: false,
envelope: mkError("AUTH_MISSING", "No GitHub credential available.", {
suggestedFix: "Set GITHUB_TOKEN or GH_TOKEN, or run `gh auth login`.",
}),
};
return cached;
}
/** Clear the cached auth result (useful for testing). */
export function resetAuthCache(): void {
cached = undefined;
}